[IMP] indentation
[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, translate=True),
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         'date_open': fields.datetime.now,
81     }
82
83     def survey_open(self, cr, uid, ids, arg):
84         self.write(cr, uid, ids, {'state': 'open', 'date_open': strftime("%Y-%m-%d %H:%M:%S")})
85         return True
86
87     def survey_close(self, cr, uid, ids, arg):
88         self.write(cr, uid, ids, {'state': 'close', 'date_close': strftime("%Y-%m-%d %H:%M:%S") })
89         return True
90
91     def survey_cancel(self, cr, uid, ids, arg):
92         self.write(cr, uid, ids, {'state': 'cancel' })
93         return True
94
95     def copy(self, cr, uid, ids, default=None, context=None):
96         vals = {}
97         current_rec = self.read(cr, uid, ids, context=context)
98         title = _("%s (copy)") % (current_rec.get('title'))
99         vals.update({'title':title})
100         vals.update({'history':[],'tot_start_survey':0,'tot_comp_survey':0})
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
148     def fill_survey(self, cr, uid, ids, context=None):
149         sur_obj = self.read(cr, uid, ids,['title', 'page_ids'], context=context)
150         for sur in sur_obj:
151             name = sur['title']
152             pages = sur['page_ids']
153             if not pages:
154                 raise osv.except_osv(_('Warning!'), _('This survey has no question defined. Please define the questions and answers first.'))
155             context.update({'active':False,'survey_id': ids[0]})
156         return {
157             'view_type': 'form',
158             'view_mode': 'form',
159             'res_model': 'survey.question.wiz',
160             'type': 'ir.actions.act_window',
161             'target': 'new',
162             'name': name,
163             'context': context
164         }
165     def test_survey(self, cr, uid, ids, context=None):
166         sur_obj = self.read(cr, uid, ids,['title','page_ids'], context=context)
167         for sur in sur_obj:
168             name = sur['title']
169             pages = sur['page_ids']
170             if not pages:
171                 raise osv.except_osv(_('Warning!'), _('This survey has no pages defined. Please define pages first.'))
172             context.update({'active':False,'survey_id': ids[0]})
173         return {
174             'view_type': 'form',
175             'view_mode': 'form',
176             'res_model': 'survey.question.wiz',
177             'type': 'ir.actions.act_window',
178             'target': 'new',
179             'name': name,
180             'context': context
181         }
182
183     def edit_survey(self, cr, uid, ids, context=None):
184         sur_obj = self.read(cr, uid, ids,['title','page_ids'], context=context)
185         for sur in sur_obj:
186             name = sur['title']
187             pages = sur['page_ids']
188             if not pages:
189                 raise osv.except_osv(_('Warning!'), _('This survey has no question defined. Please define the questions and answers first.'))
190             context.update({'survey_id': ids[0]})
191         return {
192             'view_type': 'form',
193             'view_mode': 'form',
194             'res_model': 'survey.question.wiz',
195             'type': 'ir.actions.act_window',
196             'target': 'new',
197             'name': name,
198             'context': context
199         }
200
201 survey()
202
203 class survey_history(osv.osv):
204     _name = 'survey.history'
205     _description = 'Survey History'
206     _rec_name = 'date'
207     _columns = {
208         'survey_id': fields.many2one('survey', 'Survey'),
209         'user_id': fields.many2one('res.users', 'User', readonly=True),
210         'date': fields.datetime('Date started', readonly=1),
211     }
212     _defaults = {
213          'date': lambda * a: datetime.datetime.now()
214     }
215 survey_history()
216
217 class survey_page(osv.osv):
218     _name = 'survey.page'
219     _description = 'Survey Pages'
220     _rec_name = 'title'
221     _order = 'sequence'
222     _columns = {
223         'title': fields.char('Page Title', size=128, required=1),
224         'survey_id': fields.many2one('survey', 'Survey', ondelete='cascade'),
225         'question_ids': fields.one2many('survey.question', 'page_id', 'Questions'),
226         'sequence': fields.integer('Page Nr'),
227         'note': fields.text('Description'),
228     }
229     _defaults = {
230         'sequence': lambda * a: 1
231     }
232
233     def default_get(self, cr, uid, fields, context=None):
234         if context is None:
235             context = {}
236         data = super(survey_page, self).default_get(cr, uid, fields, context)
237         if context.has_key('survey_id'):
238             data['survey_id'] = context.get('survey_id', False)
239         return data
240
241     def survey_save(self, cr, uid, ids, context=None):
242         if context is None:
243             context = {}
244         search_obj = self.pool.get('ir.ui.view')
245         search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
246         surv_name_wiz = self.pool.get('survey.name.wiz')
247         surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',0) })
248         return {
249             'view_type': 'form',
250             'view_mode': 'form',
251             'res_model': 'survey.question.wiz',
252             'type': 'ir.actions.act_window',
253             'target': 'new',
254             'search_view_id': search_id[0],
255             'context': context
256         }
257
258     def copy(self, cr, uid, ids, default=None, context=None):
259         vals = {}
260         current_rec = self.read(cr, uid, ids, context=context)
261         title = _("%s (copy)") % (current_rec.get('title'))
262         vals.update({'title':title})
263         return super(survey_page, self).copy(cr, uid, ids, vals, context=context)
264
265 survey_page()
266
267 class survey_question(osv.osv):
268     _name = 'survey.question'
269     _description = 'Survey Question'
270     _rec_name = 'question'
271     _order = 'sequence'
272
273     def _calc_response(self, cr, uid, ids, field_name, arg, context=None):
274         if len(ids) == 0:
275             return {}
276         val = {}
277         cr.execute("select question_id, count(id) as Total_response from \
278                 survey_response_line where state='done' and question_id IN %s\
279                  group by question_id" ,(tuple(ids),))
280         ids1 = copy.deepcopy(ids)
281         for rec in  cr.fetchall():
282             ids1.remove(rec[0])
283             val[rec[0]] = int(rec[1])
284         for id in ids1:
285             val[id] = 0
286         return val
287
288     _columns = {
289         'page_id': fields.many2one('survey.page', 'Survey Page', ondelete='cascade', required=1),
290         'question':  fields.char('Question', size=128, required=1),
291         'answer_choice_ids': fields.one2many('survey.answer', 'question_id', 'Answer'),
292         'is_require_answer': fields.boolean('Require Answer to Question'),
293         'required_type': fields.selection([('all','All'), ('at least','At Least'), ('at most','At Most'), ('exactly','Exactly'), ('a range','A Range')], 'Respondent must answer'),
294         'req_ans': fields.integer('#Required Answer'),
295         'maximum_req_ans': fields.integer('Maximum Required Answer'),
296         'minimum_req_ans': fields.integer('Minimum Required Answer'),
297         'req_error_msg': fields.text('Error Message'),
298         'allow_comment': fields.boolean('Allow Comment Field'),
299         'sequence': fields.integer('Sequence'),
300         'tot_resp': fields.function(_calc_response, string="Total Answer"),
301         'survey': fields.related('page_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
302         'descriptive_text': fields.text('Descriptive Text', size=255),
303         'column_heading_ids': fields.one2many('survey.question.column.heading', 'question_id',' Column heading'),
304         'type': fields.selection([('multiple_choice_only_one_ans','Multiple Choice (Only One Answer)'),
305              ('multiple_choice_multiple_ans','Multiple Choice (Multiple Answer)'),
306              ('matrix_of_choices_only_one_ans','Matrix of Choices (Only One Answers Per Row)'),
307              ('matrix_of_choices_only_multi_ans','Matrix of Choices (Multiple Answers Per Row)'),
308              ('matrix_of_drop_down_menus','Matrix of Drop-down Menus'),
309              ('rating_scale','Rating Scale'),('single_textbox','Single Textbox'),
310              ('multiple_textboxes','Multiple Textboxes'),
311              ('multiple_textboxes_diff_type','Multiple Textboxes With Different Type'),
312              ('comment','Comment/Essay Box'),
313              ('numerical_textboxes','Numerical Textboxes'),('date','Date'),
314              ('date_and_time','Date and Time'),('descriptive_text','Descriptive Text'),
315              ('table','Table'),
316             ], 'Question Type',  required=1,),
317         'is_comment_require': fields.boolean('Add Comment Field'),
318         'comment_label': fields.char('Field Label', size = 255),
319         'comment_field_type': fields.selection([('char', 'Single Line Of Text'), ('text', 'Paragraph of Text')], 'Comment Field Type'),
320         'comment_valid_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),
321              ('must_be_specific_length', 'Must Be Specific Length'),
322              ('must_be_whole_number', 'Must Be A Whole Number'),
323              ('must_be_decimal_number', 'Must Be A Decimal Number'),
324              ('must_be_date', 'Must Be A Date'),
325              ('must_be_email_address', 'Must Be An Email Address'),
326              ], 'Text Validation'),
327         'comment_minimum_no': fields.integer('Minimum number'),
328         'comment_maximum_no': fields.integer('Maximum number'),
329         'comment_minimum_float': fields.float('Minimum decimal number'),
330         'comment_maximum_float': fields.float('Maximum decimal number'),
331         'comment_minimum_date': fields.date('Minimum date'),
332         'comment_maximum_date': fields.date('Maximum date'),
333         'comment_valid_err_msg': fields.text('Error message'),
334         'make_comment_field': fields.boolean('Make Comment Field an Answer Choice'),
335         'make_comment_field_err_msg': fields.text('Error message'),
336         'is_validation_require': fields.boolean('Validate Text'),
337         'validation_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),\
338              ('must_be_specific_length', 'Must Be Specific Length'),\
339              ('must_be_whole_number', 'Must Be A Whole Number'),\
340              ('must_be_decimal_number', 'Must Be A Decimal Number'),\
341              ('must_be_date', 'Must Be A Date'),\
342              ('must_be_email_address', 'Must Be An Email Address')\
343              ], 'Text Validation'),
344         'validation_minimum_no': fields.integer('Minimum number'),
345         'validation_maximum_no': fields.integer('Maximum number'),
346         'validation_minimum_float': fields.float('Minimum decimal number'),
347         'validation_maximum_float': fields.float('Maximum decimal number'),
348         'validation_minimum_date': fields.date('Minimum date'),
349         'validation_maximum_date': fields.date('Maximum date'),
350         'validation_valid_err_msg': fields.text('Error message'),
351         'numeric_required_sum': fields.integer('Sum of all choices'),
352         'numeric_required_sum_err_msg': fields.text('Error message'),
353         'rating_allow_one_column_require': fields.boolean('Allow Only One Answer per Column (Forced Ranking)'),
354         'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible?'),
355         'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible?'),
356         'in_visible_answer_type': fields.boolean('Is Answer Type Invisible?'),
357         'comment_column': fields.boolean('Add comment column in matrix'),
358         'column_name': fields.char('Column Name',size=256),
359         'no_of_rows': fields.integer('No of Rows'),
360     }
361     _defaults = {
362          'sequence': lambda * a: 1,
363          'type': lambda * a: 'multiple_choice_multiple_ans',
364          'req_error_msg': lambda * a: 'This question requires an answer.',
365          'required_type': lambda * a: 'at least',
366          'req_ans': lambda * a: 1,
367          'comment_field_type': lambda * a: 'char',
368          'comment_label': lambda * a: 'Other (please specify)',
369          'comment_valid_type': lambda * a: 'do_not_validate',
370          'comment_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
371          'validation_type': lambda * a: 'do_not_validate',
372          'validation_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
373          'numeric_required_sum_err_msg': lambda * a :'The choices need to add up to [enter sum here].',
374          'make_comment_field_err_msg': lambda * a : 'Please enter a comment.',
375          'in_visible_answer_type': lambda * a: 1
376     }
377
378     def on_change_type(self, cr, uid, ids, type, context=None):
379         val = {}
380         val['is_require_answer'] = False
381         val['is_comment_require'] = False
382         val['is_validation_require'] = False
383         val['comment_column'] = False
384
385         if type in ['multiple_textboxes_diff_type']:
386             val['in_visible_answer_type'] = False
387             return {'value': val}
388
389         if type in ['rating_scale']:
390             val.update({'in_visible_rating_weight':False, 'in_visible_menu_choice':True})
391             return {'value': val}
392
393         elif type in ['matrix_of_drop_down_menus']:
394             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':False})
395             return {'value': val}
396
397         elif type in ['single_textbox']:
398             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True})
399             return {'value': val}
400
401         else:
402             val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True,\
403                          'in_visible_answer_type':True})
404             return {'value': val}
405
406     def write(self, cr, uid, ids, vals, context=None):
407         questions = self.read(cr,uid, ids, ['answer_choice_ids', 'type', 'required_type',\
408                         'req_ans', 'minimum_req_ans', 'maximum_req_ans', 'column_heading_ids', 'page_id', 'question'])
409         for question in questions:
410             col_len = len(question['column_heading_ids'])
411             if vals.has_key('column_heading_ids'):
412                 for col in vals['column_heading_ids']:
413                     if type(col[2]) == type({}):
414                         col_len += 1
415                     else:
416                         col_len -= 1
417
418             if vals.has_key('type'):
419                 que_type = vals['type']
420             else:
421                 que_type = question['type']
422
423             if que_type in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans',\
424                              'matrix_of_drop_down_menus', 'rating_scale']:
425                 if not col_len:
426                     raise osv.except_osv(_('Warning!'),_('You must enter one or more column headings for question "%s" of page %s.') % (question['question'], question['page_id'][1]))
427             ans_len = len(question['answer_choice_ids'])
428
429             if vals.has_key('answer_choice_ids'):
430                 for ans in vals['answer_choice_ids']:
431                     if type(ans[2]) == type({}):
432                         ans_len += 1
433                     else:
434                         ans_len -= 1
435
436             if que_type not in ['descriptive_text', 'single_textbox', 'comment','table']:
437                 if not ans_len:
438                     raise osv.except_osv(_('Warning!'),_('You must enter one or more Answers for question "%s" of page %s.') % (question['question'], question['page_id'][1]))
439             req_type = ""
440
441             if vals.has_key('required_type'):
442                 req_type = vals['required_type']
443             else:
444                 req_type = question['required_type']
445
446             if que_type in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', \
447                         'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus',\
448                          'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
449                 if req_type in ['at least', 'at most', 'exactly']:
450                     if vals.has_key('req_ans'):
451                         if not vals['req_ans'] or  vals['req_ans'] > ans_len:
452                             raise osv.except_osv(_('Warning!'),_("#Required Answer you entered \
453                                     is greater than the number of answer. \
454                                     Please use a number that is smaller than %d.") % (ans_len + 1))
455                     else:
456                         if not question['req_ans'] or  question['req_ans'] > ans_len:
457                             raise osv.except_osv(_('Warning!'),_("#Required Answer you entered is \
458                                     greater than the number of answer.\
459                                     Please use a number that is smaller than %d.") % (ans_len + 1))
460
461                 if req_type == 'a range':
462                     minimum_ans = 0
463                     maximum_ans = 0
464                     if vals.has_key('minimum_req_ans'):
465                         minimum_ans = vals['minimum_req_ans']
466                         if not vals['minimum_req_ans'] or  vals['minimum_req_ans'] > ans_len:
467                             raise osv.except_osv(_('Warning!'),_("Minimum Required Answer\
468                                      you entered is greater than the number of answer.\
469                                     Please use a number that is smaller than %d.") % (ans_len + 1))
470                     else:
471                         minimum_ans = question['minimum_req_ans']
472                         if not question['minimum_req_ans'] or  question['minimum_req_ans'] > ans_len:
473                             raise osv.except_osv(_('Warning!'),_("Minimum Required Answer you\
474                                      entered is greater than the number of answer. \
475                                      Please use a number that is smaller than %d.") % (ans_len + 1))
476                     if vals.has_key('maximum_req_ans'):
477                         maximum_ans = vals['maximum_req_ans']
478                         if not vals['maximum_req_ans'] or vals['maximum_req_ans'] > ans_len:
479                             raise osv.except_osv(_('Warning!'),_("Maximum Required Answer you \
480                                     entered for your maximum is greater than the number of answer.\
481                                      Please use a number that is smaller than %d.") % (ans_len + 1))
482                     else:
483                         maximum_ans = question['maximum_req_ans']
484                         if not question['maximum_req_ans'] or question['maximum_req_ans'] > ans_len:
485                             raise osv.except_osv(_('Warning!'),_("Maximum Required Answer you\
486                                      entered for your maximum is greater than the number of answer.\
487                                       Please use a number that is smaller than %d.") % (ans_len + 1))
488                     if maximum_ans <= minimum_ans:
489                         raise osv.except_osv(_('Warning!'),_("Maximum Required Answer is greater \
490                                     than Minimum Required Answer"))
491
492             if question['type'] ==  'matrix_of_drop_down_menus' and vals.has_key('column_heading_ids'):
493                 for col in vals['column_heading_ids']:
494                     if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
495                         raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices\
496                                  in column heading."))
497                     elif not col[2] or not col[2].has_key('menu_choice') or\
498                              col[2]['menu_choice'].strip() == '':
499                         raise osv.except_osv(_('Warning!'),_("You must enter one or more menu \
500                                 choices in column heading (white spaces not allowed)."))
501
502         return super(survey_question, self).write(cr, uid, ids, vals, context=context)
503
504     def create(self, cr, uid, vals, context=None):
505         minimum_ans = 0
506         maximum_ans = 0
507         page = self.pool.get('survey.page').browse(cr, uid, vals['page_id'], context=context).title
508         if vals.has_key('answer_choice_ids') and  not len(vals['answer_choice_ids']):
509             if vals.has_key('type') and vals['type'] not in ['descriptive_text', 'single_textbox', 'comment','table']:
510                 raise osv.except_osv(_('Warning!'),_('You must enter one or more answers for question "%s" of page %s .') % (vals['question'], page))
511
512         if vals.has_key('column_heading_ids') and  not len(vals['column_heading_ids']):
513             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']:
514                 raise osv.except_osv(_('Warning!'),_('You must enter one or more column headings for question "%s" of page %s.')% (vals['question'], page))
515
516         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']:
517             if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] in ['at least', 'at most', 'exactly']:
518                 if vals.has_key('answer_choice_ids') and vals['req_ans'] > len(vals['answer_choice_ids']) or not vals['req_ans']:
519                     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))
520
521             if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] == 'a range':
522                 minimum_ans = vals['minimum_req_ans']
523                 maximum_ans = vals['maximum_req_ans']
524                 if vals.has_key('answer_choice_ids') or vals['minimum_req_ans'] > len(vals['answer_choice_ids']) or not vals['minimum_req_ans']:
525                     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))
526                 if vals.has_key('answer_choice_ids') or vals['maximum_req_ans'] > len(vals['answer_choice_ids']) or not vals['maximum_req_ans']:
527                     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))
528                 if maximum_ans <= minimum_ans:
529                     raise osv.except_osv(_('Warning!'),_("Maximum Required Answer is greater than Minimum Required Answer."))
530
531         if vals['type'] ==  'matrix_of_drop_down_menus':
532             for col in vals['column_heading_ids']:
533                 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
534                     raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices in column heading."))
535                 elif not col[2] or not col[2].has_key('menu_choice') or col[2]['menu_choice'].strip() == '':
536                     raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices in column heading (white spaces not allowed)."))
537
538         res = super(survey_question, self).create(cr, uid, vals, context)
539         return res
540
541     def survey_save(self, cr, uid, ids, context=None):
542         if context is None:
543             context = {}
544         search_obj = self.pool.get('ir.ui.view')
545         search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
546         surv_name_wiz = self.pool.get('survey.name.wiz')
547         surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',False) })
548         return {
549             'view_type': 'form',
550             'view_mode': 'form',
551             'res_model': 'survey.question.wiz',
552             'type': 'ir.actions.act_window',
553             'target': 'new',
554             'search_view_id': search_id[0],
555             'context': context
556         }
557
558     def default_get(self, cr, uid, fields, context=None):
559         if context is None:
560             context = {}
561         data = super(survey_question, self).default_get(cr, uid, fields, context)
562         if context.has_key('page_id'):
563             data['page_id']= context.get('page_id', False)
564         return data
565
566 survey_question()
567
568
569 class survey_question_column_heading(osv.osv):
570     _name = 'survey.question.column.heading'
571     _description = 'Survey Question Column Heading'
572     _rec_name = 'title'
573
574     def _get_in_visible_rating_weight(self, cr, uid, context=None):
575         if context is None:
576             context = {}
577         if context.get('in_visible_rating_weight', False):
578             return context['in_visible_rating_weight']
579         return False
580     def _get_in_visible_menu_choice(self,cr, uid, context=None):
581         if context is None:
582             context = {}
583         if context.get('in_visible_menu_choice', False):
584             return context['in_visible_menu_choice']
585         return False
586
587     _columns = {
588         'title': fields.char('Column Heading', size=128, required=1),
589         'menu_choice': fields.text('Menu Choice'),
590         'rating_weight': fields.integer('Weight'),
591         'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
592         'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible ??'),
593         'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible??')
594     }
595     _defaults={
596        'in_visible_rating_weight': _get_in_visible_rating_weight,
597        'in_visible_menu_choice': _get_in_visible_menu_choice,
598     }
599 survey_question_column_heading()
600
601 class survey_answer(osv.osv):
602     _name = 'survey.answer'
603     _description = 'Survey Answer'
604     _rec_name = 'answer'
605     _order = 'sequence'
606
607     def _calc_response_avg(self, cr, uid, ids, field_name, arg, context=None):
608         val = {}
609         for rec in self.browse(cr, uid, ids, context=context):
610             cr.execute("select count(question_id) ,(select count(answer_id) \
611                 from survey_response_answer sra, survey_response_line sa \
612                 where sra.response_id = sa.id and sra.answer_id = %d \
613                 and sa.state='done') as tot_ans from survey_response_line \
614                 where question_id = %d and state = 'done'"\
615                      % (rec.id, rec.question_id.id))
616             res = cr.fetchone()
617             if res[0]:
618                 avg = float(res[1]) * 100 / res[0]
619             else:
620                 avg = 0.0
621             val[rec.id] = {
622                 'response': res[1],
623                 'average': round(avg, 2),
624             }
625         return val
626
627     def _get_in_visible_answer_type(self, cr, uid, context=None):
628         if context is None:
629             context = {}
630         return context.get('in_visible_answer_type', False)
631
632     _columns = {
633         'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
634         'answer': fields.char('Answer', size=128, required=1),
635         'sequence': fields.integer('Sequence'),
636         'response': fields.function(_calc_response_avg, string="#Answer", multi='sums'),
637         'average': fields.function(_calc_response_avg, string="#Avg", multi='sums'),
638         'type': fields.selection([('char','Character'),('date','Date'),('datetime','Date & Time'),\
639             ('integer','Integer'),('float','Float'),('selection','Selection'),\
640             ('email','Email')], "Type of Answer",required=1),
641         'menu_choice': fields.text('Menu Choices'),
642         'in_visible_answer_type': fields.boolean('Is Answer Type Invisible??')
643     }
644     _defaults = {
645 #         'sequence' : lambda * a: 1,
646          'type' : lambda * a: 'char',
647          'in_visible_answer_type':_get_in_visible_answer_type,
648     }
649
650     def default_get(self, cr, uid, fields, context=None):
651         if context is None:
652             context = {}
653         data = super(survey_answer, self).default_get(cr, uid, fields, context)
654         return data
655
656 survey_answer()
657
658 class survey_response(osv.osv):
659     _name = "survey.response"
660     _rec_name = 'date_create'
661     _columns = {
662         'survey_id' : fields.many2one('survey', 'Survey', required=1, ondelete='cascade'),
663         'date_create' : fields.datetime('Create Date', required=1),
664         'user_id' : fields.many2one('res.users', 'User'),
665         'response_type' : fields.selection([('manually', 'Manually'), ('link', 'Link')], \
666                                     'Answer Type', required=1, readonly=1),
667         'question_ids' : fields.one2many('survey.response.line', 'response_id', 'Answer'),
668         'state' : fields.selection([('done', 'Finished '),('skip', 'Not Finished')], \
669                             'Status', readonly=True),
670     }
671     _defaults = {
672         'state' : lambda * a: "skip",
673         'response_type' : lambda * a: "manually",
674     }
675
676     def name_get(self, cr, uid, ids, context=None):
677         if not len(ids):
678             return []
679         reads = self.read(cr, uid, ids, ['user_id','date_create'], context=context)
680         res = []
681         for record in reads:
682             name = (record['user_id'] and record['user_id'][1] or '' )+ ' (' + record['date_create'].split('.')[0] + ')'
683             res.append((record['id'], name))
684         return res
685
686     def copy(self, cr, uid, id, default=None, context=None):
687         raise osv.except_osv(_('Warning!'),_('You cannot duplicate the resource!'))
688
689 survey_response()
690
691 class survey_response_line(osv.osv):
692     _name = 'survey.response.line'
693     _description = 'Survey Response Line'
694     _rec_name = 'date_create'
695     _columns = {
696         'response_id': fields.many2one('survey.response', 'Answer', ondelete='cascade'),
697         'date_create': fields.datetime('Create Date', required=1),
698         'state': fields.selection([('draft', 'Draft'), ('done', 'Answered'),('skip', 'Skiped')],\
699                                    'Status', readonly=True),
700         'question_id': fields.many2one('survey.question', 'Question'),
701         'page_id': fields.related('question_id', 'page_id', type='many2one', \
702                                   relation='survey.page', string='Page'),
703         'response_answer_ids': fields.one2many('survey.response.answer', 'response_id', 'Answer'),
704         'response_table_ids': fields.one2many('survey.tbl.column.heading', \
705                                     'response_table_id', 'Answer'),
706         'comment': fields.text('Notes'),
707         'single_text': fields.char('Text', size=255),
708     }
709     _defaults = {
710         'state' : lambda * a: "draft",
711     }
712
713 survey_response_line()
714
715 class survey_tbl_column_heading(osv.osv):
716     _name = 'survey.tbl.column.heading'
717     _order = 'name'
718     _columns = {
719         'name': fields.integer('Row Number'),
720         'column_id': fields.many2one('survey.question.column.heading', 'Column'),
721         'value': fields.char('Value', size = 255),
722         'response_table_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
723     }
724
725 survey_tbl_column_heading()
726
727 class survey_response_answer(osv.osv):
728     _name = 'survey.response.answer'
729     _description = 'Survey Answer'
730     _rec_name = 'response_id'
731     _columns = {
732         'response_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
733         'answer_id': fields.many2one('survey.answer', 'Answer', required=1, ondelete='cascade'),
734         'column_id': fields.many2one('survey.question.column.heading','Column'),
735         'answer': fields.char('Value', size =255),
736         'value_choice': fields.char('Value Choice', size =255),
737         'comment': fields.text('Notes'),
738         'comment_field': fields.char('Comment', size = 255)
739     }
740
741 survey_response_answer()
742
743 class res_users(osv.osv):
744     _inherit = "res.users"
745     _name = "res.users"
746     _columns = {
747         'survey_id': fields.many2many('survey', 'survey_users_rel', 'uid', 'sid', 'Groups'),
748     }
749
750 res_users()
751
752 class survey_request(osv.osv):
753     _name = "survey.request"
754     _order = 'date_deadline'
755     _rec_name = 'date_deadline'
756     _columns = {
757         'date_deadline': fields.date("Deadline date"),
758         'user_id': fields.many2one("res.users", "User"),
759         'email': fields.char("Email", size=64),
760         'survey_id': fields.many2one("survey", "Survey", required=1, ondelete='cascade'),
761         'response': fields.many2one('survey.response', 'Answer'),
762         'state': fields.selection([('draft','Draft'),('cancel', 'Cancelled'),('waiting_answer', 'Waiting Answer'),('done', 'Done')], 'Status', readonly=1)
763     }
764     _defaults = {
765         'state': lambda * a: 'draft',
766 #        'date_deadline': lambda * a :  (datetime.now() + relativedelta(months=+1)).strftime("%Y-%m-%d %H:%M:%S")
767     }
768     def survey_req_waiting_answer(self, cr, uid, ids, arg):
769         self.write(cr, uid, ids, { 'state' : 'waiting_answer'})
770         return True
771
772     def survey_req_draft(self, cr, uid, ids, arg):
773         self.write(cr, uid, ids, { 'state' : 'draft'})
774         return True
775
776     def survey_req_done(self, cr, uid, ids, arg):
777         self.write(cr, uid, ids, { 'state' : 'done'})
778         return True
779
780     def survey_req_cancel(self, cr, uid, ids, arg):
781         self.write(cr, uid, ids, { 'state' : 'cancel'})
782         return True
783
784     def on_change_user(self, cr, uid, ids, user_id, context=None):
785         if user_id:
786             user_obj = self.pool.get('res.users')
787             user = user_obj.browse(cr, uid, user_id, context=context)
788             return {'value': {'email': user.email}}
789         return {}
790
791 survey_request()
792
793 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: