8008e990fb1303962161ad2c16b172c1d655db4e
[odoo/odoo.git] / addons / survey / survey.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com>
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
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
27
28 import datetime
29 import logging
30 import re
31 import uuid
32
33 _logger = logging.getLogger(__name__)
34
35
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.
40     '''
41
42     _name = 'survey.survey'
43     _description = 'Survey'
44     _rec_name = 'title'
45     _inherit = ['mail.thread', 'ir.needaction_mixin']
46
47     # Protected methods #
48
49     def _has_questions(self, cr, uid, ids, context=None):
50         """ Ensure that this survey has at least one page with at least one
51         question. """
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]:
55                 return False
56         return True
57
58     ## Function fields ##
59
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')
65         for id in ids:
66             res[id] = sur_res_obj.search(cr, uid,  # SUPERUSER_ID,
67                 [('survey_id', '=', id), ('type', '=', 'link')],
68                 context=context, count=True)
69         return res
70
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
73         completed or not """
74         res = dict((id, 0) for id in ids)
75         sur_res_obj = self.pool.get('survey.user_input')
76         for id in ids:
77             res[id] = sur_res_obj.search(cr, uid,  # SUPERUSER_ID,
78                 ['&', ('survey_id', '=', id), '|', ('state', '=', 'skip'), ('state', '=', 'done')],
79                 context=context, count=True)
80         return res
81
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')
86         for id in ids:
87             res[id] = sur_res_obj.search(cr, uid,  # SUPERUSER_ID,
88                 [('survey_id', '=', id), ('state', '=', 'done')],
89                 context=context, count=True)
90         return res
91
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,
95             'web.base.url')
96         res = {}
97         for survey in self.browse(cr, uid, ids, context=context):
98             res[survey.id] = urljoin(base_url, "survey/start/%s" % slug(survey))
99         return res
100
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,
104             'web.base.url')
105         res = {}
106         for survey in self.browse(cr, uid, ids, context=context):
107             res[survey.id] = urljoin(base_url, "survey/print/%s" % slug(survey))
108         return res
109
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,
113             'web.base.url')
114         res = {}
115         for survey in self.browse(cr, uid, ids, context=context):
116             res[survey.id] = urljoin(base_url, "survey/results/%s" % slug(survey))
117         return res
118
119     # Model fields #
120
121     _columns = {
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')
163     }
164
165     _defaults = {
166         'user_input_limit': 0,
167         'state': 'draft',
168         'visible_to_user': True,
169         'auth_required': True,
170         'users_can_go_back': False,
171         'color': 0
172     }
173
174     _sql_constraints = {
175         ('positive_user_input_limit', 'CHECK (user_input_limit >= 0)', 'Automatic closing limit must be positive')
176     }
177
178     # Public methods #
179
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)
190             else:
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)
200
201     def copy(self, cr, uid, ids, default=None, context=None):
202         vals = {}
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,
208             context=context)
209
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.
213
214         If page_id == 0, it will always return the first page of the survey.
215
216         If all the pages have been displayed and go_back == False, it will
217         return None
218
219         If go_back == True, it will return the *previous* page instead of the
220         next page.
221
222         .. note::
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))
228
229         # First page
230         if page_id == 0:
231             return (pages[0][1], 0, len(pages) == 1)
232
233         current_page_index = pages.index((filter(lambda p: p[1].id == page_id, pages))[0])
234
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)
241         else:
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
246             else:
247                 return (pages[current_page_index + 1][1], current_page_index + 1, False)
248
249     # Web client actions
250
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)
262         return {}
263
264     def action_start_survey(self, cr, uid, ids, context=None):
265         ''' Open the website page with the survey form '''
266         trail = ""
267         if context and 'survey_token' in context:
268             trail = "/" + context['survey_token']
269         return {
270             'type': 'ir.actions.act_url',
271             'name': "Start Survey",
272             'target': 'self',
273             'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + trail
274         }
275
276     def action_send_survey(self, cr, uid, ids, context=None):
277         ''' Open a window to compose an email, pre-filled with the survey
278         message '''
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.'))
281
282         survey_browse = self.pool.get('survey.survey').browse(cr, uid, ids,
283             context=context)[0]
284         if survey_browse.state != "open":
285             raise osv.except_osv(_('Warning!'),
286                 _("You cannot send invitations unless the survey is open."))
287
288         assert len(ids) == 1, 'This option should only be used for a single \
289                                 survey at a time.'
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
294         ctx = dict(context)
295
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}
303                    )
304         return {
305             'type': 'ir.actions.act_window',
306             'view_type': 'form',
307             'view_mode': 'form',
308             'res_model': 'survey.mail.compose.message',
309             'target': 'new',
310             'context': ctx,
311         }
312
313     def action_print_survey(self, cr, uid, ids, context=None):
314         ''' Open the website page with the survey printable view '''
315         trail = ""
316         if context and 'survey_token' in context:
317             trail = "/" + context['survey_token']
318         return {
319             'type': 'ir.actions.act_url',
320             'name': "Print Survey",
321             'target': 'self',
322             'url': self.read(cr, uid, ids, ['print_url'], context=context)[0]['print_url'] + trail
323         }
324
325     def action_result_survey(self, cr, uid, ids, context=None):
326         ''' Open the website page with the survey results view '''
327         return {
328             'type': 'ir.actions.act_url',
329             'name': "Results of the Survey",
330             'target': 'self',
331             'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
332         }
333
334     def action_test_survey(self, cr, uid, ids, context=None):
335         ''' Open the website page with the survey form into test mode'''
336         return {
337             'type': 'ir.actions.act_url',
338             'name': "Results of the Survey",
339             'target': 'self',
340             'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + "/phantom"
341         }
342
343
344 class survey_stage(osv.Model):
345     """Stages for Kanban view of surveys"""
346
347     _name = 'survey.stage'
348     _description = 'Survey Stage'
349     _order = 'sequence'
350
351     _columns = {
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")
356     }
357     _defaults = {
358         'sequence': 1,
359         'survey_open': True
360     }
361     _sql_constraints = [
362         ('positive_sequence', 'CHECK(sequence >= 0)', 'Sequence number MUST be a natural')
363     ]
364
365
366 class survey_page(osv.Model):
367     '''A page for a survey.
368
369     Pages are essentially containers, allowing to group questions by ordered
370     screens.
371
372     .. note::
373         A page should be deleted if the survey it belongs to is deleted. '''
374
375     _name = 'survey.page'
376     _description = 'Survey Page'
377     _rec_name = 'title'
378     _order = 'sequence'
379
380     # Model Fields #
381
382     _columns = {
383         'title': fields.char('Page Title', required=1,
384             translate=True),
385         'survey_id': fields.many2one('survey.survey', 'Survey',
386             ondelete='cascade', required=True),
387         'question_ids': fields.one2many('survey.question', 'page_id',
388             'Questions'),
389         'sequence': fields.integer('Page number'),
390         'description': fields.html('Description',
391             help="An introductory text to your page", translate=True,
392             oldname="note"),
393     }
394     _defaults = {
395         'sequence': 10
396     }
397
398     # Public methods #
399
400     def copy(self, cr, uid, ids, default=None, context=None):
401         vals = {}
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,
406             context=context)
407
408
409 class survey_question(osv.Model):
410     ''' Questions that will be asked in a survey.
411
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'
417     _order = 'sequence'
418
419     # Model fields #
420
421     _columns = {
422         # Question metadata
423         'page_id': fields.many2one('survey.page', 'Survey page',
424             ondelete='cascade'),
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',
428             ondelete='cascade'),
429         'sequence': fields.integer(string='Sequence'),
430
431         # Question
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'),
436
437         # Answer
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
457
458         # Display options
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')],
467                                          'Display mode'),
468
469         # Comments
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'),
477
478         # Validation
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',
498                                             translate=True),
499
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)]),
518     }
519     _defaults = {
520         'page_id': lambda s, cr, uid, c: c.get('page_id'),
521         'sequence': 10,
522         'type': 'free_text',
523         'matrix_subtype': 'simple',
524         'column_nb': '12',
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,
533     }
534     _sql_constraints = [
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!')
542     ]
543
544     def survey_save(self, cr, uid, ids, context=None):
545         if context is None:
546             context = {}
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)})
550         return {
551             'view_type': 'form',
552             'view_mode': 'form',
553             'res_model': 'survey.question.wiz',
554             'type': 'ir.actions.act_window',
555             'target': 'new',
556             'context': context
557         }
558
559     # Validation methods
560
561     def validate_question(self, cr, uid, question, post, answer_tag, context=None):
562         ''' Validate question, depending on question type and parameters '''
563         try:
564             checker = getattr(self, 'validate_' + question.type)
565         except AttributeError:
566             _logger.warning(question.type + ": This type of question has no validation method")
567             return {}
568         else:
569             return checker(cr, uid, question, post, answer_tag, context=context)
570
571     def validate_free_text(self, cr, uid, question, post, answer_tag, context=None):
572         errors = {}
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})
577         return errors
578
579     def validate_textbox(self, cr, uid, question, post, answer_tag, context=None):
580         errors = {}
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})
591
592             # Answer must be an integer in a particular range
593             elif question.validation_type == "is_integer":
594                 try:
595                     intanswer = int(answer)
596                 # Answer is not an integer
597                 except ValueError:
598                     errors.update({answer_tag: question.validation_error_msg})
599                 else:
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":
605                 try:
606                     floatanswer = float(answer)
607                 # Answer is not an integer
608                 except ValueError:
609                     errors.update({answer_tag: question.validation_error_msg})
610                 else:
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})
614
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>
622             #       will be accepted
623             elif question.validation_type == "is_email":
624                 if not re.match(r"[^@]+@[^@]+\.[^@]+", answer):
625                     errors.update({answer_tag: question.validation_error_msg})
626             else:
627                 pass
628         return errors
629
630     def validate_numerical_box(self, cr, uid, question, post, answer_tag, context=None):
631         errors = {}
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
637         if answer:
638             try:
639                 float(answer)
640             except ValueError:
641                 errors.update({answer_tag: question.constr_error_msg})
642         return errors
643
644     def validate_datetime(self, cr, uid, question, post, answer_tag, context=None):
645         errors = {}
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
652         return errors
653
654     def validate_simple_choice(self, cr, uid, question, post, answer_tag, context=None):
655         errors = {}
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})
666         return errors
667
668     def validate_multiple_choice(self, cr, uid, question, post, answer_tag, context=None):
669         errors = {}
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})
681         return errors
682
683     def validate_matrix(self, cr, uid, question, post, answer_tag, context=None):
684         errors = {}
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()]))
694             else:
695                 raise RuntimeError("Invalid matrix subtype")
696             # Validate lines
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})
707             else:
708                 pass  # Everything is okay
709         return errors
710
711
712 class survey_label(osv.Model):
713     ''' A suggested answer for a question '''
714     _name = 'survey.label'
715     _rec_name = 'value'
716     _order = 'sequence'
717     _description = 'Survey Label'
718
719     _columns = {
720         'question_id': fields.many2one('survey.question', 'Question',
721             ondelete='cascade'),
722         'question_id_2': fields.many2one('survey.question', 'Question',
723             ondelete='cascade'),
724         'sequence': fields.integer('Label Sequence order'),
725         'value': fields.char("Suggested value", translate=True,
726             required=True),
727         'quizz_mark': fields.float('Score for this answer'),
728     }
729     defaults = {
730         'sequence': 100,
731     }
732
733
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'
739
740     def _quizz_get_score(self, cr, uid, ids, name, args, context=None):
741         ret = dict()
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])
744         return ret
745
746     _columns = {
747         'survey_id': fields.many2one('survey.survey', 'Survey', required=True,
748                                      readonly=1, ondelete='restrict'),
749         'date_create': fields.datetime('Creation Date', required=True,
750                                        readonly=1),
751         'deadline': fields.datetime("Deadline",
752                                 help="Date by which the person can open the survey and submit answers.\
753                                 Warning: ",
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')],
761                                   'Status',
762                                   readonly=True),
763         'test_entry': fields.boolean('Test entry', readonly=1),
764         'token': fields.char("Identification token", readonly=1, required=1),
765
766         # Optional Identification data
767         'partner_id': fields.many2one('res.partner', 'Partner', readonly=1),
768         'email': fields.char("E-mail", readonly=1),
769
770         # Displaying data
771         'last_displayed_page_id': fields.many2one('survey.page',
772                                               'Last displayed page'),
773         # The answers !
774         'user_input_line_ids': fields.one2many('survey.user_input_line',
775                                                'user_input_id', 'Answers'),
776
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"),
780
781         'quizz_score': fields.function(_quizz_get_score, type="float", string="Score for the quiz")
782     }
783     _defaults = {
784         'date_create': fields.datetime.now,
785         'type': 'manually',
786         'state': 'new',
787         'token': lambda s, cr, uid, c: uuid.uuid4().__str__(),
788         'quizz_score': 0.0,
789     }
790
791     _sql_constraints = [
792         ('unique_token', 'UNIQUE (token)', 'A token must be unique!')
793     ]
794
795     def copy(self, cr, uid, id, default=None, context=None):
796         raise osv.except_osv(_('Warning!'), _('You cannot duplicate this \
797             element!'))
798
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))],
804                                            context=context)
805         if empty_user_input_ids:
806             self.unlink(cr, uid, empty_user_input_ids, context=context)
807
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)
812
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 {}
817         context.update({
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',
822         })
823         return self.pool.get('survey.survey').action_send_survey(cr, uid,
824             [record.survey_id.id], context=context)
825
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]
829         return {
830             'type': 'ir.actions.act_url',
831             'name': "View Answers",
832             'target': 'self',
833             'url': '%s/%s' % (user_input['print_url'], user_input['token'])
834         }
835
836     def action_survey_results(self, cr, uid, ids, context=None):
837         ''' Open the website page with the survey results '''
838         return {
839             'type': 'ir.actions.act_url',
840             'name': "Survey Results",
841             'target': 'self',
842             'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
843         }
844
845
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'
850
851     _columns = {
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'),
865                                          ('date', 'Date'),
866                                          ('free_text', 'Free Text'),
867                                          ('suggestion', 'Suggestion')],
868                                         'Answer Type'),
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")
876     }
877
878     _defaults = {
879         'skipped': False,
880         'date_create': fields.datetime.now()
881     }
882
883     def create(self, cr, uid, vals, context=None):
884         value_suggested = vals.get('value_suggested')
885         if 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)
889
890     def write(self, cr, uid, ids, vals, context=None):
891         value_suggested = vals.get('value_suggested')
892         if 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)
896
897     def save_lines(self, cr, uid, user_input_id, question, post, answer_tag,
898                    context=None):
899         ''' Save answers to questions, depending on question type
900
901         If an answer already exists for question and user_input_id, it will be
902         overwritten (in order to maintain data consistency). '''
903         try:
904             saver = getattr(self, 'save_line_' + question.type)
905         except AttributeError:
906             _logger.error(question.type + ": This type of question has no saving function")
907             return False
908         else:
909             saver(cr, uid, user_input_id, question, post, answer_tag, context=context)
910
911     def save_line_free_text(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
912         vals = {
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,
917             'skipped': False,
918         }
919         if answer_tag in post and post[answer_tag].strip() != '':
920             vals.update({'answer_type': 'free_text', 'value_free_text': post[answer_tag]})
921         else:
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)],
926                               context=context)
927         if old_uil:
928             self.write(cr, uid, old_uil[0], vals, context=context)
929         else:
930             self.create(cr, uid, vals, context=context)
931         return True
932
933     def save_line_textbox(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
934         vals = {
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,
939             'skipped': False
940         }
941         if answer_tag in post and post[answer_tag].strip() != '':
942             vals.update({'answer_type': 'text', 'value_text': post[answer_tag]})
943         else:
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)],
948                               context=context)
949         if old_uil:
950             self.write(cr, uid, old_uil[0], vals, context=context)
951         else:
952             self.create(cr, uid, vals, context=context)
953         return True
954
955     def save_line_numerical_box(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
956         vals = {
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,
961             'skipped': False
962         }
963         if answer_tag in post and post[answer_tag].strip() != '':
964             vals.update({'answer_type': 'number', 'value_number': float(post[answer_tag])})
965         else:
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)],
970                               context=context)
971         if old_uil:
972             self.write(cr, uid, old_uil[0], vals, context=context)
973         else:
974             self.create(cr, uid, vals, context=context)
975         return True
976
977     def save_line_datetime(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
978         vals = {
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,
983             'skipped': False
984         }
985         if answer_tag in post and post[answer_tag].strip() != '':
986             vals.update({'answer_type': 'date', 'value_date': post[answer_tag]})
987         else:
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)],
992                               context=context)
993         if old_uil:
994             self.write(cr, uid, old_uil[0], vals, context=context)
995         else:
996             self.create(cr, uid, vals, context=context)
997         return True
998
999     def save_line_simple_choice(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1000         vals = {
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,
1005             'skipped': False
1006         }
1007         if answer_tag in post and post[answer_tag].strip() != '':
1008             vals.update({'answer_type': 'suggestion', 'value_suggested': post[answer_tag]})
1009         else:
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)],
1014                               context=context)
1015         if old_uil:
1016             self.write(cr, uid, old_uil[0], vals, context=context)
1017         else:
1018             self.create(cr, uid, vals, context=context)
1019         return True
1020
1021     def save_line_multiple_choice(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1022         vals = {
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,
1027             'skipped': False
1028         }
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)],
1032                               context=context)
1033         if old_uil:
1034             self.unlink(cr, uid, old_uil, context=context)
1035
1036         ca = dict_keys_startswith(post, answer_tag)
1037         if len(ca) > 0:
1038             for a in ca:
1039                 vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a]})
1040                 self.create(cr, uid, vals, context=context)
1041         else:
1042             vals.update({'answer_type': None, 'skipped': True})
1043             self.create(cr, uid, vals, context=context)
1044         return True
1045
1046     def save_line_matrix(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1047         vals = {
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,
1052             'skipped': False
1053         }
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)],
1057                               context=context)
1058         if old_uil:
1059             self.unlink(cr, uid, old_uil, context=context)
1060
1061         ca = dict_keys_startswith(post, answer_tag)
1062         no_answers = True
1063
1064         if question.matrix_subtype == 'simple':
1065             for row in question.labels_ids_2:
1066                 a_tag = "%s_%s" % (answer_tag, row.id)
1067                 if a_tag in ca:
1068                     no_answers = False
1069                     vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a_tag], 'value_suggested_row': row.id})
1070                     self.create(cr, uid, vals, context=context)
1071
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)
1076                     if a_tag in ca:
1077                         no_answers = False
1078                         vals.update({'answer_type': 'suggestion', 'value_suggested': col.id, 'value_suggested_row': row.id})
1079                         self.create(cr, uid, vals, context=context)
1080         if no_answers:
1081             vals.update({'answer_type': None, 'skipped': True})
1082             self.create(cr, uid, vals, context=context)
1083         return True
1084
1085
1086 def dict_keys_startswith(dictionary, string):
1087     '''Returns a dictionary containing the elements of <dict> whose keys start
1088     with <string>.
1089
1090     .. note::
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())}