[MERGE] Merged with server/trunk.
[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         'id': fields.integer('ID'),
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([('open', 'Open'), ('cancel', 'Cancelled'),('close', 'Closed') ], '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('Email Notification on Answer'),
70         'type': fields.many2one('survey.type', 'Type'),
71         'color': fields.integer('Color Index'),
72         'invited_user_ids': fields.many2many('res.users', 'survey_invited_user_rel', 'sid', 'uid', 'Invited User'),
73     }
74     _defaults = {
75         'state': lambda * a: "open",
76         'tot_start_survey': lambda * a: 0,
77         'tot_comp_survey': lambda * a: 0,
78         'send_response': lambda * a: 1,
79         'response_user': lambda * a:1,
80     }
81
82     def survey_open(self, cr, uid, ids, arg):
83         self.write(cr, uid, ids, {'state': 'open', 'date_open': strftime("%Y-%m-%d %H:%M:%S")})
84         return True
85
86     def survey_close(self, cr, uid, ids, arg):
87         self.write(cr, uid, ids, {'state': 'close', 'date_close': strftime("%Y-%m-%d %H:%M:%S") })
88         return True
89
90     def survey_cancel(self, cr, uid, ids, arg):
91         self.write(cr, uid, ids, {'state': 'cancel' })
92         return True
93
94     def copy(self, cr, uid, ids, default=None, context=None):
95         vals = {}
96         current_rec = self.read(cr, uid, ids, context=context)
97         title = current_rec.get('title') + ' (Copy)'
98         vals.update({'title':title})
99         vals.update({'history':[],'tot_start_survey':0,'tot_comp_survey':0})
100         return super(survey, self).copy(cr, uid, ids, vals, context=context)
101
102     def action_print_survey(self, cr, uid, ids, context=None):
103         """
104         If response is available then print this response otherwise print survey form(print template of the survey).
105         @param self: The object pointer
106         @param cr: the current row, from the database cursor,
107         @param uid: the current user’s ID for security checks,
108         @param ids: List of Survey IDs
109         @param context: A standard dictionary for contextual values
110         @return : Dictionary value for print survey form.
111         """
112         if context is None:
113             context = {}
114         datas = {}
115         if 'response_id' in context:
116             response_id = context.get('response_id', 0)
117             datas['ids'] = [context.get('survey_id', 0)]
118         else:
119             response_id = self.pool.get('survey.response').search(cr, uid, [('survey_id','=', ids)], context=context)
120             datas['ids'] = ids
121         page_setting = {'orientation': 'vertical', 'without_pagebreak': 0, 'paper_size': 'letter', 'page_number': 1, 'survey_title': 1}
122         report = {}
123         if response_id and response_id[0]:
124             context.update({'survey_id': datas['ids']})
125             datas['form'] = page_setting
126             datas['model'] = 'survey.print.answer'
127             report = {
128                 'type': 'ir.actions.report.xml',
129                 'report_name': 'survey.browse.response',
130                 'datas': datas,
131                 'context' : context,
132                 'nodestroy':True,
133             }
134         else:
135
136             datas['form'] = page_setting
137             datas['model'] = 'survey.print'
138             report = {
139                 'type': 'ir.actions.report.xml',
140                 'report_name': 'survey.form',
141                 'datas': datas,
142                 'context' : context,
143                 'nodestroy':True,
144             }
145         return report
146     
147     def fill_survey(self, cr, uid, ids, context=None):
148         return {
149             'view_type': 'form',
150             'view_mode': 'form',
151             'res_model': 'survey.question.wiz',
152             'type': 'ir.actions.act_window',
153             'target': 'new',
154             'context': {'survey_id': ids[0]}
155         }
156
157 survey()
158
159 class survey_history(osv.osv):
160     _name = 'survey.history'
161     _description = 'Survey History'
162     _rec_name = 'date'
163     _columns = {
164         'survey_id': fields.many2one('survey', 'Survey'),
165         'user_id': fields.many2one('res.users', 'User', readonly=True),
166         'date': fields.datetime('Date started', readonly=1),
167     }
168     _defaults = {
169          'date': lambda * a: datetime.datetime.now()
170     }
171 survey_history()
172
173 class survey_page(osv.osv):
174     _name = 'survey.page'
175     _description = 'Survey Pages'
176     _rec_name = 'title'
177     _order = 'sequence'
178     _columns = {
179         'title': fields.char('Page Title', size=128, required=1),
180         'survey_id': fields.many2one('survey', 'Survey', ondelete='cascade'),
181         'question_ids': fields.one2many('survey.question', 'page_id', 'Questions'),
182         'sequence': fields.integer('Page Nr'),
183         'note': fields.text('Description'),
184     }
185     _defaults = {
186         'sequence': lambda * a: 1
187     }
188
189     def default_get(self, cr, uid, fields, context=None):
190         if context is None:
191             context = {}
192         data = super(survey_page, self).default_get(cr, uid, fields, context)
193         if context.has_key('survey_id'):
194             data['survey_id'] = context.get('survey_id', False)
195         return data
196
197     def survey_save(self, cr, uid, ids, context=None):
198         if context is None:
199             context = {}
200         search_obj = self.pool.get('ir.ui.view')
201         search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
202         surv_name_wiz = self.pool.get('survey.name.wiz')
203         surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',0) })
204         return {
205             'view_type': 'form',
206             'view_mode': 'form',
207             'res_model': 'survey.question.wiz',
208             'type': 'ir.actions.act_window',
209             'target': 'new',
210             'search_view_id': search_id[0],
211             'context': context
212         }
213
214     def copy(self, cr, uid, ids, default=None, context=None):
215         vals = {}
216         current_rec = self.read(cr, uid, ids, context=context)
217         title = current_rec.get('title') + ' (Copy)'
218         vals.update({'title':title})
219         return super(survey_page, self).copy(cr, uid, ids, vals, context=context)
220
221 survey_page()
222
223 class survey_question(osv.osv):
224     _name = 'survey.question'
225     _description = 'Survey Question'
226     _rec_name = 'question'
227     _order = 'sequence'
228
229     def _calc_response(self, cr, uid, ids, field_name, arg, context=None):
230         if len(ids) == 0:
231             return {}
232         val = {}
233         cr.execute("select question_id, count(id) as Total_response from \
234                 survey_response_line where state='done' and question_id IN %s\
235                  group by question_id" ,(tuple(ids),))
236         ids1 = copy.deepcopy(ids)
237         for rec in  cr.fetchall():
238             ids1.remove(rec[0])
239             val[rec[0]] = int(rec[1])
240         for id in ids1:
241             val[id] = 0
242         return val
243
244     _columns = {
245         'page_id': fields.many2one('survey.page', 'Survey Page', ondelete='cascade', required=1),
246         'question':  fields.char('Question', size=128, required=1),
247         'answer_choice_ids': fields.one2many('survey.answer', 'question_id', 'Answer'),
248         'is_require_answer': fields.boolean('Require Answer to Question'),
249         'required_type': fields.selection([('all','All'), ('at least','At Least'), ('at most','At Most'), ('exactly','Exactly'), ('a range','A Range')], 'Respondent must answer'),
250         'req_ans': fields.integer('#Required Answer'),
251         'maximum_req_ans': fields.integer('Maximum Required Answer'),
252         'minimum_req_ans': fields.integer('Minimum Required Answer'),
253         'req_error_msg': fields.text('Error Message'),
254         'allow_comment': fields.boolean('Allow Comment Field'),
255         'sequence': fields.integer('Sequence'),
256         'tot_resp': fields.function(_calc_response, string="Total Answer"),
257         'survey': fields.related('page_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
258         'descriptive_text': fields.text('Descriptive Text', size=255),
259         'column_heading_ids': fields.one2many('survey.question.column.heading', 'question_id',' Column heading'),
260         'type': fields.selection([('multiple_choice_only_one_ans','Multiple Choice (Only One Answer)'),
261              ('multiple_choice_multiple_ans','Multiple Choice (Multiple Answer)'),
262              ('matrix_of_choices_only_one_ans','Matrix of Choices (Only One Answers Per Row)'),
263              ('matrix_of_choices_only_multi_ans','Matrix of Choices (Multiple Answers Per Row)'),
264              ('matrix_of_drop_down_menus','Matrix of Drop-down Menus'),
265              ('rating_scale','Rating Scale'),('single_textbox','Single Textbox'),
266              ('multiple_textboxes','Multiple Textboxes'),
267              ('multiple_textboxes_diff_type','Multiple Textboxes With Different Type'),
268              ('comment','Comment/Essay Box'),
269              ('numerical_textboxes','Numerical Textboxes'),('date','Date'),
270              ('date_and_time','Date and Time'),('descriptive_text','Descriptive Text'),
271              ('table','Table'),
272             ], 'Question Type',  required=1,),
273         'is_comment_require': fields.boolean('Add Comment Field'),
274         'comment_label': fields.char('Field Label', size = 255),
275         'comment_field_type': fields.selection([('char', 'Single Line Of Text'), ('text', 'Paragraph of Text')], 'Comment Field Type'),
276         'comment_valid_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),
277              ('must_be_specific_length', 'Must Be Specific Length'),
278              ('must_be_whole_number', 'Must Be A Whole Number'),
279              ('must_be_decimal_number', 'Must Be A Decimal Number'),
280              ('must_be_date', 'Must Be A Date'),
281              ('must_be_email_address', 'Must Be An Email Address'),
282              ], 'Text Validation'),
283         'comment_minimum_no': fields.integer('Minimum number'),
284         'comment_maximum_no': fields.integer('Maximum number'),
285         'comment_minimum_float': fields.float('Minimum decimal number'),
286         'comment_maximum_float': fields.float('Maximum decimal number'),
287         'comment_minimum_date': fields.date('Minimum date'),
288         'comment_maximum_date': fields.date('Maximum date'),
289         'comment_valid_err_msg': fields.text('Error message'),
290         'make_comment_field': fields.boolean('Make Comment Field an Answer Choice'),
291         'make_comment_field_err_msg': fields.text('Error message'),
292         'is_validation_require': fields.boolean('Validate Text'),
293         'validation_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),\
294              ('must_be_specific_length', 'Must Be Specific Length'),\
295              ('must_be_whole_number', 'Must Be A Whole Number'),\
296              ('must_be_decimal_number', 'Must Be A Decimal Number'),\
297              ('must_be_date', 'Must Be A Date'),\
298              ('must_be_email_address', 'Must Be An Email Address')\
299              ], 'Text Validation'),
300         'validation_minimum_no': fields.integer('Minimum number'),
301         'validation_maximum_no': fields.integer('Maximum number'),
302         'validation_minimum_float': fields.float('Minimum decimal number'),
303         'validation_maximum_float': fields.float('Maximum decimal number'),
304         'validation_minimum_date': fields.date('Minimum date'),
305         'validation_maximum_date': fields.date('Maximum date'),
306         'validation_valid_err_msg': fields.text('Error message'),
307         'numeric_required_sum': fields.integer('Sum of all choices'),
308         'numeric_required_sum_err_msg': fields.text('Error message'),
309         'rating_allow_one_column_require': fields.boolean('Allow Only One Answer per Column (Forced Ranking)'),
310         'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible?'),
311         'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible?'),
312         'in_visible_answer_type': fields.boolean('Is Answer Type Invisible?'),
313         'comment_column': fields.boolean('Add comment column in matrix'),
314         'column_name': fields.char('Column Name',size=256),
315         'no_of_rows': fields.integer('No of Rows'),
316     }
317     _defaults = {
318          'sequence': lambda * a: 1,
319          'type': lambda * a: 'multiple_choice_multiple_ans',
320          'req_error_msg': lambda * a: 'This question requires an answer.',
321          'required_type': lambda * a: 'at least',
322          'req_ans': lambda * a: 1,
323          'comment_field_type': lambda * a: 'char',
324          'comment_label': lambda * a: 'Other (please specify)',
325          'comment_valid_type': lambda * a: 'do_not_validate',
326          'comment_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
327          'validation_type': lambda * a: 'do_not_validate',
328          'validation_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
329          'numeric_required_sum_err_msg': lambda * a :'The choices need to add up to [enter sum here].',
330          'make_comment_field_err_msg': lambda * a : 'Please enter a comment.',
331          'in_visible_answer_type': lambda * a: 1
332     }
333
334     def on_change_type(self, cr, uid, ids, type, context=None):
335         val = {}
336         val['is_require_answer'] = False
337         val['is_comment_require'] = False
338         val['is_validation_require'] = False
339         val['comment_column'] = False
340
341         if type in ['multiple_textboxes_diff_type']:
342             val['in_visible_answer_type'] = False
343             return {'value': val}
344
345         if type in ['rating_scale']:
346             val.update({'in_visible_rating_weight':False, 'in_visible_menu_choice':True})
347             return {'value': val}
348
349         elif type in ['matrix_of_drop_down_menus']:
350             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':False})
351             return {'value': val}
352
353         elif type in ['single_textbox']:
354             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True})
355             return {'value': val}
356
357         else:
358             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True,\
359                          'in_visible_answer_type':True})
360             return {'value': val}
361
362     def write(self, cr, uid, ids, vals, context=None):
363         questions = self.read(cr,uid, ids, ['answer_choice_ids', 'type', 'required_type',\
364                         'req_ans', 'minimum_req_ans', 'maximum_req_ans', 'column_heading_ids'])
365         for question in questions:
366             col_len = len(question['column_heading_ids'])
367             if vals.has_key('column_heading_ids'):
368                 for col in vals['column_heading_ids']:
369                     if type(col[2]) == type({}):
370                         col_len += 1
371                     else:
372                         col_len -= 1
373
374             if vals.has_key('type'):
375                 que_type = vals['type']
376             else:
377                 que_type = question['type']
378
379             if que_type in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans',\
380                              'matrix_of_drop_down_menus', 'rating_scale']:
381                 if not col_len:
382                     raise osv.except_osv(_('Warning!'),_("You must enter one or more column headings."))
383             ans_len = len(question['answer_choice_ids'])
384
385             if vals.has_key('answer_choice_ids'):
386                 for ans in vals['answer_choice_ids']:
387                     if type(ans[2]) == type({}):
388                         ans_len += 1
389                     else:
390                         ans_len -= 1
391
392             if que_type not in ['descriptive_text', 'single_textbox', 'comment','table']:
393                 if not ans_len:
394                     raise osv.except_osv(_('Warning!'),_("You must enter one or more Answers."))
395             req_type = ""
396
397             if vals.has_key('required_type'):
398                 req_type = vals['required_type']
399             else:
400                 req_type = question['required_type']
401
402             if que_type in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', \
403                         'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus',\
404                          'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
405                 if req_type in ['at least', 'at most', 'exactly']:
406                     if vals.has_key('req_ans'):
407                         if not vals['req_ans'] or  vals['req_ans'] > ans_len:
408                             raise osv.except_osv(_('Warning!'),_("#Required Answer you entered \
409                                     is greater than the number of answer. \
410                                     Please use a number that is smaller than %d.") % (ans_len + 1))
411                     else:
412                         if not question['req_ans'] or  question['req_ans'] > ans_len:
413                             raise osv.except_osv(_('Warning!'),_("#Required Answer you entered is \
414                                     greater than the number of answer.\
415                                     Please use a number that is smaller than %d.") % (ans_len + 1))
416
417                 if req_type == 'a range':
418                     minimum_ans = 0
419                     maximum_ans = 0
420                     if vals.has_key('minimum_req_ans'):
421                         minimum_ans = vals['minimum_req_ans']
422                         if not vals['minimum_req_ans'] or  vals['minimum_req_ans'] > ans_len:
423                             raise osv.except_osv(_('Warning!'),_("Minimum Required Answer\
424                                      you entered is greater than the number of answer.\
425                                     Please use a number that is smaller than %d.") % (ans_len + 1))
426                     else:
427                         minimum_ans = question['minimum_req_ans']
428                         if not question['minimum_req_ans'] or  question['minimum_req_ans'] > ans_len:
429                             raise osv.except_osv(_('Warning!'),_("Minimum Required Answer you\
430                                      entered is greater than the number of answer. \
431                                      Please use a number that is smaller than %d.") % (ans_len + 1))
432                     if vals.has_key('maximum_req_ans'):
433                         maximum_ans = vals['maximum_req_ans']
434                         if not vals['maximum_req_ans'] or vals['maximum_req_ans'] > ans_len:
435                             raise osv.except_osv(_('Warning!'),_("Maximum Required Answer you \
436                                     entered for your maximum is greater than the number of answer.\
437                                      Please use a number that is smaller than %d.") % (ans_len + 1))
438                     else:
439                         maximum_ans = question['maximum_req_ans']
440                         if not question['maximum_req_ans'] or question['maximum_req_ans'] > ans_len:
441                             raise osv.except_osv(_('Warning!'),_("Maximum Required Answer you\
442                                      entered for your maximum is greater than the number of answer.\
443                                       Please use a number that is smaller than %d.") % (ans_len + 1))
444                     if maximum_ans <= minimum_ans:
445                         raise osv.except_osv(_('Warning!'),_("Maximum Required Answer is greater \
446                                     than Minimum Required Answer"))
447
448             if question['type'] ==  'matrix_of_drop_down_menus' and vals.has_key('column_heading_ids'):
449                 for col in vals['column_heading_ids']:
450                     if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
451                         raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices\
452                                  in column heading."))
453                     elif not col[2] or not col[2].has_key('menu_choice') or\
454                              col[2]['menu_choice'].strip() == '':
455                         raise osv.except_osv(_('Warning!'),_("You must enter one or more menu \
456                                 choices in column heading (white spaces not allowed)."))
457
458         return super(survey_question, self).write(cr, uid, ids, vals, context=context)
459
460     def create(self, cr, uid, vals, context=None):
461         minimum_ans = 0
462         maximum_ans = 0
463         if vals.has_key('answer_choice_ids') and  not len(vals['answer_choice_ids']):
464             if vals.has_key('type') and vals['type'] not in ['descriptive_text', 'single_textbox', 'comment','table']:
465                 raise osv.except_osv(_('Warning!'),_("You must enter one or more answers."))
466
467         if vals.has_key('column_heading_ids') and  not len(vals['column_heading_ids']):
468             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']:
469                 raise osv.except_osv(_('Warning!'),_("You must enter one or more column heading."))
470
471         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']:
472             if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] in ['at least', 'at most', 'exactly']:
473                 if vals.has_key('answer_choice_ids') and vals['req_ans'] > len(vals['answer_choice_ids']) or not vals['req_ans']:
474                     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))
475
476             if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] == 'a range':
477                 minimum_ans = vals['minimum_req_ans']
478                 maximum_ans = vals['maximum_req_ans']
479                 if vals.has_key('answer_choice_ids') or vals['minimum_req_ans'] > len(vals['answer_choice_ids']) or not vals['minimum_req_ans']:
480                     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))
481                 if vals.has_key('answer_choice_ids') or vals['maximum_req_ans'] > len(vals['answer_choice_ids']) or not vals['maximum_req_ans']:
482                     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))
483                 if maximum_ans <= minimum_ans:
484                     raise osv.except_osv(_('Warning!'),_("Maximum Required Answer is greater than Minimum Required Answer."))
485
486         if vals['type'] ==  'matrix_of_drop_down_menus':
487             for col in vals['column_heading_ids']:
488                 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
489                     raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices in column heading."))
490                 elif not col[2] or not col[2].has_key('menu_choice') or col[2]['menu_choice'].strip() == '':
491                     raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices in column heading (white spaces not allowed)."))
492
493         res = super(survey_question, self).create(cr, uid, vals, context)
494         return res
495
496     def survey_save(self, cr, uid, ids, context=None):
497         if context is None:
498             context = {}
499         search_obj = self.pool.get('ir.ui.view')
500         search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
501         surv_name_wiz = self.pool.get('survey.name.wiz')
502         surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',False) })
503         return {
504             'view_type': 'form',
505             'view_mode': 'form',
506             'res_model': 'survey.question.wiz',
507             'type': 'ir.actions.act_window',
508             'target': 'new',
509             'search_view_id': search_id[0],
510             'context': context
511         }
512
513     def default_get(self, cr, uid, fields, context=None):
514         if context is None:
515             context = {}
516         data = super(survey_question, self).default_get(cr, uid, fields, context)
517         if context.has_key('page_id'):
518             data['page_id']= context.get('page_id', False)
519         return data
520
521 survey_question()
522
523
524 class survey_question_column_heading(osv.osv):
525     _name = 'survey.question.column.heading'
526     _description = 'Survey Question Column Heading'
527     _rec_name = 'title'
528
529     def _get_in_visible_rating_weight(self,cr, uid, context=None):
530         if context is None:
531             context = {}
532         if context.get('in_visible_rating_weight', False):
533             return context['in_visible_rating_weight']
534         return False
535     def _get_in_visible_menu_choice(self,cr, uid, context=None):
536         if context is None:
537             context = {}
538         if context.get('in_visible_menu_choice', False):
539             return context['in_visible_menu_choice']
540         return False
541
542     _columns = {
543         'title': fields.char('Column Heading', size=128, required=1),
544         'menu_choice': fields.text('Menu Choice'),
545         'rating_weight': fields.integer('Weight'),
546         'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
547         'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible ??'),
548         'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible??')
549     }
550     _defaults={
551        'in_visible_rating_weight': _get_in_visible_rating_weight,
552        'in_visible_menu_choice': _get_in_visible_menu_choice,
553     }
554 survey_question_column_heading()
555
556 class survey_answer(osv.osv):
557     _name = 'survey.answer'
558     _description = 'Survey Answer'
559     _rec_name = 'answer'
560     _order = 'sequence'
561
562     def _calc_response_avg(self, cr, uid, ids, field_name, arg, context=None):
563         val = {}
564         for rec in self.browse(cr, uid, ids, context=context):
565             cr.execute("select count(question_id) ,(select count(answer_id) \
566                 from survey_response_answer sra, survey_response_line sa \
567                 where sra.response_id = sa.id and sra.answer_id = %d \
568                 and sa.state='done') as tot_ans from survey_response_line \
569                 where question_id = %d and state = 'done'"\
570                      % (rec.id, rec.question_id.id))
571             res = cr.fetchone()
572             if res[0]:
573                 avg = float(res[1]) * 100 / res[0]
574             else:
575                 avg = 0.0
576             val[rec.id] = {
577                 'response': res[1],
578                 'average': round(avg, 2),
579             }
580         return val
581
582     def _get_in_visible_answer_type(self,cr, uid, context=None):
583         if context is None:
584             context = {}
585         return context.get('in_visible_answer_type', False)
586
587     _columns = {
588         'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
589         'answer': fields.char('Answer', size=128, required=1),
590         'sequence': fields.integer('Sequence'),
591         'response': fields.function(_calc_response_avg, string="#Answer", multi='sums'),
592         'average': fields.function(_calc_response_avg, string="#Avg", multi='sums'),
593         'type': fields.selection([('char','Character'),('date','Date'),('datetime','Date & Time'),\
594             ('integer','Integer'),('float','Float'),('selection','Selection'),\
595             ('email','Email')], "Type of Answer",required=1),
596         'menu_choice': fields.text('Menu Choices'),
597         'in_visible_answer_type': fields.boolean('Is Answer Type Invisible??')
598     }
599     _defaults = {
600 #         'sequence' : lambda * a: 1,
601          'type' : lambda * a: 'char',
602          'in_visible_answer_type':_get_in_visible_answer_type,
603     }
604
605     def default_get(self, cr, uid, fields, context=None):
606         if context is None:
607             context = {}
608         data = super(survey_answer, self).default_get(cr, uid, fields, context)
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("Email", 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'),('cancel', 'Cancelled'),('waiting_answer', 'Waiting Answer'),('done', 'Done')], 'Status', 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.user_email}}
744         return {}
745
746 survey_request()
747
748 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: