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'), ('close', 'Closed'), ('cancel', 'Cancelled')], '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('E-mail 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',
147 class survey_history(osv.osv):
148 _name = 'survey.history'
149 _description = 'Survey History'
152 'survey_id': fields.many2one('survey', 'Survey'),
153 'user_id': fields.many2one('res.users', 'User', readonly=True),
154 'date': fields.datetime('Date started', readonly=1),
157 'date': lambda * a: datetime.datetime.now()
161 class survey_page(osv.osv):
162 _name = 'survey.page'
163 _description = 'Survey Pages'
167 'title': fields.char('Page Title', size=128, required=1),
168 'survey_id': fields.many2one('survey', 'Survey', ondelete='cascade'),
169 'question_ids': fields.one2many('survey.question', 'page_id', 'Question'),
170 'sequence': fields.integer('Page Nr'),
171 'note': fields.text('Description'),
174 'sequence': lambda * a: 1
177 def default_get(self, cr, uid, fields, context=None):
180 data = super(survey_page, self).default_get(cr, uid, fields, context)
181 self.pool.get('survey.question').data_get(cr,uid,data,context)
182 if context.has_key('survey_id'):
183 data['survey_id'] = context.get('survey_id', False)
186 def survey_save(self, cr, uid, ids, context=None):
189 search_obj = self.pool.get('ir.ui.view')
190 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
191 surv_name_wiz = self.pool.get('survey.name.wiz')
192 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',0) })
196 'res_model': 'survey.question.wiz',
197 'type': 'ir.actions.act_window',
199 'search_view_id': search_id[0],
203 def copy(self, cr, uid, ids, default=None, context=None):
205 current_rec = self.read(cr, uid, ids, context=context)
206 title = current_rec.get('title') + ' (Copy)'
207 vals.update({'title':title})
208 return super(survey_page, self).copy(cr, uid, ids, vals, context=context)
212 class survey_question(osv.osv):
213 _name = 'survey.question'
214 _description = 'Survey Question'
215 _rec_name = 'question'
218 def _calc_response(self, cr, uid, ids, field_name, arg, context=None):
222 cr.execute("select question_id, count(id) as Total_response from \
223 survey_response_line where state='done' and question_id IN %s\
224 group by question_id" ,(tuple(ids),))
225 ids1 = copy.deepcopy(ids)
226 for rec in cr.fetchall():
228 val[rec[0]] = int(rec[1])
234 'page_id': fields.many2one('survey.page', 'Survey Page', ondelete='cascade', required=1),
235 'question': fields.char('Question', size=128, required=1),
236 'answer_choice_ids': fields.one2many('survey.answer', 'question_id', 'Answer'),
237 'is_require_answer': fields.boolean('Require Answer to Question'),
238 'required_type': fields.selection([('all','All'), ('at least','At Least'), ('at most','At Most'), ('exactly','Exactly'), ('a range','A Range')], 'Respondent must answer'),
239 'req_ans': fields.integer('#Required Answer'),
240 'maximum_req_ans': fields.integer('Maximum Required Answer'),
241 'minimum_req_ans': fields.integer('Minimum Required Answer'),
242 'req_error_msg': fields.text('Error Message'),
243 'allow_comment': fields.boolean('Allow Comment Field'),
244 'sequence': fields.integer('Sequence'),
245 'tot_resp': fields.function(_calc_response, string="Total Answer"),
246 'survey': fields.related('page_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
247 'descriptive_text': fields.text('Descriptive Text', size=255),
248 'column_heading_ids': fields.one2many('survey.question.column.heading', 'question_id',' Column heading'),
249 'type': fields.selection([('multiple_choice_only_one_ans','Multiple Choice (Only One Answer)'),
250 ('multiple_choice_multiple_ans','Multiple Choice (Multiple Answer)'),
251 ('matrix_of_choices_only_one_ans','Matrix of Choices (Only One Answers Per Row)'),
252 ('matrix_of_choices_only_multi_ans','Matrix of Choices (Multiple Answers Per Row)'),
253 ('matrix_of_drop_down_menus','Matrix of Drop-down Menus'),
254 ('rating_scale','Rating Scale'),('single_textbox','Single Textbox'),
255 ('multiple_textboxes','Multiple Textboxes'),
256 ('multiple_textboxes_diff_type','Multiple Textboxes With Different Type'),
257 ('comment','Comment/Essay Box'),
258 ('numerical_textboxes','Numerical Textboxes'),('date','Date'),
259 ('date_and_time','Date and Time'),('descriptive_text','Descriptive Text'),
261 ], 'Question Type', required=1,),
262 'is_comment_require': fields.boolean('Add Comment Field'),
263 'comment_label': fields.char('Field Label', size = 255),
264 'comment_field_type': fields.selection([('char', 'Single Line Of Text'), ('text', 'Paragraph of Text')], 'Comment Field Type'),
265 'comment_valid_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),
266 ('must_be_specific_length', 'Must Be Specific Length'),
267 ('must_be_whole_number', 'Must Be A Whole Number'),
268 ('must_be_decimal_number', 'Must Be A Decimal Number'),
269 ('must_be_date', 'Must Be A Date'),
270 ('must_be_email_address', 'Must Be An Email Address'),
271 ], 'Text Validation'),
272 'comment_minimum_no': fields.integer('Minimum number'),
273 'comment_maximum_no': fields.integer('Maximum number'),
274 'comment_minimum_float': fields.float('Minimum decimal number'),
275 'comment_maximum_float': fields.float('Maximum decimal number'),
276 'comment_minimum_date': fields.date('Minimum date'),
277 'comment_maximum_date': fields.date('Maximum date'),
278 'comment_valid_err_msg': fields.text('Error message'),
279 'make_comment_field': fields.boolean('Make Comment Field an Answer Choice'),
280 'make_comment_field_err_msg': fields.text('Error message'),
281 'is_validation_require': fields.boolean('Validate Text'),
282 'validation_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),\
283 ('must_be_specific_length', 'Must Be Specific Length'),\
284 ('must_be_whole_number', 'Must Be A Whole Number'),\
285 ('must_be_decimal_number', 'Must Be A Decimal Number'),\
286 ('must_be_date', 'Must Be A Date'),\
287 ('must_be_email_address', 'Must Be An Email Address')\
288 ], 'Text Validation'),
289 'validation_minimum_no': fields.integer('Minimum number'),
290 'validation_maximum_no': fields.integer('Maximum number'),
291 'validation_minimum_float': fields.float('Minimum decimal number'),
292 'validation_maximum_float': fields.float('Maximum decimal number'),
293 'validation_minimum_date': fields.date('Minimum date'),
294 'validation_maximum_date': fields.date('Maximum date'),
295 'validation_valid_err_msg': fields.text('Error message'),
296 'numeric_required_sum': fields.integer('Sum of all choices'),
297 'numeric_required_sum_err_msg': fields.text('Error message'),
298 'rating_allow_one_column_require': fields.boolean('Allow Only One Answer per Column (Forced Ranking)'),
299 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible?'),
300 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible?'),
301 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible?'),
302 'comment_column': fields.boolean('Add comment column in matrix'),
303 'column_name': fields.char('Column Name',size=256),
304 'no_of_rows': fields.integer('No of Rows'),
307 'sequence': lambda * a: 1,
308 'type': lambda * a: 'multiple_choice_multiple_ans',
309 'req_error_msg': lambda * a: 'This question requires an answer.',
310 'required_type': lambda * a: 'at least',
311 'req_ans': lambda * a: 1,
312 'comment_field_type': lambda * a: 'char',
313 'comment_label': lambda * a: 'Other (please specify)',
314 'comment_valid_type': lambda * a: 'do_not_validate',
315 'comment_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
316 'validation_type': lambda * a: 'do_not_validate',
317 'validation_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
318 'numeric_required_sum_err_msg': lambda * a :'The choices need to add up to [enter sum here].',
319 'make_comment_field_err_msg': lambda * a : 'Please enter a comment.',
320 'in_visible_answer_type': lambda * a: 1
323 def on_change_type(self, cr, uid, ids, type, context=None):
325 val['is_require_answer'] = False
326 val['is_comment_require'] = False
327 val['is_validation_require'] = False
328 val['comment_column'] = False
330 if type in ['multiple_textboxes_diff_type']:
331 val['in_visible_answer_type'] = False
332 return {'value': val}
334 if type in ['rating_scale']:
335 val.update({'in_visible_rating_weight':False, 'in_visible_menu_choice':True})
336 return {'value': val}
338 elif type in ['matrix_of_drop_down_menus']:
339 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':False})
340 return {'value': val}
342 elif type in ['single_textbox']:
343 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True})
344 return {'value': val}
347 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True,\
348 'in_visible_answer_type':True})
349 return {'value': val}
351 def write(self, cr, uid, ids, vals, context=None):
352 questions = self.read(cr,uid, ids, ['answer_choice_ids', 'type', 'required_type',\
353 'req_ans', 'minimum_req_ans', 'maximum_req_ans', 'column_heading_ids'])
354 for question in questions:
355 col_len = len(question['column_heading_ids'])
356 if vals.has_key('column_heading_ids'):
357 for col in vals['column_heading_ids']:
358 if type(col[2]) == type({}):
363 if vals.has_key('type'):
364 que_type = vals['type']
366 que_type = question['type']
368 if que_type in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans',\
369 'matrix_of_drop_down_menus', 'rating_scale']:
371 raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
372 ans_len = len(question['answer_choice_ids'])
374 if vals.has_key('answer_choice_ids'):
375 for ans in vals['answer_choice_ids']:
376 if type(ans[2]) == type({}):
381 if que_type not in ['descriptive_text', 'single_textbox', 'comment','table']:
383 raise osv.except_osv(_('Warning !'),_("You must enter one or more Answer."))
386 if vals.has_key('required_type'):
387 req_type = vals['required_type']
389 req_type = question['required_type']
391 if que_type in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', \
392 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus',\
393 'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
394 if req_type in ['at least', 'at most', 'exactly']:
395 if vals.has_key('req_ans'):
396 if not vals['req_ans'] or vals['req_ans'] > ans_len:
397 raise osv.except_osv(_('Warning !'),_("#Required Answer you entered \
398 is greater than the number of answer. \
399 Please use a number that is smaller than %d.") % (ans_len + 1))
401 if not question['req_ans'] or question['req_ans'] > ans_len:
402 raise osv.except_osv(_('Warning !'),_("#Required Answer you entered is \
403 greater than the number of answer.\
404 Please use a number that is smaller than %d.") % (ans_len + 1))
406 if req_type == 'a range':
409 if vals.has_key('minimum_req_ans'):
410 minimum_ans = vals['minimum_req_ans']
411 if not vals['minimum_req_ans'] or vals['minimum_req_ans'] > ans_len:
412 raise osv.except_osv(_('Warning !'),_("Minimum Required Answer\
413 you entered is greater than the number of answer.\
414 Please use a number that is smaller than %d.") % (ans_len + 1))
416 minimum_ans = question['minimum_req_ans']
417 if not question['minimum_req_ans'] or question['minimum_req_ans'] > ans_len:
418 raise osv.except_osv(_('Warning !'),_("Minimum Required Answer you\
419 entered is greater than the number of answer. \
420 Please use a number that is smaller than %d.") % (ans_len + 1))
421 if vals.has_key('maximum_req_ans'):
422 maximum_ans = vals['maximum_req_ans']
423 if not vals['maximum_req_ans'] or vals['maximum_req_ans'] > ans_len:
424 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you \
425 entered for your maximum is greater than the number of answer.\
426 Please use a number that is smaller than %d.") % (ans_len + 1))
428 maximum_ans = question['maximum_req_ans']
429 if not question['maximum_req_ans'] or question['maximum_req_ans'] > ans_len:
430 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you\
431 entered for your maximum is greater than the number of answer.\
432 Please use a number that is smaller than %d.") % (ans_len + 1))
433 if maximum_ans <= minimum_ans:
434 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater \
435 than Minimum Required Answer"))
437 if question['type'] == 'matrix_of_drop_down_menus' and vals.has_key('column_heading_ids'):
438 for col in vals['column_heading_ids']:
439 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
440 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices\
442 elif not col[2] or not col[2].has_key('menu_choice') or\
443 col[2]['menu_choice'].strip() == '':
444 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu \
445 choices in column heading (white spaces not allowed)"))
447 return super(survey_question, self).write(cr, uid, ids, vals, context=context)
449 def create(self, cr, uid, vals, context=None):
452 if vals.has_key('answer_choice_ids') and not len(vals['answer_choice_ids']):
453 if vals.has_key('type') and vals['type'] not in ['descriptive_text', 'single_textbox', 'comment','table']:
454 raise osv.except_osv(_('Warning !'),_("You must enter one or more answer."))
456 if vals.has_key('column_heading_ids') and not len(vals['column_heading_ids']):
457 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']:
458 raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
460 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']:
461 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] in ['at least', 'at most', 'exactly']:
462 if vals.has_key('answer_choice_ids') and vals['req_ans'] > len(vals['answer_choice_ids']) or not vals['req_ans']:
463 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))
465 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] == 'a range':
466 minimum_ans = vals['minimum_req_ans']
467 maximum_ans = vals['maximum_req_ans']
468 if vals.has_key('answer_choice_ids') or vals['minimum_req_ans'] > len(vals['answer_choice_ids']) or not vals['minimum_req_ans']:
469 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))
470 if vals.has_key('answer_choice_ids') or vals['maximum_req_ans'] > len(vals['answer_choice_ids']) or not vals['maximum_req_ans']:
471 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))
472 if maximum_ans <= minimum_ans:
473 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater than Minimum Required Answer"))
475 if vals['type'] == 'matrix_of_drop_down_menus':
476 for col in vals['column_heading_ids']:
477 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
478 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading"))
479 elif not col[2] or not col[2].has_key('menu_choice') or col[2]['menu_choice'].strip() == '':
480 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading (white spaces not allowed)"))
482 res = super(survey_question, self).create(cr, uid, vals, context)
485 def survey_save(self, cr, uid, ids, context=None):
488 search_obj = self.pool.get('ir.ui.view')
489 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
490 surv_name_wiz = self.pool.get('survey.name.wiz')
491 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',False) })
495 'res_model': 'survey.question.wiz',
496 'type': 'ir.actions.act_window',
498 'search_view_id': search_id[0],
502 def data_get(self, cr, uid, data, context):
504 if context.get('line_order', False):
505 lines = context.get('line_order')
506 seq = data.get('sequence', 0)
509 data.update({'sequence': seq})
512 def default_get(self, cr, uid, fields, context=None):
515 data = super(survey_question, self).default_get(cr, uid, fields, context)
516 self.data_get(cr,uid,data,context)
517 if context.has_key('page_id'):
518 data['page_id']= context.get('page_id', False)
524 class survey_question_column_heading(osv.osv):
525 _name = 'survey.question.column.heading'
526 _description = 'Survey Question Column Heading'
529 def _get_in_visible_rating_weight(self,cr, uid, context=None):
532 if context.get('in_visible_rating_weight', False):
533 return context['in_visible_rating_weight']
535 def _get_in_visible_menu_choice(self,cr, uid, context=None):
538 if context.get('in_visible_menu_choice', False):
539 return context['in_visible_menu_choice']
543 'title': fields.char('Column Heading', size=128, required=1),
544 'menu_choice': fields.text('Menu Choice'),
545 'rating_weight': fields.integer('Weight'),
546 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
547 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible ??'),
548 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible??')
551 'in_visible_rating_weight': _get_in_visible_rating_weight,
552 'in_visible_menu_choice': _get_in_visible_menu_choice,
554 survey_question_column_heading()
556 class survey_answer(osv.osv):
557 _name = 'survey.answer'
558 _description = 'Survey Answer'
562 def _calc_response_avg(self, cr, uid, ids, field_name, arg, context=None):
564 for rec in self.browse(cr, uid, ids, context=context):
565 cr.execute("select count(question_id) ,(select count(answer_id) \
566 from survey_response_answer sra, survey_response_line sa \
567 where sra.response_id = sa.id and sra.answer_id = %d \
568 and sa.state='done') as tot_ans from survey_response_line \
569 where question_id = %d and state = 'done'"\
570 % (rec.id, rec.question_id.id))
573 avg = float(res[1]) * 100 / res[0]
578 'average': round(avg, 2),
582 def _get_in_visible_answer_type(self,cr, uid, context=None):
585 return context.get('in_visible_answer_type', False)
588 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
589 'answer': fields.char('Answer', size=128, required=1),
590 'sequence': fields.integer('Sequence'),
591 'response': fields.function(_calc_response_avg, string="#Answer", multi='sums'),
592 'average': fields.function(_calc_response_avg, string="#Avg", multi='sums'),
593 'type': fields.selection([('char','Character'),('date','Date'),('datetime','Date & Time'),\
594 ('integer','Integer'),('float','Float'),('selection','Selection'),\
595 ('email','Email')], "Type of Answer",required=1),
596 'menu_choice': fields.text('Menu Choices'),
597 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible??')
600 # 'sequence' : lambda * a: 1,
601 'type' : lambda * a: 'char',
602 'in_visible_answer_type':_get_in_visible_answer_type,
605 def default_get(self, cr, uid, fields, context=None):
608 data = super(survey_answer, self).default_get(cr, uid, fields, context)
609 self.pool.get('survey.question').data_get(cr,uid,data,context)
614 class survey_response(osv.osv):
615 _name = "survey.response"
616 _rec_name = 'date_create'
618 'survey_id' : fields.many2one('survey', 'Survey', required=1, ondelete='cascade'),
619 'date_create' : fields.datetime('Create Date', required=1),
620 'user_id' : fields.many2one('res.users', 'User'),
621 'response_type' : fields.selection([('manually', 'Manually'), ('link', 'Link')], \
622 'Answer Type', required=1, readonly=1),
623 'question_ids' : fields.one2many('survey.response.line', 'response_id', 'Answer'),
624 'state' : fields.selection([('done', 'Finished '),('skip', 'Not Finished')], \
625 'Status', readonly=True),
628 'state' : lambda * a: "skip",
629 'response_type' : lambda * a: "manually",
632 def name_get(self, cr, uid, ids, context=None):
635 reads = self.read(cr, uid, ids, ['user_id','date_create'], context=context)
638 name = (record['user_id'] and record['user_id'][1] or '' )+ ' (' + record['date_create'].split('.')[0] + ')'
639 res.append((record['id'], name))
642 def copy(self, cr, uid, id, default=None, context=None):
643 raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
647 class survey_response_line(osv.osv):
648 _name = 'survey.response.line'
649 _description = 'Survey Response Line'
650 _rec_name = 'date_create'
652 'response_id': fields.many2one('survey.response', 'Answer', ondelete='cascade'),
653 'date_create': fields.datetime('Create Date', required=1),
654 'state': fields.selection([('draft', 'Draft'), ('done', 'Answered'),('skip', 'Skiped')],\
655 'Status', readonly=True),
656 'question_id': fields.many2one('survey.question', 'Question'),
657 'page_id': fields.related('question_id', 'page_id', type='many2one', \
658 relation='survey.page', string='Page'),
659 'response_answer_ids': fields.one2many('survey.response.answer', 'response_id', 'Answer'),
660 'response_table_ids': fields.one2many('survey.tbl.column.heading', \
661 'response_table_id', 'Answer'),
662 'comment': fields.text('Notes'),
663 'single_text': fields.char('Text', size=255),
666 'state' : lambda * a: "draft",
669 survey_response_line()
671 class survey_tbl_column_heading(osv.osv):
672 _name = 'survey.tbl.column.heading'
675 'name': fields.integer('Row Number'),
676 'column_id': fields.many2one('survey.question.column.heading', 'Column'),
677 'value': fields.char('Value', size = 255),
678 'response_table_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
681 survey_tbl_column_heading()
683 class survey_response_answer(osv.osv):
684 _name = 'survey.response.answer'
685 _description = 'Survey Answer'
686 _rec_name = 'response_id'
688 'response_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
689 'answer_id': fields.many2one('survey.answer', 'Answer', required=1, ondelete='cascade'),
690 'column_id': fields.many2one('survey.question.column.heading','Column'),
691 'answer': fields.char('Value', size =255),
692 'value_choice': fields.char('Value Choice', size =255),
693 'comment': fields.text('Notes'),
694 'comment_field': fields.char('Comment', size = 255)
697 survey_response_answer()
699 class res_users(osv.osv):
700 _inherit = "res.users"
703 'survey_id': fields.many2many('survey', 'survey_users_rel', 'uid', 'sid', 'Groups'),
708 class survey_request(osv.osv):
709 _name = "survey.request"
710 _order = 'date_deadline'
711 _rec_name = 'date_deadline'
713 'date_deadline': fields.date("Deadline date"),
714 'user_id': fields.many2one("res.users", "User"),
715 'email': fields.char("E-mail", size=64),
716 'survey_id': fields.many2one("survey", "Survey", required=1, ondelete='cascade'),
717 'response': fields.many2one('survey.response', 'Answer'),
718 'state': fields.selection([('draft','Draft'),('waiting_answer', 'Waiting Answer'),('done', 'Done'),('cancel', 'Cancelled')], 'State', readonly=1)
721 'state': lambda * a: 'draft',
722 # 'date_deadline': lambda * a : (datetime.now() + relativedelta(months=+1)).strftime("%Y-%m-%d %H:%M:%S")
724 def survey_req_waiting_answer(self, cr, uid, ids, arg):
725 self.write(cr, uid, ids, { 'state' : 'waiting_answer'})
728 def survey_req_draft(self, cr, uid, ids, arg):
729 self.write(cr, uid, ids, { 'state' : 'draft'})
732 def survey_req_done(self, cr, uid, ids, arg):
733 self.write(cr, uid, ids, { 'state' : 'done'})
736 def survey_req_cancel(self, cr, uid, ids, arg):
737 self.write(cr, uid, ids, { 'state' : 'cancel'})
740 def on_change_user(self, cr, uid, ids, user_id, context=None):
742 user_obj = self.pool.get('res.users')
743 user = user_obj.browse(cr, uid, user_id, context=context)
744 return {'value': {'email': user.user_email}}
749 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: