[IMP] sale modules : Cleaning modules
[odoo/odoo.git] / addons / survey / survey.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import osv
24 from osv import fields
25 import tools
26 import netsvc
27 from tools.translate import _
28
29 from time import strftime
30 from datetime import datetime
31 from dateutil.relativedelta import relativedelta
32 import copy
33 import os
34
35 class survey_type(osv.osv):
36     _name = 'survey.type'
37     _description = 'Survey Type'
38     _columns = {
39         'name': fields.char("Name", size=128, required=1),
40         'code': fields.char("Code", size=64),
41     }
42 survey_type()
43
44 class survey(osv.osv):
45     _name = 'survey'
46     _description = 'Survey'
47     _rec_name = 'title'
48
49     def default_get(self, cr, uid, fields, context={}):
50         data = super(survey, self).default_get(cr, uid, fields, context)
51         return data
52
53     _columns = {
54         'title': fields.char('Survey Title', size=128, required=1),
55         'page_ids': fields.one2many('survey.page', 'survey_id', 'Page'),
56         'date_open': fields.datetime('Survey Open Date', readonly=1),
57         'date_close': fields.datetime('Survey Close Date', readonly=1),
58         'max_response_limit': fields.integer('Maximum Answer Limit',
59                      help="Set to one if survey is answerable only once"),
60         'response_user': fields.integer('Maximum Answer per User',
61                      help="Set to one if  you require only one Answer per user"),
62         'state': fields.selection([('draft', 'Draft'), ('open', 'Open'), ('close', 'Closed'), ('cancel', 'Cancelled')], 'Status', readonly=True),
63         'responsible_id': fields.many2one('res.users', 'Responsible', help="User responsible for survey"),
64         'tot_start_survey': fields.integer("Total Started Survey", readonly=1),
65         'tot_comp_survey': fields.integer("Total Completed Survey", readonly=1),
66         'note': fields.text('Description', size=128),
67         'history': fields.one2many('survey.history', 'survey_id', 'History Lines', readonly=True),
68         'users': fields.many2many('res.users', 'survey_users_rel', 'sid', 'uid', 'Users'),
69         'send_response': fields.boolean('E-mail Notification on Answer'),
70         'type': fields.many2one('survey.type', 'Type'),
71         'invited_user_ids': fields.many2many('res.users', 'survey_invited_user_rel', 'sid', 'uid', 'Invited User'),
72     }
73     _defaults = {
74         'state': lambda * a: "draft",
75         'tot_start_survey': lambda * a: 0,
76         'tot_comp_survey': lambda * a: 0,
77         'send_response': lambda * a: 1,
78         'response_user': lambda * a:1,
79     }
80
81     def survey_draft(self, cr, uid, ids, arg):
82         self.write(cr, uid, ids, {'state': 'draft'})
83         return True
84
85     def survey_open(self, cr, uid, ids, arg):
86         self.write(cr, uid, ids, {'state': 'open', 'date_open': strftime("%Y-%m-%d %H:%M:%S")})
87         return True
88
89     def survey_close(self, cr, uid, ids, arg):
90         self.write(cr, uid, ids, {'state': 'close', 'date_close': strftime("%Y-%m-%d %H:%M:%S") })
91         return True
92
93     def survey_cancel(self, cr, uid, ids, arg):
94         self.write(cr, uid, ids, {'state': 'cancel' })
95         return True
96
97     def copy(self, cr, uid, id, default=None,context={}):
98         raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
99
100     def action_print_survey(self, cr, uid, ids, context=None):
101         """
102         If response is available then print this response otherwise print survey form(print template of the survey).
103         @param self: The object pointer
104         @param cr: the current row, from the database cursor,
105         @param uid: the current user’s ID for security checks,
106         @param ids: List of Survey IDs
107         @param context: A standard dictionary for contextual values
108         @return : Dictionary value for print survey form.
109         """
110         if not context:
111             context = {}
112         datas = {}
113         if 'response_id' in context:
114             response_id = context.get('response_id', 0)
115             datas['ids'] = [context.get('survey_id', 0)]
116         else:
117             response_id = self.pool.get('survey.response').search(cr, uid, [('survey_id','=', ids)], context=context)
118             datas['ids'] = ids
119         page_setting = {'orientation': 'vertical', 'without_pagebreak': 0, 'paper_size': 'letter', 'page_number': 1, 'survey_title': 1}
120         report = {}
121         if response_id and response_id[0]:
122             context.update({'survey_id': datas['ids']})
123             datas['form'] = page_setting
124             datas['model'] = 'survey.print.answer'
125             report = {
126                 'type': 'ir.actions.report.xml',
127                 'report_name': 'survey.browse.response',
128                 'datas': datas,
129                 'context' : context,
130                 'nodestroy':True,
131             }
132         else:
133
134             datas['form'] = page_setting
135             datas['model'] = 'survey.print'
136             report = {
137                 'type': 'ir.actions.report.xml',
138                 'report_name': 'survey.form',
139                 'datas': datas,
140                 'context' : context,
141                 'nodestroy':True,
142             }
143         return report
144 survey()
145
146 class survey_history(osv.osv):
147     _name = 'survey.history'
148     _description = 'Survey History'
149     _rec_name = 'date'
150     _columns = {
151         'survey_id': fields.many2one('survey', 'Survey'),
152         'user_id': fields.many2one('res.users', 'User', readonly=True),
153         'date': fields.datetime('Date started', readonly=1),
154     }
155     _defaults = {
156          'date': lambda * a: datetime.datetime.now()
157     }
158 survey_history()
159
160 class survey_page(osv.osv):
161     _name = 'survey.page'
162     _description = 'Survey Pages'
163     _rec_name = 'title'
164     _order = 'sequence'
165     _columns = {
166         'title': fields.char('Page Title', size=128, required=1),
167         'survey_id': fields.many2one('survey', 'Survey', ondelete='cascade'),
168         'question_ids': fields.one2many('survey.question', 'page_id', 'Question'),
169         'sequence': fields.integer('Page Nr'),
170         'note': fields.text('Description'),
171     }
172     _defaults = {
173         'sequence': lambda * a: 1
174     }
175
176     def default_get(self, cr, uid, fields, context={}):
177         data = super(survey_page, self).default_get(cr, uid, fields, context)
178         if context.get('line_order',False):
179             if len(context['line_order'][-1]) > 2 and type(context['line_order'][-1][2]) == type({}) and context['line_order'][-1][2].has_key('sequence'):
180                 data['sequence'] = context['line_order'][-1][2]['sequence'] + 1
181         if context.has_key('survey_id'):
182             data['survey_id'] = context['survey_id']
183         return data
184
185     def survey_save(self, cr, uid, ids, context):
186         search_obj = self.pool.get('ir.ui.view')
187         search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
188         surv_name_wiz = self.pool.get('survey.name.wiz')
189         surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',0) })
190         return {
191             'view_type': 'form',
192             'view_mode': 'form',
193             'res_model': 'survey.question.wiz',
194             'type': 'ir.actions.act_window',
195             'target': 'new',
196             'search_view_id': search_id[0],
197             'context': context
198         }
199
200     def copy(self, cr, uid, id, default=None, context={}):
201         raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
202
203 survey_page()
204
205 class survey_question(osv.osv):
206     _name = 'survey.question'
207     _description = 'Survey Question'
208     _rec_name = 'question'
209     _order = 'sequence'
210
211     def _calc_response(self, cr, uid, ids, field_name, arg, context):
212         if len(ids) == 0:
213             return {}
214         val = {}
215         cr.execute("select question_id, count(id) as Total_response from \
216                 survey_response_line where state='done' and question_id IN %s\
217                  group by question_id" ,(tuple(ids),))
218         ids1 = copy.deepcopy(ids)
219         for rec in  cr.fetchall():
220             ids1.remove(rec[0])
221             val[rec[0]] = int(rec[1])
222         for id in ids1:
223             val[id] = 0
224         return val
225
226     _columns = {
227         'page_id': fields.many2one('survey.page', 'Survey Page', ondelete='cascade', required=1),
228         'question':  fields.char('Question', size=128, required=1),
229         'answer_choice_ids': fields.one2many('survey.answer', 'question_id', 'Answer'),
230         'is_require_answer': fields.boolean('Require Answer to Question'),
231         'required_type': fields.selection([('all','All'), ('at least','At Least'), ('at most','At Most'), ('exactly','Exactly'), ('a range','A Range')], 'Respondent must answer'),
232         'req_ans': fields.integer('#Required Answer'),
233         'maximum_req_ans': fields.integer('Maximum Required Answer'),
234         'minimum_req_ans': fields.integer('Minimum Required Answer'),
235         'req_error_msg': fields.text('Error Message'),
236         'allow_comment': fields.boolean('Allow Comment Field'),
237         'sequence': fields.integer('Sequence'),
238         'tot_resp': fields.function(_calc_response, method=True, string="Total Answer"),
239         'survey': fields.related('page_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
240         'descriptive_text': fields.text('Descriptive Text', size=255),
241         'column_heading_ids': fields.one2many('survey.question.column.heading', 'question_id',' Column heading'),
242         'type': fields.selection([('multiple_choice_only_one_ans','Multiple Choice (Only One Answer)'),
243              ('multiple_choice_multiple_ans','Multiple Choice (Multiple Answer)'),
244              ('matrix_of_choices_only_one_ans','Matrix of Choices (Only One Answers Per Row)'),
245              ('matrix_of_choices_only_multi_ans','Matrix of Choices (Multiple Answers Per Row)'),
246              ('matrix_of_drop_down_menus','Matrix of Drop-down Menus'),
247              ('rating_scale','Rating Scale'),('single_textbox','Single Textbox'),
248              ('multiple_textboxes','Multiple Textboxes'),
249              ('multiple_textboxes_diff_type','Multiple Textboxes With Different Type'),
250              ('comment','Comment/Essay Box'),
251              ('numerical_textboxes','Numerical Textboxes'),('date','Date'),
252              ('date_and_time','Date and Time'),('descriptive_text','Descriptive Text'),
253              ('table','Table'),
254             ], 'Question Type',  required=1,),
255         'is_comment_require': fields.boolean('Add Comment Field'),
256         'comment_label': fields.char('Field Label', size = 255),
257         'comment_field_type': fields.selection([('char', 'Single Line Of Text'), ('text', 'Paragraph of Text')], 'Comment Field Type'),
258         'comment_valid_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),
259              ('must_be_specific_length', 'Must Be Specific Length'),
260              ('must_be_whole_number', 'Must Be A Whole Number'),
261              ('must_be_decimal_number', 'Must Be A Decimal Number'),
262              ('must_be_date', 'Must Be A Date'),
263              ('must_be_email_address', 'Must Be An Email Address'),
264              ], 'Text Validation'),
265         'comment_minimum_no': fields.integer('Minimum number'),
266         'comment_maximum_no': fields.integer('Maximum number'),
267         'comment_minimum_float': fields.float('Minimum decimal number'),
268         'comment_maximum_float': fields.float('Maximum decimal number'),
269         'comment_minimum_date': fields.date('Minimum date'),
270         'comment_maximum_date': fields.date('Maximum date'),
271         'comment_valid_err_msg': fields.text('Error message'),
272         'make_comment_field': fields.boolean('Make Comment Field an Answer Choice'),
273         'make_comment_field_err_msg': fields.text('Error message'),
274         'is_validation_require': fields.boolean('Validate Text'),
275         'validation_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),\
276              ('must_be_specific_length', 'Must Be Specific Length'),\
277              ('must_be_whole_number', 'Must Be A Whole Number'),\
278              ('must_be_decimal_number', 'Must Be A Decimal Number'),\
279              ('must_be_date', 'Must Be A Date'),\
280              ('must_be_email_address', 'Must Be An Email Address')\
281              ], 'Text Validation'),
282         'validation_minimum_no': fields.integer('Minimum number'),
283         'validation_maximum_no': fields.integer('Maximum number'),
284         'validation_minimum_float': fields.float('Minimum decimal number'),
285         'validation_maximum_float': fields.float('Maximum decimal number'),
286         'validation_minimum_date': fields.date('Minimum date'),
287         'validation_maximum_date': fields.date('Maximum date'),
288         'validation_valid_err_msg': fields.text('Error message'),
289         'numeric_required_sum': fields.integer('Sum of all choices'),
290         'numeric_required_sum_err_msg': fields.text('Error message'),
291         'rating_allow_one_column_require': fields.boolean('Allow Only One Answer per Column (Forced Ranking)'),
292         'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible?'),
293         'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible?'),
294         'in_visible_answer_type': fields.boolean('Is Answer Type Invisible?'),
295         'comment_column': fields.boolean('Add comment column in matrix'),
296         'column_name': fields.char('Column Name',size=256),
297         'no_of_rows': fields.integer('No of Rows'),
298     }
299     _defaults = {
300          'sequence': lambda * a: 1,
301          'type': lambda * a: 'multiple_choice_multiple_ans',
302          'req_error_msg': lambda * a: 'This question requires an answer.',
303          'required_type': lambda * a: 'at least',
304          'req_ans': lambda * a: 1,
305          'comment_field_type': lambda * a: 'char',
306          'comment_label': lambda * a: 'Other (please specify)',
307          'comment_valid_type': lambda * a: 'do_not_validate',
308          'comment_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
309          'validation_type': lambda * a: 'do_not_validate',
310          'validation_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
311          'numeric_required_sum_err_msg': lambda * a :'The choices need to add up to [enter sum here].',
312          'make_comment_field_err_msg': lambda * a : 'Please enter a comment.',
313          'in_visible_answer_type': lambda * a: 1
314     }
315
316     def on_change_type(self, cr, uid, ids, type, context=None):
317         val = {}
318         val['is_require_answer'] = False
319         val['is_comment_require'] = False
320         val['is_validation_require'] = False
321         val['comment_column'] = False
322
323         if type in ['multiple_textboxes_diff_type']:
324             val['in_visible_answer_type'] = False
325             return {'value': val}
326
327         if type in ['rating_scale']:
328             val.update({'in_visible_rating_weight':False, 'in_visible_menu_choice':True})
329             return {'value': val}
330
331         elif type in ['matrix_of_drop_down_menus']:
332             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':False})
333             return {'value': val}
334
335         elif type in ['single_textbox']:
336             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True})
337             return {'value': val}
338
339         else:
340             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True,\
341                          'in_visible_answer_type':True})
342             return {'value': val}
343
344     def write(self, cr, uid, ids, vals, context=None):
345         questions = self.read(cr,uid, ids, ['answer_choice_ids', 'type', 'required_type',\
346                         'req_ans', 'minimum_req_ans', 'maximum_req_ans', 'column_heading_ids'])
347         for question in questions:
348             col_len = len(question['column_heading_ids'])
349             if vals.has_key('column_heading_ids'):
350                 for col in vals['column_heading_ids']:
351                     if type(col[2]) == type({}):
352                         col_len += 1
353                     else:
354                         col_len -= 1
355
356             if vals.has_key('type'):
357                 que_type = vals['type']
358             else:
359                 que_type = question['type']
360
361             if que_type in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans',\
362                              'matrix_of_drop_down_menus', 'rating_scale']:
363                 if not col_len:
364                     raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
365             ans_len = len(question['answer_choice_ids'])
366
367             if vals.has_key('answer_choice_ids'):
368                 for ans in vals['answer_choice_ids']:
369                     if type(ans[2]) == type({}):
370                         ans_len += 1
371                     else:
372                         ans_len -= 1
373
374             if que_type not in ['descriptive_text', 'single_textbox', 'comment','table']:
375                 if not ans_len:
376                     raise osv.except_osv(_('Warning !'),_("You must enter one or more Answer."))
377             req_type = ""
378
379             if vals.has_key('required_type'):
380                 req_type = vals['required_type']
381             else:
382                 req_type = question['required_type']
383
384             if que_type in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', \
385                         'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus',\
386                          'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
387                 if req_type in ['at least', 'at most', 'exactly']:
388                     if vals.has_key('req_ans'):
389                         if not vals['req_ans'] or  vals['req_ans'] > ans_len:
390                             raise osv.except_osv(_('Warning !'),_("#Required Answer you entered \
391                                     is greater than the number of answer. \
392                                     Please use a number that is smaller than %d.") % (ans_len + 1))
393                     else:
394                         if not question['req_ans'] or  question['req_ans'] > ans_len:
395                             raise osv.except_osv(_('Warning !'),_("#Required Answer you entered is \
396                                     greater than the number of answer.\
397                                     Please use a number that is smaller than %d.") % (ans_len + 1))
398
399                 if req_type == 'a range':
400                     minimum_ans = 0
401                     maximum_ans = 0
402                     if vals.has_key('minimum_req_ans'):
403                         minimum_ans = vals['minimum_req_ans']
404                         if not vals['minimum_req_ans'] or  vals['minimum_req_ans'] > ans_len:
405                             raise osv.except_osv(_('Warning !'),_("Minimum Required Answer\
406                                      you entered is greater than the number of answer.\
407                                     Please use a number that is smaller than %d.") % (ans_len + 1))
408                     else:
409                         minimum_ans = question['minimum_req_ans']
410                         if not question['minimum_req_ans'] or  question['minimum_req_ans'] > ans_len:
411                             raise osv.except_osv(_('Warning !'),_("Minimum Required Answer you\
412                                      entered is greater than the number of answer. \
413                                      Please use a number that is smaller than %d.") % (ans_len + 1))
414                     if vals.has_key('maximum_req_ans'):
415                         maximum_ans = vals['maximum_req_ans']
416                         if not vals['maximum_req_ans'] or vals['maximum_req_ans'] > ans_len:
417                             raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you \
418                                     entered for your maximum is greater than the number of answer.\
419                                      Please use a number that is smaller than %d.") % (ans_len + 1))
420                     else:
421                         maximum_ans = question['maximum_req_ans']
422                         if not question['maximum_req_ans'] or question['maximum_req_ans'] > ans_len:
423                             raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you\
424                                      entered for your maximum is greater than the number of answer.\
425                                       Please use a number that is smaller than %d.") % (ans_len + 1))
426                     if maximum_ans <= minimum_ans:
427                         raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater \
428                                     than Minimum Required Answer"))
429
430             if question['type'] ==  'matrix_of_drop_down_menus' and vals.has_key('column_heading_ids'):
431                 for col in vals['column_heading_ids']:
432                     if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
433                         raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices\
434                                  in column heading"))
435                     elif not col[2] or not col[2].has_key('menu_choice') or\
436                              col[2]['menu_choice'].strip() == '':
437                         raise osv.except_osv(_('Warning !'),_("You must enter one or more menu \
438                                 choices in column heading (white spaces not allowed)"))
439
440         return super(survey_question, self).write(cr, uid, ids, vals, context=context)
441
442     def create(self, cr, uid, vals, context):
443         minimum_ans = 0
444         maximum_ans = 0
445         if vals.has_key('answer_choice_ids') and  not len(vals['answer_choice_ids']):
446             if vals.has_key('type') and vals['type'] not in ['descriptive_text', 'single_textbox', 'comment','table']:
447                 raise osv.except_osv(_('Warning !'),_("You must enter one or more answer."))
448
449         if vals.has_key('column_heading_ids') and  not len(vals['column_heading_ids']):
450             if vals.has_key('type') and vals['type'] in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus', 'rating_scale']:
451                 raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
452
453         if vals['type'] in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus', 'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
454             if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] in ['at least', 'at most', 'exactly']:
455                 if vals.has_key('answer_choice_ids') and vals['req_ans'] > len(vals['answer_choice_ids']) or not vals['req_ans']:
456                     raise osv.except_osv(_('Warning !'),_("#Required Answer you entered is greater than the number of answer. Please use a number that is smaller than %d.") % (len(vals['answer_choice_ids'])+1))
457
458             if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] == 'a range':
459                 minimum_ans = vals['minimum_req_ans']
460                 maximum_ans = vals['maximum_req_ans']
461                 if vals.has_key('answer_choice_ids') or vals['minimum_req_ans'] > len(vals['answer_choice_ids']) or not vals['minimum_req_ans']:
462                     raise osv.except_osv(_('Warning !'),_("Minimum Required Answer you entered is greater than the number of answer. Please use a number that is smaller than %d.") % (len(vals['answer_choice_ids'])+1))
463                 if vals.has_key('answer_choice_ids') or vals['maximum_req_ans'] > len(vals['answer_choice_ids']) or not vals['maximum_req_ans']:
464                     raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you entered for your maximum is greater than the number of answer. Please use a number that is smaller than %d.") % (len(vals['answer_choice_ids'])+1))
465                 if maximum_ans <= minimum_ans:
466                     raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater than Minimum Required Answer"))
467
468         if vals['type'] ==  'matrix_of_drop_down_menus':
469             for col in vals['column_heading_ids']:
470                 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
471                     raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading"))
472                 elif not col[2] or not col[2].has_key('menu_choice') or col[2]['menu_choice'].strip() == '':
473                     raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading (white spaces not allowed)"))
474
475         res = super(survey_question, self).create(cr, uid, vals, context)
476         return res
477
478     def survey_save(self, cr, uid, ids, context):
479         search_obj = self.pool.get('ir.ui.view')
480         search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
481         surv_name_wiz = self.pool.get('survey.name.wiz')
482         surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',False) })
483         return {
484             'view_type': 'form',
485             'view_mode': 'form',
486             'res_model': 'survey.question.wiz',
487             'type': 'ir.actions.act_window',
488             'target': 'new',
489             'search_view_id': search_id[0],
490             'context': context
491         }
492
493     def default_get(self, cr, uid, fields, context={}):
494         data = super(survey_question, self).default_get(cr, uid, fields, context)
495         if context.get('line_order',False):
496             if len(context['line_order'][-1]) > 2 and type(context['line_order'][-1][2]) == type({}) and context['line_order'][-1][2].has_key('sequence'):
497                 data['sequence'] = context['line_order'][-1][2]['sequence'] + 1
498
499         if context.has_key('page_id'):
500             data['page_id']= context.get('page_id', False)
501         return data
502
503 survey_question()
504
505
506 class survey_question_column_heading(osv.osv):
507     _name = 'survey.question.column.heading'
508     _description = 'Survey Question Column Heading'
509     _rec_name = 'title'
510
511     def _get_in_visible_rating_weight(self,cr, uid, context={}):
512         if context.get('in_visible_rating_weight', False):
513             return context['in_visible_rating_weight']
514         return False
515     def _get_in_visible_menu_choice(self,cr, uid, context={}):
516         if context.get('in_visible_menu_choice', False):
517             return context['in_visible_menu_choice']
518         return False
519
520     _columns = {
521         'title': fields.char('Column Heading', size=128, required=1),
522         'menu_choice': fields.text('Menu Choice'),
523         'rating_weight': fields.integer('Weight'),
524         'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
525         'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible ??'),
526         'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible??')
527     }
528     _defaults={
529        'in_visible_rating_weight': _get_in_visible_rating_weight,
530        'in_visible_menu_choice': _get_in_visible_menu_choice,
531     }
532 survey_question_column_heading()
533
534 class survey_answer(osv.osv):
535     _name = 'survey.answer'
536     _description = 'Survey Answer'
537     _rec_name = 'answer'
538     _order = 'sequence'
539
540     def _calc_response_avg(self, cr, uid, ids, field_name, arg, context):
541         val = {}
542         for rec in self.browse(cr, uid, ids, context):
543             cr.execute("select count(question_id) ,(select count(answer_id) \
544                 from survey_response_answer sra, survey_response_line sa \
545                 where sra.response_id = sa.id and sra.answer_id = %d \
546                 and sa.state='done') as tot_ans from survey_response_line \
547                 where question_id = %d and state = 'done'"\
548                      % (rec.id, rec.question_id.id))
549             res = cr.fetchone()
550             if res[0]:
551                 avg = float(res[1]) * 100 / res[0]
552             else:
553                 avg = 0.0
554             val[rec.id] = {
555                 'response': res[1],
556                 'average': round(avg, 2),
557             }
558         return val
559
560     def _get_in_visible_answer_type(self,cr, uid, context={}):
561         return context.get('in_visible_answer_type', False)
562
563     _columns = {
564         'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
565         'answer': fields.char('Answer', size=128, required=1),
566         'sequence': fields.integer('Sequence'),
567         'response': fields.function(_calc_response_avg, method=True, string="#Answer", multi='sums'),
568         'average': fields.function(_calc_response_avg, method=True, string="#Avg", multi='sums'),
569         'type': fields.selection([('char','Character'),('date','Date'),('datetime','Date & Time'),\
570             ('integer','Integer'),('float','Float'),('selection','Selection'),\
571             ('email','Email')], "Type of Answer",required=1),
572         'menu_choice': fields.text('Menu Choices'),
573         'in_visible_answer_type': fields.boolean('Is Answer Type Invisible??')
574     }
575     _defaults = {
576 #         'sequence' : lambda * a: 1,
577          'type' : lambda * a: 'char',
578          'in_visible_answer_type':_get_in_visible_answer_type,
579     }
580
581     def default_get(self, cr, uid, fields, context={}):
582         data = super(survey_answer, self).default_get(cr, uid, fields, context)
583         if context.get('line_order', False):
584             if len(context['line_order'][-1]) > 2 and type(context['line_order'][-1][2]) == type({}) and context['line_order'][-1][2].has_key('sequence'):
585                 data['sequence'] = context['line_order'][-1][2]['sequence'] + 1
586         return data
587
588 survey_answer()
589
590 class survey_response(osv.osv):
591     _name = "survey.response"
592     _rec_name = 'date_create'
593     _columns = {
594         'survey_id' : fields.many2one('survey', 'Survey', required=1, ondelete='cascade'),
595         'date_create' : fields.datetime('Create Date', required=1),
596         'user_id' : fields.many2one('res.users', 'User'),
597         'response_type' : fields.selection([('manually', 'Manually'), ('link', 'Link')], \
598                                     'Answer Type', required=1, readonly=1),
599         'question_ids' : fields.one2many('survey.response.line', 'response_id', 'Answer'),
600         'state' : fields.selection([('done', 'Finished '),('skip', 'Not Finished')], \
601                             'Status', readonly=True),
602     }
603     _defaults = {
604         'state' : lambda * a: "skip",
605         'response_type' : lambda * a: "manually",
606     }
607
608     def name_get(self, cr, uid, ids, context=None):
609         if not len(ids):
610             return []
611         reads = self.read(cr, uid, ids, ['user_id','date_create'], context)
612         res = []
613         for record in reads:
614             name = (record['user_id'] and record['user_id'][1] or '' )+ ' (' + record['date_create'].split('.')[0] + ')'
615             res.append((record['id'], name))
616         return res
617
618     def copy(self, cr, uid, id, default=None,context={}):
619         raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
620
621 survey_response()
622
623 class survey_response_line(osv.osv):
624     _name = 'survey.response.line'
625     _description = 'Survey Response Line'
626     _rec_name = 'date_create'
627     _columns = {
628         'response_id': fields.many2one('survey.response', 'Answer', ondelete='cascade'),
629         'date_create': fields.datetime('Create Date', required=1),
630         'state': fields.selection([('draft', 'Draft'), ('done', 'Answered'),('skip', 'Skiped')],\
631                                    'Status', readonly=True),
632         'question_id': fields.many2one('survey.question', 'Question'),
633         'page_id': fields.related('question_id', 'page_id', type='many2one', \
634                                   relation='survey.page', string='Page'),
635         'response_answer_ids': fields.one2many('survey.response.answer', 'response_id', 'Answer'),
636         'response_table_ids': fields.one2many('survey.tbl.column.heading', \
637                                     'response_table_id', 'Answer'),
638         'comment': fields.text('Notes'),
639         'single_text': fields.char('Text', size=255),
640     }
641     _defaults = {
642         'state' : lambda * a: "draft",
643     }
644
645 survey_response_line()
646
647 class survey_tbl_column_heading(osv.osv):
648     _name = 'survey.tbl.column.heading'
649     _order = 'name'
650     _columns = {
651         'name': fields.integer('Row Number'),
652         'column_id': fields.many2one('survey.question.column.heading', 'Column'),
653         'value': fields.char('Value', size = 255),
654         'response_table_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
655     }
656
657 survey_tbl_column_heading()
658
659 class survey_response_answer(osv.osv):
660     _name = 'survey.response.answer'
661     _description = 'Survey Answer'
662     _rec_name = 'response_id'
663     _columns = {
664         'response_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
665         'answer_id': fields.many2one('survey.answer', 'Answer', required=1, ondelete='cascade'),
666         'column_id': fields.many2one('survey.question.column.heading','Column'),
667         'answer': fields.char('Value', size =255),
668         'value_choice': fields.char('Value Choice', size =255),
669         'comment': fields.text('Notes'),
670         'comment_field': fields.char('Comment', size = 255)
671     }
672
673 survey_response_answer()
674
675 class res_users(osv.osv):
676     _inherit = "res.users"
677     _name = "res.users"
678     _columns = {
679         'survey_id': fields.many2many('survey', 'survey_users_rel', 'uid', 'sid', 'Groups'),
680     }
681
682 res_users()
683
684 class survey_request(osv.osv):
685     _name = "survey.request"
686     _order = 'date_deadline'
687     _rec_name = 'date_deadline'
688     _columns = {
689         'date_deadline': fields.date("Deadline date"),
690         'user_id': fields.many2one("res.users", "User"),
691         'email': fields.char("E-mail", size=64),
692         'survey_id': fields.many2one("survey", "Survey", required=1, ondelete='cascade'),
693         'response': fields.many2one('survey.response', 'Answer'),
694         'state': fields.selection([('draft','Draft'),('waiting_answer', 'Wating Answer'),('done', 'Done'),('cancel', 'Cancelled')], 'State', readonly=1)
695     }
696     _defaults = {
697         'state': lambda * a: 'draft',
698 #        'date_deadline': lambda * a :  (datetime.now() + relativedelta(months=+1)).strftime("%Y-%m-%d %H:%M:%S")
699     }
700     def survey_req_waiting_answer(self, cr, uid, ids, arg):
701         self.write(cr, uid, ids, { 'state' : 'waiting_answer'})
702         return True
703
704     def survey_req_draft(self, cr, uid, ids, arg):
705         self.write(cr, uid, ids, { 'state' : 'draft'})
706         return True
707
708     def survey_req_done(self, cr, uid, ids, arg):
709         self.write(cr, uid, ids, { 'state' : 'done'})
710         return True
711
712     def survey_req_cancel(self, cr, uid, ids, arg):
713         self.write(cr, uid, ids, { 'state' : 'cancel'})
714         return True
715
716     def on_change_user(self, cr, uid, ids, user_id, context=None):
717         if user_id:
718             user_obj = self.pool.get('res.users')
719             user = user_obj.browse(cr, uid, user_id)
720             return {'value': {'email': user.address_id.email}}
721         return {}
722
723 survey_request()
724
725 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: