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