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