1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com>
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.
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.
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/>.
20 ##############################################################################
23 from osv import fields
26 from tools.translate import _
28 from time import strftime
29 from datetime import datetime
30 from dateutil.relativedelta import relativedelta
34 class survey_type(osv.osv):
36 _description = 'Survey Type'
38 'name': fields.char("Name", size=128, required=1, translate=True),
39 'code': fields.char("Code", size=64),
43 class survey(osv.osv):
45 _description = 'Survey'
48 def default_get(self, cr, uid, fields, context=None):
49 data = super(survey, self).default_get(cr, uid, fields, context)
53 'id': fields.integer('ID'),
54 'title': fields.char('Survey Title', size=128, required=1),
55 'page_ids': fields.one2many('survey.page', 'survey_id', 'Page'),
56 'date_open': fields.datetime('Survey Open Date', readonly=1),
57 'date_close': fields.datetime('Survey Close Date', readonly=1),
58 'max_response_limit': fields.integer('Maximum Answer Limit',
59 help="Set to one if survey is answerable only once"),
60 'response_user': fields.integer('Maximum Answer per User',
61 help="Set to one if you require only one Answer per user"),
62 'state': fields.selection([('open', 'Open'), ('cancel', 'Cancelled'),('close', 'Closed') ], 'Status', readonly=True),
63 'responsible_id': fields.many2one('res.users', 'Responsible', help="User responsible for survey"),
64 'tot_start_survey': fields.integer("Total Started Survey", readonly=1),
65 'tot_comp_survey': fields.integer("Total Completed Survey", readonly=1),
66 'note': fields.text('Description', size=128),
67 'history': fields.one2many('survey.history', 'survey_id', 'History Lines', readonly=True),
68 'users': fields.many2many('res.users', 'survey_users_rel', 'sid', 'uid', 'Users'),
69 'send_response': fields.boolean('Email Notification on Answer'),
70 'type': fields.many2one('survey.type', 'Type'),
71 'color': fields.integer('Color Index'),
72 'invited_user_ids': fields.many2many('res.users', 'survey_invited_user_rel', 'sid', 'uid', 'Invited User'),
75 'state': lambda * a: "open",
76 'tot_start_survey': lambda * a: 0,
77 'tot_comp_survey': lambda * a: 0,
78 'send_response': lambda * a: 1,
79 'response_user': lambda * a:1,
80 'date_open': fields.datetime.now,
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")})
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") })
91 def survey_cancel(self, cr, uid, ids, arg):
92 self.write(cr, uid, ids, {'state': 'cancel' })
95 def copy(self, cr, uid, ids, default=None, context=None):
97 current_rec = self.read(cr, uid, ids, context=context)
98 title = _("%s (copy)") % (current_rec.get('title'))
99 vals.update({'title':title})
100 vals.update({'history':[],'tot_start_survey':0,'tot_comp_survey':0})
101 return super(survey, self).copy(cr, uid, ids, vals, context=context)
103 def action_print_survey(self, cr, uid, ids, context=None):
105 If response is available then print this response otherwise print survey form(print template of the survey).
106 @param self: The object pointer
107 @param cr: the current row, from the database cursor,
108 @param uid: the current user’s ID for security checks,
109 @param ids: List of Survey IDs
110 @param context: A standard dictionary for contextual values
111 @return : Dictionary value for print survey form.
116 if 'response_id' in context:
117 response_id = context.get('response_id', 0)
118 datas['ids'] = [context.get('survey_id', 0)]
120 response_id = self.pool.get('survey.response').search(cr, uid, [('survey_id','=', ids)], context=context)
122 page_setting = {'orientation': 'vertical', 'without_pagebreak': 0, 'paper_size': 'letter', 'page_number': 1, 'survey_title': 1}
124 if response_id and response_id[0]:
125 context.update({'survey_id': datas['ids']})
126 datas['form'] = page_setting
127 datas['model'] = 'survey.print.answer'
129 'type': 'ir.actions.report.xml',
130 'report_name': 'survey.browse.response',
137 datas['form'] = page_setting
138 datas['model'] = 'survey.print'
140 'type': 'ir.actions.report.xml',
141 'report_name': 'survey.form',
148 def fill_survey(self, cr, uid, ids, context=None):
149 sur_obj = self.read(cr, uid, ids,['title', 'page_ids'], context=context)
152 pages = sur['page_ids']
154 raise osv.except_osv(_('Warning!'), _('This survey has no question defined. Please define the questions and answers first.'))
155 context.update({'active':False,'survey_id': ids[0]})
159 'res_model': 'survey.question.wiz',
160 'type': 'ir.actions.act_window',
165 def test_survey(self, cr, uid, ids, context=None):
166 sur_obj = self.read(cr, uid, ids,['title','page_ids'], context=context)
169 pages = sur['page_ids']
171 raise osv.except_osv(_('Warning!'), _('This survey has no pages defined. Please define pages first.'))
172 context.update({'active':False,'survey_id': ids[0]})
176 'res_model': 'survey.question.wiz',
177 'type': 'ir.actions.act_window',
183 def edit_survey(self, cr, uid, ids, context=None):
184 sur_obj = self.read(cr, uid, ids,['title','page_ids'], context=context)
187 pages = sur['page_ids']
189 raise osv.except_osv(_('Warning!'), _('This survey has no question defined. Please define the questions and answers first.'))
190 context.update({'survey_id': ids[0]})
194 'res_model': 'survey.question.wiz',
195 'type': 'ir.actions.act_window',
203 class survey_history(osv.osv):
204 _name = 'survey.history'
205 _description = 'Survey History'
208 'survey_id': fields.many2one('survey', 'Survey'),
209 'user_id': fields.many2one('res.users', 'User', readonly=True),
210 'date': fields.datetime('Date started', readonly=1),
213 'date': lambda * a: datetime.datetime.now()
217 class survey_page(osv.osv):
218 _name = 'survey.page'
219 _description = 'Survey Pages'
223 'title': fields.char('Page Title', size=128, required=1),
224 'survey_id': fields.many2one('survey', 'Survey', ondelete='cascade'),
225 'question_ids': fields.one2many('survey.question', 'page_id', 'Questions'),
226 'sequence': fields.integer('Page Nr'),
227 'note': fields.text('Description'),
230 'sequence': lambda * a: 1
233 def default_get(self, cr, uid, fields, context=None):
236 data = super(survey_page, self).default_get(cr, uid, fields, context)
237 if context.has_key('survey_id'):
238 data['survey_id'] = context.get('survey_id', False)
241 def survey_save(self, cr, uid, ids, context=None):
244 search_obj = self.pool.get('ir.ui.view')
245 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
246 surv_name_wiz = self.pool.get('survey.name.wiz')
247 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',0) })
251 'res_model': 'survey.question.wiz',
252 'type': 'ir.actions.act_window',
254 'search_view_id': search_id[0],
258 def copy(self, cr, uid, ids, default=None, context=None):
260 current_rec = self.read(cr, uid, ids, context=context)
261 title = _("%s (copy)") % (current_rec.get('title'))
262 vals.update({'title':title})
263 return super(survey_page, self).copy(cr, uid, ids, vals, context=context)
267 class survey_question(osv.osv):
268 _name = 'survey.question'
269 _description = 'Survey Question'
270 _rec_name = 'question'
273 def _calc_response(self, cr, uid, ids, field_name, arg, context=None):
277 cr.execute("select question_id, count(id) as Total_response from \
278 survey_response_line where state='done' and question_id IN %s\
279 group by question_id" ,(tuple(ids),))
280 ids1 = copy.deepcopy(ids)
281 for rec in cr.fetchall():
283 val[rec[0]] = int(rec[1])
289 'page_id': fields.many2one('survey.page', 'Survey Page', ondelete='cascade', required=1),
290 'question': fields.char('Question', size=128, required=1),
291 'answer_choice_ids': fields.one2many('survey.answer', 'question_id', 'Answer'),
292 'is_require_answer': fields.boolean('Require Answer to Question'),
293 'required_type': fields.selection([('all','All'), ('at least','At Least'), ('at most','At Most'), ('exactly','Exactly'), ('a range','A Range')], 'Respondent must answer'),
294 'req_ans': fields.integer('#Required Answer'),
295 'maximum_req_ans': fields.integer('Maximum Required Answer'),
296 'minimum_req_ans': fields.integer('Minimum Required Answer'),
297 'req_error_msg': fields.text('Error Message'),
298 'allow_comment': fields.boolean('Allow Comment Field'),
299 'sequence': fields.integer('Sequence'),
300 'tot_resp': fields.function(_calc_response, string="Total Answer"),
301 'survey': fields.related('page_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
302 'descriptive_text': fields.text('Descriptive Text', size=255),
303 'column_heading_ids': fields.one2many('survey.question.column.heading', 'question_id',' Column heading'),
304 'type': fields.selection([('multiple_choice_only_one_ans','Multiple Choice (Only One Answer)'),
305 ('multiple_choice_multiple_ans','Multiple Choice (Multiple Answer)'),
306 ('matrix_of_choices_only_one_ans','Matrix of Choices (Only One Answers Per Row)'),
307 ('matrix_of_choices_only_multi_ans','Matrix of Choices (Multiple Answers Per Row)'),
308 ('matrix_of_drop_down_menus','Matrix of Drop-down Menus'),
309 ('rating_scale','Rating Scale'),('single_textbox','Single Textbox'),
310 ('multiple_textboxes','Multiple Textboxes'),
311 ('multiple_textboxes_diff_type','Multiple Textboxes With Different Type'),
312 ('comment','Comment/Essay Box'),
313 ('numerical_textboxes','Numerical Textboxes'),('date','Date'),
314 ('date_and_time','Date and Time'),('descriptive_text','Descriptive Text'),
316 ], 'Question Type', required=1,),
317 'is_comment_require': fields.boolean('Add Comment Field'),
318 'comment_label': fields.char('Field Label', size = 255),
319 'comment_field_type': fields.selection([('char', 'Single Line Of Text'), ('text', 'Paragraph of Text')], 'Comment Field Type'),
320 'comment_valid_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),
321 ('must_be_specific_length', 'Must Be Specific Length'),
322 ('must_be_whole_number', 'Must Be A Whole Number'),
323 ('must_be_decimal_number', 'Must Be A Decimal Number'),
324 ('must_be_date', 'Must Be A Date'),
325 ('must_be_email_address', 'Must Be An Email Address'),
326 ], 'Text Validation'),
327 'comment_minimum_no': fields.integer('Minimum number'),
328 'comment_maximum_no': fields.integer('Maximum number'),
329 'comment_minimum_float': fields.float('Minimum decimal number'),
330 'comment_maximum_float': fields.float('Maximum decimal number'),
331 'comment_minimum_date': fields.date('Minimum date'),
332 'comment_maximum_date': fields.date('Maximum date'),
333 'comment_valid_err_msg': fields.text('Error message'),
334 'make_comment_field': fields.boolean('Make Comment Field an Answer Choice'),
335 'make_comment_field_err_msg': fields.text('Error message'),
336 'is_validation_require': fields.boolean('Validate Text'),
337 'validation_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),\
338 ('must_be_specific_length', 'Must Be Specific Length'),\
339 ('must_be_whole_number', 'Must Be A Whole Number'),\
340 ('must_be_decimal_number', 'Must Be A Decimal Number'),\
341 ('must_be_date', 'Must Be A Date'),\
342 ('must_be_email_address', 'Must Be An Email Address')\
343 ], 'Text Validation'),
344 'validation_minimum_no': fields.integer('Minimum number'),
345 'validation_maximum_no': fields.integer('Maximum number'),
346 'validation_minimum_float': fields.float('Minimum decimal number'),
347 'validation_maximum_float': fields.float('Maximum decimal number'),
348 'validation_minimum_date': fields.date('Minimum date'),
349 'validation_maximum_date': fields.date('Maximum date'),
350 'validation_valid_err_msg': fields.text('Error message'),
351 'numeric_required_sum': fields.integer('Sum of all choices'),
352 'numeric_required_sum_err_msg': fields.text('Error message'),
353 'rating_allow_one_column_require': fields.boolean('Allow Only One Answer per Column (Forced Ranking)'),
354 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible?'),
355 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible?'),
356 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible?'),
357 'comment_column': fields.boolean('Add comment column in matrix'),
358 'column_name': fields.char('Column Name',size=256),
359 'no_of_rows': fields.integer('No of Rows'),
362 'sequence': lambda * a: 1,
363 'type': lambda * a: 'multiple_choice_multiple_ans',
364 'req_error_msg': lambda * a: 'This question requires an answer.',
365 'required_type': lambda * a: 'at least',
366 'req_ans': lambda * a: 1,
367 'comment_field_type': lambda * a: 'char',
368 'comment_label': lambda * a: 'Other (please specify)',
369 'comment_valid_type': lambda * a: 'do_not_validate',
370 'comment_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
371 'validation_type': lambda * a: 'do_not_validate',
372 'validation_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
373 'numeric_required_sum_err_msg': lambda * a :'The choices need to add up to [enter sum here].',
374 'make_comment_field_err_msg': lambda * a : 'Please enter a comment.',
375 'in_visible_answer_type': lambda * a: 1
378 def on_change_type(self, cr, uid, ids, type, context=None):
380 val['is_require_answer'] = False
381 val['is_comment_require'] = False
382 val['is_validation_require'] = False
383 val['comment_column'] = False
385 if type in ['multiple_textboxes_diff_type']:
386 val['in_visible_answer_type'] = False
387 return {'value': val}
389 if type in ['rating_scale']:
390 val.update({'in_visible_rating_weight':False, 'in_visible_menu_choice':True})
391 return {'value': val}
393 elif type in ['matrix_of_drop_down_menus']:
394 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':False})
395 return {'value': val}
397 elif type in ['single_textbox']:
398 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True})
399 return {'value': val}
402 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True,\
403 'in_visible_answer_type':True})
404 return {'value': val}
406 def write(self, cr, uid, ids, vals, context=None):
407 questions = self.read(cr,uid, ids, ['answer_choice_ids', 'type', 'required_type',\
408 'req_ans', 'minimum_req_ans', 'maximum_req_ans', 'column_heading_ids', 'page_id', 'question'])
409 for question in questions:
410 col_len = len(question['column_heading_ids'])
411 if vals.has_key('column_heading_ids'):
412 for col in vals['column_heading_ids']:
413 if type(col[2]) == type({}):
418 if vals.has_key('type'):
419 que_type = vals['type']
421 que_type = question['type']
423 if que_type in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans',\
424 'matrix_of_drop_down_menus', 'rating_scale']:
426 raise osv.except_osv(_('Warning!'),_('You must enter one or more column headings for question "%s" of page %s.') % (question['question'], question['page_id'][1]))
427 ans_len = len(question['answer_choice_ids'])
429 if vals.has_key('answer_choice_ids'):
430 for ans in vals['answer_choice_ids']:
431 if type(ans[2]) == type({}):
436 if que_type not in ['descriptive_text', 'single_textbox', 'comment','table']:
438 raise osv.except_osv(_('Warning!'),_('You must enter one or more Answers for question "%s" of page %s.') % (question['question'], question['page_id'][1]))
441 if vals.has_key('required_type'):
442 req_type = vals['required_type']
444 req_type = question['required_type']
446 if que_type in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', \
447 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus',\
448 'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
449 if req_type in ['at least', 'at most', 'exactly']:
450 if vals.has_key('req_ans'):
451 if not vals['req_ans'] or vals['req_ans'] > ans_len:
452 raise osv.except_osv(_('Warning!'),_("#Required Answer you entered \
453 is greater than the number of answer. \
454 Please use a number that is smaller than %d.") % (ans_len + 1))
456 if not question['req_ans'] or question['req_ans'] > ans_len:
457 raise osv.except_osv(_('Warning!'),_("#Required Answer you entered is \
458 greater than the number of answer.\
459 Please use a number that is smaller than %d.") % (ans_len + 1))
461 if req_type == 'a range':
464 if vals.has_key('minimum_req_ans'):
465 minimum_ans = vals['minimum_req_ans']
466 if not vals['minimum_req_ans'] or vals['minimum_req_ans'] > ans_len:
467 raise osv.except_osv(_('Warning!'),_("Minimum Required Answer\
468 you entered is greater than the number of answer.\
469 Please use a number that is smaller than %d.") % (ans_len + 1))
471 minimum_ans = question['minimum_req_ans']
472 if not question['minimum_req_ans'] or question['minimum_req_ans'] > ans_len:
473 raise osv.except_osv(_('Warning!'),_("Minimum Required Answer you\
474 entered is greater than the number of answer. \
475 Please use a number that is smaller than %d.") % (ans_len + 1))
476 if vals.has_key('maximum_req_ans'):
477 maximum_ans = vals['maximum_req_ans']
478 if not vals['maximum_req_ans'] or vals['maximum_req_ans'] > ans_len:
479 raise osv.except_osv(_('Warning!'),_("Maximum Required Answer you \
480 entered for your maximum is greater than the number of answer.\
481 Please use a number that is smaller than %d.") % (ans_len + 1))
483 maximum_ans = question['maximum_req_ans']
484 if not question['maximum_req_ans'] or question['maximum_req_ans'] > ans_len:
485 raise osv.except_osv(_('Warning!'),_("Maximum Required Answer you\
486 entered for your maximum is greater than the number of answer.\
487 Please use a number that is smaller than %d.") % (ans_len + 1))
488 if maximum_ans <= minimum_ans:
489 raise osv.except_osv(_('Warning!'),_("Maximum Required Answer is greater \
490 than Minimum Required Answer"))
492 if question['type'] == 'matrix_of_drop_down_menus' and vals.has_key('column_heading_ids'):
493 for col in vals['column_heading_ids']:
494 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
495 raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices\
496 in column heading."))
497 elif not col[2] or not col[2].has_key('menu_choice') or\
498 col[2]['menu_choice'].strip() == '':
499 raise osv.except_osv(_('Warning!'),_("You must enter one or more menu \
500 choices in column heading (white spaces not allowed)."))
502 return super(survey_question, self).write(cr, uid, ids, vals, context=context)
504 def create(self, cr, uid, vals, context=None):
507 page = self.pool.get('survey.page').browse(cr, uid, vals['page_id'], context=context).title
508 if vals.has_key('answer_choice_ids') and not len(vals['answer_choice_ids']):
509 if vals.has_key('type') and vals['type'] not in ['descriptive_text', 'single_textbox', 'comment','table']:
510 raise osv.except_osv(_('Warning!'),_('You must enter one or more answers for question "%s" of page %s .') % (vals['question'], page))
512 if vals.has_key('column_heading_ids') and not len(vals['column_heading_ids']):
513 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']:
514 raise osv.except_osv(_('Warning!'),_('You must enter one or more column headings for question "%s" of page %s.')% (vals['question'], page))
516 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']:
517 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] in ['at least', 'at most', 'exactly']:
518 if vals.has_key('answer_choice_ids') and vals['req_ans'] > len(vals['answer_choice_ids']) or not vals['req_ans']:
519 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))
521 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] == 'a range':
522 minimum_ans = vals['minimum_req_ans']
523 maximum_ans = vals['maximum_req_ans']
524 if vals.has_key('answer_choice_ids') or vals['minimum_req_ans'] > len(vals['answer_choice_ids']) or not vals['minimum_req_ans']:
525 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))
526 if vals.has_key('answer_choice_ids') or vals['maximum_req_ans'] > len(vals['answer_choice_ids']) or not vals['maximum_req_ans']:
527 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))
528 if maximum_ans <= minimum_ans:
529 raise osv.except_osv(_('Warning!'),_("Maximum Required Answer is greater than Minimum Required Answer."))
531 if vals['type'] == 'matrix_of_drop_down_menus':
532 for col in vals['column_heading_ids']:
533 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
534 raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices in column heading."))
535 elif not col[2] or not col[2].has_key('menu_choice') or col[2]['menu_choice'].strip() == '':
536 raise osv.except_osv(_('Warning!'),_("You must enter one or more menu choices in column heading (white spaces not allowed)."))
538 res = super(survey_question, self).create(cr, uid, vals, context)
541 def survey_save(self, cr, uid, ids, context=None):
544 search_obj = self.pool.get('ir.ui.view')
545 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
546 surv_name_wiz = self.pool.get('survey.name.wiz')
547 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',False) })
551 'res_model': 'survey.question.wiz',
552 'type': 'ir.actions.act_window',
554 'search_view_id': search_id[0],
558 def default_get(self, cr, uid, fields, context=None):
561 data = super(survey_question, self).default_get(cr, uid, fields, context)
562 if context.has_key('page_id'):
563 data['page_id']= context.get('page_id', False)
569 class survey_question_column_heading(osv.osv):
570 _name = 'survey.question.column.heading'
571 _description = 'Survey Question Column Heading'
574 def _get_in_visible_rating_weight(self, cr, uid, context=None):
577 if context.get('in_visible_rating_weight', False):
578 return context['in_visible_rating_weight']
580 def _get_in_visible_menu_choice(self,cr, uid, context=None):
583 if context.get('in_visible_menu_choice', False):
584 return context['in_visible_menu_choice']
588 'title': fields.char('Column Heading', size=128, required=1),
589 'menu_choice': fields.text('Menu Choice'),
590 'rating_weight': fields.integer('Weight'),
591 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
592 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible ??'),
593 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible??')
596 'in_visible_rating_weight': _get_in_visible_rating_weight,
597 'in_visible_menu_choice': _get_in_visible_menu_choice,
599 survey_question_column_heading()
601 class survey_answer(osv.osv):
602 _name = 'survey.answer'
603 _description = 'Survey Answer'
607 def _calc_response_avg(self, cr, uid, ids, field_name, arg, context=None):
609 for rec in self.browse(cr, uid, ids, context=context):
610 cr.execute("select count(question_id) ,(select count(answer_id) \
611 from survey_response_answer sra, survey_response_line sa \
612 where sra.response_id = sa.id and sra.answer_id = %d \
613 and sa.state='done') as tot_ans from survey_response_line \
614 where question_id = %d and state = 'done'"\
615 % (rec.id, rec.question_id.id))
618 avg = float(res[1]) * 100 / res[0]
623 'average': round(avg, 2),
627 def _get_in_visible_answer_type(self, cr, uid, context=None):
630 return context.get('in_visible_answer_type', False)
633 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
634 'answer': fields.char('Answer', size=128, required=1),
635 'sequence': fields.integer('Sequence'),
636 'response': fields.function(_calc_response_avg, string="#Answer", multi='sums'),
637 'average': fields.function(_calc_response_avg, string="#Avg", multi='sums'),
638 'type': fields.selection([('char','Character'),('date','Date'),('datetime','Date & Time'),\
639 ('integer','Integer'),('float','Float'),('selection','Selection'),\
640 ('email','Email')], "Type of Answer",required=1),
641 'menu_choice': fields.text('Menu Choices'),
642 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible??')
645 # 'sequence' : lambda * a: 1,
646 'type' : lambda * a: 'char',
647 'in_visible_answer_type':_get_in_visible_answer_type,
650 def default_get(self, cr, uid, fields, context=None):
653 data = super(survey_answer, self).default_get(cr, uid, fields, context)
658 class survey_response(osv.osv):
659 _name = "survey.response"
660 _rec_name = 'date_create'
662 'survey_id' : fields.many2one('survey', 'Survey', required=1, ondelete='cascade'),
663 'date_create' : fields.datetime('Create Date', required=1),
664 'user_id' : fields.many2one('res.users', 'User'),
665 'response_type' : fields.selection([('manually', 'Manually'), ('link', 'Link')], \
666 'Answer Type', required=1, readonly=1),
667 'question_ids' : fields.one2many('survey.response.line', 'response_id', 'Answer'),
668 'state' : fields.selection([('done', 'Finished '),('skip', 'Not Finished')], \
669 'Status', readonly=True),
672 'state' : lambda * a: "skip",
673 'response_type' : lambda * a: "manually",
676 def name_get(self, cr, uid, ids, context=None):
679 reads = self.read(cr, uid, ids, ['user_id','date_create'], context=context)
682 name = (record['user_id'] and record['user_id'][1] or '' )+ ' (' + record['date_create'].split('.')[0] + ')'
683 res.append((record['id'], name))
686 def copy(self, cr, uid, id, default=None, context=None):
687 raise osv.except_osv(_('Warning!'),_('You cannot duplicate the resource!'))
691 class survey_response_line(osv.osv):
692 _name = 'survey.response.line'
693 _description = 'Survey Response Line'
694 _rec_name = 'date_create'
696 'response_id': fields.many2one('survey.response', 'Answer', ondelete='cascade'),
697 'date_create': fields.datetime('Create Date', required=1),
698 'state': fields.selection([('draft', 'Draft'), ('done', 'Answered'),('skip', 'Skiped')],\
699 'Status', readonly=True),
700 'question_id': fields.many2one('survey.question', 'Question'),
701 'page_id': fields.related('question_id', 'page_id', type='many2one', \
702 relation='survey.page', string='Page'),
703 'response_answer_ids': fields.one2many('survey.response.answer', 'response_id', 'Answer'),
704 'response_table_ids': fields.one2many('survey.tbl.column.heading', \
705 'response_table_id', 'Answer'),
706 'comment': fields.text('Notes'),
707 'single_text': fields.char('Text', size=255),
710 'state' : lambda * a: "draft",
713 survey_response_line()
715 class survey_tbl_column_heading(osv.osv):
716 _name = 'survey.tbl.column.heading'
719 'name': fields.integer('Row Number'),
720 'column_id': fields.many2one('survey.question.column.heading', 'Column'),
721 'value': fields.char('Value', size = 255),
722 'response_table_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
725 survey_tbl_column_heading()
727 class survey_response_answer(osv.osv):
728 _name = 'survey.response.answer'
729 _description = 'Survey Answer'
730 _rec_name = 'response_id'
732 'response_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
733 'answer_id': fields.many2one('survey.answer', 'Answer', required=1, ondelete='cascade'),
734 'column_id': fields.many2one('survey.question.column.heading','Column'),
735 'answer': fields.char('Value', size =255),
736 'value_choice': fields.char('Value Choice', size =255),
737 'comment': fields.text('Notes'),
738 'comment_field': fields.char('Comment', size = 255)
741 survey_response_answer()
743 class res_users(osv.osv):
744 _inherit = "res.users"
747 'survey_id': fields.many2many('survey', 'survey_users_rel', 'uid', 'sid', 'Groups'),
752 class survey_request(osv.osv):
753 _name = "survey.request"
754 _order = 'date_deadline'
755 _rec_name = 'date_deadline'
757 'date_deadline': fields.date("Deadline date"),
758 'user_id': fields.many2one("res.users", "User"),
759 'email': fields.char("Email", size=64),
760 'survey_id': fields.many2one("survey", "Survey", required=1, ondelete='cascade'),
761 'response': fields.many2one('survey.response', 'Answer'),
762 'state': fields.selection([('draft','Draft'),('cancel', 'Cancelled'),('waiting_answer', 'Waiting Answer'),('done', 'Done')], 'Status', readonly=1)
765 'state': lambda * a: 'draft',
766 # 'date_deadline': lambda * a : (datetime.now() + relativedelta(months=+1)).strftime("%Y-%m-%d %H:%M:%S")
768 def survey_req_waiting_answer(self, cr, uid, ids, arg):
769 self.write(cr, uid, ids, { 'state' : 'waiting_answer'})
772 def survey_req_draft(self, cr, uid, ids, arg):
773 self.write(cr, uid, ids, { 'state' : 'draft'})
776 def survey_req_done(self, cr, uid, ids, arg):
777 self.write(cr, uid, ids, { 'state' : 'done'})
780 def survey_req_cancel(self, cr, uid, ids, arg):
781 self.write(cr, uid, ids, { 'state' : 'cancel'})
784 def on_change_user(self, cr, uid, ids, user_id, context=None):
786 user_obj = self.pool.get('res.users')
787 user = user_obj.browse(cr, uid, user_id, context=context)
788 return {'value': {'email': user.email}}
793 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: