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),
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 'invited_user_ids': fields.many2many('res.users', 'survey_invited_user_rel', 'sid', 'uid', 'Invited User'),
74 'state': lambda * a: "open",
75 'tot_start_survey': lambda * a: 0,
76 'tot_comp_survey': lambda * a: 0,
77 'send_response': lambda * a: 1,
78 'response_user': lambda * a:1,
81 def survey_open(self, cr, uid, ids, arg):
82 self.write(cr, uid, ids, {'state': 'open', 'date_open': strftime("%Y-%m-%d %H:%M:%S")})
85 def survey_close(self, cr, uid, ids, arg):
86 self.write(cr, uid, ids, {'state': 'close', 'date_close': strftime("%Y-%m-%d %H:%M:%S") })
89 def survey_cancel(self, cr, uid, ids, arg):
90 self.write(cr, uid, ids, {'state': 'cancel' })
93 def copy(self, cr, uid, ids, default=None, context=None):
95 current_rec = self.read(cr, uid, ids, context=context)
96 title = current_rec.get('title') + ' (Copy)'
97 vals.update({'title':title})
98 vals.update({'history':[],'tot_start_survey':0,'tot_comp_survey':0})
99 return super(survey, self).copy(cr, uid, ids, vals, context=context)
101 def action_print_survey(self, cr, uid, ids, context=None):
103 If response is available then print this response otherwise print survey form(print template of the survey).
104 @param self: The object pointer
105 @param cr: the current row, from the database cursor,
106 @param uid: the current user’s ID for security checks,
107 @param ids: List of Survey IDs
108 @param context: A standard dictionary for contextual values
109 @return : Dictionary value for print survey form.
114 if 'response_id' in context:
115 response_id = context.get('response_id', 0)
116 datas['ids'] = [context.get('survey_id', 0)]
118 response_id = self.pool.get('survey.response').search(cr, uid, [('survey_id','=', ids)], context=context)
120 page_setting = {'orientation': 'vertical', 'without_pagebreak': 0, 'paper_size': 'letter', 'page_number': 1, 'survey_title': 1}
122 if response_id and response_id[0]:
123 context.update({'survey_id': datas['ids']})
124 datas['form'] = page_setting
125 datas['model'] = 'survey.print.answer'
127 'type': 'ir.actions.report.xml',
128 'report_name': 'survey.browse.response',
135 datas['form'] = page_setting
136 datas['model'] = 'survey.print'
138 'type': 'ir.actions.report.xml',
139 'report_name': 'survey.form',
146 def fill_survey(self, cr, uid, ids, context=None):
150 'res_model': 'survey.question.wiz',
151 'type': 'ir.actions.act_window',
153 'context': {'survey_id': ids[0]}
158 class survey_history(osv.osv):
159 _name = 'survey.history'
160 _description = 'Survey History'
163 'survey_id': fields.many2one('survey', 'Survey'),
164 'user_id': fields.many2one('res.users', 'User', readonly=True),
165 'date': fields.datetime('Date started', readonly=1),
168 'date': lambda * a: datetime.datetime.now()
172 class survey_page(osv.osv):
173 _name = 'survey.page'
174 _description = 'Survey Pages'
178 'title': fields.char('Page Title', size=128, required=1),
179 'survey_id': fields.many2one('survey', 'Survey', ondelete='cascade'),
180 'question_ids': fields.one2many('survey.question', 'page_id', 'Question'),
181 'sequence': fields.integer('Page Nr'),
182 'note': fields.text('Description'),
185 'sequence': lambda * a: 1
188 def default_get(self, cr, uid, fields, context=None):
191 data = super(survey_page, self).default_get(cr, uid, fields, context)
192 if context.has_key('survey_id'):
193 data['survey_id'] = context.get('survey_id', False)
196 def survey_save(self, cr, uid, ids, context=None):
199 search_obj = self.pool.get('ir.ui.view')
200 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
201 surv_name_wiz = self.pool.get('survey.name.wiz')
202 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',0) })
206 'res_model': 'survey.question.wiz',
207 'type': 'ir.actions.act_window',
209 'search_view_id': search_id[0],
213 def copy(self, cr, uid, ids, default=None, context=None):
215 current_rec = self.read(cr, uid, ids, context=context)
216 title = current_rec.get('title') + ' (Copy)'
217 vals.update({'title':title})
218 return super(survey_page, self).copy(cr, uid, ids, vals, context=context)
222 class survey_question(osv.osv):
223 _name = 'survey.question'
224 _description = 'Survey Question'
225 _rec_name = 'question'
228 def _calc_response(self, cr, uid, ids, field_name, arg, context=None):
232 cr.execute("select question_id, count(id) as Total_response from \
233 survey_response_line where state='done' and question_id IN %s\
234 group by question_id" ,(tuple(ids),))
235 ids1 = copy.deepcopy(ids)
236 for rec in cr.fetchall():
238 val[rec[0]] = int(rec[1])
244 'page_id': fields.many2one('survey.page', 'Survey Page', ondelete='cascade', required=1),
245 'question': fields.char('Question', size=128, required=1),
246 'answer_choice_ids': fields.one2many('survey.answer', 'question_id', 'Answer'),
247 'is_require_answer': fields.boolean('Require Answer to Question'),
248 'required_type': fields.selection([('all','All'), ('at least','At Least'), ('at most','At Most'), ('exactly','Exactly'), ('a range','A Range')], 'Respondent must answer'),
249 'req_ans': fields.integer('#Required Answer'),
250 'maximum_req_ans': fields.integer('Maximum Required Answer'),
251 'minimum_req_ans': fields.integer('Minimum Required Answer'),
252 'req_error_msg': fields.text('Error Message'),
253 'allow_comment': fields.boolean('Allow Comment Field'),
254 'sequence': fields.integer('Sequence'),
255 'tot_resp': fields.function(_calc_response, string="Total Answer"),
256 'survey': fields.related('page_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
257 'descriptive_text': fields.text('Descriptive Text', size=255),
258 'column_heading_ids': fields.one2many('survey.question.column.heading', 'question_id',' Column heading'),
259 'type': fields.selection([('multiple_choice_only_one_ans','Multiple Choice (Only One Answer)'),
260 ('multiple_choice_multiple_ans','Multiple Choice (Multiple Answer)'),
261 ('matrix_of_choices_only_one_ans','Matrix of Choices (Only One Answers Per Row)'),
262 ('matrix_of_choices_only_multi_ans','Matrix of Choices (Multiple Answers Per Row)'),
263 ('matrix_of_drop_down_menus','Matrix of Drop-down Menus'),
264 ('rating_scale','Rating Scale'),('single_textbox','Single Textbox'),
265 ('multiple_textboxes','Multiple Textboxes'),
266 ('multiple_textboxes_diff_type','Multiple Textboxes With Different Type'),
267 ('comment','Comment/Essay Box'),
268 ('numerical_textboxes','Numerical Textboxes'),('date','Date'),
269 ('date_and_time','Date and Time'),('descriptive_text','Descriptive Text'),
271 ], 'Question Type', required=1,),
272 'is_comment_require': fields.boolean('Add Comment Field'),
273 'comment_label': fields.char('Field Label', size = 255),
274 'comment_field_type': fields.selection([('char', 'Single Line Of Text'), ('text', 'Paragraph of Text')], 'Comment Field Type'),
275 'comment_valid_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),
276 ('must_be_specific_length', 'Must Be Specific Length'),
277 ('must_be_whole_number', 'Must Be A Whole Number'),
278 ('must_be_decimal_number', 'Must Be A Decimal Number'),
279 ('must_be_date', 'Must Be A Date'),
280 ('must_be_email_address', 'Must Be An Email Address'),
281 ], 'Text Validation'),
282 'comment_minimum_no': fields.integer('Minimum number'),
283 'comment_maximum_no': fields.integer('Maximum number'),
284 'comment_minimum_float': fields.float('Minimum decimal number'),
285 'comment_maximum_float': fields.float('Maximum decimal number'),
286 'comment_minimum_date': fields.date('Minimum date'),
287 'comment_maximum_date': fields.date('Maximum date'),
288 'comment_valid_err_msg': fields.text('Error message'),
289 'make_comment_field': fields.boolean('Make Comment Field an Answer Choice'),
290 'make_comment_field_err_msg': fields.text('Error message'),
291 'is_validation_require': fields.boolean('Validate Text'),
292 'validation_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),\
293 ('must_be_specific_length', 'Must Be Specific Length'),\
294 ('must_be_whole_number', 'Must Be A Whole Number'),\
295 ('must_be_decimal_number', 'Must Be A Decimal Number'),\
296 ('must_be_date', 'Must Be A Date'),\
297 ('must_be_email_address', 'Must Be An Email Address')\
298 ], 'Text Validation'),
299 'validation_minimum_no': fields.integer('Minimum number'),
300 'validation_maximum_no': fields.integer('Maximum number'),
301 'validation_minimum_float': fields.float('Minimum decimal number'),
302 'validation_maximum_float': fields.float('Maximum decimal number'),
303 'validation_minimum_date': fields.date('Minimum date'),
304 'validation_maximum_date': fields.date('Maximum date'),
305 'validation_valid_err_msg': fields.text('Error message'),
306 'numeric_required_sum': fields.integer('Sum of all choices'),
307 'numeric_required_sum_err_msg': fields.text('Error message'),
308 'rating_allow_one_column_require': fields.boolean('Allow Only One Answer per Column (Forced Ranking)'),
309 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible?'),
310 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible?'),
311 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible?'),
312 'comment_column': fields.boolean('Add comment column in matrix'),
313 'column_name': fields.char('Column Name',size=256),
314 'no_of_rows': fields.integer('No of Rows'),
317 'sequence': lambda * a: 1,
318 'type': lambda * a: 'multiple_choice_multiple_ans',
319 'req_error_msg': lambda * a: 'This question requires an answer.',
320 'required_type': lambda * a: 'at least',
321 'req_ans': lambda * a: 1,
322 'comment_field_type': lambda * a: 'char',
323 'comment_label': lambda * a: 'Other (please specify)',
324 'comment_valid_type': lambda * a: 'do_not_validate',
325 'comment_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
326 'validation_type': lambda * a: 'do_not_validate',
327 'validation_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
328 'numeric_required_sum_err_msg': lambda * a :'The choices need to add up to [enter sum here].',
329 'make_comment_field_err_msg': lambda * a : 'Please enter a comment.',
330 'in_visible_answer_type': lambda * a: 1
333 def on_change_type(self, cr, uid, ids, type, context=None):
335 val['is_require_answer'] = False
336 val['is_comment_require'] = False
337 val['is_validation_require'] = False
338 val['comment_column'] = False
340 if type in ['multiple_textboxes_diff_type']:
341 val['in_visible_answer_type'] = False
342 return {'value': val}
344 if type in ['rating_scale']:
345 val.update({'in_visible_rating_weight':False, 'in_visible_menu_choice':True})
346 return {'value': val}
348 elif type in ['matrix_of_drop_down_menus']:
349 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':False})
350 return {'value': val}
352 elif type in ['single_textbox']:
353 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True})
354 return {'value': val}
357 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True,\
358 'in_visible_answer_type':True})
359 return {'value': val}
361 def write(self, cr, uid, ids, vals, context=None):
362 questions = self.read(cr,uid, ids, ['answer_choice_ids', 'type', 'required_type',\
363 'req_ans', 'minimum_req_ans', 'maximum_req_ans', 'column_heading_ids'])
364 for question in questions:
365 col_len = len(question['column_heading_ids'])
366 if vals.has_key('column_heading_ids'):
367 for col in vals['column_heading_ids']:
368 if type(col[2]) == type({}):
373 if vals.has_key('type'):
374 que_type = vals['type']
376 que_type = question['type']
378 if que_type in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans',\
379 'matrix_of_drop_down_menus', 'rating_scale']:
381 raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
382 ans_len = len(question['answer_choice_ids'])
384 if vals.has_key('answer_choice_ids'):
385 for ans in vals['answer_choice_ids']:
386 if type(ans[2]) == type({}):
391 if que_type not in ['descriptive_text', 'single_textbox', 'comment','table']:
393 raise osv.except_osv(_('Warning !'),_("You must enter one or more Answer."))
396 if vals.has_key('required_type'):
397 req_type = vals['required_type']
399 req_type = question['required_type']
401 if que_type in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', \
402 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus',\
403 'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
404 if req_type in ['at least', 'at most', 'exactly']:
405 if vals.has_key('req_ans'):
406 if not vals['req_ans'] or vals['req_ans'] > ans_len:
407 raise osv.except_osv(_('Warning !'),_("#Required Answer you entered \
408 is greater than the number of answer. \
409 Please use a number that is smaller than %d.") % (ans_len + 1))
411 if not question['req_ans'] or question['req_ans'] > ans_len:
412 raise osv.except_osv(_('Warning !'),_("#Required Answer you entered is \
413 greater than the number of answer.\
414 Please use a number that is smaller than %d.") % (ans_len + 1))
416 if req_type == 'a range':
419 if vals.has_key('minimum_req_ans'):
420 minimum_ans = vals['minimum_req_ans']
421 if not vals['minimum_req_ans'] or vals['minimum_req_ans'] > ans_len:
422 raise osv.except_osv(_('Warning !'),_("Minimum Required Answer\
423 you entered is greater than the number of answer.\
424 Please use a number that is smaller than %d.") % (ans_len + 1))
426 minimum_ans = question['minimum_req_ans']
427 if not question['minimum_req_ans'] or question['minimum_req_ans'] > ans_len:
428 raise osv.except_osv(_('Warning !'),_("Minimum Required Answer you\
429 entered is greater than the number of answer. \
430 Please use a number that is smaller than %d.") % (ans_len + 1))
431 if vals.has_key('maximum_req_ans'):
432 maximum_ans = vals['maximum_req_ans']
433 if not vals['maximum_req_ans'] or vals['maximum_req_ans'] > ans_len:
434 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you \
435 entered for your maximum is greater than the number of answer.\
436 Please use a number that is smaller than %d.") % (ans_len + 1))
438 maximum_ans = question['maximum_req_ans']
439 if not question['maximum_req_ans'] or question['maximum_req_ans'] > ans_len:
440 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you\
441 entered for your maximum is greater than the number of answer.\
442 Please use a number that is smaller than %d.") % (ans_len + 1))
443 if maximum_ans <= minimum_ans:
444 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater \
445 than Minimum Required Answer"))
447 if question['type'] == 'matrix_of_drop_down_menus' and vals.has_key('column_heading_ids'):
448 for col in vals['column_heading_ids']:
449 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
450 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices\
452 elif not col[2] or not col[2].has_key('menu_choice') or\
453 col[2]['menu_choice'].strip() == '':
454 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu \
455 choices in column heading (white spaces not allowed)"))
457 return super(survey_question, self).write(cr, uid, ids, vals, context=context)
459 def create(self, cr, uid, vals, context=None):
462 if vals.has_key('answer_choice_ids') and not len(vals['answer_choice_ids']):
463 if vals.has_key('type') and vals['type'] not in ['descriptive_text', 'single_textbox', 'comment','table']:
464 raise osv.except_osv(_('Warning !'),_("You must enter one or more answer."))
466 if vals.has_key('column_heading_ids') and not len(vals['column_heading_ids']):
467 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']:
468 raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
470 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']:
471 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] in ['at least', 'at most', 'exactly']:
472 if vals.has_key('answer_choice_ids') and vals['req_ans'] > len(vals['answer_choice_ids']) or not vals['req_ans']:
473 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))
475 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] == 'a range':
476 minimum_ans = vals['minimum_req_ans']
477 maximum_ans = vals['maximum_req_ans']
478 if vals.has_key('answer_choice_ids') or vals['minimum_req_ans'] > len(vals['answer_choice_ids']) or not vals['minimum_req_ans']:
479 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))
480 if vals.has_key('answer_choice_ids') or vals['maximum_req_ans'] > len(vals['answer_choice_ids']) or not vals['maximum_req_ans']:
481 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))
482 if maximum_ans <= minimum_ans:
483 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater than Minimum Required Answer"))
485 if vals['type'] == 'matrix_of_drop_down_menus':
486 for col in vals['column_heading_ids']:
487 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
488 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading"))
489 elif not col[2] or not col[2].has_key('menu_choice') or col[2]['menu_choice'].strip() == '':
490 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading (white spaces not allowed)"))
492 res = super(survey_question, self).create(cr, uid, vals, context)
495 def survey_save(self, cr, uid, ids, context=None):
498 search_obj = self.pool.get('ir.ui.view')
499 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
500 surv_name_wiz = self.pool.get('survey.name.wiz')
501 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',False) })
505 'res_model': 'survey.question.wiz',
506 'type': 'ir.actions.act_window',
508 'search_view_id': search_id[0],
512 def default_get(self, cr, uid, fields, context=None):
515 data = super(survey_question, self).default_get(cr, uid, fields, context)
516 if context.has_key('page_id'):
517 data['page_id']= context.get('page_id', False)
523 class survey_question_column_heading(osv.osv):
524 _name = 'survey.question.column.heading'
525 _description = 'Survey Question Column Heading'
528 def _get_in_visible_rating_weight(self,cr, uid, context=None):
531 if context.get('in_visible_rating_weight', False):
532 return context['in_visible_rating_weight']
534 def _get_in_visible_menu_choice(self,cr, uid, context=None):
537 if context.get('in_visible_menu_choice', False):
538 return context['in_visible_menu_choice']
542 'title': fields.char('Column Heading', size=128, required=1),
543 'menu_choice': fields.text('Menu Choice'),
544 'rating_weight': fields.integer('Weight'),
545 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
546 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible ??'),
547 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible??')
550 'in_visible_rating_weight': _get_in_visible_rating_weight,
551 'in_visible_menu_choice': _get_in_visible_menu_choice,
553 survey_question_column_heading()
555 class survey_answer(osv.osv):
556 _name = 'survey.answer'
557 _description = 'Survey Answer'
561 def _calc_response_avg(self, cr, uid, ids, field_name, arg, context=None):
563 for rec in self.browse(cr, uid, ids, context=context):
564 cr.execute("select count(question_id) ,(select count(answer_id) \
565 from survey_response_answer sra, survey_response_line sa \
566 where sra.response_id = sa.id and sra.answer_id = %d \
567 and sa.state='done') as tot_ans from survey_response_line \
568 where question_id = %d and state = 'done'"\
569 % (rec.id, rec.question_id.id))
572 avg = float(res[1]) * 100 / res[0]
577 'average': round(avg, 2),
581 def _get_in_visible_answer_type(self,cr, uid, context=None):
584 return context.get('in_visible_answer_type', False)
587 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
588 'answer': fields.char('Answer', size=128, required=1),
589 'sequence': fields.integer('Sequence'),
590 'response': fields.function(_calc_response_avg, string="#Answer", multi='sums'),
591 'average': fields.function(_calc_response_avg, string="#Avg", multi='sums'),
592 'type': fields.selection([('char','Character'),('date','Date'),('datetime','Date & Time'),\
593 ('integer','Integer'),('float','Float'),('selection','Selection'),\
594 ('email','Email')], "Type of Answer",required=1),
595 'menu_choice': fields.text('Menu Choices'),
596 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible??')
599 # 'sequence' : lambda * a: 1,
600 'type' : lambda * a: 'char',
601 'in_visible_answer_type':_get_in_visible_answer_type,
604 def default_get(self, cr, uid, fields, context=None):
607 data = super(survey_answer, self).default_get(cr, uid, fields, context)
612 class survey_response(osv.osv):
613 _name = "survey.response"
614 _rec_name = 'date_create'
616 'survey_id' : fields.many2one('survey', 'Survey', required=1, ondelete='cascade'),
617 'date_create' : fields.datetime('Create Date', required=1),
618 'user_id' : fields.many2one('res.users', 'User'),
619 'response_type' : fields.selection([('manually', 'Manually'), ('link', 'Link')], \
620 'Answer Type', required=1, readonly=1),
621 'question_ids' : fields.one2many('survey.response.line', 'response_id', 'Answer'),
622 'state' : fields.selection([('done', 'Finished '),('skip', 'Not Finished')], \
623 'Status', readonly=True),
626 'state' : lambda * a: "skip",
627 'response_type' : lambda * a: "manually",
630 def name_get(self, cr, uid, ids, context=None):
633 reads = self.read(cr, uid, ids, ['user_id','date_create'], context=context)
636 name = (record['user_id'] and record['user_id'][1] or '' )+ ' (' + record['date_create'].split('.')[0] + ')'
637 res.append((record['id'], name))
640 def copy(self, cr, uid, id, default=None, context=None):
641 raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
645 class survey_response_line(osv.osv):
646 _name = 'survey.response.line'
647 _description = 'Survey Response Line'
648 _rec_name = 'date_create'
650 'response_id': fields.many2one('survey.response', 'Answer', ondelete='cascade'),
651 'date_create': fields.datetime('Create Date', required=1),
652 'state': fields.selection([('draft', 'Draft'), ('done', 'Answered'),('skip', 'Skiped')],\
653 'Status', readonly=True),
654 'question_id': fields.many2one('survey.question', 'Question'),
655 'page_id': fields.related('question_id', 'page_id', type='many2one', \
656 relation='survey.page', string='Page'),
657 'response_answer_ids': fields.one2many('survey.response.answer', 'response_id', 'Answer'),
658 'response_table_ids': fields.one2many('survey.tbl.column.heading', \
659 'response_table_id', 'Answer'),
660 'comment': fields.text('Notes'),
661 'single_text': fields.char('Text', size=255),
664 'state' : lambda * a: "draft",
667 survey_response_line()
669 class survey_tbl_column_heading(osv.osv):
670 _name = 'survey.tbl.column.heading'
673 'name': fields.integer('Row Number'),
674 'column_id': fields.many2one('survey.question.column.heading', 'Column'),
675 'value': fields.char('Value', size = 255),
676 'response_table_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
679 survey_tbl_column_heading()
681 class survey_response_answer(osv.osv):
682 _name = 'survey.response.answer'
683 _description = 'Survey Answer'
684 _rec_name = 'response_id'
686 'response_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
687 'answer_id': fields.many2one('survey.answer', 'Answer', required=1, ondelete='cascade'),
688 'column_id': fields.many2one('survey.question.column.heading','Column'),
689 'answer': fields.char('Value', size =255),
690 'value_choice': fields.char('Value Choice', size =255),
691 'comment': fields.text('Notes'),
692 'comment_field': fields.char('Comment', size = 255)
695 survey_response_answer()
697 class res_users(osv.osv):
698 _inherit = "res.users"
701 'survey_id': fields.many2many('survey', 'survey_users_rel', 'uid', 'sid', 'Groups'),
706 class survey_request(osv.osv):
707 _name = "survey.request"
708 _order = 'date_deadline'
709 _rec_name = 'date_deadline'
711 'date_deadline': fields.date("Deadline date"),
712 'user_id': fields.many2one("res.users", "User"),
713 'email': fields.char("Email", size=64),
714 'survey_id': fields.many2one("survey", "Survey", required=1, ondelete='cascade'),
715 'response': fields.many2one('survey.response', 'Answer'),
716 'state': fields.selection([('draft','Draft'),('cancel', 'Cancelled'),('waiting_answer', 'Waiting Answer'),('done', 'Done')], 'Status', readonly=1)
719 'state': lambda * a: 'draft',
720 # 'date_deadline': lambda * a : (datetime.now() + relativedelta(months=+1)).strftime("%Y-%m-%d %H:%M:%S")
722 def survey_req_waiting_answer(self, cr, uid, ids, arg):
723 self.write(cr, uid, ids, { 'state' : 'waiting_answer'})
726 def survey_req_draft(self, cr, uid, ids, arg):
727 self.write(cr, uid, ids, { 'state' : 'draft'})
730 def survey_req_done(self, cr, uid, ids, arg):
731 self.write(cr, uid, ids, { 'state' : 'done'})
734 def survey_req_cancel(self, cr, uid, ids, arg):
735 self.write(cr, uid, ids, { 'state' : 'cancel'})
738 def on_change_user(self, cr, uid, ids, user_id, context=None):
740 user_obj = self.pool.get('res.users')
741 user = user_obj.browse(cr, uid, user_id, context=context)
742 return {'value': {'email': user.user_email}}
747 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: