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