1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
24 from osv import fields
27 from tools.translate import _
29 from time import strftime
30 from datetime import datetime
31 from dateutil.relativedelta import relativedelta
35 class survey_type(osv.osv):
37 _description = 'Survey Type'
39 'name': fields.char("Name", size=128, required=1),
40 'code': fields.char("Code", size=64),
44 class survey(osv.osv):
46 _description = 'Survey'
49 def default_get(self, cr, uid, fields, context={}):
50 data = super(survey, self).default_get(cr, uid, fields, context)
54 'title': fields.char('Survey Title', size=128, required=1),
55 'page_ids': fields.one2many('survey.page', 'survey_id', 'Page'),
56 'date_open': fields.datetime('Survey Open Date', readonly=1),
57 'date_close': fields.datetime('Survey Close Date', readonly=1),
58 'max_response_limit': fields.integer('Maximum Answer Limit',
59 help="Set to one if survey is answerable only once"),
60 'response_user': fields.integer('Maximum Answer per User',
61 help="Set to one if you require only one Answer per user"),
62 'state': fields.selection([('draft', 'Draft'), ('open', 'Open'), ('close', 'Closed'), ('cancel', 'Cancelled')], 'Status', readonly=True),
63 'responsible_id': fields.many2one('res.users', 'Responsible', help="User responsible for survey"),
64 'tot_start_survey': fields.integer("Total Started Survey", readonly=1),
65 'tot_comp_survey': fields.integer("Total Completed Survey", readonly=1),
66 'note': fields.text('Description', size=128),
67 'history': fields.one2many('survey.history', 'survey_id', 'History Lines', readonly=True),
68 'users': fields.many2many('res.users', 'survey_users_rel', 'sid', 'uid', 'Users'),
69 'send_response': fields.boolean('E-mail Notification on Answer'),
70 'type': fields.many2one('survey.type', 'Type'),
71 'invited_user_ids': fields.many2many('res.users', 'survey_invited_user_rel', 'sid', 'uid', 'Invited User'),
74 'state': lambda * a: "draft",
75 'tot_start_survey': lambda * a: 0,
76 'tot_comp_survey': lambda * a: 0,
77 'send_response': lambda * a: 1,
78 'response_user': lambda * a:1,
81 def survey_draft(self, cr, uid, ids, arg):
82 self.write(cr, uid, ids, {'state': 'draft'})
85 def survey_open(self, cr, uid, ids, arg):
86 self.write(cr, uid, ids, {'state': 'open', 'date_open': strftime("%Y-%m-%d %H:%M:%S")})
89 def survey_close(self, cr, uid, ids, arg):
90 self.write(cr, uid, ids, {'state': 'close', 'date_close': strftime("%Y-%m-%d %H:%M:%S") })
93 def survey_cancel(self, cr, uid, ids, arg):
94 self.write(cr, uid, ids, {'state': 'cancel' })
97 def copy(self, cr, uid, id, default=None,context={}):
98 raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
100 def action_print_survey(self, cr, uid, ids, context=None):
102 If response is available then print this response otherwise print survey form(print template of the survey).
103 @param self: The object pointer
104 @param cr: the current row, from the database cursor,
105 @param uid: the current user’s ID for security checks,
106 @param ids: List of Survey IDs
107 @param context: A standard dictionary for contextual values
108 @return : Dictionary value for print survey form.
113 if 'response_id' in context:
114 response_id = context.get('response_id', 0)
115 datas['ids'] = [context.get('survey_id', 0)]
117 response_id = self.pool.get('survey.response').search(cr, uid, [('survey_id','=', ids)], context=context)
119 page_setting = {'orientation': 'vertical', 'without_pagebreak': 0, 'paper_size': 'letter', 'page_number': 1, 'survey_title': 1}
121 if response_id and response_id[0]:
122 context.update({'survey_id': datas['ids']})
123 datas['form'] = page_setting
124 datas['model'] = 'survey.print.answer'
126 'type': 'ir.actions.report.xml',
127 'report_name': 'survey.browse.response',
134 datas['form'] = page_setting
135 datas['model'] = 'survey.print'
137 'type': 'ir.actions.report.xml',
138 'report_name': 'survey.form',
146 class survey_history(osv.osv):
147 _name = 'survey.history'
148 _description = 'Survey History'
151 'survey_id': fields.many2one('survey', 'Survey'),
152 'user_id': fields.many2one('res.users', 'User', readonly=True),
153 'date': fields.datetime('Date started', readonly=1),
156 'date': lambda * a: datetime.datetime.now()
160 class survey_page(osv.osv):
161 _name = 'survey.page'
162 _description = 'Survey Pages'
166 'title': fields.char('Page Title', size=128, required=1),
167 'survey_id': fields.many2one('survey', 'Survey', ondelete='cascade'),
168 'question_ids': fields.one2many('survey.question', 'page_id', 'Question'),
169 'sequence': fields.integer('Page Nr'),
170 'note': fields.text('Description'),
173 'sequence': lambda * a: 1
176 def default_get(self, cr, uid, fields, context={}):
177 data = super(survey_page, self).default_get(cr, uid, fields, context)
178 if context.get('line_order',False):
179 if len(context['line_order'][-1]) > 2 and type(context['line_order'][-1][2]) == type({}) and context['line_order'][-1][2].has_key('sequence'):
180 data['sequence'] = context['line_order'][-1][2]['sequence'] + 1
181 if context.has_key('survey_id'):
182 data['survey_id'] = context['survey_id']
185 def survey_save(self, cr, uid, ids, context):
186 search_obj = self.pool.get('ir.ui.view')
187 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
188 surv_name_wiz = self.pool.get('survey.name.wiz')
189 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',0) })
193 'res_model': 'survey.question.wiz',
194 'type': 'ir.actions.act_window',
196 'search_view_id': search_id[0],
200 def copy(self, cr, uid, id, default=None, context={}):
201 raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
205 class survey_question(osv.osv):
206 _name = 'survey.question'
207 _description = 'Survey Question'
208 _rec_name = 'question'
211 def _calc_response(self, cr, uid, ids, field_name, arg, context):
215 cr.execute("select question_id, count(id) as Total_response from \
216 survey_response_line where state='done' and question_id IN %s\
217 group by question_id" ,(tuple(ids),))
218 ids1 = copy.deepcopy(ids)
219 for rec in cr.fetchall():
221 val[rec[0]] = int(rec[1])
227 'page_id': fields.many2one('survey.page', 'Survey Page', ondelete='cascade', required=1),
228 'question': fields.char('Question', size=128, required=1),
229 'answer_choice_ids': fields.one2many('survey.answer', 'question_id', 'Answer'),
230 'is_require_answer': fields.boolean('Require Answer to Question'),
231 'required_type': fields.selection([('all','All'), ('at least','At Least'), ('at most','At Most'), ('exactly','Exactly'), ('a range','A Range')], 'Respondent must answer'),
232 'req_ans': fields.integer('#Required Answer'),
233 'maximum_req_ans': fields.integer('Maximum Required Answer'),
234 'minimum_req_ans': fields.integer('Minimum Required Answer'),
235 'req_error_msg': fields.text('Error Message'),
236 'allow_comment': fields.boolean('Allow Comment Field'),
237 'sequence': fields.integer('Sequence'),
238 'tot_resp': fields.function(_calc_response, method=True, string="Total Answer"),
239 'survey': fields.related('page_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
240 'descriptive_text': fields.text('Descriptive Text', size=255),
241 'column_heading_ids': fields.one2many('survey.question.column.heading', 'question_id',' Column heading'),
242 'type': fields.selection([('multiple_choice_only_one_ans','Multiple Choice (Only One Answer)'),
243 ('multiple_choice_multiple_ans','Multiple Choice (Multiple Answer)'),
244 ('matrix_of_choices_only_one_ans','Matrix of Choices (Only One Answers Per Row)'),
245 ('matrix_of_choices_only_multi_ans','Matrix of Choices (Multiple Answers Per Row)'),
246 ('matrix_of_drop_down_menus','Matrix of Drop-down Menus'),
247 ('rating_scale','Rating Scale'),('single_textbox','Single Textbox'),
248 ('multiple_textboxes','Multiple Textboxes'),
249 ('multiple_textboxes_diff_type','Multiple Textboxes With Different Type'),
250 ('comment','Comment/Essay Box'),
251 ('numerical_textboxes','Numerical Textboxes'),('date','Date'),
252 ('date_and_time','Date and Time'),('descriptive_text','Descriptive Text'),
254 ], 'Question Type', required=1,),
255 'is_comment_require': fields.boolean('Add Comment Field'),
256 'comment_label': fields.char('Field Label', size = 255),
257 'comment_field_type': fields.selection([('char', 'Single Line Of Text'), ('text', 'Paragraph of Text')], 'Comment Field Type'),
258 'comment_valid_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),
259 ('must_be_specific_length', 'Must Be Specific Length'),
260 ('must_be_whole_number', 'Must Be A Whole Number'),
261 ('must_be_decimal_number', 'Must Be A Decimal Number'),
262 ('must_be_date', 'Must Be A Date'),
263 ('must_be_email_address', 'Must Be An Email Address'),
264 ], 'Text Validation'),
265 'comment_minimum_no': fields.integer('Minimum number'),
266 'comment_maximum_no': fields.integer('Maximum number'),
267 'comment_minimum_float': fields.float('Minimum decimal number'),
268 'comment_maximum_float': fields.float('Maximum decimal number'),
269 'comment_minimum_date': fields.date('Minimum date'),
270 'comment_maximum_date': fields.date('Maximum date'),
271 'comment_valid_err_msg': fields.text('Error message'),
272 'make_comment_field': fields.boolean('Make Comment Field an Answer Choice'),
273 'make_comment_field_err_msg': fields.text('Error message'),
274 'is_validation_require': fields.boolean('Validate Text'),
275 'validation_type': fields.selection([('do_not_validate', '''Don't Validate Comment Text.'''),\
276 ('must_be_specific_length', 'Must Be Specific Length'),\
277 ('must_be_whole_number', 'Must Be A Whole Number'),\
278 ('must_be_decimal_number', 'Must Be A Decimal Number'),\
279 ('must_be_date', 'Must Be A Date'),\
280 ('must_be_email_address', 'Must Be An Email Address')\
281 ], 'Text Validation'),
282 'validation_minimum_no': fields.integer('Minimum number'),
283 'validation_maximum_no': fields.integer('Maximum number'),
284 'validation_minimum_float': fields.float('Minimum decimal number'),
285 'validation_maximum_float': fields.float('Maximum decimal number'),
286 'validation_minimum_date': fields.date('Minimum date'),
287 'validation_maximum_date': fields.date('Maximum date'),
288 'validation_valid_err_msg': fields.text('Error message'),
289 'numeric_required_sum': fields.integer('Sum of all choices'),
290 'numeric_required_sum_err_msg': fields.text('Error message'),
291 'rating_allow_one_column_require': fields.boolean('Allow Only One Answer per Column (Forced Ranking)'),
292 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible?'),
293 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible?'),
294 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible?'),
295 'comment_column': fields.boolean('Add comment column in matrix'),
296 'column_name': fields.char('Column Name',size=256),
297 'no_of_rows': fields.integer('No of Rows'),
300 'sequence': lambda * a: 1,
301 'type': lambda * a: 'multiple_choice_multiple_ans',
302 'req_error_msg': lambda * a: 'This question requires an answer.',
303 'required_type': lambda * a: 'at least',
304 'req_ans': lambda * a: 1,
305 'comment_field_type': lambda * a: 'char',
306 'comment_label': lambda * a: 'Other (please specify)',
307 'comment_valid_type': lambda * a: 'do_not_validate',
308 'comment_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
309 'validation_type': lambda * a: 'do_not_validate',
310 'validation_valid_err_msg': lambda * a : 'The comment you entered is in an invalid format.',
311 'numeric_required_sum_err_msg': lambda * a :'The choices need to add up to [enter sum here].',
312 'make_comment_field_err_msg': lambda * a : 'Please enter a comment.',
313 'in_visible_answer_type': lambda * a: 1
316 def on_change_type(self, cr, uid, ids, type, context=None):
318 val['is_require_answer'] = False
319 val['is_comment_require'] = False
320 val['is_validation_require'] = False
321 val['comment_column'] = False
323 if type in ['multiple_textboxes_diff_type']:
324 val['in_visible_answer_type'] = False
325 return {'value': val}
327 if type in ['rating_scale']:
328 val.update({'in_visible_rating_weight':False, 'in_visible_menu_choice':True})
329 return {'value': val}
331 elif type in ['matrix_of_drop_down_menus']:
332 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':False})
333 return {'value': val}
335 elif type in ['single_textbox']:
336 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True})
337 return {'value': val}
340 val.update({'in_visible_rating_weight':True, 'in_visible_menu_choice':True,\
341 'in_visible_answer_type':True})
342 return {'value': val}
344 def write(self, cr, uid, ids, vals, context=None):
345 questions = self.read(cr,uid, ids, ['answer_choice_ids', 'type', 'required_type',\
346 'req_ans', 'minimum_req_ans', 'maximum_req_ans', 'column_heading_ids'])
347 for question in questions:
348 col_len = len(question['column_heading_ids'])
349 if vals.has_key('column_heading_ids'):
350 for col in vals['column_heading_ids']:
351 if type(col[2]) == type({}):
356 if vals.has_key('type'):
357 que_type = vals['type']
359 que_type = question['type']
361 if que_type in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans',\
362 'matrix_of_drop_down_menus', 'rating_scale']:
364 raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
365 ans_len = len(question['answer_choice_ids'])
367 if vals.has_key('answer_choice_ids'):
368 for ans in vals['answer_choice_ids']:
369 if type(ans[2]) == type({}):
374 if que_type not in ['descriptive_text', 'single_textbox', 'comment','table']:
376 raise osv.except_osv(_('Warning !'),_("You must enter one or more Answer."))
379 if vals.has_key('required_type'):
380 req_type = vals['required_type']
382 req_type = question['required_type']
384 if que_type in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', \
385 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus',\
386 'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
387 if req_type in ['at least', 'at most', 'exactly']:
388 if vals.has_key('req_ans'):
389 if not vals['req_ans'] or vals['req_ans'] > ans_len:
390 raise osv.except_osv(_('Warning !'),_("#Required Answer you entered \
391 is greater than the number of answer. \
392 Please use a number that is smaller than %d.") % (ans_len + 1))
394 if not question['req_ans'] or question['req_ans'] > ans_len:
395 raise osv.except_osv(_('Warning !'),_("#Required Answer you entered is \
396 greater than the number of answer.\
397 Please use a number that is smaller than %d.") % (ans_len + 1))
399 if req_type == 'a range':
402 if vals.has_key('minimum_req_ans'):
403 minimum_ans = vals['minimum_req_ans']
404 if not vals['minimum_req_ans'] or vals['minimum_req_ans'] > ans_len:
405 raise osv.except_osv(_('Warning !'),_("Minimum Required Answer\
406 you entered is greater than the number of answer.\
407 Please use a number that is smaller than %d.") % (ans_len + 1))
409 minimum_ans = question['minimum_req_ans']
410 if not question['minimum_req_ans'] or question['minimum_req_ans'] > ans_len:
411 raise osv.except_osv(_('Warning !'),_("Minimum Required Answer you\
412 entered is greater than the number of answer. \
413 Please use a number that is smaller than %d.") % (ans_len + 1))
414 if vals.has_key('maximum_req_ans'):
415 maximum_ans = vals['maximum_req_ans']
416 if not vals['maximum_req_ans'] or vals['maximum_req_ans'] > ans_len:
417 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you \
418 entered for your maximum is greater than the number of answer.\
419 Please use a number that is smaller than %d.") % (ans_len + 1))
421 maximum_ans = question['maximum_req_ans']
422 if not question['maximum_req_ans'] or question['maximum_req_ans'] > ans_len:
423 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you\
424 entered for your maximum is greater than the number of answer.\
425 Please use a number that is smaller than %d.") % (ans_len + 1))
426 if maximum_ans <= minimum_ans:
427 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater \
428 than Minimum Required Answer"))
430 if question['type'] == 'matrix_of_drop_down_menus' and vals.has_key('column_heading_ids'):
431 for col in vals['column_heading_ids']:
432 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
433 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices\
435 elif not col[2] or not col[2].has_key('menu_choice') or\
436 col[2]['menu_choice'].strip() == '':
437 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu \
438 choices in column heading (white spaces not allowed)"))
440 return super(survey_question, self).write(cr, uid, ids, vals, context=context)
442 def create(self, cr, uid, vals, context):
445 if vals.has_key('answer_choice_ids') and not len(vals['answer_choice_ids']):
446 if vals.has_key('type') and vals['type'] not in ['descriptive_text', 'single_textbox', 'comment','table']:
447 raise osv.except_osv(_('Warning !'),_("You must enter one or more answer."))
449 if vals.has_key('column_heading_ids') and not len(vals['column_heading_ids']):
450 if vals.has_key('type') and vals['type'] in ['matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus', 'rating_scale']:
451 raise osv.except_osv(_('Warning !'),_("You must enter one or more column heading."))
453 if vals['type'] in ['multiple_choice_multiple_ans','matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans', 'matrix_of_drop_down_menus', 'rating_scale','multiple_textboxes','numerical_textboxes','date','date_and_time']:
454 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] in ['at least', 'at most', 'exactly']:
455 if vals.has_key('answer_choice_ids') and vals['req_ans'] > len(vals['answer_choice_ids']) or not vals['req_ans']:
456 raise osv.except_osv(_('Warning !'),_("#Required Answer you entered is greater than the number of answer. Please use a number that is smaller than %d.") % (len(vals['answer_choice_ids'])+1))
458 if vals.has_key('is_require_answer') and vals.has_key('required_type') and vals['required_type'] == 'a range':
459 minimum_ans = vals['minimum_req_ans']
460 maximum_ans = vals['maximum_req_ans']
461 if vals.has_key('answer_choice_ids') or vals['minimum_req_ans'] > len(vals['answer_choice_ids']) or not vals['minimum_req_ans']:
462 raise osv.except_osv(_('Warning !'),_("Minimum Required Answer you entered is greater than the number of answer. Please use a number that is smaller than %d.") % (len(vals['answer_choice_ids'])+1))
463 if vals.has_key('answer_choice_ids') or vals['maximum_req_ans'] > len(vals['answer_choice_ids']) or not vals['maximum_req_ans']:
464 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer you entered for your maximum is greater than the number of answer. Please use a number that is smaller than %d.") % (len(vals['answer_choice_ids'])+1))
465 if maximum_ans <= minimum_ans:
466 raise osv.except_osv(_('Warning !'),_("Maximum Required Answer is greater than Minimum Required Answer"))
468 if vals['type'] == 'matrix_of_drop_down_menus':
469 for col in vals['column_heading_ids']:
470 if not col[2] or not col[2].has_key('menu_choice') or not col[2]['menu_choice']:
471 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading"))
472 elif not col[2] or not col[2].has_key('menu_choice') or col[2]['menu_choice'].strip() == '':
473 raise osv.except_osv(_('Warning !'),_("You must enter one or more menu choices in column heading (white spaces not allowed)"))
475 res = super(survey_question, self).create(cr, uid, vals, context)
478 def survey_save(self, cr, uid, ids, context):
479 search_obj = self.pool.get('ir.ui.view')
480 search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')])
481 surv_name_wiz = self.pool.get('survey.name.wiz')
482 surv_name_wiz.write(cr, uid, [context.get('sur_name_id',False)], {'transfer':True, 'page_no' : context.get('page_number',False) })
486 'res_model': 'survey.question.wiz',
487 'type': 'ir.actions.act_window',
489 'search_view_id': search_id[0],
493 def default_get(self, cr, uid, fields, context={}):
494 data = super(survey_question, self).default_get(cr, uid, fields, context)
495 if context.get('line_order',False):
496 if len(context['line_order'][-1]) > 2 and type(context['line_order'][-1][2]) == type({}) and context['line_order'][-1][2].has_key('sequence'):
497 data['sequence'] = context['line_order'][-1][2]['sequence'] + 1
499 if context.has_key('page_id'):
500 data['page_id']= context.get('page_id', False)
506 class survey_question_column_heading(osv.osv):
507 _name = 'survey.question.column.heading'
508 _description = 'Survey Question Column Heading'
511 def _get_in_visible_rating_weight(self,cr, uid, context={}):
512 if context.get('in_visible_rating_weight', False):
513 return context['in_visible_rating_weight']
515 def _get_in_visible_menu_choice(self,cr, uid, context={}):
516 if context.get('in_visible_menu_choice', False):
517 return context['in_visible_menu_choice']
521 'title': fields.char('Column Heading', size=128, required=1),
522 'menu_choice': fields.text('Menu Choice'),
523 'rating_weight': fields.integer('Weight'),
524 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
525 'in_visible_rating_weight': fields.boolean('Is Rating Scale Invisible ??'),
526 'in_visible_menu_choice': fields.boolean('Is Menu Choice Invisible??')
529 'in_visible_rating_weight': _get_in_visible_rating_weight,
530 'in_visible_menu_choice': _get_in_visible_menu_choice,
532 survey_question_column_heading()
534 class survey_answer(osv.osv):
535 _name = 'survey.answer'
536 _description = 'Survey Answer'
540 def _calc_response_avg(self, cr, uid, ids, field_name, arg, context):
542 for rec in self.browse(cr, uid, ids, context):
543 cr.execute("select count(question_id) ,(select count(answer_id) \
544 from survey_response_answer sra, survey_response_line sa \
545 where sra.response_id = sa.id and sra.answer_id = %d \
546 and sa.state='done') as tot_ans from survey_response_line \
547 where question_id = %d and state = 'done'"\
548 % (rec.id, rec.question_id.id))
551 avg = float(res[1]) * 100 / res[0]
556 'average': round(avg, 2),
560 def _get_in_visible_answer_type(self,cr, uid, context={}):
561 return context.get('in_visible_answer_type', False)
564 'question_id': fields.many2one('survey.question', 'Question', ondelete='cascade'),
565 'answer': fields.char('Answer', size=128, required=1),
566 'sequence': fields.integer('Sequence'),
567 'response': fields.function(_calc_response_avg, method=True, string="#Answer", multi='sums'),
568 'average': fields.function(_calc_response_avg, method=True, string="#Avg", multi='sums'),
569 'type': fields.selection([('char','Character'),('date','Date'),('datetime','Date & Time'),\
570 ('integer','Integer'),('float','Float'),('selection','Selection'),\
571 ('email','Email')], "Type of Answer",required=1),
572 'menu_choice': fields.text('Menu Choices'),
573 'in_visible_answer_type': fields.boolean('Is Answer Type Invisible??')
576 # 'sequence' : lambda * a: 1,
577 'type' : lambda * a: 'char',
578 'in_visible_answer_type':_get_in_visible_answer_type,
581 def default_get(self, cr, uid, fields, context={}):
582 data = super(survey_answer, self).default_get(cr, uid, fields, context)
583 if context.get('line_order', False):
584 if len(context['line_order'][-1]) > 2 and type(context['line_order'][-1][2]) == type({}) and context['line_order'][-1][2].has_key('sequence'):
585 data['sequence'] = context['line_order'][-1][2]['sequence'] + 1
590 class survey_response(osv.osv):
591 _name = "survey.response"
592 _rec_name = 'date_create'
594 'survey_id' : fields.many2one('survey', 'Survey', required=1, ondelete='cascade'),
595 'date_create' : fields.datetime('Create Date', required=1),
596 'user_id' : fields.many2one('res.users', 'User'),
597 'response_type' : fields.selection([('manually', 'Manually'), ('link', 'Link')], \
598 'Answer Type', required=1, readonly=1),
599 'question_ids' : fields.one2many('survey.response.line', 'response_id', 'Answer'),
600 'state' : fields.selection([('done', 'Finished '),('skip', 'Not Finished')], \
601 'Status', readonly=True),
604 'state' : lambda * a: "skip",
605 'response_type' : lambda * a: "manually",
608 def name_get(self, cr, uid, ids, context=None):
611 reads = self.read(cr, uid, ids, ['user_id','date_create'], context)
614 name = (record['user_id'] and record['user_id'][1] or '' )+ ' (' + record['date_create'].split('.')[0] + ')'
615 res.append((record['id'], name))
618 def copy(self, cr, uid, id, default=None,context={}):
619 raise osv.except_osv(_('Warning !'),_('You cannot duplicate the resource!'))
623 class survey_response_line(osv.osv):
624 _name = 'survey.response.line'
625 _description = 'Survey Response Line'
626 _rec_name = 'date_create'
628 'response_id': fields.many2one('survey.response', 'Answer', ondelete='cascade'),
629 'date_create': fields.datetime('Create Date', required=1),
630 'state': fields.selection([('draft', 'Draft'), ('done', 'Answered'),('skip', 'Skiped')],\
631 'Status', readonly=True),
632 'question_id': fields.many2one('survey.question', 'Question'),
633 'page_id': fields.related('question_id', 'page_id', type='many2one', \
634 relation='survey.page', string='Page'),
635 'response_answer_ids': fields.one2many('survey.response.answer', 'response_id', 'Answer'),
636 'response_table_ids': fields.one2many('survey.tbl.column.heading', \
637 'response_table_id', 'Answer'),
638 'comment': fields.text('Notes'),
639 'single_text': fields.char('Text', size=255),
642 'state' : lambda * a: "draft",
645 survey_response_line()
647 class survey_tbl_column_heading(osv.osv):
648 _name = 'survey.tbl.column.heading'
651 'name': fields.integer('Row Number'),
652 'column_id': fields.many2one('survey.question.column.heading', 'Column'),
653 'value': fields.char('Value', size = 255),
654 'response_table_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
657 survey_tbl_column_heading()
659 class survey_response_answer(osv.osv):
660 _name = 'survey.response.answer'
661 _description = 'Survey Answer'
662 _rec_name = 'response_id'
664 'response_id': fields.many2one('survey.response.line', 'Answer', ondelete='cascade'),
665 'answer_id': fields.many2one('survey.answer', 'Answer', required=1, ondelete='cascade'),
666 'column_id': fields.many2one('survey.question.column.heading','Column'),
667 'answer': fields.char('Value', size =255),
668 'value_choice': fields.char('Value Choice', size =255),
669 'comment': fields.text('Notes'),
670 'comment_field': fields.char('Comment', size = 255)
673 survey_response_answer()
675 class res_users(osv.osv):
676 _inherit = "res.users"
679 'survey_id': fields.many2many('survey', 'survey_users_rel', 'uid', 'sid', 'Groups'),
684 class survey_request(osv.osv):
685 _name = "survey.request"
686 _order = 'date_deadline'
687 _rec_name = 'date_deadline'
689 'date_deadline': fields.date("Deadline date"),
690 'user_id': fields.many2one("res.users", "User"),
691 'email': fields.char("E-mail", size=64),
692 'survey_id': fields.many2one("survey", "Survey", required=1, ondelete='cascade'),
693 'response': fields.many2one('survey.response', 'Answer'),
694 'state': fields.selection([('draft','Draft'),('waiting_answer', 'Wating Answer'),('done', 'Done'),('cancel', 'Cancelled')], 'State', readonly=1)
697 'state': lambda * a: 'draft',
698 # 'date_deadline': lambda * a : (datetime.now() + relativedelta(months=+1)).strftime("%Y-%m-%d %H:%M:%S")
700 def survey_req_waiting_answer(self, cr, uid, ids, arg):
701 self.write(cr, uid, ids, { 'state' : 'waiting_answer'})
704 def survey_req_draft(self, cr, uid, ids, arg):
705 self.write(cr, uid, ids, { 'state' : 'draft'})
708 def survey_req_done(self, cr, uid, ids, arg):
709 self.write(cr, uid, ids, { 'state' : 'done'})
712 def survey_req_cancel(self, cr, uid, ids, arg):
713 self.write(cr, uid, ids, { 'state' : 'cancel'})
716 def on_change_user(self, cr, uid, ids, user_id, context=None):
718 user_obj = self.pool.get('res.users')
719 user = user_obj.browse(cr, uid, user_id)
720 return {'value': {'email': user.address_id.email}}
725 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: