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')
178 def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
179 """ Read group customization in order to display all the stages in the
180 kanban view, even if they are empty """
181 stage_obj = self.pool.get('survey.stage')
182 order = stage_obj._order
183 access_rights_uid = access_rights_uid or uid
185 if read_group_order == 'stage_id desc':
186 order = '%s desc' % order
188 stage_ids = stage_obj._search(cr, uid, [], order=order, access_rights_uid=access_rights_uid, context=context)
189 result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
191 # restore order of the search
192 result.sort(lambda x, y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
195 for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
196 fold[stage.id] = stage.fold or False
200 'stage_id': _read_group_stage_ids
205 def write(self, cr, uid, ids, vals, context=None):
206 new_state = vals.get('state')
207 if new_state == 'draft':
208 vals.update({'date_open': None})
209 vals.update({'date_close': None})
210 self.message_post(cr, uid, ids, body="""<p>Survey drafted</p>""", context=context)
211 elif new_state == 'open':
212 if self._has_questions(cr, uid, ids, context=None):
213 vals.update({'date_open': fields.datetime.now(), 'date_close': None})
214 self.message_post(cr, uid, ids, body="""<p>Survey opened</p>""", context=context)
216 raise osv.except_osv(_('Error!'), _('You can not open a survey that has no questions.'))
217 elif new_state == 'close':
218 vals.update({'date_close': fields.datetime.now()})
219 self.message_post(cr, uid, ids, body="""<p>Survey closed</p>""", context=context)
220 # Purge the tests records
221 self.pool.get('survey.user_input').purge_tests(cr, uid, context=context)
222 elif new_state == 'cancel':
223 self.message_post(cr, uid, ids, body="""<p>Survey cancelled</p>""", context=context)
224 return super(survey_survey, self).write(cr, uid, ids, vals, context=context)
226 def copy(self, cr, uid, ids, default=None, context=None):
228 current_rec = self.read(cr, uid, ids, context=context)
229 title = _("%s (copy)") % (current_rec.get('title'))
230 vals['title'] = title
231 vals['user_input_ids'] = []
232 return super(survey_survey, self).copy(cr, uid, ids, vals,
235 def next_page(self, cr, uid, user_input, page_id, go_back=False, context=None):
236 '''The next page to display to the user, knowing that page_id is the id
237 of the last displayed page.
239 If page_id == 0, it will always return the first page of the survey.
241 If all the pages have been displayed and go_back == False, it will
244 If go_back == True, it will return the *previous* page instead of the
248 It is assumed here that a careful user will not try to set go_back
249 to True if she knows that the page to display is the first one!
250 (doing this will probably cause a giant worm to eat her house)'''
251 survey = user_input.survey_id
252 pages = list(enumerate(survey.page_ids))
256 return (pages[0][1], 0, len(pages) == 1)
258 current_page_index = pages.index((filter(lambda p: p[1].id == page_id, pages))[0])
260 # All the pages have been displayed
261 if current_page_index == len(pages) - 1 and not go_back:
262 return (None, -1, False)
263 # Let's get back, baby!
264 elif go_back and survey.users_can_go_back:
265 return (pages[current_page_index - 1][1], current_page_index - 1, False)
267 # This will show the last page
268 if current_page_index == len(pages) - 2:
269 return (pages[current_page_index + 1][1], current_page_index + 1, True)
270 # This will show a regular page
272 return (pages[current_page_index + 1][1], current_page_index + 1, False)
276 def action_kanban_update_state(self, cr, uid, ids, context=None):
277 ''' Change the state from the kanban ball '''
278 for survey in self.read(cr, uid, ids, ['state'], context=context):
279 if survey['state'] == 'draft':
280 self.write(cr, uid, [survey['id']], {'state': 'open'}, context=context)
281 elif survey['state'] == 'open':
282 self.write(cr, uid, [survey['id']], {'state': 'close'}, context=context)
283 elif survey['state'] == 'close':
284 self.write(cr, uid, [survey['id']], {'state': 'cancel'}, context=context)
285 elif survey['state'] == 'cancel':
286 self.write(cr, uid, [survey['id']], {'state': 'draft'}, context=context)
289 def action_start_survey(self, cr, uid, ids, context=None):
290 ''' Open the website page with the survey form '''
292 if context and 'survey_token' in context:
293 trail = "/" + context['survey_token']
295 'type': 'ir.actions.act_url',
296 'name': "Start Survey",
298 'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + trail
301 def action_send_survey(self, cr, uid, ids, context=None):
302 ''' Open a window to compose an email, pre-filled with the survey
304 if not self._has_questions(cr, uid, ids, context=None):
305 raise osv.except_osv(_('Error!'), _('You cannot send an invitation for a survey that has no questions.'))
307 survey_browse = self.pool.get('survey.survey').browse(cr, uid, ids,
309 if survey_browse.state != "open":
310 raise osv.except_osv(_('Warning!'),
311 _("You cannot send invitations unless the survey is open."))
313 assert len(ids) == 1, 'This option should only be used for a single \
315 ir_model_data = self.pool.get('ir.model.data')
316 templates = ir_model_data.get_object_reference(cr, uid,
317 'survey', 'email_template_survey')
318 template_id = templates[1] if len(templates) > 0 else False
321 ctx.update({'default_model': 'survey.survey',
322 'default_res_id': ids[0],
323 'default_survey_id': ids[0],
324 'default_use_template': bool(template_id),
325 'default_template_id': template_id,
326 'default_composition_mode': 'comment',
327 'survey_state': survey_browse.state}
330 'type': 'ir.actions.act_window',
333 'res_model': 'survey.mail.compose.message',
338 def action_print_survey(self, cr, uid, ids, context=None):
339 ''' Open the website page with the survey printable view '''
341 if context and 'survey_token' in context:
342 trail = "/" + context['survey_token']
344 'type': 'ir.actions.act_url',
345 'name': "Print Survey",
347 'url': self.read(cr, uid, ids, ['print_url'], context=context)[0]['print_url'] + trail
350 def action_result_survey(self, cr, uid, ids, context=None):
351 ''' Open the website page with the survey results view '''
353 'type': 'ir.actions.act_url',
354 'name': "Results of the Survey",
356 'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
359 def action_test_survey(self, cr, uid, ids, context=None):
360 ''' Open the website page with the survey form into test mode'''
362 'type': 'ir.actions.act_url',
363 'name': "Results of the Survey",
365 'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + "/phantom"
369 class survey_stage(osv.Model):
370 """Stages for Kanban view of surveys"""
372 _name = 'survey.stage'
373 _description = 'Survey Stage'
377 'name': fields.text(string="Name", required=True, translate=True),
378 'sequence': fields.integer(string="Sequence"),
379 'survey_open': fields.boolean(string="Display these surveys?"),
380 'fold': fields.boolean(string="Folded column by default")
387 ('positive_sequence', 'CHECK(sequence >= 0)', 'Sequence number MUST be a natural')
391 class survey_page(osv.Model):
392 '''A page for a survey.
394 Pages are essentially containers, allowing to group questions by ordered
398 A page should be deleted if the survey it belongs to is deleted. '''
400 _name = 'survey.page'
401 _description = 'Survey Page'
408 'title': fields.char('Page Title', required=1,
410 'survey_id': fields.many2one('survey.survey', 'Survey',
411 ondelete='cascade', required=True),
412 'question_ids': fields.one2many('survey.question', 'page_id',
414 'sequence': fields.integer('Page number'),
415 'description': fields.html('Description',
416 help="An introductory text to your page", translate=True,
425 def copy(self, cr, uid, ids, default=None, context=None):
427 current_rec = self.read(cr, uid, ids, context=context)
428 title = _("%s (copy)") % (current_rec.get('title'))
429 vals.update({'title': title})
430 return super(survey_page, self).copy(cr, uid, ids, vals,
434 class survey_question(osv.Model):
435 ''' Questions that will be asked in a survey.
437 Each question can have one of more suggested answers (eg. in case of
438 dropdown choices, multi-answer checkboxes, radio buttons...).'''
439 _name = 'survey.question'
440 _description = 'Survey Question'
441 _rec_name = 'question'
448 'page_id': fields.many2one('survey.page', 'Survey page',
450 'survey_id': fields.related('page_id', 'survey_id', type='many2one',
451 relation='survey.survey', string='Survey'),
452 'parent_id': fields.many2one('survey.question', 'Parent question',
454 'sequence': fields.integer(string='Sequence'),
457 'question': fields.char('Question', required=1, translate=True),
458 'description': fields.html('Description', help="Use this field to add \
459 additional explanations about your question", translate=True,
460 oldname='descriptive_text'),
463 'type': fields.selection([('free_text', 'Long text zone'),
464 ('textbox', 'Text box'),
465 ('numerical_box', 'Numerical box'),
466 ('datetime', 'Date and Time'),
467 ('simple_choice', 'Multiple choice (one answer)'),
468 ('multiple_choice', 'Multiple choice (multiple answers)'),
469 ('matrix', 'Matrix')], 'Question Type', required=1),
470 'matrix_subtype': fields.selection([('simple', 'One choice per line'),
471 ('multiple', 'Several choices per line')], 'Matrix Type'),
472 'labels_ids': fields.one2many('survey.label',
473 'question_id', 'Suggested answers', oldname='answer_choice_ids'),
474 'labels_ids_2': fields.one2many('survey.label',
475 'question_id_2', 'Suggested answers'),
476 # labels are used for proposed choices
477 # if question.type == simple choice | multiple choice
478 # -> only labels_ids is used
479 # if question.type == matrix
480 # -> labels_ids are the columns of the matrix
481 # -> labels_ids_2 are the rows of the matrix
484 'column_nb': fields.selection([('12', '1 column choices'),
485 ('6', '2 columns choices'),
486 ('4', '3 columns choices'),
487 ('3', '4 columns choices'),
488 ('2', '6 columns choices')],
489 'Number of columns'),
490 'display_mode': fields.selection([('columns', 'Columns'),
491 ('dropdown', 'Dropdown menu')],
495 'comments_allowed': fields.boolean('Allow comments',
496 oldname="allow_comment"),
497 'comment_children_ids': fields.many2many('survey.question',
498 'question_comment_children_ids', 'comment_id', 'parent_id',
499 'Comment question'), # one2one in fact
500 'comment_count_as_answer': fields.boolean('Comment field is an answer choice',
501 oldname='make_comment_field'),
504 'validation_required': fields.boolean('Validate entry',
505 oldname='is_validation_require'),
506 'validation_type': fields.selection([
507 ('has_length', 'Must have a specific length'),
508 ('is_integer', 'Must be an integer'),
509 ('is_decimal', 'Must be a decimal number'),
510 #('is_date', 'Must be a date'),
511 ('is_email', 'Must be an email address')],
512 'Validation type', translate=True),
513 'validation_length_min': fields.integer('Minimum length'),
514 'validation_length_max': fields.integer('Maximum length'),
515 'validation_min_float_value': fields.float('Minimum value'),
516 'validation_max_float_value': fields.float('Maximum value'),
517 'validation_min_int_value': fields.integer('Minimum value'),
518 'validation_max_int_value': fields.integer('Maximum value'),
519 'validation_min_date': fields.date('Start date range'),
520 'validation_max_date': fields.date('End date range'),
521 'validation_error_msg': fields.char('Error message',
522 oldname='validation_valid_err_msg',
525 # Constraints on number of answers (matrices)
526 'constr_mandatory': fields.boolean('Mandatory question',
527 oldname="is_require_answer"),
528 'constr_type': fields.selection([('all', 'all'),
529 ('at least', 'at least'),
530 ('at most', 'at most'),
531 ('exactly', 'exactly'),
532 ('a range', 'a range')],
533 'Constraint on answers number', oldname='required_type'),
534 'constr_maximum_req_ans': fields.integer('Maximum Required Answer',
535 oldname='maximum_req_ans'),
536 'constr_minimum_req_ans': fields.integer('Minimum Required Answer',
537 oldname='minimum_req_ans'),
538 'constr_error_msg': fields.char("Error message",
539 oldname='req_error_msg'),
540 'user_input_line_ids': fields.one2many('survey.user_input_line',
541 'question_id', 'Answers',
542 domain=[('skipped', '=', False)]),
545 'page_id': lambda s, cr, uid, c: c.get('page_id'),
548 'matrix_subtype': 'simple',
550 'display_mode': 'dropdown',
551 'constr_type': 'at least',
552 'constr_minimum_req_ans': 1,
553 'constr_maximum_req_ans': 1,
554 'constr_error_msg': lambda s, cr, uid, c:
555 _('This question requires an answer.'),
556 'validation_error_msg': lambda s, cr, uid, c: _('The answer you entered has an invalid format.'),
557 'validation_required': False,
560 ('positive_len_min', 'CHECK (validation_length_min >= 0)', 'A length must be positive!'),
561 ('positive_len_max', 'CHECK (validation_length_max >= 0)', 'A length must be positive!'),
562 ('validation_length', 'CHECK (validation_length_min <= validation_length_max)', 'Max length cannot be smaller than min length!'),
563 ('validation_float', 'CHECK (validation_min_float_value <= validation_max_float_value)', 'Max value cannot be smaller than min value!'),
564 ('validation_int', 'CHECK (validation_min_int_value <= validation_max_int_value)', 'Max value cannot be smaller than min value!'),
565 ('validation_date', 'CHECK (validation_min_date <= validation_max_date)', 'Max date cannot be smaller than min date!'),
566 ('constr_number', 'CHECK (constr_minimum_req_ans <= constr_maximum_req_ans)', 'Max number of answers cannot be smaller than min number!')
569 def survey_save(self, cr, uid, ids, context=None):
572 surv_name_wiz = self.pool.get('survey.question.wiz')
573 surv_name_wiz.write(cr, uid, [context.get('wizard_id', False)],
574 {'transfer': True, 'page_no': context.get('page_number', False)})
578 'res_model': 'survey.question.wiz',
579 'type': 'ir.actions.act_window',
586 def validate_question(self, cr, uid, question, post, answer_tag, context=None):
587 ''' Validate question, depending on question type and parameters '''
589 checker = getattr(self, 'validate_' + question.type)
590 except AttributeError:
591 _logger.warning(question.type + ": This type of question has no validation method")
594 return checker(cr, uid, question, post, answer_tag, context=context)
596 def validate_free_text(self, cr, uid, question, post, answer_tag, context=None):
598 answer = post[answer_tag].strip()
599 # Empty answer to mandatory question
600 if question.constr_mandatory and not answer:
601 errors.update({answer_tag: question.constr_error_msg})
604 def validate_textbox(self, cr, uid, question, post, answer_tag, context=None):
606 answer = post[answer_tag].strip()
607 # Empty answer to mandatory question
608 if question.constr_mandatory and not answer:
609 errors.update({answer_tag: question.constr_error_msg})
610 # Answer validation (if properly defined)
611 if answer and question.validation_required and question.validation_type:
612 # Length of the answer must be in a range
613 if question.validation_type == "has_length":
614 if not (question.validation_length_min <= len(answer) <= question.validation_length_max):
615 errors.update({answer_tag: question.validation_error_msg})
617 # Answer must be an integer in a particular range
618 elif question.validation_type == "is_integer":
620 intanswer = int(answer)
621 # Answer is not an integer
623 errors.update({answer_tag: question.validation_error_msg})
625 # Answer is not in the right range
626 if not (question.validation_min_int_value <= intanswer <= question.validation_max_int_value):
627 errors.update({answer_tag: question.validation_error_msg})
628 # Answer must be a float in a particular range
629 elif question.validation_type == "is_decimal":
631 floatanswer = float(answer)
632 # Answer is not an integer
634 errors.update({answer_tag: question.validation_error_msg})
636 # Answer is not in the right range
637 if not (question.validation_min_float_value <= floatanswer <= question.validation_max_float_value):
638 errors.update({answer_tag: question.validation_error_msg})
640 # Answer must be a date in a particular range
641 elif question.validation_type == "is_date":
642 raise Exception("Not implemented")
643 # Answer must be an email address
644 # Note: this validation is very basic:
645 # all the strings of the form
646 # <something>@<anything>.<extension>
648 elif question.validation_type == "is_email":
649 if not re.match(r"[^@]+@[^@]+\.[^@]+", answer):
650 errors.update({answer_tag: question.validation_error_msg})
655 def validate_numerical_box(self, cr, uid, question, post, answer_tag, context=None):
657 answer = post[answer_tag].strip()
658 # Empty answer to mandatory question
659 if question.constr_mandatory and not answer:
660 errors.update({answer_tag: question.constr_error_msg})
661 # Checks if user input is a number
666 errors.update({answer_tag: question.constr_error_msg})
669 def validate_datetime(self, cr, uid, question, post, answer_tag, context=None):
671 answer = post[answer_tag].strip()
672 # Empty answer to mandatory question
673 if question.constr_mandatory and not answer:
674 errors.update({answer_tag: question.constr_error_msg})
675 # Checks if user input is a datetime
676 # TODO when datepicker will be available
679 def validate_simple_choice(self, cr, uid, question, post, answer_tag, context=None):
681 if question.comments_allowed:
682 comment_tag = "%s_%s" % (answer_tag, question.comment_children_ids[0].id)
683 # Empty answer to mandatory question
684 if question.constr_mandatory and not answer_tag in post:
685 errors.update({answer_tag: question.constr_error_msg})
686 if question.constr_mandatory and answer_tag in post and post[answer_tag].strip() == '':
687 errors.update({answer_tag: question.constr_error_msg})
688 # Answer is a comment and is empty
689 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():
690 errors.update({answer_tag: question.constr_error_msg})
693 def validate_multiple_choice(self, cr, uid, question, post, answer_tag, context=None):
695 if question.constr_mandatory:
696 answer_candidates = dict_keys_startswith(post, answer_tag)
697 comment_flag = answer_candidates.pop(("%s_%s" % (answer_tag, -1)), None)
698 if question.comments_allowed:
699 comment_answer = answer_candidates.pop(("%s_%s" % (answer_tag, question.comment_children_ids[0].id)), '').strip()
700 # There is no answer neither comments (if comments count as answer)
701 if not answer_candidates and question.comment_count_as_answer and comment_flag and comment_answer:
702 errors.update({answer_tag: question.constr_error_msg})
703 # There is no answer at all
704 if not answer_candidates and not comment_flag:
705 errors.update({answer_tag: question.constr_error_msg})
708 def validate_matrix(self, cr, uid, question, post, answer_tag, context=None):
710 if question.constr_mandatory:
711 lines_number = len(question.labels_ids_2)
712 answer_candidates = dict_keys_startswith(post, answer_tag)
713 #comment_answer = answer_candidates.pop(("%s_%s" % (answer_tag, question.comment_children_ids[0].id)), None)
714 # Number of lines that have been answered
715 if question.matrix_subtype == 'simple':
716 answer_number = len(answer_candidates)
717 elif question.matrix_subtype == 'multiple':
718 answer_number = len(set([sk.rsplit('_', 1)[0] for sk in answer_candidates.keys()]))
720 raise RuntimeError("Invalid matrix subtype")
722 if question.constr_type == 'all' and answer_number != lines_number:
723 errors.update({answer_tag: question.constr_error_msg})
724 elif question.constr_type == 'at least' and answer_number < question.constr_minimum_req_ans:
725 errors.update({answer_tag: question.constr_error_msg})
726 elif question.constr_type == 'at most' and answer_number > question.constr_maximum_req_ans:
727 errors.update({answer_tag: question.constr_error_msg})
728 elif question.constr_type == 'exactly' and answer_number != question.constr_maximum_req_ans:
729 errors.update({answer_tag: question.constr_error_msg})
730 elif question.constr_type == 'a range' and not (question.constr_minimum_req_ans <= answer_number <= question.constr_maximum_req_ans):
731 errors.update({answer_tag: question.constr_error_msg})
733 pass # Everything is okay
737 class survey_label(osv.Model):
738 ''' A suggested answer for a question '''
739 _name = 'survey.label'
742 _description = 'Survey Label'
745 'question_id': fields.many2one('survey.question', 'Question',
747 'question_id_2': fields.many2one('survey.question', 'Question',
749 'sequence': fields.integer('Label Sequence order'),
750 'value': fields.char("Suggested value", translate=True,
752 'quizz_mark': fields.float('Score for this answer'),
759 class survey_user_input(osv.Model):
760 ''' Metadata for a set of one user's answers to a particular survey '''
761 _name = "survey.user_input"
762 _rec_name = 'date_create'
763 _description = 'Survey User Input'
765 def _quizz_get_score(self, cr, uid, ids, name, args, context=None):
767 for user_input in self.browse(cr, uid, ids, context=context):
768 ret[user_input.id] = sum([uil.quizz_mark for uil in user_input.user_input_line_ids] or [0.0])
772 'survey_id': fields.many2one('survey.survey', 'Survey', required=True,
773 readonly=1, ondelete='restrict'),
774 'date_create': fields.datetime('Creation Date', required=True,
776 'deadline': fields.datetime("Deadline",
777 help="Date by which the person can open the survey and submit answers.\
779 oldname="date_deadline"),
780 'type': fields.selection([('manually', 'Manually'), ('link', 'Link')],
781 'Answer Type', required=1, readonly=1,
782 oldname="response_type"),
783 'state': fields.selection([('new', 'Not started yet'),
784 ('skip', 'Partially completed'),
785 ('done', 'Completed')],
788 'test_entry': fields.boolean('Test entry', readonly=1),
789 'token': fields.char("Identification token", readonly=1, required=1),
791 # Optional Identification data
792 'partner_id': fields.many2one('res.partner', 'Partner', readonly=1),
793 'email': fields.char("E-mail", readonly=1),
796 'last_displayed_page_id': fields.many2one('survey.page',
797 'Last displayed page'),
799 'user_input_line_ids': fields.one2many('survey.user_input_line',
800 'user_input_id', 'Answers'),
802 # URLs used to display the answers
803 'result_url': fields.related('survey_id', 'result_url', string="Public link to the survey results"),
804 'print_url': fields.related('survey_id', 'print_url', string="Public link to the empty survey"),
806 'quizz_score': fields.function(_quizz_get_score, type="float", string="Score for the quiz")
809 'date_create': fields.datetime.now,
812 'token': lambda s, cr, uid, c: uuid.uuid4().__str__(),
817 ('unique_token', 'UNIQUE (token)', 'A token must be unique!')
820 def copy(self, cr, uid, id, default=None, context=None):
821 raise osv.except_osv(_('Warning!'), _('You cannot duplicate this \
824 def do_clean_emptys(self, cr, uid, automatic=False, context=None):
825 ''' Remove empty user inputs that have been created manually (cronjob) '''
826 empty_user_input_ids = self.search(cr, uid, [('type', '=', 'manually'),
827 ('state', '=', 'new'),
828 ('date_create', '<', (datetime.datetime.now() - datetime.timedelta(hours=1)).strftime(DF))],
830 if empty_user_input_ids:
831 self.unlink(cr, uid, empty_user_input_ids, context=context)
833 def purge_tests(self, cr, uid, context=None):
834 ''' Remove the test entries '''
835 old_tests = self.search(cr, uid, [('test_entry', '=', True)], context=context)
836 return self.unlink(cr, uid, old_tests, context=context)
838 def action_survey_resent(self, cr, uid, ids, context=None):
839 ''' Sent again the invitation '''
840 record = self.browse(cr, uid, ids[0], context=context)
841 context = context or {}
843 'survey_resent_token': True,
844 'default_partner_ids': record.partner_id and [record.partner_id.id] or [],
845 'default_multi_email': record.email or "",
846 'default_public': 'email_private',
848 return self.pool.get('survey.survey').action_send_survey(cr, uid,
849 [record.survey_id.id], context=context)
851 def action_view_answers(self, cr, uid, ids, context=None):
852 ''' Open the website page with the survey form '''
853 user_input = self.read(cr, uid, ids, ['print_url', 'token'], context=context)[0]
855 'type': 'ir.actions.act_url',
856 'name': "View Answers",
858 'url': '%s/%s' % (user_input['print_url'], user_input['token'])
861 def action_survey_results(self, cr, uid, ids, context=None):
862 ''' Open the website page with the survey results '''
864 'type': 'ir.actions.act_url',
865 'name': "Survey Results",
867 'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
871 class survey_user_input_line(osv.Model):
872 _name = 'survey.user_input_line'
873 _description = 'Survey User Input Line'
874 _rec_name = 'date_create'
877 'user_input_id': fields.many2one('survey.user_input', 'User Input',
878 ondelete='cascade', required=1),
879 'question_id': fields.many2one('survey.question', 'Question',
880 ondelete='restrict'),
881 'page_id': fields.related('question_id', 'page_id', type='many2one',
882 relation='survey.page', string="Page"),
883 'survey_id': fields.related('user_input_id', 'survey_id',
884 type="many2one", relation="survey.survey",
885 string='Survey', store=True),
886 'date_create': fields.datetime('Create Date', required=1),
887 'skipped': fields.boolean('Skipped'),
888 'answer_type': fields.selection([('text', 'Text'),
889 ('number', 'Number'),
891 ('free_text', 'Free Text'),
892 ('suggestion', 'Suggestion')],
894 'value_text': fields.char("Text answer"),
895 'value_number': fields.float("Numerical answer"),
896 'value_date': fields.datetime("Date answer"),
897 'value_free_text': fields.text("Free Text answer"),
898 'value_suggested': fields.many2one('survey.label', "Suggested answer"),
899 'value_suggested_row': fields.many2one('survey.label', "Row answer"),
900 'quizz_mark': fields.float("Score given for this answer")
905 'date_create': fields.datetime.now()
908 def create(self, cr, uid, vals, context=None):
909 value_suggested = vals.get('value_suggested')
911 mark = self.pool.get('survey.label').browse(cr, uid, int(value_suggested), context=context).quizz_mark
912 vals.update({'quizz_mark': mark})
913 return super(survey_user_input_line, self).create(cr, uid, vals, context=context)
915 def write(self, cr, uid, ids, vals, context=None):
916 value_suggested = vals.get('value_suggested')
918 mark = self.pool.get('survey.label').browse(cr, uid, int(value_suggested), context=context).quizz_mark
919 vals.update({'quizz_mark': mark})
920 return super(survey_user_input_line, self).write(cr, uid, ids, vals, context=context)
922 def save_lines(self, cr, uid, user_input_id, question, post, answer_tag,
924 ''' Save answers to questions, depending on question type
926 If an answer already exists for question and user_input_id, it will be
927 overwritten (in order to maintain data consistency). '''
929 saver = getattr(self, 'save_line_' + question.type)
930 except AttributeError:
931 _logger.error(question.type + ": This type of question has no saving function")
934 saver(cr, uid, user_input_id, question, post, answer_tag, context=context)
936 def save_line_free_text(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
938 'user_input_id': user_input_id,
939 'question_id': question.id,
940 'page_id': question.page_id.id,
941 'survey_id': question.survey_id.id,
944 if answer_tag in post and post[answer_tag].strip() != '':
945 vals.update({'answer_type': 'free_text', 'value_free_text': post[answer_tag]})
947 vals.update({'answer_type': None, 'skipped': True})
948 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
949 ('survey_id', '=', question.survey_id.id),
950 ('question_id', '=', question.id)],
953 self.write(cr, uid, old_uil[0], vals, context=context)
955 self.create(cr, uid, vals, context=context)
958 def save_line_textbox(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
960 'user_input_id': user_input_id,
961 'question_id': question.id,
962 'page_id': question.page_id.id,
963 'survey_id': question.survey_id.id,
966 if answer_tag in post and post[answer_tag].strip() != '':
967 vals.update({'answer_type': 'text', 'value_text': post[answer_tag]})
969 vals.update({'answer_type': None, 'skipped': True})
970 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
971 ('survey_id', '=', question.survey_id.id),
972 ('question_id', '=', question.id)],
975 self.write(cr, uid, old_uil[0], vals, context=context)
977 self.create(cr, uid, vals, context=context)
980 def save_line_numerical_box(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
982 'user_input_id': user_input_id,
983 'question_id': question.id,
984 'page_id': question.page_id.id,
985 'survey_id': question.survey_id.id,
988 if answer_tag in post and post[answer_tag].strip() != '':
989 vals.update({'answer_type': 'number', 'value_number': float(post[answer_tag])})
991 vals.update({'answer_type': None, 'skipped': True})
992 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
993 ('survey_id', '=', question.survey_id.id),
994 ('question_id', '=', question.id)],
997 self.write(cr, uid, old_uil[0], vals, context=context)
999 self.create(cr, uid, vals, context=context)
1002 def save_line_datetime(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1004 'user_input_id': user_input_id,
1005 'question_id': question.id,
1006 'page_id': question.page_id.id,
1007 'survey_id': question.survey_id.id,
1010 if answer_tag in post and post[answer_tag].strip() != '':
1011 vals.update({'answer_type': 'date', 'value_date': post[answer_tag]})
1013 vals.update({'answer_type': None, 'skipped': True})
1014 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
1015 ('survey_id', '=', question.survey_id.id),
1016 ('question_id', '=', question.id)],
1019 self.write(cr, uid, old_uil[0], vals, context=context)
1021 self.create(cr, uid, vals, context=context)
1024 def save_line_simple_choice(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1026 'user_input_id': user_input_id,
1027 'question_id': question.id,
1028 'page_id': question.page_id.id,
1029 'survey_id': question.survey_id.id,
1032 if answer_tag in post and post[answer_tag].strip() != '':
1033 vals.update({'answer_type': 'suggestion', 'value_suggested': post[answer_tag]})
1035 vals.update({'answer_type': None, 'skipped': True})
1036 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
1037 ('survey_id', '=', question.survey_id.id),
1038 ('question_id', '=', question.id)],
1041 self.write(cr, uid, old_uil[0], vals, context=context)
1043 self.create(cr, uid, vals, context=context)
1046 def save_line_multiple_choice(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 vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a]})
1065 self.create(cr, uid, vals, context=context)
1067 vals.update({'answer_type': None, 'skipped': True})
1068 self.create(cr, uid, vals, context=context)
1071 def save_line_matrix(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1073 'user_input_id': user_input_id,
1074 'question_id': question.id,
1075 'page_id': question.page_id.id,
1076 'survey_id': question.survey_id.id,
1079 old_uil = self.search(cr, uid, [('user_input_id', '=', user_input_id),
1080 ('survey_id', '=', question.survey_id.id),
1081 ('question_id', '=', question.id)],
1084 self.unlink(cr, uid, old_uil, context=context)
1086 ca = dict_keys_startswith(post, answer_tag)
1089 if question.matrix_subtype == 'simple':
1090 for row in question.labels_ids_2:
1091 a_tag = "%s_%s" % (answer_tag, row.id)
1094 vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a_tag], 'value_suggested_row': row.id})
1095 self.create(cr, uid, vals, context=context)
1097 elif question.matrix_subtype == 'multiple':
1098 for col in question.labels_ids:
1099 for row in question.labels_ids_2:
1100 a_tag = "%s_%s_%s" % (answer_tag, row.id, col.id)
1103 vals.update({'answer_type': 'suggestion', 'value_suggested': col.id, 'value_suggested_row': row.id})
1104 self.create(cr, uid, vals, context=context)
1106 vals.update({'answer_type': None, 'skipped': True})
1107 self.create(cr, uid, vals, context=context)
1111 def dict_keys_startswith(dictionary, string):
1112 '''Returns a dictionary containing the elements of <dict> whose keys start
1116 This function uses dictionary comprehensions (Python >= 2.7)'''
1117 return {k: dictionary[k] for k in filter(lambda key: key.startswith(string), dictionary.keys())}