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