[IMP] survey:
[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     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
184
185         if read_group_order == 'stage_id desc':
186             order = '%s desc' % order
187
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)
190
191         # restore order of the search
192         result.sort(lambda x, y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
193
194         fold = {}
195         for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
196             fold[stage.id] = stage.fold or False
197         return result, fold
198
199     _group_by_full = {
200         'stage_id': _read_group_stage_ids
201     }
202
203     # Public methods #
204
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)
215             else:
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)
225
226     def copy(self, cr, uid, ids, default=None, context=None):
227         vals = {}
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,
233             context=context)
234
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.
238
239         If page_id == 0, it will always return the first page of the survey.
240
241         If all the pages have been displayed and go_back == False, it will
242         return None
243
244         If go_back == True, it will return the *previous* page instead of the
245         next page.
246
247         .. note::
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))
253
254         # First page
255         if page_id == 0:
256             return (pages[0][1], 0, len(pages) == 1)
257
258         current_page_index = pages.index((filter(lambda p: p[1].id == page_id, pages))[0])
259
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)
266         else:
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
271             else:
272                 return (pages[current_page_index + 1][1], current_page_index + 1, False)
273
274     # Web client actions
275
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)
287         return {}
288
289     def action_start_survey(self, cr, uid, ids, context=None):
290         ''' Open the website page with the survey form '''
291         trail = ""
292         if context and 'survey_token' in context:
293             trail = "/" + context['survey_token']
294         return {
295             'type': 'ir.actions.act_url',
296             'name': "Start Survey",
297             'target': 'self',
298             'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + trail
299         }
300
301     def action_send_survey(self, cr, uid, ids, context=None):
302         ''' Open a window to compose an email, pre-filled with the survey
303         message '''
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.'))
306
307         survey_browse = self.pool.get('survey.survey').browse(cr, uid, ids,
308             context=context)[0]
309         if survey_browse.state != "open":
310             raise osv.except_osv(_('Warning!'),
311                 _("You cannot send invitations unless the survey is open."))
312
313         assert len(ids) == 1, 'This option should only be used for a single \
314                                 survey at a time.'
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
319         ctx = dict(context)
320
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}
328                    )
329         return {
330             'type': 'ir.actions.act_window',
331             'view_type': 'form',
332             'view_mode': 'form',
333             'res_model': 'survey.mail.compose.message',
334             'target': 'new',
335             'context': ctx,
336         }
337
338     def action_print_survey(self, cr, uid, ids, context=None):
339         ''' Open the website page with the survey printable view '''
340         trail = ""
341         if context and 'survey_token' in context:
342             trail = "/" + context['survey_token']
343         return {
344             'type': 'ir.actions.act_url',
345             'name': "Print Survey",
346             'target': 'self',
347             'url': self.read(cr, uid, ids, ['print_url'], context=context)[0]['print_url'] + trail
348         }
349
350     def action_result_survey(self, cr, uid, ids, context=None):
351         ''' Open the website page with the survey results view '''
352         return {
353             'type': 'ir.actions.act_url',
354             'name': "Results of the Survey",
355             'target': 'self',
356             'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
357         }
358
359     def action_test_survey(self, cr, uid, ids, context=None):
360         ''' Open the website page with the survey form into test mode'''
361         return {
362             'type': 'ir.actions.act_url',
363             'name': "Results of the Survey",
364             'target': 'self',
365             'url': self.read(cr, uid, ids, ['public_url'], context=context)[0]['public_url'] + "/phantom"
366         }
367
368
369 class survey_stage(osv.Model):
370     """Stages for Kanban view of surveys"""
371
372     _name = 'survey.stage'
373     _description = 'Survey Stage'
374     _order = 'sequence'
375
376     _columns = {
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")
381     }
382     _defaults = {
383         'sequence': 1,
384         'survey_open': True
385     }
386     _sql_constraints = [
387         ('positive_sequence', 'CHECK(sequence >= 0)', 'Sequence number MUST be a natural')
388     ]
389
390
391 class survey_page(osv.Model):
392     '''A page for a survey.
393
394     Pages are essentially containers, allowing to group questions by ordered
395     screens.
396
397     .. note::
398         A page should be deleted if the survey it belongs to is deleted. '''
399
400     _name = 'survey.page'
401     _description = 'Survey Page'
402     _rec_name = 'title'
403     _order = 'sequence'
404
405     # Model Fields #
406
407     _columns = {
408         'title': fields.char('Page Title', required=1,
409             translate=True),
410         'survey_id': fields.many2one('survey.survey', 'Survey',
411             ondelete='cascade', required=True),
412         'question_ids': fields.one2many('survey.question', 'page_id',
413             'Questions'),
414         'sequence': fields.integer('Page number'),
415         'description': fields.html('Description',
416             help="An introductory text to your page", translate=True,
417             oldname="note"),
418     }
419     _defaults = {
420         'sequence': 10
421     }
422
423     # Public methods #
424
425     def copy(self, cr, uid, ids, default=None, context=None):
426         vals = {}
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,
431             context=context)
432
433
434 class survey_question(osv.Model):
435     ''' Questions that will be asked in a survey.
436
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'
442     _order = 'sequence'
443
444     # Model fields #
445
446     _columns = {
447         # Question metadata
448         'page_id': fields.many2one('survey.page', 'Survey page',
449             ondelete='cascade'),
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',
453             ondelete='cascade'),
454         'sequence': fields.integer(string='Sequence'),
455
456         # Question
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'),
461
462         # Answer
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
482
483         # Display options
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')],
492                                          'Display mode'),
493
494         # Comments
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'),
502
503         # Validation
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',
523                                             translate=True),
524
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)]),
543     }
544     _defaults = {
545         'page_id': lambda s, cr, uid, c: c.get('page_id'),
546         'sequence': 10,
547         'type': 'free_text',
548         'matrix_subtype': 'simple',
549         'column_nb': '12',
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,
558     }
559     _sql_constraints = [
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!')
567     ]
568
569     def survey_save(self, cr, uid, ids, context=None):
570         if context is None:
571             context = {}
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)})
575         return {
576             'view_type': 'form',
577             'view_mode': 'form',
578             'res_model': 'survey.question.wiz',
579             'type': 'ir.actions.act_window',
580             'target': 'new',
581             'context': context
582         }
583
584     # Validation methods
585
586     def validate_question(self, cr, uid, question, post, answer_tag, context=None):
587         ''' Validate question, depending on question type and parameters '''
588         try:
589             checker = getattr(self, 'validate_' + question.type)
590         except AttributeError:
591             _logger.warning(question.type + ": This type of question has no validation method")
592             return {}
593         else:
594             return checker(cr, uid, question, post, answer_tag, context=context)
595
596     def validate_free_text(self, cr, uid, question, post, answer_tag, context=None):
597         errors = {}
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})
602         return errors
603
604     def validate_textbox(self, cr, uid, question, post, answer_tag, context=None):
605         errors = {}
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})
616
617             # Answer must be an integer in a particular range
618             elif question.validation_type == "is_integer":
619                 try:
620                     intanswer = int(answer)
621                 # Answer is not an integer
622                 except ValueError:
623                     errors.update({answer_tag: question.validation_error_msg})
624                 else:
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":
630                 try:
631                     floatanswer = float(answer)
632                 # Answer is not an integer
633                 except ValueError:
634                     errors.update({answer_tag: question.validation_error_msg})
635                 else:
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})
639
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>
647             #       will be accepted
648             elif question.validation_type == "is_email":
649                 if not re.match(r"[^@]+@[^@]+\.[^@]+", answer):
650                     errors.update({answer_tag: question.validation_error_msg})
651             else:
652                 pass
653         return errors
654
655     def validate_numerical_box(self, cr, uid, question, post, answer_tag, context=None):
656         errors = {}
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
662         if answer:
663             try:
664                 float(answer)
665             except ValueError:
666                 errors.update({answer_tag: question.constr_error_msg})
667         return errors
668
669     def validate_datetime(self, cr, uid, question, post, answer_tag, context=None):
670         errors = {}
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
677         return errors
678
679     def validate_simple_choice(self, cr, uid, question, post, answer_tag, context=None):
680         errors = {}
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})
691         return errors
692
693     def validate_multiple_choice(self, cr, uid, question, post, answer_tag, context=None):
694         errors = {}
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})
706         return errors
707
708     def validate_matrix(self, cr, uid, question, post, answer_tag, context=None):
709         errors = {}
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()]))
719             else:
720                 raise RuntimeError("Invalid matrix subtype")
721             # Validate lines
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})
732             else:
733                 pass  # Everything is okay
734         return errors
735
736
737 class survey_label(osv.Model):
738     ''' A suggested answer for a question '''
739     _name = 'survey.label'
740     _rec_name = 'value'
741     _order = 'sequence'
742     _description = 'Survey Label'
743
744     _columns = {
745         'question_id': fields.many2one('survey.question', 'Question',
746             ondelete='cascade'),
747         'question_id_2': fields.many2one('survey.question', 'Question',
748             ondelete='cascade'),
749         'sequence': fields.integer('Label Sequence order'),
750         'value': fields.char("Suggested value", translate=True,
751             required=True),
752         'quizz_mark': fields.float('Score for this answer'),
753     }
754     defaults = {
755         'sequence': 100,
756     }
757
758
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'
764
765     def _quizz_get_score(self, cr, uid, ids, name, args, context=None):
766         ret = dict()
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])
769         return ret
770
771     _columns = {
772         'survey_id': fields.many2one('survey.survey', 'Survey', required=True,
773                                      readonly=1, ondelete='restrict'),
774         'date_create': fields.datetime('Creation Date', required=True,
775                                        readonly=1),
776         'deadline': fields.datetime("Deadline",
777                                 help="Date by which the person can open the survey and submit answers.\
778                                 Warning: ",
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')],
786                                   'Status',
787                                   readonly=True),
788         'test_entry': fields.boolean('Test entry', readonly=1),
789         'token': fields.char("Identification token", readonly=1, required=1),
790
791         # Optional Identification data
792         'partner_id': fields.many2one('res.partner', 'Partner', readonly=1),
793         'email': fields.char("E-mail", readonly=1),
794
795         # Displaying data
796         'last_displayed_page_id': fields.many2one('survey.page',
797                                               'Last displayed page'),
798         # The answers !
799         'user_input_line_ids': fields.one2many('survey.user_input_line',
800                                                'user_input_id', 'Answers'),
801
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"),
805
806         'quizz_score': fields.function(_quizz_get_score, type="float", string="Score for the quiz")
807     }
808     _defaults = {
809         'date_create': fields.datetime.now,
810         'type': 'manually',
811         'state': 'new',
812         'token': lambda s, cr, uid, c: uuid.uuid4().__str__(),
813         'quizz_score': 0.0,
814     }
815
816     _sql_constraints = [
817         ('unique_token', 'UNIQUE (token)', 'A token must be unique!')
818     ]
819
820     def copy(self, cr, uid, id, default=None, context=None):
821         raise osv.except_osv(_('Warning!'), _('You cannot duplicate this \
822             element!'))
823
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))],
829                                            context=context)
830         if empty_user_input_ids:
831             self.unlink(cr, uid, empty_user_input_ids, context=context)
832
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)
837
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 {}
842         context.update({
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',
847         })
848         return self.pool.get('survey.survey').action_send_survey(cr, uid,
849             [record.survey_id.id], context=context)
850
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]
854         return {
855             'type': 'ir.actions.act_url',
856             'name': "View Answers",
857             'target': 'self',
858             'url': '%s/%s' % (user_input['print_url'], user_input['token'])
859         }
860
861     def action_survey_results(self, cr, uid, ids, context=None):
862         ''' Open the website page with the survey results '''
863         return {
864             'type': 'ir.actions.act_url',
865             'name': "Survey Results",
866             'target': 'self',
867             'url': self.read(cr, uid, ids, ['result_url'], context=context)[0]['result_url']
868         }
869
870
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'
875
876     _columns = {
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'),
890                                          ('date', 'Date'),
891                                          ('free_text', 'Free Text'),
892                                          ('suggestion', 'Suggestion')],
893                                         'Answer Type'),
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")
901     }
902
903     _defaults = {
904         'skipped': False,
905         'date_create': fields.datetime.now()
906     }
907
908     def create(self, cr, uid, vals, context=None):
909         value_suggested = vals.get('value_suggested')
910         if 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)
914
915     def write(self, cr, uid, ids, vals, context=None):
916         value_suggested = vals.get('value_suggested')
917         if 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)
921
922     def save_lines(self, cr, uid, user_input_id, question, post, answer_tag,
923                    context=None):
924         ''' Save answers to questions, depending on question type
925
926         If an answer already exists for question and user_input_id, it will be
927         overwritten (in order to maintain data consistency). '''
928         try:
929             saver = getattr(self, 'save_line_' + question.type)
930         except AttributeError:
931             _logger.error(question.type + ": This type of question has no saving function")
932             return False
933         else:
934             saver(cr, uid, user_input_id, question, post, answer_tag, context=context)
935
936     def save_line_free_text(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
937         vals = {
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,
942             'skipped': False,
943         }
944         if answer_tag in post and post[answer_tag].strip() != '':
945             vals.update({'answer_type': 'free_text', 'value_free_text': post[answer_tag]})
946         else:
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)],
951                               context=context)
952         if old_uil:
953             self.write(cr, uid, old_uil[0], vals, context=context)
954         else:
955             self.create(cr, uid, vals, context=context)
956         return True
957
958     def save_line_textbox(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
959         vals = {
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,
964             'skipped': False
965         }
966         if answer_tag in post and post[answer_tag].strip() != '':
967             vals.update({'answer_type': 'text', 'value_text': post[answer_tag]})
968         else:
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)],
973                               context=context)
974         if old_uil:
975             self.write(cr, uid, old_uil[0], vals, context=context)
976         else:
977             self.create(cr, uid, vals, context=context)
978         return True
979
980     def save_line_numerical_box(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
981         vals = {
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,
986             'skipped': False
987         }
988         if answer_tag in post and post[answer_tag].strip() != '':
989             vals.update({'answer_type': 'number', 'value_number': float(post[answer_tag])})
990         else:
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)],
995                               context=context)
996         if old_uil:
997             self.write(cr, uid, old_uil[0], vals, context=context)
998         else:
999             self.create(cr, uid, vals, context=context)
1000         return True
1001
1002     def save_line_datetime(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1003         vals = {
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,
1008             'skipped': False
1009         }
1010         if answer_tag in post and post[answer_tag].strip() != '':
1011             vals.update({'answer_type': 'date', 'value_date': post[answer_tag]})
1012         else:
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)],
1017                               context=context)
1018         if old_uil:
1019             self.write(cr, uid, old_uil[0], vals, context=context)
1020         else:
1021             self.create(cr, uid, vals, context=context)
1022         return True
1023
1024     def save_line_simple_choice(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1025         vals = {
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,
1030             'skipped': False
1031         }
1032         if answer_tag in post and post[answer_tag].strip() != '':
1033             vals.update({'answer_type': 'suggestion', 'value_suggested': post[answer_tag]})
1034         else:
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)],
1039                               context=context)
1040         if old_uil:
1041             self.write(cr, uid, old_uil[0], vals, context=context)
1042         else:
1043             self.create(cr, uid, vals, context=context)
1044         return True
1045
1046     def save_line_multiple_choice(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         if len(ca) > 0:
1063             for a in ca:
1064                 vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a]})
1065                 self.create(cr, uid, vals, context=context)
1066         else:
1067             vals.update({'answer_type': None, 'skipped': True})
1068             self.create(cr, uid, vals, context=context)
1069         return True
1070
1071     def save_line_matrix(self, cr, uid, user_input_id, question, post, answer_tag, context=None):
1072         vals = {
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,
1077             'skipped': False
1078         }
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)],
1082                               context=context)
1083         if old_uil:
1084             self.unlink(cr, uid, old_uil, context=context)
1085
1086         ca = dict_keys_startswith(post, answer_tag)
1087         no_answers = True
1088
1089         if question.matrix_subtype == 'simple':
1090             for row in question.labels_ids_2:
1091                 a_tag = "%s_%s" % (answer_tag, row.id)
1092                 if a_tag in ca:
1093                     no_answers = False
1094                     vals.update({'answer_type': 'suggestion', 'value_suggested': ca[a_tag], 'value_suggested_row': row.id})
1095                     self.create(cr, uid, vals, context=context)
1096
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)
1101                     if a_tag in ca:
1102                         no_answers = False
1103                         vals.update({'answer_type': 'suggestion', 'value_suggested': col.id, 'value_suggested_row': row.id})
1104                         self.create(cr, uid, vals, context=context)
1105         if no_answers:
1106             vals.update({'answer_type': None, 'skipped': True})
1107             self.create(cr, uid, vals, context=context)
1108         return True
1109
1110
1111 def dict_keys_startswith(dictionary, string):
1112     '''Returns a dictionary containing the elements of <dict> whose keys start
1113     with <string>.
1114
1115     .. note::
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())}