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
739
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'pos_epson_printer', 'version': '1.0', 'category': 'Sales/Point of Sale', 'sequence': 6, 'summary': 'Epson ePOS Printers in PoS', 'description': """ Use Epson ePOS Printers without the IoT Box in the Point of Sale """, 'depends': ['point_of_sale'], 'data': [ 'views/pos_config_views.xml', ], 'installable': True, 'auto_install': True, 'assets': { 'point_of_sale.assets': [ 'pos_epson_printer/static/src/js/**/*', ], 'web.assets_qweb': [ 'pos_epson_printer/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
24.633333
739
486
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 PosConfig(models.Model): _inherit = 'pos.config' epson_printer_ip = fields.Char(string='Epson Printer IP', help="Local IP address of an Epson receipt printer.") @api.onchange('epson_printer_ip') def _onchange_epson_printer_ip(self): if self.epson_printer_ip in (False, ''): self.iface_cashdrawer = False
34.714286
486
778
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Egypt ETA Hardware Driver', 'category': 'Accounting/Accounting', 'website': 'https://www.odoo.com', 'summary': 'Egypt ETA Hardware Driver', 'description': """ Egypt ETA Hardware Driver ======================= This module allows Odoo to digitally sign invoices using an USB key approved by the egyptian government Special thanks to Plementus <[email protected]> for their help in developing this module. Requirements per system ----------------------- Windows: - eps2003csp11.dll Linux/macOS: - OpenSC """, 'external_dependencies': { 'python': ['PyKCS11'], }, 'installable': False, 'license': 'LGPL-3', }
24.3125
778
5,368
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import logging import platform import json from passlib.context import CryptContext from odoo import http from odoo.tools.config import config _logger = logging.getLogger(__name__) try: import PyKCS11 except ImportError: PyKCS11 = None _logger.error('Could not import library PyKCS11') crypt_context = CryptContext(schemes=['pbkdf2_sha512']) class EtaUsbController(http.Controller): def _is_access_token_valid(self, access_token): stored_hash = config.get('proxy_access_token') if not stored_hash: # empty password/hash => authentication forbidden return False return crypt_context.verify(access_token, stored_hash) @http.route('/hw_l10n_eg_eta/certificate', type='http', auth='none', cors='*', csrf=False, save_session=False, methods=['POST']) def eta_certificate(self, pin, access_token): """ Gets the certificate from the token and returns it to the main odoo instance so that we can prepare the cades-bes object on the main odoo instance rather than this middleware @param pin: pin of the token @param access_token: token shared with the main odoo instance """ if not PyKCS11: return self._get_error_template('no_pykcs11') if not self._is_access_token_valid(access_token): return self._get_error_template('unauthorized') session, error = self._get_session(pin) if error: return error try: cert = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])[0] cert_bytes = bytes(session.getAttributeValue(cert, [PyKCS11.CKA_VALUE])[0]) payload = { 'certificate': base64.b64encode(cert_bytes).decode() } return json.dumps(payload) except Exception as ex: return self._get_error_template(str(ex)) finally: session.logout() session.closeSession() @http.route('/hw_l10n_eg_eta/sign', type='http', auth='none', cors='*', csrf=False, save_session=False, methods=['POST']) def eta_sign(self, pin, access_token, invoices): """ Check if the access_token is valid and sign the invoices accessing the usb key with the pin. @param pin: pin of the token @param access_token: token shared with the main odoo instance @param invoices: dictionary of invoices. Keys are invoices ids, value are the base64 encoded binaries to sign """ if not PyKCS11: return self._get_error_template('no_pykcs11') if not self._is_access_token_valid(access_token): return self._get_error_template('unauthorized') session, error = self._get_session(pin) if error: return error try: cert = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])[0] cert_id = session.getAttributeValue(cert, [PyKCS11.CKA_ID])[0] priv_key = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_ID, cert_id)])[0] invoice_dict = dict() invoices = json.loads(invoices) for invoice, eta_inv in invoices.items(): to_sign = base64.b64decode(eta_inv) signed_data = session.sign(priv_key, to_sign, PyKCS11.Mechanism(PyKCS11.CKM_SHA256_RSA_PKCS)) invoice_dict[invoice] = base64.b64encode(bytes(signed_data)).decode() payload = { 'invoices': json.dumps(invoice_dict), } return json.dumps(payload) except Exception as ex: return self._get_error_template(str(ex)) finally: session.logout() session.closeSession() def _get_session(self, pin): session = False lib, error = self.get_crypto_lib() if error: return session, error try: pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load(pkcs11dll_filename=lib) except PyKCS11.PyKCS11Error: return session, self._get_error_template('missing_dll') slots = pkcs11.getSlotList(tokenPresent=True) if not slots: return session, self._get_error_template('no_drive') if len(slots) > 1: return session, self._get_error_template('multiple_drive') try: session = pkcs11.openSession(slots[0], PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION) session.login(pin) except Exception as ex: error = self._get_error_template(str(ex)) return session, error def get_crypto_lib(self): error = lib = False system = platform.system() if system == 'Linux': lib = '/usr/lib/x86_64-linux-gnu/opensc-pkcs11.so' elif system == 'Windows': lib = 'C:/Windows/System32/eps2003csp11.dll' elif system == 'Darwin': lib = '/Library/OpenSC/lib/onepin-opensc-pkcs11.so' else: error = self._get_error_template('unsupported_system') return lib, error def _get_error_template(self, error_str): return json.dumps({ 'error': error_str, })
38.342857
5,368
1,292
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Online Jobs', 'category': 'Website/Website', 'sequence': 310, 'version': '1.0', 'summary': 'Manage your online hiring process', 'description': "This module allows to publish your available job positions on your website and keep track of application submissions easily. It comes as an add-on of *Recruitment* app.", 'depends': ['hr_recruitment', 'website_mail'], 'data': [ 'security/ir.model.access.csv', 'security/website_hr_recruitment_security.xml', 'data/config_data.xml', 'views/website_hr_recruitment_templates.xml', 'views/hr_recruitment_views.xml', 'views/hr_job_views.xml', ], 'demo': [ 'data/hr_job_demo.xml', ], 'installable': True, 'application': True, 'auto_install': ['hr_recruitment', 'website_mail'], 'assets': { 'web.assets_frontend': [ 'website_hr_recruitment/static/src/scss/**/*', ], 'website.assets_editor': [ 'website_hr_recruitment/static/src/js/**/*', ], 'web.assets_tests': [ 'website_hr_recruitment/static/tests/**/*', ], }, 'license': 'LGPL-3', }
34
1,292
1,668
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.api import Environment import odoo.tests @odoo.tests.tagged('post_install', '-at_install') class TestWebsiteHrRecruitmentForm(odoo.tests.HttpCase): def test_tour(self): job_guru = self.env['hr.job'].create({ 'name': 'Guru', 'is_published': True, }) job_intern = self.env['hr.job'].create({ 'name': 'Internship', 'is_published': True, }) self.start_tour('/', 'website_hr_recruitment_tour_edit_form', login='admin') self.start_tour('/', 'website_hr_recruitment_tour') # check result guru_applicant = self.env['hr.applicant'].search([('description', '=', '### [GURU] HR RECRUITMENT TEST DATA ###'), ('job_id', '=', job_guru.id),]) self.assertEqual(len(guru_applicant), 1) self.assertEqual(guru_applicant.partner_name, 'John Smith') self.assertEqual(guru_applicant.email_from, '[email protected]') self.assertEqual(guru_applicant.partner_phone, '118.218') internship_applicant = self.env['hr.applicant'].search([('description', '=', '### HR [INTERN] RECRUITMENT TEST DATA ###'), ('job_id', '=', job_intern.id),]) self.assertEqual(len(internship_applicant), 1) self.assertEqual(internship_applicant.partner_name, 'Jack Doe') self.assertEqual(internship_applicant.email_from, '[email protected]') self.assertEqual(internship_applicant.partner_phone, '118.712')
49.058824
1,668
407
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class Department(models.Model): _inherit = 'hr.department' def name_get(self): # Get department name using superuser, because model is not accessible # for portal users self_sudo = self.sudo() return super(Department, self_sudo).name_get()
29.071429
407
497
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.addons.http_routing.models.ir_http import url_for class Website(models.Model): _inherit = "website" def get_suggested_controllers(self): suggested_controllers = super(Website, self).get_suggested_controllers() suggested_controllers.append((_('Jobs'), url_for('/jobs'), 'website_hr_recruitment')) return suggested_controllers
35.5
497
3,059
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from werkzeug import urls from odoo import api, fields, models, _ from odoo.tools.translate import html_translate from odoo.exceptions import UserError class RecruitmentSource(models.Model): _inherit = 'hr.recruitment.source' url = fields.Char(compute='_compute_url', string='Url Parameters') @api.depends('source_id', 'source_id.name', 'job_id', 'job_id.company_id') def _compute_url(self): for source in self: source.url = urls.url_join(source.job_id.get_base_url(), "%s?%s" % ( source.job_id.website_url, urls.url_encode({ 'utm_campaign': self.env.ref('hr_recruitment.utm_campaign_job').name, 'utm_medium': self.env.ref('utm.utm_medium_website').name, 'utm_source': source.source_id.name }) )) class Applicant(models.Model): _inherit = 'hr.applicant' def website_form_input_filter(self, request, values): if 'partner_name' in values: applicant_job = self.env['hr.job'].sudo().search([('id', '=', values['job_id'])]).name if 'job_id' in values else False name = '%s - %s' % (values['partner_name'], applicant_job) if applicant_job else _("%s's Application", values['partner_name']) values.setdefault('name', name) if values.get('job_id'): job = self.env['hr.job'].browse(values.get('job_id')) if not job.sudo().website_published: raise UserError(_("You cannot apply for this job.")) stage = self.env['hr.recruitment.stage'].sudo().search([ ('fold', '=', False), '|', ('job_ids', '=', False), ('job_ids', '=', values['job_id']), ], order='sequence asc', limit=1) if stage: values['stage_id'] = stage.id return values class Job(models.Model): _name = 'hr.job' _inherit = ['hr.job', 'website.seo.metadata', 'website.published.multi.mixin'] def _get_default_website_description(self): default_description = self.env.ref("website_hr_recruitment.default_website_description", raise_if_not_found=False) return (default_description._render() if default_description else "") website_published = fields.Boolean(help='Set if the application is published on the website of the company.') website_description = fields.Html('Website description', translate=html_translate, sanitize_attributes=False, default=_get_default_website_description, prefetch=False, sanitize_form=False) def _compute_website_url(self): super(Job, self)._compute_website_url() for job in self: job.website_url = "/jobs/detail/%s" % job.id def set_open(self): self.write({'website_published': False}) return super(Job, self).set_open() def get_backend_menu_id(self): return self.env.ref('hr_recruitment.menu_hr_recruitment_root').id
41.90411
3,059
4,651
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.addons.http_routing.models.ir_http import slug from odoo.http import request from werkzeug.exceptions import NotFound class WebsiteHrRecruitment(http.Controller): def sitemap_jobs(env, rule, qs): if not qs or qs.lower() in '/jobs': yield {'loc': '/jobs'} @http.route([ '/jobs', '/jobs/country/<model("res.country"):country>', '/jobs/department/<model("hr.department"):department>', '/jobs/country/<model("res.country"):country>/department/<model("hr.department"):department>', '/jobs/office/<int:office_id>', '/jobs/country/<model("res.country"):country>/office/<int:office_id>', '/jobs/department/<model("hr.department"):department>/office/<int:office_id>', '/jobs/country/<model("res.country"):country>/department/<model("hr.department"):department>/office/<int:office_id>', ], type='http', auth="public", website=True, sitemap=sitemap_jobs) def jobs(self, country=None, department=None, office_id=None, **kwargs): env = request.env(context=dict(request.env.context, show_address=True, no_tag_br=True)) Country = env['res.country'] Jobs = env['hr.job'] # List jobs available to current UID domain = request.website.website_domain() job_ids = Jobs.search(domain, order="is_published desc, sequence, no_of_recruitment desc").ids # Browse jobs as superuser, because address is restricted jobs = Jobs.sudo().browse(job_ids) # Default search by user country if not (country or department or office_id or kwargs.get('all_countries')): country_code = request.session['geoip'].get('country_code') if country_code: countries_ = Country.search([('code', '=', country_code)]) country = countries_[0] if countries_ else None if not any(j for j in jobs if j.address_id and j.address_id.country_id == country): country = False # Filter job / office for country if country and not kwargs.get('all_countries'): jobs = [j for j in jobs if not j.address_id or j.address_id.country_id.id == country.id] offices = set(j.address_id for j in jobs if not j.address_id or j.address_id.country_id.id == country.id) else: offices = set(j.address_id for j in jobs if j.address_id) # Deduce departments and countries offices of those jobs departments = set(j.department_id for j in jobs if j.department_id) countries = set(o.country_id for o in offices if o.country_id) if department: jobs = [j for j in jobs if j.department_id and j.department_id.id == department.id] if office_id and office_id in [x.id for x in offices]: jobs = [j for j in jobs if j.address_id and j.address_id.id == office_id] else: office_id = False # Render page return request.render("website_hr_recruitment.index", { 'jobs': jobs, 'countries': countries, 'departments': departments, 'offices': offices, 'country_id': country, 'department_id': department, 'office_id': office_id, }) @http.route('/jobs/add', type='http', auth="user", website=True) def jobs_add(self, **kwargs): # avoid branding of website_description by setting rendering_bundle in context job = request.env['hr.job'].with_context(rendering_bundle=True).create({ 'name': _('Job Title'), }) return request.redirect("/jobs/detail/%s?enable_editor=1" % slug(job)) @http.route('''/jobs/detail/<model("hr.job"):job>''', type='http', auth="public", website=True, sitemap=True) def jobs_detail(self, job, **kwargs): return request.render("website_hr_recruitment.detail", { 'job': job, 'main_object': job, }) @http.route('''/jobs/apply/<model("hr.job"):job>''', type='http', auth="public", website=True, sitemap=True) def jobs_apply(self, job, **kwargs): error = {} default = {} if 'website_hr_recruitment_error' in request.session: error = request.session.pop('website_hr_recruitment_error') default = request.session.pop('website_hr_recruitment_default') return request.render("website_hr_recruitment.apply", { 'job': job, 'error': error, 'default': default, })
46.049505
4,651
837
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "India Sales and Warehouse Management", 'icon': '/l10n_in/static/description/icon.png', 'summary': """ Define default sales journal on the warehouse""", 'description': """ Define default sales journal on the warehouse, help you to choose correct sales journal on the sales order when you change the warehouse. useful when you setup the multiple GSTIN units. """, 'author': "Odoo", 'website': "https://www.odoo.com", 'category': 'Accounting/Localizations/Sale', 'version': '0.1', 'depends': ['l10n_in_sale', 'l10n_in_stock'], 'data': [ 'views/stock_warehouse_views.xml', ], 'auto_install': True, 'license': 'LGPL-3', }
27.9
837
560
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class AccountMove(models.Model): _inherit = "account.move" def _l10n_in_get_warehouse_address(self): res = super()._l10n_in_get_warehouse_address() if self.invoice_line_ids.sale_line_ids: company_shipping_id = self.mapped("invoice_line_ids.sale_line_ids.order_id.warehouse_id.partner_id") if len(company_shipping_id) == 1: return company_shipping_id return res
35
560
288
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class Stock(models.Model): _inherit = 'stock.warehouse' l10n_in_sale_journal_id = fields.Many2one('account.journal', string="Sale Journal")
28.8
288
577
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class SaleOrder(models.Model): _inherit = "sale.order" @api.depends('company_id', 'warehouse_id') def _compute_l10n_in_journal_id(self): super()._compute_l10n_in_journal_id() for order in self: if order.l10n_in_company_country_code == 'IN': if order.warehouse_id.l10n_in_sale_journal_id: order.l10n_in_journal_id = order.warehouse_id.l10n_in_sale_journal_id.id
36.0625
577
584
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Mass Mail Tests', 'version': '1.0', 'category': 'Hidden', 'sequence': 8765, 'summary': 'Mass Mail Tests: feature and performance tests for mass mailing', 'description': """This module contains tests related to mass mailing. Those are present in a separate module to use specific test models defined in test_mail. """, 'depends': ['test_mail', 'mass_mailing'], 'data': [ 'security/ir.model.access.csv', ], 'demo': [ ], 'installable': True, 'application': False, 'license': 'LGPL-3', }
27.809524
584
3,882
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from freezegun import freeze_time from unittest.mock import patch from odoo.addons.mass_mailing.models.mail_thread import BLACKLIST_MAX_BOUNCED_LIMIT from odoo.addons.test_mass_mailing.tests import common from odoo.tests import tagged from odoo.tests.common import users from odoo.tools import mute_logger from odoo.sql_db import Cursor @tagged('mail_blacklist') class TestAutoBlacklist(common.TestMassMailCommon): @classmethod def setUpClass(cls): super(TestAutoBlacklist, cls).setUpClass() cls.target_rec = cls._create_mailing_test_records()[0] cls.mailing_bl.write({'mailing_domain': [('id', 'in', cls.target_rec.ids)]}) @users('user_marketing') def test_mailing_bounce_w_auto_bl(self): self._test_mailing_bounce_w_auto_bl(None) @users('user_marketing') def test_mailing_bounce_w_auto_bl_partner(self): bounced_partner = self.env['res.partner'].sudo().create({ 'name': 'Bounced Partner', 'email': self.target_rec.email_from, 'message_bounce': BLACKLIST_MAX_BOUNCED_LIMIT, }) self._test_mailing_bounce_w_auto_bl({'bounced_partner': bounced_partner}) @users('user_marketing') def test_mailing_bounce_w_auto_bl_partner_duplicates(self): bounced_partners = self.env['res.partner'].sudo().create({ 'name': 'Bounced Partner1', 'email': self.target_rec.email_from, 'message_bounce': BLACKLIST_MAX_BOUNCED_LIMIT, }) | self.env['res.partner'].sudo().create({ 'name': 'Bounced Partner2', 'email': self.target_rec.email_from, 'message_bounce': BLACKLIST_MAX_BOUNCED_LIMIT, }) self._test_mailing_bounce_w_auto_bl({'bounced_partner': bounced_partners}) @mute_logger('odoo.addons.mail.models.mail_thread') def _test_mailing_bounce_w_auto_bl(self, bounce_base_values): mailing = self.mailing_bl.with_env(self.env) target = self.target_rec.with_env(self.env) # create bounced history of 4 statistics traces = self.env['mailing.trace'] for idx in range(4): new_mailing = mailing.copy() new_dt = datetime.datetime.now() - datetime.timedelta(weeks=idx+2) # Cursor.now() uses transaction's timestamp and not datetime lib -> freeze_time # is not sufficient with freeze_time(new_dt), patch.object(Cursor, 'now', lambda *args, **kwargs: new_dt): traces += self._create_bounce_trace(new_mailing, target, dt=datetime.datetime.now() - datetime.timedelta(weeks=idx+2)) self.gateway_mail_bounce(new_mailing, target, bounce_base_values) # mass mail record: ok, not blacklisted yet with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() self.assertMailTraces( [{'email': '[email protected]'}], mailing, target, check_mail=True ) # call bounced self.gateway_mail_bounce(mailing, target, bounce_base_values) # check blacklist blacklist_record = self.env['mail.blacklist'].sudo().search([('email', '=', target.email_normalized)]) self.assertEqual(len(blacklist_record), 1) self.assertTrue(target.is_blacklisted) # mass mail record: ko, blacklisted new_mailing = mailing.copy({'mailing_domain': [('id', 'in', target.ids)]}) with self.mock_mail_gateway(mail_unlink_sent=False): new_mailing.action_send_mail() self.assertMailTraces( [{'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_bl'}], new_mailing, target, check_mail=True )
41.741935
3,882
18,930
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.test_mass_mailing.data.mail_test_data import MAIL_TEMPLATE from odoo.addons.test_mass_mailing.tests.common import TestMassMailCommon from odoo.tests import tagged from odoo.tests.common import users from odoo.tools import mute_logger, email_normalize @tagged('mass_mailing') class TestMassMailing(TestMassMailCommon): @classmethod def setUpClass(cls): super(TestMassMailing, cls).setUpClass() @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_thread') def test_mailing_gateway_reply(self): customers = self.env['res.partner'] for x in range(0, 3): customers |= self.env['res.partner'].create({ 'name': 'Customer_%02d' % x, 'email': '"Customer_%02d" <customer_%[email protected]' % (x, x), }) mailing = self.env['mailing.mailing'].create({ 'name': 'TestName', 'subject': 'TestSubject', 'body_html': 'Hello <t t-out="object.name" />', 'reply_to_mode': 'new', 'reply_to': '%s@%s' % (self.test_alias.alias_name, self.test_alias.alias_domain), 'keep_archives': True, 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'mailing_domain': '%s' % [('id', 'in', customers.ids)], }) mailing.action_put_in_queue() with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() self.gateway_mail_reply_wrecord(MAIL_TEMPLATE, customers[0], use_in_reply_to=True) self.gateway_mail_reply_wrecord(MAIL_TEMPLATE, customers[1], use_in_reply_to=False) # customer2 looses headers mail_mail = self._find_mail_mail_wrecord(customers[2]) self.format_and_process( MAIL_TEMPLATE, mail_mail.email_to, mail_mail.reply_to, subject='Re: %s' % mail_mail.subject, extra='', msg_id='<123456.%s.%[email protected]>' % (customers[2]._name, customers[2].id), target_model=customers[2]._name, target_field=customers[2]._rec_name, ) mailing.flush() # check traces status traces = self.env['mailing.trace'].search([('model', '=', customers._name), ('res_id', 'in', customers.ids)]) self.assertEqual(len(traces), 3) customer0_trace = traces.filtered(lambda t: t.res_id == customers[0].id) self.assertEqual(customer0_trace.trace_status, 'reply') customer1_trace = traces.filtered(lambda t: t.res_id == customers[1].id) self.assertEqual(customer1_trace.trace_status, 'reply') customer2_trace = traces.filtered(lambda t: t.res_id == customers[2].id) self.assertEqual(customer2_trace.trace_status, 'sent') # check mailing statistics self.assertEqual(mailing.sent, 3) self.assertEqual(mailing.delivered, 3) self.assertEqual(mailing.opened, 2) self.assertEqual(mailing.replied, 2) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_gateway_update(self): mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids) recipients = self._create_mailing_test_records(model='mailing.test.optout', count=5) self.assertEqual(len(recipients), 5) mailing.write({ 'mailing_model_id': self.env['ir.model']._get('mailing.test.optout'), 'mailing_domain': [('id', 'in', recipients.ids)] }) with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() self.assertMailTraces( [{'email': record.email_normalized} for record in recipients], mailing, recipients, mail_links_info=[[ ('url0', 'https://www.odoo.tz/my/%s' % record.name, True, {}), ('url1', 'https://www.odoo.be', True, {}), ('url2', 'https://www.odoo.com', True, {}), ('url3', 'https://www.odoo.eu', True, {}), ('url4', 'https://www.example.com/foo/bar?baz=qux', True, {'baz': 'qux'}), ('url5', '%s/event/dummy-event-0' % mailing.get_base_url(), True, {}), # view is not shortened and parsed at sending ('url6', '%s/view' % mailing.get_base_url(), False, {}), ('url7', 'mailto:[email protected]', False, {}), # unsubscribe is not shortened and parsed at sending ('url8', '%s/unsubscribe_from_list' % mailing.get_base_url(), False, {}), ] for record in recipients], check_mail=True ) self.assertMailingStatistics(mailing, expected=5, delivered=5, sent=5) # simulate a click self.gateway_mail_click(mailing, recipients[0], 'https://www.odoo.be') mailing.invalidate_cache() self.assertMailingStatistics(mailing, expected=5, delivered=5, sent=5, opened=1, clicked=1) # simulate a bounce self.assertEqual(recipients[1].message_bounce, 0) self.gateway_mail_bounce(mailing, recipients[1]) mailing.invalidate_cache() self.assertMailingStatistics(mailing, expected=5, delivered=4, sent=5, opened=1, clicked=1, bounced=1) self.assertEqual(recipients[1].message_bounce, 1) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_reply_to_mode_new(self): mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids) recipients = self._create_mailing_test_records(model='mailing.test.blacklist', count=5) self.assertEqual(len(recipients), 5) initial_messages = recipients.message_ids mailing.write({ 'mailing_domain': [('id', 'in', recipients.ids)], 'keep_archives': False, 'reply_to_mode': 'new', 'reply_to': self.test_alias.display_name, }) with self.mock_mail_gateway(mail_unlink_sent=True): mailing.action_send_mail() answer_rec = self.gateway_mail_reply_wemail(MAIL_TEMPLATE, recipients[0].email_normalized, target_model=self.test_alias.alias_model_id.model) self.assertTrue(bool(answer_rec)) self.assertEqual(answer_rec.name, 'Re: %s' % mailing.subject) self.assertEqual( answer_rec.message_ids.subject, 'Re: %s' % mailing.subject, 'Answer should be logged') self.assertEqual(recipients.message_ids, initial_messages) self.assertMailingStatistics(mailing, expected=5, delivered=5, sent=5, opened=1, replied=1) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_reply_to_mode_update(self): mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids) recipients = self._create_mailing_test_records(model='mailing.test.blacklist', count=5) self.assertEqual(len(recipients), 5) mailing.write({ 'mailing_domain': [('id', 'in', recipients.ids)], 'keep_archives': False, 'reply_to_mode': 'update', 'reply_to': self.test_alias.display_name, }) with self.mock_mail_gateway(mail_unlink_sent=True): mailing.action_send_mail() answer_rec = self.gateway_mail_reply_wemail(MAIL_TEMPLATE, recipients[0].email_normalized, target_model=self.test_alias.alias_model_id.model) self.assertFalse(bool(answer_rec)) self.assertEqual( recipients[0].message_ids[1].subject, mailing.subject, 'Should have keep a log (to enable thread-based answer)') self.assertEqual( recipients[0].message_ids[0].subject, 'Re: %s' % mailing.subject, 'Answer should be logged') self.assertMailingStatistics(mailing, expected=5, delivered=5, sent=5, opened=1, replied=1) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_thread') def test_mailing_trace_utm(self): """ Test mailing UTMs are caught on reply""" self._create_mailing_list() self.test_alias.write({ 'alias_model_id': self.env['ir.model']._get('mailing.test.utm').id }) source = self.env['utm.source'].create({'name': 'Source test'}) medium = self.env['utm.medium'].create({'name': 'Medium test'}) campaign = self.env['utm.campaign'].create({'name': 'Campaign test'}) subject = 'MassMailingTestUTM' mailing = self.env['mailing.mailing'].create({ 'name': 'UTMTest', 'subject': subject, 'body_html': '<p>Hello <t t-out="object.name"/></p>', 'reply_to_mode': 'new', 'reply_to': '%s@%s' % (self.test_alias.alias_name, self.test_alias.alias_domain), 'keep_archives': True, 'mailing_model_id': self.env['ir.model']._get('mailing.list').id, 'contact_list_ids': [(4, self.mailing_list_1.id)], 'source_id': source.id, 'medium_id': medium.id, 'campaign_id': campaign.id }) with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() traces = self.env['mailing.trace'].search([('model', '=', self.mailing_list_1.contact_ids._name), ('res_id', 'in', self.mailing_list_1.contact_ids.ids)]) self.assertEqual(len(traces), 3) # simulate response to mailing self.gateway_mail_reply_wrecord(MAIL_TEMPLATE, self.mailing_list_1.contact_ids[0], use_in_reply_to=True) self.gateway_mail_reply_wrecord(MAIL_TEMPLATE, self.mailing_list_1.contact_ids[1], use_in_reply_to=False) mailing_test_utms = self.env['mailing.test.utm'].search([('name', '=', 'Re: %s' % subject)]) self.assertEqual(len(mailing_test_utms), 2) for test_utm in mailing_test_utms: self.assertEqual(test_utm.campaign_id, campaign) self.assertEqual(test_utm.source_id, source) self.assertEqual(test_utm.medium_id, medium) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_w_blacklist(self): mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids) recipients = self._create_mailing_test_records(count=5) # blacklist records 2, 3, 4 self.env['mail.blacklist'].create({'email': recipients[2].email_normalized}) self.env['mail.blacklist'].create({'email': recipients[3].email_normalized}) self.env['mail.blacklist'].create({'email': recipients[4].email_normalized}) # unblacklist record 2 self.env['mail.blacklist'].action_remove_with_reason( recipients[2].email_normalized, "human error" ) self.env['mail.blacklist'].flush(['active']) mailing.write({'mailing_domain': [('id', 'in', recipients.ids)]}) with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() self.assertMailTraces( [{'email': '[email protected]'}, {'email': '[email protected]'}, {'email': '[email protected]'}, {'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_bl'}, {'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_bl'}], mailing, recipients, check_mail=True ) self.assertEqual(mailing.canceled, 2) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_w_blacklist_nomixin(self): """Test that blacklist is applied even if the target model doesn't inherit from mail.thread.blacklist.""" test_records = self._create_mailing_test_records(model='mailing.test.simple', count=2) self.mailing_bl.write({ 'mailing_domain': [('id', 'in', test_records.ids)], 'mailing_model_id': self.env['ir.model']._get('mailing.test.simple').id, }) self.env['mail.blacklist'].create([{ 'email': test_records[0].email_from, 'active': True, }]) with self.mock_mail_gateway(mail_unlink_sent=False): self.mailing_bl.action_send_mail() self.assertMailTraces([ {'email': email_normalize(test_records[0].email_from), 'trace_status': 'cancel', 'failure_type': 'mail_bl'}, {'email': email_normalize(test_records[1].email_from), 'trace_status': 'sent'}, ], self.mailing_bl, test_records, check_mail=False) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_w_opt_out(self): mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids) recipients = self._create_mailing_test_records(model='mailing.test.optout', count=5) # optout records 0 and 1 (recipients[0] | recipients[1]).write({'opt_out': True}) # blacklist records 4 self.env['mail.blacklist'].create({'email': recipients[4].email_normalized}) mailing.write({ 'mailing_model_id': self.env['ir.model']._get('mailing.test.optout'), 'mailing_domain': [('id', 'in', recipients.ids)] }) with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() self.assertMailTraces( [{'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_optout'}, {'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_optout'}, {'email': '[email protected]'}, {'email': '[email protected]'}, {'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_bl'}], mailing, recipients, check_mail=True ) self.assertEqual(mailing.canceled, 3) @users('user_marketing') def test_mailing_w_seenlist_unstored_partner(self): """ Test seen list when partners are not stored. """ test_customers = self.env['res.partner'].sudo().create([ {'email': f'"Mailing Partner {idx}" <email.from.{idx}@test.example.com', 'name': f'Mailing Partner {idx}', } for idx in range(8) ]) test_records = self.env['mailing.test.partner.unstored'].create([ {'email_from': f'email.from.{idx}@test.example.com', 'name': f'Mailing Record {idx}', } for idx in range(10) ]) self.assertEqual(test_records[:8].partner_id, test_customers) self.assertFalse(test_records[9:].partner_id) mailing = self.env['mailing.mailing'].create({ 'body_html': '<p>Marketing stuff for ${object.name}</p>', 'mailing_domain': [('id', 'in', test_records.ids)], 'mailing_model_id': self.env['ir.model']._get_id('mailing.test.partner.unstored'), 'name': 'test', 'subject': 'Blacklisted', }) # create existing traces to check the seen list traces = self._create_sent_traces( mailing, test_records[:3] ) traces.flush() # check remaining recipients effectively check seen list mailing.action_put_in_queue() res_ids = mailing._get_remaining_recipients() self.assertEqual(sorted(res_ids), sorted(test_records[3:].ids)) with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() self.assertEqual(len(self._mails), 7, 'Mailing: seen list should contain 3 existing traces') @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_mailing_list_optout(self): """ Test mailing list model specific optout behavior """ mailing_contact_1 = self.env['mailing.contact'].create({'name': 'test 1A', 'email': '[email protected]'}) mailing_contact_2 = self.env['mailing.contact'].create({'name': 'test 1B', 'email': '[email protected]'}) mailing_contact_3 = self.env['mailing.contact'].create({'name': 'test 3', 'email': '[email protected]'}) mailing_contact_4 = self.env['mailing.contact'].create({'name': 'test 4', 'email': '[email protected]'}) mailing_contact_5 = self.env['mailing.contact'].create({'name': 'test 5', 'email': '[email protected]'}) # create mailing list record mailing_list_1 = self.env['mailing.list'].create({ 'name': 'A', 'contact_ids': [ (4, mailing_contact_1.id), (4, mailing_contact_2.id), (4, mailing_contact_3.id), (4, mailing_contact_5.id), ] }) mailing_list_2 = self.env['mailing.list'].create({ 'name': 'B', 'contact_ids': [ (4, mailing_contact_3.id), (4, mailing_contact_4.id), ] }) # contact_1 is optout but same email is not optout from the same list # contact 3 is optout in list 1 but not in list 2 # contact 5 is optout subs = self.env['mailing.contact.subscription'].search([ '|', '|', '&', ('contact_id', '=', mailing_contact_1.id), ('list_id', '=', mailing_list_1.id), '&', ('contact_id', '=', mailing_contact_3.id), ('list_id', '=', mailing_list_1.id), '&', ('contact_id', '=', mailing_contact_5.id), ('list_id', '=', mailing_list_1.id) ]) subs.write({'opt_out': True}) # create mass mailing record mailing = self.env['mailing.mailing'].create({ 'name': 'SourceName', 'subject': 'MailingSubject', 'body_html': '<p>Hello <t t-out="object.name"/></p>', 'mailing_model_id': self.env['ir.model']._get('mailing.list').id, 'contact_list_ids': [(4, ml.id) for ml in mailing_list_1 | mailing_list_2], }) with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() self.assertMailTraces( [{'email': '[email protected]', 'trace_status': 'sent'}, {'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_dup'}, {'email': '[email protected]'}, {'email': '[email protected]'}, {'email': '[email protected]', 'trace_status': 'cancel', 'failure_type': 'mail_optout'}], mailing, mailing_contact_1 + mailing_contact_2 + mailing_contact_3 + mailing_contact_4 + mailing_contact_5, check_mail=True ) self.assertEqual(mailing.canceled, 2)
47.325
18,930
2,477
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import users from odoo.addons.test_mass_mailing.tests import common class TestLinkTracker(common.TestMassMailCommon): def setUp(self): super(TestLinkTracker, self).setUp() self.link = self.env['link.tracker'].search_or_create({ 'url': 'https://www.example.com' }) self.click = self.env['link.tracker.click'].create({ 'link_id': self.link.id, 'ip': '100.00.00.00', 'country_id': self.env.ref('base.fr').id, }) def test_add_link(self): code = self.link.code self.assertEqual(self.link.count, 1) # click from a new IP should create a new entry click = self.env['link.tracker.click'].sudo().add_click( code, ip='100.00.00.01', country_code='BEL' ) self.assertEqual(click.ip, '100.00.00.01') self.assertEqual(click.country_id, self.env.ref('base.be')) self.assertEqual(self.link.count, 2) # click from same IP (even another country) does not create a new entry click = self.env['link.tracker.click'].sudo().add_click( code, ip='100.00.00.01', country_code='FRA' ) self.assertEqual(click, None) self.assertEqual(self.link.count, 2) @users('user_marketing') def test_add_link_mail_stat(self): record = self.env['mailing.test.blacklist'].create({}) code = self.link.code self.assertEqual(self.link.count, 1) trace = self.env['mailing.trace'].create({ 'mass_mailing_id': self.mailing_bl.id, 'model': record._name, 'res_id': record.id, }) self.assertEqual(trace.trace_status, 'outgoing') self.assertFalse(trace.links_click_datetime) # click from a new IP should create a new entry and update stat when provided click = self.env['link.tracker.click'].sudo().add_click( code, ip='100.00.00.01', country_code='BEL', mailing_trace_id=trace.id ) self.assertEqual(self.link.count, 2) self.assertEqual(click.mass_mailing_id, self.mailing_bl) self.assertTrue(trace.trace_status, 'open') self.assertTrue(trace.links_click_datetime) self.assertEqual(trace.links_click_ids, click)
35.385714
2,477
5,139
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import html from odoo.addons.mail.tests.common import mail_new_test_user from odoo.addons.test_mass_mailing.data.mail_test_data import MAIL_TEMPLATE from odoo.addons.test_mass_mailing.tests.common import TestMassMailCommon from odoo.tests.common import users from odoo.tests import tagged from odoo.tools import formataddr, mute_logger @tagged('digest') class TestMailingStatistics(TestMassMailCommon): @classmethod def setUpClass(cls): super(TestMailingStatistics, cls).setUpClass() cls.user_marketing_2 = mail_new_test_user( cls.env, groups='base.group_user,base.group_partner_manager,mass_mailing.group_mass_mailing_user', login='user_marketing_2', name='Marie Marketing', signature='--\nMarie' ) @users('user_marketing') @mute_logger('odoo.addons.mass_mailing.models.mailing', 'odoo.addons.mail.models.mail_mail', 'odoo.addons.mail.models.mail_thread') def test_mailing_statistics(self): target_records = self._create_mailing_test_records(model='mailing.test.blacklist', count=10) mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids) mailing.write({'mailing_domain': [('id', 'in', target_records.ids)], 'user_id': self.user_marketing_2.id}) mailing.action_put_in_queue() with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() # simulate some replies and clicks self.gateway_mail_reply_wrecord(MAIL_TEMPLATE, target_records[0], use_in_reply_to=True) self.gateway_mail_reply_wrecord(MAIL_TEMPLATE, target_records[1], use_in_reply_to=True) self.gateway_mail_reply_wrecord(MAIL_TEMPLATE, target_records[2], use_in_reply_to=True) self.gateway_mail_click(mailing, target_records[0], 'https://www.odoo.be') self.gateway_mail_click(mailing, target_records[2], 'https://www.odoo.be') self.gateway_mail_click(mailing, target_records[3], 'https://www.odoo.be') # check mailing statistics self.assertEqual(mailing.clicked, 3) self.assertEqual(mailing.delivered, 10) self.assertEqual(mailing.opened, 4) self.assertEqual(mailing.opened_ratio, 40) self.assertEqual(mailing.replied, 3) self.assertEqual(mailing.replied_ratio, 30) self.assertEqual(mailing.sent, 10) with self.mock_mail_gateway(mail_unlink_sent=True): mailing._action_send_statistics() self.assertEqual(len(self._new_mails), 1, "Mailing: a mail should have been created for statistics") mail = self._new_mails[0] # test email values self.assertEqual(mail.author_id, self.user_marketing_2.partner_id) self.assertEqual(mail.email_from, self.user_marketing_2.email_formatted) self.assertEqual(mail.email_to, self.user_marketing_2.email_formatted) self.assertEqual(mail.reply_to, self.company_admin.partner_id.email_formatted) self.assertEqual(mail.state, 'outgoing') # test body content: KPIs body_html = html.fromstring(mail.body_html) kpi_values = body_html.xpath('//div[@data-field="mail"]//*[hasclass("kpi_value")]/text()') self.assertEqual( [t.strip().strip('%') for t in kpi_values], ['100', str(mailing.opened_ratio), str(mailing.replied_ratio)] ) # test body content: clicks (a bit hackish but hey we are in stable) kpi_click_values = body_html.xpath('//div[hasclass("global_layout")]/table//tr[contains(@style,"color: #888888")]/td[contains(@style,"width: 30%")]/text()') first_link_value = int(kpi_click_values[0].strip().split()[1].strip('()')) self.assertEqual(first_link_value, mailing.clicked) @users('user_marketing') @mute_logger('odoo.addons.mass_mailing.models.mailing', 'odoo.addons.mail.models.mail_mail', 'odoo.addons.mail.models.mail_thread') def test_mailing_statistics_wo_user(self): target_records = self._create_mailing_test_records(model='mailing.test.blacklist', count=10) mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids) mailing.write({'mailing_domain': [('id', 'in', target_records.ids)], 'user_id': False}) mailing.action_put_in_queue() with self.mock_mail_gateway(mail_unlink_sent=False): mailing.action_send_mail() with self.mock_mail_gateway(mail_unlink_sent=False): mailing._action_send_statistics() self.assertEqual(len(self._new_mails), 1, "Mailing: a mail should have been created for statistics") mail = self._new_mails[0] # test email values self.assertEqual(mail.author_id, self.user_marketing.partner_id) self.assertEqual(mail.email_from, self.user_marketing.email_formatted) self.assertEqual(mail.email_to, self.user_marketing.email_formatted) self.assertEqual(mail.reply_to, self.company_admin.partner_id.email_formatted) self.assertEqual(mail.state, 'outgoing')
51.909091
5,139
6,402
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import users from odoo.addons.test_mass_mailing.tests import common from odoo.exceptions import AccessError class TestBLAccessRights(common.TestMassMailCommon): @classmethod def setUpClass(cls): super(TestBLAccessRights, cls).setUpClass() cls._create_portal_user() cls.bl_rec = cls.env['mail.blacklist'].create([ {'email': 'Not A Stark <[email protected]>'}, ]) cls.bl_previous = cls.env['mail.blacklist'].search([]) @users('employee') def test_bl_crud_employee(self): with self.assertRaises(AccessError): self.env['mail.blacklist'].create([{'email': '[email protected]'}]) with self.assertRaises(AccessError): self.bl_rec.with_user(self.env.user).read([]) with self.assertRaises(AccessError): self.bl_rec.with_user(self.env.user).write({'email': '[email protected]'}) with self.assertRaises(AccessError): self.bl_rec.with_user(self.env.user).unlink() @users('portal_test') def test_bl_crud_portal(self): with self.assertRaises(AccessError): self.env['mail.blacklist'].create([{'email': '[email protected]'}]) with self.assertRaises(AccessError): self.bl_rec.with_user(self.env.user).read([]) with self.assertRaises(AccessError): self.bl_rec.with_user(self.env.user).write({'email': '[email protected]'}) with self.assertRaises(AccessError): self.bl_rec.with_user(self.env.user).unlink() @users('user_marketing') def test_bl_crud_marketing(self): self.env['mail.blacklist'].create([{'email': '[email protected]'}]) read_res = self.bl_rec.with_user(self.env.user).read([]) self.assertEqual(read_res[0]['id'], self.bl_rec.id) self.bl_rec.with_user(self.env.user).write({'email': '[email protected]'}) self.assertEqual(self.bl_rec.email, '[email protected]') self.bl_rec.with_user(self.env.user).unlink() class TestBLConsistency(common.TestMassMailCommon): _base_list = ['[email protected]', '[email protected]'] def setUp(self): super(TestBLConsistency, self).setUp() self.bl_rec = self.env['mail.blacklist'].create([ {'email': 'Not A Stark <[email protected]>'}, ]) self.bl_previous = self.env['mail.blacklist'].search([]) @users('user_marketing') def test_bl_check_case_add(self): """ Test emails case when adding through _add """ bl_sudo = self.env['mail.blacklist'].sudo() existing = bl_sudo.create({ 'email': '[email protected]', 'active': False, }) added = self.env['mail.blacklist']._add('[email protected]') self.assertEqual(existing, added) self.assertTrue(existing.active) @users('user_marketing') def test_bl_check_case_remove(self): """ Test emails case when deactivating through _remove """ bl_sudo = self.env['mail.blacklist'].sudo() existing = bl_sudo.create({ 'email': '[email protected]', 'active': True, }) added = self.env['mail.blacklist']._remove('[email protected]') self.assertEqual(existing, added) self.assertFalse(existing.active) @users('user_marketing') def test_bl_create_duplicate(self): """ Test emails are inserted only once if duplicated """ bl_sudo = self.env['mail.blacklist'].sudo() self.env['mail.blacklist'].create([ {'email': self._base_list[0]}, {'email': self._base_list[1]}, {'email': 'Another Ned Stark <%s>' % self._base_list[1]}, ]) new_bl = bl_sudo.search([('id', 'not in', self.bl_previous.ids)]) self.assertEqual(len(new_bl), 2) self.assertEqual( set(v.lower() for v in self._base_list), set(v.lower() for v in new_bl.mapped('email')) ) @users('user_marketing') def test_bl_create_parsing(self): """ Test email is correctly extracted from given entries """ bl_sudo = self.env['mail.blacklist'].sudo() self.env['mail.blacklist'].create([ {'email': self._base_list[0]}, {'email': self._base_list[1]}, {'email': 'Not Ned Stark <[email protected]>'}, ]) new_bl = bl_sudo.search([('id', 'not in', self.bl_previous.ids)]) self.assertEqual(len(new_bl), 3) self.assertEqual( set(v.lower() for v in self._base_list + ['[email protected]']), set(v.lower() for v in new_bl.mapped('email')) ) @users('user_marketing') def test_bl_search_exact(self): search_res = self.env['mail.blacklist'].search([('email', '=', '[email protected]')]) self.assertEqual(search_res, self.bl_rec) @users('user_marketing') def test_bl_search_parsing(self): search_res = self.env['mail.blacklist'].search([('email', '=', 'Not A Stark <[email protected]>')]) self.assertEqual(search_res, self.bl_rec) search_res = self.env['mail.blacklist'].search([('email', '=', '"John J. Snow" <[email protected]>')]) self.assertEqual(search_res, self.bl_rec) search_res = self.env['mail.blacklist'].search([('email', '=', 'Aegon? <[email protected]>')]) self.assertEqual(search_res, self.bl_rec) search_res = self.env['mail.blacklist'].search([('email', '=', '"John; \"You know Nothing\" Snow" <[email protected]>')]) self.assertEqual(search_res, self.bl_rec) @users('user_marketing') def test_bl_search_case(self): search_res = self.env['mail.blacklist'].search([('email', '=', '[email protected]>')]) self.assertEqual(search_res, self.bl_rec) @users('user_marketing') def test_bl_search_partial(self): search_res = self.env['mail.blacklist'].search([('email', 'ilike', 'John')]) self.assertEqual(search_res, self.bl_rec) search_res = self.env['mail.blacklist'].search([('email', 'ilike', '[email protected]>')]) self.assertEqual(search_res, self.bl_rec)
38.8
6,402
4,679
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mail.tests.common import mail_new_test_user from odoo.tests.common import TransactionCase, users, warmup from odoo.tests import tagged from odoo.tools import mute_logger @tagged('mail_performance', 'post_install', '-at_install') class TestMassMailPerformanceBase(TransactionCase): def setUp(self): super(TestMassMailPerformanceBase, self).setUp() self.user_employee = mail_new_test_user( self.env, login='emp', groups='base.group_user', name='Ernest Employee', notification_type='inbox') self.user_marketing = mail_new_test_user( self.env, login='marketing', groups='base.group_user,mass_mailing.group_mass_mailing_user', name='Martial Marketing', signature='--\nMartial') # setup mail gateway self.alias_domain = 'example.com' self.alias_catchall = 'catchall.test' self.alias_bounce = 'bounce.test' self.default_from = 'notifications' self.env['ir.config_parameter'].set_param('mail.bounce.alias', self.alias_bounce) self.env['ir.config_parameter'].set_param('mail.catchall.domain', self.alias_domain) self.env['ir.config_parameter'].set_param('mail.catchall.alias', self.alias_catchall) self.env['ir.config_parameter'].set_param('mail.default.from', self.default_from) # patch registry to simulate a ready environment self.patch(self.env.registry, 'ready', True) @tagged('mail_performance', 'post_install', '-at_install') class TestMassMailPerformance(TestMassMailPerformanceBase): def setUp(self): super(TestMassMailPerformance, self).setUp() values = [{ 'name': 'Recipient %s' % x, 'email_from': 'Recipient <rec.%[email protected]>' % x, } for x in range(0, 50)] self.mm_recs = self.env['mailing.performance'].create(values) @users('__system__', 'marketing') @warmup @mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink', 'odoo.tests') def test_send_mailing(self): mailing = self.env['mailing.mailing'].create({ 'name': 'Test', 'subject': 'Test', 'body_html': '<p>Hello <a role="button" href="https://www.example.com/foo/bar?baz=qux">quux</a><a role="button" href="/unsubscribe_from_list">Unsubscribe</a></p>', 'reply_to_mode': 'new', 'mailing_model_id': self.ref('test_mass_mailing.model_mailing_performance'), 'mailing_domain': [('id', 'in', self.mm_recs.ids)], }) # runbot needs +151 compared to local with self.assertQueryCount(__system__=1672, marketing=1673): # tmm 1521/1522 mailing.action_send_mail() self.assertEqual(mailing.sent, 50) self.assertEqual(mailing.delivered, 50) @tagged('mail_performance', 'post_install', '-at_install') class TestMassMailBlPerformance(TestMassMailPerformanceBase): def setUp(self): """ In this setup we prepare 20 blacklist entries. We therefore add 20 recipients compared to first test in order to have comparable results. """ super(TestMassMailBlPerformance, self).setUp() values = [{ 'name': 'Recipient %s' % x, 'email_from': 'Recipient <rec.%[email protected]>' % x, } for x in range(0, 62)] self.mm_recs = self.env['mailing.performance.blacklist'].create(values) for x in range(1, 13): self.env['mail.blacklist'].create({ 'email': 'rec.%[email protected]' % (x * 5) }) self.env['mailing.performance.blacklist'].flush() @users('__system__', 'marketing') @warmup @mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink', 'odoo.tests') def test_send_mailing_w_bl(self): mailing = self.env['mailing.mailing'].create({ 'name': 'Test', 'subject': 'Test', 'body_html': '<p>Hello <a role="button" href="https://www.example.com/foo/bar?baz=qux">quux</a><a role="button" href="/unsubscribe_from_list">Unsubscribe</a></p>', 'reply_to_mode': 'new', 'mailing_model_id': self.ref('test_mass_mailing.model_mailing_performance_blacklist'), 'mailing_domain': [('id', 'in', self.mm_recs.ids)], }) # runbot needs +175 compared to local with self.assertQueryCount(__system__=1961, marketing=1962): # tmm 1786/1787 mailing.action_send_mail() self.assertEqual(mailing.sent, 50) self.assertEqual(mailing.delivered, 50)
42.926606
4,679
3,254
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.addons.test_mail.tests.common import TestMailCommon class TestMassMailCommon(MassMailCommon, TestMailCommon): @classmethod def setUpClass(cls): super(TestMassMailCommon, cls).setUpClass() cls.test_alias = cls.env['mail.alias'].create({ 'alias_name': 'test.alias', 'alias_user_id': False, 'alias_model_id': cls.env['ir.model']._get('mailing.test.simple').id, 'alias_contact': 'everyone' }) # enforce last update by user_marketing to match _process_mass_mailing_queue # taking last writer as user running a batch cls.mailing_bl = cls.env['mailing.mailing'].with_user(cls.user_marketing).create({ 'name': 'SourceName', 'subject': 'MailingSubject', # `+ ""` is for insuring that _prepend_preview rule out that case 'preview': 'Hi {{ object.name + "" }} :)', 'body_html': """<div><p>Hello <t t-out="object.name"/></p>, <t t-set="url" t-value="'www.odoo.com'"/> <t t-set="httpurl" t-value="'https://www.odoo.eu'"/>f <span>Website0: <a id="url0" t-attf-href="https://www.odoo.tz/my/{{object.name}}">https://www.odoo.tz/my/<t t-out="object.name"/></a></span> <span>Website1: <a id="url1" href="https://www.odoo.be">https://www.odoo.be</a></span> <span>Website2: <a id="url2" t-attf-href="https://{{url}}">https://<t t-out="url"/></a></span> <span>Website3: <a id="url3" t-att-href="httpurl"><t t-out="httpurl"/></a></span> <span>External1: <a id="url4" href="https://www.example.com/foo/bar?baz=qux">Youpie</a></span> <span>Internal1: <a id="url5" href="/event/dummy-event-0">Internal link</a></span> <span>Internal2: <a id="url6" href="/view"/>View link</a></span> <span>Email: <a id="url7" href="mailto:[email protected]">[email protected]</a></span> <p>Stop spam ? <a id="url8" role="button" href="/unsubscribe_from_list">Ok</a></p> </div>""", 'mailing_type': 'mail', 'mailing_model_id': cls.env['ir.model']._get('mailing.test.blacklist').id, 'reply_to_mode': 'update', }) @classmethod def _create_test_blacklist_records(cls, model='mailing.test.blacklist', count=1): """ Deprecated, remove in 14.4 """ return cls.__create_mailing_test_records(model=model, count=count) @classmethod def _create_mailing_test_records(cls, model='mailing.test.blacklist', partners=None, count=1): """ Helper to create data. Currently simple, to be improved. """ Model = cls.env[model] email_field = 'email' if 'email' in Model else 'email_from' partner_field = 'customer_id' if 'customer_id' in Model else 'partner_id' vals_list = [] for x in range(0, count): vals = { 'name': 'TestRecord_%02d' % x, email_field: '"TestCustomer %02d" <test.record.%[email protected]>' % (x, x), } if partners: vals[partner_field] = partners[x % len(partners)] vals_list.append(vals) return cls.env[model].create(vals_list)
47.15942
3,254
3,060
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.test_mass_mailing.models.mailing_models import MailingBLacklist from odoo.addons.test_mass_mailing.tests import common from odoo.exceptions import UserError from odoo.tests.common import users class TestBLMixin(common.TestMassMailCommon): @classmethod def setUpClass(cls): super(TestBLMixin, cls).setUpClass() cls.env['mail.blacklist'].create([{ 'email': '[email protected]', 'active': True, }, { 'email': '[email protected]', 'active': False, }]) @users('employee') def test_bl_mixin_primary_field_consistency(self): MailingBLacklist._primary_email = 'not_a_field' with self.assertRaises(UserError): self.env['mailing.test.blacklist'].search([('is_blacklisted', '=', False)]) MailingBLacklist._primary_email = ['not_a_str'] with self.assertRaises(UserError): self.env['mailing.test.blacklist'].search([('is_blacklisted', '=', False)]) MailingBLacklist._primary_email = 'email_from' self.env['mailing.test.blacklist'].search([('is_blacklisted', '=', False)]) @users('employee') def test_bl_mixin_is_blacklisted(self): """ Test is_blacklisted field computation """ record = self.env['mailing.test.blacklist'].create({'email_from': '[email protected]'}) self.assertTrue(record.is_blacklisted) record = self.env['mailing.test.blacklist'].create({'email_from': '[email protected]'}) self.assertFalse(record.is_blacklisted) @users('employee') def test_bl_mixin_search_blacklisted(self): """ Test is_blacklisted field search implementation """ record1 = self.env['mailing.test.blacklist'].create({'email_from': '[email protected]'}) record2 = self.env['mailing.test.blacklist'].create({'email_from': '[email protected]'}) search_res = self.env['mailing.test.blacklist'].search([('is_blacklisted', '=', False)]) self.assertEqual(search_res, record2) search_res = self.env['mailing.test.blacklist'].search([('is_blacklisted', '!=', True)]) self.assertEqual(search_res, record2) search_res = self.env['mailing.test.blacklist'].search([('is_blacklisted', '=', True)]) self.assertEqual(search_res, record1) search_res = self.env['mailing.test.blacklist'].search([('is_blacklisted', '!=', False)]) self.assertEqual(search_res, record1) @users('employee') def test_bl_mixin_search_blacklisted_format(self): """ Test is_blacklisted field search using email parsing """ record1 = self.env['mailing.test.blacklist'].create({'email_from': 'Arya Stark <[email protected]>'}) self.assertTrue(record1.is_blacklisted) search_res = self.env['mailing.test.blacklist'].search([('is_blacklisted', '=', True)]) self.assertEqual(search_res, record1)
43.098592
3,060
5,143
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.test_mass_mailing.tests.common import TestMassMailCommon from odoo.addons.base.tests.common import MockSmtplibCase from odoo.tests import tagged from odoo.tests.common import users from odoo.tools import mute_logger @tagged('mass_mailing') class TestMassMailingServer(TestMassMailCommon, MockSmtplibCase): @classmethod def setUpClass(cls): super(TestMassMailingServer, cls).setUpClass() cls._init_mail_gateway() cls.env['ir.mail_server'].search([]).unlink() cls._init_mail_servers() cls.recipients = cls._create_mailing_test_records(model='mailing.test.optout', count=8) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink', 'odoo.addons.mass_mailing.models.mailing') def test_mass_mailing_server_batch(self): """Test that the right mail server is chosen to send the mailing. Test also the envelop and the SMTP headers. """ # Test sending mailing in batch mailings = self.env['mailing.mailing'].create([{ 'subject': 'Mailing', 'body_html': 'Body for <t t-out="object.name" />', 'email_from': '[email protected]', 'mailing_model_id': self.env['ir.model']._get('mailing.test.optout').id, }, { 'subject': 'Mailing', 'body_html': 'Body for <t t-out="object.name" />', 'email_from': '[email protected]', 'mailing_model_id': self.env['ir.model']._get('mailing.test.optout').id, }]) with self.mock_smtplib_connection(): mailings.action_send_mail() self.assertEqual(self.find_mail_server_mocked.call_count, 2, 'Must be called only once per mail from') self.assert_email_sent_smtp( smtp_from='[email protected]', message_from='[email protected]', from_filter=self.server_user.from_filter, emails_count=8, ) self.assert_email_sent_smtp( # Must use the bounce address here because the mail server # is configured for the entire domain "test.com" smtp_from=lambda x: 'bounce' in x, message_from='[email protected]', from_filter=self.server_domain.from_filter, emails_count=8, ) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink', 'odoo.addons.mass_mailing.models.mailing') def test_mass_mailing_server_default(self): # We do not have a mail server for this address email, so fall back to the # "notifications@domain" email. mailings = self.env['mailing.mailing'].create([{ 'subject': 'Mailing', 'body_html': 'Body for <t t-out="object.name" />', 'email_from': '"Testing" <unknow_email@unknow_domain.com>', 'mailing_model_id': self.env['ir.model']._get('mailing.test.optout').id, }]) with self.mock_smtplib_connection(): mailings.action_send_mail() self.assertEqual(self.find_mail_server_mocked.call_count, 1) self.assert_email_sent_smtp( smtp_from='[email protected]', message_from='"Testing" <[email protected]>', from_filter=self.server_notification.from_filter, emails_count=8, ) self.assertEqual(self.find_mail_server_mocked.call_count, 1, 'Must be called only once') @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink', 'odoo.addons.mass_mailing.models.mailing') def test_mass_mailing_server_forced(self): # We force a mail server on one mailing mailings = self.env['mailing.mailing'].create([{ 'subject': 'Mailing', 'body_html': 'Body for <t t-out="object.name" />', 'email_from': self.server_user.from_filter, 'mailing_model_id': self.env['ir.model']._get('mailing.test.optout').id, }, { 'subject': 'Mailing', 'body_html': 'Body for <t t-out="object.name" />', 'email_from': 'unknow_email@unknow_domain.com', 'mailing_model_id': self.env['ir.model']._get('mailing.test.optout').id, 'mail_server_id': self.server_notification.id, }]) with self.mock_smtplib_connection(): mailings.action_send_mail() self.assertEqual(self.find_mail_server_mocked.call_count, 1, 'Must not be called when mail server is forced') self.assert_email_sent_smtp( smtp_from='[email protected]', message_from='[email protected]', from_filter=self.server_user.from_filter, emails_count=8, ) self.assert_email_sent_smtp( smtp_from='unknow_email@unknow_domain.com', message_from='unknow_email@unknow_domain.com', from_filter=self.server_notification.from_filter, emails_count=8, )
43.584746
5,143
4,440
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import lxml.html from odoo.addons.test_mass_mailing.tests.common import TestMassMailCommon from odoo.fields import Command from odoo.tests.common import users from odoo.tools import mute_logger class TestMailingTest(TestMassMailCommon): @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_render_mixin') def test_mailing_test_button(self): mailing = self.env['mailing.mailing'].create({ 'name': 'TestButton', 'subject': 'Subject {{ object.name }}', 'preview': 'Preview {{ object.name }}', 'state': 'draft', 'mailing_type': 'mail', 'body_html': '<p>Hello <t t-out="object.name"/></p>', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, }) mailing_test = self.env['mailing.mailing.test'].create({ 'email_to': '[email protected]', 'mass_mailing_id': mailing.id, }) with self.mock_mail_gateway(): mailing_test.send_mail_test() # not great but matches send_mail_test, maybe that should be a method # on mailing_test? record = self.env[mailing.mailing_model_real].search([], limit=1) first_child = lxml.html.fromstring(self._mails.pop()['body']).xpath('//body/*[1]')[0] self.assertEqual(first_child.tag, 'div') self.assertIn('display:none', first_child.get('style'), "the preview node should be hidden") self.assertEqual(first_child.text.strip(), "Preview " + record.name, "the preview node should contain the preview text") # Test if bad inline_template in the subject raises an error mailing.write({'subject': 'Subject {{ object.name_id.id }}'}) with self.mock_mail_gateway(), self.assertRaises(Exception): mailing_test.send_mail_test() # Test if bad inline_template in the body raises an error mailing.write({ 'subject': 'Subject {{ object.name }}', 'body_html': '<p>Hello <t t-out="object.name_id.id"/></p>', }) with self.mock_mail_gateway(), self.assertRaises(Exception): mailing_test.send_mail_test() # Test if bad inline_template in the preview raises an error mailing.write({ 'body_html': '<p>Hello <t t-out="object.name"/></p>', 'preview': 'Preview {{ object.name_id.id }}', }) with self.mock_mail_gateway(), self.assertRaises(Exception): mailing_test.send_mail_test() def test_mailing_test_equals_reality(self): """ Check that both test and real emails will format the qweb and inline placeholders correctly in body and subject. """ contact_list = self.env['mailing.list'].create({ 'name': 'Testers', 'contact_ids': [Command.create({ 'name': 'Mitchell Admin', 'email': '[email protected]', })], }) mailing = self.env['mailing.mailing'].create({ 'name': 'TestButton', 'subject': 'Subject {{ object.name }} <t t-out="object.name"/>', 'state': 'draft', 'mailing_type': 'mail', 'body_html': '<p>Hello {{ object.name }} <t t-out="object.name"/></p>', 'mailing_model_id': self.env['ir.model']._get('mailing.list').id, 'contact_list_ids': [contact_list.id], }) mailing_test = self.env['mailing.mailing.test'].create({ 'email_to': '[email protected]', 'mass_mailing_id': mailing.id, }) with self.mock_mail_gateway(): mailing_test.send_mail_test() expected_subject = 'Subject Mitchell Admin <t t-out="object.name"/>' expected_body = 'Hello {{ object.name }} Mitchell Admin' self.assertSentEmail(self.env.user.partner_id, ['[email protected]'], subject=expected_subject, body_content=expected_body) with self.mock_mail_gateway(): # send the mailing mailing.action_launch() self.env.ref('mass_mailing.ir_cron_mass_mailing_queue').method_direct_trigger() self.assertSentEmail(self.env.user.partner_id, ['[email protected]'], subject=expected_subject, body_content=expected_body)
41.495327
4,440
1,108
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 MailingTestPartnerUnstored(models.Model): """ Check mailing with unstored fields """ _description = 'Mailing Model without stored partner_id' _name = 'mailing.test.partner.unstored' _inherit = ['mail.thread.blacklist'] _primary_email = 'email_from' name = fields.Char() email_from = fields.Char() partner_id = fields.Many2one( 'res.partner', 'Customer', compute='_compute_partner_id', store=False) @api.depends('email_from') def _compute_partner_id(self): partners = self.env['res.partner'].search( [('email_normalized', 'in', self.filtered('email_from').mapped('email_normalized'))] ) self.partner_id = False for record in self.filtered('email_from'): record.partner_id = next( (partner.id for partner in partners if partner.email_normalized == record.email_normalized), False )
34.625
1,108
2,984
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 MailingSimple(models.Model): """ A very simple model only inheriting from mail.thread to test pure mass mailing features and base performances. """ _description = 'Simple Mailing' _name = 'mailing.test.simple' _inherit = ['mail.thread'] name = fields.Char() email_from = fields.Char() class MailingUTM(models.Model): """ Model inheriting from mail.thread and utm.mixin for checking utm of mailing is caught and set on reply """ _description = 'Mailing: UTM enabled to test UTM sync with mailing' _name = 'mailing.test.utm' _inherit = ['mail.thread', 'utm.mixin'] name = fields.Char() class MailingBLacklist(models.Model): """ Model using blacklist mechanism for mass mailing features. """ _description = 'Mailing Blacklist Enabled' _name = 'mailing.test.blacklist' _inherit = ['mail.thread.blacklist'] _primary_email = 'email_from' name = fields.Char() email_from = fields.Char() customer_id = fields.Many2one('res.partner', 'Customer', tracking=True) user_id = fields.Many2one('res.users', 'Responsible', tracking=True) class MailingOptOut(models.Model): """ Model using blacklist mechanism and a hijacked opt-out mechanism for mass mailing features. """ _description = 'Mailing Blacklist / Optout Enabled' _name = 'mailing.test.optout' _inherit = ['mail.thread.blacklist'] _primary_email = 'email_from' name = fields.Char() email_from = fields.Char() opt_out = fields.Boolean() customer_id = fields.Many2one('res.partner', 'Customer', tracking=True) user_id = fields.Many2one('res.users', 'Responsible', tracking=True) def _mailing_get_opt_out_list(self, mailing): res_ids = mailing._get_recipients() opt_out_contacts = set(self.search([ ('id', 'in', res_ids), ('opt_out', '=', True) ]).mapped('email_normalized')) return opt_out_contacts class MailingPerformance(models.Model): """ A very simple model only inheriting from mail.thread to test pure mass mailing performances. """ _name = 'mailing.performance' _description = 'Mailing: base performance' _inherit = ['mail.thread'] name = fields.Char() email_from = fields.Char() class MailingPerformanceBL(models.Model): """ Model using blacklist mechanism for mass mailing performance. """ _name = 'mailing.performance.blacklist' _description = 'Mailing: blacklist performance' _inherit = ['mail.thread.blacklist'] _primary_email = 'email_from' # blacklist field to check name = fields.Char() email_from = fields.Char() user_id = fields.Many2one( 'res.users', 'Responsible', tracking=True) container_id = fields.Many2one( 'mail.test.container', 'Meta Container Record', tracking=True)
33.909091
2,984
1,212
py
PYTHON
15.0
MAIL_TEMPLATE = """Return-Path: <[email protected]> To: {to} cc: {cc} Received: by mail1.openerp.com (Postfix, from userid 10002) id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST) From: {email_from} Subject: {subject} MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="----=_Part_4200734_24778174.1344608186754" Date: Fri, 10 Aug 2012 14:16:26 +0000 Message-ID: {msg_id} {extra} ------=_Part_4200734_24778174.1344608186754 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable I would gladly answer to your mass mailing ! -- Your Dear Customer ------=_Part_4200734_24778174.1344608186754 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head>=20 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf-8" /> </head>=20 <body style=3D"margin: 0; padding: 0; background: #ffffff;-webkit-text-size-adjust: 100%;">=20 <p>I would gladly answer to your mass mailing !</p> <p>--<br/> Your Dear Customer <p> </body> </html> ------=_Part_4200734_24778174.1344608186754-- """
28.857143
1,212
1,905
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Attendances', 'version': '2.0', 'category': 'Human Resources/Attendances', 'sequence': 240, 'summary': 'Track employee attendance', 'description': """ This module aims to manage employee's attendances. ================================================== Keeps account of the attendances of the employees on the basis of the actions(Check in/Check out) performed by them. """, 'website': 'https://www.odoo.com/app/employees', 'depends': ['hr', 'barcodes'], 'data': [ 'security/hr_attendance_security.xml', 'security/ir.model.access.csv', 'views/hr_attendance_view.xml', 'views/hr_attendance_overtime_view.xml', 'report/hr_attendance_report_views.xml', 'views/hr_department_view.xml', 'views/hr_employee_view.xml', 'views/res_config_settings_views.xml', ], 'demo': [ 'data/hr_attendance_demo.xml' ], 'installable': True, 'auto_install': False, 'application': True, 'assets': { 'web.assets_backend': [ 'hr_attendance/static/src/js/employee_kanban_view_handler.js', 'hr_attendance/static/src/js/greeting_message.js', 'hr_attendance/static/src/js/kiosk_mode.js', 'hr_attendance/static/src/js/kiosk_confirm.js', 'hr_attendance/static/src/js/my_attendances.js', 'hr_attendance/static/src/js/time_widget.js', 'hr_attendance/static/src/scss/hr_attendance.scss', ], 'web.qunit_suite_tests': [ ('after', 'web/static/tests/legacy/views/kanban_tests.js', 'hr_attendance/static/tests/hr_attendance_tests.js'), ], 'web.assets_qweb': [ 'hr_attendance/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
35.277778
1,905
5,669
py
PYTHON
15.0
# -*- coding: utf-8 -*- import pytz from datetime import datetime from unittest.mock import patch from odoo import fields from odoo.tests import new_test_user from odoo.tests.common import TransactionCase class TestHrAttendance(TransactionCase): """Test for presence validity""" def setUp(self): super(TestHrAttendance, self).setUp() self.user = new_test_user(self.env, login='fru', groups='base.group_user,hr_attendance.group_hr_attendance_use_pin') self.user_no_pin = new_test_user(self.env, login='gru', groups='base.group_user') self.test_employee = self.env['hr.employee'].create({ 'name': "François Russie", 'user_id': self.user.id, 'pin': '1234', }) self.employee_kiosk = self.env['hr.employee'].create({ 'name': "Machiavel", 'pin': '5678', }) def test_employee_state(self): # Make sure the attendance of the employee will display correctly assert self.test_employee.attendance_state == 'checked_out' self.test_employee._attendance_action_change() assert self.test_employee.attendance_state == 'checked_in' self.test_employee._attendance_action_change() assert self.test_employee.attendance_state == 'checked_out' def test_checkin_self_without_pin(self): """ Employee can check in/out without pin with his own account """ employee = self.test_employee.with_user(self.user) employee.with_user(self.user).attendance_manual({}, entered_pin=None) self.assertEqual(employee.attendance_state, 'checked_in', "He should be able to check in without pin") employee.attendance_manual({}, entered_pin=None) self.assertEqual(employee.attendance_state, 'checked_out', "He should be able to check out without pin") def test_checkin_self_with_pin(self): """ Employee can check in/out with pin with his own account """ employee = self.test_employee.with_user(self.user) employee.attendance_manual({}, entered_pin='1234') self.assertEqual(employee.attendance_state, 'checked_in', "He should be able to check in with his pin") employee.attendance_manual({}, entered_pin='1234') self.assertEqual(employee.attendance_state, 'checked_out', "He should be able to check out with his pin") def test_checkin_self_wrong_pin(self): """ Employee cannot check in/out with wrong pin with his own account """ employee = self.test_employee.with_user(self.user) action = employee.attendance_manual({}, entered_pin='9999') self.assertNotEqual(employee.attendance_state, 'checked_in', "He should not be able to check in with a wrong pin") self.assertTrue(action.get('warning')) def test_checkin_kiosk_with_pin(self): """ Employee can check in/out with his pin in kiosk """ employee = self.employee_kiosk.with_user(self.user) employee.attendance_manual({}, entered_pin='5678') self.assertEqual(employee.attendance_state, 'checked_in', "He should be able to check in with his pin") employee.attendance_manual({}, entered_pin='5678') self.assertEqual(employee.attendance_state, 'checked_out', "He should be able to check out with his pin") def test_checkin_kiosk_with_wrong_pin(self): """ Employee cannot check in/out with wrong pin in kiosk """ employee = self.employee_kiosk.with_user(self.user) action = employee.attendance_manual({}, entered_pin='8888') self.assertNotEqual(employee.attendance_state, 'checked_in', "He should not be able to check in with a wrong pin") self.assertTrue(action.get('warning')) def test_checkin_kiosk_without_pin(self): """ Employee cannot check in/out without his pin in kiosk """ employee = self.employee_kiosk.with_user(self.user) action = employee.attendance_manual({}, entered_pin=None) self.assertNotEqual(employee.attendance_state, 'checked_in', "He should not be able to check in with no pin") self.assertTrue(action.get('warning')) def test_checkin_kiosk_no_pin_mode(self): """ Employee cannot check in/out without pin in kiosk when user has not group `use_pin` """ employee = self.employee_kiosk.with_user(self.user_no_pin) employee.attendance_manual({}, entered_pin=None) self.assertEqual(employee.attendance_state, 'checked_out', "He shouldn't be able to check in without") def test_hours_today(self): """ Test day start is correctly computed according to the employee's timezone """ def tz_datetime(year, month, day, hour, minute): tz = pytz.timezone('Europe/Brussels') return tz.localize(datetime(year, month, day, hour, minute)).astimezone(pytz.utc).replace(tzinfo=None) employee = self.env['hr.employee'].create({'name': 'Cunégonde', 'tz': 'Europe/Brussels'}) self.env['hr.attendance'].create({ 'employee_id': employee.id, 'check_in': tz_datetime(2019, 3, 1, 22, 0), # should count from midnight in the employee's timezone (=the previous day in utc!) 'check_out': tz_datetime(2019, 3, 2, 2, 0), }) self.env['hr.attendance'].create({ 'employee_id': employee.id, 'check_in': tz_datetime(2019, 3, 2, 11, 0), }) # now = 2019/3/2 14:00 in the employee's timezone with patch.object(fields.Datetime, 'now', lambda: tz_datetime(2019, 3, 2, 14, 0).astimezone(pytz.utc).replace(tzinfo=None)): self.assertEqual(employee.hours_today, 5, "It should have counted 5 hours")
52.472222
5,667
2,412
py
PYTHON
15.0
# -*- coding: utf-8 -*- import time from odoo.tests.common import TransactionCase class TestHrAttendance(TransactionCase): """Tests for attendance date ranges validity""" def setUp(self): super(TestHrAttendance, self).setUp() self.attendance = self.env['hr.attendance'] self.test_employee = self.env['hr.employee'].create({'name': "Jacky"}) # demo data contains set up for self.test_employee self.open_attendance = self.attendance.create({ 'employee_id': self.test_employee.id, 'check_in': time.strftime('%Y-%m-10 10:00'), }) def test_attendance_in_before_out(self): # Make sure check_out is before check_in with self.assertRaises(Exception): self.my_attend = self.attendance.create({ 'employee_id': self.test_employee.id, 'check_in': time.strftime('%Y-%m-10 12:00'), 'check_out': time.strftime('%Y-%m-10 11:00'), }) def test_attendance_no_check_out(self): # Make sure no second attandance without check_out can be created with self.assertRaises(Exception): self.attendance.create({ 'employee_id': self.test_employee.id, 'check_in': time.strftime('%Y-%m-10 11:00'), }) # 5 next tests : Make sure that when attendances overlap an error is raised def test_attendance_1(self): self.attendance.create({ 'employee_id': self.test_employee.id, 'check_in': time.strftime('%Y-%m-10 07:30'), 'check_out': time.strftime('%Y-%m-10 09:00'), }) with self.assertRaises(Exception): self.attendance.create({ 'employee_id': self.test_employee.id, 'check_in': time.strftime('%Y-%m-10 08:30'), 'check_out': time.strftime('%Y-%m-10 09:30'), }) def test_new_attendances(self): # Make sure attendance modification raises an error when it causes an overlap self.attendance.create({ 'employee_id': self.test_employee.id, 'check_in': time.strftime('%Y-%m-10 11:00'), 'check_out': time.strftime('%Y-%m-10 12:00'), }) with self.assertRaises(Exception): self.open_attendance.write({ 'check_out': time.strftime('%Y-%m-10 11:30'), })
38.903226
2,412
12,036
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, datetime from odoo.tests import new_test_user from odoo.tests.common import tagged, TransactionCase @tagged('post_install', '-at_install', 'hr_attendance_overtime') class TestHrAttendanceOvertime(TransactionCase): """ Tests for overtime """ @classmethod def setUpClass(cls): super().setUpClass() cls.company = cls.env['res.company'].create({ 'name': 'SweatChipChop Inc.', 'hr_attendance_overtime': True, 'overtime_start_date': datetime(2021, 1, 1), 'overtime_company_threshold': 10, 'overtime_employee_threshold': 10, }) cls.user = new_test_user(cls.env, login='fru', groups='base.group_user,hr_attendance.group_hr_attendance', company_id=cls.company.id).with_company(cls.company) cls.employee = cls.env['hr.employee'].create({ 'name': "Marie-Edouard De La Court", 'user_id': cls.user.id, 'company_id': cls.company.id, 'tz': 'UTC', }) cls.other_employee = cls.env['hr.employee'].create({ 'name': 'Yolanda', 'company_id': cls.company.id, }) cls.jpn_employee = cls.env['hr.employee'].create({ 'name': 'Sacha', 'company_id': cls.company.id, 'tz': 'Asia/Tokyo', }) cls.honolulu_employee = cls.env['hr.employee'].create({ 'name': 'Susan', 'company_id': cls.company.id, 'tz': 'Pacific/Honolulu', }) def test_overtime_company_settings(self): self.company.hr_attendance_overtime = False self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 8, 0), 'check_out': datetime(2021, 1, 4, 20, 0) }) overtime = self.env['hr.attendance.overtime'].search_count([('employee_id', '=', self.employee.id), ('date', '=', date(2021, 1, 4))]) self.assertFalse(overtime, 'No overtime should be created') self.company.write({ 'hr_attendance_overtime': True, 'overtime_start_date': date(2021, 1, 1) }) overtime = self.env['hr.attendance.overtime'].search_count([('employee_id', '=', self.employee.id), ('date', '=', date(2021, 1, 4))]) self.assertTrue(overtime, 'Overtime should be created') self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2020, 12, 30, 8, 0), 'check_out': datetime(2020, 12, 30, 20, 0) }) overtime = self.env['hr.attendance.overtime'].search_count([('employee_id', '=', self.employee.id), ('date', '=', date(2020, 12, 30))]) self.assertFalse(overtime, 'No overtime should be created before the start date') def test_simple_overtime(self): checkin_am = self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 8, 0) }) self.env['hr.attendance'].create({ 'employee_id': self.other_employee.id, 'check_in': datetime(2021, 1, 4, 8, 0), 'check_out': datetime(2021, 1, 4, 22, 0) }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id), ('date', '=', date(2021, 1, 4))]) self.assertFalse(overtime, 'No overtime record should exist for that employee') checkin_am.write({'check_out': datetime(2021, 1, 4, 12, 0)}) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id), ('date', '=', date(2021, 1, 4))]) self.assertTrue(overtime, 'An overtime record should be created') self.assertEqual(overtime.duration, -4) checkin_pm = self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 13, 0) }) self.assertEqual(overtime.duration, 0, 'Overtime duration should be 0 when an attendance has not been checked out.') checkin_pm.write({'check_out': datetime(2021, 1, 4, 18, 0)}) self.assertTrue(overtime.exists(), 'Overtime should not be deleted') self.assertAlmostEqual(overtime.duration, 1) self.assertAlmostEqual(self.employee.total_overtime, 1) def test_overtime_weekend(self): self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 2, 8, 0), 'check_out': datetime(2021, 1, 2, 11, 0) }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id), ('date', '=', date(2021, 1, 2))]) self.assertTrue(overtime, 'Overtime should be created') self.assertEqual(overtime.duration, 3, 'Should have 3 hours of overtime') self.assertEqual(self.employee.total_overtime, 3, 'Should still have 3 hours of overtime') def test_overtime_multiple(self): attendance = self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 2, 8, 0), 'check_out': datetime(2021, 1, 2, 19, 0) }) self.assertEqual(self.employee.total_overtime, 11) self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 7, 0), 'check_out': datetime(2021, 1, 4, 16, 0) }) self.assertEqual(self.employee.total_overtime, 12) attendance.unlink() self.assertEqual(self.employee.total_overtime, 1) def test_overtime_change_employee(self): attendance = self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 7, 0), 'check_out': datetime(2021, 1, 4, 18, 0) }) self.assertEqual(self.employee.total_overtime, 3) self.assertEqual(self.other_employee.total_overtime, 0) attendance.employee_id = self.other_employee.id self.assertEqual(self.other_employee.total_overtime, 3) self.assertEqual(self.employee.total_overtime, 0) def test_overtime_far_timezones(self): self.env['hr.attendance'].create({ 'employee_id': self.jpn_employee.id, # Since dates have to be stored in utc these are the tokyo timezone times for 7-18 (UTC+9) 'check_in': datetime(2021, 1, 3, 22, 0), 'check_out': datetime(2021, 1, 4, 9, 0), }) self.env['hr.attendance'].create({ 'employee_id': self.honolulu_employee.id, # Same but for alaskan times (UTC-10) 'check_in': datetime(2021, 1, 4, 17, 0), 'check_out': datetime(2021, 1, 5, 4, 0), }) self.assertEqual(self.jpn_employee.total_overtime, 3) self.assertEqual(self.honolulu_employee.total_overtime, 3) def test_overtime_unclosed(self): attendance = self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 8, 0), }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertFalse(overtime, 'Overtime entry should not exist at this point.') # Employees goes to eat attendance.write({ 'check_out': datetime(2021, 1, 4, 12, 0), }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertTrue(overtime, 'An overtime entry should have been created.') self.assertEqual(overtime.duration, -4, 'User still has to work the afternoon.') self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 13, 0), }) self.assertEqual(overtime.duration, 0, 'Overtime entry has been reset due to an unclosed attendance.') def test_overtime_company_threshold(self): self.env['hr.attendance'].create([ { 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 7, 55), 'check_out': datetime(2021, 1, 4, 12, 0), }, { 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 13, 0), 'check_out': datetime(2021, 1, 4, 17, 5), } ]) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertFalse(overtime, 'No overtime should be counted because of the threshold.') self.company.write({ 'hr_attendance_overtime': True, 'overtime_start_date': date(2021, 1, 1), 'overtime_company_threshold': 4, }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertTrue(overtime, 'Overtime entry should exist since the threshold has been lowered.') self.assertAlmostEqual(overtime.duration, 10 / 60, msg='Overtime should be equal to 10 minutes.') def test_overtime_employee_threshold(self): self.env['hr.attendance'].create([ { 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 8, 5), 'check_out': datetime(2021, 1, 4, 12, 0), }, { 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 13, 0), 'check_out': datetime(2021, 1, 4, 16, 55), } ]) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertFalse(overtime, 'No overtime should be counted because of the threshold.') self.company.write({ 'hr_attendance_overtime': True, 'overtime_start_date': date(2021, 1, 1), 'overtime_employee_threshold': 4, }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertTrue(overtime, 'Overtime entry should exist since the threshold has been lowered.') self.assertAlmostEqual(overtime.duration, -(10 / 60), msg='Overtime should be equal to -10 minutes.') def test_overtime_both_threshold(self): self.env['hr.attendance'].create([ { 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 8, 5), 'check_out': datetime(2021, 1, 4, 12, 0), }, { 'employee_id': self.employee.id, 'check_in': datetime(2021, 1, 4, 13, 0), 'check_out': datetime(2021, 1, 4, 17, 5), } ]) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertFalse(overtime, 'No overtime should be counted because of the threshold.') self.company.write({ 'hr_attendance_overtime': True, 'overtime_start_date': date(2021, 1, 1), 'overtime_employee_threshold': 4, }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertTrue(overtime, 'Overtime entry should exist since the employee threshold has been lowered.') self.assertAlmostEqual(overtime.duration, -(5 / 60), msg='Overtime should be equal to -5 minutes.') self.company.write({ 'hr_attendance_overtime': True, 'overtime_start_date': date(2021, 1, 1), 'overtime_company_threshold': 4, }) overtime = self.env['hr.attendance.overtime'].search([('employee_id', '=', self.employee.id)]) self.assertFalse(overtime, 'Overtime entry should be unlinked since both overtime cancel each other.')
45.24812
12,036
984
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 HrEmployeePublic(models.Model): _inherit = 'hr.employee.public' # These are required for manual attendance attendance_state = fields.Selection(related='employee_id.attendance_state', readonly=True, groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance") hours_today = fields.Float(related='employee_id.hours_today', readonly=True, groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance") last_attendance_id = fields.Many2one(related='employee_id.last_attendance_id', readonly=True, groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance") total_overtime = fields.Float(related='employee_id.total_overtime', readonly=True, groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance")
57.882353
984
1,248
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 HrAttendanceOvertime(models.Model): _name = "hr.attendance.overtime" _description = "Attendance Overtime" _rec_name = 'employee_id' _order = 'date desc' def _default_employee(self): return self.env.user.employee_id employee_id = fields.Many2one( 'hr.employee', string="Employee", default=_default_employee, required=True, ondelete='cascade', index=True) company_id = fields.Many2one(related='employee_id.company_id') date = fields.Date(string='Day') duration = fields.Float(string='Extra Hours', default=0.0, required=True) duration_real = fields.Float( string='Extra Hours (Real)', default=0.0, help="Extra-hours including the threshold duration") adjustment = fields.Boolean(default=False) def init(self): # Allows only 1 overtime record per employee per day unless it's an adjustment self.env.cr.execute(""" CREATE UNIQUE INDEX IF NOT EXISTS hr_attendance_overtime_unique_employee_per_day ON %s (employee_id, date) WHERE adjustment is false""" % (self._table))
37.818182
1,248
462
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class IrUiMenu(models.Model): _inherit = 'ir.ui.menu' def _load_menus_blacklist(self): res = super()._load_menus_blacklist() if self.env.user.has_group('hr_attendance.group_hr_attendance_user'): res.append(self.env.ref('hr_attendance.menu_hr_attendance_attendances_overview').id) return res
33
462
3,259
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.osv.expression import OR class ResCompany(models.Model): _inherit = 'res.company' hr_attendance_overtime = fields.Boolean(string="Count Extra Hours") overtime_start_date = fields.Date(string="Extra Hours Starting Date") overtime_company_threshold = fields.Integer(string="Tolerance Time In Favor Of Company", default=0) overtime_employee_threshold = fields.Integer(string="Tolerance Time In Favor Of Employee", default=0) def write(self, vals): search_domain = False # Overtime to generate delete_domain = False # Overtime to delete overtime_enabled_companies = self.filtered('hr_attendance_overtime') # Prevent any further logic if we are disabling the feature is_disabling_overtime = False # If we disable overtime if 'hr_attendance_overtime' in vals and not vals['hr_attendance_overtime'] and overtime_enabled_companies: delete_domain = [('company_id', 'in', overtime_enabled_companies.ids)] vals['overtime_start_date'] = False is_disabling_overtime = True start_date = vals.get('hr_attendance_overtime') and vals.get('overtime_start_date') # Also recompute if the threshold have changed if not is_disabling_overtime and ( start_date or 'overtime_company_threshold' in vals or 'overtime_employee_threshold' in vals): for company in self: # If we modify the thresholds only if start_date == company.overtime_start_date and \ (vals.get('overtime_company_threshold') != company.overtime_company_threshold) or\ (vals.get('overtime_employee_threshold') != company.overtime_employee_threshold): search_domain = OR([search_domain, [('employee_id.company_id', '=', company.id)]]) # If we enabled the overtime with a start date elif not company.overtime_start_date and start_date: search_domain = OR([search_domain, [ ('employee_id.company_id', '=', company.id), ('check_in', '>=', start_date)]]) # If we move the start date into the past elif start_date and company.overtime_start_date > start_date: search_domain = OR([search_domain, [ ('employee_id.company_id', '=', company.id), ('check_in', '>=', start_date), ('check_in', '<=', company.overtime_start_date)]]) # If we move the start date into the future elif start_date and company.overtime_start_date < start_date: delete_domain = OR([delete_domain, [ ('company_id', '=', company.id), ('date', '<', start_date)]]) res = super().write(vals) if delete_domain: self.env['hr.attendance.overtime'].search(delete_domain).unlink() if search_domain: self.env['hr.attendance'].search(search_domain)._update_overtime() return res
52.564516
3,259
10,901
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import pytz from dateutil.relativedelta import relativedelta from odoo import models, fields, api, exceptions, _ from odoo.tools import float_round class HrEmployee(models.Model): _inherit = "hr.employee" attendance_ids = fields.One2many( 'hr.attendance', 'employee_id', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user", help='list of attendances for the employee') last_attendance_id = fields.Many2one( 'hr.attendance', compute='_compute_last_attendance_id', store=True, groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user") last_check_in = fields.Datetime( related='last_attendance_id.check_in', store=True, groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user") last_check_out = fields.Datetime( related='last_attendance_id.check_out', store=True, groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user") attendance_state = fields.Selection( string="Attendance Status", compute='_compute_attendance_state', selection=[('checked_out', "Checked out"), ('checked_in', "Checked in")], groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user") hours_last_month = fields.Float( compute='_compute_hours_last_month', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user") hours_today = fields.Float( compute='_compute_hours_today', groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user") hours_last_month_display = fields.Char( compute='_compute_hours_last_month', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user") overtime_ids = fields.One2many( 'hr.attendance.overtime', 'employee_id', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user") total_overtime = fields.Float( compute='_compute_total_overtime', compute_sudo=True, groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user") @api.depends('overtime_ids.duration', 'attendance_ids') def _compute_total_overtime(self): for employee in self: if employee.company_id.hr_attendance_overtime: employee.total_overtime = float_round(sum(employee.overtime_ids.mapped('duration')), 2) else: employee.total_overtime = 0 @api.depends('user_id.im_status', 'attendance_state') def _compute_presence_state(self): """ Override to include checkin/checkout in the presence state Attendance has the second highest priority after login """ super()._compute_presence_state() employees = self.filtered(lambda e: e.hr_presence_state != 'present') employee_to_check_working = self.filtered(lambda e: e.attendance_state == 'checked_out' and e.hr_presence_state == 'to_define') working_now_list = employee_to_check_working._get_employee_working_now() for employee in employees: if employee.attendance_state == 'checked_out' and employee.hr_presence_state == 'to_define' and \ employee.id not in working_now_list: employee.hr_presence_state = 'absent' elif employee.attendance_state == 'checked_in': employee.hr_presence_state = 'present' def _compute_hours_last_month(self): now = fields.Datetime.now() now_utc = pytz.utc.localize(now) for employee in self: tz = pytz.timezone(employee.tz or 'UTC') now_tz = now_utc.astimezone(tz) start_tz = now_tz + relativedelta(months=-1, day=1, hour=0, minute=0, second=0, microsecond=0) start_naive = start_tz.astimezone(pytz.utc).replace(tzinfo=None) end_tz = now_tz + relativedelta(day=1, hour=0, minute=0, second=0, microsecond=0) end_naive = end_tz.astimezone(pytz.utc).replace(tzinfo=None) attendances = self.env['hr.attendance'].search([ ('employee_id', '=', employee.id), '&', ('check_in', '<=', end_naive), ('check_out', '>=', start_naive), ]) hours = 0 for attendance in attendances: check_in = max(attendance.check_in, start_naive) check_out = min(attendance.check_out, end_naive) hours += (check_out - check_in).total_seconds() / 3600.0 employee.hours_last_month = round(hours, 2) employee.hours_last_month_display = "%g" % employee.hours_last_month def _compute_hours_today(self): now = fields.Datetime.now() now_utc = pytz.utc.localize(now) for employee in self: # start of day in the employee's timezone might be the previous day in utc tz = pytz.timezone(employee.tz) now_tz = now_utc.astimezone(tz) start_tz = now_tz + relativedelta(hour=0, minute=0) # day start in the employee's timezone start_naive = start_tz.astimezone(pytz.utc).replace(tzinfo=None) attendances = self.env['hr.attendance'].search([ ('employee_id', '=', employee.id), ('check_in', '<=', now), '|', ('check_out', '>=', start_naive), ('check_out', '=', False), ]) worked_hours = 0 for attendance in attendances: delta = (attendance.check_out or now) - max(attendance.check_in, start_naive) worked_hours += delta.total_seconds() / 3600.0 employee.hours_today = worked_hours @api.depends('attendance_ids') def _compute_last_attendance_id(self): for employee in self: employee.last_attendance_id = self.env['hr.attendance'].search([ ('employee_id', '=', employee.id), ], limit=1) @api.depends('last_attendance_id.check_in', 'last_attendance_id.check_out', 'last_attendance_id') def _compute_attendance_state(self): for employee in self: att = employee.last_attendance_id.sudo() employee.attendance_state = att and not att.check_out and 'checked_in' or 'checked_out' @api.model def attendance_scan(self, barcode): """ Receive a barcode scanned from the Kiosk Mode and change the attendances of corresponding employee. Returns either an action or a warning. """ employee = self.sudo().search([('barcode', '=', barcode)], limit=1) if employee: return employee._attendance_action('hr_attendance.hr_attendance_action_kiosk_mode') return {'warning': _("No employee corresponding to Badge ID '%(barcode)s.'") % {'barcode': barcode}} def attendance_manual(self, next_action, entered_pin=None): self.ensure_one() attendance_user_and_no_pin = self.user_has_groups( 'hr_attendance.group_hr_attendance_user,' '!hr_attendance.group_hr_attendance_use_pin') can_check_without_pin = attendance_user_and_no_pin or (self.user_id == self.env.user and entered_pin is None) if can_check_without_pin or entered_pin is not None and entered_pin == self.sudo().pin: return self._attendance_action(next_action) if not self.user_has_groups('hr_attendance.group_hr_attendance_user'): return {'warning': _('To activate Kiosk mode without pin code, you must have access right as an Officer or above in the Attendance app. Please contact your administrator.')} return {'warning': _('Wrong PIN')} def _attendance_action(self, next_action): """ Changes the attendance of the employee. Returns an action to the check in/out message, next_action defines which menu the check in/out message should return to. ("My Attendances" or "Kiosk Mode") """ self.ensure_one() employee = self.sudo() action_message = self.env["ir.actions.actions"]._for_xml_id("hr_attendance.hr_attendance_action_greeting_message") action_message['previous_attendance_change_date'] = employee.last_attendance_id and (employee.last_attendance_id.check_out or employee.last_attendance_id.check_in) or False action_message['employee_name'] = employee.name action_message['barcode'] = employee.barcode action_message['next_action'] = next_action action_message['hours_today'] = employee.hours_today if employee.user_id: modified_attendance = employee.with_user(employee.user_id)._attendance_action_change() else: modified_attendance = employee._attendance_action_change() action_message['attendance'] = modified_attendance.read()[0] action_message['total_overtime'] = employee.total_overtime return {'action': action_message} def _attendance_action_change(self): """ Check In/Check Out action Check In: create a new attendance record Check Out: modify check_out field of appropriate attendance record """ self.ensure_one() action_date = fields.Datetime.now() if self.attendance_state != 'checked_in': vals = { 'employee_id': self.id, 'check_in': action_date, } return self.env['hr.attendance'].create(vals) attendance = self.env['hr.attendance'].search([('employee_id', '=', self.id), ('check_out', '=', False)], limit=1) if attendance: attendance.check_out = action_date else: raise exceptions.UserError(_('Cannot perform check out on %(empl_name)s, could not find corresponding check in. ' 'Your attendances have probably been modified manually by human resources.') % {'empl_name': self.sudo().name, }) return attendance @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): if 'pin' in groupby or 'pin' in self.env.context.get('group_by', '') or self.env.context.get('no_group_by'): raise exceptions.UserError(_('Such grouping is not allowed.')) return super(HrEmployee, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) def _compute_presence_icon(self): res = super()._compute_presence_icon() # All employee must chek in or check out. Everybody must have an icon employee_to_define = self.filtered(lambda e: e.hr_icon_display == 'presence_undetermined') employee_to_define.hr_icon_display = 'presence_to_define' return res
52.408654
10,901
986
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 User(models.Model): _inherit = ['res.users'] hours_last_month = fields.Float(related='employee_id.hours_last_month') hours_last_month_display = fields.Char(related='employee_id.hours_last_month_display') attendance_state = fields.Selection(related='employee_id.attendance_state') last_check_in = fields.Datetime(related='employee_id.last_attendance_id.check_in') last_check_out = fields.Datetime(related='employee_id.last_attendance_id.check_out') total_overtime = fields.Float(related='employee_id.total_overtime') @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + [ 'hours_last_month', 'hours_last_month_display', 'attendance_state', 'last_check_in', 'last_check_out', 'total_overtime' ]
37.923077
986
1,914
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' group_attendance_use_pin = fields.Boolean( string='Employee PIN', implied_group="hr_attendance.group_hr_attendance_use_pin") hr_attendance_overtime = fields.Boolean( string="Count Extra Hours", readonly=False) overtime_start_date = fields.Date(string="Extra Hours Starting Date", readonly=False) overtime_company_threshold = fields.Integer( string="Tolerance Time In Favor Of Company", readonly=False) overtime_employee_threshold = fields.Integer( string="Tolerance Time In Favor Of Employee", readonly=False) @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() company = self.env.company res.update({ 'hr_attendance_overtime': company.hr_attendance_overtime, 'overtime_start_date': company.overtime_start_date, 'overtime_company_threshold': company.overtime_company_threshold, 'overtime_employee_threshold': company.overtime_employee_threshold, }) return res def set_values(self): super(ResConfigSettings, self).set_values() company = self.env.company # Done this way to have all the values written at the same time, # to avoid recomputing the overtimes several times with # invalid company configurations fields_to_check = [ 'hr_attendance_overtime', 'overtime_start_date', 'overtime_company_threshold', 'overtime_employee_threshold', ] if any(self[field] != company[field] for field in fields_to_check): company.write({field: self[field] for field in fields_to_check})
41.608696
1,914
17,620
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from datetime import datetime, timedelta from operator import itemgetter import pytz from odoo import models, fields, api, exceptions, _ from odoo.tools import format_datetime from odoo.osv.expression import AND, OR from odoo.tools.float_utils import float_is_zero class HrAttendance(models.Model): _name = "hr.attendance" _description = "Attendance" _order = "check_in desc" def _default_employee(self): return self.env.user.employee_id employee_id = fields.Many2one('hr.employee', string="Employee", default=_default_employee, required=True, ondelete='cascade', index=True) department_id = fields.Many2one('hr.department', string="Department", related="employee_id.department_id", readonly=True) check_in = fields.Datetime(string="Check In", default=fields.Datetime.now, required=True) check_out = fields.Datetime(string="Check Out") worked_hours = fields.Float(string='Worked Hours', compute='_compute_worked_hours', store=True, readonly=True) def name_get(self): result = [] for attendance in self: if not attendance.check_out: result.append((attendance.id, _("%(empl_name)s from %(check_in)s") % { 'empl_name': attendance.employee_id.name, 'check_in': format_datetime(self.env, attendance.check_in, dt_format=False), })) else: result.append((attendance.id, _("%(empl_name)s from %(check_in)s to %(check_out)s") % { 'empl_name': attendance.employee_id.name, 'check_in': format_datetime(self.env, attendance.check_in, dt_format=False), 'check_out': format_datetime(self.env, attendance.check_out, dt_format=False), })) return result @api.depends('check_in', 'check_out') def _compute_worked_hours(self): for attendance in self: if attendance.check_out and attendance.check_in: delta = attendance.check_out - attendance.check_in attendance.worked_hours = delta.total_seconds() / 3600.0 else: attendance.worked_hours = False @api.constrains('check_in', 'check_out') def _check_validity_check_in_check_out(self): """ verifies if check_in is earlier than check_out. """ for attendance in self: if attendance.check_in and attendance.check_out: if attendance.check_out < attendance.check_in: raise exceptions.ValidationError(_('"Check Out" time cannot be earlier than "Check In" time.')) @api.constrains('check_in', 'check_out', 'employee_id') def _check_validity(self): """ Verifies the validity of the attendance record compared to the others from the same employee. For the same employee we must have : * maximum 1 "open" attendance record (without check_out) * no overlapping time slices with previous employee records """ for attendance in self: # we take the latest attendance before our check_in time and check it doesn't overlap with ours last_attendance_before_check_in = self.env['hr.attendance'].search([ ('employee_id', '=', attendance.employee_id.id), ('check_in', '<=', attendance.check_in), ('id', '!=', attendance.id), ], order='check_in desc', limit=1) if last_attendance_before_check_in and last_attendance_before_check_in.check_out and last_attendance_before_check_in.check_out > attendance.check_in: raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % { 'empl_name': attendance.employee_id.name, 'datetime': format_datetime(self.env, attendance.check_in, dt_format=False), }) if not attendance.check_out: # if our attendance is "open" (no check_out), we verify there is no other "open" attendance no_check_out_attendances = self.env['hr.attendance'].search([ ('employee_id', '=', attendance.employee_id.id), ('check_out', '=', False), ('id', '!=', attendance.id), ], order='check_in desc', limit=1) if no_check_out_attendances: raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee hasn't checked out since %(datetime)s") % { 'empl_name': attendance.employee_id.name, 'datetime': format_datetime(self.env, no_check_out_attendances.check_in, dt_format=False), }) else: # we verify that the latest attendance with check_in time before our check_out time # is the same as the one before our check_in time computed before, otherwise it overlaps last_attendance_before_check_out = self.env['hr.attendance'].search([ ('employee_id', '=', attendance.employee_id.id), ('check_in', '<', attendance.check_out), ('id', '!=', attendance.id), ], order='check_in desc', limit=1) if last_attendance_before_check_out and last_attendance_before_check_in != last_attendance_before_check_out: raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % { 'empl_name': attendance.employee_id.name, 'datetime': format_datetime(self.env, last_attendance_before_check_out.check_in, dt_format=False), }) @api.model def _get_day_start_and_day(self, employee, dt): #Returns a tuple containing the datetime in naive UTC of the employee's start of the day # and the date it was for that employee if not dt.tzinfo: date_employee_tz = pytz.utc.localize(dt).astimezone(pytz.timezone(employee._get_tz())) else: date_employee_tz = dt start_day_employee_tz = date_employee_tz.replace(hour=0, minute=0, second=0) return (start_day_employee_tz.astimezone(pytz.utc).replace(tzinfo=None), start_day_employee_tz.date()) def _get_attendances_dates(self): # Returns a dictionnary {employee_id: set((datetimes, dates))} attendances_emp = defaultdict(set) for attendance in self.filtered(lambda a: a.employee_id.company_id.hr_attendance_overtime and a.check_in): check_in_day_start = attendance._get_day_start_and_day(attendance.employee_id, attendance.check_in) if check_in_day_start[0] < datetime.combine(attendance.employee_id.company_id.overtime_start_date, datetime.min.time()): continue attendances_emp[attendance.employee_id].add(check_in_day_start) if attendance.check_out: check_out_day_start = attendance._get_day_start_and_day(attendance.employee_id, attendance.check_out) attendances_emp[attendance.employee_id].add(check_out_day_start) return attendances_emp def _update_overtime(self, employee_attendance_dates=None): if employee_attendance_dates is None: employee_attendance_dates = self._get_attendances_dates() overtime_to_unlink = self.env['hr.attendance.overtime'] overtime_vals_list = [] for emp, attendance_dates in employee_attendance_dates.items(): # get_attendances_dates returns the date translated from the local timezone without tzinfo, # and contains all the date which we need to check for overtime attendance_domain = [] for attendance_date in attendance_dates: attendance_domain = OR([attendance_domain, [ ('check_in', '>=', attendance_date[0]), ('check_in', '<', attendance_date[0] + timedelta(hours=24)), ]]) attendance_domain = AND([[('employee_id', '=', emp.id)], attendance_domain]) # Attendances per LOCAL day attendances_per_day = defaultdict(lambda: self.env['hr.attendance']) all_attendances = self.env['hr.attendance'].search(attendance_domain) for attendance in all_attendances: check_in_day_start = attendance._get_day_start_and_day(attendance.employee_id, attendance.check_in) attendances_per_day[check_in_day_start[1]] += attendance # As _attendance_intervals_batch and _leave_intervals_batch both take localized dates we need to localize those date start = pytz.utc.localize(min(attendance_dates, key=itemgetter(0))[0]) stop = pytz.utc.localize(max(attendance_dates, key=itemgetter(0))[0] + timedelta(hours=24)) # Retrieve expected attendance intervals expected_attendances = emp.resource_calendar_id._attendance_intervals_batch( start, stop, emp.resource_id )[emp.resource_id.id] # Substract Global Leaves and Employee's Leaves leave_intervals = emp.resource_calendar_id._leave_intervals_batch(start, stop, emp.resource_id, domain=[]) expected_attendances -= leave_intervals[False] | leave_intervals[emp.resource_id.id] # working_times = {date: [(start, stop)]} working_times = defaultdict(lambda: []) for expected_attendance in expected_attendances: # Exclude resource.calendar.attendance working_times[expected_attendance[0].date()].append(expected_attendance[:2]) overtimes = self.env['hr.attendance.overtime'].sudo().search([ ('employee_id', '=', emp.id), ('date', 'in', [day_data[1] for day_data in attendance_dates]), ('adjustment', '=', False), ]) company_threshold = emp.company_id.overtime_company_threshold / 60.0 employee_threshold = emp.company_id.overtime_employee_threshold / 60.0 for day_data in attendance_dates: attendance_date = day_data[1] attendances = attendances_per_day.get(attendance_date, self.browse()) unfinished_shifts = attendances.filtered(lambda a: not a.check_out) overtime_duration = 0 overtime_duration_real = 0 # Overtime is not counted if any shift is not closed or if there are no attendances for that day, # this could happen when deleting attendances. if not unfinished_shifts and attendances: # The employee usually doesn't work on that day if not working_times[attendance_date]: # User does not have any resource_calendar_attendance for that day (week-end for example) overtime_duration = sum(attendances.mapped('worked_hours')) overtime_duration_real = overtime_duration # The employee usually work on that day else: # Compute start and end time for that day planned_start_dt, planned_end_dt = False, False planned_work_duration = 0 for calendar_attendance in working_times[attendance_date]: planned_start_dt = min(planned_start_dt, calendar_attendance[0]) if planned_start_dt else calendar_attendance[0] planned_end_dt = max(planned_end_dt, calendar_attendance[1]) if planned_end_dt else calendar_attendance[1] planned_work_duration += (calendar_attendance[1] - calendar_attendance[0]).total_seconds() / 3600.0 # Count time before, during and after 'working hours' pre_work_time, work_duration, post_work_time = 0, 0, 0 for attendance in attendances: # consider check_in as planned_start_dt if within threshold # if delta_in < 0: Checked in after supposed start of the day # if delta_in > 0: Checked in before supposed start of the day local_check_in = pytz.utc.localize(attendance.check_in) delta_in = (planned_start_dt - local_check_in).total_seconds() / 3600.0 # Started before or after planned date within the threshold interval if (delta_in > 0 and delta_in <= company_threshold) or\ (delta_in < 0 and abs(delta_in) <= employee_threshold): local_check_in = planned_start_dt local_check_out = pytz.utc.localize(attendance.check_out) # same for check_out as planned_end_dt delta_out = (local_check_out - planned_end_dt).total_seconds() / 3600.0 # if delta_out < 0: Checked out before supposed start of the day # if delta_out > 0: Checked out after supposed start of the day # Finised before or after planned date within the threshold interval if (delta_out > 0 and delta_out <= company_threshold) or\ (delta_out < 0 and abs(delta_out) <= employee_threshold): local_check_out = planned_end_dt # There is an overtime at the start of the day if local_check_in < planned_start_dt: pre_work_time += (min(planned_start_dt, local_check_out) - local_check_in).total_seconds() / 3600.0 # Interval inside the working hours -> Considered as working time if local_check_in <= planned_end_dt and local_check_out >= planned_start_dt: work_duration += (min(planned_end_dt, local_check_out) - max(planned_start_dt, local_check_in)).total_seconds() / 3600.0 # There is an overtime at the end of the day if local_check_out > planned_end_dt: post_work_time += (local_check_out - max(planned_end_dt, local_check_in)).total_seconds() / 3600.0 # Overtime within the planned work hours + overtime before/after work hours is > company threshold overtime_duration = work_duration - planned_work_duration if pre_work_time > company_threshold: overtime_duration += pre_work_time if post_work_time > company_threshold: overtime_duration += post_work_time # Global overtime including the thresholds overtime_duration_real = sum(attendances.mapped('worked_hours')) - planned_work_duration overtime = overtimes.filtered(lambda o: o.date == attendance_date) if not float_is_zero(overtime_duration, 2) or unfinished_shifts: # Do not create if any attendance doesn't have a check_out, update if exists if unfinished_shifts: overtime_duration = 0 if not overtime and overtime_duration: overtime_vals_list.append({ 'employee_id': emp.id, 'date': attendance_date, 'duration': overtime_duration, 'duration_real': overtime_duration_real, }) elif overtime: overtime.sudo().write({ 'duration': overtime_duration, 'duration_real': overtime_duration }) elif overtime: overtime_to_unlink |= overtime self.env['hr.attendance.overtime'].sudo().create(overtime_vals_list) overtime_to_unlink.sudo().unlink() @api.model_create_multi def create(self, vals_list): res = super().create(vals_list) res._update_overtime() return res def write(self, vals): attendances_dates = self._get_attendances_dates() result = super(HrAttendance, self).write(vals) if any(field in vals for field in ['employee_id', 'check_in', 'check_out']): # Merge attendance dates before and after write to recompute the # overtime if the attendances have been moved to another day for emp, dates in self._get_attendances_dates().items(): attendances_dates[emp] |= dates self._update_overtime(attendances_dates) return result def unlink(self): attendances_dates = self._get_attendances_dates() super(HrAttendance, self).unlink() self._update_overtime(attendances_dates) @api.returns('self', lambda value: value.id) def copy(self): raise exceptions.UserError(_('You cannot duplicate an attendance.'))
59.127517
17,620
2,036
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 class HRAttendanceReport(models.Model): _name = "hr.attendance.report" _description = "Attendance Statistics" _auto = False department_id = fields.Many2one('hr.department', string="Department", readonly=True) employee_id = fields.Many2one('hr.employee', string="Employee", readonly=True) check_in = fields.Date("Check In", readonly=True) worked_hours = fields.Float("Hours Worked", readonly=True) overtime_hours = fields.Float("Extra Hours", readonly=True) @api.model def _select(self): return """ SELECT hra.id, hr_employee.department_id, hra.employee_id, hra.check_in, hra.worked_hours, coalesce(ot.duration, 0) as overtime_hours """ @api.model def _from(self): return """ FROM ( SELECT id, row_number() over (partition by employee_id, CAST(check_in AS DATE)) as ot_check, employee_id, CAST(check_in as DATE) as check_in, worked_hours FROM hr_attendance ) as hra """ def _join(self): return """ LEFT JOIN hr_employee ON hr_employee.id = hra.employee_id LEFT JOIN hr_attendance_overtime ot ON hra.ot_check = 1 AND ot.employee_id = hra.employee_id AND ot.date = hra.check_in AND ot.adjustment = FALSE """ def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute(""" CREATE OR REPLACE VIEW %s AS ( %s %s %s ) """ % (self._table, self._select(), self._from(), self._join()) )
31.8125
2,036
368
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 class HrAttendance(http.Controller): @http.route('/hr_attendance/kiosk_keepalive', auth='user', type='json') def kiosk_keepalive(self): request.httprequest.session.modified = True return {}
30.666667
368
725
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Sale Coupon", 'summary': "Use discount coupons in sales orders", 'description': """Integrate coupon mechanism in sales orders.""", 'category': 'Sales/Sales', 'version': '1.0', 'depends': ['coupon', 'sale'], 'data': [ 'data/mail_template_data.xml', 'security/sale_coupon_security.xml', 'security/ir.model.access.csv', 'wizard/sale_coupon_apply_code_views.xml', 'views/sale_order_views.xml', 'views/coupon_views.xml', 'views/coupon_program_views.xml', 'views/res_config_settings_views.xml', ], 'license': 'LGPL-3', }
34.52381
725
3,409
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_coupon.tests.common import TestSaleCouponCommon from odoo.exceptions import UserError from odoo.tests import tagged @tagged('post_install', '-at_install') class TestSaleInvoicing(TestSaleCouponCommon): def test_invoicing_order_with_promotions(self): discount_coupon_program = self.env['coupon.program'].create({ 'name': '10% Discount', # Default behavior 'program_type': 'coupon_program', 'reward_type': 'discount', 'discount_apply_on': 'on_order', 'promo_code_usage': 'no_code_needed', }) # Override the default invoice_policy on products discount_coupon_program.discount_line_product_id.invoice_policy = 'order' product = self.env['product.product'].create({ 'invoice_policy': 'delivery', 'name': 'Product invoiced on delivery', 'lst_price': 500, }) order = self.empty_order order.write({ 'order_line': [ (0, 0, { 'product_id': product.id, }) ] }) order.recompute_coupon_lines() # Order is not confirmed, there shouldn't be any invoiceable line invoiceable_lines = order._get_invoiceable_lines() self.assertEqual(len(invoiceable_lines), 0) order.action_confirm() invoiceable_lines = order._get_invoiceable_lines() # Product was not delivered, we cannot invoice # the product line nor the promotion line self.assertEqual(len(invoiceable_lines), 0) with self.assertRaises(UserError): order._create_invoices() order.order_line[0].qty_delivered = 1 # Product is delivered, the two lines can be invoiced. invoiceable_lines = order._get_invoiceable_lines() self.assertEqual(order.order_line, invoiceable_lines) account_move = order._create_invoices() self.assertEqual(len(account_move.invoice_line_ids), 2) def test_coupon_on_order_sequence(self): # discount_coupon_program self.env['coupon.program'].create({ 'name': '10% Discount', # Default behavior 'program_type': 'coupon_program', 'reward_type': 'discount', 'discount_apply_on': 'on_order', 'promo_code_usage': 'no_code_needed', }) order = self.empty_order # orderline1 self.env['sale.order.line'].create({ 'product_id': self.env.ref('product.product_product_6').id, 'name': 'largeCabinet', 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 2, 'Coupon correctly applied') # orderline2 self.env['sale.order.line'].create({ 'product_id': self.env.ref('product.product_product_11').id, 'name': 'conferenceChair', 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 3, 'Coupon correctly applied') self.assertTrue(order.order_line.sorted(lambda x: x.sequence)[-1].is_reward_line, 'Global coupons appear on the last line')
38.303371
3,409
3,065
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_coupon.tests.common import TestSaleCouponCommon from odoo.exceptions import UserError from odoo.tests import tagged @tagged('post_install', '-at_install') class TestSaleCouponMultiCompany(TestSaleCouponCommon): def setUp(self): super(TestSaleCouponMultiCompany, self).setUp() self.company_a = self.env.company self.company_b = self.env['res.company'].create(dict(name="TEST")) self.immediate_promotion_program_c2 = self.env['coupon.program'].create({ 'name': 'Buy A + 1 B, 1 B are free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'reward_product_id': self.product_B.id, 'rule_products_domain': "[('id', 'in', [%s])]" % (self.product_A.id), 'active': True, 'company_id': self.company_b.id, }) def test_applicable_programs(self): order = self.empty_order order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() def _get_applied_programs(order): # temporary copy of sale_order._get_applied_programs # to ensure each commit stays independent # can be later removed and replaced in master. return order.code_promo_program_id + order.no_code_promo_program_ids + order.applied_coupon_ids.mapped('program_id') self.assertNotIn(self.immediate_promotion_program_c2, order._get_applicable_programs()) self.assertNotIn(self.immediate_promotion_program_c2, _get_applied_programs(order)) order_b = self.env["sale.order"].create({ 'company_id': self.company_b.id, 'partner_id': order.partner_id.id, }) order_b.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) self.assertNotIn(self.immediate_promotion_program, order_b._get_applicable_programs()) order_b.recompute_coupon_lines() self.assertIn(self.immediate_promotion_program_c2, _get_applied_programs(order_b)) self.assertNotIn(self.immediate_promotion_program, _get_applied_programs(order_b))
39.294872
3,065
18,008
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.addons.sale_coupon.tests.common import TestSaleCouponCommon from odoo.exceptions import UserError from odoo.fields import Date class TestProgramRules(TestSaleCouponCommon): # Test all the validity rules to allow a customer to have a reward. # The check based on the products is already done in the basic operations test def test_program_rules_partner_based(self): # Test case: Based on the partners domain self.immediate_promotion_program.write({'rule_partners_domain': "[('id', 'in', [%s])]" % (self.steve.id)}) order = self.empty_order order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "The promo offert should have been applied as the partner is correct, the discount is not created") order = self.env['sale.order'].create({'partner_id': self.env['res.partner'].create({'name': 'My Partner'}).id}) order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied, the discount is created") def test_program_rules_minimum_purchased_amount(self): # Test case: Based on the minimum purchased self.immediate_promotion_program.write({ 'rule_minimum_amount': 1006, 'rule_minimum_amount_tax_inclusion': 'tax_excluded' }) order = self.empty_order order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied as the purchased amount is not enough") order = self.env['sale.order'].create({'partner_id': self.steve.id}) order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '10 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 10.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() # 10*100 + 5 = 1005 self.assertEqual(len(order.order_line.ids), 2, "The promo offert should not be applied as the purchased amount is not enough") self.immediate_promotion_program.rule_minimum_amount = 1005 order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "The promo offert should be applied as the purchased amount is now enough") # 10*(100*1.15) + (5*1.15) = 10*115 + 5.75 = 1155.75 self.immediate_promotion_program.rule_minimum_amount = 1006 self.immediate_promotion_program.rule_minimum_amount_tax_inclusion = 'tax_included' order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "The promo offert should be applied as the initial amount required is now tax included") def test_program_rules_validity_dates_and_uses(self): # Test case: Based on the validity dates and the number of allowed uses self.immediate_promotion_program.write({ 'rule_date_from': Date.to_string((datetime.now() - timedelta(days=7))), 'rule_date_to': Date.to_string((datetime.now() - timedelta(days=2))), 'maximum_use_number': 1, }) order = self.empty_order order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied we're not between the validity dates") self.immediate_promotion_program.write({ 'rule_date_from': Date.to_string((datetime.now() - timedelta(days=7))), 'rule_date_to': Date.to_string((datetime.now() + timedelta(days=2))), }) order = self.env['sale.order'].create({'partner_id': self.steve.id}) order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 10.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "The promo offert should have been applied as we're between the validity dates") order = self.env['sale.order'].create({'partner_id': self.env['res.partner'].create({'name': 'My Partner'}).id}) order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 10.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied as the number of uses is exceeded") def test_program_rules_one_date(self): # Test case: Based on the validity dates and the number of allowed uses # VFE NOTE the .rule_id is necessary to ensure the dates constraints doesn't raise # because the orm applies the related inverse one by one, raising the constraint... self.immediate_promotion_program.rule_id.write({ 'rule_date_from': False, 'rule_date_to': Date.to_string((datetime.now() - timedelta(days=2))), }) order = self.empty_order order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertNotIn(self.immediate_promotion_program, order._get_applicable_programs()) self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied we're not between the validity dates") self.immediate_promotion_program.rule_id.write({ 'rule_date_from': Date.to_string((datetime.now() + timedelta(days=1))), 'rule_date_to': False, }) order.recompute_coupon_lines() self.assertNotIn(self.immediate_promotion_program, order._get_applicable_programs()) self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied we're not between the validity dates") self.immediate_promotion_program.rule_id.write({ 'rule_date_from': False, 'rule_date_to': Date.to_string((datetime.now() + timedelta(days=2))), }) order.recompute_coupon_lines() self.assertIn(self.immediate_promotion_program, order._get_applicable_programs()) self.assertEqual(len(order.order_line.ids), 3, "The promo offer should have been applied as we're between the validity dates") self.immediate_promotion_program.rule_id.write({ 'rule_date_from': Date.to_string((datetime.now() - timedelta(days=1))), 'rule_date_to': False, }) order.recompute_coupon_lines() self.assertIn(self.immediate_promotion_program, order._get_applicable_programs()) self.assertEqual(len(order.order_line.ids), 3, "The promo offer should have been applied as we're between the validity dates") def test_program_rules_date(self): # Test case: Based on the validity dates # VFE NOTE the .rule_id is necessary to ensure the dates constraints doesn't raise # because the orm applies the related inverse one by one, raising the constraint... self.immediate_promotion_program.rule_id.write({ 'rule_date_from': Date.to_string((datetime.now() - timedelta(days=7))), 'rule_date_to': Date.to_string((datetime.now() - timedelta(days=2))), }) order = self.empty_order order.write({ 'date_order': Date.to_string((datetime.now() - timedelta(days=5))), }) order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }), (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertNotIn(self.immediate_promotion_program, order._get_applicable_programs()) self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied we're not between the validity dates") self.immediate_promotion_program.rule_id.write({ 'rule_date_from': Date.to_string((datetime.now() + timedelta(days=2))), 'rule_date_to': Date.to_string((datetime.now() + timedelta(days=7))), }) order.recompute_coupon_lines() self.assertNotIn(self.immediate_promotion_program, order._get_applicable_programs()) self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied we're not between the validity dates") self.immediate_promotion_program.rule_id.write({ 'rule_date_from': Date.to_string((datetime.now() - timedelta(days=2))), 'rule_date_to': Date.to_string((datetime.now() + timedelta(days=2))), }) order.recompute_coupon_lines() self.assertIn(self.immediate_promotion_program, order._get_applicable_programs()) self.assertEqual(len(order.order_line.ids), 3, "The promo offer should have been applied as we're between the validity dates") def test_program_rules_coupon_qty_and_amount_remove_not_eligible(self): ''' This test will: * Check quantity and amount requirements works as expected (since it's slightly different from a promotion_program) * Ensure that if a reward from a coupon_program was allowed and the conditions are not met anymore, the reward will be removed on recompute. ''' self.immediate_promotion_program.active = False # Avoid having this program to add rewards on this test order = self.empty_order program = self.env['coupon.program'].create({ 'name': 'Get 10% discount if buy at least 4 Product A and $320', 'program_type': 'coupon_program', 'reward_type': 'discount', 'discount_type': 'percentage', 'discount_percentage': 10.0, 'rule_products_domain': "[('id', 'in', [%s])]" % (self.product_A.id), 'rule_min_quantity': 3, 'rule_minimum_amount': 320.00, }) sol1 = self.env['sale.order.line'].create({ 'product_id': self.product_A.id, 'name': 'Product A', 'product_uom_qty': 2.0, 'order_id': order.id, }) sol2 = self.env['sale.order.line'].create({ 'product_id': self.product_B.id, 'name': 'Product B', 'product_uom_qty': 4.0, 'order_id': order.id, }) # Default value for coupon generate wizard is generate by quantity and generate only one coupon self.env['coupon.generate.wizard'].with_context(active_id=program.id).create({}).generate_coupon() coupon = program.coupon_ids[0] # Not enough amount since we only have 220 (100*2 + 5*4) with self.assertRaises(UserError): self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() sol2.product_uom_qty = 24 # Not enough qty since we only have 3 Product A (Amount is ok: 100*2 + 5*24 = 320) with self.assertRaises(UserError): self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() sol1.product_uom_qty = 3 self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "The order should contains the Product A line, the Product B line and the discount line") self.assertEqual(coupon.state, 'used', "The coupon should be set to Consumed as it has been used") sol1.product_uom_qty = 2 order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The discount line should have been removed as we don't meet the program requirements") self.assertEqual(coupon.state, 'new', "The coupon should be reset to Valid as it's reward got removed") def test_program_rules_promotion_use_best(self): ''' This test will: * Verify the best global promotion according to the current sale order is used. ''' self.immediate_promotion_program.active = False # Avoid having this program to add rewards on this test order = self.empty_order program_5pc = self.env['coupon.program'].create({ 'name': 'Get 5% discount if buy at least 2 Product', 'program_type': 'promotion_program', 'reward_type': 'discount', 'discount_type': 'percentage', 'discount_percentage': 5.0, 'rule_min_quantity': 2, 'promo_code_usage': 'no_code_needed', }) program_10pc = self.env['coupon.program'].create({ 'name': 'Get 10% discount if buy at least 4 Product', 'program_type': 'promotion_program', 'reward_type': 'discount', 'discount_type': 'percentage', 'discount_percentage': 10.0, 'rule_min_quantity': 4, 'promo_code_usage': 'no_code_needed', }) sol = self.env['sale.order.line'].create({ 'product_id': self.product_A.id, 'name': 'Product A', 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "The order should only contains the Product A line") sol.product_uom_qty = 3 order.recompute_coupon_lines() discounts = set(order.order_line.mapped('name')) - {'Product A'} self.assertEqual(len(discounts), 1, "The order should contains the Product A line and a discount") # The name of the discount is dynamically changed to smth looking like: # "Discount: Get 5% discount if buy at least 2 Product - On product with following tax: Tax 15.00%" self.assertTrue('Get 5% discount' in discounts.pop(), "The discount should be a 5% discount") sol.product_uom_qty = 5 order.recompute_coupon_lines() discounts = set(order.order_line.mapped('name')) - {'Product A'} self.assertEqual(len(discounts), 1, "The order should contains the Product A line and a discount") self.assertTrue('Get 10% discount' in discounts.pop(), "The discount should be a 10% discount")
45.705584
18,008
17,656
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_coupon.tests.common import TestSaleCouponCommon from odoo.exceptions import UserError class TestProgramWithCodeOperations(TestSaleCouponCommon): # Test the basic operation (apply_coupon) on an coupon program on which we should # apply the reward when the code is correct or remove the reward automatically when the reward is # not valid anymore. def test_program_usability(self): # After clicking "Generate coupons", there is no domain so it shows "Match all records". # But when you click, domain is false (default field value; empty string) so it won't generate anything. # This is even more weird because if you add something in the domain and then delete it, # you visually come back to the initial state except the domain became '[]' instead of ''. # In this case, it will generate the coupon for every partner. # Thus, we should ensure that if you leave the domain untouched, it generates a coupon for each partner # as hinted on the screen ('Match all records (X records)') self.env['coupon.generate.wizard'].with_context(active_id=self.code_promotion_program.id).create({ 'generation_type': 'nbr_customer', }).generate_coupon() self.assertEqual(len(self.code_promotion_program.coupon_ids), len(self.env['res.partner'].search([])), "It should have generated a coupon for every partner") def test_program_basic_operation_coupon_code(self): # Test case: Generate a coupon for my customer, and add a reward then remove it automatically self.code_promotion_program.reward_type = 'discount' self.env['coupon.generate.wizard'].with_context(active_id=self.code_promotion_program.id).create({ 'generation_type': 'nbr_customer', 'partners_domain': "[('id', 'in', [%s])]" % (self.steve.id), }).generate_coupon() coupon = self.code_promotion_program.coupon_ids # Test the valid code on a wrong sales order wrong_partner_order = self.env['sale.order'].create({ 'partner_id': self.env['res.partner'].create({'name': 'My Partner'}).id, }) with self.assertRaises(UserError): self.env['sale.coupon.apply.code'].with_context(active_id=wrong_partner_order.id).create({ 'coupon_code': coupon.code }).process_coupon() # Test now on a valid sales order order = self.empty_order order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2) self.assertEqual(coupon.state, 'used') # Remove the product A from the sale order order.write({'order_line': [(2, order.order_line[0].id, False)]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 0) self.assertEqual(coupon.state, 'new') def test_program_coupon_double_consuming(self): # Test case: # - Generate a coupon # - add to a sale order A, cancel the sale order # - add to a sale order B, confirm the order # - go back to A, reset to draft and confirm self.code_promotion_program.reward_type = 'discount' self.env['coupon.generate.wizard'].with_context(active_id=self.code_promotion_program.id).create({ 'generation_type': 'nbr_coupon', 'nbr_coupons': 1, }).generate_coupon() coupon = self.code_promotion_program.coupon_ids sale_order_a = self.empty_order.copy() sale_order_b = self.empty_order.copy() sale_order_a.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) self.env['sale.coupon.apply.code'].with_context(active_id=sale_order_a.id).create({ 'coupon_code': coupon.code }).process_coupon() sale_order_a.recompute_coupon_lines() self.assertEqual(len(sale_order_a.order_line.ids), 2) self.assertEqual(coupon.state, 'used') self.assertEqual(coupon.sales_order_id, sale_order_a) sale_order_a.action_cancel() sale_order_b.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) self.env['sale.coupon.apply.code'].with_context(active_id=sale_order_b.id).create({ 'coupon_code': coupon.code }).process_coupon() sale_order_b.recompute_coupon_lines() self.assertEqual(len(sale_order_b.order_line.ids), 2) self.assertEqual(coupon.state, 'used') self.assertEqual(coupon.sales_order_id, sale_order_b) sale_order_b.action_confirm() sale_order_a.action_draft() sale_order_a.action_confirm() # reward line removed automatically self.assertEqual(len(sale_order_a.order_line.ids), 1) def test_coupon_code_with_pricelist(self): # Test case: Generate a coupon (10% discount) and apply it on an order with a specific pricelist (10% discount) self.env['coupon.generate.wizard'].with_context(active_id=self.code_promotion_program_with_discount.id).create({ 'generation_type': 'nbr_coupon', 'nbr_coupons': 1, }).generate_coupon() coupon = self.code_promotion_program_with_discount.coupon_ids first_pricelist = self.env['product.pricelist'].create({ 'name': 'First pricelist', 'discount_policy': 'with_discount', 'item_ids': [(0, 0, { 'compute_price': 'percentage', 'base': 'list_price', 'percent_price': 10, 'applied_on': '3_global', 'name': 'First discount' })] }) order = self.empty_order order.pricelist_id = first_pricelist order.write({'order_line': [ (0, False, { 'product_id': self.product_C.id, 'name': '1 Product C', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2) self.assertEqual(coupon.state, 'used') self.assertEqual(order.amount_total, 81, "SO total should be 81: (10% of 100 with pricelist) + 10% of 90 with coupon code") def test_on_next_order_reward_promotion_program(self): # The flow: # 1. Create a program `A` that gives a free `Product B` on next order if you buy a an `product A` # This program should be code_needed with code `free_B_on_next_order` # 2. Create a program `B` that gives 10% discount on next order automatically # 3. Create a SO with a `third product` and recompute coupon, you SHOULD get a coupon (from program `B`) for your next order that will discount 10% # 4. Try to apply `A`, it should error since we did not buy any product A. # 5. Add a product A to the cart and try to apply `A` again, this time it should work # 6. Verify you have 2 generated coupons and validate the SO (so the 2 generated coupons will be valid) # 7. Create a new SO (with the same partner) and try to apply coupon generated by `A`. it SHOULD error since we don't have any `Product B` in the cart # 8. Add a Product B in the cart # 9. Try to apply once again coupon generated by `A`, it should give you the free product B # 10. Try to apply coupon generated by `B`, it should give you 10% discount. # => SO will then be 0$ until we recompute the order lines # 1. self.immediate_promotion_program.write({ 'promo_applicability': 'on_next_order', 'promo_code_usage': 'code_needed', 'promo_code': 'free_B_on_next_order', }) # 2. self.p1 = self.env['coupon.program'].create({ 'name': 'Code for 10% on next order', 'discount_type': 'percentage', 'discount_percentage': 10.0, 'program_type': 'promotion_program', 'promo_code_usage': 'no_code_needed', 'promo_applicability': 'on_next_order', }) # 3. order = self.empty_order.copy() self.third_product = self.env['product.product'].create({ 'name': 'Thrid Product', 'list_price': 5, 'sale_ok': True }) order.write({'order_line': [ (0, False, { 'product_id': self.third_product.id, 'name': '1 Third Product', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(self.p1.coupon_ids.ids), 1, "You should get a coupon for you next order that will offer 10% discount") # 4. with self.assertRaises(UserError): self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'free_B_on_next_order' }).process_coupon() # 5. order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'free_B_on_next_order' }).process_coupon() # 6. self.assertEqual(len(order.generated_coupon_ids), 2, "You should get a second coupon for your next order that will offer a free Product B") order.action_confirm() # 7. order_bis = self.empty_order with self.assertRaises(UserError): self.env['sale.coupon.apply.code'].with_context(active_id=order_bis.id).create({ 'coupon_code': order.generated_coupon_ids[1].code }).process_coupon() # 8. order_bis.write({'order_line': [ (0, False, { 'product_id': self.product_B.id, 'name': '1 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) # 9. self.env['sale.coupon.apply.code'].with_context(active_id=order_bis.id).create({ 'coupon_code': order.generated_coupon_ids[1].code }).process_coupon() self.assertEqual(len(order_bis.order_line), 2, "You should get a free Product B") # 10. self.env['sale.coupon.apply.code'].with_context(active_id=order_bis.id).create({ 'coupon_code': order.generated_coupon_ids[0].code }).process_coupon() self.assertEqual(len(order_bis.order_line), 3, "You should get a 10% discount line") self.assertEqual(order_bis.amount_total, 0, "SO total should be null: (Paid product - Free product = 0) + 10% of nothing") def test_on_next_order_reward_promotion_program_with_requirements(self): self.immediate_promotion_program.write({ 'promo_applicability': 'on_next_order', 'promo_code_usage': 'code_needed', 'promo_code': 'free_B_on_next_order', 'rule_minimum_amount': 700, 'rule_minimum_amount_tax_inclusion': 'tax_excluded' }) order = self.empty_order.copy() self.product_A.lst_price = 700 order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'free_B_on_next_order' }).process_coupon() self.assertEqual(len(self.immediate_promotion_program.coupon_ids.ids), 1, "You should get a coupon for you next order that will offer a free product B") order_bis = self.empty_order order_bis.write({'order_line': [ (0, False, { 'product_id': self.product_B.id, 'name': '1 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) with self.assertRaises(UserError): # It should error since we did not validated the previous SO, so the coupon is `reserved` but not `new` self.env['sale.coupon.apply.code'].with_context(active_id=order_bis.id).create({ 'coupon_code': order.generated_coupon_ids[0].code }).process_coupon() order.action_confirm() # It should not error even if the SO does not have the requirements (700$ and 1 product A), since these requirements where only used to generate the coupon that we are now applying self.env['sale.coupon.apply.code'].with_context(active_id=order_bis.id).create({ 'coupon_code': order.generated_coupon_ids[0].code }).process_coupon() self.assertEqual(len(order_bis.order_line), 2, "You should get 1 regular product_B and 1 free product_B") order_bis.recompute_coupon_lines() self.assertEqual(len(order_bis.order_line), 2, "Free product from a coupon generated from a promotion program on next order should not dissapear") def test_edit_and_reapply_promotion_program(self): # The flow: # 1. Create a program auto applied, giving a fixed amount discount # 2. Create a SO and apply the program # 3. Change the program, requiring a mandatory code # 4. Reapply the program on the same SO via code # 1. self.p1 = self.env['coupon.program'].create({ 'name': 'Promo fixed amount', 'promo_code_usage': 'no_code_needed', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 10.0, 'program_type': 'promotion_program', }) # 2. order = self.empty_order.copy() order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 2, "You should get a discount line") # 3. self.p1.write({ 'promo_code_usage': 'code_needed', 'promo_code': 'test', }) order.recompute_coupon_lines() # 4. with self.assertRaises(UserError): self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'test' }).process_coupon() self.assertEqual(len(order.order_line), 2, "You should get a discount line") def test_apply_program_no_reward_link(self): # Tests that applying a promo code that does not generate reward lines # does not link on the order self.env['coupon.program'].create({ 'name': 'Code for 10% on orders', 'promo_code_usage': 'code_needed', 'promo_code': 'test_10pc', 'discount_type': 'percentage', 'discount_percentage': 10.0, 'program_type': 'promotion_program', }) self.empty_order.write({'order_line': [ (0, False, { 'product_id': self.product_C.id, 'name': '1 Product C', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, 'price_unit': 0, }) ]}) self.env['sale.coupon.apply.code'].with_context(active_id=self.empty_order.id).create({ 'coupon_code': 'test_10pc', }).process_coupon() self.assertFalse(self.empty_order.code_promo_program_id, 'The program should not be linked to the order') # Same for a coupon's code self.env['coupon.generate.wizard'].with_context(active_id=self.code_promotion_program_with_discount.id).create({ 'generation_type': 'nbr_coupon', 'nbr_coupons': 1, }).generate_coupon() coupon = self.code_promotion_program_with_discount.coupon_ids self.env['sale.coupon.apply.code'].with_context(active_id=self.empty_order.id).create({ 'coupon_code': coupon.code, }).process_coupon() self.assertFalse(self.empty_order.applied_coupon_ids, 'No coupon should be linked to the order') self.assertEqual(coupon.state, 'new', 'Coupon should be in a new state')
46.341207
17,656
79,677
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_coupon.tests.common import TestSaleCouponCommon from odoo.exceptions import UserError from odoo.tests import tagged from odoo.tools.float_utils import float_compare @tagged('post_install', '-at_install') class TestSaleCouponProgramNumbers(TestSaleCouponCommon): def setUp(self): super(TestSaleCouponProgramNumbers, self).setUp() self.largeCabinet = self.env['product.product'].create({ 'name': 'Large Cabinet', 'list_price': 320.0, 'taxes_id': False, }) self.conferenceChair = self.env['product.product'].create({ 'name': 'Conference Chair', 'list_price': 16.5, 'taxes_id': False, }) self.pedalBin = self.env['product.product'].create({ 'name': 'Pedal Bin', 'list_price': 47.0, 'taxes_id': False, }) self.drawerBlack = self.env['product.product'].create({ 'name': 'Drawer Black', 'list_price': 25.0, 'taxes_id': False, }) self.largeMeetingTable = self.env['product.product'].create({ 'name': 'Large Meeting Table', 'list_price': 40000.0, 'taxes_id': False, }) self.steve = self.env['res.partner'].create({ 'name': 'Steve Bucknor', 'email': '[email protected]', }) self.empty_order = self.env['sale.order'].create({ 'partner_id': self.steve.id }) self.p1 = self.env['coupon.program'].create({ 'name': 'Code for 10% on orders', 'promo_code_usage': 'code_needed', 'promo_code': 'test_10pc', 'discount_type': 'percentage', 'discount_percentage': 10.0, 'program_type': 'promotion_program', }) self.p2 = self.env['coupon.program'].create({ 'name': 'Buy 3 cabinets, get one for free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'program_type': 'promotion_program', 'reward_product_id': self.largeCabinet.id, 'rule_min_quantity': 3, 'rule_products_domain': '[["name","ilike","large cabinet"]]', }) self.p3 = self.env['coupon.program'].create({ 'name': 'Buy 1 drawer black, get a free Large Meeting Table', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'program_type': 'promotion_program', 'reward_product_id': self.largeMeetingTable.id, 'rule_products_domain': '[["name","ilike","drawer black"]]', }) self.discount_coupon_program = self.env['coupon.program'].create({ 'name': '$100 coupon', 'program_type': 'coupon_program', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 100, 'active': True, 'discount_apply_on': 'on_order', 'rule_minimum_amount': 100.00, }) def test_program_numbers_free_and_paid_product_qty(self): # These tests will focus on numbers (free product qty, SO total, reduction total..) order = self.empty_order sol1 = self.env['sale.order.line'].create({ 'product_id': self.largeCabinet.id, 'name': 'Large Cabinet', 'product_uom_qty': 4.0, 'order_id': order.id, }) # Check we correctly get a free product order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "We should have 2 lines as we now have one 'Free Large Cabinet' line as we bought 4 of them") # Check free product's price is not added to total when applying reduction (Or the discount will also be applied on the free product's price) self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, 'test_10pc') self.assertEqual(len(order.order_line.ids), 3, "We should 3 lines as we should have a new line for promo code reduction") self.assertEqual(order.amount_total, 864, "Only paid product should have their price discounted") order.order_line.filtered(lambda x: 'Discount' in x.name).unlink() # Remove Discount # Check free product is removed since we are below minimum required quantity sol1.product_uom_qty = 3 order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "Free Large Cabinet should have been removed") # Free product in cart will be considered as paid product when changing quantity of paid product, so the free product quantity computation will be wrong. # 100 Large Cabinet in cart, 25 free, set quantity to 10 Large Cabinet, you should have 2 free Large Cabinet but you get 8 because it add the 25 initial free Large Cabinet to the total paid Large Cabinet when computing (25+10 > 35 > /4 = 8 free Large Cabinet) sol1.product_uom_qty = 100 order.recompute_coupon_lines() self.assertEqual(order.order_line.filtered(lambda x: x.is_reward_line).product_uom_qty, 25, "We should have 25 Free Large Cabinet") sol1.product_uom_qty = 10 order.recompute_coupon_lines() self.assertEqual(order.order_line.filtered(lambda x: x.is_reward_line).product_uom_qty, 2, "We should have 2 Free Large Cabinet") def test_program_numbers_check_eligibility(self): # These tests will focus on numbers (free product qty, SO total, reduction total..) # Check if we have enough paid product to receive free product in case of a free product that is different from the paid product required # Buy A, get free b. (remember we need a paid B in cart to receive free b). If your cart is 4A 1B then you should receive 1b (you are eligible to receive 4 because you have 4A but since you dont have enought B in your cart, you are limited to the B quantity) order = self.empty_order sol1 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'name': 'drawer black', 'product_uom_qty': 4.0, 'order_id': order.id, }) sol2 = self.env['sale.order.line'].create({ 'product_id': self.largeMeetingTable.id, 'name': 'Large Meeting Table', 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "We should have a 'Free Large Meeting Table' promotion line") self.assertEqual(order.order_line.filtered(lambda x: x.is_reward_line).product_uom_qty, 1, "We should receive one and only one free Large Meeting Table") # Check the required value amount to be eligible for the program is correctly computed (eg: it does not add negative value (from free product) to total) # A = free b | Have your cart with A 2B b | cart value should be A + 1B but in code it is only A (free b value is subsstract 2 times) # This is because _amount_all() is summing all SO lines (so + (-b.value)) and again in _check_promo_code() order.amount_untaxed + order.reward_amount | amount_untaxed has already free product value substracted (_amount_all) sol1.product_uom_qty = 1 sol2.product_uom_qty = 2 self.p1.rule_minimum_amount = 5000 order.recompute_coupon_lines() self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, 'test_10pc') self.assertEqual(len(order.order_line.ids), 4, "We should have 4 lines as we should have a new line for promo code reduction") # Check you can still have auto applied promotion if you have a promo code set to the order self.env['sale.order.line'].create({ 'product_id': self.largeCabinet.id, 'name': 'Large Cabinet', 'product_uom_qty': 4.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 6, "We should have 2 more lines as we now have one 'Free Large Cabinet' line since we bought 4 of them") def test_program_numbers_taxes_and_rules(self): percent_tax = self.env['account.tax'].create({ 'name': "15% Tax", 'amount_type': 'percent', 'amount': 15, 'price_include': True, }) p_specific_product = self.env['coupon.program'].create({ 'name': '20% reduction on Large Cabinet in cart', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 20.0, 'rule_minimum_amount': 320.00, 'discount_apply_on': 'specific_products', 'discount_specific_product_ids': [(6, 0, [self.largeCabinet.id])], }) order = self.empty_order self.largeCabinet.taxes_id = percent_tax sol1 = self.env['sale.order.line'].create({ 'product_id': self.largeCabinet.id, 'name': 'Large Cabinet', 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "We should not get the reduction line since we dont have 320$ tax excluded (cabinet is 320$ tax included)") sol1.tax_id.price_include = False sol1._compute_tax_id() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "We should now get the reduction line since we have 320$ tax included (cabinet is 320$ tax included)") # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 1 | 320.00 | 15% excl | 320.00 | 368.00 | 48.00 # 20% discount on | 1 | -64.00 | 15% excl | -64.00 | -73.60 | -9.60 # large cabinet | # -------------------------------------------------------------------------------- # TOTAL | 256.00 | 294.40 | 38.40 self.assertAlmostEqual(order.amount_total, 294.4, 2, "Check discount has been applied correctly (eg: on taxes aswell)") # test coupon with code works the same as auto applied_programs p_specific_product.write({'promo_code_usage': 'code_needed', 'promo_code': '20pc'}) order.order_line.filtered(lambda l: l.is_reward_line).unlink() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "Reduction should be removed since we deleted it and it is now a promo code usage, it shouldn't be automatically reapplied") self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, '20pc') order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "We should now get the reduction line since we have 320$ tax included (cabinet is 320$ tax included)") # check discount applied only on Large Cabinet self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'name': 'Drawer Black', 'product_uom_qty': 10.0, 'order_id': order.id, }) order.recompute_coupon_lines() # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Drawer Black | 10 | 25.00 | / | 250.00 | 250.00 | / # Large Cabinet | 1 | 320.00 | 15% excl | 320.00 | 368.00 | 48.00 # 20% discount on | 1 | -64.00 | 15% excl | -64.00 | -73.60 | -9.60 # large cabinet | # -------------------------------------------------------------------------------- # TOTAL | 506.00 | 544.40 | 38.40 self.assertEqual(order.amount_total, 544.4, "We should only get reduction on cabinet") sol1.product_uom_qty = 10 order.recompute_coupon_lines() # Note: Since we now have 2 free Large Cabinet, we should discount only 8 of the 10 Large Cabinet in carts since we don't want to discount free Large Cabinet # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Drawer Black | 10 | 25.00 | / | 250.00 | 250.00 | / # Large Cabinet | 10 | 320.00 | 15% excl | 3200.00 | 3680.00 | 480.00 # Free Large Cabinet | 2 | -320.00 | 15% excl | -640.00 | -736.00 | -96.00 # 20% discount on | 1 | -512.00 | 15% excl | -512.00 | -588.80 | -78.80 # large cabinet | # -------------------------------------------------------------------------------- # TOTAL | 2298.00 | 2605.20 | 305.20 self.assertAlmostEqual(order.amount_total, 2605.20, 2, "Changing cabinet quantity should change discount amount correctly") p_specific_product.discount_max_amount = 200 order.recompute_coupon_lines() # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Drawer Black | 10 | 25.00 | / | 250.00 | 250.00 | / # Large Cabinet | 10 | 320.00 | 15% excl | 3200.00 | 3680.00 | 480.00 # Free Large Cabinet | 2 | -320.00 | 15% excl | -640.00 | -736.00 | -96.00 # 20% discount on | 1 | -200.00 | 15% excl | -200.00 | -230.00 | -30.00 # large cabinet | # limited to 200 HTVA # -------------------------------------------------------------------------------- # TOTAL | 2610.00 | 2964.00 | 354.00 self.assertEqual(order.amount_total, 2964, "The discount should be limited to $200 tax excluded") self.assertEqual(order.amount_untaxed, 2610, "The discount should be limited to $200 tax excluded (2)") def test_program_numbers_one_discount_line_per_tax(self): order = self.empty_order # Create taxes self.tax_15pc_excl = self.env['account.tax'].create({ 'name': "15% Tax excl", 'amount_type': 'percent', 'amount': 15, }) self.tax_50pc_excl = self.env['account.tax'].create({ 'name': "50% Tax excl", 'amount_type': 'percent', 'amount': 50, }) self.tax_35pc_incl = self.env['account.tax'].create({ 'name': "35% Tax incl", 'amount_type': 'percent', 'amount': 35, 'price_include': True, }) # Set tax and prices on products as neeed for the test (self.product_A + self.largeCabinet + self.conferenceChair + self.pedalBin + self.drawerBlack).write({'list_price': 100}) (self.largeCabinet + self.drawerBlack).write({'taxes_id': [(4, self.tax_15pc_excl.id, False)]}) self.conferenceChair.taxes_id = self.tax_10pc_incl self.pedalBin.taxes_id = None self.product_A.taxes_id = (self.tax_35pc_incl + self.tax_50pc_excl) # Add products in order self.env['sale.order.line'].create({ 'product_id': self.largeCabinet.id, 'name': 'Large Cabinet', 'product_uom_qty': 7.0, 'order_id': order.id, }) sol2 = self.env['sale.order.line'].create({ 'product_id': self.conferenceChair.id, 'name': 'Conference Chair', 'product_uom_qty': 5.0, 'order_id': order.id, }) self.env['sale.order.line'].create({ 'product_id': self.pedalBin.id, 'name': 'Pedal Bin', 'product_uom_qty': 10.0, 'order_id': order.id, }) self.env['sale.order.line'].create({ 'product_id': self.product_A.id, 'name': 'product A with multiple taxes', 'product_uom_qty': 3.0, 'order_id': order.id, }) self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'name': 'Drawer Black', 'product_uom_qty': 2.0, 'order_id': order.id, }) # Create needed programs self.p2.active = False self.p_large_cabinet = self.env['coupon.program'].create({ 'name': 'Buy 1 large cabinet, get one for free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'program_type': 'promotion_program', 'reward_product_id': self.largeCabinet.id, 'rule_products_domain': '[["name","ilike","large cabinet"]]', }) self.p_conference_chair = self.env['coupon.program'].create({ 'name': 'Buy 1 chair, get one for free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'program_type': 'promotion_program', 'reward_product_id': self.conferenceChair.id, 'rule_products_domain': '[["name","ilike","conference chair"]]', }) self.p_pedal_bin = self.env['coupon.program'].create({ 'name': 'Buy 1 bin, get one for free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'program_type': 'promotion_program', 'reward_product_id': self.pedalBin.id, 'rule_products_domain': '[["name","ilike","pedal bin"]]', }) # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 5 | 100.00 | 10% incl | 454.55 | 500.00 | 45.45 # Pedal bin | 10 | 100.00 | / | 1000.00 | 1000.00 | / # Large Cabinet | 7 | 100.00 | 15% excl | 700.00 | 805.00 | 105.00 # Drawer Black | 2 | 100.00 | 15% excl | 200.00 | 230.00 | 30.00 # Product A | 3 | 100.00 | 35% incl | 222.22 | 411.11 | 188.89 # 50% excl # -------------------------------------------------------------------------------- # TOTAL | 2576.77 | 2946.11 | 369.34 self.assertEqual(order.amount_total, 2946.11, "The order total without any programs should be 2946.11") self.assertEqual(order.amount_untaxed, 2576.77, "The order untaxed total without any programs should be 2576.77") self.assertEqual(len(order.order_line.ids), 5, "The order without any programs should have 5 lines") # Apply all the programs order.recompute_coupon_lines() # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Free ConferenceChair | 2 | -100.00 | 10% incl | -181.82 | -200.00 | -18.18 # Free Pedal Bin | 5 | -100.00 | / | -500.00 | -500.00 | / # Free Large Cabinet | 3 | -100.00 | 15% excl | -300.00 | -345.00 | -45.00 # -------------------------------------------------------------------------------- # TOTAL AFTER APPLYING FREE PRODUCT PROGRAMS | 1594.95 | 1901.11 | 306.16 self.assertAlmostEqual(order.amount_total, 1901.11, 2, "The order total with programs should be 1901.11") self.assertEqual(order.amount_untaxed, 1594.95, "The order untaxed total with programs should be 1594.95") self.assertEqual(len(order.order_line.ids), 8, "Order should contains 5 regular product lines and 3 free product lines") # Apply 10% on top of everything self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, 'test_10pc') # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # 10% on tax 10% incl | 1 | -30.00 | 10% incl | -27.27 | -30.00 | -2.73 # 10% on no tax | 1 | -50.00 | / | -50.00 | -50.00 | / # 10% on tax 15% excl | 1 | -40.00 | 15% excl | -60.00 | -69.00 | -9.00 # 10% on tax 35%+50% | 1 | -30.00 | 35% incl | -22.22 | -45.00 | -18.89 # 50% excl # -------------------------------------------------------------------------------- # TOTAL AFTER APPLYING 10% GLOBAL PROGRAM | 1435.46 | 1711.00 | 275.54 self.assertEqual(order.amount_total, 1711, "The order total with programs should be 1711") self.assertEqual(order.amount_untaxed, 1435.46, "The order untaxed total with programs should be 1435.46") self.assertEqual(len(order.order_line.ids), 12, "Order should contains 5 regular product lines, 3 free product lines and 4 discount lines (one for every tax)") # -- This is a test inside the test order.order_line._compute_tax_id() self.assertEqual(order.amount_total, 1711, "Recomputing tax on sale order lines should not change total amount") self.assertEqual(order.amount_untaxed, 1435.46, "Recomputing tax on sale order lines should not change untaxed amount") self.assertEqual(len(order.order_line.ids), 12, "Recomputing tax on sale order lines should not change number of order line") order.recompute_coupon_lines() self.assertEqual(order.amount_total, 1711, "Recomputing tax on sale order lines should not change total amount") self.assertEqual(order.amount_untaxed, 1435.46, "Recomputing tax on sale order lines should not change untaxed amount") self.assertEqual(len(order.order_line.ids), 12, "Recomputing tax on sale order lines should not change number of order line") # -- End test inside the test # Now we want to apply a 20% discount only on Large Cabinet self.env['coupon.program'].create({ 'name': '20% reduction on Large Cabinet in cart', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 20.0, 'discount_apply_on': 'specific_products', 'discount_specific_product_ids': [(6, 0, [self.largeCabinet.id])], }) order.recompute_coupon_lines() # Note: we have 7 regular Large Cabinets and 3 free Large Cabinets. We should then discount only 4 really paid Large Cabinets # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # 20% on Large Cabinet | 1 | -80.00 | 15% excl | -80.00 | -92.00 | -12.00 # -------------------------------------------------------------------------------- # TOTAL AFTER APPLYING 20% ON LARGE CABINET | 1355.45 | 1619.00 | 263.54 self.assertEqual(order.amount_total, 1619, "The order total with programs should be 1619") self.assertEqual(order.amount_untaxed, 1355.46, "The order untaxed total with programs should be 1435.45") self.assertEqual(len(order.order_line.ids), 13, "Order should have a new discount line for 20% on Large Cabinet") # Check that if you delete one of the discount tax line, the others tax lines from the same promotion got deleted as well. order.order_line.filtered(lambda l: '10%' in l.name)[0].unlink() self.assertEqual(len(order.order_line.ids), 9, "All of the 10% discount line per tax should be removed") # At this point, removing the Conference Chair's discount line (split per tax) removed also the others discount lines # linked to the same program (eg: other taxes lines). So the coupon got removed from the SO since there were no discount lines left # Add back the coupon to continue the test flow self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, 'test_10pc') order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 13, "The 10% discount line should be back") # Check that if you change a product qty, his discount tax line got updated sol2.product_uom_qty = 7 order.recompute_coupon_lines() # Conference Chair | 5 | 100.00 | 10% incl | 454.55 | 500.00 | 45.45 # Free ConferenceChair | 2 | -100.00 | 10% incl | -181.82 | -200.00 | -18.18 # 10% on tax 10% incl | 1 | -30.00 | 10% incl | -27.27 | -30.00 | -2.73 # -------------------------------------------------------------------------------- # TOTAL OF Conference Chair LINES | 245.46 | 270.00 | 24.54 # ==> Should become: # Conference Chair | 7 | 100.00 | 10% incl | 636.36 | 700.00 | 63.64 # Free ConferenceChair | 3 | -100.00 | 10% incl | -272.73 | -300.00 | -27.27 # 10% on tax 10% incl | 1 | -40.00 | 10% incl | -36.36 | -40.00 | -3.64 # -------------------------------------------------------------------------------- # TOTAL OF Conference Chair LINES | 327.27 | 360.00 | 32.73 # AFTER ADDING 2 Conference Chair | # -------------------------------------------------------------------------------- # => DIFFERENCES BEFORE/AFTER | 81.81 | 90.00 | 8.19 self.assertEqual(order.amount_untaxed, 1355.46 + 81.81, "The order should have one more paid Conference Chair with 10% incl tax and discounted by 10%") # Check that if you remove a product, his reward lines got removed, especially the discount per tax one sol2.unlink() order.recompute_coupon_lines() # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Pedal Bins | 10 | 100.00 | / | 1000.00 | 1000.00 | / # Large Cabinet | 7 | 100.00 | 15% excl | 700.00 | 805.00 | 105.00 # Drawer Black | 2 | 100.00 | 15% excl | 200.00 | 230.00 | 30.00 # Product A | 3 | 100.00 | 35% incl | 222.22 | 411.11 | 188.89 # 50% excl # Free Pedal Bin | 5 | -100.00 | / | -500.00 | -500.00 | / # Free Large Cabinet | 3 | -100.00 | 15% excl | -300.00 | -345.00 | -45.00 # 20% on Large Cabinet | 1 | -80.00 | 15% excl | -80.00 | -92.00 | -12.00 # 10% on no tax | 1 | -50.00 | / | -50.00 | -50.00 | / # 10% on tax 15% excl | 1 | -60.00 | 15% excl | -60.00 | -69.00 | -9.00 # 10% on tax 35%+50% | 1 | -30.00 | 35% incl | -22.22 | -41.11 | -18.89 # 50% excl # -------------------------------------------------------------------------------- # TOTAL | 1110.0 | 1349.11 | 239.0 self.assertAlmostEqual(order.amount_total, 1349.0, 2, "The order total with programs should be 1509.11") self.assertEqual(order.amount_untaxed, 1110.0, "The order untaxed total with programs should be 1242.22") self.assertEqual(len(order.order_line.ids), 10, "Order should contains 7 lines: 4 products lines," " 2 free products lines, a 20% discount line" "and 3 10% discount ") def test_program_numbers_extras(self): # Check that you can't apply a global discount promo code if there is already an auto applied global discount self.p1.copy({'promo_code_usage': 'no_code_needed', 'name': 'Auto applied 10% global discount'}) order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.largeCabinet.id, 'name': 'Large Cabinet', 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "We should get 1 Large Cabinet line and 1 10% auto applied global discount line") self.assertEqual(order.amount_total, 288, "320$ - 10%") with self.assertRaises(UserError): # Can't apply a second global discount self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'test_10pc' }).process_coupon() def test_program_fixed_price(self): # Check fixed amount discount order = self.empty_order fixed_amount_program = self.env['coupon.program'].create({ 'name': '$249 discount', 'promo_code_usage': 'no_code_needed', 'program_type': 'promotion_program', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 249.0, }) self.tax_0pc_excl = self.env['account.tax'].create({ 'name': "0% Tax excl", 'amount_type': 'percent', 'amount': 0, }) fixed_amount_program.discount_line_product_id.write({'taxes_id': [(4, self.tax_0pc_excl.id, False)]}) sol1 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'name': 'Drawer Black', 'product_uom_qty': 1.0, 'order_id': order.id, 'tax_id': [(4, self.tax_0pc_excl.id)] }) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 0, "Total should be null. The fixed amount discount is higher than the SO total, it should be reduced to the SO total") self.assertEqual(len(order.order_line.ids), 2, "There should be the product line and the reward line") sol1.product_uom_qty = 17 order.recompute_coupon_lines() self.assertEqual(order.amount_total, 176, "Fixed amount discount should be totally deduced") self.assertEqual(len(order.order_line.ids), 2, "Number of lines should be unchanged as we just recompute the reward line") sol2 = order.order_line.filtered(lambda l: l.id != sol1.id) self.assertEqual(len(sol2.tax_id.ids), 1, "One tax should be present on the reward line") self.assertEqual(sol2.tax_id.id, self.tax_0pc_excl.id, "The tax should be 0% Tax excl") fixed_amount_program.write({'active': False}) # Check archived product will remove discount lines on recompute order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "Archiving the program should remove the program reward line") def test_program_next_order(self): order = self.empty_order self.env['coupon.program'].create({ 'name': 'Free Pedal Bin if at least 1 article', 'promo_code_usage': 'no_code_needed', 'promo_applicability': 'on_next_order', 'program_type': 'promotion_program', 'reward_type': 'product', 'reward_product_id': self.pedalBin.id, 'rule_min_quantity': 2, }) sol1 = self.env['sale.order.line'].create({ 'product_id': self.largeCabinet.id, 'name': 'Large Cabinet', 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "Nothing should be added to the cart") self.assertEqual(len(order.generated_coupon_ids), 0, "No coupon should have been generated yet") sol1.product_uom_qty = 2 order.recompute_coupon_lines() generated_coupon = order.generated_coupon_ids self.assertEqual(len(order.order_line.ids), 1, "Nothing should be added to the cart (2)") self.assertEqual(len(generated_coupon), 1, "A coupon should have been generated") self.assertEqual(generated_coupon.state, 'reserved', "The coupon should be reserved") sol1.product_uom_qty = 1 order.recompute_coupon_lines() generated_coupon = order.generated_coupon_ids self.assertEqual(len(order.order_line.ids), 1, "Nothing should be added to the cart (3)") self.assertEqual(len(generated_coupon), 1, "No more coupon should have been generated and the existing one should not have been deleted") self.assertEqual(generated_coupon.state, 'expired', "The coupon should have been set as expired as it is no more valid since we don't have the required quantity") sol1.product_uom_qty = 2 order.recompute_coupon_lines() generated_coupon = order.generated_coupon_ids self.assertEqual(len(generated_coupon), 1, "We should still have only 1 coupon as we now benefit again from the program but no need to create a new one (see next assert)") self.assertEqual(generated_coupon.state, 'reserved', "The coupon should be set back to reserved as we had already an expired one, no need to create a new one") def test_coupon_rule_minimum_amount(self): """ Ensure coupon with minimum amount rule are correctly applied on orders """ order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.conferenceChair.id, 'name': 'Conference Chair', 'product_uom_qty': 10.0, 'order_id': order.id, }) self.assertEqual(order.amount_total, 165.0, "The order amount is not correct") self.env['coupon.generate.wizard'].with_context(active_id=self.discount_coupon_program.id).create({}).generate_coupon() coupon = self.discount_coupon_program.coupon_ids[0] self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() self.assertEqual(order.amount_total, 65.0, "The coupon should be correctly applied") order.recompute_coupon_lines() self.assertEqual(order.amount_total, 65.0, "The coupon should not be removed from the order") def test_coupon_and_program_discount_fixed_amount(self): """ Ensure coupon and program discount both with minimum amount rule can cohexists without making the order go below 0 """ order = self.empty_order orderline = self.env['sale.order.line'].create({ 'product_id': self.conferenceChair.id, 'name': 'Conference Chair', 'product_uom_qty': 10.0, 'order_id': order.id, }) self.assertEqual(order.amount_total, 165.0, "The order amount is not correct") self.env['coupon.program'].create({ 'name': '$100 promotion program', 'program_type': 'promotion_program', 'promo_code_usage': 'code_needed', 'promo_code': 'testpromo', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 100, 'active': True, 'discount_apply_on': 'on_order', 'rule_minimum_amount': 100.00, }) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'testpromo' }).process_coupon() self.assertEqual(order.amount_total, 65.0, "The promotion program should be correctly applied") order.recompute_coupon_lines() self.assertEqual(order.amount_total, 65.0, "The promotion program should not be removed after recomputation") self.env['coupon.generate.wizard'].with_context(active_id=self.discount_coupon_program.id).create({}).generate_coupon() coupon = self.discount_coupon_program.coupon_ids[0] with self.assertRaises(UserError): self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() orderline.write({'product_uom_qty': 15}) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() self.assertEqual(order.amount_total, 47.5, "The promotion program should now be correctly applied") orderline.write({'product_uom_qty': 5}) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 82.5, "The promotion programs should have been removed from the order to avoid negative amount") def test_coupon_and_coupon_discount_fixed_amount_tax_excl(self): """ Ensure multiple coupon can cohexists without making the order go below 0 * Have an order of 300 (3 lines: 1 tax excl 15%, 2 notax) * Apply a coupon A of 10% discount, unconditioned * Apply a coupon B of 288.5 discount, unconditioned * Order should not go below 0 * Even applying the coupon in reverse order should yield same result """ coupon_program = self.env['coupon.program'].create({ 'name': '$288.5 coupon', 'program_type': 'coupon_program', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 288.5, 'active': True, 'discount_apply_on': 'on_order', }) order = self.empty_order orderline = self.env['sale.order.line'].create([ { 'product_id': self.conferenceChair.id, 'name': 'Conference Chair', 'product_uom_qty': 1.0, 'price_unit': 100.0, 'order_id': order.id, 'tax_id': [(6, 0, (self.tax_15pc_excl.id,))], }, { 'product_id': self.pedalBin.id, 'name': 'Computer Case', 'product_uom_qty': 1.0, 'price_unit': 100.0, 'order_id': order.id, 'tax_id': [(6, 0, [])], }, { 'product_id': self.product_A.id, 'name': 'Computer Case', 'product_uom_qty': 1.0, 'price_unit': 100.0, 'order_id': order.id, 'tax_id': [(6, 0, [])], }, ]) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'test_10pc' }).process_coupon() self.assertEqual(order.amount_total, 283.5, "The promotion program should be correctly applied") self.env['coupon.generate.wizard'].with_context(active_id=coupon_program.id).create({ 'generation_type': 'nbr_coupon', 'nbr_coupons': 1, }).generate_coupon() coupon = coupon_program.coupon_ids self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() order.recompute_coupon_lines() self.assertEqual(order.amount_tax, 0) self.assertEqual(order.amount_untaxed, 0.0, "The untaxed amount should not go below 0") self.assertEqual(order.amount_total, 0, "The promotion program should not make the order total go below 0") order.order_line[3:].unlink() #remove all coupon order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 3, "The promotion program should be removed") self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() self.assertEqual(order.amount_total, 26.5, "The promotion program should be correctly applied") order.recompute_coupon_lines() self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'test_10pc' }).process_coupon() order.recompute_coupon_lines() self.assertEqual(order.amount_tax, 0) self.assertEqual(order.amount_untaxed, 0.0) self.assertEqual(order.amount_total, 0, "The promotion program should not make the order total go below 0be altered after recomputation") def test_coupon_and_coupon_discount_fixed_amount_tax_incl(self): """ Ensure multiple coupon can cohexists without making the order go below 0 * Have an order of 300 (3 lines: 1 tax incl 10%, 2 notax) * Apply a coupon A of 10% discount, unconditioned * Apply a coupon B of 290 discount, unconditioned * Order should not go below 0 * Even applying the coupon in reverse order should yield same result """ coupon_program = self.env['coupon.program'].create({ 'name': '$290 coupon', 'program_type': 'coupon_program', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 290, 'active': True, 'discount_apply_on': 'on_order', }) order = self.empty_order self.env['sale.order.line'].create([ { 'product_id': self.conferenceChair.id, 'name': 'Conference Chair', 'product_uom_qty': 1.0, 'price_unit': 100.0, 'order_id': order.id, 'tax_id': [(6, 0, (self.tax_10pc_incl.id,))], }, { 'product_id': self.pedalBin.id, 'name': 'Computer Case', 'product_uom_qty': 1.0, 'price_unit': 100.0, 'order_id': order.id, 'tax_id': [(6, 0, [])], }, { 'product_id': self.product_A.id, 'name': 'Computer Case', 'product_uom_qty': 1.0, 'price_unit': 100.0, 'order_id': order.id, 'tax_id': [(6, 0, [])], }, ]) self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'test_10pc' }).process_coupon() self.assertEqual(order.amount_total, 270.0, "The promotion program should be correctly applied") self.env['coupon.generate.wizard'].with_context(active_id=coupon_program.id).create({ 'generation_type': 'nbr_coupon', 'nbr_coupons': 1, }).generate_coupon() coupon = coupon_program.coupon_ids self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() self.assertEqual(order.amount_total, 0.0, "The promotion program should not make the order total go below 0") order.recompute_coupon_lines() self.assertEqual(order.amount_total, 0.0, "The promotion program should not be altered after recomputation") order.order_line[3:].unlink() #remove all coupon order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 3, "The promotion program should be removed") self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() self.assertEqual(order.amount_total, 10.0, "The promotion program should be correctly applied") order.recompute_coupon_lines() self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': 'test_10pc' }).process_coupon() order.recompute_coupon_lines() self.assertEqual(order.amount_total, 0.0, "The promotion program should not be altered after recomputation") def test_program_percentage_discount_on_product_included_tax(self): # test 100% percentage discount (tax included) program = self.env['coupon.program'].create({ 'name': '100% discount', 'promo_code_usage': 'no_code_needed', 'program_type': 'promotion_program', 'discount_percentage': 100.0, 'rule_minimum_amount_tax_inclusion': 'tax_included', }) self.tax_10pc_incl.price_include = True self.drawerBlack.taxes_id = self.tax_10pc_incl order = self.empty_order order.order_line = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The discount should be applied") self.assertEqual(order.amount_total, 0.0, "Order should be 0 as it is a 100% discount") # test 95% percentage discount (tax included) program.discount_percentage = 95 order.recompute_coupon_lines() # lst_price is 25$ so total now should be 1.25$ (1.14$ + 0.11$ taxes) self.assertEqual(len(order.order_line.ids), 2, "The discount should be applied") self.assertAlmostEqual(order.amount_tax, 0.11, places=2) self.assertAlmostEqual(order.amount_untaxed, 1.14, places=2) def test_program_discount_on_multiple_specific_products(self): """ Ensure a discount on multiple specific products is correctly computed. - Simple: Discount must be applied on all the products set on the promotion - Advanced: This discount must be split by different taxes """ order = self.empty_order p_specific_products = self.env['coupon.program'].create({ 'name': '20% reduction on Conference Chair and Drawer Black in cart', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 25.0, 'discount_apply_on': 'specific_products', 'discount_specific_product_ids': [(6, 0, [self.conferenceChair.id, self.drawerBlack.id])], }) self.env['sale.order.line'].create({ 'product_id': self.conferenceChair.id, 'name': 'Conference Chair', 'product_uom_qty': 4.0, 'order_id': order.id, }) sol2 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'name': 'Drawer Black', 'product_uom_qty': 2.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "Conference Chair + Drawer Black + 20% discount line") # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 4 | 16.50 | / | 66.00 | 66.00 | 0.00 # Drawer Black | 2 | 25.00 | / | 50.00 | 50.00 | 0.00 # 25% discount | 1 | -29.00 | / | -29.00 | -29.00 | 0.00 # -------------------------------------------------------------------------------- # TOTAL | 87.00 | 87.00 | 0.00 self.assertEqual(order.amount_total, 87.00, "Total should be 87.00, see above comment") # remove Drawer Black case from promotion p_specific_products.discount_specific_product_ids = [(6, 0, [self.conferenceChair.id])] order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "Should still be Conference Chair + Drawer Black + 20% discount line") # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 4 | 16.50 | / | 66.00 | 66.00 | 0.00 # Drawer Black | 2 | 25.00 | / | 50.00 | 50.00 | 0.00 # 25% discount | 1 | -16.50 | / | -16.50 | -16.50 | 0.00 # -------------------------------------------------------------------------------- # TOTAL | 99.50 | 99.50 | 0.00 self.assertEqual(order.amount_total, 99.50, "The 12.50 discount from the drawer black should be gone") # ========================================================================= # PART 2: Same flow but with different taxes on products to ensure discount is split per VAT # Add back Drawer Black in promotion p_specific_products.discount_specific_product_ids = [(6, 0, [self.conferenceChair.id, self.drawerBlack.id])] percent_tax = self.env['account.tax'].create({ 'name': "30% Tax", 'amount_type': 'percent', 'amount': 30, 'price_include': True, }) sol2.tax_id = percent_tax order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 4, "Conference Chair + Drawer Black + 20% on no TVA product (Conference Chair) + 20% on 15% tva product (Drawer Black)") # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 4 | 16.50 | / | 66.00 | 66.00 | 0.00 # Drawer Black | 2 | 25.00 | 30% incl | 38.46 | 50.00 | 11.54 # 25% discount | 1 | -16.50 | / | -16.50 | -16.50 | 0.00 # 25% discount | 1 | -12.50 | 30% incl | -9.62 | -12.50 | -2.88 # -------------------------------------------------------------------------------- # TOTAL | 78.34 | 87.00 | 8.66 self.assertEqual(order.amount_total, 87.00, "Total untaxed should be as per above comment") self.assertEqual(order.amount_untaxed, 78.34, "Total with taxes should be as per above comment") def test_program_numbers_free_prod_with_min_amount_and_qty_on_same_prod(self): # This test focus on giving a free product based on both # minimum amount and quantity condition on an # auto applied promotion program order = self.empty_order self.p3 = self.env['coupon.program'].create({ 'name': 'Buy 2 Chairs, get 1 free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'program_type': 'promotion_program', 'reward_product_id': self.conferenceChair.id, 'rule_min_quantity': 2, 'rule_minimum_amount': self.conferenceChair.lst_price * 2, 'rule_products_domain': '[["sale_ok","=",True], ["id","=", %d]]' % self.conferenceChair.id, }) sol1 = self.env['sale.order.line'].create({ 'product_id': self.conferenceChair.id, 'name': 'Conf Chair', 'product_uom_qty': 2.0, 'order_id': order.id, }) sol2 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'name': 'Drawer', 'product_uom_qty': 1.0, 'order_id': order.id, }) # dummy line order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The promotion lines should not be applied") sol1.write({'product_uom_qty': 3.0}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "The promotion lines should have been added") self.assertEqual(order.amount_total, self.conferenceChair.lst_price * (sol1.product_uom_qty - 1) + self.drawerBlack.lst_price * sol2.product_uom_qty, "The promotion line was not applied to the amount total") sol2.unlink() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The other product should not affect the promotion") self.assertEqual(order.amount_total, self.conferenceChair.lst_price * (sol1.product_uom_qty - 1), "The promotion line was not applied to the amount total") sol1.write({'product_uom_qty': 2.0}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "The promotion lines should have been removed") def test_program_step_percentages(self): # test step-like percentages increase over amount testprod = self.env['product.product'].create({ 'name': 'testprod', 'lst_price': 118.0, }) self.env['coupon.program'].create({ 'name': '10% discount', 'promo_code_usage': 'no_code_needed', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 10.0, 'rule_minimum_amount': 1500.0, 'rule_minimum_amount_tax_inclusion': 'tax_included', }) self.env['coupon.program'].create({ 'name': '15% discount', 'promo_code_usage': 'no_code_needed', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 15.0, 'rule_minimum_amount': 1750.0, 'rule_minimum_amount_tax_inclusion': 'tax_included', }) self.env['coupon.program'].create({ 'name': '20% discount', 'promo_code_usage': 'no_code_needed', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 20.0, 'rule_minimum_amount': 2000.0, 'rule_minimum_amount_tax_inclusion': 'tax_included', }) self.env['coupon.program'].create({ 'name': '25% discount', 'promo_code_usage': 'no_code_needed', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 25.0, 'rule_minimum_amount': 2500.0, 'rule_minimum_amount_tax_inclusion': 'tax_included', }) #apply 10% order = self.empty_order order_line = self.env['sale.order.line'].create({ 'product_id': testprod.id, 'name': 'testprod', 'product_uom_qty': 14.0, 'price_unit': 118.0, 'order_id': order.id, 'tax_id': False, }) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 1486.80, "10% discount should be applied") self.assertEqual(len(order.order_line.ids), 2, "discount should be applied") #switch to 15% order_line.write({'product_uom_qty': 15}) self.assertEqual(order.amount_total, 1604.8, "Discount improperly applied") self.assertEqual(len(order.order_line.ids), 2, "No discount applied while it should") #switch to 20% order_line.write({'product_uom_qty': 17}) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 1604.8, "Discount improperly applied") self.assertEqual(len(order.order_line.ids), 2, "No discount applied while it should") #still 20% order_line.write({'product_uom_qty': 20}) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 1888.0, "Discount improperly applied") self.assertEqual(len(order.order_line.ids), 2, "No discount applied while it should") #back to 10% order_line.write({'product_uom_qty': 14}) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 1486.80, "Discount improperly applied") self.assertEqual(len(order.order_line.ids), 2, "No discount applied while it should") def test_program_free_prods_with_min_qty_and_reward_qty_and_rule(self): order = self.empty_order coupon_program = self.env['coupon.program'].create({ 'name': '2 free conference chair if at least 1 large cabinet', 'promo_code_usage': 'code_needed', 'program_type': 'promotion_program', 'reward_type': 'product', 'reward_product_quantity': 2, 'reward_product_id': self.conferenceChair.id, 'rule_min_quantity': 1, 'rule_products_domain': '["&", ["sale_ok","=",True], ["name","ilike","large cabinet"]]', }) # set large cabinet and conference chair prices self.largeCabinet.write({'list_price': 500, 'sale_ok': True,}) self.conferenceChair.write({'list_price': 100, 'sale_ok': True}) # create SOL self.env['sale.order.line'].create({ 'product_id': self.largeCabinet.id, 'name': 'Large Cabinet', 'product_uom_qty': 1.0, 'order_id': order.id, }) sol2 = self.env['sale.order.line'].create({ 'product_id': self.conferenceChair.id, 'name': 'Conference chair', 'product_uom_qty': 2.0, 'order_id': order.id, }) self.assertEqual(len(order.order_line), 2, 'The order must contain 2 order lines since the coupon is not yet applied') self.assertEqual(order.amount_total, 700.0, 'The price must be 500.0 since the coupon is not yet applied') # generate and apply coupon self.env['coupon.generate.wizard'].with_context(active_id=coupon_program.id).create({ 'generation_type': 'nbr_coupon', 'nbr_coupons': 1, }).generate_coupon() coupon = coupon_program.coupon_ids self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({ 'coupon_code': coupon.code }).process_coupon() # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 2 | 100.00 | / | 200.00 | 200.00 | / # Large Cabinet | 1 | 500.00 | / | 500.00 | 500.00 | / # # Free Conference Chair | 2 | -100.00 | / | -200.00 | -200.00 | / # -------------------------------------------------------------------------------- # TOTAL | 500.00 | 500.00 | / self.assertEqual(len(order.order_line), 3, 'The order must contain 3 order lines including one for free conference chair') self.assertEqual(order.amount_total, 500.0, 'The price must be 500.0 since two conference chairs are free') self.assertEqual(order.order_line[2].price_total, -200.0, 'The last order line should apply a reduction of 200.0 since there are two conference chairs that cost 100.0 each') # prevent user to get illicite discount by decreasing the to 1 the reward product qty after applying the coupon sol2.product_uom_qty = 1.0 order.recompute_coupon_lines() # in this case user should not have -200.0 # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 1 | 100.00 | / | 100.00 | 100.00 | / # Large Cabine | 1 | 500.00 | / | 500.00 | 500.00 | / # # Free Conference Chair | 2 | -100.00 | / | -200.00 | -200.00 | / # -------------------------------------------------------------------------------- # TOTAL | 400.00 | 400.00 | / # he should rather have this one # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | # -------------------------------------------------------------------------------- # Conference Chair | 1 | 100.00 | / | 100.00 | 100.00 | / # Large Cabinet | 1 | 500.00 | / | 500.00 | 500.00 | / # # Free Conference Chair | 1 | -100.00 | / | -100.00 | -100.00 | / # -------------------------------------------------------------------------------- # TOTAL | 500.00 | 500.00 | / self.assertEqual(order.amount_total, 500.0, 'The price must be 500.0 since two conference chairs are free and the user only bought one') self.assertEqual(order.order_line[2].price_total, -100.0, 'The last order line should apply a reduction of 100.0 since there is one conference chair that cost 100.0') def test_program_free_product_different_than_rule_product_with_multiple_application(self): order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'product_uom_qty': 2.0, 'order_id': order.id, }) sol_B = self.env['sale.order.line'].create({ 'product_id': self.largeMeetingTable.id, 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 3, 'The order must contain 3 order lines: 1x for Black Drawer, 1x for Large Meeting Table and 1x for free Large Meeting Table') self.assertEqual(order.amount_total, self.drawerBlack.list_price * 2, 'The price must be 50.0 since the Large Meeting Table is free: 2*25.00 (Black Drawer) + 1*40000.00 (Large Meeting Table) - 1*40000.00 (free Large Meeting Table)') self.assertEqual(order.order_line.filtered(lambda x: x.is_reward_line).product_uom_qty, 1, "Only one free Large Meeting Table should be offered, as only one paid Large Meeting Table is in cart. You can't have more free product than paid product.") sol_B.product_uom_qty = 2 order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 3, 'The order must contain 3 order lines: 1x for Black Drawer, 1x for Large Meeting Table and 1x for free Large Meeting Table') self.assertEqual(order.amount_total, self.drawerBlack.list_price * 2, 'The price must be 50.0 since the 2 Large Meeting Table are free: 2*25.00 (Black Drawer) + 2*40000.00 (Large Meeting Table) - 2*40000.00 (free Large Meeting Table)') self.assertEqual(order.order_line.filtered(lambda x: x.is_reward_line).product_uom_qty, 2, 'The 2 Large Meeting Table should be offered, as the promotion says 1 Black Drawer = 1 free Large Meeting Table and there are 2 Black Drawer') def test_program_modify_reward_line_qty(self): order = self.empty_order product_F = self.env['product.product'].create({ 'name': 'Product F', 'list_price': 100, 'sale_ok': True, 'taxes_id': [(6, 0, [])], }) self.env['coupon.program'].create({ 'name': '1 Product F = 5$ discount', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 5, 'rule_products_domain': "[('id', 'in', [%s])]" % (product_F.id), 'active': True, }) self.env['sale.order.line'].create({ 'product_id': product_F.id, 'product_uom_qty': 2.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 2, 'The order must contain 2 order lines: 1x Product F and 1x 5$ discount') self.assertEqual(order.amount_total, 195.0, 'The price must be 195.0 since there is a 5$ discount and 2x Product F') self.assertEqual(order.order_line.filtered(lambda x: x.is_reward_line).product_uom_qty, 1, 'The reward line should have a quantity of 1 since Fixed Amount discounts apply only once per Sale Order') order.order_line[1].product_uom_qty = 2 self.assertEqual(len(order.order_line), 2, 'The order must contain 2 order lines: 1x Product F and 1x 5$ discount') self.assertEqual(order.amount_total, 190.0, 'The price must be 190.0 since there is now 2x 5$ discount and 2x Product F') self.assertEqual(order.order_line.filtered(lambda x: x.is_reward_line).price_unit, -5, 'The discount unit price should still be -5 after the quantity was manually changed') def test_program_maximum_use_number_with_other_promo(self): self.env['coupon.program'].create({ 'name': '20% discount on first order', 'promo_code_usage': 'no_code_needed', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 20.0, 'maximum_use_number': 1, }) self.p1.promo_code_usage = 'no_code_needed' #check that 20% is applied at first order order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 20.0, "20% discount should be applied") self.assertEqual(len(order.order_line.ids), 2, "discount should be applied") #check that 10% is applied at second order order2 = self.env['sale.order'].create({'partner_id': self.steve.id}) self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'product_uom_qty': 1.0, 'order_id': order2.id, }) order2.recompute_coupon_lines() self.assertEqual(order2.amount_total, 22.5, "10% discount should be applied") self.assertEqual(len(order2.order_line.ids), 2, "discount should be applied") def test_program_maximum_use_number_last_order(self): # reuse p1 with a different promo code and a maximum_use_number of 1 self.p1.promo_code = 'promo1' self.p1.maximum_use_number = 1 # check that the discount is applied on the first order order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'product_uom_qty': 1.0, 'order_id': order.id, }) self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, 'promo1') order.recompute_coupon_lines() self.assertEqual(order.amount_total, 22.5, "10% discount should be applied") self.assertEqual(len(order.order_line.ids), 2, "discount should be applied") # duplicating to mimic website behavior (each refresh to /shop/cart # recompute coupon lines if website_sale_coupon is installed) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 22.5, "10% discount should be applied") self.assertEqual(len(order.order_line.ids), 2, "discount should be applied") # applying the code again should return that it has been expired. self.assertDictEqual(self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, 'promo1'), {'error': 'Promo code promo1 has been expired.'}) def test_fixed_amount_taxes_attribution(self): self.env['coupon.program'].create({ 'name': '$5 coupon', 'program_type': 'promotion_program', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 5, 'active': True, 'discount_apply_on': 'on_order', }) order = self.empty_order sol = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 10, 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 5, 'Price should be 10$ - 5$(discount) = 5$') self.assertEqual(order.amount_tax, 0, 'No taxes are applied yet') sol.tax_id = self.tax_10pc_base_incl order.recompute_coupon_lines() self.assertEqual(order.amount_total, 5, 'Price should be 10$ - 5$(discount) = 5$') self.assertEqual(float_compare(order.amount_tax, 5 / 11, precision_rounding=3), 0, '10% Tax included in 5$') sol.tax_id = self.tax_10pc_excl order.recompute_coupon_lines() # Value is 5.99 instead of 6 because you cannot have 6 with 10% tax excluded and a precision rounding of 2 self.assertAlmostEqual(order.amount_total, 6, 1, msg='Price should be 11$ - 5$(discount) = 6$') self.assertEqual(float_compare(order.amount_tax, 6 / 11, precision_rounding=3), 0, '10% Tax included in 6$') sol.tax_id = self.tax_20pc_excl order.recompute_coupon_lines() self.assertEqual(order.amount_total, 7, 'Price should be 12$ - 5$(discount) = 7$') self.assertEqual(float_compare(order.amount_tax, 7 / 12, precision_rounding=3), 0, '20% Tax included on 7$') sol.tax_id = self.tax_10pc_base_incl + self.tax_10pc_excl order.recompute_coupon_lines() self.assertAlmostEqual(order.amount_total, 6, 1, msg='Price should be 11$ - 5$(discount) = 6$') self.assertEqual(float_compare(order.amount_tax, 6 / 12, precision_rounding=3), 0, '20% Tax included on 6$') def test_fixed_amount_taxes_attribution_multiline(self): self.env['coupon.program'].create({ 'name': '$5 coupon', 'program_type': 'promotion_program', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 5, 'active': True, 'discount_apply_on': 'on_order', }) order = self.empty_order sol1 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 10, 'product_uom_qty': 1.0, 'order_id': order.id, }) sol2 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 10, 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertAlmostEqual(order.amount_total, 15, 1, msg='Price should be 20$ - 5$(discount) = 15$') self.assertEqual(order.amount_tax, 0, 'No taxes are applied yet') sol1.tax_id = self.tax_10pc_base_incl order.recompute_coupon_lines() self.assertAlmostEqual(order.amount_total, 15, 1, msg='Price should be 20$ - 5$(discount) = 15$') self.assertEqual(float_compare(order.amount_tax, 5 / 11 + 0, precision_rounding=3), 0, '10% Tax included in 5$ in sol1 (highest cost) and 0 in sol2') sol2.tax_id = self.tax_10pc_excl order.recompute_coupon_lines() self.assertAlmostEqual(order.amount_total, 16, 1, msg='Price should be 21$ - 5$(discount) = 16$') # Tax amount = 10% in 10$ + 10% in 11$ - 10% in 5$ (apply on excluded) self.assertEqual(float_compare(order.amount_tax, 5 / 11, precision_rounding=3), 0) sol2.tax_id = self.tax_10pc_base_incl + self.tax_10pc_excl order.recompute_coupon_lines() self.assertAlmostEqual(order.amount_total, 16, 1, msg='Price should be 21$ - 5$(discount) = 16$') # Promo apply on line 2 (10% inc + 10% exc) # Tax amount = 10% in 10$ + 10% in 10$ + 10% in 11 - 10% in 5$ - 10% in 4.55$ (100/110*5) # = 10/11 + 10/11 + 11/11 - 5/11 - 4.55/11 # = 21.45/11 self.assertEqual(float_compare(order.amount_tax, 21.45 / 11, precision_rounding=3), 0) sol3 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 10, 'product_uom_qty': 1.0, 'order_id': order.id, }) sol3.tax_id = self.tax_10pc_excl order.recompute_coupon_lines() self.assertAlmostEqual(order.amount_total, 27, 1, msg='Price should be 32$ - 5$(discount) = 27$') # Promo apply on line 2 (10% inc + 10% exc) # Tax amount = 10% in 10$ + 10% in 10$ + 10% in 11$ + 10% in 11$ - 10% in 5$ - 10% in 4.55$ (100/110*5) # = 10/11 + 10/11 + 11/11 + 11/11 - 5/11 - 4.55/11 # = 32.45/11 self.assertEqual(float_compare(order.amount_tax, 32.45 / 11, precision_rounding=3), 0) def test_order_promo(self): promo_5off = self.env['coupon.program'].create({ 'name': '$5 coupon', 'program_type': 'promotion_program', 'promo_code_usage': 'code_needed', 'promo_code': '5off', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 5, 'discount_apply_on': 'on_order', }) promo_20pc = self.env['coupon.program'].create({ 'name': '20% reduction on order', 'promo_code_usage': 'no_code_needed', 'promo_code': '20pc', 'reward_type': 'discount', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 20.0, 'discount_apply_on': 'on_order', }) order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 10, 'product_uom_qty': 1.0, 'order_id': order.id, }) # Test percentage then flat order.recompute_coupon_lines() self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, '5off') order.recompute_coupon_lines() self.assertEqual(order.amount_total, 3, 'Price should be 10$ - 2$(20% of 10$) - 5$(flat discount) = 3$') self.assertEqual(len(order.order_line), 3, 'There should be 3 lines') order.order_line[1:].unlink() # Test flat then percentage promo_20pc.promo_code_usage = 'code_needed' promo_5off.promo_code_usage = 'no_code_needed' order.recompute_coupon_lines() self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, '20pc') order.recompute_coupon_lines() self.assertEqual(order.amount_total, 3, 'Price should be 10$ - 2$(20% of 10$) - 5$(flat discount) = 3$') self.assertEqual(len(order.order_line), 3, 'There should be 3 lines') # Test reapplying already present promo self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, '20pc') order.recompute_coupon_lines() self.assertEqual(order.amount_total, 3, 'Price should be 10$ - 2$(20% of 10$) - 5$(flat discount) = 3$') self.assertEqual(len(order.order_line), 3, 'There should be 3 lines') def test_fixed_amount_with_negative_cost(self): self.env['coupon.program'].create({ 'name': '$10 coupon', 'program_type': 'promotion_program', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 10, 'active': True, 'discount_apply_on': 'on_order', }) order = self.empty_order sol1 = self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 10, 'product_uom_qty': 1.0, 'order_id': order.id, }) self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'name': 'hand discount', 'price_unit': -5, 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 3, 'Promotion should add 1 line') self.assertEqual(order.amount_total, 0, '10$ discount should cover the whole price') sol1.price_unit = 20 order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 3, 'Promotion should add 1 line') self.assertEqual(order.amount_total, 5, '10$ discount should be applied on top of the 15$ original price') def test_fixed_amount_with_tax_sale_order_amount_remain_positive(self): prod = self.env['coupon.program'].create({ 'name': '$10 coupon', 'program_type': 'promotion_program', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 10, 'active': True, 'discount_apply_on': 'on_order', }) prod.discount_line_product_id.taxes_id = self.tax_15pc_excl order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 5, 'product_uom_qty': 1.0, 'order_id': order.id, 'tax_id': self.tax_15pc_excl, }) order.recompute_coupon_lines() self.assertEqual(order.amount_total, 0, 'Sale Order total amount cannot be negative') def test_fixed_amount_change_promo_amount(self): promo = self.env['coupon.program'].create({ 'name': '$10 coupon', 'program_type': 'promotion_program', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'discount_type': 'fixed_amount', 'discount_fixed_amount': 10, 'active': True, 'discount_apply_on': 'on_order', }) order = self.empty_order self.env['sale.order.line'].create({ 'product_id': self.drawerBlack.id, 'price_unit': 10, 'product_uom_qty': 1.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 2, 'Promotion should add 1 line') self.assertEqual(order.amount_total, 0, '10$ - 10$(discount) = 0$(total) ') promo.discount_fixed_amount = 5 order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 2, 'Promotion should add 1 line') self.assertEqual(order.amount_total, 5, '10$ - 5$(discount) = 5$(total) ') promo.discount_fixed_amount = 0 order.recompute_coupon_lines() self.assertEqual(len(order.order_line), 1, 'Promotion line should not be present') self.assertEqual(order.amount_total, 10, '10$ - 0$(discount) = 10$(total) ')
51.704737
79,677
4,230
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 class TestSaleCouponCommon(TestSaleProductAttributeValueCommon): @classmethod def setUpClass(cls): super(TestSaleCouponCommon, cls).setUpClass() # set currency to not rely on demo data and avoid possible race condition cls.currency_ratio = 1.0 pricelist = cls.env.ref('product.list0') pricelist.currency_id = cls._setup_currency(cls.currency_ratio) # Set all the existing programs to active=False to avoid interference cls.env['coupon.program'].search([]).write({'active': False}) # create partner for sale order. cls.steve = cls.env['res.partner'].create({ 'name': 'Steve Bucknor', 'email': '[email protected]', }) cls.empty_order = cls.env['sale.order'].create({ 'partner_id': cls.steve.id }) cls.uom_unit = cls.env.ref('uom.product_uom_unit') # Taxes cls.tax_15pc_excl = cls.env['account.tax'].create({ 'name': "Tax 15%", 'amount_type': 'percent', 'amount': 15, 'type_tax_use': 'sale', }) cls.tax_10pc_incl = cls.env['account.tax'].create({ 'name': "10% Tax incl", 'amount_type': 'percent', 'amount': 10, 'price_include': True, }) cls.tax_10pc_base_incl = cls.env['account.tax'].create({ 'name': "10% Tax incl base amount", 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'include_base_amount': True, }) cls.tax_10pc_excl = cls.env['account.tax'].create({ 'name': "10% Tax excl", 'amount_type': 'percent', 'amount': 10, 'price_include': False, }) cls.tax_20pc_excl = cls.env['account.tax'].create({ 'name': "20% Tax excl", 'amount_type': 'percent', 'amount': 20, 'price_include': False, }) #products cls.product_A = cls.env['product.product'].create({ 'name': 'Product A', 'list_price': 100, 'sale_ok': True, 'taxes_id': [(6, 0, [cls.tax_15pc_excl.id])], }) cls.product_B = cls.env['product.product'].create({ 'name': 'Product B', 'list_price': 5, 'sale_ok': True, 'taxes_id': [(6, 0, [cls.tax_15pc_excl.id])], }) cls.product_C = cls.env['product.product'].create({ 'name': 'Product C', 'list_price': 100, 'sale_ok': True, 'taxes_id': [(6, 0, [])], }) # Immediate Program By A + B: get B free # No Conditions cls.immediate_promotion_program = cls.env['coupon.program'].create({ 'name': 'Buy A + 1 B, 1 B are free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'reward_product_id': cls.product_B.id, 'rule_products_domain': "[('id', 'in', [%s])]" % (cls.product_A.id), 'active': True, }) cls.code_promotion_program = cls.env['coupon.program'].create({ 'name': 'Buy 1 A + Enter code, 1 A is free', 'promo_code_usage': 'code_needed', 'reward_type': 'product', 'reward_product_id': cls.product_A.id, 'rule_products_domain': "[('id', 'in', [%s])]" % (cls.product_A.id), 'active': True, }) cls.code_promotion_program_with_discount = cls.env['coupon.program'].create({ 'name': 'Buy 1 C + Enter code, 10 percent discount on C', 'promo_code_usage': 'code_needed', 'reward_type': 'discount', 'discount_type': 'percentage', 'discount_percentage': 10, 'rule_products_domain': "[('id', 'in', [%s])]" % (cls.product_C.id), 'active': True, 'discount_apply_on': 'on_order', })
34.672131
4,230
3,253
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_coupon.tests.common import TestSaleCouponCommon class TestProgramWithoutCodeOperations(TestSaleCouponCommon): # Test some basic operation (create, write, unlink) on an immediate coupon program on which we should # apply or remove the reward automatically, as there's no program code. def test_immediate_program_basic_operation(self): # 2 products A are needed self.immediate_promotion_program.write({'rule_min_quantity': 2.0}) order = self.empty_order # Test case 1 (1 A): Assert that no reward is given, as the product B is missing order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': '1 Product A', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "The promo offer shouldn't have been applied as the product B isn't in the order") # Test case 2 (1 A 1 B): Assert that no reward is given, as the product B is not present in the correct quantity order.write({'order_line': [ (0, False, { 'product_id': self.product_B.id, 'name': '2 Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The promo offer shouldn't have been applied as 2 product A aren't in the order") # Test case 3 (2 A 1 B): Assert that the reward is given as the product B is now in the order order.write({'order_line': [(1, order.order_line[0].id, {'product_uom_qty': 2.0})]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "The promo offert should have been applied, the discount is not created") # Test case 4 (1 A 1 B): Assert that the reward is removed as we don't buy 2 products B anymore order.write({'order_line': [(1, order.order_line[0].id, {'product_uom_qty': 1.0})]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "The promo reward should have been removed as the rules are not matched anymore") self.assertEqual(order.order_line[0].product_id.id, self.product_A.id, "The wrong line has been removed") self.assertEqual(order.order_line[1].product_id.id, self.product_B.id, "The wrong line has been removed") # Test case 5 (1 B): Assert that the reward is removed when the order is modified and doesn't match the rules anymore order.write({'order_line': [ (1, order.order_line[0].id, {'product_uom_qty': 2.0}), (2, order.order_line[0].id, False) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1, "The promo reward should have been removed as the rules are not matched anymore") self.assertEqual(order.order_line.product_id.id, self.product_B.id, "The wrong line has been removed")
55.135593
3,253
3,165
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.osv import expression class SaleCouponApplyCode(models.TransientModel): _name = 'sale.coupon.apply.code' _rec_name = 'coupon_code' _description = 'Sales Coupon Apply Code' coupon_code = fields.Char(string="Code", required=True) def process_coupon(self): """ Apply the entered coupon code if valid, raise an UserError otherwise. """ sales_order = self.env['sale.order'].browse(self.env.context.get('active_id')) error_status = self.apply_coupon(sales_order, self.coupon_code) if error_status.get('error', False): raise UserError(error_status.get('error', False)) if error_status.get('not_found', False): raise UserError(error_status.get('not_found', False)) def apply_coupon(self, order, coupon_code): error_status = {} program_domain = order._get_coupon_program_domain() program_domain = expression.AND([program_domain, [('promo_code', '=', coupon_code)]]) program = self.env['coupon.program'].search(program_domain) if program: error_status = program._check_promo_code(order, coupon_code) if not error_status: if program.promo_applicability == 'on_next_order': # Avoid creating the coupon if it already exist if program.discount_line_product_id.id not in order.generated_coupon_ids.filtered(lambda coupon: coupon.state in ['new', 'reserved']).mapped('discount_line_product_id').ids: coupon = order._create_reward_coupon(program) return { 'generated_coupon': { 'reward': coupon.program_id.discount_line_product_id.name, 'code': coupon.code, } } else: # The program is applied on this order # Only link the promo program if reward lines were created order_line_count = len(order.order_line) order._create_reward_line(program) if order_line_count < len(order.order_line): order.code_promo_program_id = program else: coupon = self.env['coupon.coupon'].search([('code', '=', coupon_code)], limit=1) if coupon: error_status = coupon._check_coupon_code(order.date_order.date(), order.partner_id.id, order=order) if not error_status: # Consume coupon only if reward lines were created order_line_count = len(order.order_line) order._create_reward_line(coupon.program_id) if order_line_count < len(order.order_line): order.applied_coupon_ids += coupon coupon.write({'state': 'used'}) else: error_status = {'not_found': _('This coupon is invalid (%s).') % (coupon_code)} return error_status
50.238095
3,165
34,984
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.tools.misc import formatLang class SaleOrder(models.Model): _inherit = "sale.order" applied_coupon_ids = fields.One2many('coupon.coupon', 'sales_order_id', string="Applied Coupons", copy=False) generated_coupon_ids = fields.One2many('coupon.coupon', 'order_id', string="Offered Coupons", copy=False) reward_amount = fields.Float(compute='_compute_reward_total') no_code_promo_program_ids = fields.Many2many('coupon.program', string="Applied Immediate Promo Programs", domain="[('promo_code_usage', '=', 'no_code_needed'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", copy=False) code_promo_program_id = fields.Many2one('coupon.program', string="Applied Promo Program", domain="[('promo_code_usage', '=', 'code_needed'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", copy=False) promo_code = fields.Char(related='code_promo_program_id.promo_code', help="Applied program code", readonly=False) @api.depends('order_line') def _compute_reward_total(self): for order in self: order.reward_amount = sum([line.price_subtotal for line in order._get_reward_lines()]) def _get_no_effect_on_threshold_lines(self): self.ensure_one() lines = self.env['sale.order.line'] return lines def recompute_coupon_lines(self): for order in self: order._remove_invalid_reward_lines() if order.state != 'cancel': order._create_new_no_code_promo_reward_lines() order._update_existing_reward_lines() @api.returns('self', lambda value: value.id) def copy(self, default=None): order = super(SaleOrder, self).copy(default) reward_line = order._get_reward_lines() if reward_line: reward_line.unlink() order._create_new_no_code_promo_reward_lines() return order def action_confirm(self): res = super().action_confirm() valid_coupon_ids = self.generated_coupon_ids.filtered(lambda coupon: coupon.state not in ['expired', 'cancel']) valid_coupon_ids.write({'state': 'new', 'partner_id': self.partner_id}) (self.generated_coupon_ids - valid_coupon_ids).write({'state': 'cancel', 'partner_id': self.partner_id}) self.applied_coupon_ids.write({'state': 'used'}) self._send_reward_coupon_mail() return res def _action_cancel(self): res = super()._action_cancel() self.generated_coupon_ids.write({'state': 'expired'}) self.applied_coupon_ids.write({'state': 'new'}) self.applied_coupon_ids.sales_order_id = False self.recompute_coupon_lines() return res def action_draft(self): res = super(SaleOrder, self).action_draft() self.generated_coupon_ids.write({'state': 'reserved'}) return res def _get_reward_lines(self): self.ensure_one() return self.order_line.filtered(lambda line: line.is_reward_line) def _is_reward_in_order_lines(self, program): self.ensure_one() order_quantity = sum(self.order_line.filtered(lambda line: line.product_id == program.reward_product_id).mapped('product_uom_qty')) return order_quantity >= program.reward_product_quantity def _is_global_discount_already_applied(self): applied_programs = self.no_code_promo_program_ids + \ self.code_promo_program_id + \ self.applied_coupon_ids.mapped('program_id') return applied_programs.filtered(lambda program: program._is_global_discount_program()) def _get_reward_values_product(self, program): price_unit = self.order_line.filtered(lambda line: program.reward_product_id == line.product_id)[0].price_reduce order_lines = (self.order_line - self._get_reward_lines()).filtered(lambda x: program._get_valid_products(x.product_id)) max_product_qty = sum(order_lines.mapped('product_uom_qty')) or 1 total_qty = sum(self.order_line.filtered(lambda x: x.product_id == program.reward_product_id).mapped('product_uom_qty')) # Remove needed quantity from reward quantity if same reward and rule product if program._get_valid_products(program.reward_product_id): # number of times the program should be applied program_in_order = max_product_qty // (program.rule_min_quantity + program.reward_product_quantity) # multipled by the reward qty reward_product_qty = program.reward_product_quantity * program_in_order # do not give more free reward than products reward_product_qty = min(reward_product_qty, total_qty) if program.rule_minimum_amount: order_total = sum(order_lines.mapped('price_total')) - (program.reward_product_quantity * program.reward_product_id.lst_price) reward_product_qty = min(reward_product_qty, order_total // program.rule_minimum_amount) else: program_in_order = max_product_qty // program.rule_min_quantity reward_product_qty = min(program.reward_product_quantity * program_in_order, total_qty) reward_qty = min(int(int(max_product_qty / program.rule_min_quantity) * program.reward_product_quantity), reward_product_qty) # Take the default taxes on the reward product, mapped with the fiscal position taxes = program.reward_product_id.taxes_id.filtered(lambda t: t.company_id.id == self.company_id.id) taxes = self.fiscal_position_id.map_tax(taxes) return { 'product_id': program.discount_line_product_id.id, 'price_unit': - price_unit, 'product_uom_qty': reward_qty, 'is_reward_line': True, 'name': _("Free Product") + " - " + program.reward_product_id.name, 'product_uom': program.reward_product_id.uom_id.id, 'tax_id': [(4, tax.id, False) for tax in taxes], } def _get_paid_order_lines(self): """ Returns the sale order lines that are not reward lines. It will also return reward lines being free product lines. """ free_reward_product = self.env['coupon.program'].search([('reward_type', '=', 'product')]).mapped('discount_line_product_id') return self.order_line.filtered(lambda x: not x._is_not_sellable_line() or x.product_id in free_reward_product) def _get_base_order_lines(self, program): """ Returns the sale order lines not linked to the given program. """ return self.order_line.filtered(lambda x: not x._is_not_sellable_line() or (x.is_reward_line and x.product_id != program.discount_line_product_id)) def _get_reward_values_discount_fixed_amount(self, program): total_amount = sum(self._get_base_order_lines(program).mapped('price_total')) fixed_amount = program._compute_program_amount('discount_fixed_amount', self.currency_id) if total_amount < fixed_amount: return total_amount else: return fixed_amount def _get_coupon_program_domain(self): return [] def _get_cheapest_line(self): # Unit prices tax included return min(self.order_line.filtered(lambda x: not x._is_not_sellable_line() and x.price_reduce > 0), key=lambda x: x['price_reduce']) def _get_reward_values_discount_percentage_per_line(self, program, line): discount_amount = line.product_uom_qty * line.price_reduce * (program.discount_percentage / 100) return discount_amount def _get_max_reward_values_per_tax(self, program, taxes): lines = self.order_line.filtered(lambda l: l.tax_id == taxes and l.product_id != program.discount_line_product_id) return sum(lines.mapped(lambda l: l.price_reduce * l.product_uom_qty)) def _get_reward_values_fixed_amount(self, program): discount_amount = self._get_reward_values_discount_fixed_amount(program) # In case there is a tax set on the promotion product, we give priority to it. # This allow manual overwrite of taxes for promotion. if program.discount_line_product_id.taxes_id: line_taxes = self.fiscal_position_id.map_tax(program.discount_line_product_id.taxes_id) if self.fiscal_position_id else program.discount_line_product_id.taxes_id lines = self._get_base_order_lines(program) discount_amount = min( sum(lines.mapped(lambda l: l.price_reduce * l.product_uom_qty)), discount_amount ) return [{ 'name': _("Discount: %s", program.name), 'product_id': program.discount_line_product_id.id, 'price_unit': -discount_amount, 'product_uom_qty': 1.0, 'product_uom': program.discount_line_product_id.uom_id.id, 'is_reward_line': True, 'tax_id': [(4, tax.id, False) for tax in line_taxes], }] lines = self._get_paid_order_lines() # Remove Free Lines lines = lines.filtered('price_reduce') reward_lines = {} tax_groups = set([line.tax_id for line in lines]) max_discount_per_tax_groups = {tax_ids: self._get_max_reward_values_per_tax(program, tax_ids) for tax_ids in tax_groups} for tax_ids in sorted(tax_groups, key=lambda tax_ids: max_discount_per_tax_groups[tax_ids], reverse=True): if discount_amount <= 0: return reward_lines.values() curr_lines = lines.filtered(lambda l: l.tax_id == tax_ids) lines_price = sum(curr_lines.mapped(lambda l: l.price_reduce * l.product_uom_qty)) lines_total = sum(curr_lines.mapped('price_total')) discount_line_amount_price = min(max_discount_per_tax_groups[tax_ids], (discount_amount * lines_price / lines_total)) if not discount_line_amount_price: continue discount_amount -= discount_line_amount_price * lines_total / lines_price reward_lines[tax_ids] = { 'name': _( "Discount: %(program)s - On product with following taxes: %(taxes)s", program=program.name, taxes=", ".join(tax_ids.mapped('name')), ), 'product_id': program.discount_line_product_id.id, 'price_unit': -discount_line_amount_price, 'product_uom_qty': 1.0, 'product_uom': program.discount_line_product_id.uom_id.id, 'is_reward_line': True, 'tax_id': [(4, tax.id, False) for tax in tax_ids], } return reward_lines.values() def _get_reward_values_discount(self, program): if program.discount_type == 'fixed_amount': return self._get_reward_values_fixed_amount(program) else: return self._get_reward_values_percentage_amount(program) def _get_reward_values_percentage_amount(self, program): # Invalidate multiline fixed_price discount line as they should apply after % discount fixed_price_products = self._get_applied_programs().filtered( lambda p: p.discount_type == 'fixed_amount' ).mapped('discount_line_product_id') self.order_line.filtered(lambda l: l.product_id in fixed_price_products).write({'price_unit': 0}) reward_dict = {} lines = self._get_paid_order_lines() amount_total = sum([any(line.tax_id.mapped('price_include')) and line.price_total or line.price_subtotal for line in self._get_base_order_lines(program)]) if program.discount_apply_on == 'cheapest_product': line = self._get_cheapest_line() if line: discount_line_amount = min(line.price_reduce * (program.discount_percentage / 100), amount_total) if discount_line_amount: taxes = self.fiscal_position_id.map_tax(line.tax_id) reward_dict[line.tax_id] = { 'name': _("Discount: %s", program.name), 'product_id': program.discount_line_product_id.id, 'price_unit': - discount_line_amount if discount_line_amount > 0 else 0, 'product_uom_qty': 1.0, 'product_uom': program.discount_line_product_id.uom_id.id, 'is_reward_line': True, 'tax_id': [(4, tax.id, False) for tax in taxes], } elif program.discount_apply_on in ['specific_products', 'on_order']: if program.discount_apply_on == 'specific_products': # We should not exclude reward line that offer this product since we need to offer only the discount on the real paid product (regular product - free product) free_product_lines = self.env['coupon.program'].search([('reward_type', '=', 'product'), ('reward_product_id', 'in', program.discount_specific_product_ids.ids)]).mapped('discount_line_product_id') lines = lines.filtered(lambda x: x.product_id in (program.discount_specific_product_ids | free_product_lines)) # when processing lines we should not discount more than the order remaining total currently_discounted_amount = 0 for line in lines: discount_line_amount = min(self._get_reward_values_discount_percentage_per_line(program, line), amount_total - currently_discounted_amount) if discount_line_amount: if line.tax_id in reward_dict: reward_dict[line.tax_id]['price_unit'] -= discount_line_amount else: taxes = self.fiscal_position_id.map_tax(line.tax_id) reward_dict[line.tax_id] = { 'name': _( "Discount: %(program)s - On product with following taxes: %(taxes)s", program=program.name, taxes=", ".join(taxes.mapped('name')), ), 'product_id': program.discount_line_product_id.id, 'price_unit': - discount_line_amount if discount_line_amount > 0 else 0, 'product_uom_qty': 1.0, 'product_uom': program.discount_line_product_id.uom_id.id, 'is_reward_line': True, 'tax_id': [(4, tax.id, False) for tax in taxes], } currently_discounted_amount += discount_line_amount # If there is a max amount for discount, we might have to limit some discount lines or completely remove some lines max_amount = program._compute_program_amount('discount_max_amount', self.currency_id) if max_amount > 0: amount_already_given = 0 for val in list(reward_dict): amount_to_discount = amount_already_given + reward_dict[val]["price_unit"] if abs(amount_to_discount) > max_amount: reward_dict[val]["price_unit"] = - (max_amount - abs(amount_already_given)) add_name = formatLang(self.env, max_amount, currency_obj=self.currency_id) reward_dict[val]["name"] += "( " + _("limited to ") + add_name + ")" amount_already_given += reward_dict[val]["price_unit"] if reward_dict[val]["price_unit"] == 0: del reward_dict[val] return reward_dict.values() def _get_reward_line_values(self, program): self.ensure_one() self = self.with_context(lang=self.partner_id.lang) program = program.with_context(lang=self.partner_id.lang) values = [] if program.reward_type == 'discount': values = self._get_reward_values_discount(program) elif program.reward_type == 'product': values = [self._get_reward_values_product(program)] seq = max(self.order_line.mapped('sequence'), default=10) + 1 for value in values: value['sequence'] = seq return values def _create_reward_line(self, program): self.write({'order_line': [(0, False, value) for value in self._get_reward_line_values(program)]}) def _create_reward_coupon(self, program): # if there is already a coupon that was set as expired, reactivate that one instead of creating a new one coupon = self.env['coupon.coupon'].search([ ('program_id', '=', program.id), ('state', '=', 'expired'), ('partner_id', '=', self.partner_id.id), ('order_id', '=', self.id), ('discount_line_product_id', '=', program.discount_line_product_id.id), ], limit=1) if coupon: coupon.write({'state': 'reserved'}) else: coupon = self.env['coupon.coupon'].sudo().create({ 'program_id': program.id, 'state': 'reserved', 'partner_id': self.partner_id.id, 'order_id': self.id, 'discount_line_product_id': program.discount_line_product_id.id }) self.generated_coupon_ids |= coupon return coupon def _send_reward_coupon_mail(self): template = self.env.ref('sale_coupon.mail_template_sale_coupon', raise_if_not_found=False) if template: for order in self: for coupon in order.generated_coupon_ids.filtered(lambda coupon: coupon.state == 'new'): order.message_post_with_template( template.id, composition_mode='comment', model='coupon.coupon', res_id=coupon.id, email_layout_xmlid='mail.mail_notification_light', ) def _get_applicable_programs(self): """ This method is used to return the valid applicable programs on given order. """ self.ensure_one() programs = self.env['coupon.program'].with_context( no_outdated_coupons=True, ).search([ ('company_id', 'in', [self.company_id.id, False]), '|', ('rule_date_from', '=', False), ('rule_date_from', '<=', fields.Datetime.now()), '|', ('rule_date_to', '=', False), ('rule_date_to', '>=', fields.Datetime.now()), ], order="id")._filter_programs_from_common_rules(self) # no impact code... # should be programs = programs.filtered if we really want to filter... # if self.promo_code: # programs._filter_promo_programs_with_code(self) return programs def _get_applicable_no_code_promo_program(self): self.ensure_one() programs = self.env['coupon.program'].with_context( no_outdated_coupons=True, applicable_coupon=True, ).search([ ('promo_code_usage', '=', 'no_code_needed'), '|', ('rule_date_from', '=', False), ('rule_date_from', '<=', fields.Datetime.now()), '|', ('rule_date_to', '=', False), ('rule_date_to', '>=', fields.Datetime.now()), '|', ('company_id', '=', self.company_id.id), ('company_id', '=', False), ])._filter_programs_from_common_rules(self) return programs def _get_valid_applied_coupon_program(self): self.ensure_one() # applied_coupon_ids's coupons might be coming from: # * a coupon generated from a previous order that benefited from a promotion_program that rewarded the next sale order. # In that case requirements to benefit from the program (Quantity and price) should not be checked anymore # * a coupon_program, in that case the promo_applicability is always for the current order and everything should be checked (filtered) programs = self.applied_coupon_ids.mapped('program_id').filtered(lambda p: p.promo_applicability == 'on_next_order')._filter_programs_from_common_rules(self, True) programs += self.applied_coupon_ids.mapped('program_id').filtered(lambda p: p.promo_applicability == 'on_current_order')._filter_programs_from_common_rules(self) return programs def _create_new_no_code_promo_reward_lines(self): '''Apply new programs that are applicable''' self.ensure_one() order = self programs = order._get_applicable_no_code_promo_program() programs = programs._keep_only_most_interesting_auto_applied_global_discount_program() for program in programs: # VFE REF in master _get_applicable_no_code_programs already filters programs # why do we need to reapply this bunch of checks in _check_promo_code ???? # We should only apply a little part of the checks in _check_promo_code... error_status = program._check_promo_code(order, False) if not error_status.get('error'): if program.promo_applicability == 'on_next_order': order.state != 'cancel' and order._create_reward_coupon(program) elif program.discount_line_product_id.id not in self.order_line.mapped('product_id').ids: self.write({'order_line': [(0, False, value) for value in self._get_reward_line_values(program)]}) order.no_code_promo_program_ids |= program def _update_existing_reward_lines(self): '''Update values for already applied rewards''' def update_line(order, lines, values): '''Update the lines and return them if they should be deleted''' lines_to_remove = self.env['sale.order.line'] # move coupons to the end of the SO values['sequence'] = max(order.order_line.mapped('sequence')) + 1 # Check commit 6bb42904a03 for next if/else # Remove reward line if price or qty equal to 0 if values['product_uom_qty'] and values['price_unit']: lines.write(values) else: if program.reward_type != 'free_shipping': # Can't remove the lines directly as we might be in a recordset loop lines_to_remove += lines else: values.update(price_unit=0.0) lines.write(values) return lines_to_remove self.ensure_one() order = self applied_programs = order._get_applied_programs_with_rewards_on_current_order() for program in applied_programs.sorted(lambda ap: (ap.discount_type == 'fixed_amount', ap.discount_apply_on == 'on_order')): values = order._get_reward_line_values(program) lines = order.order_line.filtered(lambda line: line.product_id == program.discount_line_product_id) if program.reward_type == 'discount': lines_to_remove = lines lines_to_add = [] lines_to_keep = [] # Values is what discount lines should really be, lines is what we got in the SO at the moment # 1. If values & lines match, we should update the line (or delete it if no qty or price?) # As removing a lines remove all the other lines linked to the same program, we need to save them # using lines_to_keep # 2. If the value is not in the lines, we should add it # 3. if the lines contains a tax not in value, we should remove it for value in values: value_found = False for line in lines: # Case 1. if not len(set(line.tax_id.mapped('id')).symmetric_difference(set([v[1] for v in value['tax_id']]))): value_found = True # Working on Case 3. # update_line update the line to the correct value and returns them if they should be unlinked update_to_remove = update_line(order, line, value) if not update_to_remove: lines_to_keep += [(0, False, value)] lines_to_remove -= line # Working on Case 2. if not value_found: lines_to_add += [(0, False, value)] # Case 3. line_update = [] if lines_to_remove: line_update += [(3, line_id, 0) for line_id in lines_to_remove.ids] line_update += lines_to_keep line_update += lines_to_add order.write({'order_line': line_update}) else: update_line(order, lines, values[0]).unlink() def _remove_invalid_reward_lines(self): """ Find programs & coupons that are not applicable anymore. It will then unlink the related reward order lines. It will also unset the order's fields that are storing the applied coupons & programs. Note: It will also remove a reward line coming from an archive program. """ self.ensure_one() order = self applied_programs = order._get_applied_programs() applicable_programs = self.env['coupon.program'] if applied_programs: applicable_programs = order._get_applicable_programs() + order._get_valid_applied_coupon_program() applicable_programs = applicable_programs._keep_only_most_interesting_auto_applied_global_discount_program() programs_to_remove = applied_programs - applicable_programs reward_product_ids = applied_programs.discount_line_product_id.ids # delete reward line coming from an archived coupon (it will never be updated/removed when recomputing the order) invalid_lines = order.order_line.filtered(lambda line: line.is_reward_line and line.product_id.id not in reward_product_ids) if programs_to_remove: product_ids_to_remove = programs_to_remove.discount_line_product_id.ids if product_ids_to_remove: # Invalid generated coupon for which we are not eligible anymore ('expired' since it is specific to this SO and we may again met the requirements) self.generated_coupon_ids.filtered(lambda coupon: coupon.program_id.discount_line_product_id.id in product_ids_to_remove).write({'state': 'expired'}) # Reset applied coupons for which we are not eligible anymore ('valid' so it can be use on another ) coupons_to_remove = order.applied_coupon_ids.filtered(lambda coupon: coupon.program_id in programs_to_remove) coupons_to_remove.write({'state': 'new'}) # Unbind promotion and coupon programs which requirements are not met anymore order.no_code_promo_program_ids -= programs_to_remove order.code_promo_program_id -= programs_to_remove if coupons_to_remove: order.applied_coupon_ids -= coupons_to_remove # Remove their reward lines if product_ids_to_remove: invalid_lines |= order.order_line.filtered(lambda line: line.product_id.id in product_ids_to_remove) invalid_lines.unlink() def _get_applied_programs_with_rewards_on_current_order(self): # Need to add filter on current order. Indeed, it has always been calculating reward line even if on next order (which is useless and do calculation for nothing) # This problem could not be noticed since it would only update or delete existing lines related to that program, it would not find the line to update since not in the order # But now if we dont find the reward line in the order, we add it (since we can now have multiple line per program in case of discount on different vat), thus the bug # mentionned ahead will be seen now return self.no_code_promo_program_ids.filtered(lambda p: p.promo_applicability == 'on_current_order') + \ self.applied_coupon_ids.mapped('program_id') + \ self.code_promo_program_id.filtered(lambda p: p.promo_applicability == 'on_current_order') def _get_applied_programs_with_rewards_on_next_order(self): return self.no_code_promo_program_ids.filtered(lambda p: p.promo_applicability == 'on_next_order') + \ self.code_promo_program_id.filtered(lambda p: p.promo_applicability == 'on_next_order') def _get_applied_programs(self): """Returns all applied programs on current order: Expected to return same result than: self._get_applied_programs_with_rewards_on_current_order() + self._get_applied_programs_with_rewards_on_next_order() """ return self.code_promo_program_id + self.no_code_promo_program_ids + self.applied_coupon_ids.mapped('program_id') def _get_invoice_status(self): # Handling of a specific situation: an order contains # a product invoiced on delivery and a promo line invoiced # on order. We would avoid having the invoice status 'to_invoice' # if the created invoice will only contain the promotion line super()._get_invoice_status() for order in self.filtered(lambda order: order.invoice_status == 'to invoice'): paid_lines = order._get_paid_order_lines() if not any(line.invoice_status == 'to invoice' for line in paid_lines): order.invoice_status = 'no' def _get_invoiceable_lines(self, final=False): """ Ensures we cannot invoice only reward lines. Since promotion lines are specified with service products, those lines are directly invoiceable when the order is confirmed which can result in invoices containing only promotion lines. To avoid those cases, we allow the invoicing of promotion lines iff at least another 'basic' lines is also invoiceable. """ invoiceable_lines = super()._get_invoiceable_lines(final) reward_lines = self._get_reward_lines() if invoiceable_lines <= reward_lines: return self.env['sale.order.line'].browse() return invoiceable_lines def update_prices(self): """Recompute coupons/promotions after pricelist prices reset.""" super().update_prices() if any(line.is_reward_line for line in self.order_line): self.recompute_coupon_lines() class SaleOrderLine(models.Model): _inherit = "sale.order.line" is_reward_line = fields.Boolean('Is a program reward line') def _is_not_sellable_line(self): return self.is_reward_line or super()._is_not_sellable_line() def unlink(self): related_program_lines = self.env['sale.order.line'] # Reactivate coupons related to unlinked reward line for line in self.filtered(lambda line: line.is_reward_line): coupons_to_reactivate = line.order_id.applied_coupon_ids.filtered( lambda coupon: coupon.program_id.discount_line_product_id == line.product_id ) coupons_to_reactivate.write({'state': 'new'}) line.order_id.applied_coupon_ids -= coupons_to_reactivate # Remove the program from the order if the deleted line is the reward line of the program # And delete the other lines from this program (It's the case when discount is split per different taxes) related_program = self.env['coupon.program'].search([('discount_line_product_id', '=', line.product_id.id)]) if related_program: line.order_id.no_code_promo_program_ids -= related_program line.order_id.code_promo_program_id -= related_program related_program_lines |= line.order_id.order_line.filtered(lambda l: l.product_id.id == related_program.discount_line_product_id.id) - line return super(SaleOrderLine, self | related_program_lines).unlink() def _compute_tax_id(self): reward_lines = self.filtered('is_reward_line') super(SaleOrderLine, self - reward_lines)._compute_tax_id() # Discount reward line is split per tax, the discount is set on the line but not on the product # as the product is the generic discount line. # In case of a free product, retrieving the tax on the line instead of the product won't affect the behavior. for line in reward_lines: line = line.with_company(line.company_id) fpos = line.order_id.fiscal_position_id or line.order_id.fiscal_position_id.get_fiscal_position(line.order_partner_id.id) # If company_id is set, always filter taxes by the company taxes = line.tax_id.filtered(lambda r: not line.company_id or r.company_id == line.company_id) line.tax_id = fpos.map_tax(taxes) def _get_display_price(self, product): # A product created from a promotion does not have a list_price. # The price_unit of a reward order line is computed by the promotion, so it can be used directly if self.is_reward_line: return self.price_unit return super()._get_display_price(product) # Invalidation of `coupon.program.order_count` # `test_program_rules_validity_dates_and_uses`, # Overriding modified is quite hardcore as you need to know how works the cache and the invalidation system, # but at least the below works and should be efficient. # Another possibility is to add on product.product a one2many to sale.order.line 'order_line_ids', # and then add the depends @api.depends('discount_line_product_id.order_line_ids'), # but I am not sure this will as efficient as the below. def modified(self, fnames, *args, **kwargs): super(SaleOrderLine, self).modified(fnames, *args, **kwargs) if 'product_id' in fnames: Program = self.env['coupon.program'].sudo() field_order_count = Program._fields['order_count'] field_total_order_count = Program._fields['total_order_count'] programs = self.env.cache.get_records(Program, field_order_count) programs |= self.env.cache.get_records(Program, field_total_order_count) if programs: products = self.filtered('is_reward_line').mapped('product_id') for program in programs: if program.discount_line_product_id in products: self.env.cache.invalidate([(field_order_count, program.ids), (field_total_order_count, program.ids)])
55.266983
34,984
3,184
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 Coupon(models.Model): _inherit = 'coupon.coupon' order_id = fields.Many2one('sale.order', 'Order Reference', readonly=True, help="The sales order from which coupon is generated") sales_order_id = fields.Many2one('sale.order', 'Used in', readonly=True, help="The sales order on which the coupon is applied") def _check_coupon_code(self, order_date, partner_id, **kwargs): message = super(Coupon, self)._check_coupon_code(order_date, partner_id, **kwargs) order = kwargs.get('order', False) if message.get('error', False) or not order: return message applicable_programs = order._get_applicable_programs() # Minimum requirement should not be checked if the coupon got generated by a promotion program (the requirement should have only be checked to generate the coupon) if self.program_id.program_type == 'coupon_program' and not self.program_id._filter_on_mimimum_amount(order): message = {'error': _( 'A minimum of %(amount)s %(currency)s should be purchased to get the reward', amount=self.program_id.rule_minimum_amount, currency=self.program_id.currency_id.name )} elif self.program_id in order.applied_coupon_ids.mapped('program_id'): message = {'error': _('A Coupon is already applied for the same reward')} elif self.program_id._is_global_discount_program() and order._is_global_discount_already_applied(): message = {'error': _('Global discounts are not cumulable.')} elif self.program_id.reward_type == 'product' and not order._is_reward_in_order_lines(self.program_id): message = {'error': _('The reward products should be in the sales order lines to apply the discount.')} elif not self.program_id._is_valid_partner(order.partner_id): message = {'error': _("The customer doesn't have access to this reward.")} # Product requirement should not be checked if the coupon got generated by a promotion program (the requirement should have only be checked to generate the coupon) elif self.program_id.program_type == 'coupon_program' and not self.program_id._filter_programs_on_products(order): message = {'error': _("You don't have the required product quantities on your sales order. All the products should be recorded on the sales order. (Example: You need to have 3 T-shirts on your sales order if the promotion is 'Buy 2, Get 1 Free').")} else: if self.program_id not in applicable_programs and self.program_id.promo_applicability == 'on_current_order': message = {'error': _('At least one of the required conditions is not met to get the reward!')} return message def _get_default_template(self): default_template = super()._get_default_template() if not default_template: return self.env.ref('sale_coupon.mail_template_sale_coupon', False) return default_template
64.979592
3,184
12,120
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 babel.dates import format_datetime class CouponProgram(models.Model): _inherit = 'coupon.program' order_count = fields.Integer(compute='_compute_order_count') # The api.depends is handled in `def modified` of `sale_coupon/models/sale_order.py` def _compute_order_count(self): for program in self: program.order_count = self.env['sale.order.line'].sudo().search_count([('product_id', '=', program.discount_line_product_id.id)]) def action_view_sales_orders(self): self.ensure_one() orders = self.env['sale.order.line'].search([('product_id', '=', self.discount_line_product_id.id)]).mapped('order_id') return { 'name': _('Sales Orders'), 'view_mode': 'tree,form', 'res_model': 'sale.order', 'search_view_id': [self.env.ref('sale.sale_order_view_search_inherit_quotation').id], 'type': 'ir.actions.act_window', 'domain': [('id', 'in', orders.ids)], 'context': dict(self._context, create=False), } def _check_promo_code(self, order, coupon_code): message = {} if self.maximum_use_number != 0 and self.total_order_count >= self.maximum_use_number: message = {'error': _('Promo code %s has been expired.') % (coupon_code)} elif not self._filter_on_mimimum_amount(order): message = {'error': _( 'A minimum of %(amount)s %(currency)s should be purchased to get the reward', amount=self.rule_minimum_amount, currency=self.currency_id.name )} elif self.promo_code and self.promo_code == order.promo_code: message = {'error': _('The promo code is already applied on this order')} elif self in order.no_code_promo_program_ids: message = {'error': _('The promotional offer is already applied on this order')} elif not self.active: message = {'error': _('Promo code is invalid')} elif self.rule_date_from and self.rule_date_from > fields.Datetime.now(): tzinfo = self.env.context.get('tz') or self.env.user.tz or 'UTC' locale = self.env.context.get('lang') or self.env.user.lang or 'en_US' message = {'error': _('This coupon is not yet usable. It will be starting from %s') % (format_datetime(self.rule_date_from, format='short', tzinfo=tzinfo, locale=locale))} elif self.rule_date_to and fields.Datetime.now() > self.rule_date_to: message = {'error': _('Promo code is expired')} elif order.promo_code and self.promo_code_usage == 'code_needed': message = {'error': _('Promotionals codes are not cumulative.')} elif self._is_global_discount_program() and order._is_global_discount_already_applied(): message = {'error': _('Global discounts are not cumulative.')} elif self.promo_applicability == 'on_current_order' and self.reward_type == 'product' and not order._is_reward_in_order_lines(self): message = {'error': _('The reward products should be in the sales order lines to apply the discount.')} elif not self._is_valid_partner(order.partner_id): message = {'error': _("The customer doesn't have access to this reward.")} elif not self._filter_programs_on_products(order): message = {'error': _("You don't have the required product quantities on your sales order. If the reward is same product quantity, please make sure that all the products are recorded on the sales order (Example: You need to have 3 T-shirts on your sales order if the promotion is 'Buy 2, Get 1 Free'.")} elif self.promo_applicability == 'on_current_order' and not self.env.context.get('applicable_coupon'): applicable_programs = order._get_applicable_programs() if self not in applicable_programs: message = {'error': _('At least one of the required conditions is not met to get the reward!')} return message def _filter_on_mimimum_amount(self, order): no_effect_lines = order._get_no_effect_on_threshold_lines() order_amount = { 'amount_untaxed' : order.amount_untaxed - sum(line.price_subtotal for line in no_effect_lines), 'amount_tax' : order.amount_tax - sum(line.price_tax for line in no_effect_lines) } program_ids = list() for program in self: if program.reward_type != 'discount': # avoid the filtered lines = self.env['sale.order.line'] else: lines = order.order_line.filtered(lambda line: line.product_id == program.discount_line_product_id or line.product_id == program.reward_id.discount_line_product_id or (program.program_type == 'promotion_program' and line.is_reward_line) ) untaxed_amount = order_amount['amount_untaxed'] - sum(line.price_subtotal for line in lines) tax_amount = order_amount['amount_tax'] - sum(line.price_tax for line in lines) program_amount = program._compute_program_amount('rule_minimum_amount', order.currency_id) if program.rule_minimum_amount_tax_inclusion == 'tax_included' and program_amount <= (untaxed_amount + tax_amount) or program_amount <= untaxed_amount: program_ids.append(program.id) return self.browse(program_ids) def _filter_on_validity_dates(self, order): return self.filtered(lambda program: (not program.rule_date_from or program.rule_date_from <= fields.Datetime.now()) and (not program.rule_date_to or program.rule_date_to >= fields.Datetime.now()) ) def _filter_promo_programs_with_code(self, order): '''Filter Promo program with code with a different promo_code if a promo_code is already ordered''' return self.filtered(lambda program: program.promo_code_usage == 'code_needed' and program.promo_code != order.promo_code) def _filter_unexpired_programs(self, order): return self.filtered( lambda program: program.maximum_use_number == 0 or program.total_order_count < program.maximum_use_number or program in (order.code_promo_program_id + order.no_code_promo_program_ids) ) def _filter_programs_on_partners(self, order): return self.filtered(lambda program: program._is_valid_partner(order.partner_id)) def _filter_programs_on_products(self, order): """ To get valid programs according to product list. i.e Buy 1 imac + get 1 ipad mini free then check 1 imac is on cart or not or Buy 1 coke + get 1 coke free then check 2 cokes are on cart or not """ order_lines = order.order_line.filtered(lambda line: line.product_id) - order._get_reward_lines() products = order_lines.mapped('product_id') products_qties = dict.fromkeys(products, 0) for line in order_lines: products_qties[line.product_id] += line.product_uom_qty valid_program_ids = list() for program in self: if not program.rule_products_domain or program.rule_products_domain == "[]": valid_program_ids.append(program.id) continue valid_products = program._get_valid_products(products) if not valid_products: # The program can be directly discarded continue ordered_rule_products_qty = sum(products_qties[product] for product in valid_products) # Avoid program if 1 ordered foo on a program '1 foo, 1 free foo' if program.promo_applicability == 'on_current_order' and \ program.reward_type == 'product' and program._get_valid_products(program.reward_product_id): ordered_rule_products_qty -= program.reward_product_quantity if ordered_rule_products_qty >= program.rule_min_quantity: valid_program_ids.append(program.id) return self.browse(valid_program_ids) def _filter_not_ordered_reward_programs(self, order): """ Returns the programs when the reward is actually in the order lines """ programs = self.env['coupon.program'] order_products = order.order_line.product_id for program in self: if program.reward_type == 'product' and program.reward_product_id not in order_products: continue elif ( program.reward_type == 'discount' and program.discount_apply_on == 'specific_products' and not any(discount_product in order_products for discount_product in program.discount_specific_product_ids) ): continue programs += program return programs def _filter_programs_from_common_rules(self, order, next_order=False): """ Return the programs if every conditions is met :param bool next_order: is the reward given from a previous order """ programs = self # Minimum requirement should not be checked if the coupon got generated by a promotion program (the requirement should have only be checked to generate the coupon) if not next_order: programs = programs and programs._filter_on_mimimum_amount(order) if not self.env.context.get("no_outdated_coupons"): programs = programs and programs._filter_on_validity_dates(order) programs = programs and programs._filter_unexpired_programs(order) programs = programs and programs._filter_programs_on_partners(order) # Product requirement should not be checked if the coupon got generated by a promotion program (the requirement should have only be checked to generate the coupon) if not next_order: programs = programs and programs._filter_programs_on_products(order) programs_curr_order = programs.filtered(lambda p: p.promo_applicability == 'on_current_order') programs = programs.filtered(lambda p: p.promo_applicability == 'on_next_order') if programs_curr_order: # Checking if rewards are in the SO should not be performed for rewards on_next_order programs += programs_curr_order._filter_not_ordered_reward_programs(order) return programs def _get_discount_product_values(self): res = super()._get_discount_product_values() res['invoice_policy'] = 'order' return res def _is_global_discount_program(self): self.ensure_one() return self.promo_applicability == 'on_current_order' and \ self.reward_type == 'discount' and \ self.discount_type == 'percentage' and \ self.discount_apply_on == 'on_order' def _keep_only_most_interesting_auto_applied_global_discount_program(self): '''Given a record set of programs, remove the less interesting auto applied global discount to keep only the most interesting one. We should not take promo code programs into account as a 10% auto applied is considered better than a 50% promo code, as the user might not know about the promo code. ''' programs = self.filtered(lambda p: p._is_global_discount_program() and p.promo_code_usage == 'no_code_needed') if not programs: return self most_interesting_program = max(programs, key=lambda p: p.discount_percentage) # remove least interesting programs return self - (programs - most_interesting_program) # The api.depends is handled in `def modified` of `sale_coupon/models/sale_order.py` def _compute_total_order_count(self): super(CouponProgram, self)._compute_total_order_count() for program in self: program.total_order_count += program.order_count
56.635514
12,120
711
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Mollie Payment Acquirer', 'version': '1.0', 'category': 'Accounting/Payment Acquirers', 'sequence': 356, 'summary': 'Payment Acquirer: Mollie Implementation', 'description': """Mollie Payment Acquirer""", 'author': 'Odoo S.A, Applix BV, Droggol Infotech Pvt. Ltd.', 'website': 'https://www.mollie.com', 'depends': ['payment'], 'data': [ 'views/payment_mollie_templates.xml', 'views/payment_views.xml', 'data/payment_acquirer_data.xml', ], 'application': True, 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3' }
29.625
711
835
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # List of ISO 15897 locale supported by Mollie # See full details at `locale` parameter at https://docs.mollie.com/reference/v2/payments-api/create-payment SUPPORTED_LOCALES = [ 'en_US', 'nl_NL', 'nl_BE', 'fr_FR', 'fr_BE', 'de_DE', 'de_AT', 'de_CH', 'es_ES', 'ca_ES', 'pt_PT', 'it_IT', 'nb_NO', 'sv_SE', 'fi_FI', 'da_DK', 'is_IS', 'hu_HU', 'pl_PL', 'lv_LV', 'lt_LT' ] # Currency codes in ISO 4217 format supported by mollie. # See https://docs.mollie.com/payments/multicurrency SUPPORTED_CURRENCIES = [ 'AED', 'AUD', 'BGN', 'BRL', 'CAD', 'CHF', 'CZK', 'DKK', 'EUR', 'GBP', 'HKD', 'HRK', 'HUF', 'ILS', 'ISK', 'JPY', 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PLN', 'RON', 'RUB', 'SEK', 'SGD', 'THB', 'TWD', 'USD', 'ZAR' ]
37.954545
835
524
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.payment.tests.common import PaymentCommon class MollieCommon(PaymentCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.mollie = cls._prepare_acquirer('mollie', update_values={ 'mollie_api_key': 'dummy', }) cls.acquirer = cls.mollie cls.currency = cls.currency_euro
32.75
524
560
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 .common import MollieCommon @tagged('post_install', '-at_install') class MollieTest(MollieCommon): def test_payment_request_payload_values(self): tx = self.create_transaction(flow='redirect') payload = tx._mollie_prepare_payment_request_payload() self.assertDictEqual(payload['amount'], {'currency': 'EUR', 'value': '1111.11'}) self.assertEqual(payload['description'], tx.reference)
31.111111
560
5,173
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pprint from werkzeug import urls from odoo import _, models from odoo.exceptions import ValidationError from odoo.addons.payment_mollie.const import SUPPORTED_LOCALES from odoo.addons.payment_mollie.controllers.main import MollieController _logger = logging.getLogger(__name__) class PaymentTransaction(models.Model): _inherit = 'payment.transaction' def _get_specific_rendering_values(self, processing_values): """ Override of payment to return Mollie-specific rendering values. Note: self.ensure_one() from `_get_processing_values` :param dict processing_values: The generic and specific processing values of the transaction :return: The dict of acquirer-specific rendering values :rtype: dict """ res = super()._get_specific_rendering_values(processing_values) if self.provider != 'mollie': return res payload = self._mollie_prepare_payment_request_payload() _logger.info("sending '/payments' request for link creation:\n%s", pprint.pformat(payload)) payment_data = self.acquirer_id._mollie_make_request('/payments', data=payload) # The acquirer reference is set now to allow fetching the payment status after redirection self.acquirer_reference = payment_data.get('id') # Extract the checkout URL from the payment data and add it with its query parameters to the # rendering values. Passing the query parameters separately is necessary to prevent them # from being stripped off when redirecting the user to the checkout URL, which can happen # when only one payment method is enabled on Mollie and query parameters are provided. checkout_url = payment_data["_links"]["checkout"]["href"] parsed_url = urls.url_parse(checkout_url) url_params = urls.url_decode(parsed_url.query) return {'api_url': checkout_url, 'url_params': url_params} def _mollie_prepare_payment_request_payload(self): """ Create the payload for the payment request based on the transaction values. :return: The request payload :rtype: dict """ user_lang = self.env.context.get('lang') base_url = self.acquirer_id.get_base_url() redirect_url = urls.url_join(base_url, MollieController._return_url) webhook_url = urls.url_join(base_url, MollieController._notify_url) return { 'description': self.reference, 'amount': { 'currency': self.currency_id.name, 'value': f"{self.amount:.2f}", }, 'locale': user_lang if user_lang in SUPPORTED_LOCALES else 'en_US', # Since Mollie does not provide the transaction reference when returning from # redirection, we include it in the redirect URL to be able to match the transaction. 'redirectUrl': f'{redirect_url}?ref={self.reference}', 'webhookUrl': f'{webhook_url}?ref={self.reference}', } def _get_tx_from_feedback_data(self, provider, data): """ Override of payment to find the transaction based on Mollie data. :param str provider: The provider of the acquirer that handled the transaction :param dict data: The feedback data sent by the provider :return: The transaction if found :rtype: recordset of `payment.transaction` :raise: ValidationError if the data match no transaction """ tx = super()._get_tx_from_feedback_data(provider, data) if provider != 'mollie': return tx tx = self.search([('reference', '=', data.get('ref')), ('provider', '=', 'mollie')]) if not tx: raise ValidationError( "Mollie: " + _("No transaction found matching reference %s.", data.get('ref')) ) return tx def _process_feedback_data(self, data): """ Override of payment to process the transaction based on Mollie data. Note: self.ensure_one() :param dict data: The feedback data sent by the provider :return: None """ super()._process_feedback_data(data) if self.provider != 'mollie': return payment_data = self.acquirer_id._mollie_make_request( f'/payments/{self.acquirer_reference}', method="GET" ) payment_status = payment_data.get('status') if payment_status == 'pending': self._set_pending() elif payment_status == 'authorized': self._set_authorized() elif payment_status == 'paid': self._set_done() elif payment_status in ['expired', 'canceled', 'failed']: self._set_canceled("Mollie: " + _("Canceled payment with status: %s", payment_status)) else: _logger.info("Received data with invalid payment status: %s", payment_status) self._set_error( "Mollie: " + _("Received data with invalid payment status: %s", payment_status) )
41.384
5,173
429
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 AccountPaymentMethod(models.Model): _inherit = 'account.payment.method' @api.model def _get_payment_method_information(self): res = super()._get_payment_method_information() res['mollie'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]} return res
30.642857
429
3,111
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import requests from werkzeug import urls from odoo import _, api, fields, models, service from odoo.exceptions import ValidationError from odoo.addons.payment_mollie.const import SUPPORTED_CURRENCIES _logger = logging.getLogger(__name__) class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection( selection_add=[('mollie', 'Mollie')], ondelete={'mollie': 'set default'} ) mollie_api_key = fields.Char( string="Mollie API Key", help="The Test or Live API Key depending on the configuration of the acquirer", required_if_provider="mollie", groups="base.group_system" ) #=== BUSINESS METHODS ===# @api.model def _get_compatible_acquirers(self, *args, currency_id=None, **kwargs): """ Override of payment to unlist Mollie acquirers for unsupported currencies. """ acquirers = super()._get_compatible_acquirers(*args, currency_id=currency_id, **kwargs) currency = self.env['res.currency'].browse(currency_id).exists() if currency and currency.name not in SUPPORTED_CURRENCIES: acquirers = acquirers.filtered(lambda a: a.provider != 'mollie') return acquirers def _get_default_payment_method_id(self): self.ensure_one() if self.provider != 'mollie': return super()._get_default_payment_method_id() return self.env.ref('payment_mollie.payment_method_mollie').id def _mollie_make_request(self, endpoint, data=None, method='POST'): """ Make a request at mollie endpoint. Note: self.ensure_one() :param str endpoint: The endpoint to be reached by the request :param dict data: The payload of the request :param str method: The HTTP method of the request :return The JSON-formatted content of the response :rtype: dict :raise: ValidationError if an HTTP error occurs """ self.ensure_one() endpoint = f'/v2/{endpoint.strip("/")}' url = urls.url_join('https://api.mollie.com/', endpoint) odoo_version = service.common.exp_version()['server_version'] module_version = self.env.ref('base.module_payment_mollie').installed_version headers = { "Accept": "application/json", "Authorization": f'Bearer {self.mollie_api_key}', "Content-Type": "application/json", # See https://docs.mollie.com/integration-partners/user-agent-strings "User-Agent": f'Odoo/{odoo_version} MollieNativeOdoo/{module_version}', } try: response = requests.request(method, url, json=data, headers=headers, timeout=60) response.raise_for_status() except requests.exceptions.RequestException: _logger.exception("Unable to communicate with Mollie: %s", url) raise ValidationError("Mollie: " + _("Could not establish the connection to the API.")) return response.json()
38.8875
3,111
2,575
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pprint from odoo import http from odoo.exceptions import ValidationError from odoo.http import request _logger = logging.getLogger(__name__) class MollieController(http.Controller): _return_url = "/payment/mollie/return" _notify_url = "/payment/mollie/notify" @http.route( _return_url, type='http', auth='public', methods=['GET', 'POST'], csrf=False, save_session=False ) def mollie_return(self, **data): """ Process the data returned by Mollie after redirection. The route is flagged with `save_session=False` to prevent Odoo from assigning a new session to the user if they are redirected to this route with a POST request. Indeed, as the session cookie is created without a `SameSite` attribute, some browsers that don't implement the recommended default `SameSite=Lax` behavior will not include the cookie in the redirection request from the payment provider to Odoo. As the redirection to the '/payment/status' page will satisfy any specification of the `SameSite` attribute, the session of the user will be retrieved and with it the transaction which will be immediately post-processed. :param dict data: The feedback data (only `id`) and the transaction reference (`ref`) embedded in the return URL """ _logger.info("Received Mollie return data:\n%s", pprint.pformat(data)) request.env['payment.transaction'].sudo()._handle_feedback_data('mollie', data) return request.redirect('/payment/status') @http.route(_notify_url, type='http', auth='public', methods=['POST'], csrf=False) def mollie_notify(self, **data): """ Process the data sent by Mollie to the webhook. :param dict data: The feedback data (only `id`) and the transaction reference (`ref`) embedded in the return URL :return: An empty string to acknowledge the notification :rtype: str """ _logger.info("Received Mollie notify data:\n%s", pprint.pformat(data)) try: request.env['payment.transaction'].sudo()._handle_feedback_data('mollie', data) except ValidationError: # Acknowledge the notification to avoid getting spammed _logger.exception("unable to handle the notification data; skipping to acknowledge") return '' # Acknowledge the notification with an HTTP 200 response
47.685185
2,575
751
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Point of Sale Discounts', 'version': '1.0', 'category': 'Sales/Point of Sale', 'sequence': 6, 'summary': 'Simple Discounts in the Point of Sale ', 'description': """ This module allows the cashier to quickly give percentage-based discount to a customer. """, 'depends': ['point_of_sale'], 'data': [ 'views/pos_discount_views.xml', ], 'installable': True, 'assets': { 'point_of_sale.assets': [ 'pos_discount/static/src/js/**/*', ], 'web.assets_qweb': [ 'pos_discount/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
24.225806
751
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 PosConfig(models.Model): _inherit = 'pos.config' iface_discount = fields.Boolean(string='Order Discounts', help='Allow the cashier to give discounts on the whole order.') discount_pc = fields.Float(string='Discount Percentage', help='The default discount percentage', default=10.0) discount_product_id = fields.Many2one('product.product', string='Discount Product', domain="[('sale_ok', '=', True)]", help='The product used to model the discount.') @api.onchange('company_id','module_pos_discount') def _default_discount_product_id(self): product = self.env.ref("point_of_sale.product_product_consumable", raise_if_not_found=False) self.discount_product_id = product if self.module_pos_discount and product and (not product.company_id or product.company_id == self.company_id) else False @api.model def _default_discount_value_on_module_install(self): configs = self.env['pos.config'].search([]) open_configs = ( self.env['pos.session'] .search(['|', ('state', '!=', 'closed'), ('rescue', '=', True)]) .mapped('config_id') ) # Do not modify configs where an opened session exists. for conf in (configs - open_configs): conf._default_discount_product_id()
48.233333
1,447
1,070
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Dashboards', 'version': '1.0', 'category': 'Productivity', 'sequence': 225, 'summary': 'Build your own dashboards', 'description': """ Lets the user create a custom dashboard. ======================================== Allows users to create custom dashboard. """, 'depends': ['base', 'web'], 'data': [ 'security/ir.model.access.csv', 'views/board_views.xml', ], 'application': True, 'assets': { 'web.assets_backend': [ 'board/static/src/**/*.scss', 'board/static/src/**/*.js', ], 'web.qunit_suite_tests': [ 'board/static/tests/**/*', ('remove', 'board/static/tests/mobile/**/*'), # mobile test ], 'web.qunit_mobile_suite_tests': [ 'board/static/tests/mobile/**/*', ], 'web.assets_qweb': [ 'board/static/src/**/*.xml', ], }, 'license': 'LGPL-3', }
27.435897
1,070
2,126
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 Board(models.AbstractModel): _name = 'board.board' _description = "Board" _auto = False # This is necessary for when the web client opens a dashboard. Technically # speaking, the dashboard is a form view, and opening it makes the client # initialize a dummy record by invoking onchange(). And the latter requires # an 'id' field to work properly... id = fields.Id() @api.model_create_multi def create(self, vals_list): return self @api.model def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): """ Overrides orm field_view_get. @return: Dictionary of Fields, arch and toolbar. """ res = super(Board, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) custom_view = self.env['ir.ui.view.custom'].search([('user_id', '=', self.env.uid), ('ref_id', '=', view_id)], limit=1) if custom_view: res.update({'custom_view_id': custom_view.id, 'arch': custom_view.arch}) res.update({ 'arch': self._arch_preprocessing(res['arch']), 'toolbar': {'print': [], 'action': [], 'relate': []} }) return res @api.model def _arch_preprocessing(self, arch): from lxml import etree def remove_unauthorized_children(node): for child in node.iterchildren(): if child.tag == 'action' and child.get('invisible'): node.remove(child) else: remove_unauthorized_children(child) return node archnode = etree.fromstring(arch) # add the js_class 'board' on the fly to force the webclient to # instantiate a BoardView instead of FormView archnode.set('js_class', 'board') return etree.tostring(remove_unauthorized_children(archnode), pretty_print=True, encoding='unicode')
37.298246
2,126
2,026
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree as ElementTree from odoo.http import Controller, route, request class Board(Controller): @route('/board/add_to_dashboard', type='json', auth='user') def add_to_dashboard(self, action_id, context_to_save, domain, view_mode, name=''): # Retrieve the 'My Dashboard' action from its xmlid action = request.env.ref('board.open_board_my_dash_action').sudo() if action and action['res_model'] == 'board.board' and action['views'][0][1] == 'form' and action_id: # Maybe should check the content instead of model board.board ? view_id = action['views'][0][0] board = request.env['board.board'].fields_view_get(view_id, 'form') if board and 'arch' in board: xml = ElementTree.fromstring(board['arch']) column = xml.find('./board/column') if column is not None: # We don't want to save allowed_company_ids # Otherwise on dashboard, the multi-company widget does not filter the records if 'allowed_company_ids' in context_to_save: context_to_save.pop('allowed_company_ids') new_action = ElementTree.Element('action', { 'name': str(action_id), 'string': name, 'view_mode': view_mode, 'context': str(context_to_save), 'domain': str(domain) }) column.insert(0, new_action) arch = ElementTree.tostring(xml, encoding='unicode') request.env['ir.ui.view.custom'].create({ 'user_id': request.session.uid, 'ref_id': view_id, 'arch': arch }) return True return False
46.045455
2,026
626
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Paypal Payment Acquirer', 'version': '2.0', 'category': 'Accounting/Payment Acquirers', 'sequence': 365, 'summary': 'Payment Acquirer: Paypal Implementation', 'description': """Paypal Payment Acquirer""", 'depends': ['payment'], 'data': [ 'views/payment_views.xml', 'views/payment_paypal_templates.xml', 'data/payment_acquirer_data.xml', 'data/payment_paypal_email_data.xml', ], 'application': True, 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3', }
31.3
626
713
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # ISO 4217 codes of currencies supported by PayPal SUPPORTED_CURRENCIES = ( 'AUD', 'BRL', 'CAD', 'CNY', 'CZK', 'DKK', 'EUR', 'HKD', 'HUF', 'ILS', 'JPY', 'MYR', 'MXN', 'TWD', 'NZD', 'NOK', 'PHP', 'PLN', 'GBP', 'RUB', 'SGD', 'SEK', 'CHF', 'THB', 'USD', ) # Mapping of transaction states to PayPal payment statuses # See https://developer.paypal.com/docs/api-basics/notifications/ipn/IPNandPDTVariables/ PAYMENT_STATUS_MAPPING = { 'pending': ('Pending',), 'done': ('Processed', 'Completed'), 'cancel': ('Voided', 'Expired'), }
18.763158
713
7,507
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import ValidationError from odoo.tools import mute_logger from odoo.tests import tagged from .common import PaypalCommon from ..controllers.main import PaypalController @tagged('post_install', '-at_install') class PaypalForm(PaypalCommon): def _get_expected_values(self): return_url = self._build_url(PaypalController._return_url) values = { 'address1': 'Huge Street 2/543', 'amount': str(self.amount), 'business': self.paypal.paypal_email_account, 'cancel_return': return_url, 'city': 'Sin City', 'cmd': '_xclick', 'country': 'BE', 'currency_code': self.currency.name, 'email': '[email protected]', 'first_name': 'Norbert', 'item_name': f'{self.paypal.company_id.name}: {self.reference}', 'item_number': self.reference, 'last_name': 'Buyer', 'lc': 'en_US', 'notify_url': self._build_url(PaypalController._notify_url), 'return': return_url, 'rm': '2', 'zip': '1000', } if self.paypal.fees_active: fees = self.currency.round(self.paypal._compute_fees(self.amount, self.currency, self.partner.country_id)) if fees: # handling input is only specified if truthy values['handling'] = str(fees) return values def test_redirect_form_values(self): tx = self.create_transaction(flow='redirect') with mute_logger('odoo.addons.payment.models.payment_transaction'): processing_values = tx._get_processing_values() form_info = self._extract_values_from_html_form(processing_values['redirect_form_html']) self.assertEqual( form_info['action'], 'https://www.sandbox.paypal.com/cgi-bin/webscr') expected_values = self._get_expected_values() self.assertDictEqual( expected_values, form_info['inputs'], "Paypal: invalid inputs specified in the redirect form.") def test_redirect_form_with_fees(self): self.paypal.write({ 'fees_active': True, 'fees_dom_fixed': 1.0, 'fees_dom_var': 0.35, 'fees_int_fixed': 1.5, 'fees_int_var': 0.50, }) expected_values = self._get_expected_values() tx = self.create_transaction(flow='redirect') with mute_logger('odoo.addons.payment.models.payment_transaction'): processing_values = tx._get_processing_values() form_info = self._extract_values_from_html_form(processing_values['redirect_form_html']) self.assertEqual(form_info['action'], 'https://www.sandbox.paypal.com/cgi-bin/webscr') self.assertDictEqual( expected_values, form_info['inputs'], "Paypal: invalid inputs specified in the redirect form.") def test_feedback_processing(self): # typical data posted by paypal after client has successfully paid paypal_post_data = { 'protection_eligibility': u'Ineligible', 'last_name': u'Poilu', 'txn_id': u'08D73520KX778924N', 'receiver_email': 'dummy', 'payment_status': u'Pending', 'payment_gross': u'', 'tax': u'0.00', 'residence_country': u'FR', 'address_state': u'Alsace', 'payer_status': u'verified', 'txn_type': u'web_accept', 'address_street': u'Av. de la Pelouse, 87648672 Mayet', 'handling_amount': u'0.00', 'payment_date': u'03:21:19 Nov 18, 2013 PST', 'first_name': u'Norbert', 'item_name': self.reference, 'address_country': u'France', 'charset': u'windows-1252', 'notify_version': u'3.7', 'address_name': u'Norbert Poilu', 'pending_reason': u'multi_currency', 'item_number': self.reference, 'receiver_id': u'dummy', 'transaction_subject': u'', 'business': u'dummy', 'test_ipn': u'1', 'payer_id': u'VTDKRZQSAHYPS', 'verify_sign': u'An5ns1Kso7MWUdW4ErQKJJJ4qi4-AVoiUf-3478q3vrSmqh08IouiYpM', 'address_zip': u'75002', 'address_country_code': u'FR', 'address_city': u'Paris', 'address_status': u'unconfirmed', 'mc_currency': u'EUR', 'shipping': u'0.00', 'payer_email': u'[email protected]', 'payment_type': u'instant', 'mc_gross': str(self.amount), 'ipn_track_id': u'866df2ccd444b', 'quantity': u'1' } # should raise error about unknown tx with self.assertRaises(ValidationError): self.env['payment.transaction']._handle_feedback_data('paypal', paypal_post_data) tx = self.create_transaction(flow='redirect') # Validate the transaction (pending feedback) self.env['payment.transaction']._handle_feedback_data('paypal', paypal_post_data) self.assertEqual(tx.state, 'pending', 'paypal: wrong state after receiving a valid pending notification') self.assertEqual(tx.state_message, 'multi_currency', 'paypal: wrong state message after receiving a valid pending notification') self.assertEqual(tx.acquirer_reference, '08D73520KX778924N', 'paypal: wrong txn_id after receiving a valid pending notification') # Reset the transaction tx.write({'state': 'draft', 'acquirer_reference': False}) # Validate the transaction ('completed' feedback) paypal_post_data['payment_status'] = 'Completed' self.env['payment.transaction']._handle_feedback_data('paypal', paypal_post_data) self.assertEqual(tx.state, 'done', 'paypal: wrong state after receiving a valid pending notification') self.assertEqual(tx.acquirer_reference, '08D73520KX778924N', 'paypal: wrong txn_id after receiving a valid pending notification') def test_fees_computation(self): #If the merchant needs to keep 100€, the transaction will be equal to 103.30€. #In this way, Paypal will take 103.30 * 2.9% + 0.30 = 3.30€ #And the merchant will take 103.30 - 3.30 = 100€ self.paypal.write({ 'fees_active': True, 'fees_int_fixed': 0.30, 'fees_int_var': 2.90, }) total_fee = self.paypal._compute_fees(100, False, False) self.assertEqual(round(total_fee, 2), 3.3, 'Wrong computation of the Paypal fees') def test_parsing_pdt_validation_response_returns_notification_data(self): """ Test that the notification data are parsed from the content of a validation response.""" response_content = 'SUCCESS\nkey1=val1\nkey2=val+2\n' notification_data = PaypalController._parse_pdt_validation_response(response_content) self.assertDictEqual(notification_data, {'key1': 'val1', 'key2': 'val 2'}) def test_fail_to_parse_pdt_validation_response_if_not_successful(self): """ Test that no notification data are returned from parsing unsuccessful PDT validation.""" response_content = 'FAIL\ndoes-not-matter' notification_data = PaypalController._parse_pdt_validation_response(response_content) self.assertIsNone(notification_data)
44.904192
7,499
589
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.payment.tests.common import PaymentCommon class PaypalCommon(PaymentCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.paypal = cls._prepare_acquirer('paypal', update_values={ 'paypal_email_account': '[email protected]', 'fees_active': False, }) # Override default values cls.acquirer = cls.paypal cls.currency = cls.currency_euro
32.722222
589
4,854
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from werkzeug import urls from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.addons.payment import utils as payment_utils from odoo.addons.payment_paypal.const import PAYMENT_STATUS_MAPPING from odoo.addons.payment_paypal.controllers.main import PaypalController _logger = logging.getLogger(__name__) class PaymentTransaction(models.Model): _inherit = 'payment.transaction' # See https://developer.paypal.com/docs/api-basics/notifications/ipn/IPNandPDTVariables/ paypal_type = fields.Char( string="PayPal Transaction Type", help="This has no use in Odoo except for debugging.") def _get_specific_rendering_values(self, processing_values): """ Override of payment to return Paypal-specific rendering values. Note: self.ensure_one() from `_get_processing_values` :param dict processing_values: The generic and specific processing values of the transaction :return: The dict of acquirer-specific processing values :rtype: dict """ res = super()._get_specific_rendering_values(processing_values) if self.provider != 'paypal': return res base_url = self.acquirer_id.get_base_url() partner_first_name, partner_last_name = payment_utils.split_partner_name(self.partner_name) notify_url = self.acquirer_id.paypal_use_ipn \ and urls.url_join(base_url, PaypalController._notify_url) return { 'address1': self.partner_address, 'amount': self.amount, 'business': self.acquirer_id.paypal_email_account, 'city': self.partner_city, 'country': self.partner_country_id.code, 'currency_code': self.currency_id.name, 'email': self.partner_email, 'first_name': partner_first_name, 'handling': self.fees, 'item_name': f"{self.company_id.name}: {self.reference}", 'item_number': self.reference, 'last_name': partner_last_name, 'lc': self.partner_lang, 'notify_url': notify_url, 'return_url': urls.url_join(base_url, PaypalController._return_url), 'state': self.partner_state_id.name, 'zip_code': self.partner_zip, 'api_url': self.acquirer_id._paypal_get_api_url(), } @api.model def _get_tx_from_feedback_data(self, provider, data): """ Override of payment to find the transaction based on Paypal data. :param str provider: The provider of the acquirer that handled the transaction :param dict data: The feedback data sent by the provider :return: The transaction if found :rtype: recordset of `payment.transaction` :raise: ValidationError if the data match no transaction """ tx = super()._get_tx_from_feedback_data(provider, data) if provider != 'paypal': return tx reference = data.get('item_number') tx = self.search([('reference', '=', reference), ('provider', '=', 'paypal')]) if not tx: raise ValidationError( "PayPal: " + _("No transaction found matching reference %s.", reference) ) return tx def _process_feedback_data(self, data): """ Override of payment to process the transaction based on Paypal data. Note: self.ensure_one() :param dict data: The feedback data sent by the provider :return: None :raise: ValidationError if inconsistent data were received """ super()._process_feedback_data(data) if self.provider != 'paypal': return txn_id = data.get('txn_id') txn_type = data.get('txn_type') if not all((txn_id, txn_type)): raise ValidationError( "PayPal: " + _( "Missing value for txn_id (%(txn_id)s) or txn_type (%(txn_type)s).", txn_id=txn_id, txn_type=txn_type ) ) self.acquirer_reference = txn_id self.paypal_type = txn_type payment_status = data.get('payment_status') if payment_status in PAYMENT_STATUS_MAPPING['pending']: self._set_pending(state_message=data.get('pending_reason')) elif payment_status in PAYMENT_STATUS_MAPPING['done']: self._set_done() elif payment_status in PAYMENT_STATUS_MAPPING['cancel']: self._set_canceled() else: _logger.info("received data with invalid payment status: %s", payment_status) self._set_error( "PayPal: " + _("Received data with invalid payment status: %s", payment_status) )
40.115702
4,854
429
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 AccountPaymentMethod(models.Model): _inherit = 'account.payment.method' @api.model def _get_payment_method_information(self): res = super()._get_payment_method_information() res['paypal'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]} return res
30.642857
429
2,111
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import _, api, fields, models from odoo.addons.payment_paypal.const import SUPPORTED_CURRENCIES _logger = logging.getLogger(__name__) class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection( selection_add=[('paypal', "Paypal")], ondelete={'paypal': 'set default'}) paypal_email_account = fields.Char( string="Email", help="The public business email solely used to identify the account with PayPal", required_if_provider='paypal') paypal_seller_account = fields.Char( string="Merchant Account ID", groups='base.group_system') paypal_pdt_token = fields.Char(string="PDT Identity Token", groups='base.group_system') paypal_use_ipn = fields.Boolean( string="Use IPN", help="Paypal Instant Payment Notification", default=True) @api.model def _get_compatible_acquirers(self, *args, currency_id=None, **kwargs): """ Override of payment to unlist PayPal acquirers when the currency is not supported. """ acquirers = super()._get_compatible_acquirers(*args, currency_id=currency_id, **kwargs) currency = self.env['res.currency'].browse(currency_id).exists() if currency and currency.name not in SUPPORTED_CURRENCIES: acquirers = acquirers.filtered(lambda a: a.provider != 'paypal') return acquirers def _paypal_get_api_url(self): """ Return the API URL according to the acquirer state. Note: self.ensure_one() :return: The API URL :rtype: str """ self.ensure_one() if self.state == 'enabled': return 'https://www.paypal.com/cgi-bin/webscr' else: return 'https://www.sandbox.paypal.com/cgi-bin/webscr' def _get_default_payment_method_id(self): self.ensure_one() if self.provider != 'paypal': return super()._get_default_payment_method_id() return self.env.ref('payment_paypal.payment_method_paypal').id
37.035088
2,111
8,968
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pprint import requests from requests.exceptions import ConnectionError, HTTPError from werkzeug import urls from odoo import _, http from odoo.exceptions import ValidationError from odoo.http import request from odoo.tools import html_escape _logger = logging.getLogger(__name__) class PaypalController(http.Controller): _return_url = '/payment/paypal/dpn/' _notify_url = '/payment/paypal/ipn/' @http.route( _return_url, type='http', auth='public', methods=['GET', 'POST'], csrf=False, save_session=False ) def paypal_dpn(self, **data): """ Route used by the PDT notification. The "PDT notification" is actually POST data sent along the user redirection. The route also allows the GET method in case the user clicks on "go back to merchant site". The route is flagged with `save_session=False` to prevent Odoo from assigning a new session to the user if they are redirected to this route with a POST request. Indeed, as the session cookie is created without a `SameSite` attribute, some browsers that don't implement the recommended default `SameSite=Lax` behavior will not include the cookie in the redirection request from the payment provider to Odoo. As the redirection to the '/payment/status' page will satisfy any specification of the `SameSite` attribute, the session of the user will be retrieved and with it the transaction which will be immediately post-processed. """ _logger.info("beginning DPN with post data:\n%s", pprint.pformat(data)) if not data: # The customer has cancelled the payment pass # Redirect them to the status page to browse the draft transaction else: try: notification_data = self._validate_pdt_data_authenticity(**data) except ValidationError: _logger.exception("could not verify the origin of the PDT; discarding it") else: request.env['payment.transaction'].sudo()._handle_feedback_data( 'paypal', notification_data ) return request.redirect('/payment/status') def _validate_pdt_data_authenticity(self, **data): """ Validate the authenticity of PDT data and return the retrieved notification data. The validation is done in four steps: 1. Make a POST request to Paypal with `tx`, the GET param received with the PDT data, and with the two other required params `cmd` and `at`. 2. PayPal sends back a response text starting with either 'SUCCESS' or 'FAIL'. If the validation was a success, the notification data are appended to the response text as a string formatted as follows: 'SUCCESS\nparam1=value1\nparam2=value2\n...' 3. Extract the notification data and process these instead of the PDT data. 4. Return an empty HTTP 200 response (done at the end of the route controller). See https://developer.paypal.com/docs/api-basics/notifications/payment-data-transfer/. :param dict data: The data whose authenticity must be checked. :return: The retrieved notification data :raise ValidationError: if the authenticity could not be verified """ tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_feedback_data( 'paypal', data ) if 'tx' not in data: # PDT is not enabled and PayPal directly sent the notification data. tx_sudo._log_message_on_linked_documents(_( "The status of transaction with reference %(ref)s was not synchronized because the " "'Payment data transfer' option is not enabled on the PayPal dashboard.", ref=tx_sudo.reference, )) raise ValidationError("PayPal: PDT are not enabled; cannot verify data origin") else: acquirer_sudo = tx_sudo.acquirer_id if not acquirer_sudo.paypal_pdt_token: # We received PDT data but can't verify them record_link = f'<a href=# data-oe-model=payment.acquirer ' \ f'data-oe-id={acquirer_sudo.id}>{html_escape(acquirer_sudo.name)}</a>' tx_sudo._log_message_on_linked_documents(_( "The status of transaction with reference %(ref)s was not synchronized because " "the PDT Identify Token is not configured on the acquirer %(acq_link)s.", ref=tx_sudo.reference, acq_link=record_link )) raise ValidationError("PayPal: The PDT token is not set; cannot verify data origin") else: # The PayPal account is configured to receive PDT data, and the PDT token is set # Request a PDT data authenticity check and the notification data to PayPal url = acquirer_sudo._paypal_get_api_url() payload = { 'cmd': '_notify-synch', 'tx': data['tx'], 'at': acquirer_sudo.paypal_pdt_token, } try: response = requests.post(url, data=payload, timeout=10) response.raise_for_status() except (ConnectionError, HTTPError): raise ValidationError("PayPal: Encountered an error when verifying PDT origin") else: notification_data = self._parse_pdt_validation_response(response.text) if notification_data is None: raise ValidationError("PayPal: The PDT origin was not verified by PayPal") return notification_data @staticmethod def _parse_pdt_validation_response(response_content): """ Parse the validation response and return the parsed notification data. :param str response_content: The PDT validation request response :return: The parsed notification data :rtype: dict """ response_items = response_content.splitlines() if response_items[0] == 'SUCCESS': notification_data = {} for notification_data_param in response_items[1:]: key, raw_value = notification_data_param.split('=', 1) notification_data[key] = urls.url_unquote_plus(raw_value) return notification_data return None @http.route(_notify_url, type='http', auth='public', methods=['GET', 'POST'], csrf=False) def paypal_ipn(self, **data): """ Route used by the IPN. """ _logger.info("beginning IPN with post data:\n%s", pprint.pformat(data)) try: self._validate_ipn_data_authenticity(**data) request.env['payment.transaction'].sudo()._handle_feedback_data('paypal', data) except ValidationError: # Acknowledge the notification to avoid getting spammed _logger.exception("unable to handle the IPN data; skipping to acknowledge the notif") return '' def _validate_ipn_data_authenticity(self, **data): """ Validate the authenticity of IPN data. The verification is done in three steps: 1. POST the complete, unaltered, message back to Paypal (preceded by `cmd=_notify-validate`), in the same encoding. 2. PayPal sends back either 'VERIFIED' or 'INVALID'. 3. Return an empty HTTP 200 response (done at the end of the route method). See https://developer.paypal.com/docs/api-basics/notifications/ipn/IPNIntro/. :param dict data: The data whose authenticity must be checked. :return: None :raise ValidationError: if the authenticity could not be verified """ tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_feedback_data( 'paypal', data ) acquirer_sudo = tx_sudo.acquirer_id # Request PayPal for an authenticity check data['cmd'] = '_notify-validate' response = requests.post(acquirer_sudo._paypal_get_api_url(), data, timeout=60) response.raise_for_status() # Inspect the response code and raise if not 'VERIFIED'. response_code = response.text if response_code == 'VERIFIED': _logger.info("authenticity of notification data verified") else: if response_code == 'INVALID': error_message = "PayPal: " + _("Notification data were not acknowledged.") else: error_message = "PayPal: " + _( "Received unrecognized authentication check response code: received %s, " "expected VERIFIED or INVALID.", response_code ) tx_sudo._set_error(error_message) raise ValidationError(error_message)
48.73913
8,968
451
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Mass mailing sms on lead / opportunities', 'category': 'Hidden', 'version': '1.0', 'summary': 'Add lead / opportunities info on mass mailing sms', 'description': """Mass mailing sms on lead / opportunities""", 'depends': ['mass_mailing_crm', 'mass_mailing_sms'], 'auto_install': True, 'license': 'LGPL-3', }
34.692308
451
298
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 UtmCampaign(models.Model): _inherit = 'utm.campaign' ab_testing_sms_winner_selection = fields.Selection(selection_add=[('crm_lead_count', 'Leads')])
29.8
298
1,869
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'SMS gateway', 'version': '2.2', 'category': 'Hidden/Tools', 'summary': 'SMS Text Messaging', 'description': """ This module gives a framework for SMS text messaging ---------------------------------------------------- The service is provided by the In App Purchase Odoo platform. """, 'depends': [ 'base', 'iap_mail', 'mail', 'phone_validation' ], 'data': [ 'data/ir_cron_data.xml', 'wizard/sms_cancel_views.xml', 'wizard/sms_composer_views.xml', 'wizard/sms_template_preview_views.xml', 'wizard/sms_resend_views.xml', 'views/ir_actions_views.xml', 'views/mail_notification_views.xml', 'views/res_config_settings_views.xml', 'views/res_partner_views.xml', 'views/sms_sms_views.xml', 'views/sms_template_views.xml', 'security/ir.model.access.csv', 'security/sms_security.xml', ], 'demo': [ 'data/sms_demo.xml', 'data/mail_demo.xml', ], 'installable': True, 'auto_install': True, 'assets': { 'mail.assets_discuss_public': [ 'sms/static/src/components/*/*', 'sms/static/src/models/*/*.js', ], 'web.assets_backend': [ 'sms/static/src/js/fields_phone_widget.js', 'sms/static/src/js/fields_sms_widget.js', 'sms/static/src/components/*/*.js', 'sms/static/src/models/*/*.js', ], 'web.qunit_suite_tests': [ 'sms/static/tests/sms_widget_test.js', 'sms/static/src/components/*/tests/*.js', ], 'web.assets_qweb': [ 'sms/static/src/components/*/*.xml', ], }, 'license': 'LGPL-3', }
30.145161
1,869
4,996
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, users from odoo.addons.mail.tests.common import mail_new_test_user from odoo.exceptions import AccessError from odoo.tests import tagged from odoo.tools import mute_logger @tagged('post_install', '-at_install') class TestSmsTemplateAccessRights(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user_admin = mail_new_test_user(cls.env, login='user_system', groups='base.group_user,base.group_system') cls.basic_user = mail_new_test_user(cls.env, login='user_employee', groups='base.group_user') sms_enabled_models = cls.env['ir.model'].search([('is_mail_thread', '=', True), ('transient', '=', False)]) vals = [] for model in sms_enabled_models: vals.append({ 'name': 'SMS Template ' + model.name, 'body': 'Body Test', 'model_id': model.id, }) cls.sms_templates = cls.env['sms.template'].create(vals) cls.sms_dynamic_template = cls.env['sms.template'].sudo().create({ 'body': '{{ object.name }}', 'model_id': cls.env['ir.model'].sudo().search([('model', '=', 'res.partner')]).id, }) cls.partner = cls.env['res.partner'].create({'name': 'Test Partner'}) @users('user_employee') @mute_logger('odoo.models.unlink') def test_access_rights_user(self): # Check if a member of group_user can only read on sms.template for sms_template in self.env['sms.template'].browse(self.sms_templates.ids): self.assertTrue(bool(sms_template.name)) with self.assertRaises(AccessError): sms_template.write({'name': 'Update Template'}) with self.assertRaises(AccessError): self.env['sms.template'].create({ 'name': 'New SMS Template ' + sms_template.model_id.name, 'body': 'Body Test', 'model_id': sms_template.model_id.id, }) with self.assertRaises(AccessError): sms_template.unlink() @users('user_system') @mute_logger('odoo.models.unlink', 'odoo.addons.base.models.ir_model') def test_access_rights_system(self): admin = self.env.ref('base.user_admin') for sms_template in self.env['sms.template'].browse(self.sms_templates.ids): self.assertTrue(bool(sms_template.name)) sms_template.write({'body': 'New body from admin'}) self.env['sms.template'].create({ 'name': 'New SMS Template ' + sms_template.model_id.name, 'body': 'Body Test', 'model_id': sms_template.model_id.id, }) # check admin is allowed to read all templates since he can be a member of # other groups applying restrictions based on the model self.assertTrue(bool(self.env['sms.template'].with_user(admin).browse(sms_template.ids).name)) sms_template.unlink() @users('user_employee') def test_sms_template_rendering_restricted(self): self.env['ir.config_parameter'].sudo().set_param('mail.restrict.template.rendering', True) self.basic_user.groups_id -= self.env.ref('mail.group_mail_template_editor') sms_composer = self.env['sms.composer'].create({ 'composition_mode': 'comment', 'template_id': self.sms_dynamic_template.id, 'res_id': self.partner.id, 'res_model': 'res.partner', }) self.assertEqual(sms_composer.body, self.partner.name, 'Simple user should be able to render SMS template') sms_composer.composition_mode = 'mass' self.assertEqual(sms_composer.body, '{{ object.name }}', 'In mass mode, we should not render the template') body = sms_composer._prepare_body_values(self.partner)[self.partner.id] self.assertEqual(body, self.partner.name, 'In mass mode, if the user did not change the body, he should be able to render it') sms_composer.body = 'New body: {{ 4 + 9 }}' with self.assertRaises(AccessError, msg='User should not be able to write new inline_template code'): sms_composer._prepare_body_values(self.partner) @users('user_system') def test_sms_template_rendering_unrestricted(self): self.env['ir.config_parameter'].sudo().set_param('mail.restrict.template.rendering', True) sms_composer = self.env['sms.composer'].create({ 'composition_mode': 'comment', 'template_id': self.sms_dynamic_template.id, 'res_id': self.partner.id, 'res_model': 'res.partner', }) body = sms_composer._prepare_body_values(self.partner)[self.partner.id] self.assertIn(self.partner.name, body, 'Template Editor should be able to write new Jinja code')
46.259259
4,996
13,520
py
PYTHON
15.0
# -*- coding: utf-8 -*- from contextlib import contextmanager from unittest.mock import patch from odoo import exceptions, tools from odoo.tests import common from odoo.addons.mail.tests.common import MailCommon from odoo.addons.phone_validation.tools import phone_validation from odoo.addons.sms.models.sms_api import SmsApi from odoo.addons.sms.models.sms_sms import SmsSms class MockSMS(common.BaseCase): def tearDown(self): super(MockSMS, self).tearDown() self._clear_sms_sent() @contextmanager def mockSMSGateway(self, sms_allow_unlink=False, sim_error=None, nbr_t_error=None): self._clear_sms_sent() sms_create_origin = SmsSms.create sms_send_origin = SmsSms._send def _contact_iap(local_endpoint, params): # mock single sms sending if local_endpoint == '/iap/message_send': self._sms += [{ 'number': number, 'body': params['message'], } for number in params['numbers']] return True # send_message v0 API returns always True # mock batch sending if local_endpoint == '/iap/sms/2/send': result = [] for to_send in params['messages']: res = {'res_id': to_send['res_id'], 'state': 'success', 'credit': 1} error = sim_error or (nbr_t_error and nbr_t_error.get(to_send['number'])) if error and error == 'credit': res.update(credit=0, state='insufficient_credit') elif error and error == 'wrong_number_format': res.update(state='wrong_number_format') elif error and error == 'unregistered': res.update(state='unregistered') elif error and error == 'server_error': res.update(state='server_error') elif error and error == 'jsonrpc_exception': raise exceptions.AccessError( 'The url that this service requested returned an error. Please contact the author of the app. The url it tried to contact was ' + local_endpoint ) result.append(res) if res['state'] == 'success': self._sms.append({ 'number': to_send['number'], 'body': to_send['content'], }) return result def _sms_sms_create(model, *args, **kwargs): res = sms_create_origin(model, *args, **kwargs) self._new_sms += res.sudo() return res def _sms_sms_send(records, unlink_failed=False, unlink_sent=True, raise_exception=False): if sms_allow_unlink: return sms_send_origin(records, unlink_failed=unlink_failed, unlink_sent=unlink_sent, raise_exception=raise_exception) else: return sms_send_origin(records, unlink_failed=False, unlink_sent=False, raise_exception=raise_exception) return True try: with patch.object(SmsApi, '_contact_iap', side_effect=_contact_iap), \ patch.object(SmsSms, 'create', autospec=True, wraps=SmsSms, side_effect=_sms_sms_create), \ patch.object(SmsSms, '_send', autospec=True, wraps=SmsSms, side_effect=_sms_sms_send): yield finally: pass def _clear_sms_sent(self): self._sms = [] self._new_sms = self.env['sms.sms'].sudo() def _clear_outoing_sms(self): """ As SMS gateway mock keeps SMS, we may need to remove them manually if there are several tests in the same tx. """ self.env['sms.sms'].sudo().search([('state', '=', 'outgoing')]).unlink() class SMSCase(MockSMS): """ Main test class to use when testing SMS integrations. Contains helpers and tools related to notification sent by SMS. """ def _find_sms_sent(self, partner, number): if number is None and partner: number = partner.phone_get_sanitized_number() sent_sms = next((sms for sms in self._sms if sms['number'] == number), None) if not sent_sms: raise AssertionError('sent sms not found for %s (number: %s)' % (partner, number)) return sent_sms def _find_sms_sms(self, partner, number, status): if number is None and partner: number = partner.phone_get_sanitized_number() domain = [('id', 'in', self._new_sms.ids), ('partner_id', '=', partner.id), ('number', '=', number)] if status: domain += [('state', '=', status)] sms = self.env['sms.sms'].sudo().search(domain) if not sms: raise AssertionError('sms.sms not found for %s (number: %s / status %s)' % (partner, number, status)) if len(sms) > 1: raise NotImplementedError() return sms def assertNoSMS(self): """ Check no sms went through gateway during mock. """ self.assertTrue(len(self._new_sms) == 0) def assertSMSIapSent(self, numbers, content=None): """ Check sent SMS. Order is not checked. Each number should have received the same content. Useful to check batch sending. :param numbers: list of numbers; :param content: content to check for each number; """ for number in numbers: sent_sms = next((sms for sms in self._sms if sms['number'] == number), None) self.assertTrue(bool(sent_sms), 'Number %s not found in %s' % (number, repr([s['number'] for s in self._sms]))) if content is not None: self.assertIn(content, sent_sms['body']) def assertSMSSent(self, numbers, content=None): """ Deprecated. Remove in 14.4 """ return self.assertSMSIapSent(numbers, content=content) def assertSMS(self, partner, number, status, failure_type=None, content=None, fields_values=None): """ Find a ``sms.sms`` record, based on given partner, number and status. :param partner: optional partner, used to find a ``sms.sms`` and a number if not given; :param number: optional number, used to find a ``sms.sms``, notably if partner is not given; :param failure_type: check failure type if SMS is not sent or outgoing; :param content: if given, should be contained in sms body; :param fields_values: optional values allowing to check directly some values on ``sms.sms`` record; """ sms_sms = self._find_sms_sms(partner, number, status) if failure_type: self.assertEqual(sms_sms.failure_type, failure_type) if content is not None: self.assertIn(content, sms_sms.body) for fname, fvalue in (fields_values or {}).items(): self.assertEqual( sms_sms[fname], fvalue, 'SMS: expected %s for %s, got %s' % (fvalue, fname, sms_sms[fname])) if status == 'sent': self.assertSMSIapSent([sms_sms.number], content=content) def assertSMSCanceled(self, partner, number, failure_type, content=None, fields_values=None): """ Check canceled SMS. Search is done for a pair partner / number where partner can be an empty recordset. """ self.assertSMS(partner, number, 'canceled', failure_type=failure_type, content=content, fields_values=fields_values) def assertSMSFailed(self, partner, number, failure_type, content=None, fields_values=None): """ Check failed SMS. Search is done for a pair partner / number where partner can be an empty recordset. """ self.assertSMS(partner, number, 'error', failure_type=failure_type, content=content, fields_values=fields_values) def assertSMSOutgoing(self, partner, number, content=None, fields_values=None): """ Check outgoing SMS. Search is done for a pair partner / number where partner can be an empty recordset. """ self.assertSMS(partner, number, 'outgoing', content=content, fields_values=fields_values) def assertNoSMSNotification(self, messages=None): base_domain = [('notification_type', '=', 'sms')] if messages is not None: base_domain += [('mail_message_id', 'in', messages.ids)] self.assertEqual(self.env['mail.notification'].search(base_domain), self.env['mail.notification']) self.assertEqual(self._sms, []) def assertSMSNotification(self, recipients_info, content, messages=None, check_sms=True, sent_unlink=False): """ Check content of notifications. :param recipients_info: list[{ 'partner': res.partner record (may be empty), 'number': number used for notification (may be empty, computed based on partner), 'state': ready / sent / exception / canceled (sent by default), 'failure_type': optional: sms_number_missing / sms_number_format / sms_credit / sms_server }, { ... }] """ partners = self.env['res.partner'].concat(*list(p['partner'] for p in recipients_info if p.get('partner'))) numbers = [p['number'] for p in recipients_info if p.get('number')] # special case of void notifications: check for False / False notifications if not partners and not numbers: numbers = [False] base_domain = [ '|', ('res_partner_id', 'in', partners.ids), '&', ('res_partner_id', '=', False), ('sms_number', 'in', numbers), ('notification_type', '=', 'sms') ] if messages is not None: base_domain += [('mail_message_id', 'in', messages.ids)] notifications = self.env['mail.notification'].search(base_domain) self.assertEqual(notifications.mapped('res_partner_id'), partners) for recipient_info in recipients_info: partner = recipient_info.get('partner', self.env['res.partner']) number = recipient_info.get('number') state = recipient_info.get('state', 'sent') if number is None and partner: number = partner.phone_get_sanitized_number() notif = notifications.filtered(lambda n: n.res_partner_id == partner and n.sms_number == number and n.notification_status == state) self.assertTrue(notif, 'SMS: not found notification for %s (number: %s, state: %s)' % (partner, number, state)) if state not in ('sent', 'ready', 'canceled'): self.assertEqual(notif.failure_type, recipient_info['failure_type']) if check_sms: if state == 'sent': if sent_unlink: self.assertSMSIapSent([number], content=content) else: self.assertSMS(partner, number, 'sent', content=content) elif state == 'ready': self.assertSMS(partner, number, 'outgoing', content=content) elif state == 'exception': self.assertSMS(partner, number, 'error', failure_type=recipient_info['failure_type'], content=content) elif state == 'canceled': self.assertSMS(partner, number, 'canceled', failure_type=recipient_info['failure_type'], content=content) else: raise NotImplementedError('Not implemented') if messages is not None: for message in messages: self.assertEqual(content, tools.html2plaintext(message.body).rstrip('\n')) def assertSMSLogged(self, records, body): for record in records: message = record.message_ids[-1] self.assertEqual(message.subtype_id, self.env.ref('mail.mt_note')) self.assertEqual(message.message_type, 'sms') self.assertEqual(tools.html2plaintext(message.body).rstrip('\n'), body) class SMSCommon(MailCommon, MockSMS): @classmethod def setUpClass(cls): super(SMSCommon, cls).setUpClass() cls.user_employee.write({'login': 'employee'}) # update country to belgium in order to test sanitization of numbers cls.user_employee.company_id.write({'country_id': cls.env.ref('base.be').id}) # some numbers for testing cls.random_numbers_str = '+32456998877, 0456665544' cls.random_numbers = cls.random_numbers_str.split(', ') cls.random_numbers_san = [phone_validation.phone_format(number, 'BE', '32', force_format='E164') for number in cls.random_numbers] cls.test_numbers = ['+32456010203', '0456 04 05 06', '0032456070809'] cls.test_numbers_san = [phone_validation.phone_format(number, 'BE', '32', force_format='E164') for number in cls.test_numbers] # some numbers for mass testing cls.mass_numbers = ['04561%s2%s3%s' % (x, x, x) for x in range(0, 10)] cls.mass_numbers_san = [phone_validation.phone_format(number, 'BE', '32', force_format='E164') for number in cls.mass_numbers] @classmethod def _create_sms_template(cls, model, body=False): return cls.env['sms.template'].create({ 'name': 'Test Template', 'model_id': cls.env['ir.model']._get(model).id, 'body': body if body else 'Dear {{ object.display_name }} this is an SMS.' })
48.633094
13,520
19,854
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from ast import literal_eval from odoo import api, fields, models, _ from odoo.addons.phone_validation.tools import phone_validation from odoo.exceptions import UserError from odoo.tools import html2plaintext, plaintext2html class SendSMS(models.TransientModel): _name = 'sms.composer' _description = 'Send SMS Wizard' @api.model def default_get(self, fields): result = super(SendSMS, self).default_get(fields) result['res_model'] = result.get('res_model') or self.env.context.get('active_model') if not result.get('active_domain'): result['active_domain'] = repr(self.env.context.get('active_domain', [])) if not result.get('res_ids'): if not result.get('res_id') and self.env.context.get('active_ids') and len(self.env.context.get('active_ids')) > 1: result['res_ids'] = repr(self.env.context.get('active_ids')) if not result.get('res_id'): if not result.get('res_ids') and self.env.context.get('active_id'): result['res_id'] = self.env.context.get('active_id') return result # documents composition_mode = fields.Selection([ ('numbers', 'Send to numbers'), ('comment', 'Post on a document'), ('mass', 'Send SMS in batch')], string='Composition Mode', compute='_compute_composition_mode', readonly=False, required=True, store=True) res_model = fields.Char('Document Model Name') res_id = fields.Integer('Document ID') res_ids = fields.Char('Document IDs') res_ids_count = fields.Integer( 'Visible records count', compute='_compute_recipients_count', compute_sudo=False, help='Number of recipients that will receive the SMS if sent in mass mode, without applying the Active Domain value') use_active_domain = fields.Boolean('Use active domain') active_domain = fields.Text('Active domain', readonly=True) active_domain_count = fields.Integer( 'Active records count', compute='_compute_recipients_count', compute_sudo=False, help='Number of records found when searching with the value in Active Domain') comment_single_recipient = fields.Boolean( 'Single Mode', compute='_compute_comment_single_recipient', compute_sudo=False, help='Indicates if the SMS composer targets a single specific recipient') # options for comment and mass mode mass_keep_log = fields.Boolean('Keep a note on document', default=True) mass_force_send = fields.Boolean('Send directly', default=False) mass_use_blacklist = fields.Boolean('Use blacklist', default=True) # recipients recipient_valid_count = fields.Integer('# Valid recipients', compute='_compute_recipients', compute_sudo=False) recipient_invalid_count = fields.Integer('# Invalid recipients', compute='_compute_recipients', compute_sudo=False) recipient_single_description = fields.Text('Recipients (Partners)', compute='_compute_recipient_single', compute_sudo=False) recipient_single_number = fields.Char('Stored Recipient Number', compute='_compute_recipient_single', compute_sudo=False) recipient_single_number_itf = fields.Char( 'Recipient Number', compute='_compute_recipient_single', readonly=False, compute_sudo=False, store=True, help='UX field allowing to edit the recipient number. If changed it will be stored onto the recipient.') recipient_single_valid = fields.Boolean("Is valid", compute='_compute_recipient_single_valid', compute_sudo=False) number_field_name = fields.Char('Number Field') numbers = fields.Char('Recipients (Numbers)') sanitized_numbers = fields.Char('Sanitized Number', compute='_compute_sanitized_numbers', compute_sudo=False) # content template_id = fields.Many2one('sms.template', string='Use Template', domain="[('model', '=', res_model)]") body = fields.Text( 'Message', compute='_compute_body', readonly=False, store=True, required=True) @api.depends('res_ids_count', 'active_domain_count') @api.depends_context('sms_composition_mode') def _compute_composition_mode(self): for composer in self: if self.env.context.get('sms_composition_mode') == 'guess' or not composer.composition_mode: if composer.res_ids_count > 1 or (composer.use_active_domain and composer.active_domain_count > 1): composer.composition_mode = 'mass' else: composer.composition_mode = 'comment' @api.depends('res_model', 'res_id', 'res_ids', 'active_domain') def _compute_recipients_count(self): for composer in self: composer.res_ids_count = len(literal_eval(composer.res_ids)) if composer.res_ids else 0 if composer.res_model: composer.active_domain_count = self.env[composer.res_model].search_count(literal_eval(composer.active_domain or '[]')) else: composer.active_domain_count = 0 @api.depends('res_id', 'composition_mode') def _compute_comment_single_recipient(self): for composer in self: composer.comment_single_recipient = bool(composer.res_id and composer.composition_mode == 'comment') @api.depends('res_model', 'res_id', 'res_ids', 'use_active_domain', 'composition_mode', 'number_field_name', 'sanitized_numbers') def _compute_recipients(self): for composer in self: composer.recipient_valid_count = 0 composer.recipient_invalid_count = 0 if composer.composition_mode not in ('comment', 'mass') or not composer.res_model: continue records = composer._get_records() if records and issubclass(type(records), self.pool['mail.thread']): res = records._sms_get_recipients_info(force_field=composer.number_field_name, partner_fallback=not composer.comment_single_recipient) composer.recipient_valid_count = len([rid for rid, rvalues in res.items() if rvalues['sanitized']]) composer.recipient_invalid_count = len([rid for rid, rvalues in res.items() if not rvalues['sanitized']]) else: composer.recipient_invalid_count = 0 if ( composer.sanitized_numbers or (composer.composition_mode == 'mass' and composer.use_active_domain) ) else 1 @api.depends('res_model', 'number_field_name') def _compute_recipient_single(self): for composer in self: records = composer._get_records() if not records or not issubclass(type(records), self.pool['mail.thread']) or not composer.comment_single_recipient: composer.recipient_single_description = False composer.recipient_single_number = '' composer.recipient_single_number_itf = '' continue records.ensure_one() res = records._sms_get_recipients_info(force_field=composer.number_field_name, partner_fallback=False) composer.recipient_single_description = res[records.id]['partner'].name or records._sms_get_default_partners().display_name composer.recipient_single_number = res[records.id]['number'] or '' if not composer.recipient_single_number_itf: composer.recipient_single_number_itf = res[records.id]['number'] or '' if not composer.number_field_name: composer.number_field_name = res[records.id]['field_store'] @api.depends('recipient_single_number', 'recipient_single_number_itf') def _compute_recipient_single_valid(self): for composer in self: value = composer.recipient_single_number_itf or composer.recipient_single_number if value: records = composer._get_records() sanitized = phone_validation.phone_sanitize_numbers_w_record([value], records)[value]['sanitized'] composer.recipient_single_valid = bool(sanitized) else: composer.recipient_single_valid = False @api.depends('numbers', 'res_model', 'res_id') def _compute_sanitized_numbers(self): for composer in self: if composer.numbers: record = composer._get_records() if composer.res_model and composer.res_id else self.env.user numbers = [number.strip() for number in composer.numbers.split(',')] sanitize_res = phone_validation.phone_sanitize_numbers_w_record(numbers, record) sanitized_numbers = [info['sanitized'] for info in sanitize_res.values() if info['sanitized']] invalid_numbers = [number for number, info in sanitize_res.items() if info['code']] if invalid_numbers: raise UserError(_('Following numbers are not correctly encoded: %s', repr(invalid_numbers))) composer.sanitized_numbers = ','.join(sanitized_numbers) else: composer.sanitized_numbers = False @api.depends('composition_mode', 'res_model', 'res_id', 'template_id') def _compute_body(self): for record in self: if record.template_id and record.composition_mode == 'comment' and record.res_id: record.body = record.template_id._render_field('body', [record.res_id], compute_lang=True)[record.res_id] elif record.template_id: record.body = record.template_id.body # ------------------------------------------------------------ # CRUD # ------------------------------------------------------------ @api.model def create(self, values): # TDE FIXME: currently have to compute manually to avoid required issue, waiting VFE branch if not values.get('body') or not values.get('composition_mode'): values_wdef = self._add_missing_default_values(values) cache_composer = self.new(values_wdef) cache_composer._compute_body() cache_composer._compute_composition_mode() values['body'] = values.get('body') or cache_composer.body values['composition_mode'] = values.get('composition_mode') or cache_composer.composition_mode return super(SendSMS, self).create(values) # ------------------------------------------------------------ # Actions # ------------------------------------------------------------ def action_send_sms(self): if self.composition_mode in ('numbers', 'comment'): if self.comment_single_recipient and not self.recipient_single_valid: raise UserError(_('Invalid recipient number. Please update it.')) elif not self.comment_single_recipient and self.recipient_invalid_count: raise UserError(_('%s invalid recipients', self.recipient_invalid_count)) self._action_send_sms() return False def action_send_sms_mass_now(self): if not self.mass_force_send: self.write({'mass_force_send': True}) return self.action_send_sms() def _action_send_sms(self): records = self._get_records() if self.composition_mode == 'numbers': return self._action_send_sms_numbers() elif self.composition_mode == 'comment': if records is None or not issubclass(type(records), self.pool['mail.thread']): return self._action_send_sms_numbers() if self.comment_single_recipient: return self._action_send_sms_comment_single(records) else: return self._action_send_sms_comment(records) else: return self._action_send_sms_mass(records) def _action_send_sms_numbers(self): self.env['sms.api']._send_sms_batch([{ 'res_id': 0, 'number': number, 'content': self.body, } for number in self.sanitized_numbers.split(',')]) return True def _action_send_sms_comment_single(self, records=None): # If we have a recipient_single_original number, it's possible this number has been corrected in the popup # if invalid. As a consequence, the test cannot be based on recipient_invalid_count, which count is based # on the numbers in the database. records = records if records is not None else self._get_records() records.ensure_one() if not self.number_field_name: self.numbers = self.recipient_single_number_itf or self.recipient_single_number elif self.recipient_single_number_itf and self.recipient_single_number_itf != self.recipient_single_number: records.write({self.number_field_name: self.recipient_single_number_itf}) return self._action_send_sms_comment(records=records) def _action_send_sms_comment(self, records=None): records = records if records is not None else self._get_records() subtype_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note') messages = self.env['mail.message'] all_bodies = self._prepare_body_values(records) for record in records: messages += record._message_sms( all_bodies[record.id], subtype_id=subtype_id, number_field=self.number_field_name, sms_numbers=self.sanitized_numbers.split(',') if self.sanitized_numbers else None) return messages def _action_send_sms_mass(self, records=None): records = records if records is not None else self._get_records() sms_record_values = self._prepare_mass_sms_values(records) sms_all = self._prepare_mass_sms(records, sms_record_values) if sms_all and self.mass_keep_log and records and issubclass(type(records), self.pool['mail.thread']): log_values = self._prepare_mass_log_values(records, sms_record_values) records._message_log_batch(**log_values) if sms_all and self.mass_force_send: sms_all.filtered(lambda sms: sms.state == 'outgoing').send(auto_commit=False, raise_exception=False) return self.env['sms.sms'].sudo().search([('id', 'in', sms_all.ids)]) return sms_all # ------------------------------------------------------------ # Mass mode specific # ------------------------------------------------------------ def _get_blacklist_record_ids(self, records, recipients_info): """ Get a list of blacklisted records. Those will be directly canceled with the right error code. """ if self.mass_use_blacklist: bl_numbers = self.env['phone.blacklist'].sudo().search([]).mapped('number') return [r.id for r in records if recipients_info[r.id]['sanitized'] in bl_numbers] return [] def _get_optout_record_ids(self, records, recipients_info): """ Compute opt-outed contacts, not necessarily blacklisted. Void by default as no opt-out mechanism exist in SMS, see SMS Marketing. """ return [] def _get_done_record_ids(self, records, recipients_info): """ Get a list of already-done records. Order of record set is used to spot duplicates so pay attention to it if necessary. """ done_ids, done = [], [] for record in records: sanitized = recipients_info[record.id]['sanitized'] if sanitized in done: done_ids.append(record.id) else: done.append(sanitized) return done_ids def _prepare_recipient_values(self, records): recipients_info = records._sms_get_recipients_info(force_field=self.number_field_name) return recipients_info def _prepare_body_values(self, records): if self.template_id and self.body == self.template_id.body: all_bodies = self.template_id._render_field('body', records.ids, compute_lang=True) else: all_bodies = self.env['mail.render.mixin']._render_template(self.body, records._name, records.ids) return all_bodies def _prepare_mass_sms_values(self, records): all_bodies = self._prepare_body_values(records) all_recipients = self._prepare_recipient_values(records) blacklist_ids = self._get_blacklist_record_ids(records, all_recipients) optout_ids = self._get_optout_record_ids(records, all_recipients) done_ids = self._get_done_record_ids(records, all_recipients) result = {} for record in records: recipients = all_recipients[record.id] sanitized = recipients['sanitized'] if sanitized and record.id in blacklist_ids: state = 'canceled' failure_type = 'sms_blacklist' elif sanitized and record.id in optout_ids: state = 'canceled' failure_type = 'sms_optout' elif sanitized and record.id in done_ids: state = 'canceled' failure_type = 'sms_duplicate' elif not sanitized: state = 'canceled' failure_type = 'sms_number_format' if recipients['number'] else 'sms_number_missing' else: state = 'outgoing' failure_type = '' result[record.id] = { 'body': all_bodies[record.id], 'partner_id': recipients['partner'].id, 'number': sanitized if sanitized else recipients['number'], 'state': state, 'failure_type': failure_type, } return result def _prepare_mass_sms(self, records, sms_record_values): sms_create_vals = [sms_record_values[record.id] for record in records] return self.env['sms.sms'].sudo().create(sms_create_vals) def _prepare_log_body_values(self, sms_records_values): result = {} for record_id, sms_values in sms_records_values.items(): result[record_id] = plaintext2html(html2plaintext(sms_values['body'])) return result def _prepare_mass_log_values(self, records, sms_records_values): return { 'bodies': self._prepare_log_body_values(sms_records_values), 'message_type': 'sms', } # ------------------------------------------------------------ # Tools # ------------------------------------------------------------ def _get_composer_values(self, composition_mode, res_model, res_id, body, template_id): result = {} if composition_mode == 'comment': if not body and template_id and res_id: template = self.env['sms.template'].browse(template_id) result['body'] = template._render_template(template.body, res_model, [res_id])[res_id] elif template_id: template = self.env['sms.template'].browse(template_id) result['body'] = template.body else: if not body and template_id: template = self.env['sms.template'].browse(template_id) result['body'] = template.body return result def _get_records(self): if not self.res_model: return None if self.use_active_domain: active_domain = literal_eval(self.active_domain or '[]') records = self.env[self.res_model].search(active_domain) elif self.res_ids: records = self.env[self.res_model].browse(literal_eval(self.res_ids)) elif self.res_id: records = self.env[self.res_model].browse(self.res_id) else: records = self.env[self.res_model] records = records.with_context(mail_notify_author=True) return records
50.390863
19,854
1,636
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 SMSCancel(models.TransientModel): _name = 'sms.cancel' _description = 'Dismiss notification for resend by model' model = fields.Char(string='Model', required=True) help_message = fields.Char(string='Help message', compute='_compute_help_message') @api.depends('model') def _compute_help_message(self): for wizard in self: wizard.help_message = _("Are you sure you want to discard %s SMS delivery failures? You won't be able to re-send these SMS later!") % (wizard._context.get('unread_counter')) def action_cancel(self): # TDE CHECK: delete pending SMS author_id = self.env.user.partner_id.id for wizard in self: self._cr.execute(""" SELECT notif.id, msg.id FROM mail_notification notif JOIN mail_message msg ON notif.mail_message_id = msg.id WHERE notif.notification_type = 'sms' IS TRUE AND notif.notification_status IN ('bounce', 'exception') AND msg.model = %s AND msg.author_id = %s """, (wizard.model, author_id)) res = self._cr.fetchall() notif_ids = [row[0] for row in res] message_ids = list(set([row[1] for row in res])) if notif_ids: self.env['mail.notification'].browse(notif_ids).sudo().write({'notification_status': 'canceled'}) if message_ids: self.env['mail.message'].browse(message_ids)._notify_message_notification_update() return {'type': 'ir.actions.act_window_close'}
43.052632
1,636
2,182
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 SMSTemplatePreview(models.TransientModel): _name = "sms.template.preview" _description = "SMS Template Preview" @api.model def _selection_target_model(self): return [(model.model, model.name) for model in self.env['ir.model'].sudo().search([])] @api.model def _selection_languages(self): return self.env['res.lang'].get_installed() @api.model def default_get(self, fields): result = super(SMSTemplatePreview, self).default_get(fields) sms_template_id = self.env.context.get('default_sms_template_id') if not sms_template_id or 'resource_ref' not in fields: return result sms_template = self.env['sms.template'].browse(sms_template_id) res = self.env[sms_template.model_id.model].search([], limit=1) if res: result['resource_ref'] = '%s,%s' % (sms_template.model_id.model, res.id) return result sms_template_id = fields.Many2one('sms.template', required=True, ondelete='cascade') lang = fields.Selection(_selection_languages, string='Template Preview Language') model_id = fields.Many2one('ir.model', related="sms_template_id.model_id") body = fields.Char('Body', compute='_compute_sms_template_fields') resource_ref = fields.Reference(string='Record reference', selection='_selection_target_model') no_record = fields.Boolean('No Record', compute='_compute_no_record') @api.depends('model_id') def _compute_no_record(self): for preview in self: preview.no_record = (self.env[preview.model_id.model].search_count([]) == 0) if preview.model_id else True @api.depends('lang', 'resource_ref') def _compute_sms_template_fields(self): for wizard in self: if wizard.sms_template_id and wizard.resource_ref: wizard.body = wizard.sms_template_id._render_field('body', [wizard.resource_ref.id], set_lang=wizard.lang)[wizard.resource_ref.id] else: wizard.body = wizard.sms_template_id.body
44.530612
2,182
5,554
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _, api, exceptions, fields, models class SMSRecipient(models.TransientModel): _name = 'sms.resend.recipient' _description = 'Resend Notification' _rec_name = 'sms_resend_id' sms_resend_id = fields.Many2one('sms.resend', required=True) notification_id = fields.Many2one('mail.notification', required=True, ondelete='cascade') resend = fields.Boolean(string="Resend", default=True) failure_type = fields.Selection( related='notification_id.failure_type', related_sudo=True, readonly=True) partner_id = fields.Many2one('res.partner', 'Partner', related='notification_id.res_partner_id', readonly=True) partner_name = fields.Char('Recipient', readonly='True') sms_number = fields.Char('Number') class SMSResend(models.TransientModel): _name = 'sms.resend' _description = 'SMS Resend' _rec_name = 'mail_message_id' @api.model def default_get(self, fields): result = super(SMSResend, self).default_get(fields) if 'recipient_ids' in fields and result.get('mail_message_id'): mail_message_id = self.env['mail.message'].browse(result['mail_message_id']) result['recipient_ids'] = [(0, 0, { 'notification_id': notif.id, 'resend': True, 'failure_type': notif.failure_type, 'partner_name': notif.res_partner_id.display_name or mail_message_id.record_name, 'sms_number': notif.sms_number, }) for notif in mail_message_id.notification_ids if notif.notification_type == 'sms' and notif.notification_status in ('exception', 'bounce')] return result mail_message_id = fields.Many2one('mail.message', 'Message', readonly=True, required=True) recipient_ids = fields.One2many('sms.resend.recipient', 'sms_resend_id', string='Recipients') has_cancel = fields.Boolean(compute='_compute_has_cancel') has_insufficient_credit = fields.Boolean(compute='_compute_has_insufficient_credit') has_unregistered_account = fields.Boolean(compute='_compute_has_unregistered_account') @api.depends("recipient_ids.failure_type") def _compute_has_unregistered_account(self): self.has_unregistered_account = self.recipient_ids.filtered(lambda p: p.failure_type == 'sms_acc') @api.depends("recipient_ids.failure_type") def _compute_has_insufficient_credit(self): self.has_insufficient_credit = self.recipient_ids.filtered(lambda p: p.failure_type == 'sms_credit') @api.depends("recipient_ids.resend") def _compute_has_cancel(self): self.has_cancel = self.recipient_ids.filtered(lambda p: not p.resend) def _check_access(self): if not self.mail_message_id or not self.mail_message_id.model or not self.mail_message_id.res_id: raise exceptions.UserError(_('You do not have access to the message and/or related document.')) record = self.env[self.mail_message_id.model].browse(self.mail_message_id.res_id) record.check_access_rights('read') record.check_access_rule('read') def action_resend(self): self._check_access() all_notifications = self.env['mail.notification'].sudo().search([ ('mail_message_id', '=', self.mail_message_id.id), ('notification_type', '=', 'sms'), ('notification_status', 'in', ('exception', 'bounce')) ]) sudo_self = self.sudo() to_cancel_ids = [r.notification_id.id for r in sudo_self.recipient_ids if not r.resend] to_resend_ids = [r.notification_id.id for r in sudo_self.recipient_ids if r.resend] if to_cancel_ids: all_notifications.filtered(lambda n: n.id in to_cancel_ids).write({'notification_status': 'canceled'}) if to_resend_ids: record = self.env[self.mail_message_id.model].browse(self.mail_message_id.res_id) sms_pid_to_number = dict((r.partner_id.id, r.sms_number) for r in self.recipient_ids if r.resend and r.partner_id) pids = list(sms_pid_to_number.keys()) numbers = [r.sms_number for r in self.recipient_ids if r.resend and not r.partner_id] rdata = [] for pid, active, pshare, notif, groups in self.env['mail.followers']._get_recipient_data(record, 'sms', False, pids=pids): if pid and notif == 'sms': rdata.append({'id': pid, 'share': pshare, 'active': active, 'notif': notif, 'groups': groups or [], 'type': 'customer' if pshare else 'user'}) if rdata or numbers: record._notify_record_by_sms( self.mail_message_id, rdata, check_existing=True, sms_numbers=numbers, sms_pid_to_number=sms_pid_to_number, put_in_queue=False ) self.mail_message_id._notify_message_notification_update() return {'type': 'ir.actions.act_window_close'} def action_cancel(self): self._check_access() sudo_self = self.sudo() sudo_self.mapped('recipient_ids.notification_id').write({'notification_status': 'canceled'}) self.mail_message_id._notify_message_notification_update() return {'type': 'ir.actions.act_window_close'} def action_buy_credits(self): url = self.env['iap.account'].get_credits_url(service_name='sms') return { 'type': 'ir.actions.act_url', 'url': url, }
48.295652
5,554
576
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class PhoneMixin(models.AbstractModel): _inherit = 'mail.thread.phone' def _sms_get_number_fields(self): """ Add fields coming from mail.thread.phone implementation. """ phone_fields = self._phone_get_number_fields() sms_fields = super(PhoneMixin, self)._sms_get_number_fields() for fname in (f for f in sms_fields if f not in phone_fields): phone_fields.append(fname) return phone_fields
36
576
953
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 Followers(models.Model): _inherit = ['mail.followers'] def _get_recipient_data(self, records, message_type, subtype_id, pids=None): if message_type == 'sms': if pids is None: sms_pids = records._sms_get_default_partners().ids else: sms_pids = pids res = super(Followers, self)._get_recipient_data(records, message_type, subtype_id, pids=pids) new_res = [] for pid, active, pshare, notif, groups in res: if pid and pid in sms_pids: notif = 'sms' new_res.append((pid, active, pshare, notif, groups)) return new_res else: return super(Followers, self)._get_recipient_data(records, message_type, subtype_id, pids=pids)
39.708333
953
2,875
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _, api, models from odoo.addons.iap.tools import iap_tools DEFAULT_ENDPOINT = 'https://iap-sms.odoo.com' class SmsApi(models.AbstractModel): _name = 'sms.api' _description = 'SMS API' @api.model def _contact_iap(self, local_endpoint, params): account = self.env['iap.account'].get('sms') params['account_token'] = account.account_token endpoint = self.env['ir.config_parameter'].sudo().get_param('sms.endpoint', DEFAULT_ENDPOINT) # TODO PRO, the default timeout is 15, do we have to increase it ? return iap_tools.iap_jsonrpc(endpoint + local_endpoint, params=params) @api.model def _send_sms(self, numbers, message): """ Send a single message to several numbers :param numbers: list of E164 formatted phone numbers :param message: content to send :raises ? TDE FIXME """ params = { 'numbers': numbers, 'message': message, } return self._contact_iap('/iap/message_send', params) @api.model def _send_sms_batch(self, messages): """ Send SMS using IAP in batch mode :param messages: list of SMS to send, structured as dict [{ 'res_id': integer: ID of sms.sms, 'number': string: E164 formatted phone number, 'content': string: content to send }] :return: return of /iap/sms/1/send controller which is a list of dict [{ 'res_id': integer: ID of sms.sms, 'state': string: 'insufficient_credit' or 'wrong_number_format' or 'success', 'credit': integer: number of credits spent to send this SMS, }] :raises: normally none """ params = { 'messages': messages } return self._contact_iap('/iap/sms/2/send', params) @api.model def _get_sms_api_error_messages(self): """ Returns a dict containing the error message to display for every known error 'state' resulting from the '_send_sms_batch' method. We prefer a dict instead of a message-per-error-state based method so we only call the 'get_credits_url' once, to avoid extra RPC calls. """ buy_credits_url = self.sudo().env['iap.account'].get_credits_url(service_name='sms') buy_credits = '<a href="%s" target="_blank">%s</a>' % ( buy_credits_url, _('Buy credits.') ) return { 'unregistered': _("You don't have an eligible IAP account."), 'insufficient_credit': ' '.join([_('You don\'t have enough credits on your IAP account.'), buy_credits]), 'wrong_number_format': _("The number you're trying to reach is not correctly formatted."), }
37.828947
2,875
1,753
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 IrModel(models.Model): _inherit = 'ir.model' is_mail_thread_sms = fields.Boolean( string="Mail Thread SMS", default=False, store=False, compute='_compute_is_mail_thread_sms', search='_search_is_mail_thread_sms', help="Whether this model supports messages and notifications through SMS", ) @api.depends('is_mail_thread') def _compute_is_mail_thread_sms(self): for model in self: if model.is_mail_thread: ModelObject = self.env[model.model] potential_fields = ModelObject._sms_get_number_fields() + ModelObject._sms_get_partner_fields() if any(fname in ModelObject._fields for fname in potential_fields): model.is_mail_thread_sms = True continue model.is_mail_thread_sms = False def _search_is_mail_thread_sms(self, operator, value): thread_models = self.search([('is_mail_thread', '=', True)]) valid_models = self.env['ir.model'] for model in thread_models: if model.model not in self.env: continue ModelObject = self.env[model.model] potential_fields = ModelObject._sms_get_number_fields() + ModelObject._sms_get_partner_fields() if any(fname in ModelObject._fields for fname in potential_fields): valid_models |= model search_sms = (operator == '=' and value) or (operator == '!=' and not value) if search_sms: return [('id', 'in', valid_models.ids)] return [('id', 'not in', valid_models.ids)]
42.756098
1,753
748
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 MailNotification(models.Model): _inherit = 'mail.notification' notification_type = fields.Selection(selection_add=[ ('sms', 'SMS') ], ondelete={'sms': 'cascade'}) sms_id = fields.Many2one('sms.sms', string='SMS', index=True, ondelete='set null') sms_number = fields.Char('SMS Number') failure_type = fields.Selection(selection_add=[ ('sms_number_missing', 'Missing Number'), ('sms_number_format', 'Wrong Number Format'), ('sms_credit', 'Insufficient Credit'), ('sms_server', 'Server Error'), ('sms_acc', 'Unregistered Account') ])
35.619048
748
9,328
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import threading from odoo import api, fields, models, tools, _ _logger = logging.getLogger(__name__) class SmsSms(models.Model): _name = 'sms.sms' _description = 'Outgoing SMS' _rec_name = 'number' _order = 'id DESC' IAP_TO_SMS_STATE = { 'success': 'sent', 'insufficient_credit': 'sms_credit', 'wrong_number_format': 'sms_number_format', 'server_error': 'sms_server', 'unregistered': 'sms_acc' } number = fields.Char('Number') body = fields.Text() partner_id = fields.Many2one('res.partner', 'Customer') mail_message_id = fields.Many2one('mail.message', index=True) state = fields.Selection([ ('outgoing', 'In Queue'), ('sent', 'Sent'), ('error', 'Error'), ('canceled', 'Canceled') ], 'SMS Status', readonly=True, copy=False, default='outgoing', required=True) failure_type = fields.Selection([ ('sms_number_missing', 'Missing Number'), ('sms_number_format', 'Wrong Number Format'), ('sms_credit', 'Insufficient Credit'), ('sms_server', 'Server Error'), ('sms_acc', 'Unregistered Account'), # mass mode specific codes ('sms_blacklist', 'Blacklisted'), ('sms_duplicate', 'Duplicate'), ('sms_optout', 'Opted Out'), ], copy=False) def action_set_canceled(self): self.state = 'canceled' notifications = self.env['mail.notification'].sudo().search([ ('sms_id', 'in', self.ids), # sent is sent -> cannot reset ('notification_status', 'not in', ['canceled', 'sent']), ]) if notifications: notifications.write({'notification_status': 'canceled'}) if not self._context.get('sms_skip_msg_notification', False): notifications.mail_message_id._notify_message_notification_update() def action_set_error(self, failure_type): self.state = 'error' self.failure_type = failure_type notifications = self.env['mail.notification'].sudo().search([ ('sms_id', 'in', self.ids), # sent can be set to error due to IAP feedback ('notification_status', '!=', 'exception'), ]) if notifications: notifications.write({'notification_status': 'exception', 'failure_type': failure_type}) if not self._context.get('sms_skip_msg_notification', False): notifications.mail_message_id._notify_message_notification_update() def action_set_outgoing(self): self.state = 'outgoing' notifications = self.env['mail.notification'].sudo().search([ ('sms_id', 'in', self.ids), # sent is sent -> cannot reset ('notification_status', 'not in', ['ready', 'sent']), ]) if notifications: notifications.write({'notification_status': 'ready', 'failure_type': False}) if not self._context.get('sms_skip_msg_notification', False): notifications.mail_message_id._notify_message_notification_update() def send(self, unlink_failed=False, unlink_sent=True, auto_commit=False, raise_exception=False): """ Main API method to send SMS. :param unlink_failed: unlink failed SMS after IAP feedback; :param unlink_sent: unlink sent SMS after IAP feedback; :param auto_commit: commit after each batch of SMS; :param raise_exception: raise if there is an issue contacting IAP; """ for batch_ids in self._split_batch(): self.browse(batch_ids)._send(unlink_failed=unlink_failed, unlink_sent=unlink_sent, raise_exception=raise_exception) # auto-commit if asked except in testing mode if auto_commit is True and not getattr(threading.current_thread(), 'testing', False): self._cr.commit() def resend_failed(self): sms_to_send = self.filtered(lambda sms: sms.state == 'error') notification_title = _('Warning') notification_type = 'danger' notification_message = '' if sms_to_send: sms_to_send.send() success_sms = len(sms_to_send) - len(sms_to_send.exists()) if success_sms > 0: notification_title = _('Success') notification_type = 'success' notification_message = _('%s out of the %s selected SMS Text Messages have successfully been resent.', success_sms, len(self)) else: notification_message = _('The SMS Text Messages could not be resent.') else: notification_message = _('There are no SMS Text Messages to resend.') return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'title': notification_title, 'message': notification_message, 'type': notification_type, } } @api.model def _process_queue(self, ids=None): """ Send immediately queued messages, committing after each message is sent. This is not transactional and should not be called during another transaction! :param list ids: optional list of emails ids to send. If passed no search is performed, and these ids are used instead. """ domain = [('state', '=', 'outgoing')] filtered_ids = self.search(domain, limit=10000).ids # TDE note: arbitrary limit we might have to update if ids: ids = list(set(filtered_ids) & set(ids)) else: ids = filtered_ids ids.sort() res = None try: # auto-commit except in testing mode auto_commit = not getattr(threading.current_thread(), 'testing', False) res = self.browse(ids).send(unlink_failed=False, unlink_sent=True, auto_commit=auto_commit, raise_exception=False) except Exception: _logger.exception("Failed processing SMS queue") return res def _split_batch(self): batch_size = int(self.env['ir.config_parameter'].sudo().get_param('sms.session.batch.size', 500)) for sms_batch in tools.split_every(batch_size, self.ids): yield sms_batch def _send(self, unlink_failed=False, unlink_sent=True, raise_exception=False): """ This method tries to send SMS after checking the number (presence and formatting). """ iap_data = [{ 'res_id': record.id, 'number': record.number, 'content': record.body, } for record in self] try: iap_results = self.env['sms.api']._send_sms_batch(iap_data) except Exception as e: _logger.info('Sent batch %s SMS: %s: failed with exception %s', len(self.ids), self.ids, e) if raise_exception: raise self._postprocess_iap_sent_sms( [{'res_id': sms.id, 'state': 'server_error'} for sms in self], unlink_failed=unlink_failed, unlink_sent=unlink_sent) else: _logger.info('Send batch %s SMS: %s: gave %s', len(self.ids), self.ids, iap_results) self._postprocess_iap_sent_sms(iap_results, unlink_failed=unlink_failed, unlink_sent=unlink_sent) def _postprocess_iap_sent_sms(self, iap_results, failure_reason=None, unlink_failed=False, unlink_sent=True): todelete_sms_ids = [] if unlink_failed: todelete_sms_ids += [item['res_id'] for item in iap_results if item['state'] != 'success'] if unlink_sent: todelete_sms_ids += [item['res_id'] for item in iap_results if item['state'] == 'success'] for state in self.IAP_TO_SMS_STATE.keys(): sms_ids = [item['res_id'] for item in iap_results if item['state'] == state] if sms_ids: if state != 'success' and not unlink_failed: self.env['sms.sms'].sudo().browse(sms_ids).write({ 'state': 'error', 'failure_type': self.IAP_TO_SMS_STATE[state], }) if state == 'success' and not unlink_sent: self.env['sms.sms'].sudo().browse(sms_ids).write({ 'state': 'sent', 'failure_type': False, }) notifications = self.env['mail.notification'].sudo().search([ ('notification_type', '=', 'sms'), ('sms_id', 'in', sms_ids), ('notification_status', 'not in', ('sent', 'canceled')), ]) if notifications: notifications.write({ 'notification_status': 'sent' if state == 'success' else 'exception', 'failure_type': self.IAP_TO_SMS_STATE[state] if state != 'success' else False, 'failure_reason': failure_reason if failure_reason else False, }) self.mail_message_id._notify_message_notification_update() if todelete_sms_ids: self.browse(todelete_sms_ids).sudo().unlink()
44
9,328
17,255
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, models, fields from odoo.addons.phone_validation.tools import phone_validation from odoo.tools import html2plaintext, plaintext2html _logger = logging.getLogger(__name__) class MailThread(models.AbstractModel): _inherit = 'mail.thread' message_has_sms_error = fields.Boolean( 'SMS Delivery error', compute='_compute_message_has_sms_error', search='_search_message_has_sms_error', help="If checked, some messages have a delivery error.") def _compute_message_has_sms_error(self): res = {} if self.ids: self._cr.execute(""" SELECT msg.res_id, COUNT(msg.res_id) FROM mail_message msg RIGHT JOIN mail_notification rel ON rel.mail_message_id = msg.id AND rel.notification_type = 'sms' AND rel.notification_status in ('exception') WHERE msg.author_id = %s AND msg.model = %s AND msg.res_id in %s AND msg.message_type != 'user_notification' GROUP BY msg.res_id""", (self.env.user.partner_id.id, self._name, tuple(self.ids),)) res.update(self._cr.fetchall()) for record in self: record.message_has_sms_error = bool(res.get(record._origin.id, 0)) @api.model def _search_message_has_sms_error(self, operator, operand): return ['&', ('message_ids.has_sms_error', operator, operand), ('message_ids.author_id', '=', self.env.user.partner_id.id)] def _sms_get_partner_fields(self): """ This method returns the fields to use to find the contact to link whensending an SMS. Having partner is not necessary, having only phone number fields is possible. However it gives more flexibility to notifications management when having partners. """ fields = [] if hasattr(self, 'partner_id'): fields.append('partner_id') if hasattr(self, 'partner_ids'): fields.append('partner_ids') return fields def _sms_get_default_partners(self): """ This method will likely need to be overridden by inherited models. :returns partners: recordset of res.partner """ partners = self.env['res.partner'] for fname in self._sms_get_partner_fields(): partners = partners.union(*self.mapped(fname)) # ensure ordering return partners def _sms_get_number_fields(self): """ This method returns the fields to use to find the number to use to send an SMS on a record. """ if 'mobile' in self: return ['mobile'] return [] def _sms_get_recipients_info(self, force_field=False, partner_fallback=True): """" Get SMS recipient information on current record set. This method checks for numbers and sanitation in order to centralize computation. Example of use cases * click on a field -> number is actually forced from field, find customer linked to record, force its number to field or fallback on customer fields; * contact -> find numbers from all possible phone fields on record, find customer, force its number to found field number or fallback on customer fields; :param force_field: either give a specific field to find phone number, either generic heuristic is used to find one based on ``_sms_get_number_fields``; :param partner_fallback: if no value found in the record, check its customer values based on ``_sms_get_default_partners``; :return dict: record.id: { 'partner': a res.partner recordset that is the customer (void or singleton) linked to the recipient. See ``_sms_get_default_partners``; 'sanitized': sanitized number to use (coming from record's field or partner's phone fields). Set to False is number impossible to parse and format; 'number': original number before sanitation; 'partner_store': whether the number comes from the customer phone fields. If False it means number comes from the record itself, even if linked to a customer; 'field_store': field in which the number has been found (generally mobile or phone, see ``_sms_get_number_fields``); } for each record in self """ result = dict.fromkeys(self.ids, False) tocheck_fields = [force_field] if force_field else self._sms_get_number_fields() for record in self: all_numbers = [record[fname] for fname in tocheck_fields if fname in record] all_partners = record._sms_get_default_partners() valid_number = False for fname in [f for f in tocheck_fields if f in record]: valid_number = phone_validation.phone_sanitize_numbers_w_record([record[fname]], record)[record[fname]]['sanitized'] if valid_number: break if valid_number: result[record.id] = { 'partner': all_partners[0] if all_partners else self.env['res.partner'], 'sanitized': valid_number, 'number': record[fname], 'partner_store': False, 'field_store': fname, } elif all_partners and partner_fallback: partner = self.env['res.partner'] for partner in all_partners: for fname in self.env['res.partner']._sms_get_number_fields(): valid_number = phone_validation.phone_sanitize_numbers_w_record([partner[fname]], record)[partner[fname]]['sanitized'] if valid_number: break if not valid_number: fname = 'mobile' if partner.mobile else ('phone' if partner.phone else 'mobile') result[record.id] = { 'partner': partner, 'sanitized': valid_number if valid_number else False, 'number': partner[fname], 'partner_store': True, 'field_store': fname, } else: # did not find any sanitized number -> take first set value as fallback; # if none, just assign False to the first available number field value, fname = next( ((value, fname) for value, fname in zip(all_numbers, tocheck_fields) if value), (False, tocheck_fields[0] if tocheck_fields else False) ) result[record.id] = { 'partner': self.env['res.partner'], 'sanitized': False, 'number': value, 'partner_store': False, 'field_store': fname } return result def _message_sms_schedule_mass(self, body='', template=False, active_domain=None, **composer_values): """ Shortcut method to schedule a mass sms sending on a recordset. :param template: an optional sms.template record; :param active_domain: bypass self.ids and apply composer on active_domain instead; """ composer_context = { 'default_res_model': self._name, 'default_composition_mode': 'mass', 'default_template_id': template.id if template else False, } if body and not template: composer_context['default_body'] = body if active_domain is not None: composer_context['default_use_active_domain'] = True composer_context['default_active_domain'] = repr(active_domain) else: composer_context['default_res_ids'] = self.ids create_vals = { 'mass_force_send': False, 'mass_keep_log': True, } if composer_values: create_vals.update(composer_values) composer = self.env['sms.composer'].with_context(**composer_context).create(create_vals) return composer._action_send_sms() def _message_sms_with_template(self, template=False, template_xmlid=False, template_fallback='', partner_ids=False, **kwargs): """ Shortcut method to perform a _message_sms with an sms.template. :param template: a valid sms.template record; :param template_xmlid: XML ID of an sms.template (if no template given); :param template_fallback: plaintext (inline_template-enabled) in case template and template xml id are falsy (for example due to deleted data); """ self.ensure_one() if not template and template_xmlid: template = self.env.ref(template_xmlid, raise_if_not_found=False) if template: body = template._render_field('body', self.ids, compute_lang=True)[self.id] else: body = self.env['sms.template']._render_template(template_fallback, self._name, self.ids)[self.id] return self._message_sms(body, partner_ids=partner_ids, **kwargs) def _message_sms(self, body, subtype_id=False, partner_ids=False, number_field=False, sms_numbers=None, sms_pid_to_number=None, **kwargs): """ Main method to post a message on a record using SMS-based notification method. :param body: content of SMS; :param subtype_id: mail.message.subtype used in mail.message associated to the sms notification process; :param partner_ids: if set is a record set of partners to notify; :param number_field: if set is a name of field to use on current record to compute a number to notify; :param sms_numbers: see ``_notify_record_by_sms``; :param sms_pid_to_number: see ``_notify_record_by_sms``; """ self.ensure_one() sms_pid_to_number = sms_pid_to_number if sms_pid_to_number is not None else {} if number_field or (partner_ids is False and sms_numbers is None): info = self._sms_get_recipients_info(force_field=number_field)[self.id] info_partner_ids = info['partner'].ids if info['partner'] else False info_number = info['sanitized'] if info['sanitized'] else info['number'] if info_partner_ids and info_number: sms_pid_to_number[info_partner_ids[0]] = info_number if info_partner_ids: partner_ids = info_partner_ids + (partner_ids or []) if not info_partner_ids: if info_number: sms_numbers = [info_number] + (sms_numbers or []) # will send a falsy notification allowing to fix it through SMS wizards elif not sms_numbers: sms_numbers = [False] if subtype_id is False: subtype_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note') return self.message_post( body=plaintext2html(html2plaintext(body)), partner_ids=partner_ids or [], # TDE FIXME: temp fix otherwise crash mail_thread.py message_type='sms', subtype_id=subtype_id, sms_numbers=sms_numbers, sms_pid_to_number=sms_pid_to_number, **kwargs ) def _notify_thread(self, message, msg_vals=False, notify_by_email=True, **kwargs): recipients_data = super(MailThread, self)._notify_thread(message, msg_vals=msg_vals, notify_by_email=notify_by_email, **kwargs) self._notify_record_by_sms(message, recipients_data, msg_vals=msg_vals, **kwargs) return recipients_data def _notify_record_by_sms(self, message, recipients_data, msg_vals=False, sms_numbers=None, sms_pid_to_number=None, check_existing=False, put_in_queue=False, **kwargs): """ Notification method: by SMS. :param message: mail.message record to notify; :param recipients_data: see ``_notify_thread``; :param msg_vals: see ``_notify_thread``; :param sms_numbers: additional numbers to notify in addition to partners and classic recipients; :param pid_to_number: force a number to notify for a given partner ID instead of taking its mobile / phone number; :param check_existing: check for existing notifications to update based on mailed recipient, otherwise create new notifications; :param put_in_queue: use cron to send queued SMS instead of sending them directly; """ sms_pid_to_number = sms_pid_to_number if sms_pid_to_number is not None else {} sms_numbers = sms_numbers if sms_numbers is not None else [] sms_create_vals = [] sms_all = self.env['sms.sms'].sudo() # pre-compute SMS data body = msg_vals['body'] if msg_vals and msg_vals.get('body') else message.body sms_base_vals = { 'body': html2plaintext(body), 'mail_message_id': message.id, 'state': 'outgoing', } # notify from computed recipients_data (followers, specific recipients) partners_data = [r for r in recipients_data if r['notif'] == 'sms'] partner_ids = [r['id'] for r in partners_data] if partner_ids: for partner in self.env['res.partner'].sudo().browse(partner_ids): number = sms_pid_to_number.get(partner.id) or partner.mobile or partner.phone sanitize_res = phone_validation.phone_sanitize_numbers_w_record([number], partner)[number] number = sanitize_res['sanitized'] or number sms_create_vals.append(dict( sms_base_vals, partner_id=partner.id, number=number )) # notify from additional numbers if sms_numbers: sanitized = phone_validation.phone_sanitize_numbers_w_record(sms_numbers, self) tocreate_numbers = [ value['sanitized'] or original for original, value in sanitized.items() ] sms_create_vals += [dict( sms_base_vals, partner_id=False, number=n, state='outgoing' if n else 'error', failure_type='' if n else 'sms_number_missing', ) for n in tocreate_numbers] # create sms and notification existing_pids, existing_numbers = [], [] if sms_create_vals: sms_all |= self.env['sms.sms'].sudo().create(sms_create_vals) if check_existing: existing = self.env['mail.notification'].sudo().search([ '|', ('res_partner_id', 'in', partner_ids), '&', ('res_partner_id', '=', False), ('sms_number', 'in', sms_numbers), ('notification_type', '=', 'sms'), ('mail_message_id', '=', message.id) ]) for n in existing: if n.res_partner_id.id in partner_ids and n.mail_message_id == message: existing_pids.append(n.res_partner_id.id) if not n.res_partner_id and n.sms_number in sms_numbers and n.mail_message_id == message: existing_numbers.append(n.sms_number) notif_create_values = [{ 'mail_message_id': message.id, 'res_partner_id': sms.partner_id.id, 'sms_number': sms.number, 'notification_type': 'sms', 'sms_id': sms.id, 'is_read': True, # discard Inbox notification 'notification_status': 'ready' if sms.state == 'outgoing' else 'exception', 'failure_type': '' if sms.state == 'outgoing' else sms.failure_type, } for sms in sms_all if (sms.partner_id and sms.partner_id.id not in existing_pids) or (not sms.partner_id and sms.number not in existing_numbers)] if notif_create_values: self.env['mail.notification'].sudo().create(notif_create_values) if existing_pids or existing_numbers: for sms in sms_all: notif = next((n for n in existing if (n.res_partner_id.id in existing_pids and n.res_partner_id.id == sms.partner_id.id) or (not n.res_partner_id and n.sms_number in existing_numbers and n.sms_number == sms.number)), False) if notif: notif.write({ 'notification_type': 'sms', 'notification_status': 'ready', 'sms_id': sms.id, 'sms_number': sms.number, }) if sms_all and not put_in_queue: sms_all.filtered(lambda sms: sms.state == 'outgoing').send(auto_commit=False, raise_exception=False) return True
49.3
17,255
3,323
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 SMSTemplate(models.Model): "Templates for sending SMS" _name = "sms.template" _inherit = ['mail.render.mixin'] _description = 'SMS Templates' _unrestricted_rendering = True @api.model def default_get(self, fields): res = super(SMSTemplate, self).default_get(fields) if not fields or 'model_id' in fields and not res.get('model_id') and res.get('model'): res['model_id'] = self.env['ir.model']._get(res['model']).id return res name = fields.Char('Name', translate=True) model_id = fields.Many2one( 'ir.model', string='Applies to', required=True, domain=['&', ('is_mail_thread_sms', '=', True), ('transient', '=', False)], help="The type of document this template can be used with", ondelete='cascade') model = fields.Char('Related Document Model', related='model_id.model', index=True, store=True, readonly=True) body = fields.Char('Body', translate=True, required=True) # Use to create contextual action (same as for email template) sidebar_action_id = fields.Many2one('ir.actions.act_window', 'Sidebar action', readonly=True, copy=False, help="Sidebar action to make this template available on records " "of the related document model") # Overrides of mail.render.mixin @api.depends('model') def _compute_render_model(self): for template in self: template.render_model = template.model # ------------------------------------------------------------ # CRUD # ------------------------------------------------------------ @api.returns('self', lambda value: value.id) def copy(self, default=None): default = dict(default or {}, name=_("%s (copy)", self.name)) return super(SMSTemplate, self).copy(default=default) def unlink(self): self.sudo().mapped('sidebar_action_id').unlink() return super(SMSTemplate, self).unlink() def action_create_sidebar_action(self): ActWindow = self.env['ir.actions.act_window'] view = self.env.ref('sms.sms_composer_view_form') for template in self: button_name = _('Send SMS (%s)', template.name) action = ActWindow.create({ 'name': button_name, 'type': 'ir.actions.act_window', 'res_model': 'sms.composer', # Add default_composition_mode to guess to determine if need to use mass or comment composer 'context': "{'default_template_id' : %d, 'sms_composition_mode': 'guess', 'default_res_ids': active_ids, 'default_res_id': active_id}" % (template.id), 'view_mode': 'form', 'view_id': view.id, 'target': 'new', 'binding_model_id': template.model_id.id, }) template.write({'sidebar_action_id': action.id}) return True def action_unlink_sidebar_action(self): for template in self: if template.sidebar_action_id: template.sidebar_action_id.unlink() return True
42.602564
3,323
2,468
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from operator import itemgetter from odoo import exceptions, fields, models from odoo.tools import groupby class MailMessage(models.Model): """ Override MailMessage class in order to add a new type: SMS messages. Those messages comes with their own notification method, using SMS gateway. """ _inherit = 'mail.message' message_type = fields.Selection(selection_add=[ ('sms', 'SMS') ], ondelete={'sms': lambda recs: recs.write({'message_type': 'email'})}) has_sms_error = fields.Boolean( 'Has SMS error', compute='_compute_has_sms_error', search='_search_has_sms_error', help='Has error') def _compute_has_sms_error(self): sms_error_from_notification = self.env['mail.notification'].sudo().search([ ('notification_type', '=', 'sms'), ('mail_message_id', 'in', self.ids), ('notification_status', '=', 'exception')]).mapped('mail_message_id') for message in self: message.has_sms_error = message in sms_error_from_notification def _search_has_sms_error(self, operator, operand): if operator == '=' and operand: return ['&', ('notification_ids.notification_status', '=', 'exception'), ('notification_ids.notification_type', '=', 'sms')] raise NotImplementedError() def message_format(self, format_reply=True): """ Override in order to retrieves data about SMS (recipient name and SMS status) TDE FIXME: clean the overall message_format thingy """ message_values = super(MailMessage, self).message_format(format_reply=format_reply) all_sms_notifications = self.env['mail.notification'].sudo().search([ ('mail_message_id', 'in', [r['id'] for r in message_values]), ('notification_type', '=', 'sms') ]) msgid_to_notif = defaultdict(lambda: self.env['mail.notification'].sudo()) for notif in all_sms_notifications: msgid_to_notif[notif.mail_message_id.id] += notif for message in message_values: customer_sms_data = [(notif.id, notif.res_partner_id.display_name or notif.sms_number, notif.notification_status) for notif in msgid_to_notif.get(message['id'], [])] message['sms_ids'] = customer_sms_data return message_values
44.872727
2,468
614
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class ResPartner(models.Model): _name = 'res.partner' _inherit = ['mail.thread.phone', 'res.partner'] def _sms_get_default_partners(self): """ Override of mail.thread method. SMS recipients on partners are the partners themselves. """ return self def _phone_get_number_fields(self): """ This method returns the fields to use to find the number to use to send an SMS on a record. """ return ['mobile', 'phone']
30.7
614
1,702
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 ServerActions(models.Model): """ Add SMS option in server actions. """ _name = 'ir.actions.server' _inherit = ['ir.actions.server'] state = fields.Selection(selection_add=[ ('sms', 'Send SMS Text Message'), ], ondelete={'sms': 'cascade'}) # SMS sms_template_id = fields.Many2one( 'sms.template', 'SMS Template', ondelete='set null', domain="[('model_id', '=', model_id)]", ) sms_mass_keep_log = fields.Boolean('Log as Note', default=True) @api.constrains('state', 'model_id') def _check_sms_capability(self): for action in self: if action.state == 'sms' and not action.model_id.is_mail_thread: raise ValidationError(_("Sending SMS can only be done on a mail.thread model")) def _run_action_sms_multi(self, eval_context=None): # TDE CLEANME: when going to new api with server action, remove action if not self.sms_template_id or self._is_recompute(): return False records = eval_context.get('records') or eval_context.get('record') if not records: return False composer = self.env['sms.composer'].with_context( default_res_model=records._name, default_res_ids=records.ids, default_composition_mode='mass', default_template_id=self.sms_template_id.id, default_mass_keep_log=self.sms_mass_keep_log, ).create({}) composer.action_send_sms() return False
37
1,702
754
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Project Mail Plugin', 'version': '1.0', 'category': 'Services/Project', 'sequence': 5, 'summary': 'Integrate your inbox with projects', 'description': "Turn emails received in your mailbox into tasks and log their content as internal notes.", 'data': [ 'views/project_task_views.xml' ], 'website': 'https://www.odoo.com/app/project', 'web.assets_backend': [ 'project_mail_plugin/static/src/to_translate/**/*', ], 'depends': [ 'project', 'mail_plugin', ], 'installable': True, 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
29
754
2,642
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo.http import request from odoo.addons.mail_plugin.controllers import mail_plugin _logger = logging.getLogger(__name__) class MailPluginController(mail_plugin.MailPluginController): def _get_contact_data(self, partner): """ Overrides the base module's get_contact_data method by Adding the "tasks" key within the initial contact information dict loaded when opening an email on Outlook. This is structured this way to enable the "project" feature on the Outlook side only if the Odoo version supports it. Return the tasks key only if the current user can create tasks. So, if he can not create tasks, the section won't be visible on the addin side (like if the project module was not installed on the database). """ contact_values = super(MailPluginController, self)._get_contact_data(partner) if not request.env['project.task'].check_access_rights('create', raise_exception=False): return contact_values if not partner: contact_values['tasks'] = [] else: partner_tasks = request.env['project.task'].search( [('partner_id', '=', partner.id)], offset=0, limit=5) accessible_projects = partner_tasks.project_id._filter_access_rules('read').mapped("id") tasks_values = [ { 'task_id': task.id, 'name': task.name, 'project_name': task.project_id.name, } for task in partner_tasks if task.project_id.id in accessible_projects] contact_values['tasks'] = tasks_values contact_values['can_create_project'] = request.env['project.project'].check_access_rights( 'create', raise_exception=False) return contact_values def _mail_content_logging_models_whitelist(self): models_whitelist = super(MailPluginController, self)._mail_content_logging_models_whitelist() if not request.env['project.task'].check_access_rights('create', raise_exception=False): return models_whitelist return models_whitelist + ['project.task'] def _translation_modules_whitelist(self): modules_whitelist = super(MailPluginController, self)._translation_modules_whitelist() if not request.env['project.task'].check_access_rights('create', raise_exception=False): return modules_whitelist return modules_whitelist + ['project_mail_plugin']
42.612903
2,642
1,937
py
PYTHON
15.0
from odoo import Command, http, _ from odoo.http import request class ProjectClient(http.Controller): @http.route('/mail_plugin/project/search', type='json', auth='outlook', cors="*") def projects_search(self, search_term, limit=5): """ Used in the plugin side when searching for projects. Fetches projects that have names containing the search_term. """ projects = request.env['project.project'].search([('name', 'ilike', search_term)], limit=limit) return [ { 'project_id': project.id, 'name': project.name, 'partner_name': project.partner_id.name, 'company_id': project.company_id.id } for project in projects.sudo() ] @http.route('/mail_plugin/task/create', type='json', auth='outlook', cors="*") def task_create(self, email_subject, email_body, project_id, partner_id): partner = request.env['res.partner'].browse(partner_id).exists() if not partner: return {'error': 'partner_not_found'} if not request.env['project.project'].browse(project_id).exists(): return {'error': 'project_not_found'} if not email_subject: email_subject = _('Task for %s', partner.name) record = request.env['project.task'].with_company(partner.company_id).create({ 'name': email_subject, 'partner_id': partner_id, 'description': email_body, 'project_id': project_id, 'user_ids': [Command.link(request.env.uid)], }) return {'task_id': record.id, 'name': record.name} @http.route('/mail_plugin/project/create', type='json', auth='outlook', cors="*") def project_create(self, name): record = request.env['project.project'].create({'name': name}) return {"project_id": record.id, "name": record.name}
38.74
1,937
1,120
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Saudi Arabia - Accounting', 'version': '2.0', 'author': 'DVIT.ME', 'category': 'Accounting/Localizations/Account Charts', 'description': """ Odoo Arabic localization for most arabic countries and Saudi Arabia. This initially includes chart of accounts of USA translated to Arabic. In future this module will include some payroll rules for ME . """, 'website': 'http://www.dvit.me', 'depends': ['account', 'l10n_multilang'], 'data': [ 'data/account_data.xml', 'data/account_chart_template_data.xml', 'data/account.account.template.csv', 'data/account_tax_group.xml', 'data/l10n_sa_chart_data.xml', 'data/account_tax_report_data.xml', 'data/account_tax_template_data.xml', 'data/account_fiscal_position_template_data.xml', 'data/account_chart_template_configure_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'post_init_hook': 'load_translations', 'license': 'LGPL-3', }
33.939394
1,120
2,993
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, api class AccountChartTemplate(models.Model): _inherit = 'account.chart.template' def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None): """ If Saudi Arabia chart, we add 3 new journals Tax Adjustments, IFRS 16 and Zakat""" if self == self.env.ref('l10n_sa.sa_chart_template_standard'): if not journals_dict: journals_dict = [] journals_dict.extend( [{'name': 'Tax Adjustments', 'company_id': company.id, 'code': 'TA', 'type': 'general', 'favorite': True, 'sequence': 1}, {'name': 'IFRS 16 Right of Use Asset', 'company_id': company.id, 'code': 'IFRS', 'type': 'general', 'favorite': True, 'sequence': 10}, {'name': 'Zakat', 'company_id': company.id, 'code': 'ZAKAT', 'type': 'general', 'favorite': True, 'sequence': 10}]) return super()._prepare_all_journals(acc_template_ref, company, journals_dict=journals_dict) def _load_template(self, company, code_digits=None, account_ref=None, taxes_ref=None): account_ref, taxes_ref = super(AccountChartTemplate, self)._load_template(company=company, code_digits=code_digits, account_ref=account_ref, taxes_ref=taxes_ref) if self == self.env.ref('l10n_sa.sa_chart_template_standard'): ifrs_journal_id = self.env['account.journal'].search([('company_id', '=', company.id), ('code', '=', 'IFRS')], limit=1) if ifrs_journal_id: ifrs_account_ids = [self.env.ref('l10n_sa.sa_account_100101').id, self.env.ref('l10n_sa.sa_account_100102').id, self.env.ref('l10n_sa.sa_account_400070').id] ifrs_accounts = self.env['account.account'].browse([account_ref.get(id) for id in ifrs_account_ids]) for account in ifrs_accounts: account.allowed_journal_ids = [(4, ifrs_journal_id.id, 0)] zakat_journal_id = self.env['account.journal'].search([('company_id', '=', company.id), ('code', '=', 'ZAKAT')], limit=1) if zakat_journal_id: zakat_account_ids = [self.env.ref('l10n_sa.sa_account_201019').id, self.env.ref('l10n_sa.sa_account_400072').id] zakat_accounts = self.env['account.account'].browse([account_ref.get(id) for id in zakat_account_ids]) for account in zakat_accounts: account.allowed_journal_ids = [(4, zakat_journal_id.id, 0)] return account_ref, taxes_ref
68.022727
2,993