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