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 ##############################################################################
22 from openerp.osv import fields, osv
23 from openerp.tools.translate import _
24 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT as DF
25 from openerp.addons.website.models.website import slug
26 from urlparse import urljoin
33 _logger = logging.getLogger(__name__)
36 class survey_survey(osv.Model):
37 '''Settings for a multi-page/multi-question survey.
38 Each survey can have one or more attached pages, and each page can display
39 one or more questions.
42 _name = 'survey.survey'
43 _description = 'Survey'
45 _inherit = ['mail.thread', 'ir.needaction_mixin']
49 def _has_questions(self, cr, uid, ids, context=None):
50 """ Ensure that this survey has at least one page with at least one
52 for survey in self.browse(cr, uid, ids, context=context):
53 if not survey.page_ids or not [page.question_ids
54 for page in survey.page_ids if page.question_ids]:
60 def _get_tot_sent_survey(self, cr, uid, ids, name, arg, context=None):
61 """ Returns the number of invitations sent for this survey, be they
62 (partially) completed or not """
63 res = dict((id, 0) for id in ids)
64 sur_res_obj = self.pool.get('survey.user_input')
66 res[id] = sur_res_obj.search(cr, uid, # SUPERUSER_ID,
67 [('survey_id', '=', id), ('type', '=', 'link')],
68 context=context, count=True)
71 def _get_tot_start_survey(self, cr, uid, ids, name, arg, context=None):
72 """ Returns the number of started instances of this survey, be they
74 res = dict((id, 0) for id in ids)
75 sur_res_obj = self.pool.get('survey.user_input')
77 res[id] = sur_res_obj.search(cr, uid, # SUPERUSER_ID,
78 ['&', ('survey_id', '=', id), '|', ('state', '=', 'skip'), ('state', '=', 'done')],
79 context=context, count=True)
82 def _get_tot_comp_survey(self, cr, uid, ids, name, arg, context=None):
83 """ Returns the number of completed instances of this survey """
84 res = dict((id, 0) for id in ids)
85 sur_res_obj = self.pool.get('survey.user_input')
87 res[id] = sur_res_obj.search(cr, uid, # SUPERUSER_ID,
88 [('survey_id', '=', id), ('state', '=', 'done')],
89 context=context, count=True)
92 def _get_public_url(self, cr, uid, ids, name, arg, context=None):
93 """ Computes a public URL for the survey """
94 base_url = self.pool.get('ir.config_parameter').get_param(cr, uid,
97 for survey in self.browse(cr, uid, ids, context=context):
98 res[survey.id] = urljoin(base_url, "survey/start/%s" % slug(survey))
101 def _get_print_url(self, cr, uid, ids, name, arg, context=None):
102 """ Computes a printing URL for the survey """
103 base_url = self.pool.get('ir.config_parameter').get_param(cr, uid,
106 for survey in self.browse(cr, uid, ids, context=context):
107 res[survey.id] = urljoin(base_url, "survey/print/%s" % slug(survey))
110 def _get_result_url(self, cr, uid, ids, name, arg, context=None):
111 """ Computes an URL for the survey results """
112 base_url = self.pool.get('ir.config_parameter').get_param(cr, uid,
115 for survey in self.browse(cr, uid, ids, context=context):
116 res[survey.id] = urljoin(base_url, "survey/results/%s" % slug(survey))
122 'title': fields.char('Title', required=1, translate=True),
123 'res_model': fields.char('Category'),
124 'page_ids': fields.one2many('survey.page', 'survey_id', 'Pages'),
125 'date_open': fields.datetime('Opening date', readonly=True),
126 'date_close': fields.datetime('Closing date', readonly=True),
127 'user_input_limit': fields.integer('Automatic closing limit',
128 help="Limits the number of instances of this survey that can be completed (if set to 0, no limit is applied)",
129 oldname='max_response_limit'),
130 'state': fields.selection(
131 [('draft', 'Draft'), ('open', 'Open'), ('close', 'Closed'),
132 ('cancel', 'Cancelled')], 'Status', required=1, translate=1),
133 'stage_id': fields.many2one('survey.stage', string="Stage"),
134 'visible_to_user': fields.boolean('Public in website',
135 help="If unchecked, only invited users will be able to open the survey."),
136 'auth_required': fields.boolean('Login required',
137 help="Users with a public link will be requested to login before taking part to the survey",
138 oldname="authenticate"),
139 'users_can_go_back': fields.boolean('Users can go back',
140 help="If checked, users can go back to previous pages."),
141 'tot_sent_survey': fields.function(_get_tot_sent_survey,
142 string="Number of sent surveys", type="integer"),
143 'tot_start_survey': fields.function(_get_tot_start_survey,
144 string="Number of started surveys", type="integer"),
145 'tot_comp_survey': fields.function(_get_tot_comp_survey,
146 string="Number of completed surveys", type="integer"),
147 'description': fields.html('Description', translate=True,
148 oldname="description", help="A long description of the purpose of the survey"),
149 'color': fields.integer('Color Index'),
150 'user_input_ids': fields.one2many('survey.user_input', 'survey_id',
151 'User responses', readonly=1),
152 'public_url': fields.function(_get_public_url,
153 string="Public link", type="char"),
154 'print_url': fields.function(_get_print_url,
155 string="Print link", type="char"),
156 'result_url': fields.function(_get_result_url,
157 string="Results link", type="char"),
158 'email_template_id': fields.many2one('email.template',
159 'Email Template', ondelete='set null'),
160 'thank_you_message': fields.html('Thank you message', translate=True,
161 help="This message will be displayed when survey is completed"),
162 'quizz_mode': fields.boolean(string='Quizz mode')
166 'user_input_limit': 0,
168 'visible_to_user': True,
169 'auth_required': True,
170 'users_can_go_back': False,
175 ('positive_user_input_limit', 'CHECK (user_input_limit >= 0)', 'Automatic closing limit must be positive')
180 def write(self, cr, uid, ids, vals, context=None):
181 new_state = vals.get('state')
182 if new_state == 'draft':
183 vals.update({'date_open': None})
184 vals.update({'date_close': None})
185 self.message_post(cr, uid, ids, body="""<p>Survey drafted</p>""", context=context)
186 elif new_state == 'open':
187 if self._has_questions(cr, uid, ids, context=None):
188 vals.update({'date_open': fields.datetime.now(), 'date_close': None})
189 self.message_post(cr, uid, ids, body="""<p>Survey opened</p>""", context=context)
191 raise osv.except_osv(_('Error!'), _('You can not open a survey that has no questions.'))
192 elif new_state == 'close':
193 vals.update({'date_close': fields.datetime.now()})
194 self.message_post(cr, uid, ids, body="""<p>Survey closed</p>""", context=context)
195 # Purge the tests records
196 self.pool.get('survey.user_input').purge_tests(cr, uid, context=context)
197 elif new_state == 'cancel':
198 self.message_post(cr, uid, ids, body="""<p>Survey cancelled</p>""", context=context)
199 return super(survey_survey, self).write(cr, uid, ids, vals, context=context)
201 def copy(self, cr, uid, ids, default=None, context=None):
203 current_rec = self.read(cr, uid, ids, context=context)
204 title = _("%s (copy)") % (current_rec.get('title'))
205 vals['title'] = title
206 vals['user_input_ids'] = []
207 return super(survey_survey, self).copy(cr, uid, ids, vals,
210 def next_page(self, cr, uid, user_input, page_id, go_back=False, context=None):
211 '''The next page to display to the user, knowing that page_id is the id
212 of the last displayed page.
214 If page_id == 0, it will always return the first page of the survey.
216 If all the pages have been displayed and go_back == False, it will
219 If go_back == True, it will return the *previous* page instead of the
223 It is assumed here that a careful user will not try to set go_back
224 to True if she knows that the page to display is the first one!
225 (doing this will probably cause a giant worm to eat her house)'''
226 survey = user_input.survey_id
227 pages = list(enumerate(survey.page_ids))
231 return (pages[0][1], 0, len(pages) == 1)
233 current_page_index = pages.index((filter(lambda p: p[1].id == page_id, pages))[0])
235 # All the pages have been displayed
236 if current_page_index == len(pages) - 1 and not go_back:
237 return (None, -1, False)
238 # Let's get back, baby!
239 elif go_back and survey.users_can_go_back:
240 return (pages[current_page_index - 1][1], current_page_index - 1, False)
242 # This will show the last page
243 if current_page_index == len(pages) - 2:
244 return (pages[current_page_index + 1][1], current_page_index + 1, True)
245 # This will show a regular page
247 return (pages[current_page_index + 1][1], current_page_index + 1, False)
251 def action_kanban_update_state(self, cr, uid, ids, context=None):
252 ''' Change the state from the kanban ball '''
253 for survey in self.read(cr, uid, ids, ['state'], context=context):
254 if survey['state'] == 'draft':
255 self.write(cr, uid, [survey['id']], {'state': 'open'}, context=context)
256 elif survey['state'] == 'open':
257 self.write(cr, uid, [survey['id']], {'state': 'close'}, context=context)
258 elif survey['state'] == 'close':
259 self.write(cr, uid, [survey['id']], {'state': 'cancel'}, context=context)
260 elif survey['state'] == 'cancel':
261 self.write(cr, uid, [survey['id']], {'state': 'draft'}, context=context)
264 def action_start_survey(self, cr, uid, ids, context=None):
265 ''' Open the website page with the survey form '''
267 if context and 'survey_token' in context:
268 trail = "/" + context['survey_token']
270 'type': 'ir.actions.act_url',
271 'name': "Start Survey",
273 'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + trail
276 def action_send_survey(self, cr, uid, ids, context=None):
277 ''' Open a window to compose an email, pre-filled with the survey
279 if not self._has_questions(cr, uid, ids, context=None):
280 raise osv.except_osv(_('Error!'), _('You cannot send an invitation for a survey that has no questions.'))
282 survey_browse = self.pool.get('survey.survey').browse(cr, uid, ids,
284 if survey_browse.state != "open":
285 raise osv.except_osv(_('Warning!'),
286 _("You cannot send invitations unless the survey is open."))
288 assert len(ids) == 1, 'This option should only be used for a single \
290 ir_model_data = self.pool.get('ir.model.data')
291 templates = ir_model_data.get_object_reference(cr, uid,
292 'survey', 'email_template_survey')
293 template_id = templates[1] if len(templates) > 0 else False
296 ctx.update({'default_model': 'survey.survey',
297 'default_res_id': ids[0],
298 'default_survey_id': ids[0],
299 'default_use_template': bool(template_id),
300 'default_template_id': template_id,
301 'default_composition_mode': 'comment',
302 'survey_state': survey_browse.state}
305 'type': 'ir.actions.act_window',
308 'res_model': 'survey.mail.compose.message',
313 def action_print_survey(self, cr, uid, ids, context=None):
314 ''' Open the website page with the survey printable view '''
316 if context and 'survey_token' in context:
317 trail = "/" + context['survey_token']
319 'type': 'ir.actions.act_url',
320 'name': "Print Survey",
322 'url': self.read(cr, uid, ids, ['print_url'], context=context)[0]['print_url'] + trail
325 def action_result_survey(self, cr, uid, ids, context=None):
326 ''' Open the website page with the survey results view '''
328 'type': 'ir.actions.act_url',
329 'name': "Results of the Survey",
331 'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
334 def action_test_survey(self, cr, uid, ids, context=None):
335 ''' Open the website page with the survey form into test mode'''
337 'type': 'ir.actions.act_url',
338 'name': "Results of the Survey",
340 'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + "/phantom"
344 class survey_stage(osv.Model):
345 """Stages for Kanban view of surveys"""
347 _name = 'survey.stage'
348 _description = 'Survey Stage'
352 'name': fields.text(string="Name", required=True, translate=True),
353 'sequence': fields.integer(string="Sequence"),
354 'survey_open': fields.boolean(string="Display these surveys?"),
355 'folded': fields.boolean(string="Folded column by default")
362 ('positive_sequence', 'CHECK(sequence >= 0)', 'Sequence number MUST be a natural')
366 class survey_page(osv.Model):
367 '''A page for a survey.
369 Pages are essentially containers, allowing to group questions by ordered
373 A page should be deleted if the survey it belongs to is deleted. '''
375 _name = 'survey.page'
376 _description = 'Survey Page'
383 'title': fields.char('Page Title', required=1,
385 'survey_id': fields.many2one('survey.survey', 'Survey',
386 ondelete='cascade', required=True),
387 'question_ids': fields.one2many('survey.question', 'page_id',
389 'sequence': fields.integer('Page number'),
390 'description': fields.html('Description',
391 help="An introductory text to your page", translate=True,
400 def copy(self, cr, uid, ids, default=None, context=None):
402 current_rec = self.read(cr, uid, ids, context=context)
403 title = _("%s (copy)") % (current_rec.get('title'))
404 vals.update({'title': title})
405 return super(survey_page, self).copy(cr, uid, ids, vals,
409 class survey_question(osv.Model):
410 ''' Questions that will be asked in a survey.
412 Each question can have one of more suggested answers (eg. in case of
413 dropdown choices, multi-answer checkboxes, radio buttons...).'''
414 _name = 'survey.question'
415 _description = 'Survey Question'
416 _rec_name = 'question'
423 'page_id': fields.many2one('survey.page', 'Survey page',
425 'survey_id': fields.related('page_id', 'survey_id', type='many2one',
426 relation='survey.survey', string='Survey'),
427 'parent_id': fields.many2one('survey.question', 'Parent question',
429 'sequence': fields.integer(string='Sequence'),
432 'question': fields.char('Question', required=1, translate=True),
433 'description': fields.html('Description', help="Use this field to add \
434 additional explanations about your question", translate=True,
435 oldname='descriptive_text'),
438 'type': fields.selection([('free_text', 'Long text zone'),
439 ('textbox', 'Text box'),
440 ('numerical_box', 'Numerical box'),
441 ('datetime', 'Date and Time'),
442 ('simple_choice', 'Multiple choice (one answer)'),
443 ('multiple_choice', 'Multiple choice (multiple answers)'),
444 ('matrix', 'Matrix')], 'Question Type', required=1),
445 'matrix_subtype': fields.selection([('simple', 'One choice per line'),
446 ('multiple', 'Several choices per line')], 'Matrix Type'),
447 'labels_ids': fields.one2many('survey.label',
448 'question_id', 'Suggested answers', oldname='answer_choice_ids'),
449 'labels_ids_2': fields.one2many('survey.label',
450 'question_id_2', 'Suggested answers'),
451 # labels are used for proposed choices
452 # if question.type == simple choice | multiple choice
453 # -> only labels_ids is used
454 # if question.type == matrix
455 # -> labels_ids are the columns of the matrix
456 # -> labels_ids_2 are the rows of the matrix
459 'column_nb': fields.selection([('12', '1 column choices'),
460 ('6', '2 columns choices'),
461 ('4', '3 columns choices'),
462 ('3', '4 columns choices'),
463 ('2', '6 columns choices')],
464 'Number of columns'),
465 'display_mode': fields.selection([('columns', 'Columns'),
466 ('dropdown', 'Dropdown menu')],
470 'comments_allowed': fields.boolean('Allow comments',
471 oldname="allow_comment"),
472 'comment_children_ids': fields.many2many('survey.question',
473 'question_comment_children_ids', 'comment_id', 'parent_id',
474 'Comment question'), # one2one in fact
475 'comment_count_as_answer': fields.boolean('Comment field is an answer choice',
476 oldname='make_comment_field'),
479 'validation_required': fields.boolean('Validate entry',
480 oldname='is_validation_require'),
481 'validation_type': fields.selection([
482 ('has_length', 'Must have a specific length'),
483 ('is_integer', 'Must be an integer'),
484 ('is_decimal', 'Must be a decimal number'),
485 #('is_date', 'Must be a date'),
486 ('is_email', 'Must be an email address')],
487 'Validation type', translate=True),
488 'validation_length_min': fields.integer('Minimum length'),
489 'validation_length_max': fields.integer('Maximum length'),
490 'validation_min_float_value': fields.float('Minimum value'),
491 'validation_max_float_value': fields.float('Maximum value'),
492 'validation_min_int_value': fields.integer('Minimum value'),
493 'validation_max_int_value': fields.integer('Maximum value'),
494 'validation_min_date': fields.date('Start date range'),
495 'validation_max_date': fields.date('End date range'),
496 'validation_error_msg': fields.char('Error message',
497 oldname='validation_valid_err_msg',
500 # Constraints on number of answers (matrices)
501 'constr_mandatory': fields.boolean('Mandatory question',
502 oldname="is_require_answer"),
503 'constr_type': fields.selection([('all', 'all'),
504 ('at least', 'at least'),
505 ('at most', 'at most'),
506 ('exactly', 'exactly'),
507 ('a range', 'a range')],
508 'Constraint on answers number', oldname='required_type'),
509 'constr_maximum_req_ans': fields.integer('Maximum Required Answer',
510 oldname='maximum_req_ans'),
511 'constr_minimum_req_ans': fields.integer('Minimum Required Answer',
512 oldname='minimum_req_ans'),
513 'constr_error_msg': fields.char("Error message",
514 oldname='req_error_msg'),
515 'user_input_line_ids': fields.one2many('survey.user_input_line',
516 'question_id', 'Answers',
517 domain=[('skipped', '=', False)]),
520 'page_id': lambda s, cr, uid, c: c.get('page_id'),
523 'matrix_subtype': 'simple',
525 'display_mode': 'dropdown',
526 'constr_type': 'at least',
527 'constr_minimum_req_ans': 1,
528 'constr_maximum_req_ans': 1,
529 'constr_error_msg': lambda s, cr, uid, c:
530 _('This question requires an answer.'),
531 'validation_error_msg': lambda s, cr, uid, c: _('The answer you entered has an invalid format.'),
532 'validation_required': False,
535 ('positive_len_min', 'CHECK (validation_length_min >= 0)', 'A length must be positive!'),
536 ('positive_len_max', 'CHECK (validation_length_max >= 0)', 'A length must be positive!'),
537 ('validation_length', 'CHECK (validation_length_min <= validation_length_max)', 'Max length cannot be smaller than min length!'),
538 ('validation_float', 'CHECK (validation_min_float_value <= validation_max_float_value)', 'Max value cannot be smaller than min value!'),
539 ('validation_int', 'CHECK (validation_min_int_value <= validation_max_int_value)', 'Max value cannot be smaller than min value!'),
540 ('validation_date', 'CHECK (validation_min_date <= validation_max_date)', 'Max date cannot be smaller than min date!'),
541 ('constr_number', 'CHECK (constr_minimum_req_ans <= constr_maximum_req_ans)', 'Max number of answers cannot be smaller than min number!')
544 def survey_save(self, cr, uid, ids, context=None):
547 surv_name_wiz = self.pool.get('survey.question.wiz')
548 surv_name_wiz.write(cr, uid, [context.get('wizard_id', False)],
549 {'transfer': True, 'page_no': context.get('page_number', False)})
553 'res_model': 'survey.question.wiz',
554 'type': 'ir.actions.act_window',
561 def validate_question(self, cr, uid, question, post, answer_tag, context=None):
562 ''' Validate question, depending on question type and parameters '''
564 checker = getattr(self, 'validate_' + question.type)
565 except AttributeError:
566 _logger.warning(question.type + ": This type of question has no validation method")
569 return checker(cr, uid, question, post, answer_tag, context=context)
571 def validate_free_text(self, cr, uid, question, post, answer_tag, context=None):
573 answer = post[answer_tag].strip()
574 # Empty answer to mandatory question
575 if question.constr_mandatory and not answer:
576 errors.update({answer_tag: question.constr_error_msg})
579 def validate_textbox(self, cr, uid, question, post, answer_tag, context=None):
581 answer = post[answer_tag].strip()
582 # Empty answer to mandatory question
583 if question.constr_mandatory and not answer:
584 errors.update({answer_tag: question.constr_error_msg})
585 # Answer validation (if properly defined)
586 if answer and question.validation_required and question.validation_type:
587 # Length of the answer must be in a range
588 if question.validation_type == "has_length":
589 if not (question.validation_length_min <= len(answer) <= question.validation_length_max):
590 errors.update({answer_tag: question.validation_error_msg})
592 # Answer must be an integer in a particular range
593 elif question.validation_type == "is_integer":
595 intanswer = int(answer)
596 # Answer is not an integer
598 errors.update({answer_tag: question.validation_error_msg})
600 # Answer is not in the right range
601 if not (question.validation_min_int_value <= intanswer <= question.validation_max_int_value):
602 errors.update({answer_tag: question.validation_error_msg})
603 # Answer must be a float in a particular range
604 elif question.validation_type == "is_decimal":
606 floatanswer = float(answer)
607 # Answer is not an integer
609 errors.update({answer_tag: question.validation_error_msg})
611 # Answer is not in the right range
612 if not (question.validation_min_float_value <= floatanswer <= question.validation_max_float_value):
613 errors.update({answer_tag: question.validation_error_msg})
615 # Answer must be a date in a particular range
616 elif question.validation_type == "is_date":
617 raise Exception("Not implemented")
618 # Answer must be an email address
619 # Note: this validation is very basic:
620 # all the strings of the form
621 # <something>@<anything>.<extension>
623 elif question.validation_type == "is_email":
624 if not re.match(r"[^@]+@[^@]+\.[^@]+", answer):
625 errors.update({answer_tag: question.validation_error_msg})
630 def validate_numerical_box(self, cr, uid, question, post, answer_tag, context=None):
632 answer = post[answer_tag].strip()
633 # Empty answer to mandatory question
634 if question.constr_mandatory and not answer:
635 errors.update({answer_tag: question.constr_error_msg})
636 # Checks if user input is a number
641 errors.update({answer_tag: question.constr_error_msg})
644 def validate_datetime(self, cr, uid, question, post, answer_tag, context=None):
646 answer = post[answer_tag].strip()
647 # Empty answer to mandatory question
648 if question.constr_mandatory and not answer:
649 errors.update({answer_tag: question.constr_error_msg})
650 # Checks if user input is a datetime
651 # TODO when datepicker will be available
654 def validate_simple_choice(self, cr, uid, question, post, answer_tag, context=None):
656 if question.comments_allowed:
657 comment_tag = "%s_%s" % (answer_tag, question.comment_children_ids[0].id)
658 # Empty answer to mandatory question
659 if question.constr_mandatory and not answer_tag in post:
660 errors.update({answer_tag: question.constr_error_msg})
661 if question.constr_mandatory and answer_tag in post and post[answer_tag].strip() == '':
662 errors.update({answer_tag: question.constr_error_msg})
663 # Answer is a comment and is empty
664 if question.constr_mandatory and answer_tag in post and post[answer_tag] == "-1" and question.comment_count_as_answer and comment_tag in post and not post[comment_tag].strip():
665 errors.update({answer_tag: question.constr_error_msg})
668 def validate_multiple_choice(self, cr, uid, question, post, answer_tag, context=None):
670 if question.constr_mandatory:
671 answer_candidates = dict_keys_startswith(post, answer_tag)
672 comment_flag = answer_candidates.pop(("%s_%s" % (answer_tag, -1)), None)
673 if question.comments_allowed:
674 comment_answer = answer_candidates.pop(("%s_%s" % (answer_tag, question.comment_children_ids[0].id)), '').strip()
675 # There is no answer neither comments (if comments count as answer)
676 if not answer_candidates and question.comment_count_as_answer and comment_flag and comment_answer:
677 errors.update({answer_tag: question.constr_error_msg})
678 # There is no answer at all
679 if not answer_candidates and not comment_flag:
680 errors.update({answer_tag: question.constr_error_msg})
683 def validate_matrix(self, cr, uid, question, post, answer_tag, context=None):
685 if question.constr_mandatory:
686 lines_number = len(question.labels_ids_2)
687 answer_candidates = dict_keys_startswith(post, answer_tag)
688 #comment_answer = answer_candidates.pop(("%s_%s" % (answer_tag, question.comment_children_ids[0].id)), None)
689 # Number of lines that have been answered
690 if question.matrix_subtype == 'simple':
691 answer_number = len(answer_candidates)
692 elif question.matrix_subtype == 'multiple':
693 answer_number = len(set([sk.rsplit('_', 1)[0] for sk in answer_candidates.keys()]))
695 raise RuntimeError("Invalid matrix subtype")
697 if question.constr_type == 'all' and answer_number != lines_number:
698 errors.update({answer_tag: question.constr_error_msg})
699 elif question.constr_type == 'at least' and answer_number < question.constr_minimum_req_ans:
700 errors.update({answer_tag: question.constr_error_msg})
701 elif question.constr_type == 'at most' and answer_number > question.constr_maximum_req_ans:
702 errors.update({answer_tag: question.constr_error_msg})
703 elif question.constr_type == 'exactly' and answer_number != question.constr_maximum_req_ans:
704 errors.update({answer_tag: question.constr_error_msg})
705 elif question.constr_type == 'a range' and not (question.constr_minimum_req_ans <= answer_number <= question.constr_maximum_req_ans):
706 errors.update({answer_tag: question.constr_error_msg})
708 pass # Everything is okay
712 class survey_label(osv.Model):
713 ''' A suggested answer for a question '''
714 _name = 'survey.label'
717 _description = 'Survey Label'
720 'question_id': fields.many2one('survey.question', 'Question',
722 'question_id_2': fields.many2one('survey.question', 'Question',
724 'sequence': fields.integer('Label Sequence order'),
725 'value': fields.char("Suggested value", translate=True,
727 'quizz_mark': fields.float('Score for this answer'),
734 class survey_user_input(osv.Model):
735 ''' Metadata for a set of one user's answers to a particular survey '''
736 _name = "survey.user_input"
737 _rec_name = 'date_create'
738 _description = 'Survey User Input'
740 def _quizz_get_score(self, cr, uid, ids, name, args, context=None):
742 for user_input in self.browse(cr, uid, ids, context=context):
743 ret[user_input.id] = sum([uil.quizz_mark for uil in user_input.user_input_line_ids] or [0.0])
747 'survey_id': fields.many2one('survey.survey', 'Survey', required=True,
748 readonly=1, ondelete='restrict'),
749 'date_create': fields.datetime('Creation Date', required=True,
751 'deadline': fields.datetime("Deadline",
752 help="Date by which the person can open the survey and submit answers.\
754 oldname="date_deadline"),
755 'type': fields.selection([('manually', 'Manually'), ('link', 'Link')],
756 'Answer Type', required=1, readonly=1,
757 oldname="response_type"),
758 'state': fields.selection([('new', 'Not started yet'),
759 ('skip', 'Partially completed'),
760 ('done', 'Completed')],
763 'test_entry': fields.boolean('Test entry', readonly=1),
764 'token': fields.char("Identification token", readonly=1, required=1),
766 # Optional Identification data
767 'partner_id': fields.many2one('res.partner', 'Partner', readonly=1),
768 'email': fields.char("E-mail", readonly=1),
771 'last_displayed_page_id': fields.many2one('survey.page',
772 'Last displayed page'),
774 'user_input_line_ids': fields.one2many('survey.user_input_line',
775 'user_input_id', 'Answers'),
777 # URLs used to display the answers
778 'result_url': fields.related('survey_id', 'result_url', string="Public link to the survey results"),
779 'print_url': fields.related('survey_id', 'print_url', string="Public link to the empty survey"),
781 'quizz_score': fields.function(_quizz_get_score, type="float", string="Score for the quiz")
784 'date_create': fields.datetime.now,
787 'token': lambda s, cr, uid, c: uuid.uuid4().__str__(),
792 ('unique_token', 'UNIQUE (token)', 'A token must be unique!')
795 def copy(self, cr, uid, id, default=None, context=None):
796 raise osv.except_osv(_('Warning!'), _('You cannot duplicate this \
799 def do_clean_emptys(self, cr, uid, automatic=False, context=None):
800 ''' Remove empty user inputs that have been created manually (cronjob) '''
801 empty_user_input_ids = self.search(cr, uid, [('type', '=', 'manually'),
802 ('state', '=', 'new'),
803 ('date_create', '<', (datetime.datetime.now() - datetime.timedelta(hours=1)).strftime(DF))],
805 if empty_user_input_ids:
806 self.unlink(cr, uid, empty_user_input_ids, context=context)
808 def purge_tests(self, cr, uid, context=None):
809 ''' Remove the test entries '''
810 old_tests = self.search(cr, uid, [('test_entry', '=', True)], context=context)
811 return self.unlink(cr, uid, old_tests, context=context)
813 def action_survey_resent(self, cr, uid, ids, context=None):
814 ''' Sent again the invitation '''
815 record = self.browse(cr, uid, ids[0], context=context)
816 context = context or {}
818 'survey_resent_token': True,
819 'default_partner_ids': record.partner_id and [record.partner_id.id] or [],
820 'default_multi_email': record.email or "",
821 'default_public': 'email_private',
823 return self.pool.get('survey.survey').action_send_survey(cr, uid,
824 [record.survey_id.id], context=context)
826 def action_view_answers(self, cr, uid, ids, context=None):
827 ''' Open the website page with the survey form '''
828 user_input = self.read(cr, uid, ids, ['print_url', 'token'], context=context)[0]
830 'type': 'ir.actions.act_url',
831 'name': "View Answers",
833 'url': '%s/%s' % (user_input['print_url'], user_input['token'])
836 def action_survey_results(self, cr, uid, ids, context=None):
837 ''' Open the website page with the survey results '''
839 'type': 'ir.actions.act_url',
840 'name': "Survey Results",
842 'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
846 class survey_user_input_line(osv.Model):
847 _name = 'survey.user_input_line'
848 _description = 'Survey User Input Line'
849 _rec_name = 'date_create'
852 'user_input_id': fields.many2one('survey.user_input', 'User Input',
853 ondelete='cascade', required=1),
854 'question_id': fields.many2one('survey.question', 'Question',
855 ondelete='restrict'),
856 'page_id': fields.related('question_id', 'page_id', type='many2one',
857 relation='survey.page', string="Page"),
858 'survey_id': fields.related('user_input_id', 'survey_id',
859 type="many2one", relation="survey.survey",
860 string='Survey', store=True),
861 'date_create': fields.datetime('Create Date', required=1),
862 'skipped': fields.boolean('Skipped'),
863 'answer_type': fields.selection([('text', 'Text'),
864 ('number', 'Number'),
866 ('free_text', 'Free Text'),
867 ('suggestion', 'Suggestion')],
869 'value_text': fields.char("Text answer"),
870 'value_number': fields.float("Numerical answer"),
871 'value_date': fields.datetime("Date answer"),
872 'value_free_text': fields.text("Free Text answer"),
873 'value_suggested': fields.many2one('survey.label', "Suggested answer"),
874 'value_suggested_row': fields.many2one('survey.label', "Row answer"),
875 'quizz_mark': fields.float("Score given for this answer")
880 'date_create': fields.datetime.now()
883 def create(self, cr, uid, vals, context=None):
884 value_suggested = vals.get('value_suggested')
886 mark = self.pool.get('survey.label').browse(cr, uid, int(value_suggested), context=context).quizz_mark
887 vals.update({'quizz_mark': mark})
888 return super(survey_user_input_line, self).create(cr, uid, vals, context=context)
890 def write(self, cr, uid, ids, vals, context=None):
891 value_suggested = vals.get('value_suggested')
893 mark = self.pool.get('survey.label').browse(cr, uid, int(value_suggested), context=context).quizz_mark
894 vals.update({'quizz_mark': mark})
895 return super(survey_user_input_line, self).write(cr, uid, ids, vals, context=context)
897 def save_lines(self, cr, uid, user_input_id, question, post, answer_tag,
899 ''' Save answers to questions, depending on question type
901 If an answer already exists for question and user_input_id, it will be
902 overwritten (in order to maintain data consistency). '''
904 saver = getattr(self, 'save_line_' + question.type)
905 except AttributeError:
906 _logger.error(question.type + ": This type of question has no saving function")
909 saver(cr, uid, user_input_id, question, post, answer_tag, context=context)
911 def save_line_free_text(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
913 'user_input_id': user_input_id,
914 'question_id': question.id,
915 'page_id': question.page_id.id,
916 'survey_id': question.survey_id.id,
919 if answer_tag in post and post[answer_tag].strip() != '':
920 vals.update({'answer_type': 'free_text', 'value_free_text': post[answer_tag]})
922 vals.update({'answer_type': None, 'skipped': True})
923 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
924 ('survey_id', '=', question.survey_id.id),
925 ('question_id', '=', question.id)],
928 self.write(cr, uid, old_uil[0], vals, context=context)
930 self.create(cr, uid, vals, context=context)
933 def save_line_textbox(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
935 'user_input_id': user_input_id,
936 'question_id': question.id,
937 'page_id': question.page_id.id,
938 'survey_id': question.survey_id.id,
941 if answer_tag in post and post[answer_tag].strip() != '':
942 vals.update({'answer_type': 'text', 'value_text': post[answer_tag]})
944 vals.update({'answer_type': None, 'skipped': True})
945 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
946 ('survey_id', '=', question.survey_id.id),
947 ('question_id', '=', question.id)],
950 self.write(cr, uid, old_uil[0], vals, context=context)
952 self.create(cr, uid, vals, context=context)
955 def save_line_numerical_box(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
957 'user_input_id': user_input_id,
958 'question_id': question.id,
959 'page_id': question.page_id.id,
960 'survey_id': question.survey_id.id,
963 if answer_tag in post and post[answer_tag].strip() != '':
964 vals.update({'answer_type': 'number', 'value_number': float(post[answer_tag])})
966 vals.update({'answer_type': None, 'skipped': True})
967 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
968 ('survey_id', '=', question.survey_id.id),
969 ('question_id', '=', question.id)],
972 self.write(cr, uid, old_uil[0], vals, context=context)
974 self.create(cr, uid, vals, context=context)
977 def save_line_datetime(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
979 'user_input_id': user_input_id,
980 'question_id': question.id,
981 'page_id': question.page_id.id,
982 'survey_id': question.survey_id.id,
985 if answer_tag in post and post[answer_tag].strip() != '':
986 vals.update({'answer_type': 'date', 'value_date': post[answer_tag]})
988 vals.update({'answer_type': None, 'skipped': True})
989 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
990 ('survey_id', '=', question.survey_id.id),
991 ('question_id', '=', question.id)],
994 self.write(cr, uid, old_uil[0], vals, context=context)
996 self.create(cr, uid, vals, context=context)
999 def save_line_simple_choice(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1001 'user_input_id': user_input_id,
1002 'question_id': question.id,
1003 'page_id': question.page_id.id,
1004 'survey_id': question.survey_id.id,
1007 if answer_tag in post and post[answer_tag].strip() != '':
1008 vals.update({'answer_type': 'suggestion', 'value_suggested': post[answer_tag]})
1010 vals.update({'answer_type': None, 'skipped': True})
1011 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
1012 ('survey_id', '=', question.survey_id.id),
1013 ('question_id', '=', question.id)],
1016 self.write(cr, uid, old_uil[0], vals, context=context)
1018 self.create(cr, uid, vals, context=context)
1021 def save_line_multiple_choice(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1023 'user_input_id': user_input_id,
1024 'question_id': question.id,
1025 'page_id': question.page_id.id,
1026 'survey_id': question.survey_id.id,
1029 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
1030 ('survey_id', '=', question.survey_id.id),
1031 ('question_id', '=', question.id)],
1034 self.unlink(cr, uid, old_uil, context=context)
1036 ca = dict_keys_startswith(post, answer_tag)
1039 vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a]})
1040 self.create(cr, uid, vals, context=context)
1042 vals.update({'answer_type': None, 'skipped': True})
1043 self.create(cr, uid, vals, context=context)
1046 def save_line_matrix(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1048 'user_input_id': user_input_id,
1049 'question_id': question.id,
1050 'page_id': question.page_id.id,
1051 'survey_id': question.survey_id.id,
1054 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
1055 ('survey_id', '=', question.survey_id.id),
1056 ('question_id', '=', question.id)],
1059 self.unlink(cr, uid, old_uil, context=context)
1061 ca = dict_keys_startswith(post, answer_tag)
1064 if question.matrix_subtype == 'simple':
1065 for row in question.labels_ids_2:
1066 a_tag = "%s_%s" % (answer_tag, row.id)
1069 vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a_tag], 'value_suggested_row': row.id})
1070 self.create(cr, uid, vals, context=context)
1072 elif question.matrix_subtype == 'multiple':
1073 for col in question.labels_ids:
1074 for row in question.labels_ids_2:
1075 a_tag = "%s_%s_%s" % (answer_tag, row.id, col.id)
1078 vals.update({'answer_type': 'suggestion', 'value_suggested': col.id, 'value_suggested_row': row.id})
1079 self.create(cr, uid, vals, context=context)
1081 vals.update({'answer_type': None, 'skipped': True})
1082 self.create(cr, uid, vals, context=context)
1086 def dict_keys_startswith(dictionary, string):
1087 '''Returns a dictionary containing the elements of <dict> whose keys start
1091 This function uses dictionary comprehensions (Python >= 2.7)'''
1092 return {k: dictionary[k] for k in filter(lambda key: key.startswith(string), dictionary.keys())}