main.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import json
  4. import logging
  5. import werkzeug
  6. from datetime import datetime, timedelta
  7. from dateutil.relativedelta import relativedelta
  8. from odoo import fields, http, SUPERUSER_ID, _
  9. from odoo.exceptions import UserError
  10. from odoo.http import request, content_disposition
  11. from odoo.osv import expression
  12. from odoo.tools import format_datetime, format_date, is_html_empty
  13. from odoo.addons.base.models.ir_qweb import keep_query
  14. _logger = logging.getLogger(__name__)
  15. class Survey(http.Controller):
  16. # ------------------------------------------------------------
  17. # ACCESS
  18. # ------------------------------------------------------------
  19. def _fetch_from_access_token(self, survey_token, answer_token):
  20. """ Check that given token matches an answer from the given survey_id.
  21. Returns a sudo-ed browse record of survey in order to avoid access rights
  22. issues now that access is granted through token. """
  23. survey_sudo = request.env['survey.survey'].with_context(active_test=False).sudo().search([('access_token', '=', survey_token)])
  24. if not answer_token:
  25. answer_sudo = request.env['survey.user_input'].sudo()
  26. else:
  27. answer_sudo = request.env['survey.user_input'].sudo().search([
  28. ('survey_id', '=', survey_sudo.id),
  29. ('access_token', '=', answer_token)
  30. ], limit=1)
  31. return survey_sudo, answer_sudo
  32. def _check_validity(self, survey_token, answer_token, ensure_token=True, check_partner=True):
  33. """ Check survey is open and can be taken. This does not checks for
  34. security rules, only functional / business rules. It returns a string key
  35. allowing further manipulation of validity issues
  36. * survey_wrong: survey does not exist;
  37. * survey_auth: authentication is required;
  38. * survey_closed: survey is closed and does not accept input anymore;
  39. * survey_void: survey is void and should not be taken;
  40. * token_wrong: given token not recognized;
  41. * token_required: no token given although it is necessary to access the
  42. survey;
  43. * answer_deadline: token linked to an expired answer;
  44. :param ensure_token: whether user input existence based on given access token
  45. should be enforced or not, depending on the route requesting a token or
  46. allowing external world calls;
  47. :param check_partner: Whether we must check that the partner associated to the target
  48. answer corresponds to the active user.
  49. """
  50. survey_sudo, answer_sudo = self._fetch_from_access_token(survey_token, answer_token)
  51. if not survey_sudo.exists():
  52. return 'survey_wrong'
  53. if answer_token and not answer_sudo:
  54. return 'token_wrong'
  55. if not answer_sudo and ensure_token:
  56. return 'token_required'
  57. if not answer_sudo and survey_sudo.access_mode == 'token':
  58. return 'token_required'
  59. if survey_sudo.users_login_required and request.env.user._is_public():
  60. return 'survey_auth'
  61. if not survey_sudo.active and (not answer_sudo or not answer_sudo.test_entry):
  62. return 'survey_closed'
  63. if (not survey_sudo.page_ids and survey_sudo.questions_layout == 'page_per_section') or not survey_sudo.question_ids:
  64. return 'survey_void'
  65. if answer_sudo and check_partner:
  66. if request.env.user._is_public() and answer_sudo.partner_id and not answer_token:
  67. # answers from public user should not have any partner_id; this indicates probably a cookie issue
  68. return 'answer_wrong_user'
  69. if not request.env.user._is_public() and answer_sudo.partner_id != request.env.user.partner_id:
  70. # partner mismatch, probably a cookie issue
  71. return 'answer_wrong_user'
  72. if answer_sudo and answer_sudo.deadline and answer_sudo.deadline < datetime.now():
  73. return 'answer_deadline'
  74. return True
  75. def _get_access_data(self, survey_token, answer_token, ensure_token=True, check_partner=True):
  76. """ Get back data related to survey and user input, given the ID and access
  77. token provided by the route.
  78. : param ensure_token: whether user input existence should be enforced or not(see ``_check_validity``)
  79. : param check_partner: whether the partner of the target answer should be checked (see ``_check_validity``)
  80. """
  81. survey_sudo, answer_sudo = request.env['survey.survey'].sudo(), request.env['survey.user_input'].sudo()
  82. has_survey_access, can_answer = False, False
  83. validity_code = self._check_validity(survey_token, answer_token, ensure_token=ensure_token, check_partner=check_partner)
  84. if validity_code != 'survey_wrong':
  85. survey_sudo, answer_sudo = self._fetch_from_access_token(survey_token, answer_token)
  86. try:
  87. survey_user = survey_sudo.with_user(request.env.user)
  88. survey_user.check_access_rights(self, 'read', raise_exception=True)
  89. survey_user.check_access_rule(self, 'read')
  90. except:
  91. pass
  92. else:
  93. has_survey_access = True
  94. can_answer = bool(answer_sudo)
  95. if not can_answer:
  96. can_answer = survey_sudo.access_mode == 'public'
  97. return {
  98. 'survey_sudo': survey_sudo,
  99. 'answer_sudo': answer_sudo,
  100. 'has_survey_access': has_survey_access,
  101. 'can_answer': can_answer,
  102. 'validity_code': validity_code,
  103. }
  104. def _redirect_with_error(self, access_data, error_key):
  105. survey_sudo = access_data['survey_sudo']
  106. answer_sudo = access_data['answer_sudo']
  107. if error_key == 'survey_void' and access_data['can_answer']:
  108. return request.render("survey.survey_void_content", {'survey': survey_sudo, 'answer': answer_sudo})
  109. elif error_key == 'survey_closed' and access_data['can_answer']:
  110. return request.render("survey.survey_closed_expired", {'survey': survey_sudo})
  111. elif error_key == 'survey_auth':
  112. if not answer_sudo: # survey is not even started
  113. redirect_url = '/web/login?redirect=/survey/start/%s' % survey_sudo.access_token
  114. elif answer_sudo.access_token: # survey is started but user is not logged in anymore.
  115. if answer_sudo.partner_id and (answer_sudo.partner_id.user_ids or survey_sudo.users_can_signup):
  116. if answer_sudo.partner_id.user_ids:
  117. answer_sudo.partner_id.signup_cancel()
  118. else:
  119. answer_sudo.partner_id.signup_prepare(expiration=fields.Datetime.now() + relativedelta(days=1))
  120. redirect_url = answer_sudo.partner_id._get_signup_url_for_action(url='/survey/start/%s?answer_token=%s' % (survey_sudo.access_token, answer_sudo.access_token))[answer_sudo.partner_id.id]
  121. else:
  122. redirect_url = '/web/login?redirect=%s' % ('/survey/start/%s?answer_token=%s' % (survey_sudo.access_token, answer_sudo.access_token))
  123. return request.render("survey.survey_auth_required", {'survey': survey_sudo, 'redirect_url': redirect_url})
  124. elif error_key == 'answer_deadline' and answer_sudo.access_token:
  125. return request.render("survey.survey_closed_expired", {'survey': survey_sudo})
  126. return request.redirect("/")
  127. # ------------------------------------------------------------
  128. # TEST / RETRY SURVEY ROUTES
  129. # ------------------------------------------------------------
  130. @http.route('/survey/test/<string:survey_token>', type='http', auth='user', website=True)
  131. def survey_test(self, survey_token, **kwargs):
  132. """ Test mode for surveys: create a test answer, only for managers or officers
  133. testing their surveys """
  134. survey_sudo, dummy = self._fetch_from_access_token(survey_token, False)
  135. try:
  136. answer_sudo = survey_sudo._create_answer(user=request.env.user, test_entry=True)
  137. except:
  138. return request.redirect('/')
  139. return request.redirect('/survey/start/%s?%s' % (survey_sudo.access_token, keep_query('*', answer_token=answer_sudo.access_token)))
  140. @http.route('/survey/retry/<string:survey_token>/<string:answer_token>', type='http', auth='public', website=True)
  141. def survey_retry(self, survey_token, answer_token, **post):
  142. """ This route is called whenever the user has attempts left and hits the 'Retry' button
  143. after failing the survey."""
  144. access_data = self._get_access_data(survey_token, answer_token, ensure_token=True)
  145. if access_data['validity_code'] is not True:
  146. return self._redirect_with_error(access_data, access_data['validity_code'])
  147. survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo']
  148. if not answer_sudo:
  149. # attempts to 'retry' without having tried first
  150. return request.redirect("/")
  151. try:
  152. retry_answer_sudo = survey_sudo._create_answer(
  153. user=request.env.user,
  154. partner=answer_sudo.partner_id,
  155. email=answer_sudo.email,
  156. invite_token=answer_sudo.invite_token,
  157. test_entry=answer_sudo.test_entry,
  158. **self._prepare_retry_additional_values(answer_sudo)
  159. )
  160. except:
  161. return request.redirect("/")
  162. return request.redirect('/survey/start/%s?%s' % (survey_sudo.access_token, keep_query('*', answer_token=retry_answer_sudo.access_token)))
  163. def _prepare_retry_additional_values(self, answer):
  164. return {
  165. 'deadline': answer.deadline,
  166. }
  167. def _prepare_survey_finished_values(self, survey, answer, token=False):
  168. values = {'survey': survey, 'answer': answer}
  169. if token:
  170. values['token'] = token
  171. if survey.scoring_type != 'no_scoring':
  172. values['graph_data'] = json.dumps(answer._prepare_statistics()[answer])
  173. return values
  174. # ------------------------------------------------------------
  175. # TAKING SURVEY ROUTES
  176. # ------------------------------------------------------------
  177. @http.route('/survey/start/<string:survey_token>', type='http', auth='public', website=True)
  178. def survey_start(self, survey_token, answer_token=None, email=False, **post):
  179. """ Start a survey by providing
  180. * a token linked to a survey;
  181. * a token linked to an answer or generate a new token if access is allowed;
  182. """
  183. # Get the current answer token from cookie
  184. answer_from_cookie = False
  185. if not answer_token:
  186. answer_token = request.httprequest.cookies.get('survey_%s' % survey_token)
  187. answer_from_cookie = bool(answer_token)
  188. access_data = self._get_access_data(survey_token, answer_token, ensure_token=False)
  189. if answer_from_cookie and access_data['validity_code'] in ('answer_wrong_user', 'token_wrong'):
  190. # If the cookie had been generated for another user or does not correspond to any existing answer object
  191. # (probably because it has been deleted), ignore it and redo the check.
  192. # The cookie will be replaced by a legit value when resolving the URL, so we don't clean it further here.
  193. access_data = self._get_access_data(survey_token, None, ensure_token=False)
  194. if access_data['validity_code'] is not True:
  195. return self._redirect_with_error(access_data, access_data['validity_code'])
  196. survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo']
  197. if not answer_sudo:
  198. try:
  199. answer_sudo = survey_sudo._create_answer(user=request.env.user, email=email)
  200. except UserError:
  201. answer_sudo = False
  202. if not answer_sudo:
  203. try:
  204. survey_sudo.with_user(request.env.user).check_access_rights('read')
  205. survey_sudo.with_user(request.env.user).check_access_rule('read')
  206. except:
  207. return request.redirect("/")
  208. else:
  209. return request.render("survey.survey_403_page", {'survey': survey_sudo})
  210. return request.redirect('/survey/%s/%s' % (survey_sudo.access_token, answer_sudo.access_token))
  211. def _prepare_survey_data(self, survey_sudo, answer_sudo, **post):
  212. """ This method prepares all the data needed for template rendering, in function of the survey user input state.
  213. :param post:
  214. - previous_page_id : come from the breadcrumb or the back button and force the next questions to load
  215. to be the previous ones. """
  216. data = {
  217. 'is_html_empty': is_html_empty,
  218. 'survey': survey_sudo,
  219. 'answer': answer_sudo,
  220. 'breadcrumb_pages': [{
  221. 'id': page.id,
  222. 'title': page.title,
  223. } for page in survey_sudo.page_ids],
  224. 'format_datetime': lambda dt: format_datetime(request.env, dt, dt_format=False),
  225. 'format_date': lambda date: format_date(request.env, date)
  226. }
  227. if survey_sudo.questions_layout != 'page_per_question':
  228. triggering_answer_by_question, triggered_questions_by_answer, selected_answers = answer_sudo._get_conditional_values()
  229. data.update({
  230. 'triggering_answer_by_question': {
  231. question.id: triggering_answer_by_question[question].id for question in triggering_answer_by_question.keys()
  232. if triggering_answer_by_question[question]
  233. },
  234. 'triggered_questions_by_answer': {
  235. answer.id: triggered_questions_by_answer[answer].ids
  236. for answer in triggered_questions_by_answer.keys()
  237. },
  238. 'selected_answers': selected_answers.ids
  239. })
  240. if not answer_sudo.is_session_answer and survey_sudo.is_time_limited and answer_sudo.start_datetime:
  241. data.update({
  242. 'server_time': fields.Datetime.now(),
  243. 'timer_start': answer_sudo.start_datetime.isoformat(),
  244. 'time_limit_minutes': survey_sudo.time_limit
  245. })
  246. page_or_question_key = 'question' if survey_sudo.questions_layout == 'page_per_question' else 'page'
  247. # Bypass all if page_id is specified (comes from breadcrumb or previous button)
  248. if 'previous_page_id' in post:
  249. previous_page_or_question_id = int(post['previous_page_id'])
  250. new_previous_id = survey_sudo._get_next_page_or_question(answer_sudo, previous_page_or_question_id, go_back=True).id
  251. page_or_question = request.env['survey.question'].sudo().browse(previous_page_or_question_id)
  252. data.update({
  253. page_or_question_key: page_or_question,
  254. 'previous_page_id': new_previous_id,
  255. 'has_answered': answer_sudo.user_input_line_ids.filtered(lambda line: line.question_id.id == new_previous_id),
  256. 'can_go_back': survey_sudo._can_go_back(answer_sudo, page_or_question),
  257. })
  258. return data
  259. if answer_sudo.state == 'in_progress':
  260. if answer_sudo.is_session_answer:
  261. next_page_or_question = survey_sudo.session_question_id
  262. else:
  263. next_page_or_question = survey_sudo._get_next_page_or_question(
  264. answer_sudo,
  265. answer_sudo.last_displayed_page_id.id if answer_sudo.last_displayed_page_id else 0)
  266. if next_page_or_question:
  267. data.update({
  268. 'survey_last': survey_sudo._is_last_page_or_question(answer_sudo, next_page_or_question)
  269. })
  270. if answer_sudo.is_session_answer and next_page_or_question.is_time_limited:
  271. data.update({
  272. 'timer_start': survey_sudo.session_question_start_time.isoformat(),
  273. 'time_limit_minutes': next_page_or_question.time_limit / 60
  274. })
  275. data.update({
  276. page_or_question_key: next_page_or_question,
  277. 'has_answered': answer_sudo.user_input_line_ids.filtered(lambda line: line.question_id == next_page_or_question),
  278. 'can_go_back': survey_sudo._can_go_back(answer_sudo, next_page_or_question),
  279. })
  280. if survey_sudo.questions_layout != 'one_page':
  281. data.update({
  282. 'previous_page_id': survey_sudo._get_next_page_or_question(answer_sudo, next_page_or_question.id, go_back=True).id
  283. })
  284. elif answer_sudo.state == 'done' or answer_sudo.survey_time_limit_reached:
  285. # Display success message
  286. return self._prepare_survey_finished_values(survey_sudo, answer_sudo)
  287. return data
  288. def _prepare_question_html(self, survey_sudo, answer_sudo, **post):
  289. """ Survey page navigation is done in AJAX. This function prepare the 'next page' to display in html
  290. and send back this html to the survey_form widget that will inject it into the page.
  291. Background url must be given to the caller in order to process its refresh as we don't have the next question
  292. object at frontend side."""
  293. survey_data = self._prepare_survey_data(survey_sudo, answer_sudo, **post)
  294. if answer_sudo.state == 'done':
  295. survey_content = request.env['ir.qweb']._render('survey.survey_fill_form_done', survey_data)
  296. else:
  297. survey_content = request.env['ir.qweb']._render('survey.survey_fill_form_in_progress', survey_data)
  298. survey_progress = False
  299. if answer_sudo.state == 'in_progress' and not survey_data.get('question', request.env['survey.question']).is_page:
  300. if survey_sudo.questions_layout == 'page_per_section':
  301. page_ids = survey_sudo.page_ids.ids
  302. survey_progress = request.env['ir.qweb']._render('survey.survey_progression', {
  303. 'survey': survey_sudo,
  304. 'page_ids': page_ids,
  305. 'page_number': page_ids.index(survey_data['page'].id) + (1 if survey_sudo.progression_mode == 'number' else 0)
  306. })
  307. elif survey_sudo.questions_layout == 'page_per_question':
  308. page_ids = (answer_sudo.predefined_question_ids.ids
  309. if not answer_sudo.is_session_answer
  310. else survey_sudo.question_ids.ids)
  311. survey_progress = request.env['ir.qweb']._render('survey.survey_progression', {
  312. 'survey': survey_sudo,
  313. 'page_ids': page_ids,
  314. 'page_number': page_ids.index(survey_data['question'].id)
  315. })
  316. background_image_url = survey_sudo.background_image_url
  317. if 'question' in survey_data:
  318. background_image_url = survey_data['question'].background_image_url
  319. elif 'page' in survey_data:
  320. background_image_url = survey_data['page'].background_image_url
  321. return {
  322. 'survey_content': survey_content,
  323. 'survey_progress': survey_progress,
  324. 'survey_navigation': request.env['ir.qweb']._render('survey.survey_navigation', survey_data),
  325. 'background_image_url': background_image_url
  326. }
  327. @http.route('/survey/<string:survey_token>/<string:answer_token>', type='http', auth='public', website=True)
  328. def survey_display_page(self, survey_token, answer_token, **post):
  329. access_data = self._get_access_data(survey_token, answer_token, ensure_token=True)
  330. if access_data['validity_code'] is not True:
  331. return self._redirect_with_error(access_data, access_data['validity_code'])
  332. answer_sudo = access_data['answer_sudo']
  333. if answer_sudo.state != 'done' and answer_sudo.survey_time_limit_reached:
  334. answer_sudo._mark_done()
  335. return request.render('survey.survey_page_fill',
  336. self._prepare_survey_data(access_data['survey_sudo'], answer_sudo, **post))
  337. # --------------------------------------------------------------------------
  338. # ROUTES to handle question images + survey background transitions + Tool
  339. # --------------------------------------------------------------------------
  340. @http.route('/survey/<string:survey_token>/get_background_image',
  341. type='http', auth="public", website=True, sitemap=False)
  342. def survey_get_background(self, survey_token):
  343. survey_sudo, dummy = self._fetch_from_access_token(survey_token, False)
  344. return request.env['ir.binary']._get_image_stream_from(
  345. survey_sudo, 'background_image'
  346. ).get_response()
  347. @http.route('/survey/<string:survey_token>/<int:section_id>/get_background_image',
  348. type='http', auth="public", website=True, sitemap=False)
  349. def survey_section_get_background(self, survey_token, section_id):
  350. survey_sudo, dummy = self._fetch_from_access_token(survey_token, False)
  351. section = survey_sudo.page_ids.filtered(lambda q: q.id == section_id)
  352. if not section:
  353. # trying to access a question that is not in this survey
  354. raise werkzeug.exceptions.Forbidden()
  355. return request.env['ir.binary']._get_image_stream_from(
  356. section, 'background_image'
  357. ).get_response()
  358. @http.route('/survey/get_question_image/<string:survey_token>/<string:answer_token>/<int:question_id>/<int:suggested_answer_id>', type='http', auth="public", website=True, sitemap=False)
  359. def survey_get_question_image(self, survey_token, answer_token, question_id, suggested_answer_id):
  360. access_data = self._get_access_data(survey_token, answer_token, ensure_token=True)
  361. if access_data['validity_code'] is not True:
  362. return werkzeug.exceptions.Forbidden()
  363. survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo']
  364. suggested_answer = False
  365. if int(question_id) in survey_sudo.question_ids.ids:
  366. suggested_answer = request.env['survey.question.answer'].sudo().search([
  367. ('id', '=', int(suggested_answer_id)),
  368. ('question_id', '=', int(question_id)),
  369. ('question_id.survey_id', '=', survey_sudo.id),
  370. ])
  371. if not suggested_answer:
  372. return werkzeug.exceptions.NotFound()
  373. return request.env['ir.binary']._get_image_stream_from(
  374. suggested_answer, 'value_image'
  375. ).get_response()
  376. # ----------------------------------------------------------------
  377. # JSON ROUTES to begin / continue survey (ajax navigation) + Tools
  378. # ----------------------------------------------------------------
  379. @http.route('/survey/begin/<string:survey_token>/<string:answer_token>', type='json', auth='public', website=True)
  380. def survey_begin(self, survey_token, answer_token, **post):
  381. """ Route used to start the survey user input and display the first survey page. """
  382. access_data = self._get_access_data(survey_token, answer_token, ensure_token=True)
  383. if access_data['validity_code'] is not True:
  384. return {'error': access_data['validity_code']}
  385. survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo']
  386. if answer_sudo.state != "new":
  387. return {'error': _("The survey has already started.")}
  388. answer_sudo._mark_in_progress()
  389. return self._prepare_question_html(survey_sudo, answer_sudo, **post)
  390. @http.route('/survey/next_question/<string:survey_token>/<string:answer_token>', type='json', auth='public', website=True)
  391. def survey_next_question(self, survey_token, answer_token, **post):
  392. """ Method used to display the next survey question in an ongoing session.
  393. Triggered on all attendees screens when the host goes to the next question. """
  394. access_data = self._get_access_data(survey_token, answer_token, ensure_token=True)
  395. if access_data['validity_code'] is not True:
  396. return {'error': access_data['validity_code']}
  397. survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo']
  398. if answer_sudo.state == 'new' and answer_sudo.is_session_answer:
  399. answer_sudo._mark_in_progress()
  400. return self._prepare_question_html(survey_sudo, answer_sudo, **post)
  401. @http.route('/survey/submit/<string:survey_token>/<string:answer_token>', type='json', auth='public', website=True)
  402. def survey_submit(self, survey_token, answer_token, **post):
  403. """ Submit a page from the survey.
  404. This will take into account the validation errors and store the answers to the questions.
  405. If the time limit is reached, errors will be skipped, answers will be ignored and
  406. survey state will be forced to 'done'"""
  407. # Survey Validation
  408. access_data = self._get_access_data(survey_token, answer_token, ensure_token=True)
  409. if access_data['validity_code'] is not True:
  410. return {'error': access_data['validity_code']}
  411. survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo']
  412. if answer_sudo.state == 'done':
  413. return {'error': 'unauthorized'}
  414. questions, page_or_question_id = survey_sudo._get_survey_questions(answer=answer_sudo,
  415. page_id=post.get('page_id'),
  416. question_id=post.get('question_id'))
  417. if not answer_sudo.test_entry and not survey_sudo._has_attempts_left(answer_sudo.partner_id, answer_sudo.email, answer_sudo.invite_token):
  418. # prevent cheating with users creating multiple 'user_input' before their last attempt
  419. return {'error': 'unauthorized'}
  420. if answer_sudo.survey_time_limit_reached or answer_sudo.question_time_limit_reached:
  421. if answer_sudo.question_time_limit_reached:
  422. time_limit = survey_sudo.session_question_start_time + relativedelta(
  423. seconds=survey_sudo.session_question_id.time_limit
  424. )
  425. time_limit += timedelta(seconds=3)
  426. else:
  427. time_limit = answer_sudo.start_datetime + timedelta(minutes=survey_sudo.time_limit)
  428. time_limit += timedelta(seconds=10)
  429. if fields.Datetime.now() > time_limit:
  430. # prevent cheating with users blocking the JS timer and taking all their time to answer
  431. return {'error': 'unauthorized'}
  432. errors = {}
  433. # Prepare answers / comment by question, validate and save answers
  434. for question in questions:
  435. inactive_questions = request.env['survey.question'] if answer_sudo.is_session_answer else answer_sudo._get_inactive_conditional_questions()
  436. if question in inactive_questions: # if question is inactive, skip validation and save
  437. continue
  438. answer, comment = self._extract_comment_from_answers(question, post.get(str(question.id)))
  439. errors.update(question.validate_question(answer, comment))
  440. if not errors.get(question.id):
  441. answer_sudo.save_lines(question, answer, comment)
  442. if errors and not (answer_sudo.survey_time_limit_reached or answer_sudo.question_time_limit_reached):
  443. return {'error': 'validation', 'fields': errors}
  444. if not answer_sudo.is_session_answer:
  445. answer_sudo._clear_inactive_conditional_answers()
  446. if answer_sudo.survey_time_limit_reached or survey_sudo.questions_layout == 'one_page':
  447. answer_sudo._mark_done()
  448. elif 'previous_page_id' in post:
  449. # when going back, save the last displayed to reload the survey where the user left it.
  450. answer_sudo.write({'last_displayed_page_id': post['previous_page_id']})
  451. # Go back to specific page using the breadcrumb. Lines are saved and survey continues
  452. return self._prepare_question_html(survey_sudo, answer_sudo, **post)
  453. else:
  454. if not answer_sudo.is_session_answer:
  455. next_page = survey_sudo._get_next_page_or_question(answer_sudo, page_or_question_id)
  456. if not next_page:
  457. answer_sudo._mark_done()
  458. answer_sudo.write({'last_displayed_page_id': page_or_question_id})
  459. return self._prepare_question_html(survey_sudo, answer_sudo)
  460. def _extract_comment_from_answers(self, question, answers):
  461. """ Answers is a custom structure depending of the question type
  462. that can contain question answers but also comments that need to be
  463. extracted before validating and saving answers.
  464. If multiple answers, they are listed in an array, except for matrix
  465. where answers are structured differently. See input and output for
  466. more info on data structures.
  467. :param question: survey.question
  468. :param answers:
  469. * question_type: free_text, text_box, numerical_box, date, datetime
  470. answers is a string containing the value
  471. * question_type: simple_choice with no comment
  472. answers is a string containing the value ('question_id_1')
  473. * question_type: simple_choice with comment
  474. ['question_id_1', {'comment': str}]
  475. * question_type: multiple choice
  476. ['question_id_1', 'question_id_2'] + [{'comment': str}] if holds a comment
  477. * question_type: matrix
  478. {'matrix_row_id_1': ['question_id_1', 'question_id_2'],
  479. 'matrix_row_id_2': ['question_id_1', 'question_id_2']
  480. } + {'comment': str} if holds a comment
  481. :return: tuple(
  482. same structure without comment,
  483. extracted comment for given question
  484. ) """
  485. comment = None
  486. answers_no_comment = []
  487. if answers:
  488. if question.question_type == 'matrix':
  489. if 'comment' in answers:
  490. comment = answers['comment'].strip()
  491. answers.pop('comment')
  492. answers_no_comment = answers
  493. else:
  494. if not isinstance(answers, list):
  495. answers = [answers]
  496. for answer in answers:
  497. if isinstance(answer, dict) and 'comment' in answer:
  498. comment = answer['comment'].strip()
  499. else:
  500. answers_no_comment.append(answer)
  501. if len(answers_no_comment) == 1:
  502. answers_no_comment = answers_no_comment[0]
  503. return answers_no_comment, comment
  504. # ------------------------------------------------------------
  505. # COMPLETED SURVEY ROUTES
  506. # ------------------------------------------------------------
  507. @http.route('/survey/print/<string:survey_token>', type='http', auth='public', website=True, sitemap=False)
  508. def survey_print(self, survey_token, review=False, answer_token=None, **post):
  509. '''Display an survey in printable view; if <answer_token> is set, it will
  510. grab the answers of the user_input_id that has <answer_token>.'''
  511. access_data = self._get_access_data(survey_token, answer_token, ensure_token=False, check_partner=False)
  512. if access_data['validity_code'] is not True and (
  513. access_data['has_survey_access'] or
  514. access_data['validity_code'] not in ['token_required', 'survey_closed', 'survey_void']):
  515. return self._redirect_with_error(access_data, access_data['validity_code'])
  516. survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo']
  517. return request.render('survey.survey_page_print', {
  518. 'is_html_empty': is_html_empty,
  519. 'review': review,
  520. 'survey': survey_sudo,
  521. 'answer': answer_sudo if survey_sudo.scoring_type != 'scoring_without_answers' else answer_sudo.browse(),
  522. 'questions_to_display': answer_sudo._get_print_questions(),
  523. 'scoring_display_correction': survey_sudo.scoring_type == 'scoring_with_answers' and answer_sudo,
  524. 'format_datetime': lambda dt: format_datetime(request.env, dt, dt_format=False),
  525. 'format_date': lambda date: format_date(request.env, date),
  526. })
  527. @http.route('/survey/<model("survey.survey"):survey>/certification_preview', type="http", auth="user", website=True)
  528. def show_certification_pdf(self, survey, **kwargs):
  529. preview_url = '/survey/%s/get_certification_preview' % survey.id
  530. return request.render('survey.certification_preview', {
  531. 'preview_url': preview_url,
  532. 'page_title': survey.title,
  533. })
  534. @http.route(['/survey/<model("survey.survey"):survey>/get_certification_preview'], type="http", auth="user", methods=['GET'], website=True)
  535. def survey_get_certification_preview(self, survey, **kwargs):
  536. if not request.env.user.has_group('survey.group_survey_user'):
  537. raise werkzeug.exceptions.Forbidden()
  538. fake_user_input = survey._create_answer(user=request.env.user, test_entry=True)
  539. response = self._generate_report(fake_user_input, download=False)
  540. fake_user_input.sudo().unlink()
  541. return response
  542. @http.route(['/survey/<int:survey_id>/get_certification'], type='http', auth='user', methods=['GET'], website=True)
  543. def survey_get_certification(self, survey_id, **kwargs):
  544. """ The certification document can be downloaded as long as the user has succeeded the certification """
  545. survey = request.env['survey.survey'].sudo().search([
  546. ('id', '=', survey_id),
  547. ('certification', '=', True)
  548. ])
  549. if not survey:
  550. # no certification found
  551. return request.redirect("/")
  552. succeeded_attempt = request.env['survey.user_input'].sudo().search([
  553. ('partner_id', '=', request.env.user.partner_id.id),
  554. ('survey_id', '=', survey_id),
  555. ('scoring_success', '=', True)
  556. ], limit=1)
  557. if not succeeded_attempt:
  558. raise UserError(_("The user has not succeeded the certification"))
  559. return self._generate_report(succeeded_attempt, download=True)
  560. # ------------------------------------------------------------
  561. # REPORTING SURVEY ROUTES AND TOOLS
  562. # ------------------------------------------------------------
  563. @http.route('/survey/results/<model("survey.survey"):survey>', type='http', auth='user', website=True)
  564. def survey_report(self, survey, answer_token=None, **post):
  565. """ Display survey Results & Statistics for given survey.
  566. New structure: {
  567. 'survey': current survey browse record,
  568. 'question_and_page_data': see ``SurveyQuestion._prepare_statistics()``,
  569. 'survey_data'= see ``SurveySurvey._prepare_statistics()``
  570. 'search_filters': [],
  571. 'search_finished': either filter on finished inputs only or not,
  572. 'search_passed': either filter on passed inputs only or not,
  573. 'search_failed': either filter on failed inputs only or not,
  574. }
  575. """
  576. user_input_lines, search_filters = self._extract_filters_data(survey, post)
  577. survey_data = survey._prepare_statistics(user_input_lines)
  578. question_and_page_data = survey.question_and_page_ids._prepare_statistics(user_input_lines)
  579. template_values = {
  580. # survey and its statistics
  581. 'survey': survey,
  582. 'question_and_page_data': question_and_page_data,
  583. 'survey_data': survey_data,
  584. # search
  585. 'search_filters': search_filters,
  586. 'search_finished': post.get('finished') == 'true',
  587. 'search_failed': post.get('failed') == 'true',
  588. 'search_passed': post.get('passed') == 'true',
  589. }
  590. if survey.session_show_leaderboard:
  591. template_values['leaderboard'] = survey._prepare_leaderboard_values()
  592. return request.render('survey.survey_page_statistics', template_values)
  593. def _generate_report(self, user_input, download=True):
  594. report = request.env["ir.actions.report"].sudo()._render_qweb_pdf('survey.certification_report', [user_input.id], data={'report_type': 'pdf'})[0]
  595. report_content_disposition = content_disposition('Certification.pdf')
  596. if not download:
  597. content_split = report_content_disposition.split(';')
  598. content_split[0] = 'inline'
  599. report_content_disposition = ';'.join(content_split)
  600. return request.make_response(report, headers=[
  601. ('Content-Type', 'application/pdf'),
  602. ('Content-Length', len(report)),
  603. ('Content-Disposition', report_content_disposition),
  604. ])
  605. def _get_user_input_domain(self, survey, line_filter_domain, **post):
  606. user_input_domain = ['&', ('test_entry', '=', False), ('survey_id', '=', survey.id)]
  607. if line_filter_domain:
  608. matching_line_ids = request.env['survey.user_input.line'].sudo().search(line_filter_domain).ids
  609. user_input_domain = expression.AND([
  610. [('user_input_line_ids', 'in', matching_line_ids)],
  611. user_input_domain
  612. ])
  613. if post.get('finished'):
  614. user_input_domain = expression.AND([[('state', '=', 'done')], user_input_domain])
  615. else:
  616. user_input_domain = expression.AND([[('state', '!=', 'new')], user_input_domain])
  617. if post.get('failed'):
  618. user_input_domain = expression.AND([[('scoring_success', '=', False)], user_input_domain])
  619. elif post.get('passed'):
  620. user_input_domain = expression.AND([[('scoring_success', '=', True)], user_input_domain])
  621. return user_input_domain
  622. def _extract_filters_data(self, survey, post):
  623. search_filters = []
  624. line_filter_domain, line_choices = [], []
  625. for data in post.get('filters', '').split('|'):
  626. try:
  627. row_id, answer_id = (int(item) for item in data.split(','))
  628. except:
  629. pass
  630. else:
  631. if row_id and answer_id:
  632. line_filter_domain = expression.AND([
  633. ['&', ('matrix_row_id', '=', row_id), ('suggested_answer_id', '=', answer_id)],
  634. line_filter_domain
  635. ])
  636. answers = request.env['survey.question.answer'].browse([row_id, answer_id])
  637. elif answer_id:
  638. line_choices.append(answer_id)
  639. answers = request.env['survey.question.answer'].browse([answer_id])
  640. if answer_id:
  641. question_id = answers[0].matrix_question_id or answers[0].question_id
  642. search_filters.append({
  643. 'row_id': row_id,
  644. 'answer_id': answer_id,
  645. 'question': question_id.title,
  646. 'answers': '%s%s' % (answers[0].value, ': %s' % answers[1].value if len(answers) > 1 else '')
  647. })
  648. if line_choices:
  649. line_filter_domain = expression.AND([[('suggested_answer_id', 'in', line_choices)], line_filter_domain])
  650. user_input_domain = self._get_user_input_domain(survey, line_filter_domain, **post)
  651. user_input_lines = request.env['survey.user_input'].sudo().search(user_input_domain).mapped('user_input_line_ids')
  652. return user_input_lines, search_filters