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
444
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 ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' digest_emails = fields.Boolean(string="Digest Emails", config_parameter='digest.default_digest_emails') digest_id = fields.Many2one('digest.digest', string='Digest Email', config_parameter='digest.default_digest_id')
44.4
444
2,028
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from werkzeug.exceptions import Forbidden, NotFound from werkzeug.urls import url_encode from odoo import _ from odoo.http import Controller, request, route from odoo.tools import consteq class DigestController(Controller): @route('/digest/<int:digest_id>/unsubscribe', type='http', website=True, auth='public') def digest_unsubscribe(self, digest_id, token=None, user_id=None): digest_sudo = request.env['digest.digest'].sudo().browse(digest_id).exists() # new route parameters if digest_sudo and token and user_id: correct_token = digest_sudo._get_unsubscribe_token(int(user_id)) if not consteq(correct_token, token): raise NotFound() digest_sudo._action_unsubscribe_users(request.env['res.users'].sudo().browse(int(user_id))) # old route was given without any token or user_id but only for auth users elif digest_sudo and not token and not user_id and not request.env.user.share: digest_sudo.action_unsubcribe() else: raise NotFound() return request.render('digest.portal_digest_unsubscribed', { 'digest': digest_sudo, }) @route('/digest/<int:digest_id>/set_periodicity', type='http', website=True, auth='user') def digest_set_periodicity(self, digest_id, periodicity='weekly'): if not request.env.user.has_group('base.group_erp_manager'): raise Forbidden() if periodicity not in ('daily', 'weekly', 'monthly', 'quarterly'): raise ValueError(_('Invalid periodicity set on digest')) digest = request.env['digest.digest'].browse(digest_id).exists() digest.action_set_periodicity(periodicity) url_params = { 'model': digest._name, 'id': digest.id, 'active_id': digest.id, } return request.redirect('/web?#%s' % url_encode(url_params))
41.387755
2,028
667
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Google reCAPTCHA integration', 'category': 'Hidden', 'version': '1.0', 'description': """ This module implements reCaptchaV3 so that you can prevent bot spam on your public modules. """, 'depends': ['base_setup'], 'data': [ 'views/res_config_settings_view.xml', ], 'auto_install': False, 'assets': { 'web.assets_frontend': [ 'google_recaptcha/static/src/scss/recaptcha.scss', 'google_recaptcha/static/src/js/recaptcha.js', ], }, 'license': 'LGPL-3', }
29
667
5,405
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import requests from odoo import api, models, _ from odoo.http import request from odoo.exceptions import UserError, ValidationError logger = logging.getLogger(__name__) class Http(models.AbstractModel): _inherit = 'ir.http' def session_info(self): session_info = super().session_info() return self._add_public_key_to_session_info(session_info) @api.model def get_frontend_session_info(self): frontend_session_info = super().get_frontend_session_info() return self._add_public_key_to_session_info(frontend_session_info) @api.model def _add_public_key_to_session_info(self, session_info): """Add the ReCaptcha public key to the given session_info object""" public_key = self.env['ir.config_parameter'].sudo().get_param('recaptcha_public_key') if public_key: session_info['recaptcha_public_key'] = public_key return session_info @api.model def _verify_request_recaptcha_token(self, action): """ Verify the recaptcha token for the current request. If no recaptcha private key is set the recaptcha verification is considered inactive and this method will return True. """ ip_addr = request.httprequest.remote_addr token = request.params.pop('recaptcha_token_response', False) recaptcha_result = request.env['ir.http']._verify_recaptcha_token(ip_addr, token, action) if recaptcha_result in ['is_human', 'no_secret']: return True if recaptcha_result == 'wrong_secret': raise ValidationError(_("The reCaptcha private key is invalid.")) elif recaptcha_result == 'wrong_token': raise ValidationError(_("The reCaptcha token is invalid.")) elif recaptcha_result == 'timeout': raise UserError(_("Your request has timed out, please retry.")) elif recaptcha_result == 'bad_request': raise UserError(_("The request is invalid or malformed.")) else: return False @api.model def _verify_recaptcha_token(self, ip_addr, token, action=False): """ Verify a recaptchaV3 token and returns the result as a string. RecaptchaV3 verify DOC: https://developers.google.com/recaptcha/docs/verify :return: The result of the call to the google API: is_human: The token is valid and the user trustworthy. is_bot: The user is not trustworthy and most likely a bot. no_secret: No reCaptcha secret set in settings. wrong_action: the action performed to obtain the token does not match the one we are verifying. wrong_token: The token provided is invalid or empty. wrong_secret: The private key provided in settings is invalid. timeout: The request has timout or the token provided is too old. bad_request: The request is invalid or malformed. :rtype: str """ private_key = request.env['ir.config_parameter'].sudo().get_param('recaptcha_private_key') if not private_key: return 'no_secret' min_score = request.env['ir.config_parameter'].sudo().get_param('recaptcha_min_score') try: r = requests.post('https://www.recaptcha.net/recaptcha/api/siteverify', { 'secret': private_key, 'response': token, 'remoteip': ip_addr, }, timeout=2) # it takes ~50ms to retrieve the response result = r.json() res_success = result['success'] res_action = res_success and action and result['action'] except requests.exceptions.Timeout: logger.error("Trial captcha verification timeout for ip address %s", ip_addr) return 'timeout' except Exception: logger.error("Trial captcha verification bad request response") return 'bad_request' if res_success: score = result.get('score', False) if score < float(min_score): logger.warning("Trial captcha verification for ip address %s failed with score %f.", ip_addr, score) return 'is_bot' if res_action and res_action != action: logger.warning("Trial captcha verification for ip address %s failed with action %f, expected: %s.", ip_addr, score, action) return 'wrong_action' logger.info("Trial captcha verification for ip address %s succeeded with score %f.", ip_addr, score) return 'is_human' errors = result.get('error-codes', []) logger.warning("Trial captcha verification for ip address %s failed error codes %r. token was: [%s]", ip_addr, errors, token) for error in errors: if error in ['missing-input-secret', 'invalid-input-secret']: return 'wrong_secret' if error in ['missing-input-response', 'invalid-input-response']: return 'wrong_token' if error == 'timeout-or-duplicate': return 'timeout' if error == 'bad-request': return 'bad_request' return 'is_bot'
47.831858
5,405
752
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 ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' recaptcha_public_key = fields.Char("Site Key", config_parameter='recaptcha_public_key', groups='base.group_system') recaptcha_private_key = fields.Char("Secret Key", config_parameter='recaptcha_private_key', groups='base.group_system') recaptcha_min_score = fields.Float( "Minimum score", config_parameter='recaptcha_min_score', groups='base.group_system', default="0.5", help="Should be between 0.0 and 1.0.\n1.0 is very likely a good interaction, 0.0 is very likely a bot" )
44.235294
752
1,950
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'VAT Number Validation', 'version': '1.0', 'category': 'Accounting/Accounting', 'description': """ VAT validation for Partner's VAT numbers. ========================================= After installing this module, values entered in the VAT field of Partners will be validated for all supported countries. The country is inferred from the 2-letter country code that prefixes the VAT number, e.g. ``BE0477472701`` will be validated using the Belgian rules. There are two different levels of VAT number validation: -------------------------------------------------------- * By default, a simple off-line check is performed using the known validation rules for the country, usually a simple check digit. This is quick and always available, but allows numbers that are perhaps not truly allocated, or not valid anymore. * When the "VAT VIES Check" option is enabled (in the configuration of the user's Company), VAT numbers will be instead submitted to the online EU VIES database, which will truly verify that the number is valid and currently allocated to a EU company. This is a little bit slower than the simple off-line check, requires an Internet connection, and may not be available all the time. If the service is not available or does not support the requested country (e.g. for non-EU countries), a simple check will be performed instead. Supported countries currently include EU countries, and a few non-EU countries such as Chile, Colombia, Mexico, Norway or Russia. For unsupported countries, only the country code will be validated. """, 'depends': ['account'], 'data': [ 'views/res_company_views.xml', 'views/res_partner_views.xml', 'views/res_config_settings_views.xml', ], 'license': 'LGPL-3', }
44.318182
1,950
4,208
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase, tagged from odoo.exceptions import ValidationError from unittest.mock import patch import stdnum.eu.vat class TestStructure(TransactionCase): @classmethod def setUpClass(cls): def check_vies(vat_number): return {'valid': vat_number == 'BE0477472701'} super().setUpClass() cls.env.user.company_id.vat_check_vies = False cls._vies_check_func = check_vies def test_peru_ruc_format(self): """Only values that has the length of 11 will be checked as RUC, that's what we are proving. The second part will check for a valid ruc and there will be no problem at all. """ partner = self.env['res.partner'].create({'name': "Dummy partner", 'country_id': self.env.ref('base.pe').id}) with self.assertRaises(ValidationError): partner.vat = '11111111111' partner.vat = '20507822470' def test_vat_country_difference(self): """Test the validation when country code is different from vat code""" partner = self.env['res.partner'].create({ 'name': "Test", 'country_id': self.env.ref('base.mx').id, 'vat': 'RORO790707I47', }) self.assertEqual(partner.vat, 'RORO790707I47', "Partner VAT should not be altered") def test_parent_validation(self): """Test the validation with company and contact""" # set an invalid vat number self.env.user.company_id.vat_check_vies = False company = self.env["res.partner"].create({ "name": "World Company", "country_id": self.env.ref("base.be").id, "vat": "ATU12345675", "company_type": "company", }) # reactivate it and correct the vat number with patch('odoo.addons.base_vat.models.res_partner.check_vies', type(self)._vies_check_func): self.env.user.company_id.vat_check_vies = True with self.assertRaises(ValidationError), self.env.cr.savepoint(): company.vat = "BE0987654321" # VIES refused, don't fallback on other check company.vat = "BE0477472701" def test_vat_syntactic_validation(self): """ Tests VAT validation (both successes and failures), with the different country detection cases possible. """ test_partner = self.env['res.partner'].create({'name': "John Dex"}) # VAT starting with country code: use the starting country code test_partner.write({'vat': 'BE0477472701', 'country_id': self.env.ref('base.fr').id}) test_partner.write({'vat': 'BE0477472701', 'country_id': None}) with self.assertRaises(ValidationError): test_partner.write({'vat': 'BE42', 'country_id': self.env.ref('base.fr').id}) with self.assertRaises(ValidationError): test_partner.write({'vat': 'BE42', 'country_id': None}) # No country code in VAT: use the partner's country test_partner.write({'vat': '0477472701', 'country_id': self.env.ref('base.be').id}) with self.assertRaises(ValidationError): test_partner.write({'vat': '42', 'country_id': self.env.ref('base.be').id}) # If no country can be guessed: VAT number should always be considered valid # (for technical reasons due to ORM and res.company making related fields towards res.partner for country_id and vat) test_partner.write({'vat': '0477472701', 'country_id': None}) def test_vat_eu(self): """ Foreign companies that trade with non-enterprises in the EU may have a VATIN starting with "EU" instead of a country code. """ test_partner = self.env['res.partner'].create({'name': "Turlututu", 'country_id': self.env.ref('base.fr').id}) test_partner.write({'vat': "EU528003646", 'country_id': None}) @tagged('-standard', 'external') class TestStructureVIES(TestStructure): @classmethod def setUpClass(cls): super().setUpClass() cls.env.user.company_id.vat_check_vies = True cls._vies_check_func = stdnum.eu.vat.check_vies
43.381443
4,208
261
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 ResCompany(models.Model): _inherit = 'res.company' vat_check_vies = fields.Boolean(string='Verify VAT Numbers')
26.1
261
271
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' vat_check_vies = fields.Boolean(related='company_id.vat_check_vies', readonly=False, string='Verify VAT Numbers')
27.1
271
1,025
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models, _ from odoo.exceptions import ValidationError class AccountFiscalPosition(models.Model): _inherit = 'account.fiscal.position' @api.constrains('country_id', 'foreign_vat') def _validate_foreign_vat(self): for record in self: if not record.foreign_vat: continue checked_country_code = self.env['res.partner']._run_vat_test(record.foreign_vat, record.country_id) if checked_country_code and checked_country_code != record.country_id.code.lower(): raise ValidationError(_("The country detected for this foreign VAT number does not match the one set on this fiscal position.")) if not checked_country_code: fp_label = _("fiscal position [%s]", record.name) error_message = self.env['res.partner']._build_vat_error_message(record.country_id.code.lower(), record.foreign_vat, fp_label) raise ValidationError(error_message)
42.708333
1,025
28,183
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import string import re import stdnum from stdnum.eu.vat import check_vies from stdnum.exceptions import InvalidComponent from stdnum.util import clean import logging from odoo import api, models, fields, tools, _ from odoo.tools.misc import ustr from odoo.exceptions import ValidationError _logger = logging.getLogger(__name__) _eu_country_vat = { 'GR': 'EL' } _eu_country_vat_inverse = {v: k for k, v in _eu_country_vat.items()} _ref_vat = { 'al': 'ALJ91402501L', 'ar': 'AR200-5536168-2 or 20055361682', 'at': 'ATU12345675', 'au': '83 914 571 673', 'be': 'BE0477472701', 'bg': 'BG1234567892', 'ch': 'CHE-123.456.788 TVA or CHE-123.456.788 MWST or CHE-123.456.788 IVA', # Swiss by Yannick Vaucher @ Camptocamp 'cl': 'CL76086428-5', 'co': 'CO213123432-1 or CO213.123.432-1', 'cy': 'CY10259033P', 'cz': 'CZ12345679', 'de': 'DE123456788', 'dk': 'DK12345674', 'do': 'DO1-01-85004-3 or 101850043', 'ec': 'EC1792060346-001', 'ee': 'EE123456780', 'el': 'EL12345670', 'es': 'ESA12345674', 'fi': 'FI12345671', 'fr': 'FR23334175221', 'gb': 'GB123456782 or XI123456782', 'gr': 'GR12345670', 'hu': 'HU12345676', 'hr': 'HR01234567896', # Croatia, contributed by Milan Tribuson 'ie': 'IE1234567FA', 'in': "12AAAAA1234AAZA", 'is': 'IS062199', 'it': 'IT12345670017', 'lt': 'LT123456715', 'lu': 'LU12345613', 'lv': 'LV41234567891', 'mc': 'FR53000004605', 'mt': 'MT12345634', 'mx': 'MXGODE561231GR8 or GODE561231GR8', 'nl': 'NL123456782B90', 'no': 'NO123456785', 'pe': '10XXXXXXXXY or 20XXXXXXXXY or 15XXXXXXXXY or 16XXXXXXXXY or 17XXXXXXXXY', 'ph': '123-456-789-123', 'pl': 'PL1234567883', 'pt': 'PT123456789', 'ro': 'RO1234567897', 'rs': 'RS101134702', 'ru': 'RU123456789047', 'se': 'SE123456789701', 'si': 'SI12345679', 'sk': 'SK2022749619', 'sm': 'SM24165', 'tr': 'TR1234567890 (VERGINO) or TR17291716060 (TCKIMLIKNO)', # Levent Karakas @ Eska Yazilim A.S. 've': 'V-12345678-1, V123456781, V-12.345.678-1', 'xi': 'XI123456782', 'sa': '310175397400003 [Fifteen digits, first and last digits should be "3"]' } _region_specific_vat_codes = { 'xi', } class ResPartner(models.Model): _inherit = 'res.partner' vat = fields.Char(string="VAT/Tax ID") def _split_vat(self, vat): vat_country, vat_number = vat[:2].lower(), vat[2:].replace(' ', '') return vat_country, vat_number @api.model def simple_vat_check(self, country_code, vat_number): ''' Check the VAT number depending of the country. http://sima-pc.com/nif.php ''' if not ustr(country_code).encode('utf-8').isalpha(): return False check_func_name = 'check_vat_' + country_code check_func = getattr(self, check_func_name, None) or getattr(stdnum.util.get_cc_module(country_code, 'vat'), 'is_valid', None) if not check_func: # No VAT validation available, default to check that the country code exists if country_code.upper() == 'EU': # Foreign companies that trade with non-enterprises in the EU # may have a VATIN starting with "EU" instead of a country code. return True country_code = _eu_country_vat_inverse.get(country_code, country_code) return bool(self.env['res.country'].search([('code', '=ilike', country_code)])) return check_func(vat_number) @api.model @tools.ormcache('vat') def _check_vies(self, vat): # Store the VIES result in the cache. In case an exception is raised during the request # (e.g. service unavailable), the fallback on simple_vat_check is not kept in cache. return check_vies(vat) @api.model def vies_vat_check(self, country_code, vat_number): try: # Validate against VAT Information Exchange System (VIES) # see also http://ec.europa.eu/taxation_customs/vies/ vies_result = self._check_vies(country_code.upper() + vat_number) return vies_result['valid'] except InvalidComponent: return False except Exception: # see http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl # Fault code may contain INVALID_INPUT, SERVICE_UNAVAILABLE, MS_UNAVAILABLE, # TIMEOUT or SERVER_BUSY. There is no way we can validate the input # with VIES if any of these arise, including the first one (it means invalid # country code or empty VAT number), so we fall back to the simple check. _logger.exception("Failed VIES VAT check.") return self.simple_vat_check(country_code, vat_number) @api.model def fix_eu_vat_number(self, country_id, vat): europe = self.env.ref('base.europe') country = self.env["res.country"].browse(country_id) if not europe: europe = self.env["res.country.group"].search([('name', '=', 'Europe')], limit=1) if europe and country and country.id in europe.country_ids.ids: vat = re.sub('[^A-Za-z0-9]', '', vat).upper() country_code = _eu_country_vat.get(country.code, country.code).upper() if vat[:2] != country_code: vat = country_code + vat return vat @api.constrains('vat', 'country_id') def check_vat(self): # The context key 'no_vat_validation' allows you to store/set a VAT number without doing validations. # This is for API pushes from external platforms where you have no control over VAT numbers. if self.env.context.get('no_vat_validation'): return for partner in self: country = partner.commercial_partner_id.country_id if partner.vat and self._run_vat_test(partner.vat, country, partner.is_company) is False: partner_label = _("partner [%s]", partner.name) msg = partner._build_vat_error_message(country and country.code.lower() or None, partner.vat, partner_label) raise ValidationError(msg) @api.model def _run_vat_test(self, vat_number, default_country, partner_is_company=True): """ Checks a VAT number, either syntactically or using VIES, depending on the active company's configuration. A first check is made by using the first two characters of the VAT as the country code. It it fails, a second one is made using default_country instead. :param vat_number: a string with the VAT number to check. :param default_country: a res.country object :param partner_is_company: True if the partner is a company, else False :return: The country code (in lower case) of the country the VAT number was validated for, if it was validated. False if it could not be validated against the provided or guessed country. None if no country was available for the check, and no conclusion could be made with certainty. """ # Get company if self.env.context.get('company_id'): company = self.env['res.company'].browse(self.env.context['company_id']) else: company = self.env.company # Get check function: either simple syntactic check or call to VIES service eu_countries = self.env.ref('base.europe').country_ids if company.vat_check_vies and default_country in eu_countries and partner_is_company: check_func = self.vies_vat_check else: check_func = self.simple_vat_check check_result = None # First check with country code as prefix of the TIN vat_country_code, vat_number_split = self._split_vat(vat_number) vat_has_legit_country_code = self.env['res.country'].search([('code', '=', vat_country_code.upper())]) if not vat_has_legit_country_code: vat_has_legit_country_code = vat_country_code.lower() in _region_specific_vat_codes if vat_has_legit_country_code: check_result = check_func(vat_country_code, vat_number_split) if check_result: return vat_country_code # If it fails, check with default_country (if it exists) if default_country: check_result = check_func(default_country.code.lower(), vat_number) if check_result: return default_country.code.lower() # We allow any number if it doesn't start with a country code and the partner has no country. # This is necessary to support an ORM limitation: setting vat and country_id together on a company # triggers two distinct write on res.partner, one for each field, both triggering this constraint. # If vat is set before country_id, the constraint must not break. return check_result @api.model def _build_vat_error_message(self, country_code, wrong_vat, record_label): if self.env.context.get('company_id'): company = self.env['res.company'].browse(self.env.context['company_id']) else: company = self.env.company vat_label = _("VAT") if country_code and company.country_id and country_code == company.country_id.code.lower(): vat_label = company.country_id.vat_label expected_format = _ref_vat.get(country_code, "'CC##' (CC=Country Code, ##=VAT Number)") if company.vat_check_vies: return '\n' + _( "The %(vat_label)s number [%(wrong_vat)s] for %(record_label)s either failed the VIES VAT validation check or did not respect the expected format %(expected_format)s.", vat_label=vat_label, wrong_vat=wrong_vat, record_label=record_label, expected_format=expected_format, ) return '\n' + _( 'The %(vat_label)s number [%(wrong_vat)s] for %(record_label)s does not seem to be valid. \nNote: the expected format is %(expected_format)s', vat_label=vat_label, wrong_vat=wrong_vat, record_label=record_label, expected_format=expected_format, ) __check_vat_al_re = re.compile(r'^[JKLM][0-9]{8}[A-Z]$') def check_vat_al(self, vat): """Check Albania VAT number""" number = stdnum.util.get_cc_module('al', 'vat').compact(vat) if len(number) == 10 and self.__check_vat_al_re.match(number): return True return False __check_vat_ch_re = re.compile(r'E([0-9]{9}|-[0-9]{3}\.[0-9]{3}\.[0-9]{3})(MWST|TVA|IVA)$') def check_vat_ch(self, vat): ''' Check Switzerland VAT number. ''' # A new VAT number format in Switzerland has been introduced between 2011 and 2013 # https://www.estv.admin.ch/estv/fr/home/mehrwertsteuer/fachinformationen/steuerpflicht/unternehmens-identifikationsnummer--uid-.html # The old format "TVA 123456" is not valid since 2014 # Accepted format are: (spaces are ignored) # CHE#########MWST # CHE#########TVA # CHE#########IVA # CHE-###.###.### MWST # CHE-###.###.### TVA # CHE-###.###.### IVA # # /!\ The english abbreviation VAT is not valid /!\ match = self.__check_vat_ch_re.match(vat) if match: # For new TVA numbers, the last digit is a MOD11 checksum digit build with weighting pattern: 5,4,3,2,7,6,5,4 num = [s for s in match.group(1) if s.isdigit()] # get the digits only factor = (5, 4, 3, 2, 7, 6, 5, 4) csum = sum([int(num[i]) * factor[i] for i in range(8)]) check = (11 - (csum % 11)) % 11 return check == int(num[8]) return False def is_valid_ruc_ec(self, vat): ci = stdnum.util.get_cc_module("ec", "ci") ruc = stdnum.util.get_cc_module("ec", "ruc") if len(vat) == 10: return ci.is_valid(vat) elif len(vat) == 13: if vat[2] == "6" and ci.is_valid(vat[:10]): return True else: return ruc.is_valid(vat) return False def check_vat_ec(self, vat): vat = clean(vat, ' -.').upper().strip() return self.is_valid_ruc_ec(vat) def _ie_check_char(self, vat): vat = vat.zfill(8) extra = 0 if vat[7] not in ' W': if vat[7].isalpha(): extra = 9 * (ord(vat[7]) - 64) else: # invalid return -1 checksum = extra + sum((8-i) * int(x) for i, x in enumerate(vat[:7])) return 'WABCDEFGHIJKLMNOPQRSTUV'[checksum % 23] def check_vat_ie(self, vat): """ Temporary Ireland VAT validation to support the new format introduced in January 2013 in Ireland, until upstream is fixed. TODO: remove when fixed upstream""" if len(vat) not in (8, 9) or not vat[2:7].isdigit(): return False if len(vat) == 8: # Normalize pre-2013 numbers: final space or 'W' not significant vat += ' ' if vat[:7].isdigit(): return vat[7] == self._ie_check_char(vat[:7] + vat[8]) elif vat[1] in (string.ascii_uppercase + '+*'): # Deprecated format # See http://www.revenue.ie/en/online/third-party-reporting/reporting-payment-details/faqs.html#section3 return vat[7] == self._ie_check_char(vat[2:7] + vat[0] + vat[8]) return False # Mexican VAT verification, contributed by Vauxoo # and Panos Christeas <[email protected]> __check_vat_mx_re = re.compile(br"(?P<primeras>[A-Za-z\xd1\xf1&]{3,4})" \ br"[ \-_]?" \ br"(?P<ano>[0-9]{2})(?P<mes>[01][0-9])(?P<dia>[0-3][0-9])" \ br"[ \-_]?" \ br"(?P<code>[A-Za-z0-9&\xd1\xf1]{3})$") def check_vat_mx(self, vat): ''' Mexican VAT verification Verificar RFC México ''' # we convert to 8-bit encoding, to help the regex parse only bytes vat = ustr(vat).encode('iso8859-1') m = self.__check_vat_mx_re.match(vat) if not m: #No valid format return False try: ano = int(m.group('ano')) if ano > 30: ano = 1900 + ano else: ano = 2000 + ano datetime.date(ano, int(m.group('mes')), int(m.group('dia'))) except ValueError: return False # Valid format and valid date return True # Netherlands VAT verification __check_vat_nl_re = re.compile("(?:NL)?[0-9A-Z+*]{10}[0-9]{2}") def check_vat_nl(self, vat): """ Temporary Netherlands VAT validation to support the new format introduced in January 2020, until upstream is fixed. Algorithm detail: http://kleineondernemer.nl/index.php/nieuw-btw-identificatienummer-vanaf-1-januari-2020-voor-eenmanszaken TODO: remove when fixed upstream """ try: from stdnum.util import clean from stdnum.nl.bsn import checksum except ImportError: return True vat = clean(vat, ' -.').upper().strip() # Remove the prefix if vat.startswith("NL"): vat = vat[2:] if not len(vat) == 12: return False # Check the format match = self.__check_vat_nl_re.match(vat) if not match: return False # Match letters to integers char_to_int = {k: str(ord(k) - 55) for k in string.ascii_uppercase} char_to_int['+'] = '36' char_to_int['*'] = '37' # 2 possible checks: # - For natural persons # - For non-natural persons and combinations of natural persons (company) # Natural person => mod97 full checksum check_val_natural = '2321' for x in vat: check_val_natural += x if x.isdigit() else char_to_int[x] if int(check_val_natural) % 97 == 1: return True # Company => weighted(9->2) mod11 on bsn vat = vat[:-3] if vat.isdigit() and checksum(vat) == 0: return True return False # Norway VAT validation, contributed by Rolv Råen (adEgo) <[email protected]> # Support for MVA suffix contributed by Bringsvor Consulting AS ([email protected]) def check_vat_no(self, vat): """ Check Norway VAT number.See http://www.brreg.no/english/coordination/number.html """ if len(vat) == 12 and vat.upper().endswith('MVA'): vat = vat[:-3] # Strictly speaking we should enforce the suffix MVA but... if len(vat) != 9: return False try: int(vat) except ValueError: return False sum = (3 * int(vat[0])) + (2 * int(vat[1])) + \ (7 * int(vat[2])) + (6 * int(vat[3])) + \ (5 * int(vat[4])) + (4 * int(vat[5])) + \ (3 * int(vat[6])) + (2 * int(vat[7])) check = 11 - (sum % 11) if check == 11: check = 0 if check == 10: # 10 is not a valid check digit for an organization number return False return check == int(vat[8]) # Peruvian VAT validation, contributed by Vauxoo def check_vat_pe(self, vat): if len(vat) != 11 or not vat.isdigit(): return False dig_check = 11 - (sum([int('5432765432'[f]) * int(vat[f]) for f in range(0, 10)]) % 11) if dig_check == 10: dig_check = 0 elif dig_check == 11: dig_check = 1 return int(vat[10]) == dig_check # Philippines TIN (+ branch code) validation __check_vat_ph_re = re.compile(r"\d{3}-\d{3}-\d{3}(-\d{3,5})?$") def check_vat_ph(self, vat): return len(vat) >= 11 and len(vat) <= 17 and self.__check_vat_ph_re.match(vat) def check_vat_ru(self, vat): ''' Check Russia VAT number. Method copied from vatnumber 1.2 lib https://code.google.com/archive/p/vatnumber/ ''' if len(vat) != 10 and len(vat) != 12: return False try: int(vat) except ValueError: return False if len(vat) == 10: check_sum = 2 * int(vat[0]) + 4 * int(vat[1]) + 10 * int(vat[2]) + \ 3 * int(vat[3]) + 5 * int(vat[4]) + 9 * int(vat[5]) + \ 4 * int(vat[6]) + 6 * int(vat[7]) + 8 * int(vat[8]) check = check_sum % 11 if check % 10 != int(vat[9]): return False else: check_sum1 = 7 * int(vat[0]) + 2 * int(vat[1]) + 4 * int(vat[2]) + \ 10 * int(vat[3]) + 3 * int(vat[4]) + 5 * int(vat[5]) + \ 9 * int(vat[6]) + 4 * int(vat[7]) + 6 * int(vat[8]) + \ 8 * int(vat[9]) check = check_sum1 % 11 if check != int(vat[10]): return False check_sum2 = 3 * int(vat[0]) + 7 * int(vat[1]) + 2 * int(vat[2]) + \ 4 * int(vat[3]) + 10 * int(vat[4]) + 3 * int(vat[5]) + \ 5 * int(vat[6]) + 9 * int(vat[7]) + 4 * int(vat[8]) + \ 6 * int(vat[9]) + 8 * int(vat[10]) check = check_sum2 % 11 if check != int(vat[11]): return False return True # VAT validation in Turkey, contributed by # Levent Karakas @ Eska Yazilim A.S. def check_vat_tr(self, vat): if not (10 <= len(vat) <= 11): return False try: int(vat) except ValueError: return False # check vat number (vergi no) if len(vat) == 10: sum = 0 check = 0 for f in range(0, 9): c1 = (int(vat[f]) + (9-f)) % 10 c2 = (c1 * (2 ** (9-f))) % 9 if (c1 != 0) and (c2 == 0): c2 = 9 sum += c2 if sum % 10 == 0: check = 0 else: check = 10 - (sum % 10) return int(vat[9]) == check # check personal id (tc kimlik no) if len(vat) == 11: c1a = 0 c1b = 0 c2 = 0 for f in range(0, 9, 2): c1a += int(vat[f]) for f in range(1, 9, 2): c1b += int(vat[f]) c1 = ((7 * c1a) - c1b) % 10 for f in range(0, 10): c2 += int(vat[f]) c2 = c2 % 10 return int(vat[9]) == c1 and int(vat[10]) == c2 return False __check_vat_sa_re = re.compile(r"^3[0-9]{13}3$") # Saudi Arabia TIN validation def check_vat_sa(self, vat): """ Check company VAT TIN according to ZATCA specifications: The VAT number should start and begin with a '3' and be 15 digits long """ return self.__check_vat_sa_re.match(vat) or False def check_vat_ua(self, vat): res = [] for partner in self: if partner.commercial_partner_id.country_id.code == 'MX': if len(vat) == 10: res.append(True) else: res.append(False) elif partner.commercial_partner_id.is_company: if len(vat) == 12: res.append(True) else: res.append(False) else: if len(vat) == 10 or len(vat) == 9: res.append(True) else: res.append(False) return all(res) def check_vat_ve(self, vat): # https://tin-check.com/en/venezuela/ # https://techdocs.broadcom.com/us/en/symantec-security-software/information-security/data-loss-prevention/15-7/About-content-packs/What-s-included-in-Content-Pack-2021-02/Updated-data-identifiers-in-Content-Pack-2021-02/venezuela-national-identification-number-v115451096-d327e108002-CP2021-02.html # Sources last visited on 2022-12-09 # VAT format: (kind - 1 letter)(identifier number - 8-digit number)(check digit - 1 digit) vat_regex = re.compile(r""" ([vecjpg]) # group 1 - kind ( (?P<optional_1>-)? # optional '-' (1) [0-9]{2} (?(optional_1)(?P<optional_2>[.])?) # optional '.' (2) only if (1) [0-9]{3} (?(optional_2)[.]) # mandatory '.' if (2) [0-9]{3} (?(optional_1)-) # mandatory '-' if (1) ) # group 2 - identifier number ([0-9]{1}) # group X - check digit """, re.VERBOSE | re.IGNORECASE) matches = re.fullmatch(vat_regex, vat) if not matches: return False kind, identifier_number, *_, check_digit = matches.groups() kind = kind.lower() identifier_number = identifier_number.replace("-", "").replace(".", "") check_digit = int(check_digit) if kind == 'v': # Venezuela citizenship kind_digit = 1 elif kind == 'e': # Foreigner kind_digit = 2 elif kind == 'c' or kind == 'j': # Township/Communal Council or Legal entity kind_digit = 3 elif kind == 'p': # Passport kind_digit = 4 else: # Government ('g') kind_digit = 5 # === Checksum validation === multipliers = [3, 2, 7, 6, 5, 4, 3, 2] checksum = kind_digit * 4 checksum += sum(map(lambda n, m: int(n) * m, identifier_number, multipliers)) checksum_digit = 11 - checksum % 11 if checksum_digit > 9: checksum_digit = 0 return check_digit == checksum_digit def check_vat_xi(self, vat): """ Temporary Nothern Ireland VAT validation following Brexit As of January 1st 2021, companies in Northern Ireland have a new VAT number starting with XI TODO: remove when stdnum is updated to 1.16 in supported distro""" check_func = getattr(stdnum.util.get_cc_module('gb', 'vat'), 'is_valid', None) if not check_func: return len(vat) == 9 return check_func(vat) def check_vat_in(self, vat): #reference from https://www.gstzen.in/a/format-of-a-gst-number-gstin.html if vat and len(vat) == 15: all_gstin_re = [ r'[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[Zz1-9A-Ja-j]{1}[0-9a-zA-Z]{1}', # Normal, Composite, Casual GSTIN r'[0-9]{4}[A-Z]{3}[0-9]{5}[UO]{1}[N][A-Z0-9]{1}', #UN/ON Body GSTIN r'[0-9]{4}[a-zA-Z]{3}[0-9]{5}[N][R][0-9a-zA-Z]{1}', #NRI GSTIN r'[0-9]{2}[a-zA-Z]{4}[a-zA-Z0-9]{1}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[DK]{1}[0-9a-zA-Z]{1}', #TDS GSTIN r'[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[C]{1}[0-9a-zA-Z]{1}' #TCS GSTIN ] return any(re.compile(rx).match(vat) for rx in all_gstin_re) return False def check_vat_au(self, vat): ''' The Australian equivalent of a VAT number is an ABN number. TFN (Australia Tax file numbers) are private and not to be entered into systems or publicly displayed, so ABN numbers are the public facing number that legally must be displayed on all invoices ''' check_func = getattr(stdnum.util.get_cc_module('au', 'abn'), 'is_valid', None) if not check_func: vat = vat.replace(" ", "") return len(vat) == 11 and vat.isdigit() return check_func(vat) def format_vat_eu(self, vat): # Foreign companies that trade with non-enterprises in the EU # may have a VATIN starting with "EU" instead of a country code. return vat def format_vat_ch(self, vat): stdnum_vat_format = getattr(stdnum.util.get_cc_module('ch', 'vat'), 'format', None) return stdnum_vat_format('CH' + vat)[2:] if stdnum_vat_format else vat def format_vat_sm(self, vat): stdnum_vat_format = stdnum.util.get_cc_module('sm', 'vat').compact return stdnum_vat_format('SM' + vat)[2:] def _fix_vat_number(self, vat, country_id): code = self.env['res.country'].browse(country_id).code if country_id else False vat_country, vat_number = self._split_vat(vat) if code and code.lower() != vat_country: return vat stdnum_vat_fix_func = getattr(stdnum.util.get_cc_module(vat_country, 'vat'), 'compact', None) #If any localization module need to define vat fix method for it's country then we give first priority to it. format_func_name = 'format_vat_' + vat_country format_func = getattr(self, format_func_name, None) or stdnum_vat_fix_func if format_func: vat_number = format_func(vat_number) return vat_country.upper() + vat_number @api.model_create_multi def create(self, vals_list): for values in vals_list: if values.get('vat'): country_id = values.get('country_id') values['vat'] = self._fix_vat_number(values['vat'], country_id) return super(ResPartner, self).create(vals_list) def write(self, values): if values.get('vat') and len(self.mapped('country_id')) == 1: country_id = values.get('country_id', self.country_id.id) values['vat'] = self._fix_vat_number(values['vat'], country_id) return super(ResPartner, self).write(values)
39.916431
28,181
669
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Luxembourg - Peppol Identifier", 'version': '1.0', 'description': """ Some Luxembourg public institutions do not have a VAT number but have been assigned an arbitrary number (see: https://pch.gouvernement.lu/fr/peppol.html). Thus, this module adds the Peppol Identifier field on the account.move form view. If this field is set, it is then read when exporting electronic invoicing formats. """, 'depends': ['l10n_lu', 'account_edi_ubl_cii'], 'data': [ 'views/partner_view.xml', ], 'license': 'LGPL-3', }
39.352941
669
326
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 ResPartner(models.Model): _inherit = 'res.partner' country_code = fields.Char(related='country_id.code') l10n_lu_peppol_identifier = fields.Char("Peppol Unique Identifier")
29.636364
326
432
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "MRP Project", 'version': '1.0', 'summary': "Monitor MRP using project", 'description': "", 'category': 'Services/Project', 'depends': ['mrp_account', 'project'], 'data': [ 'views/project_views.xml', ], 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
25.411765
432
2,577
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _, _lt class Project(models.Model): _inherit = "project.project" production_count = fields.Integer(related="analytic_account_id.production_count", groups='mrp.group_mrp_user') workorder_count = fields.Integer(related="analytic_account_id.workorder_count", groups='mrp.group_mrp_user') bom_count = fields.Integer(related="analytic_account_id.bom_count", groups='mrp.group_mrp_user') def action_view_mrp_production(self): self.ensure_one() action = self.analytic_account_id.action_view_mrp_production() if self.production_count > 1: action["view_mode"] = 'tree,form,kanban,calendar,pivot,graph' return action def action_view_mrp_bom(self): self.ensure_one() action = self.analytic_account_id.action_view_mrp_bom() if self.bom_count > 1: action['view_mode'] = 'tree,form,kanban' return action def action_view_workorder(self): self.ensure_one() action = self.analytic_account_id.action_view_workorder() if self.workorder_count > 1: action['view_mode'] = 'tree,form,kanban,calendar,pivot,graph' return action # ---------------------------- # Project Updates # ---------------------------- def _get_stat_buttons(self): buttons = super(Project, self)._get_stat_buttons() if self.user_has_groups('mrp.group_mrp_user'): buttons.extend([{ 'icon': 'wrench', 'text': _lt('Manufacturing Orders'), 'number': self.production_count, 'action_type': 'object', 'action': 'action_view_mrp_production', 'show': self.production_count > 0, 'sequence': 19, }, { 'icon': 'cog', 'text': _lt('Work Orders'), 'number': self.workorder_count, 'action_type': 'object', 'action': 'action_view_workorder', 'show': self.workorder_count > 0, 'sequence': 20, }, { 'icon': 'flask', 'text': _lt('Bills of Materials'), 'number': self.bom_count, 'action_type': 'object', 'action': 'action_view_mrp_bom', 'show': self.bom_count > 0, 'sequence': 21, }]) return buttons
37.347826
2,577
700
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Purchase Requisition Stock Dropshipping', 'version': '1.0', 'category': 'Hidden', 'summary': 'Purchase Requisition, Stock, Dropshipping', 'description': """ This module makes the link between the purchase requisition and dropshipping applications. Set shipping address on purchase orders created from purchase agreements and link with originating sale order. """, 'depends': ['purchase_requisition_stock', 'stock_dropshipping'], 'data': [ 'views/purchase_views.xml', ], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
31.818182
700
2,595
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.fields import Command from odoo.tests import common from odoo.tests.common import Form class TestPurchaseRequisitionStockDropshipping(common.TransactionCase): def test_purchase_requisition_stock_dropshipping(self): # create 'dropship - call for tender' product product = self.env['product.product'].create({'name': 'prsds-product'}) dropshipping_route = self.env.ref('stock_dropshipping.route_drop_shipping') product.write({'route_ids': [Command.set([dropshipping_route.id])]}) product.write({'purchase_requisition': 'tenders'}) # sell this product customer = self.env['res.partner'].create({'name': 'prsds-customer'}) sale_order = self.env['sale.order'].create({ 'partner_id': customer.id, 'partner_invoice_id': customer.id, 'partner_shipping_id': customer.id, 'order_line': [Command.create({ 'name': product.name, 'product_id': product.id, 'product_uom_qty': 10.00, 'product_uom': product.uom_id.id, 'price_unit': 10, })], }) # confirm order sale_order.action_confirm() # call for tender must exists call_for_tender = self.env['purchase.requisition'].search([('origin', '=', sale_order.name)]) self.assertTrue(call_for_tender) # confirm call for tender call_for_tender.action_in_progress() # create purchase order from call for tender vendor = self.env['res.partner'].create({'name': 'prsds-vendor'}) f = Form(self.env['purchase.order'].with_context(default_requisition_id=call_for_tender)) f.partner_id = vendor purchase_order = f.save() # check purchase order self.assertEqual(purchase_order.requisition_id.id, call_for_tender.id, 'Purchase order should be linked with call for tender') self.assertEqual(purchase_order.dest_address_id.id, customer.id, 'Purchase order should be delivered at customer') self.assertEqual(len(purchase_order.order_line), 1, 'Purchase order should have one line') purchase_order_line = purchase_order.order_line self.assertEqual(purchase_order_line.sale_order_id.id, sale_order.id, 'Purchase order should be linked with sale order') self.assertEqual(purchase_order_line.sale_line_id.id, sale_order.order_line.id, 'Purchase order line should be linked with sale order line')
46.339286
2,595
611
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class PurchaseOrder(models.Model): _inherit = 'purchase.order' @api.onchange('requisition_id') def _onchange_requisition_id(self): super()._onchange_requisition_id() if self.requisition_id and self.requisition_id.procurement_group_id: self.group_id = self.requisition_id.procurement_group_id.id if self.group_id.sale_id.partner_shipping_id: self.dest_address_id = self.group_id.sale_id.partner_shipping_id.id
38.1875
611
1,076
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class PurchaseRequisition(models.Model): _inherit = 'purchase.requisition' def _prepare_tender_values(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values): res = super()._prepare_tender_values(product_id, product_qty, product_uom, location_id, name, origin, company_id, values) if 'sale_line_id' in values: res['line_ids'][0][2]['sale_line_id'] = values['sale_line_id'] return res class PurchaseRequisitionLine(models.Model): _inherit = "purchase.requisition.line" sale_line_id = fields.Many2one('sale.order.line', string="Origin Sale Order Line") def _prepare_purchase_order_line(self, name, product_qty=0.0, price_unit=0.0, taxes_ids=False): res = super()._prepare_purchase_order_line(name, product_qty, price_unit, taxes_ids) if self.sale_line_id: res['sale_line_id'] = self.sale_line_id.id return res
41.384615
1,076
1,750
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Course Certifications", 'summary': 'Add certification capabilities to your courses', 'description': """This module lets you use the full power of certifications within your courses.""", 'category': 'Website/eLearning', 'version': '1.0', 'depends': ['website_slides', 'survey'], 'installable': True, 'auto_install': True, 'data': [ 'security/ir.model.access.csv', 'views/slide_channel_views.xml', 'views/slide_slide_views.xml', 'views/survey_survey_views.xml', 'views/website_slides_menu_views.xml', 'views/website_slides_templates_course.xml', 'views/website_slides_templates_lesson.xml', 'views/website_slides_templates_lesson_fullscreen.xml', 'views/website_slides_templates_homepage.xml', 'views/survey_templates.xml', 'views/website_profile.xml', 'data/mail_template_data.xml', 'data/gamification_data.xml', ], 'demo': [ 'data/survey_demo.xml', 'data/slide_slide_demo.xml', 'data/survey.user_input.line.csv', ], 'assets': { 'web.assets_frontend': [ 'website_slides_survey/static/src/scss/website_slides_survey.scss', 'website_slides_survey/static/src/js/slides_upload.js', 'website_slides_survey/static/src/js/slides_course_fullscreen_player.js', 'website_slides_survey/static/src/js/slides_certification_upload_toast.js', ], 'survey.survey_assets': [ 'website_slides_survey/static/src/scss/website_slides_survey_result.scss', ], }, 'license': 'LGPL-3', }
39.772727
1,750
6,384
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.survey.tests.common import TestSurveyCommon class TestCourseCertificationFailureFlow(TestSurveyCommon): def test_course_certification_failure_flow(self): # Step 1: create a simple certification # -------------------------------------------------- with self.with_user('survey_user'): certification = self.env['survey.survey'].create({ 'title': 'Small course certification', 'access_mode': 'public', 'users_login_required': True, 'scoring_type': 'scoring_with_answers', 'certification': True, 'is_attempts_limited': True, 'scoring_success_min': 100.0, 'attempts_limit': 2, }) self._add_question( None, 'Question 1', 'simple_choice', sequence=1, survey_id=certification.id, labels=[ {'value': 'Wrong answer'}, {'value': 'Correct answer', 'is_correct': True, 'answer_score': 1.0} ]) self._add_question( None, 'Question 2', 'simple_choice', sequence=2, survey_id=certification.id, labels=[ {'value': 'Wrong answer'}, {'value': 'Correct answer', 'is_correct': True, 'answer_score': 1.0} ]) # Step 1.1: create a simple channel self.channel = self.env['slide.channel'].sudo().create({ 'name': 'Test Channel', 'channel_type': 'training', 'enroll': 'public', 'visibility': 'public', 'is_published': True, }) # Step 2: link the certification to a slide of type 'certification' self.slide_certification = self.env['slide.slide'].sudo().create({ 'name': 'Certification slide', 'channel_id': self.channel.id, 'slide_type': 'certification', 'survey_id': certification.id, 'is_published': True, }) # Step 3: add public user as member of the channel self.channel._action_add_members(self.user_public.partner_id) # forces recompute of partner_ids as we create directly in relation self.channel.invalidate_cache() slide_partner = self.slide_certification._action_set_viewed(self.user_public.partner_id) self.slide_certification.with_user(self.user_public)._generate_certification_url() self.assertEqual(1, len(slide_partner.user_input_ids), 'A user input should have been automatically created upon slide view') # Step 4: fill in the created user_input with wrong answers self.fill_in_answer(slide_partner.user_input_ids[0], certification.question_ids) self.assertFalse(slide_partner.survey_scoring_success, 'Quizz should not be marked as passed with wrong answers') # forces recompute of partner_ids as we delete directly in relation self.channel.invalidate_cache() self.assertIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should still be a member of the course because he still has attempts left') # Step 5: simulate a 'retry' retry_user_input = self.slide_certification.survey_id.sudo()._create_answer( partner=self.user_public.partner_id, **{ 'slide_id': self.slide_certification.id, 'slide_partner_id': slide_partner.id }, invite_token=slide_partner.user_input_ids[0].invite_token ) # Step 6: fill in the new user_input with wrong answers again self.fill_in_answer(retry_user_input, certification.question_ids) # forces recompute of partner_ids as we delete directly in relation self.channel.invalidate_cache() self.assertNotIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should have been kicked out of the course because he failed his last attempt') # Step 7: add public user as member of the channel once again self.channel._action_add_members(self.user_public.partner_id) # forces recompute of partner_ids as we create directly in relation self.channel.invalidate_cache() self.assertIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should be a member of the course once again') new_slide_partner = self.slide_certification._action_set_viewed(self.user_public.partner_id) self.slide_certification.with_user(self.user_public)._generate_certification_url() self.assertEqual(1, len(new_slide_partner.user_input_ids.filtered(lambda user_input: user_input.state != 'done')), 'A new user input should have been automatically created upon slide view') # Step 8: fill in the created user_input with correct answers this time self.fill_in_answer(new_slide_partner.user_input_ids.filtered(lambda user_input: user_input.state != 'done')[0], certification.question_ids, good_answers=True) self.assertTrue(new_slide_partner.survey_scoring_success, 'Quizz should be marked as passed with correct answers') # forces recompute of partner_ids as we delete directly in relation self.channel.invalidate_cache() self.assertIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should still be a member of the course') def fill_in_answer(self, answer, questions, good_answers=False): """ Fills in the user_input with answers for all given questions. You can control whether the answer will be correct or not with the 'good_answers' param. (It's assumed that wrong answers are at index 0 of question.suggested_answer_ids and good answers at index 1) """ answer.write({ 'state': 'done', 'user_input_line_ids': [ (0, 0, { 'question_id': question.id, 'answer_type': 'suggestion', 'answer_score': 1 if good_answers else 0, 'suggested_answer_id': question.suggested_answer_ids[1 if good_answers else 0].id }) for question in questions ] })
52.760331
6,384
5,846
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 SlidePartnerRelation(models.Model): _inherit = 'slide.slide.partner' user_input_ids = fields.One2many('survey.user_input', 'slide_partner_id', 'Certification attempts') survey_scoring_success = fields.Boolean('Certification Succeeded', compute='_compute_survey_scoring_success', store=True) @api.depends('partner_id', 'user_input_ids.scoring_success') def _compute_survey_scoring_success(self): succeeded_user_inputs = self.env['survey.user_input'].sudo().search([ ('slide_partner_id', 'in', self.ids), ('scoring_success', '=', True) ]) succeeded_slide_partners = succeeded_user_inputs.mapped('slide_partner_id') for record in self: record.survey_scoring_success = record in succeeded_slide_partners def _compute_field_value(self, field): super()._compute_field_value(field) if field.name == 'survey_scoring_success': self.filtered('survey_scoring_success').write({ 'completed': True }) class Slide(models.Model): _inherit = 'slide.slide' slide_type = fields.Selection(selection_add=[ ('certification', 'Certification') ], ondelete={'certification': 'set default'}) survey_id = fields.Many2one('survey.survey', 'Certification') nbr_certification = fields.Integer("Number of Certifications", compute='_compute_slides_statistics', store=True) _sql_constraints = [ ('check_survey_id', "CHECK(slide_type != 'certification' OR survey_id IS NOT NULL)", "A slide of type 'certification' requires a certification."), ('check_certification_preview', "CHECK(slide_type != 'certification' OR is_preview = False)", "A slide of type certification cannot be previewed."), ] @api.onchange('survey_id') def _on_change_survey_id(self): if self.survey_id: self.slide_type = 'certification' @api.model def create(self, values): rec = super(Slide, self).create(values) if rec.survey_id: rec.slide_type = 'certification' if 'survey_id' in values: rec._ensure_challenge_category() return rec def write(self, values): old_surveys = self.mapped('survey_id') result = super(Slide, self).write(values) if 'survey_id' in values: self._ensure_challenge_category(old_surveys=old_surveys - self.mapped('survey_id')) return result def unlink(self): old_surveys = self.mapped('survey_id') result = super(Slide, self).unlink() self._ensure_challenge_category(old_surveys=old_surveys, unlink=True) return result def _ensure_challenge_category(self, old_surveys=None, unlink=False): """ If a slide is linked to a survey that gives a badge, the challenge category of this badge must be set to 'slides' in order to appear under the certification badge list on ranks_badges page. If the survey is unlinked from the slide, the challenge category must be reset to 'certification'""" if old_surveys: old_certification_challenges = old_surveys.mapped('certification_badge_id').challenge_ids old_certification_challenges.write({'challenge_category': 'certification'}) if not unlink: certification_challenges = self.mapped('survey_id').mapped('certification_badge_id').challenge_ids certification_challenges.write({'challenge_category': 'slides'}) def _generate_certification_url(self): """ get a map of certification url for certification slide from `self`. The url will come from the survey user input: 1/ existing and not done user_input for member of the course 2/ create a new user_input for member 3/ for no member, a test user_input is created and the url is returned Note: the slide.slides.partner should already exist We have to generate a new invite_token to differentiate pools of attempts since the course can be enrolled multiple times. """ certification_urls = {} for slide in self.filtered(lambda slide: slide.slide_type == 'certification' and slide.survey_id): if slide.channel_id.is_member: user_membership_id_sudo = slide.user_membership_id.sudo() if user_membership_id_sudo.user_input_ids: last_user_input = next(user_input for user_input in user_membership_id_sudo.user_input_ids.sorted( lambda user_input: user_input.create_date, reverse=True )) certification_urls[slide.id] = last_user_input.get_start_url() else: user_input = slide.survey_id.sudo()._create_answer( partner=self.env.user.partner_id, check_attempts=False, **{ 'slide_id': slide.id, 'slide_partner_id': user_membership_id_sudo.id }, invite_token=self.env['survey.user_input']._generate_invite_token() ) certification_urls[slide.id] = user_input.get_start_url() else: user_input = slide.survey_id.sudo()._create_answer( partner=self.env.user.partner_id, check_attempts=False, test_entry=True, **{ 'slide_id': slide.id } ) certification_urls[slide.id] = user_input.get_start_url() return certification_urls
48.31405
5,846
312
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 Channel(models.Model): _inherit = 'slide.channel' nbr_certification = fields.Integer("Number of Certifications", compute='_compute_slides_statistics', store=True)
31.2
312
2,770
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api from odoo.osv import expression class SurveyUserInput(models.Model): _inherit = 'survey.user_input' slide_id = fields.Many2one('slide.slide', 'Related course slide', help="The related course slide when there is no membership information") slide_partner_id = fields.Many2one('slide.slide.partner', 'Subscriber information', help="Slide membership information for the logged in user") @api.model_create_multi def create(self, vals_list): records = super(SurveyUserInput, self).create(vals_list) records._check_for_failed_attempt() return records def write(self, vals): res = super(SurveyUserInput, self).write(vals) if 'state' in vals: self._check_for_failed_attempt() return res def _check_for_failed_attempt(self): """ If the user fails his last attempt at a course certification, we remove him from the members of the course (and he has to enroll again). He receives an email in the process notifying him of his failure and suggesting he enrolls to the course again. The purpose is to have a 'certification flow' where the user can re-purchase the certification when they have failed it.""" if self: user_inputs = self.search([ ('id', 'in', self.ids), ('state', '=', 'done'), ('scoring_success', '=', False), ('slide_partner_id', '!=', False) ]) if user_inputs: for user_input in user_inputs: removed_memberships_per_partner = {} if user_input.survey_id._has_attempts_left(user_input.partner_id, user_input.email, user_input.invite_token): # skip if user still has attempts left continue self.env.ref('website_slides_survey.mail_template_user_input_certification_failed').send_mail( user_input.id, notif_layout="mail.mail_notification_light" ) removed_memberships = removed_memberships_per_partner.get( user_input.partner_id, self.env['slide.channel'] ) removed_memberships |= user_input.slide_partner_id.channel_id removed_memberships_per_partner[user_input.partner_id] = removed_memberships for partner_id, removed_memberships in removed_memberships_per_partner.items(): removed_memberships._remove_membership(partner_id.ids)
43.28125
2,770
2,628
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 Survey(models.Model): _inherit = 'survey.survey' slide_ids = fields.One2many( 'slide.slide', 'survey_id', string="Certification Slides", help="The slides this survey is linked to through the e-learning application") slide_channel_ids = fields.One2many( 'slide.channel', string="Certification Courses", compute='_compute_slide_channel_data', help="The courses this survey is linked to through the e-learning application", groups='website_slides.group_website_slides_officer') slide_channel_count = fields.Integer("Courses Count", compute='_compute_slide_channel_data', groups='website_slides.group_website_slides_officer') @api.depends('slide_ids.channel_id') def _compute_slide_channel_data(self): for survey in self: survey.slide_channel_ids = survey.slide_ids.mapped('channel_id') survey.slide_channel_count = len(survey.slide_channel_ids) # --------------------------------------------------------- # Actions # --------------------------------------------------------- def action_survey_view_slide_channels(self): action = self.env["ir.actions.actions"]._for_xml_id("website_slides.slide_channel_action_overview") action['display_name'] = _("Courses") if self.slide_channel_count == 1: action.update({'views': [(False, 'form')], 'res_id': self.slide_channel_ids[0].id}) else: action.update({'views': [[False, 'tree'], [False, 'form']], 'domain': [('id', 'in', self.slide_channel_ids.ids)]}) return action # --------------------------------------------------------- # Business # --------------------------------------------------------- def _check_answer_creation(self, user, partner, email, test_entry=False, check_attempts=True, invite_token=False): """ Overridden to allow website_slides_officer to test certifications. """ self.ensure_one() if test_entry and user.has_group('website_slides.group_website_slides_officer'): return True return super(Survey, self)._check_answer_creation(user, partner, email, test_entry=test_entry, check_attempts=check_attempts, invite_token=invite_token) def _prepare_challenge_category(self): slide_survey = self.env['slide.slide'].search([('survey_id', '=', self.id)]) return 'slides' if slide_survey else 'certification'
48.666667
2,628
800
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.survey.controllers import main class Survey(main.Survey): def _prepare_survey_finished_values(self, survey, answer, token=False): result = super(Survey, self)._prepare_survey_finished_values(survey, answer, token) if answer.slide_id: result['channel_id'] = answer.slide_id.channel_id return result def _prepare_retry_additional_values(self, answer): result = super(Survey, self)._prepare_retry_additional_values(answer) if answer.slide_id: result['slide_id'] = answer.slide_id.id if answer.slide_partner_id: result['slide_partner_id'] = answer.slide_partner_id.id return result
36.363636
800
7,640
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import werkzeug import werkzeug.utils import werkzeug.exceptions from odoo import _ from odoo import http from odoo.exceptions import AccessError from odoo.http import request from odoo.osv import expression from odoo.addons.website_slides.controllers.main import WebsiteSlides class WebsiteSlidesSurvey(WebsiteSlides): @http.route(['/slides_survey/slide/get_certification_url'], type='http', auth='user', website=True) def slide_get_certification_url(self, slide_id, **kw): fetch_res = self._fetch_slide(slide_id) if fetch_res.get('error'): raise werkzeug.exceptions.NotFound() slide = fetch_res['slide'] if slide.channel_id.is_member: slide.action_set_viewed() certification_url = slide._generate_certification_url().get(slide.id) if not certification_url: raise werkzeug.exceptions.NotFound() return request.redirect(certification_url) @http.route(['/slides_survey/certification/search_read'], type='json', auth='user', methods=['POST'], website=True) def slides_certification_search_read(self, fields): can_create = request.env['survey.survey'].check_access_rights('create', raise_exception=False) return { 'read_results': request.env['survey.survey'].search_read([('certification', '=', True)], fields), 'can_create': can_create, } # ------------------------------------------------------------ # Overrides # ------------------------------------------------------------ @http.route(['/slides/add_slide'], type='json', auth='user', methods=['POST'], website=True) def create_slide(self, *args, **post): create_new_survey = post['slide_type'] == "certification" and post.get('survey') and not post['survey']['id'] linked_survey_id = int(post.get('survey', {}).get('id') or 0) if create_new_survey: # If user cannot create a new survey, no need to create the slide either. if not request.env['survey.survey'].check_access_rights('create', raise_exception=False): return {'error': _('You are not allowed to create a survey.')} # Create survey first as certification slide needs a survey_id (constraint) post['survey_id'] = request.env['survey.survey'].create({ 'title': post['survey']['title'], 'questions_layout': 'page_per_question', 'is_attempts_limited': True, 'attempts_limit': 1, 'is_time_limited': False, 'scoring_type': 'scoring_without_answers', 'certification': True, 'scoring_success_min': 70.0, 'certification_mail_template_id': request.env.ref('survey.mail_template_certification').id, }).id elif linked_survey_id: try: request.env['survey.survey'].browse([linked_survey_id]).read(['title']) except AccessError: return {'error': _('You are not allowed to link a certification.')} post['survey_id'] = post['survey']['id'] # Then create the slide result = super(WebsiteSlidesSurvey, self).create_slide(*args, **post) if create_new_survey: # Set the redirect_url used in toaster action_id = request.env.ref('survey.action_survey_form').id result.update({ 'redirect_url': '/web#id=%s&action=%s&model=survey.survey&view_type=form' % (post['survey_id'], action_id), 'redirect_to_certification': True }) return result # Utils # --------------------------------------------------- def _set_completed_slide(self, slide): if slide.slide_type == 'certification': raise werkzeug.exceptions.Forbidden(_("Certification slides are completed when the survey is succeeded.")) return super(WebsiteSlidesSurvey, self)._set_completed_slide(slide) def _get_valid_slide_post_values(self): result = super(WebsiteSlidesSurvey, self)._get_valid_slide_post_values() result.append('survey_id') return result # Profile # --------------------------------------------------- def _prepare_user_slides_profile(self, user): values = super(WebsiteSlidesSurvey, self)._prepare_user_slides_profile(user) values.update({ 'certificates': self._get_users_certificates(user)[user.id] }) return values # All Users Page # --------------------------------------------------- def _prepare_all_users_values(self, users): result = super(WebsiteSlidesSurvey, self)._prepare_all_users_values(users) certificates_per_user = self._get_users_certificates(users) for index, user in enumerate(users): result[index].update({ 'certification_count': len(certificates_per_user.get(user.id, [])) }) return result def _get_users_certificates(self, users): partner_ids = [user.partner_id.id for user in users] domain = [ ('slide_partner_id.partner_id', 'in', partner_ids), ('scoring_success', '=', True), ('slide_partner_id.survey_scoring_success', '=', True) ] certificates = request.env['survey.user_input'].sudo().search(domain) users_certificates = { user.id: [ certificate for certificate in certificates if certificate.partner_id == user.partner_id ] for user in users } return users_certificates # Badges & Ranks Page # --------------------------------------------------- def _prepare_ranks_badges_values(self, **kwargs): """ Extract certification badges, to render them in ranks/badges page in another section. Order them by number of granted users desc and show only badges linked to opened certifications.""" values = super(WebsiteSlidesSurvey, self)._prepare_ranks_badges_values(**kwargs) # 1. Getting all certification badges, sorted by granted user desc domain = expression.AND([[('survey_id', '!=', False)], self._prepare_badges_domain(**kwargs)]) certification_badges = request.env['gamification.badge'].sudo().search(domain) # keep only the badge with challenge category = slides (the rest will be displayed under 'normal badges' section certification_badges = certification_badges.filtered( lambda b: 'slides' in b.challenge_ids.mapped('challenge_category')) if not certification_badges: return values # 2. sort by granted users (done here, and not in search directly, because non stored field) certification_badges = certification_badges.sorted("granted_users_count", reverse=True) # 3. Remove certification badge from badges badges = values['badges'] - certification_badges # 4. Getting all course url for each badge certification_slides = request.env['slide.slide'].sudo().search([('survey_id', 'in', certification_badges.mapped('survey_id').ids)]) certification_badge_urls = {slide.survey_id.certification_badge_id.id: slide.channel_id.website_url for slide in certification_slides} # 5. Applying changes values.update({ 'badges': badges, 'certification_badges': certification_badges, 'certification_badge_urls': certification_badge_urls }) return values
45.748503
7,640
1,148
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Automated Action Rules', 'version': '1.0', 'category': 'Sales/Sales', 'description': """ This module allows to implement action rules for any object. ============================================================ Use automated actions to automatically trigger actions for various screens. **Example:** A lead created by a specific user may be automatically set to a specific Sales Team, or an opportunity which still has status pending after 14 days might trigger an automatic reminder email. """, 'depends': ['base', 'resource', 'mail'], 'data': [ 'security/ir.model.access.csv', 'data/base_automation_data.xml', 'views/base_automation_view.xml', ], 'assets': { 'web.assets_qweb': [ 'base_automation/static/src/xml/*.xml', ], 'web.assets_backend': [ 'base_automation/static/src/js/**/*', ], 'web.qunit_suite_tests': [ 'base_automation/static/tests/**/*', ], }, 'license': 'LGPL-3', }
31.888889
1,148
3,824
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import TransactionCase from odoo.exceptions import UserError import odoo.tests @odoo.tests.tagged('post_install', '-at_install') class TestAutomation(TransactionCase): def test_01_on_create(self): """ Simple on_create with admin user """ self.env["base.automation"].create({ "name": "Force Archived Contacts", "trigger": "on_create_or_write", "model_id": self.env.ref("base.model_res_partner").id, "type": "ir.actions.server", "trigger_field_ids": [(6, 0, [self.env.ref("base.field_res_partner__name").id])], "fields_lines": [(0, 0, { "col1": self.env.ref("base.field_res_partner__active").id, "evaluation_type": "equation", "value": "False", })], }) # verify the partner can be created and the action still runs bilbo = self.env["res.partner"].create({"name": "Bilbo Baggins"}) self.assertFalse(bilbo.active) # verify the partner can be updated and the action still runs bilbo.active = True bilbo.name = "Bilbo" self.assertFalse(bilbo.active) def test_02_on_create_restricted(self): """ on_create action with low portal user """ action = self.env["base.automation"].create({ "name": "Force Archived Filters", "trigger": "on_create_or_write", "model_id": self.env.ref("base.model_ir_filters").id, "type": "ir.actions.server", "trigger_field_ids": [(6, 0, [self.env.ref("base.field_ir_filters__name").id])], "fields_lines": [(0, 0, { "col1": self.env.ref("base.field_ir_filters__active").id, "evaluation_type": "equation", "value": "False", })], }) # action cached was cached with admin, force CacheMiss action.env.clear() self_portal = self.env["ir.filters"].with_user(self.env.ref("base.user_demo").id) # verify the portal user can create ir.filters but can not read base.automation self.assertTrue(self_portal.env["ir.filters"].check_access_rights("create", raise_exception=False)) self.assertFalse(self_portal.env["base.automation"].check_access_rights("read", raise_exception=False)) # verify the filter can be created and the action still runs filters = self_portal.create({ "name": "Where is Bilbo?", "domain": "[('name', 'ilike', 'bilbo')]", "model_id": "res.partner", }) self.assertFalse(filters.active) # verify the filter can be updated and the action still runs filters.active = True filters.name = "Where is Bilbo Baggins?" self.assertFalse(filters.active) def test_03_on_change_restricted(self): """ on_create action with low portal user """ action = self.env["base.automation"].create({ "name": "Force Archived Filters", "trigger": "on_change", "model_id": self.env.ref("base.model_ir_filters").id, "type": "ir.actions.server", "on_change_field_ids": [(6, 0, [self.env.ref("base.field_ir_filters__name").id])], "state": "code", "code": """action = {'value': {'active': False}}""", }) # action cached was cached with admin, force CacheMiss action.env.clear() self_portal = self.env["ir.filters"].with_user(self.env.ref("base.user_demo").id) # simulate a onchange call on name onchange = self_portal.onchange({}, [], {"name": "1", "active": ""}) self.assertEqual(onchange["value"]["active"], False)
42.488889
3,824
1,485
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import tagged, HttpCase @tagged('-at_install', 'post_install', 'mail_composer') class TestMailFullComposer(HttpCase): def test_full_composer_tour(self): self.env['mail.template'].create({ 'name': 'Test template', # name hardcoded for test 'partner_to': '${object.id}', 'lang': '${object.lang}', 'auto_delete': True, 'model_id': self.ref('base.model_res_partner'), }) test_user = self.env['res.users'].create({ 'email': '[email protected]', 'groups_id': [ (6, 0, [self.ref('base.group_user'), self.ref('base.group_partner_manager')]), ], 'name': 'Test User', 'login': 'testuser', 'password': 'testuser', }) automated_action = self.env['base.automation'].create({ 'name': 'Test', 'active': True, 'trigger': 'on_change', 'on_change_field_ids': (4, self.ref('mail.field_mail_compose_message__template_id'),), 'state': 'code', 'model_id': self.env.ref('mail.model_mail_compose_message').id, }) self.start_tour("/web#id=%d&model=res.partner" % test_user.partner_id, 'mail/static/tests/tours/mail_full_composer_test_tour.js', login='testuser') automated_action.unlink()
38.076923
1,485
24,892
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import logging import traceback from collections import defaultdict from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models, SUPERUSER_ID from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT from odoo.tools import safe_eval _logger = logging.getLogger(__name__) DATE_RANGE_FUNCTION = { 'minutes': lambda interval: relativedelta(minutes=interval), 'hour': lambda interval: relativedelta(hours=interval), 'day': lambda interval: relativedelta(days=interval), 'month': lambda interval: relativedelta(months=interval), False: lambda interval: relativedelta(0), } DATE_RANGE_FACTOR = { 'minutes': 1, 'hour': 60, 'day': 24 * 60, 'month': 30 * 24 * 60, False: 0, } class BaseAutomation(models.Model): _name = 'base.automation' _description = 'Automated Action' _order = 'sequence' action_server_id = fields.Many2one( 'ir.actions.server', 'Server Actions', domain="[('model_id', '=', model_id)]", delegate=True, required=True, ondelete='restrict') active = fields.Boolean(default=True, help="When unchecked, the rule is hidden and will not be executed.") trigger = fields.Selection([ ('on_create', 'On Creation'), ('on_write', 'On Update'), ('on_create_or_write', 'On Creation & Update'), ('on_unlink', 'On Deletion'), ('on_change', 'Based on Form Modification'), ('on_time', 'Based on Timed Condition') ], string='Trigger', required=True) trg_date_id = fields.Many2one('ir.model.fields', string='Trigger Date', help="""When should the condition be triggered. If present, will be checked by the scheduler. If empty, will be checked at creation and update.""", domain="[('model_id', '=', model_id), ('ttype', 'in', ('date', 'datetime'))]") trg_date_range = fields.Integer(string='Delay after trigger date', help="""Delay after the trigger date. You can put a negative number if you need a delay before the trigger date, like sending a reminder 15 minutes before a meeting.""") trg_date_range_type = fields.Selection([('minutes', 'Minutes'), ('hour', 'Hours'), ('day', 'Days'), ('month', 'Months')], string='Delay type', default='hour') trg_date_calendar_id = fields.Many2one("resource.calendar", string='Use Calendar', help="When calculating a day-based timed condition, it is possible to use a calendar to compute the date based on working days.") filter_pre_domain = fields.Char(string='Before Update Domain', help="If present, this condition must be satisfied before the update of the record.") filter_domain = fields.Char(string='Apply on', help="If present, this condition must be satisfied before executing the action rule.") last_run = fields.Datetime(readonly=True, copy=False) on_change_field_ids = fields.Many2many( "ir.model.fields", relation="base_automation_onchange_fields_rel", string="On Change Fields Trigger", help="Fields that trigger the onchange.", ) trigger_field_ids = fields.Many2many('ir.model.fields', string='Trigger Fields', help="The action will be triggered if and only if one of these fields is updated." "If empty, all fields are watched.") least_delay_msg = fields.Char(compute='_compute_least_delay_msg') # which fields have an impact on the registry and the cron CRITICAL_FIELDS = ['model_id', 'active', 'trigger', 'on_change_field_ids'] RANGE_FIELDS = ['trg_date_range', 'trg_date_range_type'] @api.onchange('model_id') def onchange_model_id(self): self.model_name = self.model_id.model @api.onchange('trigger') def onchange_trigger(self): if self.trigger in ['on_create', 'on_create_or_write', 'on_unlink']: self.filter_pre_domain = self.trg_date_id = self.trg_date_range = self.trg_date_range_type = False elif self.trigger in ['on_write', 'on_create_or_write']: self.trg_date_id = self.trg_date_range = self.trg_date_range_type = False elif self.trigger == 'on_time': self.filter_pre_domain = False self.trg_date_range_type = 'hour' @api.onchange('trigger', 'state') def _onchange_state(self): if self.trigger == 'on_change' and self.state != 'code': ff = self.fields_get(['trigger', 'state']) return {'warning': { 'title': _("Warning"), 'message': _("The \"%(trigger_value)s\" %(trigger_label)s can only be used with the \"%(state_value)s\" action type") % { 'trigger_value': dict(ff['trigger']['selection'])['on_change'], 'trigger_label': ff['trigger']['string'], 'state_value': dict(ff['state']['selection'])['code'], } }} MAIL_STATES = ('email', 'followers', 'next_activity') if self.trigger == 'on_unlink' and self.state in MAIL_STATES: return {'warning': { 'title': _("Warning"), 'message': _( "You cannot send an email, add followers or create an activity " "for a deleted record. It simply does not work." ), }} @api.model_create_multi def create(self, vals_list): for vals in vals_list: vals['usage'] = 'base_automation' base_automations = super(BaseAutomation, self).create(vals_list) self._update_cron() self._update_registry() return base_automations def write(self, vals): res = super(BaseAutomation, self).write(vals) if set(vals).intersection(self.CRITICAL_FIELDS): self._update_cron() self._update_registry() elif set(vals).intersection(self.RANGE_FIELDS): self._update_cron() return res def unlink(self): res = super(BaseAutomation, self).unlink() self._update_cron() self._update_registry() return res def _update_cron(self): """ Activate the cron job depending on whether there exists action rules based on time conditions. Also update its frequency according to the smallest action delay, or restore the default 4 hours if there is no time based action. """ cron = self.env.ref('base_automation.ir_cron_data_base_automation_check', raise_if_not_found=False) if cron: actions = self.with_context(active_test=True).search([('trigger', '=', 'on_time')]) cron.try_write({ 'active': bool(actions), 'interval_type': 'minutes', 'interval_number': self._get_cron_interval(actions), }) def _update_registry(self): """ Update the registry after a modification on action rules. """ if self.env.registry.ready and not self.env.context.get('import_file'): # re-install the model patches, and notify other workers self._unregister_hook() self._register_hook() self.env.registry.registry_invalidated = True def _get_actions(self, records, triggers): """ Return the actions of the given triggers for records' model. The returned actions' context contain an object to manage processing. """ if '__action_done' not in self._context: self = self.with_context(__action_done={}) domain = [('model_name', '=', records._name), ('trigger', 'in', triggers)] actions = self.with_context(active_test=True).sudo().search(domain) return actions.with_env(self.env) def _get_eval_context(self): """ Prepare the context used when evaluating python code :returns: dict -- evaluation context given to safe_eval """ return { 'datetime': safe_eval.datetime, 'dateutil': safe_eval.dateutil, 'time': safe_eval.time, 'uid': self.env.uid, 'user': self.env.user, } def _get_cron_interval(self, actions=None): """ Return the expected time interval used by the cron, in minutes. """ def get_delay(rec): return rec.trg_date_range * DATE_RANGE_FACTOR[rec.trg_date_range_type] if actions is None: actions = self.with_context(active_test=True).search([('trigger', '=', 'on_time')]) # Minimum 1 minute, maximum 4 hours, 10% tolerance delay = min(actions.mapped(get_delay), default=0) return min(max(1, delay // 10), 4 * 60) if delay else 4 * 60 def _compute_least_delay_msg(self): msg = _("Note that this action can be trigged up to %d minutes after its schedule.") self.least_delay_msg = msg % self._get_cron_interval() def _filter_pre(self, records): """ Filter the records that satisfy the precondition of action ``self``. """ self_sudo = self.sudo() if self_sudo.filter_pre_domain and records: domain = safe_eval.safe_eval(self_sudo.filter_pre_domain, self._get_eval_context()) return records.sudo().filtered_domain(domain).with_env(records.env) else: return records def _filter_post(self, records): return self._filter_post_export_domain(records)[0] def _filter_post_export_domain(self, records): """ Filter the records that satisfy the postcondition of action ``self``. """ self_sudo = self.sudo() if self_sudo.filter_domain and records: domain = safe_eval.safe_eval(self_sudo.filter_domain, self._get_eval_context()) return records.sudo().filtered_domain(domain).with_env(records.env), domain else: return records, None @api.model def _add_postmortem_action(self, e): if self.user_has_groups('base.group_user'): e.context = {} e.context['exception_class'] = 'base_automation' e.context['base_automation'] = { 'id': self.id, 'name': self.sudo().name, } def _process(self, records, domain_post=None): """ Process action ``self`` on the ``records`` that have not been done yet. """ # filter out the records on which self has already been done action_done = self._context['__action_done'] records_done = action_done.get(self, records.browse()) records -= records_done if not records: return # mark the remaining records as done (to avoid recursive processing) action_done = dict(action_done) action_done[self] = records_done + records self = self.with_context(__action_done=action_done) records = records.with_context(__action_done=action_done) # modify records values = {} if 'date_action_last' in records._fields: values['date_action_last'] = fields.Datetime.now() if values: records.write(values) # execute server actions action_server = self.action_server_id if action_server: for record in records: # we process the action if any watched field has been modified if self._check_trigger_fields(record): ctx = { 'active_model': record._name, 'active_ids': record.ids, 'active_id': record.id, 'domain_post': domain_post, } try: action_server.sudo().with_context(**ctx).run() except Exception as e: self._add_postmortem_action(e) raise e def _check_trigger_fields(self, record): """ Return whether any of the trigger fields has been modified on ``record``. """ self_sudo = self.sudo() if not self_sudo.trigger_field_ids: # all fields are implicit triggers return True if not self._context.get('old_values'): # this is a create: all fields are considered modified return True # Note: old_vals are in the format of read() old_vals = self._context['old_values'].get(record.id, {}) def differ(name): field = record._fields[name] return ( name in old_vals and field.convert_to_cache(record[name], record, validate=False) != field.convert_to_cache(old_vals[name], record, validate=False) ) return any(differ(field.name) for field in self_sudo.trigger_field_ids) def _register_hook(self): """ Patch models that should trigger action rules based on creation, modification, deletion of records and form onchanges. """ # # Note: the patched methods must be defined inside another function, # otherwise their closure may be wrong. For instance, the function # create refers to the outer variable 'create', which you expect to be # bound to create itself. But that expectation is wrong if create is # defined inside a loop; in that case, the variable 'create' is bound to # the last function defined by the loop. # def make_create(): """ Instanciate a create method that processes action rules. """ @api.model_create_multi def create(self, vals_list, **kw): # retrieve the action rules to possibly execute actions = self.env['base.automation']._get_actions(self, ['on_create', 'on_create_or_write']) if not actions: return create.origin(self, vals_list, **kw) # call original method records = create.origin(self.with_env(actions.env), vals_list, **kw) # check postconditions, and execute actions on the records that satisfy them for action in actions.with_context(old_values=None): action._process(action._filter_post(records)) return records.with_env(self.env) return create def make_write(): """ Instanciate a write method that processes action rules. """ def write(self, vals, **kw): # retrieve the action rules to possibly execute actions = self.env['base.automation']._get_actions(self, ['on_write', 'on_create_or_write']) if not (actions and self): return write.origin(self, vals, **kw) records = self.with_env(actions.env).filtered('id') # check preconditions on records pre = {action: action._filter_pre(records) for action in actions} # read old values before the update old_values = { old_vals.pop('id'): old_vals for old_vals in (records.read(list(vals)) if vals else []) } # call original method write.origin(self.with_env(actions.env), vals, **kw) # check postconditions, and execute actions on the records that satisfy them for action in actions.with_context(old_values=old_values): records, domain_post = action._filter_post_export_domain(pre[action]) action._process(records, domain_post=domain_post) return True return write def make_compute_field_value(): """ Instanciate a compute_field_value method that processes action rules. """ # # Note: This is to catch updates made by field recomputations. # def _compute_field_value(self, field): # determine fields that may trigger an action stored_fields = [f for f in self.pool.field_computed[field] if f.store] if not any(stored_fields): return _compute_field_value.origin(self, field) # retrieve the action rules to possibly execute actions = self.env['base.automation']._get_actions(self, ['on_write', 'on_create_or_write']) records = self.filtered('id').with_env(actions.env) if not (actions and records): _compute_field_value.origin(self, field) return True # check preconditions on records pre = {action: action._filter_pre(records) for action in actions} # read old values before the update old_values = { old_vals.pop('id'): old_vals for old_vals in (records.read([f.name for f in stored_fields])) } # call original method _compute_field_value.origin(self, field) # check postconditions, and execute actions on the records that satisfy them for action in actions.with_context(old_values=old_values): records, domain_post = action._filter_post_export_domain(pre[action]) action._process(records, domain_post=domain_post) return True return _compute_field_value def make_unlink(): """ Instanciate an unlink method that processes action rules. """ def unlink(self, **kwargs): # retrieve the action rules to possibly execute actions = self.env['base.automation']._get_actions(self, ['on_unlink']) records = self.with_env(actions.env) # check conditions, and execute actions on the records that satisfy them for action in actions: action._process(action._filter_post(records)) # call original method return unlink.origin(self, **kwargs) return unlink def make_onchange(action_rule_id): """ Instanciate an onchange method for the given action rule. """ def base_automation_onchange(self): action_rule = self.env['base.automation'].browse(action_rule_id) result = {} server_action = action_rule.sudo().action_server_id.with_context( active_model=self._name, active_id=self._origin.id, active_ids=self._origin.ids, onchange_self=self, ) try: res = server_action.run() except Exception as e: action_rule._add_postmortem_action(e) raise e if res: if 'value' in res: res['value'].pop('id', None) self.update({key: val for key, val in res['value'].items() if key in self._fields}) if 'domain' in res: result.setdefault('domain', {}).update(res['domain']) if 'warning' in res: result['warning'] = res['warning'] return result return base_automation_onchange patched_models = defaultdict(set) def patch(model, name, method): """ Patch method `name` on `model`, unless it has been patched already. """ if model not in patched_models[name]: patched_models[name].add(model) ModelClass = type(model) origin = getattr(ModelClass, name) method.origin = origin wrapped = api.propagate(origin, method) wrapped.origin = origin setattr(ModelClass, name, wrapped) # retrieve all actions, and patch their corresponding model for action_rule in self.with_context({}).search([]): Model = self.env.get(action_rule.model_name) # Do not crash if the model of the base_action_rule was uninstalled if Model is None: _logger.warning("Action rule with ID %d depends on model %s" % (action_rule.id, action_rule.model_name)) continue if action_rule.trigger == 'on_create': patch(Model, 'create', make_create()) elif action_rule.trigger == 'on_create_or_write': patch(Model, 'create', make_create()) patch(Model, 'write', make_write()) patch(Model, '_compute_field_value', make_compute_field_value()) elif action_rule.trigger == 'on_write': patch(Model, 'write', make_write()) patch(Model, '_compute_field_value', make_compute_field_value()) elif action_rule.trigger == 'on_unlink': patch(Model, 'unlink', make_unlink()) elif action_rule.trigger == 'on_change': # register an onchange method for the action_rule method = make_onchange(action_rule.id) for field in action_rule.on_change_field_ids: Model._onchange_methods[field.name].append(method) def _unregister_hook(self): """ Remove the patches installed by _register_hook() """ NAMES = ['create', 'write', '_compute_field_value', 'unlink', '_onchange_methods'] for Model in self.env.registry.values(): for name in NAMES: try: delattr(Model, name) except AttributeError: pass @api.model def _check_delay(self, action, record, record_dt): if action.trg_date_calendar_id and action.trg_date_range_type == 'day': return action.trg_date_calendar_id.plan_days( action.trg_date_range, fields.Datetime.from_string(record_dt), compute_leaves=True, ) else: delay = DATE_RANGE_FUNCTION[action.trg_date_range_type](action.trg_date_range) return fields.Datetime.from_string(record_dt) + delay @api.model def _check(self, automatic=False, use_new_cursor=False): """ This Function is called by scheduler. """ if '__action_done' not in self._context: self = self.with_context(__action_done={}) # retrieve all the action rules to run based on a timed condition eval_context = self._get_eval_context() for action in self.with_context(active_test=True).search([('trigger', '=', 'on_time')]): _logger.info("Starting time-based automated action `%s`.", action.name) last_run = fields.Datetime.from_string(action.last_run) or datetime.datetime.utcfromtimestamp(0) # retrieve all the records that satisfy the action's condition domain = [] context = dict(self._context) if action.filter_domain: domain = safe_eval.safe_eval(action.filter_domain, eval_context) records = self.env[action.model_name].with_context(context).search(domain) # determine when action should occur for the records if action.trg_date_id.name == 'date_action_last' and 'create_date' in records._fields: get_record_dt = lambda record: record[action.trg_date_id.name] or record.create_date else: get_record_dt = lambda record: record[action.trg_date_id.name] # process action on the records that should be executed now = datetime.datetime.now() for record in records: record_dt = get_record_dt(record) if not record_dt: continue action_dt = self._check_delay(action, record, record_dt) if last_run <= action_dt < now: try: action._process(record) except Exception: _logger.error(traceback.format_exc()) action.write({'last_run': now.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) _logger.info("Time-based automated action `%s` done.", action.name) if automatic: # auto-commit for batch processing self._cr.commit()
46.181818
24,892
345
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 ServerAction(models.Model): _inherit = "ir.actions.server" usage = fields.Selection(selection_add=[ ('base_automation', 'Automated Action') ], ondelete={'base_automation': 'cascade'})
28.75
345
1,230
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Testing the Import/Export invoices with UBL/CII", 'version': '1.0', 'category': 'Hidden/Tests', 'description': """ This module tests the module 'account_edi_ubl_cii', it is separated since dependencies to some localizations were required. Its name begins with 'l10n' to not overload runbot. The test files are separated by sources, they were taken from: * the factur-x doc (form the FNFE) * the peppol-bis-invoice-3 doc (the github repository: https://github.com/OpenPEPPOL/peppol-bis-invoice-3/tree/master/rules/examples contains examples) * odoo, these files pass all validation tests (using ecosio or the FNFE validator) We test that the external examples are correctly imported (currency, total amount and total tax match). We also test that generating xml from odoo with given parameters gives exactly the same xml as the expected, valid ones. """, 'depends': [ 'l10n_generic_coa', 'account_edi_ubl_cii', 'l10n_fr', 'l10n_be', 'l10n_de', 'l10n_nl_edi', ], 'installable': True, 'application': False, 'auto_install': False, 'license': 'LGPL-3', }
38.4375
1,230
21,493
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.l10n_account_edi_ubl_cii_tests.tests.common import TestUBLCommon from odoo.tests import tagged import base64 @tagged('post_install_l10n', 'post_install', '-at_install') class TestUBLBE(TestUBLCommon): @classmethod def setUpClass(cls, chart_template_ref="l10n_be.l10nbe_chart_template", edi_format_ref="account_edi_ubl_cii.ubl_bis3", ): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) # seller cls.partner_1 = cls.env['res.partner'].create({ 'name': "partner_1", 'street': "Chaussée de Namur 40", 'zip': "1367", 'city': "Ramillies", 'vat': 'BE0202239951', 'country_id': cls.env.ref('base.be').id, 'bank_ids': [(0, 0, {'acc_number': 'BE15001559627230'})], 'ref': 'ref_partner_1', }) # buyer cls.partner_2 = cls.env['res.partner'].create({ 'name': "partner_2", 'street': "Rue des Bourlottes 9", 'zip': "1367", 'city': "Ramillies", 'vat': 'BE0477472701', 'country_id': cls.env.ref('base.be').id, 'bank_ids': [(0, 0, {'acc_number': 'BE90735788866632'})], 'ref': 'ref_partner_2', }) cls.tax_25 = cls.env['account.tax'].create({ 'name': 'tax_25', 'amount_type': 'percent', 'amount': 25, 'type_tax_use': 'purchase', 'country_id': cls.env.ref('base.be').id, }) cls.tax_21 = cls.env['account.tax'].create({ 'name': 'tax_21', 'amount_type': 'percent', 'amount': 21, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.be').id, 'sequence': 10, }) cls.tax_15 = cls.env['account.tax'].create({ 'name': 'tax_15', 'amount_type': 'percent', 'amount': 15, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.be').id, }) cls.tax_12 = cls.env['account.tax'].create({ 'name': 'tax_12', 'amount_type': 'percent', 'amount': 12, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.be').id, }) cls.acc_bank = cls.env['res.partner.bank'].create({ 'acc_number': 'BE15001559627231', 'partner_id': cls.company_data['company'].partner_id.id, }) cls.invoice = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': cls.journal.id, 'partner_id': cls.partner_1.id, 'partner_bank_id': cls.acc_bank, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, { 'product_id': cls.product_a.id, 'product_uom_id': cls.env.ref('uom.product_uom_dozen').id, 'price_unit': 275.0, 'quantity': 5, 'discount': 20.0, 'tax_ids': [(6, 0, cls.tax_21.ids)], })], }) @classmethod def setup_company_data(cls, company_name, chart_template): # OVERRIDE # to force the company to be belgian res = super().setup_company_data( company_name, chart_template=chart_template, country_id=cls.env.ref("base.be").id, vat="BE0246697724") return res #################################################### # Test export - import #################################################### def test_export_import_invoice(self): invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_21.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( invoice, xpaths=''' <xpath expr="./*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][1]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][2]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][3]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='PaymentMeans']/*[local-name()='PaymentID']" position="replace"> <PaymentID>___ignore___</PaymentID> </xpath> ''', expected_file='from_odoo/bis3_out_invoice.xml', ) self.assertEqual(xml_filename[-12:], "ubl_bis3.xml") # ensure we test the right format ! self._assert_imported_invoice_from_etree(invoice, xml_etree, xml_filename) def test_export_import_refund(self): refund = self._generate_move( self.partner_1, self.partner_2, move_type='out_refund', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_21.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( refund, xpaths=''' <xpath expr="./*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr="./*[local-name()='PaymentMeans']/*[local-name()='PaymentID']" position="replace"> <PaymentID>___ignore___</PaymentID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][1]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][2]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][3]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> ''', expected_file='from_odoo/bis3_out_refund.xml', ) self.assertEqual(xml_filename[-12:], "ubl_bis3.xml") self._assert_imported_invoice_from_etree(refund, xml_etree, xml_filename) def test_encoding_in_attachment_ubl(self): self._test_encoding_in_attachment('ubl_bis3', 'INV_2017_00002_ubl_bis3.xml') def test_sending_to_public_admin(self): """ A public administration has no VAT, but has an arbitrary number (see: https://pch.gouvernement.lu/fr/peppol.html). When a partner has no VAT, the node PartyTaxScheme should not appear. NB: The `EndpointID` node should be filled with this arbitrary number, that is why `l10n_lu_peppol_id` module was created. However we cannot use it here because it would require adding it to the dependencies of `l10n_account_edi_ubl_cii_tests` in stable. """ self.partner_2.vat = None invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2, 'price_unit': 100, 'tax_ids': [(6, 0, self.tax_21.ids)], } ], ) self._assert_invoice_attachment( invoice, xpaths=''' <xpath expr="./*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr="./*[local-name()='PaymentMeans']/*[local-name()='PaymentID']" position="replace"> <PaymentID>___ignore___</PaymentID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][1]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> ''', expected_file='from_odoo/bis3_out_invoice_public_admin.xml', ) def test_rounding_price_unit(self): """ OpenPeppol states that: * All document level amounts shall be rounded to two decimals for accounting * Invoice line net amount shall be rounded to two decimals See: https://docs.peppol.eu/poacc/billing/3.0/bis/#_rounding Do not round the unit prices. It allows to obtain the correct line amounts when prices have more than 2 digits. """ # Set the allowed number of digits for the price_unit decimal_precision = self.env['decimal.precision'].search([('name', '=', 'Product Price')], limit=1) self.assertTrue(bool(decimal_precision), "The decimal precision for Product Price is required for this test") decimal_precision.digits = 4 invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 10000, 'price_unit': 0.4567, 'tax_ids': [(6, 0, self.tax_21.ids)], } ], ) self._assert_invoice_attachment(invoice, None, 'from_odoo/bis3_out_invoice_rounding.xml') def test_export_with_fixed_taxes_case1(self): # CASE 1: simple invoice with a recupel tax invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 99, 'tax_ids': [(6, 0, [self.recupel.id, self.tax_21.id])], } ], ) self.assertEqual(invoice.amount_total, 121) self._assert_invoice_attachment(invoice, None, 'from_odoo/bis3_ecotaxes_case1.xml') def test_export_with_fixed_taxes_case2(self): # CASE 2: Same but with several ecotaxes invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 98, 'tax_ids': [(6, 0, [self.recupel.id, self.auvibel.id, self.tax_21.id])], } ], ) self.assertEqual(invoice.amount_total, 121) self._assert_invoice_attachment(invoice, None, 'from_odoo/bis3_ecotaxes_case2.xml') def test_export_with_fixed_taxes_case3(self): # CASE 3: same as Case 1 but taxes are Price Included self.recupel.price_include = True self.tax_21.price_include = True # Price TTC = 121 = (99 + 1 ) * 1.21 invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 121, 'tax_ids': [(6, 0, [self.recupel.id, self.tax_21.id])], } ], ) self.assertEqual(invoice.amount_total, 121) self._assert_invoice_attachment(invoice, None, 'from_odoo/bis3_ecotaxes_case3.xml') #################################################### # Test import #################################################### def test_import_partner_ubl(self): """ Given an invoice where partner_1 is the vendor and partner_2 is the customer with an EDI attachment. * Uploading the attachment as an invoice should create an invoice with the buyer = partner_2. * Uploading the attachment as a vendor bill should create a bill with the vendor = partner_1. """ invoice = self._generate_move( seller=self.partner_1, buyer=self.partner_2, move_type='out_invoice', invoice_line_ids=[{'product_id': self.product_a.id}], ) new_invoice = self._import_invoice_attachment(invoice, 'ubl_bis3', self.company_data['default_journal_sale']) self.assertEqual(self.partner_2, new_invoice.partner_id) new_invoice = self._import_invoice_attachment(invoice, 'ubl_bis3', self.company_data['default_journal_purchase']) self.assertEqual(self.partner_1, new_invoice.partner_id) def test_import_and_create_partner_ubl(self): """ Tests whether the partner is created at import if no match is found when decoding the EDI attachment """ partner_vals = { 'name': "Buyer", 'mail': "[email protected]", 'phone': "1111", 'vat': "BE980737405", } # assert there is no matching partner partner_match = self.env['account.edi.format']._retrieve_partner(**partner_vals) self.assertFalse(partner_match) # Import attachment as an invoice invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': self.company_data['default_journal_sale'].id, }) self.update_invoice_from_file( module_name='l10n_account_edi_ubl_cii_tests', subfolder='tests/test_files/from_odoo', filename='ubl_test_import_partner.xml', invoice=invoice) # assert a new partner has been created partner_vals['email'] = partner_vals.pop('mail') self.assertRecordValues(invoice.partner_id, [partner_vals]) def test_import_export_invoice_xml(self): """ Test whether the elements only specific to ubl_be are correctly exported and imported in the xml file """ self.invoice.action_post() attachment = self.invoice._get_edi_attachment(self.edi_format) self.assertTrue(attachment) xml_content = base64.b64decode(attachment.with_context(bin_size=False).datas) xml_etree = self.get_xml_tree_from_string(xml_content) self.assertEqual( xml_etree.find('{*}ProfileID').text, 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0' ) self.assertEqual( xml_etree.find('{*}CustomizationID').text, 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0' ) # Export: in bis3, under Country, the Name element should not appear, but IdentificationCode still should self.assertIsNotNone(xml_etree.find('.//{*}Country/{*}IdentificationCode')) self.assertIsNone(xml_etree.find('.//{*}Country/{*}Name')) # Import: created_bill = self.env['account.move'].create({'move_type': 'in_invoice'}) created_bill.message_post(attachment_ids=[attachment.id]) self.assertTrue(created_bill) def test_import_invoice_xml(self): self._assert_imported_invoice_from_file(subfolder='tests/test_files/from_odoo', filename='bis3_out_invoice.xml', amount_total=3164.22, amount_tax=482.22, list_line_subtotals=[1782, 1000, -100], currency_id=self.currency_data['currency'].id) def test_import_invoice_xml_open_peppol_examples(self): # Source: https://github.com/OpenPEPPOL/peppol-bis-invoice-3/tree/master/rules/examples subfolder = 'tests/test_files/from_peppol-bis-invoice-3_doc' # source: Allowance-example.xml self._assert_imported_invoice_from_file(subfolder=subfolder, filename='bis3_allowance.xml', amount_total=7125, amount_tax=1225, list_line_subtotals=[200, -200, 4000, 1000, 900]) # source: base-creditnote-correction.xml self._assert_imported_invoice_from_file(subfolder=subfolder, filename='bis3_credit_note.xml', amount_total=1656.25, amount_tax=331.25, list_line_subtotals=[25, 2800, -1500], move_type='in_refund') # source: base-negative-inv-correction.xml self._assert_imported_invoice_from_file(subfolder=subfolder, filename='bis3_invoice_negative_amounts.xml', amount_total=1656.25, amount_tax=331.25, list_line_subtotals=[25, 2800, -1500], move_type='in_refund') # source: vat-category-E.xml self._assert_imported_invoice_from_file(subfolder=subfolder, filename='bis3_tax_exempt_gbp.xml', amount_total=1200, amount_tax=0, list_line_subtotals=[1200], currency_id=self.env.ref('base.GBP').id) def test_import_existing_invoice_flip_move_type(self): """ Tests whether the move_type of an existing invoice can be flipped when importing an attachment For instance: with an email alias to create account_move, first the move is created (using alias_defaults, which contains move_type = 'out_invoice') then the attachment is decoded, if it represents a credit note, the move type needs to be changed to 'out_refund' """ invoice = self.env['account.move'].create({'move_type': 'out_invoice'}) self.update_invoice_from_file( 'l10n_account_edi_ubl_cii_tests', 'tests/test_files/from_odoo', 'bis3_out_refund.xml', invoice, ) self.assertRecordValues(invoice, [{'move_type': 'out_refund', 'amount_total': 3164.22}]) def test_import_fixed_taxes(self): """ Tests whether we correctly decode the xml attachments created using fixed taxes. See the tests above to create these xml attachments ('test_export_with_fixed_taxes_case_[X]'). NB: use move_type = 'out_invoice' s.t. we can retrieve the taxes used to create the invoices. """ subfolder = "tests/test_files/from_odoo" # The tax 21% from l10n_be is retrieved since it's a duplicate of self.tax_21 tax_21 = self.env.ref(f'l10n_be.{self.env.company.id}_attn_VAT-OUT-21-L') self._assert_imported_invoice_from_file( subfolder=subfolder, filename='bis3_ecotaxes_case1.xml', amount_total=121, amount_tax=22, list_line_subtotals=[99], currency_id=self.currency_data['currency'].id, list_line_price_unit=[99], list_line_discount=[0], list_line_taxes=[tax_21+self.recupel], move_type='out_invoice', ) self._assert_imported_invoice_from_file( subfolder=subfolder, filename='bis3_ecotaxes_case2.xml', amount_total=121, amount_tax=23, list_line_subtotals=[98], currency_id=self.currency_data['currency'].id, list_line_price_unit=[98], list_line_discount=[0], list_line_taxes=[tax_21+self.recupel+self.auvibel], move_type='out_invoice', ) self._assert_imported_invoice_from_file( subfolder=subfolder, filename='bis3_ecotaxes_case3.xml', amount_total=121, amount_tax=22, list_line_subtotals=[99], currency_id=self.currency_data['currency'].id, list_line_price_unit=[99], list_line_discount=[0], list_line_taxes=[tax_21+self.recupel], move_type='out_invoice', )
44.681913
21,492
9,724
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.l10n_account_edi_ubl_cii_tests.tests.common import TestUBLCommon from odoo.tests import tagged import base64 @tagged('post_install_l10n', 'post_install', '-at_install') class TestUBLDE(TestUBLCommon): @classmethod def setUpClass(cls, chart_template_ref="l10n_de_skr03.l10n_de_chart_template", edi_format_ref="account_edi_ubl_cii.ubl_de", ): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) cls.partner_1 = cls.env['res.partner'].create({ 'name': "partner_1", 'street': "Legoland-Allee 3", 'zip': "89312", 'city': "Günzburg", 'vat': 'DE257486969', 'phone': '+49 180 6 225789', 'email': '[email protected]', 'country_id': cls.env.ref('base.de').id, 'bank_ids': [(0, 0, {'acc_number': 'DE48500105176424548921'})], 'ref': 'ref_partner_1', }) cls.partner_2 = cls.env['res.partner'].create({ 'name': "partner_2", 'street': "Europa-Park-Straße 2", 'zip': "77977", 'city': "Rust", 'vat': 'DE186775212', 'country_id': cls.env.ref('base.de').id, 'bank_ids': [(0, 0, {'acc_number': 'DE50500105175653254743'})], 'ref': 'ref_partner_2', }) cls.tax_19 = cls.env['account.tax'].create({ 'name': 'tax_19', 'amount_type': 'percent', 'amount': 19, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.de').id, }) cls.tax_7 = cls.env['account.tax'].create({ 'name': 'tax_7', 'amount_type': 'percent', 'amount': 7, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.de').id, }) @classmethod def setup_company_data(cls, company_name, chart_template): # OVERRIDE # to force the company to be german + add phone and email res = super().setup_company_data( company_name, chart_template=chart_template, country_id=cls.env.ref("base.de").id, phone="+49(0) 30 227-0", email="test@xrechnung@com", ) return res #################################################### # Test export - import #################################################### def test_export_import_invoice(self): invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_19.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( invoice, xpaths=''' <xpath expr="./*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][1]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][2]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][3]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='PaymentMeans']/*[local-name()='PaymentID']" position="replace"> <PaymentID>___ignore___</PaymentID> </xpath> ''', expected_file='from_odoo/xrechnung_ubl_out_invoice.xml', ) self.assertEqual(xml_filename[-10:], "ubl_de.xml") self._assert_imported_invoice_from_etree(invoice, xml_etree, xml_filename) def test_export_import_refund(self): refund = self._generate_move( self.partner_1, self.partner_2, move_type='out_refund', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_19.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( refund, xpaths=''' <xpath expr="./*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][1]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][2]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][3]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='PaymentMeans']/*[local-name()='PaymentID']" position="replace"> <PaymentID>___ignore___</PaymentID> </xpath> ''', expected_file='from_odoo/xrechnung_ubl_out_refund.xml', ) self.assertEqual(xml_filename[-10:], "ubl_de.xml") self._assert_imported_invoice_from_etree(refund, xml_etree, xml_filename) #################################################### # Test import #################################################### def test_import_invoice_xml(self): self._assert_imported_invoice_from_file(subfolder='tests/test_files/from_odoo', filename='xrechnung_ubl_out_invoice.xml', amount_total=3083.58, amount_tax=401.58, list_line_subtotals=[1782, 1000, -100], currency_id=self.currency_data['currency'].id) def test_import_export_invoice_xml(self): """ Test whether the elements which are only specific to ubl_de are correctly exported and imported in the xml file """ acc_bank = self.env['res.partner.bank'].create({ 'acc_number': 'BE15001559627232', 'partner_id': self.company_data['company'].partner_id.id, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': self.journal.id, 'partner_id': self.partner_1.id, 'partner_bank_id': acc_bank, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'currency_id': self.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 275.0, 'quantity': 5, 'discount': 20.0, 'tax_ids': [(6, 0, self.tax_19.ids)], })], }) partner = invoice.commercial_partner_id invoice.action_post() attachment = invoice._get_edi_attachment(self.edi_format) self.assertTrue(attachment) xml_content = base64.b64decode(attachment.with_context(bin_size=False).datas) xml_etree = self.get_xml_tree_from_string(xml_content) # Export: BuyerReference is in the out_invoice xml self.assertEqual(xml_etree.find('{*}BuyerReference').text, partner.ref) self.assertEqual( xml_etree.find('{*}CustomizationID').text, 'urn:cen.eu:en16931:2017#compliant#urn:xoev-de:kosit:standard:xrechnung_2.2#conformant#urn:xoev-de:kosit:extension:xrechnung_2.2' ) created_bill = self.env['account.move'].create({'move_type': 'in_invoice'}) created_bill.message_post(attachment_ids=[attachment.id]) self.assertTrue(created_bill)
41.547009
9,722
8,472
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.l10n_account_edi_ubl_cii_tests.tests.common import TestUBLCommon from odoo.tests import tagged @tagged('post_install_l10n', 'post_install', '-at_install') class TestUBLNL(TestUBLCommon): @classmethod def setUpClass(cls, chart_template_ref="l10n_nl.l10nnl_chart_template", edi_format_ref="l10n_nl_edi.edi_nlcius_1", ): """ this test will fail if l10n_nl_edi is not installed. In order not to duplicate the account.edi.format already installed, we use the existing ones (comprising l10n_nl_edi.nlcius_1). """ super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) cls.partner_1 = cls.env['res.partner'].create({ 'name': "partner_1", 'street': "Kunststraat, 3", 'zip': "1000", 'city': "Amsterdam", 'vat': 'NL000099998B57', 'phone': '+31 180 6 225789', 'email': '[email protected]', 'country_id': cls.env.ref('base.nl').id, 'bank_ids': [(0, 0, {'acc_number': 'NL000099998B57'})], 'l10n_nl_kvk': '77777677', 'ref': 'ref_partner_1', }) cls.partner_2 = cls.env['res.partner'].create({ 'name': "partner_2", 'street': "Europaweg, 2", 'zip': "1200", 'city': "Rotterdam", 'vat': 'NL41452B11', 'country_id': cls.env.ref('base.nl').id, 'bank_ids': [(0, 0, {'acc_number': 'NL93999574162167'})], 'l10n_nl_kvk': '1234567', 'ref': 'ref_partner_2', }) cls.tax_19 = cls.env['account.tax'].create({ 'name': 'tax_19', 'amount_type': 'percent', 'amount': 19, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.nl').id, }) cls.tax_7 = cls.env['account.tax'].create({ 'name': 'tax_7', 'amount_type': 'percent', 'amount': 7, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.nl').id, }) cls.tax_19_purchase = cls.env['account.tax'].create({ 'name': 'tax_19', 'amount_type': 'percent', 'amount': 19, 'type_tax_use': 'purchase', 'country_id': cls.env.ref('base.nl').id, }) cls.tax_7_purchase = cls.env['account.tax'].create({ 'name': 'tax_7', 'amount_type': 'percent', 'amount': 7, 'type_tax_use': 'purchase', 'country_id': cls.env.ref('base.nl').id, }) @classmethod def setup_company_data(cls, company_name, chart_template): # OVERRIDE # to force the company to be dutch res = super().setup_company_data( company_name, chart_template=chart_template, country_id=cls.env.ref("base.nl").id, ) return res #################################################### # Test export - import #################################################### def test_export_import_invoice(self): invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_19.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( invoice, xpaths=''' <xpath expr="./*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][1]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][2]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='InvoiceLine'][3]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='PaymentMeans']/*[local-name()='PaymentID']" position="replace"> <PaymentID>___ignore___</PaymentID> </xpath> ''', expected_file='from_odoo/nlcius_out_invoice.xml', ) self.assertEqual(xml_filename[-10:], "nlcius.xml") self._assert_imported_invoice_from_etree(invoice, xml_etree, xml_filename) def test_export_import_refund(self): refund = self._generate_move( self.partner_1, self.partner_2, move_type='out_refund', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_19.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_7.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( refund, xpaths=''' <xpath expr="./*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][1]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][2]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='CreditNoteLine'][3]/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='PaymentMeans']/*[local-name()='PaymentID']" position="replace"> <PaymentID>___ignore___</PaymentID> </xpath> ''', expected_file='from_odoo/nlcius_out_refund.xml', ) self.assertEqual(xml_filename[-10:], "nlcius.xml") self._assert_imported_invoice_from_etree(refund, xml_etree, xml_filename) #################################################### # Test import #################################################### def test_import_invoice_xml(self): # test files https://github.com/peppolautoriteit-nl/validation ? self._assert_imported_invoice_from_file(subfolder='tests/test_files/from_odoo', filename='nlcius_out_invoice.xml', amount_total=3083.58, amount_tax=401.58, list_line_subtotals=[1782, 1000, -100], currency_id=self.currency_data['currency'].id)
40.535885
8,472
9,976
py
PYTHON
15.0
# -*- coding: utf-8 -*- import base64 from freezegun import freeze_time from odoo.addons.account_edi.tests.common import AccountEdiTestCommon from odoo import fields from odoo.modules.module import get_resource_path from odoo.tests import tagged from lxml import etree @tagged('post_install_l10n', 'post_install', '-at_install') class TestUBLCommon(AccountEdiTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None, edi_format_ref=None): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) # Ensure the testing currency is using a valid ISO code. real_usd = cls.env.ref('base.USD') real_usd.name = 'FUSD' real_usd.flush(['name']) cls.currency_data['currency'].name = 'USD' # remove this tax, otherwise, at import, this tax with children taxes can be selected and the total is wrong cls.tax_armageddon.children_tax_ids.unlink() cls.tax_armageddon.unlink() # Fixed Taxes cls.recupel = cls.env['account.tax'].create({ 'name': "RECUPEL", 'amount_type': 'fixed', 'amount': 1, 'include_base_amount': True, 'sequence': 1, }) cls.auvibel = cls.env['account.tax'].create({ 'name': "AUVIBEL", 'amount_type': 'fixed', 'amount': 1, 'include_base_amount': True, 'sequence': 2, }) @classmethod def setup_company_data(cls, company_name, chart_template=None, **kwargs): # OVERRIDE to force the company with EUR currency. eur = cls.env.ref('base.EUR') if not eur.active: eur.active = True res = super().setup_company_data(company_name, chart_template=chart_template, **kwargs) res['company'].currency_id = eur return res def assert_same_invoice(self, invoice1, invoice2, **invoice_kwargs): self.assertEqual(len(invoice1.invoice_line_ids), len(invoice2.invoice_line_ids)) self.assertRecordValues(invoice2, [{ 'partner_id': invoice1.partner_id.id, 'invoice_date': fields.Date.from_string(invoice1.date), 'currency_id': invoice1.currency_id.id, 'amount_untaxed': invoice1.amount_untaxed, 'amount_tax': invoice1.amount_tax, 'amount_total': invoice1.amount_total, **invoice_kwargs, }]) default_invoice_line_kwargs_list = [{}] * len(invoice1.invoice_line_ids) invoice_line_kwargs_list = invoice_kwargs.get('invoice_line_ids', default_invoice_line_kwargs_list) self.assertRecordValues(invoice2.invoice_line_ids, [{ 'quantity': line.quantity, 'price_unit': line.price_unit, 'discount': line.discount, 'product_id': line.product_id.id, 'product_uom_id': line.product_uom_id.id, **invoice_line_kwargs, } for line, invoice_line_kwargs in zip(invoice1.invoice_line_ids, invoice_line_kwargs_list)]) # ------------------------------------------------------------------------- # IMPORT HELPERS # ------------------------------------------------------------------------- @freeze_time('2017-01-01') def _assert_imported_invoice_from_etree(self, invoice, xml_etree, xml_filename): """ Create an account.move directly from an xml file, asserts the invoice obtained is the same as the expected invoice. """ new_invoice = self.edi_format._create_invoice_from_xml_tree( xml_filename, xml_etree, # /!\ use the same journal as the invoice's one to import the xml ! invoice.journal_id, ) self.assertTrue(new_invoice) self.assert_same_invoice(invoice, new_invoice) def _assert_imported_invoice_from_file(self, subfolder, filename, amount_total, amount_tax, list_line_subtotals, list_line_price_unit=None, list_line_discount=None, list_line_taxes=None, move_type='in_invoice', currency_id=None): """ Create an empty account.move, update the file to fill its fields, asserts the currency, total and tax amounts are as expected. """ if not currency_id: currency_id = self.env.ref('base.EUR').id # Create empty account.move, then update a file if move_type == 'in_invoice': invoice = self._create_empty_vendor_bill() elif move_type == 'out_invoice': invoice = self.env['account.move'].create({ 'move_type': move_type, 'journal_id': self.company_data['default_journal_sale'].id, }) else: invoice = self.env['account.move'].create({ 'move_type': move_type, 'journal_id': self.company_data['default_journal_purchase'].id, }) invoice_count = len(self.env['account.move'].search([])) # Import the file to fill the empty invoice self.update_invoice_from_file('l10n_account_edi_ubl_cii_tests', subfolder, filename, invoice) # Checks self.assertEqual(len(self.env['account.move'].search([])), invoice_count) self.assertRecordValues(invoice, [{ 'amount_total': amount_total, 'amount_tax': amount_tax, 'currency_id': currency_id, }]) if list_line_price_unit: self.assertEqual(invoice.invoice_line_ids.mapped('price_unit'), list_line_price_unit) if list_line_discount: self.assertEqual(invoice.invoice_line_ids.mapped('discount'), list_line_discount) if list_line_taxes: for line, taxes in zip(invoice.invoice_line_ids, list_line_taxes): self.assertEqual(line.tax_ids, taxes) self.assertEqual(invoice.invoice_line_ids.mapped('price_subtotal'), list_line_subtotals) # ------------------------------------------------------------------------- # EXPORT HELPERS # ------------------------------------------------------------------------- @freeze_time('2017-01-01') def _generate_move(self, seller, buyer, **invoice_kwargs): """ Create and post an account.move. """ # Setup the seller. self.env.company.write({ 'partner_id': seller.id, 'name': seller.name, 'street': seller.street, 'zip': seller.zip, 'city': seller.city, 'vat': seller.vat, 'country_id': seller.country_id.id, }) move_type = invoice_kwargs['move_type'] account_move = self.env['account.move'].create({ 'partner_id': buyer.id, 'partner_bank_id': (seller if move_type == 'out_invoice' else buyer).bank_ids[:1].id, 'invoice_payment_term_id': self.pay_terms_b.id, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'currency_id': self.currency_data['currency'].id, 'narration': 'test narration', 'ref': 'ref_move', **invoice_kwargs, 'invoice_line_ids': [ (0, 0, { 'sequence': i, **invoice_line_kwargs, }) for i, invoice_line_kwargs in enumerate(invoice_kwargs.get('invoice_line_ids', [])) ], }) # this is needed for formats not enabled by default on the journal account_move.journal_id.edi_format_ids += self.edi_format account_move.action_post() return account_move def _assert_invoice_attachment(self, invoice, xpaths, expected_file): """ Get attachment from a posted account.move, and asserts it's the same as the expected xml file. """ attachment = invoice._get_edi_attachment(self.edi_format) self.assertTrue(attachment) xml_filename = attachment.name xml_content = base64.b64decode(attachment.with_context(bin_size=False).datas) xml_etree = self.get_xml_tree_from_string(xml_content) expected_file_path = get_resource_path('l10n_account_edi_ubl_cii_tests', 'tests/test_files', expected_file) expected_etree = etree.parse(expected_file_path).getroot() modified_etree = self.with_applied_xpath( expected_etree, xpaths ) self.assertXmlTreeEqual( xml_etree, modified_etree, ) return xml_etree, xml_filename def _import_invoice_attachment(self, invoice, edi_code, journal): """ Extract the attachment from the invoice and import it on the given journal. """ # Get the attachment from the invoice edi_attachment = invoice.edi_document_ids.filtered( lambda doc: doc.edi_format_id.code == edi_code).attachment_id edi_etree = self.get_xml_tree_from_string(edi_attachment.raw) # import the attachment and return the resulting invoice return self.edi_format._create_invoice_from_xml_tree( filename='test_filename', tree=edi_etree, journal=journal, ) def _test_encoding_in_attachment(self, edi_code, filename): """ Generate an invoice, assert that the tag '<?xml version='1.0' encoding='UTF-8'?>' is present in the attachment """ invoice = self._generate_move( seller=self.partner_1, buyer=self.partner_2, move_type='out_invoice', invoice_line_ids=[{'product_id': self.product_a.id}], ) edi_attachment = invoice.edi_document_ids.filtered( lambda doc: doc.edi_format_id.code == edi_code).attachment_id self.assertEqual(edi_attachment.name, filename) self.assertIn(b"<?xml version='1.0' encoding='UTF-8'?>", edi_attachment.raw)
41.394191
9,976
20,577
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.l10n_account_edi_ubl_cii_tests.tests.common import TestUBLCommon from odoo.tests import tagged @tagged('post_install_l10n', 'post_install', '-at_install') class TestCIIFR(TestUBLCommon): @classmethod def setUpClass(cls, chart_template_ref="l10n_fr.l10n_fr_pcg_chart_template", edi_format_ref="account_edi_facturx.edi_facturx_1_0_05", ): """ this test will fail if account_edi_facturx is not installed. In order not to duplicate the account.edi.format already installed, we use the existing ones (comprising account_edi_facturx.facturx_1_0_05). """ super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) cls.partner_1 = cls.env['res.partner'].create({ 'name': "partner_1", 'street': "Rue Jean Jaurès, 42", 'zip': "75000", 'city': "Paris", 'vat': 'FR05677404089', 'country_id': cls.env.ref('base.fr').id, 'bank_ids': [(0, 0, {'acc_number': 'FR15001559627230'})], 'phone': '+1 (650) 555-0111', 'email': "[email protected]", 'ref': 'ref_partner_1', }) cls.partner_2 = cls.env['res.partner'].create({ 'name': "partner_2", 'street': "Rue Charles de Gaulle", 'zip': "52330", 'city': "Colombey-les-Deux-Églises", 'vat': 'FR35562153452', 'country_id': cls.env.ref('base.fr').id, 'bank_ids': [(0, 0, {'acc_number': 'FR90735788866632'})], 'ref': 'ref_partner_2', }) cls.tax_21 = cls.env['account.tax'].create({ 'name': 'tax_21', 'amount_type': 'percent', 'amount': 21, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.fr').id, 'sequence': 10, }) cls.tax_12 = cls.env['account.tax'].create({ 'name': 'tax_12', 'amount_type': 'percent', 'amount': 12, 'type_tax_use': 'sale', 'country_id': cls.env.ref('base.fr').id, }) cls.tax_21_purchase = cls.env['account.tax'].create({ 'name': 'tax_21', 'amount_type': 'percent', 'amount': 21, 'type_tax_use': 'purchase', 'country_id': cls.env.ref('base.fr').id, }) cls.tax_12_purchase = cls.env['account.tax'].create({ 'name': 'tax_12', 'amount_type': 'percent', 'amount': 12, 'type_tax_use': 'purchase', 'country_id': cls.env.ref('base.fr').id, }) cls.tax_5_purchase = cls.env['account.tax'].create({ 'name': 'tax_5', 'amount_type': 'percent', 'amount': 5, 'type_tax_use': 'purchase', }) cls.tax_5 = cls.env['account.tax'].create({ 'name': 'tax_5', 'amount_type': 'percent', 'amount': 5, 'type_tax_use': 'sale', }) cls.tax_5_incl = cls.env['account.tax'].create({ 'name': 'tax_5_incl', 'amount_type': 'percent', 'amount': 5, 'type_tax_use': 'sale', 'price_include': True, }) @classmethod def setup_company_data(cls, company_name, chart_template): # OVERRIDE # to force the company to be french res = super().setup_company_data( company_name, chart_template=chart_template, country_id=cls.env.ref("base.fr").id, phone='+1 (650) 555-0111', # [BR-DE-6] "Seller contact telephone number" (BT-42) is required email="[email protected]", # [BR-DE-7] The element "Seller contact email address" (BT-43) is required ) return res #################################################### # Test export - import #################################################### def test_export_pdf(self): acc_bank = self.env['res.partner.bank'].create({ 'acc_number': 'FR15001559627231', 'partner_id': self.company_data['company'].partner_id.id, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': self.journal.id, 'partner_id': self.partner_1.id, 'partner_bank_id': acc_bank, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'currency_id': self.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 275.0, 'quantity': 5, 'discount': 20.0, 'tax_ids': [(6, 0, self.tax_21.ids)], })], }) invoice.action_post() pdf_attachment = invoice._get_edi_attachment(self.edi_format) self.assertEqual(pdf_attachment['name'], 'factur-x.xml') def test_export_import_invoice(self): invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_21.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( invoice, xpaths=''' <xpath expr="./*[local-name()='ExchangedDocument']/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='IssuerAssignedID']" position="replace"> <IssuerAssignedID>___ignore___</IssuerAssignedID> </xpath> <xpath expr=".//*[local-name()='PaymentReference']" position="replace"> <PaymentReference>___ignore___</PaymentReference> </xpath> ''', expected_file='from_odoo/facturx_out_invoice.xml', ) self.assertEqual(xml_filename, "factur-x.xml") self._assert_imported_invoice_from_etree(invoice, xml_etree, xml_filename) def test_export_import_refund(self): refund = self._generate_move( self.partner_1, self.partner_2, move_type='out_refund', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 2.0, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, 'price_unit': 990.0, 'discount': 10.0, 'tax_ids': [(6, 0, self.tax_21.ids)], }, { 'product_id': self.product_b.id, 'quantity': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, { 'product_id': self.product_b.id, 'quantity': -1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.tax_12.ids)], }, ], ) xml_etree, xml_filename = self._assert_invoice_attachment( refund, xpaths=''' <xpath expr="./*[local-name()='ExchangedDocument']/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='IssuerAssignedID']" position="replace"> <IssuerAssignedID>___ignore___</IssuerAssignedID> </xpath> ''', expected_file='from_odoo/facturx_out_refund.xml' ) self.assertEqual(xml_filename, "factur-x.xml") self._assert_imported_invoice_from_etree(refund, xml_etree, xml_filename) def test_export_tax_included(self): """ Tests whether the tax included price_units are correctly converted to tax excluded amounts in the exported xml """ invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 100, 'tax_ids': [(6, 0, self.tax_5_incl.ids)], }, { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 100, 'tax_ids': [(6, 0, self.tax_5.ids)], }, { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 200, 'discount': 10, 'tax_ids': [(6, 0, self.tax_5_incl.ids)], }, { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 200, 'discount': 10, 'tax_ids': [(6, 0, self.tax_5.ids)], }, ], ) self._assert_invoice_attachment( invoice, xpaths=''' <xpath expr="./*[local-name()='ExchangedDocument']/*[local-name()='ID']" position="replace"> <ID>___ignore___</ID> </xpath> <xpath expr=".//*[local-name()='IssuerAssignedID']" position="replace"> <IssuerAssignedID>___ignore___</IssuerAssignedID> </xpath> ''', expected_file='from_odoo/facturx_out_invoice_tax_incl.xml' ) def test_encoding_in_attachment_facturx(self): self._test_encoding_in_attachment('facturx_1_0_05', 'factur-x.xml') def test_export_with_fixed_taxes_case1(self): # CASE 1: simple invoice with a recupel tax invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 99, 'tax_ids': [(6, 0, [self.recupel.id, self.tax_21.id])], } ], ) self.assertEqual(invoice.amount_total, 121) self._assert_invoice_attachment(invoice, None, 'from_odoo/facturx_ecotaxes_case1.xml') def test_export_with_fixed_taxes_case2(self): # CASE 2: Same but with several ecotaxes invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 98, 'tax_ids': [(6, 0, [self.recupel.id, self.auvibel.id, self.tax_21.id])], } ], ) self.assertEqual(invoice.amount_total, 121) self._assert_invoice_attachment(invoice, None, 'from_odoo/facturx_ecotaxes_case2.xml') def test_export_with_fixed_taxes_case3(self): # CASE 3: same as Case 1 but taxes are Price Included self.recupel.price_include = True self.tax_21.price_include = True # Price TTC = 121 = (99 + 1 ) * 1.21 invoice = self._generate_move( self.partner_1, self.partner_2, move_type='out_invoice', invoice_line_ids=[ { 'product_id': self.product_a.id, 'quantity': 1, 'price_unit': 121, 'tax_ids': [(6, 0, [self.recupel.id, self.tax_21.id])], } ], ) self.assertEqual(invoice.amount_total, 121) self._assert_invoice_attachment(invoice, None, 'from_odoo/facturx_ecotaxes_case3.xml') #################################################### # Test import #################################################### def test_import_partner_facturx(self): """ Given an invoice where partner_1 is the vendor and partner_2 is the customer with an EDI attachment. * Uploading the attachment as an invoice should create an invoice with the buyer = partner_2. * Uploading the attachment as a vendor bill should create a bill with the vendor = partner_1. """ invoice = self._generate_move( seller=self.partner_1, buyer=self.partner_2, move_type='out_invoice', invoice_line_ids=[{'product_id': self.product_a.id}], ) new_invoice = self._import_invoice_attachment(invoice, 'facturx_1_0_05', self.company_data['default_journal_sale']) self.assertEqual(self.partner_2, new_invoice.partner_id) new_invoice = self._import_invoice_attachment(invoice, 'facturx_1_0_05', self.company_data['default_journal_purchase']) self.assertEqual(self.partner_1, new_invoice.partner_id) def test_import_and_create_partner_facturx(self): """ Tests whether the partner is created at import if no match is found when decoding the EDI attachment """ partner_vals = { 'name': "Buyer", 'mail': "[email protected]", 'phone': "1111", 'vat': "FR89215010646", } # assert there is no matching partner partner_match = self.env['account.edi.format']._retrieve_partner(**partner_vals) self.assertFalse(partner_match) # Import attachment as an invoice invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': self.company_data['default_journal_sale'].id, }) self.update_invoice_from_file( module_name='l10n_account_edi_ubl_cii_tests', subfolder='tests/test_files/from_odoo', filename='facturx_test_import_partner.xml', invoice=invoice) # assert a new partner has been created partner_vals['email'] = partner_vals.pop('mail') self.assertRecordValues(invoice.partner_id, [partner_vals]) def test_import_tax_included(self): """ Tests whether the tax included / tax excluded are correctly decoded when importing a document. The imported xml represents the following invoice: Description Quantity Unit Price Disc (%) Taxes Amount -------------------------------------------------------------------------------- Product A 1 100 0 5% (incl) 95.24 Product A 1 100 0 5% (not incl) 100 Product A 2 200 10 5% (incl) 171.43 Product A 2 200 10 5% (not incl) 180 ----------------------- Untaxed Amount: 546.67 Taxes: 27.334 ----------------------- Total: 574.004 """ self._assert_imported_invoice_from_file( subfolder='tests/test_files/from_odoo', filename='facturx_out_invoice_tax_incl.xml', amount_total=574.004, amount_tax=27.334, list_line_subtotals=[95.24, 100, 171.43, 180], # /!\ The price_unit are different for taxes with price_include, because all amounts in Factur-X should be # tax excluded. At import, the tax included amounts are thus converted into tax excluded ones. # Yet, the line subtotals and total will be the same (if an equivalent tax exist with price_include = False) list_line_price_unit=[95.24, 100, 190.48, 200], list_line_discount=[0, 0, 10, 10], # Again, all taxes in the imported invoice are price_include = False list_line_taxes=[self.tax_5_purchase]*4, move_type='in_invoice', currency_id=self.env['res.currency'].search([('name', '=', 'USD')], limit=1).id, ) def test_import_fnfe_examples(self): # Source: official documentation of the FNFE (subdirectory: "5. FACTUR-X 1.0.06 - Examples") subfolder = 'tests/test_files/from_factur-x_doc' # the 2 following files have the same pdf but one is labelled as an invoice and the other as a refund # source: Avoir_FR_type380_EN16931.pdf self._assert_imported_invoice_from_file(subfolder=subfolder, filename='facturx_credit_note_type380.xml', amount_total=233.47, amount_tax=14.99, list_line_subtotals=[20.48, 198], move_type='in_refund') # source: Avoir_FR_type381_EN16931.pdf self._assert_imported_invoice_from_file(subfolder=subfolder, filename='facturx_credit_note_type381.xml', amount_total=233.47, amount_tax=14.99, list_line_subtotals=[20.48, 198], move_type='in_refund') # source: Facture_F20220024_EN_16931_basis_quantity, basis quantity != 1 for one of the lines self._assert_imported_invoice_from_file(subfolder=subfolder, filename='facturx_invoice_basis_quantity.xml', amount_total=108, amount_tax=8, list_line_subtotals=[-5, 10, 60, 28, 7]) # source: Facture_F20220029_EN_16931_K.pdf, credit note labelled as an invoice with negative amounts self._assert_imported_invoice_from_file(subfolder=subfolder, filename='facturx_invoice_negative_amounts.xml', amount_total=100, amount_tax=0, list_line_subtotals=[-5, 10, 60, 30, 5], move_type='in_refund') def test_import_fixed_taxes(self): """ Tests whether we correctly decode the xml attachments created using fixed taxes. See the tests above to create these xml attachments ('test_export_with_fixed_taxes_case_[X]'). NB: use move_type = 'out_invoice' s.t. we can retrieve the taxes used to create the invoices. """ subfolder = "tests/test_files/from_odoo" self._assert_imported_invoice_from_file( subfolder=subfolder, filename='facturx_ecotaxes_case1.xml', amount_total=121, amount_tax=22, list_line_subtotals=[99], currency_id=self.currency_data['currency'].id, list_line_price_unit=[99], list_line_discount=[0], list_line_taxes=[self.tax_21+self.recupel], move_type='out_invoice', ) self._assert_imported_invoice_from_file( subfolder=subfolder, filename='facturx_ecotaxes_case2.xml', amount_total=121, amount_tax=23, list_line_subtotals=[98], currency_id=self.currency_data['currency'].id, list_line_price_unit=[98], list_line_discount=[0], list_line_taxes=[self.tax_21+self.recupel+self.auvibel], move_type='out_invoice', ) self._assert_imported_invoice_from_file( subfolder=subfolder, filename='facturx_ecotaxes_case3.xml', amount_total=121, amount_tax=22, list_line_subtotals=[99], currency_id=self.currency_data['currency'].id, list_line_price_unit=[99], list_line_discount=[0], list_line_taxes=[self.tax_21+self.recupel], move_type='out_invoice', )
43.869936
20,575
974
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Booths/Exhibitors Bridge', 'category': 'Marketing/Events', 'version': '1.0', 'summary': 'Event Booths, automatically create a sponsor.', 'description': """ Automatically create a sponsor when renting a booth. """, 'depends': ['website_event_exhibitor', 'website_event_booth'], 'data': [ 'data/event_booth_category_data.xml', 'views/event_booth_category_views.xml', 'views/event_booth_views.xml', 'views/event_booth_registration_templates.xml', 'views/event_booth_templates.xml', 'views/mail_templates.xml' ], 'auto_install': True, 'assets': { 'web.assets_frontend': [ '/website_event_booth_exhibitor/static/src/js/booth_sponsor_details.js', ], 'web.assets_tests': [ 'website_event_booth_exhibitor/static/tests/tours/website_event_booth_exhibitor.js', ], }, 'license': 'LGPL-3', }
30.4375
974
640
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.base.tests.common import HttpCaseWithUserDemo, HttpCaseWithUserPortal from odoo.tests import tagged @tagged('post_install', '-at_install') class TestWEventBoothExhibitorCommon(HttpCaseWithUserDemo, HttpCaseWithUserPortal): def test_register(self): self.browser_js( '/event', 'odoo.__DEBUG__.services["web_tour.tour"].run("webooth_exhibitor_register")', 'odoo.__DEBUG__.services["web_tour.tour"].tours.webooth_exhibitor_register.ready', login='admin' )
37.647059
640
1,014
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 EventBoothCategory(models.Model): _inherit = 'event.booth.category' @api.model def _get_exhibitor_type(self): return self.env['event.sponsor']._fields['exhibitor_type'].selection use_sponsor = fields.Boolean(string='Create Sponsor', help="If set, when booking a booth a sponsor will be created for the user") sponsor_type_id = fields.Many2one('event.sponsor.type', string='Sponsor Level') exhibitor_type = fields.Selection(_get_exhibitor_type, string='Sponsor Type') @api.onchange('use_sponsor') def _onchange_use_sponsor(self): if self.use_sponsor: if not self.sponsor_type_id: self.sponsor_type_id = self.env['event.sponsor.type'].search([], order="sequence desc", limit=1).id if not self.exhibitor_type: self.exhibitor_type = self._get_exhibitor_type()[0][0]
42.25
1,014
2,703
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 EventBooth(models.Model): _inherit = 'event.booth' use_sponsor = fields.Boolean(related='booth_category_id.use_sponsor') sponsor_type_id = fields.Many2one(related='booth_category_id.sponsor_type_id') sponsor_id = fields.Many2one('event.sponsor', string='Sponsor', copy=False) sponsor_name = fields.Char(string='Sponsor Name', related='sponsor_id.name') sponsor_email = fields.Char(string='Sponsor Email', related='sponsor_id.email') sponsor_mobile = fields.Char(string='Sponsor Mobile', related='sponsor_id.mobile') sponsor_phone = fields.Char(string='Sponsor Phone', related='sponsor_id.phone') sponsor_subtitle = fields.Char(string='Sponsor Slogan', related='sponsor_id.subtitle') sponsor_website_description = fields.Html(string='Sponsor Description', related='sponsor_id.website_description') sponsor_image_512 = fields.Image(string='Sponsor Logo', related='sponsor_id.image_512') def action_view_sponsor(self): action = self.env['ir.actions.act_window']._for_xml_id('website_event_exhibitor.event_sponsor_action') action['views'] = [(False, 'form')] action['res_id'] = self.sponsor_id.id return action def _get_or_create_sponsor(self, vals): self.ensure_one() sponsor_id = self.env['event.sponsor'].sudo().search([ ('partner_id', '=', self.partner_id.id), ('sponsor_type_id', '=', self.sponsor_type_id.id), ('exhibitor_type', '=', self.booth_category_id.exhibitor_type), ('event_id', '=', self.event_id.id), ], limit=1) if not sponsor_id: values = { 'event_id': self.event_id.id, 'sponsor_type_id': self.sponsor_type_id.id, 'exhibitor_type': self.booth_category_id.exhibitor_type, 'partner_id': self.partner_id.id, **{key.partition('sponsor_')[2]: value for key, value in vals.items() if key.startswith('sponsor_')}, } if self.booth_category_id.exhibitor_type == 'online': values.update({ 'room_name': 'odoo-exhibitor-%s' % self.partner_id.name, }) sponsor_id = self.env['event.sponsor'].sudo().create(values) return sponsor_id.id def _action_post_confirm(self, write_vals): for booth in self: if booth.use_sponsor and booth.partner_id: booth.sponsor_id = booth._get_or_create_sponsor(write_vals) super(EventBooth, self)._action_post_confirm(write_vals)
50.055556
2,703
2,284
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 from odoo.addons.website_event.controllers.main import WebsiteEventController from odoo.tools import plaintext2html class WebsiteEventBoothController(WebsiteEventController): def _prepare_booth_registration_values(self, event, kwargs): booth_values = super(WebsiteEventBoothController, self)._prepare_booth_registration_values(event, kwargs) if not booth_values.get('contact_email'): booth_values['contact_email'] = kwargs.get('sponsor_email') if not booth_values.get('contact_name'): booth_values['contact_name'] = kwargs.get('sponsor_name') if not booth_values.get('contact_mobile'): booth_values['contact_mobile'] = kwargs.get('sponsor_mobile') if not booth_values.get('contact_phone'): booth_values['contact_phone'] = kwargs.get('sponsor_phone') booth_values.update(**self._prepare_booth_registration_sponsor_values(event, booth_values, kwargs)) return booth_values def _prepare_booth_registration_partner_values(self, event, kwargs): if not kwargs.get('contact_email') and kwargs.get('sponsor_email'): kwargs['contact_email'] = kwargs['sponsor_email'] return super(WebsiteEventBoothController, self)._prepare_booth_registration_partner_values(event, kwargs) def _prepare_booth_registration_sponsor_values(self, event, booth_values, kwargs): sponsor_values = { 'sponsor_name': kwargs.get('sponsor_name') or booth_values.get('contact_name'), 'sponsor_email': kwargs.get('sponsor_email') or booth_values.get('contact_email'), 'sponsor_mobile': kwargs.get('sponsor_mobile') or booth_values.get('contact_mobile'), 'sponsor_phone': kwargs.get('sponsor_phone') or booth_values.get('contact_phone'), 'sponsor_subtitle': kwargs.get('sponsor_slogan'), 'sponsor_website_description': plaintext2html(kwargs.get('sponsor_description')) if kwargs.get('sponsor_description') else '', 'sponsor_image_512': base64.b64encode(kwargs['sponsor_image'].read()) if kwargs.get('sponsor_image') else False, } return sponsor_values
55.707317
2,284
6,913
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import contextlib import re from lxml import etree from psycopg2 import sql from unittest.mock import Mock, MagicMock, patch import werkzeug import odoo from odoo.tools.misc import DotDict def get_video_embed_code(video_url): ''' Computes the valid iframe from given URL that can be embedded (or False in case of invalid URL). ''' if not video_url: return False # To detect if we have a valid URL or not validURLRegex = r'^(http:\/\/|https:\/\/|\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$' # Regex for few of the widely used video hosting services ytRegex = r'^(?:(?:https?:)?\/\/)?(?:www\.)?(?:youtu\.be\/|youtube(-nocookie)?\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((?:\w|-){11})(?:\S+)?$' vimeoRegex = r'\/\/(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*' dmRegex = r'.+dailymotion.com\/(video|hub|embed)\/([^_?]+)[^#]*(#video=([^_&]+))?' igRegex = r'(.*)instagram.com\/p\/(.[a-zA-Z0-9]*)' ykuRegex = r'(.*).youku\.com\/(v_show\/id_|embed\/)(.+)' if not re.search(validURLRegex, video_url): return False else: embedUrl = False ytMatch = re.search(ytRegex, video_url) vimeoMatch = re.search(vimeoRegex, video_url) dmMatch = re.search(dmRegex, video_url) igMatch = re.search(igRegex, video_url) ykuMatch = re.search(ykuRegex, video_url) if ytMatch and len(ytMatch.groups()[1]) == 11: embedUrl = '//www.youtube%s.com/embed/%s?rel=0' % (ytMatch.groups()[0] or '', ytMatch.groups()[1]) elif vimeoMatch: embedUrl = '//player.vimeo.com/video/%s' % (vimeoMatch.groups()[2]) elif dmMatch: embedUrl = '//www.dailymotion.com/embed/video/%s' % (dmMatch.groups()[1]) elif igMatch: embedUrl = '//www.instagram.com/p/%s/embed/' % (igMatch.groups()[1]) elif ykuMatch: ykuLink = ykuMatch.groups()[2] if '.html?' in ykuLink: ykuLink = ykuLink.split('.html?')[0] embedUrl = '//player.youku.com/embed/%s' % (ykuLink) else: # We directly use the provided URL as it is embedUrl = video_url return '<iframe class="embed-responsive-item" src="%s" allowFullScreen="true" frameborder="0"></iframe>' % embedUrl def werkzeugRaiseNotFound(*args, **kwargs): raise werkzeug.exceptions.NotFound() @contextlib.contextmanager def MockRequest( env, *, routing=True, multilang=True, context=None, cookies=None, country_code=None, website=None, sale_order_id=None, website_sale_current_pl=None, ): router = MagicMock() match = router.return_value.bind.return_value.match if routing: match.return_value[0].routing = { 'type': 'http', 'website': True, 'multilang': multilang } else: match.side_effect = werkzeugRaiseNotFound if context is None: context = {} lang_code = context.get('lang', env.context.get('lang', 'en_US')) context.setdefault('lang', lang_code) request = Mock( context=context, db=None, endpoint=match.return_value[0] if routing else None, env=env, httprequest=Mock( host='localhost', path='/hello', app=odoo.http.root, environ={'REMOTE_ADDR': '127.0.0.1'}, cookies=cookies or {}, referrer='', ), lang=env['res.lang']._lang_get(lang_code), redirect=env['ir.http']._redirect, session=DotDict( geoip={'country_code': country_code}, debug=False, sale_order_id=sale_order_id, website_sale_current_pl=website_sale_current_pl, ), website=website, render=lambda *a, **kw: '<MockResponse>', ) with contextlib.ExitStack() as s: odoo.http._request_stack.push(request) s.callback(odoo.http._request_stack.pop) s.enter_context(patch('odoo.http.root.get_db_router', router)) yield request # Fuzzy matching tools def distance(s1="", s2="", limit=4): """ Limited Levenshtein-ish distance (inspired from Apache text common) Note: this does not return quick results for simple cases (empty string, equal strings) those checks should be done outside loops that use this function. :param s1: first string :param s2: second string :param limit: maximum distance to take into account, return -1 if exceeded :return: number of character changes needed to transform s1 into s2 or -1 if this exceeds the limit """ BIG = 100000 # never reached integer if len(s1) > len(s2): s1, s2 = s2, s1 l1 = len(s1) l2 = len(s2) if l2 - l1 > limit: return -1 boundary = min(l1, limit) + 1 p = [i if i < boundary else BIG for i in range(0, l1 + 1)] d = [BIG for _ in range(0, l1 + 1)] for j in range(1, l2 + 1): j2 = s2[j -1] d[0] = j range_min = max(1, j - limit) range_max = min(l1, j + limit) if range_min > 1: d[range_min -1] = BIG for i in range(range_min, range_max + 1): if s1[i - 1] == j2: d[i] = p[i - 1] else: d[i] = 1 + min(d[i - 1], p[i], p[i - 1]) p, d = d, p return p[l1] if p[l1] <= limit else -1 def similarity_score(s1, s2): """ Computes a score that describes how much two strings are matching. :param s1: first string :param s2: second string :return: float score, the higher the more similar pairs returning non-positive scores should be considered non similar """ dist = distance(s1, s2) if dist == -1: return -1 set1 = set(s1) score = len(set1.intersection(s2)) / len(set1) score -= dist / len(s1) score -= len(set1.symmetric_difference(s2)) / (len(s1) + len(s2)) return score def text_from_html(html_fragment): """ Returns the plain non-tag text from an html :param html_fragment: document from which text must be extracted :return: text extracted from the html """ # lxml requires one single root element tree = etree.fromstring('<p>%s</p>' % html_fragment, etree.XMLParser(recover=True)) return ' '.join(tree.itertext()) def get_unaccent_sql_wrapper(cr): """ Returns a function that wraps SQL within unaccent if available TODO remove when this tool becomes globally available :param cr: cursor on which the wrapping is done :return: function that wraps SQL with unaccent if available """ if odoo.registry(cr.dbname).has_unaccent: return lambda x: sql.SQL("unaccent({wrapped_sql})").format(wrapped_sql=x) return lambda x: x
34.222772
6,913
12,255
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Website', 'category': 'Website/Website', 'sequence': 20, 'summary': 'Enterprise website builder', 'website': 'https://www.odoo.com/app/website', 'version': '1.0', 'description': "", 'depends': [ 'digest', 'web', 'web_editor', 'http_routing', 'portal', 'social_media', 'auth_signup', 'mail', 'google_recaptcha', 'utm', ], 'installable': True, 'data': [ # security.xml first, data.xml need the group to exist (checking it) 'security/website_security.xml', 'security/ir.model.access.csv', 'data/ir_asset.xml', 'data/ir_cron_data.xml', 'data/mail_mail_data.xml', 'data/website_data.xml', 'data/website_visitor_cron.xml', 'data/digest_data.xml', 'views/assets.xml', 'views/website_templates.xml', 'views/website_navbar_templates.xml', 'views/website_configurator_templates.xml', 'views/snippets/snippets.xml', 'views/snippets/s_title.xml', 'views/snippets/s_cover.xml', 'views/snippets/s_text_image.xml', 'views/snippets/s_image_text.xml', 'views/snippets/s_banner.xml', 'views/snippets/s_text_block.xml', 'views/snippets/s_features.xml', 'views/snippets/s_three_columns.xml', 'views/snippets/s_picture.xml', 'views/snippets/s_carousel.xml', 'views/snippets/s_alert.xml', 'views/snippets/s_card.xml', 'views/snippets/s_share.xml', 'views/snippets/s_rating.xml', 'views/snippets/s_hr.xml', 'views/snippets/s_facebook_page.xml', 'views/snippets/s_image_gallery.xml', 'views/snippets/s_countdown.xml', 'views/snippets/s_product_catalog.xml', 'views/snippets/s_comparisons.xml', 'views/snippets/s_company_team.xml', 'views/snippets/s_call_to_action.xml', 'views/snippets/s_references.xml', 'views/snippets/s_popup.xml', 'views/snippets/s_faq_collapse.xml', 'views/snippets/s_features_grid.xml', 'views/snippets/s_tabs.xml', 'views/snippets/s_table_of_content.xml', 'views/snippets/s_chart.xml', 'views/snippets/s_parallax.xml', 'views/snippets/s_quotes_carousel.xml', 'views/snippets/s_numbers.xml', 'views/snippets/s_masonry_block.xml', 'views/snippets/s_media_list.xml', 'views/snippets/s_showcase.xml', 'views/snippets/s_timeline.xml', 'views/snippets/s_process_steps.xml', 'views/snippets/s_text_highlight.xml', 'views/snippets/s_progress_bar.xml', 'views/snippets/s_blockquote.xml', 'views/snippets/s_badge.xml', 'views/snippets/s_color_blocks_2.xml', 'views/snippets/s_product_list.xml', 'views/snippets/s_mega_menu_multi_menus.xml', 'views/snippets/s_mega_menu_menu_image_menu.xml', 'views/snippets/s_mega_menu_thumbnails.xml', 'views/snippets/s_mega_menu_little_icons.xml', 'views/snippets/s_mega_menu_images_subtitles.xml', 'views/snippets/s_mega_menu_menus_logos.xml', 'views/snippets/s_mega_menu_odoo_menu.xml', 'views/snippets/s_mega_menu_big_icons_subtitles.xml', 'views/snippets/s_mega_menu_cards.xml', 'views/snippets/s_google_map.xml', 'views/snippets/s_map.xml', 'views/snippets/s_dynamic_snippet.xml', 'views/snippets/s_dynamic_snippet_carousel.xml', 'views/snippets/s_embed_code.xml', 'views/snippets/s_website_form.xml', 'views/snippets/s_searchbar.xml', 'views/website_views.xml', 'views/website_visitor_views.xml', 'views/res_config_settings_views.xml', 'views/website_rewrite.xml', 'views/ir_actions_views.xml', 'views/ir_asset_views.xml', 'views/ir_attachment_views.xml', 'views/ir_model_views.xml', 'views/res_partner_views.xml', 'wizard/base_language_install_views.xml', 'wizard/website_robots.xml', ], 'demo': [ 'data/website_demo.xml', ], 'application': True, 'post_init_hook': 'post_init_hook', 'uninstall_hook': 'uninstall_hook', 'assets': { 'web.assets_frontend': [ ('replace', 'web/static/src/legacy/js/public/public_root_instance.js', 'website/static/src/js/content/website_root_instance.js'), 'website/static/src/scss/website.scss', 'website/static/src/scss/website.ui.scss', 'website/static/src/js/utils.js', 'website/static/src/js/content/website_root.js', 'website/static/src/js/widgets/dialog.js', 'website/static/src/js/widgets/fullscreen_indication.js', 'website/static/src/js/content/compatibility.js', 'website/static/src/js/content/menu.js', 'website/static/src/js/content/snippets.animation.js', 'website/static/src/js/menu/navbar.js', 'website/static/src/js/show_password.js', 'website/static/src/js/post_link.js', 'website/static/src/js/user_custom_javascript.js', # Stable fix, will be replaced by an `ir.asset` in master to be able # to archive and not load that JS file if we have to create a 001.js # and the DB has no snippet using the 000.js left. 'website/static/src/snippets/s_map/000.js', ], 'web.assets_frontend_minimal': [ 'website/static/src/js/content/inject_dom.js', 'website/static/src/js/content/auto_hide_menu.js', 'website/static/src/js/content/adapt_content.js', ], 'web.assets_frontend_lazy': [ # Remove assets_frontend_minimal ('remove', 'website/static/src/js/content/inject_dom.js'), ('remove', 'website/static/src/js/content/auto_hide_menu.js'), ('remove', 'website/static/src/js/content/adapt_content.js'), ], 'web._assets_primary_variables': [ 'website/static/src/scss/primary_variables.scss', 'website/static/src/scss/options/user_values.scss', 'website/static/src/scss/options/colors/user_color_palette.scss', 'website/static/src/scss/options/colors/user_gray_color_palette.scss', 'website/static/src/scss/options/colors/user_theme_color_palette.scss', ], 'web._assets_secondary_variables': [ ('prepend', 'website/static/src/scss/secondary_variables.scss'), ], 'web.assets_tests': [ 'website/static/tests/tours/**/*', ], 'web.assets_backend': [ 'website/static/src/scss/view_hierarchy.scss', 'website/static/src/scss/website.backend.scss', 'website/static/src/scss/website_visitor_views.scss', 'website/static/src/scss/website.theme_install.scss', 'website/static/src/js/backend/button.js', 'website/static/src/js/backend/dashboard.js', 'website/static/src/js/backend/res_config_settings.js', 'website/static/src/js/backend/view_hierarchy.js', 'website/static/src/js/widget_iframe.js', 'website/static/src/js/theme_preview_kanban.js', 'website/static/src/js/theme_preview_form.js', ], 'web.qunit_suite_tests': [ 'website/static/tests/dashboard_tests.js', 'website/static/tests/website_tests.js', ], 'web._assets_frontend_helpers': [ ('prepend', 'website/static/src/scss/bootstrap_overridden.scss'), ], 'website.assets_wysiwyg': [ ('include', 'web._assets_helpers'), 'web_editor/static/src/scss/bootstrap_overridden.scss', 'web/static/lib/bootstrap/scss/_variables.scss', 'website/static/src/scss/website.wysiwyg.scss', 'website/static/src/scss/website.edit_mode.scss', 'website/static/src/js/editor/editor.js', 'website/static/src/js/editor/snippets.editor.js', 'website/static/src/js/editor/snippets.options.js', 'website/static/src/snippets/s_facebook_page/options.js', 'website/static/src/snippets/s_image_gallery/options.js', 'website/static/src/snippets/s_countdown/options.js', 'website/static/src/snippets/s_masonry_block/options.js', 'website/static/src/snippets/s_popup/options.js', 'website/static/src/snippets/s_product_catalog/options.js', 'website/static/src/snippets/s_chart/options.js', 'website/static/src/snippets/s_rating/options.js', 'website/static/src/snippets/s_tabs/options.js', 'website/static/src/snippets/s_progress_bar/options.js', 'website/static/src/snippets/s_blockquote/options.js', 'website/static/src/snippets/s_showcase/options.js', 'website/static/src/snippets/s_table_of_content/options.js', 'website/static/src/snippets/s_timeline/options.js', 'website/static/src/snippets/s_media_list/options.js', 'website/static/src/snippets/s_google_map/options.js', 'website/static/src/snippets/s_map/options.js', 'website/static/src/snippets/s_dynamic_snippet/options.js', 'website/static/src/snippets/s_dynamic_snippet_carousel/options.js', 'website/static/src/snippets/s_embed_code/options.js', 'website/static/src/snippets/s_website_form/options.js', 'website/static/src/snippets/s_searchbar/options.js', 'website/static/src/js/editor/wysiwyg.js', 'website/static/src/js/editor/widget_link.js', 'website/static/src/js/widgets/media.js', 'website/static/src/js/widgets/link_popover_widget.js', ], 'website.assets_editor': [ ('include', 'web._assets_helpers'), 'web/static/lib/bootstrap/scss/_variables.scss', 'web/static/src/legacy/scss/ace.scss', 'website/static/src/scss/website.editor.ui.scss', 'website/static/src/scss/website.theme_install.scss', 'website/static/src/js/form_editor_registry.js', 'website/static/src/js/menu/content.js', 'website/static/src/js/menu/customize.js', 'website/static/src/js/menu/debug_menu.js', 'website/static/src/js/menu/edit.js', 'website/static/src/js/menu/mobile_view.js', 'website/static/src/js/menu/new_content.js', 'website/static/src/js/menu/seo.js', 'website/static/src/js/menu/translate.js', 'website/static/src/js/set_view_track.js', 'website/static/src/js/tours/homepage.js', 'website/static/src/js/tours/tour_utils.js', 'website/static/src/js/widgets/ace.js', ], 'web.assets_qweb': [ 'website/static/src/xml/website.backend.xml', 'website/static/src/xml/website_widget.xml', 'website/static/src/xml/theme_preview.xml', 'website/static/src/components/configurator/configurator.xml', ], 'website.test_bundle': [ '/web/static/lib/qweb/qweb2.js', 'http://test.external.link/javascript1.js', '/web/static/lib/jquery.ui/jquery-ui.css', 'http://test.external.link/style1.css', '/web/static/src/boot.js', 'http://test.external.link/javascript2.js', 'http://test.external.link/style2.css', ], 'website.website_configurator_assets_js': [ '/website/static/src/components/configurator/configurator.js', ], 'website.website_configurator_assets_scss': [ ('include', 'web.assets_frontend'), '/website/static/src/scss/configurator.scss', '/website/static/src/scss/website.theme_install.scss', '/website/static/src/scss/website.wysiwyg.scss' ] }, 'license': 'LGPL-3', }
46.420455
12,255
1,810
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from odoo import tests from odoo.tools import mute_logger @tests.tagged('post_install', '-at_install') class TestControllers(tests.HttpCase): @mute_logger('odoo.addons.http_routing.models.ir_http', 'odoo.http') def test_last_created_pages_autocompletion(self): self.authenticate("admin", "admin") Page = self.env['website.page'] last_5_url_edited = [] base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') suggested_links_url = base_url + '/website/get_suggested_links' for i in range(0, 10): new_page = Page.create({ 'name': 'Generic', 'type': 'qweb', 'arch': ''' <div>content</div> ''', 'key': "test.generic_view-%d" % i, 'url': "/generic-%d" % i, 'is_published': True, }) if i % 2 == 0: # mark as old new_page._write({'write_date': '2020-01-01'}) else: last_5_url_edited.append(new_page.url) res = self.opener.post(url=suggested_links_url, json={'params': {'needle': '/'}}) resp = json.loads(res.content) assert 'result' in resp suggested_links = resp['result'] last_modified_history = next(o for o in suggested_links['others'] if o["title"] == "Last modified pages") last_modified_values = map(lambda o: o['value'], last_modified_history['values']) matching_pages = set(map(lambda o: o['value'], suggested_links['matching_pages'])) self.assertEqual(set(last_modified_values), set(last_5_url_edited) - matching_pages)
39.347826
1,810
4,378
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from psycopg2 import IntegrityError from odoo.tests.common import TransactionCase, new_test_user from odoo.exceptions import ValidationError from odoo.service.model import check from odoo.tools import mute_logger from odoo.addons.website.tools import MockRequest class TestWebsiteResUsers(TransactionCase): def setUp(self): super().setUp() websites = self.env['website'].create([ {'name': 'Test Website'}, {'name': 'Test Website 2'}, ]) self.website_1, self.website_2 = websites def test_no_website(self): new_test_user(self.env, login='Pou', website_id=False) with self.assertRaises(ValidationError): new_test_user(self.env, login='Pou', website_id=False) def test_websites_set_null(self): user_1 = new_test_user(self.env, login='Pou', website_id=self.website_1.id) user_2 = new_test_user(self.env, login='Pou', website_id=self.website_2.id) with self.assertRaises(ValidationError): (user_1 | user_2).write({'website_id': False}) def test_null_and_website(self): new_test_user(self.env, login='Pou', website_id=self.website_1.id) new_test_user(self.env, login='Pou', website_id=False) def test_change_login(self): new_test_user(self.env, login='Pou', website_id=self.website_1.id) user_belle = new_test_user(self.env, login='Belle', website_id=self.website_1.id) with self.assertRaises(IntegrityError), mute_logger('odoo.sql_db'): user_belle.login = 'Pou' def test_change_login_no_website(self): new_test_user(self.env, login='Pou', website_id=False) user_belle = new_test_user(self.env, login='Belle', website_id=False) with self.assertRaises(ValidationError): user_belle.login = 'Pou' def test_same_website_message(self): @check # Check decorator, otherwise translation is not applied def check_new_test_user(dbname): new_test_user(self.env(context={'land': 'en_US'}), login='Pou', website_id=self.website_1.id) new_test_user(self.env, login='Pou', website_id=self.website_1.id) # Should be a ValidationError (with a nice translated error message), # not an IntegrityError with self.assertRaises(ValidationError), mute_logger('odoo.sql_db'): check_new_test_user(self.env.registry._db.dbname) def _create_user_via_website(self, website, login): # We need a fake request to _signup_create_user. with MockRequest(self.env, website=website): return self.env['res.users'].with_context(website_id=website.id)._signup_create_user({ 'name': login, 'login': login, }) def _create_and_check_portal_user(self, website_specific, company_1, company_2, website_1, website_2): # Disable/Enable cross-website for portal users. website_1.specific_user_account = website_specific website_2.specific_user_account = website_specific user_1 = self._create_user_via_website(website_1, 'user1') user_2 = self._create_user_via_website(website_2, 'user2') self.assertEqual(user_1.company_id, company_1) self.assertEqual(user_2.company_id, company_2) if website_specific: self.assertEqual(user_1.website_id, website_1) self.assertEqual(user_2.website_id, website_2) else: self.assertEqual(user_1.website_id.id, False) self.assertEqual(user_2.website_id.id, False) def test_multi_website_multi_company(self): company_1 = self.env['res.company'].create({'name': "Company 1"}) company_2 = self.env['res.company'].create({'name': "Company 2"}) website_1 = self.env['website'].create({'name': "Website 1", 'company_id': company_1.id}) website_2 = self.env['website'].create({'name': "Website 2", 'company_id': company_2.id}) # Permit uninvited signup. website_1.auth_signup_uninvited = 'b2c' website_2.auth_signup_uninvited = 'b2c' self._create_and_check_portal_user(False, company_1, company_2, website_1, website_2) self._create_and_check_portal_user(True, company_1, company_2, website_1, website_2)
44.673469
4,378
3,233
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch import odoo.tests from odoo.addons.iap.tools.iap_tools import iap_jsonrpc_mocked from odoo.tools import mute_logger class TestConfiguratorCommon(odoo.tests.HttpCase): def _theme_upgrade_upstream(self): # patch to prevent module install/upgrade during tests pass def setUp(self): super().setUp() def iap_jsonrpc_mocked_configurator(*args, **kwargs): endpoint = args[0] params = kwargs.get('params', {}) language = params.get('lang', 'en_US') if endpoint.endswith('/api/website/1/configurator/industries'): if language == 'fr_FR': return {"industries": [ {"id": 1, "label": "abbey in fr"}, {"id": 2, "label": "aboriginal and torres strait islander organisation in fr"}, {"id": 3, "label": "aboriginal art gallery in fr"}, {"id": 4, "label": "abortion clinic in fr"}, {"id": 5, "label": "abrasives supplier in fr"}, {"id": 6, "label": "abundant life church in fr"}]} else: return {"industries": [ {"id": 1, "label": "abbey"}, {"id": 2, "label": "aboriginal and torres strait islander organisation"}, {"id": 3, "label": "aboriginal art gallery"}, {"id": 4, "label": "abortion clinic"}, {"id": 5, "label": "abrasives supplier"}, {"id": 6, "label": "abundant life church"}]} elif '/api/website/2/configurator/recommended_themes' in endpoint: return [] elif '/api/website/2/configurator/custom_resources/' in endpoint: return {'images': {}} iap_jsonrpc_mocked() iap_patch = patch('odoo.addons.iap.tools.iap_tools.iap_jsonrpc', iap_jsonrpc_mocked_configurator) iap_patch.start() self.addCleanup(iap_patch.stop) patcher = patch('odoo.addons.website.models.ir_module_module.IrModuleModule._theme_upgrade_upstream', wraps=self._theme_upgrade_upstream) patcher.start() self.addCleanup(patcher.stop) @odoo.tests.common.tagged('post_install', '-at_install') class TestConfiguratorTranslation(TestConfiguratorCommon): def test_01_configurator_translation(self): with mute_logger('odoo.addons.base.models.ir_translation'): self.env["base.language.install"].create({'lang': 'fr_FR', 'overwrite': True}).lang_install() website_fr = self.env['website'].create({ 'name': "Website Fr", 'default_lang_id': self.env.ref('base.lang_fr').id }) # disable configurator todo to ensure this test goes through active_todo = self.env['ir.actions.todo'].search([('state', '=', 'open')], limit=1) active_todo.update({'state': 'done'}) self.start_tour('/website/force/%s?path=%%2Fwebsite%%2Fconfigurator' % website_fr.id, 'configurator_translation', login='admin')
47.544118
3,233
7,933
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import TransactionCase, tagged @tagged('post_install', '-at_install') class TestDisableSnippetsAssets(TransactionCase): def setUp(self): super().setUp() self.View = self.env['ir.ui.view'] self.WebsiteMenu = self.env['website.menu'] self.Website = self.env['website'] self.IrAsset = self.env['ir.asset'] self.homepage = self.View.create({ 'name': 'Home', 'type': 'qweb', 'arch_db': HOMEPAGE_OUTDATED, 'key': 'website.homepage', }) self.mega_menu = self.WebsiteMenu.create({ 'name': 'Image Gallery V001', 'mega_menu_content': MEGA_MENU_UP_TO_DATE, }) self.initial_active_snippets_assets = self._get_active_snippets_assets() def test_homepage_outdated_and_mega_menu_up_to_date(self): self.Website._disable_unused_snippets_assets() # Old snippet with scss and js s_website_form_000_scss = self._get_snippet_asset('s_website_form', '000', 'scss') s_website_form_001_scss = self._get_snippet_asset('s_website_form', '001', 'scss') s_website_form_000_js = self._get_snippet_asset('s_website_form', '000', 'js') self.assertEqual(s_website_form_000_scss.active, True) self.assertEqual(s_website_form_001_scss.active, True) self.assertEqual(s_website_form_000_js.active, True) # Old snippet with scss and scss variables s_masonry_block_000_scss = self._get_snippet_asset('s_masonry_block', '000', 'scss') s_masonry_block_000_variables_scss = self._get_snippet_asset('s_masonry_block', '000_variables', 'scss') s_masonry_block_001_scss = self._get_snippet_asset('s_masonry_block', '001', 'scss') self.assertEqual(s_masonry_block_000_scss.active, True) self.assertEqual(s_masonry_block_000_variables_scss.active, True) self.assertEqual(s_masonry_block_001_scss.active, True) # New snippet s_image_gallery_000 = self._get_snippet_asset('s_image_gallery', '000', 'scss') s_image_gallery_001 = self._get_snippet_asset('s_image_gallery', '001', 'scss') self.assertEqual(s_image_gallery_000.active, False) self.assertEqual(s_image_gallery_001.active, True) unwanted_snippets_assets_changes = set(self.initial_active_snippets_assets) - set(self._get_active_snippets_assets()) - set([s_image_gallery_000.path]) # The vaccuum should not have activated/deactivated any other snippet asset than the original ones self.assertEqual( len(unwanted_snippets_assets_changes), 0, 'Following snippets are not following the snippet versioning system structure, or their previous assets have not been deactivated:\n' + '\n'.join(unwanted_snippets_assets_changes)) def test_homepage_up_to_date_and_mega_menu_outdated(self): self.homepage.write({ 'arch_db': HOMEPAGE_UP_TO_DATE, }) self.mega_menu.write({ 'mega_menu_content': MEGA_MENU_OUTDATED, }) self.Website._disable_unused_snippets_assets() s_website_form_000_scss = self._get_snippet_asset('s_website_form', '000', 'scss') s_website_form_001_scss = self._get_snippet_asset('s_website_form', '001', 'scss') s_website_form_000_js = self._get_snippet_asset('s_website_form', '000', 'js') self.assertEqual(s_website_form_000_scss.active, False) self.assertEqual(s_website_form_001_scss.active, True) self.assertEqual(s_website_form_000_js.active, True) s_masonry_block_000_scss = self._get_snippet_asset('s_masonry_block', '000', 'scss') s_masonry_block_000_variables_scss = self._get_snippet_asset('s_masonry_block', '000_variables', 'scss') s_masonry_block_001_scss = self._get_snippet_asset('s_masonry_block', '001', 'scss') self.assertEqual(s_masonry_block_000_scss.active, False) self.assertEqual(s_masonry_block_000_variables_scss.active, False) self.assertEqual(s_masonry_block_001_scss.active, True) s_image_gallery_000 = self._get_snippet_asset('s_image_gallery', '000', 'scss') s_image_gallery_001 = self._get_snippet_asset('s_image_gallery', '001', 'scss') self.assertEqual(s_image_gallery_000.active, True) self.assertEqual(s_image_gallery_001.active, True) def _get_snippet_asset(self, snippet_id, asset_version, asset_type): return self.IrAsset.search([('path', '=', 'website/static/src/snippets/' + snippet_id + '/' + asset_version + '.' + asset_type)], limit=1) def _get_active_snippets_assets(self): return self.IrAsset.search([('path', 'like', 'snippets'), ('active', '=', True)]).mapped('path') HOMEPAGE_UP_TO_DATE = """ <t name="Homepage" t-name="website.homepage1"> <t t-call="website.layout"> <t t-set="pageName" t-value="'homepage'"/> <div id="wrap" class="oe_structure oe_empty"> <section class="s_website_form pt16 pb16 o_colored_level" data-vcss="001" data-snippet="s_website_form" data-name="Form"> <div class="container"> <form action="/website_form/" method="post" enctype="multipart/form-data" class="o_mark_required" data-mark="*" data-success-mode="redirect" data-success-page="/contactus-thank-you" data-model_name="mail.mail"> </form> </div> </section> <section class="s_masonry_block" data-vcss="001" data-snippet="s_masonry_block" data-name="Masonry"> <div class="container-fluid"/> </section> <section class="s_showcase pt48 pb48 o_colored_level" data-vcss="002" data-snippet="s_showcase" data-name="Showcase"> <div class="container"> </div> </section> </div> </t> </t> """ HOMEPAGE_OUTDATED = """ <t name="Homepage" t-name="website.homepage1"> <t t-call="website.layout"> <t t-set="pageName" t-value="'homepage'"/> <div id="wrap" class="oe_structure oe_empty"> <form action="/website_form/" method="post" class="s_website_form container-fluid mt32 o_fake_not_editable" enctype="multipart/form-data" data-name="Form Builder" data-model_name="mail.mail" data-success_page="/contactus-thank-you" data-snippet="s_website_form"> <div class="container"> </div> </form> <section class="s_masonry_block" data-vcss="001" data-snippet="s_masonry_block" data-name="Masonry"> <div class="container-fluid"/> </section> <section class="s_masonry_block" data-snippet="s_masonry_block" data-name="Masonry"> <div class="container-fluid"/> </section> <section class="s_showcase pt48 pb48 o_colored_level" data-vcss="002" data-snippet="s_showcase" data-name="Showcase"> <div class="container"> </div> </section> </div> </t> </t> """ MEGA_MENU_UP_TO_DATE = """ <section class="s_mega_menu_multi_menus py-4 o_colored_level" data-name="Multi-Menus"> <div class="container"> </div> </section> <section class="s_image_gallery o_slideshow s_image_gallery_show_indicators s_image_gallery_indicators_rounded pt24 o_colored_level" data-vcss="001" data-columns="3" style="height: 500px; overflow: hidden;" data-snippet="s_image_gallery" data-name="Image Gallery"> <div class="container"> </div> </section> """ MEGA_MENU_OUTDATED = """ <section class="s_mega_menu_multi_menus py-4 o_colored_level" data-name="Multi-Menus"> <div class="container"> </div> </section> <section class="s_image_gallery o_slideshow s_image_gallery_show_indicators s_image_gallery_indicators_rounded pt24 o_colored_level" data-columns="3" style="height: 500px; overflow: hidden;" data-snippet="s_image_gallery" data-name="Image Gallery"> <div class="container"> </div> </section> """
48.078788
7,933
8,236
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree import re from odoo import http, tools from odoo.addons.base.tests.common import TransactionCaseWithUserDemo from odoo.addons.website.tools import MockRequest from odoo.modules.module import get_module_resource from odoo.tests.common import TransactionCase class TestQweb(TransactionCaseWithUserDemo): def _load(self, module, *args): tools.convert_file(self.cr, 'website', get_module_resource(module, *args), {}, 'init', False, 'test') def test_qweb_post_processing_att(self): t = self.env['ir.ui.view'].create({ 'name': 'test', 'type': 'qweb', 'arch_db': '''<t t-name="attr-escaping"> <img src="http://test.external.img/img.png"/> <img t-att-src="url"/> </t>''' }) result = """ <img src="http://test.external.img/img.png" loading="lazy"/> <img src="http://test.external.img/img2.png" loading="lazy"/> """ rendered = self.env['ir.qweb']._render(t.id, {'url': 'http://test.external.img/img2.png'}) self.assertEqual(rendered.strip(), result.strip()) def test_qweb_cdn(self): self._load('website', 'tests', 'template_qweb_test.xml') website = self.env.ref('website.default_website') website.write({ "cdn_activated": True, "cdn_url": "http://test.cdn" }) demo = self.env['res.users'].search([('login', '=', 'demo')])[0] demo.write({"signature": '''<span class="toto"> span<span class="fa"></span><img src="/web/image/1"/> </span>'''}) demo_env = self.env(user=demo) html = demo_env['ir.qweb']._render('website.test_template', {"user": demo}, website_id= website.id) asset_data = etree.HTML(html).xpath('//*[@data-asset-bundle]')[0] asset_xmlid = asset_data.attrib.get('data-asset-bundle') asset_version = asset_data.attrib.get('data-asset-version') html = html.strip() html = re.sub(r'\?unique=[^"]+', '', html).encode('utf8') attachments = demo_env['ir.attachment'].search([('url', '=like', '/web/assets/%-%/website.test_bundle.%')]) self.assertEqual(len(attachments), 2) format_data = { "js": attachments[0].url, "css": attachments[1].url, "user_id": demo.id, "filename": "Marc%20Demo", "alt": "Marc Demo", "asset_xmlid": asset_xmlid, "asset_version": asset_version, } self.assertHTMLEqual(html, ("""<!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="http://test.external.link/style1.css"/> <link type="text/css" rel="stylesheet" href="http://test.external.link/style2.css"/> <link type="text/css" rel="stylesheet" href="http://test.cdn%(css)s" data-asset-bundle="%(asset_xmlid)s" data-asset-version="%(asset_version)s"/> <meta/> <script type="text/javascript" src="http://test.external.link/javascript1.js"></script> <script type="text/javascript" src="http://test.external.link/javascript2.js"></script> <script type="text/javascript" src="http://test.cdn%(js)s" data-asset-bundle="%(asset_xmlid)s" data-asset-version="%(asset_version)s"></script> </head> <body> <img src="http://test.external.link/img.png" loading="lazy"/> <img src="http://test.cdn/website/static/img.png" loading="lazy"/> <a href="http://test.external.link/link">x</a> <a href="http://test.cdn/web/content/local_link">x</a> <span style="background-image: url(&#39;http://test.cdn/web/image/2&#39;)">xxx</span> <div widget="html"><span class="toto"> span<span class="fa"></span><img src="http://test.cdn/web/image/1" loading="lazy"> </span></div> <div widget="image"><img src="http://test.cdn/web/image/res.users/%(user_id)s/avatar_1920/%(filename)s" class="img img-fluid" alt="%(alt)s" loading="lazy"/></div> </body> </html>""" % format_data).encode('utf8')) class TestQwebProcessAtt(TransactionCase): def setUp(self): super(TestQwebProcessAtt, self).setUp() self.website = self.env.ref('website.default_website') self.env['res.lang']._activate_lang('fr_FR') self.website.language_ids = self.env.ref('base.lang_en') + self.env.ref('base.lang_fr') self.website.default_lang_id = self.env.ref('base.lang_en') self.website.cdn_activated = True self.website.cdn_url = "http://test.cdn" self.website.cdn_filters = "\n".join(["^(/[a-z]{2}_[A-Z]{2})?/a$", "^(/[a-z]{2})?/a$", "^/b$"]) def _test_att(self, url, expect, tag='a', attribute='href'): self.assertEqual( self.env['ir.qweb']._post_processing_att(tag, {attribute: url}, {}), expect ) def test_process_att_no_request(self): # no request so no URL rewriting self._test_att('/', {'href': '/'}) self._test_att('/en', {'href': '/en'}) self._test_att('/fr', {'href': '/fr'}) # no URL rewritting for CDN self._test_att('/a', {'href': '/a'}) def test_process_att_no_website(self): with MockRequest(self.env): # no website so URL rewriting self._test_att('/', {'href': '/'}) self._test_att('/en', {'href': '/en'}) self._test_att('/fr', {'href': '/fr'}) # no URL rewritting for CDN self._test_att('/a', {'href': '/a'}) def test_process_att_monolang_route(self): with MockRequest(self.env, website=self.website, multilang=False): # lang not changed in URL but CDN enabled self._test_att('/a', {'href': 'http://test.cdn/a'}) self._test_att('/en/a', {'href': 'http://test.cdn/en/a'}) self._test_att('/b', {'href': 'http://test.cdn/b'}) self._test_att('/en/b', {'href': '/en/b'}) def test_process_att_no_request_lang(self): with MockRequest(self.env, website=self.website): self._test_att('/', {'href': '/'}) self._test_att('/en/', {'href': '/'}) self._test_att('/fr/', {'href': '/fr/'}) self._test_att('/fr', {'href': '/fr'}) def test_process_att_with_request_lang(self): with MockRequest(self.env, website=self.website, context={'lang': 'fr_FR'}): self._test_att('/', {'href': '/fr/'}) self._test_att('/en/', {'href': '/'}) self._test_att('/fr/', {'href': '/fr/'}) self._test_att('/fr', {'href': '/fr'}) def test_process_att_matching_cdn_and_lang(self): with MockRequest(self.env, website=self.website): # lang prefix is added before CDN self._test_att('/a', {'href': 'http://test.cdn/a'}) self._test_att('/en/a', {'href': 'http://test.cdn/a'}) self._test_att('/fr/a', {'href': 'http://test.cdn/fr/a'}) self._test_att('/b', {'href': 'http://test.cdn/b'}) self._test_att('/en/b', {'href': 'http://test.cdn/b'}) self._test_att('/fr/b', {'href': '/fr/b'}) def test_process_att_no_route(self): with MockRequest(self.env, website=self.website, context={'lang': 'fr_FR'}, routing=False): # default on multilang=True if route is not /{module}/static/ self._test_att('/web/static/hi', {'href': '/web/static/hi'}) self._test_att('/my-page', {'href': '/fr/my-page'}) def test_process_att_url_crap(self): with MockRequest(self.env, website=self.website): match = http.root.get_db_router.return_value.bind.return_value.match # #{fragment} is stripped from URL when testing route self._test_att('/x#y?z', {'href': '/x#y?z'}) match.assert_called_with('/x', method='POST', query_args=None) match.reset_calls() self._test_att('/x?y#z', {'href': '/x?y#z'}) match.assert_called_with('/x', method='POST', query_args='y')
46.269663
8,236
1,644
py
PYTHON
15.0
import odoo.tests from odoo.tests.common import HOST from odoo.tools import config @odoo.tests.common.tagged('post_install', '-at_install') class TestWebsiteAttachment(odoo.tests.HttpCase): def test_01_type_url_301_image(self): IMD = self.env['ir.model.data'] IrAttachment = self.env['ir.attachment'] img1 = IrAttachment.create({ 'public': True, 'name': 's_banner_default_image.jpg', 'type': 'url', 'url': '/website/static/src/img/snippets_demo/s_banner.jpg' }) img2 = IrAttachment.create({ 'public': True, 'name': 's_banner_default_image.jpg', 'type': 'url', 'url': '/web/image/test.an_image_url' }) IMD.create({ 'name': 'an_image_url', 'module': 'test', 'model': img1._name, 'res_id': img1.id, }) IMD.create({ 'name': 'an_image_redirect_301', 'module': 'test', 'model': img2._name, 'res_id': img2.id, }) req = self.url_open('/web/image/test.an_image_url') self.assertEqual(req.status_code, 200) base = "http://%s:%s" % (HOST, config['http_port']) req = self.opener.get(base + '/web/image/test.an_image_redirect_301', allow_redirects=False) self.assertEqual(req.status_code, 301) self.assertEqual(req.headers['Location'], base + '/web/image/test.an_image_url') req = self.opener.get(base + '/web/image/test.an_image_redirect_301', allow_redirects=True) self.assertEqual(req.status_code, 200)
32.235294
1,644
15,032
py
PYTHON
15.0
# coding: utf-8 from lxml import html from odoo.addons.website.controllers.main import Website from odoo.addons.website.tools import MockRequest from odoo.tests import common, HttpCase, tagged from odoo.tests.common import HOST from odoo.tools import config from odoo.tools import mute_logger @tagged('-at_install', 'post_install') class TestPage(common.TransactionCase): def setUp(self): super(TestPage, self).setUp() View = self.env['ir.ui.view'] Page = self.env['website.page'] Menu = self.env['website.menu'] self.base_view = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': '<div>content</div>', 'key': 'test.base_view', }) self.extension_view = View.create({ 'name': 'Extension', 'mode': 'extension', 'inherit_id': self.base_view.id, 'arch': '<div position="inside">, extended content</div>', 'key': 'test.extension_view', }) self.page_1 = Page.create({ 'view_id': self.base_view.id, 'url': '/page_1', }) self.page_1_menu = Menu.create({ 'name': 'Page 1 menu', 'page_id': self.page_1.id, 'website_id': 1, }) def test_copy_page(self): View = self.env['ir.ui.view'] Page = self.env['website.page'] Menu = self.env['website.menu'] # Specific page self.specific_view = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': '<div>Specific View</div>', 'key': 'test.specific_view', }) self.page_specific = Page.create({ 'view_id': self.specific_view.id, 'url': '/page_specific', 'website_id': 1, }) self.page_specific_menu = Menu.create({ 'name': 'Page Specific menu', 'page_id': self.page_specific.id, 'website_id': 1, }) total_pages = Page.search_count([]) total_menus = Menu.search_count([]) # Copying a specific page should create a new page with an unique URL (suffixed by -X) Page.clone_page(self.page_specific.id, clone_menu=True) cloned_page = Page.search([('url', '=', '/page_specific-1')]) cloned_menu = Menu.search([('url', '=', '/page_specific-1')]) self.assertEqual(len(cloned_page), 1, "A page with an URL /page_specific-1 should've been created") self.assertEqual(Page.search_count([]), total_pages + 1, "Should have cloned the page") # It should also copy its menu with new url/name/page_id (if the page has a menu) self.assertEqual(len(cloned_menu), 1, "A specific page (with a menu) being cloned should have it's menu also cloned") self.assertEqual(cloned_menu.page_id, cloned_page, "The new cloned menu and the new cloned page should be linked (m2o)") self.assertEqual(Menu.search_count([]), total_menus + 1, "Should have cloned the page menu") Page.clone_page(self.page_specific.id, page_name="about-us", clone_menu=True) cloned_page_about_us = Page.search([('url', '=', '/about-us')]) cloned_menu_about_us = Menu.search([('url', '=', '/about-us')]) self.assertEqual(len(cloned_page_about_us), 1, "A page with an URL /about-us should've been created") self.assertEqual(len(cloned_menu_about_us), 1, "A specific page (with a menu) being cloned should have it's menu also cloned") self.assertEqual(cloned_menu_about_us.page_id, cloned_page_about_us, "The new cloned menu and the new cloned page should be linked (m2o)") # It should also copy its menu with new url/name/page_id (if the page has a menu) self.assertEqual(Menu.search_count([]), total_menus + 2, "Should have cloned the page menu") total_pages = Page.search_count([]) total_menus = Menu.search_count([]) # Copying a generic page should create a specific page with same URL Page.clone_page(self.page_1.id, clone_menu=True) cloned_generic_page = Page.search([('url', '=', '/page_1'), ('id', '!=', self.page_1.id), ('website_id', '!=', False)]) self.assertEqual(len(cloned_generic_page), 1, "A generic page being cloned should create a specific one for the current website") self.assertEqual(cloned_generic_page.url, self.page_1.url, "The URL of the cloned specific page should be the same as the generic page it has been cloned from") self.assertEqual(Page.search_count([]), total_pages + 1, "Should have cloned the generic page as a specific page for this website") self.assertEqual(Menu.search_count([]), total_menus, "It should not create a new menu as the generic page's menu belong to another website") # Except if the URL already exists for this website (its the case now that we already cloned it once) Page.clone_page(self.page_1.id, clone_menu=True) cloned_generic_page_2 = Page.search([('url', '=', '/page_1-1'), ('id', '!=', self.page_1.id)]) self.assertEqual(len(cloned_generic_page_2), 1, "A generic page being cloned should create a specific page with a new URL if there is already a specific page with that URL") def test_cow_page(self): Menu = self.env['website.menu'] Page = self.env['website.page'] View = self.env['ir.ui.view'] # backend write, no COW total_pages = Page.search_count([]) total_menus = Menu.search_count([]) total_views = View.search_count([]) self.page_1.write({'arch': '<div>modified base content</div>'}) self.assertEqual(total_pages, Page.search_count([])) self.assertEqual(total_menus, Menu.search_count([])) self.assertEqual(total_views, View.search_count([])) # edit through frontend self.page_1.with_context(website_id=1).write({'arch': '<div>website 1 content</div>'}) # 1. should have created website-specific copies for: # - page # - view x2 (base view + extension view) # 2. should not have created menu copy as menus are not shared/COW # 3. and shouldn't have touched original records self.assertEqual(total_pages + 1, Page.search_count([])) self.assertEqual(total_menus, Menu.search_count([])) self.assertEqual(total_views + 2, View.search_count([])) self.assertEqual(self.page_1.arch, '<div>modified base content</div>') self.assertEqual(bool(self.page_1.website_id), False) new_page = Page.search([('url', '=', '/page_1'), ('id', '!=', self.page_1.id)]) self.assertEqual(new_page.website_id.id, 1) self.assertEqual(new_page.view_id.inherit_children_ids[0].website_id.id, 1) self.assertEqual(new_page.arch, '<div>website 1 content</div>') def test_cow_extension_view(self): ''' test cow on extension view itself (like web_editor would do in the frontend) ''' Menu = self.env['website.menu'] Page = self.env['website.page'] View = self.env['ir.ui.view'] # nothing special should happen when editing through the backend total_pages = Page.search_count([]) total_menus = Menu.search_count([]) total_views = View.search_count([]) self.extension_view.write({'arch': '<div>modified extension content</div>'}) self.assertEqual(self.extension_view.arch, '<div>modified extension content</div>') self.assertEqual(total_pages, Page.search_count([])) self.assertEqual(total_menus, Menu.search_count([])) self.assertEqual(total_views, View.search_count([])) # When editing through the frontend a website-specific copy # for the extension view should be created. When rendering the # original website.page on website 1 it will look differently # due to this new extension view. self.extension_view.with_context(website_id=1).write({'arch': '<div>website 1 content</div>'}) self.assertEqual(total_pages, Page.search_count([])) self.assertEqual(total_menus, Menu.search_count([])) self.assertEqual(total_views + 1, View.search_count([])) self.assertEqual(self.extension_view.arch, '<div>modified extension content</div>') self.assertEqual(bool(self.page_1.website_id), False) new_view = View.search([('name', '=', 'Extension'), ('website_id', '=', 1)]) self.assertEqual(new_view.arch, '<div>website 1 content</div>') self.assertEqual(new_view.website_id.id, 1) def test_cou_page_backend(self): Page = self.env['website.page'] View = self.env['ir.ui.view'] # currently the view unlink of website.page can't handle views with inherited views self.extension_view.unlink() self.page_1.unlink() self.assertEqual(Page.search_count([('url', '=', '/page_1')]), 0) self.assertEqual(View.search_count([('name', 'in', ('Base', 'Extension'))]), 0) def test_cou_page_frontend(self): Page = self.env['website.page'] View = self.env['ir.ui.view'] Website = self.env['website'] website2 = self.env['website'].create({ 'name': 'My Second Website', 'domain': '', }) # currently the view unlink of website.page can't handle views with inherited views self.extension_view.unlink() website_id = 1 self.page_1.with_context(website_id=website_id).unlink() self.assertEqual(bool(self.base_view.exists()), False) self.assertEqual(bool(self.page_1.exists()), False) # Not COU but deleting a page will delete its menu (cascade) self.assertEqual(bool(self.page_1_menu.exists()), False) pages = Page.search([('url', '=', '/page_1')]) self.assertEqual(len(pages), Website.search_count([]) - 1, "A specific page for every website should have been created, except for the one from where we deleted the generic one.") self.assertTrue(website_id not in pages.mapped('website_id').ids, "The website from which we deleted the generic page should not have a specific one.") self.assertTrue(website_id not in View.search([('name', 'in', ('Base', 'Extension'))]).mapped('website_id').ids, "Same for views") @tagged('-at_install', 'post_install') class WithContext(HttpCase): def setUp(self): super().setUp() Page = self.env['website.page'] View = self.env['ir.ui.view'] self.base_view = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': '''<t name="Homepage" t-name="website.base_view"> <t t-call="website.layout"> I am a generic page </t> </t>''', 'key': 'test.base_view', }) self.page = Page.create({ 'view_id': self.base_view.id, 'url': '/page_1', 'is_published': True, }) def test_unpublished_page(self): specific_page = self.page.copy({'website_id': self.env['website'].get_current_website().id}) specific_page.write({'is_published': False, 'arch': self.page.arch.replace('I am a generic page', 'I am a specific page')}) self.authenticate(None, None) r = self.url_open(specific_page.url) self.assertEqual(r.status_code, 404, "Restricted users should see a 404 and not the generic one as we unpublished the specific one") self.authenticate('admin', 'admin') r = self.url_open(specific_page.url) self.assertEqual(r.status_code, 200, "Admin should see the specific unpublished page") self.assertEqual('I am a specific page' in r.text, True, "Admin should see the specific unpublished page") def test_search(self): dbname = common.get_db_name() admin_uid = self.env.ref('base.user_admin').id website = self.env['website'].get_current_website() robot = self.xmlrpc_object.execute( dbname, admin_uid, 'admin', 'website', 'search_pages', [website.id], 'info' ) self.assertIn({'loc': '/website/info'}, robot) pages = self.xmlrpc_object.execute( dbname, admin_uid, 'admin', 'website', 'search_pages', [website.id], 'page' ) self.assertIn( '/page_1', [p['loc'] for p in pages], ) @mute_logger('odoo.addons.http_routing.models.ir_http') def test_03_error_page_debug(self): with MockRequest(self.env, website=self.env['website'].browse(1)): self.base_view.arch = self.base_view.arch.replace('I am a generic page', '<t t-esc="15/0"/>') r = self.url_open(self.page.url) self.assertEqual(r.status_code, 500, "15/0 raise a 500 error page") self.assertNotIn('ZeroDivisionError: division by zero', r.text, "Error should not be shown when not in debug.") r = self.url_open(self.page.url + '?debug=1') self.assertEqual(r.status_code, 500, "15/0 raise a 500 error page (2)") self.assertIn('ZeroDivisionError: division by zero', r.text, "Error should be shown in debug.") def test_homepage_not_slash_url(self): website = self.env['website'].browse([1]) # Set another page (/page_1) as homepage website.write({ 'homepage_id': self.page.id, 'domain': f"http://{HOST}:{config['http_port']}", }) assert self.page.url != '/' r = self.url_open('/') r.raise_for_status() self.assertEqual(r.status_code, 200, "There should be no crash when a public user is accessing `/` which is rerouting to another page with a different URL.") root_html = html.fromstring(r.content) canonical_url = root_html.xpath('//link[@rel="canonical"]')[0].attrib['href'] self.assertEqual(canonical_url, website.domain + "/") def test_page_url_case_insensitive_match(self): r = self.url_open('/page_1') self.assertEqual(r.status_code, 200, "Reaching page URL, common case") r2 = self.url_open('/Page_1', allow_redirects=False) self.assertEqual(r2.status_code, 303, "URL exists only in different casing, should redirect to it") self.assertTrue(r2.headers.get('Location').endswith('/page_1'), "Should redirect /Page_1 to /page_1") @tagged('-at_install', 'post_install') class TestNewPage(common.TransactionCase): def test_new_page_used_key(self): website = self.env.ref('website.default_website') controller = Website() with MockRequest(self.env, website=website): controller.pagenew(path="snippets") pages = self.env['website.page'].search([('url', '=', '/snippets')]) self.assertEqual(len(pages), 1, "Exactly one page should be at /snippets.") self.assertNotEqual(pages.key, "website.snippets", "Page's key cannot be website.snippets.")
49.285246
15,032
15,250
py
PYTHON
15.0
# coding: utf-8 # Part of Odoo. See LICENSE file for full copyright and licensing details. from contextlib import contextmanager from datetime import datetime, timedelta from unittest.mock import patch from odoo.addons.base.tests.common import HttpCaseWithUserDemo from odoo.addons.website.tools import MockRequest from odoo.addons.website.models.website_visitor import WebsiteVisitor from odoo.tests import common, tagged class MockVisitor(common.BaseCase): @contextmanager def mock_visitor_from_request(self, force_visitor=False): def _get_visitor_from_request(model, *args, **kwargs): return force_visitor with patch.object(WebsiteVisitor, '_get_visitor_from_request', autospec=True, wraps=WebsiteVisitor, side_effect=_get_visitor_from_request) as _get_visitor_from_request_mock: yield @tagged('-at_install', 'post_install', 'website_visitor') class WebsiteVisitorTests(MockVisitor, HttpCaseWithUserDemo): def setUp(self): super(WebsiteVisitorTests, self).setUp() self.website = self.env['website'].search([ ('company_id', '=', self.env.user.company_id.id) ], limit=1) self.cookies = {} untracked_view = self.env['ir.ui.view'].create({ 'name': 'UntackedView', 'type': 'qweb', 'arch': '''<t name="Homepage" t-name="website.base_view"> <t t-call="website.layout"> I am a generic page² </t> </t>''', 'key': 'test.base_view', 'track': False, }) tracked_view = self.env['ir.ui.view'].create({ 'name': 'TrackedView', 'type': 'qweb', 'arch': '''<t name="Homepage" t-name="website.base_view"> <t t-call="website.layout"> I am a generic page </t> </t>''', 'key': 'test.base_view', 'track': True, }) tracked_view_2 = self.env['ir.ui.view'].create({ 'name': 'TrackedView2', 'type': 'qweb', 'arch': '''<t name="OtherPage" t-name="website.base_view"> <t t-call="website.layout"> I am a generic second page </t> </t>''', 'key': 'test.base_view', 'track': True, }) [self.untracked_page, self.tracked_page, self.tracked_page_2] = self.env['website.page'].create([ { 'view_id': untracked_view.id, 'url': '/untracked_view', 'website_published': True, }, { 'view_id': tracked_view.id, 'url': '/tracked_view', 'website_published': True, }, { 'view_id': tracked_view_2.id, 'url': '/tracked_view_2', 'website_published': True, }, ]) self.user_portal = self.env['res.users'].search([('login', '=', 'portal')]) self.partner_portal = self.user_portal.partner_id if not self.user_portal: self.env['ir.config_parameter'].sudo().set_param('auth_password_policy.minlength', 4) self.partner_portal = self.env['res.partner'].create({ 'name': 'Joel Willis', 'email': '[email protected]', }) self.user_portal = self.env['res.users'].create({ 'login': 'portal', 'password': 'portal', 'partner_id': self.partner_portal.id, 'groups_id': [(6, 0, [self.env.ref('base.group_portal').id])], }) def _get_last_visitor(self): return self.env['website.visitor'].search([], limit=1, order="id DESC") def assertPageTracked(self, visitor, page): """ Check a page is in visitor tracking data """ self.assertIn(page, visitor.website_track_ids.page_id) self.assertIn(page, visitor.page_ids) def assertVisitorTracking(self, visitor, pages): """ Check the whole tracking history of a visitor """ for page in pages: self.assertPageTracked(visitor, page) self.assertEqual( len(visitor.website_track_ids), len(pages) ) def assertVisitorDeactivated(self, visitor, main_visitor): """ Temporary method to check that a visitor has been de-activated / merged with other visitor, notably in case of login (see User.authenticate() as well as Visitor._link_to_visitor() ). As final result depends on installed modules (see overrides) due to stable improvements linked to EventOnline, this method contains a hack to avoid doing too much overrides just for that behavior. """ if 'parent_id' in self.env['website.visitor']: self.assertTrue(bool(visitor)) self.assertFalse(visitor.active) self.assertTrue(main_visitor.active) self.assertEqual(visitor.parent_id, main_visitor) else: self.assertFalse(visitor) self.assertTrue(bool(main_visitor)) def test_visitor_creation_on_tracked_page(self): """ Test various flows involving visitor creation and update. """ existing_visitors = self.env['website.visitor'].search([]) existing_tracks = self.env['website.track'].search([]) self.url_open(self.untracked_page.url) self.url_open(self.tracked_page.url) self.url_open(self.tracked_page.url) new_visitor = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) new_track = self.env['website.track'].search([('id', 'not in', existing_tracks.ids)]) self.assertEqual(len(new_visitor), 1, "1 visitor should be created") self.assertEqual(len(new_track), 1, "There should be 1 tracked page") self.assertEqual(new_visitor.visit_count, 1) self.assertEqual(new_visitor.website_track_ids, new_track) self.assertVisitorTracking(new_visitor, self.tracked_page) # ------------------------------------------------------------ # Admin connects # ------------------------------------------------------------ self.cookies = {'visitor_uuid': new_visitor.access_token} with MockRequest(self.env, website=self.website, cookies=self.cookies): self.authenticate(self.user_admin.login, 'admin') visitor_admin = new_visitor # visit a page self.url_open(self.tracked_page_2.url) # check tracking and visitor / user sync self.assertVisitorTracking(visitor_admin, self.tracked_page | self.tracked_page_2) self.assertEqual(visitor_admin.partner_id, self.partner_admin) self.assertEqual(visitor_admin.name, self.partner_admin.name) # ------------------------------------------------------------ # Portal connects # ------------------------------------------------------------ with MockRequest(self.env, website=self.website, cookies=self.cookies): self.authenticate(self.user_portal.login, 'portal') self.assertFalse( self.env['website.visitor'].search([('id', 'not in', (existing_visitors | visitor_admin).ids)]), "No extra visitor should be created") # visit a page self.url_open(self.tracked_page.url) self.url_open(self.untracked_page.url) self.url_open(self.tracked_page_2.url) self.url_open(self.tracked_page_2.url) # 2 time to be sure it does not record twice # new visitor is created new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) self.assertEqual(len(new_visitors), 2, "One extra visitor should be created") visitor_portal = new_visitors[0] self.assertEqual(visitor_portal.partner_id, self.partner_portal) self.assertEqual(visitor_portal.name, self.partner_portal.name) self.assertVisitorTracking(visitor_portal, self.tracked_page | self.tracked_page_2) # ------------------------------------------------------------ # Back to anonymous # ------------------------------------------------------------ # portal user disconnects self.logout() # visit some pages self.url_open(self.tracked_page.url) self.url_open(self.untracked_page.url) self.url_open(self.tracked_page_2.url) self.url_open(self.tracked_page_2.url) # 2 time to be sure it does not record twice # new visitor is created new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) self.assertEqual(len(new_visitors), 3, "One extra visitor should be created") visitor_anonymous = new_visitors[0] self.cookies['visitor_uuid'] = visitor_anonymous.access_token self.assertFalse(visitor_anonymous.name) self.assertFalse(visitor_anonymous.partner_id) self.assertVisitorTracking(visitor_anonymous, self.tracked_page | self.tracked_page_2) visitor_anonymous_tracks = visitor_anonymous.website_track_ids # ------------------------------------------------------------ # Admin connects again # ------------------------------------------------------------ with MockRequest(self.env, website=self.website, cookies=self.cookies): self.authenticate(self.user_admin.login, 'admin') # one visitor is deleted visitor_anonymous = self.env['website.visitor'].with_context(active_test=False).search([('id', '=', visitor_anonymous.id)]) self.assertVisitorDeactivated(visitor_anonymous, visitor_admin) new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) self.assertEqual(new_visitors, visitor_admin | visitor_portal) visitor_admin = self.env['website.visitor'].search([('partner_id', '=', self.partner_admin.id)]) # tracks are linked self.assertTrue(visitor_anonymous_tracks < visitor_admin.website_track_ids) self.assertEqual(len(visitor_admin.website_track_ids), 4, "There should be 4 tracked page for the admin") # ------------------------------------------------------------ # Back to anonymous # ------------------------------------------------------------ # admin disconnects self.logout() # visit some pages self.url_open(self.tracked_page.url) self.url_open(self.untracked_page.url) self.url_open(self.tracked_page_2.url) self.url_open(self.tracked_page_2.url) # 2 time to be sure it does not record twice # new visitor created new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) self.assertEqual(len(new_visitors), 3, "One extra visitor should be created") visitor_anonymous_2 = new_visitors[0] self.cookies['visitor_uuid'] = visitor_anonymous_2.access_token self.assertFalse(visitor_anonymous_2.name) self.assertFalse(visitor_anonymous_2.partner_id) self.assertVisitorTracking(visitor_anonymous_2, self.tracked_page | self.tracked_page_2) visitor_anonymous_2_tracks = visitor_anonymous_2.website_track_ids # ------------------------------------------------------------ # Portal connects again # ------------------------------------------------------------ with MockRequest(self.env, website=self.website, cookies=self.cookies): self.authenticate(self.user_portal.login, 'portal') # one visitor is deleted new_visitors = self.env['website.visitor'].search([('id', 'not in', existing_visitors.ids)]) self.assertEqual(new_visitors, visitor_admin | visitor_portal) # tracks are linked self.assertTrue(visitor_anonymous_2_tracks < visitor_portal.website_track_ids) self.assertEqual(len(visitor_portal.website_track_ids), 4, "There should be 4 tracked page for the portal user") # simulate the portal user comes back 30min later for track in visitor_portal.website_track_ids: track.write({'visit_datetime': track.visit_datetime - timedelta(minutes=30)}) # visit a page self.url_open(self.tracked_page.url) visitor_portal.invalidate_cache(fnames=['website_track_ids']) # tracks are created self.assertEqual(len(visitor_portal.website_track_ids), 5, "There should be 5 tracked page for the portal user") # simulate the portal user comes back 8hours later visitor_portal.write({'last_connection_datetime': visitor_portal.last_connection_datetime - timedelta(hours=8)}) self.url_open(self.tracked_page.url) visitor_portal.invalidate_cache(fnames=['visit_count']) # check number of visits self.assertEqual(visitor_portal.visit_count, 2, "There should be 2 visits for the portal user") def test_visitor_archive(self): """ Test cron archiving inactive visitors and their re-activation when authenticating an user. """ self.env['ir.config_parameter'].sudo().set_param('website.visitor.live.days', 7) partner_demo = self.partner_demo old_visitor = self.env['website.visitor'].create({ 'lang_id': self.env.ref('base.lang_en').id, 'country_id': self.env.ref('base.be').id, 'website_id': 1, 'partner_id': partner_demo.id, }) self.assertTrue(old_visitor.active) self.assertEqual(partner_demo.visitor_ids, old_visitor, "Visitor and its partner should be synchronized") # archive old visitor old_visitor.last_connection_datetime = datetime.now() - timedelta(days=8) self.env['website.visitor']._cron_archive_visitors() self.assertEqual(old_visitor.active, False, "Visitor should be archived after inactivity") # reconnect with new visitor. self.url_open(self.tracked_page.url) new_visitor = self._get_last_visitor() self.assertFalse(new_visitor.partner_id) self.assertTrue(new_visitor.id > old_visitor.id, "A new visitor should have been created.") self.assertVisitorTracking(new_visitor, self.tracked_page) with self.mock_visitor_from_request(force_visitor=new_visitor): self.authenticate('demo', 'demo') (new_visitor | old_visitor).flush() partner_demo.flush() partner_demo.invalidate_cache(fnames=['visitor_ids']) self.assertEqual(partner_demo.visitor_ids, old_visitor, "The partner visitor should be back to the 'old' visitor.") new_visitor = self.env['website.visitor'].search([('id', '=', new_visitor.id)]) self.assertEqual(len(new_visitor), 0, "The new visitor should be deleted when visitor authenticate once again.") self.assertEqual(old_visitor.active, True, "The old visitor should be reactivated when visitor authenticates once again.")
46.776074
15,249
470
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, tagged @tagged('-at_install', 'post_install') class TestAuthSignupUninvited(common.TransactionCase): def test_01_auth_signup_uninvited(self): self.env['website'].browse(1).auth_signup_uninvited = 'b2c' config = self.env['res.config.settings'].create({}) self.assertEqual(config.auth_signup_uninvited, 'b2c')
36.153846
470
7,186
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml.html import document_fromstring import odoo.tests class TestUrlCommon(odoo.tests.HttpCase): def setUp(self): super(TestUrlCommon, self).setUp() self.domain = 'http://' + odoo.tests.HOST self.website = self.env['website'].create({ 'name': 'test base url', 'domain': self.domain, }) lang_fr = self.env['res.lang']._activate_lang('fr_FR') self.website.language_ids = self.env.ref('base.lang_en') + lang_fr self.website.default_lang_id = self.env.ref('base.lang_en') def _assertCanonical(self, url, canonical_url): res = self.url_open(url) canonical_link = document_fromstring(res.content).xpath("/html/head/link[@rel='canonical']") self.assertEqual(len(canonical_link), 1) self.assertEqual(canonical_link[0].attrib["href"], canonical_url) @odoo.tests.tagged('-at_install', 'post_install') class TestBaseUrl(TestUrlCommon): def test_01_base_url(self): ICP = self.env['ir.config_parameter'] icp_base_url = ICP.sudo().get_param('web.base.url') # Test URL is correct for the website itself when the domain is set self.assertEqual(self.website.get_base_url(), self.domain) # Test URL is correct for a model without website_id without_website_id = self.env['ir.attachment'].create({'name': 'test base url'}) self.assertEqual(without_website_id.get_base_url(), icp_base_url) # Test URL is correct for a model with website_id... with_website_id = self.env['res.partner'].create({'name': 'test base url'}) # ...when no website is set on the model with_website_id.website_id = False self.assertEqual(with_website_id.get_base_url(), icp_base_url) # ...when the website is correctly set with_website_id.website_id = self.website self.assertEqual(with_website_id.get_base_url(), self.domain) # ...when the set website doesn't have a domain self.website.domain = False self.assertEqual(with_website_id.get_base_url(), icp_base_url) # Test URL is correct for the website itself when no domain is set self.assertEqual(self.website.get_base_url(), icp_base_url) # Test URL is correctly auto fixed domains = [ # trailing / ("https://www.monsite.com/", "https://www.monsite.com"), # no scheme ("www.monsite.com", "https://www.monsite.com"), ("monsite.com", "https://monsite.com"), # respect scheme ("https://www.monsite.com", "https://www.monsite.com"), ("http://www.monsite.com", "http://www.monsite.com"), # respect port ("www.monsite.com:8069", "https://www.monsite.com:8069"), ("www.monsite.com:8069/", "https://www.monsite.com:8069"), # no guess wwww ("monsite.com", "https://monsite.com"), # mix ("www.monsite.com/", "https://www.monsite.com"), ] for (domain, expected) in domains: self.website.domain = domain self.assertEqual(self.website.get_base_url(), expected) def test_02_canonical_url(self): # test does not work in local due to port self._assertCanonical('/', self.website.get_base_url() + '/') self._assertCanonical('/?debug=1', self.website.get_base_url() + '/') self._assertCanonical('/a-page', self.website.get_base_url() + '/a-page') self._assertCanonical('/en_US', self.website.get_base_url() + '/') self._assertCanonical('/fr_FR', self.website.get_base_url() + '/fr') @odoo.tests.tagged('-at_install', 'post_install') class TestGetBaseUrl(odoo.tests.TransactionCase): def test_01_get_base_url(self): # Setup web_base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') company_1 = self.env['res.company'].create({ 'name': 'Company 1', }) company_2 = self.env['res.company'].create({ 'name': 'Company 2', }) # Finish setup & Check cache self.assertFalse(company_1.website_id, "No website yet created for this company.") website_1_domain = 'https://my-website.net' website_1 = self.env['website'].create({ 'name': 'Website Test 1', 'domain': website_1_domain, 'company_id': company_1.id, }) self.assertEqual(website_1, company_1.website_id, "Company cache for `website_id` should have been invalidated and recomputed.") # Check `get_base_url()` through `website_id` & `company_id` properties attach = self.env['ir.attachment'].create({'name': 'test base url', 'website_id': website_1.id}) self.assertEqual(attach.get_base_url(), website_1_domain, "Domain should be the one from the record.website_id.") attach.write({'company_id': company_2.id, 'website_id': False}) self.assertEqual(attach.get_base_url(), web_base_url, "Domain should be the one from the ICP as the record as no website_id, and it's company_id has no website_id.") attach.write({'company_id': company_1.id}) self.assertEqual(attach.get_base_url(), website_1_domain, "Domain should be the one from the record.company_id.website_id.") # Check advanced cache behavior.. website_2_domain = 'https://my-website-2.net' website_2 = self.env['website'].create({ 'name': 'Website Test 2', 'domain': website_2_domain, 'company_id': company_1.id, 'sequence': website_1.sequence - 1, }) # .. on create .. self.assertEqual(attach.get_base_url(), website_2_domain, "Domain should be the one from the record.company_id.website_id and company_1.website_id should be the one with lowest sequence.") website_1.sequence = website_2.sequence - 1 # .. on `sequence` write .. self.assertEqual(attach.get_base_url(), website_1_domain, "Lowest sequence is now website_2, so record.company_id.website_id should be website_1 as cache should be invalidated.") website_1.company_id = company_2.id # .. on `company_id` write.. self.assertEqual(attach.get_base_url(), website_2_domain, "Cache should be recomputed, only website_1 remains for company_2.") website_2.unlink() # .. on unlink .. self.assertEqual(attach.get_base_url(), web_base_url, "Cache should be recomputed, no more website for company_1.") def test_02_get_base_url_recordsets(self): Attachment = self.env['ir.attachment'] web_base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') self.assertEqual(Attachment.get_base_url(), web_base_url, "Empty recordset should get ICP value.") with self.assertRaises(ValueError): # if more than one record, an error we should be raised Attachment.search([], limit=2).get_base_url()
47.589404
7,186
13,533
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import odoo import odoo.tests @odoo.tests.tagged('-at_install', 'post_install') class TestUiCustomizeTheme(odoo.tests.HttpCase): def test_01_attachment_website_unlink(self): ''' Some ir.attachment needs to be unlinked when a website is unlink, otherwise some flows will just crash. That's the case when 2 website have their theme color customized. Removing a website will make its customized attachment generic, thus having 2 attachments with the same URL available for other websites, leading to singleton errors (among other). But no all attachment should be deleted, eg we don't want to delete a SO or invoice PDF coming from an ecommerce order. ''' Website = self.env['website'] Page = self.env['website.page'] Attachment = self.env['ir.attachment'] website_default = Website.browse(1) website_test = Website.create({'name': 'Website Test'}) # simulate attachment state when editing 2 theme through customize custom_url = '/TEST/website/static/src/scss/options/colors/user_theme_color_palette.custom.web.assets_common.scss' scss_attachment = Attachment.create({ 'name': custom_url, 'type': 'binary', 'mimetype': 'text/scss', 'datas': '', 'url': custom_url, 'website_id': website_default.id }) scss_attachment.copy({'website_id': website_test.id}) # simulate PDF from ecommerce order # Note: it will only have its website_id flag if the website has a domain # equal to the current URL (fallback or get_current_website()) so_attachment = Attachment.create({ 'name': 'SO036.pdf', 'type': 'binary', 'mimetype': 'application/pdf', 'datas': '', 'website_id': website_test.id }) # avoid sql error on page website_id restrict Page.search([('website_id', '=', website_test.id)]).unlink() website_test.unlink() self.assertEqual(Attachment.search_count([('url', '=', custom_url)]), 1, 'Should not left duplicates when deleting a website') self.assertTrue(so_attachment.exists(), 'Most attachment should not be deleted') self.assertFalse(so_attachment.website_id, 'Website should be removed') @odoo.tests.tagged('-at_install', 'post_install') class TestUiHtmlEditor(odoo.tests.HttpCase): def test_html_editor_multiple_templates(self): Website = self.env['website'] View = self.env['ir.ui.view'] Page = self.env['website.page'] self.generic_view = View.create({ 'name': 'Generic', 'type': 'qweb', 'arch': ''' <div>content</div> ''', 'key': 'test.generic_view', }) self.generic_page = Page.create({ 'view_id': self.generic_view.id, 'url': '/generic', }) generic_page = Website.viewref('test.generic_view') # Use an empty page layout with oe_structure id for this test oe_structure_layout = ''' <t name="Generic" t-name="test.generic_view"> <t t-call="website.layout"> <div id="oe_structure_test_ui" class="oe_structure oe_empty"/> </t> </t> ''' generic_page.arch = oe_structure_layout self.start_tour("/", 'html_editor_multiple_templates', login='admin') self.assertEqual(View.search_count([('key', '=', 'test.generic_view')]), 2, "homepage view should have been COW'd") self.assertTrue(generic_page.arch == oe_structure_layout, "Generic homepage view should be untouched") self.assertEqual(len(generic_page.inherit_children_ids.filtered(lambda v: 'oe_structure' in v.name)), 0, "oe_structure view should have been deleted when aboutus was COW") specific_page = Website.with_context(website_id=1).viewref('test.generic_view') self.assertTrue(specific_page.arch != oe_structure_layout, "Specific homepage view should have been changed") self.assertEqual(len(specific_page.inherit_children_ids.filtered(lambda v: 'oe_structure' in v.name)), 1, "oe_structure view should have been created on the specific tree") def test_html_editor_scss(self): self.env.ref('base.user_demo').write({ 'groups_id': [(6, 0, [ self.env.ref('base.group_user').id, self.env.ref('website.group_website_designer').id ])] }) self.start_tour("/", 'test_html_editor_scss', login='admin', timeout=120) def media_dialog_undraw(self): self.start_tour("/", 'website_media_dialog_undraw', login='admin') @odoo.tests.tagged('-at_install', 'post_install') class TestUiTranslate(odoo.tests.HttpCase): def test_admin_tour_rte_translator(self): self.env['res.lang'].create({ 'name': 'Parseltongue', 'code': 'pa_GB', 'iso_code': 'pa_GB', 'url_code': 'pa_GB', }) self.start_tour("/", 'rte_translator', login='admin', timeout=120) @odoo.tests.common.tagged('post_install', '-at_install') class TestUi(odoo.tests.HttpCase): def test_01_admin_tour_homepage(self): self.start_tour("/?enable_editor=1", 'homepage', login='admin') def test_02_restricted_editor(self): self.restricted_editor = self.env['res.users'].create({ 'name': 'Restricted Editor', 'login': 'restricted', 'password': 'restricted', 'groups_id': [(6, 0, [ self.ref('base.group_user'), self.ref('website.group_website_publisher') ])] }) self.start_tour("/", 'restricted_editor', login='restricted') def test_03_backend_dashboard(self): self.start_tour("/", 'backend_dashboard', login='admin') def test_04_website_navbar_menu(self): website = self.env['website'].search([], limit=1) self.env['website.menu'].create({ 'name': 'Test Tour Menu', 'url': '/test-tour-menu', 'parent_id': website.menu_id.id, 'sequence': 0, 'website_id': website.id, }) self.start_tour("/", 'website_navbar_menu') def test_05_specific_website_editor(self): website_default = self.env['website'].search([], limit=1) new_website = self.env['website'].create({'name': 'New Website'}) code = b"document.body.dataset.hello = 'world';" attach = self.env['ir.attachment'].create({ 'name': 'EditorExtension.js', 'mimetype': 'text/javascript', 'datas': base64.b64encode(code), }) custom_url = '/web/content/%s/%s' % (attach.id, attach.name) attach.url = custom_url self.env['ir.asset'].create({ 'name': 'EditorExtension', 'bundle': 'website.assets_wysiwyg', 'path': custom_url, 'website_id': new_website.id, }) self.start_tour("/website/force/%s" % website_default.id, "generic_website_editor", login='admin') self.start_tour("/website/force/%s" % new_website.id, "specific_website_editor", login='admin') def test_06_public_user_editor(self): website_default = self.env['website'].search([], limit=1) website_default.homepage_id.arch = """ <t name="Homepage" t-name="website.homepage"> <t t-call="website.layout"> <textarea class="o_public_user_editor_test_textarea o_wysiwyg_loader"/> </t> </t> """ self.start_tour("/", "public_user_editor", login=None) def test_07_snippet_version(self): website_snippets = self.env.ref('website.snippets') self.env['ir.ui.view'].create([{ 'name': 'Test snip', 'type': 'qweb', 'key': 'website.s_test_snip', 'arch': """ <section class="s_test_snip"> <t t-snippet-call="website.s_share"/> </section> """, }, { 'type': 'qweb', 'inherit_id': website_snippets.id, 'arch': """ <xpath expr="//t[@t-snippet='website.s_parallax']" position="after"> <t t-snippet="website.s_test_snip" t-thumbnail="/website/static/src/img/snippets_thumbs/s_website_form.svg"/> </xpath> """, }]) self.start_tour("/", 'snippet_version', login='admin') def test_08_website_style_custo(self): self.start_tour("/", "website_style_edition", login="admin") def test_09_website_edit_link_popover(self): self.start_tour("/", "edit_link_popover", login="admin") def test_10_website_conditional_visibility(self): self.start_tour('/', 'conditional_visibility_1', login='admin') self.start_tour('/', 'conditional_visibility_2', login='admin') self.start_tour('/', 'conditional_visibility_3', login='admin') self.start_tour('/', 'conditional_visibility_4', login='admin') def test_11_website_snippet_background_edition(self): self.env['ir.attachment'].create({ 'public': True, 'type': 'url', 'url': '/web/image/123/test.png', 'name': 'test.png', 'mimetype': 'image/png', }) self.start_tour('/', 'snippet_background_edition', login='admin') def test_12_edit_translated_page_redirect(self): lang = self.env['res.lang']._activate_lang('nl_NL') self.env['website'].browse(1).write({'language_ids': [(4, lang.id, 0)]}) self.start_tour("/nl/contactus", 'edit_translated_page_redirect', login='admin') def test_13_editor_focus_blur_unit_test(self): # TODO this should definitely not be a website python tour test but # while waiting for a proper web_editor qunit JS test suite for the # editor, it is better than no test at all as this was broken multiple # times already. self.env["ir.ui.view"].create([{ 'name': 's_focusblur', 'key': 'website.s_focusblur', 'type': 'qweb', 'arch': """ <section class="s_focusblur bg-success py-5"> <div class="container"> <div class="row"> <div class="col-lg-6 s_focusblur_child1 bg-warning py-5"></div> <div class="col-lg-6 s_focusblur_child2 bg-danger py-5"></div> </div> </div> </section> """, }, { 'name': 's_focusblur_snippets', 'mode': 'extension', 'inherit_id': self.env.ref('website.snippets').id, 'key': 'website.s_focusblur_snippets', 'type': 'qweb', 'arch': """ <data> <xpath expr="//*[@id='snippet_structure']//t[@t-snippet]" position="before"> <t t-snippet="website.s_focusblur"/> </xpath> </data> """, }, { 'name': 's_focusblur_options', 'mode': 'extension', 'inherit_id': self.env.ref('web_editor.snippet_options').id, 'key': 'website.s_focusblur_options', 'type': 'qweb', 'arch': """ <data> <xpath expr="."> <div data-js="FocusBlurParent" data-selector=".s_focusblur"/> <div data-js="FocusBlurChild1" data-selector=".s_focusblur_child1"/> <div data-js="FocusBlurChild2" data-selector=".s_focusblur_child2"/> </xpath> </data> """, }]) self.start_tour("/?enable_editor=1", "focus_blur_snippets", login="admin") def test_14_carousel_snippet_content_removal(self): self.start_tour("/", "carousel_content_removal", login='admin') def test_15_website_link_tools(self): self.start_tour("/", "link_tools", login="admin") def test_16_website_edit_megamenu(self): self.start_tour("/", "edit_megamenu", login="admin") def test_17_website_edit_menus(self): self.start_tour("/", "edit_menus", login="admin") def test_18_website_snippets_menu_tabs(self): self.start_tour("/?enable_editor=1", "website_snippets_menu_tabs", login="admin") def test_19_website_page_options(self): self.start_tour("/?enable_editor=1", "website_page_options", login="admin") def test_29_website_backend_menus_redirect(self): Menu = self.env['ir.ui.menu'] menu_root = Menu.create({'name': 'Test Root'}) Menu.create({ 'name': 'Test Child', 'parent_id': menu_root.id, 'action': 'ir.actions.act_window,%d' % (self.env.ref('base.open_module_tree').id,), }) self.env.ref('base.user_admin').action_id = self.env.ref('base.menu_administration').id self.assertFalse(menu_root.action, 'The top menu should not have an action (or the test/tour will not test anything).') self.start_tour('/', 'website_backend_menus_redirect', login='admin')
42.556604
13,533
76,578
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import unittest from itertools import zip_longest from lxml import etree as ET, html from lxml.html import builder as h from odoo.tests import common, HttpCase, tagged def attrs(**kwargs): return {'data-oe-%s' % key: str(value) for key, value in kwargs.items()} class TestViewSavingCommon(common.TransactionCase): def _create_imd(self, view): xml_id = view.key.split('.') return self.env['ir.model.data'].create({ 'module': xml_id[0], 'name': xml_id[1], 'model': view._name, 'res_id': view.id, }) class TestViewSaving(TestViewSavingCommon): def eq(self, a, b): self.assertEqual(a.tag, b.tag) self.assertEqual(a.attrib, b.attrib) self.assertEqual((a.text or '').strip(), (b.text or '').strip()) self.assertEqual((a.tail or '').strip(), (b.tail or '').strip()) for ca, cb in zip_longest(a, b): self.eq(ca, cb) def setUp(self): super(TestViewSaving, self).setUp() self.arch = h.DIV( h.DIV( h.H3("Column 1"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("Item 1"), h.LI(h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char'))), h.LI(h.SPAN("+00 00 000 00 0 000", attrs(model='res.company', id=1, field='phone', type='char'))) )) ) self.view_id = self.env['ir.ui.view'].create({ 'name': "Test View", 'type': 'qweb', 'key': 'website.test_view', 'arch': ET.tostring(self.arch, encoding='unicode') }) def test_embedded_extraction(self): fields = self.env['ir.ui.view'].extract_embedded_fields(self.arch) expect = [ h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char')), h.SPAN("+00 00 000 00 0 000", attrs(model='res.company', id=1, field='phone', type='char')), ] for actual, expected in zip_longest(fields, expect): self.eq(actual, expected) def test_embedded_save(self): embedded = h.SPAN("+00 00 000 00 0 000", attrs( model='res.company', id=1, field='phone', type='char')) self.env['ir.ui.view'].save_embedded_field(embedded) company = self.env['res.company'].browse(1) self.assertEqual(company.phone, "+00 00 000 00 0 000") @unittest.skip("save conflict for embedded (saved by third party or previous version in page) not implemented") def test_embedded_conflict(self): e1 = h.SPAN("My Company", attrs(model='res.company', id=1, field='name')) e2 = h.SPAN("Leeroy Jenkins", attrs(model='res.company', id=1, field='name')) View = self.env['ir.ui.view'] View.save_embedded_field(e1) # FIXME: more precise exception with self.assertRaises(Exception): View.save_embedded_field(e2) def test_embedded_to_field_ref(self): View = self.env['ir.ui.view'] embedded = h.SPAN("My Company", attrs(expression="bob")) self.eq( View.to_field_ref(embedded), h.SPAN({'t-field': 'bob'}) ) def test_to_field_ref_keep_attributes(self): View = self.env['ir.ui.view'] att = attrs(expression="bob", model="res.company", id=1, field="name") att['id'] = "whop" att['class'] = "foo bar" embedded = h.SPAN("My Company", att) self.eq(View.to_field_ref(embedded), h.SPAN({'t-field': 'bob', 'class': 'foo bar', 'id': 'whop'})) def test_replace_arch(self): replacement = h.P("Wheee") result = self.view_id.replace_arch_section(None, replacement) self.eq(result, h.DIV("Wheee")) def test_replace_arch_2(self): replacement = h.DIV(h.P("Wheee")) result = self.view_id.replace_arch_section(None, replacement) self.eq(result, replacement) def test_fixup_arch(self): replacement = h.H1("I am the greatest title alive!") result = self.view_id.replace_arch_section('/div/div[1]/h3', replacement) self.eq(result, h.DIV( h.DIV( h.H3("I am the greatest title alive!"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("Item 1"), h.LI(h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char'))), h.LI(h.SPAN("+00 00 000 00 0 000", attrs(model='res.company', id=1, field='phone', type='char'))) )) )) def test_multiple_xpath_matches(self): with self.assertRaises(ValueError): self.view_id.replace_arch_section('/div/div/h3', h.H6("Lol nope")) def test_save(self): Company = self.env['res.company'] # create an xmlid for the view imd = self._create_imd(self.view_id) self.assertEqual(self.view_id.model_data_id, imd) self.assertFalse(imd.noupdate) replacement = ET.tostring(h.DIV( h.H3("Column 2"), h.UL( h.LI("wob wob wob"), h.LI(h.SPAN("Acme Corporation", attrs(model='res.company', id=1, field='name', expression="bob", type='char'))), h.LI(h.SPAN("+12 3456789", attrs(model='res.company', id=1, field='phone', expression="edmund", type='char'))), ) ), encoding='unicode') self.view_id.with_context(website_id=1).save(value=replacement, xpath='/div/div[2]') self.assertFalse(imd.noupdate, "view's xml_id shouldn't be set to 'noupdate' in a website context as `save` method will COW") # remove newly created COW view so next `save()`` wont be redirected to COW view self.env['website'].with_context(website_id=1).viewref(self.view_id.key).unlink() self.view_id.save(value=replacement, xpath='/div/div[2]') # the xml_id of the view should be flagged as 'noupdate' self.assertTrue(imd.noupdate) company = Company.browse(1) self.assertEqual(company.name, "Acme Corporation") self.assertEqual(company.phone, "+12 3456789") self.eq( ET.fromstring(self.view_id.arch), h.DIV( h.DIV( h.H3("Column 1"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("wob wob wob"), h.LI(h.SPAN({'t-field': "bob"})), h.LI(h.SPAN({'t-field': "edmund"})) )) ) ) def test_save_escaped_text(self): """ Test saving html special chars in text nodes """ view = self.env['ir.ui.view'].create({ 'arch': u'<t t-name="dummy"><p><h1>hello world</h1></p></t>', 'type': 'qweb' }) # script and style text nodes should not escaped client side replacement = u'<script>1 && "hello & world"</script>' view.save(replacement, xpath='/t/p/h1') self.assertIn( replacement.replace(u'&', u'&amp;'), view.arch, 'inline script should be escaped server side' ) self.assertIn( replacement, view._render(), 'inline script should not be escaped when rendering' ) # common text nodes should be be escaped client side replacement = u'world &amp;amp; &amp;lt;b&amp;gt;cie' view.save(replacement, xpath='/t/p') self.assertIn(replacement, view.arch, 'common text node should not be escaped server side') self.assertIn( replacement, str(view._render()).replace(u'&', u'&amp;'), 'text node characters wrongly unescaped when rendering' ) def test_save_oe_structure_with_attr(self): """ Test saving oe_structure with attributes """ view = self.env['ir.ui.view'].create({ 'arch': u'<t t-name="dummy"><div class="oe_structure" t-att-test="1" data-test="1" id="oe_structure_test"/></t>', 'type': 'qweb' }).with_context(website_id=1, load_all_views=True) replacement = u'<div class="oe_structure" data-test="1" id="oe_structure_test" data-oe-id="55" test="2">hello</div>' view.save(replacement, xpath='/t/div') # branding data-oe-* should be stripped self.assertIn( '<div class="oe_structure" data-test="1" id="oe_structure_test" test="2">hello</div>', view.get_combined_arch(), 'saved element attributes are saved excluding branding ones' ) def test_save_only_embedded(self): Company = self.env['res.company'] company_id = 1 company = Company.browse(company_id) company.write({'name': "Foo Corporation"}) node = html.tostring(h.SPAN( "Acme Corporation", attrs(model='res.company', id=company_id, field="name", expression='bob', type='char')), encoding='unicode') View = self.env['ir.ui.view'] View.browse(company_id).save(value=node) self.assertEqual(company.name, "Acme Corporation") def test_field_tail(self): replacement = ET.tostring( h.LI(h.SPAN("+12 3456789", attrs( model='res.company', id=1, type='char', field='phone', expression="edmund")), "whop whop" ), encoding="utf-8") self.view_id.save(value=replacement, xpath='/div/div[2]/ul/li[3]') self.eq( ET.fromstring(self.view_id.arch.encode('utf-8')), h.DIV( h.DIV( h.H3("Column 1"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("Item 1"), h.LI(h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char'))), h.LI(h.SPAN({'t-field': "edmund"}), "whop whop"), )) ) ) @tagged('-at_install', 'post_install') class TestCowViewSaving(TestViewSavingCommon): def setUp(self): super(TestCowViewSaving, self).setUp() View = self.env['ir.ui.view'] self.base_view = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': '<div>base content</div>', 'key': 'website.base_view', }).with_context(load_all_views=True) self.inherit_view = View.create({ 'name': 'Extension', 'mode': 'extension', 'inherit_id': self.base_view.id, 'arch': '<div position="inside">, extended content</div>', 'key': 'website.extension_view', }) def test_cow_on_base_after_extension(self): View = self.env['ir.ui.view'] self.inherit_view.with_context(website_id=1).write({'name': 'Extension Specific'}) v1 = self.base_view v2 = self.inherit_view v3 = View.search([('website_id', '=', 1), ('name', '=', 'Extension Specific')]) v4 = self.inherit_view.copy({'name': 'Second Extension'}) v5 = self.inherit_view.copy({'name': 'Third Extension (Specific)'}) v5.write({'website_id': 1}) # id | name | website_id | inherit | key # ------------------------------------------------------------------------ # 1 | Base | / | / | website.base_view # 2 | Extension | / | 1 | website.extension_view # 3 | Extension Specific | 1 | 1 | website.extension_view # 4 | Second Extension | / | 1 | website.extension_view_a5f579d5 (generated hash) # 5 | Third Extension (Specific) | 1 | 1 | website.extension_view_5gr87e6c (another generated hash) self.assertEqual(v2.key == v3.key, True, "Making specific a generic inherited view should copy it's key (just change the website_id)") self.assertEqual(v3.key != v4.key != v5.key, True, "Copying a view should generate a new key for the new view (not the case when triggering COW)") self.assertEqual('website.extension_view' in v3.key and 'website.extension_view' in v4.key and 'website.extension_view' in v5.key, True, "The copied views should have the key from the view it was copied from but with an unique suffix") total_views = View.search_count([]) v1.with_context(website_id=1).write({'name': 'Base Specific'}) # id | name | website_id | inherit | key # ------------------------------------------------------------------------ # 1 | Base | / | / | website.base_view # 2 | Extension | / | 1 | website.extension_view # 3 - DELETED # 4 | Second Extension | / | 1 | website.extension_view_a5f579d5 # 5 - DELETED # 6 | Base Specific | 1 | / | website.base_view # 7 | Extension Specific | 1 | 6 | website.extension_view # 8 | Second Extension | 1 | 6 | website.extension_view_a5f579d5 # 9 | Third Extension (Specific) | 1 | 6 | website.extension_view_5gr87e6c v6 = View.search([('website_id', '=', 1), ('name', '=', 'Base Specific')]) v7 = View.search([('website_id', '=', 1), ('name', '=', 'Extension Specific')]) v8 = View.search([('website_id', '=', 1), ('name', '=', 'Second Extension')]) v9 = View.search([('website_id', '=', 1), ('name', '=', 'Third Extension (Specific)')]) self.assertEqual(total_views + 4 - 2, View.search_count([]), "It should have duplicated the view tree with a website_id, taking only most specific (only specific `b` key), and removing website_specific from generic tree") self.assertEqual(len((v3 + v5).exists()), 0, "v3 and v5 should have been deleted as they were already specific and copied to the new specific base") # Check generic tree self.assertEqual((v1 + v2 + v4).mapped('website_id').ids, []) self.assertEqual((v2 + v4).mapped('inherit_id'), v1) # Check specific tree self.assertEqual((v6 + v7 + v8 + v9).mapped('website_id').ids, [1]) self.assertEqual((v7 + v8 + v9).mapped('inherit_id'), v6) # Check key self.assertEqual(v6.key == v1.key, True) self.assertEqual(v7.key == v2.key, True) self.assertEqual(v4.key == v8.key, True) self.assertEqual(View.search_count([('key', '=', v9.key)]), 1) def test_cow_leaf(self): View = self.env['ir.ui.view'] # edit on backend, regular write self.inherit_view.write({'arch': '<div position="replace"><div>modified content</div></div>'}) self.assertEqual(View.search_count([('key', '=', 'website.base_view')]), 1) self.assertEqual(View.search_count([('key', '=', 'website.extension_view')]), 1) arch = self.base_view.get_combined_arch() self.assertEqual(arch, '<div>modified content</div>') # edit on frontend, copy just the leaf self.inherit_view.with_context(website_id=1).write({'arch': '<div position="replace"><div>website 1 content</div></div>'}) inherit_views = View.search([('key', '=', 'website.extension_view')]) self.assertEqual(View.search_count([('key', '=', 'website.base_view')]), 1) self.assertEqual(len(inherit_views), 2) self.assertEqual(len(inherit_views.filtered(lambda v: v.website_id.id == 1)), 1) # read in backend should be unaffected arch = self.base_view.get_combined_arch() self.assertEqual(arch, '<div>modified content</div>') # read on website should reflect change arch = self.base_view.with_context(website_id=1).get_combined_arch() self.assertEqual(arch, '<div>website 1 content</div>') # website-specific inactive view should take preference over active generic one when viewing the website # this is necessary to make customize_show=True templates work correctly inherit_views.filtered(lambda v: v.website_id.id == 1).write({'active': False}) arch = self.base_view.with_context(website_id=1).get_combined_arch() self.assertEqual(arch, '<div>base content</div>') def test_cow_root(self): View = self.env['ir.ui.view'] # edit on backend, regular write self.base_view.write({'arch': '<div>modified base content</div>'}) self.assertEqual(View.search_count([('key', '=', 'website.base_view')]), 1) self.assertEqual(View.search_count([('key', '=', 'website.extension_view')]), 1) # edit on frontend, copy the entire tree self.base_view.with_context(website_id=1).write({'arch': '<div>website 1 content</div>'}) generic_base_view = View.search([('key', '=', 'website.base_view'), ('website_id', '=', False)]) website_specific_base_view = View.search([('key', '=', 'website.base_view'), ('website_id', '=', 1)]) self.assertEqual(len(generic_base_view), 1) self.assertEqual(len(website_specific_base_view), 1) inherit_views = View.search([('key', '=', 'website.extension_view')]) self.assertEqual(len(inherit_views), 2) self.assertEqual(len(inherit_views.filtered(lambda v: v.website_id.id == 1)), 1) arch = generic_base_view.with_context(load_all_views=True).get_combined_arch() self.assertEqual(arch, '<div>modified base content, extended content</div>') arch = website_specific_base_view.with_context(load_all_views=True, website_id=1).get_combined_arch() self.assertEqual(arch, '<div>website 1 content, extended content</div>') # # As there is a new SQL constraint that prevent QWeb views to have an empty `key`, this test won't work # def test_cow_view_without_key(self): # # Remove key for this test # self.base_view.key = False # # View = self.env['ir.ui.view'] # # # edit on backend, regular write # self.base_view.write({'arch': '<div>modified base content</div>'}) # self.assertEqual(self.base_view.key, False, "Writing on a keyless view should not set a key on it if there is no website in context") # # # edit on frontend, copy just the leaf # self.base_view.with_context(website_id=1).write({'arch': '<div position="replace"><div>website 1 content</div></div>'}) # self.assertEqual('website.key_' in self.base_view.key, True, "Writing on a keyless view should set a key on it if there is a website in context") # total_views_with_key = View.search_count([('key', '=', self.base_view.key)]) # self.assertEqual(total_views_with_key, 2, "It should have set the key on generic view then copy to specific view (with they key)") def test_cow_generic_view_with_already_existing_specific(self): """ Writing on a generic view should check if a website specific view already exists (The flow of this test will happen when editing a generic view in the front end and changing more than one element) """ # 1. Test with calling write directly View = self.env['ir.ui.view'] base_view = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': '<div>content</div>', }) total_views = View.with_context(active_test=False).search_count([]) base_view.with_context(website_id=1).write({'name': 'New Name'}) # This will not write on `base_view` but will copy it to a specific view on which the `name` change will be applied specific_view = View.search([['name', '=', 'New Name'], ['website_id', '=', 1]]) base_view.with_context(website_id=1).write({'name': 'Another New Name'}) specific_view.active = False base_view.with_context(website_id=1).write({'name': 'Yet Another New Name'}) self.assertEqual(total_views + 1, View.with_context(active_test=False).search_count([]), "Subsequent writes should have written on the view copied during first write") # 2. Test with calling save() from ir.ui.view view_arch = '''<t name="Second View" t-name="website.second_view"> <t t-call="website.layout"> <div id="wrap"> <div class="editable_part"/> <div class="container"> <h1>Second View</h1> </div> <div class="editable_part"/> </div> </t> </t>''' second_view = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': view_arch, }) total_views = View.with_context(active_test=False).search_count([]) second_view.with_context(website_id=1).save('<div class="editable_part" data-oe-id="%s" data-oe-xpath="/t[1]/t[1]/div[1]/div[1]" data-oe-field="arch" data-oe-model="ir.ui.view">First editable_part</div>' % second_view.id, "/t[1]/t[1]/div[1]/div[1]") second_view.with_context(website_id=1).save('<div class="editable_part" data-oe-id="%s" data-oe-xpath="/t[1]/t[1]/div[1]/div[3]" data-oe-field="arch" data-oe-model="ir.ui.view">Second editable_part</div>' % second_view.id, "/t[1]/t[1]/div[1]/div[3]") self.assertEqual(total_views + 1, View.with_context(active_test=False).search_count([]), "Second save should have written on the view copied during first save") total_specific_view = View.with_context(active_test=False).search_count([('arch_db', 'like', 'First editable_part'), ('arch_db', 'like', 'Second editable_part')]) self.assertEqual(total_specific_view, 1, "both editable_part should have been replaced on a created specific view") def test_cow_complete_flow(self): View = self.env['ir.ui.view'] total_views = View.search_count([]) self.base_view.write({'arch': '<div>Hi</div>'}) self.inherit_view.write({'arch': '<div position="inside"> World</div>'}) # id | name | content | website_id | inherit | key # ------------------------------------------------------- # 1 | Base | Hi | / | / | website.base_view # 2 | Extension | World | / | 1 | website.extension_view arch = self.base_view.with_context(website_id=1).get_combined_arch() self.assertIn('Hi World', arch) self.base_view.write({'arch': '<div>Hello</div>'}) # id | name | content | website_id | inherit | key # ------------------------------------------------------- # 1 | Base | Hello | / | / | website.base_view # 2 | Extension | World | / | 1 | website.extension_view arch = self.base_view.with_context(website_id=1).get_combined_arch() self.assertIn('Hello World', arch) self.base_view.with_context(website_id=1).write({'arch': '<div>Bye</div>'}) # id | name | content | website_id | inherit | key # ------------------------------------------------------- # 1 | Base | Hello | / | / | website.base_view # 3 | Base | Bye | 1 | / | website.base_view # 2 | Extension | World | / | 1 | website.extension_view # 4 | Extension | World | 1 | 3 | website.extension_view base_specific = View.search([('key', '=', self.base_view.key), ('website_id', '=', 1)]).with_context(load_all_views=True) extend_specific = View.search([('key', '=', self.inherit_view.key), ('website_id', '=', 1)]) self.assertEqual(total_views + 2, View.search_count([]), "Should have copied Base & Extension with a website_id") self.assertEqual(self.base_view.key, base_specific.key) self.assertEqual(self.inherit_view.key, extend_specific.key) extend_specific.write({'arch': '<div position="inside"> All</div>'}) # id | name | content | website_id | inherit | key # ------------------------------------------------------- # 1 | Base | Hello | / | / | website.base_view # 3 | Base | Bye | 1 | / | website.base_view # 2 | Extension | World | / | 1 | website.extension_view # 4 | Extension | All | 1 | 3 | website.extension_view arch = base_specific.with_context(website_id=1).get_combined_arch() self.assertEqual('Bye All' in arch, True) self.inherit_view.with_context(website_id=1).write({'arch': '<div position="inside"> Nobody</div>'}) # id | name | content | website_id | inherit | key # ------------------------------------------------------- # 1 | Base | Hello | / | / | website.base_view # 3 | Base | Bye | 1 | / | website.base_view # 2 | Extension | World | / | 1 | website.extension_view # 4 | Extension | Nobody | 1 | 3 | website.extension_view arch = base_specific.with_context(website_id=1).get_combined_arch() self.assertEqual('Bye Nobody' in arch, True, "Write on generic `inherit_view` should have been diverted to already existing specific view") base_arch = self.base_view.get_combined_arch() base_arch_w1 = self.base_view.with_context(website_id=1).get_combined_arch() self.assertEqual('Hello World' in base_arch, True) self.assertEqual(base_arch, base_arch_w1, "Reading a top level view with or without a website_id in the context should render that exact view..") # ..even if there is a specific view for that one, as get_combined_arch is supposed to render specific inherited view over generic but not specific top level instead of generic top level def test_cow_cross_inherit(self): View = self.env['ir.ui.view'] total_views = View.search_count([]) main_view = View.create({ 'name': 'Main View', 'type': 'qweb', 'arch': '<body>GENERIC<div>A</div></body>', 'key': 'website.main_view', }).with_context(load_all_views=True) View.create({ 'name': 'Child View', 'mode': 'extension', 'inherit_id': main_view.id, 'arch': '<xpath expr="//div" position="replace"><div>VIEW<p>B</p></div></xpath>', 'key': 'website.child_view', }) child_view_2 = View.with_context(load_all_views=True).create({ 'name': 'Child View 2', 'mode': 'extension', 'inherit_id': main_view.id, 'arch': '<xpath expr="//p" position="replace"><span>C</span></xpath>', 'key': 'website.child_view_2', }) # These line doing `write()` are the real tests, it should not be changed and should not crash on xpath. child_view_2.with_context(website_id=1).write({'arch': '<xpath expr="//p" position="replace"><span>D</span></xpath>'}) self.assertEqual(total_views + 3 + 1, View.search_count([]), "It should have created the 3 initial generic views and created a child_view_2 specific view") main_view.with_context(website_id=1).write({'arch': '<body>SPECIFIC<div>Z</div></body>'}) self.assertEqual(total_views + 3 + 3, View.search_count([]), "It should have duplicated the Main View tree as a specific tree and then removed the specific view from the generic tree as no more needed") generic_view = View.with_context(website_id=None).get_view_id('website.main_view') specific_view = View.with_context(website_id=1).get_view_id('website.main_view') generic_view_arch = View.browse(generic_view).with_context(load_all_views=True).get_combined_arch() specific_view_arch = View.browse(specific_view).with_context(load_all_views=True, website_id=1).get_combined_arch() self.assertEqual(generic_view_arch, '<body>GENERIC<div>VIEW<span>C</span></div></body>') self.assertEqual(specific_view_arch, '<body>SPECIFIC<div>VIEW<span>D</span></div></body>', "Writing on top level view hierarchy with a website in context should write on the view and clone it's inherited views") def test_multi_website_view_obj_active(self): ''' With the following structure: * A generic active parent view * A generic active child view, that is inactive on website 1 The methods to retrieve views should return the specific inactive child over the generic active one. ''' View = self.env['ir.ui.view'] self.inherit_view.with_context(website_id=1).write({'active': False}) # Test _view_obj() return the inactive specific over active generic inherit_view = View._view_obj(self.inherit_view.key) self.assertEqual(inherit_view.active, True, "_view_obj should return the generic one") inherit_view = View.with_context(website_id=1)._view_obj(self.inherit_view.key) self.assertEqual(inherit_view.active, False, "_view_obj should return the specific one") # Test get_related_views() return the inactive specific over active generic # Note that we cannot test get_related_views without a website in context as it will fallback on a website with get_current_website() views = View.with_context(website_id=1).get_related_views(self.base_view.key) self.assertEqual(views.mapped('active'), [True, False], "get_related_views should return the specific child") # Test filter_duplicate() return the inactive specific over active generic view = View.with_context(active_test=False).search([('key', '=', self.inherit_view.key)]).filter_duplicate() self.assertEqual(view.active, True, "filter_duplicate should return the generic one") view = View.with_context(active_test=False, website_id=1).search([('key', '=', self.inherit_view.key)]).filter_duplicate() self.assertEqual(view.active, False, "filter_duplicate should return the specific one") def test_get_related_views_tree(self): View = self.env['ir.ui.view'] self.base_view.write({'name': 'B', 'key': 'B'}) self.inherit_view.write({'name': 'I', 'key': 'I'}) View.create({ 'name': 'II', 'mode': 'extension', 'inherit_id': self.inherit_view.id, 'arch': '<div position="inside">, sub ext</div>', 'key': 'II', }) # B # | # I # | # II # First, test that children of inactive children are not returned (not multiwebsite related) self.inherit_view.active = False views = View.get_related_views('B') self.assertEqual(views.mapped('key'), ['B', 'I'], "As 'I' is inactive, 'II' (its own child) should not be returned.") self.inherit_view.active = True # Second, test multi-website self.inherit_view.with_context(website_id=1).write({'name': 'Extension'}) # Trigger cow on hierarchy View.create({ 'name': 'II2', 'mode': 'extension', 'inherit_id': self.inherit_view.id, 'arch': '<div position="inside">, sub sibling specific</div>', 'key': 'II2', }) # B # / \ # / \ # I I' # / \ | # II II2 II' views = View.with_context(website_id=1).get_related_views('B') self.assertEqual(views.mapped('key'), ['B', 'I', 'II'], "Should only return the specific tree") def test_get_related_views_tree_recursive_t_call_and_inherit_inactive(self): """ If a view A was doing a t-call on a view B and view B had view C as child. And view A had view D as child. And view D also t-call view B (that as mentionned above has view C as child). And view D was inactive (`d` in bellow schema). Then COWing C to set it as inactive would make `get_related_views()` on A to return both generic active C and COW inactive C. (Typically the case for Customize show on /shop for Wishlist, compare..) See commit message for detailed explanation. """ # A -> B # | ^ \ # | | C # d ___| View = self.env['ir.ui.view'] Website = self.env['website'] products = View.create({ 'name': 'Products', 'type': 'qweb', 'key': '_website_sale.products', 'arch': ''' <div id="products_grid"> <t t-call="_website_sale.products_item"/> </div> ''', }) products_item = View.create({ 'name': 'Products item', 'type': 'qweb', 'key': '_website_sale.products_item', 'arch': ''' <div class="product_price"/> ''', }) add_to_wishlist = View.create({ 'name': 'Wishlist', 'active': True, 'customize_show': True, 'inherit_id': products_item.id, 'key': '_website_sale_wishlist.add_to_wishlist', 'arch': ''' <xpath expr="//div[hasclass('product_price')]" position="inside"></xpath> ''', }) products_list_view = View.create({ 'name': 'List View', 'active': False, # <- That's the reason of why this behavior needed a fix 'customize_show': True, 'inherit_id': products.id, 'key': '_website_sale.products_list_view', 'arch': ''' <div id="products_grid" position="replace"> <t t-call="_website_sale.products_item"/> </div> ''', }) views = View.with_context(website_id=1).get_related_views('_website_sale.products') self.assertEqual(views, products + products_item + add_to_wishlist + products_list_view, "The four views should be returned.") add_to_wishlist.with_context(website_id=1).write({'active': False}) # Trigger cow on hierarchy add_to_wishlist_cow = Website.with_context(website_id=1).viewref(add_to_wishlist.key) views = View.with_context(website_id=1).get_related_views('_website_sale.products') self.assertEqual(views, products + products_item + add_to_wishlist_cow + products_list_view, "The generic wishlist view should have been replaced by the COW one.") def test_cow_inherit_children_order(self): """ COW method should loop on inherit_children_ids in correct order when copying them on the new specific tree. Correct order is the same as the one when applying view arch: PRIORITY, ID And not the default one from ir.ui.view (NAME, PRIORITY, ID). """ self.inherit_view.copy({ 'name': 'alphabetically before "Extension"', 'key': '_test.alphabetically_first', 'arch': '<div position="replace"><p>COMPARE</p></div>', }) # Next line should not crash, COW loop on inherit_children_ids should be sorted correctly self.base_view.with_context(website_id=1).write({'name': 'Product (W1)'}) def test_write_order_vs_cow_inherit_children_order(self): """ When both a specific inheriting view and a non-specific base view are written simultaneously, the specific inheriting base view must be updated even though its id will change during the COW of the base view. """ View = self.env['ir.ui.view'] self.inherit_view.with_context(website_id=1).write({'name': 'Specific Inherited View Changed First'}) specific_view = View.search([('name', '=', 'Specific Inherited View Changed First')]) views = View.browse([self.base_view.id, specific_view.id]) views.with_context(website_id=1).write({'active': False}) new_specific_view = View.search([('name', '=', 'Specific Inherited View Changed First')]) self.assertTrue(specific_view.id != new_specific_view.id, "Should have a new id") self.assertFalse(new_specific_view.active, "Should have been deactivated") def test_write_order_vs_cow_inherit_children_order_alt(self): """ Same as the previous test, but requesting the update in the opposite order. """ View = self.env['ir.ui.view'] self.inherit_view.with_context(website_id=1).write({'name': 'Specific Inherited View Changed First'}) specific_view = View.search([('name', '=', 'Specific Inherited View Changed First')]) views = View.browse([specific_view.id, self.base_view.id]) views.with_context(website_id=1).write({'active': False}) new_specific_view = View.search([('name', '=', 'Specific Inherited View Changed First')]) self.assertTrue(specific_view.id != new_specific_view.id, "Should have a new id") self.assertFalse(new_specific_view.active, "Should have been deactivated") def test_module_new_inherit_view_on_parent_already_forked(self): """ If a generic parent view is copied (COW) and that another module creates a child view for that generic parent, all the COW views should also get a copy of that new child view. Typically, a parent view (website_sale.product) is copied (COW) and then wishlist module is installed. Wishlist views inhering from website_sale.product are added to the generic `website_sale.product`. But it should also be added to the COW `website_sale.product` to activate the module views for that website. """ Website = self.env['website'] View = self.env['ir.ui.view'] # Simulate website_sale product view self.base_view.write({'name': 'Product', 'key': '_website_sale.product'}) # Trigger cow on website_sale hierarchy for website 1 self.base_view.with_context(website_id=1).write({'name': 'Product (W1)'}) # Simulate website_sale_comparison install View._load_records([dict(xml_id='_website_sale_comparison.product_add_to_compare', values={ 'name': 'Add to comparison in product page', 'mode': 'extension', 'inherit_id': self.base_view.id, 'arch': '<div position="replace"><p>COMPARE</p></div>', 'key': '_website_sale_comparison.product_add_to_compare', })]) Website.with_context(load_all_views=True).viewref('_website_sale_comparison.product_add_to_compare').invalidate_cache() # Simulate end of installation/update View._create_all_specific_views(['_website_sale_comparison']) specific_view = Website.with_context(load_all_views=True, website_id=1).viewref('_website_sale.product') self.assertEqual(self.base_view.key, specific_view.key, "Ensure it is equal as it should be for the rest of the test so we test the expected behaviors") specific_view_arch = specific_view.get_combined_arch() self.assertEqual(specific_view.website_id.id, 1, "Ensure we got specific view to perform the checks against") self.assertEqual(specific_view_arch, '<p>COMPARE</p>', "When a module creates an inherited view (on a generic tree), it should also create that view in the specific COW'd tree.") # Simulate website_sale_comparison update View._load_records([dict(xml_id='_website_sale_comparison.product_add_to_compare', values={ 'arch': '<div position="replace"><p>COMPARE EDITED</p></div>', })]) specific_view_arch = Website.with_context(load_all_views=True, website_id=1).viewref('_website_sale.product').get_combined_arch() self.assertEqual(specific_view_arch, '<p>COMPARE EDITED</p>', "When a module updates an inherited view (on a generic tree), it should also update the copies of that view (COW).") # Test fields that should not be COW'd random_views = View.search([('key', '!=', None)], limit=2) View._load_records([dict(xml_id='_website_sale_comparison.product_add_to_compare', values={ 'website_id': None, 'inherit_id': random_views[0].id, })]) w1_specific_child_view = Website.with_context(load_all_views=True, website_id=1).viewref('_website_sale_comparison.product_add_to_compare') generic_child_view = Website.with_context(load_all_views=True).viewref('_website_sale_comparison.product_add_to_compare') self.assertEqual(w1_specific_child_view.website_id.id, 1, "website_id is a prohibited field when COWing views during _load_records") self.assertEqual(generic_child_view.inherit_id, random_views[0], "prohibited fields only concerned write on COW'd view. Generic should still considere these fields") self.assertEqual(w1_specific_child_view.inherit_id, random_views[0], "inherit_id update should be repliacated on cow views during _load_records") # Set back the generic view as parent for the rest of the test generic_child_view.inherit_id = self.base_view w1_specific_child_view.inherit_id = specific_view # Don't update inherit_id if it was anually updated w1_specific_child_view.inherit_id = random_views[1].id View._load_records([dict(xml_id='_website_sale_comparison.product_add_to_compare', values={ 'inherit_id': random_views[0].id, })]) self.assertEqual(w1_specific_child_view.inherit_id, random_views[1], "inherit_id update should not be repliacated on cow views during _load_records if it was manually updated before") # Set back the generic view as parent for the rest of the test generic_child_view.inherit_id = self.base_view w1_specific_child_view.inherit_id = specific_view # Don't update fields from COW'd view if these fields have been modified from original view new_website = Website.create({'name': 'New Website'}) self.base_view.with_context(website_id=new_website.id).write({'name': 'Product (new_website)'}) new_website_specific_child_view = Website.with_context(load_all_views=True, website_id=new_website.id).viewref('_website_sale_comparison.product_add_to_compare') new_website_specific_child_view.priority = 6 View._load_records([dict(xml_id='_website_sale_comparison.product_add_to_compare', values={ 'priority': 3, })]) self.assertEqual(generic_child_view.priority, 3, "XML update should be written on the Generic View") self.assertEqual(w1_specific_child_view.priority, 3, "XML update should be written on the specific view if the fields have not been modified on that specific view") self.assertEqual(new_website_specific_child_view.priority, 6, "XML update should NOT be written on the specific view if the fields have been modified on that specific view") # Simulate website_sale update on top level view self._create_imd(self.base_view) self.base_view.invalidate_cache() View._load_records([dict(xml_id='_website_sale.product', values={ 'website_meta_title': 'A bug got fixed by updating this field', })]) all_title_updated = specific_view.website_meta_title == self.base_view.website_meta_title == "A bug got fixed by updating this field" self.assertEqual(all_title_updated, True, "Update on top level generic views should also be applied on specific views") def test_module_new_inherit_view_on_parent_already_forked_xpath_replace(self): """ Deeper, more specific test of above behavior. A module install should add/update the COW view (if allowed fields, eg not modified or prohibited (website_id, inherit_id..)). This test ensure it does not crash if the child view is a primary view. """ View = self.env['ir.ui.view'] # Simulate layout views base_view = View.create({ 'name': 'Main Frontend Layout', 'type': 'qweb', 'arch': '<t t-call="web.layout"><t t-set="head_website"/></t>', 'key': '_portal.frontend_layout', }).with_context(load_all_views=True) inherit_view = View.create({ 'name': 'Main layout', 'mode': 'extension', 'inherit_id': base_view.id, 'arch': '<xpath expr="//t[@t-set=\'head_website\']" position="replace"><t t-call-assets="assets_summernote" t-js="false" groups="website.group_website_publisher"/></xpath>', 'key': '_website.layout', }) # Trigger cow on website_sale hierarchy for website 1 base_view.with_context(website_id=1).write({'name': 'Main Frontend Layout (W1)'}) # Simulate website_sale_comparison install, that's the real test, it # should not crash. View._load_records([dict(xml_id='_website_forum.layout', values={ 'name': 'Forum Layout', 'mode': 'primary', 'inherit_id': inherit_view.id, 'arch': '<xpath expr="//t[@t-call-assets=\'assets_summernote\'][@t-js=\'false\']" position="attributes"><attribute name="groups"/></xpath>', 'key': '_website_forum.layout', })]) def test_multiple_inherit_level(self): """ Test multi-level inheritance: Base | ---> Extension (Website-specific) | ---> Extension 2 (Website-specific) """ View = self.env['ir.ui.view'] self.inherit_view.website_id = 1 inherit_view_2 = View.create({ 'name': 'Extension 2', 'mode': 'extension', 'inherit_id': self.inherit_view.id, 'arch': '<div position="inside">, extended content 2</div>', 'key': 'website.extension_view_2', 'website_id': 1, }) total_views = View.search_count([]) # id | name | content | website_id | inherit | key # -------------------------------------------------------------------------------------------- # 1 | Base | base content | / | / | website.base_view # 2 | Extension | , extended content | 1 | 1 | website.extension_view # 3 | Extension 2 | , extended content 2 | 1 | 2 | website.extension_view_2 self.base_view.with_context(website_id=1).write({'arch': '<div>modified content</div>'}) # 2 views are created, one is deleted self.assertEqual(View.search_count([]), total_views + 1) self.assertFalse(self.inherit_view.exists()) self.assertTrue(inherit_view_2.exists()) # Verify the inheritance base_specific = View.search([('key', '=', self.base_view.key), ('website_id', '=', 1)]).with_context(load_all_views=True) extend_specific = View.search([('key', '=', 'website.extension_view'), ('website_id', '=', 1)]) self.assertEqual(extend_specific.inherit_id, base_specific) self.assertEqual(inherit_view_2.inherit_id, extend_specific) # id | name | content | website_id | inherit | key # -------------------------------------------------------------------------------------------- # 1 | Base | base content | / | / | website.base_view # 4 | Base | modified content | 1 | / | website.base_view # 5 | Extension | , extended content | 1 | 4 | website.extension_view # 3 | Extension 2 | , extended content 2 | 1 | 5 | website.extension_view_2 def test_cow_extension_with_install(self): View = self.env['ir.ui.view'] # Base v1 = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': '<div>base content</div>', 'key': 'website.base_view_v1', }).with_context(load_all_views=True) self._create_imd(v1) # Extension v2 = View.create({ 'name': 'Extension', 'mode': 'extension', 'inherit_id': v1.id, 'arch': '<div position="inside"><ooo>extended content</ooo></div>', 'key': 'website.extension_view_v2', }) self._create_imd(v2) # multiwebsite specific v1.with_context(website_id=1).write({'name': 'Extension Specific'}) original_pool_init = View.pool._init View.pool._init = True try: # Simulate module install View._load_records([dict(xml_id='website.extension2_view', values={ 'name': ' ---', 'mode': 'extension', 'inherit_id': v1.id, 'arch': '<ooo position="replace"><p>EXTENSION</p></ooo>', 'key': 'website.extension2_view', })]) finally: View.pool._init = original_pool_init def test_specific_view_translation(self): Translation = self.env['ir.translation'] Translation.insert_missing(self.base_view._fields['arch_db'], self.base_view) translation = Translation.search([ ('res_id', '=', self.base_view.id), ('name', '=', 'ir.ui.view,arch_db') ]) translation.value = 'hello' translation.module = 'website' self.base_view.with_context(website_id=1).write({'active': True}) specific_view = self.base_view._get_specific_views() - self.base_view self.assertEqual(specific_view.with_context(lang='en_US').arch, '<div>hello</div>', "copy on write (COW) also copy existing translations") translation.value = 'hi' self.assertEqual(specific_view.with_context(lang='en_US').arch, '<div>hello</div>', "updating translation of base view doesn't update specific view") Translation._load_module_terms(['website'], ['en_US'], overwrite=True) specific_view.invalidate_cache(['arch_db', 'arch']) self.assertEqual(specific_view.with_context(lang='en_US').arch, '<div>hi</div>', "loading module translation copy translation from base to specific view") def test_soc_complete_flow(self): """ Check the creation of views from specific-website environments. """ View = self.env['ir.ui.view'] View.with_context(website_id=1).create({ 'name': 'Name', 'key': 'website.no_website_id', 'type': 'qweb', 'arch': '<data></data>', }) # Get created views by searching to consider potential unwanted COW created_views = View.search([('key', '=', 'website.no_website_id')]) self.assertEqual(len(created_views), 1, "Should only have created one view") self.assertEqual(created_views.website_id.id, 1, "The created view should be specific to website 1") with self.assertRaises(ValueError, msg="Should not allow to create generic view explicitely from website 1 specific context"): View.with_context(website_id=1).create({ 'name': 'Name', 'key': 'website.explicit_no_website_id', 'type': 'qweb', 'arch': '<data></data>', 'website_id': False, }) with self.assertRaises(ValueError, msg="Should not allow to create specific view for website 2 from website 1 specific context"): View.with_context(website_id=1).create({ 'name': 'Name', 'key': 'website.different_website_id', 'type': 'qweb', 'arch': '<data></data>', 'website_id': 2, }) def test_specific_view_module_update_inherit_change(self): """ During a module update, if inherit_id is changed, we need to replicate the change for cow views. """ # If D.inherit_id becomes B instead of A, after module update, we expect: # CASE 1 # A A' B A A' B # | | => / \ # D D' D D' # # CASE 2 # A A' B B' A A' B B' # | | => | | # D D' D D' # # CASE 3 # A B A B # / \ => / \ # D D' D D' # # CASE 4 # A B B' A B B' # / \ => | | # D D' D D' # 1. Setup following view trees # A A' B # | | # D D' View = self.env['ir.ui.view'] Website = self.env['website'] self._create_imd(self.inherit_view) # invalidate cache to recompute xml_id, or it will still be empty self.inherit_view.invalidate_cache() base_view_2 = self.base_view.copy({'key': 'website.base_view2', 'arch': '<div>base2 content</div>'}) self.base_view.with_context(website_id=1).write({'arch': '<div>website 1 content</div>'}) specific_view = Website.with_context(load_all_views=True, website_id=1).viewref(self.base_view.key) specific_view.inherit_children_ids.with_context(website_id=1).write({'arch': '<div position="inside">, extended content website 1</div>'}) specific_child_view = Website.with_context(load_all_views=True, website_id=1).viewref(self.inherit_view.key) # 2. Ensure view trees are as expected self.assertEqual(self.base_view.inherit_children_ids, self.inherit_view, "D should be under A") self.assertEqual(specific_view.inherit_children_ids, specific_child_view, "D' should be under A'") self.assertFalse(base_view_2.inherit_children_ids, "B should have no child") # 3. Simulate module update, D.inherit_id is now B instead of A View._load_records([dict(xml_id=self.inherit_view.key, values={ 'inherit_id': base_view_2.id, })]) # 4. Ensure view trees is now # A A' B # / \ # D D' self.assertTrue(len(self.base_view.inherit_children_ids) == len(specific_view.inherit_children_ids) == 0, "Child views should now be under view B") self.assertEqual(len(base_view_2.inherit_children_ids), 2, "D and D' should be under B") self.assertTrue(self.inherit_view in base_view_2.inherit_children_ids, "D should be under B") self.assertTrue(specific_child_view in base_view_2.inherit_children_ids, "D' should be under B") @tagged('-at_install', 'post_install') class Crawler(HttpCase): def setUp(self): super(Crawler, self).setUp() View = self.env['ir.ui.view'] self.base_view = View.create({ 'name': 'Base', 'type': 'qweb', 'arch': '<div>base content</div>', 'key': 'website.base_view', }).with_context(load_all_views=True) self.inherit_view = View.create({ 'name': 'Extension', 'mode': 'extension', 'inherit_id': self.base_view.id, 'arch': '<div position="inside">, extended content</div>', 'key': 'website.extension_view', }) def test_get_switchable_related_views(self): View = self.env['ir.ui.view'] Website = self.env['website'] # Set up website_1 = Website.create({'name': 'Website 1'}) # will have specific views website_2 = Website.create({'name': 'Website 2'}) # will use generic views self.base_view.write({'name': 'Main Frontend Layout', 'key': '_portal.frontend_layout'}) event_main_view = self.base_view.copy({ 'name': 'Events', 'key': '_website_event.index', 'arch': '<t t-call="_website.layout"><div>Arch is not important in this test</div></t>', }) self.inherit_view.write({'name': 'Main layout', 'key': '_website.layout'}) self.inherit_view.copy({'name': 'Sign In', 'customize_show': True, 'key': '_portal.user_sign_in'}) view_logo = self.inherit_view.copy({ 'name': 'Show Logo', 'inherit_id': self.inherit_view.id, 'customize_show': True, 'key': '_website.layout_logo_show', }) view_logo.copy({'name': 'Affix Top Menu', 'key': '_website.affix_top_menu'}) event_child_view = self.inherit_view.copy({ 'name': 'Filters', 'customize_show': True, 'inherit_id': event_main_view.id, 'key': '_website_event.event_left_column', 'priority': 30, }) view_photos = event_child_view.copy({'name': 'Photos', 'key': '_website_event.event_right_photos'}) event_child_view.copy({'name': 'Quotes', 'key': '_website_event.event_right_quotes', 'priority': 30}) event_child_view.copy({'name': 'Filter by Category', 'inherit_id': event_child_view.id, 'key': '_website_event.event_category'}) event_child_view.copy({'name': 'Filter by Country', 'inherit_id': event_child_view.id, 'key': '_website_event.event_location'}) View.flush() # Customize # | Main Frontend Layout # | Show Sign In # | Main Layout # | Affix Top Menu # | Show Logo # | Events # | Filters # | Photos # | Quotes # | Filters # | Filter By Category # | Filter By Country self.authenticate("admin", "admin") base_url = website_1.get_base_url() # Simulate website 2 (that use only generic views) self.url_open(base_url + '/website/force/%s' % website_2.id) # Test controller url = base_url + '/website/get_switchable_related_views' json = {'params': {'key': '_website_event.index'}} response = self.opener.post(url=url, json=json) res = response.json()['result'] self.assertEqual( [v['name'] for v in res], ['Sign In', 'Affix Top Menu', 'Show Logo', 'Filters', 'Photos', 'Quotes', 'Filter by Category', 'Filter by Country'], "Sequence should not be taken into account for customize menu", ) self.assertEqual( [v['inherit_id'][1] for v in res], ['Main Frontend Layout', 'Main layout', 'Main layout', 'Events', 'Events', 'Events', 'Filters', 'Filters'], "Sequence should not be taken into account for customize menu (Checking Customize headers)", ) # Trigger COW view_logo.with_context(website_id=website_1.id).write({'arch': '<div position="inside">, trigger COW, arch is not relevant in this test</div>'}) # This would wrongly become: # Customize # | Main Frontend Layout # | Show Sign In # | Main Layout # | Affix Top Menu # | Show Logo <==== Was above "Affix Top Menu" # | Events # | Filters # | Photos # | Quotes # | Filters # | Filter By Category # | Filter By Country # Simulate website 1 (that has specific views) self.url_open(base_url + '/website/force/%s' % website_1.id) # Test controller url = base_url + '/website/get_switchable_related_views' json = {'params': {'key': '_website_event.index'}} response = self.opener.post(url=url, json=json) res = response.json()['result'] self.assertEqual( [v['name'] for v in res], ['Sign In', 'Affix Top Menu', 'Show Logo', 'Filters', 'Photos', 'Quotes', 'Filter by Category', 'Filter by Country'], "multi-website COW should not impact customize views order (COW view will have a bigger ID and should not be last)", ) self.assertEqual( [v['inherit_id'][1] for v in res], ['Main Frontend Layout', 'Main layout', 'Main layout', 'Events', 'Events', 'Events', 'Filters', 'Filters'], "multi-website COW should not impact customize views menu header position or split (COW view will have a bigger ID and should not be last)", ) # Trigger COW view_photos.with_context(website_id=website_1.id).write({'arch': '<div position="inside">, trigger COW, arch is not relevant in this test</div>'}) # This would wrongly become: # Customize # | Main Frontend Layout # | Show Sign In # | Main Layout # | Affix Top Menu # | Show Logo # | Events # | Filters # | Quotes # | Filters # | Filter By Category # | Filter By Country # | Events <==== JS code creates a new Events header as the Event's children views are not one after the other anymore.. # | Photos <==== .. since Photos got duplicated and now have a bigger ID that others # Test controller url = base_url + '/website/get_switchable_related_views' json = {'params': {'key': '_website_event.index'}} response = self.opener.post(url=url, json=json) res = response.json()['result'] self.assertEqual( [v['name'] for v in res], ['Sign In', 'Affix Top Menu', 'Show Logo', 'Filters', 'Photos', 'Quotes', 'Filter by Category', 'Filter by Country'], "multi-website COW should not impact customize views order (COW view will have a bigger ID and should not be last) (2)", ) self.assertEqual( [v['inherit_id'][1] for v in res], ['Main Frontend Layout', 'Main layout', 'Main layout', 'Events', 'Events', 'Events', 'Filters', 'Filters'], "multi-website COW should not impact customize views menu header position or split (COW view will have a bigger ID and should not be last) (2)", ) def test_multi_website_views_retrieving(self): View = self.env['ir.ui.view'] Website = self.env['website'] website_1 = Website.create({'name': 'Website 1'}) website_2 = Website.create({'name': 'Website 2'}) main_view = View.create({ 'name': 'Products', 'type': 'qweb', 'arch': '<body>Arch is not relevant for this test</body>', 'key': '_website_sale.products', }).with_context(load_all_views=True) View.with_context(load_all_views=True).create({ 'name': 'Child View W1', 'mode': 'extension', 'inherit_id': main_view.id, 'arch': '<xpath expr="//body" position="replace">It is really not relevant!</xpath>', 'key': '_website_sale.child_view_w1', 'website_id': website_1.id, 'active': False, 'customize_show': True, }) # Simulate theme view instal + load on website theme_view = self.env['theme.ir.ui.view'].with_context(install_filename='/testviews').create({ 'name': 'Products Theme Kea', 'mode': 'extension', 'inherit_id': main_view, 'arch': '<xpath expr="//p" position="replace"><span>C</span></xpath>', 'key': '_theme_kea_sale.products', }) view_from_theme_view_on_w2 = View.with_context(load_all_views=True).create({ 'name': 'Products Theme Kea', 'mode': 'extension', 'inherit_id': main_view.id, 'arch': '<xpath expr="//body" position="replace">Really really not important for this test</xpath>', 'key': '_theme_kea_sale.products', 'website_id': website_2.id, 'customize_show': True, }) self.env['ir.model.data'].create({ 'module': '_theme_kea_sale', 'name': 'products', 'model': 'theme.ir.ui.view', 'res_id': theme_view.id, }) # ##################################################### ir.ui.view ############################################### # id | name | website_id | inherit | key | xml_id | # ---------------------------------------------------------------------------------------------------------------- # 1 | Products | / | / | _website_sale.products | / | # 2 | Child View W1 | 1 | 1 | _website_sale.child_view_w1 | / | # 3 | Products Theme Kea | 2 | 1 | _theme_kea_sale.products | / | # ################################################# theme.ir.ui.view ############################################# # id | name | inherit | key | xml_id | # ---------------------------------------------------------------------------------------------------------------- # 1 | Products Theme Kea | 1 | _theme_kea_sale.products | _theme_kea_sale.products | with self.assertRaises(ValueError): # It should crash as it should not find a view on website 1 for '_theme_kea_sale.products', !!and certainly not a theme.ir.ui.view!!. view = View.with_context(website_id=website_1.id)._view_obj('_theme_kea_sale.products') view = View.with_context(website_id=website_2.id)._view_obj('_theme_kea_sale.products') self.assertEqual(len(view), 1, "It should find the ir.ui.view with key '_theme_kea_sale.products' on website 2..") self.assertEqual(view._name, 'ir.ui.view', "..and not a theme.ir.ui.view") views = View.with_context(website_id=website_1.id).get_related_views('_website_sale.products') self.assertEqual(len(views), 2, "It should not mix apples and oranges, only ir.ui.view ['_website_sale.products', '_website_sale.child_view_w1'] should be returned") views = View.with_context(website_id=website_2.id).get_related_views('_website_sale.products') self.assertEqual(len(views), 2, "It should not mix apples and oranges, only ir.ui.view ['_website_sale.products', '_theme_kea_sale.products'] should be returned") # Part 2 of the test, it test the same stuff but from a higher level (get_related_views ends up calling _view_obj) called_theme_view = self.env['theme.ir.ui.view'].with_context(install_filename='/testviews').create({ 'name': 'Called View Kea', 'arch': '<div></div>', 'key': '_theme_kea_sale.t_called_view', }) View.create({ 'name': 'Called View Kea', 'type': 'qweb', 'arch': '<div></div>', 'key': '_theme_kea_sale.t_called_view', 'website_id': website_2.id, }).with_context(load_all_views=True) self.env['ir.model.data'].create({ 'module': '_theme_kea_sale', 'name': 't_called_view', 'model': 'theme.ir.ui.view', 'res_id': called_theme_view.id, }) view_from_theme_view_on_w2.write({'arch': '<t t-call="_theme_kea_sale.t_called_view"/>'}) # ##################################################### ir.ui.view ############################################### # id | name | website_id | inherit | key | xml_id | # ---------------------------------------------------------------------------------------------------------------- # 1 | Products | / | / | _website_sale.products | / | # 2 | Child View W1 | 1 | 1 | _website_sale.child_view_w1 | / | # 3 | Products Theme Kea | 2 | 1 | _theme_kea_sale.products | / | # 4 | Called View Kea | 2 | / | _theme_kea_sale.t_called_view | / | # ################################################# theme.ir.ui.view ############################################# # id | name | inherit | key | xml_id | # ---------------------------------------------------------------------------------------------------------------- # 1 | Products Theme Kea | 1 | _theme_kea_sale.products | _theme_kea_sale.products | # 1 | Called View Kea | / | _theme_kea_sale.t_called_view | _theme_kea_sale.t_called_view | # Next line should not crash (was mixing apples and oranges - ir.ui.view and theme.ir.ui.view) views = View.with_context(website_id=website_1.id).get_related_views('_website_sale.products') self.assertEqual(len(views), 2, "It should not mix apples and oranges, only ir.ui.view ['_website_sale.products', '_website_sale.child_view_w1'] should be returned (2)") views = View.with_context(website_id=website_2.id).get_related_views('_website_sale.products') self.assertEqual(len(views), 3, "It should not mix apples and oranges, only ir.ui.view ['_website_sale.products', '_theme_kea_sale.products', '_theme_kea_sale.t_called_view'] should be returned") # ######################################################## # Test the controller (which is calling get_related_views) self.authenticate("admin", "admin") base_url = website_1.get_base_url() # Simulate website 2 self.url_open(base_url + '/website/force/%s' % website_2.id) # Test controller url = base_url + '/website/get_switchable_related_views' json = {'params': {'key': '_website_sale.products'}} response = self.opener.post(url=url, json=json) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json()['result']), 1, "Only '_theme_kea_sale.products' should be returned as it is the only customize_show related view in website 2 context") self.assertEqual(response.json()['result'][0]['key'], '_theme_kea_sale.products', "Only '_theme_kea_sale.products' should be returned") # Simulate website 1 self.url_open(base_url + '/website/force/%s' % website_1.id) # Test controller url = base_url + '/website/get_switchable_related_views' json = {'params': {'key': '_website_sale.products'}} response = self.opener.post(url=url, json=json) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json()['result']), 1, "Only '_website_sale.child_view_w1' should be returned as it is the only customize_show related view in website 1 context") self.assertEqual(response.json()['result'][0]['key'], '_website_sale.child_view_w1', "Only '_website_sale.child_view_w1' should be returned") @tagged('post_install', '-at_install') class TestThemeViews(common.TransactionCase): def test_inherit_specific(self): View = self.env['ir.ui.view'] Website = self.env['website'] website_1 = Website.create({'name': 'Website 1'}) # 1. Simulate COW structure main_view = View.create({ 'name': 'Test Main View', 'type': 'qweb', 'arch': '<body>Arch is not relevant for this test</body>', 'key': '_test.main_view', }).with_context(load_all_views=True) # Trigger COW main_view.with_context(website_id=website_1.id).arch = '<body>specific</body>' # 2. Simulate a theme install with a child view of `main_view` test_theme_module = self.env['ir.module.module'].create({'name': 'test_theme'}) self.env['ir.model.data'].create({ 'module': 'base', 'name': 'module_test_theme_module', 'model': 'ir.module.module', 'res_id': test_theme_module.id, }) theme_view = self.env['theme.ir.ui.view'].with_context(install_filename='/testviews').create({ 'name': 'Test Child View', 'mode': 'extension', 'inherit_id': 'ir.ui.view,%s' % main_view.id, 'arch': '<xpath expr="//body" position="replace"><span>C</span></xpath>', 'key': 'test_theme.test_child_view', }) self.env['ir.model.data'].create({ 'module': 'test_theme', 'name': 'products', 'model': 'theme.ir.ui.view', 'res_id': theme_view.id, }) test_theme_module.with_context(load_all_views=True)._theme_load(website_1) # 3. Ensure everything went correctly main_views = View.search([('key', '=', '_test.main_view')]) self.assertEqual(len(main_views), 2, "View should have been COWd when writing on its arch in a website context") specific_main_view = main_views.filtered(lambda v: v.website_id == website_1) specific_main_view_children = specific_main_view.inherit_children_ids self.assertEqual(specific_main_view_children.name, 'Test Child View', "Ensure theme.ir.ui.view has been loaded as an ir.ui.view into the website..") self.assertEqual(specific_main_view_children.website_id, website_1, "..and the website is the correct one.") # 4. Simulate theme update. Do it 2 time to make sure it was not interpreted as a user change the first time. new_arch = '<xpath expr="//body" position="replace"><span>Odoo Change01</span></xpath>' theme_view.arch = new_arch test_theme_module.with_context(load_all_views=True)._theme_load(website_1) self.assertEqual(specific_main_view_children.arch, new_arch, "First time: View arch should receive theme updates.") self.assertFalse(specific_main_view_children.arch_updated) new_arch = '<xpath expr="//body" position="replace"><span>Odoo Change02</span></xpath>' theme_view.arch = new_arch test_theme_module.with_context(load_all_views=True)._theme_load(website_1) self.assertEqual(specific_main_view_children.arch, new_arch, "Second time: View arch should still receive theme updates.") # 5. Keep User arch changes new_arch = '<xpath expr="//body" position="replace"><span>Odoo</span></xpath>' specific_main_view_children.arch = new_arch theme_view.name = 'Test Child View modified' test_theme_module.with_context(load_all_views=True)._theme_load(website_1) self.assertEqual(specific_main_view_children.arch, new_arch, "View arch shouldn't have been overrided on theme update as it was modified by user.") self.assertEqual(specific_main_view_children.name, 'Test Child View modified', "View should receive modification on theme update.")
51.222742
76,578
4,410
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import time import lxml.html from werkzeug import urls import odoo import re from odoo.addons.base.tests.common import HttpCaseWithUserDemo _logger = logging.getLogger(__name__) @odoo.tests.common.tagged('post_install', '-at_install', 'crawl') class Crawler(HttpCaseWithUserDemo): """ Test suite crawling an Odoo CMS instance and checking that all internal links lead to a 200 response. If a username and a password are provided, authenticates the user before starting the crawl """ def setUp(self): super(Crawler, self).setUp() if hasattr(self.env['res.partner'], 'grade_id'): # Create at least one published parter, so that /partners doesn't # return a 404 grade = self.env['res.partner.grade'].create({ 'name': 'A test grade', 'website_published': True, }) self.env['res.partner'].create({ 'name': 'A Company for /partners', 'is_company': True, 'grade_id': grade.id, 'website_published': True, }) def crawl(self, url, seen=None, msg=''): if seen is None: seen = set() url_slug = re.sub(r"[/](([^/=?&]+-)?[0-9]+)([/]|$)", '/<slug>/', url) url_slug = re.sub(r"([^/=?&]+)=[^/=?&]+", '\g<1>=param', url_slug) if url_slug in seen: return seen else: seen.add(url_slug) _logger.info("%s %s", msg, url) r = self.url_open(url, allow_redirects=False) if r.status_code in (301, 302, 303): # check local redirect to avoid fetch externals pages new_url = r.headers.get('Location') current_url = r.url if urls.url_parse(new_url).netloc != urls.url_parse(current_url).netloc: return seen r = self.url_open(new_url) code = r.status_code self.assertIn(code, range(200, 300), "%s Fetching %s returned error response (%d)" % (msg, url, code)) if r.headers['Content-Type'].startswith('text/html'): doc = lxml.html.fromstring(r.content) for link in doc.xpath('//a[@href]'): href = link.get('href') parts = urls.url_parse(href) # href with any fragment removed href = parts.replace(fragment='').to_url() # FIXME: handle relative link (not parts.path.startswith /) if parts.netloc or \ not parts.path.startswith('/') or \ parts.path == '/web' or\ parts.path.startswith('/web/') or \ parts.path.startswith('/en_US/') or \ (parts.scheme and parts.scheme not in ('http', 'https')): continue self.crawl(href, seen, msg) return seen def test_10_crawl_public(self): t0 = time.time() t0_sql = self.registry.test_cr.sql_log_count seen = self.crawl('/', msg='Anonymous Coward') count = len(seen) duration = time.time() - t0 sql = self.registry.test_cr.sql_log_count - t0_sql _logger.runbot("public crawled %s urls in %.2fs %s queries, %.3fs %.2fq per request, ", count, duration, sql, duration / count, float(sql) / count) def test_20_crawl_demo(self): t0 = time.time() t0_sql = self.registry.test_cr.sql_log_count self.authenticate('demo', 'demo') seen = self.crawl('/', msg='demo') count = len(seen) duration = time.time() - t0 sql = self.registry.test_cr.sql_log_count - t0_sql _logger.runbot("demo crawled %s urls in %.2fs %s queries, %.3fs %.2fq per request", count, duration, sql, duration / count, float(sql) / count) def test_30_crawl_admin(self): t0 = time.time() t0_sql = self.registry.test_cr.sql_log_count self.authenticate('admin', 'admin') seen = self.crawl('/', msg='admin') count = len(seen) duration = time.time() - t0 sql = self.registry.test_cr.sql_log_count - t0_sql _logger.runbot("admin crawled %s urls in %.2fs %s queries, %.3fs %.2fq per request", count, duration, sql, duration / count, float(sql) / count)
38.017241
4,410
1,624
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # -*- coding: utf-8 -*- import odoo.tests @odoo.tests.tagged('post_install', '-at_install') class TestWebsiteFormEditor(odoo.tests.HttpCase): def test_tour(self): self.start_tour("/", 'website_form_editor_tour', login="admin") self.start_tour("/", 'website_form_editor_tour_submit') self.start_tour("/", 'website_form_editor_tour_results', login="admin") def test_website_form_contact_us_edition_with_email(self): self.start_tour('/contactus', 'website_form_contactus_edition_with_email', login="admin") self.start_tour('/contactus', 'website_form_contactus_submit', login="portal") mail = self.env['mail.mail'].search([], order='id desc', limit=1) self.assertEqual( mail.email_to, '[email protected]', 'The email was edited, the form should have been sent to the configured email') def test_website_form_contact_us_edition_no_email(self): self.start_tour('/contactus', 'website_form_contactus_edition_no_email', login="admin") self.start_tour('/contactus', 'website_form_contactus_submit', login="portal") mail = self.env['mail.mail'].search([], order='id desc', limit=1) self.assertEqual( mail.email_to, self.env.company.email, 'The email was not edited, the form should still have been sent to the company email') def test_website_form_conditional_required_checkboxes(self): self.start_tour('/', 'website_form_conditional_required_checkboxes', login="admin")
49.212121
1,624
1,694
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import sentinel from odoo.http import EndPoint from odoo.tests import HttpCase class TestHttpEndPoint(HttpCase): def test_http_endpoint_equality(self): sentinel.method.original_func = sentinel.method_original_func args = (sentinel.method, {'routing_arg': sentinel.routing_arg}) endpoint1 = EndPoint(*args) endpoint2 = EndPoint(*args) self.assertEqual(endpoint1, endpoint2) testdict = {} testdict[endpoint1] = 42 self.assertEqual(testdict[endpoint2], 42) self.assertTrue(endpoint2 in testdict) def test_can_clear_routing_map_during_render(self): """ The routing map might be cleared while rendering a qweb view. For example, if an asset bundle is regenerated the old one is unlinked, which causes a cache clearing. This test ensures that the rendering still works, even in this case. """ homepage_id = self.env['ir.ui.view'].search([ ('website_id', '=', self.env.ref('website.default_website').id), ('key', '=', 'website.homepage'), ]) self.env['ir.ui.view'].create({ 'name': 'Add cache clear to Home', 'type': 'qweb', 'mode': 'extension', 'inherit_id': homepage_id.id, 'arch_db': """ <t t-call="website.layout" position="before"> <t t-esc="website.env['ir.http']._clear_routing_map()"/> </t> """, }) r = self.url_open('/') r.raise_for_status()
35.291667
1,694
5,884
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import HttpCase EXTRA_REQUEST = 5 """ During tests, the query on 'base_registry_signaling, base_cache_signaling' won't be executed on hot state, but 6 new queries related to the test cursor will be added: SAVEPOINT "test_cursor_4" SAVEPOINT "test_cursor_4" ROLLBACK TO SAVEPOINT "test_cursor_4" SAVEPOINT "test_cursor_5" [.. usual SQL Queries .. ] SAVEPOINT "test_cursor_5" ROLLBACK TO SAVEPOINT "test_cursor_5" """ class UtilPerf(HttpCase): def _get_url_hot_query(self, url, cache=True): url += ('?' not in url and '?' or '') if not cache: url += '&nocache' # ensure worker is in hot state self.url_open(url) self.url_open(url) sql_count = self.registry.test_cr.sql_log_count self.url_open(url) return self.registry.test_cr.sql_log_count - sql_count - EXTRA_REQUEST class TestStandardPerformance(UtilPerf): def test_10_perf_sql_img_controller(self): self.authenticate('demo', 'demo') url = '/web/image/res.users/2/image_256' self.assertEqual(self._get_url_hot_query(url), 6) self.assertEqual(self._get_url_hot_query(url, cache=False), 6) def test_11_perf_sql_img_controller(self): self.authenticate('demo', 'demo') self.env['res.users'].sudo().browse(2).website_published = True url = '/web/image/res.users/2/image_256' self.assertEqual(self._get_url_hot_query(url), 6) self.assertEqual(self._get_url_hot_query(url, cache=False), 6) def test_20_perf_sql_img_controller_bis(self): url = '/web/image/website/1/favicon' self.assertEqual(self._get_url_hot_query(url), 4) self.assertEqual(self._get_url_hot_query(url, cache=False), 4) self.authenticate('portal', 'portal') self.assertEqual(self._get_url_hot_query(url), 4) self.assertEqual(self._get_url_hot_query(url, cache=False), 4) class TestWebsitePerformance(UtilPerf): def setUp(self): super().setUp() self.page, self.menu = self._create_page_with_menu('/sql_page') def _create_page_with_menu(self, url): name = url[1:] website = self.env['website'].browse(1) page = self.env['website.page'].create({ 'url': url, 'name': name, 'type': 'qweb', 'arch': '<t name="%s" t-name="website.page_test_%s"> \ <t t-call="website.layout"> \ <div id="wrap"><div class="oe_structure"/></div> \ </t> \ </t>' % (name, name), 'key': 'website.page_test_%s' % name, 'is_published': True, 'website_id': website.id, 'track': False, }) menu = self.env['website.menu'].create({ 'name': name, 'url': url, 'page_id': page.id, 'website_id': website.id, 'parent_id': website.menu_id.id }) return (page, menu) def test_10_perf_sql_queries_page(self): # standard untracked website.page self.assertEqual(self._get_url_hot_query(self.page.url), 6) self.assertEqual(self._get_url_hot_query(self.page.url, cache=False), 10) self.menu.unlink() self.assertEqual(self._get_url_hot_query(self.page.url), 6) self.assertEqual(self._get_url_hot_query(self.page.url, cache=False), 10) def test_15_perf_sql_queries_page(self): # standard tracked website.page self.page.track = True self.assertEqual(self._get_url_hot_query(self.page.url), 14) self.assertEqual(self._get_url_hot_query(self.page.url, cache=False), 18) self.menu.unlink() self.assertEqual(self._get_url_hot_query(self.page.url), 14) self.assertEqual(self._get_url_hot_query(self.page.url, cache=False), 18) def test_20_perf_sql_queries_homepage(self): # homepage "/" has its own controller self.assertEqual(self._get_url_hot_query('/'), 13) self.assertEqual(self._get_url_hot_query('/', cache=False), 17) def test_30_perf_sql_queries_page_no_layout(self): # website.page with no call to layout templates self.page.arch = '<div>I am a blank page</div>' self.assertEqual(self._get_url_hot_query(self.page.url), 6) self.assertEqual(self._get_url_hot_query(self.page.url, cache=False), 7) def test_40_perf_sql_queries_page_multi_level_menu(self): # menu structure should not impact SQL requests _, menu_a = self._create_page_with_menu('/a') _, menu_aa = self._create_page_with_menu('/aa') _, menu_b = self._create_page_with_menu('/b') _, menu_bb = self._create_page_with_menu('/bb') _, menu_bbb = self._create_page_with_menu('/bbb') _, menu_bbbb = self._create_page_with_menu('/bbbb') _, menu_bbbbb = self._create_page_with_menu('/bbbbb') self._create_page_with_menu('c') menu_bbbbb.parent_id = menu_bbbb menu_bbbb.parent_id = menu_bbb menu_bbb.parent_id = menu_bb menu_bb.parent_id = menu_b menu_aa.parent_id = menu_a self.assertEqual(self._get_url_hot_query(self.page.url), 6) self.assertEqual(self._get_url_hot_query(self.page.url, cache=False), 10) def test_50_perf_sql_web_assets(self): # assets route /web/assets/.. self.url_open('/') # create assets attachments assets_url = self.env['ir.attachment'].search([('url', '=like', '/web/assets/%/web.assets_common%.js')], limit=1).url self.assertEqual(self._get_url_hot_query(assets_url), 2) self.assertEqual(self._get_url_hot_query(assets_url, cache=False), 2)
41.43662
5,884
12,757
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from lxml import etree import re from markupsafe import Markup from odoo.addons.website.controllers.main import Website from odoo.addons.website.tools import distance, MockRequest import odoo.tests from odoo.tests.common import TransactionCase _logger = logging.getLogger(__name__) @odoo.tests.tagged('-at_install', 'post_install') class TestFuzzy(TransactionCase): def test_01_fuzzy_names(self): # Models from other modules commented out on commit: they make the test much longer # Last results observed across modules: # - 698 words in target dictionary # - 21 wrong guesses over 9379 tested typos (0.22%) # - Duration: ~5.7 seconds fields_per_model = { 'website.page': ['name', 'arch'], # 'product.public.category': ['name', 'website_description'], # 'product.template': ['name', 'description_sale'], # 'blog.blog': ['name', 'subtitle'], # 'blog.post': ['name', 'subtitle'], # 'slide.channel': ['name', 'description_short'], # 'slide.slide': ['name', 'description'], # 'event.event': ['name', 'subtitle'], } match_pattern = '\\w{4,}' words = set() for model_name, fields in fields_per_model.items(): if model_name not in self.env: continue model = self.env[model_name] if 'description' not in fields and 'description' in model: fields.append('description') # larger target dataset records = model.sudo().search_read([], fields, limit=100) for record in records: for field, value in record.items(): if isinstance(value, str): if field == 'arch': view_arch = etree.fromstring(value.encode('utf-8')) value = ' '.join(view_arch.itertext()) for word in re.findall(match_pattern, value): words.add(word.lower()) _logger.info("%s words in target dictionary", len(words)) website = self.env.ref('website.default_website') typos = {} def add_typo(expected, typo): if typo not in words: typos.setdefault(typo, set()).add(expected) for search in words: for index in range(2, len(search)): # swap letters if search[index] != search[index - 1]: add_typo(search, search[:index - 1] + search[index] + search[index - 1] + search[index + 1:]) # miss letter if len(search) > 4: add_typo(search, search[:index - 1] + search[index:]) # wrong letter add_typo(search, search[:index - 1] + '!' + search[index:]) words = list(words) words.sort() # guarantee results stability mismatch_count = 0 for search, expected in typos.items(): fuzzy_guess = website._search_find_fuzzy_term({}, search, word_list=words) if not fuzzy_guess or (fuzzy_guess not in expected and fuzzy_guess not in [exp[:-1] for exp in expected]): mismatch_count += 1 _logger.info("'%s' fuzzy matched to '%s' instead of %s", search, fuzzy_guess, expected) ratio = 100.0 * mismatch_count / len(typos) _logger.info("%s wrong guesses over %s tested typos (%.2f%%)", mismatch_count, len(typos), ratio) typos.clear() words.clear() self.assertTrue(ratio < 1, "Too many wrong fuzzy guesses") def test_02_distance(self): self.assertEqual(distance("gravity", "granity", 3), 1) self.assertEqual(distance("gravity", "graity", 3), 1) self.assertEqual(distance("gravity", "grait", 3), 2) self.assertEqual(distance("gravity", "griaty", 3), 3) self.assertEqual(distance("gravity", "giraty", 3), 3) self.assertEqual(distance("gravity", "giraty", 2), -1) self.assertEqual(distance("gravity", "girafe", 3), -1) self.assertEqual(distance("warranty", "warantl", 3), 2) # non-optimized cases still have to return correct results self.assertEqual(distance("warranty", "warranty", 3), 0) self.assertEqual(distance("", "warranty", 3), -1) self.assertEqual(distance("", "warranty", 10), 8) self.assertEqual(distance("warranty", "", 10), 8) self.assertEqual(distance("", "", 10), 0) @odoo.tests.tagged('-at_install', 'post_install') class TestAutoComplete(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.website = cls.env['website'].browse(1) cls.WebsiteController = Website() cls.options = { 'displayDescription': True, } cls.expectedParts = { 'name': True, 'description': True, 'website_url': True, } texts = [ "This page only matches few", "This page matches both few and many", "This page only matches many", "Many results contain this page", "How many times does the word many appear", "Will there be many results", "Welcome to our many friends next week-end", "This should only be approximately matched", ] for text in texts: cls._create_page(text, text, f"/{text.lower().replace(' ', '-')}") @classmethod def _create_page(cls, name, content, url): cls.env['website.page'].create({ 'name': name, 'type': 'qweb', 'arch': f'<div>{content}</div>', 'url': url, 'is_published': True, }) def _autocomplete(self, term): """ Calls the autocomplete for a given term and performs general checks """ with MockRequest(self.env, website=self.website): suggestions = self.WebsiteController.autocomplete( search_type="pages", term=term, max_nb_chars=50, options=self.options, ) if suggestions['results_count']: self.assertDictEqual(self.expectedParts, suggestions['parts'], f"Parts should contain {self.expectedParts.keys()}") for result in suggestions['results']: self.assertEqual("fa-file-o", result['_fa'], "Expect an fa icon") for field in suggestions['parts'].keys(): value = result[field] if value: self.assertTrue( isinstance(value, Markup), f"All fields should be wrapped in Markup: found {type(value)}: '{value}' in {field}" ) return suggestions def _check_highlight(self, term, value): """ Verifies if a term is highlighted in a value """ self.assertTrue(f'<span class="text-primary">{term}</span>' in value.lower(), "Term must be highlighted") def test_01_few_results(self): """ Tests an autocomplete with exact match and less than the maximum number of results """ suggestions = self._autocomplete("few") self.assertEqual(2, suggestions['results_count'], "Text data contains two pages with 'few'") self.assertEqual(2, len(suggestions['results']), "All results must be present") self.assertFalse(suggestions['fuzzy_search'], "Expects an exact match") for result in suggestions['results']: self._check_highlight("few", result['name']) self._check_highlight("few", result['description']) def test_02_many_results(self): """ Tests an autocomplete with exact match and more than the maximum number of results """ suggestions = self._autocomplete("many") self.assertEqual(6, suggestions['results_count'], "Test data contains six pages with 'many'") self.assertEqual(5, len(suggestions['results']), "Results must be limited to 5") self.assertFalse(suggestions['fuzzy_search'], "Expects an exact match") for result in suggestions['results']: self._check_highlight("many", result['name']) self._check_highlight("many", result['description']) def test_03_no_result(self): """ Tests an autocomplete without matching results """ suggestions = self._autocomplete("nothing") self.assertEqual(0, suggestions['results_count'], "Text data contains no page with 'nothing'") self.assertEqual(0, len(suggestions['results']), "No result must be present") def test_04_fuzzy_results(self): """ Tests an autocomplete with fuzzy matching results """ suggestions = self._autocomplete("appoximtly") self.assertEqual("approximately", suggestions['fuzzy_search'], "") self.assertEqual(1, suggestions['results_count'], "Text data contains one page with 'approximately'") self.assertEqual(1, len(suggestions['results']), "Single result must be present") for result in suggestions['results']: self._check_highlight("approximately", result['name']) self._check_highlight("approximately", result['description']) def test_05_long_url(self): """ Ensures that long URL do not get truncated """ url = "/this-url-is-so-long-it-would-be-truncated-without-the-fix" self._create_page("Too long", "Way too long URL", url) suggestions = self._autocomplete("long url") self.assertEqual(1, suggestions['results_count'], "Text data contains one page with 'long url'") self.assertEqual(1, len(suggestions['results']), "Single result must be present") self.assertEqual(url, suggestions['results'][0]['website_url'], 'URL must not be truncated') def test_06_case_insensitive_results(self): """ Tests an autocomplete with exact match and more than the maximum number of results. """ suggestions = self._autocomplete("Many") self.assertEqual(6, suggestions['results_count'], "Test data contains six pages with 'Many'") self.assertEqual(5, len(suggestions['results']), "Results must be limited to 5") self.assertFalse(suggestions['fuzzy_search'], "Expects an exact match") for result in suggestions['results']: self._check_highlight("many", result['name']) self._check_highlight("many", result['description']) def test_07_no_fuzzy_for_mostly_number(self): """ Ensures exact match is used when search contains mostly numbers. """ self._create_page('Product P7935432254U7 page', 'Product P7935432254U7', '/numberpage') suggestions = self._autocomplete("54321") self.assertEqual(0, suggestions['results_count'], "Test data contains no exact match") suggestions = self._autocomplete("54322") self.assertEqual(1, suggestions['results_count'], "Test data contains one exact match") suggestions = self._autocomplete("P79355") self.assertEqual(0, suggestions['results_count'], "Test data contains no exact match") suggestions = self._autocomplete("P79354") self.assertEqual(1, suggestions['results_count'], "Test data contains one exact match") self.assertFalse(suggestions['fuzzy_search'], "Expects an exact match") suggestions = self._autocomplete("produkt") self.assertEqual(1, suggestions['results_count'], "Test data contains one fuzzy match") self.assertTrue(suggestions['fuzzy_search'], "Expects a fuzzy match") def test_08_fuzzy_classic_numbers(self): """ Ensures fuzzy match is used when search contains a few numbers. """ self._create_page('iPhone 6', 'iPhone6', '/iphone6') suggestions = self._autocomplete("iphone7") self.assertEqual(1, suggestions['results_count'], "Test data contains one fuzzy match") self.assertTrue(suggestions['fuzzy_search'], "Expects an fuzzy match") def test_09_hyphen(self): """ Ensures that hyphen is considered part of word """ suggestions = self._autocomplete("weekend") self.assertEqual(1, suggestions['results_count'], "Text data contains one page with 'weekend'") self.assertEqual('week-end', suggestions['fuzzy_search'], "Expects a fuzzy match") suggestions = self._autocomplete("week-end") self.assertEqual(1, len(suggestions['results']), "All results must be present") self.assertFalse(suggestions['fuzzy_search'], "Expects an exact match")
49.832031
12,757
909
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.common.tagged('post_install', '-at_install') class TestUnsplashBeacon(odoo.tests.HttpCase): def test_01_beacon(self): self.env['ir.config_parameter'].sudo().set_param('unsplash.app_id', '123456') # Create page with unsplash image. page = self.env['website.page'].search([('url', '=', '/'), ('website_id', '=', 1)]) page.arch = '''<t name="Homepage" t-name="website.homepage1"> <t t-call="website.layout"> <t t-set="pageName" t-value="'homepage'"/> <div id="wrap" class="oe_structure oe_empty"> <img src="/unsplash/pYyOZ8q7AII/306/fairy.jpg"/> </div> </t> </t>''' # Access page. self.start_tour("/?test_unsplash_beacon", "test_unsplash_beacon")
39.521739
909
5,312
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo.addons.http_routing.models.ir_http import url_lang from odoo.addons.website.tools import MockRequest from odoo.tests import HttpCase, tagged from odoo.tests.common import HOST @tagged('-at_install', 'post_install') class TestLangUrl(HttpCase): def setUp(self): super(TestLangUrl, self).setUp() # Simulate multi lang without loading translations self.website = self.env.ref('website.default_website') self.lang_fr = self.env['res.lang']._activate_lang('fr_FR') self.lang_fr.write({'url_code': 'fr'}) self.website.language_ids = self.env.ref('base.lang_en') + self.lang_fr self.website.default_lang_id = self.env.ref('base.lang_en') def test_01_url_lang(self): with MockRequest(self.env, website=self.website): self.assertEqual(url_lang('', '[lang]'), '/[lang]/hello', "`[lang]` is used to be replaced in the url_return after installing a language, it should not be replaced or removed.") def test_02_url_redirect(self): url = '/fr_WHATEVER/contactus' r = self.url_open(url) self.assertEqual(r.status_code, 200) self.assertTrue(r.url.endswith('/fr/contactus'), "fr_WHATEVER should be forwarded to 'fr_FR' lang as closest match") url = '/fr_FR/contactus' r = self.url_open(url) self.assertEqual(r.status_code, 200) self.assertTrue(r.url.endswith('/fr/contactus'), "lang in url should use url_code ('fr' in this case)") def test_03_url_cook_lang_not_available(self): """ An activated res.lang should not be displayed in the frontend if not a website lang. """ self.website.language_ids = self.env.ref('base.lang_en') r = self.url_open('/fr/contactus') self.assertTrue('lang="en-US"' in r.text, "french should not be displayed as not a frontend lang") def test_04_url_cook_lang_not_available(self): """ `nearest_lang` should filter out lang not available in frontend. Eg: 1. go in backend in english -> request.context['lang'] = `en_US` 2. go in frontend, the request.context['lang'] is passed through `nearest_lang` which should not return english. More then a misbehavior it will crash in website language selector template. """ # 1. Load backend self.authenticate('admin', 'admin') r = self.url_open('/web') self.assertTrue('"lang": "en_US"' in r.text, "ensure english was loaded") # 2. Remove en_US from frontend self.website.language_ids = self.lang_fr self.website.default_lang_id = self.lang_fr # 3. Ensure visiting /contactus do not crash url = '/contactus' r = self.url_open(url) self.assertEqual(r.status_code, 200) self.assertTrue('lang="fr-FR"' in r.text, "Ensure contactus did not soft crash + loaded in correct lang") @tagged('-at_install', 'post_install') class TestControllerRedirect(TestLangUrl): def setUp(self): self.page = self.env['website.page'].create({ 'name': 'Test View', 'type': 'qweb', 'arch': '''<t t-call="website.layout">Test View Page</t>''', 'key': 'test.test_view', 'url': '/page_1', 'is_published': True, }) super().setUp() def test_01_controller_redirect(self): """ Trailing slash URLs should be redirected to non-slash URLs (unless the controller explicitly specifies a trailing slash in the route). """ def assertUrlRedirect(url, expected_url, msg="", code=301): if expected_url.startswith('/'): expected_url = "http://%s:%s%s" % (HOST, odoo.tools.config['http_port'], expected_url) if not msg: msg = 'Url <%s> differ from <%s>.' % (url, expected_url) r = self.url_open(url, head=True) self.assertEqual(r.status_code, code) self.assertEqual(r.headers.get('Location'), expected_url, msg) self.authenticate('admin', 'admin') # Controllers assertUrlRedirect('/my/', '/my', "Check for basic controller.") assertUrlRedirect('/my/?a=b', '/my?a=b', "Check for basic controller + URL params.") # website.page assertUrlRedirect('/page_1/', '/page_1', "Check for website.page.") assertUrlRedirect('/page_1/?a=b', '/page_1?a=b', "Check for website.page + URL params.") # == Same with language == # Controllers assertUrlRedirect('/fr/my/', '/fr/my', "Check for basic controller with language in URL.") assertUrlRedirect('/fr/my/?a=b', '/fr/my?a=b', "Check for basic controller with language in URL + URL params.") # Homepage (which is a controller) assertUrlRedirect('/fr/', '/fr', "Check for homepage + language.") assertUrlRedirect('/fr/?a=b', '/fr?a=b', "Check for homepage + language + URL params") # website.page assertUrlRedirect('/fr/page_1/', '/fr/page_1', "Check for website.page with language in URL.") assertUrlRedirect('/fr/page_1/?a=b', '/fr/page_1?a=b', "Check for website.page with language in URL + URL params.")
47.00885
5,312
1,257
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from PIL import Image from odoo.tests import tagged from odoo.tests.common import TransactionCase from odoo.tools import base64_to_image, image_to_base64 @tagged('post_install', '-at_install') class TestWebsiteResetPassword(TransactionCase): def test_01_website_favicon(self): """The goal of this test is to make sure the favicon is correctly handled on the website.""" # Test setting an Ico file directly, done through create Website = self.env['website'] website = Website.create({ 'name': 'Test Website', 'favicon': Website._default_favicon(), }) image = base64_to_image(website.favicon) self.assertEqual(image.format, 'ICO') # Test setting a JPEG file that is too big, done through write bg_color = (135, 90, 123) image = Image.new('RGB', (1920, 1080), color=bg_color) website.favicon = image_to_base64(image, 'JPEG') image = base64_to_image(website.favicon) self.assertEqual(image.format, 'ICO') self.assertEqual(image.size, (256, 256)) self.assertEqual(image.getpixel((0, 0)), bg_color)
34.916667
1,257
1,702
py
PYTHON
15.0
# coding: utf-8 from odoo.tests import common, tagged @tagged('-at_install', 'post_install') class TestTheme(common.TransactionCase): def test_theme_remove_working(self): """ This test ensure theme can be removed. Theme removal is also the first step during theme installation. """ theme_common_module = self.env['ir.module.module'].search([('name', '=', 'theme_default')]) website = self.env['website'].get_current_website() website.theme_id = theme_common_module.id self.env['ir.module.module']._theme_remove(website) def test_02_disable_view(self): """This test ensure only one template header can be active at a time.""" website_id = self.env['website'].browse(1) ThemeUtils = self.env['theme.utils'].with_context(website_id=website_id.id) ThemeUtils._reset_default_config() def _get_header_template_key(): return self.env['ir.ui.view'].search([ ('key', 'in', ThemeUtils._header_templates), ('website_id', '=', website_id.id), ]).key self.assertEqual(_get_header_template_key(), 'website.template_header_default', "Only the default template should be active.") key = 'website.template_header_magazine' ThemeUtils.enable_view(key) self.assertEqual(_get_header_template_key(), key, "Only one template can be active at a time.") key = 'website.template_header_hamburger' ThemeUtils.enable_view(key) self.assertEqual(_get_header_template_key(), key, "Ensuring it works also for non default template.")
41.512195
1,702
8,308
py
PYTHON
15.0
# coding: utf-8 import json from odoo.tests import common class TestMenu(common.TransactionCase): def setUp(self): super(TestMenu, self).setUp() self.nb_website = self.env['website'].search_count([]) def test_01_menu_got_duplicated(self): Menu = self.env['website.menu'] total_menu_items = Menu.search_count([]) self.menu_root = Menu.create({ 'name': 'Root', }) self.menu_child = Menu.create({ 'name': 'Child', 'parent_id': self.menu_root.id, }) self.assertEqual(total_menu_items + self.nb_website * 2, Menu.search_count([]), "Creating a menu without a website_id should create this menu for every website_id") def test_02_menu_count(self): Menu = self.env['website.menu'] total_menu_items = Menu.search_count([]) top_menu = self.env['website'].get_current_website().menu_id data = [ { 'id': 'new-1', 'parent_id': top_menu.id, 'name': 'New Menu Specific 1', 'url': '/new-specific-1', 'is_mega_menu': False, }, { 'id': 'new-2', 'parent_id': top_menu.id, 'name': 'New Menu Specific 2', 'url': '/new-specific-2', 'is_mega_menu': False, } ] Menu.save(1, {'data': data, 'to_delete': []}) self.assertEqual(total_menu_items + 2, Menu.search_count([]), "Creating 2 new menus should create only 2 menus records") def test_03_default_menu_for_new_website(self): Website = self.env['website'] Menu = self.env['website.menu'] total_menu_items = Menu.search_count([]) # Simulating website.menu created on module install (blog, shop, forum..) that will be created on default menu tree default_menu = self.env.ref('website.main_menu') Menu.create({ 'name': 'Sub Default Menu', 'parent_id': default_menu.id, }) self.assertEqual(total_menu_items + 1 + self.nb_website, Menu.search_count([]), "Creating a default child menu should create it as such and copy it on every website") # Ensure new website got a top menu total_menus = Menu.search_count([]) Website.create({'name': 'new website'}) self.assertEqual(total_menus + 4, Menu.search_count([]), "New website's bootstraping should have duplicate default menu tree (Top/Home/Contactus/Sub Default Menu)") def test_04_specific_menu_translation(self): Translation = self.env['ir.translation'] Menu = self.env['website.menu'] existing_menus = Menu.search([]) default_menu = self.env.ref('website.main_menu') template_menu = Menu.create({ 'parent_id': default_menu.id, 'name': 'Menu in english', 'url': 'turlututu', }) new_menus = Menu.search([]) - existing_menus specific1, specific2 = new_menus.with_context(lang='fr_FR') - template_menu # create fr_FR translation for template menu self.env.ref('base.lang_fr').active = True template_menu.with_context(lang='fr_FR').name = 'Menu en français' Translation.search([ ('name', '=', 'website.menu,name'), ('res_id', '=', template_menu.id), ]).module = 'website' self.assertEqual(specific1.name, 'Menu in english', 'Translating template menu does not translate specific menu') # have different translation for specific website specific1.name = 'Menu in french' # loading translation add missing specific translation Translation._load_module_terms(['website'], ['fr_FR']) Menu.invalidate_cache(['name']) self.assertEqual(specific1.name, 'Menu in french', 'Load translation without overwriting keep existing translation') self.assertEqual(specific2.name, 'Menu en français', 'Load translation add missing translation from template menu') # loading translation with overwrite sync all translations from menu template Translation._load_module_terms(['website'], ['fr_FR'], overwrite=True) Menu.invalidate_cache(['name']) self.assertEqual(specific1.name, 'Menu en français', 'Load translation with overwriting update existing menu from template') def test_05_default_menu_unlink(self): Menu = self.env['website.menu'] total_menu_items = Menu.search_count([]) default_menu = self.env.ref('website.main_menu') default_menu.child_id[0].unlink() self.assertEqual(total_menu_items - 1 - self.nb_website, Menu.search_count([]), "Deleting a default menu item should delete its 'copies' (same URL) from website's menu trees. In this case, the default child menu and its copies on website 1 and website 2") class TestMenuHttp(common.HttpCase): def setUp(self): super().setUp() self.page_url = '/page_specific' self.page = self.env['website.page'].create({ 'url': self.page_url, 'website_id': 1, # ir.ui.view properties 'name': 'Base', 'type': 'qweb', 'arch': '<div>Specific View</div>', 'key': 'test.specific_view', }) self.menu = self.env['website.menu'].create({ 'name': 'Page Specific menu', 'page_id': self.page.id, 'url': self.page_url, 'website_id': 1, }) def simulate_rpc_save_menu(self, data, to_delete=None): self.authenticate("admin", "admin") # `Menu.save(1, {'data': [data], 'to_delete': []})` would have been # ideal but need a full frontend context to generate routing maps, # router and registry, even MockRequest is not enough self.url_open('/web/dataset/call_kw', data=json.dumps({ "params": { 'model': 'website.menu', 'method': 'save', 'args': [1, {'data': [data], 'to_delete': to_delete or []}], 'kwargs': {}, }, }), headers={"Content-Type": "application/json", "Referer": self.page.get_base_url() + self.page_url}) def test_01_menu_page_m2o(self): # Ensure that the M2o relation tested later in the test is properly set. self.assertTrue(self.menu.page_id, "M2o should have been set by the setup") # Edit the menu URL to a 'reserved' URL data = { 'id': self.menu.id, 'parent_id': self.menu.parent_id.id, 'name': self.menu.name, 'url': '/website/info', } self.simulate_rpc_save_menu(data) self.assertFalse(self.menu.page_id, "M2o should have been unset as this is a reserved URL.") self.assertEqual(self.menu.url, '/website/info', "Menu URL should have changed.") self.assertEqual(self.page.url, self.page_url, "Page's URL shouldn't have changed.") # 3. Edit the menu URL back to the page URL data['url'] = self.page_url self.env['website.menu'].save(1, {'data': [data], 'to_delete': []}) self.assertEqual(self.menu.page_id, self.page, "M2o should have been set back, as there was a page found with the new URL set on the menu.") self.assertTrue(self.page.url == self.menu.url == self.page_url) def test_02_menu_anchors(self): # Ensure that the M2o relation tested later in the test is properly set. self.assertTrue(self.menu.page_id, "M2o should have been set by the setup") # Edit the menu URL to an anchor data = { 'id': self.menu.id, 'parent_id': self.menu.parent_id.id, 'name': self.menu.name, 'url': '#anchor', } self.simulate_rpc_save_menu(data) self.assertFalse(self.menu.page_id, "M2o should have been unset as this is an anchor URL.") self.assertEqual(self.menu.url, self.page_url + '#anchor', "Page URL should have been properly prefixed with the referer url") self.assertEqual(self.page.url, self.page_url, "Page URL should not have changed")
43.710526
8,305
2,003
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.http_routing.models.ir_http import slugify, unslug from odoo.tests.common import BaseCase class TestUnslug(BaseCase): def test_unslug(self): tests = { '': (None, None), 'foo': (None, None), 'foo-': (None, None), '-': (None, None), 'foo-1': ('foo', 1), 'foo-bar-1': ('foo-bar', 1), 'foo--1': ('foo', -1), '1': (None, 1), '1-1': ('1', 1), '--1': (None, None), 'foo---1': (None, None), 'foo1': (None, None), } for slug, expected in tests.items(): self.assertEqual(unslug(slug), expected) class TestTitleToSlug(BaseCase): """ Those tests should pass with or without python-slugify See website/models/website.py slugify method """ def test_spaces(self): self.assertEqual( "spaces", slugify(u" spaces ") ) def test_unicode(self): self.assertEqual( "heterogeneite", slugify(u"hétérogénéité") ) def test_underscore(self): self.assertEqual( "one-two", slugify(u"one_two") ) def test_caps(self): self.assertEqual( "camelcase", slugify(u"CamelCase") ) def test_special_chars(self): self.assertEqual( "o-d-o-o", slugify(u"o!#d{|\o/@~o&%^?") ) def test_str_to_unicode(self): self.assertEqual( "espana", slugify("España") ) def test_numbers(self): self.assertEqual( "article-1", slugify(u"Article 1") ) def test_all(self): self.assertEqual( "do-you-know-martine-a-la-plage", slugify(u"Do YOU know 'Martine à la plage' ?") )
24.641975
1,996
5,119
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import HttpCase, standalone, tagged @tagged('website_nightly', '-standard') class TestWebsiteNightlyRunbot(HttpCase): def test_01_website_nightly_runbot(self): """ This test is just here to avoid runbot to raise an error on the ``website_nightly`` build. Indeed, if not a single test with this tag is found, the build will be considered as failed. In Odoo 16.4 a real test is using this tag. """ """ This test ensure `inherit_id` update is correctly replicated on cow views. The view receiving the `inherit_id` update is either: 1. in a module loaded before `website`. In that case, `website` code is not loaded yet, so we store the updates to replay the changes on the cow views once `website` module is loaded (see `_check()`). This test is testing that part. 2. in a module loaded after `website`. In that case, the `inherit_id` update is directly replicated on the cow views. That behavior is tested with `test_module_new_inherit_view_on_parent_already_forked` and `test_specific_view_module_update_inherit_change` in `website` module. """ @standalone('cow_views_inherit', 'website_standalone') def test_01_cow_views_inherit_on_module_update(env): # A B A B # / \ => / \ # D D' D D' # 1. Setup hierarchy as comment above View = env['ir.ui.view'] View.with_context(_force_unlink=True, active_test=False).search([('website_id', '=', 1)]).unlink() child_view = env.ref('portal.footer_language_selector') parent_view = env.ref('portal.portal_back_in_edit_mode') # Remove any possibly existing COW view (another theme etc) parent_view.with_context(_force_unlink=True, active_test=False)._get_specific_views().unlink() child_view.with_context(_force_unlink=True, active_test=False)._get_specific_views().unlink() # Change `inherit_id` so the module update will set it back to the XML value child_view.write({'inherit_id': parent_view.id, 'arch': child_view.arch_db.replace('o_footer_copyright_name', 'text-center')}) # Trigger COW on view child_view.with_context(website_id=1).write({'name': 'COW Website 1'}) child_cow_view = child_view._get_specific_views() # 2. Ensure setup is as expected assert len(child_cow_view.inherit_id) == 1, "Should only be the XML view and its COW counterpart." assert child_cow_view.inherit_id == parent_view, "Ensure test is setup as expected." # 3. Upgrade the module portal_module = env['ir.module.module'].search([('name', '=', 'portal')]) portal_module.button_immediate_upgrade() env.reset() # clear the set of environments env = env() # get an environment that refers to the new registry # 4. Ensure cow view also got its inherit_id updated expected_parent_view = env.ref('portal.frontend_layout') # XML data assert child_view.inherit_id == expected_parent_view, "Generic view security check." assert child_cow_view.inherit_id == expected_parent_view, "COW view should also have received the `inherit_id` update." @standalone('cow_views_inherit', 'website_standalone') def test_02_cow_views_inherit_on_module_update(env): # A B B' A B B' # / \ => | | # D D' D D' # 1. Setup hierarchy as comment above View = env['ir.ui.view'] View.with_context(_force_unlink=True, active_test=False).search([('website_id', '=', 1)]).unlink() view_D = env.ref('portal.my_account_link') view_A = env.ref('portal.message_thread') # Change `inherit_id` so the module update will set it back to the XML value view_D.write({'inherit_id': view_A.id, 'arch_db': view_D.arch_db.replace('o_logout_divider', 'discussion')}) # Trigger COW on view view_B = env.ref('portal.user_dropdown') # XML data view_D.with_context(website_id=1).write({'name': 'D Website 1'}) view_B.with_context(website_id=1).write({'name': 'B Website 1'}) view_Dcow = view_D._get_specific_views() # 2. Ensure setup is as expected view_Bcow = view_B._get_specific_views() assert view_Dcow.inherit_id == view_A, "Ensure test is setup as expected." assert len(view_Bcow) == len(view_Dcow) == 1, "Ensure test is setup as expected (2)." assert view_B != view_Bcow, "Security check to ensure `_get_specific_views` return what it should." # 3. Upgrade the module portal_module = env['ir.module.module'].search([('name', '=', 'portal')]) portal_module.button_immediate_upgrade() env.reset() # clear the set of environments env = env() # get an environment that refers to the new registry # 4. Ensure cow view also got its inherit_id updated assert view_D.inherit_id == view_B, "Generic view security check." assert view_Dcow.inherit_id == view_Bcow, "COW view should also have received the `inherit_id` update."
51.707071
5,119
2,260
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.common.tagged('post_install', '-at_install') class TestIrAsset(odoo.tests.HttpCase): def test_01_website_specific_assets(self): IrAsset = self.env['ir.asset'] Website = self.env['website'] website_1 = Website.create({'name': "Website 1"}) website_2 = Website.create({'name': "Website 2"}) assets = IrAsset.create([{ 'key': 'test0', 'name': '0', 'bundle': 'test_bundle.irasset', 'path': '/website/test/base0.css', }, { 'key': 'test1', 'name': '1', 'bundle': 'test_bundle.irasset', 'path': '/website/test/base1.css', }, { 'key': 'test2', 'name': '2', 'bundle': 'test_bundle.irasset', 'path': '/website/test/base2.css', }]) # For website 1, modify asset 1 and disable asset 2. assets[1].with_context(website_id=website_1.id).write({ 'path': '/website/test/specific1.css', }) assets[2].with_context(website_id=website_1.id).write({ 'active': False, }) files = IrAsset.with_context(website_id=website_1.id)._get_asset_paths('test_bundle.irasset', addons=['website'], css=True) self.assertEqual(len(files), 2, "There should be two assets in the specific website.") self.assertEqual(files[0][0], '/website/test/base0.css', "First asset should be the same as the base one.") self.assertEqual(files[1][0], '/website/test/specific1.css', "Second asset should be the specific one.") files = IrAsset.with_context(website_id=website_2.id)._get_asset_paths('test_bundle.irasset', addons=['website'], css=True) self.assertEqual(len(files), 3, "All three assets should be in the unmodified website.") self.assertEqual(files[0][0], '/website/test/base0.css', "First asset should be the base one.") self.assertEqual(files[1][0], '/website/test/base1.css', "Second asset should be the base one.") self.assertEqual(files[2][0], '/website/test/base2.css', "Third asset should be the base one.")
44.313725
2,260
691
py
PYTHON
15.0
from odoo.tests import tagged from odoo.addons.website.tests.test_configurator import TestConfiguratorCommon @tagged('post_install', '-at_install') class TestAutomaticEditor(TestConfiguratorCommon): def test_01_automatic_editor_on_new_website(self): # We create a lang because if the new website is displayed in this lang # instead of the website's default one, the editor won't automatically # start. self.env['res.lang'].create({ 'name': 'Parseltongue', 'code': 'pa_GB', 'iso_code': 'pa_GB', 'url_code': 'pa_GB', }) self.start_tour('/', 'automatic_editor_on_new_website', login='admin')
40.647059
691
6,487
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged('post_install', '-at_install') class TestGetCurrentWebsite(TransactionCase): def setUp(self): # Unlink unused website(s) to avoid messing with the expected results self.website = self.env.ref('website.default_website') for w in self.env['website'].search([('id', '!=', self.website.id)]): try: # Website are impossible to delete most often than not, as if # there is critical business data linked to it, it will prevent # the unlink. Could easily happen with a bridge module adding # some custom data. w.unlink() except Exception: pass def test_01_get_current_website_id(self): """Make sure `_get_current_website_id works`.""" Website = self.env['website'] # clean initial state website1 = self.website website1.domain = '' website1.country_group_ids = False website2 = Website.create({ 'name': 'My Website 2', 'domain': '', 'country_group_ids': False, }) country1 = self.env['res.country'].create({'name': "My Country 1"}) country2 = self.env['res.country'].create({'name': "My Country 2"}) country3 = self.env['res.country'].create({'name': "My Country 3"}) country4 = self.env['res.country'].create({'name': "My Country 4"}) country5 = self.env['res.country'].create({'name': "My Country 5"}) country_group_1_2 = self.env['res.country.group'].create({ 'name': "My Country Group 1-2", 'country_ids': [(6, 0, (country1 + country2 + country5).ids)], }) country_group_3 = self.env['res.country.group'].create({ 'name': "My Country Group 3", 'country_ids': [(6, 0, (country3 + country5).ids)], }) # CASE: no domain, no country: get first self.assertEqual(Website._get_current_website_id('', False), website1.id) self.assertEqual(Website._get_current_website_id('', country3.id), website1.id) # CASE: no domain, given country: get by country website1.country_group_ids = country_group_1_2 website2.country_group_ids = country_group_3 self.assertEqual(Website._get_current_website_id('', country1.id), website1.id) self.assertEqual(Website._get_current_website_id('', country2.id), website1.id) self.assertEqual(Website._get_current_website_id('', country3.id), website2.id) # CASE: no domain, wrong country: get first self.assertEqual(Website._get_current_website_id('', country4.id), Website.search([]).sorted('country_group_ids')[0].id) # CASE: no domain, multiple country: get first self.assertEqual(Website._get_current_website_id('', country5.id), website1.id) # setup domain website1.domain = 'my-site-1.fr' website2.domain = 'https://my2ndsite.com:80' website1.country_group_ids = False website2.country_group_ids = False # CASE: domain set: get matching domain self.assertEqual(Website._get_current_website_id('my-site-1.fr', False), website1.id) # CASE: domain set: get matching domain (scheme and port supported) self.assertEqual(Website._get_current_website_id('my-site-1.fr:8069', False), website1.id) self.assertEqual(Website._get_current_website_id('my2ndsite.com:80', False), website2.id) self.assertEqual(Website._get_current_website_id('my2ndsite.com:8069', False), website2.id) self.assertEqual(Website._get_current_website_id('my2ndsite.com', False), website2.id) # CASE: domain set, wrong domain: get first self.assertEqual(Website._get_current_website_id('test.com', False), website1.id) # CASE: subdomain: not supported self.assertEqual(Website._get_current_website_id('www.my2ndsite.com', False), website1.id) # CASE: domain set, given country: get by domain in priority website1.country_group_ids = country_group_1_2 website2.country_group_ids = country_group_3 self.assertEqual(Website._get_current_website_id('my2ndsite.com', country1.id), website2.id) self.assertEqual(Website._get_current_website_id('my2ndsite.com', country2.id), website2.id) self.assertEqual(Website._get_current_website_id('my-site-1.fr', country3.id), website1.id) # CASE: domain set, wrong country: get first for domain self.assertEqual(Website._get_current_website_id('my2ndsite.com', country4.id), website2.id) # CASE: domain set, multiple country: get first for domain website1.domain = website2.domain self.assertEqual(Website._get_current_website_id('my2ndsite.com', country5.id), website1.id) # CASE: overlapping domain: get exact match website1.domain = 'site-1.com' website2.domain = 'even-better-site-1.com' self.assertEqual(Website._get_current_website_id('site-1.com', False), website1.id) self.assertEqual(Website._get_current_website_id('even-better-site-1.com', False), website2.id) # CASE: case insensitive website1.domain = 'Site-1.com' website2.domain = 'Even-Better-site-1.com' self.assertEqual(Website._get_current_website_id('sitE-1.com', False), website1.id) self.assertEqual(Website._get_current_website_id('even-beTTer-site-1.com', False), website2.id) # CASE: same domain, different port website1.domain = 'site-1.com:80' website2.domain = 'site-1.com:81' self.assertEqual(Website._get_current_website_id('site-1.com:80', False), website1.id) self.assertEqual(Website._get_current_website_id('site-1.com:81', False), website2.id) self.assertEqual(Website._get_current_website_id('site-1.com:82', False), website1.id) self.assertEqual(Website._get_current_website_id('site-1.com', False), website1.id) def test_02_signup_user_website_id(self): website = self.website website.specific_user_account = True user = self.env['res.users'].create({'website_id': website.id, 'login': '[email protected]', 'name': 'Hope Fully'}) self.assertTrue(user.website_id == user.partner_id.website_id == website)
47.698529
6,487
3,025
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch import odoo from odoo.tests import tagged from odoo.tests.common import HttpCase @tagged('post_install', '-at_install') class TestWebsiteResetPassword(HttpCase): def test_01_website_reset_password_tour(self): """The goal of this test is to make sure the reset password works.""" # We override unlink because we don't want the email to be auto deleted # if the send works. MailMail = odoo.addons.mail.models.mail_mail.MailMail # We override send_mail because in HttpCase on runbot we don't have an # SMTP server, so if force_send is set, the test is going to fail. MailTemplate = odoo.addons.mail.models.mail_template.MailTemplate original_send_mail = MailTemplate.send_mail def my_send_mail(*args, **kwargs): kwargs.update(force_send=False) return original_send_mail(*args, **kwargs) with patch.object(MailMail, 'unlink', lambda self: None), patch.object(MailTemplate, 'send_mail', my_send_mail): user = self.env['res.users'].create({ 'login': 'test', 'name': 'The King', 'email': '[email protected]', }) website_1 = self.env['website'].browse(1) website_2 = self.env['website'].browse(2) website_1.domain = "my-test-domain.com" website_2.domain = "https://domain-not-used.fr" user.partner_id.website_id = 2 user.invalidate_cache() # invalidate get_base_url user.action_reset_password() self.assertIn(website_2.domain, user.signup_url) user.invalidate_cache() user.partner_id.website_id = 1 user.action_reset_password() self.assertIn(website_1.domain, user.signup_url) (website_1 + website_2).domain = "" user.action_reset_password() user.invalidate_cache() self.start_tour(user.signup_url, 'website_reset_password', login=None) def test_02_multi_user_login(self): # In case Specific User Account is activated on a website, the same login can be used for # several users. Make sure we can still log in if 2 users exist. website = self.env["website"].get_current_website() website.ensure_one() # Use AAA and ZZZ as names since res.users are ordered by 'login, name' user1 = self.env["res.users"].create( {"website_id": False, "login": "[email protected]", "name": "AAA", "password": "[email protected]"} ) user2 = self.env["res.users"].create( {"website_id": website.id, "login": "[email protected]", "name": "ZZZ", "password": "[email protected]"} ) # The most specific user should be selected self.authenticate("[email protected]", "[email protected]") self.assertEqual(self.session["uid"], user2.id)
39.285714
3,025
2,655
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import html import odoo import odoo.tests from odoo.addons.website.tools import MockRequest from odoo.tests.common import HOST from odoo.tools import config @odoo.tests.common.tagged('post_install', '-at_install', 'website_snippets') class TestSnippets(odoo.tests.HttpCase): def test_01_empty_parents_autoremove(self): self.start_tour("/?enable_editor=1", "snippet_empty_parent_autoremove", login='admin') def test_02_default_shape_gets_palette_colors(self): self.start_tour("/?enable_editor=1", "default_shape_gets_palette_colors", login='admin') def test_03_snippets_all_drag_and_drop(self): with MockRequest(self.env, website=self.env['website'].browse(1)): snippets_template = self.env['ir.ui.view'].render_public_asset('website.snippets') html_template = html.fromstring(snippets_template) data_snippet_els = html_template.xpath("//*[@class='o_panel' and not(contains(@class, 'd-none'))]//*[@data-snippet]") blacklist = [ 's_facebook_page', # avoid call to external services (facebook.com) 's_map', # avoid call to maps.google.com ] snippets_names = ','.join(set(el.attrib['data-snippet'] for el in data_snippet_els if el.attrib['data-snippet'] not in blacklist)) self.start_tour("/?enable_editor=1&snippets_names=%s" % snippets_names, "snippets_all_drag_and_drop", login='admin', timeout=300) def test_04_countdown_preview(self): self.start_tour("/?enable_editor=1", "snippet_countdown", login='admin') def test_05_snippet_popup_add_remove(self): self.start_tour('/?enable_editor=1', 'snippet_popup_add_remove', login='admin') def test_06_snippet_image_gallery(self): IrAttachment = self.env['ir.attachment'] base = "http://%s:%s" % (HOST, config['http_port']) IrAttachment.create({ 'public': True, 'name': 's_default_image.jpg', 'type': 'url', 'url': base + '/web/image/website.s_banner_default_image.jpg', }) IrAttachment.create({ 'public': True, 'name': 's_default_image2.jpg', 'type': 'url', 'url': base + '/web/image/website.s_banner_default_image.jpg', }) self.start_tour("/", "snippet_image_gallery", login='admin') def test_07_snippet_images_wall(self): self.start_tour('/', 'snippet_images_wall', login='admin') def test_08_parallax(self): self.start_tour('/', 'test_parallax', login='admin')
43.52459
2,655
507
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class WebsiteRobots(models.TransientModel): _name = "website.robots" _description = "Robots.txt Editor" content = fields.Text(default=lambda s: s.env['website'].get_current_website().robots_txt) def action_save(self): self.env['website'].get_current_website().robots_txt = self.content return {'type': 'ir.actions.act_window_close'}
36.214286
507
1,249
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class BaseLanguageInstall(models.TransientModel): _inherit = "base.language.install" website_ids = fields.Many2many('website', string='Websites to translate') @api.model def default_get(self, fields): defaults = super(BaseLanguageInstall, self).default_get(fields) website_id = self._context.get('params', {}).get('website_id') if website_id: if 'website_ids' not in defaults: defaults['website_ids'] = [] defaults['website_ids'].append(website_id) return defaults def lang_install(self): action = super(BaseLanguageInstall, self).lang_install() lang = self.env['res.lang']._lang_get(self.lang) if self.website_ids and lang: self.website_ids.write({'language_ids': [(4, lang.id)]}) params = self._context.get('params', {}) if 'url_return' in params: return { 'url': params['url_return'].replace('[lang]', self.lang), 'type': 'ir.actions.act_url', 'target': 'self' } return action
35.685714
1,249
20,321
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import os from collections import OrderedDict from odoo import api, fields, models from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG from odoo.exceptions import MissingError from odoo.http import request _logger = logging.getLogger(__name__) class IrModuleModule(models.Model): _name = "ir.module.module" _description = 'Module' _inherit = _name # The order is important because of dependencies (page need view, menu need page) _theme_model_names = OrderedDict([ ('ir.ui.view', 'theme.ir.ui.view'), ('ir.asset', 'theme.ir.asset'), ('website.page', 'theme.website.page'), ('website.menu', 'theme.website.menu'), ('ir.attachment', 'theme.ir.attachment'), ]) _theme_translated_fields = { 'theme.ir.ui.view': [('theme.ir.ui.view,arch', 'ir.ui.view,arch_db')], 'theme.website.menu': [('theme.website.menu,name', 'website.menu,name')], } image_ids = fields.One2many('ir.attachment', 'res_id', domain=[('res_model', '=', _name), ('mimetype', '=like', 'image/%')], string='Screenshots', readonly=True) # for kanban view is_installed_on_current_website = fields.Boolean(compute='_compute_is_installed_on_current_website') def _compute_is_installed_on_current_website(self): """ Compute for every theme in ``self`` if the current website is using it or not. This method does not take dependencies into account, because if it did, it would show the current website as having multiple different themes installed at the same time, which would be confusing for the user. """ for module in self: module.is_installed_on_current_website = module == self.env['website'].get_current_website().theme_id def write(self, vals): """ Override to correctly upgrade themes after upgrade/installation of modules. # Install If this theme wasn't installed before, then load it for every website for which it is in the stream. eg. The very first installation of a theme on a website will trigger this. eg. If a website uses theme_A and we install sale, then theme_A_sale will be autoinstalled, and in this case we need to load theme_A_sale for the website. # Upgrade There are 2 cases to handle when upgrading a theme: * When clicking on the theme upgrade button on the interface, in which case there will be an http request made. -> We want to upgrade the current website only, not any other. * When upgrading with -u, in which case no request should be set. -> We want to upgrade every website using this theme. """ if request and request.context.get('apply_new_theme'): self = self.with_context(apply_new_theme=True) for module in self: if module.name.startswith('theme_') and vals.get('state') == 'installed': _logger.info('Module %s has been loaded as theme template (%s)' % (module.name, module.state)) if module.state in ['to install', 'to upgrade']: websites_to_update = module._theme_get_stream_website_ids() if module.state == 'to upgrade' and request: Website = self.env['website'] current_website = Website.get_current_website() websites_to_update = current_website if current_website in websites_to_update else Website for website in websites_to_update: module._theme_load(website) return super(IrModuleModule, self).write(vals) def _get_module_data(self, model_name): """ Return every theme template model of type ``model_name`` for every theme in ``self``. :param model_name: string with the technical name of the model for which to get data. (the name must be one of the keys present in ``_theme_model_names``) :return: recordset of theme template models (of type defined by ``model_name``) """ theme_model_name = self._theme_model_names[model_name] IrModelData = self.env['ir.model.data'] records = self.env[theme_model_name] for module in self: imd_ids = IrModelData.search([('module', '=', module.name), ('model', '=', theme_model_name)]).mapped('res_id') records |= self.env[theme_model_name].with_context(active_test=False).browse(imd_ids) return records def _update_records(self, model_name, website): """ This method: - Find and update existing records. For each model, overwrite the fields that are defined in the template (except few cases such as active) but keep inherited models to not lose customizations. - Create new records from templates for those that didn't exist. - Remove the models that existed before but are not in the template anymore. See _theme_cleanup for more information. There is a special 'while' loop around the 'for' to be able queue back models at the end of the iteration when they have unmet dependencies. Hopefully the dependency will be found after all models have been processed, but if it's not the case an error message will be shown. :param model_name: string with the technical name of the model to handle (the name must be one of the keys present in ``_theme_model_names``) :param website: ``website`` model for which the records have to be updated :raise MissingError: if there is a missing dependency. """ self.ensure_one() remaining = self._get_module_data(model_name) last_len = -1 while (len(remaining) != last_len): last_len = len(remaining) for rec in remaining: rec_data = rec._convert_to_base_model(website) if not rec_data: _logger.info('Record queued: %s' % rec.display_name) continue find = rec.with_context(active_test=False).mapped('copy_ids').filtered(lambda m: m.website_id == website) # special case for attachment # if module B override attachment from dependence A, we update it if not find and model_name == 'ir.attachment': # In master, a unique constraint over (theme_template_id, website_id) # will be introduced, thus ensuring unicity of 'find' find = rec.copy_ids.search([('key', '=', rec.key), ('website_id', '=', website.id), ("original_id", "=", False)]) if find: imd = self.env['ir.model.data'].search([('model', '=', find._name), ('res_id', '=', find.id)]) if imd and imd.noupdate: _logger.info('Noupdate set for %s (%s)' % (find, imd)) else: # at update, ignore active field if 'active' in rec_data: rec_data.pop('active') if model_name == 'ir.ui.view' and (find.arch_updated or find.arch == rec_data['arch']): rec_data.pop('arch') find.update(rec_data) self._post_copy(rec, find) else: new_rec = self.env[model_name].create(rec_data) self._post_copy(rec, new_rec) remaining -= rec if len(remaining): error = 'Error - Remaining: %s' % remaining.mapped('display_name') _logger.error(error) raise MissingError(error) self._theme_cleanup(model_name, website) def _post_copy(self, old_rec, new_rec): self.ensure_one() translated_fields = self._theme_translated_fields.get(old_rec._name, []) for (src_field, dst_field) in translated_fields: self._cr.execute("""INSERT INTO ir_translation (lang, src, name, res_id, state, value, type, module) SELECT t.lang, t.src, %s, %s, t.state, t.value, t.type, t.module FROM ir_translation t WHERE name = %s AND res_id = %s ON CONFLICT DO NOTHING""", (dst_field, new_rec.id, src_field, old_rec.id)) def _theme_load(self, website): """ For every type of model in ``self._theme_model_names``, and for every theme in ``self``: create/update real models for the website ``website`` based on the theme template models. :param website: ``website`` model on which to load the themes """ for module in self: _logger.info('Load theme %s for website %s from template.' % (module.mapped('name'), website.id)) for model_name in self._theme_model_names: module._update_records(model_name, website) if self._context.get('apply_new_theme'): # Both the theme install and upgrade flow ends up here. # The _post_copy() is supposed to be called only when the theme # is installed for the first time on a website. # It will basically select some header and footer template. # We don't want the system to select again the theme footer or # header template when that theme is updated later. It could # erase the change the user made after the theme install. self.env['theme.utils'].with_context(website_id=website.id)._post_copy(module) def _theme_unload(self, website): """ For every type of model in ``self._theme_model_names``, and for every theme in ``self``: remove real models that were generated based on the theme template models for the website ``website``. :param website: ``website`` model on which to unload the themes """ for module in self: _logger.info('Unload theme %s for website %s from template.' % (self.mapped('name'), website.id)) for model_name in self._theme_model_names: template = self._get_module_data(model_name) models = template.with_context(**{'active_test': False, MODULE_UNINSTALL_FLAG: True}).mapped('copy_ids').filtered(lambda m: m.website_id == website) models.unlink() self._theme_cleanup(model_name, website) def _theme_cleanup(self, model_name, website): """ Remove orphan models of type ``model_name`` from the current theme and for the website ``website``. We need to compute it this way because if the upgrade (or deletion) of a theme module removes a model template, then in the model itself the variable ``theme_template_id`` will be set to NULL and the reference to the theme being removed will be lost. However we do want the ophan to be deleted from the website when we upgrade or delete the theme from the website. ``website.page`` and ``website.menu`` don't have ``key`` field so we don't clean them. TODO in master: add a field ``theme_id`` on the models to more cleanly compute orphans. :param model_name: string with the technical name of the model to cleanup (the name must be one of the keys present in ``_theme_model_names``) :param website: ``website`` model for which the models have to be cleaned """ self.ensure_one() model = self.env[model_name] if model_name in ('website.page', 'website.menu'): return model # use active_test to also unlink archived models # and use MODULE_UNINSTALL_FLAG to also unlink inherited models orphans = model.with_context(**{'active_test': False, MODULE_UNINSTALL_FLAG: True}).search([ ('key', '=like', self.name + '.%'), ('website_id', '=', website.id), ('theme_template_id', '=', False), ]) orphans.unlink() def _theme_get_upstream(self): """ Return installed upstream themes. :return: recordset of themes ``ir.module.module`` """ self.ensure_one() return self.upstream_dependencies(exclude_states=('',)).filtered(lambda x: x.name.startswith('theme_')) def _theme_get_downstream(self): """ Return installed downstream themes that starts with the same name. eg. For theme_A, this will return theme_A_sale, but not theme_B even if theme B depends on theme_A. :return: recordset of themes ``ir.module.module`` """ self.ensure_one() return self.downstream_dependencies().filtered(lambda x: x.name.startswith(self.name)) def _theme_get_stream_themes(self): """ Returns all the themes in the stream of the current theme. First find all its downstream themes, and all of the upstream themes of both sorted by their level in hierarchy, up first. :return: recordset of themes ``ir.module.module`` """ self.ensure_one() all_mods = self + self._theme_get_downstream() for down_mod in self._theme_get_downstream() + self: for up_mod in down_mod._theme_get_upstream(): all_mods = up_mod | all_mods return all_mods def _theme_get_stream_website_ids(self): """ Websites for which this theme (self) is in the stream (up or down) of their theme. :return: recordset of websites ``website`` """ self.ensure_one() websites = self.env['website'] for website in websites.search([('theme_id', '!=', False)]): if self in website.theme_id._theme_get_stream_themes(): websites |= website return websites def _theme_upgrade_upstream(self): """ Upgrade the upstream dependencies of a theme, and install it if necessary. """ def install_or_upgrade(theme): if theme.state != 'installed': theme.button_install() themes = theme + theme._theme_get_upstream() themes.filtered(lambda m: m.state == 'installed').button_upgrade() self._button_immediate_function(install_or_upgrade) @api.model def _theme_remove(self, website): """ Remove from ``website`` its current theme, including all the themes in the stream. The order of removal will be reverse of installation to handle dependencies correctly. :param website: ``website`` model for which the themes have to be removed """ # _theme_remove is the entry point of any change of theme for a website # (either removal or installation of a theme and its dependencies). In # either case, we need to reset some default configuration before. self.env['theme.utils'].with_context(website_id=website.id)._reset_default_config() if not website.theme_id: return for theme in reversed(website.theme_id._theme_get_stream_themes()): theme._theme_unload(website) website.theme_id = False def button_choose_theme(self): """ Remove any existing theme on the current website and install the theme ``self`` instead. The actual loading of the theme on the current website will be done automatically on ``write`` thanks to the upgrade and/or install. When installating a new theme, upgrade the upstream chain first to make sure we have the latest version of the dependencies to prevent inconsistencies. :return: dict with the next action to execute """ self.ensure_one() website = self.env['website'].get_current_website() self._theme_remove(website) # website.theme_id must be set before upgrade/install to trigger the load in ``write`` website.theme_id = self # this will install 'self' if it is not installed yet if request: context = dict(request.context) context['apply_new_theme'] = True request.context = context self._theme_upgrade_upstream() active_todo = self.env['ir.actions.todo'].search([('state', '=', 'open')], limit=1) result = None if active_todo: result = active_todo.action_launch() else: result = website.button_go_website(mode_edit=True) if result.get('url') and 'enable_editor' in result['url']: result['url'] = result['url'].replace('enable_editor', 'with_loader=1&enable_editor') return result def button_remove_theme(self): """Remove the current theme of the current website.""" website = self.env['website'].get_current_website() self._theme_remove(website) def button_refresh_theme(self): """ Refresh the current theme of the current website. To refresh it, we only need to upgrade the modules. Indeed the (re)loading of the theme will be done automatically on ``write``. """ website = self.env['website'].get_current_website() website.theme_id._theme_upgrade_upstream() @api.model def update_list(self): res = super(IrModuleModule, self).update_list() self.update_theme_images() return res @api.model def update_theme_images(self): IrAttachment = self.env['ir.attachment'] existing_urls = IrAttachment.search_read([['res_model', '=', self._name], ['type', '=', 'url']], ['url']) existing_urls = {url_wrapped['url'] for url_wrapped in existing_urls} themes = self.env['ir.module.module'].with_context(active_test=False).search([ ('category_id', 'child_of', self.env.ref('base.module_category_theme').id), ], order='name') for theme in themes: terp = self.get_module_info(theme.name) images = terp.get('images', []) for image in images: image_path = '/' + os.path.join(theme.name, image) if image_path not in existing_urls: image_name = os.path.basename(image_path) IrAttachment.create({ 'type': 'url', 'name': image_name, 'url': image_path, 'res_model': self._name, 'res_id': theme.id, }) def get_themes_domain(self): """Returns the 'ir.module.module' search domain matching all available themes.""" def get_id(model_id): return self.env['ir.model.data']._xmlid_to_res_id(model_id) return [ ('category_id', 'not in', [ get_id('base.module_category_hidden'), get_id('base.module_category_theme_hidden'), ]), '|', ('category_id', '=', get_id('base.module_category_theme')), ('category_id.parent_id', '=', get_id('base.module_category_theme')) ] def _check(self): super()._check() View = self.env['ir.ui.view'] website_views_to_adapt = getattr(self.pool, 'website_views_to_adapt', []) if website_views_to_adapt: for view_replay in website_views_to_adapt: cow_view = View.browse(view_replay[0]) View._load_records_write_on_cow(cow_view, view_replay[1], view_replay[2]) self.pool.website_views_to_adapt.clear()
44.272331
20,321
941
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, tools, _ from odoo.addons.website.models import ir_http from odoo.exceptions import UserError from odoo.http import request class Lang(models.Model): _inherit = "res.lang" def write(self, vals): if 'active' in vals and not vals['active']: if self.env['website'].search([('language_ids', 'in', self._ids)]): raise UserError(_("Cannot deactivate a language that is currently used on a website.")) return super(Lang, self).write(vals) @api.model @tools.ormcache_context(keys=("website_id",)) def get_available(self): website = ir_http.get_request_website() if not website: return super().get_available() # Return the website-available ones in this case return request.website.language_ids.get_sorted()
36.192308
941
3,110
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class IrTranslation(models.Model): _inherit = "ir.translation" def _load_module_terms(self, modules, langs, overwrite=False): """ Add missing website specific translation """ res = super()._load_module_terms(modules, langs, overwrite=overwrite) if not langs or not modules: return res if overwrite: conflict_clause = """ ON CONFLICT {} DO UPDATE SET (name, lang, res_id, src, type, value, module, state, comments) = (EXCLUDED.name, EXCLUDED.lang, EXCLUDED.res_id, EXCLUDED.src, EXCLUDED.type, EXCLUDED.value, EXCLUDED.module, EXCLUDED.state, EXCLUDED.comments) WHERE EXCLUDED.value IS NOT NULL AND EXCLUDED.value != '' """; else: conflict_clause = " ON CONFLICT DO NOTHING" # Add specific view translations self.env.cr.execute(""" INSERT INTO ir_translation(name, lang, res_id, src, type, value, module, state, comments) SELECT DISTINCT ON (specific.id, t.lang, md5(src)) t.name, t.lang, specific.id, t.src, t.type, t.value, t.module, t.state, t.comments FROM ir_translation t INNER JOIN ir_ui_view generic ON t.type = 'model_terms' AND t.name = 'ir.ui.view,arch_db' AND t.res_id = generic.id INNER JOIN ir_ui_view specific ON generic.key = specific.key WHERE t.lang IN %s and t.module IN %s AND generic.website_id IS NULL AND generic.type = 'qweb' AND specific.website_id IS NOT NULL""" + conflict_clause.format( "(type, name, lang, res_id, md5(src))" ), (tuple(langs), tuple(modules))) default_menu = self.env.ref('website.main_menu', raise_if_not_found=False) if not default_menu: return res # Add specific menu translations self.env.cr.execute(""" INSERT INTO ir_translation(name, lang, res_id, src, type, value, module, state, comments) SELECT DISTINCT ON (s_menu.id, t.lang) t.name, t.lang, s_menu.id, t.src, t.type, t.value, t.module, t.state, t.comments FROM ir_translation t INNER JOIN website_menu o_menu ON t.type = 'model' AND t.name = 'website.menu,name' AND t.res_id = o_menu.id INNER JOIN website_menu s_menu ON o_menu.name = s_menu.name AND o_menu.url = s_menu.url INNER JOIN website_menu root_menu ON s_menu.parent_id = root_menu.id AND root_menu.parent_id IS NULL WHERE t.lang IN %s and t.module IN %s AND o_menu.website_id IS NULL AND o_menu.parent_id = %s AND s_menu.website_id IS NOT NULL""" + conflict_clause.format( "(type, lang, name, res_id) WHERE type = 'model'" ), (tuple(langs), tuple(modules), default_menu.id)) return res
49.365079
3,110
16,088
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import re from werkzeug.urls import url_join from odoo import api, fields, models, _ from odoo.addons.http_routing.models.ir_http import url_for from odoo.addons.website.tools import text_from_html from odoo.http import request from odoo.osv import expression from odoo.exceptions import AccessError from odoo.tools import escape_psql from odoo.tools.json import scriptsafe as json_safe logger = logging.getLogger(__name__) class SeoMetadata(models.AbstractModel): _name = 'website.seo.metadata' _description = 'SEO metadata' is_seo_optimized = fields.Boolean("SEO optimized", compute='_compute_is_seo_optimized') website_meta_title = fields.Char("Website meta title", translate=True) website_meta_description = fields.Text("Website meta description", translate=True) website_meta_keywords = fields.Char("Website meta keywords", translate=True) website_meta_og_img = fields.Char("Website opengraph image") seo_name = fields.Char("Seo name", translate=True) def _compute_is_seo_optimized(self): for record in self: record.is_seo_optimized = record.website_meta_title and record.website_meta_description and record.website_meta_keywords def _default_website_meta(self): """ This method will return default meta information. It return the dict contains meta property as a key and meta content as a value. e.g. 'og:type': 'website'. Override this method in case you want to change default value from any model. e.g. change value of og:image to product specific images instead of default images """ self.ensure_one() company = request.website.company_id.sudo() title = (request.website or company).name if 'name' in self: title = '%s | %s' % (self.name, title) img_field = 'social_default_image' if request.website.has_social_default_image else 'logo' # Default meta for OpenGraph default_opengraph = { 'og:type': 'website', 'og:title': title, 'og:site_name': company.name, 'og:url': url_join(request.httprequest.url_root, url_for(request.httprequest.path)), 'og:image': request.website.image_url(request.website, img_field), } # Default meta for Twitter default_twitter = { 'twitter:card': 'summary_large_image', 'twitter:title': title, 'twitter:image': request.website.image_url(request.website, img_field, size='300x300'), } if company.social_twitter: default_twitter['twitter:site'] = "@%s" % company.social_twitter.split('/')[-1] return { 'default_opengraph': default_opengraph, 'default_twitter': default_twitter } def get_website_meta(self): """ This method will return final meta information. It will replace default values with user's custom value (if user modified it from the seo popup of frontend) This method is not meant for overridden. To customize meta values override `_default_website_meta` method instead of this method. This method only replaces user custom values in defaults. """ root_url = request.httprequest.url_root.strip('/') default_meta = self._default_website_meta() opengraph_meta, twitter_meta = default_meta['default_opengraph'], default_meta['default_twitter'] if self.website_meta_title: opengraph_meta['og:title'] = self.website_meta_title twitter_meta['twitter:title'] = self.website_meta_title if self.website_meta_description: opengraph_meta['og:description'] = self.website_meta_description twitter_meta['twitter:description'] = self.website_meta_description opengraph_meta['og:image'] = url_join(root_url, url_for(self.website_meta_og_img or opengraph_meta['og:image'])) twitter_meta['twitter:image'] = url_join(root_url, url_for(self.website_meta_og_img or twitter_meta['twitter:image'])) return { 'opengraph_meta': opengraph_meta, 'twitter_meta': twitter_meta, 'meta_description': default_meta.get('default_meta_description') } class WebsiteCoverPropertiesMixin(models.AbstractModel): _name = 'website.cover_properties.mixin' _description = 'Cover Properties Website Mixin' cover_properties = fields.Text('Cover Properties', default=lambda s: json_safe.dumps(s._default_cover_properties())) def _default_cover_properties(self): return { "background_color_class": "o_cc3", "background-image": "none", "opacity": "0.2", "resize_class": "o_half_screen_height", } def _get_background(self, height=None, width=None): self.ensure_one() properties = json_safe.loads(self.cover_properties) img = properties.get('background-image', "none") if img.startswith('url(/web/image/'): suffix = "" if height is not None: suffix += "&height=%s" % height if width is not None: suffix += "&width=%s" % width if suffix: suffix = '?' not in img and "?%s" % suffix or suffix img = img[:-1] + suffix + ')' return img def write(self, vals): if 'cover_properties' not in vals: return super().write(vals) cover_properties = json_safe.loads(vals['cover_properties']) resize_classes = cover_properties.get('resize_class', '').split() classes = ['o_half_screen_height', 'o_full_screen_height', 'cover_auto'] if not set(resize_classes).isdisjoint(classes): # Updating cover properties and the given 'resize_class' set is # valid, normal write. return super().write(vals) # If we do not receive a valid resize_class via the cover_properties, we # keep the original one (prevents updates on list displays from # destroying resize_class). copy_vals = dict(vals) for item in self: old_cover_properties = json_safe.loads(item.cover_properties) cover_properties['resize_class'] = old_cover_properties.get('resize_class', classes[0]) copy_vals['cover_properties'] = json_safe.dumps(cover_properties) super(WebsiteCoverPropertiesMixin, item).write(copy_vals) return True class WebsiteMultiMixin(models.AbstractModel): _name = 'website.multi.mixin' _description = 'Multi Website Mixin' website_id = fields.Many2one( "website", string="Website", ondelete="restrict", help="Restrict publishing to this website.", index=True, ) def can_access_from_current_website(self, website_id=False): can_access = True for record in self: if (website_id or record.website_id.id) not in (False, request.env['website'].get_current_website().id): can_access = False continue return can_access class WebsitePublishedMixin(models.AbstractModel): _name = "website.published.mixin" _description = 'Website Published Mixin' website_published = fields.Boolean('Visible on current website', related='is_published', readonly=False) is_published = fields.Boolean('Is Published', copy=False, default=lambda self: self._default_is_published(), index=True) can_publish = fields.Boolean('Can Publish', compute='_compute_can_publish') website_url = fields.Char('Website URL', compute='_compute_website_url', help='The full URL to access the document through the website.') @api.depends_context('lang') def _compute_website_url(self): for record in self: record.website_url = '#' def _default_is_published(self): return False def website_publish_button(self): self.ensure_one() return self.write({'website_published': not self.website_published}) def open_website_url(self): return { 'type': 'ir.actions.act_url', 'url': self.website_url, 'target': 'self', } @api.model_create_multi def create(self, vals_list): records = super(WebsitePublishedMixin, self).create(vals_list) is_publish_modified = any( [set(v.keys()) & {'is_published', 'website_published'} for v in vals_list] ) if is_publish_modified and any(not record.can_publish for record in records): raise AccessError(self._get_can_publish_error_message()) return records def write(self, values): if 'is_published' in values and any(not record.can_publish for record in self): raise AccessError(self._get_can_publish_error_message()) return super(WebsitePublishedMixin, self).write(values) def create_and_get_website_url(self, **kwargs): return self.create(kwargs).website_url def _compute_can_publish(self): """ This method can be overridden if you need more complex rights management than just 'website_publisher' The publish widget will be hidden and the user won't be able to change the 'website_published' value if this method sets can_publish False """ for record in self: record.can_publish = True @api.model def _get_can_publish_error_message(self): """ Override this method to customize the error message shown when the user doesn't have the rights to publish/unpublish. """ return _("You do not have the rights to publish/unpublish") class WebsitePublishedMultiMixin(WebsitePublishedMixin): _name = 'website.published.multi.mixin' _inherit = ['website.published.mixin', 'website.multi.mixin'] _description = 'Multi Website Published Mixin' website_published = fields.Boolean(compute='_compute_website_published', inverse='_inverse_website_published', search='_search_website_published', related=False, readonly=False) @api.depends('is_published', 'website_id') @api.depends_context('website_id') def _compute_website_published(self): current_website_id = self._context.get('website_id') for record in self: if current_website_id: record.website_published = record.is_published and (not record.website_id or record.website_id.id == current_website_id) else: record.website_published = record.is_published def _inverse_website_published(self): for record in self: record.is_published = record.website_published def _search_website_published(self, operator, value): if not isinstance(value, bool) or operator not in ('=', '!='): logger.warning('unsupported search on website_published: %s, %s', operator, value) return [()] if operator in expression.NEGATIVE_TERM_OPERATORS: value = not value current_website_id = self._context.get('website_id') is_published = [('is_published', '=', value)] if current_website_id: on_current_website = self.env['website'].website_domain(current_website_id) return (['!'] if value is False else []) + expression.AND([is_published, on_current_website]) else: # should be in the backend, return things that are published anywhere return is_published def open_website_url(self): return { 'type': 'ir.actions.act_url', 'url': url_join(self.website_id._get_http_domain(), self.website_url) if self.website_id else self.website_url, 'target': 'self', } class WebsiteSearchableMixin(models.AbstractModel): """Mixin to be inherited by all models that need to searchable through website""" _name = 'website.searchable.mixin' _description = 'Website Searchable Mixin' @api.model def _search_build_domain(self, domain_list, search, fields, extra=None): """ Builds a search domain AND-combining a base domain with partial matches of each term in the search expression in any of the fields. :param domain_list: base domain list combined in the search expression :param search: search expression string :param fields: list of field names to match the terms of the search expression with :param extra: function that returns an additional subdomain for a search term :return: domain limited to the matches of the search expression """ domains = domain_list.copy() if search: for search_term in search.split(' '): subdomains = [[(field, 'ilike', escape_psql(search_term))] for field in fields] if extra: subdomains.append(extra(self.env, search_term)) domains.append(expression.OR(subdomains)) return expression.AND(domains) @api.model def _search_get_detail(self, website, order, options): """ Returns indications on how to perform the searches :param website: website within which the search is done :param order: order in which the results are to be returned :param options: search options :return: search detail as expected in elements of the result of website._search_get_details() These elements contain the following fields: - model: name of the searched model - base_domain: list of domains within which to perform the search - search_fields: fields within which the search term must be found - fetch_fields: fields from which data must be fetched - mapping: mapping from the results towards the structure used in rendering templates. The mapping is a dict that associates the rendering name of each field to a dict containing the 'name' of the field in the results list and the 'type' that must be used for rendering the value - icon: name of the icon to use if there is no image This method must be implemented by all models that inherit this mixin. """ raise NotImplementedError() @api.model def _search_fetch(self, search_detail, search, limit, order): fields = search_detail['search_fields'] base_domain = search_detail['base_domain'] domain = self._search_build_domain(base_domain, search, fields, search_detail.get('search_extra')) model = self.sudo() if search_detail.get('requires_sudo') else self results = model.search( domain, limit=limit, order=search_detail.get('order', order) ) count = model.search_count(domain) return results, count def _search_render_results(self, fetch_fields, mapping, icon, limit): results_data = self.read(fetch_fields)[:limit] for result in results_data: result['_fa'] = icon result['_mapping'] = mapping html_fields = [config['name'] for config in mapping.values() if config.get('html')] if html_fields: for result, data in zip(self, results_data): for html_field in html_fields: if data[html_field]: if html_field == 'arch': # Undo second escape of text nodes from wywsiwyg.js _getEscapedElement. data[html_field] = re.sub(r'&amp;(?=\w+;)', '&', data[html_field]) text = text_from_html(data[html_field]) text = re.sub('\\s+', ' ', text).strip() data[html_field] = text return results_data
43.016043
16,088
915
py
PYTHON
15.0
# coding: utf-8 from odoo import api, models from odoo.addons.website.models import ir_http class IrRule(models.Model): _inherit = 'ir.rule' @api.model def _eval_context(self): res = super(IrRule, self)._eval_context() # We need is_frontend to avoid showing website's company items in backend # (that could be different than current company). We can't use # `get_current_website(falback=False)` as it could also return a website # in backend (if domain set & match).. is_frontend = ir_http.get_request_website() Website = self.env['website'] res['website'] = is_frontend and Website.get_current_website() or Website return res def _compute_domain_keys(self): """ Return the list of context keys to use for caching ``_compute_domain``. """ return super(IrRule, self)._compute_domain_keys() + ['website_id']
38.125
915
1,589
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class BaseModel(models.AbstractModel): _inherit = 'base' def get_base_url(self): """ Returns the base url for a given record, given the following priority: 1. If the record has a `website_id` field, we use the url from this website as base url, if set. 2. If the record has a `company_id` field, we use the website from that company (if set). Note that a company doesn't really have a website, it is retrieve through some heuristic in its `website_id`'s compute. 3. Use the ICP `web.base.url` (super) :return: the base url for this record :rtype: string """ # Ensure zero or one record if not self: return super().get_base_url() self.ensure_one() if self._name == 'website': # Note that website_1.company_id.website_id might not be website_1 return self._get_http_domain() or super().get_base_url() if 'website_id' in self and self.website_id.domain: return self.website_id._get_http_domain() if 'company_id' in self and self.company_id.website_id.domain: return self.company_id.website_id._get_http_domain() return super().get_base_url() def get_website_meta(self): # dummy version of 'get_website_meta' above; this is a graceful fallback # for models that don't inherit from 'website.seo.metadata' return {}
39.725
1,589
21,500
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from lxml import etree import os import unittest import time import pytz import werkzeug import werkzeug.routing import werkzeug.utils from functools import partial import odoo from odoo import api, models from odoo import registry, SUPERUSER_ID from odoo.exceptions import AccessError from odoo.http import request from odoo.tools.safe_eval import safe_eval from odoo.osv.expression import FALSE_DOMAIN from odoo.addons.http_routing.models import ir_http from odoo.addons.http_routing.models.ir_http import _guess_mimetype from odoo.addons.portal.controllers.portal import _build_url_w_params logger = logging.getLogger(__name__) def sitemap_qs2dom(qs, route, field='name'): """ Convert a query_string (can contains a path) to a domain""" dom = [] if qs and qs.lower() not in route: needles = qs.strip('/').split('/') # needles will be altered and keep only element which one is not in route # diff(from=['shop', 'product'], to=['shop', 'product', 'product']) => to=['product'] unittest.util.unorderable_list_difference(route.strip('/').split('/'), needles) if len(needles) == 1: dom = [(field, 'ilike', needles[0])] else: dom = FALSE_DOMAIN return dom def get_request_website(): """ Return the website set on `request` if called in a frontend context (website=True on route). This method can typically be used to check if we are in the frontend. This method is easy to mock during python tests to simulate frontend context, rather than mocking every method accessing request.website. Don't import directly the method or it won't be mocked during tests, do: ``` from odoo.addons.website.models import ir_http my_var = ir_http.get_request_website() ``` """ return request and getattr(request, 'website', False) or False class Http(models.AbstractModel): _inherit = 'ir.http' @classmethod def routing_map(cls, key=None): key = key or (request and request.website_routing) return super(Http, cls).routing_map(key=key) @classmethod def clear_caches(cls): super(Http, cls)._clear_routing_map() return super(Http, cls).clear_caches() @classmethod def _slug_matching(cls, adapter, endpoint, **kw): for arg in kw: if isinstance(kw[arg], models.BaseModel): kw[arg] = kw[arg].with_context(slug_matching=True) qs = request.httprequest.query_string.decode('utf-8') return adapter.build(endpoint, kw) + (qs and '?%s' % qs or '') @classmethod def _match(cls, path_info, key=None): key = key or (request and request.website_routing) return super(Http, cls)._match(path_info, key=key) @classmethod def _generate_routing_rules(cls, modules, converters): website_id = request.website_routing logger.debug("_generate_routing_rules for website: %s", website_id) domain = [('redirect_type', 'in', ('308', '404')), '|', ('website_id', '=', False), ('website_id', '=', website_id)] rewrites = dict([(x.url_from, x) for x in request.env['website.rewrite'].sudo().search(domain)]) cls._rewrite_len[website_id] = len(rewrites) for url, endpoint, routing in super(Http, cls)._generate_routing_rules(modules, converters): routing = dict(routing) if url in rewrites: rewrite = rewrites[url] url_to = rewrite.url_to if rewrite.redirect_type == '308': logger.debug('Add rule %s for %s' % (url_to, website_id)) yield url_to, endpoint, routing # yield new url if url != url_to: logger.debug('Redirect from %s to %s for website %s' % (url, url_to, website_id)) _slug_matching = partial(cls._slug_matching, endpoint=endpoint) routing['redirect_to'] = _slug_matching yield url, endpoint, routing # yield original redirected to new url elif rewrite.redirect_type == '404': logger.debug('Return 404 for %s for website %s' % (url, website_id)) continue else: yield url, endpoint, routing @classmethod def _get_converters(cls): """ Get the converters list for custom url pattern werkzeug need to match Rule. This override adds the website ones. """ return dict( super(Http, cls)._get_converters(), model=ModelConverter, ) @classmethod def _auth_method_public(cls): """ If no user logged, set the public user of current website, or default public user as request uid. After this method `request.env` can be called, since the `request.uid` is set. The `env` lazy property of `request` will be correct. """ if not request.session.uid: env = api.Environment(request.cr, SUPERUSER_ID, request.context) website = env['website'].get_current_website() request.uid = website and website._get_cached('user_id') if not request.uid: super(Http, cls)._auth_method_public() @classmethod def _register_website_track(cls, response): if getattr(response, 'status_code', 0) != 200: return False template = False if hasattr(response, '_cached_page'): website_page, template = response._cached_page, response._cached_template elif hasattr(response, 'qcontext'): # classic response main_object = response.qcontext.get('main_object') website_page = getattr(main_object, '_name', False) == 'website.page' and main_object template = response.qcontext.get('response_template') view = template and request.env['website'].get_template(template) if view and view.track: request.env['website.visitor']._handle_webpage_dispatch(response, website_page) return False @classmethod def _postprocess_args(cls, arguments, rule): processing = super()._postprocess_args(arguments, rule) if processing: return processing for record in arguments.values(): if isinstance(record, models.BaseModel) and hasattr(record, 'can_access_from_current_website'): try: if not record.can_access_from_current_website(): return request.env['ir.http']._handle_exception(werkzeug.exceptions.NotFound()) except AccessError: # record.website_id might not be readable as unpublished `event.event` due to ir.rule, # return 403 instead of using `sudo()` for perfs as this is low level return request.env['ir.http']._handle_exception(werkzeug.exceptions.Forbidden()) @classmethod def _dispatch(cls): """ In case of rerouting for translate (e.g. when visiting odoo.com/fr_BE/), _dispatch calls reroute() that returns _dispatch with altered request properties. The second _dispatch will continue until end of process. When second _dispatch is finished, the first _dispatch call receive the new altered request and continue. At the end, 2 calls of _dispatch (and this override) are made with exact same request properties, instead of one. As the response has not been sent back to the client, the visitor cookie does not exist yet when second _dispatch call is treated in _handle_webpage_dispatch, leading to create 2 visitors with exact same properties. To avoid this, we check if, !!! before calling super !!!, we are in a rerouting request. If not, it means that we are handling the original request, in which we should create the visitor. We ignore every other rerouting requests. """ is_rerouting = hasattr(request, 'routing_iteration') if request.session.db: reg = registry(request.session.db) with reg.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) request.website_routing = env['website'].get_current_website().id response = super(Http, cls)._dispatch() if not is_rerouting: cls._register_website_track(response) return response @classmethod def _add_dispatch_parameters(cls, func): # DEPRECATED for /website/force/<website_id> - remove me in master~saas-14.4 # Force website with query string paramater, typically set from website selector in frontend navbar and inside tests force_website_id = request.httprequest.args.get('fw') if (force_website_id and request.session.get('force_website_id') != force_website_id and request.env.user.has_group('website.group_multi_website') and request.env.user.has_group('website.group_website_publisher')): request.env['website']._force_website(request.httprequest.args.get('fw')) context = {} if not request.context.get('tz'): context['tz'] = request.session.get('geoip', {}).get('time_zone') try: pytz.timezone(context['tz'] or '') except pytz.UnknownTimeZoneError: context.pop('tz') request.website = request.env['website'].get_current_website() # can use `request.env` since auth methods are called context['website_id'] = request.website.id # This is mainly to avoid access errors in website controllers where there is no # context (eg: /shop), and it's not going to propagate to the global context of the tab # If the company of the website is not in the allowed companies of the user, set the main # company of the user. website_company_id = request.website._get_cached('company_id') if request.website.is_public_user(): # avoid a read on res_company_user_rel in case of public user context['allowed_company_ids'] = [website_company_id] elif website_company_id in request.env.user.company_ids.ids: context['allowed_company_ids'] = [website_company_id] else: context['allowed_company_ids'] = request.env.user.company_id.ids # modify bound context request.context = dict(request.context, **context) super(Http, cls)._add_dispatch_parameters(func) if request.routing_iteration == 1: request.website = request.website.with_context(request.context) @classmethod def _get_frontend_langs(cls): if get_request_website(): return [code for code, *_ in request.env['res.lang'].get_available()] else: return super()._get_frontend_langs() @classmethod def _get_default_lang(cls): if getattr(request, 'website', False): return request.env['res.lang'].browse(request.website._get_cached('default_lang_id')) return super(Http, cls)._get_default_lang() @classmethod def _get_translation_frontend_modules_name(cls): mods = super(Http, cls)._get_translation_frontend_modules_name() installed = request.registry._init_modules | set(odoo.conf.server_wide_modules) return mods + [mod for mod in installed if mod.startswith('website')] @classmethod def _serve_page(cls): req_page = request.httprequest.path def _search_page(comparator='='): page_domain = [('url', comparator, req_page)] + request.website.website_domain() return request.env['website.page'].sudo().search(page_domain, order='website_id asc', limit=1) # specific page first page = _search_page() # case insensitive search if not page: page = _search_page('=ilike') if page: logger.info("Page %r not found, redirecting to existing page %r", req_page, page.url) return request.redirect(page.url) # redirect without trailing / if not page and req_page != "/" and req_page.endswith("/"): # mimick `_postprocess_args()` redirect path = request.httprequest.path[:-1] if request.lang != cls._get_default_lang(): path = '/' + request.lang.url_code + path if request.httprequest.query_string: path += '?' + request.httprequest.query_string.decode('utf-8') return request.redirect(path, code=301) if page: # prefetch all menus (it will prefetch website.page too) menu_pages_ids = request.website._get_menu_page_ids() page.browse([page.id] + menu_pages_ids).mapped('view_id.name') request.website.menu_id if page and (request.website.is_publisher() or page.is_visible): need_to_cache = False cache_key = page._get_cache_key(request) if ( page.cache_time # cache > 0 and request.httprequest.method == "GET" and request.env.user._is_public() # only cache for unlogged user and 'nocache' not in request.params # allow bypass cache / debug and not request.session.debug and len(cache_key) and cache_key[-1] is not None # nocache via expr ): need_to_cache = True try: r = page._get_cache_response(cache_key) if r['time'] + page.cache_time > time.time(): response = odoo.http.Response(r['content'], mimetype=r['contenttype']) response._cached_template = r['template'] response._cached_page = page return response except KeyError: pass _, ext = os.path.splitext(req_page) response = request.render(page.view_id.id, { 'deletable': True, 'main_object': page, }, mimetype=_guess_mimetype(ext)) if need_to_cache and response.status_code == 200: r = response.render() page._set_cache_response(cache_key, { 'content': r, 'contenttype': response.headers['Content-Type'], 'time': time.time(), 'template': getattr(response, 'qcontext', {}).get('response_template') }) return response return False @classmethod def _serve_redirect(cls): req_page = request.httprequest.path domain = [ ('redirect_type', 'in', ('301', '302')), # trailing / could have been removed by server_page '|', ('url_from', '=', req_page.rstrip('/')), ('url_from', '=', req_page + '/') ] domain += request.website.website_domain() return request.env['website.rewrite'].sudo().search(domain, limit=1) @classmethod def _serve_fallback(cls, exception): # serve attachment before parent = super(Http, cls)._serve_fallback(exception) if parent: # attachment return parent if not request.is_frontend: return False website_page = cls._serve_page() if website_page: return website_page redirect = cls._serve_redirect() if redirect: return request.redirect( _build_url_w_params(redirect.url_to, request.params), code=redirect.redirect_type, local=False) # safe because only designers can specify redirects return False @classmethod def _get_exception_code_values(cls, exception): code, values = super(Http, cls)._get_exception_code_values(exception) if isinstance(exception, werkzeug.exceptions.NotFound) and request.website.is_publisher(): code = 'page_404' values['path'] = request.httprequest.path[1:] if isinstance(exception, werkzeug.exceptions.Forbidden) and \ exception.description == "website_visibility_password_required": code = 'protected_403' values['path'] = request.httprequest.path return (code, values) @classmethod def _get_values_500_error(cls, env, values, exception): View = env["ir.ui.view"] values = super(Http, cls)._get_values_500_error(env, values, exception) if 'qweb_exception' in values: try: # exception.name might be int, string exception_template = int(exception.name) except ValueError: exception_template = exception.name view = View._view_obj(exception_template) if exception.html and exception.html in view.arch: values['view'] = view else: # There might be 2 cases where the exception code can't be found # in the view, either the error is in a child view or the code # contains branding (<div t-att-data="request.browse('ok')"/>). et = view.with_context(inherit_branding=False)._get_combined_arch() node = et.xpath(exception.path) if exception.path else et line = node is not None and etree.tostring(node[0], encoding='unicode') if line: values['view'] = View._views_get(exception_template).filtered( lambda v: line in v.arch ) values['view'] = values['view'] and values['view'][0] # Needed to show reset template on translated pages (`_prepare_qcontext` will set it for main lang) values['editable'] = request.uid and request.website.is_publisher() return values @classmethod def _get_error_html(cls, env, code, values): if code in ('page_404', 'protected_403'): return code.split('_')[1], env['ir.ui.view']._render_template('website.%s' % code, values) return super(Http, cls)._get_error_html(env, code, values) def binary_content(self, xmlid=None, model='ir.attachment', id=None, field='datas', unique=False, filename=None, filename_field='name', download=False, mimetype=None, default_mimetype='application/octet-stream', access_token=None): obj = None if xmlid: obj = self._xmlid_to_obj(self.env, xmlid) elif id and model in self.env: obj = self.env[model].browse(int(id)) if obj and 'website_published' in obj._fields: if self.env[obj._name].sudo().search([('id', '=', obj.id), ('website_published', '=', True)]): self = self.sudo() return super(Http, self).binary_content( xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename, filename_field=filename_field, download=download, mimetype=mimetype, default_mimetype=default_mimetype, access_token=access_token) @classmethod def _xmlid_to_obj(cls, env, xmlid): website_id = env['website'].get_current_website() if website_id and website_id.theme_id: domain = [('key', '=', xmlid), ('website_id', '=', website_id.id)] Attachment = env['ir.attachment'] if request.env.user.share: domain.append(('public', '=', True)) Attachment = Attachment.sudo() obj = Attachment.search(domain) if obj: return obj[0] return super(Http, cls)._xmlid_to_obj(env, xmlid) @api.model def get_frontend_session_info(self): session_info = super(Http, self).get_frontend_session_info() session_info.update({ 'is_website_user': request.env.user.id == request.website.user_id.id, 'lang_url_code': request.lang._get_cached('url_code'), 'geoip_country_code': request.session.get('geoip', {}).get('country_code'), }) if request.env.user.has_group('website.group_website_publisher'): session_info.update({ 'website_id': request.website.id, 'website_company_id': request.website._get_cached('company_id'), }) return session_info class ModelConverter(ir_http.ModelConverter): def to_url(self, value): if value.env.context.get('slug_matching'): return value.env.context.get('_converter_value', str(value.id)) return super().to_url(value) def generate(self, uid, dom=None, args=None): Model = request.env[self.model].with_user(uid) # Allow to current_website_id directly in route domain args.update(current_website_id=request.env['website'].get_current_website().id) domain = safe_eval(self.domain, (args or {}).copy()) if dom: domain += dom for record in Model.search(domain): # return record so URL will be the real endpoint URL as the record will go through `slug()` # the same way as endpoint URL is retrieved during dispatch (301 redirect), see `to_url()` from ModelConverter yield record
44.605809
21,500
1,517
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import fields, models, api from odoo.exceptions import UserError from odoo.tools.translate import _ _logger = logging.getLogger(__name__) class Attachment(models.Model): _inherit = "ir.attachment" # related for backward compatibility with saas-6 website_url = fields.Char(string="Website URL", related='local_url', deprecated=True, readonly=False) key = fields.Char(help='Technical field used to resolve multiple attachments in a multi-website environment.') website_id = fields.Many2one('website') @api.model def create(self, vals): website = self.env['website'].get_current_website(fallback=False) if website and 'website_id' not in vals and 'not_force_website_id' not in self.env.context: vals['website_id'] = website.id return super(Attachment, self).create(vals) @api.model def get_serving_groups(self): return super(Attachment, self).get_serving_groups() + ['website.group_website_designer'] @api.model def get_serve_attachment(self, url, extra_domain=None, extra_fields=None, order=None): website = self.env['website'].get_current_website() extra_domain = (extra_domain or []) + website.website_domain() order = ('website_id, %s' % order) if order else 'website_id' return super(Attachment, self).get_serve_attachment(url, extra_domain, extra_fields, order)
42.138889
1,517
1,440
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 from odoo.http import request _logger = logging.getLogger(__name__) class IrModelData(models.Model): _inherit = 'ir.model.data' @api.model def _process_end_unlink_record(self, record): if record._context['module'].startswith('theme_'): theme_records = self.env['ir.module.module']._theme_model_names.values() if record._name in theme_records: # use active_test to also unlink archived models # and use MODULE_UNINSTALL_FLAG to also unlink inherited models copy_ids = record.with_context({ 'active_test': False, 'MODULE_UNINSTALL_FLAG': True }).copy_ids if request: # we are in a website context, see `write()` override of # ir.module.module in website current_website = self.env['website'].get_current_website() copy_ids = copy_ids.filtered(lambda c: c.website_id == current_website) _logger.info('Deleting %s@%s (theme `copy_ids`) for website %s', copy_ids.ids, record._name, copy_ids.mapped('website_id')) copy_ids.unlink() return super()._process_end_unlink_record(record)
40
1,440
5,581
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, SUPERUSER_ID from odoo.http import request class website_form_config(models.Model): _inherit = 'website' def _website_form_last_record(self): if request and request.session.form_builder_model_model: return request.env[request.session.form_builder_model_model].browse(request.session.form_builder_id) return False class website_form_model(models.Model): _name = 'ir.model' _description = 'Models' _inherit = 'ir.model' website_form_access = fields.Boolean('Allowed to use in forms', help='Enable the form builder feature for this model.') website_form_default_field_id = fields.Many2one('ir.model.fields', 'Field for custom form data', domain="[('model', '=', model), ('ttype', '=', 'text')]", help="Specify the field which will contain meta and custom form fields datas.") website_form_label = fields.Char("Label for form action", help="Form action label. Ex: crm.lead could be 'Send an e-mail' and project.issue could be 'Create an Issue'.") website_form_key = fields.Char(help='Used in FormBuilder Registry') def _get_form_writable_fields(self): """ Restriction of "authorized fields" (fields which can be used in the form builders) to fields which have actually been opted into form builders and are writable. By default no field is writable by the form builder. """ included = { field.name for field in self.env['ir.model.fields'].sudo().search([ ('model_id', '=', self.id), ('website_form_blacklisted', '=', False) ]) } return { k: v for k, v in self.get_authorized_fields(self.model).items() if k in included } @api.model def get_authorized_fields(self, model_name): """ Return the fields of the given model name as a mapping like method `fields_get`. """ model = self.env[model_name] fields_get = model.fields_get() for key, val in model._inherits.items(): fields_get.pop(val, None) # Unrequire fields with default values default_values = model.with_user(SUPERUSER_ID).default_get(list(fields_get)) for field in [f for f in fields_get if f in default_values]: fields_get[field]['required'] = False # Remove readonly and magic fields # Remove string domains which are supposed to be evaluated # (e.g. "[('product_id', '=', product_id)]") MAGIC_FIELDS = models.MAGIC_COLUMNS + [model.CONCURRENCY_CHECK_FIELD] for field in list(fields_get): if 'domain' in fields_get[field] and isinstance(fields_get[field]['domain'], str): del fields_get[field]['domain'] if fields_get[field].get('readonly') or field in MAGIC_FIELDS or fields_get[field]['type'] == 'many2one_reference': del fields_get[field] return fields_get @api.model def get_compatible_form_models(self): if not self.env.user.has_group('website.group_website_publisher'): return [] return self.sudo().search_read( [('website_form_access', '=', True)], ['id', 'model', 'name', 'website_form_label', 'website_form_key'], ) class website_form_model_fields(models.Model): """ fields configuration for form builder """ _name = 'ir.model.fields' _description = 'Fields' _inherit = 'ir.model.fields' def init(self): # set all existing unset website_form_blacklisted fields to ``true`` # (so that we can use it as a whitelist rather than a blacklist) self._cr.execute('UPDATE ir_model_fields' ' SET website_form_blacklisted=true' ' WHERE website_form_blacklisted IS NULL') # add an SQL-level default value on website_form_blacklisted to that # pure-SQL ir.model.field creations (e.g. in _reflect) generate # the right default value for a whitelist (aka fields should be # blacklisted by default) self._cr.execute('ALTER TABLE ir_model_fields ' ' ALTER COLUMN website_form_blacklisted SET DEFAULT true') @api.model def formbuilder_whitelist(self, model, fields): """ :param str model: name of the model on which to whitelist fields :param list(str) fields: list of fields to whitelist on the model :return: nothing of import """ # postgres does *not* like ``in [EMPTY TUPLE]`` queries if not fields: return False # only allow users who can change the website structure if not self.env['res.users'].has_group('website.group_website_designer'): return False # the ORM only allows writing on custom fields and will trigger a # registry reload once that's happened. We want to be able to # whitelist non-custom fields and the registry reload absolutely # isn't desirable, so go with a method and raw SQL self.env.cr.execute( "UPDATE ir_model_fields" " SET website_form_blacklisted=false" " WHERE model=%s AND name in %s", (model, tuple(fields))) return True website_form_blacklisted = fields.Boolean( 'Blacklisted in web forms', default=True, index=True, # required=True, help='Blacklist this field for web forms' )
43.601563
5,581
9,530
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import werkzeug.exceptions import werkzeug.urls from odoo import api, fields, models from odoo.http import request from odoo.tools.translate import html_translate class Menu(models.Model): _name = "website.menu" _description = "Website Menu" _parent_store = True _order = "sequence, id" def _default_sequence(self): menu = self.search([], limit=1, order="sequence DESC") return menu.sequence or 0 @api.depends('mega_menu_content') def _compute_field_is_mega_menu(self): for menu in self: menu.is_mega_menu = bool(menu.mega_menu_content) def _set_field_is_mega_menu(self): for menu in self: if menu.is_mega_menu: if not menu.mega_menu_content: menu.mega_menu_content = self.env['ir.ui.view']._render_template('website.s_mega_menu_odoo_menu') else: menu.mega_menu_content = False menu.mega_menu_classes = False name = fields.Char('Menu', required=True, translate=True) url = fields.Char('Url', default='') page_id = fields.Many2one('website.page', 'Related Page', ondelete='cascade') new_window = fields.Boolean('New Window') sequence = fields.Integer(default=_default_sequence) website_id = fields.Many2one('website', 'Website', ondelete='cascade') parent_id = fields.Many2one('website.menu', 'Parent Menu', index=True, ondelete="cascade") child_id = fields.One2many('website.menu', 'parent_id', string='Child Menus') parent_path = fields.Char(index=True) is_visible = fields.Boolean(compute='_compute_visible', string='Is Visible') group_ids = fields.Many2many('res.groups', string='Visible Groups', help="User need to be at least in one of these groups to see the menu") is_mega_menu = fields.Boolean(compute=_compute_field_is_mega_menu, inverse=_set_field_is_mega_menu) mega_menu_content = fields.Html(translate=html_translate, sanitize=False, prefetch=True) mega_menu_classes = fields.Char() def name_get(self): if not self._context.get('display_website') and not self.env.user.has_group('website.group_multi_website'): return super(Menu, self).name_get() res = [] for menu in self: menu_name = menu.name if menu.website_id: menu_name += ' [%s]' % menu.website_id.name res.append((menu.id, menu_name)) return res @api.model def create(self, vals): ''' In case a menu without a website_id is trying to be created, we duplicate it for every website. Note: Particulary useful when installing a module that adds a menu like /shop. So every website has the shop menu. Be careful to return correct record for ir.model.data xml_id in case of default main menus creation. ''' self.clear_caches() # Only used when creating website_data.xml default menu if vals.get('url') == '/default-main-menu': return super(Menu, self).create(vals) if 'website_id' in vals: return super(Menu, self).create(vals) elif self._context.get('website_id'): vals['website_id'] = self._context.get('website_id') return super(Menu, self).create(vals) else: # create for every site for website in self.env['website'].search([]): w_vals = dict(vals, **{ 'website_id': website.id, 'parent_id': website.menu_id.id, }) res = super(Menu, self).create(w_vals) # if creating a default menu, we should also save it as such default_menu = self.env.ref('website.main_menu', raise_if_not_found=False) if default_menu and vals.get('parent_id') == default_menu.id: res = super(Menu, self).create(vals) return res # Only one record is returned but multiple could have been created def write(self, values): res = super().write(values) if 'website_id' in values or 'group_ids' in values or 'sequence' in values or 'page_id' in values: self.clear_caches() return res def unlink(self): self.clear_caches() default_menu = self.env.ref('website.main_menu', raise_if_not_found=False) menus_to_remove = self for menu in self.filtered(lambda m: default_menu and m.parent_id.id == default_menu.id): menus_to_remove |= self.env['website.menu'].search([('url', '=', menu.url), ('website_id', '!=', False), ('id', '!=', menu.id)]) return super(Menu, menus_to_remove).unlink() def _compute_visible(self): for menu in self: visible = True if menu.page_id and not menu.user_has_groups('base.group_user'): page_sudo = menu.page_id.sudo() if (not page_sudo.is_visible or (not page_sudo.view_id._handle_visibility(do_raise=False) and page_sudo.view_id.visibility != "password")): visible = False menu.is_visible = visible @api.model def clean_url(self): # clean the url with heuristic if self.page_id: url = self.page_id.sudo().url else: url = self.url if url and not self.url.startswith('/'): if '@' in self.url: if not self.url.startswith('mailto'): url = 'mailto:%s' % self.url elif not self.url.startswith('http'): url = '/%s' % self.url return url # would be better to take a menu_id as argument @api.model def get_tree(self, website_id, menu_id=None): def make_tree(node): is_homepage = bool(node.page_id and self.env['website'].browse(website_id).homepage_id.id == node.page_id.id) menu_node = { 'fields': { 'id': node.id, 'name': node.name, 'url': node.page_id.url if node.page_id else node.url, 'new_window': node.new_window, 'is_mega_menu': node.is_mega_menu, 'sequence': node.sequence, 'parent_id': node.parent_id.id, }, 'children': [], 'is_homepage': is_homepage, } for child in node.child_id: menu_node['children'].append(make_tree(child)) return menu_node menu = menu_id and self.browse(menu_id) or self.env['website'].browse(website_id).menu_id return make_tree(menu) @api.model def save(self, website_id, data): def replace_id(old_id, new_id): for menu in data['data']: if menu['id'] == old_id: menu['id'] = new_id if menu['parent_id'] == old_id: menu['parent_id'] = new_id to_delete = data.get('to_delete') if to_delete: self.browse(to_delete).unlink() for menu in data['data']: mid = menu['id'] # new menu are prefixed by new- if isinstance(mid, str): new_menu = self.create({'name': menu['name'], 'website_id': website_id}) replace_id(mid, new_menu.id) for menu in data['data']: menu_id = self.browse(menu['id']) # Check if the url match a website.page (to set the m2o relation), # except if the menu url contains '#', we then unset the page_id if '#' in menu['url']: # Multiple case possible # 1. `#` => menu container (dropdown, ..) # 2. `#anchor` => anchor on current page # 3. `/url#something` => valid internal URL # 4. https://google.com#smth => valid external URL if menu_id.page_id: menu_id.page_id = None if request and menu['url'].startswith('#') and len(menu['url']) > 1: # Working on case 2.: prefix anchor with referer URL referer_url = werkzeug.urls.url_parse(request.httprequest.headers.get('Referer', '')).path menu['url'] = referer_url + menu['url'] else: domain = self.env["website"].website_domain(website_id) + [ "|", ("url", "=", menu["url"]), ("url", "=", "/" + menu["url"]), ] page = self.env["website.page"].search(domain, limit=1) if page: menu['page_id'] = page.id menu['url'] = page.url elif menu_id.page_id: try: # a page shouldn't have the same url as a controller self.env['ir.http']._match(menu['url']) menu_id.page_id = None except werkzeug.exceptions.NotFound: menu_id.page_id.write({'url': menu['url']}) menu_id.write(menu) return True
43.715596
9,530
955
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, tools from odoo.http import request class IrUiMenu(models.Model): _inherit = 'ir.ui.menu' @api.model @tools.ormcache_context('self._uid', keys=('lang', 'force_action',)) def load_menus_root(self): root_menus = super().load_menus_root() if self.env.context.get('force_action'): web_menus = self.load_web_menus(request.session.debug if request else False) for menu in root_menus['children']: # Force the action. if ( not menu['action'] and web_menus[menu['id']]['actionModel'] and web_menus[menu['id']]['actionID'] ): menu['action'] = f"{web_menus[menu['id']]['actionModel']},{web_menus[menu['id']]['actionID']}" return root_menus
36.730769
955
278
py
PYTHON
15.0
from odoo import models class MailThread(models.AbstractModel): _inherit = 'mail.thread' def message_post_with_view(self, views_or_xmlid, **kwargs): super(MailThread, self.with_context(inherit_branding=False)).message_post_with_view(views_or_xmlid, **kwargs)
34.75
278
631
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 Contact(models.AbstractModel): _inherit = 'ir.qweb.field.contact' @api.model def get_available_options(self): options = super(Contact, self).get_available_options() options.update( website_description=dict(type='boolean', string=_('Display the website description')), UserBio=dict(type='boolean', string=_('Display the biography')), badges=dict(type='boolean', string=_('Display the badges')) ) return options
35.055556
631
15,749
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from psycopg2 import sql import re from odoo.addons.http_routing.models.ir_http import slugify from odoo.addons.website.tools import text_from_html from odoo import api, fields, models from odoo.osv import expression from odoo.tools import escape_psql from odoo.tools.safe_eval import safe_eval class Page(models.Model): _name = 'website.page' _inherits = {'ir.ui.view': 'view_id'} _inherit = [ 'website.published.multi.mixin', 'website.searchable.mixin', ] _description = 'Page' _order = 'website_id' url = fields.Char('Page URL') view_id = fields.Many2one('ir.ui.view', string='View', required=True, ondelete="cascade") website_indexed = fields.Boolean('Is Indexed', default=True) date_publish = fields.Datetime('Publishing Date') # This is needed to be able to display if page is a menu in /website/pages menu_ids = fields.One2many('website.menu', 'page_id', 'Related Menus') is_homepage = fields.Boolean(compute='_compute_homepage', inverse='_set_homepage', string='Homepage') is_visible = fields.Boolean(compute='_compute_visible', string='Is Visible') cache_time = fields.Integer(default=3600, help='Time to cache the page. (0 = no cache)') cache_key_expr = fields.Char(help='Expression (tuple) to evaluate the cached key. \nE.g.: "(request.params.get("currency"), )"') # Page options header_overlay = fields.Boolean() header_color = fields.Char() header_visible = fields.Boolean(default=True) footer_visible = fields.Boolean(default=True) # don't use mixin website_id but use website_id on ir.ui.view instead website_id = fields.Many2one(related='view_id.website_id', store=True, readonly=False, ondelete='cascade') arch = fields.Text(related='view_id.arch', readonly=False, depends_context=('website_id',)) def _compute_homepage(self): for page in self: page.is_homepage = page == self.env['website'].get_current_website().homepage_id def _set_homepage(self): for page in self: website = self.env['website'].get_current_website() if page.is_homepage: if website.homepage_id != page: website.write({'homepage_id': page.id}) else: if website.homepage_id == page: website.write({'homepage_id': None}) def _compute_visible(self): for page in self: page.is_visible = page.website_published and ( not page.date_publish or page.date_publish < fields.Datetime.now() ) def _get_most_specific_pages(self): ''' Returns the most specific pages in self. ''' ids = [] previous_page = None # Iterate a single time on the whole list sorted on specific-website first. for page in self.sorted(key=lambda p: (p.url, not p.website_id)): if not previous_page or page.url != previous_page.url: ids.append(page.id) previous_page = page return self.filtered(lambda page: page.id in ids) def get_page_properties(self): self.ensure_one() res = self.read([ 'id', 'view_id', 'name', 'url', 'website_published', 'website_indexed', 'date_publish', 'menu_ids', 'is_homepage', 'website_id', 'visibility', 'groups_id' ])[0] if not res['groups_id']: res['group_id'] = self.env.ref('base.group_user').name_get()[0] elif len(res['groups_id']) == 1: res['group_id'] = self.env['res.groups'].browse(res['groups_id']).name_get()[0] del res['groups_id'] res['visibility_password'] = res['visibility'] == 'password' and self.visibility_password_display or '' return res @api.model def save_page_info(self, website_id, data): website = self.env['website'].browse(website_id) page = self.browse(int(data['id'])) # If URL has been edited, slug it original_url = page.url url = data['url'] if not url.startswith('/'): url = '/' + url if page.url != url: url = '/' + slugify(url, max_length=1024, path=True) url = self.env['website'].get_unique_path(url) # If name has changed, check for key uniqueness if page.name != data['name']: page_key = self.env['website'].get_unique_key(slugify(data['name'])) else: page_key = page.key menu = self.env['website.menu'].search([('page_id', '=', int(data['id']))]) if not data['is_menu']: # If the page is no longer in menu, we should remove its website_menu if menu: menu.unlink() else: # The page is now a menu, check if has already one if menu: menu.write({'url': url}) else: self.env['website.menu'].create({ 'name': data['name'], 'url': url, 'page_id': data['id'], 'parent_id': website.menu_id.id, 'website_id': website.id, }) # Edits via the page manager shouldn't trigger the COW # mechanism and generate new pages. The user manages page # visibility manually with is_published here. w_vals = { 'key': page_key, 'name': data['name'], 'url': url, 'is_published': data['website_published'], 'website_indexed': data['website_indexed'], 'date_publish': data['date_publish'] or None, 'is_homepage': data['is_homepage'], 'visibility': data['visibility'], } if page.visibility == 'restricted_group' and data['visibility'] != "restricted_group": w_vals['groups_id'] = False elif 'group_id' in data: w_vals['groups_id'] = [data['group_id']] if 'visibility_pwd' in data: w_vals['visibility_password_display'] = data['visibility_pwd'] or '' page.with_context(no_cow=True).write(w_vals) # Create redirect if needed if data['create_redirect']: self.env['website.rewrite'].create({ 'name': data['name'], 'redirect_type': data['redirect_type'], 'url_from': original_url, 'url_to': url, 'website_id': website.id, }) return url @api.returns('self', lambda value: value.id) def copy(self, default=None): if default: if not default.get('view_id'): view = self.env['ir.ui.view'].browse(self.view_id.id) new_view = view.copy({'website_id': default.get('website_id')}) default['view_id'] = new_view.id default['url'] = default.get('url', self.env['website'].get_unique_path(self.url)) return super(Page, self).copy(default=default) @api.model def clone_page(self, page_id, page_name=None, clone_menu=True): """ Clone a page, given its identifier :param page_id : website.page identifier """ page = self.browse(int(page_id)) copy_param = dict(name=page_name or page.name, website_id=self.env['website'].get_current_website().id) if page_name: page_url = '/' + slugify(page_name, max_length=1024, path=True) copy_param['url'] = self.env['website'].get_unique_path(page_url) new_page = page.copy(copy_param) # Should not clone menu if the page was cloned from one website to another # Eg: Cloning a generic page (no website) will create a page with a website, we can't clone menu (not same container) if clone_menu and new_page.website_id == page.website_id: menu = self.env['website.menu'].search([('page_id', '=', page_id)], limit=1) if menu: # If the page being cloned has a menu, clone it too menu.copy({'url': new_page.url, 'name': new_page.name, 'page_id': new_page.id}) return new_page.url + '?enable_editor=1' def unlink(self): # When a website_page is deleted, the ORM does not delete its # ir_ui_view. So we got to delete it ourself, but only if the # ir_ui_view is not used by another website_page. for page in self: # Other pages linked to the ir_ui_view of the page being deleted (will it even be possible?) pages_linked_to_iruiview = self.search( [('view_id', '=', page.view_id.id), ('id', '!=', page.id)] ) if not pages_linked_to_iruiview and not page.view_id.inherit_children_ids: # If there is no other pages linked to that ir_ui_view, we can delete the ir_ui_view page.view_id.unlink() # Make sure website._get_menu_ids() will be recomputed self.clear_caches() return super(Page, self).unlink() def write(self, vals): if 'url' in vals and not vals['url'].startswith('/'): vals['url'] = '/' + vals['url'] self.clear_caches() # write on page == write on view that invalid cache return super(Page, self).write(vals) def get_website_meta(self): self.ensure_one() return self.view_id.get_website_meta() @classmethod def _get_cached_blacklist(cls): return ('data-snippet="s_website_form"', 'data-no-page-cache=', ) def _can_be_cached(self, response): """ return False if at least one blacklisted's word is present in content """ blacklist = self._get_cached_blacklist() return not any(black in str(response) for black in blacklist) def _get_cache_key(self, req): # Always call me with super() AT THE END to have cache_key_expr appended as last element # It is the only way for end user to not use cache via expr. # E.g (None if 'token' in request.params else 1,) will bypass cache_time cache_key = (req.website.id, req.lang, req.httprequest.path) if self.cache_key_expr: # e.g. (request.session.geoip.get('country_code'),) cache_key += safe_eval(self.cache_key_expr, {'request': req}) return cache_key def _get_cache_response(self, cache_key): """ Return the cached response corresponding to ``self`` and ``cache_key``. Raise a KeyError if the item is not in cache. """ # HACK: we use the same LRU as ormcache to take advantage from its # distributed invalidation, but we don't explicitly use ormcache return self.pool._Registry__cache[('website.page', _cached_response, self.id, cache_key)] def _set_cache_response(self, cache_key, response): """ Put in cache the given response. """ self.pool._Registry__cache[('website.page', _cached_response, self.id, cache_key)] = response @api.model def _search_get_detail(self, website, order, options): with_description = options['displayDescription'] # Read access on website.page requires sudo. requires_sudo = True domain = [website.website_domain()] if not self.env.user.has_group('website.group_website_designer'): # Rule must be reinforced because of sudo. domain.append([('website_published', '=', True)]) search_fields = ['name', 'url'] fetch_fields = ['id', 'name', 'url'] mapping = { 'name': {'name': 'name', 'type': 'text', 'match': True}, 'website_url': {'name': 'url', 'type': 'text', 'truncate': False}, } if with_description: search_fields.append('arch_db') fetch_fields.append('arch') mapping['description'] = {'name': 'arch', 'type': 'text', 'html': True, 'match': True} return { 'model': 'website.page', 'base_domain': domain, 'requires_sudo': requires_sudo, 'search_fields': search_fields, 'fetch_fields': fetch_fields, 'mapping': mapping, 'icon': 'fa-file-o', } @api.model def _search_fetch(self, search_detail, search, limit, order): with_description = 'description' in search_detail['mapping'] # Cannot rely on the super's _search_fetch because the search must be # performed among the most specific pages only. fields = search_detail['search_fields'] base_domain = search_detail['base_domain'] domain = self._search_build_domain(base_domain, search, fields, search_detail.get('search_extra')) # TODO In 16.0 do not rely on _filter_duplicate_pages. most_specific_pages = self.env['website'].with_context(_filter_duplicate_pages='url' not in order)._get_website_pages( domain=expression.AND(base_domain), order=order ) results = most_specific_pages.filtered_domain(domain) # already sudo if with_description and search: # Perform search in translations # TODO Remove when domains will support xml_translate fields query = sql.SQL(""" SELECT DISTINCT {table}.{id} FROM {table} LEFT JOIN ir_translation t ON {table}.{view_id} = t.{res_id} WHERE t.lang = {lang} AND t.name = ANY({names}) AND t.type = 'model_terms' AND t.value ilike {search} AND {table}.{id} IN {ids} LIMIT {limit} """).format( table=sql.Identifier(self._table), id=sql.Identifier('id'), view_id=sql.Identifier('view_id'), res_id=sql.Identifier('res_id'), lang=sql.Placeholder('lang'), names=sql.Placeholder('names'), search=sql.Placeholder('search'), ids=sql.Placeholder('ids'), limit=sql.Placeholder('limit'), ) self.env.cr.execute(query, { 'lang': self.env.lang, 'names': ['ir.ui.view,arch_db', 'ir.ui.view,name'], 'search': '%%%s%%' % escape_psql(search), 'ids': tuple(most_specific_pages.ids), 'limit': len(most_specific_pages.ids), }) ids = {row[0] for row in self.env.cr.fetchall()} if ids: ids.update(results.ids) domains = search_detail['base_domain'].copy() domains.append([('id', 'in', list(ids))]) domain = expression.AND(domains) model = self.sudo() if search_detail.get('requires_sudo') else self results = model.search( domain, limit=len(ids), order=search_detail.get('order', order) ) def filter_page(search, page, all_pages): # Search might have matched words in the xml tags and parameters therefore we make # sure the terms actually appear inside the text. text = '%s %s %s' % (page.name, page.url, text_from_html(page.arch)) pattern = '|'.join([re.escape(search_term) for search_term in search.split()]) return re.findall('(%s)' % pattern, text, flags=re.I) if pattern else False if search and with_description: results = results.filtered(lambda result: filter_page(search, result, results)) return results[:limit], len(results) # this is just a dummy function to be used as ormcache key def _cached_response(): pass
44.36338
15,749
26,515
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import os import uuid import werkzeug from odoo import api, fields, models from odoo import tools from odoo.addons import website from odoo.exceptions import AccessError from odoo.osv import expression from odoo.http import request _logger = logging.getLogger(__name__) class View(models.Model): _name = "ir.ui.view" _inherit = ["ir.ui.view", "website.seo.metadata"] website_id = fields.Many2one('website', ondelete='cascade', string="Website") page_ids = fields.One2many('website.page', 'view_id') first_page_id = fields.Many2one('website.page', string='Website Page', help='First page linked to this view', compute='_compute_first_page_id') track = fields.Boolean(string='Track', default=False, help="Allow to specify for one page of the website to be trackable or not") visibility = fields.Selection([('', 'All'), ('connected', 'Signed In'), ('restricted_group', 'Restricted Group'), ('password', 'With Password')], default='') visibility_password = fields.Char(groups='base.group_system', copy=False) visibility_password_display = fields.Char(compute='_get_pwd', inverse='_set_pwd', groups='website.group_website_designer') @api.depends('visibility_password') def _get_pwd(self): for r in self: r.visibility_password_display = r.sudo().visibility_password and '********' or '' def _set_pwd(self): crypt_context = self.env.user._crypt_context() for r in self: if r.type == 'qweb': r.sudo().visibility_password = r.visibility_password_display and crypt_context.encrypt(r.visibility_password_display) or '' r.visibility = r.visibility # double check access def _compute_first_page_id(self): for view in self: view.first_page_id = self.env['website.page'].search([('view_id', '=', view.id)], limit=1) @api.model_create_multi def create(self, vals_list): """ SOC for ir.ui.view creation. If a view is created without a website_id, it should get one if one is present in the context. Also check that an explicit website_id in create values matches the one in the context. """ website_id = self.env.context.get('website_id', False) if not website_id: return super().create(vals_list) for vals in vals_list: if 'website_id' not in vals: # Automatic addition of website ID during view creation if not # specified but present in the context vals['website_id'] = website_id else: # If website ID specified, automatic check that it is the same as # the one in the context. Otherwise raise an error. new_website_id = vals['website_id'] if not new_website_id: raise ValueError(f"Trying to create a generic view from a website {website_id} environment") elif new_website_id != website_id: raise ValueError(f"Trying to create a view for website {new_website_id} from a website {website_id} environment") return super().create(vals_list) def name_get(self): if not (self._context.get('display_key') or self._context.get('display_website')): return super(View, self).name_get() res = [] for view in self: view_name = view.name if self._context.get('display_key'): view_name += ' <%s>' % view.key if self._context.get('display_website') and view.website_id: view_name += ' [%s]' % view.website_id.name res.append((view.id, view_name)) return res def write(self, vals): '''COW for ir.ui.view. This way editing websites does not impact other websites. Also this way newly created websites will only contain the default views. ''' current_website_id = self.env.context.get('website_id') if not current_website_id or self.env.context.get('no_cow'): return super(View, self).write(vals) # We need to consider inactive views when handling multi-website cow # feature (to copy inactive children views, to search for specific # views, ...) # Website-specific views need to be updated first because they might # be relocated to new ids by the cow if they are involved in the # inheritance tree. for view in self.with_context(active_test=False).sorted(key='website_id', reverse=True): # Make sure views which are written in a website context receive # a value for their 'key' field if not view.key and not vals.get('key'): view.with_context(no_cow=True).key = 'website.key_%s' % str(uuid.uuid4())[:6] pages = view.page_ids # Disable cache of page if we guess some dynamic content (form with csrf, ...) if vals.get('arch'): to_invalidate = pages.filtered( lambda p: p.cache_time and not p._can_be_cached(vals['arch']) ) to_invalidate and _logger.info('Disable cache for page %s', to_invalidate) to_invalidate.cache_time = 0 # No need of COW if the view is already specific if view.website_id: super(View, view).write(vals) continue # Ensure the cache of the pages stay consistent when doing COW. # This is necessary when writing view fields from a page record # because the generic page will put the given values on its cache # but in reality the values were only meant to go on the specific # page. Invalidate all fields and not only those in vals because # other fields could have been changed implicitly too. pages.flush(records=pages) pages.invalidate_cache(ids=pages.ids) # If already a specific view for this generic view, write on it website_specific_view = view.search([ ('key', '=', view.key), ('website_id', '=', current_website_id) ], limit=1) if website_specific_view: super(View, website_specific_view).write(vals) continue # Set key to avoid copy() to generate an unique key as we want the # specific view to have the same key copy_vals = {'website_id': current_website_id, 'key': view.key} # Copy with the 'inherit_id' field value that will be written to # ensure the copied view's validation works if vals.get('inherit_id'): copy_vals['inherit_id'] = vals['inherit_id'] website_specific_view = view.copy(copy_vals) view._create_website_specific_pages_for_view(website_specific_view, view.env['website'].browse(current_website_id)) for inherit_child in view.inherit_children_ids.filter_duplicate().sorted(key=lambda v: (v.priority, v.id)): if inherit_child.website_id.id == current_website_id: # In the case the child was already specific to the current # website, we cannot just reattach it to the new specific # parent: we have to copy it there and remove it from the # original tree. Indeed, the order of children 'id' fields # must remain the same so that the inheritance is applied # in the same order in the copied tree. child = inherit_child.copy({'inherit_id': website_specific_view.id, 'key': inherit_child.key}) inherit_child.inherit_children_ids.write({'inherit_id': child.id}) inherit_child.unlink() else: # Trigger COW on inheriting views inherit_child.write({'inherit_id': website_specific_view.id}) super(View, website_specific_view).write(vals) return True def _load_records_write_on_cow(self, cow_view, inherit_id, values): inherit_id = self.search([ ('key', '=', self.browse(inherit_id).key), ('website_id', 'in', (False, cow_view.website_id.id)), ], order='website_id', limit=1).id values['inherit_id'] = inherit_id cow_view.with_context(no_cow=True).write(values) def _create_all_specific_views(self, processed_modules): """ When creating a generic child view, we should also create that view under specific view trees (COW'd). Top level view (no inherit_id) do not need that behavior as they will be shared between websites since there is no specific yet. """ # Only for the modules being processed regex = '^(%s)[.]' % '|'.join(processed_modules) # Retrieve the views through a SQl query to avoid ORM queries inside of for loop # Retrieves all the views that are missing their specific counterpart with all the # specific view parent id and their website id in one query query = """ SELECT generic.id, ARRAY[array_agg(spec_parent.id), array_agg(spec_parent.website_id)] FROM ir_ui_view generic INNER JOIN ir_ui_view generic_parent ON generic_parent.id = generic.inherit_id INNER JOIN ir_ui_view spec_parent ON spec_parent.key = generic_parent.key LEFT JOIN ir_ui_view specific ON specific.key = generic.key AND specific.website_id = spec_parent.website_id WHERE generic.type='qweb' AND generic.website_id IS NULL AND generic.key ~ %s AND spec_parent.website_id IS NOT NULL AND specific.id IS NULL GROUP BY generic.id """ self.env.cr.execute(query, (regex, )) result = dict(self.env.cr.fetchall()) for record in self.browse(result.keys()): specific_parent_view_ids, website_ids = result[record.id] for specific_parent_view_id, website_id in zip(specific_parent_view_ids, website_ids): record.with_context(website_id=website_id).write({ 'inherit_id': specific_parent_view_id, }) super(View, self)._create_all_specific_views(processed_modules) def unlink(self): '''This implements COU (copy-on-unlink). When deleting a generic page website-specific pages will be created so only the current website is affected. ''' current_website_id = self._context.get('website_id') if current_website_id and not self._context.get('no_cow'): for view in self.filtered(lambda view: not view.website_id): for w in self.env['website'].search([('id', '!=', current_website_id)]): # reuse the COW mechanism to create # website-specific copies, it will take # care of creating pages and menus. view.with_context(website_id=w.id).write({'name': view.name}) specific_views = self.env['ir.ui.view'] if self and self.pool._init: for view in self.filtered(lambda view: not view.website_id): specific_views += view._get_specific_views() result = super(View, self + specific_views).unlink() self.clear_caches() return result def _create_website_specific_pages_for_view(self, new_view, website): for page in self.page_ids: # create new pages for this view new_page = page.copy({ 'view_id': new_view.id, 'is_published': page.is_published, }) page.menu_ids.filtered(lambda m: m.website_id.id == website.id).page_id = new_page.id def _get_top_level_view(self): self.ensure_one() return self.inherit_id._get_top_level_view() if self.inherit_id else self @api.model def get_related_views(self, key, bundles=False): '''Make this only return most specific views for website.''' # get_related_views can be called through website=False routes # (e.g. /web_editor/get_assets_editor_resources), so website # dispatch_parameters may not be added. Manually set # website_id. (It will then always fallback on a website, this # method should never be called in a generic context, even for # tests) self = self.with_context(website_id=self.env['website'].get_current_website().id) return super(View, self).get_related_views(key, bundles=bundles) def filter_duplicate(self): """ Filter current recordset only keeping the most suitable view per distinct key. Every non-accessible view will be removed from the set: * In non website context, every view with a website will be removed * In a website context, every view from another website """ current_website_id = self._context.get('website_id') most_specific_views = self.env['ir.ui.view'] if not current_website_id: return self.filtered(lambda view: not view.website_id) for view in self: # specific view: add it if it's for the current website and ignore # it if it's for another website if view.website_id and view.website_id.id == current_website_id: most_specific_views |= view # generic view: add it only if, for the current website, there is no # specific view for this view (based on the same `key` attribute) elif not view.website_id and not any(view.key == view2.key and view2.website_id and view2.website_id.id == current_website_id for view2 in self): most_specific_views |= view return most_specific_views @api.model def _view_get_inherited_children(self, view): extensions = super(View, self)._view_get_inherited_children(view) return extensions.filter_duplicate() @api.model def _view_obj(self, view_id): ''' Given an xml_id or a view_id, return the corresponding view record. In case of website context, return the most specific one. :param view_id: either a string xml_id or an integer view_id :return: The view record or empty recordset ''' if isinstance(view_id, str) or isinstance(view_id, int): return self.env['website'].viewref(view_id) else: # It can already be a view object when called by '_views_get()' that is calling '_view_obj' # for it's inherit_children_ids, passing them directly as object record. (Note that it might # be a view_id from another website but it will be filtered in 'get_related_views()') return view_id if view_id._name == 'ir.ui.view' else self.env['ir.ui.view'] @api.model def _get_inheriting_views_domain(self): domain = super(View, self)._get_inheriting_views_domain() current_website = self.env['website'].browse(self._context.get('website_id')) website_views_domain = current_website.website_domain() # when rendering for the website we have to include inactive views # we will prefer inactive website-specific views over active generic ones if current_website: domain = [leaf for leaf in domain if 'active' not in leaf] return expression.AND([website_views_domain, domain]) @api.model def _get_inheriting_views(self): if not self._context.get('website_id'): return super(View, self)._get_inheriting_views() views = super(View, self.with_context(active_test=False))._get_inheriting_views() # prefer inactive website-specific views over active generic ones return views.filter_duplicate().filtered('active') @api.model def _get_filter_xmlid_query(self): """This method add some specific view that do not have XML ID """ if not self._context.get('website_id'): return super()._get_filter_xmlid_query() else: return """SELECT res_id FROM ir_model_data WHERE res_id IN %(res_ids)s AND model = 'ir.ui.view' AND module IN %(modules)s UNION SELECT sview.id FROM ir_ui_view sview INNER JOIN ir_ui_view oview USING (key) INNER JOIN ir_model_data d ON oview.id = d.res_id AND d.model = 'ir.ui.view' AND d.module IN %(modules)s WHERE sview.id IN %(res_ids)s AND sview.website_id IS NOT NULL AND oview.website_id IS NULL; """ @api.model @tools.ormcache_context('self.env.uid', 'self.env.su', 'xml_id', keys=('website_id',)) def get_view_id(self, xml_id): """If a website_id is in the context and the given xml_id is not an int then try to get the id of the specific view for that website, but fallback to the id of the generic view if there is no specific. If no website_id is in the context, it might randomly return the generic or the specific view, so it's probably not recommanded to use this method. `viewref` is probably more suitable. Archived views are ignored (unless the active_test context is set, but then the ormcache_context will not work as expected). """ if 'website_id' in self._context and not isinstance(xml_id, int): current_website = self.env['website'].browse(self._context.get('website_id')) domain = ['&', ('key', '=', xml_id)] + current_website.website_domain() view = self.sudo().search(domain, order='website_id', limit=1) if not view: _logger.warning("Could not find view object with xml_id '%s'", xml_id) raise ValueError('View %r in website %r not found' % (xml_id, self._context['website_id'])) return view.id return super(View, self.sudo()).get_view_id(xml_id) def _handle_visibility(self, do_raise=True): """ Check the visibility set on the main view and raise 403 if you should not have access. Order is: Public, Connected, Has group, Password It only check the visibility on the main content, others views called stay available in rpc. """ error = False self = self.sudo() if self.visibility and not request.env.user.has_group('website.group_website_designer'): if (self.visibility == 'connected' and request.website.is_public_user()): error = werkzeug.exceptions.Forbidden() elif self.visibility == 'password' and \ (request.website.is_public_user() or self.id not in request.session.get('views_unlock', [])): pwd = request.params.get('visibility_password') if pwd and self.env.user._crypt_context().verify( pwd, self.sudo().visibility_password): request.session.setdefault('views_unlock', list()).append(self.id) else: error = werkzeug.exceptions.Forbidden('website_visibility_password_required') if self.visibility not in ('password', 'connected'): try: self._check_view_access() except AccessError: error = werkzeug.exceptions.Forbidden() if error: if do_raise: raise error else: return False return True def _render(self, values=None, engine='ir.qweb', minimal_qcontext=False): """ Render the template. If website is enabled on request, then extend rendering context with website values. """ self._handle_visibility(do_raise=True) new_context = dict(self._context) if request and getattr(request, 'is_frontend', False): editable = request.website.is_publisher() translatable = editable and self._context.get('lang') != request.website.default_lang_id.code editable = not translatable and editable # in edit mode ir.ui.view will tag nodes if not translatable and not self.env.context.get('rendering_bundle'): if editable: new_context.setdefault("inherit_branding", True) elif request.env.user.has_group('website.group_website_publisher'): new_context.setdefault("inherit_branding_auto", True) if values and 'main_object' in values: if request.env.user.has_group('website.group_website_publisher'): func = getattr(values['main_object'], 'get_backend_menu_id', False) values['backend_menu_id'] = func and func() or self.env['ir.model.data']._xmlid_to_res_id('website.menu_website_configuration') if self._context != new_context: self = self.with_context(new_context) return super(View, self)._render(values, engine=engine, minimal_qcontext=minimal_qcontext) @api.model def _prepare_qcontext(self): """ Returns the qcontext : rendering context with website specific value (required to render website layout template) """ qcontext = super(View, self)._prepare_qcontext() if request and getattr(request, 'is_frontend', False): Website = self.env['website'] editable = request.website.is_publisher() translatable = editable and self._context.get('lang') != request.env['ir.http']._get_default_lang().code editable = not translatable and editable cur = Website.get_current_website() if self.env.user.has_group('website.group_website_publisher') and self.env.user.has_group('website.group_multi_website'): qcontext['multi_website_websites_current'] = {'website_id': cur.id, 'name': cur.name, 'domain': cur._get_http_domain()} qcontext['multi_website_websites'] = [ {'website_id': website.id, 'name': website.name, 'domain': website._get_http_domain()} for website in Website.search([]) if website != cur ] cur_company = self.env.company qcontext['multi_website_companies_current'] = {'company_id': cur_company.id, 'name': cur_company.name} qcontext['multi_website_companies'] = [ {'company_id': comp.id, 'name': comp.name} for comp in self.env.user.company_ids if comp != cur_company ] qcontext.update(dict( main_object=self, website=request.website, is_view_active=request.website.is_view_active, res_company=request.env['res.company'].browse(request.website._get_cached('company_id')).sudo(), translatable=translatable, editable=editable, )) return qcontext @api.model def get_default_lang_code(self): website_id = self.env.context.get('website_id') if website_id: lang_code = self.env['website'].browse(website_id).default_lang_id.code return lang_code else: return super(View, self).get_default_lang_code() def redirect_to_page_manager(self): return { 'type': 'ir.actions.act_url', 'url': '/website/pages', 'target': 'self', } def _read_template_keys(self): return super(View, self)._read_template_keys() + ['website_id'] @api.model def _save_oe_structure_hook(self): res = super(View, self)._save_oe_structure_hook() res['website_id'] = self.env['website'].get_current_website().id return res @api.model def _set_noupdate(self): '''If website is installed, any call to `save` from the frontend will actually write on the specific view (or create it if not exist yet). In that case, we don't want to flag the generic view as noupdate. ''' if not self._context.get('website_id'): super(View, self)._set_noupdate() def save(self, value, xpath=None): self.ensure_one() current_website = self.env['website'].get_current_website() # xpath condition is important to be sure we are editing a view and not # a field as in that case `self` might not exist (check commit message) if xpath and self.key and current_website: # The first time a generic view is edited, if multiple editable parts # were edited at the same time, multiple call to this method will be # done but the first one may create a website specific view. So if there # already is a website specific view, we need to divert the super to it. website_specific_view = self.env['ir.ui.view'].search([ ('key', '=', self.key), ('website_id', '=', current_website.id) ], limit=1) if website_specific_view: self = website_specific_view super(View, self).save(value, xpath=xpath) @api.model def _get_allowed_root_attrs(self): # Related to these options: # background-video, background-shapes, parallax return super()._get_allowed_root_attrs() + [ 'data-bg-video-src', 'data-shape', 'data-scroll-background-ratio', ] # -------------------------------------------------------------------------- # Snippet saving # -------------------------------------------------------------------------- @api.model def _snippet_save_view_values_hook(self): res = super()._snippet_save_view_values_hook() website_id = self.env.context.get('website_id') if website_id: res['website_id'] = website_id return res
48.473492
26,515
3,864
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 IrAsset(models.Model): _inherit = 'ir.asset' key = fields.Char(copy=False, help='Technical field used to resolve multiple assets in a multi-website environment.') website_id = fields.Many2one('website', ondelete='cascade') def _get_related_assets(self, domain): website = self.env['website'].get_current_website(fallback=False) if website: domain += website.website_domain() assets = super()._get_related_assets(domain) return assets.filter_duplicate() def _get_active_addons_list(self): """Overridden to discard inactive themes.""" addons_list = super()._get_active_addons_list() website = self.env['website'].get_current_website(fallback=False) if not website: return addons_list IrModule = self.env['ir.module.module'].sudo() # discard all theme modules except website.theme_id themes = IrModule.search(IrModule.get_themes_domain()) - website.theme_id to_remove = set(themes.mapped('name')) return [name for name in addons_list if name not in to_remove] def filter_duplicate(self): """ Filter current recordset only keeping the most suitable asset per distinct name. Every non-accessible asset will be removed from the set: * In non website context, every asset with a website will be removed * In a website context, every asset from another website """ current_website = self.env['website'].get_current_website(fallback=False) if not current_website: return self.filtered(lambda asset: not asset.website_id) most_specific_assets = self.env['ir.asset'] for asset in self: if asset.website_id == current_website: # specific asset: add it if it's for the current website and ignore # it if it's for another website most_specific_assets += asset elif not asset.website_id: # no key: added either way if not asset.key: most_specific_assets += asset # generic asset: add it iff for the current website, there is no # specific asset for this asset (based on the same `key` attribute) elif not any(asset.key == asset2.key and asset2.website_id == current_website for asset2 in self): most_specific_assets += asset return most_specific_assets def write(self, vals): """COW for ir.asset. This way editing websites does not impact other websites. Also this way newly created websites will only contain the default assets. """ current_website_id = self.env.context.get('website_id') if not current_website_id or self.env.context.get('no_cow'): return super().write(vals) for asset in self.with_context(active_test=False): # No need of COW if the asset is already specific if asset.website_id: super(IrAsset, asset).write(vals) continue # If already a specific asset for this generic asset, write on it website_specific_asset = asset.search([ ('key', '=', asset.key), ('website_id', '=', current_website_id) ], limit=1) if website_specific_asset: super(IrAsset, website_specific_asset).write(vals) continue copy_vals = {'website_id': current_website_id, 'key': asset.key} website_specific_asset = asset.copy(copy_vals) super(IrAsset, website_specific_asset).write(vals) return True
42.461538
3,864
1,732
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 Company(models.Model): _inherit = "res.company" website_id = fields.Many2one('website', compute='_compute_website_id', store=True) def _compute_website_id(self): for company in self: company.website_id = self.env['website'].search([('company_id', '=', company.id)], limit=1) @api.model def action_open_website_theme_selector(self): action = self.env["ir.actions.actions"]._for_xml_id("website.theme_install_kanban_action") action['target'] = 'new' return action def google_map_img(self, zoom=8, width=298, height=298): partner = self.sudo().partner_id return partner and partner.google_map_img(zoom, width, height) or None def google_map_link(self, zoom=8): partner = self.sudo().partner_id return partner and partner.google_map_link(zoom) or None def _get_public_user(self): self.ensure_one() # We need sudo to be able to see public users from others companies too public_users = self.env.ref('base.group_public').sudo().with_context(active_test=False).users public_users_for_website = public_users.filtered(lambda user: user.company_id == self) if public_users_for_website: return public_users_for_website[0] else: return self.env.ref('base.public_user').sudo().copy({ 'name': 'Public user for %s' % self.name, 'login': 'public-user@company-%s.com' % self.id, 'company_id': self.id, 'company_ids': [(6, 0, [self.id])], })
39.363636
1,732
9,400
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import re import requests from werkzeug.urls import url_parse from odoo import models class Assets(models.AbstractModel): _inherit = 'web_editor.assets' def make_scss_customization(self, url, values): """ Makes a scss customization of the given file. That file must contain a scss map including a line comment containing the word 'hook', to indicate the location where to write the new key,value pairs. Params: url (str): the URL of the scss file to customize (supposed to be a variable file which will appear in the assets_common bundle) values (dict): key,value mapping to integrate in the file's map (containing the word hook). If a key is already in the file's map, its value is overridden. """ IrAttachment = self.env['ir.attachment'] if 'color-palettes-name' in values: self.reset_asset('/website/static/src/scss/options/colors/user_color_palette.scss', 'web.assets_common') self.reset_asset('/website/static/src/scss/options/colors/user_gray_color_palette.scss', 'web.assets_common') # Do not reset all theme colors for compatibility (not removing alpha -> epsilon colors) self.make_scss_customization('/website/static/src/scss/options/colors/user_theme_color_palette.scss', { 'success': 'null', 'info': 'null', 'warning': 'null', 'danger': 'null', }) # Also reset gradients which are in the "website" values palette self.make_scss_customization('/website/static/src/scss/options/user_values.scss', { 'menu-gradient': 'null', 'header-boxed-gradient': 'null', 'footer-gradient': 'null', 'copyright-gradient': 'null', }) delete_attachment_id = values.pop('delete-font-attachment-id', None) if delete_attachment_id: delete_attachment_id = int(delete_attachment_id) IrAttachment.search([ '|', ('id', '=', delete_attachment_id), ('original_id', '=', delete_attachment_id), ('name', 'like', '%google-font%') ]).unlink() google_local_fonts = values.get('google-local-fonts') if google_local_fonts and google_local_fonts != 'null': # "('font_x': 45, 'font_y': '')" -> {'font_x': '45', 'font_y': ''} google_local_fonts = dict(re.findall(r"'([^']+)': '?(\d*)", google_local_fonts)) # Google is serving different font format (woff, woff2, ttf, eot..) # based on the user agent. We need to get the woff2 as this is # supported by all the browers we support. headers_woff2 = { 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36', } for font_name in google_local_fonts: if google_local_fonts[font_name]: google_local_fonts[font_name] = int(google_local_fonts[font_name]) else: font_family_attachments = IrAttachment font_content = requests.get( f'https://fonts.googleapis.com/css?family={font_name}&display=swap', timeout=5, headers=headers_woff2, ).content.decode() def fetch_google_font(src): statement = src.group() url, font_format = re.match(r'src: url\(([^\)]+)\) (.+)', statement).groups() req = requests.get(url, timeout=5, headers=headers_woff2) # https://fonts.gstatic.com/s/modak/v18/EJRYQgs1XtIEskMB-hRp7w.woff2 # -> s-modak-v18-EJRYQgs1XtIEskMB-hRp7w.woff2 name = url_parse(url).path.lstrip('/').replace('/', '-') attachment = IrAttachment.create({ 'name': f'google-font-{name}', 'type': 'binary', 'datas': base64.b64encode(req.content), 'public': True, }) nonlocal font_family_attachments font_family_attachments += attachment return 'src: url(/web/content/%s/%s) %s' % ( attachment.id, name, font_format, ) font_content = re.sub(r'src: url\(.+\)', fetch_google_font, font_content) attach_font = IrAttachment.create({ 'name': f'{font_name} (google-font)', 'type': 'binary', 'datas': base64.encodebytes(font_content.encode()), 'mimetype': 'text/css', 'public': True, }) google_local_fonts[font_name] = attach_font.id # That field is meant to keep track of the original # image attachment when an image is being modified (by the # website builder for instance). It makes sense to use it # here to link font family attachment to the main font # attachment. It will ease the unlink later. font_family_attachments.original_id = attach_font.id # {'font_x': 45, 'font_y': 55} -> "('font_x': 45, 'font_y': 55)" values['google-local-fonts'] = str(google_local_fonts).replace('{', '(').replace('}', ')') custom_url = self.make_custom_asset_file_url(url, 'web.assets_common') updatedFileContent = self.get_asset_content(custom_url) or self.get_asset_content(url) updatedFileContent = updatedFileContent.decode('utf-8') for name, value in values.items(): # Protect variable names so they cannot be computed as numbers # on SCSS compilation (e.g. var(--700) => var(700)). if isinstance(value, str): value = re.sub( r"var\(--([0-9]+)\)", lambda matchobj: "var(--#{" + matchobj.group(1) + "})", value) pattern = "'%s': %%s,\n" % name regex = re.compile(pattern % ".+") replacement = pattern % value if regex.search(updatedFileContent): updatedFileContent = re.sub(regex, replacement, updatedFileContent) else: updatedFileContent = re.sub(r'( *)(.*hook.*)', r'\1%s\1\2' % replacement, updatedFileContent) # Bundle is 'assets_common' as this route is only meant to update # variables scss files self.save_asset(url, 'web.assets_common', updatedFileContent, 'scss') def _get_custom_attachment(self, custom_url, op='='): """ See web_editor.Assets._get_custom_attachment Extend to only return the attachments related to the current website. """ if self.env.user.has_group('website.group_website_designer'): self = self.sudo() website = self.env['website'].get_current_website() res = super(Assets, self)._get_custom_attachment(custom_url, op=op) # FIXME (?) In website, those attachments should always have been # created with a website_id. The "not website_id" part in the following # condition might therefore be useless (especially since the attachments # do not seem ordered). It was developed in the spirit of served # attachments which follow this rule of "serve what belongs to the # current website or all the websites" but it probably does not make # sense here. It however allowed to discover a bug where attachments # were left without website_id. This will be kept untouched in stable # but will be reviewed and made more robust in master. return res.with_context(website_id=website.id).filtered(lambda x: not x.website_id or x.website_id == website) def _get_custom_asset(self, custom_url): """ See web_editor.Assets._get_custom_asset Extend to only return the views related to the current website. """ if self.env.user.has_group('website.group_website_designer'): # TODO: Remove me in master, see commit message, ACL added right to # unlink to designer but not working without -u in stable self = self.sudo() website = self.env['website'].get_current_website() res = super(Assets, self)._get_custom_asset(custom_url) return res.with_context(website_id=website.id).filter_duplicate() def _save_asset_hook(self): """ See web_editor.Assets._save_asset_hook Extend to add website ID at attachment creation. """ res = super(Assets, self)._save_asset_hook() website = self.env['website'].get_current_website() if website: res['website_id'] = website.id return res
50.26738
9,400
3,622
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from collections import OrderedDict from odoo import models from odoo.http import request from odoo.addons.base.models.assetsbundle import AssetsBundle from odoo.addons.http_routing.models.ir_http import url_for from odoo.osv import expression from odoo.addons.website.models import ir_http from odoo.tools import html_escape as escape re_background_image = re.compile(r"(background-image\s*:\s*url\(\s*['\"]?\s*)([^)'\"]+)") class AssetsBundleMultiWebsite(AssetsBundle): def _get_asset_url_values(self, id, unique, extra, name, sep, extension): website_id = self.env.context.get('website_id') website_id_path = website_id and ('%s/' % website_id) or '' extra = website_id_path + extra res = super(AssetsBundleMultiWebsite, self)._get_asset_url_values(id, unique, extra, name, sep, extension) return res def _get_assets_domain_for_already_processed_css(self, assets): res = super(AssetsBundleMultiWebsite, self)._get_assets_domain_for_already_processed_css(assets) current_website = self.env['website'].get_current_website(fallback=False) res = expression.AND([res, current_website.website_domain()]) return res def get_debug_asset_url(self, extra='', name='%', extension='%'): website_id = self.env.context.get('website_id') website_id_path = website_id and ('%s/' % website_id) or '' extra = website_id_path + extra return super(AssetsBundleMultiWebsite, self).get_debug_asset_url(extra, name, extension) class QWeb(models.AbstractModel): """ QWeb object for rendering stuff in the website context """ _inherit = 'ir.qweb' URL_ATTRS = { 'form': 'action', 'a': 'href', 'link': 'href', 'script': 'src', 'img': 'src', } def get_asset_bundle(self, xmlid, files, env=None, css=True, js=True): return AssetsBundleMultiWebsite(xmlid, files, env=env) def _post_processing_att(self, tagName, atts, options): if atts.get('data-no-post-process'): return atts atts = super(QWeb, self)._post_processing_att(tagName, atts, options) if tagName == 'img' and 'loading' not in atts: atts['loading'] = 'lazy' # default is auto if options.get('inherit_branding') or options.get('rendering_bundle') or \ options.get('edit_translations') or options.get('debug') or (request and request.session.debug): return atts website = ir_http.get_request_website() if not website and options.get('website_id'): website = self.env['website'].browse(options['website_id']) if not website: return atts name = self.URL_ATTRS.get(tagName) if request and name and name in atts: atts[name] = url_for(atts[name]) if not website.cdn_activated: return atts data_name = f'data-{name}' if name and (name in atts or data_name in atts): atts = OrderedDict(atts) if name in atts: atts[name] = website.get_cdn_url(atts[name]) if data_name in atts: atts[data_name] = website.get_cdn_url(atts[data_name]) if isinstance(atts.get('style'), str) and 'background-image' in atts['style']: atts = OrderedDict(atts) atts['style'] = re_background_image.sub(lambda m: '%s%s' % (m.group(1), website.get_cdn_url(m.group(2))), atts['style']) return atts
39.802198
3,622
5,475
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re import werkzeug from odoo import models, fields, api, _ from odoo.exceptions import AccessDenied, ValidationError import logging _logger = logging.getLogger(__name__) class WebsiteRoute(models.Model): _rec_name = 'path' _name = 'website.route' _description = "All Website Route" _order = 'path' path = fields.Char('Route') @api.model def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None): res = super(WebsiteRoute, self)._name_search(name=name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid) if not len(res): self._refresh() return super(WebsiteRoute, self)._name_search(name=name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid) return res def _refresh(self): _logger.debug("Refreshing website.route") ir_http = self.env['ir.http'] tocreate = [] paths = {rec.path: rec for rec in self.search([])} for url, _, routing in ir_http._generate_routing_rules(self.pool._init_modules, converters=ir_http._get_converters()): if 'GET' in (routing.get('methods') or ['GET']): if paths.get(url): paths.pop(url) else: tocreate.append({'path': url}) if tocreate: _logger.info("Add %d website.route" % len(tocreate)) self.create(tocreate) if paths: find = self.search([('path', 'in', list(paths.keys()))]) _logger.info("Delete %d website.route" % len(find)) find.unlink() class WebsiteRewrite(models.Model): _name = 'website.rewrite' _description = "Website rewrite" name = fields.Char('Name', required=True) website_id = fields.Many2one('website', string="Website", ondelete='cascade', index=True) active = fields.Boolean(default=True) url_from = fields.Char('URL from', index=True) route_id = fields.Many2one('website.route') url_to = fields.Char("URL to") redirect_type = fields.Selection([ ('404', '404 Not Found'), ('301', '301 Moved permanently'), ('302', '302 Moved temporarily'), ('308', '308 Redirect / Rewrite'), ], string='Action', default="302", help='''Type of redirect/Rewrite:\n 301 Moved permanently: The browser will keep in cache the new url. 302 Moved temporarily: The browser will not keep in cache the new url and ask again the next time the new url. 404 Not Found: If you want remove a specific page/controller (e.g. Ecommerce is installed, but you don't want /shop on a specific website) 308 Redirect / Rewrite: If you want rename a controller with a new url. (Eg: /shop -> /garden - Both url will be accessible but /shop will automatically be redirected to /garden) ''') sequence = fields.Integer() @api.onchange('route_id') def _onchange_route_id(self): self.url_from = self.route_id.path self.url_to = self.route_id.path @api.constrains('url_to', 'url_from', 'redirect_type') def _check_url_to(self): for rewrite in self: if rewrite.redirect_type in ['301', '302', '308']: if not rewrite.url_to: raise ValidationError(_('"URL to" can not be empty.')) elif not rewrite.url_to.startswith('/'): raise ValidationError(_('"URL to" must start with a leading slash.')) if not rewrite.url_from: raise ValidationError(_('"URL from" can not be empty.')) for param in re.findall('/<.*?>', rewrite.url_from): if param not in rewrite.url_to: raise ValidationError(_('"URL to" must contain parameter %s used in "URL from".') % param) for param in re.findall('/<.*?>', rewrite.url_to): if param not in rewrite.url_from: raise ValidationError(_('"URL to" cannot contain parameter %s which is not used in "URL from".') % param) try: converters = self.env['ir.http']._get_converters() routing_map = werkzeug.routing.Map(strict_slashes=False, converters=converters) rule = werkzeug.routing.Rule(rewrite.url_to) routing_map.add(rule) except ValueError as e: raise ValidationError(_('"URL to" is invalid: %s') % e) def name_get(self): result = [] for rewrite in self: name = "%s - %s" % (rewrite.redirect_type, rewrite.name) result.append((rewrite.id, name)) return result @api.model def create(self, vals): res = super(WebsiteRewrite, self).create(vals) self._invalidate_routing() return res def write(self, vals): res = super(WebsiteRewrite, self).write(vals) self._invalidate_routing() return res def unlink(self): res = super(WebsiteRewrite, self).unlink() self._invalidate_routing() return res def _invalidate_routing(self): # call clear_caches on this worker to reload routing table self.env['ir.http'].clear_caches() def refresh_routes(self): self.env['website.route']._refresh()
40.858209
5,475
12,047
py
PYTHON
15.0
# -*- coding: utf-8 -*- from ast import literal_eval from collections import OrderedDict from odoo import models, fields, api, _ from odoo.exceptions import ValidationError, MissingError from odoo.osv import expression from lxml import etree, html import logging from random import randint _logger = logging.getLogger(__name__) class WebsiteSnippetFilter(models.Model): _name = 'website.snippet.filter' _inherit = ['website.published.multi.mixin'] _description = 'Website Snippet Filter' _order = 'name ASC' name = fields.Char(required=True, translate=True) action_server_id = fields.Many2one('ir.actions.server', 'Server Action', ondelete='cascade') field_names = fields.Char(help="A list of comma-separated field names", required=True) filter_id = fields.Many2one('ir.filters', 'Filter', ondelete='cascade') limit = fields.Integer(help='The limit is the maximum number of records retrieved', required=True) website_id = fields.Many2one('website', string='Website', ondelete='cascade') model_name = fields.Char(string='Model name', compute='_compute_model_name') @api.depends('filter_id', 'action_server_id') def _compute_model_name(self): for snippet_filter in self: if snippet_filter.filter_id: snippet_filter.model_name = snippet_filter.filter_id.model_id else: # self.action_server_id snippet_filter.model_name = snippet_filter.action_server_id.model_id.model @api.constrains('action_server_id', 'filter_id') def _check_data_source_is_provided(self): for record in self: if bool(record.action_server_id) == bool(record.filter_id): raise ValidationError(_("Either action_server_id or filter_id must be provided.")) @api.constrains('limit') def _check_limit(self): """Limit must be between 1 and 16.""" for record in self: if not 0 < record.limit <= 16: raise ValidationError(_("The limit must be between 1 and 16.")) @api.constrains('field_names') def _check_field_names(self): for record in self: for field_name in record.field_names.split(","): if not field_name.strip(): raise ValidationError(_("Empty field name in %r") % (record.field_names)) def _render(self, template_key, limit, search_domain=None, with_sample=False): """Renders the website dynamic snippet items""" self.ensure_one() assert '.dynamic_filter_template_' in template_key, _("You can only use template prefixed by dynamic_filter_template_ ") if search_domain is None: search_domain = [] if self.website_id and self.env['website'].get_current_website() != self.website_id: return '' if self.model_name.replace('.', '_') not in template_key: return '' records = self._prepare_values(limit, search_domain) is_sample = with_sample and not records if is_sample: records = self._prepare_sample(limit) View = self.env['ir.ui.view'].sudo().with_context(inherit_branding=False) content = View._render_template(template_key, dict( records=records, is_sample=is_sample, )) return [etree.tostring(el, encoding='unicode') for el in html.fromstring('<root>%s</root>' % str(content)).getchildren()] def _prepare_values(self, limit=None, search_domain=None): """Gets the data and returns it the right format for render.""" self.ensure_one() # TODO adapt in master: the "limit" field is there to prevent loading # an arbitrary number of records asked by the client side. It was # however set to 6 for a blog post filter, probably thinking it was a # default limit and not a max limit. That means that configuring a # higher limit via the editor (which allows up to 16) was not working. # As a stable fix, this was made to bypass the max limit if it is under # 16, and only for newly configured snippets. max_limit = max(self.limit, 16) if self.env.context.get('_bugfix_force_minimum_max_limit_to_16') else self.limit limit = limit and min(limit, max_limit) or max_limit if self.filter_id: filter_sudo = self.filter_id.sudo() domain = filter_sudo._get_eval_domain() if 'website_id' in self.env[filter_sudo.model_id]: domain = expression.AND([domain, self.env['website'].get_current_website().website_domain()]) if 'company_id' in self.env[filter_sudo.model_id]: website = self.env['website'].get_current_website() domain = expression.AND([domain, [('company_id', 'in', [False, website.company_id.id])]]) if 'is_published' in self.env[filter_sudo.model_id]: domain = expression.AND([domain, [('is_published', '=', True)]]) if search_domain: domain = expression.AND([domain, search_domain]) try: records = self.env[filter_sudo.model_id].with_context(**literal_eval(filter_sudo.context)).search( domain, order=','.join(literal_eval(filter_sudo.sort)) or None, limit=limit ) return self._filter_records_to_values(records) except MissingError: _logger.warning("The provided domain %s in 'ir.filters' generated a MissingError in '%s'", domain, self._name) return [] elif self.action_server_id: try: return self.action_server_id.with_context( dynamic_filter=self, limit=limit, search_domain=search_domain, ).sudo().run() or [] except MissingError: _logger.warning("The provided domain %s in 'ir.actions.server' generated a MissingError in '%s'", search_domain, self._name) return [] def _get_field_name_and_type(self, model, field_name): """ Separates the name and the widget type @param model: Model to which the field belongs, without it type is deduced from field_name @param field_name: Name of the field possibly followed by a colon and a forced field type @return Tuple containing the field name and the field type """ field_name, _, field_widget = field_name.partition(":") if not field_widget: field = model._fields.get(field_name) if field: field_type = field.type elif 'image' in field_name: field_type = 'image' elif 'price' in field_name: field_type = 'monetary' else: field_type = 'text' return field_name, field_widget or field_type def _get_filter_meta_data(self): """ Extracts the meta data of each field @return OrderedDict containing the widget type for each field name """ model = self.env[self.model_name] meta_data = OrderedDict({}) for field_name in self.field_names.split(","): field_name, field_widget = self._get_field_name_and_type(model, field_name) meta_data[field_name] = field_widget return meta_data def _prepare_sample(self, length=6): """ Generates sample data and returns it the right format for render. @param length: Number of sample records to generate @return Array of objets with a value associated to each name in field_names """ if not length: return [] records = self._prepare_sample_records(length) return self._filter_records_to_values(records, is_sample=True) def _prepare_sample_records(self, length): """ Generates sample records. @param length: Number of sample records to generate @return List of of sample records """ if not length: return [] sample = [] model = self.env[self.model_name] sample_data = self._get_hardcoded_sample(model) if sample_data: for index in range(0, length): single_sample_data = sample_data[index % len(sample_data)].copy() self._fill_sample(single_sample_data, index) sample.append(model.new(single_sample_data)) return sample def _fill_sample(self, sample, index): """ Fills the missing fields of a sample @param sample: Data structure to fill with values for each name in field_names @param index: Index of the sample within the dataset """ meta_data = self._get_filter_meta_data() model = self.env[self.model_name] for field_name, field_widget in meta_data.items(): if field_name not in sample and field_name in model: if field_widget in ('image', 'binary'): sample[field_name] = None elif field_widget == 'monetary': sample[field_name] = randint(100, 10000) / 10.0 elif field_widget in ('integer', 'float'): sample[field_name] = index else: sample[field_name] = _('Sample %s', index + 1) return sample def _get_hardcoded_sample(self, model): """ Returns a hard-coded sample @param model: Model of the currently rendered view @return Sample data records with field values """ return [{}] def _filter_records_to_values(self, records, is_sample=False): """ Extract the fields from the data source 'records' and put them into a dictionary of values @param records: Model records returned by the filter @param is_sample: True if conversion if for sample records @return List of dict associating the field value to each field name """ self.ensure_one() meta_data = self._get_filter_meta_data() values = [] model = self.env[self.model_name] Website = self.env['website'] for record in records: data = {} for field_name, field_widget in meta_data.items(): field = model._fields.get(field_name) if field and field.type in ('binary', 'image'): if is_sample: data[field_name] = record[field_name].decode('utf8') if field_name in record else '/web/image' else: data[field_name] = Website.image_url(record, field_name) elif field_widget == 'monetary': model_currency = None if field and field.type == 'monetary': model_currency = record[field.get_currency_field(record)] elif 'currency_id' in model._fields: model_currency = record['currency_id'] if model_currency: website_currency = self._get_website_currency() data[field_name] = model_currency._convert( record[field_name], website_currency, Website.get_current_website().company_id, fields.Date.today() ) else: data[field_name] = record[field_name] else: data[field_name] = record[field_name] data['call_to_action_url'] = 'website_url' in record and record['website_url'] data['_record'] = record values.append(data) return values @api.model def _get_website_currency(self): company = self.env['website'].get_current_website().company_id return company.currency_id
43.179211
12,047
14,674
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 from odoo.tools.translate import xml_translate from odoo.modules.module import get_resource_from_path from odoo.addons.base.models.ir_asset import AFTER_DIRECTIVE, APPEND_DIRECTIVE, BEFORE_DIRECTIVE, DEFAULT_SEQUENCE, INCLUDE_DIRECTIVE, PREPEND_DIRECTIVE, REMOVE_DIRECTIVE, REPLACE_DIRECTIVE _logger = logging.getLogger(__name__) class ThemeAsset(models.Model): _name = 'theme.ir.asset' _description = 'Theme Asset' key = fields.Char() name = fields.Char(required=True) bundle = fields.Char(required=True) directive = fields.Selection(selection=[ (APPEND_DIRECTIVE, 'Append'), (PREPEND_DIRECTIVE, 'Prepend'), (AFTER_DIRECTIVE, 'After'), (BEFORE_DIRECTIVE, 'Before'), (REMOVE_DIRECTIVE, 'Remove'), (REPLACE_DIRECTIVE, 'Replace'), (INCLUDE_DIRECTIVE, 'Include')], default=APPEND_DIRECTIVE) path = fields.Char(required=True) target = fields.Char() active = fields.Boolean(default=True) sequence = fields.Integer(default=DEFAULT_SEQUENCE, required=True) copy_ids = fields.One2many('ir.asset', 'theme_template_id', 'Assets using a copy of me', copy=False, readonly=True) def _convert_to_base_model(self, website, **kwargs): self.ensure_one() new_asset = { 'name': self.name, 'key': self.key, 'bundle': self.bundle, 'directive': self.directive, 'path': self.path, 'target': self.target, 'active': self.active, 'sequence': self.sequence, 'website_id': website.id, 'theme_template_id': self.id, } return new_asset class ThemeView(models.Model): _name = 'theme.ir.ui.view' _description = 'Theme UI View' def compute_arch_fs(self): if 'install_filename' not in self._context: return '' path_info = get_resource_from_path(self._context['install_filename']) if path_info: return '/'.join(path_info[0:2]) name = fields.Char(required=True) key = fields.Char() type = fields.Char() priority = fields.Integer(default=DEFAULT_SEQUENCE, required=True) mode = fields.Selection([('primary', "Base view"), ('extension', "Extension View")]) active = fields.Boolean(default=True) arch = fields.Text(translate=xml_translate) arch_fs = fields.Char(default=compute_arch_fs) inherit_id = fields.Reference(selection=[('ir.ui.view', 'ir.ui.view'), ('theme.ir.ui.view', 'theme.ir.ui.view')]) copy_ids = fields.One2many('ir.ui.view', 'theme_template_id', 'Views using a copy of me', copy=False, readonly=True) customize_show = fields.Boolean() def _convert_to_base_model(self, website, **kwargs): self.ensure_one() inherit = self.inherit_id if self.inherit_id and self.inherit_id._name == 'theme.ir.ui.view': inherit = self.inherit_id.with_context(active_test=False).copy_ids.filtered(lambda x: x.website_id == website) if not inherit: # inherit_id not yet created, add to the queue return False if inherit and inherit.website_id != website: website_specific_inherit = self.env['ir.ui.view'].with_context(active_test=False).search([ ('key', '=', inherit.key), ('website_id', '=', website.id) ], limit=1) if website_specific_inherit: inherit = website_specific_inherit new_view = { 'type': self.type or 'qweb', 'name': self.name, 'arch': self.arch, 'key': self.key, 'inherit_id': inherit and inherit.id, 'arch_fs': self.arch_fs, 'priority': self.priority, 'active': self.active, 'theme_template_id': self.id, 'website_id': website.id, 'customize_show': self.customize_show, } if self.mode: # if not provided, it will be computed automatically (if inherit_id or not) new_view['mode'] = self.mode return new_view class ThemeAttachment(models.Model): _name = 'theme.ir.attachment' _description = 'Theme Attachments' name = fields.Char(required=True) key = fields.Char(required=True) url = fields.Char() copy_ids = fields.One2many('ir.attachment', 'theme_template_id', 'Attachment using a copy of me', copy=False, readonly=True) def _convert_to_base_model(self, website, **kwargs): self.ensure_one() new_attach = { 'key': self.key, 'public': True, 'res_model': 'ir.ui.view', 'type': 'url', 'name': self.name, 'url': self.url, 'website_id': website.id, 'theme_template_id': self.id, } return new_attach class ThemeMenu(models.Model): _name = 'theme.website.menu' _description = 'Website Theme Menu' name = fields.Char(required=True, translate=True) url = fields.Char(default='') page_id = fields.Many2one('theme.website.page', ondelete='cascade') new_window = fields.Boolean('New Window') sequence = fields.Integer() parent_id = fields.Many2one('theme.website.menu', index=True, ondelete="cascade") copy_ids = fields.One2many('website.menu', 'theme_template_id', 'Menu using a copy of me', copy=False, readonly=True) def _convert_to_base_model(self, website, **kwargs): self.ensure_one() page_id = self.page_id.copy_ids.filtered(lambda x: x.website_id == website) parent_id = self.parent_id.copy_ids.filtered(lambda x: x.website_id == website) new_menu = { 'name': self.name, 'url': self.url, 'page_id': page_id and page_id.id or False, 'new_window': self.new_window, 'sequence': self.sequence, 'parent_id': parent_id and parent_id.id or False, 'website_id': website.id, 'theme_template_id': self.id, } return new_menu class ThemePage(models.Model): _name = 'theme.website.page' _description = 'Website Theme Page' url = fields.Char() view_id = fields.Many2one('theme.ir.ui.view', required=True, ondelete="cascade") website_indexed = fields.Boolean('Page Indexed', default=True) copy_ids = fields.One2many('website.page', 'theme_template_id', 'Page using a copy of me', copy=False, readonly=True) def _convert_to_base_model(self, website, **kwargs): self.ensure_one() view_id = self.view_id.copy_ids.filtered(lambda x: x.website_id == website) if not view_id: # inherit_id not yet created, add to the queue return False new_page = { 'url': self.url, 'view_id': view_id.id, 'website_indexed': self.website_indexed, 'website_id': website.id, 'theme_template_id': self.id, } return new_page class Theme(models.AbstractModel): _name = 'theme.utils' _description = 'Theme Utils' _auto = False _header_templates = [ 'website.template_header_hamburger', 'website.template_header_vertical', 'website.template_header_sidebar', 'website.template_header_slogan', 'website.template_header_contact', 'website.template_header_boxed', 'website.template_header_centered_logo', 'website.template_header_image', 'website.template_header_hamburger_full', 'website.template_header_magazine', # Default one, keep it last 'website.template_header_default', ] _footer_templates = [ 'website.template_footer_descriptive', 'website.template_footer_centered', 'website.template_footer_links', 'website.template_footer_minimalist', 'website.template_footer_contact', 'website.template_footer_call_to_action', 'website.template_footer_headline', # Default one, keep it last 'website.footer_custom', ] def _post_copy(self, mod): # Call specific theme post copy theme_post_copy = '_%s_post_copy' % mod.name if hasattr(self, theme_post_copy): _logger.info('Executing method %s' % theme_post_copy) method = getattr(self, theme_post_copy) return method(mod) return False @api.model def _reset_default_config(self): # Reinitialize some css customizations self.env['web_editor.assets'].make_scss_customization( '/website/static/src/scss/options/user_values.scss', { 'font': 'null', 'headings-font': 'null', 'navbar-font': 'null', 'buttons-font': 'null', 'color-palettes-number': 'null', 'color-palettes-name': 'null', 'btn-ripple': 'null', 'header-template': 'null', 'footer-template': 'null', 'footer-scrolltop': 'null', } ) # Reinitialize effets self.disable_asset('Ripple effect SCSS') self.disable_asset('Ripple effect JS') # Reinitialize header templates for view in self._header_templates[:-1]: self.disable_view(view) self.enable_view(self._header_templates[-1]) # Reinitialize footer templates for view in self._footer_templates[:-1]: self.disable_view(view) self.enable_view(self._footer_templates[-1]) # Reinitialize footer scrolltop template self.disable_view('website.option_footer_scrolltop') # TODO Rename name in key and search with the key in master @api.model def _toggle_asset(self, name, active): ThemeAsset = self.env['theme.ir.asset'].sudo().with_context(active_test=False) obj = ThemeAsset.search([('name', '=', name)]) website = self.env['website'].get_current_website() if obj: obj = obj.copy_ids.filtered(lambda x: x.website_id == website) else: Asset = self.env['ir.asset'].sudo().with_context(active_test=False) obj = Asset.search([('name', '=', name)], limit=1) has_specific = obj.key and Asset.search_count([ ('key', '=', obj.key), ('website_id', '=', website.id) ]) >= 1 if not has_specific and active == obj.active: return obj.write({'active': active}) @api.model def _toggle_view(self, xml_id, active): obj = self.env.ref(xml_id) website = self.env['website'].get_current_website() if obj._name == 'theme.ir.ui.view': obj = obj.with_context(active_test=False) obj = obj.copy_ids.filtered(lambda x: x.website_id == website) else: # If a theme post copy wants to enable/disable a view, this is to # enable/disable a given functionality which is disabled/enabled # by default. So if a post copy asks to enable/disable a view which # is already enabled/disabled, we would not consider it otherwise it # would COW the view for nothing. View = self.env['ir.ui.view'].with_context(active_test=False) has_specific = obj.key and View.search_count([ ('key', '=', obj.key), ('website_id', '=', website.id) ]) >= 1 if not has_specific and active == obj.active: return obj.write({'active': active}) @api.model def enable_asset(self, name): self._toggle_asset(name, True) @api.model def disable_asset(self, name): self._toggle_asset(name, False) @api.model def enable_view(self, xml_id): if xml_id in self._header_templates: for view in self._header_templates: self.disable_view(view) elif xml_id in self._footer_templates: for view in self._footer_templates: self.disable_view(view) self._toggle_view(xml_id, True) @api.model def disable_view(self, xml_id): self._toggle_view(xml_id, False) @api.model def enable_header_off_canvas(self): """ Enabling off canvas require to enable quite a lot of template so this shortcut was made to make it easier. """ self.enable_view("website.option_header_off_canvas") self.enable_view("website.option_header_off_canvas_template_header_hamburger") self.enable_view("website.option_header_off_canvas_template_header_sidebar") self.enable_view("website.option_header_off_canvas_template_header_hamburger_full") class IrUiView(models.Model): _inherit = 'ir.ui.view' theme_template_id = fields.Many2one('theme.ir.ui.view', copy=False) def write(self, vals): # During a theme module update, theme views' copies receiving an arch # update should not be considered as `arch_updated`, as this is not a # user made change. test_mode = getattr(threading.current_thread(), 'testing', False) if not (test_mode or self.pool._init): return super().write(vals) no_arch_updated_views = other_views = self.env['ir.ui.view'] for record in self: # Do not mark the view as user updated if original view arch is similar arch = vals.get('arch', vals.get('arch_base')) if record.theme_template_id and record.theme_template_id.arch == arch: no_arch_updated_views += record else: other_views += record res = super(IrUiView, other_views).write(vals) if no_arch_updated_views: vals['arch_updated'] = False res &= super(IrUiView, no_arch_updated_views).write(vals) return res class IrAsset(models.Model): _inherit = 'ir.asset' theme_template_id = fields.Many2one('theme.ir.asset', copy=False) class IrAttachment(models.Model): _inherit = 'ir.attachment' key = fields.Char(copy=False) theme_template_id = fields.Many2one('theme.ir.attachment', copy=False) class WebsiteMenu(models.Model): _inherit = 'website.menu' theme_template_id = fields.Many2one('theme.website.menu', copy=False) class WebsitePage(models.Model): _inherit = 'website.page' theme_template_id = fields.Many2one('theme.website.page', copy=False)
37.625641
14,674
4,594
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models, _, Command from odoo.exceptions import ValidationError from odoo.http import request _logger = logging.getLogger(__name__) class ResUsers(models.Model): _inherit = 'res.users' website_id = fields.Many2one('website', related='partner_id.website_id', store=True, related_sudo=False, readonly=False) _sql_constraints = [ # Partial constraint, complemented by a python constraint (see below). ('login_key', 'unique (login, website_id)', 'You can not have two users with the same login!'), ] @api.constrains('login', 'website_id') def _check_login(self): """ Do not allow two users with the same login without website """ self.flush(['login', 'website_id']) self.env.cr.execute( """SELECT login FROM res_users WHERE login IN (SELECT login FROM res_users WHERE id IN %s AND website_id IS NULL) AND website_id IS NULL GROUP BY login HAVING COUNT(*) > 1 """, (tuple(self.ids),) ) if self.env.cr.rowcount: raise ValidationError(_('You can not have two users with the same login!')) @api.model def _get_login_domain(self, login): website = self.env['website'].get_current_website() return super(ResUsers, self)._get_login_domain(login) + website.website_domain() @api.model def _get_login_order(self): return 'website_id, ' + super(ResUsers, self)._get_login_order() @api.model def _signup_create_user(self, values): current_website = self.env['website'].get_current_website() # Note that for the moment, portal users can connect to all websites of # all companies as long as the specific_user_account setting is not # activated. values['company_id'] = current_website.company_id.id values['company_ids'] = [Command.link(current_website.company_id.id)] if request and current_website.specific_user_account: values['website_id'] = current_website.id new_user = super(ResUsers, self)._signup_create_user(values) return new_user @api.model def _get_signup_invitation_scope(self): current_website = self.env['website'].get_current_website() return current_website.auth_signup_uninvited or super(ResUsers, self)._get_signup_invitation_scope() @classmethod def authenticate(cls, db, login, password, user_agent_env): """ Override to link the logged in user's res.partner to website.visitor. If both a request-based visitor and a user-based visitor exist we try to update them (have same partner_id), and move sub records to the main visitor (user one). Purpose is to try to keep a main visitor with as much sub-records (tracked pages, leads, ...) as possible. """ uid = super(ResUsers, cls).authenticate(db, login, password, user_agent_env) if uid: with cls.pool.cursor() as cr: env = api.Environment(cr, uid, {}) visitor_sudo = env['website.visitor']._get_visitor_from_request() if visitor_sudo: user_partner = env.user.partner_id other_user_visitor_sudo = env['website.visitor'].with_context(active_test=False).sudo().search( [('partner_id', '=', user_partner.id), ('id', '!=', visitor_sudo.id)], order='last_connection_datetime DESC', ) # current 13.3 state: 1 result max as unique visitor / partner if other_user_visitor_sudo: visitor_main = other_user_visitor_sudo[0] other_visitors = other_user_visitor_sudo[1:] # normally void (visitor_sudo + other_visitors)._link_to_visitor(visitor_main, keep_unique=True) visitor_main.name = user_partner.name visitor_main.active = True visitor_main._update_visitor_last_visit() else: if visitor_sudo.partner_id != user_partner: visitor_sudo._link_to_partner( user_partner, update_values={'partner_id': user_partner.id}) visitor_sudo._update_visitor_last_visit() return uid
47.360825
4,594