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