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