size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
3,010
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class PurchaseOrder(models.Model): _inherit = "purchase.order" sale_order_count = fields.Integer( "Number of Source Sale", compute='_compute_sale_order_count', groups='sales_team.group_sale_salesman') @api.depends('order_line.sale_order_id') def _compute_sale_order_count(self): for purchase in self: purchase.sale_order_count = len(purchase._get_sale_orders()) def action_view_sale_orders(self): self.ensure_one() sale_order_ids = self._get_sale_orders().ids action = { 'res_model': 'sale.order', 'type': 'ir.actions.act_window', } if len(sale_order_ids) == 1: action.update({ 'view_mode': 'form', 'res_id': sale_order_ids[0], }) else: action.update({ 'name': _('Sources Sale Orders %s', self.name), 'domain': [('id', 'in', sale_order_ids)], 'view_mode': 'tree,form', }) return action def button_cancel(self): result = super(PurchaseOrder, self).button_cancel() self.sudo()._activity_cancel_on_sale() return result def _get_sale_orders(self): return self.order_line.sale_order_id def _activity_cancel_on_sale(self): """ If some PO are cancelled, we need to put an activity on their origin SO (only the open ones). Since a PO can have been modified by several SO, when cancelling one PO, many next activities can be schedulded on different SO. """ sale_to_notify_map = {} # map SO -> recordset of PO as {sale.order: set(purchase.order.line)} for order in self: for purchase_line in order.order_line: if purchase_line.sale_line_id: sale_order = purchase_line.sale_line_id.order_id sale_to_notify_map.setdefault(sale_order, self.env['purchase.order.line']) sale_to_notify_map[sale_order] |= purchase_line for sale_order, purchase_order_lines in sale_to_notify_map.items(): sale_order._activity_schedule_with_view('mail.mail_activity_data_warning', user_id=sale_order.user_id.id or self.env.uid, views_or_xmlid='sale_purchase.exception_sale_on_purchase_cancellation', render_context={ 'purchase_orders': purchase_order_lines.mapped('order_id'), 'purchase_order_lines': purchase_order_lines, }) class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' sale_order_id = fields.Many2one(related='sale_line_id.order_id', string="Sale Order", store=True, readonly=True) sale_line_id = fields.Many2one('sale.order.line', string="Origin Sale Item", index=True, copy=False)
40.675676
3,010
1,021
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = 'product.template' service_to_purchase = fields.Boolean("Subcontract Service", help="If ticked, each time you sell this product through a SO, a RfQ is automatically created to buy the product. Tip: don't forget to set a vendor on the product.") _sql_constraints = [ ('service_to_purchase', "CHECK((type != 'service' AND service_to_purchase != true) or (type = 'service'))", 'Product that is not a service can not create RFQ.'), ] @api.onchange('type') def _onchange_type(self): res = super(ProductTemplate, self)._onchange_type() if self.type != 'service': self.service_to_purchase = False return res @api.onchange('expense_policy') def _onchange_expense_policy(self): if self.expense_policy != 'no': self.service_to_purchase = False
39.269231
1,021
1,387
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Tours', 'category': 'Hidden', 'description': """ Odoo Web tours. ======================== """, 'version': '0.1', 'depends': ['web'], 'data': [ 'security/ir.model.access.csv', 'security/ir.rule.csv', 'views/tour_views.xml' ], 'assets': { 'web.assets_qweb': [ 'web_tour/static/src/debug/tour_dialog_component.xml', ], 'web.assets_common': [ 'web_tour/static/src/scss/**/*', 'web_tour/static/src/js/running_tour_action_helper.js', 'web_tour/static/src/js/tip.js', 'web_tour/static/src/js/tour_manager.js', 'web_tour/static/src/js/tour_service.js', 'web_tour/static/src/js/tour_step_utils.js', 'web_tour/static/src/js/tour_utils.js', ], 'web.assets_backend': [ 'web_tour/static/src/debug/debug_manager.js', 'web_tour/static/src/debug/tour_dialog_component.js', 'web_tour/static/src/services/*.js', ], 'web.assets_frontend': [ 'web_tour/static/src/js/public/**/*', ], 'web.qunit_suite_tests': [ 'web_tour/static/tests/**/*', ], }, 'auto_install': True, 'license': 'LGPL-3', }
30.152174
1,387
586
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.http import request class Http(models.AbstractModel): _inherit = 'ir.http' def session_info(self): result = super().session_info() if result['is_admin']: demo_modules_count = self.env['ir.module.module'].sudo().search_count([('demo', '=', True)]) result['web_tours'] = request.env['web_tour.tour'].get_consumed_tours() result['tour_disable'] = demo_modules_count > 0 return result
34.470588
586
1,061
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class Tour(models.Model): _name = "web_tour.tour" _description = "Tours" _log_access = False name = fields.Char(string="Tour name", required=True) user_id = fields.Many2one('res.users', string='Consumed by') @api.model def consume(self, tour_names): """ Sets given tours as consumed, meaning that these tours won't be active anymore for that user """ if not self.env.user.has_group('base.group_user'): # Only internal users can use this method. # TODO master: update ir.model.access records instead of using sudo() return for name in tour_names: self.sudo().create({'name': name, 'user_id': self.env.uid}) @api.model def get_consumed_tours(self): """ Returns the list of consumed tours for the current user """ return [t.name for t in self.search([('user_id', '=', self.env.uid)])]
35.366667
1,061
4,214
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Surveys', 'version': '3.4', 'category': 'Marketing/Surveys', 'description': """ Create beautiful surveys and visualize answers ============================================== It depends on the answers or reviews of some questions by different users. A survey may have multiple pages. Each page may contain multiple questions and each question may have multiple answers. Different users may give different answers of question and according to that survey is done. Partners are also sent mails with personal token for the invitation of the survey. """, 'summary': 'Create surveys and analyze answers', 'website': 'https://www.odoo.com/app/surveys', 'depends': [ 'auth_signup', 'http_routing', 'mail', 'web_tour', 'gamification'], 'data': [ 'views/survey_report_templates.xml', 'views/survey_reports.xml', 'data/mail_template_data.xml', 'data/ir_actions_data.xml', 'security/survey_security.xml', 'security/ir.model.access.csv', 'views/survey_menus.xml', 'views/survey_survey_views.xml', 'views/survey_user_views.xml', 'views/survey_question_views.xml', 'views/survey_templates.xml', 'views/survey_templates_management.xml', 'views/survey_templates_print.xml', 'views/survey_templates_statistics.xml', 'views/survey_templates_user_input_session.xml', 'views/gamification_badge_views.xml', 'wizard/survey_invite_views.xml', 'views/res_partner_views.xml', ], 'demo': [ 'data/gamification_badge_demo.xml', 'data/res_users_demo.xml', 'data/survey_demo_feedback.xml', 'data/survey_demo_feedback_user_input.xml', 'data/survey_demo_feedback_user_input_line.xml', 'data/survey_demo_certification.xml', 'data/survey_demo_certification_user_input.xml', 'data/survey_demo_certification_user_input_line.xml', 'data/survey_demo_quiz.xml', 'data/survey_demo_quiz_user_input.xml', 'data/survey_demo_quiz_user_input_line.xml', 'data/survey_demo_conditional.xml', ], 'installable': True, 'auto_install': False, 'application': True, 'sequence': 220, 'assets': { 'survey.survey_assets': [ 'web/static/lib/Chart/Chart.js', 'web/static/src/legacy/js/fields/field_utils.js', 'survey/static/src/js/survey_quick_access.js', 'survey/static/src/js/survey_timer.js', 'survey/static/src/js/survey_breadcrumb.js', 'survey/static/src/js/survey_form.js', 'survey/static/src/js/survey_print.js', 'survey/static/src/js/survey_result.js', ('include', 'web._assets_helpers'), ('include', 'web._assets_frontend_helpers'), 'web/static/lib/bootstrap/scss/_variables.scss', 'survey/static/src/css/survey_templates_print.css', 'survey/static/src/css/survey_templates_result.css', 'survey/static/src/scss/survey_templates_form.scss', ], 'survey.survey_user_input_session_assets': [ 'survey/static/src/js/libs/chartjs-plugin-datalabels.min.js', 'survey/static/src/js/survey_session_colors.js', 'survey/static/src/js/survey_session_chart.js', 'survey/static/src/js/survey_session_text_answers.js', 'survey/static/src/js/survey_session_leaderboard.js', 'survey/static/src/js/survey_session_manage.js', ], 'web.report_assets_common': [ 'survey/static/src/scss/survey_reports.scss', ], 'web.assets_backend': [ 'survey/static/src/css/survey_templates_result.css', 'survey/static/src/js/fields_section_one2many.js', 'survey/static/src/js/fields_form_page_description.js', 'survey/static/src/scss/survey_survey_views.scss', ], 'web.assets_tests': [ 'survey/static/tests/**/*', ], }, 'license': 'LGPL-3', }
41.313725
4,214
2,522
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestSurveyRandomize(TransactionCase): def test_01_generate_randomized_questions(self): """ Use random generate for a survey and verify that questions within the page are selected accordingly """ Question = self.env['survey.question'].sudo() question_and_pages = self.env['survey.question'] page_1 = Question.create({ 'title': 'Page 1', 'is_page': True, 'sequence': 1, 'random_questions_count': 3 }) question_and_pages |= page_1 question_and_pages = self._add_questions(question_and_pages, page_1, 5) page_2 = Question.create({ 'title': 'Page 2', 'is_page': True, 'sequence': 100, 'random_questions_count': 5 }) question_and_pages |= page_2 question_and_pages = self._add_questions(question_and_pages, page_2, 10) page_3 = Question.create({ 'title': 'Page 2', 'is_page': True, 'sequence': 1000, 'random_questions_count': 4 }) question_and_pages |= page_3 question_and_pages = self._add_questions(question_and_pages, page_3, 2) self.survey1 = self.env['survey.survey'].sudo().create({ 'title': "S0", 'question_and_page_ids': [(6, 0, question_and_pages.ids)], 'questions_selection': 'random' }) generated_questions = self.survey1._prepare_user_input_predefined_questions() self.assertEqual(len(generated_questions.ids), 10, msg="Expected 10 unique questions") self.assertEqual(len(generated_questions.filtered(lambda question: question.page_id == page_1)), 3, msg="Expected 3 questions in page 1") self.assertEqual(len(generated_questions.filtered(lambda question: question.page_id == page_2)), 5, msg="Expected 5 questions in page 2") self.assertEqual(len(generated_questions.filtered(lambda question: question.page_id == page_3)), 2, msg="Expected 2 questions in page 3") def _add_questions(self, question_and_pages, page, count): for i in range(count): question_and_pages |= self.env['survey.question'].sudo().create({ 'title': page.title + ' Q' + str(i + 1), 'sequence': page.sequence + (i + 1) }) return question_and_pages
42.745763
2,522
17,762
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from odoo.addons.survey.tests import common from odoo.exceptions import AccessError, UserError from odoo.tests import tagged from odoo.tests.common import users, HttpCase from odoo.tools import mute_logger @tagged('security') class TestAccess(common.TestSurveyCommon): def setUp(self): super(TestAccess, self).setUp() self.answer_0 = self._add_answer(self.survey, self.customer) self.answer_0_0 = self._add_answer_line(self.question_ft, self.answer_0, 'Test Answer') self.answer_0_1 = self._add_answer_line(self.question_num, self.answer_0, 5) @mute_logger('odoo.addons.base.models.ir_model') @users('user_emp') def test_access_survey_employee(self): # Create: nope with self.assertRaises(AccessError): self.env['survey.survey'].create({'title': 'Test Survey 2'}) with self.assertRaises(AccessError): self.env['survey.question'].create({'title': 'My Page', 'sequence': 0, 'is_page': True, 'survey_id': self.survey.id}) with self.assertRaises(AccessError): self.env['survey.question'].create({'title': 'My Question', 'sequence': 1, 'page_id': self.page_0.id}) # Read: nope with self.assertRaises(AccessError): self.env['survey.survey'].search([('title', 'ilike', 'Test')]) with self.assertRaises(AccessError): self.survey.with_user(self.env.user).read(['title']) # Write: nope with self.assertRaises(AccessError): self.survey.with_user(self.env.user).write({'title': 'New Title'}) with self.assertRaises(AccessError): self.page_0.with_user(self.env.user).write({'title': 'New Title'}) with self.assertRaises(AccessError): self.question_ft.with_user(self.env.user).write({'question': 'New Title'}) # Unlink: nope with self.assertRaises(AccessError): self.survey.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.page_0.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.question_ft.with_user(self.env.user).unlink() @mute_logger('odoo.addons.base.models.ir_model') @users('user_portal') def test_access_survey_portal(self): # Create: nope with self.assertRaises(AccessError): self.env['survey.survey'].create({'title': 'Test Survey 2'}) with self.assertRaises(AccessError): self.env['survey.question'].create({'title': 'My Page', 'sequence': 0, 'is_page': True, 'survey_id': self.survey.id}) with self.assertRaises(AccessError): self.env['survey.question'].create({'title': 'My Question', 'sequence': 1, 'page_id': self.page_0.id}) # Read: nope with self.assertRaises(AccessError): self.env['survey.survey'].search([('title', 'ilike', 'Test')]) with self.assertRaises(AccessError): self.survey.with_user(self.env.user).read(['title']) # Write: nope with self.assertRaises(AccessError): self.survey.with_user(self.env.user).write({'title': 'New Title'}) with self.assertRaises(AccessError): self.page_0.with_user(self.env.user).write({'title': 'New Title'}) with self.assertRaises(AccessError): self.question_ft.with_user(self.env.user).write({'question': 'New Title'}) # Unlink: nope with self.assertRaises(AccessError): self.survey.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.page_0.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.question_ft.with_user(self.env.user).unlink() @mute_logger('odoo.addons.base.models.ir_model') @users('user_public') def test_access_survey_public(self): # Create: nope with self.assertRaises(AccessError): self.env['survey.survey'].create({'title': 'Test Survey 2'}) with self.assertRaises(AccessError): self.env['survey.question'].create({'title': 'My Page', 'sequence': 0, 'is_page': True, 'survey_id': self.survey.id}) with self.assertRaises(AccessError): self.env['survey.question'].create({'title': 'My Question', 'sequence': 1, 'page_id': self.page_0.id}) # Read: nope with self.assertRaises(AccessError): self.env['survey.survey'].search([('title', 'ilike', 'Test')]) with self.assertRaises(AccessError): self.survey.with_user(self.env.user).read(['title']) # Write: nope with self.assertRaises(AccessError): self.survey.with_user(self.env.user).write({'title': 'New Title'}) with self.assertRaises(AccessError): self.page_0.with_user(self.env.user).write({'title': 'New Title'}) with self.assertRaises(AccessError): self.question_ft.with_user(self.env.user).write({'question': 'New Title'}) # Unlink: nope with self.assertRaises(AccessError): self.survey.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.page_0.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.question_ft.with_user(self.env.user).unlink() @users('survey_manager') def test_access_survey_survey_manager(self): # Create: all survey = self.env['survey.survey'].create({'title': 'Test Survey 2'}) self.env['survey.question'].create({'title': 'My Page', 'sequence': 0, 'is_page': True, 'survey_id': survey.id}) self.env['survey.question'].create({'title': 'My Question', 'sequence': 1, 'survey_id': survey.id}) # Read: all surveys = self.env['survey.survey'].search([('title', 'ilike', 'Test')]) self.assertEqual(surveys, self.survey | survey) surveys.read(['title']) # Write: all (self.survey | survey).write({'title': 'New Title'}) # Unlink: all (self.survey | survey).unlink() @mute_logger('odoo.addons.base.models.ir_model') @users('survey_user') def test_access_survey_survey_user(self): # Create: own only survey = self.env['survey.survey'].create({'title': 'Test Survey 2'}) self.env['survey.question'].create({'title': 'My Page', 'sequence': 0, 'is_page': True, 'survey_id': survey.id}) self.env['survey.question'].create({'title': 'My Question', 'sequence': 1, 'survey_id': survey.id}) # Read: all surveys = self.env['survey.survey'].search([('title', 'ilike', 'Test')]) self.assertEqual(surveys, self.survey | survey) surveys.read(['title']) # Write: own only survey.write({'title': 'New Title'}) with self.assertRaises(AccessError): self.survey.with_user(self.env.user).write({'title': 'New Title'}) # Unlink: own only survey.unlink() with self.assertRaises(AccessError): self.survey.with_user(self.env.user).unlink() @mute_logger('odoo.addons.base.models.ir_model') @users('user_emp') def test_access_answers_employee(self): # Create: nope with self.assertRaises(AccessError): self.env['survey.user_input'].create({'survey_id': self.survey.id}) with self.assertRaises(AccessError): self.env['survey.user_input.line'].create({'question_id': self.question_num.id, 'answer_type': 'numerical_box', 'value_numerical_box': 3, 'user_input_id': self.answer_0.id}) # Read: nope with self.assertRaises(AccessError): self.env['survey.user_input'].search([('survey_id', 'in', [self.survey.id])]) with self.assertRaises(AccessError): self.env['survey.user_input.line'].search([('survey_id', 'in', [self.survey.id])]) with self.assertRaises(AccessError): self.env['survey.user_input'].browse(self.answer_0.ids).read(['state']) with self.assertRaises(AccessError): self.env['survey.user_input.line'].browse(self.answer_0_0.ids).read(['value_numerical_box']) # Write: nope with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).write({'state': 'done'}) # Unlink: nope with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.answer_0_0.with_user(self.env.user).unlink() @mute_logger('odoo.addons.base.models.ir_model') @users('user_portal') def test_access_answers_portal(self): # Create: nope with self.assertRaises(AccessError): self.env['survey.user_input'].create({'survey_id': self.survey.id}) with self.assertRaises(AccessError): self.env['survey.user_input.line'].create({'question_id': self.question_num.id, 'answer_type': 'numerical_box', 'value_numerical_box': 3, 'user_input_id': self.answer_0.id}) # Read: nope with self.assertRaises(AccessError): self.env['survey.user_input'].search([('survey_id', 'in', [self.survey.id])]) with self.assertRaises(AccessError): self.env['survey.user_input.line'].search([('survey_id', 'in', [self.survey.id])]) with self.assertRaises(AccessError): self.env['survey.user_input'].browse(self.answer_0.ids).read(['state']) with self.assertRaises(AccessError): self.env['survey.user_input.line'].browse(self.answer_0_0.ids).read(['value_numerical_box']) # Write: nope with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).write({'state': 'done'}) # Unlink: nope with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.answer_0_0.with_user(self.env.user).unlink() @mute_logger('odoo.addons.base.models.ir_model') @users('user_public') def test_access_answers_public(self): # Create: nope with self.assertRaises(AccessError): self.env['survey.user_input'].create({'survey_id': self.survey.id}) with self.assertRaises(AccessError): self.env['survey.user_input.line'].create({'question_id': self.question_num.id, 'answer_type': 'numerical_box', 'value_numerical_box': 3, 'user_input_id': self.answer_0.id}) # Read: nope with self.assertRaises(AccessError): self.env['survey.user_input'].search([('survey_id', 'in', [self.survey.id])]) with self.assertRaises(AccessError): self.env['survey.user_input.line'].search([('survey_id', 'in', [self.survey.id])]) with self.assertRaises(AccessError): self.env['survey.user_input'].browse(self.answer_0.ids).read(['state']) with self.assertRaises(AccessError): self.env['survey.user_input.line'].browse(self.answer_0_0.ids).read(['value_numerical_box']) # Write: nope with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).write({'state': 'done'}) # Unlink: nope with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.answer_0_0.with_user(self.env.user).unlink() @mute_logger('odoo.addons.base.models.ir_model') @users('survey_user') def test_access_answers_survey_user(self): survey_own = self.env['survey.survey'].create({'title': 'Other'}) self.env['survey.question'].create({'title': 'Other', 'sequence': 0, 'is_page': True, 'survey_id': survey_own.id}) question_own = self.env['survey.question'].create({'title': 'Other Question', 'sequence': 1, 'survey_id': survey_own.id}) # Create: own survey only answer_own = self.env['survey.user_input'].create({'survey_id': survey_own.id}) answer_line_own = self.env['survey.user_input.line'].create({'question_id': question_own.id, 'answer_type': 'numerical_box', 'value_numerical_box': 3, 'user_input_id': answer_own.id}) # Read: always answers = self.env['survey.user_input'].search([('survey_id', 'in', [survey_own.id, self.survey.id])]) self.assertEqual(answers, answer_own | self.answer_0) answer_lines = self.env['survey.user_input.line'].search([('survey_id', 'in', [survey_own.id, self.survey.id])]) self.assertEqual(answer_lines, answer_line_own | self.answer_0_0 | self.answer_0_1) self.env['survey.user_input'].browse(answer_own.ids).read(['state']) self.env['survey.user_input'].browse(self.answer_0.ids).read(['state']) self.env['survey.user_input.line'].browse(answer_line_own.ids).read(['value_numerical_box']) self.env['survey.user_input.line'].browse(self.answer_0_0.ids).read(['value_numerical_box']) # Create: own survey only (moved after read because DB not correctly rollbacked with assertRaises) with self.assertRaises(AccessError): answer_other = self.env['survey.user_input'].create({'survey_id': self.survey.id}) with self.assertRaises(AccessError): answer_line_other = self.env['survey.user_input.line'].create({'question_id': self.question_num.id, 'answer_type': 'numerical_box', 'value_numerical_box': 3, 'user_input_id': self.answer_0.id}) # Write: own survey only answer_own.write({'state': 'done'}) with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).write({'state': 'done'}) # Unlink: own survey only answer_own.unlink() with self.assertRaises(AccessError): self.answer_0.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.answer_0_0.with_user(self.env.user).unlink() @users('survey_manager') def test_access_answers_survey_manager(self): admin = self.env.ref('base.user_admin') with self.with_user(admin.login): survey_other = self.env['survey.survey'].create({'title': 'Other'}) self.env['survey.question'].create({'title': 'Other', 'sequence': 0, 'is_page': True, 'survey_id': survey_other.id}) question_other = self.env['survey.question'].create({'title': 'Other Question', 'sequence': 1, 'survey_id': survey_other.id}) self.assertEqual(survey_other.create_uid, admin) self.assertEqual(question_other.create_uid, admin) # Create: always answer_own = self.env['survey.user_input'].create({'survey_id': self.survey.id}) answer_other = self.env['survey.user_input'].create({'survey_id': survey_other.id}) answer_line_own = self.env['survey.user_input.line'].create({'question_id': self.question_num.id, 'answer_type': 'numerical_box', 'value_numerical_box': 3, 'user_input_id': answer_own.id}) answer_line_other = self.env['survey.user_input.line'].create({'question_id': question_other.id, 'answer_type': 'numerical_box', 'value_numerical_box': 3, 'user_input_id': answer_other.id}) # Read: always answers = self.env['survey.user_input'].search([('survey_id', 'in', [survey_other.id, self.survey.id])]) self.assertEqual(answers, answer_own | answer_other | self.answer_0) answer_lines = self.env['survey.user_input.line'].search([('survey_id', 'in', [survey_other.id, self.survey.id])]) self.assertEqual(answer_lines, answer_line_own | answer_line_other | self.answer_0_0 | self.answer_0_1) self.env['survey.user_input'].browse(answer_own.ids).read(['state']) self.env['survey.user_input'].browse(self.answer_0.ids).read(['state']) self.env['survey.user_input.line'].browse(answer_line_own.ids).read(['value_numerical_box']) self.env['survey.user_input.line'].browse(self.answer_0_0.ids).read(['value_numerical_box']) # Write: always answer_own.write({'state': 'done'}) answer_other.write({'partner_id': self.env.user.partner_id.id}) # Unlink: always (answer_own | answer_other | self.answer_0).unlink() @tagged('post_install', '-at_install') class TestSurveySecurityControllers(common.TestSurveyCommon, HttpCase): def test_survey_start_short(self): # avoid name clash with existing data surveys = self.env['survey.survey'].search([ ('session_state', 'in', ['ready', 'in_progress']) ]) self.survey.write({ 'session_state': 'ready', 'session_code': '123456', 'session_start_time': datetime.datetime.now(), 'access_mode': 'public', 'users_login_required': False, }) # right short access token response = self.url_open(f'/s/123456') self.assertEqual(response.status_code, 200) self.assertIn('The session will begin automatically when the host starts', response.text) # `like` operator injection response = self.url_open(f'/s/______') self.assertFalse(self.survey.title in response.text) # right short token, but closed survey self.survey.action_archive() response = self.url_open(f'/s/123456') self.assertFalse(self.survey.title in response.text) # right short token, but wrong `session_state` self.survey.write({'session_state': False, 'active': True}) response = self.url_open(f'/s/123456') self.assertFalse(self.survey.title in response.text)
49.202216
17,762
3,898
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.survey.tests import common class TestSurveyComputePagesQuestions(common.TestSurveyCommon): def test_compute_pages_questions(self): with self.with_user('survey_manager'): survey = self.env['survey.survey'].create({ 'title': 'Test compute survey', }) page_0 = self.env['survey.question'].create({ 'is_page': True, 'sequence': 1, 'title': 'P1', 'survey_id': survey.id }) page0_q0 = self._add_question(page_0, 'Q1', 'text_box', survey_id=survey.id) page0_q1 = self._add_question(page_0, 'Q2', 'text_box', survey_id=survey.id) page0_q2 = self._add_question(page_0, 'Q3', 'text_box', survey_id=survey.id) page0_q3 = self._add_question(page_0, 'Q4', 'text_box', survey_id=survey.id) page0_q4 = self._add_question(page_0, 'Q5', 'text_box', survey_id=survey.id) page_1 = self.env['survey.question'].create({ 'is_page': True, 'sequence': 7, 'title': 'P2', 'survey_id': survey.id, }) page1_q0 = self._add_question(page_1, 'Q6', 'text_box', survey_id=survey.id) page1_q1 = self._add_question(page_1, 'Q7', 'text_box', survey_id=survey.id) page1_q2 = self._add_question(page_1, 'Q8', 'text_box', survey_id=survey.id) page1_q3 = self._add_question(page_1, 'Q9', 'text_box', survey_id=survey.id) self.assertEqual(len(survey.page_ids), 2, "Survey should have 2 pages") self.assertIn(page_0, survey.page_ids, "Page 1 should be contained in survey's page_ids") self.assertIn(page_1, survey.page_ids, "Page 2 should be contained in survey's page_ids") self.assertEqual(len(page_0.question_ids), 5, "Page 1 should have 5 questions") self.assertIn(page0_q0, page_0.question_ids, "Question 1 should be in page 1") self.assertIn(page0_q1, page_0.question_ids, "Question 2 should be in page 1") self.assertIn(page0_q2, page_0.question_ids, "Question 3 should be in page 1") self.assertIn(page0_q3, page_0.question_ids, "Question 4 should be in page 1") self.assertIn(page0_q4, page_0.question_ids, "Question 5 should be in page 1") self.assertEqual(len(page_1.question_ids), 4, "Page 2 should have 4 questions") self.assertIn(page1_q0, page_1.question_ids, "Question 6 should be in page 2") self.assertIn(page1_q1, page_1.question_ids, "Question 7 should be in page 2") self.assertIn(page1_q2, page_1.question_ids, "Question 8 should be in page 2") self.assertIn(page1_q3, page_1.question_ids, "Question 9 should be in page 2") self.assertEqual(page0_q0.page_id, page_0, "Question 1 should belong to page 1") self.assertEqual(page0_q1.page_id, page_0, "Question 2 should belong to page 1") self.assertEqual(page0_q2.page_id, page_0, "Question 3 should belong to page 1") self.assertEqual(page0_q3.page_id, page_0, "Question 4 should belong to page 1") self.assertEqual(page0_q4.page_id, page_0, "Question 5 should belong to page 1") self.assertEqual(page1_q0.page_id, page_1, "Question 6 should belong to page 2") self.assertEqual(page1_q1.page_id, page_1, "Question 7 should belong to page 2") self.assertEqual(page1_q2.page_id, page_1, "Question 8 should belong to page 2") self.assertEqual(page1_q3.page_id, page_1, "Question 9 should belong to page 2") # move 1 question from page 1 to page 2 page0_q2.write({'sequence': 12}) page0_q2._compute_page_id() self.assertEqual(page0_q2.page_id, page_1, "Question 3 should now belong to page 2")
57.323529
3,898
11,115
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests from odoo.addons.base.tests.common import HttpCaseWithUserDemo @odoo.tests.common.tagged('post_install', '-at_install') class TestUiFeedback(HttpCaseWithUserDemo): def setUp(self): super(TestUiFeedback, self).setUp() self.survey_feedback = self.env['survey.survey'].create({ 'title': 'User Feedback Form', 'access_token': 'b137640d-14d4-4748-9ef6-344caaaaaae', 'access_mode': 'public', 'users_can_go_back': True, 'questions_layout': 'page_per_section', 'description': """<p>This survey allows you to give a feedback about your experience with our eCommerce solution. Filling it helps us improving your experience.</p></field>""", 'question_and_page_ids': [ (0, 0, { 'title': 'General information', 'sequence': 1, 'question_type': False, 'is_page': True, 'description': """<p>This section is about general information about you. Answering them helps qualifying your answers.</p>""", }), (0, 0, { 'title': 'Where do you live ?', 'sequence': 2, 'question_type': 'char_box', 'constr_mandatory': False, }), (0, 0, { 'title': 'When is your date of birth ?', 'sequence': 3, 'question_type': 'date', 'description': False, }), (0, 0, { 'title': 'How frequently do you buy products online ?', 'sequence': 4, 'question_type': 'simple_choice', 'comments_allowed': True, 'comment_count_as_answer': True, 'constr_mandatory': True, 'suggested_answer_ids': [ (0, 0, { 'value': 'Once a day', 'sequence': 1, }), (0, 0, { 'value': 'Once a week', 'sequence': 2, }), (0, 0, { 'value': 'Once a month', 'sequence': 3, }), (0, 0, { 'value': 'Once a year', 'sequence': 4, }), (0, 0, { 'value': 'Other (answer in comment)', 'sequence': 5, })], }), (0, 0, { 'title': 'How many times did you order products on our website ?', 'sequence': 5, 'question_type': 'numerical_box', 'constr_mandatory': True, }), (0, 0, { 'title': 'About our ecommerce', 'sequence': 6, 'is_page': True, 'question_type': False, 'description': """<p>This section is about our eCommerce experience itself.</p>""", }), (0, 0, { 'title': 'Which of the following words would you use to describe our products ?', 'sequence': 7, 'question_type': 'multiple_choice', 'constr_mandatory': True, 'comments_allowed': True, 'comment_count_as_answer': False, 'suggested_answer_ids': [ (0, 0, { 'value': 'High quality', 'sequence': 1, }), (0, 0, { 'value': 'Useful', 'sequence': 2, }), (0, 0, { 'value': 'Unique', 'sequence': 3, }), (0, 0, { 'value': 'Good value for money', 'sequence': 4, }), (0, 0, { 'value': 'Overpriced', 'sequence': 5, }), (0, 0, { 'value': 'Impractical', 'sequence': 6, }), (0, 0, { 'value': 'Ineffective', 'sequence': 7, }), (0, 0, { 'value': 'Poor quality', 'sequence': 8, }), (0, 0, { 'value': 'Other', 'sequence': 9, })], }), (0, 0, { 'title': 'What do your think about our new eCommerce ?', 'sequence': 8, 'question_type': 'matrix', 'matrix_subtype': 'multiple', 'constr_mandatory': True, 'suggested_answer_ids': [(0, 0, { 'value': 'Totally disagree', 'sequence': 1 }), (0, 0, { 'value': 'Disagree', 'sequence': 2, }), (0, 0, { 'value': 'Agree', 'sequence': 3, }), (0, 0, { 'value': 'Totally agree', 'sequence': 4, })], 'matrix_row_ids': [(0, 0, { 'value': 'The new layout and design is fresh and up-to-date', 'sequence': 1, }), (0, 0, { 'value': 'It is easy to find the product that I want', 'sequence': 2, }), (0, 0, { 'value': 'The tool to compare the products is useful to make a choice', 'sequence': 3, }), (0, 0, { 'value': 'The checkout process is clear and secure', 'sequence': 4, }), (0, 0, { 'value': 'I have added products to my wishlist', 'sequence': 5, })], }), (0, 0, { 'title': 'Do you have any other comments, questions, or concerns ?', 'sequence': 9, 'question_type': 'text_box', 'constr_mandatory': False, }) ], }) def test_01_admin_survey_tour(self): access_token = self.survey_feedback.access_token self.start_tour("/survey/start/%s" % access_token, 'test_survey', login="admin") def test_02_demo_survey_tour(self): access_token = self.survey_feedback.access_token self.start_tour("/survey/start/%s" % access_token, 'test_survey', login="demo") def test_03_public_survey_tour(self): access_token = self.survey_feedback.access_token self.start_tour("/survey/start/%s" % access_token, 'test_survey') def test_04_public_survey_with_triggers(self): """ Check that chained conditional questions are correctly hidden from survey when a previously selected triggering answer is unselected. E.g., if a specific answer for "Question 1" is selected, which triggers asking "Question 2", and a specific answer for "Question 2" is selected and triggers asking "Question 3", changing the selected answer for "Question 1" should: * hide questions 2 and 3 * enable submitting the survey without answering questions 2 and 3, even if "constr_mandatory=True", as they are not visible. """ survey_with_triggers = self.env['survey.survey'].create({ 'title': 'Survey With Triggers', 'access_token': '3cfadce3-3f7e-41da-920d-10fa0eb19527', 'access_mode': 'public', 'users_can_go_back': True, 'questions_layout': 'one_page', 'description': "<p>Test survey with conditional questions</p>", 'question_and_page_ids': [ (0, 0, { 'title': 'Q1', 'sequence': 1, 'question_type': 'simple_choice', 'suggested_answer_ids': [ (0, 0, { 'value': 'Answer 1', 'sequence': 1, }), (0, 0, { 'value': 'Answer 2', 'sequence': 2, }), ], 'constr_mandatory': True, }), (0, 0, { 'title': 'Q2', 'sequence': 2, 'question_type': 'simple_choice', 'suggested_answer_ids': [ (0, 0, { 'value': 'Answer 1', 'sequence': 1, }), (0, 0, { 'value': 'Answer 2', 'sequence': 2, }) ], 'is_conditional': True, 'constr_mandatory': True, }), (0, 0, { 'title': 'Q3', 'sequence': 3, 'question_type': 'simple_choice', 'suggested_answer_ids': [ (0, 0, { 'value': 'Answer 1', 'sequence': 1, }), (0, 0, { 'value': 'Answer 2', 'sequence': 2, }) ], 'is_conditional': True, 'constr_mandatory': True, }), ] }) q1 = survey_with_triggers.question_ids.filtered(lambda q: q.title == 'Q1') q1_a1 = q1.suggested_answer_ids.filtered(lambda a: a.value == 'Answer 1') q2 = survey_with_triggers.question_ids.filtered(lambda q: q.title == 'Q2') q2_a1 = q2.suggested_answer_ids.filtered(lambda a: a.value == 'Answer 1') q3 = survey_with_triggers.question_ids.filtered(lambda q: q.title == 'Q3') q2.triggering_question_id = q1 q2.triggering_answer_id = q1_a1 q3.triggering_question_id = q2 q3.triggering_answer_id = q2_a1 access_token = survey_with_triggers.access_token self.start_tour("/survey/start/%s" % access_token, 'test_survey_chained_conditional_questions') def test_06_survey_prefill(self): access_token = self.survey_feedback.access_token self.start_tour("/survey/start/%s" % access_token, 'test_survey_prefill')
44.46
11,115
12,567
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests from odoo.addons.base.tests.common import HttpCaseWithUserDemo @odoo.tests.common.tagged('post_install', '-at_install') class TestUiCertification(HttpCaseWithUserDemo): def setUp(self): super(TestUiCertification, self).setUp() self.survey_certification = self.env['survey.survey'].create({ 'title': 'MyCompany Vendor Certification', 'access_token': '4ead4bc8-b8f2-4760-a682-1fde8daaaaac', 'access_mode': 'public', 'users_can_go_back': True, 'users_login_required': True, 'scoring_type': 'scoring_with_answers', 'certification': True, 'certification_mail_template_id': self.env.ref('survey.mail_template_certification').id, 'is_time_limited': 'limited', 'time_limit': 10.0, 'is_attempts_limited': True, 'attempts_limit': 2, 'description': """&lt;p&gt;Test your vendor skills!.&lt;/p&gt;""", 'question_and_page_ids': [ (0, 0, { 'title': 'Products', 'sequence': 1, 'is_page': True, 'question_type': False, 'description': '&lt;p&gt;Test your knowledge of your products!&lt;/p&gt;', }), (0, 0, { 'title': 'Do we sell Acoustic Bloc Screens?', 'sequence': 2, 'question_type': 'simple_choice', 'constr_mandatory': True, 'suggested_answer_ids': [ (0, 0, { 'value': 'No', 'sequence': 1, }), (0, 0, { 'value': 'Yes', 'sequence': 2, 'is_correct': True, 'answer_score': 2, }) ], }), (0, 0, { 'title': 'Select all the existing products', 'sequence': 3, 'question_type': 'multiple_choice', 'column_nb': '4', 'suggested_answer_ids': [ (0, 0, { 'value': 'Chair floor protection', 'sequence': 1, 'is_correct': True, 'answer_score': 1, }), (0, 0, { 'value': 'Fanta', 'sequence': 2, 'answer_score': -1, }), (0, 0, { 'value': 'Conference chair', 'sequence': 3, 'is_correct': True, 'answer_score': 1, }), (0, 0, { 'value': 'Drawer', 'sequence': 4, 'is_correct': True, 'answer_score': 1, }), (0, 0, { 'value': 'Customizable Lamp', 'sequence': 5, 'answer_score': -1, }) ] }), (0, 0, { 'title': 'Select all the available customizations for our Customizable Desk', 'sequence': 4, 'question_type': 'multiple_choice', 'column_nb': '4', 'suggested_answer_ids': [ (0, 0, { 'value': 'Color', 'sequence': 1, 'is_correct': True, 'answer_score': 1, }), (0, 0, { 'value': 'Height', 'sequence': 2, 'answer_score': -1, }), (0, 0, { 'value': 'Width', 'sequence': 3, 'is_correct': True, 'answer_score': 1, }), (0, 0, { 'value': 'Legs', 'sequence': 4, 'is_correct': True, 'answer_score': 1, }), (0, 0, { 'value': 'Number of drawers', 'sequence': 5, 'answer_score': -1, }) ] }), (0, 0, { 'title': 'How many versions of the Corner Desk do we have?', 'sequence': 5, 'question_type': 'simple_choice', 'constr_mandatory': True, 'suggested_answer_ids': [ (0, 0, { 'value': 1, 'sequence': 1, }), (0, 0, { 'value': 2, 'sequence': 2, 'is_correct': True, 'answer_score': 2, }), (0, 0, { 'value': 3, 'sequence': 3, }), (0, 0, { 'value': 4, 'sequence': 4, }) ] }), (0, 0, { 'title': 'Do you think we have missing products in our catalog? (not rated)', 'sequence': 6, 'question_type': 'text_box', }), (0, 0, { 'title': 'Prices', 'sequence': 7, 'is_page': True, 'question_type': False, 'description': """&lt;p&gt;Test your knowledge of our prices.&lt;/p&gt;""", }), (0, 0, { 'title': 'How much do we sell our Cable Management Box?', 'sequence': 8, 'question_type': 'simple_choice', 'constr_mandatory': True, 'suggested_answer_ids': [ (0, 0, { 'value': '$20', 'sequence': 1, }), (0, 0, { 'value': '$50', 'sequence': 2, }), (0, 0, { 'value': '$80', 'sequence': 3, }), (0, 0, { 'value': '$100', 'sequence': 4, 'is_correct': True, 'answer_score': 2, }), (0, 0, { 'value': '$200', 'sequence': 5, }), (0, 0, { 'value': '$300', 'sequence': 6, }) ] }), (0, 0, { 'title': 'Select all the products that sell for $100 or more', 'sequence': 9, 'question_type': 'multiple_choice', 'column_nb': '2', 'suggested_answer_ids': [ (0, 0, { 'value': 'Corner Desk Right Sit', 'sequence': 1, 'answer_score': 1, 'is_correct': True, }), (0, 0, { 'value': 'Desk Combination', 'sequence': 2, 'answer_score': 1, 'is_correct': True, }), (0, 0, { 'value': 'Cabinet with Doors', 'sequence': 3, 'answer_score': -1, }), (0, 0, { 'value': 'Large Desk', 'sequence': 4, 'answer_score': 1, 'is_correct': True, }), (0, 0, { 'value': 'Letter Tray', 'sequence': 5, 'answer_score': -1, }), (0, 0, { 'value': 'Office Chair Black', 'sequence': 6, 'answer_score': -1, }), ] }), (0, 0, { 'title': 'What do you think about our prices (not rated)?', 'sequence': 10, 'question_type': 'simple_choice', 'constr_mandatory': True, 'suggested_answer_ids': [ (0, 0, { 'value': 'Very underpriced', 'sequence': 1, }), (0, 0, { 'value': 'Underpriced', 'sequence': 2, }), (0, 0, { 'value': 'Correctly priced', 'sequence': 3, }), (0, 0, { 'value': 'A little bit overpriced', 'sequence': 4, }), (0, 0, { 'value': 'A lot overpriced', 'sequence': 5, }) ] }), (0, 0, { 'title': 'Policies', 'sequence': 11, 'is_page': True, 'question_type': False, 'description': """&lt;p&gt;Test your knowledge of our policies.&lt;/p&gt;""", }), (0, 0, { 'title': 'How many days is our money-back guarantee?', 'sequence': 12, 'question_type': 'numerical_box', 'constr_mandatory': True, 'is_scored_question': True, 'answer_numerical_box': 30, 'answer_score': 1, }), (0, 0, { 'title': 'If a customer purchases a product on 6 January 2020, what is the latest day we expect to ship it?', 'sequence': 13, 'question_type': 'date', 'is_scored_question': True, 'answer_date': '2020-01-08', 'answer_score': 1, }), (0, 0, { 'title': 'If a customer purchases a 1 year warranty on 6 January 2020, when do we expect the warranty to expire?', 'sequence': 14, 'question_type': 'datetime', 'is_scored_question': True, 'answer_datetime': '2021-01-07 00:00:01', 'answer_score': 1, }), (0, 0, { 'title': 'What day to you think is best for us to start having an annual sale (not rated)?', 'sequence': 15, 'question_type': 'date', }), (0, 0, { 'title': 'What day and time do you think most customers are most likely to call customer service (not rated)?', 'sequence': 16, 'question_type': 'datetime', }), (0, 0, { 'title': 'How many chairs do you think we should aim to sell in a year (not rated)?', 'sequence': 17, 'question_type': 'numerical_box', }) ] }) def test_04_certification_success_tour(self): access_token = self.survey_certification.access_token self.start_tour("/survey/start/%s" % access_token, 'test_certification_success', login="demo") def test_05_certification_failure_tour(self): access_token = self.survey_certification.access_token self.start_tour("/survey/start/%s" % access_token, 'test_certification_failure', login="demo")
44.72242
12,567
5,558
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.survey.tests import common from odoo.tests import tagged from odoo.tests.common import HttpCase @tagged('-at_install', 'post_install', 'functional') class TestSurveyFlowWithConditions(common.TestSurveyCommon, HttpCase): def test_conditional_flow_with_scoring(self): with self.with_user('survey_user'): survey = self.env['survey.survey'].create({ 'title': 'Survey', 'access_mode': 'public', 'questions_layout': 'page_per_section', 'scoring_type': 'scoring_with_answers', 'scoring_success_min': 85.0, }) page_0 = self.env['survey.question'].with_user(self.survey_manager).create({ 'title': 'First page', 'survey_id': survey.id, 'sequence': 1, 'is_page': True, }) q01 = self._add_question( page_0, 'Question 1', 'simple_choice', sequence=1, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=survey.id, labels=[ {'value': 'Answer 1'}, {'value': 'Answer 2'}, {'value': 'Answer 3'}, {'value': 'Answer 4', 'is_correct': True, 'answer_score': 1.0} ]) q02 = self._add_question( page_0, 'Question 2', 'simple_choice', sequence=2, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=survey.id, is_conditional=True, triggering_question_id=q01.id, triggering_answer_id=q01.suggested_answer_ids.filtered(lambda q: q.is_correct).id, labels=[ {'value': 'Answer 1'}, {'value': 'Answer 2', 'is_correct': True, 'answer_score': 1.0}, {'value': 'Answer 3'}, {'value': 'Answer 4'} ]) q03 = self._add_question( page_0, 'Question 3', 'simple_choice', sequence=1, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=survey.id, labels=[ {'value': 'Answer 1'}, {'value': 'Answer 2'}, {'value': 'Answer 3'}, {'value': 'Answer 4', 'is_correct': True, 'answer_score': 1.0} ]) self._add_question( # q04 page_0, 'Question 4', 'simple_choice', sequence=2, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=survey.id, is_conditional=True, triggering_question_id=q03.id, triggering_answer_id=q03.suggested_answer_ids.filtered(lambda q: q.is_correct).id, labels=[ {'value': 'Answer 1'}, {'value': 'Answer 2', 'is_correct': True, 'answer_score': 1.0}, {'value': 'Answer 3'}, {'value': 'Answer 4'} ]) q05 = self._add_question( page_0, 'Question 5', 'simple_choice', sequence=1, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=survey.id, labels=[ {'value': 'Answer 1'}, {'value': 'Answer 2'}, {'value': 'Answer 3'}, {'value': 'Answer 4', 'is_correct': True, 'answer_score': 1.0} ]) q06 = self._add_question( page_0, 'Question 6', 'simple_choice', sequence=2, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=survey.id, is_conditional=True, triggering_question_id=q05.id, triggering_answer_id=q05.suggested_answer_ids.filtered(lambda q: q.is_correct).id, labels=[ {'value': 'Answer 1'}, {'value': 'Answer 2', 'is_correct': True, 'answer_score': 1.0}, {'value': 'Answer 3'}, {'value': 'Answer 4'} ]) # User opens start page self._access_start(survey) # -> this should have generated a new user_input with a token user_inputs = self.env['survey.user_input'].search([('survey_id', '=', survey.id)]) self.assertEqual(len(user_inputs), 1) answer_token = user_inputs.access_token # User begins survey with first page response = self._access_page(survey, answer_token) self.assertResponse(response, 200) csrf_token = self._find_csrf_token(response.text) r = self._access_begin(survey, answer_token) self.assertResponse(r, 200) answers = { q01: q01.suggested_answer_ids[3], # Right q02: q02.suggested_answer_ids[1], # Right q03: q03.suggested_answer_ids[0], # Wrong q05: q05.suggested_answer_ids[3], # Right q06: q06.suggested_answer_ids[2], # Wrong } self._answer_page(page_0, answers, answer_token, csrf_token) user_inputs.invalidate_cache() self.assertEqual(round(user_inputs.scoring_percentage), 60, "Three right answers out of five (the fourth one is still hidden)") self.assertFalse(user_inputs.scoring_success)
44.464
5,558
11,602
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _ from odoo.addons.survey.tests import common from odoo.tests.common import users class TestSurveyInternals(common.TestSurveyCommon): @users('survey_manager') def test_answer_validation_mandatory(self): """ For each type of question check that mandatory questions correctly check for complete answers """ for question in self._create_one_question_per_type(): self.assertDictEqual( question.validate_question(''), {question.id: 'TestError'} ) @users('survey_manager') def test_answer_validation_date(self): question = self._add_question( self.page_0, 'Q0', 'date', validation_required=True, validation_min_date='2015-03-20', validation_max_date='2015-03-25', validation_error_msg='ValidationError') self.assertEqual( question.validate_question('Is Alfred an answer ?'), {question.id: _('This is not a date')} ) self.assertEqual( question.validate_question('2015-03-19'), {question.id: 'ValidationError'} ) self.assertEqual( question.validate_question('2015-03-26'), {question.id: 'ValidationError'} ) self.assertEqual( question.validate_question('2015-03-25'), {} ) @users('survey_manager') def test_answer_validation_numerical(self): question = self._add_question( self.page_0, 'Q0', 'numerical_box', validation_required=True, validation_min_float_value=2.2, validation_max_float_value=3.3, validation_error_msg='ValidationError') self.assertEqual( question.validate_question('Is Alfred an answer ?'), {question.id: _('This is not a number')} ) self.assertEqual( question.validate_question('2.0'), {question.id: 'ValidationError'} ) self.assertEqual( question.validate_question('4.0'), {question.id: 'ValidationError'} ) self.assertEqual( question.validate_question('2.9'), {} ) @users('survey_manager') def test_answer_validation_char_box_email(self): question = self._add_question(self.page_0, 'Q0', 'char_box', validation_email=True) self.assertEqual( question.validate_question('not an email'), {question.id: _('This answer must be an email address')} ) self.assertEqual( question.validate_question('email@example.com'), {} ) @users('survey_manager') def test_answer_validation_char_box_length(self): question = self._add_question( self.page_0, 'Q0', 'char_box', validation_required=True, validation_length_min=2, validation_length_max=8, validation_error_msg='ValidationError') self.assertEqual( question.validate_question('l'), {question.id: 'ValidationError'} ) self.assertEqual( question.validate_question('waytoomuchlonganswer'), {question.id: 'ValidationError'} ) self.assertEqual( question.validate_question('valid'), {} ) def test_partial_scores_simple_choice(self): """" Check that if partial scores are given for partially correct answers, in the case of a multiple choice question with single choice, choosing the answer with max score gives 100% of points. """ partial_scores_survey = self.env['survey.survey'].create({ 'title': 'How much do you know about words?', 'scoring_type': 'scoring_with_answers', 'scoring_success_min': 90.0, }) [a_01, a_02, a_03] = self.env['survey.question.answer'].create([{ 'value': 'A thing full of letters.', 'answer_score': 1.0 }, { 'value': 'A unit of language, [...], carrying a meaning.', 'answer_score': 4.0, 'is_correct': True }, { 'value': '42', 'answer_score': -4.0 }]) q_01 = self.env['survey.question'].create({ 'survey_id': partial_scores_survey.id, 'title': 'What is a word?', 'sequence': 1, 'question_type': 'simple_choice', 'suggested_answer_ids': [(6, 0, (a_01 | a_02 | a_03).ids)] }) user_input = self.env['survey.user_input'].create({'survey_id': partial_scores_survey.id}) self.env['survey.user_input.line'].create({ 'user_input_id': user_input.id, 'question_id': q_01.id, 'answer_type': 'suggestion', 'suggested_answer_id': a_02.id }) # Check that scoring is correct and survey is passed self.assertEqual(user_input.scoring_percentage, 100) self.assertTrue(user_input.scoring_success) @users('survey_manager') def test_skipped_values(self): """ Create one question per type of questions. Make sure they are correctly registered as 'skipped' after saving an empty answer for each of them. """ questions = self._create_one_question_per_type() survey_user = self.survey._create_answer(user=self.survey_user) for question in questions: answer = '' if question.question_type in ['char_box', 'text_box'] else None survey_user.save_lines(question, answer) for question in questions: self._assert_skipped_question(question, survey_user) def test_get_pages_and_questions_to_show(self): """ Tests the method `_get_pages_and_questions_to_show` - it takes a recordset of question.question from a survey.survey and returns a recordset without invalid conditional questions and pages without description Structure of the test survey: sequence | type | trigger | validity ---------------------------------------------------------------------- 1 | page, no description | / | X 2 | text_box | trigger is 6 | X 3 | numerical_box | trigger is 2 | X 4 | simple_choice | / | V 5 | page, description | / | V 6 | multiple_choice | / | V 7 | multiple_choice, no answers | / | V 8 | text_box | trigger is 6 | V 9 | matrix | trigger is 5 | X 10 | simple_choice | trigger is 7 | X 11 | simple_choice, no answers | trigger is 8 | X 12 | text_box | trigger is 11 | X """ my_survey = self.env['survey.survey'].create({ 'title': 'my_survey', 'questions_layout': 'page_per_question', 'questions_selection': 'all', 'access_mode': 'public', }) [ page_without_description, text_box_1, numerical_box, _simple_choice_1, page_with_description, multiple_choice_1, multiple_choice_2, text_box_2, matrix, simple_choice_2, simple_choice_3, text_box_3, ] = self.env['survey.question'].create([{ 'title': 'no desc', 'survey_id': my_survey.id, 'sequence': 1, 'question_type': False, 'is_page': True, 'description': False, }, { 'title': 'text_box with invalid trigger', 'survey_id': my_survey.id, 'sequence': 2, 'is_page': False, 'question_type': 'simple_choice', }, { 'title': 'numerical box with trigger that is invalid', 'survey_id': my_survey.id, 'sequence': 3, 'is_page': False, 'question_type': 'numerical_box', }, { 'title': 'valid simple_choice', 'survey_id': my_survey.id, 'sequence': 4, 'is_page': False, 'question_type': 'simple_choice', 'suggested_answer_ids': [(0, 0, {'value': 'a'})], }, { 'title': 'with desc', 'survey_id': my_survey.id, 'sequence': 5, 'is_page': True, 'question_type': False, 'description': 'This page has a description', }, { 'title': 'multiple choice not conditional', 'survey_id': my_survey.id, 'sequence': 6, 'is_page': False, 'question_type': 'multiple_choice', 'suggested_answer_ids': [(0, 0, {'value': 'a'})] }, { 'title': 'multiple_choice with no answers', 'survey_id': my_survey.id, 'sequence': 7, 'is_page': False, 'question_type': 'multiple_choice', }, { 'title': 'text_box with valid trigger', 'survey_id': my_survey.id, 'sequence': 8, 'is_page': False, 'question_type': 'text_box', }, { 'title': 'matrix with invalid trigger (page)', 'survey_id': my_survey.id, 'sequence': 9, 'is_page': False, 'question_type': 'matrix', }, { 'title': 'simple choice w/ invalid trigger (no suggested_answer_ids)', 'survey_id': my_survey.id, 'sequence': 10, 'is_page': False, 'question_type': 'simple_choice', }, { 'title': 'text_box w/ invalid trigger (not a mcq)', 'survey_id': my_survey.id, 'sequence': 11, 'is_page': False, 'question_type': 'simple_choice', 'suggested_answer_ids': False, }, { 'title': 'text_box w/ invalid trigger (suggested_answer_ids is False)', 'survey_id': my_survey.id, 'sequence': 12, 'is_page': False, 'question_type': 'text_box', }]) text_box_1.write({'is_conditional': True, 'triggering_question_id': multiple_choice_1.id}) numerical_box.write({'is_conditional': True, 'triggering_question_id': text_box_1.id}) text_box_2.write({'is_conditional': True, 'triggering_question_id': multiple_choice_1.id}) matrix.write({'is_conditional': True, 'triggering_question_id': page_with_description.id}) simple_choice_2.write({'is_conditional': True, 'triggering_question_id': multiple_choice_2.id}) simple_choice_3.write({'is_conditional': True, 'triggering_question_id': text_box_2.id}) text_box_3.write({'is_conditional': True, 'triggering_question_id': simple_choice_3.id}) invalid_records = page_without_description + text_box_1 + numerical_box \ + matrix + simple_choice_2 + simple_choice_3 + text_box_3 question_and_page_ids = my_survey.question_and_page_ids returned_questions_and_pages = my_survey._get_pages_and_questions_to_show() self.assertEqual(question_and_page_ids - invalid_records, returned_questions_and_pages)
39.063973
11,602
10,080
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from dateutil.relativedelta import relativedelta from unittest.mock import patch from odoo import fields from odoo.tests.common import tagged, HttpCase @tagged('post_install', '-at_install') class TestUiSession(HttpCase): def test_admin_survey_session(self): """ This method tests a full 'survey session' flow. Break down of different steps: - Create the test data - A scored survey - A nickname question - "Simple" type questions (text, date, datetime) - A regular simple choice - A scored simple choice - A scored AND timed multiple choice - Create a new survey session - Register 3 attendees to it - Open the session manager to check that our attendees are accounted for - Create some answers to our survey questions. - Then run the 'big' manage session tour (see JS doc for details) - And finally check that our session and attendees inputs are correctly closed. """ # ======================= # CREATE SURVEY TEST DATA # ======================= test_start_time = fields.Datetime.now() survey_session = self.env['survey.survey'].create({ 'title': 'User Session Survey', 'access_token': 'b137640d-14d4-4748-9ef6-344caaaaafe', 'access_mode': 'public', 'users_can_go_back': False, 'questions_layout': 'page_per_question', 'scoring_type': 'scoring_without_answers' }) nickname_question = self.env['survey.question'].create({ 'survey_id': survey_session.id, 'title': 'Nickname', 'save_as_nickname': True, 'sequence': 1, 'question_type': 'char_box', }) text_question = self.env['survey.question'].create({ 'survey_id': survey_session.id, 'title': 'Text Question', 'sequence': 2, 'question_type': 'char_box', }) date_question = self.env['survey.question'].create({ 'survey_id': survey_session.id, 'title': 'Date Question', 'sequence': 3, 'question_type': 'date', }) datetime_question = self.env['survey.question'].create({ 'survey_id': survey_session.id, 'title': 'Datetime Question', 'sequence': 4, 'question_type': 'datetime', }) simple_choice_answer_1 = self.env['survey.question.answer'].create({ 'value': 'First' }) simple_choice_answer_2 = self.env['survey.question.answer'].create({ 'value': 'Second' }) simple_choice_answer_3 = self.env['survey.question.answer'].create({ 'value': 'Third' }) simple_choice_question = self.env['survey.question'].create({ 'survey_id': survey_session.id, 'title': 'Regular Simple Choice', 'sequence': 5, 'question_type': 'simple_choice', 'suggested_answer_ids': [ (4, simple_choice_answer_1.id), (4, simple_choice_answer_2.id), (4, simple_choice_answer_3.id)], }) scored_choice_answer_1 = self.env['survey.question.answer'].create({ 'value': 'Correct', 'is_correct': True, 'answer_score': 30 }) scored_choice_answer_2 = self.env['survey.question.answer'].create({ 'value': 'Incorrect 1' }) scored_choice_answer_3 = self.env['survey.question.answer'].create({ 'value': 'Incorrect 2' }) scored_choice_answer_4 = self.env['survey.question.answer'].create({ 'value': 'Incorrect 3' }) scored_choice_question = self.env['survey.question'].create({ 'survey_id': survey_session.id, 'title': 'Scored Simple Choice', 'sequence': 6, 'question_type': 'simple_choice', 'suggested_answer_ids': [ (4, scored_choice_answer_1.id), (4, scored_choice_answer_2.id), (4, scored_choice_answer_3.id), (4, scored_choice_answer_4.id)], }) timed_scored_choice_answer_1 = self.env['survey.question.answer'].create({ 'value': 'Correct', 'is_correct': True, 'answer_score': 30 }) timed_scored_choice_answer_2 = self.env['survey.question.answer'].create({ 'value': 'Also correct but less points', 'is_correct': True, 'answer_score': 10 }) timed_scored_choice_answer_3 = self.env['survey.question.answer'].create({ 'value': 'Incorrect', 'answer_score': -40 }) timed_scored_choice_question = self.env['survey.question'].create({ 'survey_id': survey_session.id, 'title': 'Timed Scored Multiple Choice', 'sequence': 6, 'question_type': 'multiple_choice', 'is_time_limited': True, 'time_limit': 1, 'suggested_answer_ids': [ (4, timed_scored_choice_answer_1.id), (4, timed_scored_choice_answer_2.id), (4, timed_scored_choice_answer_3.id)], }) # ======================= # PART 1 : CREATE SESSION # ======================= def action_open_session_manager_mock(self): """ Mock original method to ensure we are not using another tab as it creates issues with automated tours. """ return { 'type': 'ir.actions.act_url', 'name': "Open Session Manager", 'target': 'self', 'url': '/survey/session/manage/%s' % self.access_token } with patch('odoo.addons.survey.models.survey_survey.Survey.action_open_session_manager', action_open_session_manager_mock): self.start_tour('/web', 'test_survey_session_create_tour', login='admin') # tricky part: we only take into account answers created after the session_start_time # the create_date of the answers we just saved is set to the beginning of the test. # but the session_start_time is set after that. # So we cheat on the session start date to be able to count answers properly. survey_session.write({'session_start_time': test_start_time - relativedelta(minutes=10)}) attendee_1 = survey_session._create_answer() attendee_2 = survey_session._create_answer() attendee_3 = survey_session._create_answer() all_attendees = [attendee_1, attendee_2, attendee_3] self.assertEqual('ready', survey_session.session_state) self.assertTrue(all(attendee.is_session_answer for attendee in all_attendees), "Created answers should be within the session.") self.assertTrue(all(attendee.state == 'new' for attendee in all_attendees), "Created answers should be in the 'new' state.") # ========================================= # PART 2 : OPEN SESSION AND CHECK ATTENDEES # ========================================= with patch('odoo.addons.survey.models.survey_survey.Survey.action_open_session_manager', action_open_session_manager_mock): self.start_tour('/web', 'test_survey_session_start_tour', login='admin') self.assertEqual('in_progress', survey_session.session_state) self.assertTrue(bool(survey_session.session_start_time)) # ======================================== # PART 3 : CREATE ANSWERS & MANAGE SESSION # ======================================== # create a few answers beforehand to avoid having to back and forth too # many times between the tours and the python test attendee_1.save_lines(nickname_question, 'xxxTheBestxxx') attendee_2.save_lines(nickname_question, 'azerty') attendee_3.save_lines(nickname_question, 'nicktalope') self.assertEqual('xxxTheBestxxx', attendee_1.nickname) self.assertEqual('azerty', attendee_2.nickname) self.assertEqual('nicktalope', attendee_3.nickname) attendee_1.save_lines(text_question, 'Attendee 1 is the best') attendee_2.save_lines(text_question, 'Attendee 2 rulez') attendee_3.save_lines(text_question, 'Attendee 3 will crush you') attendee_1.save_lines(date_question, '2010-10-10') attendee_2.save_lines(date_question, '2011-11-11') attendee_2.save_lines(datetime_question, '2010-10-10 10:00:00') attendee_3.save_lines(datetime_question, '2011-11-11 15:55:55') attendee_1.save_lines(simple_choice_question, simple_choice_answer_1.id) attendee_2.save_lines(simple_choice_question, simple_choice_answer_1.id) attendee_3.save_lines(simple_choice_question, simple_choice_answer_2.id) attendee_1.save_lines(scored_choice_question, scored_choice_answer_1.id) attendee_2.save_lines(scored_choice_question, scored_choice_answer_2.id) attendee_3.save_lines(scored_choice_question, scored_choice_answer_3.id) attendee_1.save_lines(timed_scored_choice_question, [timed_scored_choice_answer_1.id, timed_scored_choice_answer_3.id]) attendee_2.save_lines(timed_scored_choice_question, [timed_scored_choice_answer_1.id, timed_scored_choice_answer_2.id]) attendee_3.save_lines(timed_scored_choice_question, [timed_scored_choice_answer_2.id]) with patch('odoo.addons.survey.models.survey_survey.Survey.action_open_session_manager', action_open_session_manager_mock): self.start_tour('/web', 'test_survey_session_manage_tour', login='admin') self.assertFalse(bool(survey_session.session_state)) self.assertTrue(all(answer.state == 'done' for answer in all_attendees))
45.201794
10,080
13,616
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from collections import Counter from contextlib import contextmanager from odoo.addons.mail.tests.common import mail_new_test_user from odoo.tests import common class SurveyCase(common.TransactionCase): def setUp(self): super(SurveyCase, self).setUp() """ Some custom stuff to make the matching between questions and answers :param dict _type_match: dict key: question type value: (answer type, answer field_name) """ self._type_match = { 'text_box': ('text_box', 'value_text_box'), 'char_box': ('char_box', 'value_char_box'), 'numerical_box': ('numerical_box', 'value_numerical_box'), 'date': ('date', 'value_date'), 'simple_choice': ('suggestion', 'suggested_answer_id'), # TDE: still unclear 'multiple_choice': ('suggestion', 'suggested_answer_id'), # TDE: still unclear 'matrix': ('suggestion', ('suggested_answer_id', 'matrix_row_id')), # TDE: still unclear } # ------------------------------------------------------------ # ASSERTS # ------------------------------------------------------------ def assertAnswer(self, answer, state, page): self.assertEqual(answer.state, state) self.assertEqual(answer.last_displayed_page_id, page) def assertAnswerLines(self, page, answer, answer_data): """ Check answer lines. :param dict answer_data: key = question ID value = {'value': [user input]} """ lines = answer.user_input_line_ids.filtered(lambda l: l.page_id == page) answer_count = sum(len(user_input['value']) for user_input in answer_data.values()) self.assertEqual(len(lines), answer_count) for qid, user_input in answer_data.items(): answer_lines = lines.filtered(lambda l: l.question_id.id == qid) question = answer_lines[0].question_id # TDE note: might have several answers for a given question if question.question_type == 'multiple_choice': values = user_input['value'] answer_fname = self._type_match[question.question_type][1] self.assertEqual( Counter(getattr(line, answer_fname).id for line in answer_lines), Counter(values)) elif question.question_type == 'simple_choice': [value] = user_input['value'] answer_fname = self._type_match[question.question_type][1] self.assertEqual(getattr(answer_lines, answer_fname).id, value) elif question.question_type == 'matrix': [value_col, value_row] = user_input['value'] answer_fname_col = self._type_match[question.question_type][1][0] answer_fname_row = self._type_match[question.question_type][1][1] self.assertEqual(getattr(answer_lines, answer_fname_col).id, value_col) self.assertEqual(getattr(answer_lines, answer_fname_row).id, value_row) else: [value] = user_input['value'] answer_fname = self._type_match[question.question_type][1] if question.question_type == 'numerical_box': self.assertEqual(getattr(answer_lines, answer_fname), float(value)) else: self.assertEqual(getattr(answer_lines, answer_fname), value) def assertResponse(self, response, status_code, text_bits=None): self.assertEqual(response.status_code, status_code) for text in text_bits or []: self.assertIn(text, response.text) # ------------------------------------------------------------ # DATA CREATION # ------------------------------------------------------------ def _add_question(self, page, name, qtype, **kwargs): constr_mandatory = kwargs.pop('constr_mandatory', True) constr_error_msg = kwargs.pop('constr_error_msg', 'TestError') sequence = kwargs.pop('sequence', False) if not sequence: sequence = page.question_ids[-1].sequence + 1 if page.question_ids else page.sequence + 1 base_qvalues = { 'sequence': sequence, 'title': name, 'question_type': qtype, 'constr_mandatory': constr_mandatory, 'constr_error_msg': constr_error_msg, } if qtype in ('simple_choice', 'multiple_choice'): base_qvalues['suggested_answer_ids'] = [ (0, 0, { 'value': label['value'], 'answer_score': label.get('answer_score', 0), 'is_correct': label.get('is_correct', False) }) for label in kwargs.pop('labels') ] elif qtype == 'matrix': base_qvalues['matrix_subtype'] = kwargs.pop('matrix_subtype', 'simple') base_qvalues['suggested_answer_ids'] = [ (0, 0, {'value': label['value'], 'answer_score': label.get('answer_score', 0)}) for label in kwargs.pop('labels') ] base_qvalues['matrix_row_ids'] = [ (0, 0, {'value': label['value'], 'answer_score': label.get('answer_score', 0)}) for label in kwargs.pop('labels_2') ] else: pass base_qvalues.update(kwargs) question = self.env['survey.question'].create(base_qvalues) return question def _add_answer(self, survey, partner, **kwargs): base_avals = { 'survey_id': survey.id, 'partner_id': partner.id if partner else False, 'email': kwargs.pop('email', False), } base_avals.update(kwargs) return self.env['survey.user_input'].create(base_avals) def _add_answer_line(self, question, answer, answer_value, **kwargs): qtype = self._type_match.get(question.question_type, (False, False)) answer_type = kwargs.pop('answer_type', qtype[0]) answer_fname = kwargs.pop('answer_fname', qtype[1]) base_alvals = { 'user_input_id': answer.id, 'question_id': question.id, 'skipped': False, 'answer_type': answer_type, } base_alvals[answer_fname] = answer_value base_alvals.update(kwargs) return self.env['survey.user_input.line'].create(base_alvals) # ------------------------------------------------------------ # UTILS / CONTROLLER ENDPOINTS FLOWS # ------------------------------------------------------------ def _access_start(self, survey): return self.url_open('/survey/start/%s' % survey.access_token) def _access_page(self, survey, token): return self.url_open('/survey/%s/%s' % (survey.access_token, token)) def _access_begin(self, survey, token): url = survey.get_base_url() + '/survey/begin/%s/%s' % (survey.access_token, token) return self.opener.post(url=url, json={}) def _access_submit(self, survey, token, post_data): url = survey.get_base_url() + '/survey/submit/%s/%s' % (survey.access_token, token) return self.opener.post(url=url, json={'params': post_data}) def _find_csrf_token(self, text): csrf_token_re = re.compile("(input.+csrf_token.+value=\")([a-f0-9]{40}o[0-9]*)", re.MULTILINE) return csrf_token_re.search(text).groups()[1] def _prepare_post_data(self, question, answers, post_data): values = answers if isinstance(answers, list) else [answers] if question.question_type == 'multiple_choice': for value in values: value = str(value) if question.id in post_data: if isinstance(post_data[question.id], list): post_data[question.id].append(value) else: post_data[question.id] = [post_data[question.id], value] else: post_data[question.id] = value else: [values] = values post_data[question.id] = str(values) return post_data def _answer_question(self, question, answer, answer_token, csrf_token, button_submit='next'): # Employee submits the question answer post_data = self._format_submission_data(question, answer, {'csrf_token': csrf_token, 'token': answer_token, 'button_submit': button_submit}) response = self._access_submit(question.survey_id, answer_token, post_data) self.assertResponse(response, 200) # Employee is redirected on next question response = self._access_page(question.survey_id, answer_token) self.assertResponse(response, 200) def _answer_page(self, page, answers, answer_token, csrf_token): post_data = {} for question, answer in answers.items(): post_data[question.id] = answer.id post_data['page_id'] = page.id post_data['csrf_token'] = csrf_token post_data['token'] = answer_token response = self._access_submit(page.survey_id, answer_token, post_data) self.assertResponse(response, 200) response = self._access_page(page.survey_id, answer_token) self.assertResponse(response, 200) def _format_submission_data(self, question, answer, additional_post_data): post_data = {} post_data['question_id'] = question.id post_data.update(self._prepare_post_data(question, answer, post_data)) if question.page_id: post_data['page_id'] = question.page_id.id post_data.update(**additional_post_data) return post_data # ------------------------------------------------------------ # UTILS / TOOLS # ------------------------------------------------------------ def _assert_skipped_question(self, question, survey_user): statistics = question._prepare_statistics(survey_user.user_input_line_ids) question_data = next( (question_data for question_data in statistics if question_data.get('question') == question), False ) self.assertTrue(bool(question_data)) self.assertEqual(len(question_data.get('answer_input_skipped_ids')), 1) def _create_one_question_per_type(self): all_questions = self.env['survey.question'] for (question_type, dummy) in self.env['survey.question']._fields['question_type'].selection: kwargs = {} if question_type == 'multiple_choice': kwargs['labels'] = [{'value': 'MChoice0'}, {'value': 'MChoice1'}] elif question_type == 'simple_choice': kwargs['labels'] = [] elif question_type == 'matrix': kwargs['labels'] = [{'value': 'Column0'}, {'value': 'Column1'}] kwargs['labels_2'] = [{'value': 'Row0'}, {'value': 'Row1'}] all_questions |= self._add_question(self.page_0, 'Q0', question_type, **kwargs) return all_questions class TestSurveyCommon(SurveyCase): def setUp(self): super(TestSurveyCommon, self).setUp() """ Create test data: a survey with some pre-defined questions and various test users for ACL """ self.survey_manager = mail_new_test_user( self.env, name='Gustave Doré', login='survey_manager', email='survey.manager@example.com', groups='survey.group_survey_manager,base.group_user' ) self.survey_user = mail_new_test_user( self.env, name='Lukas Peeters', login='survey_user', email='survey.user@example.com', groups='survey.group_survey_user,base.group_user' ) self.user_emp = mail_new_test_user( self.env, name='Eglantine Employee', login='user_emp', email='employee@example.com', groups='base.group_user', password='user_emp' ) self.user_portal = mail_new_test_user( self.env, name='Patrick Portal', login='user_portal', email='portal@example.com', groups='base.group_portal' ) self.user_public = mail_new_test_user( self.env, name='Pauline Public', login='user_public', email='public@example.com', groups='base.group_public' ) self.customer = self.env['res.partner'].create({ 'name': 'Caroline Customer', 'email': 'customer@example.com', }) self.survey = self.env['survey.survey'].with_user(self.survey_manager).create({ 'title': 'Test Survey', 'access_mode': 'public', 'users_login_required': True, 'users_can_go_back': False, }) self.page_0 = self.env['survey.question'].with_user(self.survey_manager).create({ 'title': 'First page', 'survey_id': self.survey.id, 'sequence': 1, 'is_page': True, }) self.question_ft = self.env['survey.question'].with_user(self.survey_manager).create({ 'title': 'Test Free Text', 'survey_id': self.survey.id, 'sequence': 2, 'question_type': 'text_box', }) self.question_num = self.env['survey.question'].with_user(self.survey_manager).create({ 'title': 'Test NUmerical Box', 'survey_id': self.survey.id, 'sequence': 3, 'question_type': 'numerical_box', })
44.204545
13,615
5,648
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.survey.tests import common from odoo.tests import tagged from odoo.tests.common import HttpCase @tagged('-at_install', 'post_install', 'functional') class TestSurveyFlow(common.TestSurveyCommon, HttpCase): def _format_submission_data(self, page, answer_data, additional_post_data): post_data = {} post_data['page_id'] = page.id for question_id, answer_vals in answer_data.items(): question = page.question_ids.filtered(lambda q: q.id == question_id) post_data.update(self._prepare_post_data(question, answer_vals['value'], post_data)) post_data.update(**additional_post_data) return post_data def test_flow_public(self): # Step: survey manager creates the survey # -------------------------------------------------- with self.with_user('survey_manager'): survey = self.env['survey.survey'].create({ 'title': 'Public Survey for Tarte Al Djotte', 'access_mode': 'public', 'users_login_required': False, 'questions_layout': 'page_per_section', }) # First page is about customer data page_0 = self.env['survey.question'].create({ 'is_page': True, 'sequence': 1, 'title': 'Page1: Your Data', 'survey_id': survey.id, }) page0_q0 = self._add_question( page_0, 'What is your name', 'text_box', comments_allowed=False, constr_mandatory=True, constr_error_msg='Please enter your name', survey_id=survey.id) page0_q1 = self._add_question( page_0, 'What is your age', 'numerical_box', comments_allowed=False, constr_mandatory=True, constr_error_msg='Please enter your name', survey_id=survey.id) # Second page is about tarte al djotte page_1 = self.env['survey.question'].create({ 'is_page': True, 'sequence': 4, 'title': 'Page2: Tarte Al Djotte', 'survey_id': survey.id, }) page1_q0 = self._add_question( page_1, 'What do you like most in our tarte al djotte', 'multiple_choice', labels=[{'value': 'The gras'}, {'value': 'The bette'}, {'value': 'The tout'}, {'value': 'The regime is fucked up'}], survey_id=survey.id) # fetch starting data to check only newly created data during this flow answers = self.env['survey.user_input'].search([('survey_id', '=', survey.id)]) answer_lines = self.env['survey.user_input.line'].search([('survey_id', '=', survey.id)]) self.assertEqual(answers, self.env['survey.user_input']) self.assertEqual(answer_lines, self.env['survey.user_input.line']) # Step: customer takes the survey # -------------------------------------------------- # Customer opens start page r = self._access_start(survey) self.assertResponse(r, 200, [survey.title]) # -> this should have generated a new answer with a token answers = self.env['survey.user_input'].search([('survey_id', '=', survey.id)]) self.assertEqual(len(answers), 1) answer_token = answers.access_token self.assertTrue(answer_token) self.assertAnswer(answers, 'new', self.env['survey.question']) # Customer begins survey with first page r = self._access_page(survey, answer_token) self.assertResponse(r, 200) self.assertAnswer(answers, 'new', self.env['survey.question']) csrf_token = self._find_csrf_token(r.text) r = self._access_begin(survey, answer_token) self.assertResponse(r, 200) # Customer submit first page answers answer_data = { page0_q0.id: {'value': ['Alfred Poilvache']}, page0_q1.id: {'value': ['44.0']}, } post_data = self._format_submission_data(page_0, answer_data, {'csrf_token': csrf_token, 'token': answer_token, 'button_submit': 'next'}) r = self._access_submit(survey, answer_token, post_data) self.assertResponse(r, 200) answers.invalidate_cache() # TDE note: necessary as lots of sudo in controllers messing with cache # -> this should have generated answer lines self.assertAnswer(answers, 'in_progress', page_0) self.assertAnswerLines(page_0, answers, answer_data) # Customer is redirected on second page and begins filling it r = self._access_page(survey, answer_token) self.assertResponse(r, 200) csrf_token = self._find_csrf_token(r.text) # Customer submit second page answers answer_data = { page1_q0.id: {'value': [page1_q0.suggested_answer_ids.ids[0], page1_q0.suggested_answer_ids.ids[1]]}, } post_data = self._format_submission_data(page_1, answer_data, {'csrf_token': csrf_token, 'token': answer_token, 'button_submit': 'next'}) r = self._access_submit(survey, answer_token, post_data) self.assertResponse(r, 200) answers.invalidate_cache() # TDE note: necessary as lots of sudo in controllers messing with cache # -> this should have generated answer lines and closed the answer self.assertAnswer(answers, 'done', page_1) self.assertAnswerLines(page_1, answers, answer_data)
47.066667
5,648
10,793
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from odoo.addons.base.models.ir_mail_server import IrMailServer from odoo.addons.survey.tests import common from odoo.tests import tagged from odoo.tests.common import HttpCase @tagged('-at_install', 'post_install', 'functional') class TestCertificationFlow(common.TestSurveyCommon, HttpCase): def test_flow_certification(self): # Step: survey user creates the certification # -------------------------------------------------- with self.with_user('survey_user'): certification = self.env['survey.survey'].create({ 'title': 'User Certification for SO lines', 'access_mode': 'public', 'users_login_required': True, 'questions_layout': 'page_per_question', 'users_can_go_back': True, 'scoring_type': 'scoring_with_answers', 'scoring_success_min': 85.0, 'certification': True, 'certification_mail_template_id': self.env.ref('survey.mail_template_certification').id, 'is_time_limited': True, 'time_limit': 10, }) q01 = self._add_question( None, 'When do you know it\'s the right time to use the SO line model?', 'simple_choice', sequence=1, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=certification.id, labels=[ {'value': 'Please stop'}, {'value': 'Only on the SO form'}, {'value': 'Only on the Survey form'}, {'value': 'Easy, all the time!!!', 'is_correct': True, 'answer_score': 2.0} ]) q02 = self._add_question( None, 'On average, how many lines of code do you need when you use SO line widgets?', 'simple_choice', sequence=2, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=certification.id, labels=[ {'value': '1'}, {'value': '5', 'is_correct': True, 'answer_score': 2.0}, {'value': '100'}, {'value': '1000'} ]) q03 = self._add_question( None, 'What do you think about SO line widgets (not rated)?', 'text_box', sequence=3, constr_mandatory=True, constr_error_msg='Please tell us what you think', survey_id=certification.id) q04 = self._add_question( None, 'On a scale of 1 to 10, how much do you like SO line widgets (not rated)?', 'simple_choice', sequence=4, constr_mandatory=True, constr_error_msg='Please tell us what you think', survey_id=certification.id, labels=[ {'value': '-1'}, {'value': '0'}, {'value': '100'} ]) q05 = self._add_question( None, 'Select all the correct "types" of SO lines', 'multiple_choice', sequence=5, constr_mandatory=False, survey_id=certification.id, labels=[ {'value': 'sale_order', 'is_correct': True, 'answer_score': 1.0}, {'value': 'survey_page', 'is_correct': True, 'answer_score': 1.0}, {'value': 'survey_question', 'is_correct': True, 'answer_score': 1.0}, {'value': 'a_future_and_yet_unknown_model', 'is_correct': True, 'answer_score': 1.0}, {'value': 'none', 'answer_score': -1.0} ]) # Step: employee takes the certification # -------------------------------------------------- self.authenticate('user_emp', 'user_emp') # Employee opens start page response = self._access_start(certification) self.assertResponse(response, 200, [certification.title, 'Time limit for this survey', '10 minutes']) # -> this should have generated a new user_input with a token user_inputs = self.env['survey.user_input'].search([('survey_id', '=', certification.id)]) self.assertEqual(len(user_inputs), 1) self.assertEqual(user_inputs.partner_id, self.user_emp.partner_id) answer_token = user_inputs.access_token # Employee begins survey with first page response = self._access_page(certification, answer_token) self.assertResponse(response, 200) csrf_token = self._find_csrf_token(response.text) r = self._access_begin(certification, answer_token) self.assertResponse(r, 200) with patch.object(IrMailServer, 'connect'): self._answer_question(q01, q01.suggested_answer_ids.ids[3], answer_token, csrf_token) self._answer_question(q02, q02.suggested_answer_ids.ids[1], answer_token, csrf_token) self._answer_question(q03, "I think they're great!", answer_token, csrf_token) self._answer_question(q04, q04.suggested_answer_ids.ids[0], answer_token, csrf_token, button_submit='previous') self._answer_question(q03, "Just kidding, I don't like it...", answer_token, csrf_token) self._answer_question(q04, q04.suggested_answer_ids.ids[0], answer_token, csrf_token) self._answer_question(q05, [q05.suggested_answer_ids.ids[0], q05.suggested_answer_ids.ids[1], q05.suggested_answer_ids.ids[3]], answer_token, csrf_token) user_inputs.invalidate_cache() # Check that certification is successfully passed self.assertEqual(user_inputs.scoring_percentage, 87.5) self.assertTrue(user_inputs.scoring_success) # Check that the certification is still successful even if scoring_success_min of certification is modified certification.write({'scoring_success_min': 90}) self.assertTrue(user_inputs.scoring_success) # Check answer correction is taken into account self.assertNotIn("I think they're great!", user_inputs.mapped('user_input_line_ids.value_text_box')) self.assertIn("Just kidding, I don't like it...", user_inputs.mapped('user_input_line_ids.value_text_box')) certification_email = self.env['mail.mail'].sudo().search([], limit=1, order="create_date desc") # Check certification email correctly sent and contains document self.assertIn("User Certification for SO lines", certification_email.subject) self.assertIn("employee@example.com", certification_email.email_to) self.assertEqual(len(certification_email.attachment_ids), 1) self.assertEqual(certification_email.attachment_ids[0].name, 'Certification Document.html') def test_randomized_certification(self): # Step: survey user creates the randomized certification # -------------------------------------------------- with self.with_user('survey_user'): certification = self.env['survey.survey'].create({ 'title': 'User randomized Certification', 'questions_layout': 'page_per_section', 'questions_selection': 'random', 'scoring_type': 'scoring_without_answers', }) page1 = self._add_question( None, 'Page 1', None, sequence=1, survey_id=certification.id, is_page=True, random_questions_count=1, ) q101 = self._add_question( None, 'What is the answer to the first question?', 'simple_choice', sequence=2, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=certification.id, labels=[ {'value': 'The correct answer', 'is_correct': True, 'answer_score': 1.0}, {'value': 'The wrong answer'}, ]) q102 = self._add_question( None, 'What is the answer to the second question?', 'simple_choice', sequence=3, constr_mandatory=True, constr_error_msg='Please select an answer', survey_id=certification.id, labels=[ {'value': 'The correct answer', 'is_correct': True, 'answer_score': 1.0}, {'value': 'The wrong answer'}, ]) # Step: employee takes the randomized certification # -------------------------------------------------- self.authenticate('user_emp', 'user_emp') # Employee opens start page response = self._access_start(certification) # -> this should have generated a new user_input with a token user_inputs = self.env['survey.user_input'].search([('survey_id', '=', certification.id)]) self.assertEqual(len(user_inputs), 1) self.assertEqual(user_inputs.partner_id, self.user_emp.partner_id) answer_token = user_inputs.access_token # Employee begins survey with first page response = self._access_page(certification, answer_token) self.assertResponse(response, 200) csrf_token = self._find_csrf_token(response.text) r = self._access_begin(certification, answer_token) self.assertResponse(r, 200) with patch.object(IrMailServer, 'connect'): question_ids = user_inputs.predefined_question_ids self.assertEqual(len(question_ids), 1, 'Only one question should have been selected by the randomization') # Whatever which question was selected, the correct answer is the first one self._answer_question(question_ids, question_ids.suggested_answer_ids.ids[0], answer_token, csrf_token) statistics = user_inputs._prepare_statistics()[user_inputs] total_statistics = statistics['totals'] self.assertEqual(total_statistics, [ {'text': 'Correct', 'count': 1}, {'text': 'Partially', 'count': 0}, {'text': 'Incorrect', 'count': 0}, {'text': 'Unanswered', 'count': 0}, ], "With the configured randomization, there should be exactly 1 correctly answered question and none skipped.") section_statistics = statistics['by_section'] self.assertEqual(section_statistics, { 'Page 1': { 'question_count': 1, 'correct': 1, 'partial': 0, 'incorrect': 0, 'skipped': 0, } }, "With the configured randomization, there should be exactly 1 correctly answered question in the 'Page 1' section.")
50.2
10,793
11,559
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.survey.tests import common from psycopg2 import IntegrityError from odoo.exceptions import AccessError from odoo.tools import mute_logger class TestCertificationBadge(common.TestSurveyCommon): def setUp(self): super(TestCertificationBadge, self).setUp() self.certification_survey = self.env['survey.survey'].with_user(self.survey_manager).create({ 'title': 'Certification Survey', 'access_mode': 'public', 'users_login_required': True, 'scoring_type': 'scoring_with_answers', 'certification': True, }) self.certification_survey_2 = self.env['survey.survey'].with_user(self.survey_manager).create({ 'title': 'Another Certification Survey', 'access_mode': 'public', 'users_login_required': True, 'scoring_type': 'scoring_with_answers', 'certification': True, }) self.certification_badge = self.env['gamification.badge'].with_user(self.survey_manager).create({ 'name': self.certification_survey.title, 'description': 'Congratulations, you have succeeded this certification', 'rule_auth': 'nobody', 'level': None, }) self.certification_badge_2 = self.env['gamification.badge'].with_user(self.survey_manager).create({ 'name': self.certification_survey.title + ' 2', 'description': 'Congratulations, you have succeeded this certification', 'rule_auth': 'nobody', 'level': None, }) self.certification_badge_3 = self.env['gamification.badge'].with_user(self.survey_manager).create({ 'name': self.certification_survey.title + ' 3', 'description': 'Congratulations, you have succeeded this certification', 'rule_auth': 'nobody', 'level': None, }) def test_archive(self): """ Archive status of survey is propagated to its badges. """ self.certification_survey.write({ 'certification_give_badge': True, 'certification_badge_id': self.certification_badge.id }) self.certification_survey.action_archive() self.assertFalse(self.certification_survey.active) self.assertFalse(self.certification_badge.active) self.certification_survey.action_unarchive() self.assertTrue(self.certification_survey.active) self.assertTrue(self.certification_badge.active) def test_set_same_badge_on_multiple_survey(self): self.certification_survey.write({ 'certification_give_badge': True, 'certification_badge_id': self.certification_badge.id }) # set the same badge on another survey should fail: with mute_logger('odoo.sql_db'): with self.assertRaises(IntegrityError): self.certification_survey_2.write({ 'certification_give_badge': True, 'certification_badge_id': self.certification_badge.id }) self.certification_survey.flush() def test_badge_configuration(self): """ Test badge synchronization """ # add a certification badge on a new survey challenge = self.env['gamification.challenge'].search([('reward_id', '=', self.certification_badge.id)]) self.assertEqual(len(challenge), 0, """A challenge should not exist or be linked to the certification badge if the certification badge have not been activated on a certification survey""") self.certification_survey.write({ 'certification_give_badge': True, 'certification_badge_id': self.certification_badge.id }) challenge = self.env['gamification.challenge'].search([('reward_id', '=', self.certification_badge.id)]) self.assertEqual(len(challenge), 1, "A challenge should be created if the certification badge is activated on a certification survey") challenge_line = self.env['gamification.challenge.line'].search([('challenge_id', '=', challenge.id)]) self.assertEqual(len(challenge_line), 1, "A challenge_line should be created if the certification badge is activated on a certification survey") goal = challenge_line.definition_id self.assertEqual(len(goal), 1, "A goal should be created if the certification badge is activated on a certification survey") # don't give badge anymore self.certification_survey.write({'certification_give_badge': False}) self.assertEqual(self.certification_badge.id, self.certification_survey.certification_badge_id.id, 'The certification badge should still be set on certification survey even if give_badge is false.') self.assertEqual(self.certification_badge.active, False, 'The certification badge should be inactive if give_badge is false.') challenge = self.env['gamification.challenge'].search([('id', '=', challenge.id)]) self.assertEqual(len(challenge), 0, "The challenge should be deleted if the certification badge is unset from the certification survey") challenge_line = self.env['gamification.challenge.line'].search([('id', '=', challenge_line.id)]) self.assertEqual(len(challenge_line), 0, "The challenge_line should be deleted if the certification badge is unset from the certification survey") goal = self.env['gamification.goal'].search([('id', '=', goal.id)]) self.assertEqual(len(goal), 0, "The goal should be deleted if the certification badge is unset from the certification survey") # re active the badge in the survey self.certification_survey.write({'certification_give_badge': True}) self.assertEqual(self.certification_badge.active, True, 'The certification badge should be active if give_badge is true.') challenge = self.env['gamification.challenge'].search([('reward_id', '=', self.certification_badge.id)]) self.assertEqual(len(challenge), 1, "A challenge should be created if the certification badge is activated on a certification survey") challenge_line = self.env['gamification.challenge.line'].search([('challenge_id', '=', challenge.id)]) self.assertEqual(len(challenge_line), 1, "A challenge_line should be created if the certification badge is activated on a certification survey") goal = challenge_line.definition_id self.assertEqual(len(goal), 1, "A goal should be created if the certification badge is activated on a certification survey") # If 'certification_give_badge' is True but no certification badge is linked, ValueError should be raised duplicate_survey = self.certification_survey.copy() self.assertFalse(duplicate_survey.certification_give_badge, "Value for field 'certification_give_badge' should not be copied") self.assertEqual(duplicate_survey.certification_badge_id, self.env['gamification.badge'], "Badge should be empty") with self.assertRaises(ValueError): duplicate_survey.write({'certification_give_badge': True}) def test_certification_badge_access(self): self.certification_badge.with_user(self.survey_manager).write( {'description': "Spoiler alert: I'm Aegon Targaryen and I sleep with the Dragon Queen, who is my aunt by the way! So I can do whatever I want! Even if I know nothing!"}) self.certification_badge.with_user(self.survey_user).write({'description': "Youpie Yeay!"}) with self.assertRaises(AccessError): self.certification_badge.with_user(self.user_emp).write({'description': "I'm a dude who think that has every right on the Iron Throne"}) with self.assertRaises(AccessError): self.certification_badge.with_user(self.user_portal).write({'description': "Guy, you just can't do that !"}) with self.assertRaises(AccessError): self.certification_badge.with_user(self.user_public).write({'description': "What did you expect ? Schwepps !"}) def test_badge_configuration_multi(self): vals = { 'title': 'Certification Survey', 'access_mode': 'public', 'users_login_required': True, 'scoring_type': 'scoring_with_answers', 'certification': True, 'certification_give_badge': True, 'certification_badge_id': self.certification_badge.id, } survey_1 = self.env['survey.survey'].create(vals.copy()) vals.update({'certification_badge_id': self.certification_badge_2.id}) survey_2 = self.env['survey.survey'].create(vals.copy()) vals.update({'certification_badge_id': self.certification_badge_3.id}) survey_3 = self.env['survey.survey'].create(vals) certification_surveys = self.env['survey.survey'].browse([survey_1.id, survey_2.id, survey_3.id]) self.assertEqual(len(certification_surveys), 3, 'There should be 3 certification survey created') challenges = self.env['gamification.challenge'].search([('reward_id', 'in', certification_surveys.mapped('certification_badge_id').ids)]) self.assertEqual(len(challenges), 3, "3 challenges should be created") challenge_lines = self.env['gamification.challenge.line'].search([('challenge_id', 'in', challenges.ids)]) self.assertEqual(len(challenge_lines), 3, "3 challenge_lines should be created") goals = challenge_lines.mapped('definition_id') self.assertEqual(len(goals), 3, "3 goals should be created") # Test write multi certification_surveys.write({'certification_give_badge': False}) for survey in certification_surveys: self.assertEqual(survey.certification_badge_id.active, False, 'Every badge should be inactive if the 3 survey does not give badge anymore') challenges = self.env['gamification.challenge'].search([('id', 'in', challenges.ids)]) self.assertEqual(len(challenges), 0, "The 3 challenges should be deleted") challenge_lines = self.env['gamification.challenge.line'].search([('id', 'in', challenge_lines.ids)]) self.assertEqual(len(challenge_lines), 0, "The 3 challenge_lines should be deleted") goals = self.env['gamification.goal'].search([('id', 'in', goals.ids)]) self.assertEqual(len(goals), 0, "The 3 goals should be deleted") certification_surveys.write({'certification_give_badge': True}) for survey in certification_surveys: self.assertEqual(survey.certification_badge_id.active, True, 'Every badge should be reactivated if the 3 survey give badges again') challenges = self.env['gamification.challenge'].search([('reward_id', 'in', certification_surveys.mapped('certification_badge_id').ids)]) self.assertEqual(len(challenges), 3, "3 challenges should be created") challenge_lines = self.env['gamification.challenge.line'].search([('challenge_id', 'in', challenges.ids)]) self.assertEqual(len(challenge_lines), 3, "3 challenge_lines should be created") goals = challenge_lines.mapped('definition_id') self.assertEqual(len(goals), 3, "3 goals should be created")
57.507463
11,559
10,202
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import fields from odoo.addons.survey.tests import common from odoo.exceptions import UserError from odoo.tests import Form from odoo.tests.common import users class TestSurveyInvite(common.TestSurveyCommon): def setUp(self): res = super(TestSurveyInvite, self).setUp() # by default signup not allowed self.env["ir.config_parameter"].set_param('auth_signup.invitation_scope', 'b2b') return res @users('survey_manager') def test_survey_invite_action(self): # Check correctly configured survey returns an invite wizard action action = self.survey.action_send_survey() self.assertEqual(action['res_model'], 'survey.invite') # Bad cases surveys = [ # no page self.env['survey.survey'].create({'title': 'Test survey'}), # no questions self.env['survey.survey'].create({'title': 'Test survey', 'question_and_page_ids': [(0, 0, {'is_page': True, 'title': 'P0', 'sequence': 1})]}), # closed self.env['survey.survey'].with_user(self.survey_manager).create({ 'title': 'S0', 'active': False, 'question_and_page_ids': [ (0, 0, {'is_page': True, 'title': 'P0', 'sequence': 1}), (0, 0, {'title': 'Q0', 'sequence': 2, 'question_type': 'text_box'}) ] }) ] for survey in surveys: with self.assertRaises(UserError): survey.action_send_survey() @users('survey_manager') def test_survey_invite(self): Answer = self.env['survey.user_input'] deadline = fields.Datetime.now() + relativedelta(months=1) self.survey.write({'access_mode': 'public', 'users_login_required': False}) action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) # some lowlevel checks that action is correctly configured self.assertEqual(Answer.search([('survey_id', '=', self.survey.id)]), self.env['survey.user_input']) self.assertEqual(invite_form.survey_id, self.survey) invite_form.partner_ids.add(self.customer) invite_form.deadline = fields.Datetime.to_string(deadline) invite = invite_form.save() invite.action_invite() answers = Answer.search([('survey_id', '=', self.survey.id)]) self.assertEqual(len(answers), 1) self.assertEqual( set(answers.mapped('email')), set([self.customer.email])) self.assertEqual(answers.mapped('partner_id'), self.customer) self.assertEqual(set(answers.mapped('deadline')), set([deadline])) with self.subTest('Warning when inviting an already invited partner'): action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) invite_form.partner_ids.add(self.customer) self.assertIn(self.customer, invite_form.existing_partner_ids) self.assertEqual(invite_form.existing_text, 'The following customers have already received an invite: Caroline Customer.') @users('survey_manager') def test_survey_invite_authentication_nosignup(self): Answer = self.env['survey.user_input'] self.survey.write({'access_mode': 'public', 'users_login_required': True}) action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) with self.assertRaises(UserError): # do not allow to add customer (partner without user) invite_form.partner_ids.add(self.customer) invite_form.partner_ids.clear() invite_form.partner_ids.add(self.user_portal.partner_id) invite_form.partner_ids.add(self.user_emp.partner_id) with self.assertRaises(UserError): invite_form.emails = 'test1@example.com, Raoulette Vignolette <test2@example.com>' invite_form.emails = False invite = invite_form.save() invite.action_invite() answers = Answer.search([('survey_id', '=', self.survey.id)]) self.assertEqual(len(answers), 2) self.assertEqual( set(answers.mapped('email')), set([self.user_emp.email, self.user_portal.email])) self.assertEqual(answers.mapped('partner_id'), self.user_emp.partner_id | self.user_portal.partner_id) @users('survey_manager') def test_survey_invite_authentication_signup(self): self.env["ir.config_parameter"].sudo().set_param('auth_signup.invitation_scope', 'b2c') self.survey.invalidate_cache() Answer = self.env['survey.user_input'] self.survey.write({'access_mode': 'public', 'users_login_required': True}) action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) invite_form.partner_ids.add(self.customer) invite_form.partner_ids.add(self.user_portal.partner_id) invite_form.partner_ids.add(self.user_emp.partner_id) # TDE FIXME: not sure for emails in authentication + signup # invite_form.emails = 'test1@example.com, Raoulette Vignolette <test2@example.com>' invite = invite_form.save() invite.action_invite() answers = Answer.search([('survey_id', '=', self.survey.id)]) self.assertEqual(len(answers), 3) self.assertEqual( set(answers.mapped('email')), set([self.customer.email, self.user_emp.email, self.user_portal.email])) self.assertEqual(answers.mapped('partner_id'), self.customer | self.user_emp.partner_id | self.user_portal.partner_id) @users('survey_manager') def test_survey_invite_public(self): Answer = self.env['survey.user_input'] self.survey.write({'access_mode': 'public', 'users_login_required': False}) action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) invite_form.partner_ids.add(self.customer) invite_form.emails = 'test1@example.com, Raoulette Vignolette <test2@example.com>' invite = invite_form.save() invite.action_invite() answers = Answer.search([('survey_id', '=', self.survey.id)]) self.assertEqual(len(answers), 3) self.assertEqual( set(answers.mapped('email')), set(['test1@example.com', '"Raoulette Vignolette" <test2@example.com>', self.customer.email])) self.assertEqual(answers.mapped('partner_id'), self.customer) @users('survey_manager') def test_survey_invite_token(self): Answer = self.env['survey.user_input'] self.survey.write({'access_mode': 'token', 'users_login_required': False}) action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) invite_form.partner_ids.add(self.customer) invite_form.emails = 'test1@example.com, Raoulette Vignolette <test2@example.com>' invite = invite_form.save() invite.action_invite() answers = Answer.search([('survey_id', '=', self.survey.id)]) self.assertEqual(len(answers), 3) self.assertEqual( set(answers.mapped('email')), set(['test1@example.com', '"Raoulette Vignolette" <test2@example.com>', self.customer.email])) self.assertEqual(answers.mapped('partner_id'), self.customer) @users('survey_manager') def test_survey_invite_token_internal(self): Answer = self.env['survey.user_input'] self.survey.write({'access_mode': 'token', 'users_login_required': True}) action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) with self.assertRaises(UserError): # do not allow to add customer (partner without user) invite_form.partner_ids.add(self.customer) with self.assertRaises(UserError): # do not allow to add portal user invite_form.partner_ids.add(self.user_portal.partner_id) invite_form.partner_ids.clear() invite_form.partner_ids.add(self.user_emp.partner_id) with self.assertRaises(UserError): invite_form.emails = 'test1@example.com, Raoulette Vignolette <test2@example.com>' invite_form.emails = False invite = invite_form.save() invite.action_invite() answers = Answer.search([('survey_id', '=', self.survey.id)]) self.assertEqual(len(answers), 1) self.assertEqual( set(answers.mapped('email')), set([self.user_emp.email])) self.assertEqual(answers.mapped('partner_id'), self.user_emp.partner_id) def test_survey_invite_token_by_email_nosignup(self): """ Case: have multiples partners with the same email address If I set one email address, I expect one email to be sent """ first_partner = self.env['res.partner'].create({ 'name': 'Test 1', 'email': 'test@example.com', }) self.env['res.partner'].create({ 'name': 'Test 2', 'email': '"Raoul Poilvache" <TEST@example.COM>', }) self.survey.write({'access_mode': 'token', 'users_login_required': False}) action = self.survey.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context(action['context'])) invite_form.emails = 'test@example.com' invite = invite_form.save() invite.action_invite() answers = self.env['survey.user_input'].search([('survey_id', '=', self.survey.id)]) self.assertEqual(len(answers), 1) self.assertEqual(answers.partner_id.display_name, first_partner.display_name)
43.785408
10,202
12,813
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import re import werkzeug from odoo import api, fields, models, tools, _ from odoo.exceptions import UserError _logger = logging.getLogger(__name__) emails_split = re.compile(r"[;,\n\r]+") class SurveyInvite(models.TransientModel): _name = 'survey.invite' _inherit = 'mail.composer.mixin' _description = 'Survey Invitation Wizard' @api.model def _get_default_from(self): if self.env.user.email: return tools.formataddr((self.env.user.name, self.env.user.email)) raise UserError(_("Unable to post message, please configure the sender's email address.")) @api.model def _get_default_author(self): return self.env.user.partner_id # composer content attachment_ids = fields.Many2many( 'ir.attachment', 'survey_mail_compose_message_ir_attachments_rel', 'wizard_id', 'attachment_id', string='Attachments') # origin email_from = fields.Char('From', default=_get_default_from, help="Email address of the sender.") author_id = fields.Many2one( 'res.partner', 'Author', index=True, ondelete='set null', default=_get_default_author, help="Author of the message.") # recipients partner_ids = fields.Many2many( 'res.partner', 'survey_invite_partner_ids', 'invite_id', 'partner_id', string='Recipients', domain="""[ '|', (survey_users_can_signup, '=', 1), '|', (not survey_users_login_required, '=', 1), ('user_ids', '!=', False), ]""" ) existing_partner_ids = fields.Many2many( 'res.partner', compute='_compute_existing_partner_ids', readonly=True, store=False) emails = fields.Text(string='Additional emails', help="This list of emails of recipients will not be converted in contacts.\ Emails must be separated by commas, semicolons or newline.") existing_emails = fields.Text( 'Existing emails', compute='_compute_existing_emails', readonly=True, store=False) existing_mode = fields.Selection([ ('new', 'New invite'), ('resend', 'Resend invite')], string='Handle existing', default='resend', required=True) existing_text = fields.Text('Resend Comment', compute='_compute_existing_text', readonly=True, store=False) # technical info mail_server_id = fields.Many2one('ir.mail_server', 'Outgoing mail server') # survey survey_id = fields.Many2one('survey.survey', string='Survey', required=True) survey_start_url = fields.Char('Survey URL', compute='_compute_survey_start_url') survey_access_mode = fields.Selection(related="survey_id.access_mode", readonly=True) survey_users_login_required = fields.Boolean(related="survey_id.users_login_required", readonly=True) survey_users_can_signup = fields.Boolean(related='survey_id.users_can_signup') deadline = fields.Datetime(string="Answer deadline") @api.depends('partner_ids', 'survey_id') def _compute_existing_partner_ids(self): self.existing_partner_ids = list(set(self.survey_id.user_input_ids.partner_id.ids) & set(self.partner_ids.ids)) @api.depends('emails', 'survey_id') def _compute_existing_emails(self): emails = list(set(emails_split.split(self.emails or ""))) existing_emails = self.survey_id.mapped('user_input_ids.email') self.existing_emails = '\n'.join(email for email in emails if email in existing_emails) @api.depends('existing_partner_ids', 'existing_emails') def _compute_existing_text(self): existing_text = False if self.existing_partner_ids: existing_text = '%s: %s.' % ( _('The following customers have already received an invite'), ', '.join(self.mapped('existing_partner_ids.name')) ) if self.existing_emails: existing_text = '%s\n' % existing_text if existing_text else '' existing_text += '%s: %s.' % ( _('The following emails have already received an invite'), self.existing_emails ) self.existing_text = existing_text @api.depends('survey_id.access_token') def _compute_survey_start_url(self): for invite in self: invite.survey_start_url = werkzeug.urls.url_join(invite.survey_id.get_base_url(), invite.survey_id.get_start_url()) if invite.survey_id else False # Overrides of mail.composer.mixin @api.depends('survey_id') # fake trigger otherwise not computed in new mode def _compute_render_model(self): self.render_model = 'survey.user_input' @api.onchange('emails') def _onchange_emails(self): if self.emails and (self.survey_users_login_required and not self.survey_id.users_can_signup): raise UserError(_('This survey does not allow external people to participate. You should create user accounts or update survey access mode accordingly.')) if not self.emails: return valid, error = [], [] emails = list(set(emails_split.split(self.emails or ""))) for email in emails: email_check = tools.email_split_and_format(email) if not email_check: error.append(email) else: valid.extend(email_check) if error: raise UserError(_("Some emails you just entered are incorrect: %s") % (', '.join(error))) self.emails = '\n'.join(valid) @api.onchange('partner_ids') def _onchange_partner_ids(self): if self.survey_users_login_required and self.partner_ids: if not self.survey_id.users_can_signup: invalid_partners = self.env['res.partner'].search([ ('user_ids', '=', False), ('id', 'in', self.partner_ids.ids) ]) if invalid_partners: raise UserError(_( 'The following recipients have no user account: %s. You should create user accounts for them or allow external signup in configuration.', ', '.join(invalid_partners.mapped('name')) )) @api.model_create_multi def create(self, vals_list): for values in vals_list: if values.get('template_id') and not (values.get('body') or values.get('subject')): template = self.env['mail.template'].browse(values['template_id']) if not values.get('subject'): values['subject'] = template.subject if not values.get('body'): values['body'] = template.body_html return super().create(vals_list) @api.depends('template_id', 'partner_ids') def _compute_subject(self): for invite in self: langs = set(invite.partner_ids.mapped('lang')) - {False} if len(langs) == 1: invite = invite.with_context(lang=langs.pop()) super(SurveyInvite, invite)._compute_subject() @api.depends('template_id', 'partner_ids') def _compute_body(self): for invite in self: langs = set(invite.partner_ids.mapped('lang')) - {False} if len(langs) == 1: invite = invite.with_context(lang=langs.pop()) super(SurveyInvite, invite)._compute_body() # ------------------------------------------------------ # Wizard validation and send # ------------------------------------------------------ def _prepare_answers(self, partners, emails): answers = self.env['survey.user_input'] existing_answers = self.env['survey.user_input'].search([ '&', ('survey_id', '=', self.survey_id.id), '|', ('partner_id', 'in', partners.ids), ('email', 'in', emails) ]) partners_done = self.env['res.partner'] emails_done = [] if existing_answers: if self.existing_mode == 'resend': partners_done = existing_answers.mapped('partner_id') emails_done = existing_answers.mapped('email') # only add the last answer for each user of each type (partner_id & email) # to have only one mail sent per user for partner_done in partners_done: answers |= next(existing_answer for existing_answer in existing_answers.sorted(lambda answer: answer.create_date, reverse=True) if existing_answer.partner_id == partner_done) for email_done in emails_done: answers |= next(existing_answer for existing_answer in existing_answers.sorted(lambda answer: answer.create_date, reverse=True) if existing_answer.email == email_done) for new_partner in partners - partners_done: answers |= self.survey_id._create_answer(partner=new_partner, check_attempts=False, **self._get_answers_values()) for new_email in [email for email in emails if email not in emails_done]: answers |= self.survey_id._create_answer(email=new_email, check_attempts=False, **self._get_answers_values()) return answers def _get_answers_values(self): return { 'deadline': self.deadline, } def _send_mail(self, answer): """ Create mail specific for recipient containing notably its access token """ subject = self._render_field('subject', answer.ids, options={'render_safe': True})[answer.id] body = self._render_field('body', answer.ids, post_process=True)[answer.id] # post the message mail_values = { 'email_from': self.email_from, 'author_id': self.author_id.id, 'model': None, 'res_id': None, 'subject': subject, 'body_html': body, 'attachment_ids': [(4, att.id) for att in self.attachment_ids], 'auto_delete': True, } if answer.partner_id: mail_values['recipient_ids'] = [(4, answer.partner_id.id)] else: mail_values['email_to'] = answer.email # optional support of notif_layout in context notif_layout = self.env.context.get('notif_layout', self.env.context.get('custom_layout')) if notif_layout: try: template = self.env.ref(notif_layout, raise_if_not_found=True) except ValueError: _logger.warning('QWeb template %s not found when sending survey mails. Sending without layouting.' % (notif_layout)) else: template_ctx = { 'message': self.env['mail.message'].sudo().new(dict(body=mail_values['body_html'], record_name=self.survey_id.title)), 'model_description': self.env['ir.model']._get('survey.survey').display_name, 'company': self.env.company, } body = template._render(template_ctx, engine='ir.qweb', minimal_qcontext=True) mail_values['body_html'] = self.env['mail.render.mixin']._replace_local_links(body) return self.env['mail.mail'].sudo().create(mail_values) def action_invite(self): """ Process the wizard content and proceed with sending the related email(s), rendering any template patterns on the fly if needed """ self.ensure_one() Partner = self.env['res.partner'] # compute partners and emails, try to find partners for given emails valid_partners = self.partner_ids langs = set(valid_partners.mapped('lang')) - {False} if len(langs) == 1: self = self.with_context(lang=langs.pop()) valid_emails = [] for email in emails_split.split(self.emails or ''): partner = False email_normalized = tools.email_normalize(email) if email_normalized: limit = None if self.survey_users_login_required else 1 partner = Partner.search([('email_normalized', '=', email_normalized)], limit=limit) if partner: valid_partners |= partner else: email_formatted = tools.email_split_and_format(email) if email_formatted: valid_emails.extend(email_formatted) if not valid_partners and not valid_emails: raise UserError(_("Please enter at least one valid recipient.")) answers = self._prepare_answers(valid_partners, valid_emails) for answer in answers: self._send_mail(answer) return {'type': 'ir.actions.act_window_close'}
45.760714
12,813
602
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class GamificationBadge(models.Model): _inherit = 'gamification.badge' survey_ids = fields.One2many('survey.survey', 'certification_badge_id', 'Survey Ids') survey_id = fields.Many2one('survey.survey', 'Survey', compute='_compute_survey_id', store=True) @api.depends('survey_ids.certification_badge_id') def _compute_survey_id(self): for badge in self: badge.survey_id = badge.survey_ids[0] if badge.survey_ids else None
37.625
602
56,305
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import random import uuid import werkzeug from odoo import api, exceptions, fields, models, _ from odoo.exceptions import AccessError, UserError from odoo.osv import expression from odoo.tools import is_html_empty class Survey(models.Model): """ Settings for a multi-page/multi-question survey. Each survey can have one or more attached pages and each page can display one or more questions. """ _name = 'survey.survey' _description = 'Survey' _rec_name = 'title' _inherit = ['mail.thread', 'mail.activity.mixin'] def _get_default_access_token(self): return str(uuid.uuid4()) def _get_default_session_code(self): """ Attempt to generate a session code for our survey. The method will first try to generate 20 codes with 4 digits each and check if any are colliding. If we have at least one non-colliding code, we use it. If all 20 generated codes are colliding, we try with 20 codes of 5 digits, then 6, ... up to 10 digits. """ for digits_count in range(4, 10): range_lower_bound = 1 * (10 ** (digits_count - 1)) range_upper_bound = (range_lower_bound * 10) - 1 code_candidates = set([str(random.randint(range_lower_bound, range_upper_bound)) for i in range(20)]) colliding_codes = self.sudo().search_read( [('session_code', 'in', list(code_candidates))], ['session_code'] ) code_candidates -= set([colliding_code['session_code'] for colliding_code in colliding_codes]) if code_candidates: return list(code_candidates)[0] return False # could not generate a code # description title = fields.Char('Survey Title', required=True, translate=True) color = fields.Integer('Color Index', default=0) description = fields.Html( "Description", translate=True, sanitize=False, # TDE FIXME: find a way to authorize videos help="The description will be displayed on the home page of the survey. You can use this to give the purpose and guidelines to your candidates before they start it.") description_done = fields.Html( "End Message", translate=True, help="This message will be displayed when survey is completed") background_image = fields.Binary("Background Image") active = fields.Boolean("Active", default=True) user_id = fields.Many2one('res.users', string='Responsible', tracking=True, default=lambda self: self.env.user) # questions question_and_page_ids = fields.One2many('survey.question', 'survey_id', string='Sections and Questions', copy=True) page_ids = fields.One2many('survey.question', string='Pages', compute="_compute_page_and_question_ids") question_ids = fields.One2many('survey.question', string='Questions', compute="_compute_page_and_question_ids") questions_layout = fields.Selection([ ('one_page', 'One page with all the questions'), ('page_per_section', 'One page per section'), ('page_per_question', 'One page per question')], string="Layout", required=True, default='one_page') questions_selection = fields.Selection([ ('all', 'All questions'), ('random', 'Randomized per section')], string="Selection", required=True, default='all', help="If randomized is selected, you can configure the number of random questions by section. This mode is ignored in live session.") progression_mode = fields.Selection([ ('percent', 'Percentage'), ('number', 'Number')], string='Progression Mode', default='percent', help="If Number is selected, it will display the number of questions answered on the total number of question to answer.") # attendees user_input_ids = fields.One2many('survey.user_input', 'survey_id', string='User responses', readonly=True, groups='survey.group_survey_user') # security / access access_mode = fields.Selection([ ('public', 'Anyone with the link'), ('token', 'Invited people only')], string='Access Mode', default='public', required=True) access_token = fields.Char('Access Token', default=lambda self: self._get_default_access_token(), copy=False) users_login_required = fields.Boolean('Login Required', help="If checked, users have to login before answering even with a valid token.") users_can_go_back = fields.Boolean('Users can go back', help="If checked, users can go back to previous pages.") users_can_signup = fields.Boolean('Users can signup', compute='_compute_users_can_signup') # statistics answer_count = fields.Integer("Registered", compute="_compute_survey_statistic") answer_done_count = fields.Integer("Attempts", compute="_compute_survey_statistic") answer_score_avg = fields.Float("Avg Score %", compute="_compute_survey_statistic") answer_duration_avg = fields.Float("Average Duration", compute="_compute_answer_duration_avg", help="Average duration of the survey (in hours)") success_count = fields.Integer("Success", compute="_compute_survey_statistic") success_ratio = fields.Integer("Success Ratio", compute="_compute_survey_statistic") # scoring scoring_type = fields.Selection([ ('no_scoring', 'No scoring'), ('scoring_with_answers', 'Scoring with answers at the end'), ('scoring_without_answers', 'Scoring without answers at the end')], string="Scoring", required=True, default='no_scoring') scoring_success_min = fields.Float('Success %', default=80.0) # attendees context: attempts and time limitation is_attempts_limited = fields.Boolean('Limited number of attempts', help="Check this option if you want to limit the number of attempts per user", compute="_compute_is_attempts_limited", store=True, readonly=False) attempts_limit = fields.Integer('Number of attempts', default=1) is_time_limited = fields.Boolean('The survey is limited in time') time_limit = fields.Float("Time limit (minutes)", default=10) # certification certification = fields.Boolean('Is a Certification', compute='_compute_certification', readonly=False, store=True) certification_mail_template_id = fields.Many2one( 'mail.template', 'Email Template', domain="[('model', '=', 'survey.user_input')]", help="Automated email sent to the user when he succeeds the certification, containing his certification document.") certification_report_layout = fields.Selection([ ('modern_purple', 'Modern Purple'), ('modern_blue', 'Modern Blue'), ('modern_gold', 'Modern Gold'), ('classic_purple', 'Classic Purple'), ('classic_blue', 'Classic Blue'), ('classic_gold', 'Classic Gold')], string='Certification template', default='modern_purple') # Certification badge # certification_badge_id_dummy is used to have two different behaviours in the form view : # - If the certification badge is not set, show certification_badge_id and only display create option in the m2o # - If the certification badge is set, show certification_badge_id_dummy in 'no create' mode. # So it can be edited but not removed or replaced. certification_give_badge = fields.Boolean('Give Badge', compute='_compute_certification_give_badge', readonly=False, store=True, copy=False) certification_badge_id = fields.Many2one('gamification.badge', 'Certification Badge', copy=False) certification_badge_id_dummy = fields.Many2one(related='certification_badge_id', string='Certification Badge ') # live sessions session_state = fields.Selection([ ('ready', 'Ready'), ('in_progress', 'In Progress'), ], string="Session State", copy=False) session_code = fields.Char('Session Code', default=lambda self: self._get_default_session_code(), copy=False, help="This code will be used by your attendees to reach your session. Feel free to customize it however you like!") session_link = fields.Char('Session Link', compute='_compute_session_link') # live sessions - current question fields session_question_id = fields.Many2one('survey.question', string="Current Question", copy=False, help="The current question of the survey session.") session_start_time = fields.Datetime("Current Session Start Time", copy=False) session_question_start_time = fields.Datetime("Current Question Start Time", copy=False, help="The time at which the current question has started, used to handle the timer for attendees.") session_answer_count = fields.Integer("Answers Count", compute='_compute_session_answer_count') session_question_answer_count = fields.Integer("Question Answers Count", compute='_compute_session_question_answer_count') # live sessions - settings session_show_leaderboard = fields.Boolean("Show Session Leaderboard", compute='_compute_session_show_leaderboard', help="Whether or not we want to show the attendees leaderboard for this survey.") session_speed_rating = fields.Boolean("Reward quick answers", help="Attendees get more points if they answer quickly") # conditional questions management has_conditional_questions = fields.Boolean("Contains conditional questions", compute="_compute_has_conditional_questions") _sql_constraints = [ ('access_token_unique', 'unique(access_token)', 'Access token should be unique'), ('session_code_unique', 'unique(session_code)', 'Session code should be unique'), ('certification_check', "CHECK( scoring_type!='no_scoring' OR certification=False )", 'You can only create certifications for surveys that have a scoring mechanism.'), ('scoring_success_min_check', "CHECK( scoring_success_min IS NULL OR (scoring_success_min>=0 AND scoring_success_min<=100) )", 'The percentage of success has to be defined between 0 and 100.'), ('time_limit_check', "CHECK( (is_time_limited=False) OR (time_limit is not null AND time_limit > 0) )", 'The time limit needs to be a positive number if the survey is time limited.'), ('attempts_limit_check', "CHECK( (is_attempts_limited=False) OR (attempts_limit is not null AND attempts_limit > 0) )", 'The attempts limit needs to be a positive number if the survey has a limited number of attempts.'), ('badge_uniq', 'unique (certification_badge_id)', "The badge for each survey should be unique!"), ] def _compute_users_can_signup(self): signup_allowed = self.env['res.users'].sudo()._get_signup_invitation_scope() == 'b2c' for survey in self: survey.users_can_signup = signup_allowed @api.depends('user_input_ids.state', 'user_input_ids.test_entry', 'user_input_ids.scoring_percentage', 'user_input_ids.scoring_success') def _compute_survey_statistic(self): default_vals = { 'answer_count': 0, 'answer_done_count': 0, 'success_count': 0, 'answer_score_avg': 0.0, 'success_ratio': 0.0 } stat = dict((cid, dict(default_vals, answer_score_avg_total=0.0)) for cid in self.ids) UserInput = self.env['survey.user_input'] base_domain = ['&', ('survey_id', 'in', self.ids), ('test_entry', '!=', True)] read_group_res = UserInput.read_group(base_domain, ['survey_id', 'state'], ['survey_id', 'state', 'scoring_percentage', 'scoring_success'], lazy=False) for item in read_group_res: stat[item['survey_id'][0]]['answer_count'] += item['__count'] stat[item['survey_id'][0]]['answer_score_avg_total'] += item['scoring_percentage'] if item['state'] == 'done': stat[item['survey_id'][0]]['answer_done_count'] += item['__count'] if item['scoring_success']: stat[item['survey_id'][0]]['success_count'] += item['__count'] for survey_stats in stat.values(): avg_total = survey_stats.pop('answer_score_avg_total') survey_stats['answer_score_avg'] = avg_total / (survey_stats['answer_done_count'] or 1) survey_stats['success_ratio'] = (survey_stats['success_count'] / (survey_stats['answer_done_count'] or 1.0))*100 for survey in self: survey.update(stat.get(survey._origin.id, default_vals)) @api.depends('user_input_ids.survey_id', 'user_input_ids.start_datetime', 'user_input_ids.end_datetime') def _compute_answer_duration_avg(self): result_per_survey_id = {} if self.ids: self.env.cr.execute( """SELECT survey_id, avg((extract(epoch FROM end_datetime)) - (extract (epoch FROM start_datetime))) FROM survey_user_input WHERE survey_id = any(%s) AND state = 'done' AND end_datetime IS NOT NULL AND start_datetime IS NOT NULL GROUP BY survey_id""", [self.ids] ) result_per_survey_id = dict(self.env.cr.fetchall()) for survey in self: # as avg returns None if nothing found, set 0 if it's the case. survey.answer_duration_avg = (result_per_survey_id.get(survey.id) or 0) / 3600 @api.depends('question_and_page_ids') def _compute_page_and_question_ids(self): for survey in self: survey.page_ids = survey.question_and_page_ids.filtered(lambda question: question.is_page) survey.question_ids = survey.question_and_page_ids - survey.page_ids @api.depends('question_and_page_ids.is_conditional', 'users_login_required', 'access_mode') def _compute_is_attempts_limited(self): for survey in self: if not survey.is_attempts_limited or \ (survey.access_mode == 'public' and not survey.users_login_required) or \ any(question.is_conditional for question in survey.question_and_page_ids): survey.is_attempts_limited = False @api.depends('session_start_time', 'user_input_ids') def _compute_session_answer_count(self): """ We have to loop since our result is dependent of the survey.session_start_time. This field is currently used to display the count about a single survey, in the context of sessions, so it should not matter too much. """ for survey in self: answer_count = 0 input_count = self.env['survey.user_input'].read_group( [('survey_id', '=', survey.id), ('is_session_answer', '=', True), ('state', '!=', 'done'), ('create_date', '>=', survey.session_start_time)], ['create_uid:count'], ['survey_id'], ) if input_count: answer_count = input_count[0].get('create_uid', 0) survey.session_answer_count = answer_count @api.depends('session_question_id', 'session_start_time', 'user_input_ids.user_input_line_ids') def _compute_session_question_answer_count(self): """ We have to loop since our result is dependent of the survey.session_question_id and the survey.session_start_time. This field is currently used to display the count about a single survey, in the context of sessions, so it should not matter too much. """ for survey in self: answer_count = 0 input_line_count = self.env['survey.user_input.line'].read_group( [('question_id', '=', survey.session_question_id.id), ('survey_id', '=', survey.id), ('create_date', '>=', survey.session_start_time)], ['user_input_id:count_distinct'], ['question_id'], ) if input_line_count: answer_count = input_line_count[0].get('user_input_id', 0) survey.session_question_answer_count = answer_count @api.depends('session_code') def _compute_session_link(self): for survey in self: if survey.session_code: survey.session_link = werkzeug.urls.url_join( survey.get_base_url(), '/s/%s' % survey.session_code) else: survey.session_link = werkzeug.urls.url_join( survey.get_base_url(), survey.get_start_url()) @api.depends('scoring_type', 'question_and_page_ids.save_as_nickname') def _compute_session_show_leaderboard(self): for survey in self: survey.session_show_leaderboard = survey.scoring_type != 'no_scoring' and \ any(question.save_as_nickname for question in survey.question_and_page_ids) @api.depends('question_and_page_ids.is_conditional') def _compute_has_conditional_questions(self): for survey in self: survey.has_conditional_questions = any(question.is_conditional for question in survey.question_and_page_ids) @api.depends('scoring_type') def _compute_certification(self): for survey in self: if not survey.certification or survey.scoring_type == 'no_scoring': survey.certification = False @api.depends('users_login_required', 'certification') def _compute_certification_give_badge(self): for survey in self: if not survey.certification_give_badge or \ not survey.users_login_required or \ not survey.certification: survey.certification_give_badge = False # ------------------------------------------------------------ # CRUD # ------------------------------------------------------------ @api.model def create(self, vals): survey = super(Survey, self).create(vals) if vals.get('certification_give_badge'): survey.sudo()._create_certification_badge_trigger() return survey def write(self, vals): result = super(Survey, self).write(vals) if 'certification_give_badge' in vals: return self.sudo()._handle_certification_badges(vals) return result def copy_data(self, default=None): new_defaults = {'title': _("%s (copy)") % (self.title)} default = dict(new_defaults, **(default or {})) return super(Survey, self).copy_data(default) def toggle_active(self): super(Survey, self).toggle_active() activated = self.filtered(lambda survey: survey.active) activated.mapped('certification_badge_id').action_unarchive() (self - activated).mapped('certification_badge_id').action_archive() # ------------------------------------------------------------ # ANSWER MANAGEMENT # ------------------------------------------------------------ def _create_answer(self, user=False, partner=False, email=False, test_entry=False, check_attempts=True, **additional_vals): """ Main entry point to get a token back or create a new one. This method does check for current user access in order to explicitely validate security. :param user: target user asking for a token; it might be void or a public user in which case an email is welcomed; :param email: email of the person asking the token is no user exists; """ self.check_access_rights('read') self.check_access_rule('read') user_inputs = self.env['survey.user_input'] for survey in self: if partner and not user and partner.user_ids: user = partner.user_ids[0] invite_token = additional_vals.pop('invite_token', False) survey._check_answer_creation(user, partner, email, test_entry=test_entry, check_attempts=check_attempts, invite_token=invite_token) answer_vals = { 'survey_id': survey.id, 'test_entry': test_entry, 'is_session_answer': survey.session_state in ['ready', 'in_progress'] } if survey.session_state == 'in_progress': # if the session is already in progress, the answer skips the 'new' state answer_vals.update({ 'state': 'in_progress', 'start_datetime': fields.Datetime.now(), }) if user and not user._is_public(): answer_vals['partner_id'] = user.partner_id.id answer_vals['email'] = user.email answer_vals['nickname'] = user.name elif partner: answer_vals['partner_id'] = partner.id answer_vals['email'] = partner.email answer_vals['nickname'] = partner.name else: answer_vals['email'] = email answer_vals['nickname'] = email if invite_token: answer_vals['invite_token'] = invite_token elif survey.is_attempts_limited and survey.access_mode != 'public': # attempts limited: create a new invite_token # exception made for 'public' access_mode since the attempts pool is global because answers are # created every time the user lands on '/start' answer_vals['invite_token'] = self.env['survey.user_input']._generate_invite_token() answer_vals.update(additional_vals) user_inputs += user_inputs.create(answer_vals) for question in self.mapped('question_ids').filtered( lambda q: q.question_type == 'char_box' and (q.save_as_email or q.save_as_nickname)): for user_input in user_inputs: if question.save_as_email and user_input.email: user_input.save_lines(question, user_input.email) if question.save_as_nickname and user_input.nickname: user_input.save_lines(question, user_input.nickname) return user_inputs def _check_answer_creation(self, user, partner, email, test_entry=False, check_attempts=True, invite_token=False): """ Ensure conditions to create new tokens are met. """ self.ensure_one() if test_entry: # the current user must have the access rights to survey if not user.has_group('survey.group_survey_user'): raise exceptions.UserError(_('Creating test token is not allowed for you.')) else: if not self.active: raise exceptions.UserError(_('Creating token for closed/archived surveys is not allowed.')) if self.access_mode == 'authentication': # signup possible -> should have at least a partner to create an account if self.users_can_signup and not user and not partner: raise exceptions.UserError(_('Creating token for external people is not allowed for surveys requesting authentication.')) # no signup possible -> should be a not public user (employee or portal users) if not self.users_can_signup and (not user or user._is_public()): raise exceptions.UserError(_('Creating token for external people is not allowed for surveys requesting authentication.')) if self.access_mode == 'internal' and (not user or not user.has_group('base.group_user')): raise exceptions.UserError(_('Creating token for anybody else than employees is not allowed for internal surveys.')) if check_attempts and not self._has_attempts_left(partner or (user and user.partner_id), email, invite_token): raise exceptions.UserError(_('No attempts left.')) def _prepare_user_input_predefined_questions(self): """ Will generate the questions for a randomized survey. It uses the random_questions_count of every sections of the survey to pick a random number of questions and returns the merged recordset """ self.ensure_one() questions = self.env['survey.question'] # First append questions without page for question in self.question_ids: if not question.page_id: questions |= question # Then, questions in sections for page in self.page_ids: if self.questions_selection == 'all': questions |= page.question_ids else: if page.random_questions_count > 0 and len(page.question_ids) > page.random_questions_count: questions = questions.concat(*random.sample(page.question_ids, page.random_questions_count)) else: questions |= page.question_ids return questions def _can_go_back(self, answer, page_or_question): """ Check if the user can go back to the previous question/page for the currently viewed question/page. Back button needs to be configured on survey and, depending on the layout: - In 'page_per_section', we can go back if we're not on the first page - In 'page_per_question', we can go back if: - It is not a session answer (doesn't make sense to go back in session context) - We are not on the first question - The survey does not have pages OR this is not the first page of the survey (pages are displayed in 'page_per_question' layout when they have a description, see PR#44271) """ self.ensure_one() if self.users_can_go_back and answer.state == 'in_progress': if self.questions_layout == 'page_per_section' and page_or_question != self.page_ids[0]: return True elif self.questions_layout == 'page_per_question' and \ not answer.is_session_answer and \ page_or_question != answer.predefined_question_ids[0] \ and (not self.page_ids or page_or_question != self.page_ids[0]): return True return False def _has_attempts_left(self, partner, email, invite_token): self.ensure_one() if (self.access_mode != 'public' or self.users_login_required) and self.is_attempts_limited: return self._get_number_of_attempts_lefts(partner, email, invite_token) > 0 return True def _get_number_of_attempts_lefts(self, partner, email, invite_token): """ Returns the number of attempts left. """ self.ensure_one() domain = [ ('survey_id', '=', self.id), ('test_entry', '=', False), ('state', '=', 'done') ] if partner: domain = expression.AND([domain, [('partner_id', '=', partner.id)]]) else: domain = expression.AND([domain, [('email', '=', email)]]) if invite_token: domain = expression.AND([domain, [('invite_token', '=', invite_token)]]) return self.attempts_limit - self.env['survey.user_input'].search_count(domain) # ------------------------------------------------------------ # QUESTIONS MANAGEMENT # ------------------------------------------------------------ @api.model def _get_pages_or_questions(self, user_input): """ Returns the pages or questions (depending on the layout) that will be shown to the user taking the survey. In 'page_per_question' layout, we also want to show pages that have a description. """ result = self.env['survey.question'] if self.questions_layout == 'page_per_section': result = self.page_ids elif self.questions_layout == 'page_per_question': if self.questions_selection == 'random' and not self.session_state: result = user_input.predefined_question_ids else: result = self._get_pages_and_questions_to_show() return result def _get_pages_and_questions_to_show(self): """ :return: survey.question recordset excluding invalid conditional questions and pages without description """ self.ensure_one() invalid_questions = self.env['survey.question'] questions_and_valid_pages = self.question_and_page_ids.filtered( lambda question: not question.is_page or not is_html_empty(question.description)) for question in questions_and_valid_pages.filtered(lambda q: q.is_conditional).sorted(): trigger = question.triggering_question_id if (trigger in invalid_questions or trigger.is_page or trigger.question_type not in ['simple_choice', 'multiple_choice'] or not trigger.suggested_answer_ids or trigger.sequence > question.sequence or (trigger.sequence == question.sequence and trigger.id > question.id)): invalid_questions |= question return questions_and_valid_pages - invalid_questions def _get_next_page_or_question(self, user_input, page_or_question_id, go_back=False): """ Generalized logic to retrieve the next question or page to show on the survey. It's based on the page_or_question_id parameter, that is usually the currently displayed question/page. There is a special case when the survey is configured with conditional questions: - for "page_per_question" layout, the next question to display depends on the selected answers and the questions 'hierarchy'. - for "page_per_section" layout, before returning the result, we check that it contains at least a question (all section questions could be disabled based on previously selected answers) The whole logic is inverted if "go_back" is passed as True. As pages with description are considered as potential question to display, we show the page if it contains at least one active question or a description. :param user_input: user's answers :param page_or_question_id: current page or question id :param go_back: reverse the logic and get the PREVIOUS question/page :return: next or previous question/page """ survey = user_input.survey_id pages_or_questions = survey._get_pages_or_questions(user_input) Question = self.env['survey.question'] # Get Next if not go_back: if not pages_or_questions: return Question # First page if page_or_question_id == 0: return pages_or_questions[0] current_page_index = pages_or_questions.ids.index(page_or_question_id) # Get previous and we are on first page OR Get Next and we are on last page if (go_back and current_page_index == 0) or (not go_back and current_page_index == len(pages_or_questions) - 1): return Question # Conditional Questions Management triggering_answer_by_question, triggered_questions_by_answer, selected_answers = user_input._get_conditional_values() inactive_questions = user_input._get_inactive_conditional_questions() if survey.questions_layout == 'page_per_question': question_candidates = pages_or_questions[0:current_page_index] if go_back \ else pages_or_questions[current_page_index + 1:] for question in question_candidates.sorted(reverse=go_back): # pages with description are potential questions to display (are part of question_candidates) if question.is_page: contains_active_question = any(sub_question not in inactive_questions for sub_question in question.question_ids) is_description_section = not question.question_ids and not is_html_empty(question.description) if contains_active_question or is_description_section: return question else: triggering_answer = triggering_answer_by_question.get(question) if not triggering_answer or triggering_answer in selected_answers: # question is visible because not conditioned or conditioned by a selected answer return question elif survey.questions_layout == 'page_per_section': section_candidates = pages_or_questions[0:current_page_index] if go_back \ else pages_or_questions[current_page_index + 1:] for section in section_candidates.sorted(reverse=go_back): contains_active_question = any(question not in inactive_questions for question in section.question_ids) is_description_section = not section.question_ids and not is_html_empty(section.description) if contains_active_question or is_description_section: return section return Question def _is_first_page_or_question(self, page_or_question): """ This method checks if the given question or page is the first one to display. If the first section of the survey as a description, this will be the first screen to display. else, the first question will be the first screen to be displayed. This methods is used for survey session management where the host should not be able to go back on the first page or question.""" first_section_has_description = self.page_ids and not is_html_empty(self.page_ids[0].description) is_first_page_or_question = (first_section_has_description and page_or_question == self.page_ids[0]) or \ (not first_section_has_description and page_or_question == self.question_ids[0]) return is_first_page_or_question def _is_last_page_or_question(self, user_input, page_or_question): """ This method checks if the given question or page is the last one. This includes conditional questions configuration. If the given question is normally not the last one but every following questions are inactive due to conditional questions configurations (and user choices), the given question will be the last one, except if the given question is conditioning at least one of the following questions. For section, we check in each following section if there is an active question. If yes, the given page is not the last one. """ pages_or_questions = self._get_pages_or_questions(user_input) current_page_index = pages_or_questions.ids.index(page_or_question.id) next_page_or_question_candidates = pages_or_questions[current_page_index + 1:] if next_page_or_question_candidates: inactive_questions = user_input._get_inactive_conditional_questions() triggering_answer_by_question, triggered_questions_by_answer, selected_answers = user_input._get_conditional_values() if self.questions_layout == 'page_per_question': next_active_question = any(next_question not in inactive_questions for next_question in next_page_or_question_candidates) is_triggering_question = any(triggering_answer in triggered_questions_by_answer.keys() for triggering_answer in page_or_question.suggested_answer_ids) return not(next_active_question or is_triggering_question) elif self.questions_layout == 'page_per_section': is_triggering_section = False for question in page_or_question.question_ids: if any(triggering_answer in triggered_questions_by_answer.keys() for triggering_answer in question.suggested_answer_ids): is_triggering_section = True break next_active_question = False for section in next_page_or_question_candidates: next_active_question = any(next_question not in inactive_questions for next_question in section.question_ids) if next_active_question: break return not(next_active_question or is_triggering_section) return True def _get_survey_questions(self, answer=None, page_id=None, question_id=None): """ Returns a tuple containing: the survey question and the passed question_id / page_id based on the question_layout and the fact that it's a session or not. Breakdown of use cases: - We are currently running a session We return the current session question and it's id - The layout is page_per_section We return the questions for that page and the passed page_id - The layout is page_per_question We return the question for the passed question_id and the question_id - The layout is one_page We return all the questions of the survey and None In addition, we cross the returned questions with the answer.predefined_question_ids, that allows to handle the randomization of questions. """ questions, page_or_question_id = None, None if answer and answer.is_session_answer: return self.session_question_id, self.session_question_id.id if self.questions_layout == 'page_per_section': if not page_id: raise ValueError("Page id is needed for question layout 'page_per_section'") page_id = int(page_id) questions = self.env['survey.question'].sudo().search([('survey_id', '=', self.id), ('page_id', '=', page_id)]) page_or_question_id = page_id elif self.questions_layout == 'page_per_question': if not question_id: raise ValueError("Question id is needed for question layout 'page_per_question'") question_id = int(question_id) questions = self.env['survey.question'].sudo().browse(question_id) page_or_question_id = question_id else: questions = self.question_ids # we need the intersection of the questions of this page AND the questions prepared for that user_input # (because randomized surveys do not use all the questions of every page) if answer: questions = questions & answer.predefined_question_ids return questions, page_or_question_id # ------------------------------------------------------------ # CONDITIONAL QUESTIONS MANAGEMENT # ------------------------------------------------------------ def _get_conditional_maps(self): triggering_answer_by_question = {} triggered_questions_by_answer = {} for question in self.question_ids: triggering_answer_by_question[question] = question.is_conditional and question.triggering_answer_id if question.is_conditional: if question.triggering_answer_id in triggered_questions_by_answer: triggered_questions_by_answer[question.triggering_answer_id] |= question else: triggered_questions_by_answer[question.triggering_answer_id] = question return triggering_answer_by_question, triggered_questions_by_answer # ------------------------------------------------------------ # SESSIONS MANAGEMENT # ------------------------------------------------------------ def _session_open(self): """ The session start is sudo'ed to allow survey user to manage sessions of surveys they do not own. We flush after writing to make sure it's updated before bus takes over. """ if self.env.user.has_group('survey.group_survey_user'): self.sudo().write({'session_state': 'in_progress'}) self.sudo().flush(['session_state']) def _get_session_next_question(self, go_back): self.ensure_one() if not self.question_ids or not self.env.user.has_group('survey.group_survey_user'): return most_voted_answers = self._get_session_most_voted_answers() return self._get_next_page_or_question( most_voted_answers, self.session_question_id.id if self.session_question_id else 0, go_back=go_back) def _get_session_most_voted_answers(self): """ In sessions of survey that has conditional questions, as the survey is passed at the same time by many users, we need to extract the most chosen answers, to determine the next questions to display. """ # get user_inputs from current session current_user_inputs = self.user_input_ids.filtered(lambda input: input.create_date > self.session_start_time) current_user_input_lines = current_user_inputs.mapped('user_input_line_ids').filtered(lambda answer: answer.suggested_answer_id) # count the number of vote per answer votes_by_answer = dict.fromkeys(current_user_input_lines.mapped('suggested_answer_id'), 0) for answer in current_user_input_lines: votes_by_answer[answer.suggested_answer_id] += 1 # extract most voted answer for each question most_voted_answer_by_questions = dict.fromkeys(current_user_input_lines.mapped('question_id')) for question in most_voted_answer_by_questions.keys(): for answer in votes_by_answer.keys(): if answer.question_id != question: continue most_voted_answer = most_voted_answer_by_questions[question] if not most_voted_answer or votes_by_answer[most_voted_answer] < votes_by_answer[answer]: most_voted_answer_by_questions[question] = answer # return a fake 'audience' user_input fake_user_input = self.env['survey.user_input'].new({ 'survey_id': self.id, 'predefined_question_ids': [(6, 0, self._prepare_user_input_predefined_questions().ids)] }) fake_user_input_lines = self.env['survey.user_input.line'] for question, answer in most_voted_answer_by_questions.items(): fake_user_input_lines |= self.env['survey.user_input.line'].new({ 'question_id': question.id, 'suggested_answer_id': answer.id, 'survey_id': self.id, 'user_input_id': fake_user_input.id }) return fake_user_input def _prepare_leaderboard_values(self): """" The leaderboard is descending and takes the total of the attendee points minus the current question score. We need both the total and the current question points to be able to show the attendees leaderboard and shift their position based on the score they have on the current question. This prepares a structure containing all the necessary data for the animations done on the frontend side. The leaderboard is sorted based on attendees score *before* the current question. The frontend will shift positions around accordingly. """ self.ensure_one() leaderboard = self.env['survey.user_input'].search_read([ ('survey_id', '=', self.id), ('create_date', '>=', self.session_start_time) ], [ 'id', 'nickname', 'scoring_total', ], limit=15, order="scoring_total desc") if leaderboard and self.session_state == 'in_progress' and \ any(answer.answer_score for answer in self.session_question_id.suggested_answer_ids): question_scores = {} input_lines = self.env['survey.user_input.line'].search_read( [('user_input_id', 'in', [score['id'] for score in leaderboard]), ('question_id', '=', self.session_question_id.id)], ['user_input_id', 'answer_score']) for input_line in input_lines: question_scores[input_line['user_input_id'][0]] = \ question_scores.get(input_line['user_input_id'][0], 0) + input_line['answer_score'] score_position = 0 for leaderboard_item in leaderboard: question_score = question_scores.get(leaderboard_item['id'], 0) leaderboard_item.update({ 'updated_score': leaderboard_item['scoring_total'], 'scoring_total': leaderboard_item['scoring_total'] - question_score, 'leaderboard_position': score_position, 'max_question_score': sum( score for score in self.session_question_id.suggested_answer_ids.mapped('answer_score') if score > 0 ) or 1, 'question_score': question_score }) score_position += 1 leaderboard = sorted( leaderboard, key=lambda score: score['scoring_total'], reverse=True) return leaderboard # ------------------------------------------------------------ # ACTIONS # ------------------------------------------------------------ def action_send_survey(self): """ Open a window to compose an email, pre-filled with the survey message """ # Ensure that this survey has at least one question. if not self.question_ids: raise UserError(_('You cannot send an invitation for a survey that has no questions.')) # Ensure that this survey has at least one section with question(s), if question layout is 'One page per section'. if self.questions_layout == 'page_per_section': if not self.page_ids: raise UserError(_('You cannot send an invitation for a "One page per section" survey if the survey has no sections.')) if not self.page_ids.mapped('question_ids'): raise UserError(_('You cannot send an invitation for a "One page per section" survey if the survey only contains empty sections.')) if not self.active: raise exceptions.UserError(_("You cannot send invitations for closed surveys.")) template = self.env.ref('survey.mail_template_user_input_invite', raise_if_not_found=False) local_context = dict( self.env.context, default_survey_id=self.id, default_use_template=bool(template), default_template_id=template and template.id or False, notif_layout='mail.mail_notification_light', ) return { 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'survey.invite', 'target': 'new', 'context': local_context, } def action_start_survey(self, answer=None): """ Open the website page with the survey form """ self.ensure_one() url = '%s?%s' % (self.get_start_url(), werkzeug.urls.url_encode({'answer_token': answer and answer.access_token or None})) return { 'type': 'ir.actions.act_url', 'name': "Start Survey", 'target': 'self', 'url': url, } def action_print_survey(self, answer=None): """ Open the website page with the survey printable view """ self.ensure_one() url = '%s?%s' % (self.get_print_url(), werkzeug.urls.url_encode({'answer_token': answer and answer.access_token or None})) return { 'type': 'ir.actions.act_url', 'name': "Print Survey", 'target': 'self', 'url': url } def action_result_survey(self): """ Open the website page with the survey results view """ self.ensure_one() return { 'type': 'ir.actions.act_url', 'name': "Results of the Survey", 'target': 'self', 'url': '/survey/results/%s' % self.id } def action_test_survey(self): ''' Open the website page with the survey form into test mode''' self.ensure_one() return { 'type': 'ir.actions.act_url', 'name': "Test Survey", 'target': '_blank', 'url': '/survey/test/%s' % self.access_token, } def action_survey_user_input_completed(self): action = self.env['ir.actions.act_window']._for_xml_id('survey.action_survey_user_input') ctx = dict(self.env.context) ctx.update({'search_default_survey_id': self.ids[0], 'search_default_completed': 1, 'search_default_not_test': 1}) action['context'] = ctx return action def action_survey_user_input_certified(self): action = self.env['ir.actions.act_window']._for_xml_id('survey.action_survey_user_input') ctx = dict(self.env.context) ctx.update({'search_default_survey_id': self.ids[0], 'search_default_scoring_success': 1, 'search_default_not_test': 1}) action['context'] = ctx return action def action_survey_user_input(self): action = self.env['ir.actions.act_window']._for_xml_id('survey.action_survey_user_input') ctx = dict(self.env.context) ctx.update({'search_default_survey_id': self.ids[0], 'search_default_not_test': 1}) action['context'] = ctx return action def action_survey_preview_certification_template(self): self.ensure_one() return { 'type': 'ir.actions.act_url', 'target': '_blank', 'url': '/survey/%s/certification_preview' % (self.id) } def action_start_session(self): """ Sets the necessary fields for the session to take place and starts it. The write is sudo'ed because a survey user can start a session even if it's not his own survey. """ if not self.env.user.has_group('survey.group_survey_user'): raise AccessError(_('Only survey users can manage sessions.')) self.ensure_one() self.sudo().write({ 'questions_layout': 'page_per_question', 'session_start_time': fields.Datetime.now(), 'session_question_id': None, 'session_state': 'ready' }) return self.action_open_session_manager() def action_open_session_manager(self): self.ensure_one() return { 'type': 'ir.actions.act_url', 'name': "Open Session Manager", 'target': '_blank', 'url': '/survey/session/manage/%s' % self.access_token } def action_end_session(self): """ The write is sudo'ed because a survey user can end a session even if it's not his own survey. """ if not self.env.user.has_group('survey.group_survey_user'): raise AccessError(_('Only survey users can manage sessions.')) self.sudo().write({'session_state': False}) self.user_input_ids.sudo().write({'state': 'done'}) self.env['bus.bus']._sendone(self.access_token, 'end_session', {}) def get_start_url(self): return '/survey/start/%s' % self.access_token def get_start_short_url(self): """ See controller method docstring for more details. """ return '/s/%s' % self.access_token[:6] def get_print_url(self): return '/survey/print/%s' % self.access_token # ------------------------------------------------------------ # GRAPH / RESULTS # ------------------------------------------------------------ def _prepare_statistics(self, user_input_lines=None): if user_input_lines: user_input_domain = [ ('survey_id', 'in', self.ids), ('id', 'in', user_input_lines.mapped('user_input_id').ids) ] else: user_input_domain = [ ('survey_id', 'in', self.ids), ('state', '=', 'done'), ('test_entry', '=', False) ] count_data = self.env['survey.user_input'].sudo().read_group(user_input_domain, ['scoring_success', 'id:count_distinct'], ['scoring_success']) scoring_success_count = 0 scoring_failed_count = 0 for count_data_item in count_data: if count_data_item['scoring_success']: scoring_success_count += count_data_item['scoring_success_count'] else: scoring_failed_count += count_data_item['scoring_success_count'] success_graph = json.dumps([{ 'text': _('Passed'), 'count': scoring_success_count, 'color': '#2E7D32' }, { 'text': _('Missed'), 'count': scoring_failed_count, 'color': '#C62828' }]) total = scoring_success_count + scoring_failed_count return { 'global_success_rate': round((scoring_success_count / total) * 100, 1) if total > 0 else 0, 'global_success_graph': success_graph } # ------------------------------------------------------------ # GAMIFICATION / BADGES # ------------------------------------------------------------ def _prepare_challenge_category(self): return 'certification' def _create_certification_badge_trigger(self): self.ensure_one() if not self.certification_badge_id: raise ValueError(_('Certification Badge is not configured for the survey %(survey_name)s', survey_name=self.title)) goal = self.env['gamification.goal.definition'].create({ 'name': self.title, 'description': _("%s certification passed", self.title), 'domain': "['&', ('survey_id', '=', %s), ('scoring_success', '=', True)]" % self.id, 'computation_mode': 'count', 'display_mode': 'boolean', 'model_id': self.env.ref('survey.model_survey_user_input').id, 'condition': 'higher', 'batch_mode': True, 'batch_distinctive_field': self.env.ref('survey.field_survey_user_input__partner_id').id, 'batch_user_expression': 'user.partner_id.id' }) challenge = self.env['gamification.challenge'].create({ 'name': _('%s challenge certification', self.title), 'reward_id': self.certification_badge_id.id, 'state': 'inprogress', 'period': 'once', 'challenge_category': self._prepare_challenge_category(), 'reward_realtime': True, 'report_message_frequency': 'never', 'user_domain': [('karma', '>', 0)], 'visibility_mode': 'personal' }) self.env['gamification.challenge.line'].create({ 'definition_id': goal.id, 'challenge_id': challenge.id, 'target_goal': 1 }) def _handle_certification_badges(self, vals): if vals.get('certification_give_badge'): # If badge already set on records, reactivate the ones that are not active. surveys_with_badge = self.filtered(lambda survey: survey.certification_badge_id and not survey.certification_badge_id.active) surveys_with_badge.mapped('certification_badge_id').action_unarchive() # (re-)create challenge and goal for survey in self: survey._create_certification_badge_trigger() else: # if badge with owner : archive them, else delete everything (badge, challenge, goal) badges = self.mapped('certification_badge_id') challenges_to_delete = self.env['gamification.challenge'].search([('reward_id', 'in', badges.ids)]) goals_to_delete = challenges_to_delete.mapped('line_ids').mapped('definition_id') badges.action_archive() # delete all challenges and goals because not needed anymore (challenge lines are deleted in cascade) challenges_to_delete.unlink() goals_to_delete.unlink()
51.139873
56,305
30,971
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import collections import json import itertools import operator from odoo import api, fields, models, tools, _ from odoo.exceptions import UserError, ValidationError class SurveyQuestion(models.Model): """ Questions that will be asked in a survey. Each question can have one of more suggested answers (eg. in case of multi-answer checkboxes, radio buttons...). Technical note: survey.question is also the model used for the survey's pages (with the "is_page" field set to True). A page corresponds to a "section" in the interface, and the fact that it separates the survey in actual pages in the interface depends on the "questions_layout" parameter on the survey.survey model. Pages are also used when randomizing questions. The randomization can happen within a "page". Using the same model for questions and pages allows to put all the pages and questions together in a o2m field (see survey.survey.question_and_page_ids) on the view side and easily reorganize your survey by dragging the items around. It also removes on level of encoding by directly having 'Add a page' and 'Add a question' links on the tree view of questions, enabling a faster encoding. However, this has the downside of making the code reading a little bit more complicated. Efforts were made at the model level to create computed fields so that the use of these models still seems somewhat logical. That means: - A survey still has "page_ids" (question_and_page_ids filtered on is_page = True) - These "page_ids" still have question_ids (questions located between this page and the next) - These "question_ids" still have a "page_id" That makes the use and display of these information at view and controller levels easier to understand. """ _name = 'survey.question' _description = 'Survey Question' _rec_name = 'title' _order = 'sequence,id' @api.model def default_get(self, fields): defaults = super(SurveyQuestion, self).default_get(fields) if (not fields or 'question_type' in fields): defaults['question_type'] = False if defaults.get('is_page') == True else 'text_box' return defaults # question generic data title = fields.Char('Title', required=True, translate=True) description = fields.Html( 'Description', translate=True, sanitize=False, # TDE TODO: sanitize but find a way to keep youtube iframe media stuff help="Use this field to add additional explanations about your question or to illustrate it with pictures or a video") survey_id = fields.Many2one('survey.survey', string='Survey', ondelete='cascade') scoring_type = fields.Selection(related='survey_id.scoring_type', string='Scoring Type', readonly=True) sequence = fields.Integer('Sequence', default=10) # page specific is_page = fields.Boolean('Is a page?') question_ids = fields.One2many('survey.question', string='Questions', compute="_compute_question_ids") questions_selection = fields.Selection( related='survey_id.questions_selection', readonly=True, help="If randomized is selected, add the number of random questions next to the section.") random_questions_count = fields.Integer( 'Random questions count', default=1, help="Used on randomized sections to take X random questions from all the questions of that section.") # question specific page_id = fields.Many2one('survey.question', string='Page', compute="_compute_page_id", store=True) question_type = fields.Selection([ ('text_box', 'Multiple Lines Text Box'), ('char_box', 'Single Line Text Box'), ('numerical_box', 'Numerical Value'), ('date', 'Date'), ('datetime', 'Datetime'), ('simple_choice', 'Multiple choice: only one answer'), ('multiple_choice', 'Multiple choice: multiple answers allowed'), ('matrix', 'Matrix')], string='Question Type', compute='_compute_question_type', readonly=False, store=True) is_scored_question = fields.Boolean( 'Scored', compute='_compute_is_scored_question', readonly=False, store=True, copy=True, help="Include this question as part of quiz scoring. Requires an answer and answer score to be taken into account.") # -- scoreable/answerable simple answer_types: numerical_box / date / datetime answer_numerical_box = fields.Float('Correct numerical answer', help="Correct number answer for this question.") answer_date = fields.Date('Correct date answer', help="Correct date answer for this question.") answer_datetime = fields.Datetime('Correct datetime answer', help="Correct date and time answer for this question.") answer_score = fields.Float('Score', help="Score value for a correct answer to this question.") # -- char_box save_as_email = fields.Boolean( "Save as user email", compute='_compute_save_as_email', readonly=False, store=True, copy=True, help="If checked, this option will save the user's answer as its email address.") save_as_nickname = fields.Boolean( "Save as user nickname", compute='_compute_save_as_nickname', readonly=False, store=True, copy=True, help="If checked, this option will save the user's answer as its nickname.") # -- simple choice / multiple choice / matrix suggested_answer_ids = fields.One2many( 'survey.question.answer', 'question_id', string='Types of answers', copy=True, help='Labels used for proposed choices: simple choice, multiple choice and columns of matrix') allow_value_image = fields.Boolean('Images on answers', help='Display images in addition to answer label. Valid only for simple / multiple choice questions.') # -- matrix matrix_subtype = fields.Selection([ ('simple', 'One choice per row'), ('multiple', 'Multiple choices per row')], string='Matrix Type', default='simple') matrix_row_ids = fields.One2many( 'survey.question.answer', 'matrix_question_id', string='Matrix Rows', copy=True, help='Labels used for proposed choices: rows of matrix') # -- display & timing options column_nb = fields.Selection([ ('12', '1'), ('6', '2'), ('4', '3'), ('3', '4'), ('2', '6')], string='Number of columns', default='12', help='These options refer to col-xx-[12|6|4|3|2] classes in Bootstrap for dropdown-based simple and multiple choice questions.') is_time_limited = fields.Boolean("The question is limited in time", help="Currently only supported for live sessions.") time_limit = fields.Integer("Time limit (seconds)") # -- comments (simple choice, multiple choice, matrix (without count as an answer)) comments_allowed = fields.Boolean('Show Comments Field') comments_message = fields.Char('Comment Message', translate=True, default=lambda self: _("If other, please specify:")) comment_count_as_answer = fields.Boolean('Comment Field is an Answer Choice') # question validation validation_required = fields.Boolean('Validate entry') validation_email = fields.Boolean('Input must be an email') validation_length_min = fields.Integer('Minimum Text Length', default=0) validation_length_max = fields.Integer('Maximum Text Length', default=0) validation_min_float_value = fields.Float('Minimum value', default=0.0) validation_max_float_value = fields.Float('Maximum value', default=0.0) validation_min_date = fields.Date('Minimum Date') validation_max_date = fields.Date('Maximum Date') validation_min_datetime = fields.Datetime('Minimum Datetime') validation_max_datetime = fields.Datetime('Maximum Datetime') validation_error_msg = fields.Char('Validation Error message', translate=True, default=lambda self: _("The answer you entered is not valid.")) constr_mandatory = fields.Boolean('Mandatory Answer') constr_error_msg = fields.Char('Error message', translate=True, default=lambda self: _("This question requires an answer.")) # answers user_input_line_ids = fields.One2many( 'survey.user_input.line', 'question_id', string='Answers', domain=[('skipped', '=', False)], groups='survey.group_survey_user') # Conditional display is_conditional = fields.Boolean( string='Conditional Display', copy=False, help="""If checked, this question will be displayed only if the specified conditional answer have been selected in a previous question""") triggering_question_id = fields.Many2one( 'survey.question', string="Triggering Question", copy=False, compute="_compute_triggering_question_id", store=True, readonly=False, help="Question containing the triggering answer to display the current question.", domain="""[('survey_id', '=', survey_id), '&', ('question_type', 'in', ['simple_choice', 'multiple_choice']), '|', ('sequence', '<', sequence), '&', ('sequence', '=', sequence), ('id', '<', id)]""") triggering_answer_id = fields.Many2one( 'survey.question.answer', string="Triggering Answer", copy=False, compute="_compute_triggering_answer_id", store=True, readonly=False, help="Answer that will trigger the display of the current question.", domain="[('question_id', '=', triggering_question_id)]") _sql_constraints = [ ('positive_len_min', 'CHECK (validation_length_min >= 0)', 'A length must be positive!'), ('positive_len_max', 'CHECK (validation_length_max >= 0)', 'A length must be positive!'), ('validation_length', 'CHECK (validation_length_min <= validation_length_max)', 'Max length cannot be smaller than min length!'), ('validation_float', 'CHECK (validation_min_float_value <= validation_max_float_value)', 'Max value cannot be smaller than min value!'), ('validation_date', 'CHECK (validation_min_date <= validation_max_date)', 'Max date cannot be smaller than min date!'), ('validation_datetime', 'CHECK (validation_min_datetime <= validation_max_datetime)', 'Max datetime cannot be smaller than min datetime!'), ('positive_answer_score', 'CHECK (answer_score >= 0)', 'An answer score for a non-multiple choice question cannot be negative!'), ('scored_datetime_have_answers', "CHECK (is_scored_question != True OR question_type != 'datetime' OR answer_datetime is not null)", 'All "Is a scored question = True" and "Question Type: Datetime" questions need an answer'), ('scored_date_have_answers', "CHECK (is_scored_question != True OR question_type != 'date' OR answer_date is not null)", 'All "Is a scored question = True" and "Question Type: Date" questions need an answer') ] @api.depends('is_page') def _compute_question_type(self): for question in self: if not question.question_type or question.is_page: question.question_type = False @api.depends('survey_id.question_and_page_ids.is_page', 'survey_id.question_and_page_ids.sequence') def _compute_question_ids(self): """Will take all questions of the survey for which the index is higher than the index of this page and lower than the index of the next page.""" for question in self: if question.is_page: next_page_index = False for page in question.survey_id.page_ids: if page._index() > question._index(): next_page_index = page._index() break question.question_ids = question.survey_id.question_ids.filtered( lambda q: q._index() > question._index() and (not next_page_index or q._index() < next_page_index) ) else: question.question_ids = self.env['survey.question'] @api.depends('survey_id.question_and_page_ids.is_page', 'survey_id.question_and_page_ids.sequence') def _compute_page_id(self): """Will find the page to which this question belongs to by looking inside the corresponding survey""" for question in self: if question.is_page: question.page_id = None else: page = None for q in question.survey_id.question_and_page_ids.sorted(): if q == question: break if q.is_page: page = q question.page_id = page @api.depends('question_type', 'validation_email') def _compute_save_as_email(self): for question in self: if question.question_type != 'char_box' or not question.validation_email: question.save_as_email = False @api.depends('question_type') def _compute_save_as_nickname(self): for question in self: if question.question_type != 'char_box': question.save_as_nickname = False @api.depends('is_conditional') def _compute_triggering_question_id(self): """ Used as an 'onchange' : Reset the triggering question if user uncheck 'Conditional Display' Avoid CacheMiss : set the value to False if the value is not set yet.""" for question in self: if not question.is_conditional or question.triggering_question_id is None: question.triggering_question_id = False @api.depends('triggering_question_id') def _compute_triggering_answer_id(self): """ Used as an 'onchange' : Reset the triggering answer if user unset or change the triggering question or uncheck 'Conditional Display'. Avoid CacheMiss : set the value to False if the value is not set yet.""" for question in self: if not question.triggering_question_id \ or question.triggering_question_id != question.triggering_answer_id.question_id\ or question.triggering_answer_id is None: question.triggering_answer_id = False @api.depends('question_type', 'scoring_type', 'answer_date', 'answer_datetime', 'answer_numerical_box') def _compute_is_scored_question(self): """ Computes whether a question "is scored" or not. Handles following cases: - inconsistent Boolean=None edge case that breaks tests => False - survey is not scored => False - 'date'/'datetime'/'numerical_box' question types w/correct answer => True (implied without user having to activate, except for numerical whose correct value is 0.0) - 'simple_choice / multiple_choice': set to True even if logic is a bit different (coming from answers) - question_type isn't scoreable (note: choice questions scoring logic handled separately) => False """ for question in self: if question.is_scored_question is None or question.scoring_type == 'no_scoring': question.is_scored_question = False elif question.question_type == 'date': question.is_scored_question = bool(question.answer_date) elif question.question_type == 'datetime': question.is_scored_question = bool(question.answer_datetime) elif question.question_type == 'numerical_box' and question.answer_numerical_box: question.is_scored_question = True elif question.question_type in ['simple_choice', 'multiple_choice']: question.is_scored_question = True else: question.is_scored_question = False # ------------------------------------------------------------ # CRUD # ------------------------------------------------------------ @api.ondelete(at_uninstall=False) def _unlink_except_live_sessions_in_progress(self): running_surveys = self.survey_id.filtered(lambda survey: survey.session_state == 'in_progress') if running_surveys: raise UserError(_( 'You cannot delete questions from surveys "%(survey_names)s" while live sessions are in progress.', survey_names=', '.join(running_surveys.mapped('title')), )) # ------------------------------------------------------------ # VALIDATION # ------------------------------------------------------------ def validate_question(self, answer, comment=None): """ Validate question, depending on question type and parameters for simple choice, text, date and number, answer is simply the answer of the question. For other multiple choices questions, answer is a list of answers (the selected choices or a list of selected answers per question -for matrix type-): - Simple answer : answer = 'example' or 2 or question_answer_id or 2019/10/10 - Multiple choice : answer = [question_answer_id1, question_answer_id2, question_answer_id3] - Matrix: answer = { 'rowId1' : [colId1, colId2,...], 'rowId2' : [colId1, colId3, ...] } return dict {question.id (int): error (str)} -> empty dict if no validation error. """ self.ensure_one() if isinstance(answer, str): answer = answer.strip() # Empty answer to mandatory question if self.constr_mandatory and not answer and self.question_type not in ['simple_choice', 'multiple_choice']: return {self.id: self.constr_error_msg} # because in choices question types, comment can count as answer if answer or self.question_type in ['simple_choice', 'multiple_choice']: if self.question_type == 'char_box': return self._validate_char_box(answer) elif self.question_type == 'numerical_box': return self._validate_numerical_box(answer) elif self.question_type in ['date', 'datetime']: return self._validate_date(answer) elif self.question_type in ['simple_choice', 'multiple_choice']: return self._validate_choice(answer, comment) elif self.question_type == 'matrix': return self._validate_matrix(answer) return {} def _validate_char_box(self, answer): # Email format validation # all the strings of the form "<something>@<anything>.<extension>" will be accepted if self.validation_email: if not tools.email_normalize(answer): return {self.id: _('This answer must be an email address')} # Answer validation (if properly defined) # Length of the answer must be in a range if self.validation_required: if not (self.validation_length_min <= len(answer) <= self.validation_length_max): return {self.id: self.validation_error_msg} return {} def _validate_numerical_box(self, answer): try: floatanswer = float(answer) except ValueError: return {self.id: _('This is not a number')} if self.validation_required: # Answer is not in the right range with tools.ignore(Exception): if not (self.validation_min_float_value <= floatanswer <= self.validation_max_float_value): return {self.id: self.validation_error_msg} return {} def _validate_date(self, answer): isDatetime = self.question_type == 'datetime' # Checks if user input is a date try: dateanswer = fields.Datetime.from_string(answer) if isDatetime else fields.Date.from_string(answer) except ValueError: return {self.id: _('This is not a date')} if self.validation_required: # Check if answer is in the right range if isDatetime: min_date = fields.Datetime.from_string(self.validation_min_datetime) max_date = fields.Datetime.from_string(self.validation_max_datetime) dateanswer = fields.Datetime.from_string(answer) else: min_date = fields.Date.from_string(self.validation_min_date) max_date = fields.Date.from_string(self.validation_max_date) dateanswer = fields.Date.from_string(answer) if (min_date and max_date and not (min_date <= dateanswer <= max_date))\ or (min_date and not min_date <= dateanswer)\ or (max_date and not dateanswer <= max_date): return {self.id: self.validation_error_msg} return {} def _validate_choice(self, answer, comment): # Empty comment if self.constr_mandatory \ and not answer \ and not (self.comments_allowed and self.comment_count_as_answer and comment): return {self.id: self.constr_error_msg} return {} def _validate_matrix(self, answers): # Validate that each line has been answered if self.constr_mandatory and len(self.matrix_row_ids) != len(answers): return {self.id: self.constr_error_msg} return {} def _index(self): """We would normally just use the 'sequence' field of questions BUT, if the pages and questions are created without ever moving records around, the sequence field can be set to 0 for all the questions. However, the order of the recordset is always correct so we can rely on the index method.""" self.ensure_one() return list(self.survey_id.question_and_page_ids).index(self) # ------------------------------------------------------------ # STATISTICS / REPORTING # ------------------------------------------------------------ def _prepare_statistics(self, user_input_lines): """ Compute statistical data for questions by counting number of vote per choice on basis of filter """ all_questions_data = [] for question in self: question_data = {'question': question, 'is_page': question.is_page} if question.is_page: all_questions_data.append(question_data) continue # fetch answer lines, separate comments from real answers all_lines = user_input_lines.filtered(lambda line: line.question_id == question) if question.question_type in ['simple_choice', 'multiple_choice', 'matrix']: answer_lines = all_lines.filtered( lambda line: line.answer_type == 'suggestion' or ( line.skipped and not line.answer_type) or ( line.answer_type == 'char_box' and question.comment_count_as_answer) ) comment_line_ids = all_lines.filtered(lambda line: line.answer_type == 'char_box') else: answer_lines = all_lines comment_line_ids = self.env['survey.user_input.line'] skipped_lines = answer_lines.filtered(lambda line: line.skipped) done_lines = answer_lines - skipped_lines question_data.update( answer_line_ids=answer_lines, answer_line_done_ids=done_lines, answer_input_done_ids=done_lines.mapped('user_input_id'), answer_input_skipped_ids=skipped_lines.mapped('user_input_id'), comment_line_ids=comment_line_ids) question_data.update(question._get_stats_summary_data(answer_lines)) # prepare table and graph data table_data, graph_data = question._get_stats_data(answer_lines) question_data['table_data'] = table_data question_data['graph_data'] = json.dumps(graph_data) all_questions_data.append(question_data) return all_questions_data def _get_stats_data(self, user_input_lines): if self.question_type == 'simple_choice': return self._get_stats_data_answers(user_input_lines) elif self.question_type == 'multiple_choice': table_data, graph_data = self._get_stats_data_answers(user_input_lines) return table_data, [{'key': self.title, 'values': graph_data}] elif self.question_type == 'matrix': return self._get_stats_graph_data_matrix(user_input_lines) return [line for line in user_input_lines], [] def _get_stats_data_answers(self, user_input_lines): """ Statistics for question.answer based questions (simple choice, multiple choice.). A corner case with a void record survey.question.answer is added to count comments that should be considered as valid answers. This small hack allow to have everything available in the same standard structure. """ suggested_answers = [answer for answer in self.mapped('suggested_answer_ids')] if self.comment_count_as_answer: suggested_answers += [self.env['survey.question.answer']] count_data = dict.fromkeys(suggested_answers, 0) for line in user_input_lines: if line.suggested_answer_id in count_data\ or (line.value_char_box and self.comment_count_as_answer): count_data[line.suggested_answer_id] += 1 table_data = [{ 'value': _('Other (see comments)') if not sug_answer else sug_answer.value, 'suggested_answer': sug_answer, 'count': count_data[sug_answer] } for sug_answer in suggested_answers] graph_data = [{ 'text': _('Other (see comments)') if not sug_answer else sug_answer.value, 'count': count_data[sug_answer] } for sug_answer in suggested_answers] return table_data, graph_data def _get_stats_graph_data_matrix(self, user_input_lines): suggested_answers = self.mapped('suggested_answer_ids') matrix_rows = self.mapped('matrix_row_ids') count_data = dict.fromkeys(itertools.product(matrix_rows, suggested_answers), 0) for line in user_input_lines: if line.matrix_row_id and line.suggested_answer_id: count_data[(line.matrix_row_id, line.suggested_answer_id)] += 1 table_data = [{ 'row': row, 'columns': [{ 'suggested_answer': sug_answer, 'count': count_data[(row, sug_answer)] } for sug_answer in suggested_answers], } for row in matrix_rows] graph_data = [{ 'key': sug_answer.value, 'values': [{ 'text': row.value, 'count': count_data[(row, sug_answer)] } for row in matrix_rows ] } for sug_answer in suggested_answers] return table_data, graph_data def _get_stats_summary_data(self, user_input_lines): stats = {} if self.question_type in ['simple_choice', 'multiple_choice']: stats.update(self._get_stats_summary_data_choice(user_input_lines)) elif self.question_type == 'numerical_box': stats.update(self._get_stats_summary_data_numerical(user_input_lines)) if self.question_type in ['numerical_box', 'date', 'datetime']: stats.update(self._get_stats_summary_data_scored(user_input_lines)) return stats def _get_stats_summary_data_choice(self, user_input_lines): right_inputs, partial_inputs = self.env['survey.user_input'], self.env['survey.user_input'] right_answers = self.suggested_answer_ids.filtered(lambda label: label.is_correct) if self.question_type == 'multiple_choice': for user_input, lines in tools.groupby(user_input_lines, operator.itemgetter('user_input_id')): user_input_answers = self.env['survey.user_input.line'].concat(*lines).filtered(lambda l: l.answer_is_correct).mapped('suggested_answer_id') if user_input_answers and user_input_answers < right_answers: partial_inputs += user_input elif user_input_answers: right_inputs += user_input else: right_inputs = user_input_lines.filtered(lambda line: line.answer_is_correct).mapped('user_input_id') return { 'right_answers': right_answers, 'right_inputs_count': len(right_inputs), 'partial_inputs_count': len(partial_inputs), } def _get_stats_summary_data_numerical(self, user_input_lines): all_values = user_input_lines.filtered(lambda line: not line.skipped).mapped('value_numerical_box') lines_sum = sum(all_values) return { 'numerical_max': max(all_values, default=0), 'numerical_min': min(all_values, default=0), 'numerical_average': round(lines_sum / (len(all_values) or 1), 2), } def _get_stats_summary_data_scored(self, user_input_lines): return { 'common_lines': collections.Counter( user_input_lines.filtered(lambda line: not line.skipped).mapped('value_%s' % self.question_type) ).most_common(5) if self.question_type != 'datetime' else [], 'right_inputs_count': len(user_input_lines.filtered(lambda line: line.answer_is_correct).mapped('user_input_id')) } class SurveyQuestionAnswer(models.Model): """ A preconfigured answer for a question. This model stores values used for * simple choice, multiple choice: proposed values for the selection / radio; * matrix: row and column values; """ _name = 'survey.question.answer' _rec_name = 'value' _order = 'sequence, id' _description = 'Survey Label' question_id = fields.Many2one('survey.question', string='Question', ondelete='cascade') matrix_question_id = fields.Many2one('survey.question', string='Question (as matrix row)', ondelete='cascade') sequence = fields.Integer('Label Sequence order', default=10) value = fields.Char('Suggested value', translate=True, required=True) value_image = fields.Image('Image', max_width=256, max_height=256) is_correct = fields.Boolean('Is a correct answer') answer_score = fields.Float('Score for this choice', help="A positive score indicates a correct choice; a negative or null score indicates a wrong answer") @api.constrains('question_id', 'matrix_question_id') def _check_question_not_empty(self): """Ensure that field question_id XOR field matrix_question_id is not null""" for label in self: if not bool(label.question_id) != bool(label.matrix_question_id): raise ValidationError(_("A label must be attached to only one question."))
53.862609
30,971
35,543
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import uuid from dateutil.relativedelta import relativedelta from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.tools import float_is_zero _logger = logging.getLogger(__name__) class SurveyUserInput(models.Model): """ Metadata for a set of one user's answers to a particular survey """ _name = "survey.user_input" _description = "Survey User Input" _rec_name = "survey_id" _order = "create_date desc" # answer description survey_id = fields.Many2one('survey.survey', string='Survey', required=True, readonly=True, ondelete='cascade') scoring_type = fields.Selection(string="Scoring", related="survey_id.scoring_type") start_datetime = fields.Datetime('Start date and time', readonly=True) end_datetime = fields.Datetime('End date and time', readonly=True) deadline = fields.Datetime('Deadline', help="Datetime until customer can open the survey and submit answers") state = fields.Selection([ ('new', 'Not started yet'), ('in_progress', 'In Progress'), ('done', 'Completed')], string='Status', default='new', readonly=True) test_entry = fields.Boolean(readonly=True) last_displayed_page_id = fields.Many2one('survey.question', string='Last displayed question/page') # attempts management is_attempts_limited = fields.Boolean("Limited number of attempts", related='survey_id.is_attempts_limited') attempts_limit = fields.Integer("Number of attempts", related='survey_id.attempts_limit') attempts_number = fields.Integer("Attempt n°", compute='_compute_attempts_number') survey_time_limit_reached = fields.Boolean("Survey Time Limit Reached", compute='_compute_survey_time_limit_reached') # identification / access access_token = fields.Char('Identification token', default=lambda self: str(uuid.uuid4()), readonly=True, required=True, copy=False) invite_token = fields.Char('Invite token', readonly=True, copy=False) # no unique constraint, as it identifies a pool of attempts partner_id = fields.Many2one('res.partner', string='Partner', readonly=True) email = fields.Char('Email', readonly=True) nickname = fields.Char('Nickname', help="Attendee nickname, mainly used to identify him in the survey session leaderboard.") # questions / answers user_input_line_ids = fields.One2many('survey.user_input.line', 'user_input_id', string='Answers', copy=True) predefined_question_ids = fields.Many2many('survey.question', string='Predefined Questions', readonly=True) scoring_percentage = fields.Float("Score (%)", compute="_compute_scoring_values", store=True, compute_sudo=True) # stored for perf reasons scoring_total = fields.Float("Total Score", compute="_compute_scoring_values", store=True, compute_sudo=True) # stored for perf reasons scoring_success = fields.Boolean('Quizz Passed', compute='_compute_scoring_success', store=True, compute_sudo=True) # stored for perf reasons # live sessions is_session_answer = fields.Boolean('Is in a Session', help="Is that user input part of a survey session or not.") question_time_limit_reached = fields.Boolean("Question Time Limit Reached", compute='_compute_question_time_limit_reached') _sql_constraints = [ ('unique_token', 'UNIQUE (access_token)', 'An access token must be unique!'), ] @api.depends('user_input_line_ids.answer_score', 'user_input_line_ids.question_id', 'predefined_question_ids.answer_score') def _compute_scoring_values(self): for user_input in self: # sum(multi-choice question scores) + sum(simple answer_type scores) total_possible_score = 0 for question in user_input.predefined_question_ids: if question.question_type == 'simple_choice': total_possible_score += max([score for score in question.mapped('suggested_answer_ids.answer_score') if score > 0], default=0) elif question.question_type == 'multiple_choice': total_possible_score += sum(score for score in question.mapped('suggested_answer_ids.answer_score') if score > 0) elif question.is_scored_question: total_possible_score += question.answer_score if total_possible_score == 0: user_input.scoring_percentage = 0 user_input.scoring_total = 0 else: score_total = sum(user_input.user_input_line_ids.mapped('answer_score')) user_input.scoring_total = score_total score_percentage = (score_total / total_possible_score) * 100 user_input.scoring_percentage = round(score_percentage, 2) if score_percentage > 0 else 0 @api.depends('scoring_percentage', 'survey_id') def _compute_scoring_success(self): for user_input in self: user_input.scoring_success = user_input.scoring_percentage >= user_input.survey_id.scoring_success_min @api.depends( 'start_datetime', 'survey_id.is_time_limited', 'survey_id.time_limit') def _compute_survey_time_limit_reached(self): """ Checks that the user_input is not exceeding the survey's time limit. """ for user_input in self: if not user_input.is_session_answer and user_input.start_datetime: start_time = user_input.start_datetime time_limit = user_input.survey_id.time_limit user_input.survey_time_limit_reached = user_input.survey_id.is_time_limited and \ fields.Datetime.now() >= start_time + relativedelta(minutes=time_limit) else: user_input.survey_time_limit_reached = False @api.depends( 'survey_id.session_question_id.time_limit', 'survey_id.session_question_id.is_time_limited', 'survey_id.session_question_start_time') def _compute_question_time_limit_reached(self): """ Checks that the user_input is not exceeding the question's time limit. Only used in the context of survey sessions. """ for user_input in self: if user_input.is_session_answer and user_input.survey_id.session_question_start_time: start_time = user_input.survey_id.session_question_start_time time_limit = user_input.survey_id.session_question_id.time_limit user_input.question_time_limit_reached = user_input.survey_id.session_question_id.is_time_limited and \ fields.Datetime.now() >= start_time + relativedelta(seconds=time_limit) else: user_input.question_time_limit_reached = False @api.depends('state', 'test_entry', 'survey_id.is_attempts_limited', 'partner_id', 'email', 'invite_token') def _compute_attempts_number(self): attempts_to_compute = self.filtered( lambda user_input: user_input.state == 'done' and not user_input.test_entry and user_input.survey_id.is_attempts_limited ) for user_input in (self - attempts_to_compute): user_input.attempts_number = 1 if attempts_to_compute: self.env.cr.execute("""SELECT user_input.id, (COUNT(previous_user_input.id) + 1) AS attempts_number FROM survey_user_input user_input LEFT OUTER JOIN survey_user_input previous_user_input ON user_input.survey_id = previous_user_input.survey_id AND previous_user_input.state = 'done' AND previous_user_input.test_entry IS NOT TRUE AND previous_user_input.id < user_input.id AND (user_input.invite_token IS NULL OR user_input.invite_token = previous_user_input.invite_token) AND (user_input.partner_id = previous_user_input.partner_id OR user_input.email = previous_user_input.email) WHERE user_input.id IN %s GROUP BY user_input.id; """, (tuple(attempts_to_compute.ids),)) attempts_count_results = self.env.cr.dictfetchall() for user_input in attempts_to_compute: attempts_number = 1 for attempts_count_result in attempts_count_results: if attempts_count_result['id'] == user_input.id: attempts_number = attempts_count_result['attempts_number'] break user_input.attempts_number = attempts_number @api.model_create_multi def create(self, vals_list): for vals in vals_list: if 'predefined_question_ids' not in vals: suvey_id = vals.get('survey_id', self.env.context.get('default_survey_id')) survey = self.env['survey.survey'].browse(suvey_id) vals['predefined_question_ids'] = [(6, 0, survey._prepare_user_input_predefined_questions().ids)] return super(SurveyUserInput, self).create(vals_list) # ------------------------------------------------------------ # ACTIONS / BUSINESS # ------------------------------------------------------------ def action_resend(self): partners = self.env['res.partner'] emails = [] for user_answer in self: if user_answer.partner_id: partners |= user_answer.partner_id elif user_answer.email: emails.append(user_answer.email) return self.survey_id.with_context( default_existing_mode='resend', default_partner_ids=partners.ids, default_emails=','.join(emails) ).action_send_survey() def action_print_answers(self): """ Open the website page with the survey form """ self.ensure_one() return { 'type': 'ir.actions.act_url', 'name': "View Answers", 'target': 'self', 'url': '/survey/print/%s?answer_token=%s' % (self.survey_id.access_token, self.access_token) } @api.model def _generate_invite_token(self): return str(uuid.uuid4()) def _mark_in_progress(self): """ marks the state as 'in_progress' and updates the start_datetime accordingly. """ self.write({ 'start_datetime': fields.Datetime.now(), 'state': 'in_progress' }) def _mark_done(self): """ This method will: 1. mark the state as 'done' 2. send the certification email with attached document if - The survey is a certification - It has a certification_mail_template_id set - The user succeeded the test Will also run challenge Cron to give the certification badge if any.""" self.write({ 'end_datetime': fields.Datetime.now(), 'state': 'done', }) Challenge = self.env['gamification.challenge'].sudo() badge_ids = [] for user_input in self: if user_input.survey_id.certification and user_input.scoring_success: if user_input.survey_id.certification_mail_template_id and not user_input.test_entry: user_input.survey_id.certification_mail_template_id.send_mail(user_input.id, notif_layout="mail.mail_notification_light") if user_input.survey_id.certification_give_badge: badge_ids.append(user_input.survey_id.certification_badge_id.id) # Update predefined_question_id to remove inactive questions user_input.predefined_question_ids -= user_input._get_inactive_conditional_questions() if badge_ids: challenges = Challenge.search([('reward_id', 'in', badge_ids)]) if challenges: Challenge._cron_update(ids=challenges.ids, commit=False) def get_start_url(self): self.ensure_one() return '%s?answer_token=%s' % (self.survey_id.get_start_url(), self.access_token) def get_print_url(self): self.ensure_one() return '%s?answer_token=%s' % (self.survey_id.get_print_url(), self.access_token) # ------------------------------------------------------------ # CREATE / UPDATE LINES FROM SURVEY FRONTEND INPUT # ------------------------------------------------------------ def save_lines(self, question, answer, comment=None): """ Save answers to questions, depending on question type If an answer already exists for question and user_input_id, it will be overwritten (or deleted for 'choice' questions) (in order to maintain data consistency). """ old_answers = self.env['survey.user_input.line'].search([ ('user_input_id', '=', self.id), ('question_id', '=', question.id) ]) if question.question_type in ['char_box', 'text_box', 'numerical_box', 'date', 'datetime']: self._save_line_simple_answer(question, old_answers, answer) if question.save_as_email and answer: self.write({'email': answer}) if question.save_as_nickname and answer: self.write({'nickname': answer}) elif question.question_type in ['simple_choice', 'multiple_choice']: self._save_line_choice(question, old_answers, answer, comment) elif question.question_type == 'matrix': self._save_line_matrix(question, old_answers, answer, comment) else: raise AttributeError(question.question_type + ": This type of question has no saving function") def _save_line_simple_answer(self, question, old_answers, answer): vals = self._get_line_answer_values(question, answer, question.question_type) if old_answers: old_answers.write(vals) return old_answers else: return self.env['survey.user_input.line'].create(vals) def _save_line_choice(self, question, old_answers, answers, comment): if not (isinstance(answers, list)): answers = [answers] if not answers: # add a False answer to force saving a skipped line # this will make this question correctly considered as skipped in statistics answers = [False] vals_list = [] if question.question_type == 'simple_choice': if not question.comment_count_as_answer or not question.comments_allowed or not comment: vals_list = [self._get_line_answer_values(question, answer, 'suggestion') for answer in answers] elif question.question_type == 'multiple_choice': vals_list = [self._get_line_answer_values(question, answer, 'suggestion') for answer in answers] if comment: vals_list.append(self._get_line_comment_values(question, comment)) old_answers.sudo().unlink() return self.env['survey.user_input.line'].create(vals_list) def _save_line_matrix(self, question, old_answers, answers, comment): vals_list = [] if not answers and question.matrix_row_ids: # add a False answer to force saving a skipped line # this will make this question correctly considered as skipped in statistics answers = {question.matrix_row_ids[0].id: [False]} if answers: for row_key, row_answer in answers.items(): for answer in row_answer: vals = self._get_line_answer_values(question, answer, 'suggestion') vals['matrix_row_id'] = int(row_key) vals_list.append(vals.copy()) if comment: vals_list.append(self._get_line_comment_values(question, comment)) old_answers.sudo().unlink() return self.env['survey.user_input.line'].create(vals_list) def _get_line_answer_values(self, question, answer, answer_type): vals = { 'user_input_id': self.id, 'question_id': question.id, 'skipped': False, 'answer_type': answer_type, } if not answer or (isinstance(answer, str) and not answer.strip()): vals.update(answer_type=None, skipped=True) return vals if answer_type == 'suggestion': vals['suggested_answer_id'] = int(answer) elif answer_type == 'numerical_box': vals['value_numerical_box'] = float(answer) else: vals['value_%s' % answer_type] = answer return vals def _get_line_comment_values(self, question, comment): return { 'user_input_id': self.id, 'question_id': question.id, 'skipped': False, 'answer_type': 'char_box', 'value_char_box': comment, } # ------------------------------------------------------------ # STATISTICS / RESULTS # ------------------------------------------------------------ def _prepare_statistics(self): """ Prepares survey.user_input's statistics to display various charts on the frontend. Returns a structure containing answers statistics "by section" and "totals" for every input in self. e.g returned structure: { survey.user_input(1,): { 'by_section': { 'Uncategorized': { 'question_count': 2, 'correct': 2, 'partial': 0, 'incorrect': 0, 'skipped': 0, }, 'Mathematics': { 'question_count': 3, 'correct': 1, 'partial': 1, 'incorrect': 0, 'skipped': 1, }, 'Geography': { 'question_count': 4, 'correct': 2, 'partial': 0, 'incorrect': 2, 'skipped': 0, } }, 'totals' [{ 'text': 'Correct', 'count': 5, }, { 'text': 'Partially', 'count': 1, }, { 'text': 'Incorrect', 'count': 2, }, { 'text': 'Unanswered', 'count': 1, }] } }""" res = dict((user_input, { 'by_section': {} }) for user_input in self) scored_questions = self.mapped('predefined_question_ids').filtered(lambda question: question.is_scored_question) for question in scored_questions: if question.question_type in ['simple_choice', 'multiple_choice']: question_correct_suggested_answers = question.suggested_answer_ids.filtered(lambda answer: answer.is_correct) question_section = question.page_id.title or _('Uncategorized') for user_input in self: user_input_lines = user_input.user_input_line_ids.filtered(lambda line: line.question_id == question) if question.question_type in ['simple_choice', 'multiple_choice']: answer_result_key = self._choice_question_answer_result(user_input_lines, question_correct_suggested_answers) else: answer_result_key = self._simple_question_answer_result(user_input_lines) if question_section not in res[user_input]['by_section']: res[user_input]['by_section'][question_section] = { 'question_count': 0, 'correct': 0, 'partial': 0, 'incorrect': 0, 'skipped': 0, } res[user_input]['by_section'][question_section]['question_count'] += 1 res[user_input]['by_section'][question_section][answer_result_key] += 1 for user_input in self: correct_count = 0 partial_count = 0 incorrect_count = 0 skipped_count = 0 for section_counts in res[user_input]['by_section'].values(): correct_count += section_counts.get('correct', 0) partial_count += section_counts.get('partial', 0) incorrect_count += section_counts.get('incorrect', 0) skipped_count += section_counts.get('skipped', 0) res[user_input]['totals'] = [ {'text': _("Correct"), 'count': correct_count}, {'text': _("Partially"), 'count': partial_count}, {'text': _("Incorrect"), 'count': incorrect_count}, {'text': _("Unanswered"), 'count': skipped_count} ] return res def _choice_question_answer_result(self, user_input_lines, question_correct_suggested_answers): correct_user_input_lines = user_input_lines.filtered(lambda line: line.answer_is_correct and not line.skipped).mapped('suggested_answer_id') incorrect_user_input_lines = user_input_lines.filtered(lambda line: not line.answer_is_correct and not line.skipped) if question_correct_suggested_answers and correct_user_input_lines == question_correct_suggested_answers: return 'correct' elif correct_user_input_lines and correct_user_input_lines < question_correct_suggested_answers: return 'partial' elif not correct_user_input_lines and incorrect_user_input_lines: return 'incorrect' else: return 'skipped' def _simple_question_answer_result(self, user_input_line): if user_input_line.skipped: return 'skipped' elif user_input_line.answer_is_correct: return 'correct' else: return 'incorrect' # ------------------------------------------------------------ # Conditional Questions Management # ------------------------------------------------------------ def _get_conditional_values(self): """ For survey containing conditional questions, we need a triggered_questions_by_answer map that contains {key: answer, value: the question that the answer triggers, if selected}, The idea is to be able to verify, on every answer check, if this answer is triggering the display of another question. If answer is not in the conditional map: - nothing happens. If the answer is in the conditional map: - If we are in ONE PAGE survey : (handled at CLIENT side) -> display immediately the depending question - If we are in PAGE PER SECTION : (handled at CLIENT side) - If related question is on the same page : -> display immediately the depending question - If the related question is not on the same page : -> keep the answers in memory and check at next page load if the depending question is in there and display it, if so. - If we are in PAGE PER QUESTION : (handled at SERVER side) -> During submit, determine which is the next question to display getting the next question that is the next in sequence and that is either not triggered by another question's answer, or that is triggered by an already selected answer. To do all this, we need to return: - list of all selected answers: [answer_id1, answer_id2, ...] (for survey reloading, otherwise, this list is updated at client side) - triggered_questions_by_answer: dict -> for a given answer, list of questions triggered by this answer; Used mainly for dynamic show/hide behaviour at client side - triggering_answer_by_question: dict -> for a given question, the answer that triggers it Used mainly to ease template rendering """ triggering_answer_by_question, triggered_questions_by_answer = {}, {} # Ignore conditional configuration if randomised questions selection if self.survey_id.questions_selection != 'random': triggering_answer_by_question, triggered_questions_by_answer = self.survey_id._get_conditional_maps() selected_answers = self._get_selected_suggested_answers() return triggering_answer_by_question, triggered_questions_by_answer, selected_answers def _get_selected_suggested_answers(self): """ For now, only simple and multiple choices question type are handled by the conditional questions feature. Mapping all the suggested answers selected by the user will also include answers from matrix question type, Those ones won't be used. Maybe someday, conditional questions feature will be extended to work with matrix question. :return: all the suggested answer selected by the user. """ return self.mapped('user_input_line_ids.suggested_answer_id') def _clear_inactive_conditional_answers(self): """ Clean eventual answers on conditional questions that should not have been displayed to user. This method is used mainly for page per question survey, a similar method does the same treatment at client side for the other survey layouts. E.g.: if depending answer was uncheck after answering conditional question, we need to clear answers of that conditional question, for two reasons: - ensure correct scoring - if the selected answer triggers another question later in the survey, if the answer is not cleared, a question that should not be displayed to the user will be. TODO DBE: Maybe this can be the only cleaning method, even for section_per_page or one_page where conditional questions are, for now, cleared in JS directly. But this can be annoying if user typed a long answer, changed his mind unchecking depending answer and changed again his mind by rechecking the depending answer -> For now, the long answer will be lost. If we use this as the master cleaning method, long answer will be cleared only during submit. """ inactive_questions = self._get_inactive_conditional_questions() # delete user.input.line on question that should not be answered. answers_to_delete = self.user_input_line_ids.filtered(lambda answer: answer.question_id in inactive_questions) answers_to_delete.unlink() def _get_inactive_conditional_questions(self): triggering_answer_by_question, triggered_questions_by_answer, selected_answers = self._get_conditional_values() # get questions that should not be answered inactive_questions = self.env['survey.question'] for answer in triggered_questions_by_answer.keys(): if answer not in selected_answers: for question in triggered_questions_by_answer[answer]: inactive_questions |= question return inactive_questions def _get_print_questions(self): """ Get the questions to display : the ones that should have been answered = active questions In case of session, active questions are based on most voted answers :return: active survey.question browse records """ survey = self.survey_id if self.is_session_answer: most_voted_answers = survey._get_session_most_voted_answers() inactive_questions = most_voted_answers._get_inactive_conditional_questions() else: inactive_questions = self._get_inactive_conditional_questions() return survey.question_ids - inactive_questions class SurveyUserInputLine(models.Model): _name = 'survey.user_input.line' _description = 'Survey User Input Line' _rec_name = 'user_input_id' _order = 'question_sequence, id' # survey data user_input_id = fields.Many2one('survey.user_input', string='User Input', ondelete='cascade', required=True) survey_id = fields.Many2one(related='user_input_id.survey_id', string='Survey', store=True, readonly=False) question_id = fields.Many2one('survey.question', string='Question', ondelete='cascade', required=True) page_id = fields.Many2one(related='question_id.page_id', string="Section", readonly=False) question_sequence = fields.Integer('Sequence', related='question_id.sequence', store=True) # answer skipped = fields.Boolean('Skipped') answer_type = fields.Selection([ ('text_box', 'Free Text'), ('char_box', 'Text'), ('numerical_box', 'Number'), ('date', 'Date'), ('datetime', 'Datetime'), ('suggestion', 'Suggestion')], string='Answer Type') value_char_box = fields.Char('Text answer') value_numerical_box = fields.Float('Numerical answer') value_date = fields.Date('Date answer') value_datetime = fields.Datetime('Datetime answer') value_text_box = fields.Text('Free Text answer') suggested_answer_id = fields.Many2one('survey.question.answer', string="Suggested answer") matrix_row_id = fields.Many2one('survey.question.answer', string="Row answer") # scoring answer_score = fields.Float('Score') answer_is_correct = fields.Boolean('Correct') @api.constrains('skipped', 'answer_type') def _check_answer_type_skipped(self): for line in self: if (line.skipped == bool(line.answer_type)): raise ValidationError(_('A question can either be skipped or answered, not both.')) # allow 0 for numerical box if line.answer_type == 'numerical_box' and float_is_zero(line['value_numerical_box'], precision_digits=6): continue if line.answer_type == 'suggestion': field_name = 'suggested_answer_id' elif line.answer_type: field_name = 'value_%s' % line.answer_type else: # skipped field_name = False if field_name and not line[field_name]: raise ValidationError(_('The answer must be in the right type')) @api.model_create_multi def create(self, vals_list): for vals in vals_list: if not vals.get('answer_score'): score_vals = self._get_answer_score_values(vals) vals.update(score_vals) return super(SurveyUserInputLine, self).create(vals_list) def write(self, vals): res = True for line in self: vals_copy = {**vals} getter_params = { 'user_input_id': line.user_input_id.id, 'answer_type': line.answer_type, 'question_id': line.question_id.id, **vals_copy } if not vals_copy.get('answer_score'): score_vals = self._get_answer_score_values(getter_params, compute_speed_score=False) vals_copy.update(score_vals) res = super(SurveyUserInputLine, line).write(vals_copy) and res return res @api.model def _get_answer_score_values(self, vals, compute_speed_score=True): """ Get values for: answer_is_correct and associated answer_score. Requires vals to contain 'answer_type', 'question_id', and 'user_input_id'. Depending on 'answer_type' additional value of 'suggested_answer_id' may also be required. Calculates whether an answer_is_correct and its score based on 'answer_type' and corresponding question. Handles choice (answer_type == 'suggestion') questions separately from other question types. Each selected choice answer is handled as an individual answer. If score depends on the speed of the answer, it is adjusted as follows: - If the user answers in less than 2 seconds, they receive 100% of the possible points. - If user answers after that, they receive 50% of the possible points + the remaining 50% scaled by the time limit and time taken to answer [i.e. a minimum of 50% of the possible points is given to all correct answers] Example of returned values: * {'answer_is_correct': False, 'answer_score': 0} (default) * {'answer_is_correct': True, 'answer_score': 2.0} """ user_input_id = vals.get('user_input_id') answer_type = vals.get('answer_type') question_id = vals.get('question_id') if not question_id: raise ValueError(_('Computing score requires a question in arguments.')) question = self.env['survey.question'].browse(int(question_id)) # default and non-scored questions answer_is_correct = False answer_score = 0 # record selected suggested choice answer_score (can be: pos, neg, or 0) if question.question_type in ['simple_choice', 'multiple_choice']: if answer_type == 'suggestion': suggested_answer_id = vals.get('suggested_answer_id') if suggested_answer_id: question_answer = self.env['survey.question.answer'].browse(int(suggested_answer_id)) answer_score = question_answer.answer_score answer_is_correct = question_answer.is_correct # for all other scored question cases, record question answer_score (can be: pos or 0) elif question.is_scored_question: answer = vals.get('value_%s' % answer_type) if answer_type == 'numerical_box': answer = float(answer) elif answer_type == 'date': answer = fields.Date.from_string(answer) elif answer_type == 'datetime': answer = fields.Datetime.from_string(answer) if answer and answer == question['answer_%s' % answer_type]: answer_is_correct = True answer_score = question.answer_score if compute_speed_score and answer_score > 0: user_input = self.env['survey.user_input'].browse(user_input_id) session_speed_rating = user_input.exists() and user_input.is_session_answer and user_input.survey_id.session_speed_rating if session_speed_rating: max_score_delay = 2 time_limit = question.time_limit now = fields.Datetime.now() seconds_to_answer = (now - user_input.survey_id.session_question_start_time).total_seconds() question_remaining_time = time_limit - seconds_to_answer # if answered within the max_score_delay => leave score as is if question_remaining_time < 0: # if no time left answer_score /= 2 elif seconds_to_answer > max_score_delay: time_limit -= max_score_delay # we remove the max_score_delay to have all possible values score_proportion = (time_limit - seconds_to_answer) / time_limit answer_score = (answer_score / 2) * (1 + score_proportion) return { 'answer_is_correct': answer_is_correct, 'answer_score': answer_score }
49.639665
35,542
358
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class Challenge(models.Model): _inherit = 'gamification.challenge' challenge_category = fields.Selection(selection_add=[ ('certification', 'Certifications') ], ondelete={'certification': 'set default'})
29.833333
358
1,447
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' certifications_count = fields.Integer('Certifications Count', compute='_compute_certifications_count') certifications_company_count = fields.Integer('Company Certifications Count', compute='_compute_certifications_company_count') @api.depends('is_company') def _compute_certifications_count(self): read_group_res = self.env['survey.user_input'].sudo().read_group( [('partner_id', 'in', self.ids), ('scoring_success', '=', True)], ['partner_id'], 'partner_id' ) data = dict((res['partner_id'][0], res['partner_id_count']) for res in read_group_res) for partner in self: partner.certifications_count = data.get(partner.id, 0) @api.depends('is_company', 'child_ids.certifications_count') def _compute_certifications_company_count(self): self.certifications_company_count = sum(child.certifications_count for child in self.child_ids) def action_view_certifications(self): action = self.env["ir.actions.actions"]._for_xml_id("survey.res_partner_action_certifications") action['view_mode'] = 'tree' action['domain'] = ['|', ('partner_id', 'in', self.ids), ('partner_id', 'in', self.child_ids.ids)] return action
45.21875
1,447
38,228
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import logging import werkzeug from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from odoo import fields, http, SUPERUSER_ID, _ from odoo.addons.base.models.ir_ui_view import keep_query from odoo.exceptions import UserError from odoo.http import request, content_disposition from odoo.osv import expression from odoo.tools import format_datetime, format_date, is_html_empty _logger = logging.getLogger(__name__) class Survey(http.Controller): # ------------------------------------------------------------ # ACCESS # ------------------------------------------------------------ def _fetch_from_access_token(self, survey_token, answer_token): """ Check that given token matches an answer from the given survey_id. Returns a sudo-ed browse record of survey in order to avoid access rights issues now that access is granted through token. """ survey_sudo = request.env['survey.survey'].with_context(active_test=False).sudo().search([('access_token', '=', survey_token)]) if not answer_token: answer_sudo = request.env['survey.user_input'].sudo() else: answer_sudo = request.env['survey.user_input'].sudo().search([ ('survey_id', '=', survey_sudo.id), ('access_token', '=', answer_token) ], limit=1) return survey_sudo, answer_sudo def _check_validity(self, survey_token, answer_token, ensure_token=True, check_partner=True): """ Check survey is open and can be taken. This does not checks for security rules, only functional / business rules. It returns a string key allowing further manipulation of validity issues * survey_wrong: survey does not exist; * survey_auth: authentication is required; * survey_closed: survey is closed and does not accept input anymore; * survey_void: survey is void and should not be taken; * token_wrong: given token not recognized; * token_required: no token given although it is necessary to access the survey; * answer_deadline: token linked to an expired answer; :param ensure_token: whether user input existence based on given access token should be enforced or not, depending on the route requesting a token or allowing external world calls; :param check_partner: Whether we must check that the partner associated to the target answer corresponds to the active user. """ survey_sudo, answer_sudo = self._fetch_from_access_token(survey_token, answer_token) if not survey_sudo.exists(): return 'survey_wrong' if answer_token and not answer_sudo: return 'token_wrong' if not answer_sudo and ensure_token: return 'token_required' if not answer_sudo and survey_sudo.access_mode == 'token': return 'token_required' if survey_sudo.users_login_required and request.env.user._is_public(): return 'survey_auth' if not survey_sudo.active and (not answer_sudo or not answer_sudo.test_entry): return 'survey_closed' if (not survey_sudo.page_ids and survey_sudo.questions_layout == 'page_per_section') or not survey_sudo.question_ids: return 'survey_void' if answer_sudo and check_partner: if request.env.user._is_public() and answer_sudo.partner_id and not answer_token: # answers from public user should not have any partner_id; this indicates probably a cookie issue return 'answer_wrong_user' if not request.env.user._is_public() and answer_sudo.partner_id != request.env.user.partner_id: # partner mismatch, probably a cookie issue return 'answer_wrong_user' if answer_sudo and answer_sudo.deadline and answer_sudo.deadline < datetime.now(): return 'answer_deadline' return True def _get_access_data(self, survey_token, answer_token, ensure_token=True, check_partner=True): """ Get back data related to survey and user input, given the ID and access token provided by the route. : param ensure_token: whether user input existence should be enforced or not(see ``_check_validity``) : param check_partner: whether the partner of the target answer should be checked (see ``_check_validity``) """ survey_sudo, answer_sudo = request.env['survey.survey'].sudo(), request.env['survey.user_input'].sudo() has_survey_access, can_answer = False, False validity_code = self._check_validity(survey_token, answer_token, ensure_token=ensure_token, check_partner=check_partner) if validity_code != 'survey_wrong': survey_sudo, answer_sudo = self._fetch_from_access_token(survey_token, answer_token) try: survey_user = survey_sudo.with_user(request.env.user) survey_user.check_access_rights(self, 'read', raise_exception=True) survey_user.check_access_rule(self, 'read') except: pass else: has_survey_access = True can_answer = bool(answer_sudo) if not can_answer: can_answer = survey_sudo.access_mode == 'public' return { 'survey_sudo': survey_sudo, 'answer_sudo': answer_sudo, 'has_survey_access': has_survey_access, 'can_answer': can_answer, 'validity_code': validity_code, } def _redirect_with_error(self, access_data, error_key): survey_sudo = access_data['survey_sudo'] answer_sudo = access_data['answer_sudo'] if error_key == 'survey_void' and access_data['can_answer']: return request.render("survey.survey_void_content", {'survey': survey_sudo, 'answer': answer_sudo}) elif error_key == 'survey_closed' and access_data['can_answer']: return request.render("survey.survey_closed_expired", {'survey': survey_sudo}) elif error_key == 'survey_auth': if not answer_sudo: # survey is not even started redirect_url = '/web/login?redirect=/survey/start/%s' % survey_sudo.access_token elif answer_sudo.access_token: # survey is started but user is not logged in anymore. if answer_sudo.partner_id and (answer_sudo.partner_id.user_ids or survey_sudo.users_can_signup): if answer_sudo.partner_id.user_ids: answer_sudo.partner_id.signup_cancel() else: answer_sudo.partner_id.signup_prepare(expiration=fields.Datetime.now() + relativedelta(days=1)) 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] else: redirect_url = '/web/login?redirect=%s' % ('/survey/start/%s?answer_token=%s' % (survey_sudo.access_token, answer_sudo.access_token)) return request.render("survey.survey_auth_required", {'survey': survey_sudo, 'redirect_url': redirect_url}) elif error_key == 'answer_deadline' and answer_sudo.access_token: return request.render("survey.survey_closed_expired", {'survey': survey_sudo}) return request.redirect("/") # ------------------------------------------------------------ # TEST / RETRY SURVEY ROUTES # ------------------------------------------------------------ @http.route('/survey/test/<string:survey_token>', type='http', auth='user', website=True) def survey_test(self, survey_token, **kwargs): """ Test mode for surveys: create a test answer, only for managers or officers testing their surveys """ survey_sudo, dummy = self._fetch_from_access_token(survey_token, False) try: answer_sudo = survey_sudo._create_answer(user=request.env.user, test_entry=True) except: return request.redirect('/') return request.redirect('/survey/start/%s?%s' % (survey_sudo.access_token, keep_query('*', answer_token=answer_sudo.access_token))) @http.route('/survey/retry/<string:survey_token>/<string:answer_token>', type='http', auth='public', website=True) def survey_retry(self, survey_token, answer_token, **post): """ This route is called whenever the user has attempts left and hits the 'Retry' button after failing the survey.""" access_data = self._get_access_data(survey_token, answer_token, ensure_token=True) if access_data['validity_code'] is not True: return self._redirect_with_error(access_data, access_data['validity_code']) survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] if not answer_sudo: # attempts to 'retry' without having tried first return request.redirect("/") try: retry_answer_sudo = survey_sudo._create_answer( user=request.env.user, partner=answer_sudo.partner_id, email=answer_sudo.email, invite_token=answer_sudo.invite_token, test_entry=answer_sudo.test_entry, **self._prepare_retry_additional_values(answer_sudo) ) except: return request.redirect("/") return request.redirect('/survey/start/%s?%s' % (survey_sudo.access_token, keep_query('*', answer_token=retry_answer_sudo.access_token))) def _prepare_retry_additional_values(self, answer): return { 'deadline': answer.deadline, } def _prepare_survey_finished_values(self, survey, answer, token=False): values = {'survey': survey, 'answer': answer} if token: values['token'] = token if survey.scoring_type != 'no_scoring' and survey.certification: values['graph_data'] = json.dumps(answer._prepare_statistics()[answer]) return values # ------------------------------------------------------------ # TAKING SURVEY ROUTES # ------------------------------------------------------------ @http.route('/survey/start/<string:survey_token>', type='http', auth='public', website=True) def survey_start(self, survey_token, answer_token=None, email=False, **post): """ Start a survey by providing * a token linked to a survey; * a token linked to an answer or generate a new token if access is allowed; """ # Get the current answer token from cookie answer_from_cookie = False if not answer_token: answer_token = request.httprequest.cookies.get('survey_%s' % survey_token) answer_from_cookie = bool(answer_token) access_data = self._get_access_data(survey_token, answer_token, ensure_token=False) if answer_from_cookie and access_data['validity_code'] in ('answer_wrong_user', 'token_wrong'): # If the cookie had been generated for another user or does not correspond to any existing answer object # (probably because it has been deleted), ignore it and redo the check. # The cookie will be replaced by a legit value when resolving the URL, so we don't clean it further here. access_data = self._get_access_data(survey_token, None, ensure_token=False) if access_data['validity_code'] is not True: return self._redirect_with_error(access_data, access_data['validity_code']) survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] if not answer_sudo: try: answer_sudo = survey_sudo._create_answer(user=request.env.user, email=email) except UserError: answer_sudo = False if not answer_sudo: try: survey_sudo.with_user(request.env.user).check_access_rights('read') survey_sudo.with_user(request.env.user).check_access_rule('read') except: return request.redirect("/") else: return request.render("survey.survey_403_page", {'survey': survey_sudo}) return request.redirect('/survey/%s/%s' % (survey_sudo.access_token, answer_sudo.access_token)) def _prepare_survey_data(self, survey_sudo, answer_sudo, **post): """ This method prepares all the data needed for template rendering, in function of the survey user input state. :param post: - previous_page_id : come from the breadcrumb or the back button and force the next questions to load to be the previous ones. """ data = { 'is_html_empty': is_html_empty, 'survey': survey_sudo, 'answer': answer_sudo, 'breadcrumb_pages': [{ 'id': page.id, 'title': page.title, } for page in survey_sudo.page_ids], 'format_datetime': lambda dt: format_datetime(request.env, dt, dt_format=False), 'format_date': lambda date: format_date(request.env, date) } if survey_sudo.questions_layout != 'page_per_question': triggering_answer_by_question, triggered_questions_by_answer, selected_answers = answer_sudo._get_conditional_values() data.update({ 'triggering_answer_by_question': { question.id: triggering_answer_by_question[question].id for question in triggering_answer_by_question.keys() if triggering_answer_by_question[question] }, 'triggered_questions_by_answer': { answer.id: triggered_questions_by_answer[answer].ids for answer in triggered_questions_by_answer.keys() }, 'selected_answers': selected_answers.ids }) if not answer_sudo.is_session_answer and survey_sudo.is_time_limited and answer_sudo.start_datetime: data.update({ 'server_time': fields.Datetime.now(), 'timer_start': answer_sudo.start_datetime.isoformat(), 'time_limit_minutes': survey_sudo.time_limit }) page_or_question_key = 'question' if survey_sudo.questions_layout == 'page_per_question' else 'page' # Bypass all if page_id is specified (comes from breadcrumb or previous button) if 'previous_page_id' in post: previous_page_or_question_id = int(post['previous_page_id']) new_previous_id = survey_sudo._get_next_page_or_question(answer_sudo, previous_page_or_question_id, go_back=True).id page_or_question = request.env['survey.question'].sudo().browse(previous_page_or_question_id) data.update({ page_or_question_key: page_or_question, 'previous_page_id': new_previous_id, 'has_answered': answer_sudo.user_input_line_ids.filtered(lambda line: line.question_id.id == new_previous_id), 'can_go_back': survey_sudo._can_go_back(answer_sudo, page_or_question), }) return data if answer_sudo.state == 'in_progress': if answer_sudo.is_session_answer: next_page_or_question = survey_sudo.session_question_id else: next_page_or_question = survey_sudo._get_next_page_or_question( answer_sudo, answer_sudo.last_displayed_page_id.id if answer_sudo.last_displayed_page_id else 0) if next_page_or_question: data.update({ 'survey_last': survey_sudo._is_last_page_or_question(answer_sudo, next_page_or_question) }) if answer_sudo.is_session_answer and next_page_or_question.is_time_limited: data.update({ 'timer_start': survey_sudo.session_question_start_time.isoformat(), 'time_limit_minutes': next_page_or_question.time_limit / 60 }) data.update({ page_or_question_key: next_page_or_question, 'has_answered': answer_sudo.user_input_line_ids.filtered(lambda line: line.question_id == next_page_or_question), 'can_go_back': survey_sudo._can_go_back(answer_sudo, next_page_or_question), }) if survey_sudo.questions_layout != 'one_page': data.update({ 'previous_page_id': survey_sudo._get_next_page_or_question(answer_sudo, next_page_or_question.id, go_back=True).id }) elif answer_sudo.state == 'done' or answer_sudo.survey_time_limit_reached: # Display success message return self._prepare_survey_finished_values(survey_sudo, answer_sudo) return data def _prepare_question_html(self, survey_sudo, answer_sudo, **post): """ Survey page navigation is done in AJAX. This function prepare the 'next page' to display in html and send back this html to the survey_form widget that will inject it into the page.""" survey_data = self._prepare_survey_data(survey_sudo, answer_sudo, **post) survey_content = False if answer_sudo.state == 'done': survey_content = request.env.ref('survey.survey_fill_form_done')._render(survey_data) else: survey_content = request.env.ref('survey.survey_fill_form_in_progress')._render(survey_data) survey_progress = False if answer_sudo.state == 'in_progress' and not survey_data.get('question', request.env['survey.question']).is_page: if survey_sudo.questions_layout == 'page_per_section': page_ids = survey_sudo.page_ids.ids survey_progress = request.env.ref('survey.survey_progression')._render({ 'survey': survey_sudo, 'page_ids': page_ids, 'page_number': page_ids.index(survey_data['page'].id) + (1 if survey_sudo.progression_mode == 'number' else 0) }) elif survey_sudo.questions_layout == 'page_per_question': page_ids = (answer_sudo.predefined_question_ids.ids if not answer_sudo.is_session_answer else survey_sudo.question_ids.ids) survey_progress = request.env.ref('survey.survey_progression')._render({ 'survey': survey_sudo, 'page_ids': page_ids, 'page_number': page_ids.index(survey_data['question'].id) }) return { 'survey_content': survey_content, 'survey_progress': survey_progress, 'survey_navigation': request.env.ref('survey.survey_navigation')._render(survey_data), } @http.route('/survey/<string:survey_token>/<string:answer_token>', type='http', auth='public', website=True) def survey_display_page(self, survey_token, answer_token, **post): access_data = self._get_access_data(survey_token, answer_token, ensure_token=True) if access_data['validity_code'] is not True: return self._redirect_with_error(access_data, access_data['validity_code']) answer_sudo = access_data['answer_sudo'] if answer_sudo.state != 'done' and answer_sudo.survey_time_limit_reached: answer_sudo._mark_done() return request.render('survey.survey_page_fill', self._prepare_survey_data(access_data['survey_sudo'], answer_sudo, **post)) @http.route('/survey/get_background_image/<string:survey_token>/<string:answer_token>', type='http', auth="public", website=True, sitemap=False) def survey_get_background(self, survey_token, answer_token): access_data = self._get_access_data(survey_token, answer_token, ensure_token=True) if access_data['validity_code'] is not True: return werkzeug.exceptions.Forbidden() survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] status, headers, image_base64 = request.env['ir.http'].sudo().binary_content( model='survey.survey', id=survey_sudo.id, field='background_image', default_mimetype='image/png') return request.env['ir.http']._content_image_get_response(status, headers, image_base64) @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) def survey_get_question_image(self, survey_token, answer_token, question_id, suggested_answer_id): access_data = self._get_access_data(survey_token, answer_token, ensure_token=True) if access_data['validity_code'] is not True: return werkzeug.exceptions.Forbidden() survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] if not survey_sudo.question_ids.filtered(lambda q: q.id == question_id)\ .suggested_answer_ids.filtered(lambda a: a.id == suggested_answer_id): return werkzeug.exceptions.NotFound() status, headers, image_base64 = request.env['ir.http'].sudo().binary_content( model='survey.question.answer', id=suggested_answer_id, field='value_image', default_mimetype='image/png') return request.env['ir.http']._content_image_get_response(status, headers, image_base64) # ---------------------------------------------------------------- # JSON ROUTES to begin / continue survey (ajax navigation) + Tools # ---------------------------------------------------------------- @http.route('/survey/begin/<string:survey_token>/<string:answer_token>', type='json', auth='public', website=True) def survey_begin(self, survey_token, answer_token, **post): """ Route used to start the survey user input and display the first survey page. """ access_data = self._get_access_data(survey_token, answer_token, ensure_token=True) if access_data['validity_code'] is not True: return {'error': access_data['validity_code']} survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] if answer_sudo.state != "new": return {'error': _("The survey has already started.")} answer_sudo._mark_in_progress() return self._prepare_question_html(survey_sudo, answer_sudo, **post) @http.route('/survey/next_question/<string:survey_token>/<string:answer_token>', type='json', auth='public', website=True) def survey_next_question(self, survey_token, answer_token, **post): """ Method used to display the next survey question in an ongoing session. Triggered on all attendees screens when the host goes to the next question. """ access_data = self._get_access_data(survey_token, answer_token, ensure_token=True) if access_data['validity_code'] is not True: return {'error': access_data['validity_code']} survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] if answer_sudo.state == 'new' and answer_sudo.is_session_answer: answer_sudo._mark_in_progress() return self._prepare_question_html(survey_sudo, answer_sudo, **post) @http.route('/survey/submit/<string:survey_token>/<string:answer_token>', type='json', auth='public', website=True) def survey_submit(self, survey_token, answer_token, **post): """ Submit a page from the survey. This will take into account the validation errors and store the answers to the questions. If the time limit is reached, errors will be skipped, answers will be ignored and survey state will be forced to 'done'""" # Survey Validation access_data = self._get_access_data(survey_token, answer_token, ensure_token=True) if access_data['validity_code'] is not True: return {'error': access_data['validity_code']} survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] if answer_sudo.state == 'done': return {'error': 'unauthorized'} questions, page_or_question_id = survey_sudo._get_survey_questions(answer=answer_sudo, page_id=post.get('page_id'), question_id=post.get('question_id')) if not answer_sudo.test_entry and not survey_sudo._has_attempts_left(answer_sudo.partner_id, answer_sudo.email, answer_sudo.invite_token): # prevent cheating with users creating multiple 'user_input' before their last attempt return {'error': 'unauthorized'} if answer_sudo.survey_time_limit_reached or answer_sudo.question_time_limit_reached: if answer_sudo.question_time_limit_reached: time_limit = survey_sudo.session_question_start_time + relativedelta( seconds=survey_sudo.session_question_id.time_limit ) time_limit += timedelta(seconds=3) else: time_limit = answer_sudo.start_datetime + timedelta(minutes=survey_sudo.time_limit) time_limit += timedelta(seconds=10) if fields.Datetime.now() > time_limit: # prevent cheating with users blocking the JS timer and taking all their time to answer return {'error': 'unauthorized'} errors = {} # Prepare answers / comment by question, validate and save answers for question in questions: inactive_questions = request.env['survey.question'] if answer_sudo.is_session_answer else answer_sudo._get_inactive_conditional_questions() if question in inactive_questions: # if question is inactive, skip validation and save continue answer, comment = self._extract_comment_from_answers(question, post.get(str(question.id))) errors.update(question.validate_question(answer, comment)) if not errors.get(question.id): answer_sudo.save_lines(question, answer, comment) if errors and not (answer_sudo.survey_time_limit_reached or answer_sudo.question_time_limit_reached): return {'error': 'validation', 'fields': errors} if not answer_sudo.is_session_answer: answer_sudo._clear_inactive_conditional_answers() if answer_sudo.survey_time_limit_reached or survey_sudo.questions_layout == 'one_page': answer_sudo._mark_done() elif 'previous_page_id' in post: # Go back to specific page using the breadcrumb. Lines are saved and survey continues return self._prepare_question_html(survey_sudo, answer_sudo, **post) else: vals = {'last_displayed_page_id': page_or_question_id} if not answer_sudo.is_session_answer: next_page = survey_sudo._get_next_page_or_question(answer_sudo, page_or_question_id) if not next_page: answer_sudo._mark_done() answer_sudo.write(vals) return self._prepare_question_html(survey_sudo, answer_sudo) def _extract_comment_from_answers(self, question, answers): """ Answers is a custom structure depending of the question type that can contain question answers but also comments that need to be extracted before validating and saving answers. If multiple answers, they are listed in an array, except for matrix where answers are structured differently. See input and output for more info on data structures. :param question: survey.question :param answers: * question_type: free_text, text_box, numerical_box, date, datetime answers is a string containing the value * question_type: simple_choice with no comment answers is a string containing the value ('question_id_1') * question_type: simple_choice with comment ['question_id_1', {'comment': str}] * question_type: multiple choice ['question_id_1', 'question_id_2'] + [{'comment': str}] if holds a comment * question_type: matrix {'matrix_row_id_1': ['question_id_1', 'question_id_2'], 'matrix_row_id_2': ['question_id_1', 'question_id_2'] } + {'comment': str} if holds a comment :return: tuple( same structure without comment, extracted comment for given question ) """ comment = None answers_no_comment = [] if answers: if question.question_type == 'matrix': if 'comment' in answers: comment = answers['comment'].strip() answers.pop('comment') answers_no_comment = answers else: if not isinstance(answers, list): answers = [answers] for answer in answers: if isinstance(answer, dict) and 'comment' in answer: comment = answer['comment'].strip() else: answers_no_comment.append(answer) if len(answers_no_comment) == 1: answers_no_comment = answers_no_comment[0] return answers_no_comment, comment # ------------------------------------------------------------ # COMPLETED SURVEY ROUTES # ------------------------------------------------------------ @http.route('/survey/print/<string:survey_token>', type='http', auth='public', website=True, sitemap=False) def survey_print(self, survey_token, review=False, answer_token=None, **post): '''Display an survey in printable view; if <answer_token> is set, it will grab the answers of the user_input_id that has <answer_token>.''' access_data = self._get_access_data(survey_token, answer_token, ensure_token=False, check_partner=False) if access_data['validity_code'] is not True and ( access_data['has_survey_access'] or access_data['validity_code'] not in ['token_required', 'survey_closed', 'survey_void']): return self._redirect_with_error(access_data, access_data['validity_code']) survey_sudo, answer_sudo = access_data['survey_sudo'], access_data['answer_sudo'] return request.render('survey.survey_page_print', { 'is_html_empty': is_html_empty, 'review': review, 'survey': survey_sudo, 'answer': answer_sudo if survey_sudo.scoring_type != 'scoring_without_answers' else answer_sudo.browse(), 'questions_to_display': answer_sudo._get_print_questions(), 'scoring_display_correction': survey_sudo.scoring_type == 'scoring_with_answers' and answer_sudo, 'format_datetime': lambda dt: format_datetime(request.env, dt, dt_format=False), 'format_date': lambda date: format_date(request.env, date), }) @http.route('/survey/<model("survey.survey"):survey>/certification_preview', type="http", auth="user", website=True) def show_certification_pdf(self, survey, **kwargs): preview_url = '/survey/%s/get_certification_preview' % survey.id return request.render('survey.certification_preview', { 'preview_url': preview_url, 'page_title': survey.title, }) @http.route(['/survey/<model("survey.survey"):survey>/get_certification_preview'], type="http", auth="user", methods=['GET'], website=True) def survey_get_certification_preview(self, survey, **kwargs): if not request.env.user.has_group('survey.group_survey_user'): raise werkzeug.exceptions.Forbidden() fake_user_input = survey._create_answer(user=request.env.user, test_entry=True) response = self._generate_report(fake_user_input, download=False) fake_user_input.sudo().unlink() return response @http.route(['/survey/<int:survey_id>/get_certification'], type='http', auth='user', methods=['GET'], website=True) def survey_get_certification(self, survey_id, **kwargs): """ The certification document can be downloaded as long as the user has succeeded the certification """ survey = request.env['survey.survey'].sudo().search([ ('id', '=', survey_id), ('certification', '=', True) ]) if not survey: # no certification found return request.redirect("/") succeeded_attempt = request.env['survey.user_input'].sudo().search([ ('partner_id', '=', request.env.user.partner_id.id), ('survey_id', '=', survey_id), ('scoring_success', '=', True) ], limit=1) if not succeeded_attempt: raise UserError(_("The user has not succeeded the certification")) return self._generate_report(succeeded_attempt, download=True) # ------------------------------------------------------------ # REPORTING SURVEY ROUTES AND TOOLS # ------------------------------------------------------------ @http.route('/survey/results/<model("survey.survey"):survey>', type='http', auth='user', website=True) def survey_report(self, survey, answer_token=None, **post): """ Display survey Results & Statistics for given survey. New structure: { 'survey': current survey browse record, 'question_and_page_data': see ``SurveyQuestion._prepare_statistics()``, 'survey_data'= see ``SurveySurvey._prepare_statistics()`` 'search_filters': [], 'search_finished': either filter on finished inputs only or not, } """ user_input_lines, search_filters = self._extract_filters_data(survey, post) survey_data = survey._prepare_statistics(user_input_lines) question_and_page_data = survey.question_and_page_ids._prepare_statistics(user_input_lines) template_values = { # survey and its statistics 'survey': survey, 'question_and_page_data': question_and_page_data, 'survey_data': survey_data, # search 'search_filters': search_filters, 'search_finished': post.get('finished') == 'true', } if survey.session_show_leaderboard: template_values['leaderboard'] = survey._prepare_leaderboard_values() return request.render('survey.survey_page_statistics', template_values) def _generate_report(self, user_input, download=True): report = request.env.ref('survey.certification_report').with_user(SUPERUSER_ID)._render_qweb_pdf([user_input.id], data={'report_type': 'pdf'})[0] report_content_disposition = content_disposition('Certification.pdf') if not download: content_split = report_content_disposition.split(';') content_split[0] = 'inline' report_content_disposition = ';'.join(content_split) return request.make_response(report, headers=[ ('Content-Type', 'application/pdf'), ('Content-Length', len(report)), ('Content-Disposition', report_content_disposition), ]) def _get_user_input_domain(self, survey, line_filter_domain, **post): user_input_domain = ['&', ('test_entry', '=', False), ('survey_id', '=', survey.id)] if line_filter_domain: matching_line_ids = request.env['survey.user_input.line'].sudo().search(line_filter_domain).ids user_input_domain = expression.AND([ [('user_input_line_ids', 'in', matching_line_ids)], user_input_domain ]) if post.get('finished'): user_input_domain = expression.AND([[('state', '=', 'done')], user_input_domain]) else: user_input_domain = expression.AND([[('state', '!=', 'new')], user_input_domain]) return user_input_domain def _extract_filters_data(self, survey, post): search_filters = [] line_filter_domain, line_choices = [], [] for data in post.get('filters', '').split('|'): try: row_id, answer_id = (int(item) for item in data.split(',')) except: pass else: if row_id and answer_id: line_filter_domain = expression.AND([ ['&', ('matrix_row_id', '=', row_id), ('suggested_answer_id', '=', answer_id)], line_filter_domain ]) answers = request.env['survey.question.answer'].browse([row_id, answer_id]) elif answer_id: line_choices.append(answer_id) answers = request.env['survey.question.answer'].browse([answer_id]) if answer_id: question_id = answers[0].matrix_question_id or answers[0].question_id search_filters.append({ 'question': question_id.title, 'answers': '%s%s' % (answers[0].value, ': %s' % answers[1].value if len(answers) > 1 else '') }) if line_choices: line_filter_domain = expression.AND([[('suggested_answer_id', 'in', line_choices)], line_filter_domain]) user_input_domain = self._get_user_input_domain(survey, line_filter_domain, **post) user_input_lines = request.env['survey.user_input'].sudo().search(user_input_domain).mapped('user_input_line_ids') return user_input_lines, search_filters
52.438957
38,228
11,816
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import json from dateutil.relativedelta import relativedelta from werkzeug.exceptions import NotFound from odoo import fields, http from odoo.http import request from odoo.tools import is_html_empty class UserInputSession(http.Controller): def _fetch_from_token(self, survey_token): """ Check that given survey_token matches a survey 'access_token'. Unlike the regular survey controller, user trying to access the survey must have full access rights! """ return request.env['survey.survey'].search([('access_token', '=', survey_token)]) def _fetch_from_session_code(self, session_code): """ Matches a survey against a passed session_code. We don't limit the session_state to be reachable (ready / in_progress) here because in some cases, we want closed session as well (where session_state = False). Instead, when necessary, the reachability is forced in routes calling this method to avoid people using those routes to access other (private) surveys. We limit to sessions opened within the last 7 days to avoid potential abuses. """ if session_code: matching_survey = request.env['survey.survey'].sudo().search([ ('session_start_time', '>', fields.Datetime.now() - relativedelta(days=7)), ('session_code', '=', session_code), ], limit=1) if matching_survey: return matching_survey return False # ------------------------------------------------------------ # SURVEY SESSION MANAGEMENT # ------------------------------------------------------------ @http.route('/survey/session/manage/<string:survey_token>', type='http', auth='user', website=True) def survey_session_manage(self, survey_token, **kwargs): """ Main route used by the host to 'manager' the session. - If the state of the session is 'ready' We render a template allowing the host to showcase the different options of the session and to actually start the session. If there are no questions, a "void content" is displayed instead to avoid displaying a blank survey. - If the state of the session is 'in_progress' We render a template allowing the host to show the question results, display the attendees leaderboard or go to the next question of the session. """ survey = self._fetch_from_token(survey_token) if not survey or not survey.session_state: # no open session return NotFound() if survey.session_state == 'ready': if not survey.question_ids: return request.render('survey.survey_void_content', { 'survey': survey, 'answer': request.env['survey.user_input'], }) return request.render('survey.user_input_session_open', { 'survey': survey }) else: template_values = self._prepare_manage_session_values(survey) return request.render('survey.user_input_session_manage', template_values) @http.route('/survey/session/next_question/<string:survey_token>', type='json', auth='user', website=True) def survey_session_next_question(self, survey_token, go_back=False, **kwargs): """ This route is called when the host goes to the next question of the session. It's not a regular 'request.render' route because we handle the transition between questions using a AJAX call to be able to display a bioutiful fade in/out effect. It triggers the next question of the session. We artificially add 1 second to the 'current_question_start_time' to account for server delay. As the timing can influence the attendees score, we try to be fair with everyone by giving them an extra second before we start counting down. Frontend should take the delay into account by displaying the appropriate animations. Writing the next question on the survey is sudo'ed to avoid potential access right issues. e.g: a survey user can create a live session from any survey but he can only write on its own survey. """ survey = self._fetch_from_token(survey_token) if not survey or not survey.session_state: # no open session return '' if survey.session_state == 'ready': survey._session_open() next_question = survey._get_session_next_question(go_back) # using datetime.datetime because we want the millis portion if next_question: now = datetime.datetime.now() survey.sudo().write({ 'session_question_id': next_question.id, 'session_question_start_time': fields.Datetime.now() + relativedelta(seconds=1) }) request.env['bus.bus']._sendone(survey.access_token, 'next_question', {'question_start': now.timestamp()}) template_values = self._prepare_manage_session_values(survey) template_values['is_rpc_call'] = True return request.env.ref('survey.user_input_session_manage_content')._render(template_values) else: return False @http.route('/survey/session/results/<string:survey_token>', type='json', auth='user', website=True) def survey_session_results(self, survey_token, **kwargs): """ This route is called when the host shows the current question's results. It's not a regular 'request.render' route because we handle the display of results using an AJAX request to be able to include the results in the currently displayed page. """ survey = self._fetch_from_token(survey_token) if not survey or survey.session_state != 'in_progress': # no open session return False user_input_lines = request.env['survey.user_input.line'].search([ ('survey_id', '=', survey.id), ('question_id', '=', survey.session_question_id.id), ('create_date', '>=', survey.session_start_time) ]) return self._prepare_question_results_values(survey, user_input_lines) @http.route('/survey/session/leaderboard/<string:survey_token>', type='json', auth='user', website=True) def survey_session_leaderboard(self, survey_token, **kwargs): """ This route is called when the host shows the current question's attendees leaderboard. It's not a regular 'request.render' route because we handle the display of the leaderboard using an AJAX request to be able to include the results in the currently displayed page. """ survey = self._fetch_from_token(survey_token) if not survey or survey.session_state != 'in_progress': # no open session return '' return request.env.ref('survey.user_input_session_leaderboard')._render({ 'animate': True, 'leaderboard': survey._prepare_leaderboard_values() }) # ------------------------------------------------------------ # QUICK ACCESS SURVEY ROUTES # ------------------------------------------------------------ @http.route('/s', type='http', auth='public', website=True, sitemap=False) def survey_session_code(self, **post): """ Renders the survey session code page route. This page allows the user to enter the session code of the survey. It is mainly used to ease survey access for attendees in session mode. """ return request.render("survey.survey_session_code") @http.route('/s/<string:session_code>', type='http', auth='public', website=True) def survey_start_short(self, session_code): """" Redirects to 'survey_start' route using a shortened link & token. We match the session_code for open surveys. This route is used in survey sessions where we need short links for people to type. """ survey = self._fetch_from_session_code(session_code) if survey and survey.session_state in ['ready', 'in_progress']: return request.redirect("/survey/start/%s" % survey.access_token) return request.redirect("/s") @http.route('/survey/check_session_code/<string:session_code>', type='json', auth='public', website=True) def survey_check_session_code(self, session_code): """ Checks if the given code is matching a survey session_code. If yes, redirect to /s/code route. If not, return error. The user is invited to type again the code. """ survey = self._fetch_from_session_code(session_code) if survey: if survey.session_state in ['ready', 'in_progress']: return {"survey_url": "/survey/start/%s" % survey.access_token} else: return {"error": "survey_session_closed"} return {"error": "survey_wrong"} def _prepare_manage_session_values(self, survey): is_first_question, is_last_question = False, False if survey.question_ids: most_voted_answers = survey._get_session_most_voted_answers() is_first_question = survey._is_first_page_or_question(survey.session_question_id) is_last_question = survey._is_last_page_or_question(most_voted_answers, survey.session_question_id) values = { 'survey': survey, 'is_last_question': is_last_question, 'is_first_question': is_first_question, } values.update(self._prepare_question_results_values(survey, request.env['survey.user_input.line'])) return values def _prepare_question_results_values(self, survey, user_input_lines): """ Prepares usefull values to display during the host session: - question_statistics_graph The graph data to display the bar chart for questions of type 'choice' - input_lines_values The answer values to text/date/datetime questions - answers_validity An array containing the is_correct value for all question answers. We need this special variable because of Chartjs data structure. The library determines the parameters (color/label/...) by only passing the answer 'index' (and not the id or anything else we can identify). In other words, we need to know if the answer at index 2 is correct or not. - answer_count The number of answers to the current question. """ question = survey.session_question_id answers_validity = [] if (any(answer.is_correct for answer in question.suggested_answer_ids)): answers_validity = [answer.is_correct for answer in question.suggested_answer_ids] if question.comment_count_as_answer: answers_validity.append(False) full_statistics = question._prepare_statistics(user_input_lines)[0] input_line_values = [] if question.question_type in ['char_box', 'date', 'datetime']: input_line_values = [{ 'id': line.id, 'value': line['value_%s' % question.question_type] } for line in full_statistics.get('table_data', request.env['survey.user_input.line'])[:100]] return { 'is_html_empty': is_html_empty, 'question_statistics_graph': full_statistics.get('graph_data'), 'input_line_values': input_line_values, 'answers_validity': json.dumps(answers_validity), 'answer_count': survey.session_question_answer_count, 'attendees_count': survey.session_answer_count, }
47.453815
11,816
540
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Maintenance - HR', 'version': '1.0', 'sequence': 125, 'category': 'Human Resources', 'description': """ Bridge between HR and Maintenance.""", 'depends': ['hr', 'maintenance'], 'summary': 'Equipments, Assets, Internal Hardware, Allocation Tracking', 'data': [ 'security/equipment.xml', 'views/maintenance_views.xml', 'views/hr_views.xml', ], 'demo': [], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
25.714286
540
5,930
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, tools class MaintenanceEquipment(models.Model): _inherit = 'maintenance.equipment' employee_id = fields.Many2one('hr.employee', compute='_compute_equipment_assign', store=True, readonly=False, string='Assigned Employee', tracking=True) department_id = fields.Many2one('hr.department', compute='_compute_equipment_assign', store=True, readonly=False, string='Assigned Department', tracking=True) equipment_assign_to = fields.Selection( [('department', 'Department'), ('employee', 'Employee'), ('other', 'Other')], string='Used By', required=True, default='employee') owner_user_id = fields.Many2one(compute='_compute_owner', store=True) assign_date = fields.Date(compute='_compute_equipment_assign', store=True, readonly=False, copy=True) @api.depends('employee_id', 'department_id', 'equipment_assign_to') def _compute_owner(self): for equipment in self: equipment.owner_user_id = self.env.user.id if equipment.equipment_assign_to == 'employee': equipment.owner_user_id = equipment.employee_id.user_id.id elif equipment.equipment_assign_to == 'department': equipment.owner_user_id = equipment.department_id.manager_id.user_id.id @api.depends('equipment_assign_to') def _compute_equipment_assign(self): for equipment in self: if equipment.equipment_assign_to == 'employee': equipment.department_id = False equipment.employee_id = equipment.employee_id elif equipment.equipment_assign_to == 'department': equipment.employee_id = False equipment.department_id = equipment.department_id else: equipment.department_id = equipment.department_id equipment.employee_id = equipment.employee_id equipment.assign_date = fields.Date.context_today(self) @api.model def create(self, vals): equipment = super(MaintenanceEquipment, self).create(vals) # subscribe employee or department manager when equipment assign to him. partner_ids = [] if equipment.employee_id and equipment.employee_id.user_id: partner_ids.append(equipment.employee_id.user_id.partner_id.id) if equipment.department_id and equipment.department_id.manager_id and equipment.department_id.manager_id.user_id: partner_ids.append(equipment.department_id.manager_id.user_id.partner_id.id) if partner_ids: equipment.message_subscribe(partner_ids=partner_ids) return equipment def write(self, vals): partner_ids = [] # subscribe employee or department manager when equipment assign to employee or department. if vals.get('employee_id'): user_id = self.env['hr.employee'].browse(vals['employee_id'])['user_id'] if user_id: partner_ids.append(user_id.partner_id.id) if vals.get('department_id'): department = self.env['hr.department'].browse(vals['department_id']) if department and department.manager_id and department.manager_id.user_id: partner_ids.append(department.manager_id.user_id.partner_id.id) if partner_ids: self.message_subscribe(partner_ids=partner_ids) return super(MaintenanceEquipment, self).write(vals) def _track_subtype(self, init_values): self.ensure_one() if ('employee_id' in init_values and self.employee_id) or ('department_id' in init_values and self.department_id): return self.env.ref('maintenance.mt_mat_assign') return super(MaintenanceEquipment, self)._track_subtype(init_values) class MaintenanceRequest(models.Model): _inherit = 'maintenance.request' @api.returns('self') def _default_employee_get(self): return self.env.user.employee_id employee_id = fields.Many2one('hr.employee', string='Employee', default=_default_employee_get) owner_user_id = fields.Many2one(compute='_compute_owner', store=True) equipment_id = fields.Many2one(domain="['|', ('employee_id', '=', employee_id), ('employee_id', '=', False)]") @api.depends('employee_id') def _compute_owner(self): for r in self: if r.equipment_id.equipment_assign_to == 'employee': r.owner_user_id = r.employee_id.user_id.id else: r.owner_user_id = False @api.model def create(self, vals): result = super(MaintenanceRequest, self).create(vals) if result.employee_id.user_id: result.message_subscribe(partner_ids=[result.employee_id.user_id.partner_id.id]) return result def write(self, vals): if vals.get('employee_id'): employee = self.env['hr.employee'].browse(vals['employee_id']) if employee and employee.user_id: self.message_subscribe(partner_ids=[employee.user_id.partner_id.id]) return super(MaintenanceRequest, self).write(vals) @api.model def message_new(self, msg, custom_values=None): """ Overrides mail_thread message_new that is called by the mailgateway through message_process. This override updates the document according to the email. """ if custom_values is None: custom_values = {} email = tools.email_split(msg.get('from')) and tools.email_split(msg.get('from'))[0] or False user = self.env['res.users'].search([('login', '=', email)], limit=1) if user: employee = self.env.user.employee_id if employee: custom_values['employee_id'] = employee and employee[0].id return super(MaintenanceRequest, self).message_new(msg, custom_values=custom_values)
47.063492
5,930
821
py
PYTHON
15.0
from odoo import api, models, fields class Users(models.Model): _inherit = 'res.users' equipment_ids = fields.One2many('maintenance.equipment', 'owner_user_id', string="Managed Equipments") equipment_count = fields.Integer(related='employee_id.equipment_count', string="Assigned Equipments") @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + ['equipment_count'] class Employee(models.Model): _inherit = 'hr.employee' equipment_ids = fields.One2many('maintenance.equipment', 'employee_id') equipment_count = fields.Integer('Equipments', compute='_compute_equipment_count') @api.depends('equipment_ids') def _compute_equipment_count(self): for employee in self: employee.equipment_count = len(employee.equipment_ids)
34.208333
821
3,853
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'eCommerce', 'category': 'Website/Website', 'sequence': 50, 'summary': 'Sell your products online', 'website': 'https://www.odoo.com/app/ecommerce', 'version': '1.1', 'description': "", 'depends': ['website', 'sale', 'website_payment', 'website_mail', 'portal_rating', 'digest'], 'data': [ 'security/ir.model.access.csv', 'security/website_sale.xml', 'data/data.xml', 'data/mail_template_data.xml', 'data/product_snippet_template_data.xml', 'data/digest_data.xml', 'views/product_attribute_views.xml', 'views/product_views.xml', 'views/account_views.xml', 'views/onboarding_views.xml', 'views/sale_report_views.xml', 'views/sale_order_views.xml', 'views/crm_team_views.xml', 'views/templates.xml', 'views/snippets/snippets.xml', 'views/snippets/s_dynamic_snippet_products.xml', 'views/res_config_settings_views.xml', 'views/digest_views.xml', 'views/website_sale_visitor_views.xml', 'views/base_unit_view.xml' ], 'demo': [ 'data/demo.xml', ], 'installable': True, 'application': True, 'post_init_hook': '_post_init_hook', 'uninstall_hook': 'uninstall_hook', 'assets': { 'web.assets_frontend': [ 'website_sale/static/src/scss/website_sale.scss', 'website_sale/static/src/scss/website_mail.scss', 'website_sale/static/src/scss/website_sale_frontend.scss', 'website/static/lib/multirange/multirange_custom.scss', 'sale/static/src/scss/sale_portal.scss', 'sale/static/src/scss/product_configurator.scss', 'sale/static/src/js/variant_mixin.js', 'website_sale/static/src/js/variant_mixin.js', 'website_sale/static/src/js/website_sale.js', 'website_sale/static/src/js/website_sale_utils.js', 'website_sale/static/src/js/website_sale_payment.js', 'website_sale/static/src/js/website_sale_validate.js', 'website_sale/static/src/js/website_sale_recently_viewed.js', 'website_sale/static/src/js/website_sale_tracking.js', 'website/static/lib/multirange/multirange_custom.js', 'website_sale/static/src/js/website_sale_category_link.js', ], 'web._assets_primary_variables': [ 'website_sale/static/src/scss/primary_variables.scss', ], 'web.assets_backend': [ 'website_sale/static/src/js/website_sale_video_field_preview.js', 'website_sale/static/src/js/website_sale_backend.js', 'website_sale/static/src/scss/website_sale_dashboard.scss', 'website_sale/static/src/scss/website_sale_backend.scss', 'website_sale/static/src/js/tours/website_sale_shop_backend.js', ], 'website.assets_wysiwyg': [ 'website_sale/static/src/scss/website_sale.editor.scss', 'website_sale/static/src/snippets/s_dynamic_snippet_products/options.js', ], 'website.assets_editor': [ 'website_sale/static/src/js/website_sale.editor.js', 'website_sale/static/src/js/website_sale_form_editor.js', 'website_sale/static/src/js/tours/website_sale_shop_frontend.js', ], 'web.assets_common': [ 'website_sale/static/src/js/tours/tour_utils.js', 'website_sale/static/src/js/tours/website_sale_shop.js', ], 'web.assets_tests': [ 'website_sale/static/tests/**/*', ], 'web.assets_qweb': [ 'website_sale/static/src/xml/*.xml', ], }, 'license': 'LGPL-3', }
41.880435
3,853
2,553
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.models import Command from odoo.tests.common import tagged from odoo.addons.payment.tests.common import PaymentCommon from odoo.addons.website.tools import MockRequest @tagged('post_install', '-at_install') class WebsiteSaleCartPayment(PaymentCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.website = cls.env['website'].get_current_website() with MockRequest(cls.env, website=cls.website): cls.order = cls.website.sale_get_order(force_create=True) # Create the cart to retrieve cls.tx = cls.env['payment.transaction'].create({ 'amount': cls.amount, 'currency_id': cls.currency.id, 'acquirer_id': cls.acquirer.id, 'reference': cls.reference, 'operation': 'online_redirect', 'partner_id': cls.partner.id, }) cls.order.write({'transaction_ids': [Command.set([cls.tx.id])]}) def test_unpaid_orders_can_be_retrieved(self): """ Test that fetching sales orders linked to a payment transaction in the states 'draft', 'cancel', or 'error' returns the orders. """ for unpaid_order_tx_state in ('draft', 'cancel', 'error'): self.tx.state = unpaid_order_tx_state with MockRequest(self.env, website=self.website, sale_order_id=self.order.id): self.assertEqual( self.website.sale_get_order(), self.order, msg=f"The transaction state '{unpaid_order_tx_state}' should not prevent " f"retrieving the linked order.", ) def test_paid_orders_cannot_be_retrieved(self): """ Test that fetching sales orders linked to a payment transaction in the states 'pending', 'authorized', or 'done' returns an empty recordset to prevent updating the paid orders. """ self.tx.acquirer_id.support_authorization = True for paid_order_tx_state in ('pending', 'authorized', 'done'): self.tx.state = paid_order_tx_state with MockRequest(self.env, website=self.website, sale_order_id=self.order.id): self.assertFalse( self.website.sale_get_order(), msg=f"The transaction state '{paid_order_tx_state}' should prevent retrieving " f"the linked order.", )
47.277778
2,553
14,271
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import io from PIL import Image from odoo.addons.website_sale.tests.common import TestWebsiteSaleCommon import odoo.tests @odoo.tests.common.tagged('post_install', '-at_install') class TestWebsiteSaleImage(TestWebsiteSaleCommon): # registry_test_mode = False # uncomment to save the product to test in browser def test_01_admin_shop_zoom_tour(self): color_red = '#CD5C5C' name_red = 'Indian Red' color_green = '#228B22' name_green = 'Forest Green' color_blue = '#4169E1' name_blue = 'Royal Blue' # create the color attribute product_attribute = self.env['product.attribute'].create({ 'name': 'Beautiful Color', 'display_type': 'color', }) # create the color attribute values attr_values = self.env['product.attribute.value'].create([{ 'name': name_red, 'attribute_id': product_attribute.id, 'html_color': color_red, 'sequence': 1, }, { 'name': name_green, 'attribute_id': product_attribute.id, 'html_color': color_green, 'sequence': 2, }, { 'name': name_blue, 'attribute_id': product_attribute.id, 'html_color': color_blue, 'sequence': 3, }]) # first image (blue) for the template f = io.BytesIO() Image.new('RGB', (1920, 1080), color_blue).save(f, 'JPEG') f.seek(0) blue_image = base64.b64encode(f.read()) # second image (red) for the variant 1, small image (no zoom) f = io.BytesIO() Image.new('RGB', (800, 500), color_red).save(f, 'JPEG') f.seek(0) red_image = base64.b64encode(f.read()) # second image (green) for the variant 2, big image (zoom) f = io.BytesIO() Image.new('RGB', (1920, 1080), color_green).save(f, 'JPEG') f.seek(0) green_image = base64.b64encode(f.read()) # Template Extra Image 1 f = io.BytesIO() Image.new('RGB', (124, 147)).save(f, 'GIF') f.seek(0) image_gif = base64.b64encode(f.read()) # Template Extra Image 2 image_svg = base64.b64encode(b'<svg></svg>') # Red Variant Extra Image 1 f = io.BytesIO() Image.new('RGB', (767, 247)).save(f, 'BMP') f.seek(0) image_bmp = base64.b64encode(f.read()) # Green Variant Extra Image 1 f = io.BytesIO() Image.new('RGB', (2147, 3251)).save(f, 'PNG') f.seek(0) image_png = base64.b64encode(f.read()) # create the template, without creating the variants template = self.env['product.template'].with_context(create_product_product=True).create({ 'name': 'A Colorful Image', 'product_template_image_ids': [(0, 0, {'name': 'image 1', 'image_1920': image_gif}), (0, 0, {'name': 'image 4', 'image_1920': image_svg})], }) # set the color attribute and values on the template line = self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attribute.id, 'product_tmpl_id': template.id, 'value_ids': [(6, 0, attr_values.ids)] }]) value_red = line.product_template_value_ids[0] value_green = line.product_template_value_ids[1] # set a different price on the variants to differentiate them product_template_attribute_values = self.env['product.template.attribute.value'].search([('product_tmpl_id', '=', template.id)]) for val in product_template_attribute_values: if val.name == name_red: val.price_extra = 10 else: val.price_extra = 20 # Get RED variant, and set image to blue (will be set on the template # because the template image is empty and there is only one variant) product_red = template._get_variant_for_combination(value_red) product_red.write({ 'image_1920': blue_image, 'product_variant_image_ids': [(0, 0, {'name': 'image 2', 'image_1920': image_bmp})], }) self.assertEqual(template.image_1920, blue_image) # Get the green variant product_green = template._get_variant_for_combination(value_green) product_green.write({ 'image_1920': green_image, 'product_variant_image_ids': [(0, 0, {'name': 'image 3', 'image_1920': image_png})], }) # now set the red image on the first variant, that works because # template image is not empty anymore and we have a second variant product_red.image_1920 = red_image # Verify image_1920 size > 1024 can be zoomed self.assertTrue(template.can_image_1024_be_zoomed) self.assertFalse(template.product_template_image_ids[0].can_image_1024_be_zoomed) self.assertFalse(template.product_template_image_ids[1].can_image_1024_be_zoomed) self.assertFalse(product_red.can_image_1024_be_zoomed) self.assertFalse(product_red.product_variant_image_ids[0].can_image_1024_be_zoomed) self.assertTrue(product_green.can_image_1024_be_zoomed) self.assertTrue(product_green.product_variant_image_ids[0].can_image_1024_be_zoomed) # jpeg encoding is changing the color a bit jpeg_blue = (65, 105, 227) jpeg_red = (205, 93, 92) jpeg_green = (34, 139, 34) # Verify original size: keep original image = Image.open(io.BytesIO(base64.b64decode(template.image_1920))) self.assertEqual(image.size, (1920, 1080)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_blue, "blue") image = Image.open(io.BytesIO(base64.b64decode(product_red.image_1920))) self.assertEqual(image.size, (800, 500)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_red, "red") image = Image.open(io.BytesIO(base64.b64decode(product_green.image_1920))) self.assertEqual(image.size, (1920, 1080)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_green, "green") # Verify 1024 size: keep aspect ratio image = Image.open(io.BytesIO(base64.b64decode(template.image_1024))) self.assertEqual(image.size, (1024, 576)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_blue, "blue") image = Image.open(io.BytesIO(base64.b64decode(product_red.image_1024))) self.assertEqual(image.size, (800, 500)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_red, "red") image = Image.open(io.BytesIO(base64.b64decode(product_green.image_1024))) self.assertEqual(image.size, (1024, 576)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_green, "green") # Verify 512 size: keep aspect ratio image = Image.open(io.BytesIO(base64.b64decode(template.image_512))) self.assertEqual(image.size, (512, 288)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_blue, "blue") image = Image.open(io.BytesIO(base64.b64decode(product_red.image_512))) self.assertEqual(image.size, (512, 320)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_red, "red") image = Image.open(io.BytesIO(base64.b64decode(product_green.image_512))) self.assertEqual(image.size, (512, 288)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_green, "green") # Verify 256 size: keep aspect ratio image = Image.open(io.BytesIO(base64.b64decode(template.image_256))) self.assertEqual(image.size, (256, 144)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_blue, "blue") image = Image.open(io.BytesIO(base64.b64decode(product_red.image_256))) self.assertEqual(image.size, (256, 160)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_red, "red") image = Image.open(io.BytesIO(base64.b64decode(product_green.image_256))) self.assertEqual(image.size, (256, 144)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_green, "green") # Verify 128 size: keep aspect ratio image = Image.open(io.BytesIO(base64.b64decode(template.image_128))) self.assertEqual(image.size, (128, 72)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_blue, "blue") image = Image.open(io.BytesIO(base64.b64decode(product_red.image_128))) self.assertEqual(image.size, (128, 80)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_red, "red") image = Image.open(io.BytesIO(base64.b64decode(product_green.image_128))) self.assertEqual(image.size, (128, 72)) self.assertEqual(image.getpixel((image.size[0] / 2, image.size[1] / 2)), jpeg_green, "green") # self.env.cr.commit() # uncomment to save the product to test in browser self.start_tour("/", 'shop_zoom', login="admin") # CASE: unlink move image to fallback if fallback image empty template.image_1920 = False product_red.unlink() self.assertEqual(template.image_1920, red_image) # CASE: unlink does nothing special if fallback image already set self.env['product.product'].create({ 'product_tmpl_id': template.id, 'image_1920': green_image, }).unlink() self.assertEqual(template.image_1920, red_image) # CASE: display variant image first if set self.assertEqual(product_green._get_images()[0].image_1920, green_image) # CASE: display variant fallback after variant o2m, correct fallback # write on the variant field, otherwise it will write on the fallback product_green.image_variant_1920 = False images = product_green._get_images() # images on fields are resized to max 1920 image = Image.open(io.BytesIO(base64.b64decode(images[0].image_1920))) self.assertEqual(image.size, (1268, 1920)) self.assertEqual(images[1].image_1920, red_image) self.assertEqual(images[2].image_1920, image_gif) self.assertEqual(images[3].image_1920, image_svg) # CASE: When uploading a product variant image # we don't want the default_product_tmpl_id from the context to be applied if we have a product_variant_id set # we want the default_product_tmpl_id from the context to be applied if we don't have a product_variant_id set additionnal_context = {'default_product_tmpl_id': template.id} product = self.env['product.product'].create({ 'product_tmpl_id': template.id, }) product_image = self.env['product.image'].with_context(**additionnal_context).create([{ 'name': 'Template image', 'image_1920': red_image, }, { 'name': 'Variant image', 'image_1920': blue_image, 'product_variant_id': product.id, }]) template_image = product_image.filtered(lambda i: i.name == 'Template image') variant_image = product_image.filtered(lambda i: i.name == 'Variant image') self.assertEqual(template_image.product_tmpl_id.id, template.id) self.assertFalse(template_image.product_variant_id.id) self.assertFalse(variant_image.product_tmpl_id.id) self.assertEqual(variant_image.product_variant_id.id, product.id) def test_02_image_holder(self): f = io.BytesIO() Image.new('RGB', (800, 500), '#FF0000').save(f, 'JPEG') f.seek(0) image = base64.b64encode(f.read()) # create the color attribute product_attribute = self.env['product.attribute'].create({ 'name': 'Beautiful Color', 'display_type': 'color', }) # create the color attribute values attr_values = self.env['product.attribute.value'].create([{ 'name': 'Red', 'attribute_id': product_attribute.id, 'sequence': 1, }, { 'name': 'Green', 'attribute_id': product_attribute.id, 'sequence': 2, }, { 'name': 'Blue', 'attribute_id': product_attribute.id, 'sequence': 3, }]) # create the template, without creating the variants template = self.env['product.template'].with_context(create_product_product=True).create({ 'name': 'Test subject', }) # when there are no variants, the image must be obtained from the template self.assertEqual(template, template._get_image_holder()) # set the color attribute and values on the template line = self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attribute.id, 'product_tmpl_id': template.id, 'value_ids': [(6, 0, attr_values.ids)] }]) value_red = line.product_template_value_ids[0] product_red = template._get_variant_for_combination(value_red) product_red.image_variant_1920 = image value_green = line.product_template_value_ids[1] product_green = template._get_variant_for_combination(value_green) product_green.image_variant_1920 = image # when there are no template image but there are variants, the image must be obtained from the first variant self.assertEqual(product_red, template._get_image_holder()) product_red.toggle_active() # but when some variants are not available, the image must be obtained from the first available variant self.assertEqual(product_green, template._get_image_holder()) template.image_1920 = image # when there is a template image, the image must be obtained from the template self.assertEqual(template, template._get_image_holder())
44.457944
14,271
13,882
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale.tests.test_sale_product_attribute_value_config import TestSaleProductAttributeValueCommon from odoo.tests import tagged from odoo.addons.website.tools import MockRequest from odoo.addons.website_sale.tests.common import TestWebsiteSaleCommon @tagged('post_install', '-at_install') class TestWebsiteSaleProductAttributeValueConfig(TestSaleProductAttributeValueCommon, TestWebsiteSaleCommon): def test_get_combination_info(self): current_website = self.env['website'].get_current_website() pricelist = current_website.get_current_pricelist() self.computer = self.computer.with_context(website_id=current_website.id) # make sure the pricelist has a 10% discount self.env['product.pricelist.item'].create({ 'price_discount': 10, 'compute_price': 'formula', 'pricelist_id': pricelist.id, }) discount_rate = 0.9 # make sure there is a 15% tax on the product tax = self.env['account.tax'].create({'name': "Test tax", 'amount': 15}) self.computer.taxes_id = tax tax_ratio = (100 + tax.amount) / 100 currency_ratio = 2 pricelist.currency_id = self._setup_currency(currency_ratio) # ensure pricelist is set to with_discount pricelist.discount_policy = 'with_discount' # CASE: B2B setting group_tax_included = self.env.ref('account.group_show_line_subtotals_tax_included').with_context(active_test=False) group_tax_excluded = self.env.ref('account.group_show_line_subtotals_tax_excluded').with_context(active_test=False) group_tax_included.users -= self.env.user group_tax_excluded.users |= self.env.user combination_info = self.computer._get_combination_info() self.assertEqual(combination_info['price'], 2222 * discount_rate * currency_ratio) self.assertEqual(combination_info['list_price'], 2222 * discount_rate * currency_ratio) self.assertEqual(combination_info['price_extra'], 222 * currency_ratio) self.assertEqual(combination_info['has_discounted_price'], False) # CASE: B2C setting group_tax_excluded.users -= self.env.user group_tax_included.users |= self.env.user combination_info = self.computer._get_combination_info() self.assertEqual(combination_info['price'], 2222 * discount_rate * currency_ratio * tax_ratio) self.assertEqual(combination_info['list_price'], 2222 * discount_rate * currency_ratio * tax_ratio) self.assertEqual(combination_info['price_extra'], round(222 * currency_ratio * tax_ratio, 2)) self.assertEqual(combination_info['has_discounted_price'], False) # CASE: pricelist 'without_discount' pricelist.discount_policy = 'without_discount' # ideally we would need to use compare_amounts everywhere, but this is # the only rounding where it fails without it combination_info = self.computer._get_combination_info() self.assertEqual(pricelist.currency_id.compare_amounts(combination_info['price'], 2222 * discount_rate * currency_ratio * tax_ratio), 0) self.assertEqual(pricelist.currency_id.compare_amounts(combination_info['list_price'], 2222 * currency_ratio * tax_ratio), 0) self.assertEqual(pricelist.currency_id.compare_amounts(combination_info['price_extra'], 222 * currency_ratio * tax_ratio), 0) self.assertEqual(combination_info['has_discounted_price'], True) def test_get_combination_info_with_fpos(self): self.env.user.partner_id.country_id = False current_website = self.env['website'].get_current_website() pricelist = current_website.get_current_pricelist() (self.env['product.pricelist'].search([]) - pricelist).write({'active': False}) test_product = self.env['product.template'].create({ 'name': 'Test Product', 'price': 2000, }).with_context(website_id=current_website.id) computer_ssd_attribute_lines = self.env['product.template.attribute.line'].create({ 'product_tmpl_id': test_product.id, 'attribute_id': self.ssd_attribute.id, 'value_ids': [(6, 0, [self.ssd_256.id])], }) computer_ssd_attribute_lines.product_template_value_ids[0].price_extra = 200 combination = computer_ssd_attribute_lines.product_template_value_ids[0] # Add fixed price for pricelist pricelist.item_ids = self.env['product.pricelist.item'].create({ 'applied_on': "1_product", 'base': "list_price", 'compute_price': "fixed", 'fixed_price': 500, 'product_tmpl_id': test_product.id, }) # Add 15% tax on product tax15 = self.env['account.tax'].create({'name': "Test tax 15", 'amount': 15}) tax0 = self.env['account.tax'].create({'name': "Test tax 0", 'amount': 0}) test_product.taxes_id = tax15 # Enable tax included group_tax_included = self.env.ref('account.group_show_line_subtotals_tax_included').with_context(active_test=False) group_tax_excluded = self.env.ref('account.group_show_line_subtotals_tax_excluded').with_context(active_test=False) group_tax_excluded.users -= self.env.user group_tax_included.users |= self.env.user # Create fiscal position for belgium mapping taxes 15% -> 0% fpos = self.env['account.fiscal.position'].create({ 'name': 'test', 'auto_apply': True, 'country_id': self.env.ref('base.be').id, }) self.env['account.fiscal.position.tax'].create({ 'position_id': fpos.id, 'tax_src_id': tax15.id, 'tax_dest_id': tax0.id, }) combination_info = test_product._get_combination_info(combination) self.assertEqual(combination_info['price'], 575, "500$ + 15% tax") self.assertEqual(combination_info['list_price'], 575, "500$ + 15% tax (2)") self.assertEqual(combination_info['price_extra'], 230, "200$ + 15% tax") # Now with fiscal position, taxes should be mapped self.env.user.partner_id.country_id = self.env.ref('base.be').id combination_info = test_product._get_combination_info(combination) self.assertEqual(combination_info['price'], 500, "500% + 0% tax (mapped from fp 15% -> 0% for BE)") self.assertEqual(combination_info['list_price'], 500, "500% + 0% tax (mapped from fp 15% -> 0% for BE) (2)") self.assertEqual(combination_info['price_extra'], 200, "200% + 0% tax (mapped from fp 15% -> 0% for BE)") # Try same flow with tax included tax15.write({'price_include': True}) # Reset / Safety check self.env.user.partner_id.country_id = None combination_info = test_product._get_combination_info(combination) self.assertEqual(combination_info['price'], 500, "434.78$ + 15% tax") self.assertEqual(combination_info['list_price'], 500, "434.78$ + 15% tax (2)") self.assertEqual(combination_info['price_extra'], 200, "173.91$ + 15% tax") # Now with fiscal position, taxes should be mapped self.env.user.partner_id.country_id = self.env.ref('base.be').id combination_info = test_product._get_combination_info(combination) self.assertEqual(round(combination_info['price'], 2), 434.78, "434.78$ + 0% tax (mapped from fp 15% -> 0% for BE)") self.assertEqual(round(combination_info['list_price'], 2), 434.78, "434.78$ + 0% tax (mapped from fp 15% -> 0% for BE)") self.assertEqual(combination_info['price_extra'], 173.91, "173.91$ + 0% tax (mapped from fp 15% -> 0% for BE)") @tagged('post_install', '-at_install') class TestWebsiteSaleProductPricelist(TestSaleProductAttributeValueCommon, TestWebsiteSaleCommon): def test_cart_update_with_fpos(self): # We will test that the mapping of an 10% included tax by a 6% by a fiscal position is taken into account when updating the cart self.env.user.partner_id.country_id = False current_website = self.env['website'].get_current_website() pricelist = current_website.get_current_pricelist() (self.env['product.pricelist'].search([]) - pricelist).write({'active': False}) # Add 10% tax on product tax10 = self.env['account.tax'].create({'name': "Test tax 10", 'amount': 10, 'price_include': True, 'amount_type': 'percent'}) tax6 = self.env['account.tax'].create({'name': "Test tax 6", 'amount': 6, 'price_include': True, 'amount_type': 'percent'}) test_product = self.env['product.template'].create({ 'name': 'Test Product', 'price': 110, 'taxes_id': [(6, 0, [tax10.id])], }).with_context(website_id=current_website.id) # Add discout of 50% for pricelist pricelist.item_ids = self.env['product.pricelist.item'].create({ 'applied_on': "1_product", 'base': "list_price", 'compute_price': "percentage", 'percent_price': 50, 'product_tmpl_id': test_product.id, }) pricelist.discount_policy = 'without_discount' # Create fiscal position mapping taxes 10% -> 6% fpos = self.env['account.fiscal.position'].create({ 'name': 'test', }) self.env['account.fiscal.position.tax'].create({ 'position_id': fpos.id, 'tax_src_id': tax10.id, 'tax_dest_id': tax6.id, }) so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, }) sol = self.env['sale.order.line'].create({ 'name': test_product.name, 'product_id': test_product.product_variant_id.id, 'product_uom_qty': 1, 'product_uom': test_product.uom_id.id, 'price_unit': test_product.list_price, 'order_id': so.id, 'tax_id': [(6, 0, [tax10.id])], }) self.assertEqual(round(sol.price_total), 110.0, "110$ with 10% included tax") so.pricelist_id = pricelist so.fiscal_position_id = fpos sol.product_id_change() with MockRequest(self.env, website=current_website, sale_order_id=so.id): so._cart_update(product_id=test_product.product_variant_id.id, line_id=sol.id, set_qty=1) self.assertEqual(round(sol.price_total), 53, "100$ with 50% discount + 6% tax (mapped from fp 10% -> 6%)") def test_cart_update_with_fpos_no_variant_product(self): # We will test that the mapping of an 10% included tax by a 0% by a fiscal position is taken into account when updating the cart for no_variant product self.env.user.partner_id.country_id = False current_website = self.env['website'].get_current_website() pricelist = current_website.get_current_pricelist() (self.env['product.pricelist'].search([]) - pricelist).write({'active': False}) # Add 10% tax on product tax10 = self.env['account.tax'].create({'name': "Test tax 10", 'amount': 10, 'price_include': True, 'amount_type': 'percent', 'type_tax_use': 'sale'}) tax0 = self.env['account.tax'].create({'name': "Test tax 0", 'amount': 0, 'price_include': True, 'amount_type': 'percent', 'type_tax_use': 'sale'}) # Create fiscal position mapping taxes 10% -> 0% fpos = self.env['account.fiscal.position'].create({ 'name': 'test', }) self.env['account.fiscal.position.tax'].create({ 'position_id': fpos.id, 'tax_src_id': tax10.id, 'tax_dest_id': tax0.id, }) product = self.env['product.product'].create({ 'name': 'prod_no_variant', 'list_price': 110, 'taxes_id': [(6, 0, [tax10.id])], 'type': 'consu', }) # create an attribute with one variant product_attribute = self.env['product.attribute'].create({ 'name': 'test_attr', 'display_type': 'radio', 'create_variant': 'no_variant', }) # create attribute value a1 = self.env['product.attribute.value'].create({ 'name': 'pa_value', 'attribute_id': product_attribute.id, 'sequence': 1, }) # set variant value to product template product_template = self.env['product.template'].search( [('name', '=', 'prod_no_variant')], limit=1) product_template.attribute_line_ids = [(0, 0, { 'attribute_id': product_attribute.id, 'value_ids': [(6, 0, [a1.id])], })] # publish the product on website product_template.is_published = True # create a so for user using the fiscal position so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, }) sol = self.env['sale.order.line'].create({ 'name': product_template.name, 'product_id': product.id, 'product_uom_qty': 1, 'product_uom': product_template.uom_id.id, 'price_unit': product_template.list_price, 'order_id': so.id, 'tax_id': [(6, 0, [tax10.id])], }) self.assertEqual(round(sol.price_total), 110.0, "110$ with 10% included tax") so.pricelist_id = pricelist so.fiscal_position_id = fpos sol.product_id_change() with MockRequest(self.env, website=current_website, sale_order_id=so.id): so._cart_update(product_id=product.id, line_id=sol.id, set_qty=1) self.assertEqual(round(sol.price_total), 100, "100$ with public price+ 0% tax (mapped from fp 10% -> 0%)")
49.22695
13,882
838
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import HttpCase, tagged @tagged('post_install', '-at_install') class TestSitemap(HttpCase): def setUp(self): super(TestSitemap, self).setUp() self.cats = self.env['product.public.category'].create([{ 'name': 'Level 0', }, { 'name': 'Level 1', }, { 'name': 'Level 2', }]) self.cats[2].parent_id = self.cats[1].id self.cats[1].parent_id = self.cats[0].id def test_01_shop_route_sitemap(self): resp = self.url_open('/sitemap.xml') level2_url = '/shop/category/level-0-level-1-level-2-%s' % self.cats[2].id self.assertTrue(level2_url in resp.text, "Category entry in sitemap should be prefixed by its parent hierarchy.")
33.52
838
415
py
PYTHON
15.0
from odoo.tests.common import HttpCase class TestWebsiteSaleCommon(HttpCase): def setUp(self): super(TestWebsiteSaleCommon, self).setUp() # Update website pricelist to ensure currency is same as env.company website = self.env['website'].get_current_website() pricelist = website.get_current_pricelist() pricelist.write({'currency_id': self.env.company.currency_id.id})
41.5
415
3,232
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.common.tagged('post_install', '-at_install') class TestWebsiteSequence(odoo.tests.TransactionCase): def setUp(self): super(TestWebsiteSequence, self).setUp() ProductTemplate = self.env['product.template'] product_templates = ProductTemplate.search([]) # if stock is installed we can't archive since there is orderpoints if hasattr(self.env['product.product'], 'orderpoint_ids'): product_templates.mapped('product_variant_ids.orderpoint_ids').write({'active': False}) # if pos loyalty is installed we can't archive since there are loyalty rules and rewards if 'loyalty.rule' in self.env: rules = self.env['loyalty.rule'].search([]) rules.unlink() if 'loyalty.reward' in self.env: rewards = self.env['loyalty.reward'].search([]) rewards.unlink() product_templates.write({'active': False}) self.p1, self.p2, self.p3, self.p4 = ProductTemplate.create([{ 'name': 'First Product', 'website_sequence': 100, }, { 'name': 'Second Product', 'website_sequence': 180, }, { 'name': 'Third Product', 'website_sequence': 225, }, { 'name': 'Last Product', 'website_sequence': 250, }]) self._check_correct_order(self.p1 + self.p2 + self.p3 + self.p4) def _search_website_sequence_order(self, order='ASC'): '''Helper method to limit the search only to the setUp products''' return self.env['product.template'].search([ ], order='website_sequence %s' % (order)) def _check_correct_order(self, products): product_ids = self._search_website_sequence_order().ids self.assertEqual(product_ids, products.ids, "Wrong sequence order") def test_01_website_sequence(self): # 100:1, 180:2, 225:3, 250:4 self.p2.set_sequence_down() # 100:1, 180:3, 225:2, 250:4 self._check_correct_order(self.p1 + self.p3 + self.p2 + self.p4) self.p4.set_sequence_up() # 100:1, 180:3, 225:4, 250:2 self._check_correct_order(self.p1 + self.p3 + self.p4 + self.p2) self.p2.set_sequence_top() # 95:2, 100:1, 180:3, 225:4 self._check_correct_order(self.p2 + self.p1 + self.p3 + self.p4) self.p1.set_sequence_bottom() # 95:2, 180:3, 225:4, 230:1 self._check_correct_order(self.p2 + self.p3 + self.p4 + self.p1) current_sequences = self._search_website_sequence_order().mapped('website_sequence') self.assertEqual(current_sequences, [95, 180, 225, 230], "Wrong sequence order (2)") self.p2.website_sequence = 1 self.p3.set_sequence_top() # -4:3, 1:2, 225:4, 230:1 self.assertEqual(self.p3.website_sequence, -4, "`website_sequence` should go below 0") new_product = self.env['product.template'].create({ 'name': 'Last Newly Created Product', }) self.assertEqual(self._search_website_sequence_order()[-1], new_product, "new product should be last")
41.974026
3,232
5,559
py
PYTHON
15.0
# coding: utf-8 from odoo.addons.website_sale.controllers.main import WebsiteSale from odoo.addons.website.tools import MockRequest from odoo.tests import TransactionCase, tagged @tagged('post_install', '-at_install') class WebsiteSaleVisitorTests(TransactionCase): def setUp(self): super().setUp() self.website = self.env.ref('website.default_website') self.WebsiteSaleController = WebsiteSale() self.cookies = {} def test_create_visitor_on_tracked_product(self): self.WebsiteSaleController = WebsiteSale() existing_visitors = self.env['website.visitor'].search([]) existing_tracks = self.env['website.track'].search([]) product = self.env['product.product'].create({ 'name': 'Storage Box', 'website_published': True, }) with MockRequest(self.env, website=self.website): self.cookies = self.WebsiteSaleController.products_recently_viewed_update(product.id) new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) new_tracks = self.env['website.track'].search([('id', 'not in', existing_tracks.ids)]) self.assertEqual(len(new_visitors), 1, "A visitor should be created after visiting a tracked product") self.assertEqual(len(new_tracks), 1, "A track should be created after visiting a tracked product") with MockRequest(self.env, website=self.website, cookies=self.cookies): self.WebsiteSaleController.products_recently_viewed_update(product.id) new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) new_tracks = self.env['website.track'].search([('id', 'not in', existing_tracks.ids)]) self.assertEqual(len(new_visitors), 1, "No visitor should be created after visiting another tracked product") self.assertEqual(len(new_tracks), 1, "No track should be created after visiting the same tracked product before 30 min") product = self.env['product.product'].create({ 'name': 'Large Cabinet', 'website_published': True, 'list_price': 320.0, }) with MockRequest(self.env, website=self.website, cookies=self.cookies): self.WebsiteSaleController.products_recently_viewed_update(product.id) new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) new_tracks = self.env['website.track'].search([('id', 'not in', existing_tracks.ids)]) self.assertEqual(len(new_visitors), 1, "No visitor should be created after visiting another tracked product") self.assertEqual(len(new_tracks), 2, "A track should be created after visiting another tracked product") def test_dynamic_filter_newest_products(self): """Test that a product is not displayed anymore after changing it company.""" new_company = self.env['res.company'].create({ 'name': 'Test Company', }) public_user = self.env.ref('base.public_user') product = self.env['product.product'].create({ 'name': 'Test Product', 'website_published': True, 'sale_ok': True, }) self.website = self.website.with_user(public_user).with_context(website_id=self.website.id) snippet_filter = self.env.ref('website_sale.dynamic_filter_newest_products') res = snippet_filter._prepare_values(16, []) res_products = [res_product['_record'] for res_product in res] self.assertIn(product, res_products) product.product_tmpl_id.company_id = new_company product.product_tmpl_id.flush(['company_id'], product.product_tmpl_id) res = snippet_filter._prepare_values(16, []) res_products = [res_product['_record'] for res_product in res] self.assertNotIn(product, res_products) def test_recently_viewed_company_changed(self): """Test that a product is : - displayed after visiting it - not displayed after changing it company.""" new_company = self.env['res.company'].create({ 'name': 'Test Company', }) public_user = self.env.ref('base.public_user') product = self.env['product.product'].create({ 'name': 'Test Product', 'website_published': True, 'sale_ok': True, }) self.website = self.website.with_user(public_user).with_context(website_id=self.website.id) snippet_filter = self.env.ref('website_sale.dynamic_filter_latest_viewed_products') # BEFORE VISITING THE PRODUCT res = snippet_filter._prepare_values(16, []) self.assertFalse(res) # AFTER VISITING THE PRODUCT with MockRequest(self.website.env, website=self.website): self.cookies = self.WebsiteSaleController.products_recently_viewed_update(product.id) with MockRequest(self.website.env, website=self.website, cookies=self.cookies): res = snippet_filter._prepare_values(16, []) res_products = [res_product['_record'] for res_product in res] self.assertIn(product, res_products) # AFTER CHANGING PRODUCT COMPANY product.product_tmpl_id.company_id = new_company product.product_tmpl_id.flush(['company_id'], product.product_tmpl_id) with MockRequest(self.website.env, website=self.website, cookies=self.cookies): res = snippet_filter._prepare_values(16, []) self.assertFalse(res)
46.714286
5,559
4,725
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from odoo.tests.common import HttpCase, TransactionCase from odoo.addons.base.tests.common import HttpCaseWithUserPortal @tagged('post_install', '-at_install') class TestWebsiteSaleCartRecovery(HttpCaseWithUserPortal): def test_01_shop_cart_recovery_tour(self): """The goal of this test is to make sure cart recovery works.""" self.env['product.product'].create({ 'name': 'Acoustic Bloc Screens', 'list_price': 2950.0, 'website_published': True, }) self.start_tour("/", 'shop_cart_recovery', login="portal") @tagged('post_install', '-at_install') class TestWebsiteSaleCartRecoveryServer(TransactionCase): def setUp(self): res = super(TestWebsiteSaleCartRecoveryServer, self).setUp() self.customer = self.env['res.partner'].create({ 'name': 'a', 'email': 'a@example.com', }) self.recovery_template_default = self.env.ref('website_sale.mail_template_sale_cart_recovery') self.recovery_template_custom1 = self.recovery_template_default.copy() self.recovery_template_custom2 = self.recovery_template_default.copy() self.website0 = self.env['website'].create({ 'name': 'web0', 'cart_recovery_mail_template_id': self.recovery_template_default.id, }) self.website1 = self.env['website'].create({ 'name': 'web1', 'cart_recovery_mail_template_id': self.recovery_template_custom1.id, }) self.website2 = self.env['website'].create({ 'name': 'web2', 'cart_recovery_mail_template_id': self.recovery_template_custom2.id, }) self.so0 = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website0.id, 'is_abandoned_cart': True, 'cart_recovery_email_sent': False, }) self.so1 = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website1.id, 'is_abandoned_cart': True, 'cart_recovery_email_sent': False, }) self.so2 = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website2.id, 'is_abandoned_cart': True, 'cart_recovery_email_sent': False, }) return res def test_cart_recovery_mail_template(self): """Make sure that we get the correct cart recovery templates to send.""" self.assertEqual( self.so1._get_cart_recovery_template(), self.recovery_template_custom1, "We do not return the correct mail template" ) self.assertEqual( self.so2._get_cart_recovery_template(), self.recovery_template_custom2, "We do not return the correct mail template" ) # Orders that belong to different websites; we should get the default template self.assertEqual( (self.so1 + self.so2)._get_cart_recovery_template(), self.recovery_template_default, "We do not return the correct mail template" ) def test_cart_recovery_mail_template_send(self): """The goal of this test is to make sure cart recovery works.""" orders = self.so0 + self.so1 + self.so2 self.assertFalse( any(orders.mapped('cart_recovery_email_sent')), "The recovery mail should not have been sent yet." ) self.assertFalse( any(orders.mapped('access_token')), "There should not be an access token yet." ) orders._cart_recovery_email_send() self.assertTrue( all(orders.mapped('cart_recovery_email_sent')), "The recovery mail should have been sent." ) self.assertTrue( all(orders.mapped('access_token')), "All tokens should have been generated." ) sent_mail = {} for order in orders: mail = self.env["mail.mail"].search([ ('record_name', '=', order['name']) ]) sent_mail.update({order: mail}) self.assertTrue( all(len(sent_mail[order]) == 1 for order in orders), "Each cart recovery mail has been sent exactly once." ) self.assertTrue( all(order.access_token in sent_mail[order].body for order in orders), "Each mail should contain the access token of the corresponding SO." )
37.5
4,725
5,694
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo.tests import tagged from odoo.addons.base.tests.common import HttpCaseWithUserPortal @tagged('post_install', '-at_install') class TestWebsiteSaleCartAbandoned(HttpCaseWithUserPortal): def setUp(self): res = super(TestWebsiteSaleCartAbandoned, self).setUp() now = datetime.utcnow() self.customer = self.env['res.partner'].create({ 'name': 'a', 'email': 'a@example.com', }) self.public_partner = self.env['res.partner'].create({ 'name': 'public', 'email': 'public@example.com', }) self.public_user = self.env['res.users'].create({ 'name': 'Foo', 'login': 'foo', 'partner_id': self.public_partner.id, }) self.website0 = self.env['website'].create({ 'name': 'web0', 'cart_abandoned_delay': 1.0, # 1 hour }) self.website1 = self.env['website'].create({ 'name': 'web1', 'cart_abandoned_delay': 0.5, # 30 minutes }) self.website2 = self.env['website'].create({ 'name': 'web2', 'cart_abandoned_delay': 24.0, # 1 day 'user_id': self.public_user.id, # specific public user }) product = self.env['product.product'].create({ 'name': 'The Product' }) add_order_line = [[0, 0, { 'name': 'The Product', 'product_id': product.id, 'product_uom_qty': 1, }]] self.so0before = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website0.id, 'state': 'draft', 'date_order': (now - relativedelta(hours=1)) - relativedelta(minutes=1), 'order_line': add_order_line, }) self.so0after = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website0.id, 'state': 'draft', 'date_order': (now - relativedelta(hours=1)) + relativedelta(minutes=1), 'order_line': add_order_line, }) self.so1before = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website1.id, 'state': 'draft', 'date_order': (now - relativedelta(minutes=30)) - relativedelta(minutes=1), 'order_line': add_order_line, }) self.so1after = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website1.id, 'state': 'draft', 'date_order': (now - relativedelta(minutes=30)) + relativedelta(minutes=1), 'order_line': add_order_line, }) self.so2before = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website2.id, 'state': 'draft', 'date_order': (now - relativedelta(hours=24)) - relativedelta(minutes=1), 'order_line': add_order_line, }) self.so2after = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website2.id, 'state': 'draft', 'date_order': (now - relativedelta(hours=24)) + relativedelta(minutes=1), 'order_line': add_order_line, }) self.so2before_but_public = self.env['sale.order'].create({ 'partner_id': self.public_partner.id, 'website_id': self.website2.id, 'state': 'draft', 'date_order': (now - relativedelta(hours=24)) - relativedelta(minutes=1), 'order_line': add_order_line, }) # Must behave like so1before because public partner is not the one of website1 self.so1before_but_other_public = self.env['sale.order'].create({ 'partner_id': self.public_partner.id, 'website_id': self.website1.id, 'state': 'draft', 'date_order': (now - relativedelta(minutes=30)) - relativedelta(minutes=1), 'order_line': add_order_line, }) return res def test_search_abandoned_cart(self): """Make sure the search for abandoned carts uses the delay and public partner specified in each website.""" SaleOrder = self.env['sale.order'] abandoned = SaleOrder.search([('is_abandoned_cart', '=', True)]).ids self.assertTrue(self.so0before.id in abandoned) self.assertTrue(self.so1before.id in abandoned) self.assertTrue(self.so1before_but_other_public.id in abandoned) self.assertTrue(self.so2before.id in abandoned) self.assertFalse(self.so0after.id in abandoned) self.assertFalse(self.so1after.id in abandoned) self.assertFalse(self.so2after.id in abandoned) self.assertFalse(self.so2before_but_public.id in abandoned) non_abandoned = SaleOrder.search([('is_abandoned_cart', '=', False)]).ids self.assertFalse(self.so0before.id in non_abandoned) self.assertFalse(self.so1before.id in non_abandoned) self.assertFalse(self.so1before_but_other_public.id in non_abandoned) self.assertFalse(self.so2before.id in non_abandoned) self.assertTrue(self.so0after.id in non_abandoned) self.assertTrue(self.so1after.id in non_abandoned) self.assertTrue(self.so2after.id in non_abandoned) self.assertFalse(self.so2before_but_public.id in abandoned)
43.465649
5,694
28,993
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from odoo.addons.base.tests.common import TransactionCaseWithUserDemo, HttpCaseWithUserPortal from odoo.addons.website.tools import MockRequest from odoo.addons.website_sale.tests.common import TestWebsiteSaleCommon from odoo.tests import tagged from odoo.tests.common import TransactionCase from odoo.tools import DotDict ''' /!\/!\ Calling `get_pricelist_available` after setting `property_product_pricelist` on a partner will not work as expected. That field will change the output of `get_pricelist_available` but modifying it will not invalidate the cache. Thus, tests should not do: self.env.user.partner_id.property_product_pricelist = my_pricelist pls = self.get_pricelist_available() self.assertEqual(...) self.env.user.partner_id.property_product_pricelist = another_pricelist pls = self.get_pricelist_available() self.assertEqual(...) as `_get_pl_partner_order` cache won't be invalidate between the calls, output won't be the one expected and tests will actually not test anything. Try to keep one call to `get_pricelist_available` by test method. ''' @tagged('post_install', '-at_install') class TestWebsitePriceList(TestWebsiteSaleCommon): # Mock nedded because request.session doesn't exist during test def _get_pricelist_available(self, show_visible=False): return self.get_pl(self.args.get('show'), self.args.get('current_pl'), self.args.get('country')) def setUp(self): super(TestWebsitePriceList, self).setUp() self.env.user.partner_id.country_id = False # Remove country to avoid property pricelist computed. self.website = self.env.ref('website.default_website') self.website.user_id = self.env.user (self.env['product.pricelist'].search([]) - self.env.ref('product.list0')).write({'website_id': False, 'active': False}) self.benelux = self.env['res.country.group'].create({ 'name': 'BeNeLux', 'country_ids': [(6, 0, (self.env.ref('base.be') + self.env.ref('base.lu') + self.env.ref('base.nl')).ids)] }) self.list_benelux = self.env['product.pricelist'].create({ 'name': 'Benelux', 'selectable': True, 'website_id': self.website.id, 'country_group_ids': [(4, self.benelux.id)], 'sequence': 2, }) item_benelux = self.env['product.pricelist.item'].create({ 'pricelist_id': self.list_benelux.id, 'compute_price': 'percentage', 'base': 'list_price', 'percent_price': 10, 'currency_id': self.env.ref('base.EUR').id, }) self.list_christmas = self.env['product.pricelist'].create({ 'name': 'Christmas', 'selectable': False, 'website_id': self.website.id, 'country_group_ids': [(4, self.env.ref('base.europe').id)], 'sequence': 20, }) item_christmas = self.env['product.pricelist.item'].create({ 'pricelist_id': self.list_christmas.id, 'compute_price': 'formula', 'base': 'list_price', 'price_discount': 20, }) list_europe = self.env['product.pricelist'].create({ 'name': 'EUR', 'selectable': True, 'website_id': self.website.id, 'country_group_ids': [(4, self.env.ref('base.europe').id)], 'sequence': 3, 'currency_id': self.env.ref('base.EUR').id, }) item_europe = self.env['product.pricelist.item'].create({ 'pricelist_id': list_europe.id, 'compute_price': 'formula', 'base': 'list_price', }) self.env.ref('product.list0').website_id = self.website.id self.website.pricelist_id = self.ref('product.list0') ca_group = self.env['res.country.group'].create({ 'name': 'Canada', 'country_ids': [(6, 0, [self.ref('base.ca')])] }) self.env['product.pricelist'].create({ 'name': 'Canada', 'selectable': True, 'website_id': self.website.id, 'country_group_ids': [(6, 0, [ca_group.id])], 'sequence': 10 }) self.args = { 'show': False, 'current_pl': False, } patcher = patch('odoo.addons.website_sale.models.website.Website.get_pricelist_available', wraps=self._get_pricelist_available) patcher.start() self.addCleanup(patcher.stop) def get_pl(self, show, current_pl, country): self.website.invalidate_cache(['pricelist_ids'], [self.website.id]) pl_ids = self.website._get_pl_partner_order( country, show, self.website.pricelist_id.id, current_pl, self.website.pricelist_ids ) return self.env['product.pricelist'].browse(pl_ids) def test_get_pricelist_available_show(self): show = True current_pl = False country_list = { False: ['Public Pricelist', 'EUR', 'Benelux', 'Canada'], 'BE': ['EUR', 'Benelux'], 'IT': ['EUR'], 'CA': ['Canada'], 'US': ['Public Pricelist', 'EUR', 'Benelux', 'Canada'] } for country, result in country_list.items(): pls = self.get_pl(show, current_pl, country) self.assertEqual(len(set(pls.mapped('name')) & set(result)), len(pls), 'Test failed for %s (%s %s vs %s %s)' % (country, len(pls), pls.mapped('name'), len(result), result)) def test_get_pricelist_available_not_show(self): show = False current_pl = False country_list = { False: ['Public Pricelist', 'EUR', 'Benelux', 'Christmas', 'Canada'], 'BE': ['EUR', 'Benelux', 'Christmas'], 'IT': ['EUR', 'Christmas'], 'US': ['Public Pricelist', 'EUR', 'Benelux', 'Christmas', 'Canada'], 'CA': ['Canada'] } for country, result in country_list.items(): pls = self.get_pl(show, current_pl, country) self.assertEqual(len(set(pls.mapped('name')) & set(result)), len(pls), 'Test failed for %s (%s %s vs %s %s)' % (country, len(pls), pls.mapped('name'), len(result), result)) def test_get_pricelist_available_promocode(self): christmas_pl = self.list_christmas.id country_list = { False: True, 'BE': True, 'IT': True, 'US': True, 'CA': False } for country, result in country_list.items(): self.args['country'] = country # mock patch method could not pass env context available = self.website.is_pricelist_available(christmas_pl) if result: self.assertTrue(available, 'AssertTrue failed for %s' % country) else: self.assertFalse(available, 'AssertFalse failed for %s' % country) def test_get_pricelist_available_show_with_auto_property(self): show = True self.env.user.partner_id.country_id = self.env.ref('base.be') # Add EUR pricelist auto current_pl = False country_list = { False: ['Public Pricelist', 'EUR', 'Benelux', 'Canada'], 'BE': ['EUR', 'Benelux'], 'IT': ['EUR'], 'CA': ['EUR', 'Canada'], 'US': ['Public Pricelist', 'EUR', 'Benelux', 'Canada'] } for country, result in country_list.items(): pls = self.get_pl(show, current_pl, country) self.assertEqual(len(set(pls.mapped('name')) & set(result)), len(pls), 'Test failed for %s (%s %s vs %s %s)' % (country, len(pls), pls.mapped('name'), len(result), result)) def test_pricelist_combination(self): product = self.env['product.product'].create({ 'name': 'Super Product', 'list_price': 100, 'taxes_id': False, }) current_website = self.env['website'].get_current_website() website_pricelist = current_website.get_current_pricelist() website_pricelist.write({ 'discount_policy': 'with_discount', 'item_ids': [(5, 0, 0), (0, 0, { 'applied_on': '1_product', 'product_tmpl_id': product.product_tmpl_id.id, 'min_quantity': 500, 'compute_price': 'percentage', 'percent_price': 63, })] }) promo_pricelist = self.env['product.pricelist'].create({ 'name': 'Super Pricelist', 'discount_policy': 'without_discount', 'item_ids': [(0, 0, { 'applied_on': '1_product', 'product_tmpl_id': product.product_tmpl_id.id, 'base': 'pricelist', 'base_pricelist_id': website_pricelist.id, 'compute_price': 'formula', 'price_discount': 25 })] }) so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, 'order_line': [(0, 0, { 'name': product.name, 'product_id': product.id, 'product_uom_qty': 1, 'product_uom': product.uom_id.id, 'price_unit': product.list_price, 'tax_id': False, })] }) sol = so.order_line self.assertEqual(sol.price_total, 100.0) so.pricelist_id = promo_pricelist with MockRequest(self.env, website=current_website, sale_order_id=so.id): so._cart_update(product_id=product.id, line_id=sol.id, set_qty=500) self.assertEqual(sol.price_unit, 37.0, 'Both reductions should be applied') self.assertEqual(sol.price_reduce, 27.75, 'Both reductions should be applied') self.assertEqual(sol.price_total, 13875) def test_pricelist_with_no_list_price(self): product = self.env['product.product'].create({ 'name': 'Super Product', 'list_price': 0, 'taxes_id': False, }) current_website = self.env['website'].get_current_website() website_pricelist = current_website.get_current_pricelist() website_pricelist.write({ 'discount_policy': 'without_discount', 'item_ids': [(5, 0, 0), (0, 0, { 'applied_on': '1_product', 'product_tmpl_id': product.product_tmpl_id.id, 'min_quantity': 0, 'compute_price': 'fixed', 'fixed_price': 10, })] }) so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, 'order_line': [(0, 0, { 'name': product.name, 'product_id': product.id, 'product_uom_qty': 5, 'product_uom': product.uom_id.id, 'price_unit': product.list_price, 'tax_id': False, })] }) sol = so.order_line self.assertEqual(sol.price_total, 0) so.pricelist_id = website_pricelist with MockRequest(self.env, website=current_website, sale_order_id=so.id): so._cart_update(product_id=product.id, line_id=sol.id, set_qty=5) self.assertEqual(sol.price_unit, 10.0, 'Pricelist price should be applied') self.assertEqual(sol.price_reduce, 10.0, 'Pricelist price should be applied') self.assertEqual(sol.price_total, 50.0) def simulate_frontend_context(self, website_id=1): # Mock this method will be enough to simulate frontend context in most methods def get_request_website(): return self.env['website'].browse(website_id) patcher = patch('odoo.addons.website.models.ir_http.get_request_website', wraps=get_request_website) patcher.start() self.addCleanup(patcher.stop) @tagged('post_install', '-at_install') class TestWebsitePriceListAvailable(TransactionCase): # This is enough to avoid a mock (request.session/website do not exist during test) def get_pricelist_available(self, show_visible=False, website_id=1, country_code=None, website_sale_current_pl=None): request = DotDict({ 'website': self.env['website'].browse(website_id), 'session': { 'geoip': { 'country_code': country_code, }, 'website_sale_current_pl': website_sale_current_pl, }, }) return self.env['website']._get_pricelist_available(request, show_visible) def setUp(self): super(TestWebsitePriceListAvailable, self).setUp() Pricelist = self.env['product.pricelist'] Website = self.env['website'] # Set up 2 websites self.website = Website.browse(1) self.website2 = Website.create({'name': 'Website 2'}) # Remove existing pricelists and create new ones existing_pricelists = Pricelist.search([]) self.backend_pl = Pricelist.create({ 'name': 'Backend Pricelist', 'website_id': False, }) self.generic_pl_select = Pricelist.create({ 'name': 'Generic Selectable Pricelist', 'selectable': True, 'website_id': False, }) self.generic_pl_code = Pricelist.create({ 'name': 'Generic Code Pricelist', 'code': 'GENERICCODE', 'website_id': False, }) self.generic_pl_code_select = Pricelist.create({ 'name': 'Generic Code Selectable Pricelist', 'code': 'GENERICCODESELECT', 'selectable': True, 'website_id': False, }) self.w1_pl = Pricelist.create({ 'name': 'Website 1 Pricelist', 'website_id': self.website.id, }) self.w1_pl_select = Pricelist.create({ 'name': 'Website 1 Pricelist Selectable', 'website_id': self.website.id, 'selectable': True, }) self.w1_pl_code_select = Pricelist.create({ 'name': 'Website 1 Pricelist Code Selectable', 'website_id': self.website.id, 'code': 'W1CODESELECT', 'selectable': True, }) self.w1_pl_code = Pricelist.create({ 'name': 'Website 1 Pricelist Code', 'website_id': self.website.id, 'code': 'W1CODE', }) self.w2_pl = Pricelist.create({ 'name': 'Website 2 Pricelist', 'website_id': self.website2.id, }) existing_pricelists.write({'active': False}) simulate_frontend_context(self) def test_get_pricelist_available(self): # all_pl = self.backend_pl + self.generic_pl_select + self.generic_pl_code + self.generic_pl_code_select + self.w1_pl + self.w1_pl_select + self.w1_pl_code + self.w1_pl_code_select + self.w2_pl # Test get all available pricelists pls_to_return = self.generic_pl_select + self.generic_pl_code + self.generic_pl_code_select + self.w1_pl + self.w1_pl_select + self.w1_pl_code + self.w1_pl_code_select pls = self.get_pricelist_available() self.assertEqual(pls, pls_to_return, "Every pricelist having the correct website_id set or (no website_id but a code or selectable) should be returned") # Test get all available and visible pricelists pls_to_return = self.generic_pl_select + self.generic_pl_code_select + self.w1_pl_select + self.w1_pl_code_select pls = self.get_pricelist_available(show_visible=True) self.assertEqual(pls, pls_to_return, "Only selectable pricelists website compliant (website_id False or current website) should be returned") def test_property_product_pricelist_for_inactive_partner(self): # `_get_partner_pricelist_multi` should consider inactive users when searching for pricelists. # Real case if for public user. His `property_product_pricelist` need to be set as it is passed # through `_get_pl_partner_order` as the `website_pl` when searching for available pricelists # for active users. public_partner = self.env.ref('base.public_partner') self.assertFalse(public_partner.active, "Ensure public partner is inactive (purpose of this test)") pl = public_partner.property_product_pricelist self.assertEqual(len(pl), 1, "Inactive partner should still get a `property_product_pricelist`") @tagged('post_install', '-at_install') class TestWebsitePriceListAvailableGeoIP(TestWebsitePriceListAvailable): def setUp(self): super(TestWebsitePriceListAvailableGeoIP, self).setUp() # clean `property_product_pricelist` for partner for this test (clean setup) self.env['ir.property'].search([('res_id', '=', 'res.partner,%s' % self.env.user.partner_id.id)]).unlink() # set different country groups on pricelists c_EUR = self.env.ref('base.europe') c_BENELUX = self.env['res.country.group'].create({ 'name': 'BeNeLux', 'country_ids': [(6, 0, (self.env.ref('base.be') + self.env.ref('base.lu') + self.env.ref('base.nl')).ids)] }) self.BE = self.env.ref('base.be') NL = self.env.ref('base.nl') c_BE = self.env['res.country.group'].create({'name': 'Belgium', 'country_ids': [(6, 0, [self.BE.id])]}) c_NL = self.env['res.country.group'].create({'name': 'Netherlands', 'country_ids': [(6, 0, [NL.id])]}) (self.backend_pl + self.generic_pl_select + self.generic_pl_code + self.w1_pl_select).write({'country_group_ids': [(6, 0, [c_BE.id])]}) (self.generic_pl_code_select + self.w1_pl + self.w2_pl).write({'country_group_ids': [(6, 0, [c_BENELUX.id])]}) (self.w1_pl_code).write({'country_group_ids': [(6, 0, [c_EUR.id])]}) (self.w1_pl_code_select).write({'country_group_ids': [(6, 0, [c_NL.id])]}) # pricelist | selectable | website | code | country group | # ----------------------------------------------------------------------| # backend_pl | | | | BE | # generic_pl_select | V | | | BE | # generic_pl_code | | | V | BE | # generic_pl_code_select | V | | V | BENELUX | # w1_pl | | 1 | | BENELUX | # w1_pl_select | V | 1 | | BE | # w1_pl_code_select | V | 1 | V | NL | # w1_pl_code | | 1 | V | EUR | # w2_pl | | 2 | | BENELUX | # available pl for website 1 for GeoIP BE (anything except website 2, backend and NL) self.website1_be_pl = self.generic_pl_select + self.generic_pl_code + self.w1_pl_select + self.generic_pl_code_select + self.w1_pl + self.w1_pl_code def test_get_pricelist_available_geoip(self): # Test get all available pricelists with geoip and no partner pricelist (ir.property) # property_product_pricelist will also be returned in the available pricelists self.website1_be_pl += self.env.user.partner_id.property_product_pricelist pls = self.get_pricelist_available(country_code=self.BE.code) self.assertEqual(pls, self.website1_be_pl, "Only pricelists for BE and accessible on website should be returned, and the partner pl") def test_get_pricelist_available_geoip2(self): # Test get all available pricelists with geoip and a partner pricelist (ir.property) not website compliant self.env.user.partner_id.property_product_pricelist = self.backend_pl pls = self.get_pricelist_available(country_code=self.BE.code) self.assertEqual(pls, self.website1_be_pl, "Only pricelists for BE and accessible on website should be returned as partner pl is not website compliant") def test_get_pricelist_available_geoip3(self): # Test get all available pricelists with geoip and a partner pricelist (ir.property) website compliant (but not geoip compliant) self.env.user.partner_id.property_product_pricelist = self.w1_pl_code_select pls = self.get_pricelist_available(country_code=self.BE.code) self.assertEqual(pls, self.website1_be_pl, "Only pricelists for BE and accessible on website should be returned, but not the partner pricelist as it is website compliant but not GeoIP compliant.") def test_get_pricelist_available_geoip4(self): # Test get all available with geoip and visible pricelists + promo pl pls_to_return = self.generic_pl_select + self.w1_pl_select + self.generic_pl_code_select # property_product_pricelist will also be returned in the available pricelists pls_to_return += self.env.user.partner_id.property_product_pricelist current_pl = self.w1_pl_code pls = self.get_pricelist_available(country_code=self.BE.code, show_visible=True, website_sale_current_pl=current_pl.id) self.assertEqual(pls, pls_to_return + current_pl, "Only pricelists for BE, accessible en website and selectable should be returned. It should also return the applied promo pl") @tagged('post_install', '-at_install') class TestWebsitePriceListHttp(HttpCaseWithUserPortal): def test_get_pricelist_available_multi_company(self): ''' Test that the `property_product_pricelist` of `res.partner` is not computed as SUPERUSER_ID. Indeed, `property_product_pricelist` is a _compute that ends up doing a search on `product.pricelist` that woule bypass the pricelist multi-company `ir.rule`. Then it would return pricelists from another company and the code would raise an access error when reading that `property_product_pricelist`. ''' test_company = self.env['res.company'].create({'name': 'Test Company'}) test_company.flush() self.env['product.pricelist'].create({ 'name': 'Backend Pricelist For "Test Company"', 'website_id': False, 'company_id': test_company.id, 'sequence': 1, }) self.authenticate('portal', 'portal') r = self.url_open('/shop') self.assertEqual(r.status_code, 200, "The page should not raise an access error because of reading pricelists from other companies") @tagged('post_install', '-at_install') class TestWebsitePriceListMultiCompany(TransactionCaseWithUserDemo): def setUp(self): ''' Create a basic multi-company pricelist environment: - Set up 2 companies with their own company-restricted pricelist each. - Add demo user in those 2 companies - For each company, add that company pricelist to the demo user partner. - Set website's company to company 2 - Demo user will still be in company 1 ''' super(TestWebsitePriceListMultiCompany, self).setUp() self.demo_user = self.user_demo # Create and add demo user to 2 companies self.company1 = self.demo_user.company_id self.company2 = self.env['res.company'].create({'name': 'Test Company'}) self.demo_user.company_ids += self.company2 # Set company2 as current company for demo user Website = self.env['website'] self.website = self.env.ref('website.default_website') self.website.company_id = self.company2 # Delete unused website, it will make PL manipulation easier, avoiding # UserError being thrown when a website wouldn't have any PL left. Website.search([('id', '!=', self.website.id)]).unlink() self.website2 = Website.create({ 'name': 'Website 2', 'company_id': self.company1.id, }) # Create a company pricelist for each company and set it to demo user self.c1_pl = self.env['product.pricelist'].create({ 'name': 'Company 1 Pricelist', 'company_id': self.company1.id, # The `website_id` field will default to the company's website, # in this case `self.website2`. }) self.c2_pl = self.env['product.pricelist'].create({ 'name': 'Company 2 Pricelist', 'company_id': self.company2.id, 'website_id': False, }) self.demo_user.partner_id.with_company(self.company1.id).property_product_pricelist = self.c1_pl self.demo_user.partner_id.with_company(self.company2.id).property_product_pricelist = self.c2_pl # Ensure everything was done correctly self.assertEqual(self.demo_user.partner_id.with_company(self.company1.id).property_product_pricelist, self.c1_pl) self.assertEqual(self.demo_user.partner_id.with_company(self.company2.id).property_product_pricelist, self.c2_pl) irp1 = self.env['ir.property'].with_company(self.company1)._get("property_product_pricelist", "res.partner", self.demo_user.partner_id.id) irp2 = self.env['ir.property'].with_company(self.company2)._get("property_product_pricelist", "res.partner", self.demo_user.partner_id.id) self.assertEqual((irp1, irp2), (self.c1_pl, self.c2_pl), "Ensure there is an `ir.property` for demo partner for every company, and that the pricelist is the company specific one.") # ---------------------------------- IR.PROPERTY ------------------------------------- # id | name | res_id | company_id | value_reference # ------------------------------------------------------------------------------------ # 1 | 'property_product_pricelist' | | 1 | product.pricelist,1 # 2 | 'property_product_pricelist' | | 2 | product.pricelist,2 # 3 | 'property_product_pricelist' | res.partner,8 | 1 | product.pricelist,10 # 4 | 'property_product_pricelist' | res.partner,8 | 2 | product.pricelist,11 def test_property_product_pricelist_multi_company(self): ''' Test that the `property_product_pricelist` of `res.partner` is read for the company of the website and not the current user company. This is the case if the user visit a website for which the company is not the same as its user's company. Here, as demo user (company1), we will visit website1 (company2). It should return the ir.property for demo user for company2 and not for the company1 as we should get the website's company pricelist and not the demo user's current company pricelist. ''' simulate_frontend_context(self, self.website.id) # First check: It should return ir.property,4 as company_id is # website.company_id and not env.user.company_id company_id = self.website.company_id.id partner = self.demo_user.partner_id.with_company(company_id) demo_pl = partner.property_product_pricelist self.assertEqual(demo_pl, self.c2_pl) # Second thing to check: It should not error in read right access error # Indeed, the ir.rule for pricelists rights about company should allow to # also read a pricelist from another company if that company is the one # from the currently visited website. self.env(user=self.user_demo)['product.pricelist'].browse(demo_pl.id).name def test_archive_pricelist_1(self): ''' Test that when a pricelist is archived, the check that verify that all website have at least one pricelist have access to all pricelists (considering all companies). ''' self.c2_pl.website_id = self.website c2_pl2 = self.c2_pl.copy({'name': 'Copy of c2_pl'}) self.env['product.pricelist'].search([ ('id', 'not in', (self.c2_pl + self.c1_pl + c2_pl2).ids) ]).write({'active': False}) # ---------------- PRICELISTS ---------------- # name | website_id | company_id | # -------------------------------------------- # self.c1_pl | self.website2 | self.company1 | # self.c2_pl | self.website | self.company2 | # c2_pl2 | self.website | self.company2 | self.demo_user.groups_id += self.env.ref('sales_team.group_sale_manager') # The test is here: while having access only to self.company2 records, # archive should not raise an error self.c2_pl.with_user(self.demo_user).with_context(allowed_company_ids=self.company2.ids).write({'active': False})
48.645973
28,993
4,111
py
PYTHON
15.0
# coding: utf-8 from odoo.addons.website_sale.controllers.main import WebsiteSale, PaymentPortal from odoo.addons.website.tools import MockRequest from odoo.exceptions import UserError from odoo.tests.common import TransactionCase, tagged @tagged('post_install', '-at_install') class WebsiteSaleCart(TransactionCase): @classmethod def setUpClass(cls): super(WebsiteSaleCart, cls).setUpClass() cls.website = cls.env['website'].browse(1) cls.WebsiteSaleController = WebsiteSale() cls.public_user = cls.env.ref('base.public_user') def test_add_cart_deleted_product(self): # Create a published product then unlink it product = self.env['product.product'].create({ 'name': 'Test Product', 'sale_ok': True, 'website_published': True, }) product_id = product.id product.unlink() with self.assertRaises(UserError): with MockRequest(product.with_user(self.public_user).env, website=self.website.with_user(self.public_user)): self.WebsiteSaleController.cart_update_json(product_id=product_id, add_qty=1) def test_add_cart_unpublished_product(self): # Try to add an unpublished product product = self.env['product.product'].create({ 'name': 'Test Product', 'sale_ok': True, }) with self.assertRaises(UserError): with MockRequest(product.with_user(self.public_user).env, website=self.website.with_user(self.public_user)): self.WebsiteSaleController.cart_update_json(product_id=product.id, add_qty=1) # public but remove sale_ok product.sale_ok = False product.website_published = True with self.assertRaises(UserError): with MockRequest(product.with_user(self.public_user).env, website=self.website.with_user(self.public_user)): self.WebsiteSaleController.cart_update_json(product_id=product.id, add_qty=1) def test_add_cart_archived_product(self): # Try to add an archived product product = self.env['product.product'].create({ 'name': 'Test Product', 'sale_ok': True, }) product.active = False with self.assertRaises(UserError): with MockRequest(product.with_user(self.public_user).env, website=self.website.with_user(self.public_user)): self.WebsiteSaleController.cart_update_json(product_id=product.id, add_qty=1) def test_update_pricelist_with_invalid_product(self): product = self.env['product.product'].create({ 'name': 'Test Product', }) # Should not raise an exception website = self.website.with_user(self.public_user) with MockRequest(product.with_user(self.public_user).env, website=website): order = website.sale_get_order(force_create=True) order.write({ 'order_line': [(0, 0, { 'product_id': product.id, })] }) website.sale_get_order(update_pricelist=True) def test_update_cart_before_payment(self): product = self.env['product.product'].create({ 'name': 'Test Product', 'sale_ok': True, 'website_published': True, 'lst_price': 1000.0, 'standard_price': 800.0, }) website = self.website.with_user(self.public_user) with MockRequest(product.with_user(self.public_user).env, website=website): self.WebsiteSaleController.cart_update_json(product_id=product.id, add_qty=1) sale_order = website.sale_get_order() sale_order.access_token = 'test_token' old_amount = sale_order.amount_total self.WebsiteSaleController.cart_update_json(product_id=product.id, add_qty=1) # Try processing payment with the old amount with self.assertRaises(UserError): PaymentPortal().shop_payment_transaction(sale_order.id, sale_order.access_token, amount=old_amount)
42.381443
4,111
13,131
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests from odoo import api from odoo.addons.base.tests.common import HttpCaseWithUserDemo, TransactionCaseWithUserDemo, HttpCaseWithUserPortal from odoo.addons.website_sale.controllers.main import WebsiteSale from odoo.addons.website_sale.tests.common import TestWebsiteSaleCommon from odoo.addons.website.tools import MockRequest @odoo.tests.tagged('post_install', '-at_install') class TestUi(HttpCaseWithUserDemo, TestWebsiteSaleCommon): def setUp(self): super(TestUi, self).setUp() product_product_7 = self.env['product.product'].create({ 'name': 'Storage Box', 'standard_price': 70.0, 'list_price': 79.0, 'website_published': True, }) self.product_attribute_1 = self.env['product.attribute'].create({ 'name': 'Legs', 'sequence': 10, }) product_attribute_value_1 = self.env['product.attribute.value'].create({ 'name': 'Steel', 'attribute_id': self.product_attribute_1.id, 'sequence': 1, }) product_attribute_value_2 = self.env['product.attribute.value'].create({ 'name': 'Aluminium', 'attribute_id': self.product_attribute_1.id, 'sequence': 2, }) self.product_product_11_product_template = self.env['product.template'].create({ 'name': 'Conference Chair', 'list_price': 16.50, 'accessory_product_ids': [(4, product_product_7.id)], }) self.env['product.template.attribute.line'].create({ 'product_tmpl_id': self.product_product_11_product_template.id, 'attribute_id': self.product_attribute_1.id, 'value_ids': [(4, product_attribute_value_1.id), (4, product_attribute_value_2.id)], }) self.product_product_1_product_template = self.env['product.template'].create({ 'name': 'Chair floor protection', 'list_price': 12.0, }) self.env['account.journal'].create({'name': 'Cash - Test', 'type': 'cash', 'code': 'CASH - Test'}) # Avoid Shipping/Billing address page (self.env.ref('base.partner_admin') + self.partner_demo).write({ 'street': '215 Vine St', 'city': 'Scranton', 'zip': '18503', 'country_id': self.env.ref('base.us').id, 'state_id': self.env.ref('base.state_us_39').id, 'phone': '+1 555-555-5555', 'email': 'admin@yourcompany.example.com', }) def test_01_admin_shop_tour(self): self.start_tour("/", 'shop', login="admin") def test_02_admin_checkout(self): self.start_tour("/", 'shop_buy_product', login="admin") def test_03_demo_checkout(self): self.start_tour("/", 'shop_buy_product', login="demo") def test_04_admin_website_sale_tour(self): tax_group = self.env['account.tax.group'].create({'name': 'Tax 15%'}) tax = self.env['account.tax'].create({ 'name': 'Tax 15%', 'amount': 15, 'type_tax_use': 'sale', 'tax_group_id': tax_group.id }) # storage box self.product_product_7 = self.env['product.product'].create({ 'name': 'Storage Box Test', 'standard_price': 70.0, 'list_price': 79.0, 'categ_id': self.env.ref('product.product_category_all').id, 'website_published': True, 'invoice_policy': 'delivery', }) self.product_product_7.taxes_id = [tax.id] self.env['res.config.settings'].create({ 'auth_signup_uninvited': 'b2c', 'show_line_subtotals_tax_selection': 'tax_excluded', 'group_show_line_subtotals_tax_excluded': True, 'group_show_line_subtotals_tax_included': False, }).execute() self.start_tour("/", 'website_sale_tour') def test_05_google_analytics_tracking(self): self.env['website'].browse(1).write({'google_analytics_key': 'G-XXXXXXXXXXX'}) self.start_tour("/shop", 'google_analytics_view_item') self.start_tour("/shop", 'google_analytics_add_to_cart') @odoo.tests.tagged('post_install', '-at_install') class TestWebsiteSaleCheckoutAddress(TransactionCaseWithUserDemo, HttpCaseWithUserPortal): ''' The goal of this method class is to test the address management on the checkout (new/edit billing/shipping, company_id, website_id..). ''' def setUp(self): super(TestWebsiteSaleCheckoutAddress, self).setUp() self.website = self.env.ref('website.default_website') self.country_id = self.env.ref('base.be').id self.WebsiteSaleController = WebsiteSale() self.default_address_values = { 'name': 'a res.partner address', 'email': 'email@email.email', 'street': 'ooo', 'city': 'ooo', 'zip': '1200', 'country_id': self.country_id, 'submitted': 1, } def _create_so(self, partner_id=None): return self.env['sale.order'].create({ 'partner_id': partner_id, 'website_id': self.website.id, 'order_line': [(0, 0, { 'product_id': self.env['product.product'].create({ 'name': 'Product A', 'list_price': 100, 'website_published': True, 'sale_ok': True}).id, 'name': 'Product A', })] }) def _get_last_address(self, partner): ''' Useful to retrieve the last created shipping address ''' return partner.child_ids.sorted('id', reverse=True)[0] # TEST WEBSITE def test_01_create_shipping_address_specific_user_account(self): ''' Ensure `website_id` is correctly set (specific_user_account) ''' p = self.env.user.partner_id so = self._create_so(p.id) with MockRequest(self.env, website=self.website, sale_order_id=so.id) as req: req.httprequest.method = "POST" self.WebsiteSaleController.address(**self.default_address_values) self.assertFalse(self._get_last_address(p).website_id, "New shipping address should not have a website set on it (no specific_user_account).") self.website.specific_user_account = True self.WebsiteSaleController.address(**self.default_address_values) self.assertEqual(self._get_last_address(p).website_id, self.website, "New shipping address should have a website set on it (specific_user_account).") # TEST COMPANY def _setUp_multicompany_env(self): ''' Have 2 companies A & B. Have 1 website 1 which company is B Have admin on company A ''' self.company_a = self.env['res.company'].create({ 'name': 'Company A', }) self.company_b = self.env['res.company'].create({ 'name': 'Company B', }) self.company_c = self.env['res.company'].create({ 'name': 'Company C', }) self.website.company_id = self.company_b self.env.user.company_id = self.company_a self.demo_user = self.user_demo self.demo_user.company_ids += self.company_c self.demo_user.company_id = self.company_c self.demo_partner = self.demo_user.partner_id self.portal_user = self.user_portal self.portal_partner = self.portal_user.partner_id def test_02_demo_address_and_company(self): ''' This test ensure that the company_id of the address (partner) is correctly set and also, is not wrongly changed. eg: new shipping should use the company of the website and not the one from the admin, and editing a billing should not change its company. ''' self._setUp_multicompany_env() so = self._create_so(self.demo_partner.id) env = api.Environment(self.env.cr, self.demo_user.id, {}) # change also website env for `sale_get_order` to not change order partner_id with MockRequest(env, website=self.website.with_env(env), sale_order_id=so.id) as req: req.httprequest.method = "POST" # 1. Logged in user, new shipping self.WebsiteSaleController.address(**self.default_address_values) new_shipping = self._get_last_address(self.demo_partner) self.assertTrue(new_shipping.company_id != self.env.user.company_id, "Logged in user new shipping should not get the company of the sudo() neither the one from it's partner..") self.assertEqual(new_shipping.company_id, self.website.company_id, ".. but the one from the website.") # 2. Logged in user/internal user, should not edit name or email address of billing self.default_address_values['partner_id'] = self.demo_partner.id self.WebsiteSaleController.address(**self.default_address_values) self.assertEqual(self.demo_partner.company_id, self.company_c, "Logged in user edited billing (the partner itself) should not get its company modified.") self.assertNotEqual(self.demo_partner.name, self.default_address_values['name'], "Employee cannot change their name during the checkout process.") self.assertNotEqual(self.demo_partner.email, self.default_address_values['email'], "Employee cannot change their email during the checkout process.") def test_03_public_user_address_and_company(self): ''' Same as test_02 but with public user ''' self._setUp_multicompany_env() so = self._create_so(self.website.user_id.partner_id.id) env = api.Environment(self.env.cr, self.website.user_id.id, {}) # change also website env for `sale_get_order` to not change order partner_id with MockRequest(env, website=self.website.with_env(env), sale_order_id=so.id) as req: req.httprequest.method = "POST" # 1. Public user, new billing self.default_address_values['partner_id'] = -1 self.WebsiteSaleController.address(**self.default_address_values) new_partner = so.partner_id self.assertNotEqual(new_partner, self.website.user_id.partner_id, "New billing should have created a new partner and assign it on the SO") self.assertEqual(new_partner.company_id, self.website.company_id, "The new partner should get the company of the website") # 2. Public user, edit billing self.default_address_values['partner_id'] = new_partner.id self.WebsiteSaleController.address(**self.default_address_values) self.assertEqual(new_partner.company_id, self.website.company_id, "Public user edited billing (the partner itself) should not get its company modified.") def test_04_apply_empty_pl(self): ''' Ensure empty pl code reset the applied pl ''' so = self._create_so(self.env.user.partner_id.id) eur_pl = self.env['product.pricelist'].create({ 'name': 'EUR_test', 'website_id': self.website.id, 'code': 'EUR_test', }) with MockRequest(self.env, website=self.website, sale_order_id=so.id): self.WebsiteSaleController.pricelist('EUR_test') self.assertEqual(so.pricelist_id, eur_pl, "Ensure EUR_test is applied") self.WebsiteSaleController.pricelist('') self.assertNotEqual(so.pricelist_id, eur_pl, "Pricelist should be removed when sending an empty pl code") def test_05_portal_user_address_and_company(self): ''' Same as test_03 but with portal user ''' self._setUp_multicompany_env() so = self._create_so(self.portal_partner.id) env = api.Environment(self.env.cr, self.portal_user.id, {}) # change also website env for `sale_get_order` to not change order partner_id with MockRequest(env, website=self.website.with_env(env), sale_order_id=so.id) as req: req.httprequest.method = "POST" # 1. Portal user, new shipping, same with the log in user self.WebsiteSaleController.address(**self.default_address_values) new_shipping = self._get_last_address(self.portal_partner) self.assertTrue(new_shipping.company_id != self.env.user.company_id, "Portal user new shipping should not get the company of the sudo() neither the one from it's partner..") self.assertEqual(new_shipping.company_id, self.website.company_id, ".. but the one from the website.") # 2. Portal user, edit billing self.default_address_values['partner_id'] = self.portal_partner.id self.WebsiteSaleController.address(**self.default_address_values) # Name cannot be changed if there are issued invoices self.assertNotEqual(self.portal_partner.name, self.default_address_values['name'], "Portal User should not be able to change the name if they have invoices under their name.")
48.453875
13,131
13,091
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 from odoo.addons.base.tests.common import HttpCaseWithUserDemo, HttpCaseWithUserPortal from odoo.modules.module import get_module_resource from odoo.tests import tagged @tagged('post_install', '-at_install') class TestUi(HttpCaseWithUserDemo, HttpCaseWithUserPortal): def setUp(self): super(TestUi, self).setUp() # create a template product_template = self.env['product.template'].create({ 'name': 'Test Product', 'is_published': True, 'list_price': 750, }) tax = self.env['account.tax'].create({'name': "Test tax", 'amount': 10}) product_template.taxes_id = tax product_attribute = self.env['product.attribute'].create({ 'name': 'Legs', 'visibility': 'visible', 'sequence': 10, }) product_attribute_value_1 = self.env['product.attribute.value'].create({ 'name': 'Steel - Test', 'attribute_id': product_attribute.id, 'sequence': 1, }) product_attribute_value_2 = self.env['product.attribute.value'].create({ 'name': 'Aluminium', 'attribute_id': product_attribute.id, 'sequence': 2, }) # set attribute and attribute values on the template self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attribute.id, 'product_tmpl_id': product_template.id, 'value_ids': [(6, 0, [product_attribute_value_1.id, product_attribute_value_2.id])] }]) # set a different price on the variants to differentiate them product_template_attribute_values = self.env['product.template.attribute.value'] \ .search([('product_tmpl_id', '=', product_template.id)]) for ptav in product_template_attribute_values: if ptav.name == "Steel - Test": ptav.price_extra = 0 else: ptav.price_extra = 50.4 # Update the pricelist currency regarding env.company_id currency_id in case company has changed currency with COA installation. website = self.env['website'].get_current_website() pricelist = website.get_current_pricelist() pricelist.write({'currency_id': self.env.company.currency_id.id}) def test_01_admin_shop_customize_tour(self): # Enable Variant Group self.env.ref('product.group_product_variant').write({'users': [(4, self.env.ref('base.user_admin').id)]}) self.start_tour("/", 'shop_customize', login="admin") def test_02_admin_shop_custom_attribute_value_tour(self): # Make sure pricelist rule exist self.product_attribute_1 = self.env['product.attribute'].create({ 'name': 'Legs', 'sequence': 10, }) product_attribute_value_1 = self.env['product.attribute.value'].create({ 'name': 'Steel', 'attribute_id': self.product_attribute_1.id, 'sequence': 1, }) product_attribute_value_2 = self.env['product.attribute.value'].create({ 'name': 'Aluminium', 'attribute_id': self.product_attribute_1.id, 'sequence': 2, }) product_attribute_2 = self.env['product.attribute'].create({ 'name': 'Color', 'sequence': 20, }) product_attribute_value_3 = self.env['product.attribute.value'].create({ 'name': 'White', 'attribute_id': product_attribute_2.id, 'sequence': 1, }) product_attribute_value_4 = self.env['product.attribute.value'].create({ 'name': 'Black', 'attribute_id': product_attribute_2.id, 'sequence': 2, }) # Create product template self.product_product_4_product_template = self.env['product.template'].create({ 'name': 'Customizable Desk (TEST)', 'standard_price': 500.0, 'list_price': 750.0, }) # Generate variants self.env['product.template.attribute.line'].create([{ 'product_tmpl_id': self.product_product_4_product_template.id, 'attribute_id': self.product_attribute_1.id, 'value_ids': [(4, product_attribute_value_1.id), (4, product_attribute_value_2.id)], }, { 'product_tmpl_id': self.product_product_4_product_template.id, 'attribute_id': product_attribute_2.id, 'value_ids': [(4, product_attribute_value_3.id), (4, product_attribute_value_4.id)], }]) product_template = self.product_product_4_product_template # Add Custom Attribute product_attribute_value_7 = self.env['product.attribute.value'].create({ 'name': 'Custom TEST', 'attribute_id': self.product_attribute_1.id, 'sequence': 3, 'is_custom': True }) self.product_product_4_product_template.attribute_line_ids[0].write({'value_ids': [(4, product_attribute_value_7.id)]}) img_path = get_module_resource('product', 'static', 'img', 'product_product_11-image.png') img_content = base64.b64encode(open(img_path, "rb").read()) self.product_product_11_product_template = self.env['product.template'].create({ 'name': 'Conference Chair (TEST)', 'website_sequence': 9999, # laule 'image_1920': img_content, 'list_price': 16.50, }) self.env['product.template.attribute.line'].create({ 'product_tmpl_id': self.product_product_11_product_template.id, 'attribute_id': self.product_attribute_1.id, 'value_ids': [(4, product_attribute_value_1.id), (4, product_attribute_value_2.id)], }) self.product_product_11_product_template.attribute_line_ids[0].product_template_value_ids[1].price_extra = 6.40 # Setup a second optional product self.product_product_1_product_template = self.env['product.template'].create({ 'name': 'Chair floor protection', 'list_price': 12.0, }) # fix runbot, sometimes one pricelist is chosen, sometimes the other... pricelists = self.env['website'].get_current_website().get_current_pricelist() | self.env.ref('product.list0') for pricelist in pricelists: if not pricelist.item_ids.filtered(lambda i: i.product_tmpl_id == product_template and i.price_discount == 20): self.env['product.pricelist.item'].create({ 'base': 'list_price', 'applied_on': '1_product', 'pricelist_id': pricelist.id, 'product_tmpl_id': product_template.id, 'price_discount': 20, 'min_quantity': 2, 'compute_price': 'formula', }) pricelist.discount_policy = 'without_discount' self.start_tour("/", 'shop_custom_attribute_value', login="admin") def test_03_public_tour_shop_dynamic_variants(self): """ The goal of this test is to make sure product variants with dynamic attributes can be created by the public user (when being added to cart). """ # create the attribute product_attribute = self.env['product.attribute'].create({ 'name': "Dynamic Attribute", 'create_variant': 'dynamic', }) # create the attribute values product_attribute_values = self.env['product.attribute.value'].create([{ 'name': "Dynamic Value 1", 'attribute_id': product_attribute.id, 'sequence': 1, }, { 'name': "Dynamic Value 2", 'attribute_id': product_attribute.id, 'sequence': 2, }]) # create the template product_template = self.env['product.template'].create({ 'name': 'Dynamic Product', 'website_published': True, 'list_price': 0, }) # set attribute and attribute values on the template self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attribute.id, 'product_tmpl_id': product_template.id, 'value_ids': [(6, 0, product_attribute_values.ids)] }]) # set a different price on the variants to differentiate them product_template_attribute_values = self.env['product.template.attribute.value'] \ .search([('product_tmpl_id', '=', product_template.id)]) for ptav in product_template_attribute_values: if ptav.name == "Dynamic Value 1": ptav.price_extra = 10 else: # 0 to not bother with the pricelist of the public user ptav.price_extra = 0 self.start_tour("/", 'tour_shop_dynamic_variants') def test_04_portal_tour_deleted_archived_variants(self): """The goal of this test is to make sure deleted and archived variants are shown as impossible combinations. Using "portal" to have various users in the tests. """ # create the attribute product_attribute = self.env['product.attribute'].create({ 'name': "My Attribute", 'create_variant': 'always', }) # create the attribute values product_attribute_values = self.env['product.attribute.value'].create([{ 'name': "My Value 1", 'attribute_id': product_attribute.id, 'sequence': 1, }, { 'name': "My Value 2", 'attribute_id': product_attribute.id, 'sequence': 2, }, { 'name': "My Value 3", 'attribute_id': product_attribute.id, 'sequence': 3, }]) # create the template product_template = self.env['product.template'].create({ 'name': 'Test Product 2', 'is_published': True, }) # set attribute and attribute values on the template self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attribute.id, 'product_tmpl_id': product_template.id, 'value_ids': [(6, 0, product_attribute_values.ids)] }]) # set a different price on the variants to differentiate them product_template_attribute_values = self.env['product.template.attribute.value'] \ .search([('product_tmpl_id', '=', product_template.id)]) product_template_attribute_values[0].price_extra = 10 product_template_attribute_values[1].price_extra = 20 product_template_attribute_values[2].price_extra = 30 # archive first combination (first variant) product_template.product_variant_ids[0].active = False # delete second combination (which is now first variant since cache has been cleared) product_template.product_variant_ids[0].unlink() self.start_tour("/", 'tour_shop_deleted_archived_variants', login="portal") def test_05_demo_tour_no_variant_attribute(self): """The goal of this test is to make sure attributes no_variant are correctly added to cart. Using "demo" to have various users in the tests. """ # create the attribute product_attribute_no_variant = self.env['product.attribute'].create({ 'name': "No Variant Attribute", 'create_variant': 'no_variant', }) # create the attribute value product_attribute_value_no_variant = self.env['product.attribute.value'].create({ 'name': "No Variant Value", 'attribute_id': product_attribute_no_variant.id, }) # create the template product_template = self.env['product.template'].create({ 'name': 'Test Product 3', 'website_published': True, }) # set attribute and attribute value on the template ptal = self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attribute_no_variant.id, 'product_tmpl_id': product_template.id, 'value_ids': [(6, 0, product_attribute_value_no_variant.ids)] }]) # set a price on the value ptal.product_template_value_ids.price_extra = 10 self.start_tour("/", 'tour_shop_no_variant_attribute', login="demo") def test_06_admin_list_view_b2c(self): self.env.ref('product.group_product_variant').write({'users': [(4, self.env.ref('base.user_admin').id)]}) # activate b2c config = self.env['res.config.settings'].create({}) config.show_line_subtotals_tax_selection = "tax_included" config._onchange_sale_tax() config.execute() self.start_tour("/", 'shop_list_view_b2c', login="admin") def test_07_editor_shop(self): self.start_tour("/", 'shop_editor', login="admin")
40.65528
13,091
999
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch import odoo from odoo.tests import tagged from odoo.tests.common import HttpCase @tagged('post_install', '-at_install') class TestWebsiteSaleMail(HttpCase): def test_01_shop_mail_tour(self): """The goal of this test is to make sure sending SO by email works.""" self.env['product.product'].create({ 'name': 'Acoustic Bloc Screens', 'list_price': 2950.0, 'website_published': True, }) self.env['res.partner'].create({ 'name': 'Azure Interior', 'email': 'azure.Interior24@example.com', }) # we override unlink because we don't want the email to be auto deleted MailMail = odoo.addons.mail.models.mail_mail.MailMail with patch.object(MailMail, 'unlink', lambda self: None): self.start_tour("/", 'shop_mail', login="admin")
32.225806
999
803
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class PaymentWizard(models.TransientModel): _inherit = 'payment.acquirer.onboarding.wizard' _name = 'website.sale.payment.acquirer.onboarding.wizard' _description = 'Website Payment acquire onboarding wizard' def _set_payment_acquirer_onboarding_step_done(self): """ Override. """ self.env.company.sudo().set_onboarding_step_done('payment_acquirer_onboarding_state') def _start_stripe_onboarding(self): """ Override of payment to set the dashboard as start menu of the payment onboarding. """ menu_id = self.env.ref('website.menu_website_dashboard').id return self.env.company._run_payment_onboarding_step(menu_id)
42.263158
803
1,443
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ from odoo.exceptions import AccessError class Digest(models.Model): _inherit = 'digest.digest' kpi_website_sale_total = fields.Boolean('eCommerce Sales') kpi_website_sale_total_value = fields.Monetary(compute='_compute_kpi_website_sale_total_value') def _compute_kpi_website_sale_total_value(self): if not self.env.user.has_group('sales_team.group_sale_salesman_all_leads'): raise AccessError(_("Do not have access, skip this data for user's digest email")) for record in self: start, end, company = record._get_kpi_compute_parameters() confirmed_website_sales = self.env['sale.order'].search([ ('date_order', '>=', start), ('date_order', '<', end), ('state', 'not in', ['draft', 'cancel', 'sent']), ('website_id', '!=', False), ('company_id', '=', company.id) ]) record.kpi_website_sale_total_value = sum(confirmed_website_sales.mapped('amount_total')) def _compute_kpis_actions(self, company, user): res = super(Digest, self)._compute_kpis_actions(company, user) res['kpi_website_sale_total'] = 'website.backend_dashboard&menu_id=%s' % self.env.ref('website.menu_website_configuration').id return res
46.548387
1,443
2,759
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import fields,api, models, _ from odoo.exceptions import UserError, ValidationError class CrmTeam(models.Model): _inherit = "crm.team" website_ids = fields.One2many('website', 'salesteam_id', string='Websites', help="Websites using this Sales Team") abandoned_carts_count = fields.Integer( compute='_compute_abandoned_carts', string='Number of Abandoned Carts', readonly=True) abandoned_carts_amount = fields.Integer( compute='_compute_abandoned_carts', string='Amount of Abandoned Carts', readonly=True) def _compute_abandoned_carts(self): # abandoned carts to recover are draft sales orders that have no order lines, # a partner other than the public user, and created over an hour ago # and the recovery mail was not yet sent counts = {} amounts = {} website_teams = self.filtered(lambda team: team.website_ids) if website_teams: abandoned_carts_data = self.env['sale.order'].read_group([ ('is_abandoned_cart', '=', True), ('cart_recovery_email_sent', '=', False), ('team_id', 'in', website_teams.ids), ], ['amount_total', 'team_id'], ['team_id']) counts = {data['team_id'][0]: data['team_id_count'] for data in abandoned_carts_data} amounts = {data['team_id'][0]: data['amount_total'] for data in abandoned_carts_data} for team in self: team.abandoned_carts_count = counts.get(team.id, 0) team.abandoned_carts_amount = amounts.get(team.id, 0) def get_abandoned_carts(self): self.ensure_one() return { 'name': _('Abandoned Carts'), 'type': 'ir.actions.act_window', 'view_mode': 'tree,form', 'domain': [('is_abandoned_cart', '=', True)], 'search_view_id': [self.env.ref('sale.sale_order_view_search_inherit_sale').id], 'context': { 'search_default_team_id': self.id, 'default_team_id': self.id, 'search_default_recovery_email': 1, 'create': False }, 'res_model': 'sale.order', 'help': _('''<p class="o_view_nocontent_smiling_face"> You can find all abandoned carts here, i.e. the carts generated by your website's visitors from over an hour ago that haven't been confirmed yet.</p> <p>You should send an email to the customers to encourage them!</p> '''), }
45.983333
2,759
462
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class AccountMove(models.Model): _inherit = 'account.move' website_id = fields.Many2one('website', related='partner_id.website_id', string='Website', help='Website through which this invoice was created.', store=True, readonly=True, tracking=True)
38.5
462
461
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.http import request class IrHttp(models.AbstractModel): _inherit = 'ir.http' @classmethod def _dispatch(cls): affiliate_id = request.httprequest.args.get('affiliate_id') if affiliate_id: request.session['affiliate_id'] = int(affiliate_id) return super(IrHttp, cls)._dispatch()
30.733333
461
377
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class ResCountry(models.Model): _inherit = 'res.country' def get_website_sale_countries(self, mode='billing'): return self.sudo().search([]) def get_website_sale_states(self, mode='billing'): return self.sudo().state_ids
26.928571
377
21,282
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import random from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import api, models, fields, _ from odoo.http import request from odoo.osv import expression from odoo.exceptions import UserError, ValidationError _logger = logging.getLogger(__name__) class SaleOrder(models.Model): _inherit = "sale.order" website_order_line = fields.One2many( 'sale.order.line', compute='_compute_website_order_line', string='Order Lines displayed on Website', help='Order Lines to be displayed on the website. They should not be used for computation purpose.', ) cart_quantity = fields.Integer(compute='_compute_cart_info', string='Cart Quantity') only_services = fields.Boolean(compute='_compute_cart_info', string='Only Services') is_abandoned_cart = fields.Boolean('Abandoned Cart', compute='_compute_abandoned_cart', search='_search_abandoned_cart') cart_recovery_email_sent = fields.Boolean('Cart recovery email already sent') website_id = fields.Many2one('website', string='Website', readonly=True, help='Website through which this order was placed.') @api.model def _default_note_url(self): website_id = self._context.get('website_id') if website_id: return self.env['website'].browse(website_id).get_base_url() return super()._default_note_url() @api.depends('order_line') def _compute_website_order_line(self): for order in self: order.website_order_line = order.order_line @api.depends('order_line.product_uom_qty', 'order_line.product_id') def _compute_cart_info(self): for order in self: order.cart_quantity = int(sum(order.mapped('website_order_line.product_uom_qty'))) order.only_services = all(l.product_id.type == 'service' for l in order.website_order_line) @api.depends('website_id', 'date_order', 'order_line', 'state', 'partner_id') def _compute_abandoned_cart(self): for order in self: # a quotation can be considered as an abandonned cart if it is linked to a website, # is in the 'draft' state and has an expiration date if order.website_id and order.state == 'draft' and order.date_order: public_partner_id = order.website_id.user_id.partner_id # by default the expiration date is 1 hour if not specified on the website configuration abandoned_delay = order.website_id.cart_abandoned_delay or 1.0 abandoned_datetime = datetime.utcnow() - relativedelta(hours=abandoned_delay) order.is_abandoned_cart = bool(order.date_order <= abandoned_datetime and order.partner_id != public_partner_id and order.order_line) else: order.is_abandoned_cart = False def _search_abandoned_cart(self, operator, value): website_ids = self.env['website'].search_read(fields=['id', 'cart_abandoned_delay', 'partner_id']) deadlines = [[ '&', '&', ('website_id', '=', website_id['id']), ('date_order', '<=', fields.Datetime.to_string(datetime.utcnow() - relativedelta(hours=website_id['cart_abandoned_delay'] or 1.0))), ('partner_id', '!=', website_id['partner_id'][0]) ] for website_id in website_ids] abandoned_domain = [ ('state', '=', 'draft'), ('order_line', '!=', False) ] abandoned_domain.extend(expression.OR(deadlines)) abandoned_domain = expression.normalize_domain(abandoned_domain) # is_abandoned domain possibilities if (operator not in expression.NEGATIVE_TERM_OPERATORS and value) or (operator in expression.NEGATIVE_TERM_OPERATORS and not value): return abandoned_domain return expression.distribute_not(['!'] + abandoned_domain) # negative domain def _cart_find_product_line(self, product_id=None, line_id=None, **kwargs): """Find the cart line matching the given parameters. If a product_id is given, the line will match the product only if the line also has the same special attributes: `no_variant` attributes and `is_custom` values. """ self.ensure_one() product = self.env['product.product'].browse(product_id) # split lines with the same product if it has untracked attributes if product and (product.product_tmpl_id.has_dynamic_attributes() or product.product_tmpl_id._has_no_variant_attributes()) and not line_id and not kwargs.get('force_search', False): return self.env['sale.order.line'] domain = [('order_id', '=', self.id), ('product_id', '=', product_id)] if line_id: domain += [('id', '=', line_id)] else: domain += [('product_custom_attribute_value_ids', '=', False)] return self.env['sale.order.line'].sudo().search(domain) def _website_product_id_change(self, order_id, product_id, qty=0, **kwargs): order = self.sudo().browse(order_id) product_context = dict(self.env.context) product_context.setdefault('lang', order.partner_id.lang) product_context.update({ 'partner': order.partner_id, 'quantity': qty, 'date': order.date_order, 'pricelist': order.pricelist_id.id, }) product = self.env['product.product'].with_context(product_context).with_company(order.company_id.id).browse(product_id) discount = 0 if order.pricelist_id.discount_policy == 'without_discount': # This part is pretty much a copy-paste of the method '_onchange_discount' of # 'sale.order.line'. price, rule_id = order.pricelist_id.with_context(product_context).get_product_price_rule(product, qty or 1.0, order.partner_id) pu, currency = request.env['sale.order.line'].with_context(product_context)._get_real_price_currency(product, rule_id, qty, product.uom_id, order.pricelist_id.id) if order.pricelist_id and order.partner_id: order_line = order._cart_find_product_line(product.id) if order_line: price = product._get_tax_included_unit_price( self.company_id, order.currency_id, order.date_order, 'sale', fiscal_position=order.fiscal_position_id, product_price_unit=price, product_currency=order.currency_id ) pu = product._get_tax_included_unit_price( self.company_id, order.currency_id, order.date_order, 'sale', fiscal_position=order.fiscal_position_id, product_price_unit=pu, product_currency=order.currency_id ) if pu != 0: if order.pricelist_id.currency_id != currency: # we need new_list_price in the same currency as price, which is in the SO's pricelist's currency date = order.date_order or fields.Date.today() pu = currency._convert(pu, order.pricelist_id.currency_id, order.company_id, date) discount = (pu - price) / pu * 100 if discount < 0: # In case the discount is negative, we don't want to show it to the customer, # but we still want to use the price defined on the pricelist discount = 0 pu = price else: # In case the price_unit equal 0 and therefore not able to calculate the discount, # we fallback on the price defined on the pricelist. pu = price else: pu = product.price if order.pricelist_id and order.partner_id: order_line = order._cart_find_product_line(product.id, force_search=True) if order_line: pu = product._get_tax_included_unit_price( self.company_id, order.currency_id, order.date_order, 'sale', fiscal_position=order.fiscal_position_id, product_price_unit=product.price, product_currency=order.currency_id ) return { 'product_id': product_id, 'product_uom_qty': qty, 'order_id': order_id, 'product_uom': product.uom_id.id, 'price_unit': pu, 'discount': discount, } def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs): """ Add or set product quantity, add_qty can be negative """ self.ensure_one() product_context = dict(self.env.context) product_context.setdefault('lang', self.sudo().partner_id.lang) SaleOrderLineSudo = self.env['sale.order.line'].sudo().with_context(product_context) # change lang to get correct name of attributes/values product_with_context = self.env['product.product'].with_context(product_context) product = product_with_context.browse(int(product_id)).exists() if not product or (not line_id and not product._is_add_to_cart_allowed()): raise UserError(_("The given product does not exist therefore it cannot be added to cart.")) try: if add_qty: add_qty = int(add_qty) except ValueError: add_qty = 1 try: if set_qty: set_qty = int(set_qty) except ValueError: set_qty = 0 quantity = 0 order_line = False if self.state != 'draft': request.session['sale_order_id'] = None raise UserError(_('It is forbidden to modify a sales order which is not in draft status.')) if line_id is not False: order_line = self._cart_find_product_line(product_id, line_id, **kwargs)[:1] # Create line if no line with product_id can be located if not order_line: no_variant_attribute_values = kwargs.get('no_variant_attribute_values') or [] received_no_variant_values = product.env['product.template.attribute.value'].browse([int(ptav['value']) for ptav in no_variant_attribute_values]) received_combination = product.product_template_attribute_value_ids | received_no_variant_values product_template = product.product_tmpl_id # handle all cases where incorrect or incomplete data are received combination = product_template._get_closest_possible_combination(received_combination) # get or create (if dynamic) the correct variant product = product_template._create_product_variant(combination) if not product: raise UserError(_("The given combination does not exist therefore it cannot be added to cart.")) product_id = product.id values = self._website_product_id_change(self.id, product_id, qty=1, **kwargs) # add no_variant attributes that were not received for ptav in combination.filtered(lambda ptav: ptav.attribute_id.create_variant == 'no_variant' and ptav not in received_no_variant_values): no_variant_attribute_values.append({ 'value': ptav.id, }) # save no_variant attributes values if no_variant_attribute_values: values['product_no_variant_attribute_value_ids'] = [ (6, 0, [int(attribute['value']) for attribute in no_variant_attribute_values]) ] # add is_custom attribute values that were not received custom_values = kwargs.get('product_custom_attribute_values') or [] received_custom_values = product.env['product.template.attribute.value'].browse([int(ptav['custom_product_template_attribute_value_id']) for ptav in custom_values]) for ptav in combination.filtered(lambda ptav: ptav.is_custom and ptav not in received_custom_values): custom_values.append({ 'custom_product_template_attribute_value_id': ptav.id, 'custom_value': '', }) # save is_custom attributes values if custom_values: values['product_custom_attribute_value_ids'] = [(0, 0, { 'custom_product_template_attribute_value_id': custom_value['custom_product_template_attribute_value_id'], 'custom_value': custom_value['custom_value'] }) for custom_value in custom_values] # create the line order_line = SaleOrderLineSudo.create(values) try: order_line._compute_tax_id() except ValidationError as e: # The validation may occur in backend (eg: taxcloud) but should fail silently in frontend _logger.debug("ValidationError occurs during tax compute. %s" % (e)) if add_qty: add_qty -= 1 # compute new quantity if set_qty: quantity = set_qty elif add_qty is not None: quantity = order_line.product_uom_qty + (add_qty or 0) # Remove zero of negative lines if quantity <= 0: linked_line = order_line.linked_line_id order_line.unlink() if linked_line: # update description of the parent linked_product = product_with_context.browse(linked_line.product_id.id) linked_line.name = linked_line.get_sale_order_line_multiline_description_sale(linked_product) else: # update line no_variant_attributes_price_extra = [ptav.price_extra for ptav in order_line.product_no_variant_attribute_value_ids] values = self.with_context(no_variant_attributes_price_extra=tuple(no_variant_attributes_price_extra))._website_product_id_change(self.id, product_id, qty=quantity, **kwargs) order = self.sudo().browse(self.id) if self.pricelist_id.discount_policy == 'with_discount' and not self.env.context.get('fixed_price'): product_context.update({ 'partner': order.partner_id, 'quantity': quantity, 'date': order.date_order, 'pricelist': order.pricelist_id.id, }) product_with_context = self.env['product.product'].with_context(product_context).with_company(order.company_id.id) product = product_with_context.browse(product_id) order_line.write(values) # link a product to the sales order if kwargs.get('linked_line_id'): linked_line = SaleOrderLineSudo.browse(kwargs['linked_line_id']) order_line.write({ 'linked_line_id': linked_line.id, }) linked_product = product_with_context.browse(linked_line.product_id.id) linked_line.name = linked_line.get_sale_order_line_multiline_description_sale(linked_product) # Generate the description with everything. This is done after # creating because the following related fields have to be set: # - product_no_variant_attribute_value_ids # - product_custom_attribute_value_ids # - linked_line_id order_line.name = order_line.get_sale_order_line_multiline_description_sale(product) option_lines = self.order_line.filtered(lambda l: l.linked_line_id.id == order_line.id) return {'line_id': order_line.id, 'quantity': quantity, 'option_ids': list(set(option_lines.ids))} def _cart_accessories(self): """ Suggest accessories based on 'Accessory Products' of products in cart """ for order in self: products = order.website_order_line.mapped('product_id') accessory_products = self.env['product.product'] for line in order.website_order_line.filtered(lambda l: l.product_id): combination = line.product_id.product_template_attribute_value_ids + line.product_no_variant_attribute_value_ids accessory_products |= line.product_id.product_tmpl_id._get_website_accessory_product().filtered(lambda product: product not in products and product._is_variant_possible(parent_combination=combination) and (product.company_id == line.company_id or not product.company_id) ) return random.sample(accessory_products, len(accessory_products)) def action_recovery_email_send(self): for order in self: order._portal_ensure_token() composer_form_view_id = self.env.ref('mail.email_compose_message_wizard_form').id template_id = self._get_cart_recovery_template().id return { 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'mail.compose.message', 'view_id': composer_form_view_id, 'target': 'new', 'context': { 'default_composition_mode': 'mass_mail' if len(self.ids) > 1 else 'comment', 'default_res_id': self.ids[0], 'default_model': 'sale.order', 'default_use_template': bool(template_id), 'default_template_id': template_id, 'website_sale_send_recovery_email': True, 'active_ids': self.ids, }, } def _get_cart_recovery_template(self): """ Return the cart recovery template record for a set of orders. If they all belong to the same website, we return the website-specific template; otherwise we return the default template. If the default is not found, the empty ['mail.template'] is returned. """ websites = self.mapped('website_id') template = websites.cart_recovery_mail_template_id if len(websites) == 1 else False template = template or self.env.ref('website_sale.mail_template_sale_cart_recovery', raise_if_not_found=False) return template or self.env['mail.template'] def _cart_recovery_email_send(self): """Send the cart recovery email on the current recordset, making sure that the portal token exists to avoid broken links, and marking the email as sent. Similar method to action_recovery_email_send, made to be called in automated actions. Contrary to the former, it will use the website-specific template for each order.""" sent_orders = self.env['sale.order'] for order in self: template = order._get_cart_recovery_template() if template: order._portal_ensure_token() template.send_mail(order.id) sent_orders |= order sent_orders.write({'cart_recovery_email_sent': True}) def action_confirm(self): res = super(SaleOrder, self).action_confirm() for order in self: if not order.transaction_ids and not order.amount_total and self._context.get('send_email'): order._send_order_confirmation_mail() return res class SaleOrderLine(models.Model): _inherit = "sale.order.line" name_short = fields.Char(compute="_compute_name_short") linked_line_id = fields.Many2one('sale.order.line', string='Linked Order Line', domain="[('order_id', '=', order_id)]", ondelete='cascade', copy=False, index=True) option_line_ids = fields.One2many('sale.order.line', 'linked_line_id', string='Options Linked') def get_sale_order_line_multiline_description_sale(self, product): description = super(SaleOrderLine, self).get_sale_order_line_multiline_description_sale(product) if self.linked_line_id: description += "\n" + _("Option for: %s", self.linked_line_id.product_id.display_name) if self.option_line_ids: description += "\n" + '\n'.join([_("Option: %s", option_line.product_id.display_name) for option_line in self.option_line_ids]) return description @api.depends('product_id.display_name') def _compute_name_short(self): """ Compute a short name for this sale order line, to be used on the website where we don't have much space. To keep it short, instead of using the first line of the description, we take the product name without the internal reference. """ for record in self: record.name_short = record.product_id.with_context(display_default_code=False).display_name def get_description_following_lines(self): return self.name.splitlines()[1:]
50.43128
21,282
2,715
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools, _ from odoo.exceptions import ValidationError from odoo.addons.website.tools import get_video_embed_code class ProductImage(models.Model): _name = 'product.image' _description = "Product Image" _inherit = ['image.mixin'] _order = 'sequence, id' name = fields.Char("Name", required=True) sequence = fields.Integer(default=10, index=True) image_1920 = fields.Image(required=True) product_tmpl_id = fields.Many2one('product.template', "Product Template", index=True, ondelete='cascade') product_variant_id = fields.Many2one('product.product', "Product Variant", index=True, ondelete='cascade') video_url = fields.Char('Video URL', help='URL of a video for showcasing your product.') embed_code = fields.Html(compute="_compute_embed_code", sanitize=False) can_image_1024_be_zoomed = fields.Boolean("Can Image 1024 be zoomed", compute='_compute_can_image_1024_be_zoomed', store=True) @api.depends('image_1920', 'image_1024') def _compute_can_image_1024_be_zoomed(self): for image in self: image.can_image_1024_be_zoomed = image.image_1920 and tools.is_image_size_above(image.image_1920, image.image_1024) @api.depends('video_url') def _compute_embed_code(self): for image in self: image.embed_code = get_video_embed_code(image.video_url) @api.constrains('video_url') def _check_valid_video_url(self): for image in self: if image.video_url and not image.embed_code: raise ValidationError(_("Provided video URL for '%s' is not valid. Please enter a valid video URL.", image.name)) @api.model_create_multi def create(self, vals_list): """ We don't want the default_product_tmpl_id from the context to be applied if we have a product_variant_id set to avoid having the variant images to show also as template images. But we want it if we don't have a product_variant_id set. """ context_without_template = self.with_context({k: v for k, v in self.env.context.items() if k != 'default_product_tmpl_id'}) normal_vals = [] variant_vals_list = [] for vals in vals_list: if vals.get('product_variant_id') and 'default_product_tmpl_id' in self.env.context: variant_vals_list.append(vals) else: normal_vals.append(vals) return super().create(normal_vals) + super(ProductImage, context_without_template).create(variant_vals_list)
43.095238
2,715
824
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' def _action_send_mail(self, auto_commit=False): context = self._context # TODO TDE: clean that brole one day if context.get('website_sale_send_recovery_email') and self.model == 'sale.order' and context.get('active_ids'): self.env['sale.order'].search([ ('id', 'in', context.get('active_ids')), ('cart_recovery_email_sent', '=', False), ('is_abandoned_cart', '=', True) ]).write({'cart_recovery_email_sent': True}) return super(MailComposeMessage, self)._action_send_mail(auto_commit=auto_commit)
43.368421
824
21,567
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.addons.http_routing.models.ir_http import slug, unslug from odoo.tools.translate import html_translate from odoo.osv import expression class ProductTemplate(models.Model): _inherit = [ "product.template", "website.seo.metadata", 'website.published.multi.mixin', 'website.searchable.mixin', 'rating.mixin', ] _name = 'product.template' _mail_post_access = 'read' _check_company_auto = True website_description = fields.Html('Description for the website', sanitize_attributes=False, translate=html_translate, sanitize_form=False) alternative_product_ids = fields.Many2many( 'product.template', 'product_alternative_rel', 'src_id', 'dest_id', check_company=True, string='Alternative Products', help='Suggest alternatives to your customer (upsell strategy). ' 'Those products show up on the product page.') accessory_product_ids = fields.Many2many( 'product.product', 'product_accessory_rel', 'src_id', 'dest_id', string='Accessory Products', check_company=True, help='Accessories show up when the customer reviews the cart before payment (cross-sell strategy).') website_size_x = fields.Integer('Size X', default=1) website_size_y = fields.Integer('Size Y', default=1) website_ribbon_id = fields.Many2one('product.ribbon', string='Ribbon') website_sequence = fields.Integer('Website Sequence', help="Determine the display order in the Website E-commerce", default=lambda self: self._default_website_sequence(), copy=False) public_categ_ids = fields.Many2many( 'product.public.category', relation='product_public_category_product_template_rel', string='Website Product Category', help="The product will be available in each mentioned eCommerce category. Go to Shop > " "Customize and enable 'eCommerce categories' to view all eCommerce categories.") product_template_image_ids = fields.One2many('product.image', 'product_tmpl_id', string="Extra Product Media", copy=True) base_unit_count = fields.Float('Base Unit Count', required=True, default=0, compute='_compute_base_unit_count', inverse='_set_base_unit_count', store=True, help="Display base unit price on your eCommerce pages. Set to 0 to hide it for this product.") base_unit_id = fields.Many2one('website.base.unit', string='Custom Unit of Measure', compute='_compute_base_unit_id', inverse='_set_base_unit_id', store=True, help="Define a custom unit to display in the price per unit of measure field.") base_unit_price = fields.Monetary("Price Per Unit", currency_field="currency_id", compute="_compute_base_unit_price") base_unit_name = fields.Char(compute='_compute_base_unit_name', help='Displays the custom unit for the products if defined or the selected unit of measure otherwise.') @api.depends('product_variant_ids', 'product_variant_ids.base_unit_count') def _compute_base_unit_count(self): self.base_unit_count = 0 for template in self.filtered(lambda template: len(template.product_variant_ids) == 1): template.base_unit_count = template.product_variant_ids.base_unit_count def _set_base_unit_count(self): for template in self: if len(template.product_variant_ids) == 1: template.product_variant_ids.base_unit_count = template.base_unit_count @api.depends('product_variant_ids', 'product_variant_ids.base_unit_count') def _compute_base_unit_id(self): self.base_unit_id = self.env['website.base.unit'] for template in self.filtered(lambda template: len(template.product_variant_ids) == 1): template.base_unit_id = template.product_variant_ids.base_unit_id def _set_base_unit_id(self): for template in self: if len(template.product_variant_ids) == 1: template.product_variant_ids.base_unit_id = template.base_unit_id @api.depends('price', 'list_price', 'base_unit_count') def _compute_base_unit_price(self): for template in self: template_price = (template.price or template.list_price) if template.id else template.list_price template.base_unit_price = template.base_unit_count and template_price / template.base_unit_count @api.depends('uom_name', 'base_unit_id.name') def _compute_base_unit_name(self): for template in self: template.base_unit_name = template.base_unit_id.name or template.uom_name def _prepare_variant_values(self, combination): variant_dict = super()._prepare_variant_values(combination) variant_dict['base_unit_count'] = self.base_unit_count return variant_dict def _get_website_accessory_product(self): domain = self.env['website'].sale_product_domain() return self.accessory_product_ids.filtered_domain(domain) def _get_website_alternative_product(self): domain = self.env['website'].sale_product_domain() return self.alternative_product_ids.filtered_domain(domain) def _has_no_variant_attributes(self): """Return whether this `product.template` has at least one no_variant attribute. :return: True if at least one no_variant attribute, False otherwise :rtype: bool """ self.ensure_one() return any(a.create_variant == 'no_variant' for a in self.valid_product_template_attribute_line_ids.attribute_id) def _has_is_custom_values(self): self.ensure_one() """Return whether this `product.template` has at least one is_custom attribute value. :return: True if at least one is_custom attribute value, False otherwise :rtype: bool """ return any(v.is_custom for v in self.valid_product_template_attribute_line_ids.product_template_value_ids._only_active()) def _get_possible_variants_sorted(self, parent_combination=None): """Return the sorted recordset of variants that are possible. The order is based on the order of the attributes and their values. See `_get_possible_variants` for the limitations of this method with dynamic or no_variant attributes, and also for a warning about performances. :param parent_combination: combination from which `self` is an optional or accessory product :type parent_combination: recordset `product.template.attribute.value` :return: the sorted variants that are possible :rtype: recordset of `product.product` """ self.ensure_one() def _sort_key_attribute_value(value): # if you change this order, keep it in sync with _order from `product.attribute` return (value.attribute_id.sequence, value.attribute_id.id) def _sort_key_variant(variant): """ We assume all variants will have the same attributes, with only one value for each. - first level sort: same as "product.attribute"._order - second level sort: same as "product.attribute.value"._order """ keys = [] for attribute in variant.product_template_attribute_value_ids.sorted(_sort_key_attribute_value): # if you change this order, keep it in sync with _order from `product.attribute.value` keys.append(attribute.product_attribute_value_id.sequence) keys.append(attribute.id) return keys return self._get_possible_variants(parent_combination).sorted(_sort_key_variant) def _get_combination_info(self, combination=False, product_id=False, add_qty=1, pricelist=False, parent_combination=False, only_template=False): """Override for website, where we want to: - take the website pricelist if no pricelist is set - apply the b2b/b2c setting to the result This will work when adding website_id to the context, which is done automatically when called from routes with website=True. """ self.ensure_one() current_website = False if self.env.context.get('website_id'): current_website = self.env['website'].get_current_website() if not pricelist: pricelist = current_website.get_current_pricelist() combination_info = super(ProductTemplate, self)._get_combination_info( combination=combination, product_id=product_id, add_qty=add_qty, pricelist=pricelist, parent_combination=parent_combination, only_template=only_template) if self.env.context.get('website_id'): context = dict(self.env.context, ** { 'quantity': self.env.context.get('quantity', add_qty), 'pricelist': pricelist and pricelist.id }) product = (self.env['product.product'].browse(combination_info['product_id']) or self).with_context(context) partner = self.env.user.partner_id company_id = current_website.company_id tax_display = self.user_has_groups('account.group_show_line_subtotals_tax_excluded') and 'total_excluded' or 'total_included' fpos = self.env['account.fiscal.position'].sudo().get_fiscal_position(partner.id) product_taxes = product.sudo().taxes_id.filtered(lambda x: x.company_id == company_id) taxes = fpos.map_tax(product_taxes) # The list_price is always the price of one. quantity_1 = 1 combination_info['price'] = self.env['account.tax']._fix_tax_included_price_company( combination_info['price'], product_taxes, taxes, company_id) price = taxes.compute_all(combination_info['price'], pricelist.currency_id, quantity_1, product, partner)[tax_display] if pricelist.discount_policy == 'without_discount': combination_info['list_price'] = self.env['account.tax']._fix_tax_included_price_company( combination_info['list_price'], product_taxes, taxes, company_id) list_price = taxes.compute_all(combination_info['list_price'], pricelist.currency_id, quantity_1, product, partner)[tax_display] else: list_price = price combination_info['price_extra'] = self.env['account.tax']._fix_tax_included_price_company(combination_info['price_extra'], product_taxes, taxes, company_id) price_extra = taxes.compute_all(combination_info['price_extra'], pricelist.currency_id, quantity_1, product, partner)[tax_display] has_discounted_price = pricelist.currency_id.compare_amounts(list_price, price) == 1 combination_info.update( base_unit_name=product.base_unit_name, base_unit_price=product.base_unit_count and list_price / product.base_unit_count, price=price, list_price=list_price, price_extra=price_extra, has_discounted_price=has_discounted_price, ) return combination_info def _get_image_holder(self): """Returns the holder of the image to use as default representation. If the product template has an image it is the product template, otherwise if the product has variants it is the first variant :return: this product template or the first product variant :rtype: recordset of 'product.template' or recordset of 'product.product' """ self.ensure_one() if self.image_128: return self variant = self.env['product.product'].browse(self._get_first_possible_variant_id()) # if the variant has no image anyway, spare some queries by using template return variant if variant.image_variant_128 else self def _get_current_company_fallback(self, **kwargs): """Override: if a website is set on the product or given, fallback to the company of the website. Otherwise use the one from parent method.""" res = super(ProductTemplate, self)._get_current_company_fallback(**kwargs) website = self.website_id or kwargs.get('website') return website and website.company_id or res def _default_website_sequence(self): ''' We want new product to be the last (highest seq). Every product should ideally have an unique sequence. Default sequence (10000) should only be used for DB first product. As we don't resequence the whole tree (as `sequence` does), this field might have negative value. ''' self._cr.execute("SELECT MAX(website_sequence) FROM %s" % self._table) max_sequence = self._cr.fetchone()[0] if max_sequence is None: return 10000 return max_sequence + 5 def set_sequence_top(self): min_sequence = self.sudo().search([], order='website_sequence ASC', limit=1) self.website_sequence = min_sequence.website_sequence - 5 def set_sequence_bottom(self): max_sequence = self.sudo().search([], order='website_sequence DESC', limit=1) self.website_sequence = max_sequence.website_sequence + 5 def set_sequence_up(self): previous_product_tmpl = self.sudo().search([ ('website_sequence', '<', self.website_sequence), ('website_published', '=', self.website_published), ], order='website_sequence DESC', limit=1) if previous_product_tmpl: previous_product_tmpl.website_sequence, self.website_sequence = self.website_sequence, previous_product_tmpl.website_sequence else: self.set_sequence_top() def set_sequence_down(self): next_prodcut_tmpl = self.search([ ('website_sequence', '>', self.website_sequence), ('website_published', '=', self.website_published), ], order='website_sequence ASC', limit=1) if next_prodcut_tmpl: next_prodcut_tmpl.website_sequence, self.website_sequence = self.website_sequence, next_prodcut_tmpl.website_sequence else: return self.set_sequence_bottom() def _default_website_meta(self): res = super(ProductTemplate, self)._default_website_meta() res['default_opengraph']['og:description'] = res['default_twitter']['twitter:description'] = self.description_sale res['default_opengraph']['og:title'] = res['default_twitter']['twitter:title'] = self.name res['default_opengraph']['og:image'] = res['default_twitter']['twitter:image'] = self.env['website'].image_url(self, 'image_1024') res['default_meta_description'] = self.description_sale return res def _compute_website_url(self): super(ProductTemplate, self)._compute_website_url() for product in self: if product.id: product.website_url = "/shop/%s" % slug(product) def _is_sold_out(self): return self.product_variant_id._is_sold_out() def _get_website_ribbon(self): return self.website_ribbon_id # --------------------------------------------------------- # Rating Mixin API # --------------------------------------------------------- def _rating_domain(self): """ Only take the published rating into account to compute avg and count """ domain = super(ProductTemplate, self)._rating_domain() return expression.AND([domain, [('is_internal', '=', False)]]) def _get_images(self): """Return a list of records implementing `image.mixin` to display on the carousel on the website for this template. This returns a list and not a recordset because the records might be from different models (template and image). It contains in this order: the main image of the template and the Template Extra Images. """ self.ensure_one() return [self] + list(self.product_template_image_ids) @api.model def _search_get_detail(self, website, order, options): with_image = options['displayImage'] with_description = options['displayDescription'] with_category = options['displayExtraLink'] with_price = options['displayDetail'] domains = [website.sale_product_domain()] category = options.get('category') min_price = options.get('min_price') max_price = options.get('max_price') attrib_values = options.get('attrib_values') if category: domains.append([('public_categ_ids', 'child_of', unslug(category)[1])]) if min_price: domains.append([('list_price', '>=', min_price)]) if max_price: domains.append([('list_price', '<=', max_price)]) if attrib_values: attrib = None ids = [] for value in attrib_values: if not attrib: attrib = value[0] ids.append(value[1]) elif value[0] == attrib: ids.append(value[1]) else: domains.append([('attribute_line_ids.value_ids', 'in', ids)]) attrib = value[0] ids = [value[1]] if attrib: domains.append([('attribute_line_ids.value_ids', 'in', ids)]) search_fields = ['name', 'default_code', 'product_variant_ids.default_code'] fetch_fields = ['id', 'name', 'website_url'] mapping = { 'name': {'name': 'name', 'type': 'text', 'match': True}, 'default_code': {'name': 'default_code', 'type': 'text', 'match': True}, 'product_variant_ids.default_code': {'name': 'product_variant_ids.default_code', 'type': 'text', 'match': True}, 'website_url': {'name': 'website_url', 'type': 'text', 'truncate': False}, } if with_image: mapping['image_url'] = {'name': 'image_url', 'type': 'html'} if with_description: # Internal note is not part of the rendering. search_fields.append('description') fetch_fields.append('description') search_fields.append('description_sale') fetch_fields.append('description_sale') mapping['description'] = {'name': 'description_sale', 'type': 'text', 'match': True} if with_price: mapping['detail'] = {'name': 'price', 'type': 'html', 'display_currency': options['display_currency']} mapping['detail_strike'] = {'name': 'list_price', 'type': 'html', 'display_currency': options['display_currency']} if with_category: mapping['extra_link'] = {'name': 'category', 'type': 'dict', 'item_type': 'text'} mapping['extra_link_url'] = {'name': 'category_url', 'type': 'dict', 'item_type': 'text'} return { 'model': 'product.template', 'base_domain': domains, 'search_fields': search_fields, 'fetch_fields': fetch_fields, 'mapping': mapping, 'icon': 'fa-shopping-cart', } def _search_render_results(self, fetch_fields, mapping, icon, limit): with_image = 'image_url' in mapping with_category = 'extra_link' in mapping with_price = 'detail' in mapping results_data = super()._search_render_results(fetch_fields, mapping, icon, limit) current_website = self.env['website'].get_current_website() for product, data in zip(self, results_data): categ_ids = product.public_categ_ids.filtered(lambda c: not c.website_id or c.website_id == current_website) if with_price: combination_info = product._get_combination_info(only_template=True) monetary_options = {'display_currency': mapping['detail']['display_currency']} data['price'] = self.env['ir.qweb.field.monetary'].value_to_html(combination_info['price'], monetary_options) if combination_info['has_discounted_price']: data['list_price'] = self.env['ir.qweb.field.monetary'].value_to_html(combination_info['list_price'], monetary_options) if with_image: data['image_url'] = '/web/image/product.template/%s/image_128' % data['id'] if with_category and categ_ids: data['category'] = {'extra_link_title': _('Categories:') if len(categ_ids) > 1 else _('Category:')} data['category_url'] = dict() for categ in categ_ids: slug_categ = slug(categ) data['category'][slug_categ] = categ.name data['category_url'][slug_categ] = '/shop/category/%s' % slug_categ return results_data @api.model def get_google_analytics_data(self, combination): product = self.env['product.product'].browse(combination['product_id']) return { 'item_id': product.barcode or product.id, 'item_name': combination['display_name'], 'item_category': product.categ_id.name or '-', 'currency': product.currency_id.name, 'price': combination['list_price'], }
51.35
21,567
4,620
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class Product(models.Model): _inherit = "product.product" website_id = fields.Many2one(related='product_tmpl_id.website_id', readonly=False) product_variant_image_ids = fields.One2many('product.image', 'product_variant_id', string="Extra Variant Images") website_url = fields.Char('Website URL', compute='_compute_product_website_url', help='The full URL to access the document through the website.') base_unit_count = fields.Float('Base Unit Count', required=True, default=1, help="Display base unit price on your eCommerce pages. Set to 0 to hide it for this product.") base_unit_id = fields.Many2one('website.base.unit', string='Custom Unit of Measure', help="Define a custom unit to display in the price per unit of measure field.") base_unit_price = fields.Monetary("Price Per Unit", currency_field="currency_id", compute="_compute_base_unit_price") base_unit_name = fields.Char(compute='_compute_base_unit_name', help='Displays the custom unit for the products if defined or the selected unit of measure otherwise.') @api.depends('price', 'lst_price', 'base_unit_count') def _compute_base_unit_price(self): for product in self: if not product.id: product.base_unit_price = 0 else: product.base_unit_price = product.base_unit_count and (product.price or product.lst_price) / product.base_unit_count @api.depends('uom_name', 'base_unit_id') def _compute_base_unit_name(self): for product in self: product.base_unit_name = product.base_unit_id.name or product.uom_name @api.constrains('base_unit_count') def _check_base_unit_count(self): if any(product.base_unit_count < 0 for product in self): raise ValidationError(_('The value of Base Unit Count must be greater than 0. Use 0 to hide the price per unit on this product.')) @api.depends_context('lang') @api.depends('product_tmpl_id.website_url', 'product_template_attribute_value_ids') def _compute_product_website_url(self): for product in self: attributes = ','.join(str(x) for x in product.product_template_attribute_value_ids.ids) product.website_url = "%s#attr=%s" % (product.product_tmpl_id.website_url, attributes) def _prepare_variant_values(self, combination): variant_dict = super()._prepare_variant_values(combination) variant_dict['base_unit_count'] = self.base_unit_count return variant_dict def website_publish_button(self): self.ensure_one() return self.product_tmpl_id.website_publish_button() def open_website_url(self): self.ensure_one() res = self.product_tmpl_id.open_website_url() res['url'] = self.website_url return res def _get_images(self): """Return a list of records implementing `image.mixin` to display on the carousel on the website for this variant. This returns a list and not a recordset because the records might be from different models (template, variant and image). It contains in this order: the main image of the variant (if set), the Variant Extra Images, and the Template Extra Images. """ self.ensure_one() variant_images = list(self.product_variant_image_ids) if self.image_variant_1920: # if the main variant image is set, display it first variant_images = [self] + variant_images else: # If the main variant image is empty, it will fallback to template # image, in this case insert it after the other variant images, so # that all variant images are first and all template images last. variant_images = variant_images + [self] # [1:] to remove the main image from the template, we only display # the template extra images here return variant_images + self.product_tmpl_id._get_images()[1:] def _is_sold_out(self): combination_info = self.with_context(website_sale_stock_get_quantity=True).product_tmpl_id._get_combination_info(product_id=self.id) return combination_info['product_type'] == 'product' and combination_info['free_qty'] <= 0 def _is_add_to_cart_allowed(self): self.ensure_one() return self.user_has_groups('base.group_system') or (self.active and self.sale_ok and self.website_published)
50.217391
4,620
440
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.http import request class WabsitePage(models.AbstractModel): _inherit = 'website.page' def _get_cache_key(self, req): cart = request.website.sale_get_order() cache_key = (cart and cart.cart_quantity or 0,) cache_key += super()._get_cache_key(req) return cache_key
31.428571
440
782
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResCompany(models.Model): _inherit = 'res.company' website_sale_onboarding_payment_acquirer_state = fields.Selection([('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done")], string="State of the website sale onboarding payment acquirer step", default='not_done') @api.model def action_open_website_sale_onboarding_payment_acquirer(self): """ Called by onboarding panel above the quotation list.""" self.env.company.payment_onboarding_payment_method = 'stripe' menu_id = self.env.ref('website.menu_website_dashboard').id return self._run_payment_onboarding_step(menu_id)
46
782
9,827
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools, _ from odoo.exceptions import ValidationError, UserError from odoo.addons.website.models import ir_http from odoo.tools.translate import html_translate class ProductRibbon(models.Model): _name = "product.ribbon" _description = 'Product ribbon' def name_get(self): return [(ribbon.id, '%s (#%d)' % (tools.html2plaintext(ribbon.html), ribbon.id)) for ribbon in self] html = fields.Html(string='Ribbon html', required=True, translate=True, sanitize=False) bg_color = fields.Char(string='Ribbon background color', required=False) text_color = fields.Char(string='Ribbon text color', required=False) html_class = fields.Char(string='Ribbon class', required=True, default='') class ProductPricelist(models.Model): _inherit = "product.pricelist" def _default_website(self): """ Find the first company's website, if there is one. """ company_id = self.env.company.id if self._context.get('default_company_id'): company_id = self._context.get('default_company_id') domain = [('company_id', '=', company_id)] return self.env['website'].search(domain, limit=1) website_id = fields.Many2one('website', string="Website", ondelete='restrict', default=_default_website, domain="[('company_id', '=?', company_id)]") code = fields.Char(string='E-commerce Promotional Code', groups="base.group_user") selectable = fields.Boolean(help="Allow the end user to choose this price list") def clear_cache(self): # website._get_pl_partner_order() is cached to avoid to recompute at each request the # list of available pricelists. So, we need to invalidate the cache when # we change the config of website price list to force to recompute. website = self.env['website'] website._get_pl_partner_order.clear_cache(website) @api.model def create(self, data): if data.get('company_id') and not data.get('website_id'): # l10n modules install will change the company currency, creating a # pricelist for that currency. Do not use user's company in that # case as module install are done with OdooBot (company 1) self = self.with_context(default_company_id=data['company_id']) res = super(ProductPricelist, self).create(data) self.clear_cache() return res def write(self, data): res = super(ProductPricelist, self).write(data) if data.keys() & {'code', 'active', 'website_id', 'selectable', 'company_id'}: self._check_website_pricelist() self.clear_cache() return res def unlink(self): res = super(ProductPricelist, self).unlink() self._check_website_pricelist() self.clear_cache() return res def _get_partner_pricelist_multi_search_domain_hook(self, company_id): domain = super(ProductPricelist, self)._get_partner_pricelist_multi_search_domain_hook(company_id) website = ir_http.get_request_website() if website: domain += self._get_website_pricelists_domain(website.id) return domain def _get_partner_pricelist_multi_filter_hook(self): res = super(ProductPricelist, self)._get_partner_pricelist_multi_filter_hook() website = ir_http.get_request_website() if website: res = res.filtered(lambda pl: pl._is_available_on_website(website.id)) return res def _check_website_pricelist(self): for website in self.env['website'].search([]): # sudo() to be able to read pricelists/website from another company if not website.sudo().pricelist_ids: raise UserError(_("With this action, '%s' website would not have any pricelist available.") % (website.name)) def _is_available_on_website(self, website_id): """ To be able to be used on a website, a pricelist should either: - Have its `website_id` set to current website (specific pricelist). - Have no `website_id` set and should be `selectable` (generic pricelist) or should have a `code` (generic promotion). - Have no `company_id` or a `company_id` matching its website one. Note: A pricelist without a website_id, not selectable and without a code is a backend pricelist. Change in this method should be reflected in `_get_website_pricelists_domain`. """ self.ensure_one() if self.company_id and self.company_id != self.env["website"].browse(website_id).company_id: return False return self.website_id.id == website_id or (not self.website_id and (self.selectable or self.sudo().code)) def _get_website_pricelists_domain(self, website_id): ''' Check above `_is_available_on_website` for explanation. Change in this method should be reflected in `_is_available_on_website`. ''' company_id = self.env["website"].browse(website_id).company_id.id return [ '&', ('company_id', 'in', [False, company_id]), '|', ('website_id', '=', website_id), '&', ('website_id', '=', False), '|', ('selectable', '=', True), ('code', '!=', False), ] def _get_partner_pricelist_multi(self, partner_ids, company_id=None): ''' If `property_product_pricelist` is read from website, we should use the website's company and not the user's one. Passing a `company_id` to super will avoid using the current user's company. ''' website = ir_http.get_request_website() if not company_id and website: company_id = website.company_id.id return super(ProductPricelist, self)._get_partner_pricelist_multi(partner_ids, company_id) @api.constrains('company_id', 'website_id') def _check_websites_in_company(self): '''Prevent misconfiguration multi-website/multi-companies. If the record has a company, the website should be from that company. ''' for record in self.filtered(lambda pl: pl.website_id and pl.company_id): if record.website_id.company_id != record.company_id: raise ValidationError(_("""Only the company's websites are allowed.\nLeave the Company field empty or select a website from that company.""")) class ProductPublicCategory(models.Model): _name = "product.public.category" _inherit = [ 'website.seo.metadata', 'website.multi.mixin', 'website.searchable.mixin', 'image.mixin', ] _description = "Website Product Category" _parent_store = True _order = "sequence, name, id" def _default_sequence(self): cat = self.search([], limit=1, order="sequence DESC") if cat: return cat.sequence + 5 return 10000 name = fields.Char(required=True, translate=True) parent_id = fields.Many2one('product.public.category', string='Parent Category', index=True, ondelete="cascade") parent_path = fields.Char(index=True) child_id = fields.One2many('product.public.category', 'parent_id', string='Children Categories') parents_and_self = fields.Many2many('product.public.category', compute='_compute_parents_and_self') sequence = fields.Integer(help="Gives the sequence order when displaying a list of product categories.", index=True, default=_default_sequence) website_description = fields.Html('Category Description', sanitize_attributes=False, translate=html_translate, sanitize_form=False) product_tmpl_ids = fields.Many2many('product.template', relation='product_public_category_product_template_rel') @api.constrains('parent_id') def check_parent_id(self): if not self._check_recursion(): raise ValueError(_('Error ! You cannot create recursive categories.')) def name_get(self): res = [] for category in self: res.append((category.id, " / ".join(category.parents_and_self.mapped('name')))) return res def _compute_parents_and_self(self): for category in self: if category.parent_path: category.parents_and_self = self.env['product.public.category'].browse([int(p) for p in category.parent_path.split('/')[:-1]]) else: category.parents_and_self = category @api.model def _search_get_detail(self, website, order, options): with_description = options['displayDescription'] search_fields = ['name'] fetch_fields = ['id', 'name'] mapping = { 'name': {'name': 'name', 'type': 'text', 'match': True}, 'website_url': {'name': 'url', 'type': 'text', 'truncate': False}, } if with_description: search_fields.append('website_description') fetch_fields.append('website_description') mapping['description'] = {'name': 'website_description', 'type': 'text', 'match': True, 'html': True} return { 'model': 'product.public.category', 'base_domain': [website.website_domain()], 'search_fields': search_fields, 'fetch_fields': fetch_fields, 'mapping': mapping, 'icon': 'fa-folder-o', 'order': 'name desc, id desc' if 'name desc' in order else 'name asc, id desc', } def _search_render_results(self, fetch_fields, mapping, icon, limit): results_data = super()._search_render_results(fetch_fields, mapping, icon, limit) for data in results_data: data['url'] = '/shop/category/%s' % data['id'] return results_data
46.13615
9,827
7,911
py
PYTHON
15.0
# -*- coding: utf-8 -*- from collections import Counter from odoo import models, fields, api, _ from odoo.osv import expression class WebsiteSnippetFilter(models.Model): _inherit = 'website.snippet.filter' product_cross_selling = fields.Boolean(string="About cross selling products", default=False, help="True only for product filters that require a product_id because they relate to cross selling") @api.model def _get_website_currency(self): pricelist = self.env['website'].get_current_website().get_current_pricelist() return pricelist.currency_id def _get_hardcoded_sample(self, model): samples = super()._get_hardcoded_sample(model) if model._name == 'product.product': data = [{ 'image_512': b'/product/static/img/product_chair.png', 'display_name': _('Chair'), 'description_sale': _('Sit comfortably'), }, { 'image_512': b'/product/static/img/product_lamp.png', 'display_name': _('Lamp'), 'description_sale': _('Lightbulb sold separately'), }, { 'image_512': b'/product/static/img/product_product_20-image.png', 'display_name': _('Whiteboard'), 'description_sale': _('With three feet'), }, { 'image_512': b'/product/static/img/product_product_27-image.png', 'display_name': _('Drawer'), 'description_sale': _('On wheels'), }, { 'image_512': b'/product/static/img/product_product_7-image.png', 'display_name': _('Box'), 'description_sale': _('Reinforced for heavy loads'), }, { 'image_512': b'/product/static/img/product_product_9-image.png', 'display_name': _('Bin'), 'description_sale': _('Pedal-based opening system'), }] merged = [] for index in range(0, max(len(samples), len(data))): merged.append({**samples[index % len(samples)], **data[index % len(data)]}) # merge definitions samples = merged return samples def _filter_records_to_values(self, records, is_sample=False): res_products = super()._filter_records_to_values(records, is_sample) if self.model_name == 'product.product': for res_product in res_products: product = res_product.get('_record') if not is_sample: res_product.update(product._get_combination_info_variant()) if records.env.context.get('add2cart_rerender'): res_product['_add2cart_rerender'] = True return res_products @api.model def _get_products(self, mode, context): dynamic_filter = context.get('dynamic_filter') handler = getattr(self, '_get_products_%s' % mode, self._get_products_latest_sold) website = self.env['website'].get_current_website() search_domain = context.get('search_domain') limit = context.get('limit') domain = expression.AND([ [('website_published', '=', True)], website.website_domain(), [('company_id', 'in', [False, website.company_id.id])], search_domain or [], ]) products = handler(website, limit, domain, context) return dynamic_filter._filter_records_to_values(products, False) def _get_products_latest_sold(self, website, limit, domain, context): products = [] sale_orders = self.env['sale.order'].sudo().search([ ('website_id', '=', website.id), ('state', 'in', ('sale', 'done')), ], limit=8, order='date_order DESC') if sale_orders: sold_products = [p.product_id.id for p in sale_orders.order_line] products_ids = [id for id, _ in Counter(sold_products).most_common()] if products_ids: domain = expression.AND([ domain, [('id', 'in', products_ids)], ]) products = self.env['product.product'].with_context(display_default_code=False).search(domain) products = products.sorted(key=lambda p: products_ids.index(p.id))[:limit] return products def _get_products_latest_viewed(self, website, limit, domain, context): products = [] visitor = self.env['website.visitor']._get_visitor_from_request() if visitor: excluded_products = website.sale_get_order().order_line.product_id.ids tracked_products = self.env['website.track'].sudo().read_group( [('visitor_id', '=', visitor.id), ('product_id', '!=', False), ('product_id.website_published', '=', True), ('product_id', 'not in', excluded_products)], ['product_id', 'visit_datetime:max'], ['product_id'], limit=limit, orderby='visit_datetime DESC') products_ids = [product['product_id'][0] for product in tracked_products] if products_ids: domain = expression.AND([ domain, [('id', 'in', products_ids)], ]) products = self.env['product.product'].with_context(display_default_code=False, add2cart_rerender=True).search(domain, limit=limit) return products def _get_products_recently_sold_with(self, website, limit, domain, context): products = [] current_id = context.get('product_template_id') if current_id: current_id = int(current_id) sale_orders = self.env['sale.order'].sudo().search([ ('website_id', '=', website.id), ('state', 'in', ('sale', 'done')), ('order_line.product_id.product_tmpl_id', '=', current_id), ], limit=8, order='date_order DESC') if sale_orders: current_template = self.env['product.template'].browse(current_id) excluded_products = website.sale_get_order().order_line.product_id.product_tmpl_id.product_variant_ids.ids excluded_products.extend(current_template.product_variant_ids.ids) included_products = [] for sale_order in sale_orders: included_products.extend(sale_order.order_line.product_id.ids) products_ids = list(set(included_products) - set(excluded_products)) if products_ids: domain = expression.AND([ domain, [('id', 'in', products_ids)], ]) products = self.env['product.product'].with_context(display_default_code=False).search(domain, limit=limit) return products def _get_products_accessories(self, website, limit, domain, context): products = [] current_id = context.get('product_template_id') if current_id: current_id = int(current_id) current_template = self.env['product.template'].browse(current_id) if current_template.exists(): excluded_products = website.sale_get_order().order_line.product_id.ids excluded_products.extend(current_template.product_variant_ids.ids) included_products = current_template._get_website_accessory_product().ids products_ids = list(set(included_products) - set(excluded_products)) if products_ids: domain = expression.AND([ domain, [('id', 'in', products_ids)], ]) products = self.env['product.product'].with_context(display_default_code=False).search(domain, limit=limit) return products
49.44375
7,911
4,314
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' salesperson_id = fields.Many2one('res.users', related='website_id.salesperson_id', string='Salesperson', readonly=False) salesteam_id = fields.Many2one('crm.team', related='website_id.salesteam_id', string='Sales Team', readonly=False) module_website_sale_delivery = fields.Boolean("eCommerce Shipping Costs") # field used to have a nice radio in form view, resuming the 2 fields above sale_delivery_settings = fields.Selection([ ('none', 'No shipping management on website'), ('internal', "Delivery methods are only used internally: the customer doesn't pay for shipping costs"), ('website', "Delivery methods are selectable on the website: the customer pays for shipping costs"), ], string="Shipping Management") group_delivery_invoice_address = fields.Boolean(string="Shipping Address", implied_group='sale.group_delivery_invoice_address', group='base.group_portal,base.group_user,base.group_public') group_show_uom_price = fields.Boolean(default=False, string="Base Unit Price", implied_group="website_sale.group_show_uom_price", group='base.group_portal,base.group_user,base.group_public') module_website_sale_digital = fields.Boolean("Digital Content") module_website_sale_wishlist = fields.Boolean("Wishlists") module_website_sale_comparison = fields.Boolean("Product Comparison Tool") module_website_sale_gift_card = fields.Boolean("Gift Card") module_account = fields.Boolean("Invoicing") cart_recovery_mail_template = fields.Many2one('mail.template', string='Cart Recovery Email', domain="[('model', '=', 'sale.order')]", related='website_id.cart_recovery_mail_template_id', readonly=False) cart_abandoned_delay = fields.Float("Abandoned Delay", help="Number of hours after which the cart is considered abandoned.", related='website_id.cart_abandoned_delay', readonly=False) cart_add_on_page = fields.Boolean("Stay on page after adding to cart", related='website_id.cart_add_on_page', readonly=False) terms_url = fields.Char(compute='_compute_terms_url', string="URL", help="A preview will be available at this URL.") @api.depends('website_id') def _compute_terms_url(self): for record in self: record.terms_url = '%s/terms' % record.website_id.get_base_url() @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() sale_delivery_settings = 'none' if self.env['ir.module.module'].search([('name', '=', 'delivery')], limit=1).state in ('installed', 'to install', 'to upgrade'): sale_delivery_settings = 'internal' if self.env['ir.module.module'].search([('name', '=', 'website_sale_delivery')], limit=1).state in ('installed', 'to install', 'to upgrade'): sale_delivery_settings = 'website' res.update( sale_delivery_settings=sale_delivery_settings, ) return res @api.onchange('sale_delivery_settings') def _onchange_sale_delivery_settings(self): if self.sale_delivery_settings == 'none': self.update({ 'module_delivery': False, 'module_website_sale_delivery': False, }) elif self.sale_delivery_settings == 'internal': self.update({ 'module_delivery': True, 'module_website_sale_delivery': False, }) else: self.update({ 'module_delivery': True, 'module_website_sale_delivery': True, }) @api.onchange('group_discount_per_so_line') def _onchange_group_discount_per_so_line(self): if self.group_discount_per_so_line: self.update({ 'group_product_pricelist': True, }) def action_update_terms(self): self.ensure_one() return { 'type': 'ir.actions.act_url', 'url': '/terms?enable_editor=1', 'target': 'self', }
49.586207
4,314
1,293
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import OrderedDict from odoo import models, fields class ProductAttribute(models.Model): _inherit = 'product.attribute' visibility = fields.Selection([('visible', 'Visible'), ('hidden', 'Hidden')], default='visible') class ProductTemplateAttributeLine(models.Model): _inherit = 'product.template.attribute.line' def _prepare_single_value_for_display(self): """On the product page group together the attribute lines that concern the same attribute and that have only one value each. Indeed those are considered informative values, they do not generate choice for the user, so they are displayed below the configurator. The returned attributes are ordered as they appear in `self`, so based on the order of the attribute lines. """ single_value_lines = self.filtered(lambda ptal: len(ptal.value_ids) == 1) single_value_attributes = OrderedDict([(pa, self.env['product.template.attribute.line']) for pa in single_value_lines.attribute_id]) for ptal in single_value_lines: single_value_attributes[ptal.attribute_id] |= ptal return single_value_attributes
40.40625
1,293
22,180
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models, tools, SUPERUSER_ID, _ from odoo.http import request from odoo.addons.website.models import ir_http from odoo.addons.http_routing.models.ir_http import url_for _logger = logging.getLogger(__name__) class Website(models.Model): _inherit = 'website' pricelist_id = fields.Many2one('product.pricelist', compute='_compute_pricelist_id', string='Default Pricelist') currency_id = fields.Many2one('res.currency', related='pricelist_id.currency_id', depends=(), related_sudo=False, string='Default Currency', readonly=False) salesperson_id = fields.Many2one('res.users', string='Salesperson') def _get_default_website_team(self): try: team = self.env.ref('sales_team.salesteam_website_sales') return team if team.active else None except ValueError: return None salesteam_id = fields.Many2one('crm.team', string='Sales Team', ondelete="set null", default=_get_default_website_team) pricelist_ids = fields.One2many('product.pricelist', compute="_compute_pricelist_ids", string='Price list available for this Ecommerce/Website') all_pricelist_ids = fields.One2many('product.pricelist', 'website_id', string='All pricelists', help='Technical: Used to recompute pricelist_ids') def _default_recovery_mail_template(self): try: return self.env.ref('website_sale.mail_template_sale_cart_recovery').id except ValueError: return False cart_recovery_mail_template_id = fields.Many2one('mail.template', string='Cart Recovery Email', default=_default_recovery_mail_template, domain="[('model', '=', 'sale.order')]") cart_abandoned_delay = fields.Float("Abandoned Delay", default=1.0) shop_ppg = fields.Integer(default=20, string="Number of products in the grid on the shop") shop_ppr = fields.Integer(default=4, string="Number of grid columns on the shop") shop_extra_field_ids = fields.One2many('website.sale.extra.field', 'website_id', string='E-Commerce Extra Fields') cart_add_on_page = fields.Boolean("Stay on page after adding to cart", default=True) @api.depends('all_pricelist_ids') def _compute_pricelist_ids(self): Pricelist = self.env['product.pricelist'] for website in self: website.pricelist_ids = Pricelist.search( Pricelist._get_website_pricelists_domain(website.id) ) def _compute_pricelist_id(self): for website in self: website.pricelist_id = website.with_context(website_id=website.id).get_current_pricelist() # This method is cached, must not return records! See also #8795 @tools.ormcache('self.env.uid', 'country_code', 'show_visible', 'website_pl', 'current_pl', 'all_pl', 'partner_pl', 'order_pl') def _get_pl_partner_order(self, country_code, show_visible, website_pl, current_pl, all_pl, partner_pl=False, order_pl=False): """ Return the list of pricelists that can be used on website for the current user. :param str country_code: code iso or False, If set, we search only price list available for this country :param bool show_visible: if True, we don't display pricelist where selectable is False (Eg: Code promo) :param int website_pl: The default pricelist used on this website :param int current_pl: The current pricelist used on the website (If not selectable but the current pricelist we had this pricelist anyway) :param list all_pl: List of all pricelist available for this website :param int partner_pl: the partner pricelist :param int order_pl: the current cart pricelist :returns: list of pricelist ids """ def _check_show_visible(pl): """ If `show_visible` is True, we will only show the pricelist if one of this condition is met: - The pricelist is `selectable`. - The pricelist is either the currently used pricelist or the current cart pricelist, we should consider it as available even if it might not be website compliant (eg: it is not selectable anymore, it is a backend pricelist, it is not active anymore..). """ return (not show_visible or pl.selectable or pl.id in (current_pl, order_pl)) # Note: 1. pricelists from all_pl are already website compliant (went through # `_get_website_pricelists_domain`) # 2. do not read `property_product_pricelist` here as `_get_pl_partner_order` # is cached and the result of this method will be impacted by that field value. # Pass it through `partner_pl` parameter instead to invalidate the cache. # If there is a GeoIP country, find a pricelist for it self.ensure_one() pricelists = self.env['product.pricelist'] if country_code: for cgroup in self.env['res.country.group'].search([('country_ids.code', '=', country_code)]): pricelists |= cgroup.pricelist_ids.filtered( lambda pl: pl._is_available_on_website(self.id) and _check_show_visible(pl) ) # no GeoIP or no pricelist for this country if not country_code or not pricelists: pricelists |= all_pl.filtered(lambda pl: _check_show_visible(pl)) # if logged in, add partner pl (which is `property_product_pricelist`, might not be website compliant) is_public = self.user_id.id == self.env.user.id if not is_public: # keep partner_pl only if website compliant partner_pl = pricelists.browse(partner_pl).filtered(lambda pl: pl._is_available_on_website(self.id) and _check_show_visible(pl)) if country_code: # keep partner_pl only if GeoIP compliant in case of GeoIP enabled partner_pl = partner_pl.filtered( lambda pl: pl.country_group_ids and country_code in pl.country_group_ids.mapped('country_ids.code') or not pl.country_group_ids ) pricelists |= partner_pl # This method is cached, must not return records! See also #8795 return pricelists.ids def _get_pricelist_available(self, req, show_visible=False): """ Return the list of pricelists that can be used on website for the current user. Country restrictions will be detected with GeoIP (if installed). :param bool show_visible: if True, we don't display pricelist where selectable is False (Eg: Code promo) :returns: pricelist recordset """ website = ir_http.get_request_website() if not website: if self.env.context.get('website_id'): website = self.browse(self.env.context['website_id']) else: # In the weird case we are coming from the backend (https://github.com/odoo/odoo/issues/20245) website = len(self) == 1 and self or self.search([], limit=1) isocountry = req and req.session.geoip and req.session.geoip.get('country_code') or False partner = self.env.user.partner_id last_order_pl = partner.last_website_so_id.pricelist_id partner_pl = partner.property_product_pricelist pricelists = website._get_pl_partner_order(isocountry, show_visible, website.user_id.sudo().partner_id.property_product_pricelist.id, req and req.session.get('website_sale_current_pl') or None, website.pricelist_ids, partner_pl=partner_pl and partner_pl.id or None, order_pl=last_order_pl and last_order_pl.id or None) return self.env['product.pricelist'].browse(pricelists) def get_pricelist_available(self, show_visible=False): return self._get_pricelist_available(request, show_visible) def is_pricelist_available(self, pl_id): """ Return a boolean to specify if a specific pricelist can be manually set on the website. Warning: It check only if pricelist is in the 'selectable' pricelists or the current pricelist. :param int pl_id: The pricelist id to check :returns: Boolean, True if valid / available """ return pl_id in self.get_pricelist_available(show_visible=False).ids def get_current_pricelist(self): """ :returns: The current pricelist record """ # The list of available pricelists for this user. # If the user is signed in, and has a pricelist set different than the public user pricelist # then this pricelist will always be considered as available available_pricelists = self.get_pricelist_available() pl = None partner = self.env.user.partner_id if request and request.session.get('website_sale_current_pl'): # `website_sale_current_pl` is set only if the user specifically chose it: # - Either, he chose it from the pricelist selection # - Either, he entered a coupon code pl = self.env['product.pricelist'].browse(request.session['website_sale_current_pl']) if pl not in available_pricelists: pl = None request.session.pop('website_sale_current_pl') if not pl: # If the user has a saved cart, it take the pricelist of this last unconfirmed cart pl = partner.last_website_so_id.pricelist_id if not pl: # The pricelist of the user set on its partner form. # If the user is not signed in, it's the public user pricelist pl = partner.property_product_pricelist if available_pricelists and pl not in available_pricelists: # If there is at least one pricelist in the available pricelists # and the chosen pricelist is not within them # it then choose the first available pricelist. # This can only happen when the pricelist is the public user pricelist and this pricelist is not in the available pricelist for this localization # If the user is signed in, and has a special pricelist (different than the public user pricelist), # then this special pricelist is amongs these available pricelists, and therefore it won't fall in this case. pl = available_pricelists[0] if not pl: _logger.error('Fail to find pricelist for partner "%s" (id %s)', partner.name, partner.id) return pl def sale_product_domain(self): return [("sale_ok", "=", True)] + self.get_current_website().website_domain() @api.model def sale_get_payment_term(self, partner): pt = self.env.ref('account.account_payment_term_immediate', False).sudo() if pt: pt = (not pt.company_id.id or self.company_id.id == pt.company_id.id) and pt return ( partner.property_payment_term_id or pt or self.env['account.payment.term'].sudo().search([('company_id', '=', self.company_id.id)], limit=1) ).id def _prepare_sale_order_values(self, partner, pricelist): self.ensure_one() affiliate_id = request.session.get('affiliate_id') salesperson_id = affiliate_id if self.env['res.users'].sudo().browse(affiliate_id).exists() else request.website.salesperson_id.id addr = partner.address_get(['delivery']) if not request.website.is_public_user(): last_sale_order = self.env['sale.order'].sudo().search([('partner_id', '=', partner.id)], limit=1, order="date_order desc, id desc") if last_sale_order and last_sale_order.partner_shipping_id.active: # first = me addr['delivery'] = last_sale_order.partner_shipping_id.id default_user_id = partner.parent_id.user_id.id or partner.user_id.id values = { 'partner_id': partner.id, 'pricelist_id': pricelist.id, 'payment_term_id': self.sale_get_payment_term(partner), 'team_id': self.salesteam_id.id or partner.parent_id.team_id.id or partner.team_id.id, 'partner_invoice_id': partner.id, 'partner_shipping_id': addr['delivery'], 'user_id': salesperson_id or self.salesperson_id.id or default_user_id, 'website_id': self._context.get('website_id'), 'company_id': self.company_id.id, } return values def sale_get_order(self, force_create=False, code=None, update_pricelist=False, force_pricelist=False): """ Return the current sales order after mofications specified by params. :param bool force_create: Create sales order if not already existing :param str code: Code to force a pricelist (promo code) If empty, it's a special case to reset the pricelist with the first available else the default. :param bool update_pricelist: Force to recompute all the lines from sales order to adapt the price with the current pricelist. :param int force_pricelist: pricelist_id - if set, we change the pricelist with this one :returns: browse record for the current sales order """ self.ensure_one() partner = self.env.user.partner_id sale_order_id = request.session.get('sale_order_id') check_fpos = False if not sale_order_id and not self.env.user._is_public(): last_order = partner.last_website_so_id if last_order: available_pricelists = self.get_pricelist_available() # Do not reload the cart of this user last visit if the cart uses a pricelist no longer available. sale_order_id = last_order.pricelist_id in available_pricelists and last_order.id check_fpos = True # Test validity of the sale_order_id sale_order = self.env['sale.order'].with_company(request.website.company_id.id).sudo().browse(sale_order_id).exists() if sale_order_id else None # Ignore the current order if a payment has been initiated. We don't want to retrieve the # cart and allow the user to update it when the payment is about to confirm it. if sale_order and sale_order.get_portal_last_transaction().state in ('pending', 'authorized', 'done'): sale_order = None # Do not reload the cart of this user last visit if the Fiscal Position has changed. if check_fpos and sale_order: fpos_id = ( self.env['account.fiscal.position'].sudo() .with_company(sale_order.company_id.id) .get_fiscal_position(sale_order.partner_id.id, delivery_id=sale_order.partner_shipping_id.id) ).id if sale_order.fiscal_position_id.id != fpos_id: sale_order = None if not (sale_order or force_create or code): if request.session.get('sale_order_id'): request.session['sale_order_id'] = None return self.env['sale.order'] if self.env['product.pricelist'].browse(force_pricelist).exists(): pricelist_id = force_pricelist request.session['website_sale_current_pl'] = pricelist_id update_pricelist = True else: pricelist_id = request.session.get('website_sale_current_pl') or self.get_current_pricelist().id if not self._context.get('pricelist'): self = self.with_context(pricelist=pricelist_id) # cart creation was requested (either explicitly or to configure a promo code) if not sale_order: # TODO cache partner_id session pricelist = self.env['product.pricelist'].browse(pricelist_id).sudo() so_data = self._prepare_sale_order_values(partner, pricelist) sale_order = self.env['sale.order'].with_company(request.website.company_id.id).with_user(SUPERUSER_ID).create(so_data) # set fiscal position if request.website.partner_id.id != partner.id: sale_order.onchange_partner_shipping_id() else: # For public user, fiscal position based on geolocation country_code = request.session['geoip'].get('country_code') if country_code: country_id = request.env['res.country'].search([('code', '=', country_code)], limit=1).id sale_order.fiscal_position_id = request.env['account.fiscal.position'].sudo().with_company(request.website.company_id.id)._get_fpos_by_region(country_id) else: # if no geolocation, use the public user fp sale_order.onchange_partner_shipping_id() request.session['sale_order_id'] = sale_order.id # The order was created with SUPERUSER_ID, revert back to request user. sale_order = sale_order.with_user(self.env.user).sudo() # case when user emptied the cart if not request.session.get('sale_order_id'): request.session['sale_order_id'] = sale_order.id # check for change of pricelist with a coupon pricelist_id = pricelist_id or partner.property_product_pricelist.id # check for change of partner_id ie after signup if sale_order.partner_id.id != partner.id and request.website.partner_id.id != partner.id: flag_pricelist = False if pricelist_id != sale_order.pricelist_id.id: flag_pricelist = True fiscal_position = sale_order.fiscal_position_id.id # change the partner, and trigger the onchange sale_order.write({'partner_id': partner.id}) sale_order.with_context(not_self_saleperson=True).onchange_partner_id() sale_order.write({'partner_invoice_id': partner.id}) sale_order.onchange_partner_shipping_id() # fiscal position sale_order['payment_term_id'] = self.sale_get_payment_term(partner) # check the pricelist : update it if the pricelist is not the 'forced' one values = {} if sale_order.pricelist_id: if sale_order.pricelist_id.id != pricelist_id: values['pricelist_id'] = pricelist_id update_pricelist = True # if fiscal position, update the order lines taxes if sale_order.fiscal_position_id: sale_order._compute_tax_id() # if values, then make the SO update if values: sale_order.write(values) # check if the fiscal position has changed with the partner_id update recent_fiscal_position = sale_order.fiscal_position_id.id # when buying a free product with public user and trying to log in, SO state is not draft if (flag_pricelist or recent_fiscal_position != fiscal_position) and sale_order.state == 'draft': update_pricelist = True if code and code != sale_order.pricelist_id.code: code_pricelist = self.env['product.pricelist'].sudo().search([('code', '=', code)], limit=1) if code_pricelist: pricelist_id = code_pricelist.id update_pricelist = True elif code is not None and sale_order.pricelist_id.code and code != sale_order.pricelist_id.code: # code is not None when user removes code and click on "Apply" pricelist_id = partner.property_product_pricelist.id update_pricelist = True # update the pricelist if update_pricelist: request.session['website_sale_current_pl'] = pricelist_id values = {'pricelist_id': pricelist_id} sale_order.write(values) for line in sale_order.order_line: if line.exists(): sale_order._cart_update(product_id=line.product_id.id, line_id=line.id, add_qty=0) return sale_order def sale_reset(self): request.session.update({ 'sale_order_id': False, 'website_sale_current_pl': False, }) @api.model def action_dashboard_redirect(self): if self.env.user.has_group('sales_team.group_sale_salesman'): return self.env["ir.actions.actions"]._for_xml_id("website.backend_dashboard") return super(Website, self).action_dashboard_redirect() def get_suggested_controllers(self): suggested_controllers = super(Website, self).get_suggested_controllers() suggested_controllers.append((_('eCommerce'), url_for('/shop'), 'website_sale')) return suggested_controllers def _search_get_details(self, search_type, order, options): result = super()._search_get_details(search_type, order, options) if search_type in ['products', 'product_categories_only', 'all']: result.append(self.env['product.public.category']._search_get_detail(self, order, options)) if search_type in ['products', 'products_only', 'all']: result.append(self.env['product.template']._search_get_detail(self, order, options)) return result class WebsiteSaleExtraField(models.Model): _name = 'website.sale.extra.field' _description = 'E-Commerce Extra Info Shown on product page' _order = 'sequence' website_id = fields.Many2one('website') sequence = fields.Integer(default=10) field_id = fields.Many2one( 'ir.model.fields', domain=[('model_id.model', '=', 'product.template'), ('ttype', 'in', ['char', 'binary'])] ) label = fields.Char(related='field_id.field_description') name = fields.Char(related='field_id.name')
53.317308
22,180
353
py
PYTHON
15.0
from odoo import fields, models class BaseUnit(models.Model): _name = "website.base.unit" _description = "Unit of Measure for price per unit on eCommerce products." _order = "name" name = fields.Char(help="Define a custom unit to display in the price per unit of measure field.", required=True, translate=True)
35.3
353
1,072
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models from odoo.addons.website.models import ir_http class ResPartner(models.Model): _inherit = 'res.partner' last_website_so_id = fields.Many2one('sale.order', compute='_compute_last_website_so_id', string='Last Online Sales Order') def _compute_last_website_so_id(self): SaleOrder = self.env['sale.order'] for partner in self: is_public = any(u._is_public() for u in partner.with_context(active_test=False).user_ids) website = ir_http.get_request_website() if website and not is_public: partner.last_website_so_id = SaleOrder.search([ ('partner_id', '=', partner.id), ('website_id', '=', website.id), ('state', '=', 'draft'), ], order='write_date desc', limit=1) else: partner.last_website_so_id = SaleOrder # Not in a website context or public User
42.88
1,072
949
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' @api.model def _get_compatible_acquirers(self, *args, website_id=None, **kwargs): """ Override of payment to only return acquirers matching website-specific criteria. In addition to the base criteria, the website must either not be set or be the same as the one provided in the kwargs. :param int website_id: The provided website, as a `website` id :return: The compatible acquirers :rtype: recordset of `payment.acquirer` """ acquirers = super()._get_compatible_acquirers(*args, website_id=website_id, **kwargs) if website_id: acquirers = acquirers.filtered( lambda a: not a.website_id or a.website_id.id == website_id ) return acquirers
36.5
949
2,385
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, timedelta from odoo import fields, models, api class WebsiteTrack(models.Model): _inherit = 'website.track' product_id = fields.Many2one('product.product', index=True, ondelete='cascade', readonly=True) class WebsiteVisitor(models.Model): _inherit = 'website.visitor' visitor_product_count = fields.Integer('Product Views', compute="_compute_product_statistics", help="Total number of views on products") product_ids = fields.Many2many('product.product', string="Visited Products", compute="_compute_product_statistics") product_count = fields.Integer('Products Views', compute="_compute_product_statistics", help="Total number of product viewed") @api.depends('website_track_ids') def _compute_product_statistics(self): results = self.env['website.track'].read_group( [('visitor_id', 'in', self.ids), ('product_id', '!=', False), '|', ('product_id.company_id', 'in', self.env.companies.ids), ('product_id.company_id', '=', False)], ['visitor_id', 'product_id'], ['visitor_id', 'product_id'], lazy=False) mapped_data = {} for result in results: visitor_info = mapped_data.get(result['visitor_id'][0], {'product_count': 0, 'product_ids': set()}) visitor_info['product_count'] += result['__count'] visitor_info['product_ids'].add(result['product_id'][0]) mapped_data[result['visitor_id'][0]] = visitor_info for visitor in self: visitor_info = mapped_data.get(visitor.id, {'product_ids': [], 'product_count': 0}) visitor.product_ids = [(6, 0, visitor_info['product_ids'])] visitor.visitor_product_count = visitor_info['product_count'] visitor.product_count = len(visitor_info['product_ids']) def _add_viewed_product(self, product_id): """ add a website_track with a page marked as viewed""" self.ensure_one() if product_id and self.env['product.product'].browse(product_id)._is_variant_possible(): domain = [('product_id', '=', product_id)] website_track_values = {'product_id': product_id, 'visit_datetime': datetime.now()} self._add_tracking(domain, website_track_values)
49.6875
2,385
563
py
PYTHON
15.0
# coding: utf-8 # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class SaleReport(models.Model): _inherit = 'sale.report' website_id = fields.Many2one('website', readonly=True) def _group_by_sale(self, groupby=''): res = super()._group_by_sale(groupby) res += """,s.website_id""" return res def _select_additional_fields(self, fields): fields['website_id'] = ", s.website_id as website_id" return super()._select_additional_fields(fields)
31.277778
563
8,585
py
PYTHON
15.0
# -*- coding: utf-8 -*- import babel.dates from datetime import datetime, timedelta, time from odoo import fields, http, _ from odoo.addons.website.controllers.backend import WebsiteBackend from odoo.http import request from odoo.tools.misc import get_lang class WebsiteSaleBackend(WebsiteBackend): @http.route() def fetch_dashboard_data(self, website_id, date_from, date_to): Website = request.env['website'] current_website = website_id and Website.browse(website_id) or Website.get_current_website() results = super(WebsiteSaleBackend, self).fetch_dashboard_data(website_id, date_from, date_to) date_date_from = fields.Date.from_string(date_from) date_date_to = fields.Date.from_string(date_to) date_diff_days = (date_date_to - date_date_from).days datetime_from = datetime.combine(date_date_from, time.min) datetime_to = datetime.combine(date_date_to, time.max) sales_values = dict( graph=[], best_sellers=[], summary=dict( order_count=0, order_carts_count=0, order_unpaid_count=0, order_to_invoice_count=0, order_carts_abandoned_count=0, payment_to_capture_count=0, total_sold=0, order_per_day_ratio=0, order_sold_ratio=0, order_convertion_pctg=0, ) ) results['dashboards']['sales'] = sales_values results['groups']['sale_salesman'] = request.env['res.users'].has_group('sales_team.group_sale_salesman') if not results['groups']['sale_salesman']: return results results['dashboards']['sales']['utm_graph'] = self.fetch_utm_data(datetime_from, datetime_to) # Product-based computation sale_report_domain = [ ('website_id', '=', current_website.id), ('state', 'in', ['sale', 'done']), ('date', '>=', datetime_from), ('date', '<=', fields.Datetime.now()) ] report_product_lines = request.env['sale.report'].read_group( domain=sale_report_domain, fields=['product_tmpl_id', 'product_uom_qty', 'price_subtotal'], groupby='product_tmpl_id', orderby='product_uom_qty desc', limit=5) for product_line in report_product_lines: product_tmpl_id = request.env['product.template'].browse(product_line['product_tmpl_id'][0]) sales_values['best_sellers'].append({ 'id': product_tmpl_id.id, 'name': product_tmpl_id.name, 'qty': product_line['product_uom_qty'], 'sales': product_line['price_subtotal'], }) # Sale-based results computation sale_order_domain = [ ('website_id', '=', current_website.id), ('date_order', '>=', fields.Datetime.to_string(datetime_from)), ('date_order', '<=', fields.Datetime.to_string(datetime_to))] so_group_data = request.env['sale.order'].read_group(sale_order_domain, fields=['state'], groupby='state') for res in so_group_data: if res.get('state') == 'sent': sales_values['summary']['order_unpaid_count'] += res['state_count'] elif res.get('state') in ['sale', 'done']: sales_values['summary']['order_count'] += res['state_count'] sales_values['summary']['order_carts_count'] += res['state_count'] report_price_lines = request.env['sale.report'].read_group( domain=[ ('website_id', '=', current_website.id), ('state', 'in', ['sale', 'done']), ('date', '>=', datetime_from), ('date', '<=', datetime_to)], fields=['team_id', 'price_subtotal'], groupby=['team_id'], ) sales_values['summary'].update( order_to_invoice_count=request.env['sale.order'].search_count(sale_order_domain + [ ('state', 'in', ['sale', 'done']), ('order_line', '!=', False), ('partner_id', '!=', request.env.ref('base.public_partner').id), ('invoice_status', '=', 'to invoice'), ]), order_carts_abandoned_count=request.env['sale.order'].search_count(sale_order_domain + [ ('is_abandoned_cart', '=', True), ('cart_recovery_email_sent', '=', False) ]), payment_to_capture_count=request.env['payment.transaction'].search_count([ ('state', '=', 'authorized'), # that part perform a search on sale.order in order to comply with access rights as tx do not have any ('sale_order_ids', 'in', request.env['sale.order'].search(sale_order_domain + [('state', '!=', 'cancel')]).ids), ]), total_sold=sum(price_line['price_subtotal'] for price_line in report_price_lines) ) # Ratio computation sales_values['summary']['order_per_day_ratio'] = round(float(sales_values['summary']['order_count']) / date_diff_days, 2) sales_values['summary']['order_sold_ratio'] = round(float(sales_values['summary']['total_sold']) / sales_values['summary']['order_count'], 2) if sales_values['summary']['order_count'] else 0 sales_values['summary']['order_convertion_pctg'] = 100.0 * sales_values['summary']['order_count'] / sales_values['summary']['order_carts_count'] if sales_values['summary']['order_carts_count'] else 0 # Graphes computation if date_diff_days == 7: previous_sale_label = _('Previous Week') elif date_diff_days > 7 and date_diff_days <= 31: previous_sale_label = _('Previous Month') else: previous_sale_label = _('Previous Year') sales_values['graph'] += [{ 'values': self._compute_sale_graph(date_date_from, date_date_to, sale_report_domain), 'key': 'Untaxed Total', }, { 'values': self._compute_sale_graph(date_date_from - timedelta(days=date_diff_days), date_date_from, sale_report_domain, previous=True), 'key': previous_sale_label, }] return results def fetch_utm_data(self, date_from, date_to): sale_utm_domain = [ ('website_id', '!=', False), ('state', 'in', ['sale', 'done']), ('date_order', '>=', date_from), ('date_order', '<=', date_to) ] orders_data_groupby_campaign_id = request.env['sale.order'].read_group( domain=sale_utm_domain + [('campaign_id', '!=', False)], fields=['amount_total', 'id', 'campaign_id'], groupby='campaign_id') orders_data_groupby_medium_id = request.env['sale.order'].read_group( domain=sale_utm_domain + [('medium_id', '!=', False)], fields=['amount_total', 'id', 'medium_id'], groupby='medium_id') orders_data_groupby_source_id = request.env['sale.order'].read_group( domain=sale_utm_domain + [('source_id', '!=', False)], fields=['amount_total', 'id', 'source_id'], groupby='source_id') return { 'campaign_id': self.compute_utm_graph_data('campaign_id', orders_data_groupby_campaign_id), 'medium_id': self.compute_utm_graph_data('medium_id', orders_data_groupby_medium_id), 'source_id': self.compute_utm_graph_data('source_id', orders_data_groupby_source_id), } def compute_utm_graph_data(self, utm_type, utm_graph_data): return [{ 'utm_type': data[utm_type][1], 'amount_total': data['amount_total'] } for data in utm_graph_data] def _compute_sale_graph(self, date_from, date_to, sales_domain, previous=False): days_between = (date_to - date_from).days date_list = [(date_from + timedelta(days=x)) for x in range(0, days_between + 1)] daily_sales = request.env['sale.report'].read_group( domain=sales_domain, fields=['date', 'price_subtotal'], groupby='date:day') daily_sales_dict = {p['date:day']: p['price_subtotal'] for p in daily_sales} sales_graph = [{ '0': fields.Date.to_string(d) if not previous else fields.Date.to_string(d + timedelta(days=days_between)), # Respect read_group format in models.py '1': daily_sales_dict.get(babel.dates.format_date(d, format='dd MMM yyyy', locale=get_lang(request.env).code), 0) } for d in date_list] return sales_graph
46.912568
8,585
60,662
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import logging from werkzeug.exceptions import Forbidden, NotFound from werkzeug.urls import url_decode, url_encode, url_parse from odoo import fields, http, SUPERUSER_ID, tools, _ from odoo.fields import Command from odoo.http import request from odoo.addons.base.models.ir_qweb_fields import nl2br from odoo.addons.http_routing.models.ir_http import slug from odoo.addons.payment.controllers import portal as payment_portal from odoo.addons.payment.controllers.post_processing import PaymentPostProcessing from odoo.addons.website.controllers.main import QueryURL from odoo.addons.website.models.ir_http import sitemap_qs2dom from odoo.exceptions import AccessError, MissingError, ValidationError from odoo.addons.portal.controllers.portal import _build_url_w_params from odoo.addons.website.controllers import main from odoo.addons.website.controllers.form import WebsiteForm from odoo.osv import expression from odoo.tools.json import scriptsafe as json_scriptsafe _logger = logging.getLogger(__name__) class TableCompute(object): def __init__(self): self.table = {} def _check_place(self, posx, posy, sizex, sizey, ppr): res = True for y in range(sizey): for x in range(sizex): if posx + x >= ppr: res = False break row = self.table.setdefault(posy + y, {}) if row.setdefault(posx + x) is not None: res = False break for x in range(ppr): self.table[posy + y].setdefault(x, None) return res def process(self, products, ppg=20, ppr=4): # Compute products positions on the grid minpos = 0 index = 0 maxy = 0 x = 0 for p in products: x = min(max(p.website_size_x, 1), ppr) y = min(max(p.website_size_y, 1), ppr) if index >= ppg: x = y = 1 pos = minpos while not self._check_place(pos % ppr, pos // ppr, x, y, ppr): pos += 1 # if 21st products (index 20) and the last line is full (ppr products in it), break # (pos + 1.0) / ppr is the line where the product would be inserted # maxy is the number of existing lines # + 1.0 is because pos begins at 0, thus pos 20 is actually the 21st block # and to force python to not round the division operation if index >= ppg and ((pos + 1.0) // ppr) > maxy: break if x == 1 and y == 1: # simple heuristic for CPU optimization minpos = pos // ppr for y2 in range(y): for x2 in range(x): self.table[(pos // ppr) + y2][(pos % ppr) + x2] = False self.table[pos // ppr][pos % ppr] = { 'product': p, 'x': x, 'y': y, 'ribbon': p._get_website_ribbon(), } if index <= ppg: maxy = max(maxy, y + (pos // ppr)) index += 1 # Format table according to HTML needs rows = sorted(self.table.items()) rows = [r[1] for r in rows] for col in range(len(rows)): cols = sorted(rows[col].items()) x += len(cols) rows[col] = [r[1] for r in cols if r[1]] return rows class WebsiteSaleForm(WebsiteForm): @http.route('/website/form/shop.sale.order', type='http', auth="public", methods=['POST'], website=True) def website_form_saleorder(self, **kwargs): model_record = request.env.ref('sale.model_sale_order') try: data = self.extract_data(model_record, kwargs) except ValidationError as e: return json.dumps({'error_fields': e.args[0]}) order = request.website.sale_get_order() if data['record']: order.write(data['record']) if data['custom']: values = { 'body': nl2br(data['custom']), 'model': 'sale.order', 'message_type': 'comment', 'res_id': order.id, } request.env['mail.message'].with_user(SUPERUSER_ID).create(values) if data['attachments']: self.insert_attachment(model_record, order.id, data['attachments']) return json.dumps({'id': order.id}) class Website(main.Website): @http.route() def autocomplete(self, search_type=None, term=None, order=None, limit=5, max_nb_chars=999, options=None): options = options or {} if 'display_currency' not in options: options['display_currency'] = request.website.get_current_pricelist().currency_id return super().autocomplete(search_type, term, order, limit, max_nb_chars, options) @http.route() def get_switchable_related_views(self, key): views = super(Website, self).get_switchable_related_views(key) if key == 'website_sale.product': if not request.env.user.has_group('product.group_product_variant'): view_product_variants = request.website.viewref('website_sale.product_variants') views = [v for v in views if v['id'] != view_product_variants.id] return views @http.route() def toggle_switchable_view(self, view_key): super(Website, self).toggle_switchable_view(view_key) if view_key in ('website_sale.products_list_view', 'website_sale.add_grid_or_list_option'): request.session.pop('website_sale_shop_layout_mode', None) @http.route() def get_current_currency(self, **kwargs): return { 'id': request.website.currency_id.id, 'symbol': request.website.currency_id.symbol, 'position': request.website.currency_id.position, } class WebsiteSale(http.Controller): def _get_pricelist_context(self): pricelist_context = dict(request.env.context) pricelist = False if not pricelist_context.get('pricelist'): pricelist = request.website.get_current_pricelist() pricelist_context['pricelist'] = pricelist.id else: pricelist = request.env['product.pricelist'].browse(pricelist_context['pricelist']) return pricelist_context, pricelist def _get_search_order(self, post): # OrderBy will be parsed in orm and so no direct sql injection # id is added to be sure that order is a unique sort key order = post.get('order') or 'website_sequence ASC' return 'is_published desc, %s, id desc' % order def _get_search_domain(self, search, category, attrib_values, search_in_description=True): domains = [request.website.sale_product_domain()] if search: for srch in search.split(" "): subdomains = [ [('name', 'ilike', srch)], [('product_variant_ids.default_code', 'ilike', srch)] ] if search_in_description: subdomains.append([('description', 'ilike', srch)]) subdomains.append([('description_sale', 'ilike', srch)]) domains.append(expression.OR(subdomains)) if category: domains.append([('public_categ_ids', 'child_of', int(category))]) if attrib_values: attrib = None ids = [] for value in attrib_values: if not attrib: attrib = value[0] ids.append(value[1]) elif value[0] == attrib: ids.append(value[1]) else: domains.append([('attribute_line_ids.value_ids', 'in', ids)]) attrib = value[0] ids = [value[1]] if attrib: domains.append([('attribute_line_ids.value_ids', 'in', ids)]) return expression.AND(domains) def sitemap_shop(env, rule, qs): if not qs or qs.lower() in '/shop': yield {'loc': '/shop'} Category = env['product.public.category'] dom = sitemap_qs2dom(qs, '/shop/category', Category._rec_name) dom += env['website'].get_current_website().website_domain() for cat in Category.search(dom): loc = '/shop/category/%s' % slug(cat) if not qs or qs.lower() in loc: yield {'loc': loc} def _get_search_options( self, category=None, attrib_values=None, pricelist=None, min_price=0.0, max_price=0.0, conversion_rate=1, **post ): return { 'displayDescription': True, 'displayDetail': True, 'displayExtraDetail': True, 'displayExtraLink': True, 'displayImage': True, 'allowFuzzy': not post.get('noFuzzy'), 'category': str(category.id) if category else None, 'min_price': min_price / conversion_rate, 'max_price': max_price / conversion_rate, 'attrib_values': attrib_values, 'display_currency': pricelist.currency_id, } def _get_additional_shop_values(self, values): """ Hook to update values used for rendering website_sale.products template """ return {} @http.route([ '''/shop''', '''/shop/page/<int:page>''', '''/shop/category/<model("product.public.category"):category>''', '''/shop/category/<model("product.public.category"):category>/page/<int:page>''' ], type='http', auth="public", website=True, sitemap=sitemap_shop) def shop(self, page=0, category=None, search='', min_price=0.0, max_price=0.0, ppg=False, **post): add_qty = int(post.get('add_qty', 1)) try: min_price = float(min_price) except ValueError: min_price = 0 try: max_price = float(max_price) except ValueError: max_price = 0 Category = request.env['product.public.category'] if category: category = Category.search([('id', '=', int(category))], limit=1) if not category or not category.can_access_from_current_website(): raise NotFound() else: category = Category if ppg: try: ppg = int(ppg) post['ppg'] = ppg except ValueError: ppg = False if not ppg: ppg = request.env['website'].get_current_website().shop_ppg or 20 ppr = request.env['website'].get_current_website().shop_ppr or 4 attrib_list = request.httprequest.args.getlist('attrib') attrib_values = [[int(x) for x in v.split("-")] for v in attrib_list if v] attributes_ids = {v[0] for v in attrib_values} attrib_set = {v[1] for v in attrib_values} keep = QueryURL('/shop', category=category and int(category), search=search, attrib=attrib_list, min_price=min_price, max_price=max_price, order=post.get('order')) pricelist_context, pricelist = self._get_pricelist_context() request.context = dict(request.context, pricelist=pricelist.id, partner=request.env.user.partner_id) filter_by_price_enabled = request.website.is_view_active('website_sale.filter_products_price') if filter_by_price_enabled: company_currency = request.website.company_id.currency_id conversion_rate = request.env['res.currency']._get_conversion_rate(company_currency, pricelist.currency_id, request.website.company_id, fields.Date.today()) else: conversion_rate = 1 url = "/shop" if search: post["search"] = search if attrib_list: post['attrib'] = attrib_list options = self._get_search_options( category=category, attrib_values=attrib_values, pricelist=pricelist, min_price=min_price, max_price=max_price, conversion_rate=conversion_rate, **post ) # No limit because attributes are obtained from complete product list product_count, details, fuzzy_search_term = request.website._search_with_fuzzy("products_only", search, limit=None, order=self._get_search_order(post), options=options) search_product = details[0].get('results', request.env['product.template']).with_context(bin_size=True) filter_by_price_enabled = request.website.is_view_active('website_sale.filter_products_price') if filter_by_price_enabled: # TODO Find an alternative way to obtain the domain through the search metadata. Product = request.env['product.template'].with_context(bin_size=True) domain = self._get_search_domain(search, category, attrib_values) # This is ~4 times more efficient than a search for the cheapest and most expensive products from_clause, where_clause, where_params = Product._where_calc(domain).get_sql() query = f""" SELECT COALESCE(MIN(list_price), 0) * {conversion_rate}, COALESCE(MAX(list_price), 0) * {conversion_rate} FROM {from_clause} WHERE {where_clause} """ request.env.cr.execute(query, where_params) available_min_price, available_max_price = request.env.cr.fetchone() if min_price or max_price: # The if/else condition in the min_price / max_price value assignment # tackles the case where we switch to a list of products with different # available min / max prices than the ones set in the previous page. # In order to have logical results and not yield empty product lists, the # price filter is set to their respective available prices when the specified # min exceeds the max, and / or the specified max is lower than the available min. if min_price: min_price = min_price if min_price <= available_max_price else available_min_price post['min_price'] = min_price if max_price: max_price = max_price if max_price >= available_min_price else available_max_price post['max_price'] = max_price website_domain = request.website.website_domain() categs_domain = [('parent_id', '=', False)] + website_domain if search: search_categories = Category.search([('product_tmpl_ids', 'in', search_product.ids)] + website_domain).parents_and_self categs_domain.append(('id', 'in', search_categories.ids)) else: search_categories = Category categs = Category.search(categs_domain) if category: url = "/shop/category/%s" % slug(category) pager = request.website.pager(url=url, total=product_count, page=page, step=ppg, scope=7, url_args=post) offset = pager['offset'] products = search_product[offset:offset + ppg] ProductAttribute = request.env['product.attribute'] if products: # get all products without limit attributes = ProductAttribute.search([ ('product_tmpl_ids', 'in', search_product.ids), ('visibility', '=', 'visible'), ]) else: attributes = ProductAttribute.browse(attributes_ids) layout_mode = request.session.get('website_sale_shop_layout_mode') if not layout_mode: if request.website.viewref('website_sale.products_list_view').active: layout_mode = 'list' else: layout_mode = 'grid' values = { 'search': fuzzy_search_term or search, 'original_search': fuzzy_search_term and search, 'order': post.get('order', ''), 'category': category, 'attrib_values': attrib_values, 'attrib_set': attrib_set, 'pager': pager, 'pricelist': pricelist, 'add_qty': add_qty, 'products': products, 'search_product': search_product, 'search_count': product_count, # common for all searchbox 'bins': TableCompute().process(products, ppg, ppr), 'ppg': ppg, 'ppr': ppr, 'categories': categs, 'attributes': attributes, 'keep': keep, 'search_categories_ids': search_categories.ids, 'layout_mode': layout_mode, } if filter_by_price_enabled: values['min_price'] = min_price or available_min_price values['max_price'] = max_price or available_max_price values['available_min_price'] = tools.float_round(available_min_price, 2) values['available_max_price'] = tools.float_round(available_max_price, 2) if category: values['main_object'] = category values.update(self._get_additional_shop_values(values)) return request.render("website_sale.products", values) @http.route(['/shop/<model("product.template"):product>'], type='http', auth="public", website=True, sitemap=True) def product(self, product, category='', search='', **kwargs): return request.render("website_sale.product", self._prepare_product_values(product, category, search, **kwargs)) @http.route(['/shop/product/<model("product.template"):product>'], type='http', auth="public", website=True, sitemap=False) def old_product(self, product, category='', search='', **kwargs): # Compatibility pre-v14 return request.redirect(_build_url_w_params("/shop/%s" % slug(product), request.params), code=301) def _prepare_product_values(self, product, category, search, **kwargs): add_qty = int(kwargs.get('add_qty', 1)) product_context = dict(request.env.context, quantity=add_qty, active_id=product.id, partner=request.env.user.partner_id) ProductCategory = request.env['product.public.category'] if category: category = ProductCategory.browse(int(category)).exists() attrib_list = request.httprequest.args.getlist('attrib') min_price = request.params.get('min_price') max_price = request.params.get('max_price') attrib_values = [[int(x) for x in v.split("-")] for v in attrib_list if v] attrib_set = {v[1] for v in attrib_values} keep = QueryURL('/shop', category=category and category.id, search=search, attrib=attrib_list, min_price=min_price, max_price=max_price) categs = ProductCategory.search([('parent_id', '=', False)]) pricelist = request.website.get_current_pricelist() if not product_context.get('pricelist'): product_context['pricelist'] = pricelist.id product = product.with_context(product_context) # Needed to trigger the recently viewed product rpc view_track = request.website.viewref("website_sale.product").track return { 'search': search, 'category': category, 'pricelist': pricelist, 'attrib_values': attrib_values, 'attrib_set': attrib_set, 'keep': keep, 'categories': categs, 'main_object': product, 'product': product, 'add_qty': add_qty, 'view_track': view_track, } @http.route(['/shop/change_pricelist/<model("product.pricelist"):pl_id>'], type='http', auth="public", website=True, sitemap=False) def pricelist_change(self, pl_id, **post): redirect_url = request.httprequest.referrer if (pl_id.selectable or pl_id == request.env.user.partner_id.property_product_pricelist) \ and request.website.is_pricelist_available(pl_id.id): if redirect_url and request.website.is_view_active('website_sale.filter_products_price'): decoded_url = url_parse(redirect_url) args = url_decode(decoded_url.query) min_price = args.get('min_price') max_price = args.get('max_price') if min_price or max_price: previous_price_list = request.website.get_current_pricelist() try: min_price = float(min_price) args['min_price'] = min_price and str( previous_price_list.currency_id._convert(min_price, pl_id.currency_id, request.website.company_id, fields.Date.today(), round=False) ) except (ValueError, TypeError): pass try: max_price = float(max_price) args['max_price'] = max_price and str( previous_price_list.currency_id._convert(max_price, pl_id.currency_id, request.website.company_id, fields.Date.today(), round=False) ) except (ValueError, TypeError): pass redirect_url = decoded_url.replace(query=url_encode(args)).to_url() request.session['website_sale_current_pl'] = pl_id.id request.website.sale_get_order(force_pricelist=pl_id.id) return request.redirect(redirect_url or '/shop') @http.route(['/shop/pricelist'], type='http', auth="public", website=True, sitemap=False) def pricelist(self, promo, **post): redirect = post.get('r', '/shop/cart') # empty promo code is used to reset/remove pricelist (see `sale_get_order()`) if promo: pricelist = request.env['product.pricelist'].sudo().search([('code', '=', promo)], limit=1) if (not pricelist or (pricelist and not request.website.is_pricelist_available(pricelist.id))): return request.redirect("%s?code_not_available=1" % redirect) request.website.sale_get_order(code=promo) return request.redirect(redirect) @http.route(['/shop/cart'], type='http', auth="public", website=True, sitemap=False) def cart(self, access_token=None, revive='', **post): """ Main cart management + abandoned cart revival access_token: Abandoned cart SO access token revive: Revival method when abandoned cart. Can be 'merge' or 'squash' """ order = request.website.sale_get_order() if order and order.state != 'draft': request.session['sale_order_id'] = None order = request.website.sale_get_order() values = {} if access_token: abandoned_order = request.env['sale.order'].sudo().search([('access_token', '=', access_token)], limit=1) if not abandoned_order: # wrong token (or SO has been deleted) raise NotFound() if abandoned_order.state != 'draft': # abandoned cart already finished values.update({'abandoned_proceed': True}) elif revive == 'squash' or (revive == 'merge' and not request.session.get('sale_order_id')): # restore old cart or merge with unexistant request.session['sale_order_id'] = abandoned_order.id return request.redirect('/shop/cart') elif revive == 'merge': abandoned_order.order_line.write({'order_id': request.session['sale_order_id']}) abandoned_order.action_cancel() elif abandoned_order.id != request.session.get('sale_order_id'): # abandoned cart found, user have to choose what to do values.update({'access_token': abandoned_order.access_token}) values.update({ 'website_sale_order': order, 'date': fields.Date.today(), 'suggested_products': [], }) if order: order.order_line.filtered(lambda l: not l.product_id.active).unlink() _order = order if not request.env.context.get('pricelist'): _order = order.with_context(pricelist=order.pricelist_id.id) values['suggested_products'] = _order._cart_accessories() if post.get('type') == 'popover': # force no-cache so IE11 doesn't cache this XHR return request.render("website_sale.cart_popover", values, headers={'Cache-Control': 'no-cache'}) return request.render("website_sale.cart", values) @http.route(['/shop/cart/update'], type='http', auth="public", methods=['POST'], website=True) def cart_update(self, product_id, add_qty=1, set_qty=0, **kw): """This route is called when adding a product to cart (no options).""" sale_order = request.website.sale_get_order(force_create=True) if sale_order.state != 'draft': request.session['sale_order_id'] = None sale_order = request.website.sale_get_order(force_create=True) product_custom_attribute_values = None if kw.get('product_custom_attribute_values'): product_custom_attribute_values = json_scriptsafe.loads(kw.get('product_custom_attribute_values')) no_variant_attribute_values = None if kw.get('no_variant_attribute_values'): no_variant_attribute_values = json_scriptsafe.loads(kw.get('no_variant_attribute_values')) sale_order._cart_update( product_id=int(product_id), add_qty=add_qty, set_qty=set_qty, product_custom_attribute_values=product_custom_attribute_values, no_variant_attribute_values=no_variant_attribute_values ) if kw.get('express'): return request.redirect("/shop/checkout?express=1") return request.redirect("/shop/cart") @http.route(['/shop/cart/update_json'], type='json', auth="public", methods=['POST'], website=True, csrf=False) def cart_update_json(self, product_id, line_id=None, add_qty=None, set_qty=None, display=True, **kw): """ This route is called : - When changing quantity from the cart. - When adding a product from the wishlist. - When adding a product to cart on the same page (without redirection). """ order = request.website.sale_get_order(force_create=1) if order.state != 'draft': request.website.sale_reset() if kw.get('force_create'): order = request.website.sale_get_order(force_create=1) else: return {} pcav = kw.get('product_custom_attribute_values') nvav = kw.get('no_variant_attribute_values') value = order._cart_update( product_id=product_id, line_id=line_id, add_qty=add_qty, set_qty=set_qty, product_custom_attribute_values=json_scriptsafe.loads(pcav) if pcav else None, no_variant_attribute_values=json_scriptsafe.loads(nvav) if nvav else None ) if not order.cart_quantity: request.website.sale_reset() return value order = request.website.sale_get_order() value['cart_quantity'] = order.cart_quantity if not display: return value value['website_sale.cart_lines'] = request.env['ir.ui.view']._render_template("website_sale.cart_lines", { 'website_sale_order': order, 'date': fields.Date.today(), 'suggested_products': order._cart_accessories() }) value['website_sale.short_cart_summary'] = request.env['ir.ui.view']._render_template("website_sale.short_cart_summary", { 'website_sale_order': order, }) return value @http.route('/shop/save_shop_layout_mode', type='json', auth='public', website=True) def save_shop_layout_mode(self, layout_mode): assert layout_mode in ('grid', 'list'), "Invalid shop layout mode" request.session['website_sale_shop_layout_mode'] = layout_mode # ------------------------------------------------------ # Checkout # ------------------------------------------------------ def checkout_check_address(self, order): billing_fields_required = self._get_mandatory_fields_billing(order.partner_id.country_id.id) if not all(order.partner_id.read(billing_fields_required)[0].values()): return request.redirect('/shop/address?partner_id=%d' % order.partner_id.id) shipping_fields_required = self._get_mandatory_fields_shipping(order.partner_shipping_id.country_id.id) if not all(order.partner_shipping_id.read(shipping_fields_required)[0].values()): return request.redirect('/shop/address?partner_id=%d' % order.partner_shipping_id.id) def checkout_redirection(self, order): # must have a draft sales order with lines at this point, otherwise reset if not order or order.state != 'draft': request.session['sale_order_id'] = None request.session['sale_transaction_id'] = None return request.redirect('/shop') if order and not order.order_line: return request.redirect('/shop/cart') # if transaction pending / done: redirect to confirmation tx = request.env.context.get('website_sale_transaction') if tx and tx.state != 'draft': return request.redirect('/shop/payment/confirmation/%s' % order.id) def checkout_values(self, **kw): order = request.website.sale_get_order(force_create=1) shippings = [] if order.partner_id != request.website.user_id.sudo().partner_id: Partner = order.partner_id.with_context(show_address=1).sudo() shippings = Partner.search([ ("id", "child_of", order.partner_id.commercial_partner_id.ids), '|', ("type", "in", ["delivery", "other"]), ("id", "=", order.partner_id.commercial_partner_id.id) ], order='id desc') if shippings: if kw.get('partner_id') or 'use_billing' in kw: if 'use_billing' in kw: partner_id = order.partner_id.id else: partner_id = int(kw.get('partner_id')) if partner_id in shippings.mapped('id'): order.partner_shipping_id = partner_id values = { 'order': order, 'shippings': shippings, 'only_services': order and order.only_services or False } return values def _get_mandatory_fields_billing(self, country_id=False): req = ["name", "email", "street", "city", "country_id"] if country_id: country = request.env['res.country'].browse(country_id) if country.state_required: req += ['state_id'] if country.zip_required: req += ['zip'] return req def _get_mandatory_fields_shipping(self, country_id=False): req = ["name", "street", "city", "country_id"] if country_id: country = request.env['res.country'].browse(country_id) if country.state_required: req += ['state_id'] if country.zip_required: req += ['zip'] return req def checkout_form_validate(self, mode, all_form_values, data): # mode: tuple ('new|edit', 'billing|shipping') # all_form_values: all values before preprocess # data: values after preprocess error = dict() error_message = [] if data.get('partner_id'): partner_su = request.env['res.partner'].sudo().browse(int(data['partner_id'])).exists() name_change = partner_su and 'name' in data and data['name'] != partner_su.name email_change = partner_su and 'email' in data and data['email'] != partner_su.email # Prevent changing the partner name if invoices have been issued. if name_change and not partner_su.can_edit_vat(): error['name'] = 'error' error_message.append(_( "Changing your name is not allowed once invoices have been issued for your" " account. Please contact us directly for this operation." )) # Prevent change the partner name or email if it is an internal user. if (name_change or email_change) and not all(partner_su.user_ids.mapped('share')): error.update({ 'name': 'error' if name_change else None, 'email': 'error' if email_change else None, }) error_message.append(_( "If you are ordering for an external person, please place your order via the" " backend. If you wish to change your name or email address, please do so in" " the account settings or contact your administrator." )) # Required fields from form required_fields = [f for f in (all_form_values.get('field_required') or '').split(',') if f] # Required fields from mandatory field function country_id = int(data.get('country_id', False)) required_fields += mode[1] == 'shipping' and self._get_mandatory_fields_shipping(country_id) or self._get_mandatory_fields_billing(country_id) # error message for empty required fields for field_name in required_fields: val = data.get(field_name) if isinstance(val, str): val = val.strip() if not val: error[field_name] = 'missing' # email validation if data.get('email') and not tools.single_email_re.match(data.get('email')): error["email"] = 'error' error_message.append(_('Invalid Email! Please enter a valid email address.')) # vat validation Partner = request.env['res.partner'] if data.get("vat") and hasattr(Partner, "check_vat"): if country_id: data["vat"] = Partner.fix_eu_vat_number(country_id, data.get("vat")) partner_dummy = Partner.new(self._get_vat_validation_fields(data)) try: partner_dummy.check_vat() except ValidationError as exception: error["vat"] = 'error' error_message.append(exception.args[0]) if [err for err in error.values() if err == 'missing']: error_message.append(_('Some required fields are empty.')) return error, error_message def _get_vat_validation_fields(self, data): return { 'vat': data['vat'], 'country_id': int(data['country_id']) if data.get('country_id') else False, } def _checkout_form_save(self, mode, checkout, all_values): Partner = request.env['res.partner'] if mode[0] == 'new': partner_id = Partner.sudo().with_context(tracking_disable=True).create(checkout).id elif mode[0] == 'edit': partner_id = int(all_values.get('partner_id', 0)) if partner_id: # double check order = request.website.sale_get_order() shippings = Partner.sudo().search([("id", "child_of", order.partner_id.commercial_partner_id.ids)]) if partner_id not in shippings.mapped('id') and partner_id != order.partner_id.id: return Forbidden() Partner.browse(partner_id).sudo().write(checkout) return partner_id def values_preprocess(self, order, mode, values): new_values = dict() partner_fields = request.env['res.partner']._fields for k, v in values.items(): # Convert the values for many2one fields to integer since they are used as IDs if k in partner_fields and partner_fields[k].type == 'many2one': new_values[k] = bool(v) and int(v) # Store empty fields as `False` instead of empty strings `''` for consistency with other applications like # Contacts. elif v == '': new_values[k] = False else: new_values[k] = v return new_values def values_postprocess(self, order, mode, values, errors, error_msg): new_values = {} authorized_fields = request.env['ir.model']._get('res.partner')._get_form_writable_fields() for k, v in values.items(): # don't drop empty value, it could be a field to reset if k in authorized_fields and v is not None: new_values[k] = v else: # DEBUG ONLY if k not in ('field_required', 'partner_id', 'callback', 'submitted'): # classic case _logger.debug("website_sale postprocess: %s value has been dropped (empty or not writable)" % k) if request.website.specific_user_account: new_values['website_id'] = request.website.id if mode[0] == 'new': new_values['company_id'] = request.website.company_id.id new_values['team_id'] = request.website.salesteam_id and request.website.salesteam_id.id new_values['user_id'] = request.website.salesperson_id.id lang = request.lang.code if request.lang.code in request.website.mapped('language_ids.code') else None if lang: new_values['lang'] = lang if mode == ('edit', 'billing') and order.partner_id.type == 'contact': new_values['type'] = 'other' if mode[1] == 'shipping': new_values['parent_id'] = order.partner_id.commercial_partner_id.id new_values['type'] = 'delivery' return new_values, errors, error_msg @http.route(['/shop/address'], type='http', methods=['GET', 'POST'], auth="public", website=True, sitemap=False) def address(self, **kw): Partner = request.env['res.partner'].with_context(show_address=1).sudo() order = request.website.sale_get_order() redirection = self.checkout_redirection(order) if redirection: return redirection mode = (False, False) can_edit_vat = False values, errors = {}, {} partner_id = int(kw.get('partner_id', -1)) # IF PUBLIC ORDER if order.partner_id.id == request.website.user_id.sudo().partner_id.id: mode = ('new', 'billing') can_edit_vat = True # IF ORDER LINKED TO A PARTNER else: if partner_id > 0: if partner_id == order.partner_id.id: mode = ('edit', 'billing') can_edit_vat = order.partner_id.can_edit_vat() else: shippings = Partner.search([('id', 'child_of', order.partner_id.commercial_partner_id.ids)]) if order.partner_id.commercial_partner_id.id == partner_id: mode = ('new', 'shipping') partner_id = -1 elif partner_id in shippings.mapped('id'): mode = ('edit', 'shipping') else: return Forbidden() if mode and partner_id != -1: values = Partner.browse(partner_id) elif partner_id == -1: mode = ('new', 'shipping') else: # no mode - refresh without post? return request.redirect('/shop/checkout') # IF POSTED if 'submitted' in kw and request.httprequest.method == "POST": pre_values = self.values_preprocess(order, mode, kw) errors, error_msg = self.checkout_form_validate(mode, kw, pre_values) post, errors, error_msg = self.values_postprocess(order, mode, pre_values, errors, error_msg) if errors: errors['error_message'] = error_msg values = kw else: partner_id = self._checkout_form_save(mode, post, kw) # We need to validate _checkout_form_save return, because when partner_id not in shippings # it returns Forbidden() instead the partner_id if isinstance(partner_id, Forbidden): return partner_id if mode[1] == 'billing': order.partner_id = partner_id order.with_context(not_self_saleperson=True).onchange_partner_id() # This is the *only* thing that the front end user will see/edit anyway when choosing billing address order.partner_invoice_id = partner_id if not kw.get('use_same'): kw['callback'] = kw.get('callback') or \ (not order.only_services and (mode[0] == 'edit' and '/shop/checkout' or '/shop/address')) # We need to update the pricelist(by the one selected by the customer), because onchange_partner reset it # We only need to update the pricelist when it is not redirected to /confirm_order if kw.get('callback', False) != '/shop/confirm_order': request.website.sale_get_order(update_pricelist=True) elif mode[1] == 'shipping': order.partner_shipping_id = partner_id # TDE FIXME: don't ever do this # -> TDE: you are the guy that did what we should never do in commit e6f038a order.message_partner_ids = [(4, partner_id), (3, request.website.partner_id.id)] if not errors: return request.redirect(kw.get('callback') or '/shop/confirm_order') render_values = { 'website_sale_order': order, 'partner_id': partner_id, 'mode': mode, 'checkout': values, 'can_edit_vat': can_edit_vat, 'error': errors, 'callback': kw.get('callback'), 'only_services': order and order.only_services, } render_values.update(self._get_country_related_render_values(kw, render_values)) return request.render("website_sale.address", render_values) def _get_country_related_render_values(self, kw, render_values): ''' This method provides fields related to the country to render the website sale form ''' values = render_values['checkout'] mode = render_values['mode'] order = render_values['website_sale_order'] def_country_id = order.partner_id.country_id # IF PUBLIC ORDER if order.partner_id.id == request.website.user_id.sudo().partner_id.id: country_code = request.session['geoip'].get('country_code') if country_code: def_country_id = request.env['res.country'].search([('code', '=', country_code)], limit=1) else: def_country_id = request.website.user_id.sudo().country_id country = 'country_id' in values and values['country_id'] != '' and request.env['res.country'].browse(int(values['country_id'])) country = country and country.exists() or def_country_id res = { 'country': country, 'country_states': country.get_website_sale_states(mode=mode[1]), 'countries': country.get_website_sale_countries(mode=mode[1]), } return res @http.route(['/shop/checkout'], type='http', auth="public", website=True, sitemap=False) def checkout(self, **post): order = request.website.sale_get_order() redirection = self.checkout_redirection(order) if redirection: return redirection if order.partner_id.id == request.website.user_id.sudo().partner_id.id: return request.redirect('/shop/address') redirection = self.checkout_check_address(order) if redirection: return redirection values = self.checkout_values(**post) if post.get('express'): return request.redirect('/shop/confirm_order') values.update({'website_sale_order': order}) # Avoid useless rendering if called in ajax if post.get('xhr'): return 'ok' return request.render("website_sale.checkout", values) @http.route(['/shop/confirm_order'], type='http', auth="public", website=True, sitemap=False) def confirm_order(self, **post): order = request.website.sale_get_order() redirection = self.checkout_redirection(order) or self.checkout_check_address(order) if redirection: return redirection order.onchange_partner_shipping_id() order.order_line._compute_tax_id() request.session['sale_last_order_id'] = order.id request.website.sale_get_order(update_pricelist=True) extra_step = request.website.viewref('website_sale.extra_info_option') if extra_step.active: return request.redirect("/shop/extra_info") return request.redirect("/shop/payment") # ------------------------------------------------------ # Extra step # ------------------------------------------------------ @http.route(['/shop/extra_info'], type='http', auth="public", website=True, sitemap=False) def extra_info(self, **post): # Check that this option is activated extra_step = request.website.viewref('website_sale.extra_info_option') if not extra_step.active: return request.redirect("/shop/payment") # check that cart is valid order = request.website.sale_get_order() redirection = self.checkout_redirection(order) if redirection: return redirection values = { 'website_sale_order': order, 'post': post, 'escape': lambda x: x.replace("'", r"\'"), 'partner': order.partner_id.id, 'order': order, } return request.render("website_sale.extra_info", values) # ------------------------------------------------------ # Payment # ------------------------------------------------------ def _get_shop_payment_values(self, order, **kwargs): logged_in = not request.env.user._is_public() acquirers_sudo = request.env['payment.acquirer'].sudo()._get_compatible_acquirers( order.company_id.id, order.partner_id.id, currency_id=order.currency_id.id, sale_order_id=order.id, website_id=request.website.id, ) # In sudo mode to read the fields of acquirers, order and partner (if not logged in) tokens = request.env['payment.token'].search( [('acquirer_id', 'in', acquirers_sudo.ids), ('partner_id', '=', order.partner_id.id)] ) if logged_in else request.env['payment.token'] fees_by_acquirer = { acq_sudo: acq_sudo._compute_fees( order.amount_total, order.currency_id, order.partner_id.country_id ) for acq_sudo in acquirers_sudo.filtered('fees_active') } # Prevent public partner from saving payment methods but force it for logged in partners # buying subscription products show_tokenize_input = logged_in \ and not request.env['payment.acquirer'].sudo()._is_tokenization_required( sale_order_id=order.id ) return { 'website_sale_order': order, 'errors': [], 'partner': order.partner_invoice_id, 'order': order, 'payment_action_id': request.env.ref('payment.action_payment_acquirer').id, # Payment form common (checkout and manage) values 'acquirers': acquirers_sudo, 'tokens': tokens, 'fees_by_acquirer': fees_by_acquirer, 'show_tokenize_input': show_tokenize_input, 'amount': order.amount_total, 'currency': order.currency_id, 'partner_id': order.partner_id.id, 'access_token': order._portal_ensure_token(), 'transaction_route': f'/shop/payment/transaction/{order.id}', 'landing_route': '/shop/payment/validate', } @http.route('/shop/payment', type='http', auth='public', website=True, sitemap=False) def shop_payment(self, **post): """ Payment step. This page proposes several payment means based on available payment.acquirer. State at this point : - a draft sales order with lines; otherwise, clean context / session and back to the shop - no transaction in context / session, or only a draft one, if the customer did go to a payment.acquirer website but closed the tab without paying / canceling """ order = request.website.sale_get_order() redirection = self.checkout_redirection(order) or self.checkout_check_address(order) if redirection: return redirection render_values = self._get_shop_payment_values(order, **post) render_values['only_services'] = order and order.only_services or False if render_values['errors']: render_values.pop('acquirers', '') render_values.pop('tokens', '') return request.render("website_sale.payment", render_values) @http.route('/shop/payment/get_status/<int:sale_order_id>', type='json', auth="public", website=True) def shop_payment_get_status(self, sale_order_id, **post): order = request.env['sale.order'].sudo().browse(sale_order_id).exists() if order.id != request.session.get('sale_last_order_id'): # either something went wrong or the session is unbound # prevent recalling every 3rd of a second in the JS widget return {} return { 'recall': order.get_portal_last_transaction().state == 'pending', 'message': request.env['ir.ui.view']._render_template("website_sale.payment_confirmation_status", { 'order': order }) } @http.route('/shop/payment/validate', type='http', auth="public", website=True, sitemap=False) def shop_payment_validate(self, transaction_id=None, sale_order_id=None, **post): """ Method that should be called by the server when receiving an update for a transaction. State at this point : - UDPATE ME """ if sale_order_id is None: order = request.website.sale_get_order() if not order and 'sale_last_order_id' in request.session: # Retrieve the last known order from the session if the session key `sale_order_id` # was prematurely cleared. This is done to prevent the user from updating their cart # after payment in case they don't return from payment through this route. last_order_id = request.session['sale_last_order_id'] order = request.env['sale.order'].sudo().browse(last_order_id).exists() else: order = request.env['sale.order'].sudo().browse(sale_order_id) assert order.id == request.session.get('sale_last_order_id') if transaction_id: tx = request.env['payment.transaction'].sudo().browse(transaction_id) assert tx in order.transaction_ids() elif order: tx = order.get_portal_last_transaction() else: tx = None if not order or (order.amount_total and not tx): return request.redirect('/shop') if order and not order.amount_total and not tx: order.with_context(send_email=True).action_confirm() return request.redirect(order.get_portal_url()) # clean context and session, then redirect to the confirmation page request.website.sale_reset() if tx and tx.state == 'draft': return request.redirect('/shop') PaymentPostProcessing.remove_transactions(tx) return request.redirect('/shop/confirmation') @http.route(['/shop/confirmation'], type='http', auth="public", website=True, sitemap=False) def shop_payment_confirmation(self, **post): """ End of checkout process controller. Confirmation is basically seing the status of a sale.order. State at this point : - should not have any context / session info: clean them - take a sale.order id, because we request a sale.order and are not session dependant anymore """ sale_order_id = request.session.get('sale_last_order_id') if sale_order_id: order = request.env['sale.order'].sudo().browse(sale_order_id) return request.render("website_sale.confirmation", { 'order': order, 'order_tracking_info': self.order_2_return_dict(order), }) else: return request.redirect('/shop') @http.route(['/shop/print'], type='http', auth="public", website=True, sitemap=False) def print_saleorder(self, **kwargs): sale_order_id = request.session.get('sale_last_order_id') if sale_order_id: pdf, _ = request.env.ref('sale.action_report_saleorder').with_user(SUPERUSER_ID)._render_qweb_pdf([sale_order_id]) pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', u'%s' % len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) else: return request.redirect('/shop') # ------------------------------------------------------ # Edit # ------------------------------------------------------ @http.route(['/shop/add_product'], type='json', auth="user", methods=['POST'], website=True) def add_product(self, name=None, category=None, **post): product = request.env['product.product'].create({ 'name': name or _("New Product"), 'public_categ_ids': category, 'website_id': request.website.id, }) return "%s?enable_editor=1" % product.product_tmpl_id.website_url @http.route(['/shop/change_sequence'], type='json', auth='user') def change_sequence(self, id, sequence): product_tmpl = request.env['product.template'].browse(id) if sequence == "top": product_tmpl.set_sequence_top() elif sequence == "bottom": product_tmpl.set_sequence_bottom() elif sequence == "up": product_tmpl.set_sequence_up() elif sequence == "down": product_tmpl.set_sequence_down() @http.route(['/shop/change_size'], type='json', auth='user') def change_size(self, id, x, y): product = request.env['product.template'].browse(id) return product.write({'website_size_x': x, 'website_size_y': y}) @http.route(['/shop/change_ppg'], type='json', auth='user') def change_ppg(self, ppg): request.env['website'].get_current_website().shop_ppg = ppg @http.route(['/shop/change_ppr'], type='json', auth='user') def change_ppr(self, ppr): request.env['website'].get_current_website().shop_ppr = ppr def order_lines_2_google_api(self, order_lines): """ Transforms a list of order lines into a dict for google analytics """ ret = [] for line in order_lines: product = line.product_id ret.append({ 'item_id': product.barcode or product.id, 'item_name': product.name or '-', 'item_category': product.categ_id.name or '-', 'price': line.price_unit, 'quantity': line.product_uom_qty, }) return ret def order_2_return_dict(self, order): """ Returns the tracking_cart dict of the order for Google analytics basically defined to be inherited """ return { 'transaction_id': order.id, 'affiliation': order.company_id.name, 'value': order.amount_total, 'tax': order.amount_tax, 'currency': order.currency_id.name, 'items': self.order_lines_2_google_api(order.order_line), } @http.route(['/shop/country_infos/<model("res.country"):country>'], type='json', auth="public", methods=['POST'], website=True) def country_infos(self, country, mode, **kw): return dict( fields=country.get_address_fields(), states=[(st.id, st.name, st.code) for st in country.get_website_sale_states(mode=mode)], phone_code=country.phone_code, zip_required=country.zip_required, state_required=country.state_required, ) # -------------------------------------------------------------------------- # Products Recently Viewed # -------------------------------------------------------------------------- @http.route('/shop/products/recently_viewed_update', type='json', auth='public', website=True) def products_recently_viewed_update(self, product_id, **kwargs): res = {} visitor_sudo = request.env['website.visitor']._get_visitor_from_request(force_create=True) if visitor_sudo: if request.httprequest.cookies.get('visitor_uuid', '') != visitor_sudo.access_token: res['visitor_uuid'] = visitor_sudo.access_token visitor_sudo._add_viewed_product(product_id) return res @http.route('/shop/products/recently_viewed_delete', type='json', auth='public', website=True) def products_recently_viewed_delete(self, product_id, **kwargs): visitor_sudo = request.env['website.visitor']._get_visitor_from_request() if visitor_sudo: request.env['website.track'].sudo().search([('visitor_id', '=', visitor_sudo.id), ('product_id', '=', product_id)]).unlink() return {} class PaymentPortal(payment_portal.PaymentPortal): @http.route( '/shop/payment/transaction/<int:order_id>', type='json', auth='public', website=True ) def shop_payment_transaction(self, order_id, access_token, **kwargs): """ Create a draft transaction and return its processing values. :param int order_id: The sales order to pay, as a `sale.order` id :param str access_token: The access token used to authenticate the request :param dict kwargs: Locally unused data passed to `_create_transaction` :return: The mandatory values for the processing of the transaction :rtype: dict :raise: ValidationError if the invoice id or the access token is invalid """ # Check the order id and the access token try: order_sudo = self._document_check_access('sale.order', order_id, access_token) except MissingError as error: raise error except AccessError: raise ValidationError(_("The access token is invalid.")) if order_sudo.state == "cancel": raise ValidationError(_("The order has been canceled.")) if tools.float_compare(kwargs['amount'], order_sudo.amount_total, precision_rounding=order_sudo.currency_id.rounding): raise ValidationError(_("The cart has been updated. Please refresh the page.")) kwargs.update({ 'reference_prefix': None, # Allow the reference to be computed based on the order 'partner_id': order_sudo.partner_invoice_id.id, 'sale_order_id': order_id, # Include the SO to allow Subscriptions to tokenize the tx }) kwargs.pop('custom_create_values', None) # Don't allow passing arbitrary create values tx_sudo = self._create_transaction( custom_create_values={'sale_order_ids': [Command.set([order_id])]}, **kwargs, ) # Store the new transaction into the transaction list and if there's an old one, we remove # it until the day the ecommerce supports multiple orders at the same time. last_tx_id = request.session.get('__website_sale_last_tx_id') last_tx = request.env['payment.transaction'].browse(last_tx_id).sudo().exists() if last_tx: PaymentPostProcessing.remove_transactions(last_tx) request.session['__website_sale_last_tx_id'] = tx_sudo.id return tx_sudo._get_processing_values()
45.71364
60,662
1,781
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request from odoo.addons.sale.controllers.variant import VariantController class WebsiteSaleVariantController(VariantController): @http.route(['/sale/get_combination_info_website'], type='json', auth="public", methods=['POST'], website=True) def get_combination_info_website(self, product_template_id, product_id, combination, add_qty, **kw): """Special route to use website logic in get_combination_info override. This route is called in JS by appending _website to the base route. """ kw.pop('pricelist_id') combination = self.get_combination_info(product_template_id, product_id, combination, add_qty, request.website.get_current_pricelist(), **kw) if request.website.google_analytics_key: combination['product_tracking_info'] = request.env['product.template'].get_google_analytics_data(combination) carousel_view = request.env['ir.ui.view']._render_template('website_sale.shop_product_carousel', values={ 'product': request.env['product.template'].browse(combination['product_template_id']), 'product_variant': request.env['product.product'].browse(combination['product_id']), }) combination['carousel'] = carousel_view return combination @http.route(auth="public") def create_product_variant(self, product_template_id, product_template_attribute_value_ids, **kwargs): """Override because on the website the public user must access it.""" return super(WebsiteSaleVariantController, self).create_product_variant(product_template_id, product_template_attribute_value_ids, **kwargs)
57.451613
1,781
613
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Units of measure', 'version': '1.0', 'category': 'Sales/Sales', 'depends': ['base'], 'description': """ This is the base module for managing Units of measure. ======================================================================== """, 'data': [ 'data/uom_data.xml', 'security/uom_security.xml', 'security/ir.model.access.csv', 'views/uom_uom_views.xml', ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
27.863636
613
4,562
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase from odoo.exceptions import ValidationError class TestUom(TransactionCase): def setUp(self): super(TestUom, self).setUp() self.uom_gram = self.env.ref('uom.product_uom_gram') self.uom_kgm = self.env.ref('uom.product_uom_kgm') self.uom_ton = self.env.ref('uom.product_uom_ton') self.uom_unit = self.env.ref('uom.product_uom_unit') self.uom_dozen = self.env.ref('uom.product_uom_dozen') self.categ_unit_id = self.ref('uom.product_uom_categ_unit') def test_10_conversion(self): qty = self.uom_gram._compute_quantity(1020000, self.uom_ton) self.assertEqual(qty, 1.02, "Converted quantity does not correspond.") price = self.uom_gram._compute_price(2, self.uom_ton) self.assertEqual(price, 2000000.0, "Converted price does not correspond.") # If the conversion factor for Dozens (1/12) is not stored with sufficient precision, # the conversion of 1 Dozen into Units will give e.g. 12.00000000000047 Units # and the Unit rounding will round that up to 13. # This is a partial regression test for rev. 311c77bb, which is further improved # by rev. fa2f7b86. qty = self.uom_dozen._compute_quantity(1, self.uom_unit) self.assertEqual(qty, 12.0, "Converted quantity does not correspond.") # Regression test for side-effect of commit 311c77bb - converting 1234 Grams # into Kilograms should work even if grams are rounded to 1. self.uom_gram.write({'rounding': 1}) qty = self.uom_gram._compute_quantity(1234, self.uom_kgm) self.assertEqual(qty, 1.24, "Converted quantity does not correspond.") def test_20_rounding(self): product_uom = self.env['uom.uom'].create({ 'name': 'Score', 'factor_inv': 20, 'uom_type': 'bigger', 'rounding': 1.0, 'category_id': self.categ_unit_id }) qty = self.uom_unit._compute_quantity(2, product_uom) self.assertEqual(qty, 1, "Converted quantity should be rounded up.") def test_30_reference_uniqueness(self): """ Check the uniqueness of the reference UoM in a category """ time_category = self.env.ref('uom.product_uom_categ_unit') with self.assertRaises(ValidationError): self.env['uom.uom'].create({ 'name': 'Second Time Reference', 'factor_inv': 1, 'uom_type': 'reference', 'rounding': 1.0, 'category_id': time_category.id }) def test_40_custom_uom(self): """ A custom UoM is an UoM in a category without measurement type. It should behave like a normal UoM """ category = self.env['uom.category'].create({ 'name': 'Custom UoM category', }) # at first we can not create a non reference in custom category with self.assertRaises(ValidationError): self.env['uom.uom'].create({ 'name': 'Bigger UoM of my category', 'factor_inv': 42, 'uom_type': 'bigger', 'rounding': 0.5, 'category_id': category.id }) # create the reference self.env['uom.uom'].create({ 'name': 'Reference UoM of my category', 'factor_inv': 1, 'uom_type': 'reference', 'rounding': 1.0, 'category_id': category.id }) # we can create another UoM now self.env['uom.uom'].create({ 'name': 'Bigger UoM of my category', 'factor_inv': 42, 'uom_type': 'bigger', 'rounding': 0.5, 'category_id': category.id }) # we can not create a second reference in custom category with self.assertRaises(ValidationError): self.env['uom.uom'].create({ 'name': 'Second Time Reference', 'factor_inv': 1, 'uom_type': 'reference', 'rounding': 1.0, 'category_id': category.id }) def test_50_check_ratio(self): with self.assertRaises(ValidationError): self.env['uom.uom'].create({ 'name': 'Custom UoM', 'uom_type': 'bigger', 'ratio': 0, 'category_id': self.categ_unit_id })
39.327586
4,562
11,755
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta from odoo import api, fields, tools, models, _ from odoo.exceptions import UserError, ValidationError class UoMCategory(models.Model): _name = 'uom.category' _description = 'Product UoM Categories' name = fields.Char('Unit of Measure Category', required=True, translate=True) uom_ids = fields.One2many('uom.uom', 'category_id') reference_uom_id = fields.Many2one('uom.uom', "Reference UoM", store=False, help="Dummy field to keep track of reference uom change") @api.onchange('uom_ids') def _onchange_uom_ids(self): if len(self.uom_ids) == 1: self.uom_ids[0].uom_type = 'reference' self.uom_ids[0].factor = 1 else: reference_count = sum(uom.uom_type == 'reference' for uom in self.uom_ids) if reference_count == 0 and self._origin.id: return { 'warning': { 'title': _('Warning!'), 'message': _("UoM category %s should have a reference unit of measure.") % self.name } } if self.reference_uom_id: new_reference = self.uom_ids.filtered(lambda o: o.uom_type == 'reference' and o._origin.id != self.reference_uom_id.id) else: new_reference = self.uom_ids.filtered(lambda o: o.uom_type == 'reference' and o._origin.uom_type != 'reference') if new_reference: other_uoms = self.uom_ids.filtered(lambda u: u._origin.id) - new_reference for uom in other_uoms: uom.factor = uom._origin.factor / (new_reference._origin.factor or 1) if uom.factor > 1: uom.uom_type = 'smaller' else: uom.uom_type = 'bigger' self.reference_uom_id = new_reference._origin.id class UoM(models.Model): _name = 'uom.uom' _description = 'Product Unit of Measure' _order = "factor DESC, id" def _unprotected_uom_xml_ids(self): return [ "product_uom_hour", # NOTE: this uom is protected when hr_timesheet is installed. "product_uom_dozen", ] name = fields.Char('Unit of Measure', required=True, translate=True) category_id = fields.Many2one( 'uom.category', 'Category', required=True, ondelete='restrict', help="Conversion between Units of Measure can only occur if they belong to the same category. The conversion will be made based on the ratios.") factor = fields.Float( 'Ratio', default=1.0, digits=0, required=True, # force NUMERIC with unlimited precision help='How much bigger or smaller this unit is compared to the reference Unit of Measure for this category: 1 * (reference unit) = ratio * (this unit)') factor_inv = fields.Float( 'Bigger Ratio', compute='_compute_factor_inv', digits=0, # force NUMERIC with unlimited precision readonly=True, required=True, help='How many times this Unit of Measure is bigger than the reference Unit of Measure in this category: 1 * (this unit) = ratio * (reference unit)') rounding = fields.Float( 'Rounding Precision', default=0.01, digits=0, required=True, help="The computed quantity will be a multiple of this value. " "Use 1.0 for a Unit of Measure that cannot be further split, such as a piece.") active = fields.Boolean('Active', default=True, help="Uncheck the active field to disable a unit of measure without deleting it.") uom_type = fields.Selection([ ('bigger', 'Bigger than the reference Unit of Measure'), ('reference', 'Reference Unit of Measure for this category'), ('smaller', 'Smaller than the reference Unit of Measure')], 'Type', default='reference', required=True) ratio = fields.Float('Combined Ratio', compute='_compute_ratio', inverse='_set_ratio', store=False) color = fields.Integer('Color', compute='_compute_color') _sql_constraints = [ ('factor_gt_zero', 'CHECK (factor!=0)', 'The conversion ratio for a unit of measure cannot be 0!'), ('rounding_gt_zero', 'CHECK (rounding>0)', 'The rounding precision must be strictly positive.'), ('factor_reference_is_one', "CHECK((uom_type = 'reference' AND factor = 1.0) OR (uom_type != 'reference'))", "The reference unit must have a conversion factor equal to 1.") ] def _check_category_reference_uniqueness(self): for category in self.category_id: if not category.uom_ids: continue reference_count = sum( uom.uom_type == 'reference' for uom in category.uom_ids) if reference_count > 1: raise ValidationError(_("UoM category %s should only have one reference unit of measure.") % category.name) elif reference_count == 0: raise ValidationError(_("UoM category %s should have a reference unit of measure.") % category.name) @api.depends('factor') def _compute_factor_inv(self): for uom in self: uom.factor_inv = uom.factor and (1.0 / uom.factor) or 0.0 @api.depends('uom_type', 'factor') def _compute_ratio(self): for uom in self: if uom.uom_type == 'reference': uom.ratio = 1 elif uom.uom_type == 'bigger': uom.ratio = uom.factor_inv else: uom.ratio = uom.factor def _set_ratio(self): if self.ratio == 0: raise ValidationError(_("The value of ratio could not be Zero")) if self.uom_type == 'reference': self.factor = 1 elif self.uom_type == 'bigger': self.factor = 1 / self.ratio else: self.factor = self.ratio @api.depends('uom_type') def _compute_color(self): for uom in self: if uom.uom_type == 'reference': uom.color = 7 else: uom.color = 0 @api.onchange('uom_type') def _onchange_uom_type(self): if self.uom_type == 'reference': self.factor = 1 @api.onchange('factor', 'factor_inv', 'uom_type', 'rounding', 'category_id') def _onchange_critical_fields(self): if self._filter_protected_uoms() and self.create_date < (fields.Datetime.now() - timedelta(days=1)): return { 'warning': { 'title': _("Warning for %s", self.name), 'message': _( "Some critical fields have been modified on %s.\n" "Note that existing data WON'T be updated by this change.\n\n" "As units of measure impact the whole system, this may cause critical issues.\n" "E.g. modifying the rounding could disturb your inventory balance.\n\n" "Therefore, changing core units of measure in a running database is not recommended.", self.name, ) } } @api.model_create_multi def create(self, vals_list): for values in vals_list: if 'factor_inv' in values: factor_inv = values.pop('factor_inv') values['factor'] = factor_inv and (1.0 / factor_inv) or 0.0 res = super(UoM, self).create(vals_list) res._check_category_reference_uniqueness() return res def write(self, values): if 'factor_inv' in values: factor_inv = values.pop('factor_inv') values['factor'] = factor_inv and (1.0 / factor_inv) or 0.0 res = super(UoM, self).write(values) if ('uom_type' not in values or values['uom_type'] != 'reference') and\ not self.env.context.get('allow_to_change_reference'): self._check_category_reference_uniqueness() return res @api.ondelete(at_uninstall=False) def _unlink_except_master_data(self): locked_uoms = self._filter_protected_uoms() if locked_uoms: raise UserError(_( "The following units of measure are used by the system and cannot be deleted: %s\nYou can archive them instead.", ", ".join(locked_uoms.mapped('name')), )) @api.model def name_create(self, name): """ The UoM category and factor are required, so we'll have to add temporary values for imported UoMs """ values = { self._rec_name: name, 'factor': 1 } # look for the category based on the english name, i.e. no context on purpose! # TODO: should find a way to have it translated but not created until actually used if not self._context.get('default_category_id'): EnglishUoMCateg = self.env['uom.category'].with_context({}) misc_category = EnglishUoMCateg.search([('name', '=', 'Unsorted/Imported Units')]) if misc_category: values['category_id'] = misc_category.id else: values['category_id'] = EnglishUoMCateg.name_create('Unsorted/Imported Units')[0] new_uom = self.create(values) return new_uom.name_get()[0] def _compute_quantity(self, qty, to_unit, round=True, rounding_method='UP', raise_if_failure=True): """ Convert the given quantity from the current UoM `self` into a given one :param qty: the quantity to convert :param to_unit: the destination UoM record (uom.uom) :param raise_if_failure: only if the conversion is not possible - if true, raise an exception if the conversion is not possible (different UoM category), - otherwise, return the initial quantity """ if not self or not qty: return qty self.ensure_one() if self != to_unit and self.category_id.id != to_unit.category_id.id: if raise_if_failure: raise UserError(_('The unit of measure %s defined on the order line doesn\'t belong to the same category as the unit of measure %s defined on the product. Please correct the unit of measure defined on the order line or on the product, they should belong to the same category.') % (self.name, to_unit.name)) else: return qty if self == to_unit: amount = qty else: amount = qty / self.factor if to_unit: amount = amount * to_unit.factor if to_unit and round: amount = tools.float_round(amount, precision_rounding=to_unit.rounding, rounding_method=rounding_method) return amount def _compute_price(self, price, to_unit): self.ensure_one() if not self or not price or not to_unit or self == to_unit: return price if self.category_id.id != to_unit.category_id.id: return price amount = price * self.factor if to_unit: amount = amount / to_unit.factor return amount def _filter_protected_uoms(self): """Verifies self does not contain protected uoms.""" linked_model_data = self.env['ir.model.data'].sudo().search([ ('model', '=', self._name), ('res_id', 'in', self.ids), ('module', '=', 'uom'), ('name', 'not in', self._unprotected_uom_xml_ids()), ]) if not linked_model_data: return self.browse() else: return self.browse(set(linked_model_data.mapped('res_id')))
45.7393
11,755
737
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Margins by Products', 'category': 'Sales/Sales', 'description': """ Adds a reporting menu in products that computes sales, purchases, margins and other interesting indicators based on invoices. ============================================================================================================================= The wizard to launch the report has several options to help you get the data you need. """, 'depends': ['account'], 'data': [ 'security/ir.model.access.csv', 'wizard/product_margin_view.xml', 'views/product_product_views.xml' ], 'license': 'LGPL-3', }
35.095238
737
2,640
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged @tagged('post_install', '-at_install') class TestProductMargin(AccountTestInvoicingCommon): def test_product_margin(self): ''' In order to test the product_margin module ''' supplier = self.env['res.partner'].create({'name': 'Supplier'}) customer = self.env['res.partner'].create({'name': 'Customer'}) ipad = self.env['product.product'].create({ 'name': 'Ipad', 'standard_price': 500.0, 'list_price': 750.0, }) invoices = self.env['account.move'].create([ { 'move_type': 'in_invoice', 'partner_id': supplier.id, 'invoice_line_ids': [(0, 0, {'product_id': ipad.id, 'quantity': 10.0, 'price_unit': 300.0})], }, { 'move_type': 'in_invoice', 'partner_id': supplier.id, 'invoice_line_ids': [(0, 0, {'product_id': ipad.id, 'quantity': 4.0, 'price_unit': 450.0})], }, { 'move_type': 'out_invoice', 'partner_id': customer.id, 'invoice_line_ids': [(0, 0, {'product_id': ipad.id, 'quantity': 20.0, 'price_unit': 750.0})], }, { 'move_type': 'out_invoice', 'partner_id': customer.id, 'invoice_line_ids': [(0, 0, {'product_id': ipad.id, 'quantity': 10.0, 'price_unit': 550.0})], }, ]) invoices.invoice_date = invoices[0].date invoices.action_post() result = ipad._compute_product_margin_fields_values() # Sale turnover ( Quantity * Price Subtotal / Quantity) sale_turnover = ((20.0 * 750.00) + (10.0 * 550.00)) # Expected sale (Total quantity * Sale price) sale_expected = (750.00 * 30.0) # Purchase total cost (Quantity * Unit price) purchase_total_cost = ((10.0 * 300.00) + (4.0 * 450.00)) # Purchase normal cost ( Total quantity * Cost price) purchase_normal_cost = (14.0 * 500.00) total_margin = sale_turnover - purchase_total_cost expected_margin = sale_expected - purchase_normal_cost # Check total margin self.assertEqual(result[ipad.id]['total_margin'], total_margin, "Wrong Total Margin.") # Check expected margin self.assertEqual(result[ipad.id]['expected_margin'], expected_margin, "Wrong Expected Margin.")
39.402985
2,640
1,853
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo import api, fields, models, _ class ProductMargin(models.TransientModel): _name = 'product.margin' _description = 'Product Margin' from_date = fields.Date('From', default=time.strftime('%Y-01-01')) to_date = fields.Date('To', default=time.strftime('%Y-12-31')) invoice_state = fields.Selection([ ('paid', 'Paid'), ('open_paid', 'Open and Paid'), ('draft_open_paid', 'Draft, Open and Paid'), ], 'Invoice State', index=True, required=True, default="open_paid") def action_open_window(self): self.ensure_one() context = dict(self.env.context, create=False, edit=False) def ref(xml_id): proxy = self.env['ir.model.data'] return proxy._xmlid_lookup(xml_id)[2] search_view_id = ref('product.product_search_form_view') graph_view_id = ref('product_margin.view_product_margin_graph') form_view_id = ref('product_margin.view_product_margin_form') tree_view_id = ref('product_margin.view_product_margin_tree') context.update(invoice_state=self.invoice_state) if self.from_date: context.update(date_from=self.from_date) if self.to_date: context.update(date_to=self.to_date) views = [ (tree_view_id, 'tree'), (form_view_id, 'form'), (graph_view_id, 'graph') ] return { 'name': _('Product Margins'), 'context': context, "view_mode": 'tree,form,graph', 'res_model': 'product.product', 'type': 'ir.actions.act_window', 'views': views, 'view_id': False, 'search_view_id': [search_view_id], }
33.089286
1,853
11,647
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo import api, fields, models class ProductProduct(models.Model): _inherit = "product.product" date_from = fields.Date(compute='_compute_product_margin_fields_values', string='Margin Date From') date_to = fields.Date(compute='_compute_product_margin_fields_values', string='Margin Date To') invoice_state = fields.Selection(compute='_compute_product_margin_fields_values', selection=[ ('paid', 'Paid'), ('open_paid', 'Open and Paid'), ('draft_open_paid', 'Draft, Open and Paid') ], string='Invoice State', readonly=True) sale_avg_price = fields.Float(compute='_compute_product_margin_fields_values', string='Avg. Sale Unit Price', help="Avg. Price in Customer Invoices.") purchase_avg_price = fields.Float(compute='_compute_product_margin_fields_values', string='Avg. Purchase Unit Price', help="Avg. Price in Vendor Bills ") sale_num_invoiced = fields.Float(compute='_compute_product_margin_fields_values', string='# Invoiced in Sale', help="Sum of Quantity in Customer Invoices") purchase_num_invoiced = fields.Float(compute='_compute_product_margin_fields_values', string='# Invoiced in Purchase', help="Sum of Quantity in Vendor Bills") sales_gap = fields.Float(compute='_compute_product_margin_fields_values', string='Sales Gap', help="Expected Sale - Turn Over") purchase_gap = fields.Float(compute='_compute_product_margin_fields_values', string='Purchase Gap', help="Normal Cost - Total Cost") turnover = fields.Float(compute='_compute_product_margin_fields_values', string='Turnover', help="Sum of Multiplication of Invoice price and quantity of Customer Invoices") total_cost = fields.Float(compute='_compute_product_margin_fields_values', string='Total Cost', help="Sum of Multiplication of Invoice price and quantity of Vendor Bills ") sale_expected = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Sale', help="Sum of Multiplication of Sale Catalog price and quantity of Customer Invoices") normal_cost = fields.Float(compute='_compute_product_margin_fields_values', string='Normal Cost', help="Sum of Multiplication of Cost price and quantity of Vendor Bills") total_margin = fields.Float(compute='_compute_product_margin_fields_values', string='Total Margin', help="Turnover - Standard price") expected_margin = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Margin', help="Expected Sale - Normal Cost") total_margin_rate = fields.Float(compute='_compute_product_margin_fields_values', string='Total Margin Rate(%)', help="Total margin * 100 / Turnover") expected_margin_rate = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Margin (%)', help="Expected margin * 100 / Expected Sale") @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): """ Inherit read_group to calculate the sum of the non-stored fields, as it is not automatically done anymore through the XML. """ fields_list = ['turnover', 'sale_avg_price', 'sale_purchase_price', 'sale_num_invoiced', 'purchase_num_invoiced', 'sales_gap', 'purchase_gap', 'total_cost', 'sale_expected', 'normal_cost', 'total_margin', 'expected_margin', 'total_margin_rate', 'expected_margin_rate'] # Not any of the fields_list support aggregate function like :sum def truncate_aggr(field): field_no_aggr, _sep, agg = field.partition(':') if field_no_aggr in fields_list: if agg and agg != 'sum': raise NotImplementedError('Aggregate functions other than \':sum\' are not allowed.') return field_no_aggr return field fields = {truncate_aggr(field) for field in fields} res = super(ProductProduct, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) if any(x in fields for x in fields_list): # Calculate first for every product in which line it needs to be applied re_ind = 0 prod_re = {} tot_products = self.browse([]) for re in res: if re.get('__domain'): products = self.search(re['__domain']) tot_products |= products for prod in products: prod_re[prod.id] = re_ind re_ind += 1 res_val = tot_products._compute_product_margin_fields_values(field_names=[x for x in fields if fields in fields_list]) for key in res_val: for l in res_val[key]: re = res[prod_re[key]] if re.get(l): re[l] += res_val[key][l] else: re[l] = res_val[key][l] return res def _compute_product_margin_fields_values(self, field_names=None): if field_names is None: field_names = [] date_from = self.env.context.get('date_from', time.strftime('%Y-01-01')) date_to = self.env.context.get('date_to', time.strftime('%Y-12-31')) invoice_state = self.env.context.get('invoice_state', 'open_paid') res = { product_id: {'date_from': date_from, 'date_to': date_to, 'invoice_state': invoice_state, 'turnover': 0.0, 'sale_avg_price': 0.0, 'purchase_avg_price': 0.0, 'sale_num_invoiced': 0.0, 'purchase_num_invoiced': 0.0, 'sales_gap': 0.0, 'purchase_gap': 0.0, 'total_cost': 0.0, 'sale_expected': 0.0, 'normal_cost': 0.0, 'total_margin': 0.0, 'expected_margin': 0.0, 'total_margin_rate': 0.0, 'expected_margin_rate': 0.0} for product_id in self.ids } states = () payment_states = () if invoice_state == 'paid': states = ('posted',) payment_states = ('in_payment', 'paid', 'reversed') elif invoice_state == 'open_paid': states = ('posted',) payment_states = ('not_paid', 'in_payment', 'paid', 'reversed', 'partial') elif invoice_state == 'draft_open_paid': states = ('posted', 'draft') payment_states = ('not_paid', 'in_payment', 'paid', 'reversed', 'partial') if "force_company" in self.env.context: company_id = self.env.context['force_company'] else: company_id = self.env.company.id self.env['account.move.line'].flush(['price_unit', 'quantity', 'balance', 'product_id', 'display_type']) self.env['account.move'].flush(['state', 'payment_state', 'move_type', 'invoice_date', 'company_id']) self.env['product.template'].flush(['list_price']) sqlstr = """ WITH currency_rate AS ({}) SELECT l.product_id as product_id, SUM( l.price_unit / (CASE COALESCE(cr.rate, 0) WHEN 0 THEN 1.0 ELSE cr.rate END) * l.quantity * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END) * ((100 - l.discount) * 0.01) ) / NULLIF(SUM(l.quantity * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)), 0) AS avg_unit_price, SUM(l.quantity * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS num_qty, SUM(ABS(l.balance) * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS total, SUM(l.quantity * pt.list_price * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS sale_expected FROM account_move_line l LEFT JOIN account_move i ON (l.move_id = i.id) LEFT JOIN product_product product ON (product.id=l.product_id) LEFT JOIN product_template pt ON (pt.id = product.product_tmpl_id) left join currency_rate cr on (cr.currency_id = i.currency_id and cr.company_id = i.company_id and cr.date_start <= COALESCE(i.invoice_date, NOW()) and (cr.date_end IS NULL OR cr.date_end > COALESCE(i.invoice_date, NOW()))) WHERE l.product_id IN %s AND i.state IN %s AND i.payment_state IN %s AND i.move_type IN %s AND i.invoice_date BETWEEN %s AND %s AND i.company_id = %s AND l.display_type IS NULL AND l.exclude_from_invoice_tab = false GROUP BY l.product_id """.format(self.env['res.currency']._select_companies_rates()) invoice_types = ('out_invoice', 'out_refund') self.env.cr.execute(sqlstr, (tuple(self.ids), states, payment_states, invoice_types, date_from, date_to, company_id)) for product_id, avg, qty, total, sale in self.env.cr.fetchall(): res[product_id]['sale_avg_price'] = avg and avg or 0.0 res[product_id]['sale_num_invoiced'] = qty and qty or 0.0 res[product_id]['turnover'] = total and total or 0.0 res[product_id]['sale_expected'] = sale and sale or 0.0 res[product_id]['sales_gap'] = res[product_id]['sale_expected'] - res[product_id]['turnover'] res[product_id]['total_margin'] = res[product_id]['turnover'] res[product_id]['expected_margin'] = res[product_id]['sale_expected'] res[product_id]['total_margin_rate'] = res[product_id]['turnover'] and res[product_id]['total_margin'] * 100 / res[product_id]['turnover'] or 0.0 res[product_id]['expected_margin_rate'] = res[product_id]['sale_expected'] and res[product_id]['expected_margin'] * 100 / res[product_id]['sale_expected'] or 0.0 ctx = self.env.context.copy() ctx['force_company'] = company_id invoice_types = ('in_invoice', 'in_refund') self.env.cr.execute(sqlstr, (tuple(self.ids), states, payment_states, invoice_types, date_from, date_to, company_id)) for product_id, avg, qty, total, dummy in self.env.cr.fetchall(): res[product_id]['purchase_avg_price'] = avg and avg or 0.0 res[product_id]['purchase_num_invoiced'] = qty and qty or 0.0 res[product_id]['total_cost'] = total and total or 0.0 res[product_id]['total_margin'] = res[product_id].get('turnover', 0.0) - res[product_id]['total_cost'] res[product_id]['total_margin_rate'] = res[product_id].get('turnover', 0.0) and res[product_id]['total_margin'] * 100 / res[product_id].get('turnover', 0.0) or 0.0 for product in self: res[product.id]['normal_cost'] = product.standard_price * res[product.id]['purchase_num_invoiced'] res[product.id]['purchase_gap'] = res[product.id]['normal_cost'] - res[product.id]['total_cost'] res[product.id]['expected_margin'] = res[product.id].get('sale_expected', 0.0) - res[product.id]['normal_cost'] res[product.id]['expected_margin_rate'] = res[product.id].get('sale_expected', 0.0) and res[product.id]['expected_margin'] * 100 / res[product.id].get('sale_expected', 0.0) or 0.0 product.write(res[product.id]) return res
64.348066
11,647
528
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Payment - Account', 'category': 'Accounting/Accounting', 'summary': 'Account and Payment Link and Portal', 'version': '1.0', 'description': """Link Account and Payment and add Portal Payment Provide tools for account-related payment as well as portal options to enable payment. * UPDATE ME """, 'depends': ['payment'], 'data': [ 'views/account_portal_templates.xml', ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
24
528
2,990
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.http import request from odoo.addons.account.controllers import portal from odoo.addons.payment.controllers.portal import PaymentPortal from odoo.addons.portal.controllers.portal import _build_url_w_params class PortalAccount(portal.PortalAccount): def _invoice_get_page_view_values(self, invoice, access_token, **kwargs): values = super()._invoice_get_page_view_values(invoice, access_token, **kwargs) logged_in = not request.env.user._is_public() # We set partner_id to the partner id of the current user if logged in, otherwise we set it # to the invoice partner id. We do this to ensure that payment tokens are assigned to the # correct partner and to avoid linking tokens to the public user. partner_sudo = request.env.user.partner_id if logged_in else invoice.partner_id invoice_company = invoice.company_id or request.env.company acquirers_sudo = request.env['payment.acquirer'].sudo()._get_compatible_acquirers( invoice_company.id, partner_sudo.id, currency_id=invoice.currency_id.id ) # In sudo mode to read the fields of acquirers and partner (if not logged in) tokens = request.env['payment.token'].search( [('acquirer_id', 'in', acquirers_sudo.ids), ('partner_id', '=', partner_sudo.id)] ) # Tokens are cleared at the end if the user is not logged in # Make sure that the partner's company matches the invoice's company. if not PaymentPortal._can_partner_pay_in_company(partner_sudo, invoice_company): acquirers_sudo = request.env['payment.acquirer'].sudo() tokens = request.env['payment.token'] fees_by_acquirer = { acq_sudo: acq_sudo._compute_fees( invoice.amount_total, invoice.currency_id, invoice.partner_id.country_id ) for acq_sudo in acquirers_sudo.filtered('fees_active') } values.update({ 'acquirers': acquirers_sudo, 'tokens': tokens, 'fees_by_acquirer': fees_by_acquirer, 'show_tokenize_input': logged_in, # Prevent public partner from saving payment methods 'amount': invoice.amount_residual, 'currency': invoice.currency_id, 'partner_id': partner_sudo.id, 'access_token': access_token, 'transaction_route': f'/invoice/transaction/{invoice.id}/', 'landing_route': _build_url_w_params(invoice.access_url, {'access_token': access_token}) }) if not logged_in: # Don't display payment tokens of the invoice partner if the user is not logged in, but # inform that logging in will make them available. values.update({ 'existing_token': bool(tokens), 'tokens': request.env['payment.token'], }) return values
51.551724
2,990
1,909
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import AccessError, MissingError, ValidationError from odoo.fields import Command from odoo.http import request, route from odoo.addons.payment.controllers import portal as payment_portal class PaymentPortal(payment_portal.PaymentPortal): @route('/invoice/transaction/<int:invoice_id>', type='json', auth='public') def invoice_transaction(self, invoice_id, access_token, **kwargs): """ Create a draft transaction and return its processing values. :param int invoice_id: The invoice to pay, as an `account.move` id :param str access_token: The access token used to authenticate the request :param dict kwargs: Locally unused data passed to `_create_transaction` :return: The mandatory values for the processing of the transaction :rtype: dict :raise: ValidationError if the invoice id or the access token is invalid """ # Check the invoice id and the access token try: invoice_sudo = self._document_check_access('account.move', invoice_id, access_token) except MissingError as error: raise error except AccessError: raise ValidationError("The access token is invalid.") kwargs['reference_prefix'] = None # Allow the reference to be computed based on the invoice logged_in = not request.env.user._is_public() partner = request.env.user.partner_id if logged_in else invoice_sudo.partner_id kwargs['partner_id'] = partner.id kwargs.pop('custom_create_values', None) # Don't allow passing arbitrary create values tx_sudo = self._create_transaction( custom_create_values={'invoice_ids': [Command.set([invoice_id])]}, **kwargs, ) return tx_sudo._get_processing_values()
46.560976
1,909
704
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Memos pad', 'version': '0.1', 'category': 'Productivity/Notes', 'description': """ This module update memos inside Odoo for using an external pad ================================================================= Use for update your text memo in real time with the following user that you invite. """, 'summary': 'Sticky memos, Collaborative', 'depends': [ 'mail', 'pad', 'note', ], 'data': [ 'views/note_views.xml', ], 'installable': True, 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
25.142857
704
344
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class NotePad(models.Model): _name = 'note.note' _inherit = ['pad.common', 'note.note'] _pad_fields = ['note_pad'] note_pad_url = fields.Char('Pad Url', pad_content_field='memo', copy=False)
24.571429
344
593
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'POS Adyen', 'version': '1.0', 'category': 'Sales/Point of Sale', 'sequence': 6, 'summary': 'Integrate your POS with an Adyen payment terminal', 'description': '', 'data': [ 'views/pos_config_views.xml', 'views/pos_payment_method_views.xml', ], 'depends': ['point_of_sale'], 'installable': True, 'assets': { 'point_of_sale.assets': [ 'pos_adyen/static/**/*', ], }, 'license': 'LGPL-3', }
26.954545
593
987
py
PYTHON
15.0
# coding: utf-8 # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models, _ from odoo.exceptions import ValidationError _logger = logging.getLogger(__name__) class PosConfig(models.Model): _inherit = 'pos.config' adyen_ask_customer_for_tip = fields.Boolean('Ask Customers For Tip', help='Prompt the customer to tip.') @api.onchange('iface_tipproduct') def _onchange_iface_tipproduct_adyen(self): if not self.iface_tipproduct: self.adyen_ask_customer_for_tip = False @api.constrains('adyen_ask_customer_for_tip', 'iface_tipproduct', 'tip_product_id') def _check_adyen_ask_customer_for_tip(self): for config in self: if config.adyen_ask_customer_for_tip and (not config.tip_product_id or not config.iface_tipproduct): raise ValidationError(_("Please configure a tip product for POS %s to support tipping with Adyen.", config.name))
39.48
987
5,366
py
PYTHON
15.0
# coding: utf-8 # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import logging import pprint import random import requests import string from werkzeug.exceptions import Forbidden from odoo import fields, models, api, _ from odoo.exceptions import ValidationError _logger = logging.getLogger(__name__) class PosPaymentMethod(models.Model): _inherit = 'pos.payment.method' def _get_payment_terminal_selection(self): return super(PosPaymentMethod, self)._get_payment_terminal_selection() + [('adyen', 'Adyen')] # Adyen adyen_api_key = fields.Char(string="Adyen API key", help='Used when connecting to Adyen: https://docs.adyen.com/user-management/how-to-get-the-api-key/#description', copy=False) adyen_terminal_identifier = fields.Char(help='[Terminal model]-[Serial number], for example: P400Plus-123456789', copy=False) adyen_test_mode = fields.Boolean(help='Run transactions in the test environment.') adyen_latest_response = fields.Char(help='Technical field used to buffer the latest asynchronous notification from Adyen.', copy=False, groups='base.group_erp_manager') adyen_latest_diagnosis = fields.Char(help='Technical field used to determine if the terminal is still connected.', copy=False, groups='base.group_erp_manager') @api.constrains('adyen_terminal_identifier') def _check_adyen_terminal_identifier(self): for payment_method in self: if not payment_method.adyen_terminal_identifier: continue # sudo() to search all companies existing_payment_method = self.sudo().search([('id', '!=', payment_method.id), ('adyen_terminal_identifier', '=', payment_method.adyen_terminal_identifier)], limit=1) if existing_payment_method: if existing_payment_method.company_id == payment_method.company_id: raise ValidationError(_('Terminal %s is already used on payment method %s.') % (payment_method.adyen_terminal_identifier, existing_payment_method.display_name)) else: raise ValidationError(_('Terminal %s is already used in company %s on payment method %s.') % (payment_method.adyen_terminal_identifier, existing_payment_method.company_id.name, existing_payment_method.display_name)) def _get_adyen_endpoints(self): return { 'terminal_request': 'https://terminal-api-%s.adyen.com/async', } def _is_write_forbidden(self, fields): whitelisted_fields = set(('adyen_latest_response', 'adyen_latest_diagnosis')) return super(PosPaymentMethod, self)._is_write_forbidden(fields - whitelisted_fields) def _adyen_diagnosis_request_data(self, pos_config_name): service_id = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) return { "SaleToPOIRequest": { "MessageHeader": { "ProtocolVersion": "3.0", "MessageClass": "Service", "MessageCategory": "Diagnosis", "MessageType": "Request", "ServiceID": service_id, "SaleID": pos_config_name, "POIID": self.adyen_terminal_identifier, }, "DiagnosisRequest": { "HostDiagnosisFlag": False } } } def get_latest_adyen_status(self, pos_config_name): _logger.info('get_latest_adyen_status\n%s', pos_config_name) self.ensure_one() latest_response = self.sudo().adyen_latest_response latest_response = json.loads(latest_response) if latest_response else False return { 'latest_response': latest_response, } def proxy_adyen_request(self, data, operation=False): ''' Necessary because Adyen's endpoints don't have CORS enabled ''' if data['SaleToPOIRequest']['MessageHeader']['MessageCategory'] == 'Payment': # Clear only if it is a payment request self.sudo().adyen_latest_response = '' # avoid handling old responses multiple times if not operation: operation = 'terminal_request' return self._proxy_adyen_request_direct(data, operation) def _proxy_adyen_request_direct(self, data, operation): self.ensure_one() TIMEOUT = 10 _logger.info('request to adyen\n%s', pprint.pformat(data)) environment = 'test' if self.adyen_test_mode else 'live' endpoint = self._get_adyen_endpoints()[operation] % environment headers = { 'x-api-key': self.adyen_api_key, } req = requests.post(endpoint, json=data, headers=headers, timeout=TIMEOUT) # Authentication error doesn't return JSON if req.status_code == 401: return { 'error': { 'status_code': req.status_code, 'message': req.text } } if req.text == 'ok': return True return req.json()
43.626016
5,366
1,427
py
PYTHON
15.0
# coding: utf-8 import logging import pprint import json from odoo import fields, http from odoo.http import request _logger = logging.getLogger(__name__) class PosAdyenController(http.Controller): @http.route('/pos_adyen/notification', type='json', methods=['POST'], auth='none', csrf=False) def notification(self): data = json.loads(request.httprequest.data) # ignore if it's not a response to a sales request if not data.get('SaleToPOIResponse'): return _logger.info('notification received from adyen:\n%s', pprint.pformat(data)) terminal_identifier = data['SaleToPOIResponse']['MessageHeader']['POIID'] payment_method = request.env['pos.payment.method'].sudo().search([('adyen_terminal_identifier', '=', terminal_identifier)], limit=1) if payment_method: # These are only used to see if the terminal is reachable, # store the most recent ID we received. if data['SaleToPOIResponse'].get('DiagnosisResponse'): payment_method.adyen_latest_diagnosis = data['SaleToPOIResponse']['MessageHeader']['ServiceID'] else: payment_method.adyen_latest_response = json.dumps(data) _logger.info('notification writed from adyen\n%s', data) else: _logger.error('received a message for a terminal not registered in Odoo: %s', terminal_identifier)
43.242424
1,427
625
py
PYTHON
15.0
{ 'name': '2FA by mail', 'description': """ 2FA by mail =============== Two-Factor authentication by sending a code to the user email inbox when the 2FA using an authenticator app is not configured. To enforce users to use a two-factor authentication by default, and encourage users to configure their 2FA using an authenticator app. """, 'depends': ['auth_totp', 'mail'], 'category': 'Extra Tools', 'data': [ 'data/mail_template_data.xml', 'security/ir.model.access.csv', 'views/res_config_settings_views.xml', 'views/templates.xml', ], 'license': 'LGPL-3', }
31.25
625
5,493
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import babel.dates import logging from datetime import datetime, timedelta from odoo import _, models from odoo.exceptions import AccessDenied, UserError from odoo.http import request from odoo.tools.misc import babel_locale_parse, hmac from odoo.addons.auth_totp.models.totp import hotp, TOTP _logger = logging.getLogger(__name__) TOTP_RATE_LIMITS = { 'send_email': (10, 3600), 'code_check': (10, 3600), } class Users(models.Model): _inherit = 'res.users' def _mfa_type(self): r = super()._mfa_type() if r is not None: return r ICP = self.env['ir.config_parameter'].sudo() otp_required = False if ICP.get_param('auth_totp.policy') == 'all_required': otp_required = True elif ICP.get_param('auth_totp.policy') == 'employee_required' and self.has_group('base.group_user'): otp_required = True if otp_required: return 'totp_mail' def _mfa_url(self): r = super()._mfa_url() if r is not None: return r if self._mfa_type() == 'totp_mail': return '/web/login/totp' def _totp_check(self, code): self._totp_rate_limit('code_check') user = self.sudo() if user._mfa_type() != 'totp_mail': return super()._totp_check(code) key = self._get_totp_mail_key() match = TOTP(key).match(code, window=3600, timestep=3600) if match is None: _logger.info("2FA check (mail): FAIL for %s %r", self, self.login) raise AccessDenied(_("Verification failed, please double-check the 6-digit code")) _logger.info("2FA check(mail): SUCCESS for %s %r", self, self.login) self._totp_rate_limit_purge('code_check') self._totp_rate_limit_purge('send_email') return True def _get_totp_mail_key(self): self.ensure_one() return hmac(self.env(su=True), 'auth_totp_mail-code', (self.id, self.login, self.login_date)).encode() def _get_totp_mail_code(self): self.ensure_one() key = self._get_totp_mail_key() now = datetime.now() counter = int(datetime.timestamp(now) / 3600) code = hotp(key, counter) expiration = timedelta(seconds=3600) lang = babel_locale_parse(self.env.context.get('lang') or self.lang) expiration = babel.dates.format_timedelta(expiration, lang) return str(code).zfill(6), expiration def _send_totp_mail_code(self): self.ensure_one() self._totp_rate_limit('send_email') if not self.email: raise UserError(_("Cannot send email: user %s has no email address.", self.name)) template = self.env.ref('auth_totp_mail_enforce.mail_template_totp_mail_code').sudo() context = {} if request: geoip = request.session.geoip device = request.httprequest.user_agent.platform browser = request.httprequest.user_agent.browser context.update({ 'location': f"{geoip['city']}, {geoip['country_name']}" if geoip else None, 'device': device and device.capitalize() or None, 'browser': browser and browser.capitalize() or None, 'ip': request.httprequest.environ['REMOTE_ADDR'], }) email_values = { 'email_to': self.email, 'email_cc': False, 'auto_delete': True, 'recipient_ids': [], 'partner_ids': [], 'scheduled_date': False, } with self.env.cr.savepoint(): template.with_context(**context).send_mail( self.id, force_send=True, raise_exception=True, email_values=email_values, notif_layout='mail.mail_notification_light' ) def _totp_rate_limit(self, limit_type): self.ensure_one() assert request, "A request is required to be able to rate limit TOTP related actions" limit, interval = TOTP_RATE_LIMITS.get(limit_type) RateLimitLog = self.env['auth.totp.rate.limit.log'].sudo() ip = request.httprequest.environ['REMOTE_ADDR'] domain = [ ('user_id', '=', self.id), ('create_date', '>=', datetime.now() - timedelta(seconds=interval)), ('limit_type', '=', limit_type), ('ip', '=', ip), ] count = RateLimitLog.search_count(domain) if count >= limit: descriptions = { 'send_email': _('You reached the limit of authentication mails sent for your account'), 'code_check': _('You reached the limit of code verifications for your account'), } description = descriptions.get(limit_type) raise AccessDenied(description) RateLimitLog.create({ 'user_id': self.id, 'ip': ip, 'limit_type': limit_type, }) def _totp_rate_limit_purge(self, limit_type): self.ensure_one() assert request, "A request is required to be able to rate limit TOTP related actions" ip = request.httprequest.environ['REMOTE_ADDR'] RateLimitLog = self.env['auth.totp.rate.limit.log'].sudo() RateLimitLog.search([ ('user_id', '=', self.id), ('limit_type', '=', limit_type), ('ip', '=', ip), ]).unlink()
37.114865
5,493
1,030
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' auth_totp_enforce = fields.Boolean( string="Enforce two-factor authentication", ) auth_totp_policy = fields.Selection([ ('employee_required', 'Employees only'), ('all_required', 'All users') ], string="Two-factor authentication enforcing policy", config_parameter='auth_totp.policy', ) @api.onchange('auth_totp_enforce') def _onchange_auth_totp_enforce(self): if self.auth_totp_enforce: self.auth_totp_policy = 'employee_required' else: self.auth_totp_policy = False @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() res['auth_totp_enforce'] = bool(self.env['ir.config_parameter'].sudo().get_param('auth_totp.policy')) return res
32.1875
1,030
692
py
PYTHON
15.0
from odoo import fields, models class AuthTotpRateLimitLog(models.TransientModel): _name = 'auth.totp.rate.limit.log' _description = 'TOTP rate limit logs' def init(self): self.env.cr.execute(""" CREATE INDEX IF NOT EXISTS auth_totp_rate_limit_log_user_id_limit_type_create_date_idx ON auth_totp_rate_limit_log(user_id, limit_type, create_date); """) user_id = fields.Many2one('res.users', required=True, readonly=True) scope = fields.Char(readonly=True) ip = fields.Char(readonly=True) limit_type = fields.Selection([ ('send_email', 'Send Email'), ('code_check', 'Code Checking'), ], readonly=True)
34.6
692
1,052
py
PYTHON
15.0
# -*- coding: utf-8 -*- import odoo.addons.auth_totp.controllers.home from odoo import http from odoo.exceptions import AccessDenied, UserError from odoo.http import request class Home(odoo.addons.auth_totp.controllers.home.Home): @http.route() def web_totp(self, redirect=None, **kwargs): response = super().web_totp(redirect=redirect, **kwargs) if response.status_code != 200 or response.qcontext['user']._mfa_type() != 'totp_mail': # In case the response from the super is a redirection # or the user has another TOTP method, we return the response from the call to super. return response assert request.session.pre_uid and not request.session.uid, \ "The user must still be in the pre-authentication phase" # Send the email containing the code to the user inbox try: response.qcontext['user']._send_totp_mail_code() except (AccessDenied, UserError) as e: response.qcontext['error'] = str(e) return response
40.461538
1,052
997
py
PYTHON
15.0
{ 'name': 'eCommerce Delivery', 'category': 'Website/Website', 'summary': 'Add delivery costs to online sales', 'version': '1.0', 'description': """ Add a selection of delivery methods to your eCommerce store. Configure your own methods with a pricing grid or integrate with carriers for a fully automated shipping process. """, 'depends': ['website_sale', 'delivery', 'website_sale_stock'], 'data': [ 'views/website_sale_delivery_templates.xml', 'views/website_sale_delivery_views.xml', 'views/res_config_settings_views.xml', 'data/website_sale_delivery_data.xml' ], 'demo': [ 'data/website_sale_delivery_demo.xml' ], 'installable': True, 'auto_install': True, 'assets': { 'web.assets_frontend': [ 'website_sale_delivery/static/src/**/*', ], 'web.assets_tests': [ 'website_sale_delivery/static/tests/**/*', ], }, 'license': 'LGPL-3', }
32.16129
997
2,604
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.tagged('post_install', '-at_install') class TestUi(odoo.tests.HttpCase): def test_01_free_delivery_when_exceed_threshold(self): # Avoid Shipping/Billing address page self.env.ref('base.partner_admin').write({ 'street': '215 Vine St', 'city': 'Scranton', 'zip': '18503', 'country_id': self.env.ref('base.us').id, 'state_id': self.env.ref('base.state_us_39').id, 'phone': '+1 555-555-5555', 'email': 'admin@yourcompany.example.com', }) office_chair = self.env['product.product'].create({ 'name': 'Office Chair Black TEST', 'list_price': 12.50, }) self.env.ref("delivery.free_delivery_carrier").write({ 'name': 'Delivery Now Free Over 10', 'fixed_price': 2, 'free_over': True, 'amount': 10, }) self.product_delivery_poste = self.env['product.product'].create({ 'name': 'The Poste', 'type': 'service', 'categ_id': self.env.ref('delivery.product_category_deliveries').id, 'sale_ok': False, 'purchase_ok': False, 'list_price': 20.0, }) self.carrier = self.env['delivery.carrier'].create({ 'name': 'The Poste', 'sequence': 9999, # ensure last to load price async 'fixed_price': 20.0, 'delivery_type': 'base_on_rule', 'product_id': self.product_delivery_poste.id, 'website_published': True, }) self.env['delivery.price.rule'].create([{ 'carrier_id': self.carrier.id, 'max_value': 5, 'list_base_price': 20, }, { 'carrier_id': self.carrier.id, 'operator': '>=', 'max_value': 5, 'list_base_price': 50, }, { 'carrier_id': self.carrier.id, 'operator': '>=', 'max_value': 300, 'variable': 'price', 'list_base_price': 0, }]) self.env['account.journal'].create({'name': 'Cash - Test', 'type': 'cash', 'code': 'CASH - Test'}) # Ensure "Wire Transfer" is the default acquirer. # Acquirers are sorted by state, showing `test` acquirers first (don't ask why). self.env.ref("payment.payment_acquirer_transfer").write({"state": "test"}) self.start_tour("/", 'check_free_delivery', login="admin")
36.676056
2,604
1,832
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from odoo.exceptions import UserError from odoo.addons.payment.tests.common import PaymentCommon from odoo.addons.website_sale_delivery.controllers.main import WebsiteSaleDelivery from odoo.addons.website.tools import MockRequest from odoo.tests import tagged @tagged('post_install', '-at_install') class TestWebsiteSaleDeliveryController(PaymentCommon): def setUp(self): super().setUp() self.website = self.env.ref('website.default_website') self.Controller = WebsiteSaleDelivery() # test that changing the carrier while there is a pending transaction raises an error def test_controller_change_carrier_when_transaction(self): with MockRequest(self.env, website=self.website): order = self.website.sale_get_order(force_create=True) order.transaction_ids = self.create_transaction(flow='redirect', state='pending') with self.assertRaises(UserError): with patch( 'odoo.addons.website_sale.models.website.Website.sale_get_order', return_value=order, ): # Patch to retrieve the order even if it is linked to a pending transaction. self.Controller.update_eshop_carrier(carrier_id=1) # test that changing the carrier while there is a draft transaction doesn't raise an error def test_controller_change_carrier_when_draft_transaction(self): with MockRequest(self.env, website=self.website): order = self.website.sale_get_order(force_create=True) order.transaction_ids = self.create_transaction(flow='redirect', state='draft') self.Controller.update_eshop_carrier(carrier_id=1)
50.888889
1,832
409
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class DeliveryCarrier(models.Model): _name = 'delivery.carrier' _inherit = ['delivery.carrier', 'website.published.multi.mixin'] website_description = fields.Text(related='product_id.description_sale', string='Description for Online Quotations', readonly=False)
37.181818
409
1,576
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResCountry(models.Model): _inherit = 'res.country' def get_website_sale_countries(self, mode='billing'): res = super(ResCountry, self).get_website_sale_countries(mode=mode) if mode == 'shipping': countries = self.env['res.country'] delivery_carriers = self.env['delivery.carrier'].sudo().search([('website_published', '=', True)]) for carrier in delivery_carriers: if not carrier.country_ids and not carrier.state_ids: countries = res break countries |= carrier.country_ids res = res & countries return res def get_website_sale_states(self, mode='billing'): res = super(ResCountry, self).get_website_sale_states(mode=mode) states = self.env['res.country.state'] if mode == 'shipping': dom = ['|', ('country_ids', 'in', self.id), ('country_ids', '=', False), ('website_published', '=', True)] delivery_carriers = self.env['delivery.carrier'].sudo().search(dom) for carrier in delivery_carriers: if not carrier.country_ids or not carrier.state_ids: states = res break states |= carrier.state_ids if not states: states = states.search([('country_id', '=', self.id)]) res = res & states return res
38.439024
1,576
4,389
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) class SaleOrder(models.Model): _inherit = 'sale.order' amount_delivery = fields.Monetary( compute='_compute_amount_delivery', string='Delivery Amount', help="The amount without tax.", store=True, tracking=True) def _compute_website_order_line(self): super(SaleOrder, self)._compute_website_order_line() for order in self: order.website_order_line = order.website_order_line.filtered(lambda l: not l.is_delivery) @api.depends('order_line.price_unit', 'order_line.tax_id', 'order_line.discount', 'order_line.product_uom_qty') def _compute_amount_delivery(self): for order in self: if self.env.user.has_group('account.group_show_line_subtotals_tax_excluded'): order.amount_delivery = sum(order.order_line.filtered('is_delivery').mapped('price_subtotal')) else: order.amount_delivery = sum(order.order_line.filtered('is_delivery').mapped('price_total')) def _check_carrier_quotation(self, force_carrier_id=None): self.ensure_one() DeliveryCarrier = self.env['delivery.carrier'] if self.only_services: self.write({'carrier_id': None}) self._remove_delivery_line() return True else: self = self.with_company(self.company_id) keep_carrier = self.env.context.get('keep_carrier', False) # attempt to use partner's preferred carrier if not force_carrier_id and self.partner_shipping_id.property_delivery_carrier_id and not keep_carrier: force_carrier_id = self.partner_shipping_id.property_delivery_carrier_id.id carrier = force_carrier_id and DeliveryCarrier.browse(force_carrier_id) or self.carrier_id available_carriers = self._get_delivery_methods() if carrier: if carrier not in available_carriers: carrier = DeliveryCarrier else: # set the forced carrier at the beginning of the list to be verfied first below available_carriers -= carrier available_carriers = carrier + available_carriers if force_carrier_id or not carrier or carrier not in available_carriers: for delivery in available_carriers: verified_carrier = delivery._match_address(self.partner_shipping_id) if verified_carrier: carrier = delivery break self.write({'carrier_id': carrier.id}) self._remove_delivery_line() if carrier: res = carrier.rate_shipment(self) if res.get('success'): self.set_delivery_line(carrier, res['price']) self.delivery_rating_success = True self.delivery_message = res['warning_message'] else: self.set_delivery_line(carrier, 0.0) self.delivery_rating_success = False self.delivery_message = res['error_message'] return bool(carrier) def _get_delivery_methods(self): address = self.partner_shipping_id # searching on website_published will also search for available website (_search method on computed field) return self.env['delivery.carrier'].sudo().search([('website_published', '=', True)]).available_carriers(address) def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs): """ Override to update carrier quotation if quantity changed """ self._remove_delivery_line() # When you update a cart, it is not enouf to remove the "delivery cost" line # The carrier might also be invalid, eg: if you bought things that are too heavy # -> this may cause a bug if you go to the checkout screen, choose a carrier, # then update your cart (the cart becomes uneditable) self.write({'carrier_id': False}) values = super(SaleOrder, self)._cart_update(product_id, line_id, add_qty, set_qty, **kwargs) return values
46.691489
4,389
6,348
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http, _ from odoo.http import request from odoo.addons.website_sale.controllers.main import WebsiteSale from odoo.exceptions import UserError class WebsiteSaleDelivery(WebsiteSale): @http.route() def shop_payment(self, **post): order = request.website.sale_get_order() carrier_id = post.get('carrier_id') keep_carrier = post.get('keep_carrier', False) if keep_carrier: keep_carrier = bool(int(keep_carrier)) if carrier_id: carrier_id = int(carrier_id) if order: order.with_context(keep_carrier=keep_carrier)._check_carrier_quotation(force_carrier_id=carrier_id) if carrier_id: return request.redirect("/shop/payment") return super(WebsiteSaleDelivery, self).shop_payment(**post) @http.route(['/shop/update_carrier'], type='json', auth='public', methods=['POST'], website=True, csrf=False) def update_eshop_carrier(self, **post): order = request.website.sale_get_order() carrier_id = int(post['carrier_id']) if order and carrier_id != order.carrier_id.id: if any(tx.state not in ("cancel", "error", "draft") for tx in order.transaction_ids): raise UserError(_('It seems that there is already a transaction for your order, you can not change the delivery method anymore')) order._check_carrier_quotation(force_carrier_id=carrier_id) return self._update_website_sale_delivery_return(order, **post) @http.route(['/shop/carrier_rate_shipment'], type='json', auth='public', methods=['POST'], website=True) def cart_carrier_rate_shipment(self, carrier_id, **kw): order = request.website.sale_get_order(force_create=True) if not int(carrier_id) in order._get_delivery_methods().ids: raise UserError(_('It seems that a delivery method is not compatible with your address. Please refresh the page and try again.')) Monetary = request.env['ir.qweb.field.monetary'] res = {'carrier_id': carrier_id} carrier = request.env['delivery.carrier'].sudo().browse(int(carrier_id)) rate = carrier.rate_shipment(order) if rate.get('success'): tax_ids = carrier.product_id.taxes_id.filtered(lambda t: t.company_id == order.company_id) if tax_ids: fpos = order.fiscal_position_id tax_ids = fpos.map_tax(tax_ids) taxes = tax_ids.compute_all( rate['price'], currency=order.currency_id, quantity=1.0, product=carrier.product_id, partner=order.partner_shipping_id, ) if request.env.user.has_group('account.group_show_line_subtotals_tax_excluded'): rate['price'] = taxes['total_excluded'] else: rate['price'] = taxes['total_included'] res['status'] = True res['new_amount_delivery'] = Monetary.value_to_html(rate['price'], {'display_currency': order.currency_id}) res['is_free_delivery'] = not bool(rate['price']) res['error_message'] = rate['warning_message'] else: res['status'] = False res['new_amount_delivery'] = Monetary.value_to_html(0.0, {'display_currency': order.currency_id}) res['error_message'] = rate['error_message'] return res def order_lines_2_google_api(self, order_lines): """ Transforms a list of order lines into a dict for google analytics """ order_lines_not_delivery = order_lines.filtered(lambda line: not line.is_delivery) return super(WebsiteSaleDelivery, self).order_lines_2_google_api(order_lines_not_delivery) def order_2_return_dict(self, order): """ Returns the tracking_cart dict of the order for Google analytics """ ret = super(WebsiteSaleDelivery, self).order_2_return_dict(order) delivery_line = order.order_line.filtered('is_delivery') if delivery_line: ret['shipping'] = delivery_line.price_unit return ret def _get_shop_payment_values(self, order, **kwargs): values = super(WebsiteSaleDelivery, self)._get_shop_payment_values(order, **kwargs) has_storable_products = any(line.product_id.type in ['consu', 'product'] for line in order.order_line) if not order._get_delivery_methods() and has_storable_products: values['errors'].append( (_('Sorry, we are unable to ship your order'), _('No shipping method is available for your current order and shipping address. ' 'Please contact us for more information.'))) if has_storable_products: if order.carrier_id and not order.delivery_rating_success: order._remove_delivery_line() delivery_carriers = order._get_delivery_methods() values['deliveries'] = delivery_carriers.sudo() values['delivery_has_storable'] = has_storable_products values['delivery_action_id'] = request.env.ref('delivery.action_delivery_carrier_form').id return values def _update_website_sale_delivery_return(self, order, **post): Monetary = request.env['ir.qweb.field.monetary'] carrier_id = int(post['carrier_id']) currency = order.currency_id if order: return { 'status': order.delivery_rating_success, 'error_message': order.delivery_message, 'carrier_id': carrier_id, 'is_free_delivery': not bool(order.amount_delivery), 'new_amount_delivery': Monetary.value_to_html(order.amount_delivery, {'display_currency': currency}), 'new_amount_untaxed': Monetary.value_to_html(order.amount_untaxed, {'display_currency': currency}), 'new_amount_tax': Monetary.value_to_html(order.amount_tax, {'display_currency': currency}), 'new_amount_total': Monetary.value_to_html(order.amount_total, {'display_currency': currency}), 'new_amount_total_raw': order.amount_total, } return {}
49.984252
6,348