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
663
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 EventBoothCategory(models.Model): _name = 'event.booth.category' _description = 'Event Booth Category' _inherit = ['image.mixin'] _order = 'sequence ASC' active = fields.Boolean(default=True) name = fields.Char(string='Name', required=True, translate=True) sequence = fields.Integer(string='Sequence', default=10) description = fields.Html(string='Description', translate=True, sanitize_attributes=False) booth_ids = fields.One2many('event.booth', 'booth_category_id', string='Booths')
39
663
4,365
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models from odoo import Command class Event(models.Model): _inherit = 'event.event' event_booth_ids = fields.One2many( 'event.booth', 'event_id', string='Booths', copy=True, compute='_compute_event_booth_ids', readonly=False, store=True) event_booth_count = fields.Integer( string='Total Booths', compute='_compute_event_booth_count') event_booth_count_available = fields.Integer( string='Available Booths', compute='_compute_event_booth_count') event_booth_category_ids = fields.Many2many( 'event.booth.category', compute='_compute_event_booth_category_ids') event_booth_category_available_ids = fields.Many2many( 'event.booth.category', compute='_compute_event_booth_category_available_ids', help='Booth Category for which booths are still available. Used in frontend') @api.depends('event_type_id') def _compute_event_booth_ids(self): """ Update event configuration from its event type. Depends are set only on event_type_id itself, not its sub fields. Purpose is to emulate an onchange: if event type is changed, update event configuration. Changing event type content itself should not trigger this method. When synchronizing booths: * lines that are available are removed; * template lines are added; """ for event in self: if not event.event_type_id and not event.event_booth_ids: event.event_booth_ids = False continue # booths to keep: those that are not available booths_to_remove = event.event_booth_ids.filtered(lambda booth: booth.is_available) command = [Command.unlink(booth.id) for booth in booths_to_remove] if event.event_type_id.event_type_booth_ids: command += [ Command.create({ attribute_name: line[attribute_name] if not isinstance(line[attribute_name], models.BaseModel) else line[attribute_name].id for attribute_name in self.env['event.type.booth']._get_event_booth_fields_whitelist() }) for line in event.event_type_id.event_type_booth_ids ] event.event_booth_ids = command def _get_booth_stat_count(self): elements = self.env['event.booth'].sudo().read_group( [('event_id', 'in', self.ids)], ['event_id', 'state'], ['event_id', 'state'], lazy=False ) elements_total_count = dict() elements_available_count = dict() for element in elements: event_id = element['event_id'][0] if element['state'] == 'available': elements_available_count[event_id] = element['__count'] elements_total_count.setdefault(event_id, 0) elements_total_count[event_id] += element['__count'] return elements_available_count, elements_total_count @api.depends('event_booth_ids', 'event_booth_ids.state') def _compute_event_booth_count(self): if self.ids and all(bool(event.id) for event in self): # no new/onchange mode -> optimized booths_available_count, booths_total_count = self._get_booth_stat_count() for event in self: event.event_booth_count_available = booths_available_count.get(event.id, 0) event.event_booth_count = booths_total_count.get(event.id, 0) else: for event in self: event.event_booth_count = len(event.event_booth_ids) event.event_booth_count_available = len(event.event_booth_ids.filtered(lambda booth: booth.is_available)) @api.depends('event_booth_ids.booth_category_id') def _compute_event_booth_category_ids(self): for event in self: event.event_booth_category_ids = event.event_booth_ids.mapped('booth_category_id') @api.depends('event_booth_ids.is_available') def _compute_event_booth_category_available_ids(self): for event in self: event.event_booth_category_available_ids = event.event_booth_ids.filtered(lambda booth: booth.is_available).mapped('booth_category_id')
48.5
4,365
987
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 EventBooth(models.Model): _name = 'event.type.booth' _description = 'Event Booth Template' def _get_default_booth_category(self): """Assign booth category by default if only one exists""" category_id = self.env['event.booth.category'].search([]) if category_id and len(category_id) == 1: return category_id name = fields.Char(string='Name', required=True, translate=True) event_type_id = fields.Many2one( 'event.type', string='Event Category', ondelete='cascade', required=True) booth_category_id = fields.Many2one( 'event.booth.category', string='Booth Category', default=_get_default_booth_category, ondelete='restrict', required=True) @api.model def _get_event_booth_fields_whitelist(self): return ['name', 'booth_category_id']
36.555556
987
4,671
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models from odoo.osv import expression class EventBooth(models.Model): _name = 'event.booth' _description = 'Event Booth' _inherit = [ 'event.type.booth', 'mail.thread', 'mail.activity.mixin' ] # owner event_type_id = fields.Many2one(ondelete='set null', required=False) event_id = fields.Many2one('event.event', string='Event', ondelete='cascade', required=True) # customer partner_id = fields.Many2one('res.partner', string='Renter', tracking=True, copy=False) contact_name = fields.Char('Renter Name', compute='_compute_contact_name', readonly=False, store=True, copy=False) contact_email = fields.Char('Renter Email', compute='_compute_contact_email', readonly=False, store=True, copy=False) contact_mobile = fields.Char('Renter Mobile', compute='_compute_contact_mobile', readonly=False, store=True, copy=False) contact_phone = fields.Char('Renter Phone', compute='_compute_contact_phone', readonly=False, store=True, copy=False) # state state = fields.Selection( [('available', 'Available'), ('unavailable', 'Unavailable')], string='Status', group_expand='_group_expand_states', default='available', required=True, tracking=True, help='Shows the availability of a Booth') is_available = fields.Boolean(compute='_compute_is_available', search='_search_is_available') @api.depends('partner_id') def _compute_contact_name(self): for booth in self: if not booth.contact_name: booth.contact_name = booth.partner_id.name or False @api.depends('partner_id') def _compute_contact_email(self): for booth in self: if not booth.contact_email: booth.contact_email = booth.partner_id.email or False @api.depends('partner_id') def _compute_contact_mobile(self): for booth in self: if not booth.contact_mobile: booth.contact_mobile = booth.partner_id.mobile or False @api.depends('partner_id') def _compute_contact_phone(self): for booth in self: if not booth.contact_phone: booth.contact_phone = booth.partner_id.phone or False @api.depends('state') def _compute_is_available(self): for booth in self: booth.is_available = booth.state == 'available' def _search_is_available(self, operator, operand): negative = operator in expression.NEGATIVE_TERM_OPERATORS if (negative and operand) or not operand: return [('state', '=', 'unavailable')] return [('state', '=', 'available')] def _group_expand_states(self, states, domain, order): return [key for key, val in type(self).state.selection] @api.model_create_multi def create(self, vals_list): res = super(EventBooth, self.with_context(mail_create_nosubscribe=True)).create(vals_list) unavailable_booths = res.filtered(lambda booth: not booth.is_available) unavailable_booths._post_confirmation_message() return res def write(self, vals): to_confirm = self.filtered(lambda booth: booth.state == 'available') wpartner = {} if 'state' in vals or 'partner_id' in vals: wpartner = dict( (booth, booth.partner_id.ids) for booth in self.filtered(lambda booth: booth.partner_id) ) res = super(EventBooth, self).write(vals) if vals.get('state') == 'unavailable' or vals.get('partner_id'): for booth in self: booth.message_subscribe(booth.partner_id.ids) for booth in self: if wpartner.get(booth) and booth.partner_id.id not in wpartner[booth]: booth.message_unsubscribe(wpartner[booth]) if vals.get('state') == 'unavailable': to_confirm._action_post_confirm(vals) return res def _post_confirmation_message(self): for booth in self: booth.event_id.message_post_with_view( 'event_booth.event_booth_booked_template', values={ 'booth': booth, }, subtype_id=self.env.ref('event_booth.mt_event_booth_booked').id, ) def action_confirm(self, additional_values=None): write_vals = dict({'state': 'unavailable'}, **additional_values or {}) self.write(write_vals) def _action_post_confirm(self, write_vals): self._post_confirmation_message()
39.923077
4,671
816
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Italy - E-invoicing (SdiCoop)', 'version': '0.3', 'depends': [ 'l10n_it_edi', 'account_edi', 'account_edi_proxy_client', ], 'author': 'Odoo', 'description': """ E-invoice implementation for Italy with the web-service. Ability to send and receive document from SdiCoop. Files sent by SdiCoop are first stored on the proxy and then fetched by this module. """, 'category': 'Accounting/Localizations/EDI', 'website': 'http://www.odoo.com/', 'data': [ 'data/cron.xml', 'views/l10n_it_view.xml', 'views/res_config_settings_views.xml', ], 'post_init_hook': '_disable_pec_mail_post_init', 'license': 'LGPL-3', }
31.384615
816
10,636
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import namedtuple from lxml import etree from odoo import fields from odoo.tests import tagged from odoo.addons.l10n_it_edi_sdicoop.tests.test_edi_xml import TestItEdi @tagged('post_install_l10n', 'post_install', '-at_install') class TestItEdiReverseCharge(TestItEdi): @classmethod def setUpClass(cls): super().setUpClass() # Helper functions ----------- def get_tag_ids(tag_codes): """ Helper function to define tag ids for taxes """ return cls.env['account.account.tag'].search([ ('applicability', '=', 'taxes'), ('country_id.code', '=', 'IT'), ('name', 'in', tag_codes)]).ids RepartitionLine = namedtuple('Line', 'factor_percent repartition_type tag_ids') def repartition_lines(*lines): """ Helper function to define repartition lines in taxes """ return [(5, 0, 0)] + [(0, 0, {**line._asdict(), 'tag_ids': get_tag_ids(line[2])}) for line in lines] ProductLine = namedtuple('Line', 'data name product_id') def product_lines(*lines): """ Helper function to define move lines based on a product """ return [(0, 0, {**line[0], 'name': line[1], 'product_id': line[2]}) for line in lines] # Company ----------- cls.company.partner_id.l10n_it_pa_index = "0803HR0" # Partner ----------- cls.french_partner = cls.env['res.partner'].create({ 'name': 'Alessi', 'vat': 'FR15437982937', 'country_id': cls.env.ref('base.fr').id, 'street': 'Avenue Test rue', 'zip': '84000', 'city': 'Avignon', 'is_company': True }) # Taxes ----------- tax_data = { 'name': 'Tax 4% (Goods) Reverse Charge', 'amount': 4.0, 'amount_type': 'percent', 'type_tax_use': 'purchase', 'invoice_repartition_line_ids': repartition_lines( RepartitionLine(100, 'base', ('+03', '+vj9')), RepartitionLine(100, 'tax', ('+5v',)), RepartitionLine(-100, 'tax', ('-4v',))), 'refund_repartition_line_ids': repartition_lines( RepartitionLine(100, 'base', ('-03', '-vj9')), RepartitionLine(100, 'tax', False), RepartitionLine(-100, 'tax', False)), } # Purchase tax 4% with Reverse Charge cls.purchase_tax_4p = cls.env['account.tax'].with_company(cls.company).create(tax_data) cls.line_tax_4p = cls.standard_line.copy() cls.line_tax_4p['tax_ids'] = [(6, 0, cls.purchase_tax_4p.ids)] # Purchase tax 4% with Reverse Charge, targeting the tax grid for import of goods # already in Italy in a VAT deposit tax_data_4p_already_in_italy = { **tax_data, 'name': 'Tax 4% purchase Reverse Charge, in Italy', 'invoice_repartition_line_ids': repartition_lines( RepartitionLine(100, 'base', ('+03', '+vj3')), RepartitionLine(100, 'tax', ('+5v',)), RepartitionLine(-100, 'tax', ('-4v',))), 'refund_repartition_line_ids': repartition_lines( RepartitionLine(100, 'base', ('-03', '-vj3')), RepartitionLine(100, 'tax', False), RepartitionLine(-100, 'tax', False)), } cls.purchase_tax_4p_already_in_italy = cls.env['account.tax'].with_company(cls.company).create(tax_data_4p_already_in_italy) cls.line_tax_4p_already_in_italy = cls.standard_line.copy() cls.line_tax_4p_already_in_italy['tax_ids'] = [(6, 0, cls.purchase_tax_4p_already_in_italy.ids)] # Purchase tax 22% with Reverse Charge tax_data_22p = {**tax_data, 'name': 'Tax 22% purchase Reverse Charge', 'amount': 22.0} cls.purchase_tax_22p = cls.env['account.tax'].with_company(cls.company).create(tax_data_22p) cls.line_tax_22p = cls.standard_line.copy() cls.line_tax_22p['tax_ids'] = [(6, 0, cls.purchase_tax_22p.ids)] # Export tax 0% tax_data_0v = {**tax_data, "type_tax_use": "sale", "amount": 0} cls.sale_tax_0v = cls.env['account.tax'].with_company(cls.company).create(tax_data_0v) cls.line_tax_sale = cls.standard_line.copy() cls.line_tax_sale['tax_ids'] = [(6, 0, cls.sale_tax_0v.ids)] # Products ----------- # Product A with 0% sale export and tax 4% reverse carge purchase tax product_a = cls.env['product.product'].with_company(cls.company).create({ 'name': 'product_a', 'lst_price': 1000.0, 'standard_price': 800.0, 'type': 'consu', 'taxes_id': [(6, 0, cls.sale_tax_0v.ids)], 'supplier_taxes_id': [(6, 0, cls.purchase_tax_4p.ids)], }) # Product B with 0% sale export and tax 4% reverse charge purchase tax product_b = cls.env['product.product'].with_company(cls.company).create({ 'name': 'product_b', 'lst_price': 1000.0, 'standard_price': 800.0, 'type': 'consu', 'taxes_id': [(6, 0, cls.sale_tax_0v.ids)], 'supplier_taxes_id': [(6, 0, cls.purchase_tax_4p.ids)], }) # Moves ----------- # Export invoice cls.reverse_charge_invoice = cls.env['account.move'].with_company(cls.company).create({ 'company_id': cls.company.id, 'move_type': 'out_invoice', 'invoice_date': fields.Date.from_string('2022-03-24'), 'partner_id': cls.french_partner.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': product_lines( ProductLine(cls.line_tax_sale, 'Product A', product_a.id), ProductLine(cls.line_tax_sale, 'Product B', product_b.id) ), }) # Import bill #1 bill_data = { 'company_id': cls.company.id, 'move_type': 'in_invoice', 'invoice_date': fields.Date.from_string('2022-03-24'), 'partner_id': cls.french_partner.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': product_lines( ProductLine(cls.line_tax_22p, 'Product A', product_a.id), ProductLine(cls.line_tax_4p, 'Product B, taxed 4%', product_b.id) ) } cls.reverse_charge_bill = cls.env['account.move'].with_company(cls.company).create(bill_data) # Import bill #2 bill_data_2 = { **bill_data, 'invoice_line_ids': product_lines( ProductLine(cls.line_tax_22p, 'Product A', product_a.id), ProductLine(cls.line_tax_4p_already_in_italy, 'Product B, taxed 4% Already in Italy', product_b.id), ), } cls.reverse_charge_bill_2 = cls.env['account.move'].with_company(cls.company).create(bill_data_2) cls.reverse_charge_refund = cls.reverse_charge_bill.with_company(cls.company)._reverse_moves([{ 'invoice_date': fields.Date.from_string('2022-03-24'), }]) # Posting moves ----------- cls.reverse_charge_invoice._post() cls.reverse_charge_bill._post() cls.reverse_charge_bill_2._post() cls.reverse_charge_refund._post() def _cleanup_etree(self, content, xpaths=None): xpaths = { **(xpaths or {}), '//FatturaElettronicaBody/Allegati': 'Allegati', '//DatiTrasmissione/ProgressivoInvio': 'ProgressivoInvio', } return self.with_applied_xpath( etree.fromstring(content), "".join([f"<xpath expr='{x}' position='replace'>{y}</xpath>" for x, y in xpaths.items()]) ) def _test_invoice_with_sample_file(self, invoice, filename, xpaths_file=None, xpaths_result=None): result = self._cleanup_etree(invoice._export_as_xml(), xpaths_result) expected = self._cleanup_etree(self._get_test_file_content(filename), xpaths_file) self.assertXmlTreeEqual(result, expected) def test_reverse_charge_invoice(self): self._test_invoice_with_sample_file(self.reverse_charge_invoice, "reverse_charge_invoice.xml") def test_reverse_charge_bill(self): self._test_invoice_with_sample_file(self.reverse_charge_bill, "reverse_charge_bill.xml") def test_reverse_charge_bill_2(self): self._test_invoice_with_sample_file( self.reverse_charge_bill_2, "reverse_charge_bill.xml", xpaths_result={ "//DatiGeneraliDocumento/Numero": "<Numero/>", "(//DettaglioLinee/Descrizione)[2]": "<Descrizione/>", }, xpaths_file={ "//DatiGeneraliDocumento/TipoDocumento": "<TipoDocumento>TD19</TipoDocumento>", "//DatiGeneraliDocumento/Numero": "<Numero/>", "(//DettaglioLinee/Descrizione)[2]": "<Descrizione/>", } ) def test_reverse_charge_refund(self): self._test_invoice_with_sample_file( self.reverse_charge_refund, "reverse_charge_bill.xml", xpaths_result={ "//DatiGeneraliDocumento/Numero": "<Numero/>", "//DatiPagamento/DettaglioPagamento/DataScadenzaPagamento": "<DataScadenzaPagamento/>", }, xpaths_file={ "//DatiGeneraliDocumento/Numero": "<Numero/>", "//DatiGeneraliDocumento/ImportoTotaleDocumento": "<ImportoTotaleDocumento>-1808.91</ImportoTotaleDocumento>", "//DatiPagamento/DettaglioPagamento/DataScadenzaPagamento": "<DataScadenzaPagamento/>", "(//DettaglioLinee/PrezzoUnitario)[1]": "<PrezzoUnitario>-800.400000</PrezzoUnitario>", "(//DettaglioLinee/PrezzoUnitario)[2]": "<PrezzoUnitario>-800.400000</PrezzoUnitario>", "(//DettaglioLinee/PrezzoTotale)[1]": "<PrezzoTotale>-800.40</PrezzoTotale>", "(//DettaglioLinee/PrezzoTotale)[2]": "<PrezzoTotale>-800.40</PrezzoTotale>", "(//DatiRiepilogo/ImponibileImporto)[1]": "<ImponibileImporto>-800.40</ImponibileImporto>", "(//DatiRiepilogo/ImponibileImporto)[2]": "<ImponibileImporto>-800.40</ImponibileImporto>", "(//DatiRiepilogo/Imposta)[1]": "<Imposta>-176.09</Imposta>", "(//DatiRiepilogo/Imposta)[2]": "<Imposta>-32.02</Imposta>", } )
46.854626
10,636
36,805
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import logging from lxml import etree from freezegun import freeze_time from odoo import tools from odoo.tests import tagged from odoo.addons.account_edi.tests.common import AccountEdiTestCommon from odoo.exceptions import UserError _logger = logging.getLogger(__name__) @tagged('post_install_l10n', 'post_install', '-at_install') class TestItEdi(AccountEdiTestCommon): @classmethod def setUpClass(cls): super().setUpClass(chart_template_ref='l10n_it.l10n_it_chart_template_generic', edi_format_ref='l10n_it_edi.edi_fatturaPA') # Use the company_data_2 to test that the e-invoice is imported for the right company cls.company = cls.company_data_2['company'] cls.company.l10n_it_codice_fiscale = '01234560157' cls.company.vat = 'IT01234560157' cls.test_bank = cls.env['res.partner.bank'].with_company(cls.company).create({ 'partner_id': cls.company.partner_id.id, 'acc_number': 'IT1212341234123412341234123', 'bank_name': 'BIG BANK', 'bank_bic': 'BIGGBANQ', }) cls.company.l10n_it_tax_system = "RF01" cls.company.street = "1234 Test Street" cls.company.zip = "12345" cls.company.city = "Prova" cls.company.country_id = cls.env.ref('base.it') cls.price_included_tax = cls.env['account.tax'].create({ 'name': '22% price included tax', 'amount': 22.0, 'amount_type': 'percent', 'price_include': True, 'include_base_amount': True, 'company_id': cls.company.id, }) cls.tax_10 = cls.env['account.tax'].create({ 'name': '10% tax', 'amount': 10.0, 'amount_type': 'percent', 'company_id': cls.company.id, }) cls.tax_zero_percent_hundred_percent_repartition = cls.env['account.tax'].create({ 'name': 'all of nothing', 'amount': 0, 'amount_type': 'percent', 'company_id': cls.company.id, 'invoice_repartition_line_ids': [ (0, 0, {'factor_percent': 100, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 100, 'repartition_type': 'tax'}), ], 'refund_repartition_line_ids': [ (0, 0, {'factor_percent': 100, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 100, 'repartition_type': 'tax'}), ], }) cls.tax_zero_percent_zero_percent_repartition = cls.env['account.tax'].create({ 'name': 'none of nothing', 'amount': 0, 'amount_type': 'percent', 'company_id': cls.company.id, 'invoice_repartition_line_ids': [ (0, 0, {'factor_percent': 100, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 0, 'repartition_type': 'tax'}), ], 'refund_repartition_line_ids': [ (0, 0, {'factor_percent': 100, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 0, 'repartition_type': 'tax'}), ], }) cls.italian_partner_a = cls.env['res.partner'].create({ 'name': 'Alessi', 'vat': 'IT00465840031', 'l10n_it_codice_fiscale': '93026890017', 'country_id': cls.env.ref('base.it').id, 'street': 'Via Privata Alessi 6', 'zip': '28887', 'city': 'Milan', 'company_id': cls.company.id, 'is_company': True, }) cls.italian_partner_b = cls.env['res.partner'].create({ 'name': 'pa partner', 'vat': 'IT06655971007', 'l10n_it_codice_fiscale': '06655971007', 'l10n_it_pa_index': '123456', 'country_id': cls.env.ref('base.it').id, 'street': 'Via Test PA', 'zip': '32121', 'city': 'PA Town', 'is_company': True }) cls.italian_partner_no_address_codice = cls.env['res.partner'].create({ 'name': 'Alessi', 'l10n_it_codice_fiscale': '00465840031', 'is_company': True, }) cls.italian_partner_no_address_VAT = cls.env['res.partner'].create({ 'name': 'Alessi', 'vat': 'IT00465840031', 'is_company': True, }) cls.american_partner = cls.env['res.partner'].create({ 'name': 'Alessi', 'vat': '00465840031', 'country_id': cls.env.ref('base.us').id, 'is_company': True, }) cls.standard_line = { 'name': 'standard_line', 'quantity': 1, 'price_unit': 800.40, 'tax_ids': [(6, 0, [cls.company.account_sale_tax_id.id])] } cls.standard_line_below_400 = { 'name': 'cheap_line', 'quantity': 1, 'price_unit': 100.00, 'tax_ids': [(6, 0, [cls.company.account_sale_tax_id.id])] } cls.standard_line_400 = { 'name': '400_line', 'quantity': 1, 'price_unit': 327.87, 'tax_ids': [(6, 0, [cls.company.account_sale_tax_id.id])] } cls.price_included_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_a.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line, 'name': 'something price included', 'tax_ids': [(6, 0, [cls.price_included_tax.id])] }), (0, 0, { **cls.standard_line, 'name': 'something else price included', 'tax_ids': [(6, 0, [cls.price_included_tax.id])] }), (0, 0, { **cls.standard_line, 'name': 'something not price included', }), ], }) cls.partial_discount_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_a.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line, 'name': 'no discount', }), (0, 0, { **cls.standard_line, 'name': 'special discount', 'discount': 50, }), (0, 0, { **cls.standard_line, 'name': "an offer you can't refuse", 'discount': 100, }), ], }) cls.full_discount_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_a.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line, 'name': 'nothing shady just a gift for my friend', 'discount': 100, }), ], }) cls.non_latin_and_latin_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_a.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line, 'name': 'ʢ◉ᴥ◉ʡ', }), (0, 0, { **cls.standard_line, 'name': '–-', }), (0, 0, { **cls.standard_line, 'name': 'this should be the same as it was', }), ], }) cls.below_400_codice_simplified_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_no_address_codice.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line_below_400, }), (0, 0, { **cls.standard_line_below_400, 'name': 'cheap_line_2', 'quantity': 2, 'price_unit': 10.0, }), ], }) cls.total_400_VAT_simplified_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_no_address_VAT.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line_400, }), ], }) cls.more_400_simplified_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_no_address_codice.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line, }), ], }) cls.non_domestic_simplified_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.american_partner.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line_below_400, }), ], }) cls.pa_partner_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_b.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': [ (0, 0, cls.standard_line), ], }) # We create this because we are unable to post without a proxy user existing cls.proxy_user = cls.env['account_edi_proxy_client.user'].create({ 'id_client': 'l10n_it_edi_sdicoop_test', 'company_id': cls.company.id, 'edi_format_id': cls.edi_format.id, 'edi_identification': 'l10n_it_edi_sdicoop_test', 'private_key': 'l10n_it_edi_sdicoop_test', }) cls.zero_tax_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_a.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line, 'name': 'line with tax of 0% with repartition line of 100% ', 'tax_ids': [(6, 0, [cls.tax_zero_percent_hundred_percent_repartition.id])], }), (0, 0, { **cls.standard_line, 'name': 'line with tax of 0% with repartition line of 0% ', 'tax_ids': [(6, 0, [cls.tax_zero_percent_zero_percent_repartition.id])], }), ], }) cls.negative_price_invoice = cls.env['account.move'].with_company(cls.company).create({ 'move_type': 'out_invoice', 'invoice_date': datetime.date(2022, 3, 24), 'partner_id': cls.italian_partner_a.id, 'partner_bank_id': cls.test_bank.id, 'invoice_line_ids': [ (0, 0, { **cls.standard_line, }), (0, 0, { **cls.standard_line, 'name': 'negative_line', 'price_unit': -100.0, }), (0, 0, { **cls.standard_line, 'name': 'negative_line_different_tax', 'price_unit': -50.0, 'tax_ids': [(6, 0, [cls.tax_10.id])] }), ], }) cls.negative_price_credit_note = cls.negative_price_invoice.with_company(cls.company)._reverse_moves([{ 'invoice_date': datetime.date(2022, 3, 24), }]) # post the invoices cls.price_included_invoice._post() cls.partial_discount_invoice._post() cls.full_discount_invoice._post() cls.non_latin_and_latin_invoice._post() cls.below_400_codice_simplified_invoice._post() cls.total_400_VAT_simplified_invoice._post() cls.pa_partner_invoice._post() cls.zero_tax_invoice._post() cls.negative_price_invoice._post() cls.negative_price_credit_note._post() cls.edi_basis_xml = cls._get_test_file_content('IT00470550013_basis.xml') cls.edi_simplified_basis_xml = cls._get_test_file_content('IT00470550013_simpl.xml') @classmethod def _get_test_file_content(cls, filename): """ Get the content of a test file inside this module """ path = 'l10n_it_edi_sdicoop/tests/expected_xmls/' + filename with tools.file_open(path, mode='rb') as test_file: return test_file.read() def test_price_included_taxes(self): """ When the tax is price included, there should be a rounding value added to the xml, if the sum(subtotals) * tax_rate is not equal to taxable base * tax rate (there is a constraint in the edi where taxable base * tax rate = tax amount, but also taxable base = sum(subtotals) + rounding amount) """ # In this case, the first two lines use a price_include tax the # subtotals should be 800.40 / (100 + 22.0) * 100 = 656.065564.., # where 22.0 is the tax rate. # # Since the subtotals are rounded we actually have 656.07 lines = self.price_included_invoice.line_ids price_included_lines = lines.filtered(lambda line: line.tax_ids == self.price_included_tax) self.assertEqual([line.price_subtotal for line in price_included_lines], [656.07, 656.07]) # So the taxable a base the edi expects (for this tax) is actually 1312.14 price_included_tax_line = lines.filtered(lambda line: line.tax_line_id == self.price_included_tax) self.assertEqual(price_included_tax_line.tax_base_amount, 1312.14) # The tax amount of the price included tax should be: # per line: 800.40 - (800.40 / (100 + 22) * 100) = 144.33 # tax amount: 144.33 * 2 = 288.66 self.assertEqual(price_included_tax_line.price_total, 288.66) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_basis_xml), ''' <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <DettaglioLinee> <NumeroLinea>1</NumeroLinea> <Descrizione>something price included</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>656.070000</PrezzoUnitario> <PrezzoTotale>656.07</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>2</NumeroLinea> <Descrizione>something else price included</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>656.070000</PrezzoUnitario> <PrezzoTotale>656.07</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>3</NumeroLinea> <Descrizione>something not price included</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DatiRiepilogo> <AliquotaIVA>22.00</AliquotaIVA> <Arrotondamento>-0.04909091</Arrotondamento> <ImponibileImporto>1312.09</ImponibileImporto> <Imposta>288.66</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> <DatiRiepilogo> <AliquotaIVA>22.00</AliquotaIVA> <ImponibileImporto>800.40</ImponibileImporto> <Imposta>176.09</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> </DatiBeniServizi> </xpath> <xpath expr="//DettaglioPagamento//ImportoPagamento" position="inside"> 2577.29 </xpath> <xpath expr="//DatiGeneraliDocumento//ImportoTotaleDocumento" position="inside"> 2577.29 </xpath> ''') invoice_etree = etree.fromstring(self.price_included_invoice._export_as_xml()) # Remove the attachment and its details invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_partially_discounted_invoice(self): # The EDI can account for discounts, but a line with, for example, a 100% discount should still have # a corresponding tax with a base amount of 0 invoice_etree = etree.fromstring(self.partial_discount_invoice._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_basis_xml), ''' <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <DettaglioLinee> <NumeroLinea>1</NumeroLinea> <Descrizione>no discount</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>2</NumeroLinea> <Descrizione>special discount</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <ScontoMaggiorazione> <Tipo>SC</Tipo> <Percentuale>50.00</Percentuale> </ScontoMaggiorazione> <PrezzoTotale>400.20</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>3</NumeroLinea> <Descrizione>an offer you can't refuse</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <ScontoMaggiorazione> <Tipo>SC</Tipo> <Percentuale>100.00</Percentuale> </ScontoMaggiorazione> <PrezzoTotale>0.00</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DatiRiepilogo> <AliquotaIVA>22.00</AliquotaIVA> <ImponibileImporto>1200.60</ImponibileImporto> <Imposta>264.13</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> </DatiBeniServizi> </xpath> <xpath expr="//DettaglioPagamento//ImportoPagamento" position="inside"> 1464.73 </xpath> <xpath expr="//DatiGeneraliDocumento//ImportoTotaleDocumento" position="inside"> 1464.73 </xpath> ''') invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_fully_discounted_inovice(self): invoice_etree = etree.fromstring(self.full_discount_invoice._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_basis_xml), ''' <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <DettaglioLinee> <NumeroLinea>1</NumeroLinea> <Descrizione>nothing shady just a gift for my friend</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <ScontoMaggiorazione> <Tipo>SC</Tipo> <Percentuale>100.00</Percentuale> </ScontoMaggiorazione> <PrezzoTotale>0.00</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DatiRiepilogo> <AliquotaIVA>22.00</AliquotaIVA> <ImponibileImporto>0.00</ImponibileImporto> <Imposta>0.00</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> </DatiBeniServizi> </xpath> <xpath expr="//DettaglioPagamento//ImportoPagamento" position="inside"> 0.00 </xpath> <xpath expr="//DatiGeneraliDocumento//ImportoTotaleDocumento" position="inside"> 0.00 </xpath> ''') invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_non_latin_and_latin_invoice(self): invoice_etree = etree.fromstring(self.non_latin_and_latin_invoice._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_basis_xml), ''' <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <DettaglioLinee> <NumeroLinea>1</NumeroLinea> <Descrizione>?????</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>2</NumeroLinea> <Descrizione>?-</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>3</NumeroLinea> <Descrizione>this should be the same as it was</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DatiRiepilogo> <AliquotaIVA>22.00</AliquotaIVA> <ImponibileImporto>2401.20</ImponibileImporto> <Imposta>528.27</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> </DatiBeniServizi> </xpath> <xpath expr="//DettaglioPagamento//ImportoPagamento" position="inside"> 2929.47 </xpath> <xpath expr="//DatiGeneraliDocumento//ImportoTotaleDocumento" position="inside"> 2929.47 </xpath> ''') invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_below_400_codice_simplified_invoice(self): invoice_etree = etree.fromstring(self.below_400_codice_simplified_invoice._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_simplified_basis_xml), ''' <xpath expr="//FatturaElettronicaHeader//CessionarioCommittente" position="inside"> <IdentificativiFiscali> <CodiceFiscale>00465840031</CodiceFiscale> </IdentificativiFiscali> </xpath> <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <Descrizione>cheap_line</Descrizione> <Importo>122.00</Importo> <DatiIVA> <Imposta>22.00</Imposta> </DatiIVA> </DatiBeniServizi> <DatiBeniServizi> <Descrizione>cheap_line_2</Descrizione> <Importo>24.40</Importo> <DatiIVA> <Imposta>4.40</Imposta> </DatiIVA> </DatiBeniServizi> </xpath> ''') invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_total_400_VAT_simplified_invoice(self): invoice_etree = etree.fromstring(self.total_400_VAT_simplified_invoice._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_simplified_basis_xml), ''' <xpath expr="//FatturaElettronicaHeader//CessionarioCommittente" position="inside"> <IdentificativiFiscali> <IdFiscaleIVA> <IdPaese>IT</IdPaese> <IdCodice>00465840031</IdCodice> </IdFiscaleIVA> </IdentificativiFiscali> </xpath> <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <Descrizione>400_line</Descrizione> <Importo>400.00</Importo> <DatiIVA> <Imposta>72.13</Imposta> </DatiIVA> </DatiBeniServizi> </xpath> ''') invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_more_400_simplified_invoice(self): with self.assertRaises(UserError): self.more_400_simplified_invoice._post() def test_non_domestic_simplified_invoice(self): with self.assertRaises(UserError): self.non_domestic_simplified_invoice._post() def test_send_pa_partner(self): res = self.edi_format._l10n_it_post_invoices_step_1(self.pa_partner_invoice) self.assertEqual(res[self.pa_partner_invoice], {'attachment': self.pa_partner_invoice.l10n_it_edi_attachment_id, 'success': True}) def test_zero_percent_taxes(self): invoice_etree = etree.fromstring(self.zero_tax_invoice._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_basis_xml), ''' <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <DettaglioLinee> <NumeroLinea>1</NumeroLinea> <Descrizione>line with tax of 0% with repartition line of 100%</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>0.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>2</NumeroLinea> <Descrizione>line with tax of 0% with repartition line of 0%</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>0.00</AliquotaIVA> </DettaglioLinee> <DatiRiepilogo> <AliquotaIVA>0.00</AliquotaIVA> <ImponibileImporto>800.40</ImponibileImporto> <Imposta>0.00</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> <DatiRiepilogo> <AliquotaIVA>0.00</AliquotaIVA> <ImponibileImporto>800.40</ImponibileImporto> <Imposta>0.00</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> </DatiBeniServizi> </xpath> <xpath expr="//DettaglioPagamento//ImportoPagamento" position="inside"> 1600.80 </xpath> <xpath expr="//DatiGeneraliDocumento//ImportoTotaleDocumento" position="inside"> 1600.80 </xpath> ''' ) invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_negative_price_invoice(self): invoice_etree = etree.fromstring(self.negative_price_invoice._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_basis_xml), ''' <xpath expr="//FatturaElettronicaBody//DatiBeniServizi" position="replace"> <DatiBeniServizi> <DettaglioLinee> <NumeroLinea>1</NumeroLinea> <Descrizione>standard_line</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>2</NumeroLinea> <Descrizione>negative_line</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>-100.000000</PrezzoUnitario> <PrezzoTotale>-100.00</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>3</NumeroLinea> <Descrizione>negative_line_different_tax</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>-50.000000</PrezzoUnitario> <PrezzoTotale>-50.00</PrezzoTotale> <AliquotaIVA>10.00</AliquotaIVA> </DettaglioLinee> <DatiRiepilogo> <AliquotaIVA>22.00</AliquotaIVA> <ImponibileImporto>700.40</ImponibileImporto> <Imposta>154.09</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> <DatiRiepilogo> <AliquotaIVA>10.00</AliquotaIVA> <ImponibileImporto>-50.00</ImponibileImporto> <Imposta>-5.00</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> </DatiBeniServizi> </xpath> <xpath expr="//DettaglioPagamento//ImportoPagamento" position="inside"> 799.49 </xpath> <xpath expr="//DatiGeneraliDocumento//ImportoTotaleDocumento" position="inside"> 799.49 </xpath> ''') invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree) def test_negative_price_credit_note(self): invoice_etree = etree.fromstring(self.negative_price_credit_note._export_as_xml()) expected_etree = self.with_applied_xpath( etree.fromstring(self.edi_basis_xml), ''' <xpath expr="//DatiGeneraliDocumento/TipoDocumento" position="replace"> <TipoDocumento>TD04</TipoDocumento> </xpath> <xpath expr="//DatiGeneraliDocumento//ImportoTotaleDocumento" position="inside"> 799.49 </xpath> <xpath expr="//DatiBeniServizi" position="replace"> <DatiBeniServizi> <DettaglioLinee> <NumeroLinea>1</NumeroLinea> <Descrizione>standard_line</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>800.400000</PrezzoUnitario> <PrezzoTotale>800.40</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>2</NumeroLinea> <Descrizione>negative_line</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>-100.000000</PrezzoUnitario> <PrezzoTotale>-100.00</PrezzoTotale> <AliquotaIVA>22.00</AliquotaIVA> </DettaglioLinee> <DettaglioLinee> <NumeroLinea>3</NumeroLinea> <Descrizione>negative_line_different_tax</Descrizione> <Quantita>1.00</Quantita> <PrezzoUnitario>-50.000000</PrezzoUnitario> <PrezzoTotale>-50.00</PrezzoTotale> <AliquotaIVA>10.00</AliquotaIVA> </DettaglioLinee> <DatiRiepilogo> <AliquotaIVA>22.00</AliquotaIVA> <ImponibileImporto>700.40</ImponibileImporto> <Imposta>154.09</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> <DatiRiepilogo> <AliquotaIVA>10.00</AliquotaIVA> <ImponibileImporto>-50.00</ImponibileImporto> <Imposta>-5.00</Imposta> <EsigibilitaIVA>I</EsigibilitaIVA> </DatiRiepilogo> </DatiBeniServizi> </xpath> <xpath expr="//DatiPagamento" position="replace"/> ''') invoice_etree = self.with_applied_xpath(invoice_etree, "<xpath expr='.//Allegati' position='replace'/>") self.assertXmlTreeEqual(invoice_etree, expected_etree)
44.981663
36,795
19,342
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _, _lt from odoo.exceptions import UserError from odoo.addons.account_edi_proxy_client.models.account_edi_proxy_user import AccountEdiProxyError from lxml import etree import base64 import logging _logger = logging.getLogger(__name__) class AccountEdiFormat(models.Model): _inherit = 'account.edi.format' # ------------------------------------------------------------------------- # Import # ------------------------------------------------------------------------- def _cron_receive_fattura_pa(self): ''' Check the proxy for incoming invoices. ''' proxy_users = self.env['account_edi_proxy_client.user'].search([('edi_format_id', '=', self.env.ref('l10n_it_edi.edi_fatturaPA').id)]) if proxy_users._get_demo_state() == 'demo': return for proxy_user in proxy_users: company = proxy_user.company_id try: res = proxy_user._make_request(proxy_user._get_server_url() + '/api/l10n_it_edi/1/in/RicezioneInvoice') except AccountEdiProxyError as e: res = {} _logger.error('Error while receiving file from SdiCoop: %s', e) proxy_acks = [] retrigger = False for id_transaction, fattura in res.items(): # The server has a maximum number of documents it can send at a time # If that maximum is reached, then we search for more # by re-triggering the download cron, avoiding the timeout. current_num, max_num = fattura.get('current_num', 0), fattura.get('max_num', 0) retrigger = retrigger or current_num == max_num > 0 if self.env['ir.attachment'].search([('name', '=', fattura['filename']), ('res_model', '=', 'account.move')], limit=1): # name should be unique, the invoice already exists _logger.info('E-invoice already exist: %s', fattura['filename']) proxy_acks.append(id_transaction) continue file = proxy_user._decrypt_data(fattura['file'], fattura['key']) try: tree = etree.fromstring(file) except Exception: # should not happen as the file has been checked by SdiCoop _logger.info('Received file badly formatted, skipping: \n %s', file) continue invoice = self.env['account.move'].with_company(company).create({'move_type': 'in_invoice'}) attachment = self.env['ir.attachment'].create({ 'name': fattura['filename'], 'raw': file, 'type': 'binary', 'res_model': 'account.move', 'res_id': invoice.id }) if not self.env.context.get('test_skip_commit'): self.env.cr.commit() #In case something fails after, we still have the attachment # So that we don't delete the attachment when deleting the invoice attachment.res_id = False attachment.res_model = False invoice.unlink() invoice = self.env.ref('l10n_it_edi.edi_fatturaPA')._create_invoice_from_xml_tree(fattura['filename'], tree) attachment.write({'res_model': 'account.move', 'res_id': invoice.id}) proxy_acks.append(id_transaction) if not self.env.context.get('test_skip_commit'): self.env.cr.commit() if proxy_acks: try: proxy_user._make_request(proxy_user._get_server_url() + '/api/l10n_it_edi/1/ack', params={'transaction_ids': proxy_acks}) except AccountEdiProxyError as e: _logger.error('Error while receiving file from SdiCoop: %s', e) if retrigger: _logger.info('Retriggering "Receive invoices from the exchange system"...') self.env.ref('l10n_it_edi_sdicoop.ir_cron_receive_fattura_pa_invoice')._trigger() # ------------------------------------------------------------------------- # Export # ------------------------------------------------------------------------- def _get_invoice_edi_content(self, move): #OVERRIDE if self.code != 'fattura_pa': return super()._get_invoice_edi_content(move) return move._export_as_xml() def _check_move_configuration(self, move): # OVERRIDE res = super()._check_move_configuration(move) if self.code != 'fattura_pa': return res res.extend(self._l10n_it_edi_check_invoice_configuration(move)) if not self._get_proxy_user(move.company_id): res.append(_("You must accept the terms and conditions in the settings to use FatturaPA.")) return res def _needs_web_services(self): self.ensure_one() return self.code == 'fattura_pa' or super()._needs_web_services() def _l10n_it_edi_is_required_for_invoice(self, invoice): """ _is_required_for_invoice for SdiCoop. OVERRIDE """ is_self_invoice = self._l10n_it_edi_is_self_invoice(invoice) return ( (invoice.is_sale_document() or (is_self_invoice and invoice.is_purchase_document())) and invoice.l10n_it_send_state not in ('sent', 'delivered', 'delivered_accepted') and invoice.country_code == 'IT' ) def _support_batching(self, move=None, state=None, company=None): # OVERRIDE if self.code == 'fattura_pa': return state == 'to_send' and move.is_invoice() return super()._support_batching(move=move, state=state, company=company) def _get_batch_key(self, move, state): # OVERRIDE if self.code != 'fattura_pa': return super()._get_batch_key(move, state) return move.move_type, bool(move.l10n_it_edi_transaction) def _l10n_it_post_invoices_step_1(self, invoices): ''' Send the invoices to the proxy. ''' to_return = {} to_send = {} for invoice in invoices: xml = "<?xml version='1.0' encoding='UTF-8'?>" + str(invoice._export_as_xml()) filename = self._l10n_it_edi_generate_electronic_invoice_filename(invoice) attachment = self.env['ir.attachment'].create({ 'name': filename, 'res_id': invoice.id, 'res_model': invoice._name, 'raw': xml.encode(), 'description': _('Italian invoice: %s', invoice.move_type), 'type': 'binary', }) invoice.l10n_it_edi_attachment_id = attachment if invoice._is_commercial_partner_pa(): invoice.message_post( body=(_("Invoices for PA are not managed by Odoo, you can download the document and send it on your own.")) ) to_return[invoice] = {'attachment': attachment, 'success': True} else: to_send[filename] = { 'invoice': invoice, 'data': {'filename': filename, 'xml': base64.b64encode(xml.encode()).decode()}} company = invoices.company_id proxy_user = self._get_proxy_user(company) if not proxy_user: # proxy user should exist, because there is a check in _check_move_configuration return {invoice: { 'error': _("You must accept the terms and conditions in the settings to use FatturaPA."), 'blocking_level': 'error'} for invoice in invoices} responses = {} if proxy_user._get_demo_state() == 'demo': responses = {i['data']['filename']: {'id_transaction': 'demo'} for i in to_send.values()} else: try: responses = self._l10n_it_edi_upload([i['data'] for i in to_send.values()], proxy_user) except AccountEdiProxyError as e: return {invoice: {'error': e.message, 'blocking_level': 'error'} for invoice in invoices} for filename, response in responses.items(): invoice = to_send[filename]['invoice'] to_return[invoice] = response if 'id_transaction' in response: invoice.l10n_it_edi_transaction = response['id_transaction'] to_return[invoice].update({ 'error': _('The invoice was sent to FatturaPA, but we are still awaiting a response. Click the link above to check for an update.'), 'blocking_level': 'info', }) return to_return def _l10n_it_post_invoices_step_2(self, invoices): ''' Check if the sent invoices have been processed by FatturaPA. ''' to_check = {i.l10n_it_edi_transaction: i for i in invoices} to_return = {} company = invoices.company_id proxy_user = self._get_proxy_user(company) if not proxy_user: # proxy user should exist, because there is a check in _check_move_configuration return {invoice: { 'error': _("You must accept the terms and conditions in the settings to use FatturaPA."), 'blocking_level': 'error'} for invoice in invoices} if proxy_user._get_demo_state() == 'demo': # simulate success and bypass ack return {invoice: {'attachment': invoice.l10n_it_edi_attachment_id} for invoice in invoices} else: try: responses = proxy_user._make_request(proxy_user._get_server_url() + '/api/l10n_it_edi/1/in/TrasmissioneFatture', params={'ids_transaction': list(to_check.keys())}) except AccountEdiProxyError as e: return {invoice: {'error': e.message, 'blocking_level': 'error'} for invoice in invoices} proxy_acks = [] for id_transaction, response in responses.items(): invoice = to_check[id_transaction] if 'error' in response: to_return[invoice] = response continue state = response['state'] if state == 'awaiting_outcome': to_return[invoice] = { 'error': _('The invoice was sent to FatturaPA, but we are still awaiting a response. Click the link above to check for an update.'), 'blocking_level': 'info'} elif state == 'not_found': # Invoice does not exist on proxy. Either it does not belong to this proxy_user or it was not created correctly when # it was sent to the proxy. to_return[invoice] = {'error': _('You are not allowed to check the status of this invoice.'), 'blocking_level': 'error'} elif state == 'ricevutaConsegna': if invoice._is_commercial_partner_pa(): to_return[invoice] = {'error': _('The invoice has been succesfully transmitted. The addressee has 15 days to accept or reject it.')} else: to_return[invoice] = {'attachment': invoice.l10n_it_edi_attachment_id, 'success': True} proxy_acks.append(id_transaction) elif state == 'notificaMancataConsegna': if invoice._is_commercial_partner_pa(): to_return[invoice] = {'error': _( 'The invoice has been issued, but the delivery to the Public Administration' ' has failed. The Exchange System will contact them to report the problem' ' and request that they provide a solution.' ' During the following 10 days, the Exchange System will try to forward the' ' FatturaPA file to the Public Administration in question again.' ' Should this also fail, the System will notify Odoo of the failed delivery,' ' and you will be required to send the invoice to the Administration' ' through another channel, outside of the Exchange System.')} else: to_return[invoice] = {'success': True, 'attachment': invoice.l10n_it_edi_attachment_id} invoice._message_log(body=_( 'The invoice has been issued, but the delivery to the Addressee has' ' failed. You will be required to send a courtesy copy of the invoice' ' to your customer through another channel, outside of the Exchange' ' System, and promptly notify him that the original is deposited' ' in his personal area on the portal "Invoices and Fees" of the' ' Revenue Agency.')) proxy_acks.append(id_transaction) elif state == 'NotificaDecorrenzaTermini': # This condition is part of the Public Administration flow invoice._message_log(body=_( 'The invoice has been correctly issued. The Public Administration recipient' ' had 15 days to either accept or refused this document, but they did not reply,' ' so from now on we consider it accepted.')) to_return[invoice] = {'attachment': invoice.l10n_it_edi_attachment_id, 'success': True} proxy_acks.append(id_transaction) # In the transaction states above, we don't need to read the attachment. # In the following cases instead we need to read the information inside # about the notification itself, i.e. the error message in case of rejection. else: attachment_file = response.get('file') if not attachment_file: # It means there is no status update, so we can skip it document = invoice.edi_document_ids.filtered(lambda d: d.edi_format_id.code == 'fattura_pa') to_return[invoice] = {'error': document.error, 'blocking_level': document.blocking_level} continue xml = proxy_user._decrypt_data(attachment_file, response['key']) response_tree = etree.fromstring(xml) if state == 'notificaScarto': elements = response_tree.xpath('//Errore') error_codes = [element.find('Codice').text for element in elements] errors = [element.find('Descrizione').text for element in elements] # Duplicated invoice if '00404' in error_codes: idx = error_codes.index('00404') invoice.message_post(body=_( 'This invoice number had already been submitted to the SdI, so it is' ' set as Sent. Please verify that the system is correctly configured,' ' because the correct flow does not need to send the same invoice' ' twice for any reason.\n' ' Original message from the SDI: %s', errors[idx])) to_return[invoice] = {'attachment': invoice.l10n_it_edi_attachment_id, 'success': True} else: # Add helpful text if duplicated filename error if '00002' in error_codes: idx = error_codes.index('00002') errors[idx] = _( 'The filename is duplicated. Try again (or adjust the FatturaPA Filename sequence).' ' Original message from the SDI: %s', [errors[idx]] ) to_return[invoice] = {'error': self._format_error_message(_('The invoice has been refused by the Exchange System'), errors), 'blocking_level': 'error'} invoice.l10n_it_edi_transaction = False proxy_acks.append(id_transaction) elif state == 'notificaEsito': outcome = response_tree.find('Esito').text if outcome == 'EC01': to_return[invoice] = {'attachment': invoice.l10n_it_edi_attachment_id, 'success': True} else: # ECO2 to_return[invoice] = {'error': _('The invoice was refused by the addressee.'), 'blocking_level': 'error'} proxy_acks.append(id_transaction) if proxy_acks: try: proxy_user._make_request(proxy_user._get_server_url() + '/api/l10n_it_edi/1/ack', params={'transaction_ids': proxy_acks}) except AccountEdiProxyError as e: # Will be ignored and acked again next time. _logger.error('Error while acking file to SdiCoop: %s', e) return to_return def _post_fattura_pa(self, invoices): # OVERRIDE if not invoices[0].l10n_it_edi_transaction: return self._l10n_it_post_invoices_step_1(invoices) else: return self._l10n_it_post_invoices_step_2(invoices) # ------------------------------------------------------------------------- # Proxy methods # ------------------------------------------------------------------------- def _get_proxy_identification(self, company): if self.code != 'fattura_pa': return super()._get_proxy_identification() if not company.l10n_it_codice_fiscale: raise UserError(_('Please fill your codice fiscale to be able to receive invoices from FatturaPA')) return self.env['res.partner']._l10n_it_normalize_codice_fiscale(company.l10n_it_codice_fiscale) def _l10n_it_edi_upload(self, files, proxy_user): '''Upload files to fatturapa. :param files: A list of dictionary {filename, base64_xml}. :returns: A dictionary. * message: Message from fatturapa. * transactionId: The fatturapa ID of this request. * error: An eventual error. * error_level: Info, warning, error. ''' ERRORS = { 'EI01': {'error': _lt('Attached file is empty'), 'blocking_level': 'error'}, 'EI02': {'error': _lt('Service momentarily unavailable'), 'blocking_level': 'warning'}, 'EI03': {'error': _lt('Unauthorized user'), 'blocking_level': 'error'}, } if not files: return {} result = proxy_user._make_request(proxy_user._get_server_url() + '/api/l10n_it_edi/1/out/SdiRiceviFile', params={'files': files}) # Translate the errors. for filename in result.keys(): if 'error' in result[filename]: result[filename] = ERRORS.get(result[filename]['error'], {'error': result[filename]['error'], 'blocking_level': 'error'}) return result
50.238961
19,342
1,085
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) DEFAULT_FACTUR_ITALIAN_DATE_FORMAT = '%Y-%m-%d' class AccountMove(models.Model): _inherit = 'account.move' l10n_it_edi_transaction = fields.Char(copy=False, string="FatturaPA Transaction") l10n_it_edi_attachment_id = fields.Many2one('ir.attachment', copy=False, string="FatturaPA Attachment", ondelete="restrict") def send_pec_mail(self): self.ensure_one() # OVERRIDE # With SdiCoop web-service, no need to send PEC mail. # Set the state to 'other' because the invoice should not be managed par l10n_it_edi. self.l10n_it_send_state = 'other' @api.depends('l10n_it_edi_transaction') def _compute_show_reset_to_draft_button(self): super(AccountMove, self)._compute_show_reset_to_draft_button() for move in self.filtered(lambda m: m.l10n_it_edi_transaction): move.show_reset_to_draft_button = False
36.166667
1,085
5,242
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models, fields, _ from odoo.exceptions import UserError class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' is_edi_proxy_active = fields.Boolean(compute='_compute_is_edi_proxy_active') l10n_it_edi_proxy_current_state = fields.Char(compute='_compute_l10n_it_edi_proxy_current_state') l10n_it_edi_sdicoop_register = fields.Boolean(compute='_compute_l10n_it_edi_sdicoop_register', inverse='_set_l10n_it_edi_sdicoop_register_demo_mode') l10n_it_edi_sdicoop_demo_mode = fields.Selection( [('demo', 'Demo'), ('test', 'Test (experimental)'), ('prod', 'Official')], compute='_compute_l10n_it_edi_sdicoop_demo_mode', inverse='_set_l10n_it_edi_sdicoop_register_demo_mode', readonly=False) def _create_proxy_user(self, company_id): fattura_pa = self.env.ref('l10n_it_edi.edi_fatturaPA') edi_identification = fattura_pa._get_proxy_identification(company_id) self.env['account_edi_proxy_client.user']._register_proxy_user(company_id, fattura_pa, edi_identification) @api.depends('company_id.account_edi_proxy_client_ids', 'company_id.account_edi_proxy_client_ids.active') def _compute_l10n_it_edi_sdicoop_demo_mode(self): for config in self: config.l10n_it_edi_sdicoop_demo_mode = self.env['account_edi_proxy_client.user']._get_demo_state() def _set_l10n_it_edi_sdicoop_demo_mode(self): for config in self: self.env['ir.config_parameter'].set_param('account_edi_proxy_client.demo', config.l10n_it_edi_sdicoop_demo_mode) @api.depends('company_id.account_edi_proxy_client_ids', 'company_id.account_edi_proxy_client_ids.active') def _compute_is_edi_proxy_active(self): for config in self: config.is_edi_proxy_active = config.company_id.account_edi_proxy_client_ids @api.depends('company_id.account_edi_proxy_client_ids', 'company_id.account_edi_proxy_client_ids.active') def _compute_l10n_it_edi_proxy_current_state(self): fattura_pa = self.env.ref('l10n_it_edi.edi_fatturaPA') for config in self: proxy_user = config.company_id.account_edi_proxy_client_ids.search([ ('company_id', '=', config.company_id.id), ('edi_format_id','=', fattura_pa.id), ], limit=1) config.l10n_it_edi_proxy_current_state = 'inactive' if not proxy_user else 'demo' if proxy_user.id_client[:4] == 'demo' else 'active' @api.depends('company_id') def _compute_l10n_it_edi_sdicoop_register(self): """Needed because it expects a compute""" self.l10n_it_edi_sdicoop_register = False def button_create_proxy_user(self): # For now, only fattura_pa uses the proxy. # To use it for more, we have to either make the activation of the proxy on a format basis # or create a user per format here (but also when installing new formats) fattura_pa = self.env.ref('l10n_it_edi.edi_fatturaPA') edi_identification = fattura_pa._get_proxy_identification(self.company_id) if not edi_identification: return self.env['account_edi_proxy_client.user']._register_proxy_user(self.company_id, fattura_pa, edi_identification) def _set_l10n_it_edi_sdicoop_register_demo_mode(self): fattura_pa = self.env.ref('l10n_it_edi.edi_fatturaPA') for config in self: proxy_user = self.env['account_edi_proxy_client.user'].search([ ('company_id', '=', config.company_id.id), ('edi_format_id', '=', fattura_pa.id) ], limit=1) real_proxy_users = self.env['account_edi_proxy_client.user'].sudo().search([ ('id_client', 'not like', 'demo'), ]) # Update the config as per the selected radio button previous_demo_state = proxy_user._get_demo_state() self.env['ir.config_parameter'].set_param('account_edi_proxy_client.demo', config.l10n_it_edi_sdicoop_demo_mode) # If the user is trying to change from a state in which they have a registered official or testing proxy client # to another state, we should stop them if real_proxy_users and previous_demo_state != config.l10n_it_edi_sdicoop_demo_mode: raise UserError(_("The company has already registered with the service as 'Test' or 'Official', it cannot change.")) if config.l10n_it_edi_sdicoop_register: # There should only be one user at a time, if there are no users, register one if not proxy_user: self._create_proxy_user(config.company_id) return # If there is a demo user, and we are transitioning from demo to test or production, we should # delete all demo users and then create the new user. elif proxy_user.id_client[:4] == 'demo' and config.l10n_it_edi_sdicoop_demo_mode != 'demo': self.env['account_edi_proxy_client.user'].search([('id_client', '=like', 'demo%')]).sudo().unlink() self._create_proxy_user(config.company_id)
51.90099
5,242
738
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # Original Copyright 2015 Eezee-It, modified and maintained by Odoo. { 'name': 'Worldline SIPS', 'version': '2.0', 'category': 'Accounting/Payment Acquirers', 'sequence': 385, 'description': """ Worldline SIPS Payment Acquirer for online payments Implements the Worldline SIPS API for payment acquirers. Other SIPS providers may be compatible, though this is not guaranteed.""", 'depends': ['payment'], 'data': [ 'views/payment_views.xml', 'views/payment_sips_templates.xml', 'data/payment_acquirer_data.xml', ], 'application': True, 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3', }
30.75
738
576
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.payment.tests.common import PaymentCommon class SipsCommon(PaymentCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.sips = cls._prepare_acquirer('sips', update_values={ 'sips_merchant_id': 'dummy_mid', 'sips_secret': 'dummy_secret', }) # Override default values cls.acquirer = cls.sips cls.currency = cls.currency_euro
32
576
6,907
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import json from freezegun import freeze_time from odoo.exceptions import ValidationError from odoo.tests import tagged from odoo.tools import mute_logger from .common import SipsCommon from ..controllers.main import SipsController from ..models.payment_acquirer import SUPPORTED_CURRENCIES @tagged('post_install', '-at_install') class SipsTest(SipsCommon): def test_compatible_acquirers(self): for curr in SUPPORTED_CURRENCIES: currency = self._prepare_currency(curr) acquirers = self.env['payment.acquirer']._get_compatible_acquirers( partner_id=self.partner.id, company_id=self.company.id, currency_id=currency.id, ) self.assertIn(self.sips, acquirers) unsupported_currency = self._prepare_currency('VEF') acquirers = self.env['payment.acquirer']._get_compatible_acquirers( partner_id=self.partner.id, company_id=self.company.id, currency_id=unsupported_currency.id, ) self.assertNotIn(self.sips, acquirers) # freeze time for consistent singularize_prefix behavior during the test @freeze_time("2011-11-02 12:00:21") def test_reference(self): tx = self.create_transaction(flow="redirect", reference="") self.assertEqual(tx.reference, "tx20111102120021", "Payulatam: transaction reference wasn't correctly singularized.") def test_redirect_form_values(self): self.patch(self, 'base_url', 'http://localhost:8069') self.patch(type(self.env['base']), 'get_base_url', lambda _: 'http://localhost:8069') tx = self.create_transaction(flow="redirect") with mute_logger('odoo.addons.payment.models.payment_transaction'): processing_values = tx._get_processing_values() form_info = self._extract_values_from_html_form(processing_values['redirect_form_html']) form_inputs = form_info['inputs'] self.assertEqual(form_info['action'], self.sips.sips_test_url) self.assertEqual(form_inputs['InterfaceVersion'], self.sips.sips_version) return_url = self._build_url(SipsController._return_url) notify_url = self._build_url(SipsController._notify_url) self.assertEqual(form_inputs['Data'], f'amount=111111|currencyCode=978|merchantId=dummy_mid|normalReturnUrl={return_url}|' \ f'automaticResponseUrl={notify_url}|transactionReference={self.reference}|' \ f'statementReference={self.reference}|keyVersion={self.sips.sips_key_version}|' \ f'returnContext={json.dumps(dict(reference=self.reference))}' ) self.assertEqual(form_inputs['Seal'], '4d7cc67c0168e8ce11c25fbe1937231c644861e320702ab544022b032b9eb4a2') def test_feedback_processing(self): # typical data posted by Sips after client has successfully paid sips_post_data = { 'Data': 'captureDay=0|captureMode=AUTHOR_CAPTURE|currencyCode=840|' 'merchantId=002001000000001|orderChannel=INTERNET|' 'responseCode=00|transactionDateTime=2020-04-08T06:15:59+02:00|' 'transactionReference=SO100x1|keyVersion=1|' 'acquirerResponseCode=00|amount=31400|authorisationId=0020000006791167|' 'paymentMeanBrand=IDEAL|paymentMeanType=CREDIT_TRANSFER|' 'customerIpAddress=127.0.0.1|returnContext={"return_url": ' '"/payment/process", "reference": ' '"SO100x1"}|scoreValue=-3.0|scoreColor=GREEN|scoreInfo=A3;N;N#SC;N;TRANS=3:2;CUMUL=4500:250000|' 'scoreProfile=25_BUSINESS_SCORE_PRE_AUTHORISATION|scoreThreshold=-7;-5|holderAuthentRelegation=N|' 'holderAuthentStatus=|transactionOrigin=INTERNET|paymentPattern=ONE_SHOT|customerMobilePhone=null|' 'mandateAuthentMethod=null|mandateUsage=null|transactionActors=null|' 'mandateId=null|captureLimitDate=20200408|dccStatus=null|dccResponseCode=null|' 'dccAmount=null|dccCurrencyCode=null|dccExchangeRate=null|' 'dccExchangeRateValidity=null|dccProvider=null|' 'statementReference=SO100x1|panEntryMode=MANUAL|walletType=null|' 'holderAuthentMethod=NO_AUTHENT_METHOD', 'Encode': '', 'InterfaceVersion': 'HP_2.4', 'Seal': 'f03f64da6f57c171904d12bf709b1d6d3385131ac914e97a7e1db075ed438f3e', 'locale': 'en', } with self.assertRaises(ValidationError): # unknown transaction self.env['payment.transaction']._handle_feedback_data('sips', sips_post_data) self.amount = 314.0 self.reference = 'SO100x1' tx = self.create_transaction(flow="redirect") # Validate the transaction self.env['payment.transaction']._handle_feedback_data('sips', sips_post_data) self.assertEqual(tx.state, 'done', 'Sips: validation did not put tx into done state') self.assertEqual(tx.acquirer_reference, self.reference, 'Sips: validation did not update tx id') # same process for an payment in error on sips's end sips_post_data = { 'Data': 'captureDay=0|captureMode=AUTHOR_CAPTURE|currencyCode=840|' 'merchantId=002001000000001|orderChannel=INTERNET|responseCode=12|' 'transactionDateTime=2020-04-08T06:24:08+02:00|transactionReference=SO100x2|' 'keyVersion=1|amount=31400|customerIpAddress=127.0.0.1|returnContext={"return_url": ' '"/payment/process", "reference": ' '"SO100x2"}|scoreValue=-3.0|scoreColor=GREEN|scoreInfo=A3;N;N#SC;N;TRANS=3:2;CUMUL=4500:250000|' 'scoreProfile=25_BUSINESS_SCORE_PRE_AUTHORISATION|scoreThreshold=-7;-5' '|paymentPattern=ONE_SHOT|customerMobilePhone=null|mandateAuthentMethod=null|' 'mandateUsage=null|transactionActors=null|mandateId=null|captureLimitDate=null|' 'dccStatus=null|dccResponseCode=null|dccAmount=null|dccCurrencyCode=null|' 'dccExchangeRate=null|dccExchangeRateValidity=null|dccProvider=null|' 'statementReference=SO100x2|panEntryMode=null|walletType=null|holderAuthentMethod=null', 'InterfaceVersion': 'HP_2.4', 'Seal': '6e1995ea5432580860a04d8515b6eb1507996f97b3c5fa04fb6d9568121a16a2' } self.reference = 'SO100x2' tx2 = self.create_transaction(flow="redirect") self.env['payment.transaction']._handle_feedback_data('sips', sips_post_data) self.assertEqual(tx2.state, 'cancel', 'Sips: erroneous validation did not put tx into error state')
54.385827
6,907
7,435
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # Original Copyright 2015 Eezee-It, modified and maintained by Odoo. import json import logging from werkzeug import urls from odoo import _, api, models from odoo.exceptions import ValidationError from odoo.addons.payment import utils as payment_utils from odoo.addons.payment_sips.controllers.main import SipsController from .const import RESPONSE_CODES_MAPPING, SUPPORTED_CURRENCIES _logger = logging.getLogger(__name__) class PaymentTransaction(models.Model): _inherit = 'payment.transaction' @api.model def _compute_reference(self, provider, prefix=None, separator='-', **kwargs): """ Override of payment to ensure that Sips requirements for references are satisfied. Sips requirements for transaction are as follows: - References can only be made of alphanumeric characters. This is satisfied by forcing the custom separator to 'x' to ensure that no '-' character will be used to append a suffix. Additionally, the prefix is sanitized if it was provided, and generated with 'tx' as default otherwise. This prevents the prefix to be generated based on document names that may contain non-alphanum characters (eg: INV/2020/...). - References must be unique at provider level for a given merchant account. This is satisfied by singularizing the prefix with the current datetime. If two transactions are created simultaneously, `_compute_reference` ensures the uniqueness of references by suffixing a sequence number. :param str provider: The provider of the acquirer handling the transaction :param str prefix: The custom prefix used to compute the full reference :param str separator: The custom separator used to separate the prefix from the suffix :return: The unique reference for the transaction :rtype: str """ if provider == 'sips': # We use an empty separator for cosmetic reasons: As the default prefix is 'tx', we want # the singularized prefix to look like 'tx2020...' and not 'txx2020...'. prefix = payment_utils.singularize_reference_prefix(separator='') separator = 'x' # Still, we need a dedicated separator between the prefix and the seq. return super()._compute_reference(provider, prefix=prefix, separator=separator, **kwargs) def _get_specific_rendering_values(self, processing_values): """ Override of payment to return Sips-specific rendering values. Note: self.ensure_one() from `_get_processing_values` :param dict processing_values: The generic and specific processing values of the transaction :return: The dict of acquirer-specific processing values :rtype: dict """ res = super()._get_specific_rendering_values(processing_values) if self.provider != 'sips': return res base_url = self.get_base_url() data = { 'amount': payment_utils.to_minor_currency_units(self.amount, self.currency_id), 'currencyCode': SUPPORTED_CURRENCIES[self.currency_id.name], # The ISO 4217 code 'merchantId': self.acquirer_id.sips_merchant_id, 'normalReturnUrl': urls.url_join(base_url, SipsController._return_url), 'automaticResponseUrl': urls.url_join(base_url, SipsController._notify_url), 'transactionReference': self.reference, 'statementReference': self.reference, 'keyVersion': self.acquirer_id.sips_key_version, 'returnContext': json.dumps(dict(reference=self.reference)), } api_url = self.acquirer_id.sips_prod_url if self.acquirer_id.state == 'enabled' \ else self.acquirer_id.sips_test_url data = '|'.join([f'{k}={v}' for k, v in data.items()]) return { 'api_url': api_url, 'Data': data, 'InterfaceVersion': self.acquirer_id.sips_version, 'Seal': self.acquirer_id._sips_generate_shasign(data), } @api.model def _get_tx_from_feedback_data(self, provider, data): """ Override of payment to find the transaction based on Sips data. :param str provider: The provider of the acquirer that handled the transaction :param dict data: The feedback data sent by the provider :return: The transaction if found :rtype: recordset of `payment.transaction` :raise: ValidationError if the data match no transaction :raise: ValidationError if the currency is not supported :raise: ValidationError if the amount mismatch """ tx = super()._get_tx_from_feedback_data(provider, data) if provider != 'sips': return tx data = self._sips_data_to_object(data['Data']) reference = data.get('transactionReference') if not reference: return_context = json.loads(data.get('returnContext', '{}')) reference = return_context.get('reference') tx = self.search([('reference', '=', reference), ('provider', '=', 'sips')]) if not tx: raise ValidationError( "Sips: " + _("No transaction found matching reference %s.", reference) ) sips_currency = SUPPORTED_CURRENCIES.get(tx.currency_id.name) if not sips_currency: raise ValidationError( "Sips: " + _("This currency is not supported: %s.", tx.currency_id.name) ) amount_converted = payment_utils.to_major_currency_units( float(data.get('amount', '0.0')), tx.currency_id ) if tx.currency_id.compare_amounts(amount_converted, tx.amount) != 0: raise ValidationError( "Sips: " + _( "Incorrect amount: received %(received).2f, expected %(expected).2f", received=amount_converted, expected=tx.amount ) ) return tx def _process_feedback_data(self, data): """ Override of payment to process the transaction based on Sips data. Note: self.ensure_one() :param dict data: The feedback data sent by the provider :return: None """ super()._process_feedback_data(data) if self.provider != 'sips': return data = self._sips_data_to_object(data.get('Data')) self.acquirer_reference = data.get('transactionReference') response_code = data.get('responseCode') if response_code in RESPONSE_CODES_MAPPING['pending']: status = "pending" self._set_pending() elif response_code in RESPONSE_CODES_MAPPING['done']: status = "done" self._set_done() elif response_code in RESPONSE_CODES_MAPPING['cancel']: status = "cancel" self._set_canceled() else: status = "error" self._set_error(_("Unrecognized response received from the payment provider.")) _logger.info( "ref: %s, got response [%s], set as '%s'.", self.reference, response_code, status ) def _sips_data_to_object(self, data): res = {} for element in data.split('|'): key, value = element.split('=', 1) res[key] = value return res
44.255952
7,435
427
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class AccountPaymentMethod(models.Model): _inherit = 'account.payment.method' @api.model def _get_payment_method_information(self): res = super()._get_payment_method_information() res['sips'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]} return res
30.5
427
2,491
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # Original Copyright 2015 Eezee-It, modified and maintained by Odoo. from hashlib import sha256 from odoo import api, fields, models from .const import SUPPORTED_CURRENCIES class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection( selection_add=[('sips', "Sips")], ondelete={'sips': 'set default'}) sips_merchant_id = fields.Char( string="Merchant ID", help="The ID solely used to identify the merchant account with Sips", required_if_provider='sips') sips_secret = fields.Char( string="SIPS Secret Key", size=64, required_if_provider='sips', groups='base.group_system') sips_key_version = fields.Integer( string="Secret Key Version", required_if_provider='sips', default=2) sips_test_url = fields.Char( string="Test URL", required_if_provider='sips', default="https://payment-webinit.simu.sips-services.com/paymentInit") sips_prod_url = fields.Char( string="Production URL", required_if_provider='sips', default="https://payment-webinit.sips-services.com/paymentInit") sips_version = fields.Char( string="Interface Version", required_if_provider='sips', default="HP_2.31") @api.model def _get_compatible_acquirers(self, *args, currency_id=None, **kwargs): """ Override of payment to unlist Sips acquirers when the currency is not supported. """ acquirers = super()._get_compatible_acquirers(*args, currency_id=currency_id, **kwargs) currency = self.env['res.currency'].browse(currency_id).exists() if currency and currency.name not in SUPPORTED_CURRENCIES: acquirers = acquirers.filtered(lambda a: a.provider != 'sips') return acquirers def _sips_generate_shasign(self, data): """ Generate the shasign for incoming or outgoing communications. Note: self.ensure_one() :param str data: The data to use to generate the shasign :return: shasign :rtype: str """ self.ensure_one() key = self.sips_secret shasign = sha256((data + key).encode('utf-8')) return shasign.hexdigest() def _get_default_payment_method_id(self): self.ensure_one() if self.provider != 'sips': return super()._get_default_payment_method_id() return self.env.ref('payment_sips.payment_method_sips').id
40.177419
2,491
2,004
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # ISO 4217 Data for currencies supported by sips # NOTE: these are listed on the Atos Wordline SIPS POST documentation page # at https://documentation.sips.worldline.com/en/WLSIPS.001-GD-Data-dictionary.html#Sips.001_DD_en-Value-currencyCode # Yet with the simu environment, some of these currencies are *not* working # I have no way to know if this is caused by the SIMU environment, or if it's # the doc of SIPS that lists currencies that don't work, but since this list is # restrictive, I'm gonna assume they are supported when using the right flow # and payment methods, which may not work in SIMU... # Since SIPS advises to use 'in production', well... SUPPORTED_CURRENCIES = { 'ARS': '032', 'AUD': '036', 'BHD': '048', 'KHR': '116', 'CAD': '124', 'LKR': '144', 'CNY': '156', 'HRK': '191', 'CZK': '203', 'DKK': '208', 'HKD': '344', 'HUF': '348', 'ISK': '352', 'INR': '356', 'ILS': '376', 'JPY': '392', 'KRW': '410', 'KWD': '414', 'MYR': '458', 'MUR': '480', 'MXN': '484', 'NPR': '524', 'NZD': '554', 'NOK': '578', 'QAR': '634', 'RUB': '643', 'SAR': '682', 'SGD': '702', 'ZAR': '710', 'SEK': '752', 'CHF': '756', 'THB': '764', 'AED': '784', 'TND': '788', 'GBP': '826', 'USD': '840', 'TWD': '901', 'RSD': '941', 'RON': '946', 'TRY': '949', 'XOF': '952', 'XPF': '953', 'BGN': '975', 'EUR': '978', 'UAH': '980', 'PLN': '985', 'BRL': '986', } # Mapping of transaction states to Sips response codes. # See https://documentation.sips.worldline.com/en/WLSIPS.001-GD-Data-dictionary.html#Sips.001_DD_en-Value-currencyCode RESPONSE_CODES_MAPPING = { 'pending': ('60',), 'done': ('00',), 'cancel': ( '03', '05', '12', '14', '17', '24', '25', '30', '34', '40', '51', '54', '63', '75', '90', '94', '97', '99' ), }
28.225352
2,004
3,079
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # Original Copyright 2015 Eezee-It, modified and maintained by Odoo. import logging import pprint from odoo import http from odoo.exceptions import ValidationError from odoo.http import request _logger = logging.getLogger(__name__) class SipsController(http.Controller): _return_url = '/payment/sips/dpn/' _notify_url = '/payment/sips/ipn/' @http.route( _return_url, type='http', auth='public', methods=['POST'], csrf=False, save_session=False ) def sips_dpn(self, **post): """ Process the data returned by SIPS after redirection. The route is flagged with `save_session=False` to prevent Odoo from assigning a new session to the user if they are redirected to this route with a POST request. Indeed, as the session cookie is created without a `SameSite` attribute, some browsers that don't implement the recommended default `SameSite=Lax` behavior will not include the cookie in the redirection request from the payment provider to Odoo. As the redirection to the '/payment/status' page will satisfy any specification of the `SameSite` attribute, the session of the user will be retrieved and with it the transaction which will be immediately post-processed. :param dict post: The feedback data to process """ _logger.info("beginning Sips DPN _handle_feedback_data with data %s", pprint.pformat(post)) try: if self._sips_validate_data(post): request.env['payment.transaction'].sudo()._handle_feedback_data('sips', post) except ValidationError: pass return request.redirect('/payment/status') @http.route(_notify_url, type='http', auth='public', methods=['POST'], csrf=False) def sips_ipn(self, **post): """ Sips IPN. """ _logger.info("beginning Sips IPN _handle_feedback_data with data %s", pprint.pformat(post)) if not post: # SIPS sometimes sends empty notifications, the reason why is unclear but they tend to # pollute logs and do not provide any meaningful information; log as a warning instead # of a traceback. _logger.warning("received empty notification; skip.") else: try: if self._sips_validate_data(post): request.env['payment.transaction'].sudo()._handle_feedback_data('sips', post) except ValidationError: pass # Acknowledge the notification to avoid getting spammed return '' def _sips_validate_data(self, post): tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_feedback_data('sips', post) acquirer_sudo = tx_sudo.acquirer_id security = acquirer_sudo._sips_generate_shasign(post['Data']) if security == post['Seal']: _logger.debug('validated data') return True else: _logger.warning('data are tampered') return False
45.279412
3,079
1,377
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "pos_hr", 'category': "Hidden", 'summary': 'Link module between Point of Sale and HR', 'description': """ This module allows Employees (and not users) to log in to the Point of Sale application using a barcode, a PIN number or both. The actual till still requires one user but an unlimited number of employees can log on to that till and process sales. """, 'depends': ['point_of_sale', 'hr'], 'data': [ 'views/pos_config.xml', 'views/pos_order_view.xml', 'views/pos_order_report_view.xml', ], 'installable': True, 'auto_install': True, 'assets': { 'point_of_sale.assets': [ 'pos_hr/static/src/css/pos.css', 'pos_hr/static/src/js/models.js', 'pos_hr/static/src/js/useSelectEmployee.js', 'pos_hr/static/src/js/Chrome.js', 'pos_hr/static/src/js/HeaderLockButton.js', 'pos_hr/static/src/js/CashierName.js', 'pos_hr/static/src/js/LoginScreen.js', 'pos_hr/static/src/js/PaymentScreen.js', ], 'web.assets_tests': [ 'pos_hr/static/tests/**/*', ], 'web.assets_qweb': [ 'pos_hr/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
32.785714
1,377
2,179
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import tools from odoo.api import Environment from odoo.tools import DEFAULT_SERVER_DATE_FORMAT from datetime import date, timedelta from odoo.tests import Form, tagged, new_test_user from odoo.addons.point_of_sale.tests.test_frontend import TestPointOfSaleHttpCommon class TestPosHrHttpCommon(TestPointOfSaleHttpCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.env.user.groups_id += cls.env.ref('hr.group_hr_user') cls.main_pos_config.write({"module_pos_hr": True}) # Admin employee admin = cls.env.ref("hr.employee_admin").sudo().copy({ "company_id": cls.env.company.id, "user_id": cls.env.user.id, "name": "Mitchell Admin", "pin": False, }) # User employee emp1 = cls.env.ref("hr.employee_han").sudo().copy({ "company_id": cls.env.company.id, }) emp1_user = new_test_user( cls.env, login="emp1_user", groups="base.group_user", name="Pos Employee1", email="[email protected]", ) emp1.write({"name": "Pos Employee1", "pin": "2580", "user_id": emp1_user.id}) # Non-user employee emp2 = cls.env.ref("hr.employee_jve").sudo().copy({ "company_id": cls.env.company.id, }) emp2.write({"name": "Pos Employee2", "pin": "1234"}) (admin + emp1 + emp2).company_id = cls.env.company with Form(cls.main_pos_config) as config: config.employee_ids.add(emp1) config.employee_ids.add(emp2) @tagged("post_install", "-at_install") class TestUi(TestPosHrHttpCommon): def test_01_pos_hr_tour(self): # open a session, the /pos/ui controller will redirect to it self.main_pos_config.open_session_cb(check_coa=False) self.start_tour( "/pos/ui?config_id=%d" % self.main_pos_config.id, "PosHrTour", login="accountman", )
33.523077
2,179
317
py
PYTHON
15.0
# -*- coding: utf-8 -*- from functools import partial from odoo import models, fields class PosConfig(models.Model): _inherit = 'pos.config' employee_ids = fields.Many2many( 'hr.employee', string="Employees with access", help='If left empty, all employees can log in to the PoS session')
24.384615
317
1,904
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import hashlib from odoo import api, models, _ from odoo.exceptions import UserError class HrEmployee(models.Model): _inherit = 'hr.employee' def get_barcodes_and_pin_hashed(self): if not self.env.user.has_group('point_of_sale.group_pos_user'): return [] # Apply visibility filters (record rules) visible_emp_ids = self.search([('id', 'in', self.ids)]) employees_data = self.sudo().search_read([('id', 'in', visible_emp_ids.ids)], ['barcode', 'pin']) for e in employees_data: e['barcode'] = hashlib.sha1(e['barcode'].encode('utf8')).hexdigest() if e['barcode'] else False e['pin'] = hashlib.sha1(e['pin'].encode('utf8')).hexdigest() if e['pin'] else False return employees_data @api.ondelete(at_uninstall=False) def _unlink_except_active_pos_session(self): configs_with_employees = self.env['pos.config'].sudo().search([('module_pos_hr', '=', 'True')]).filtered(lambda c: c.current_session_id) configs_with_all_employees = configs_with_employees.filtered(lambda c: not c.employee_ids) configs_with_specific_employees = configs_with_employees.filtered(lambda c: c.employee_ids & self) if configs_with_all_employees or configs_with_specific_employees: error_msg = _("You cannot delete an employee that may be used in an active PoS session, close the session(s) first: \n") for employee in self: config_ids = configs_with_all_employees | configs_with_specific_employees.filtered(lambda c: employee in c.employee_ids) if config_ids: error_msg += _("Employee: %s - PoS Config(s): %s \n") % (employee.name, ', '.join(config.name for config in config_ids)) raise UserError(error_msg)
51.459459
1,904
1,282
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api class PosOrder(models.Model): _inherit = "pos.order" employee_id = fields.Many2one('hr.employee', help="Person who uses the cash register. It can be a reliever, a student or an interim employee.", states={'done': [('readonly', True)], 'invoiced': [('readonly', True)]}) cashier = fields.Char(string="Cashier", compute="_compute_cashier", store=True) @api.model def _order_fields(self, ui_order): order_fields = super(PosOrder, self)._order_fields(ui_order) order_fields['employee_id'] = ui_order.get('employee_id') return order_fields @api.depends('employee_id', 'user_id') def _compute_cashier(self): for order in self: if order.employee_id: order.cashier = order.employee_id.name else: order.cashier = order.user_id.name def _export_for_ui(self, order): result = super(PosOrder, self)._export_for_ui(order) result.update({ 'employee_id': order.employee_id.id, }) return result def _get_fields_for_draft_order(self): fields = super(PosOrder, self)._get_fields_for_draft_order() fields.append('employee_id') return fields
36.628571
1,282
471
py
PYTHON
15.0
# -*- coding: utf-8 -*- from functools import partial from odoo import models, fields class PosOrderReport(models.Model): _inherit = "report.pos.order" employee_id = fields.Many2one( 'hr.employee', string='Employee', readonly=True) def _select(self): return super(PosOrderReport, self)._select() + ',s.employee_id AS employee_id' def _group_by(self): return super(PosOrderReport, self)._group_by() + ',s.employee_id'
27.705882
471
460
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Link Tracker', 'category': 'Marketing', 'description': """ Shorten URLs and use them to track clicks and UTMs """, 'version': '1.1', 'depends': ['utm', 'mail'], 'data': [ 'views/link_tracker_views.xml', 'views/utm_campaign_views.xml', 'security/ir.model.access.csv', ], 'license': 'LGPL-3', }
25.555556
460
5,354
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from .common import MockLinkTracker from odoo.tests import common from odoo.exceptions import UserError class TestLinkTracker(common.TransactionCase, MockLinkTracker): def setUp(self): super(TestLinkTracker, self).setUp() self._web_base_url = 'https://test.odoo.com' self.env['ir.config_parameter'].sudo().set_param('web.base.url', self._web_base_url) def test_create(self): link_trackers = self.env['link.tracker'].create([ { 'url': 'odoo.com', 'title': 'Odoo', }, { 'url': 'example.com', 'title': 'Odoo', }, { 'url': 'http://test.example.com', 'title': 'Odoo', }, ]) self.assertEqual( link_trackers.mapped('url'), ['http://odoo.com', 'http://example.com', 'http://test.example.com'], ) self.assertEqual(len(set(link_trackers.mapped('code'))), 3) def test_search_or_create(self): link_tracker_1 = self.env['link.tracker'].create({ 'url': 'https://odoo.com', 'title': 'Odoo', }) link_tracker_2 = self.env['link.tracker'].search_or_create({ 'url': 'https://odoo.com', 'title': 'Odoo', }) self.assertEqual(link_tracker_1, link_tracker_2) link_tracker_3 = self.env['link.tracker'].search_or_create({ 'url': 'https://odoo.be', 'title': 'Odoo', }) self.assertNotEqual(link_tracker_1, link_tracker_3) def test_constraint(self): campaign_id = self.env['utm.campaign'].search([], limit=1) self.env['link.tracker'].create({ 'url': 'https://odoo.com', 'title': 'Odoo', }) link_1 = self.env['link.tracker'].create({ 'url': '2nd url', 'title': 'Odoo', 'campaign_id': campaign_id.id, }) with self.assertRaises(UserError): self.env['link.tracker'].create({ 'url': 'https://odoo.com', 'title': 'Odoo', }) with self.assertRaises(UserError): self.env['link.tracker'].create({ 'url': '2nd url', 'title': 'Odoo', 'campaign_id': campaign_id.id, }) link_2 = self.env['link.tracker'].create({ 'url': '2nd url', 'title': 'Odoo', 'campaign_id': campaign_id.id, 'medium_id': self.env['utm.medium'].search([], limit=1).id }) # test in batch with self.assertRaises(UserError): # both link trackers on which we write will have the same values (link_1 | link_2).write({'campaign_id': False, 'medium_id': False}) with self.assertRaises(UserError): (link_1 | link_2).write({'medium_id': False}) def test_no_external_tracking(self): self.env['ir.config_parameter'].set_param('link_tracker.no_external_tracking', '1') campaign = self.env['utm.campaign'].create({'name': 'campaign'}) source = self.env['utm.source'].create({'name': 'source'}) medium = self.env['utm.medium'].create({'name': 'medium'}) expected_utm_params = { 'utm_campaign': campaign.name, 'utm_source': source.name, 'utm_medium': medium.name, } # URL to an external website -> UTM parameters should no be added # because the system parameter "no_external_tracking" is set link = self.env['link.tracker'].create({ 'url': 'http://external.com/test?a=example.com', 'campaign_id': campaign.id, 'source_id': source.id, 'medium_id': medium.id, 'title': 'Title', }) self.assertLinkParams( 'http://external.com/test', link, {'a': 'example.com'} ) # URL to the local website -> UTM parameters should be added since we know we handle them # even though the parameter "no_external_tracking" is enabled link.url = f'{self._web_base_url}/test?a=example.com' self.assertLinkParams( f'{self._web_base_url}/test', link, {**expected_utm_params, 'a': 'example.com'} ) # Relative URL to the local website -> UTM parameters should be added since we know we handle them # even though the parameter "no_external_tracking" is enabled link.url = '/test?a=example.com' self.assertLinkParams( '/test', link, {**expected_utm_params, 'a': 'example.com'} ) # Deactivate the system parameter self.env['ir.config_parameter'].set_param('link_tracker.no_external_tracking', False) # URL to an external website -> UTM parameters should be added since # the system parameter "link_tracker.no_external_tracking" is disabled link.url = 'http://external.com/test?a=example.com' self.assertLinkParams( 'http://external.com/test', link, {**expected_utm_params, 'a': 'example.com'} )
34.320513
5,354
3,744
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import werkzeug from lxml import etree from unittest.mock import patch from odoo.tests import common class MockLinkTracker(common.BaseCase): def setUp(self): super(MockLinkTracker, self).setUp() def _get_title_from_url(url): return "Test_TITLE" link_tracker_title_patch = patch('odoo.addons.link_tracker.models.link_tracker.LinkTracker._get_title_from_url', wraps=_get_title_from_url) link_tracker_title_patch.start() self.addCleanup(link_tracker_title_patch.stop) def _get_href_from_anchor_id(self, body, anchor_id): """ Parse en html body to find the href of an element given its ID. """ html = etree.fromstring(body, parser=etree.HTMLParser()) return html.xpath("//*[@id='%s']" % anchor_id)[0].attrib.get('href') def _get_tracker_from_short_url(self, short_url): code = self.env['link.tracker.code'].sudo().search([ ('code', '=', short_url.split('/r/')[-1]) ]) return code.link_id def assertLinkShortenedHtml(self, body, link_info, link_params=None): """ Find shortened links in an HTML content. Usage : self.assertLinkShortenedHtml( message.body, ('url0', 'http://www.odoo.com', True), {'utm_campaign': self.utm_c.name, 'utm_medium': self.utm_m.name} ) """ (anchor_id, url, is_shortened) = link_info anchor_href = self._get_href_from_anchor_id(body, anchor_id) if is_shortened: self.assertTrue('/r/' in anchor_href, '%s should be shortened: %s' % (anchor_id, anchor_href)) link_tracker = self._get_tracker_from_short_url(anchor_href) self.assertEqual(url, link_tracker.url) self.assertLinkParams(url, link_tracker, link_params=link_params) else: self.assertTrue('/r/' not in anchor_href, '%s should not be shortened: %s' % (anchor_id, anchor_href)) self.assertEqual(anchor_href, url) def assertLinkShortenedText(self, body, link_info, link_params=None): """ Find shortened links in an text content. Usage : self.assertLinkShortenedText( message.body, ('http://www.odoo.com', True), {'utm_campaign': self.utm_c.name, 'utm_medium': self.utm_m.name} ) """ (url, is_shortened) = link_info link_tracker = self.env['link.tracker'].search([('url', '=', url)]) if is_shortened: self.assertEqual(len(link_tracker), 1) self.assertIn(link_tracker.short_url, body, '%s should be shortened' % (url)) self.assertLinkParams(url, link_tracker, link_params=link_params) else: self.assertEqual(len(link_tracker), 0) self.assertIn(url, body) def assertLinkParams(self, url, link_tracker, link_params=None): """ Usage self.assertLinkTracker( 'http://www.example.com', link_tracker, {'utm_campaign': self.utm_c.name, 'utm_medium': self.utm_m.name} ) """ # check UTMS are correctly set on redirect URL original_url = werkzeug.urls.url_parse(url) redirect_url = werkzeug.urls.url_parse(link_tracker.redirected_url) redirect_params = redirect_url.decode_query().to_dict(flat=True) self.assertEqual(redirect_url.scheme, original_url.scheme) self.assertEqual(redirect_url.decode_netloc(), original_url.decode_netloc()) self.assertEqual(redirect_url.path, original_url.path) if link_params: self.assertEqual(redirect_params, link_params)
41.142857
3,744
6,973
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from odoo.tests import common, tagged from odoo.tools import TEXT_URL_REGEX @tagged('-at_install', 'post_install') class TestMailRenderMixin(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.base_url = cls.env["mail.render.mixin"].get_base_url() def test_shorten_links(self): test_links = [ '<a href="https://gitlab.com" title="title" fake="fake">test_label</a>', '<a href="https://test_542152qsdqsd.com"/>', """<a href="https://third_test_54212.com"> <img src="imagesrc"/> </a> """, """<a href="https://test_strange_html.com" title="title" fake='fake' > test_strange_html_label </a> """, '<a href="https://test_escaped.com" title="title" fake="fake"> test_escaped &lt; &gt; </a>', '<a href="https://url_with_params.com?a=b&c=d">label</a>', ] self.env["mail.render.mixin"]._shorten_links("".join(test_links), {}) trackers_to_find = [ [("url", "=", "https://gitlab.com"), ("label", "=", "test_label")], [("url", "=", "https://test_542152qsdqsd.com")], [ ("url", "=", "https://test_strange_html.com"), ("label", "=", "test_strange_html_label"), ], [ ("url", "=", "https://test_escaped.com"), ("label", "=", "test_escaped < >"), ], [ ("url", "=", "https://url_with_params.com?a=b&c=d"), ("label", "=", "label"), ], ] trackers_to_fail = [ [("url", "=", "https://test_542152qsdqsd.com"), ("label", "ilike", "_")] ] for tracker_to_find in trackers_to_find: self.assertTrue(self.env["link.tracker"].search(tracker_to_find)) for tracker_to_fail in trackers_to_fail: self.assertFalse(self.env["link.tracker"].search(tracker_to_fail)) def test_shorten_links_html_skip_shorts(self): old_content = self.env["mail.render.mixin"]._shorten_links( 'This is a link: <a href="https://test_542152qsdqsd.com">old</a>', {}) created_short_url_match = re.search(TEXT_URL_REGEX, old_content) self.assertIsNotNone(created_short_url_match) created_short_url = created_short_url_match[0] self.assertRegex(created_short_url, "{base_url}/r/[\\w]+".format(base_url=self.base_url)) new_content = self.env["mail.render.mixin"]._shorten_links( 'Reusing this old <a href="{old_short_url}">link</a> with a new <a href="https://odoo.com">one</a>' .format(old_short_url=created_short_url), {} ) expected = re.compile( 'Reusing this old <a href="{old_short_url}">link</a> with a new <a href="{base_url}/r/[\\w]+">one</a>' .format(old_short_url=created_short_url, base_url=self.base_url) ) self.assertRegex(new_content, expected) def test_shorten_links_html_including_base_url(self): content = ( 'This is a link: <a href="https://www.worldcommunitygrid.org">https://www.worldcommunitygrid.org</a><br/>\n' 'This is another: <a href="{base_url}/web#debug=1&more=2">{base_url}</a><br/>\n' 'And a third: <a href="{base_url}">Here</a>\n' 'And a forth: <a href="{base_url}">Here</a>\n' 'And a fifth: <a href="{base_url}">Here too</a>\n' 'And a last, more complex: <a href="https://boinc.berkeley.edu/forum_thread.php?id=14544&postid=106833">There!</a>' .format(base_url=self.base_url) ) expected_pattern = re.compile( 'This is a link: <a href="{base_url}/r/[\\w]+">https://www.worldcommunitygrid.org</a><br/>\n' 'This is another: <a href="{base_url}/r/[\\w]+">{base_url}</a><br/>\n' 'And a third: <a href="{base_url}/r/([\\w]+)">Here</a>\n' 'And a forth: <a href="{base_url}/r/([\\w]+)">Here</a>\n' 'And a fifth: <a href="{base_url}/r/([\\w]+)">Here too</a>\n' 'And a last, more complex: <a href="{base_url}/r/([\\w]+)">There!</a>' .format(base_url=self.base_url) ) new_content = self.env["mail.render.mixin"]._shorten_links(content, {}) self.assertRegex(new_content, expected_pattern) matches = expected_pattern.search(new_content).groups() # 3rd and 4th lead to the same short_url self.assertEqual(matches[0], matches[1]) # 5th has different label but should currently lead to the same link self.assertEqual(matches[1], matches[2]) def test_shorten_links_text_including_base_url(self): content = ( 'This is a link: https://www.worldcommunitygrid.org\n' 'This is another: {base_url}/web#debug=1&more=2\n' 'A third: {base_url}\n' 'A forth: {base_url}\n' 'And a last, with question mark: https://boinc.berkeley.edu/forum_thread.php?id=14544&postid=106833' .format(base_url=self.base_url) ) expected_pattern = re.compile( 'This is a link: {base_url}/r/[\\w]+\n' 'This is another: {base_url}/r/[\\w]+\n' 'A third: {base_url}/r/([\\w]+)\n' 'A forth: {base_url}/r/([\\w]+)\n' 'And a last, with question mark: {base_url}/r/([\\w]+)' .format(base_url=self.base_url) ) new_content = self.env["mail.render.mixin"]._shorten_links_text(content, {}) self.assertRegex(new_content, expected_pattern) matches = expected_pattern.search(new_content).groups() # 3rd and 4th lead to the same short_url self.assertEqual(matches[0], matches[1]) def test_shorten_links_text_skip_shorts(self): old_content = self.env["mail.render.mixin"]._shorten_links_text( 'This is a link: https://test_542152qsdqsd.com', {}) created_short_url_match = re.search(TEXT_URL_REGEX, old_content) self.assertIsNotNone(created_short_url_match) created_short_url = created_short_url_match[0] self.assertRegex(created_short_url, "{base_url}/r/[\\w]+".format(base_url=self.base_url)) new_content = self.env["mail.render.mixin"]._shorten_links_text( 'Reusing this old link {old_short_url} with a new one, https://odoo.com</a>' .format(old_short_url=created_short_url), {} ) expected = re.compile( 'Reusing this old link {old_short_url} with a new one, {base_url}/r/[\\w]+' .format(old_short_url=created_short_url, base_url=self.base_url) ) self.assertRegex(new_content, expected)
46.178808
6,973
3,853
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re import markupsafe from html import unescape from werkzeug import urls from odoo import api, models, tools class MailRenderMixin(models.AbstractModel): _inherit = "mail.render.mixin" # ------------------------------------------------------------ # TOOLS # ------------------------------------------------------------ @api.model def _shorten_links(self, html, link_tracker_vals, blacklist=None, base_url=None): """ Shorten links in an html content. It uses the '/r' short URL routing introduced in this module. Using the standard Odoo regex local links are found and replaced by global URLs (not including mailto, tel, sms). TDE FIXME: could be great to have a record to enable website-based URLs :param link_tracker_vals: values given to the created link.tracker, containing for example: campaign_id, medium_id, source_id, and any other relevant fields like mass_mailing_id in mass_mailing; :param list blacklist: list of (local) URLs to not shorten (e.g. '/unsubscribe_from_list') :param str base_url: either given, either based on config parameter :return: updated html """ base_url = base_url or self.env['ir.config_parameter'].sudo().get_param('web.base.url') short_schema = base_url + '/r/' for match in set(re.findall(tools.HTML_TAG_URL_REGEX, html)): long_url = match[1] # Don't shorten already-shortened links if long_url.startswith(short_schema): continue # Don't shorten urls present in blacklist (aka to skip list) if blacklist and any(s in long_url for s in blacklist): continue label = (match[3] or '').strip() create_vals = dict(link_tracker_vals, url=unescape(long_url), label=unescape(label)) link = self.env['link.tracker'].search_or_create(create_vals) if link.short_url: # `str` manipulation required to support replacing "&" characters, common in urls new_href = match[0].replace(long_url, link.short_url) html = html.replace(markupsafe.Markup(match[0]), markupsafe.Markup(new_href)) return html @api.model def _shorten_links_text(self, content, link_tracker_vals, blacklist=None, base_url=None): """ Shorten links in a string content. Works like ``_shorten_links`` but targeting string content, not html. :return: updated content """ if not content: return content base_url = base_url or self.env['ir.config_parameter'].sudo().get_param('web.base.url') shortened_schema = base_url + '/r/' unsubscribe_schema = base_url + '/sms/' for original_url in set(re.findall(tools.TEXT_URL_REGEX, content)): # don't shorten already-shortened links or links towards unsubscribe page if original_url.startswith(shortened_schema) or original_url.startswith(unsubscribe_schema): continue # support blacklist items in path, like /u/ parsed = urls.url_parse(original_url, scheme='http') if blacklist and any(item in parsed.path for item in blacklist): continue create_vals = dict(link_tracker_vals, url=unescape(original_url)) link = self.env['link.tracker'].search_or_create(create_vals) if link.short_url: # Ensures we only replace the same link and not a subpart of a longer one, multiple times if applicable content = re.sub(re.escape(original_url) + r'(?![\w@:%.+&~#=/-])', link.short_url, content) return content
45.329412
3,853
747
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class UtmCampaign(models.Model): _inherit = ['utm.campaign'] _description = 'UTM Campaign' click_count = fields.Integer(string="Number of clicks generated by the campaign", compute="_compute_clicks_count") def _compute_clicks_count(self): click_data = self.env['link.tracker.click'].read_group( [('campaign_id', 'in', self.ids)], ['campaign_id'], ['campaign_id']) mapped_data = {datum['campaign_id'][0]: datum['campaign_id_count'] for datum in click_data} for campaign in self: campaign.click_count = mapped_data.get(campaign.id, 0)
35.571429
747
12,140
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import random import requests import string from lxml import html from werkzeug import urls from odoo import tools, models, fields, api, _ from odoo.exceptions import UserError from odoo.osv import expression URL_MAX_SIZE = 10 * 1024 * 1024 class LinkTracker(models.Model): """ Link trackers allow users to wrap any URL into a short URL that can be tracked by Odoo. Clicks are counter on each link. A tracker is linked to UTMs allowing to analyze marketing actions. This model is also used in mass_mailing where each link in html body is automatically converted into a short link that is tracked and integrates UTMs. """ _name = "link.tracker" _rec_name = "short_url" _description = "Link Tracker" _order="count DESC" _inherit = ["utm.mixin"] # URL info url = fields.Char(string='Target URL', required=True) absolute_url = fields.Char("Absolute URL", compute="_compute_absolute_url") short_url = fields.Char(string='Tracked URL', compute='_compute_short_url') redirected_url = fields.Char(string='Redirected URL', compute='_compute_redirected_url') short_url_host = fields.Char(string='Host of the short URL', compute='_compute_short_url_host') title = fields.Char(string='Page Title', store=True) label = fields.Char(string='Button label') # Tracking link_code_ids = fields.One2many('link.tracker.code', 'link_id', string='Codes') code = fields.Char(string='Short URL code', compute='_compute_code') link_click_ids = fields.One2many('link.tracker.click', 'link_id', string='Clicks') count = fields.Integer(string='Number of Clicks', compute='_compute_count', store=True) @api.depends("url") def _compute_absolute_url(self): for tracker in self: url = urls.url_parse(tracker.url) if url.scheme: tracker.absolute_url = tracker.url else: tracker.absolute_url = tracker.get_base_url().join(url).to_url() @api.depends('link_click_ids.link_id') def _compute_count(self): if self.ids: clicks_data = self.env['link.tracker.click'].read_group( [('link_id', 'in', self.ids)], ['link_id'], ['link_id'] ) mapped_data = {m['link_id'][0]: m['link_id_count'] for m in clicks_data} else: mapped_data = dict() for tracker in self: tracker.count = mapped_data.get(tracker.id, 0) @api.depends('code') def _compute_short_url(self): for tracker in self: tracker.short_url = urls.url_join(tracker.short_url_host, '%(code)s' % {'code': tracker.code}) def _compute_short_url_host(self): for tracker in self: tracker.short_url_host = tracker.get_base_url() + '/r/' def _compute_code(self): for tracker in self: record = self.env['link.tracker.code'].search([('link_id', '=', tracker.id)], limit=1, order='id DESC') tracker.code = record.code @api.depends('url') def _compute_redirected_url(self): """Compute the URL to which we will redirect the user. By default, add UTM values as GET parameters. But if the system parameter `link_tracker.no_external_tracking` is set, we add the UTM values in the URL *only* for URLs that redirect to the local website (base URL). """ no_external_tracking = self.env['ir.config_parameter'].sudo().get_param('link_tracker.no_external_tracking') for tracker in self: base_domain = urls.url_parse(tracker.get_base_url()).netloc parsed = urls.url_parse(tracker.url) if no_external_tracking and parsed.netloc and parsed.netloc != base_domain: tracker.redirected_url = parsed.to_url() continue utms = {} for key, field_name, cook in self.env['utm.mixin'].tracking_fields(): field = self._fields[field_name] attr = getattr(tracker, field_name) if field.type == 'many2one': attr = attr.name if attr: utms[key] = attr utms.update(parsed.decode_query()) tracker.redirected_url = parsed.replace(query=urls.url_encode(utms)).to_url() @api.model @api.depends('url') def _get_title_from_url(self, url): try: head = requests.head(url, allow_redirects=True, timeout=5) if ( int(head.headers.get('Content-Length', 0)) > URL_MAX_SIZE or 'text/html' not in head.headers.get('Content-Type', 'text/html') ): return url # HTML parser can work with a part of page, so ask server to limit downloading to 50 KB page = requests.get(url, timeout=5, headers={"range": "bytes=0-50000"}) p = html.fromstring(page.text.encode('utf-8'), parser=html.HTMLParser(encoding='utf-8')) title = p.find('.//title').text except: title = url return title @api.constrains('url', 'campaign_id', 'medium_id', 'source_id') def _check_unicity(self): """Check that the link trackers are unique.""" # build a query to fetch all needed link trackers at once search_query = expression.OR([ expression.AND([ [('url', '=', tracker.url)], [('campaign_id', '=', tracker.campaign_id.id)], [('medium_id', '=', tracker.medium_id.id)], [('source_id', '=', tracker.source_id.id)], ]) for tracker in self ]) # Can not be implemented with a SQL constraint because we want to care about null values. all_link_trackers = self.search(search_query) # check for unicity for tracker in self: if all_link_trackers.filtered( lambda l: l.url == tracker.url and l.campaign_id == tracker.campaign_id and l.medium_id == tracker.medium_id and l.source_id == tracker.source_id ) != tracker: raise UserError(_( 'Link Tracker values (URL, campaign, medium and source) must be unique (%s, %s, %s, %s).', tracker.url, tracker.campaign_id.name, tracker.medium_id.name, tracker.source_id.name, )) @api.model_create_multi def create(self, vals_list): vals_list = [vals.copy() for vals in vals_list] for vals in vals_list: if 'url' not in vals: raise ValueError(_('Creating a Link Tracker without URL is not possible')) vals['url'] = tools.validate_url(vals['url']) if not vals.get('title'): vals['title'] = self._get_title_from_url(vals['url']) # Prevent the UTMs to be set by the values of UTM cookies for (__, fname, __) in self.env['utm.mixin'].tracking_fields(): if fname not in vals: vals[fname] = False links = super(LinkTracker, self).create(vals_list) link_tracker_codes = self.env['link.tracker.code']._get_random_code_strings(len(vals_list)) self.env['link.tracker.code'].sudo().create([ { 'code': code, 'link_id': link.id, } for link, code in zip(links, link_tracker_codes) ]) return links @api.model def search_or_create(self, vals): if 'url' not in vals: raise ValueError(_('Creating a Link Tracker without URL is not possible')) vals['url'] = tools.validate_url(vals['url']) search_domain = [ (fname, '=', value) for fname, value in vals.items() if fname in ['url', 'campaign_id', 'medium_id', 'source_id'] ] result = self.search(search_domain, limit=1) if result: return result return self.create(vals) @api.model def convert_links(self, html, vals, blacklist=None): raise NotImplementedError('Moved on mail.render.mixin') def _convert_links_text(self, body, vals, blacklist=None): raise NotImplementedError('Moved on mail.render.mixin') def action_view_statistics(self): action = self.env['ir.actions.act_window']._for_xml_id('link_tracker.link_tracker_click_action_statistics') action['domain'] = [('link_id', '=', self.id)] action['context'] = dict(self._context, create=False) return action def action_visit_page(self): return { 'name': _("Visit Webpage"), 'type': 'ir.actions.act_url', 'url': self.url, 'target': 'new', } @api.model def recent_links(self, filter, limit): if filter == 'newest': return self.search_read([], order='create_date DESC, id DESC', limit=limit) elif filter == 'most-clicked': return self.search_read([('count', '!=', 0)], order='count DESC', limit=limit) elif filter == 'recently-used': return self.search_read([('count', '!=', 0)], order='write_date DESC, id DESC', limit=limit) else: return {'Error': "This filter doesn't exist."} @api.model def get_url_from_code(self, code): code_rec = self.env['link.tracker.code'].sudo().search([('code', '=', code)]) if not code_rec: return None return code_rec.link_id.redirected_url class LinkTrackerCode(models.Model): _name = "link.tracker.code" _description = "Link Tracker Code" _rec_name = 'code' code = fields.Char(string='Short URL Code', required=True, store=True) link_id = fields.Many2one('link.tracker', 'Link', required=True, ondelete='cascade') _sql_constraints = [ ('code', 'unique( code )', 'Code must be unique.') ] @api.model def _get_random_code_strings(self, n=1): size = 3 while True: code_propositions = [ ''.join(random.choices(string.ascii_letters + string.digits, k=size)) for __ in range(n) ] if len(set(code_propositions)) != n or self.search([('code', 'in', code_propositions)]): size += 1 else: return code_propositions class LinkTrackerClick(models.Model): _name = "link.tracker.click" _rec_name = "link_id" _description = "Link Tracker Click" campaign_id = fields.Many2one( 'utm.campaign', 'UTM Campaign', related="link_id.campaign_id", store=True) link_id = fields.Many2one( 'link.tracker', 'Link', index=True, required=True, ondelete='cascade') ip = fields.Char(string='Internet Protocol') country_id = fields.Many2one('res.country', 'Country') def _prepare_click_values_from_route(self, **route_values): click_values = dict((fname, route_values[fname]) for fname in self._fields if fname in route_values) if not click_values.get('country_id') and route_values.get('country_code'): click_values['country_id'] = self.env['res.country'].search([('code', '=', route_values['country_code'])], limit=1).id return click_values @api.model def add_click(self, code, **route_values): """ Main API to add a click on a link. """ tracker_code = self.env['link.tracker.code'].search([('code', '=', code)]) if not tracker_code: return None ip = route_values.get('ip', False) existing = self.search_count(['&', ('link_id', '=', tracker_code.link_id.id), ('ip', '=', ip)]) if existing: return None route_values['link_id'] = tracker_code.link_id.id click_values = self._prepare_click_values_from_route(**route_values) return self.create(click_values)
38.417722
12,140
740
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request class LinkTracker(http.Controller): @http.route('/r/<string:code>', type='http', auth='public', website=True) def full_url_redirect(self, code, **post): country_code = request.session.geoip and request.session.geoip.get('country_code') or False request.env['link.tracker.click'].sudo().add_click( code, ip=request.httprequest.remote_addr, country_code=country_code ) redirect_url = request.env['link.tracker'].get_url_from_code(code) return request.redirect(redirect_url or '', code=301, local=False)
38.947368
740
671
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Product Availability Notifications', 'category': 'Website/Website', 'summary': 'Bridge module for Website sale comparison and wishlist', 'description': """ It allows for comparing products from the wishlist """, 'depends': [ 'website_sale_comparison', 'website_sale_wishlist', ], 'data': [ 'views/templates.xml', ], 'assets': { 'web.assets_frontend': [ 'website_sale_comparison_wishlist/static/src/**/*', ], }, 'auto_install': True, 'license': 'LGPL-3', }
26.84
671
742
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Hr Recruitment Interview Forms", 'version': '1.0', 'category': 'Human Resources', 'summary': 'Surveys', 'description': """ Use interview forms during recruitment process. This module is integrated with the survey module to allow you to define interviews for different jobs. """, 'depends': ['survey', 'hr_recruitment'], 'data': [ 'security/hr_recruitment_survey_security.xml', 'views/hr_job_views.xml', 'views/hr_applicant_views.xml', 'views/res_config_setting_views.xml', ], 'demo': [ 'data/survey_demo.xml', 'data/hr_job_demo.xml', ], 'auto_install': False, 'license': 'LGPL-3', }
29.68
742
3,004
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, Form class TestRecruitmentSurvey(common.SingleTransactionCase): @classmethod def setUpClass(cls): super(TestRecruitmentSurvey, cls).setUpClass() # Create some sample data to avoid demo data cls.department_admins = cls.env['hr.department'].create({'name': 'Admins'}) cls.survey_sysadmin = cls.env['survey.survey'].create({'title': 'Questions for Sysadmin job offer'}) # We need this, so that when we send survey, we don't get an error cls.question_ft = cls.env['survey.question'].create({ 'title': 'Test Free Text', 'survey_id': cls.survey_sysadmin.id, 'sequence': 2, 'question_type': 'text_box', }) cls.job = cls.env['hr.job'].create({ 'name': 'Technical worker', 'survey_id': cls.survey_sysadmin.id, }) cls.job_sysadmin = cls.env['hr.applicant'].create({ 'name': 'Technical worker', 'partner_name': 'Jane Doe', 'email_from': '[email protected]', 'department_id': cls.department_admins.id, 'description': 'A nice Sys Admin job offer !', 'job_id': cls.job.id, }) def test_send_survey(self): # We ensure that response is False because we don't know test order self.job_sysadmin.response_id = False Answer = self.env['survey.user_input'] answers = Answer.search([('survey_id', '=', self.survey_sysadmin.id)]) answers.unlink() self.survey_sysadmin.write({'access_mode': 'public', 'users_login_required': False}) action = self.job_sysadmin.action_send_survey() invite_form = Form(self.env[action['res_model']].with_context({ **action['context'], })) invite = invite_form.save() invite.action_invite() self.assertEqual(invite.applicant_id, self.job_sysadmin) self.assertNotEqual(self.job_sysadmin.response_id.id, False) answers = Answer.search([('survey_id', '=', self.survey_sysadmin.id)]) self.assertEqual(len(answers), 1) self.assertEqual(self.job_sysadmin.response_id, answers) self.assertEqual( set(answers.mapped('email')), set([self.job_sysadmin.email_from])) def test_print_survey(self): # We ensure that response is False because we don't know test order self.job_sysadmin.response_id = False action_print = self.job_sysadmin.action_print_survey() self.assertEqual(action_print['type'], 'ir.actions.act_url') self.job_sysadmin.response_id = self.env['survey.user_input'].create({'survey_id': self.survey_sysadmin.id}) action_print_with_response = self.job_sysadmin.action_print_survey() self.assertIn(self.job_sysadmin.response_id.access_token, action_print_with_response['url'])
42.914286
3,004
1,043
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ class Job(models.Model): _inherit = "hr.job" survey_id = fields.Many2one( 'survey.survey', "Interview Form", help="Choose an interview form for this job position and you will be able to print/answer this interview from all applicants who apply for this job") def action_print_survey(self): return self.survey_id.action_print_survey() def action_new_survey(self): self.ensure_one() survey = self.env['survey.survey'].create({ 'title': _("Interview Form : %s") % self.name, }) self.write({'survey_id': survey.id}) action = { 'name': _('Survey'), 'view_mode': 'form,tree', 'res_model': 'survey.survey', 'type': 'ir.actions.act_window', 'context': {'form_view_initial_mode': 'edit'}, 'res_id': survey.id, } return action
32.59375
1,043
2,032
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.tools.misc import clean_context class SurveyInvite(models.TransientModel): _inherit = "survey.invite" applicant_id = fields.Many2one('hr.applicant', string='Applicant') def action_invite(self): self.ensure_one() if self.applicant_id: survey = self.survey_id.with_context(clean_context(self.env.context)) if not self.applicant_id.response_id: self.applicant_id.write({ 'response_id': survey._create_answer(partner=self.applicant_id.partner_id).id }) partner = self.applicant_id.partner_id survey_link = '<a href="#" data-oe-model="%s" data-oe-id="%s">%s</a>' % (survey._name, survey.id, survey.title) partner_link = '<a href="#" data-oe-model="%s" data-oe-id="%s">%s</a>' % (partner._name, partner.id, partner.name) content = _('The survey %(survey_link)s has been sent to %(partner_link)s', survey_link=survey_link, partner_link=partner_link) body = '<p>%s</p>' % content self.applicant_id.message_post(body=body) return super().action_invite() class SurveyUserInput(models.Model): _inherit = "survey.user_input" applicant_id = fields.One2many('hr.applicant', 'response_id', string='Applicant') def _mark_done(self): odoobot = self.env.ref('base.partner_root') for user_input in self: if user_input.applicant_id: body = _('The applicant "%s" has finished the survey.', user_input.applicant_id.partner_name) user_input.applicant_id.message_post(body=body, author_id=odoobot.id) return super()._mark_done() @api.model_create_multi def create(self, values_list): if 'default_applicant_id' in self.env.context: self = self.with_context(default_applicant_id=False) return super().create(values_list)
42.333333
2,032
1,527
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ from odoo.exceptions import UserError class Applicant(models.Model): _inherit = "hr.applicant" survey_id = fields.Many2one('survey.survey', related='job_id.survey_id', string="Survey", readonly=True) response_id = fields.Many2one('survey.user_input', "Response", ondelete="set null", copy=False) response_state = fields.Selection(related='response_id.state', readonly=True) def action_print_survey(self): """ If response is available then print this response otherwise print survey form (print template of the survey) """ self.ensure_one() return self.survey_id.action_print_survey(answer=self.response_id) def action_send_survey(self): self.ensure_one() # if an applicant does not already has associated partner_id create it if not self.partner_id: if not self.partner_name: raise UserError(_('You must define a Contact Name for this applicant.')) self.partner_id = self.env['res.partner'].create({ 'is_company': False, 'type': 'private', 'name': self.partner_name, 'email': self.email_from, 'phone': self.partner_phone, 'mobile': self.partner_mobile }) return self.survey_id.with_context(default_applicant_id=self.id, default_partner_ids=self.partner_id.ids).action_send_survey()
44.911765
1,527
251
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Sale Mrp Margin", 'category': 'Sales/Sales', 'version': '0.1', 'description': 'Handle BoM prices to compute sale margin.', 'depends': ['sale_mrp', 'sale_stock_margin'], 'license': 'LGPL-3', }
27.888889
251
2,053
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_mrp.tests import test_sale_mrp_flow from odoo.tests import common, Form @common.tagged('post_install', '-at_install') class TestSaleMrpFlow(test_sale_mrp_flow.TestSaleMrpFlow): def test_kit_cost_calculation(self): """ Check that the average cost price is computed correctly after SO confirmation: BOM 1: - 1 unit of “super kit”: - 2 units of “component a” BOM 2: - 1 unit of “component a”: - 3 units of "component b" 1 unit of "component b" = $10 1 unit of "super kit" = 2 * 3 * $10 = *$60 """ super_kit = self._cls_create_product('Super Kit', self.uom_unit) (super_kit + self.component_a + self.component_b).categ_id.property_cost_method = 'average' self.env['mrp.bom'].create({ 'product_tmpl_id': self.component_a.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, { 'product_id': self.component_b.id, 'product_qty': 3.0, })] }) self.env['mrp.bom'].create({ 'product_tmpl_id': super_kit.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, { 'product_id': self.component_a.id, 'product_qty': 2.0, })] }) self.component_b.standard_price = 10 self.component_a.button_bom_cost() super_kit.button_bom_cost() so_form = Form(self.env['sale.order']) so_form.partner_id = self.partner_a with so_form.order_line.new() as line: line.product_id = super_kit so = so_form.save() self.assertEqual(so.order_line.purchase_price, 60) so.action_confirm() self.assertEqual(so.order_line.purchase_price, 60)
39.25
2,041
624
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Free Delivery with Coupon on eCommerce", 'summary': """Allows to offer free shippings in coupon reward on eCommerce""", 'description': """Allows to offer free shippings in coupon reward on eCommerce""", 'category': 'Website/Website', 'version': '1.0', 'depends': ['website_sale_delivery', 'sale_coupon_delivery'], 'auto_install': True, 'assets': { 'web.assets_frontend': [ 'website_sale_coupon_delivery/static/**/*', ], }, 'license': 'LGPL-3', }
36.705882
624
2,446
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import http from odoo.addons.website_sale_delivery.controllers.main import WebsiteSaleDelivery from odoo.http import request class WebsiteSaleCouponDelivery(WebsiteSaleDelivery): @http.route() def update_eshop_carrier(self, **post): Monetary = request.env['ir.qweb.field.monetary'] result = super(WebsiteSaleCouponDelivery, self).update_eshop_carrier(**post) order = request.website.sale_get_order() free_shipping_lines = None if order: order.recompute_coupon_lines() order.validate_taxes_on_sales_order() free_shipping_lines = order._get_free_shipping_lines() if free_shipping_lines: currency = order.currency_id amount_free_shipping = sum(free_shipping_lines.mapped('price_subtotal')) result.update({ 'new_amount_delivery': Monetary.value_to_html(0.0, {'display_currency': currency}), 'new_amount_untaxed': Monetary.value_to_html(order.amount_untaxed, {'display_currency': currency}), 'new_amount_tax': Monetary.value_to_html(order.amount_tax, {'display_currency': currency}), 'new_amount_total': Monetary.value_to_html(order.amount_total, {'display_currency': currency}), 'new_amount_order_discounted': Monetary.value_to_html(order.reward_amount - amount_free_shipping, {'display_currency': currency}), 'new_amount_total_raw': order.amount_total, }) return result @http.route() def cart_carrier_rate_shipment(self, carrier_id, **kw): Monetary = request.env['ir.qweb.field.monetary'] order = request.website.sale_get_order(force_create=True) free_shipping_lines = order._get_free_shipping_lines() # Avoid computing carrier price delivery is free (coupon). It means if # the carrier has error (eg 'delivery only for Belgium') it will show # Free until the user clicks on it. if free_shipping_lines: return { 'carrier_id': carrier_id, 'status': True, 'is_free_delivery': True, 'new_amount_delivery': Monetary.value_to_html(0.0, {'display_currency': order.currency_id}), 'error_message': None, } return super(WebsiteSaleCouponDelivery, self).cart_carrier_rate_shipment(carrier_id, **kw)
48.92
2,446
784
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Customer References', 'category': 'Website/Website', 'summary': 'Publish your customer references', 'version': '1.0', 'description': """ Publish your customers as business references on your website to attract new potential prospects. """, 'depends': [ 'website_crm_partner_assign', 'website_partner', 'website_google_map', ], 'demo': [ 'data/res_partner_demo.xml', ], 'data': [ 'views/website_customer_templates.xml', 'views/res_partner_views.xml', 'security/ir.model.access.csv', 'security/ir_rule.xml', ], 'installable': True, 'license': 'LGPL-3', }
28
784
502
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ from odoo.addons.http_routing.models.ir_http import url_for class Website(models.Model): _inherit = "website" def get_suggested_controllers(self): suggested_controllers = super(Website, self).get_suggested_controllers() suggested_controllers.append((_('References'), url_for('/customers'), 'website_customer')) return suggested_controllers
35.857143
502
1,274
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 Partner(models.Model): _inherit = 'res.partner' website_tag_ids = fields.Many2many('res.partner.tag', 'res_partner_res_partner_tag_rel', 'partner_id', 'tag_id', string='Website tags') def get_backend_menu_id(self): return self.env.ref('contacts.menu_contacts').id class Tags(models.Model): _name = 'res.partner.tag' _description = 'Partner Tags - These tags can be used on website to find customers by sector, or ...' _inherit = 'website.published.mixin' @api.model def get_selection_class(self): classname = ['default', 'primary', 'success', 'warning', 'danger'] return [(x, str.title(x)) for x in classname] name = fields.Char('Category Name', required=True, translate=True) partner_ids = fields.Many2many('res.partner', 'res_partner_res_partner_tag_rel', 'tag_id', 'partner_id', string='Partners') classname = fields.Selection('get_selection_class', 'Class', default='default', help="Bootstrap class to customize the color", required=True) active = fields.Boolean('Active', default=True) def _default_is_published(self): return True
37.470588
1,274
6,664
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import werkzeug.urls from odoo import http from odoo.addons.http_routing.models.ir_http import unslug, slug from odoo.addons.website.models.ir_http import sitemap_qs2dom from odoo.tools.translate import _ from odoo.http import request class WebsiteCustomer(http.Controller): _references_per_page = 20 def sitemap_industry(env, rule, qs): if not qs or qs.lower() in '/customers': yield {'loc': '/customers'} Industry = env['res.partner.industry'] dom = sitemap_qs2dom(qs, '/customers/industry', Industry._rec_name) for industry in Industry.search(dom): loc = '/customers/industry/%s' % slug(industry) if not qs or qs.lower() in loc: yield {'loc': loc} dom = [('website_published', '=', True), ('assigned_partner_id', '!=', False), ('country_id', '!=', False)] dom += sitemap_qs2dom(qs, '/customers/country') countries = env['res.partner'].sudo().read_group(dom, ['id', 'country_id'], groupby='country_id') for country in countries: loc = '/customers/country/%s' % slug(country['country_id']) if not qs or qs.lower() in loc: yield {'loc': loc} @http.route([ '/customers', '/customers/page/<int:page>', '/customers/country/<model("res.country"):country>', '/customers/country/<model("res.country"):country>/page/<int:page>', '/customers/industry/<model("res.partner.industry"):industry>', '/customers/industry/<model("res.partner.industry"):industry>/page/<int:page>', '/customers/industry/<model("res.partner.industry"):industry>/country/<model("res.country"):country>', '/customers/industry/<model("res.partner.industry"):industry>/country/<model("res.country"):country>/page/<int:page>', ], type='http', auth="public", website=True, sitemap=sitemap_industry) def customers(self, country=None, industry=None, page=0, **post): Tag = request.env['res.partner.tag'] Partner = request.env['res.partner'] search_value = post.get('search') domain = [('website_published', '=', True), ('assigned_partner_id', '!=', False)] if search_value: domain += [ '|', '|', ('name', 'ilike', search_value), ('website_description', 'ilike', search_value), ('industry_id.name', 'ilike', search_value), ] tag_id = post.get('tag_id') if tag_id: tag_id = unslug(tag_id)[1] or 0 domain += [('website_tag_ids', 'in', tag_id)] # group by industry, based on customers found with the search(domain) industries = Partner.sudo().read_group(domain, ["id", "industry_id"], groupby="industry_id", orderby="industry_id") partners_count = Partner.sudo().search_count(domain) if industry: domain.append(('industry_id', '=', industry.id)) if industry.id not in (x['industry_id'][0] for x in industries if x['industry_id']): if industry.exists(): industries.append({ 'industry_id_count': 0, 'industry_id': (industry.id, industry.name) }) industries.sort(key=lambda d: (d.get('industry_id') or (0, ''))[1]) industries.insert(0, { 'industry_id_count': partners_count, 'industry_id': (0, _("All Industries")) }) # group by country, based on customers found with the search(domain) countries = Partner.sudo().read_group(domain, ["id", "country_id"], groupby="country_id", orderby="country_id") country_count = Partner.sudo().search_count(domain) if country: domain += [('country_id', '=', country.id)] if country.id not in (x['country_id'][0] for x in countries if x['country_id']): if country.exists(): countries.append({ 'country_id_count': 0, 'country_id': (country.id, country.name) }) countries.sort(key=lambda d: (d['country_id'] or (0, ""))[1]) countries.insert(0, { 'country_id_count': country_count, 'country_id': (0, _("All Countries")) }) # search customers to display partner_count = Partner.sudo().search_count(domain) # pager url = '/customers' if industry: url += '/industry/%s' % industry.id if country: url += '/country/%s' % country.id pager = request.website.pager( url=url, total=partner_count, page=page, step=self._references_per_page, scope=7, url_args=post ) partners = Partner.sudo().search(domain, offset=pager['offset'], limit=self._references_per_page) google_map_partner_ids = ','.join(str(it) for it in partners.ids) google_maps_api_key = request.website.google_maps_api_key tags = Tag.search([('website_published', '=', True), ('partner_ids', 'in', partners.ids)], order='classname, name ASC') tag = tag_id and Tag.browse(tag_id) or False values = { 'countries': countries, 'current_country_id': country.id if country else 0, 'current_country': country or False, 'industries': industries, 'current_industry_id': industry.id if industry else 0, 'current_industry': industry or False, 'partners': partners, 'google_map_partner_ids': google_map_partner_ids, 'pager': pager, 'post': post, 'search_path': "?%s" % werkzeug.urls.url_encode(post), 'tag': tag, 'tags': tags, 'google_maps_api_key': google_maps_api_key, } return request.render("website_customer.index", values) # Do not use semantic controller due to SUPERUSER_ID @http.route(['/customers/<partner_id>'], type='http', auth="public", website=True) def partners_detail(self, partner_id, **post): _, partner_id = unslug(partner_id) if partner_id: partner = request.env['res.partner'].sudo().browse(partner_id) if partner.exists() and partner.website_published: values = {} values['main_object'] = values['partner'] = partner return request.render("website_customer.details", values) return self.customers(**post)
43.842105
6,664
957
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "HR Attendance Holidays", 'summary': """Attendance Holidays""", 'category': 'Human Resources', 'description': """ Convert employee's extra hours to leave allocations. """, 'version': '1.0', 'depends': ['hr_attendance', 'hr_holidays'], 'auto_install': True, 'data': [ 'security/hr_holidays_attendance_security.xml', 'views/hr_leave_allocation_views.xml', 'views/hr_leave_type_views.xml', 'views/hr_leave_views.xml', 'views/hr_employee_views.xml', 'views/res_users_views.xml', 'data/hr_holidays_attendance_data.xml', ], 'demo': [ 'data/hr_holidays_attendance_demo.xml', ], 'assets': { 'web.assets_qweb': [ 'hr_holidays_attendance/static/src/xml/time_off_calendar.xml', ], }, 'license': 'LGPL-3', }
30.870968
957
10,309
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from odoo.tests import new_test_user from odoo.tests.common import TransactionCase, tagged from odoo.exceptions import AccessError, ValidationError import time @tagged('post_install', '-at_install', 'holidays_attendance') class TestHolidaysOvertime(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.company = cls.env['res.company'].create({ 'name': 'SweatChipChop Inc.', 'hr_attendance_overtime': True, 'overtime_start_date': datetime(2021, 1, 1), }) cls.user = new_test_user(cls.env, login='user', groups='base.group_user,hr_attendance.group_hr_attendance', company_id=cls.company.id).with_company(cls.company) cls.user_manager = new_test_user(cls.env, login='manager', groups='base.group_user,hr_holidays.group_hr_holidays_user', company_id=cls.company.id).with_company(cls.company) cls.manager = cls.env['hr.employee'].create({ 'name': 'Dominique', 'user_id': cls.user_manager.id, 'company_id': cls.company.id, }) cls.employee = cls.env['hr.employee'].create({ 'name': 'Barnabé', 'user_id': cls.user.id, 'parent_id': cls.manager.id, 'company_id': cls.company.id, }) cls.leave_type_no_alloc = cls.env['hr.leave.type'].create({ 'name': 'Overtime Compensation No Allocation', 'company_id': cls.company.id, 'requires_allocation': 'no', 'overtime_deductible': True, }) cls.leave_type_employee_allocation = cls.env['hr.leave.type'].create({ 'name': 'Overtime Compensation Employee Allocation', 'company_id': cls.company.id, 'requires_allocation': 'yes', 'employee_requests': 'yes', 'overtime_deductible': True, }) cls.leave_type_manager_alloc = cls.env['hr.leave.type'].create({ 'name': 'Overtime Compensation Manager Allocation', 'company_id': cls.company.id, 'requires_allocation': 'yes', 'employee_requests': 'no', 'allocation_validation_type': 'set', 'overtime_deductible': True, }) def new_attendance(self, check_in, check_out=False): return self.env['hr.attendance'].create({ 'employee_id': self.employee.id, 'check_in': check_in, 'check_out': check_out, }) def test_deduct_button_visibility(self): with self.with_user('user'): self.assertFalse(self.user.request_overtime, 'Button should not be visible') self.new_attendance(check_in=datetime(2021, 1, 2, 8), check_out=datetime(2021, 1, 2, 18)) self.assertEqual(self.user.total_overtime, 10, 'Should have 10 hours of overtime') self.assertTrue(self.user.request_overtime, 'Button should be visible') def test_check_overtime(self): with self.with_user('user'): self.assertEqual(self.user.total_overtime, 0, 'No overtime') with self.assertRaises(ValidationError), self.cr.savepoint(): self.env['hr.leave'].create({ 'name': 'no overtime', 'employee_id': self.employee.id, 'holiday_status_id': self.leave_type_no_alloc.id, 'number_of_days': 1, 'date_from': datetime(2021, 1, 4), 'date_to': datetime(2021, 1, 5), 'state': 'draft', }) self.new_attendance(check_in=datetime(2021, 1, 2, 8), check_out=datetime(2021, 1, 2, 16)) self.assertEqual(self.employee.total_overtime, 8, 'Should have 8 hours of overtime') leave = self.env['hr.leave'].create({ 'name': 'no overtime', 'employee_id': self.employee.id, 'holiday_status_id': self.leave_type_no_alloc.id, 'number_of_days': 1, 'date_from': datetime(2021, 1, 4), 'date_to': datetime(2021, 1, 5), }) # The employee doesn't have the right to read the overtime from the leave overtime = leave.sudo().overtime_id.with_user(self.user) # An employee cannot delete an overtime adjustment with self.assertRaises(AccessError), self.cr.savepoint(): overtime.unlink() # ... nor change its duration with self.assertRaises(AccessError), self.cr.savepoint(): overtime.duration = 8 def test_leave_adjust_overtime(self): self.new_attendance(check_in=datetime(2021, 1, 2, 8), check_out=datetime(2021, 1, 2, 16)) self.assertEqual(self.employee.total_overtime, 8, 'Should have 8 hours of overtime') leave = self.env['hr.leave'].create({ 'name': 'no overtime', 'employee_id': self.employee.id, 'holiday_status_id': self.leave_type_no_alloc.id, 'number_of_days': 1, 'date_from': datetime(2021, 1, 4), 'date_to': datetime(2021, 1, 5), }) self.assertTrue(leave.overtime_id.adjustment, "An adjustment overtime should be created") self.assertEqual(leave.overtime_id.duration, -8) self.assertEqual(self.employee.total_overtime, 0) leave.action_refuse() self.assertFalse(leave.overtime_id.exists(), "Overtime should be deleted") self.assertEqual(self.employee.total_overtime, 8) leave.action_draft() self.assertTrue(leave.overtime_id.exists(), "Overtime should be created") self.assertEqual(self.employee.total_overtime, 0) overtime = leave.overtime_id leave.unlink() self.assertFalse(overtime.exists(), "Overtime should be deleted along with the leave") self.assertEqual(self.employee.total_overtime, 8) def test_leave_check_overtime_write(self): self.new_attendance(check_in=datetime(2021, 1, 2, 8), check_out=datetime(2021, 1, 2, 16)) self.new_attendance(check_in=datetime(2021, 1, 3, 8), check_out=datetime(2021, 1, 3, 16)) self.assertEqual(self.employee.total_overtime, 16) leave = self.env['hr.leave'].create({ 'name': 'no overtime', 'employee_id': self.employee.id, 'holiday_status_id': self.leave_type_no_alloc.id, 'number_of_days': 1, 'date_from': datetime(2021, 1, 4), 'date_to': datetime(2021, 1, 5), }) self.assertEqual(self.employee.total_overtime, 8) leave.date_to = datetime(2021, 1, 6) self.assertEqual(self.employee.total_overtime, 0) with self.assertRaises(ValidationError), self.cr.savepoint(): leave.date_to = datetime(2021, 1, 7) leave.date_to = datetime(2021, 1, 5) self.assertEqual(self.employee.total_overtime, 8) def test_employee_create_allocation(self): with self.with_user('user'): self.assertEqual(self.employee.total_overtime, 0) with self.assertRaises(ValidationError), self.cr.savepoint(): self.env['hr.leave.allocation'].create({ 'name': 'test allocation', 'holiday_status_id': self.leave_type_employee_allocation.id, 'employee_id': self.employee.id, 'number_of_days': 1, 'state': 'draft', 'date_from': time.strftime('%Y-1-1'), 'date_to': time.strftime('%Y-12-31'), }) self.new_attendance(check_in=datetime(2021, 1, 2, 8), check_out=datetime(2021, 1, 2, 16)) self.assertAlmostEqual(self.employee.total_overtime, 8, 'Should have 8 hours of overtime') allocation = self.env['hr.leave.allocation'].create({ 'name': 'test allocation', 'holiday_status_id': self.leave_type_employee_allocation.id, 'employee_id': self.employee.id, 'number_of_days': 1, 'state': 'draft', 'date_from': time.strftime('%Y-1-1'), 'date_to': time.strftime('%Y-12-31'), }) allocation.action_confirm() self.assertEqual(self.employee.total_overtime, 0) leave_type = self.env['hr.leave.type'].sudo().create({ 'name': 'Overtime Compensation Employee Allocation', 'company_id': self.company.id, 'requires_allocation': 'yes', 'employee_requests': 'yes', 'overtime_deductible': False, }) # User can request another allocation even without overtime allocation2 = self.env['hr.leave.allocation'].create({ 'name': 'test allocation', 'holiday_status_id': leave_type.id, 'employee_id': self.employee.id, 'number_of_days': 1, 'state': 'draft', 'date_from': time.strftime('%Y-1-1'), 'date_to': time.strftime('%Y-12-31'), }) allocation2.action_confirm() def test_allocation_check_overtime_write(self): self.new_attendance(check_in=datetime(2021, 1, 2, 8), check_out=datetime(2021, 1, 2, 16)) self.new_attendance(check_in=datetime(2021, 1, 3, 8), check_out=datetime(2021, 1, 3, 16)) self.assertEqual(self.employee.total_overtime, 16, 'Should have 16 hours of overtime') alloc = self.env['hr.leave.allocation'].create({ 'name': 'test allocation', 'holiday_status_id': self.leave_type_employee_allocation.id, 'employee_id': self.employee.id, 'number_of_days': 1, 'state': 'draft', 'date_from': time.strftime('%Y-1-1'), 'date_to': time.strftime('%Y-12-31'), }) self.assertEqual(self.employee.total_overtime, 8) with self.assertRaises(ValidationError), self.cr.savepoint(): alloc.number_of_days = 3 alloc.number_of_days = 2 self.assertEqual(self.employee.total_overtime, 0)
44.051282
10,308
5,196
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from datetime import timedelta from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.tools import float_round class HRLeave(models.Model): _inherit = 'hr.leave' overtime_id = fields.Many2one('hr.attendance.overtime', string='Extra Hours', groups='hr_holidays.group_hr_holidays_user') employee_overtime = fields.Float(related='employee_id.total_overtime') overtime_deductible = fields.Boolean(compute='_compute_overtime_deductible') @api.depends('holiday_status_id') def _compute_overtime_deductible(self): for leave in self: leave.overtime_deductible = leave.holiday_status_id.overtime_deductible and leave.holiday_status_id.requires_allocation == 'no' @api.model_create_multi def create(self, vals_list): res = super().create(vals_list) self._check_overtime_deductible(res) return res def write(self, vals): res = super().write(vals) fields_to_check = {'number_of_days', 'date_from', 'date_to', 'state', 'employee_id', 'holiday_status_id'} if not any(field for field in fields_to_check if field in vals): return res if vals.get('holiday_status_id'): self._check_overtime_deductible(self) #User may not have access to overtime_id field for leave in self.sudo().filtered('overtime_id'): # It must always be possible to refuse leave based on overtime if vals.get('state') in ['refuse']: continue employee = leave.employee_id duration = leave.number_of_hours_display overtime_duration = leave.overtime_id.sudo().duration if overtime_duration != duration: if duration > employee.total_overtime - overtime_duration: raise ValidationError(_('The employee does not have enough extra hours to extend this leave.')) leave.overtime_id.sudo().duration = -1 * duration return res def _check_overtime_deductible(self, leaves): # If the type of leave is overtime deductible, we have to check that the employee has enough extra hours for leave in leaves: if not leave.overtime_deductible: continue employee = leave.employee_id.sudo() duration = leave.number_of_hours_display if duration > employee.total_overtime: if employee.user_id == self.env.user: raise ValidationError(_('You do not have enough extra hours to request this leave')) raise ValidationError(_('The employee does not have enough extra hours to request this leave.')) if not leave.overtime_id: leave.sudo().overtime_id = self.env['hr.attendance.overtime'].sudo().create({ 'employee_id': employee.id, 'date': fields.Date.today(), 'adjustment': True, 'duration': -1 * duration, }) def action_draft(self): overtime_leaves = self.filtered('overtime_deductible') if any([l.employee_overtime < float_round(l.number_of_hours_display, 2) for l in overtime_leaves]): if self.employee_id.user_id.id == self.env.user.id: raise ValidationError(_('You do not have enough extra hours to request this leave')) raise ValidationError(_('The employee does not have enough extra hours to request this leave.')) res = super().action_draft() overtime_leaves.overtime_id.sudo().unlink() for leave in overtime_leaves: overtime = self.env['hr.attendance.overtime'].sudo().create({ 'employee_id': leave.employee_id.id, 'date': fields.Date.today(), 'adjustment': True, 'duration': -1 * leave.number_of_hours_display }) leave.sudo().overtime_id = overtime.id return res def action_refuse(self): res = super().action_refuse() self.sudo().overtime_id.unlink() return res def _validate_leave_request(self): super()._validate_leave_request() self._update_leaves_overtime() def _remove_resource_leave(self): res = super()._remove_resource_leave() self._update_leaves_overtime() return res def _update_leaves_overtime(self): employee_dates = defaultdict(set) for leave in self: if leave.employee_id and leave.employee_company_id.hr_attendance_overtime: for d in range((leave.date_to - leave.date_from).days + 1): employee_dates[leave.employee_id].add(self.env['hr.attendance']._get_day_start_and_day(leave.employee_id, leave.date_from + timedelta(days=d))) if employee_dates: self.env['hr.attendance']._update_overtime(employee_dates) def unlink(self): # TODO master change to ondelete self.sudo().overtime_id.unlink() return super().unlink()
45.182609
5,196
1,160
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 ResCompany(models.Model): _inherit = 'res.company' @api.model def _check_extra_hours_time_off(self): extra_hours_time_off_type = self.env.ref('hr_holidays_attendance.holiday_status_extra_hours', raise_if_not_found=False) if not extra_hours_time_off_type: return all_companies = self.env['res.company'].sudo().search([]) # Unarchive time of type if the feature is enabled if any(company.hr_attendance_overtime and not extra_hours_time_off_type.active for company in all_companies): extra_hours_time_off_type.toggle_active() # Archive time of type if the feature is disabled for all the company if all(not company.hr_attendance_overtime and extra_hours_time_off_type.active for company in all_companies): extra_hours_time_off_type.toggle_active() def write(self, vals): res = super().write(vals) if 'hr_attendance_overtime' in vals: self._check_extra_hours_time_off() return res
42.962963
1,160
4,163
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.tools import float_round from odoo.osv import expression class HolidaysAllocation(models.Model): _inherit = 'hr.leave.allocation' def default_get(self, fields): res = super().default_get(fields) if 'holiday_status_id' in fields and self.env.context.get('deduct_extra_hours'): domain = [('overtime_deductible', '=', True), ('requires_allocation', '=', 'yes')] if self.env.context.get('deduct_extra_hours_employee_request', False): # Prevent loading manager allocated time off type in self request contexts domain = expression.AND([domain, [('employee_requests', '=', 'yes')]]) leave_type = self.env['hr.leave.type'].search(domain, limit=1) res['holiday_status_id'] = leave_type.id return res overtime_deductible = fields.Boolean(compute='_compute_overtime_deductible') overtime_id = fields.Many2one('hr.attendance.overtime', string='Extra Hours', groups='hr_holidays.group_hr_holidays_user') employee_overtime = fields.Float(related='employee_id.total_overtime') hr_attendance_overtime = fields.Boolean(related='employee_company_id.hr_attendance_overtime') @api.depends('holiday_status_id') def _compute_overtime_deductible(self): for allocation in self: allocation.overtime_deductible = allocation.hr_attendance_overtime and allocation.holiday_status_id.overtime_deductible @api.model_create_multi def create(self, vals_list): res = super().create(vals_list) for allocation in res: if allocation.overtime_deductible and allocation.holiday_type == 'employee': duration = allocation.number_of_hours_display if duration > allocation.employee_id.total_overtime: raise ValidationError(_('The employee does not have enough overtime hours to request this leave.')) if not allocation.overtime_id: allocation.sudo().overtime_id = self.env['hr.attendance.overtime'].sudo().create({ 'employee_id': allocation.employee_id.id, 'date': fields.Date.today(), 'adjustment': True, 'duration': -1 * duration, }) return res def write(self, vals): res = super().write(vals) if 'number_of_days' not in vals: return res for allocation in self.filtered('overtime_id'): employee = allocation.employee_id duration = allocation.number_of_hours_display overtime_duration = allocation.overtime_id.sudo().duration if overtime_duration != duration: if duration > employee.total_overtime - overtime_duration: raise ValidationError(_('The employee does not have enough extra hours to extend this allocation.')) allocation.overtime_id.sudo().duration = -1 * duration return res def action_draft(self): overtime_allocations = self.filtered('overtime_deductible') if any([a.employee_overtime < float_round(a.number_of_hours_display, 2) for a in overtime_allocations]): raise ValidationError(_('The employee does not have enough extra hours to request this allocation.')) res = super().action_draft() overtime_allocations.overtime_id.sudo().unlink() for allocation in overtime_allocations: overtime = self.env['hr.attendance.overtime'].sudo().create({ 'employee_id': allocation.employee_id.id, 'date': fields.Date.today(), 'adjustment': True, 'duration': -1 * allocation.number_of_hours_display }) allocation.sudo().overtime_id = overtime.id return res def action_refuse(self): res = super().action_refuse() self.overtime_id.sudo().unlink() return res
48.976471
4,163
1,104
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 ResUsers(models.Model): _inherit = 'res.users' request_overtime = fields.Boolean(compute='_compute_request_overtime') @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + ['request_overtime'] @api.depends_context('uid') @api.depends('total_overtime') def _compute_request_overtime(self): is_holiday_user = self.env.user.has_group('hr_holidays.group_hr_holidays_user') time_off_types = self.env['hr.leave.type'].search_count([ ('requires_allocation', '=', 'yes'), ('employee_requests', '=', 'yes'), ('overtime_deductible', '=', True) ]) for user in self: if user.total_overtime >= 1: if is_holiday_user: user.request_overtime = True else: user.request_overtime = time_off_types else: user.request_overtime = False
34.5
1,104
1,925
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 HRLeaveType(models.Model): _inherit = 'hr.leave.type' hr_attendance_overtime = fields.Boolean(compute='_compute_hr_attendance_overtime') overtime_deductible = fields.Boolean( "Deduct Extra Hours", default=False, help="Once a time off of this type is approved, extra hours in attendances will be deducted.") def get_employees_days(self, employee_ids, date=None): res = super().get_employees_days(employee_ids, date) deductible_time_off_type_ids = self.env['hr.leave.type'].search([ ('overtime_deductible', '=', True), ('requires_allocation', '=', 'no')]).ids for employee_id, allocations in res.items(): for allocation_id in allocations: if allocation_id in deductible_time_off_type_ids: res[employee_id][allocation_id]['virtual_remaining_leaves'] = self.env['hr.employee'].sudo().browse(employee_id).total_overtime res[employee_id][allocation_id]['overtime_deductible'] = True else: res[employee_id][allocation_id]['overtime_deductible'] = False return res def _get_days_request(self): res = super()._get_days_request() res[1]['overtime_deductible'] = self.overtime_deductible return res @api.depends('company_id.hr_attendance_overtime') def _compute_hr_attendance_overtime(self): # If no company is linked to the time off type, use the current company's setting for leave_type in self: if leave_type.company_id: leave_type.hr_attendance_overtime = leave_type.company_id.hr_attendance_overtime else: leave_type.hr_attendance_overtime = self.env.company.hr_attendance_overtime
46.95122
1,925
868
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "India Purchase and Warehouse Management", 'icon': '/l10n_in/static/description/icon.png', 'summary': """ Define default purchase journal on the warehouse""", 'description': """ Define default purchase journal on the warehouse, help you to choose correct purchase journal on the purchase order when you change the picking operation. useful when you setup the multiple GSTIN units. """, 'author': "Odoo", 'website': "https://www.odoo.com", 'category': 'Accounting/Localizations/Purchase', 'version': '1.0', 'depends': ['l10n_in_purchase', 'l10n_in_stock'], 'data': [ 'views/stock_warehouse_views.xml', ], 'auto_install': True, 'license': 'LGPL-3', }
28.933333
868
596
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class AccountMove(models.Model): _inherit = "account.move" def _l10n_in_get_warehouse_address(self): res = super()._l10n_in_get_warehouse_address() if self.invoice_line_ids.purchase_line_id: company_shipping_id = self.mapped( "invoice_line_ids.purchase_line_id.move_ids.warehouse_id.partner_id" ) if len(company_shipping_id) == 1: return company_shipping_id return res
33.111111
596
296
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class Stock(models.Model): _inherit = 'stock.warehouse' l10n_in_purchase_journal_id = fields.Many2one('account.journal', string="Purchase Journal")
29.6
296
580
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class PurchaseOrder(models.Model): _inherit = "purchase.order" @api.onchange('company_id', 'picking_type_id') def l10n_in_onchange_company_id(self): if self.picking_type_id.warehouse_id and self.picking_type_id.warehouse_id.l10n_in_purchase_journal_id: self.l10n_in_journal_id = self.picking_type_id.warehouse_id.l10n_in_purchase_journal_id.id else: super().l10n_in_onchange_company_id()
38.666667
580
473
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Sale Coupon Delivery", 'summary': """Allows to offer free shippings in coupon reward""", 'description': """Integrate coupon mechanism with shipping costs.""", 'category': 'Sales/Sales', 'version': '1.0', 'depends': ['sale_coupon', 'delivery'], 'data': [ ], 'demo': [ ], 'auto_install': True, 'license': 'LGPL-3', }
29.5625
473
11,043
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_coupon.tests.common import TestSaleCouponCommon from odoo.tests import Form, tagged @tagged('post_install', '-at_install') class TestSaleCouponProgramRules(TestSaleCouponCommon): @classmethod def setUpClass(cls): super(TestSaleCouponProgramRules, cls).setUpClass() cls.iPadMini = cls.env['product.product'].create({'name': 'Large Cabinet', 'list_price': 320.0}) tax_15pc_excl = cls.env['account.tax'].create({ 'name': "15% Tax excl", 'amount_type': 'percent', 'amount': 15, }) cls.product_delivery_poste = cls.env['product.product'].create({ 'name': 'The Poste', 'type': 'service', 'categ_id': cls.env.ref('delivery.product_category_deliveries').id, 'sale_ok': False, 'purchase_ok': False, 'list_price': 20.0, 'taxes_id': [(6, 0, [tax_15pc_excl.id])], }) cls.carrier = cls.env['delivery.carrier'].create({ 'name': 'The Poste', 'fixed_price': 20.0, 'delivery_type': 'base_on_rule', 'product_id': cls.product_delivery_poste.id, }) cls.env['delivery.price.rule'].create([{ 'carrier_id': cls.carrier.id, 'max_value': 5, 'list_base_price': 20, }, { 'carrier_id': cls.carrier.id, 'operator': '>=', 'max_value': 5, 'list_base_price': 50, }, { 'carrier_id': cls.carrier.id, 'operator': '>=', 'max_value': 300, 'variable': 'price', 'list_base_price': 0, }]) # Test a free shipping reward + some expected behavior # (automatic line addition or removal) def test_free_shipping_reward(self): # Test case 1: The minimum amount is not reached, the reward should # not be created self.immediate_promotion_program.active = False self.env['coupon.program'].create({ 'name': 'Free Shipping if at least 100 euros', 'promo_code_usage': 'no_code_needed', 'reward_type': 'free_shipping', 'rule_minimum_amount': 100.0, 'rule_minimum_amount_tax_inclusion': 'tax_included', 'active': True, }) order = self.env['sale.order'].create({ 'partner_id': self.steve.id, }) # Price of order will be 5*1.15 = 5.75 (tax included) order.write({'order_line': [ (0, False, { 'product_id': self.product_B.id, 'name': 'Product B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 1) # I add delivery cost in Sales order delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({ 'default_order_id': order.id, 'default_carrier_id': self.env['delivery.carrier'].search([])[1] })) choose_delivery_carrier = delivery_wizard.save() choose_delivery_carrier.button_confirm() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2) # Test Case 1b: amount is not reached but is on a threshold # The amount of deliverable product + the one of the delivery exceeds the minimum amount # yet the program shouldn't be applied # Order price will be 5.75 + 81.74*1.15 = 99.75 order.write({'order_line': [ (0, False, { 'product_id': self.product_B.id, 'name': 'Product 1B', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, 'price_unit': 81.74, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3) # Test case 2: the amount is sufficient, the shipping should # be reimbursed order.write({'order_line': [ (0, False, { 'product_id': self.product_A.id, 'name': 'Product 1', 'product_uom': self.uom_unit.id, 'product_uom_qty': 1.0, 'price_unit': 0.30, }) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 5) # Test case 3: the amount is not sufficient now, the reward should be removed order.write({'order_line': [ (2, order.order_line.filtered(lambda line: line.product_id.id == self.product_A.id).id, False) ]}) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3) def test_shipping_cost(self): # Free delivery should not be taken into account when checking for minimum required threshold p_minimum_threshold_free_delivery = self.env['coupon.program'].create({ 'name': 'free shipping if > 872 tax exl', 'promo_code_usage': 'no_code_needed', 'reward_type': 'free_shipping', 'program_type': 'promotion_program', 'rule_minimum_amount': 872, }) p_minimum_threshold_discount = self.env['coupon.program'].create({ 'name': '10% reduction if > 872 tax exl', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 10.0, 'rule_minimum_amount': 872, }) order = self.empty_order self.iPadMini.taxes_id = self.tax_10pc_incl sol1 = self.env['sale.order.line'].create({ 'product_id': self.iPadMini.id, 'name': 'Large Cabinet', 'product_uom_qty': 3.0, 'order_id': order.id, }) order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2, "We should get the 10% discount line since we bought 872.73$") order.carrier_id = self.env['delivery.carrier'].search([])[1] # I add delivery cost in Sales order delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({ 'default_order_id': order.id, 'default_carrier_id': self.env['delivery.carrier'].search([])[1] })) choose_delivery_carrier = delivery_wizard.save() choose_delivery_carrier.button_confirm() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "We should get the delivery line but not the free delivery since we are below 872.73$ with the 10% discount") p_minimum_threshold_free_delivery.sequence = 10 (order.order_line - sol1).unlink() # I add delivery cost in Sales order delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({ 'default_order_id': order.id, 'default_carrier_id': self.env['delivery.carrier'].search([])[1] })) choose_delivery_carrier = delivery_wizard.save() choose_delivery_carrier.button_confirm() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 4, "We should get both promotion line since the free delivery will be applied first and won't change the SO total") def test_shipping_cost_numbers(self): # Free delivery should not be taken into account when checking for minimum required threshold p_minimum_threshold_free_delivery = self.env['coupon.program'].create({ 'name': 'free shipping if > 872 tax exl', 'promo_code_usage': 'code_needed', 'promo_code': 'free_shipping', 'reward_type': 'free_shipping', 'program_type': 'promotion_program', 'rule_minimum_amount': 872, }) self.p2 = self.env['coupon.program'].create({ 'name': 'Buy 4 large cabinet, get one for free', 'promo_code_usage': 'no_code_needed', 'reward_type': 'product', 'program_type': 'promotion_program', 'reward_product_id': self.iPadMini.id, 'rule_min_quantity': 3, 'rule_products_domain': '[["name","ilike","large cabinet"]]', }) order = self.empty_order self.iPadMini.taxes_id = self.tax_10pc_incl sol1 = self.env['sale.order.line'].create({ 'product_id': self.iPadMini.id, 'name': 'Large Cabinet', 'product_uom_qty': 3.0, 'order_id': order.id, }) # I add delivery cost in Sales order delivery_wizard = Form(self.env['choose.delivery.carrier'].with_context({ 'default_order_id': order.id, 'default_carrier_id': self.carrier.id })) choose_delivery_carrier = delivery_wizard.save() choose_delivery_carrier.button_confirm() order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 2) self.assertEqual(order.reward_amount, 0) # Shipping is 20 + 15%tax self.assertEqual(sum([line.price_total for line in order._get_no_effect_on_threshold_lines()]), 23) self.assertEqual(order.amount_untaxed, 872.73 + 20) self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, 'free_shipping') order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 3, "We should get the delivery line and the free delivery since we are below 872.73$ with the 10% discount") self.assertEqual(order.reward_amount, -20) self.assertEqual(sum([line.price_total for line in order._get_no_effect_on_threshold_lines()]), 0) self.assertEqual(order.amount_untaxed, 872.73) sol1.product_uom_qty = 4 order.recompute_coupon_lines() self.assertEqual(len(order.order_line.ids), 4, "We should get a free Large Cabinet") self.assertEqual(order.reward_amount, -20 -290.91) self.assertEqual(sum([line.price_total for line in order._get_no_effect_on_threshold_lines()]), 0) self.assertEqual(order.amount_untaxed, 872.73) p_specific_product = self.env['coupon.program'].create({ 'name': '20% reduction on large cabinet in cart', 'promo_code_usage': 'no_code_needed', 'reward_type': 'discount', 'program_type': 'promotion_program', 'discount_type': 'percentage', 'discount_percentage': 20.0, 'discount_apply_on': 'cheapest_product', }) p_specific_product.discount_apply_on = 'cheapest_product' order.recompute_coupon_lines() # 872.73 - (20% of 1 iPad) = 872.73 - 58.18 = 814.55 self.assertAlmostEqual(order.amount_untaxed, 814.55, 2, "One large cabinet should be discounted by 20%")
43.305882
11,043
3,428
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ class SaleOrder(models.Model): _inherit = "sale.order" def _get_no_effect_on_threshold_lines(self): self.ensure_one() # Do not count shipping and free shipping free_delivery_product = self.env['coupon.program'].search([('reward_type', '=', 'free_shipping')]).mapped('discount_line_product_id') lines = self.order_line.filtered(lambda line: line.is_delivery or line.product_id in free_delivery_product) return lines + super(SaleOrder, self)._get_no_effect_on_threshold_lines() def _get_paid_order_lines(self): """ Returns the taxes included sale order total amount without the rewards amount""" free_reward_product = self.env['coupon.program'].search([('reward_type', '=', 'product')]).mapped('discount_line_product_id') return self.order_line.filtered(lambda x: not x._is_not_sellable_line() or x.product_id in free_reward_product) def _get_reward_line_values(self, program): if program.reward_type == 'free_shipping': return [self._get_reward_values_free_shipping(program)] else: return super(SaleOrder, self)._get_reward_line_values(program) def _get_reward_values_free_shipping(self, program): delivery_line = self.order_line.filtered(lambda x: x.is_delivery) taxes = delivery_line.product_id.taxes_id.filtered(lambda t: t.company_id.id == self.company_id.id) taxes = self.fiscal_position_id.map_tax(taxes) return { 'name': _("Discount: %s", program.name), 'product_id': program.discount_line_product_id.id, 'price_unit': delivery_line and - delivery_line.price_unit or 0.0, 'product_uom_qty': 1.0, 'product_uom': program.discount_line_product_id.uom_id.id, 'order_id': self.id, 'is_reward_line': True, 'tax_id': [(4, tax.id, False) for tax in taxes], } def _get_cheapest_line(self): # Unit prices tax included return min(self.order_line.filtered(lambda x: not x._is_not_sellable_line() and x.price_reduce > 0), key=lambda x: x['price_reduce']) class SalesOrderLine(models.Model): _inherit = "sale.order.line" def unlink(self): # Due to delivery_set and delivery_unset methods that are called everywhere, don't unlink # reward lines if it's a free shipping self = self.exists() orders = self.mapped('order_id') applied_programs = orders.mapped('no_code_promo_program_ids') + \ orders.mapped('code_promo_program_id') + \ orders.mapped('applied_coupon_ids').mapped('program_id') free_shipping_products = applied_programs.filtered( lambda program: program.reward_type == 'free_shipping' ).mapped('discount_line_product_id') lines_to_unlink = self.filtered(lambda line: line.product_id not in free_shipping_products) # Unless these lines are the last ones res = super(SalesOrderLine, lines_to_unlink).unlink() only_free_shipping_line_orders = orders.filtered(lambda order: len(order.order_line.ids) == 1 and order.order_line.is_reward_line) super(SalesOrderLine, only_free_shipping_line_orders.mapped('order_line')).unlink() return res
52.738462
3,428
697
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 CouponReward(models.Model): _inherit = 'coupon.reward' _description = "Coupon Reward" reward_type = fields.Selection(selection_add=[('free_shipping', 'Free Shipping')]) def name_get(self): result = [] reward_names = super(CouponReward, self).name_get() free_shipping_reward_ids = self.filtered(lambda reward: reward.reward_type == 'free_shipping').ids for res in reward_names: result.append((res[0], res[0] in free_shipping_reward_ids and _("Free Shipping") or res[1])) return result
36.684211
697
605
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ class Coupon(models.Model): _inherit = "coupon.coupon" def _check_coupon_code(self, order_date, partner_id, **kwargs): order = kwargs.get('order', False) if order and self.program_id.reward_type == 'free_shipping' and not order.order_line.filtered(lambda line: line.is_delivery): return {'error': _('The shipping costs are not in the order lines.')} return super(Coupon, self)._check_coupon_code(order_date, partner_id, **kwargs)
40.333333
605
1,091
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _, api class CouponProgram(models.Model): _inherit = "coupon.program" def _filter_not_ordered_reward_programs(self, order): """ Returns the programs when the reward is actually in the order lines """ programs = super(CouponProgram, self)._filter_not_ordered_reward_programs(order) # Do not filter on free delivery programs. As delivery_unset is called everywhere (which is # rather stupid), the delivery line is unliked to be created again instead of writing on it to # modify the price_unit. That way, the reward is unlink and is not set back again. return programs def _check_promo_code(self, order, coupon_code): if self.reward_type == 'free_shipping' and not any(line.is_delivery for line in order.order_line): return {'error': _('The shipping costs are not in the order lines.')} return super(CouponProgram, self)._check_promo_code(order, coupon_code)
45.458333
1,091
698
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Generic - Accounting', 'version': '1.1', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This is the base module to manage the generic accounting chart in Odoo. ============================================================================== Install some generic chart of accounts. """, 'depends': [ 'account', ], 'data': [ 'data/l10n_generic_coa.xml', 'data/account.account.template.csv', 'data/l10n_generic_coa_post.xml', ], 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3', }
29.083333
698
1,246
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2015 Willow IT Pty Ltd (<http://www.willowit.com.au>). { 'name': 'Australian - Accounting', 'version': '1.1', 'category': 'Accounting/Localizations/Account Charts', 'description': """ Australian Accounting Module ============================ Australian accounting basic charts and localizations. Also: - activates a number of regional currencies. - sets up Australian taxes. """, 'author': 'Richard deMeester - Willow IT', 'website': 'http://www.willowit.com', 'depends': ['account'], 'data': [ 'data/l10n_au_chart_data.xml', 'data/account.account.template.csv', 'data/account_chart_template_data.xml', 'data/account_tax_report_data.xml', 'data/account.tax.group.csv', 'data/account_tax_template_data.xml', 'data/account_fiscal_position_tax_template_data.xml', 'data/account_chart_template_configure_data.xml', 'data/res_currency_data.xml', 'views/menuitems.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
31.948718
1,246
786
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { "name": "Website Jitsi", 'category': 'Hidden', 'version': '1.0', "summary": "Create Jitsi room on website.", 'website': 'https://www.odoo.com/app/events', "description": "Create Jitsi room on website.", "depends": [ "website" ], "data": [ 'views/chat_room_templates.xml', 'views/chat_room_views.xml', 'views/res_config_settings.xml', 'security/ir.model.access.csv', ], 'application': False, 'assets': { 'web.assets_frontend': [ 'website_jitsi/static/src/css/chat_room.css', 'website_jitsi/static/src/js/chat_room.js', ], }, 'license': 'LGPL-3', }
27.103448
786
2,682
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from uuid import uuid4 from odoo import api, fields, models class ChatRoom(models.Model): """ Store all useful information to manage chat room (currently limited to Jitsi). This model embeds all information about the chat room. We do not store them in the related mixin (see chat.room.mixin) to avoid to add too many fields on the models which want to use the chat room mixin as the behavior can be optional in those models. The participant count is automatically updated thanks to the chat room widget to avoid having a costly computed field with a members model. """ _name = "chat.room" _description = "Chat Room" def _default_name(self, objname='room'): return "odoo-%s-%s" % (objname, str(uuid4())[:8]) name = fields.Char( "Room Name", required=True, copy=False, default=lambda self: self._default_name()) is_full = fields.Boolean("Full", compute="_compute_is_full") jitsi_server_domain = fields.Char( 'Jitsi Server Domain', compute='_compute_jitsi_server_domain', help='The Jitsi server domain can be customized through the settings to use a different server than the default "meet.jit.si"') lang_id = fields.Many2one( "res.lang", "Language", default=lambda self: self.env["res.lang"].search([("code", "=", self.env.user.lang)], limit=1)) max_capacity = fields.Selection( [("4", "4"), ("8", "8"), ("12", "12"), ("16", "16"), ("20", "20"), ("no_limit", "No limit")], string="Max capacity", default="8", required=True) participant_count = fields.Integer("Participant count", default=0, copy=False) # reporting fields last_activity = fields.Datetime( "Last Activity", copy=False, readonly=True, default=lambda self: fields.Datetime.now()) max_participant_reached = fields.Integer( "Max participant reached", copy=False, readonly=True, help="Maximum number of participant reached in the room at the same time") @api.depends("max_capacity", "participant_count") def _compute_is_full(self): for room in self: if room.max_capacity == "no_limit": room.is_full = False else: room.is_full = room.participant_count >= int(room.max_capacity) def _compute_jitsi_server_domain(self): jitsi_server_domain = self.env['ir.config_parameter'].sudo().get_param( 'website_jitsi.jitsi_server_domain', 'meet.jit.si') for room in self: room.jitsi_server_domain = jitsi_server_domain
43.967213
2,682
3,914
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from odoo import api, fields, models from odoo.tools import remove_accents class ChatRoomMixin(models.AbstractModel): """Add the chat room configuration (`chat.room`) on the needed models. The chat room configuration contains all information about the room. So, we store all the chat room logic at the same place, for all models. Embed chat room related fields prefixed with `room_`. """ _name = "chat.room.mixin" _description = "Chat Room Mixin" ROOM_CONFIG_FIELDS = [ ('room_name', 'name'), ('room_lang_id', 'lang_id'), ('room_max_capacity', 'max_capacity'), ('room_participant_count', 'participant_count') ] chat_room_id = fields.Many2one("chat.room", "Chat Room", readonly=True, copy=False, ondelete="set null") # chat room related fields room_name = fields.Char("Room Name", related="chat_room_id.name") room_is_full = fields.Boolean("Room Is Full", related="chat_room_id.is_full") room_lang_id = fields.Many2one("res.lang", "Language", related="chat_room_id.lang_id", readonly=False) room_max_capacity = fields.Selection(string="Max capacity", related="chat_room_id.max_capacity", readonly=False, required=True) room_participant_count = fields.Integer("Participant count", related="chat_room_id.participant_count", readonly=False) room_last_activity = fields.Datetime("Last activity", related="chat_room_id.last_activity") room_max_participant_reached = fields.Integer("Peak participants", related="chat_room_id.max_participant_reached") @api.model_create_multi def create(self, values_list): for values in values_list: if any(values.get(fmatch[0]) for fmatch in self.ROOM_CONFIG_FIELDS) and not values.get('chat_room_id'): if values.get('room_name'): values['room_name'] = self._jitsi_sanitize_name(values['room_name']) room_values = dict((fmatch[1], values[fmatch[0]]) for fmatch in self.ROOM_CONFIG_FIELDS if values.get(fmatch[0])) values['chat_room_id'] = self.env['chat.room'].create(room_values).id return super(ChatRoomMixin, self).create(values_list) def write(self, values): if any(values.get(fmatch[0]) for fmatch in self.ROOM_CONFIG_FIELDS): if values.get('room_name'): values['room_name'] = self._jitsi_sanitize_name(values['room_name']) for document in self.filtered(lambda doc: not doc.chat_room_id): room_values = dict((fmatch[1], values[fmatch[0]]) for fmatch in self.ROOM_CONFIG_FIELDS if values.get(fmatch[0])) document.chat_room_id = self.env['chat.room'].create(room_values).id return super(ChatRoomMixin, self).write(values) def copy_data(self, default=None): if default is None: default = {} if self.chat_room_id: chat_room_default = {} if 'room_name' not in default: chat_room_default['name'] = self._jitsi_sanitize_name(self.chat_room_id.name) default['chat_room_id'] = self.chat_room_id.copy(default=chat_room_default).id return super(ChatRoomMixin, self).copy_data(default=default) def unlink(self): rooms = self.chat_room_id res = super(ChatRoomMixin, self).unlink() rooms.unlink() return res def _jitsi_sanitize_name(self, name): sanitized = re.sub(r'[^\w+.]+', '-', remove_accents(name).lower()) counter, sanitized_suffixed = 1, sanitized existing = self.env['chat.room'].search([('name', '=like', '%s%%' % sanitized)]).mapped('name') while sanitized_suffixed in existing: sanitized_suffixed = '%s-%d' % (sanitized, counter) counter += 1 return sanitized_suffixed
50.831169
3,914
503
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' jitsi_server_domain = fields.Char( 'Jitsi Server Domain', default='meet.jit.si', config_parameter='website_jitsi.jitsi_server_domain', help='The Jitsi server domain can be customized through the settings to use a different server than the default "meet.jit.si"')
41.916667
503
2,142
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from werkzeug.exceptions import NotFound from odoo import http from odoo.http import request class WebsiteJitsiController(http.Controller): @http.route(["/jitsi/update_status"], type="json", auth="public") def jitsi_update_status(self, room_name, participant_count, joined): """ Update room status: participant count, max reached Use the SQL keywords "FOR UPDATE SKIP LOCKED" in order to skip if the row is locked (instead of raising an exception, wait for a moment and retry). This endpoint may be called multiple times and we don't care having small errors in participant count compared to performance issues. :raise ValueError: wrong participant count :raise NotFound: wrong room name """ if participant_count < 0: raise ValueError() chat_room = self._chat_room_exists(room_name) if not chat_room: raise NotFound() request.env.cr.execute( """ WITH req AS ( SELECT id FROM chat_room -- Can not update the chat room if we do not have its name WHERE name = %s FOR UPDATE SKIP LOCKED ) UPDATE chat_room AS wcr SET participant_count = %s, last_activity = NOW(), max_participant_reached = GREATEST(max_participant_reached, %s) FROM req WHERE wcr.id = req.id; """, [room_name, participant_count, participant_count] ) @http.route(["/jitsi/is_full"], type="json", auth="public") def jitsi_is_full(self, room_name): return self._chat_room_exists(room_name).is_full # ------------------------------------------------------------ # TOOLS # ------------------------------------------------------------ def _chat_room_exists(self, room_name): return request.env["chat.room"].sudo().search([("name", "=", room_name)], limit=1)
36.305085
2,142
665
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Associations Management', 'version': '0.1', 'category': 'Marketing', 'description': """ This module is to configure modules related to an association. ============================================================== It installs the profile for associations to manage events, registrations, memberships, membership products (schemes). """, 'depends': ['base_setup', 'membership', 'event'], 'data': ['views/association_views.xml'], 'demo': [], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
30.227273
665
397
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Import/Export invoices with UBL (BIS3)', 'description': ''' Support for Export/Import in UBL format (BIS3). ''', 'version': '1.0', 'category': 'Accounting/Accounting', 'depends': ['account_edi_ubl'], 'data': [ 'data/bis3_templates.xml', ], 'installable': True, 'application': False, 'license': 'LGPL-3', }
24.8125
397
8,062
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.exceptions import UserError from odoo.tests.common import Form COUNTRY_EAS = { 'HU': 9910, 'AD': 9922, 'AL': 9923, 'BA': 9924, 'BE': 9925, 'BG': 9926, 'CH': 9927, 'CY': 9928, 'CZ': 9929, 'DE': 9930, 'EE': 9931, 'UK': 9932, 'GR': 9933, 'HR': 9934, 'IE': 9935, 'LI': 9936, 'LT': 9937, 'LU': 9938, 'LV': 9939, 'MC': 9940, 'ME': 9941, 'MK': 9942, 'MT': 9943, 'NL': 9944, 'PL': 9945, 'PT': 9946, 'RO': 9947, 'RS': 9948, 'SI': 9949, 'SK': 9950, 'SM': 9951, 'TR': 9952, 'VA': 9953, 'SE': 9955, 'FR': 9957 } class AccountEdiFormat(models.Model): ''' This edi_format is "abstract" meaning that it provides an additional layer for similar edi_format (formats deriving from EN16931) that share some functionalities but needs to be extended to be used. ''' _inherit = 'account.edi.format' #################################################### # Export #################################################### def _get_bis3_values(self, invoice): values = super()._get_ubl_values(invoice) values.update({ 'customization_id': 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0', 'profile_id': 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0', }) # Tax details. def grouping_key_generator(tax_values): tax = tax_values['tax_id'] return { 'tax_percent': tax.amount, 'tax_category': 'S' if tax.amount else 'Z', } values['tax_details'] = invoice._prepare_edi_tax_details( filter_to_apply=lambda x: x['tax_repartition_line_id'].use_in_tax_closing, grouping_key_generator=grouping_key_generator, ) for line_vals in values['invoice_line_vals_list']: if len(values['tax_details']['invoice_line_tax_details'][line_vals['line']]['tax_details']) > 1: raise UserError("Multiple vat percentage not supported on the same invoice line") tax_details_no_tax_closing = invoice._prepare_edi_tax_details( filter_to_apply=lambda x: not x['tax_repartition_line_id'].use_in_tax_closing, ) for line_vals in values['invoice_line_vals_list']: line_vals['price_subtotal_with_no_tax_closing'] = line_vals['line'].price_subtotal for tax_detail in tax_details_no_tax_closing['invoice_line_tax_details'][line_vals['line']]['tax_details'].values(): line_vals['price_subtotal_with_no_tax_closing'] += tax_detail['tax_amount_currency'] values['total_untaxed_amount'] = sum(x['price_subtotal_with_no_tax_closing'] for x in values['invoice_line_vals_list']) # Misc. for partner_vals in (values['customer_vals'], values['supplier_vals']): partner = partner_vals['partner'] if partner.country_id.code in COUNTRY_EAS: partner_vals['bis3_endpoint'] = partner.vat partner_vals['bis3_endpoint_scheme'] = COUNTRY_EAS[partner.country_id.code] return values #################################################### # Import #################################################### def _get_bis3_namespaces(self): return { 'cac': 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2', 'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2', } def _bis3_get_extra_partner_domains(self, tree): """ Returns an additional domain to find the partner of the invoice based on specific implementation of BIS3. TO OVERRIDE :returns: a list of domains """ return [] def _decode_bis3(self, tree, invoice): """ Decodes an EN16931 invoice into an invoice. :param tree: the UBL (EN16931) tree to decode. :param invoice: the invoice to update or an empty recordset. :returns: the invoice where the UBL (EN16931) data was imported. """ def _find_value(path, root=tree): element = root.find(path) return element.text if element is not None else None element = tree.find('./{*}InvoiceTypeCode') if element is not None: type_code = element.text move_type = 'in_refund' if type_code == '381' else 'in_invoice' else: move_type = 'in_invoice' default_journal = invoice.with_context(default_move_type=move_type)._get_default_journal() with Form(invoice.with_context(default_move_type=move_type, default_journal_id=default_journal.id)) as invoice_form: # Reference element = tree.find('./{*}ID') if element is not None: invoice_form.ref = element.text # Dates element = tree.find('./{*}IssueDate') if element is not None: invoice_form.invoice_date = element.text element = tree.find('./{*}DueDate') if element is not None: invoice_form.invoice_date_due = element.text # Currency currency = self._retrieve_currency(_find_value('./{*}DocumentCurrencyCode')) if currency and currency.active: invoice_form.currency_id = currency # Partner specific_domain = self._bis3_get_extra_partner_domains(tree) invoice_form.partner_id = self._retrieve_partner( name=_find_value('./{*}AccountingSupplierParty/{*}Party/*/{*}Name'), phone=_find_value('./{*}AccountingSupplierParty/{*}Party/*/{*}Telephone'), mail=_find_value('./{*}AccountingSupplierParty/{*}Party/*/{*}ElectronicMail'), vat=_find_value('./{*}AccountingSupplierParty/{*}Party/{*}PartyTaxScheme/{*}CompanyID'), domain=specific_domain, ) # Lines for eline in tree.findall('.//{*}InvoiceLine'): with invoice_form.invoice_line_ids.new() as invoice_line_form: # Product invoice_line_form.product_id = self._retrieve_product( default_code=_find_value('./{*}Item/{*}SellersItemIdentification/{*}ID', eline), name=_find_value('./{*}Item/{*}Name', eline), barcode=_find_value('./{*}Item/{*}StandardItemIdentification/{*}ID[@schemeID=\'0160\']', eline) ) # Quantity element = eline.find('./{*}InvoicedQuantity') quantity = element is not None and float(element.text) or 1.0 invoice_line_form.quantity = quantity # Price Unit element = eline.find('./{*}Price/{*}PriceAmount') price_unit = element is not None and float(element.text) or 0.0 line_extension_amount = element is not None and float(element.text) or 0.0 invoice_line_form.price_unit = price_unit or line_extension_amount / invoice_line_form.quantity or 0.0 # Name element = eline.find('./{*}Item/{*}Description') invoice_line_form.name = element is not None and element.text or '' # Taxes tax_elements = eline.findall('./{*}Item/{*}ClassifiedTaxCategory') invoice_line_form.tax_ids.clear() for tax_element in tax_elements: invoice_line_form.tax_ids.add(self._retrieve_tax( amount=_find_value('./{*}Percent', tax_element), type_tax_use=invoice_form.journal_id.type )) return invoice_form.save()
39.326829
8,062
5,183
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Argentina - Accounting', 'icon': '/base/static/img/country_flags/ar.png', 'version': "3.5", 'description': """ Functional ---------- This module add accounting features for the Argentinean localization, which represent the minimal configuration needed for a company to operate in Argentina and under the AFIP (Administración Federal de Ingresos Públicos) regulations and guidelines. Follow the next configuration steps for Production: 1. Go to your company and configure your VAT number and AFIP Responsibility Type 2. Go to Accounting / Settings and set the Chart of Account that you will like to use. 3. Create your Sale journals taking into account AFIP POS info. Demo data for testing: * 3 companies were created, one for each AFIP responsibility type with the respective Chart of Account installed. Choose the company that fix you in order to make tests: * (AR) Responsable Inscripto * (AR) Exento * (AR) Monotributo * Journal sales configured to Pre printed and Expo invoices in all companies * Invoices and other documents examples already validated in “(AR) Responsable Inscripto” company * Partners example for the different responsibility types: * ADHOC (IVA Responsable Inscripto) * Consejo Municipal Rosario (IVA Sujeto Exento) * Gritti (Monotributo) * Cerro Castor. IVA Liberado in Zona Franca * Expresso (Cliente del Exterior) * Odoo (Proveedor del Exterior) Highlights: * Chart of account will not be automatically installed, each CoA Template depends on the AFIP Responsibility of the company, you will need to install the CoA for your needs. * No sales journals will be generated when installing a CoA, you will need to configure your journals manually. * The Document type will be properly pre selected when creating an invoice depending on the fiscal responsibility of the issuer and receiver of the document and the related journal. * A CBU account type has been added and also CBU Validation Technical --------- This module adds both models and fields that will be eventually used for the electronic invoice module. Here is a summary of the main features: Master Data: * Chart of Account: one for each AFIP responsibility that is related to a legal entity: * Responsable Inscripto (RI) * Exento (EX) * Monotributo (Mono) * Argentinean Taxes and Account Tax Groups (VAT taxes with the existing aliquots and other types) * AFIP Responsibility Types * Fiscal Positions (in order to map taxes) * Legal Documents Types in Argentina * Identification Types valid in Argentina. * Country AFIP codes and Country VAT codes for legal entities, natural persons and others * Currency AFIP codes * Unit of measures AFIP codes * Partners: Consumidor Final and AFIP """, 'author': 'ADHOC SA', 'category': 'Accounting/Localizations/Account Charts', 'depends': [ 'l10n_latam_invoice_document', 'l10n_latam_base', ], 'data': [ 'security/ir.model.access.csv', 'data/l10n_latam_identification_type_data.xml', 'data/l10n_ar_afip_responsibility_type_data.xml', 'data/account_chart_template_data.xml', 'data/account.group.template.csv', 'data/account.account.template.csv', 'data/account_chart_template_data2.xml', 'data/account_tax_group_data.xml', 'data/account_tax_template_data.xml', 'data/account_fiscal_template.xml', 'data/uom_uom_data.xml', 'data/l10n_latam.document.type.csv', 'data/l10n_latam.document.type.xml', 'data/res_partner_data.xml', 'data/res.currency.csv', 'data/res.country.csv', 'views/account_move_view.xml', 'views/res_partner_view.xml', 'views/res_company_view.xml', 'views/res_country_view.xml', 'views/afip_menuitem.xml', 'views/l10n_ar_afip_responsibility_type_view.xml', 'views/res_currency_view.xml', 'views/account_fiscal_position_view.xml', 'views/uom_uom_view.xml', 'views/account_journal_view.xml', 'views/l10n_latam_document_type_view.xml', 'views/report_invoice.xml', 'views/res_config_settings_view.xml', 'report/invoice_report_view.xml', 'data/account_chart_template_configure_data.xml', ], 'demo': [ # we create demo data on different companies (not main_company) to # allow different setups and also to allow multi-localization demo data 'demo/exento_demo.xml', 'demo/mono_demo.xml', 'demo/respinsc_demo.xml', 'demo/res_partner_demo.xml', 'demo/account_tax_demo.xml', 'demo/product_product_demo.xml', 'demo/account_customer_invoice_demo.xml', 'demo/account_customer_refund_demo.xml', 'demo/account_supplier_invoice_demo.xml', 'demo/account_supplier_refund_demo.xml', ], 'installable': True, 'auto_install': False, 'application': False, 'assets': { 'web.assets_backend': [ 'l10n_ar/static/src/**/*', ], }, 'license': 'LGPL-3', }
39.519084
5,177
1,445
py
PYTHON
15.0
# -*- coding: utf-8 -*- import logging from odoo import api, models _logger = logging.getLogger(__name__) class AccountChartTemplate(models.Model): _inherit = "account.chart.template" @api.model def _get_demo_data(self): ref = self.env.ref # Do not load generic demo data on these companies ar_demo_companies = ( ref('l10n_ar.company_mono', raise_if_not_found=False), ref('l10n_ar.company_exento', raise_if_not_found=False), ref('l10n_ar.company_ri', raise_if_not_found=False), ) if self.env.company in ar_demo_companies: return [] yield ('res.partner', { 'base.res_partner_12': { 'l10n_ar_afip_responsibility_type_id': ref('l10n_ar.res_IVARI').id, }, 'base.res_partner_2': { 'l10n_ar_afip_responsibility_type_id': ref('l10n_ar.res_IVARI').id, }, }) for model, data in super()._get_demo_data(): yield model, data @api.model def _get_demo_data_move(self): cid = self.env.company.id model, data = super()._get_demo_data_move() if self.env.company.account_fiscal_country_id.code == "AR": data[f'{cid}_demo_invoice_5']['l10n_latam_document_number'] = '1-1' data[f'{cid}_demo_invoice_equipment_purchase']['l10n_latam_document_number'] = '1-2' return model, data
33.604651
1,445
37,997
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields from odoo.tests.common import Form, tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon import random import logging import time _logger = logging.getLogger(__name__) @tagged('external_l10n', '-at_install', 'post_install', '-standard', 'external') class TestAr(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref='l10n_ar.l10nar_ri_chart_template'): super(TestAr, cls).setUpClass(chart_template_ref=chart_template_ref) # ==== Company ==== cls.company_data['company'].write({ 'parent_id': cls.env.ref('base.main_company').id, 'currency_id': cls.env.ref('base.ARS').id, 'name': '(AR) Responsable Inscripto (Unit Tests)', "l10n_ar_afip_start_date": time.strftime('%Y-01-01'), 'l10n_ar_gross_income_type': 'local', 'l10n_ar_gross_income_number': '901-21885123', }) cls.company_ri = cls.company_data['company'] cls.company_ri.partner_id.write({ 'name': '(AR) Responsable Inscripto (Unit Tests)', 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_IVARI").id, 'l10n_latam_identification_type_id': cls.env.ref("l10n_ar.it_cuit").id, 'vat': '30111111118', "street": 'Calle Falsa 123', "city": 'Rosario', "country_id": cls.env.ref("base.ar").id, "state_id": cls.env.ref("base.state_ar_s").id, "zip": '2000', "phone": '+1 555 123 8069', "email": '[email protected]', "website": 'www.example.com', }) cls.partner_ri = cls.company_ri.partner_id # ==== Company MONO ==== cls.company_mono = cls.setup_company_data('(AR) Monotributista (Unit Tests)', chart_template=cls.env.ref('l10n_ar.l10nar_base_chart_template'))['company'] cls.company_mono.write({ 'parent_id': cls.env.ref('base.main_company').id, 'currency_id': cls.env.ref('base.ARS').id, 'name': '(AR) Monotributista (Unit Tests)', "l10n_ar_afip_start_date": time.strftime('%Y-01-01'), 'l10n_ar_gross_income_type': 'exempt', }) cls.company_mono.partner_id.write({ 'name': '(AR) Monotributista (Unit Tests)', 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_RM").id, 'l10n_latam_identification_type_id': cls.env.ref("l10n_ar.it_cuit").id, 'vat': '20222222223', "street": 'Calle Falsa 123', "city": 'Rosario', "country_id": cls.env.ref("base.ar").id, "state_id": cls.env.ref("base.state_ar_s").id, "zip": '2000', "phone": '+1 555 123 8069', "email": '[email protected]', "website": 'www.example.com', }) cls.partner_mono = cls.company_mono.partner_id # ==== Bank Account ==== cls.bank_account_ri = cls.env['res.partner.bank'].create({ 'acc_number': '7982898111100056688080', 'partner_id': cls.company_ri.partner_id.id, 'company_id': cls.company_ri.id, }) # ==== Partners / Customers ==== cls.partner_afip = cls.env.ref("l10n_ar.partner_afip") cls.res_partner_adhoc = cls.env['res.partner'].create({ "name": "ADHOC SA", "is_company": 1, "city": "Rosario", "zip": "2000", "state_id": cls.env.ref("base.state_ar_s").id, "country_id": cls.env.ref("base.ar").id, "street": "Ovidio Lagos 41 bis", "email": "[email protected]", "phone": "(+54) (341) 208 0203", "website": "http://www.adhoc.com.ar", 'l10n_latam_identification_type_id': cls.env.ref("l10n_ar.it_cuit").id, 'vat': "30714295698", 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_IVARI").id, }) cls.partner_cf = cls.env['res.partner'].create({ "name": "Consumidor Final Anónimo", "l10n_latam_identification_type_id": cls.env.ref('l10n_ar.it_Sigd').id, "l10n_ar_afip_responsibility_type_id": cls.env.ref("l10n_ar.res_CF").id, }) cls.res_partner_gritti_mono = cls.env['res.partner'].create({ "name": "Gritti Agrimensura (Monotributo)", "is_company": 1, "city": "Rosario", "zip": "2000", "state_id": cls.env.ref("base.state_ar_s").id, "country_id": cls.env.ref("base.ar").id, "street": "Calle Falsa 123", "email": "[email protected]", "phone": "(+54) (341) 111 2222", "website": "http://www.grittiagrimensura.com", 'l10n_latam_identification_type_id': cls.env.ref("l10n_ar.it_cuit").id, 'vat': "27320732811", 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_RM").id, }) cls.res_partner_cerrocastor = cls.env['res.partner'].create({ "name": "Cerro Castor (Tierra del Fuego)", "is_company": 1, "city": "Ushuaia", "state_id": cls.env.ref("base.state_ar_v").id, "country_id": cls.env.ref("base.ar").id, "street": "Ruta 3 km 26", "email": "[email protected]", "phone": "(+00) (11) 4444 5556", "website": "http://www.cerrocastor.com", 'l10n_latam_identification_type_id': cls.env.ref("l10n_ar.it_cuit").id, 'vat': "27333333339", 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_IVA_LIB").id, }) cls.res_partner_cmr = cls.env['res.partner'].create({ "name": "Concejo Municipal de Rosario (IVA Sujeto Exento)", "is_company": 1, "city": "Rosario", "zip": "2000", "state_id": cls.env.ref("base.state_ar_s").id, "country_id": cls.env.ref("base.ar").id, "street": "Cordoba 501", "email": "[email protected]", "phone": "(+54) (341) 222 3333", "website": "http://www.concejorosario.gov.ar/", 'l10n_latam_identification_type_id': cls.env.ref("l10n_ar.it_cuit").id, 'vat': "30684679372", 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_IVAE").id, }) cls.res_partner_expresso = cls.env['res.partner'].create({ "name": "Expresso", "is_company": 1, "city": "Barcelona", "zip": "11002", "country_id": cls.env.ref("base.es").id, "street": "La gran avenida 123", "email": "[email protected]", "phone": "(+00) (11) 222 3333", "website": "http://www.expresso.com/", 'l10n_latam_identification_type_id': cls.env.ref("l10n_latam_base.it_fid").id, 'vat': "2222333344445555", 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_EXT").id, }) cls.partner_mipyme = cls.env['res.partner'].create({ "name": "Belgrano Cargas Y Logistica S (Mipyme)", "is_company": 1, "city": "Buenos Aires", "zip": "1425", "state_id": cls.env.ref("base.state_ar_c").id, "country_id": cls.env.ref("base.ar").id, "street": "Av. Santa Fe 4636", "email": "[email protected]", "phone": "(123)-456-7890", "website": "http://www.mypime-inc.com", 'l10n_latam_identification_type_id': cls.env.ref("l10n_ar.it_cuit").id, 'vat': "30714101443", 'l10n_ar_afip_responsibility_type_id': cls.env.ref("l10n_ar.res_IVARI").id, }) cls.partner_mipyme_ex = cls.partner_mipyme.copy({'name': 'MiPyme Exento', 'l10n_ar_afip_responsibility_type_id': cls.env.ref('l10n_ar.res_IVAE').id}) # ==== Taxes ==== cls.tax_21 = cls._search_tax(cls, 'iva_21') cls.tax_27 = cls._search_tax(cls, 'iva_27') cls.tax_0 = cls._search_tax(cls, 'iva_0') cls.tax_10_5 = cls._search_tax(cls, 'iva_105') cls.tax_no_gravado = cls._search_tax(cls, 'iva_no_gravado') cls.tax_perc_iibb = cls._search_tax(cls, 'percepcion_iibb_ba') cls.tax_iva_exento = cls._search_tax(cls, 'iva_exento') cls.tax_21_purchase = cls._search_tax(cls, 'iva_21', type_tax_use='purchase') cls.tax_no_gravado_purchase = cls._search_tax(cls, 'iva_no_gravado', type_tax_use='purchase') # ==== Products ==== uom_unit = cls.env.ref('uom.product_uom_unit') uom_hour = cls.env.ref('uom.product_uom_hour') cls.product_iva_21 = cls.env['product.product'].create({ 'name': 'Large Cabinet (VAT 21)', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'lst_price': 320.0, 'standard_price': 800.0, 'type': "consu", 'default_code': 'E-COM07', }) cls.service_iva_27 = cls.env['product.product'].create({ # demo 'product_product_telefonia' 'name': 'Telephone service (VAT 27)', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'lst_price': 130.0, 'standard_price': 250.0, 'type': 'service', 'default_code': 'TELEFONIA', 'taxes_id': [(6, 0, cls.tax_27.ids)], }) cls.product_iva_cero = cls.env['product.product'].create({ # demo 'product_product_cero' 'name': 'Non-industrialized animals and vegetables (VAT Zero)', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'list_price': 160.0, 'standard_price': 200.0, 'type': 'consu', 'default_code': 'CERO', 'taxes_id': [(6, 0, cls.tax_0.ids)], }) cls.product_iva_105 = cls.env['product.product'].create({ # demo 'product.product_product_27' 'name': 'Laptop Customized (VAT 10,5)', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'standard_price': 4500.0, 'type': 'consu', 'default_code': '10,5', 'taxes_id': [(6, 0, cls.tax_10_5.ids)], }) cls.service_iva_21 = cls.env['product.product'].create({ # demo data product.product_product_2 'name': 'Virtual Home Staging (VAT 21)', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'list_price': 38.25, 'standard_price': 45.5, 'type': 'service', 'default_code': 'VAT 21', 'taxes_id': [(6, 0, cls.tax_21.ids)], }) cls.product_no_gravado = cls.env['product.product'].create({ # demo data product_product_no_gravado 'name': 'Untaxed concepts (VAT NT)', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'list_price': 40.00, 'standard_price': 50.0, 'type': 'consu', 'default_code': 'NOGRAVADO', 'taxes_id': [(6, 0, cls.tax_no_gravado.ids)], }) cls.product_iva_105_perc = cls.product_iva_105.copy({ # product.product_product_25 "name": "Laptop E5023 (VAT 10,5)", "standard_price": 3280.0, # agregamos percecipn aplicada y sufrida tambien 'taxes_id': [(6, 0, [cls.tax_10_5.id, cls.tax_perc_iibb.id])], }) cls.product_iva_exento = cls.env['product.product'].create({ # demo product_product_exento 'name': 'Book: Development in Odoo (VAT Exempt)', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'standard_price': 100.0, "list_price": 80.0, 'type': 'consu', 'default_code': 'EXENTO', 'taxes_id': [(6, 0, cls.tax_iva_exento.ids)], }) cls.service_wo_tax = cls.env['product.product'].create({ # demo product_product_quote_despacho 'name': 'Service WO TAX', 'type': 'service', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'default_code': 'AFIP_DESPACHO', }) cls.service_iva_no_gravado = cls.env['product.product'].create({ # demo product_product_arancel 'name': 'Server VAT Untaxed', 'type': 'service', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, 'default_code': 'AFIP_ARANCEL', "supplier_taxes_id": [(6, 0, (cls.tax_no_gravado_purchase).ids)], }) # ==== Document Types ==== cls.document_type = { 'invoice_a': cls.env.ref('l10n_ar.dc_a_f'), 'credit_note_a': cls.env.ref('l10n_ar.dc_a_nc'), 'invoice_b': cls.env.ref('l10n_ar.dc_b_f'), 'credit_note_b': cls.env.ref('l10n_ar.dc_b_nc'), 'invoice_e': cls.env.ref('l10n_ar.dc_e_f'), 'invoice_mipyme_a': cls.env.ref('l10n_ar.dc_fce_a_f'), 'invoice_mipyme_b': cls.env.ref('l10n_ar.dc_fce_b_f'), } # ==== Journals ==== cls.sale_expo_journal_ri = cls.env["account.journal"].create({ 'name': "Expo Sales Journal", 'company_id': cls.company_ri.id, 'type': "sale", 'code': "S0002", 'l10n_latam_use_documents': "True", 'l10n_ar_afip_pos_number': 2, 'l10n_ar_afip_pos_partner_id': cls.partner_ri.id, 'l10n_ar_afip_pos_system': "FEERCEL", 'refund_sequence': False, }) # ==== Invoices ==== cls.demo_invoices = {} cls.demo_credit_notes = {} cls.demo_bills = {} def _create_test_invoices_like_demo(self, use_current_date=True): """ Create in the unit tests the same invoices created in demo data """ payment_term_id = self.env.ref("account.account_payment_term_end_following_month") invoice_user_id = self.env.user incoterm = self.env.ref("account.incoterm_EXW") invoices_to_create = { 'test_invoice_1': { "ref": "test_invoice_1: Invoice to gritti support service, vat 21", "partner_id": self.res_partner_gritti_mono, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": "out_invoice", "invoice_date": "2021-03-01", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21} ], }, 'test_invoice_2': { "ref": "test_invoice_2: Invoice to CMR with vat 21, 27 and 10,5", "partner_id": self.res_partner_cmr, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": "out_invoice", "invoice_date": "2021-03-05", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, {'product_id': self.service_iva_27, 'price_unit': 250.0, 'quantity': 1}, {'product_id': self.product_iva_105_perc, 'price_unit': 3245.0, 'quantity': 2} ], }, 'test_invoice_3': { "ref": "test_invoice_3: Invoice to ADHOC with vat cero and 21", "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-01", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, {'product_id': self.product_iva_cero, 'price_unit': 200.0, 'quantity': 1} ], }, 'test_invoice_4': { 'ref': 'test_invoice_4: Invoice to ADHOC with vat exempt and 21', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-01", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, {'product_id': self.product_iva_exento, 'price_unit': 100.0, 'quantity': 1}, ], }, 'test_invoice_5': { 'ref': 'test_invoice_5: Invoice to ADHOC with all type of taxes', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, {'product_id': self.service_iva_27, 'price_unit': 250.0, 'quantity': 1}, {'product_id': self.product_iva_105_perc, 'price_unit': 3245.0, 'quantity': 2}, {'product_id': self.product_no_gravado, 'price_unit': 50.0, 'quantity': 10}, {'product_id': self.product_iva_cero, 'price_unit': 200.0, 'quantity': 1}, {'product_id': self.product_iva_exento, 'price_unit': 100.0, 'quantity': 1} ], }, 'test_invoice_6': { 'ref': 'test_invoice_6: Invoice to cerro castor, fiscal position changes taxes to exempt', "partner_id": self.res_partner_cerrocastor, "journal_id": self.sale_expo_journal_ri, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-03", "company_id": self.company_ri, "invoice_incoterm_id": incoterm, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, {'product_id': self.service_iva_27, 'price_unit': 250.0, 'quantity': 1}, {'product_id': self.product_iva_105_perc, 'price_unit': 3245.0, 'quantity': 2}, {'product_id': self.product_no_gravado, 'price_unit': 50.0, 'quantity': 10}, {'product_id': self.product_iva_cero, 'price_unit': 200.0, 'quantity': 1}, {'product_id': self.product_iva_exento, 'price_unit': 100.0, 'quantity': 1}, ], }, 'test_invoice_7': { 'ref': 'test_invoice_7: Export invoice to expresso, fiscal position changes tax to exempt (type 4 because it have services)', "partner_id": self.res_partner_expresso, "journal_id": self.sale_expo_journal_ri, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-03", "company_id": self.company_ri, "invoice_incoterm_id": incoterm, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, {'product_id': self.service_iva_27, 'price_unit': 250.0, 'quantity': 1}, {'product_id': self.product_iva_105_perc, 'price_unit': 3245.0, 'quantity': 2}, {'product_id': self.product_no_gravado, 'price_unit': 50.0, 'quantity': 10}, {'product_id': self.product_iva_cero, 'price_unit': 200.0, 'quantity': 1}, {'product_id': self.product_iva_exento, 'price_unit': 100.0, 'quantity': 1}, ], }, 'test_invoice_8': { 'ref': 'test_invoice_8: Invoice to consumidor final', "partner_id": self.partner_cf, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21, 'price_unit': 642.0, 'quantity': 1}, ], }, 'test_invoice_10': { 'ref': 'test_invoice_10; Invoice to ADHOC in USD and vat 21', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 1000.0, 'quantity': 5}, ], "currency_id": self.env.ref("base.USD"), }, 'test_invoice_11': { 'ref': 'test_invoice_11: Invoice to ADHOC with many lines in order to prove rounding error, with 4 decimals of precision for the currency and 2 decimals for the product the error apperar', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21, 'price_unit': 1.12, 'quantity': 1, 'name': 'Support Services 1'}, {'product_id': self.service_iva_21, 'price_unit': 1.12, 'quantity': 1, 'name': 'Support Services 2'}, {'product_id': self.service_iva_21, 'price_unit': 1.12, 'quantity': 1, 'name': 'Support Services 3'}, {'product_id': self.service_iva_21, 'price_unit': 1.12, 'quantity': 1, 'name': 'Support Services 4'}, ], }, 'test_invoice_12': { 'ref': 'test_invoice_12: Invoice to ADHOC with many lines in order to test rounding error, it is required to use a 4 decimal precision in prodct in order to the error occur', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21, 'price_unit': 15.7076, 'quantity': 1, 'name': 'Support Services 1'}, {'product_id': self.service_iva_21, 'price_unit': 5.3076, 'quantity': 2, 'name': 'Support Services 2'}, {'product_id': self.service_iva_21, 'price_unit': 3.5384, 'quantity': 2, 'name': 'Support Services 3'}, {'product_id': self.service_iva_21, 'price_unit': 1.6376, 'quantity': 2, 'name': 'Support Services 4'}, ], }, 'test_invoice_13': { 'ref': 'test_invoice_13: Invoice to ADHOC with many lines in order to test zero amount invoices y rounding error. it is required to set the product decimal precision to 4 and change 260.59 for 260.60 in order to reproduce the error', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21, 'price_unit': 24.3, 'quantity': 3, 'name': 'Support Services 1'}, {'product_id': self.service_iva_21, 'price_unit': 260.59, 'quantity': 1, 'name': 'Support Services 2'}, {'product_id': self.service_iva_21, 'price_unit': 48.72, 'quantity': 1, 'name': 'Support Services 3'}, {'product_id': self.service_iva_21, 'price_unit': 13.666, 'quantity': 1, 'name': 'Support Services 4'}, {'product_id': self.service_iva_21, 'price_unit': 11.329, 'quantity': 2, 'name': 'Support Services 5'}, {'product_id': self.service_iva_21, 'price_unit': 68.9408, 'quantity': 1, 'name': 'Support Services 6'}, {'product_id': self.service_iva_21, 'price_unit': 4.7881, 'quantity': 2, 'name': 'Support Services 7'}, {'product_id': self.service_iva_21, 'price_unit': 12.0625, 'quantity': 2, 'name': 'Support Services 8'}, ], }, 'test_invoice_14': { 'ref': 'test_invoice_14: Export invoice to expresso, fiscal position changes tax to exempt (type 1 because only products)', "partner_id": self.res_partner_expresso, "journal_id": self.sale_expo_journal_ri, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-20", "company_id": self.company_ri, "invoice_incoterm_id": incoterm, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, ], }, 'test_invoice_15': { 'ref': 'test_invoice_15: Export invoice to expresso, fiscal position changes tax to exempt (type 2 because only service)', "partner_id": self.res_partner_expresso, "journal_id": self.sale_expo_journal_ri, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-20", "company_id": self.company_ri, "invoice_incoterm_id": incoterm, "invoice_line_ids": [ {'product_id': self.service_iva_27, 'price_unit': 250.0, 'quantity': 1}, ], }, 'test_invoice_16': { 'ref': 'test_invoice_16: Export invoice to expresso, fiscal position changes tax to exempt (type 1 because it have products only, used to test refund of expo)', "partner_id": self.res_partner_expresso, "journal_id": self.sale_expo_journal_ri, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-22", "company_id": self.company_ri, "invoice_incoterm_id": incoterm, "invoice_line_ids": [ {'product_id': self.product_iva_105, 'price_unit': 642.0, 'quantity': 5}, ], }, 'test_invoice_17': { 'ref': 'test_invoice_17: Invoice to ADHOC with 100%% of discount', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21, 'price_unit': 24.3, 'quantity': 3, 'name': 'Support Services 8', 'discount': 100}, ], }, 'test_invoice_18': { 'ref': 'test_invoice_18: Invoice to ADHOC with 100%% of discount and with different VAT aliquots', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21, 'price_unit': 24.3, 'quantity': 3, 'name': 'Support Services 8', 'discount': 100}, {'product_id': self.service_iva_27, 'price_unit': 250.0, 'quantity': 1, 'discount': 100}, {'product_id': self.product_iva_105_perc, 'price_unit': 3245.0, 'quantity': 1}, ], }, 'test_invoice_19': { 'ref': 'test_invoice_19: Invoice to ADHOC with multiple taxes and perceptions', "partner_id": self.res_partner_adhoc, "invoice_user_id": invoice_user_id, "invoice_payment_term_id": payment_term_id, "move_type": 'out_invoice', "invoice_date": "2021-03-13", "company_id": self.company_ri, "invoice_line_ids": [ {'product_id': self.service_iva_21, 'price_unit': 24.3, 'quantity': 3, 'name': 'Support Services 8'}, {'product_id': self.service_iva_27, 'price_unit': 250.0, 'quantity': 1}, {'product_id': self.product_iva_105_perc, 'price_unit': 3245.0, 'quantity': 1}, ], } } for key, values in invoices_to_create.items(): with Form(self.env['account.move'].with_context(default_move_type=values['move_type'])) as invoice_form: invoice_form.ref = values['ref'] invoice_form.partner_id = values['partner_id'] invoice_form.invoice_user_id = values['invoice_user_id'] invoice_form.invoice_payment_term_id = values['invoice_payment_term_id'] if not use_current_date: invoice_form.invoice_date = values['invoice_date'] if values.get('invoice_incoterm_id'): invoice_form.invoice_incoterm_id = values['invoice_incoterm_id'] for line in values['invoice_line_ids']: with invoice_form.invoice_line_ids.new() as line_form: line_form.product_id = line.get('product_id') line_form.price_unit = line.get('price_unit') line_form.quantity = line.get('quantity') if line.get('tax_ids'): line_form.tax_ids = line.get('tax_ids') line_form.name = 'xxxx' line_form.account_id = self.company_data['default_account_revenue'] invoice = invoice_form.save() self.demo_invoices[key] = invoice # Helpers @classmethod def _get_afip_pos_system_real_name(cls): return {'PREPRINTED': 'II_IM'} def _create_journal(self, afip_ws, data=None): """ Create a journal of a given AFIP ws type. If there is a problem because we are using a AFIP certificate that is already been in use then change the certificate and try again """ data = data or {} afip_ws = afip_ws.upper() pos_number = str(random.randint(0, 99999)) if 'l10n_ar_afip_pos_number' in data: pos_number = data.get('l10n_ar_afip_pos_number') values = {'name': '%s %s' % (afip_ws.replace('WS', ''), pos_number), 'type': 'sale', 'code': afip_ws, 'l10n_ar_afip_pos_system': self._get_afip_pos_system_real_name().get(afip_ws), 'l10n_ar_afip_pos_number': pos_number, 'l10n_latam_use_documents': True, 'company_id': self.env.company.id, 'l10n_ar_afip_pos_partner_id': self.partner_ri.id, 'sequence': 1} values.update(data) journal = self.env['account.journal'].create(values) _logger.info('Created journal %s for company %s' % (journal.name, self.env.company.name)) return journal def _create_invoice(self, data=None, invoice_type='out_invoice'): data = data or {} with Form(self.env['account.move'].with_context(default_move_type=invoice_type)) as invoice_form: invoice_form.partner_id = data.get('partner', self.partner) if 'in_' not in invoice_type: invoice_form.journal_id = data.get('journal', self.journal) if data.get('document_type'): invoice_form.l10n_latam_document_type_id = data.get('document_type') if data.get('document_number'): invoice_form.l10n_latam_document_number = data.get('document_number') if data.get('incoterm'): invoice_form.invoice_incoterm_id = data.get('incoterm') if data.get('currency'): invoice_form.currency_id = data.get('currency') for line in data.get('lines', [{}]): with invoice_form.invoice_line_ids.new() as invoice_line_form: if line.get('display_type'): invoice_line_form.display_type = line.get('display_type') invoice_line_form.name = line.get('name', 'not invoice line') else: invoice_line_form.product_id = line.get('product', self.product_iva_21) invoice_line_form.quantity = line.get('quantity', 1) invoice_line_form.price_unit = line.get('price_unit', 100) invoice_form.invoice_date = invoice_form.date invoice = invoice_form.save() return invoice def _create_invoice_product(self, data=None): data = data or {} return self._create_invoice(data) def _create_invoice_service(self, data=None): data = data or {} newlines = [] for line in data.get('lines', [{}]): line.update({'product': self.service_iva_27}) newlines.append(line) data.update({'lines': newlines}) return self._create_invoice(data) def _create_invoice_product_service(self, data=None): data = data or {} newlines = [] for line in data.get('lines', [{}]): line.update({'product': self.product_iva_21}) newlines.append(line) data.update({'lines': newlines + [{'product': self.service_iva_27}]}) return self._create_invoice(data) def _create_credit_note(self, invoice, data=None): data = data or {} refund_wizard = self.env['account.move.reversal'].with_context({'active_ids': [invoice.id], 'active_model': 'account.move'}).create({ 'reason': data.get('reason', 'Mercadería defectuosa'), 'refund_method': data.get('refund_method', 'refund'), 'journal_id': invoice.journal_id.id}) forced_document_type = data.get('document_type') if forced_document_type: refund_wizard.l10n_latam_document_type_id = forced_document_type.id res = refund_wizard.reverse_moves() refund = self.env['account.move'].browse(res['res_id']) return refund def _create_debit_note(self, invoice, data=None): data = data or {} debit_note_wizard = self.env['account.debit.note'].with_context( {'active_ids': [invoice.id], 'active_model': 'account.move', 'default_copy_lines': True}).create({ 'reason': data.get('reason', 'Mercadería defectuosa')}) res = debit_note_wizard.create_debit() debit_note = self.env['account.move'].browse(res['res_id']) return debit_note def _search_tax(self, tax_type, type_tax_use='sale'): res = self.env['account.tax'].with_context(active_test=False).search([ ('type_tax_use', '=', type_tax_use), ('company_id', '=', self.env.company.id), ('tax_group_id', '=', self.env.ref('l10n_ar.tax_group_' + tax_type).id)], limit=1) self.assertTrue(res, '%s Tax was not found' % (tax_type)) return res def _search_fp(self, name): return self.env['account.fiscal.position'].search([('company_id', '=', self.env.company.id), ('name', '=', name)]) def _post(self, invoice): invoice.action_post() self.assertEqual(invoice.state, 'posted') def _prepare_multicurrency_values(self): # Enable multi currency self.env.user.write({'groups_id': [(4, self.env.ref('base.group_multi_currency').id)]}) # Set ARS as main currency self._set_today_rate(self.env.ref('base.ARS'), 1.0) # Set Rates for USD currency self._set_today_rate(self.env.ref('base.USD'), 1.0 / 162.013) def _set_today_rate(self, currency, value): rate_obj = self.env['res.currency.rate'] rate = rate_obj.search([('currency_id', '=', currency.id), ('name', '=', fields.Date.to_string(fields.Date.today())), ('company_id', '=', self.env.company.id)]) if rate: rate.rate = value else: rate_obj.create({'company_id': self.env.company.id, 'currency_id': currency.id, 'rate': value})
50.862115
37,994
4,787
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from . import common from odoo.tests import tagged @tagged('post_install_l10n', '-at_install', 'post_install') class TestManual(common.TestAr): @classmethod def setUpClass(cls): super(TestManual, cls).setUpClass() cls.journal = cls._create_journal(cls, 'preprinted') cls.partner = cls.res_partner_adhoc cls._create_test_invoices_like_demo(cls) def test_01_create_invoice(self): """ Create and validate an invoice for a Responsable Inscripto * Proper set the current user company * Properly set the tax amount of the product / partner * Proper fiscal position (this case not fiscal position is selected) """ invoice = self._create_invoice() self.assertEqual(invoice.company_id, self.company_ri, 'created with wrong company') self.assertEqual(invoice.amount_tax, 21, 'invoice taxes are not properly set') self.assertEqual(invoice.amount_total, 121.0, 'invoice taxes has not been applied to the total') self.assertEqual(invoice.l10n_latam_document_type_id, self.document_type['invoice_a'], 'selected document type should be Factura A') self._post(invoice) self.assertEqual(invoice.state, 'posted', 'invoice has not been validate in Odoo') self.assertEqual(invoice.name, 'FA-A %05d-00000002' % self.journal.l10n_ar_afip_pos_number, 'Invoice number is wrong') def test_02_fiscal_position(self): # ADHOC SA > IVA Responsable Inscripto > Without Fiscal Positon invoice = self._create_invoice({'partner': self.partner}) self.assertFalse(invoice.fiscal_position_id, 'Fiscal position should be set to empty') # Consumidor Final > IVA Responsable Inscripto > Without Fiscal Positon invoice = self._create_invoice({'partner': self.partner_cf}) self.assertFalse(invoice.fiscal_position_id, 'Fiscal position should be set to empty') # Cerro Castor > IVA Liberado – Ley Nº 19.640 > Compras / Ventas Zona Franca > IVA Exento invoice = self._create_invoice({'partner': self.res_partner_cerrocastor}) self.assertEqual(invoice.fiscal_position_id, self._search_fp('Compras / Ventas Zona Franca')) # Expresso > Cliente / Proveedor del Exterior > > IVA Exento invoice = self._create_invoice({'partner': self.res_partner_expresso}) self.assertEqual(invoice.fiscal_position_id, self._search_fp('Compras / Ventas al exterior')) def test_03_corner_cases(self): """ Mono partner of type Service and VAT 21 """ self._post(self.demo_invoices['test_invoice_1']) def test_04_corner_cases(self): """ Exento partner with multiple VAT types 21, 27 and 10,5' """ self._post(self.demo_invoices['test_invoice_2']) def test_05_corner_cases(self): """ RI partner with VAT 0 and 21 """ self._post(self.demo_invoices['test_invoice_3']) def test_06_corner_cases(self): """ RI partner with VAT exempt and 21 """ self._post(self.demo_invoices['test_invoice_4']) def test_07_corner_cases(self): """ RI partner with all type of taxes """ self._post(self.demo_invoices['test_invoice_5']) def test_08_corner_cases(self): """ Consumidor Final """ self._post(self.demo_invoices['test_invoice_8']) def test_09_corner_cases(self): """ RI partner with many lines in order to prove rounding error, with 4 decimals of precision for the currency and 2 decimals for the product the error appear """ self._post(self.demo_invoices['test_invoice_11']) def test_10_corner_cases(self): """ RI partner with many lines in order to test rounding error, it is required to use a 4 decimal precision in product in order to the error occur """ self._post(self.demo_invoices['test_invoice_12']) def test_11_corner_cases(self): """ RI partner with many lines in order to test zero amount invoices y rounding error. it is required to set the product decimal precision to 4 and change 260,59 for 260.60 in order to reproduce the error """ self._post(self.demo_invoices['test_invoice_13']) def test_12_corner_cases(self): """ RI partner with 100%% of discount """ self._post(self.demo_invoices['test_invoice_17']) def test_13_corner_cases(self): """ RI partner with 100%% of discount and with different VAT aliquots """ self._post(self.demo_invoices['test_invoice_18']) def test_14_corner_cases(self): """ Responsable Inscripto" in USD and VAT 21 """ self._prepare_multicurrency_values() self._post(self.demo_invoices['test_invoice_10'])
48.323232
4,784
257
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class L10nLatamIdentificationType(models.Model): _inherit = "l10n_latam.identification.type" l10n_ar_afip_code = fields.Char("AFIP Code")
28.555556
257
22,650
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, _ from odoo.exceptions import UserError, RedirectWarning, ValidationError from dateutil.relativedelta import relativedelta import logging _logger = logging.getLogger(__name__) class AccountMove(models.Model): _inherit = 'account.move' @api.model def _l10n_ar_get_document_number_parts(self, document_number, document_type_code): # import shipments if document_type_code in ['66', '67']: pos = invoice_number = '0' else: pos, invoice_number = document_number.split('-') return {'invoice_number': int(invoice_number), 'point_of_sale': int(pos)} l10n_ar_afip_responsibility_type_id = fields.Many2one( 'l10n_ar.afip.responsibility.type', string='AFIP Responsibility Type', help='Defined by AFIP to' ' identify the type of responsibilities that a person or a legal entity could have and that impacts in the' ' type of operations and requirements they need.') l10n_ar_currency_rate = fields.Float(copy=False, digits=(16, 6), readonly=True, string="Currency Rate") # Mostly used on reports l10n_ar_afip_concept = fields.Selection( compute='_compute_l10n_ar_afip_concept', selection='_get_afip_invoice_concepts', string="AFIP Concept", help="A concept is suggested regarding the type of the products on the invoice but it is allowed to force a" " different type if required.") l10n_ar_afip_service_start = fields.Date(string='AFIP Service Start Date', readonly=True, states={'draft': [('readonly', False)]}) l10n_ar_afip_service_end = fields.Date(string='AFIP Service End Date', readonly=True, states={'draft': [('readonly', False)]}) @api.constrains('move_type', 'journal_id') def _check_moves_use_documents(self): """ Do not let to create not invoices entries in journals that use documents """ not_invoices = self.filtered(lambda x: x.company_id.account_fiscal_country_id.code == "AR" and x.journal_id.type in ['sale', 'purchase'] and x.l10n_latam_use_documents and not x.is_invoice()) if not_invoices: raise ValidationError(_("The selected Journal can't be used in this transaction, please select one that doesn't use documents as these are just for Invoices.")) @api.constrains('move_type', 'l10n_latam_document_type_id') def _check_invoice_type_document_type(self): """ LATAM module define that we are not able to use debit_note or invoice document types in an invoice refunds, However for Argentinian Document Type's 99 (internal type = invoice) we are able to used in a refund invoices. In this method we exclude the argentinian documents that can be used as invoice and refund from the generic constraint """ docs_used_for_inv_and_ref = self.filtered( lambda x: x.country_code == 'AR' and x.l10n_latam_document_type_id.code in self._get_l10n_ar_codes_used_for_inv_and_ref() and x.move_type in ['out_refund', 'in_refund']) super(AccountMove, self - docs_used_for_inv_and_ref)._check_invoice_type_document_type() def _get_afip_invoice_concepts(self): """ Return the list of values of the selection field. """ return [('1', 'Products / Definitive export of goods'), ('2', 'Services'), ('3', 'Products and Services'), ('4', '4-Other (export)')] @api.depends('invoice_line_ids', 'invoice_line_ids.product_id', 'invoice_line_ids.product_id.type', 'journal_id') def _compute_l10n_ar_afip_concept(self): recs_afip = self.filtered(lambda x: x.company_id.account_fiscal_country_id.code == "AR" and x.l10n_latam_use_documents) for rec in recs_afip: rec.l10n_ar_afip_concept = rec._get_concept() remaining = self - recs_afip remaining.l10n_ar_afip_concept = '' def _get_concept(self): """ Method to get the concept of the invoice considering the type of the products on the invoice """ self.ensure_one() invoice_lines = self.invoice_line_ids.filtered(lambda x: not x.display_type) product_types = set([x.product_id.type for x in invoice_lines if x.product_id]) consumable = set(['consu', 'product']) service = set(['service']) # on expo invoice you can mix services and products expo_invoice = self.l10n_latam_document_type_id.code in ['19', '20', '21'] # Default value "product" afip_concept = '1' if product_types == service: afip_concept = '2' elif product_types - consumable and product_types - service and not expo_invoice: afip_concept = '3' return afip_concept @api.model def _get_l10n_ar_codes_used_for_inv_and_ref(self): """ List of document types that can be used as an invoice and refund. This list can be increased once needed and demonstrated. As far as we've checked document types of wsfev1 don't allow negative amounts so, for example document 60 and 61 could not be used as refunds. """ return ['99', '186', '188', '189'] def _get_l10n_latam_documents_domain(self): self.ensure_one() domain = super()._get_l10n_latam_documents_domain() if self.journal_id.company_id.account_fiscal_country_id.code == "AR": letters = self.journal_id._get_journal_letter(counterpart_partner=self.partner_id.commercial_partner_id) domain += ['|', ('l10n_ar_letter', '=', False), ('l10n_ar_letter', 'in', letters)] codes = self.journal_id._get_journal_codes() if codes: domain.append(('code', 'in', codes)) if self.move_type == 'in_refund': domain = ['|', ('code', 'in', self._get_l10n_ar_codes_used_for_inv_and_ref())] + domain return domain def _check_argentinean_invoice_taxes(self): # check vat on companies thats has it (Responsable inscripto) for inv in self.filtered(lambda x: x.company_id.l10n_ar_company_requires_vat): purchase_aliquots = 'not_zero' # we require a single vat on each invoice line except from some purchase documents if inv.move_type in ['in_invoice', 'in_refund'] and inv.l10n_latam_document_type_id.purchase_aliquots == 'zero': purchase_aliquots = 'zero' for line in inv.mapped('invoice_line_ids').filtered(lambda x: x.display_type not in ('line_section', 'line_note')): vat_taxes = line.tax_ids.filtered(lambda x: x.tax_group_id.l10n_ar_vat_afip_code) if len(vat_taxes) != 1: raise UserError(_('There should be a single tax from the "VAT" tax group per line, add it to "%s". If you already have it, please check the tax configuration, in advanced options, in the corresponding field "Tax Group".') % line.name) elif purchase_aliquots == 'zero' and vat_taxes.tax_group_id.l10n_ar_vat_afip_code != '0': raise UserError(_('On invoice id "%s" you must use VAT Not Applicable on every line.') % inv.id) elif purchase_aliquots == 'not_zero' and vat_taxes.tax_group_id.l10n_ar_vat_afip_code == '0': raise UserError(_('On invoice id "%s" you must use VAT taxes different than VAT Not Applicable.') % inv.id) def _set_afip_service_dates(self): for rec in self.filtered(lambda m: m.invoice_date and m.l10n_ar_afip_concept in ['2', '3', '4']): if not rec.l10n_ar_afip_service_start: rec.l10n_ar_afip_service_start = rec.invoice_date + relativedelta(day=1) if not rec.l10n_ar_afip_service_end: rec.l10n_ar_afip_service_end = rec.invoice_date + relativedelta(day=1, days=-1, months=+1) def _set_afip_responsibility(self): """ We save the information about the receptor responsability at the time we validate the invoice, this is necessary because the user can change the responsability after that any time """ for rec in self: rec.l10n_ar_afip_responsibility_type_id = rec.commercial_partner_id.l10n_ar_afip_responsibility_type_id.id def _set_afip_rate(self): """ We set the l10n_ar_currency_rate value with the accounting date. This should be done after invoice has been posted in order to have the proper accounting date""" for rec in self: if rec.company_id.currency_id == rec.currency_id: rec.l10n_ar_currency_rate = 1.0 elif not rec.l10n_ar_currency_rate: rec.l10n_ar_currency_rate = rec.currency_id._convert( 1.0, rec.company_id.currency_id, rec.company_id, rec.date, round=False) @api.onchange('partner_id') def _onchange_afip_responsibility(self): if self.company_id.account_fiscal_country_id.code == 'AR' and self.l10n_latam_use_documents and self.partner_id \ and not self.partner_id.l10n_ar_afip_responsibility_type_id: return {'warning': { 'title': _('Missing Partner Configuration'), 'message': _('Please configure the AFIP Responsibility for "%s" in order to continue') % ( self.partner_id.name)}} @api.onchange('partner_id') def _onchange_partner_journal(self): """ This method is used when the invoice is created from the sale or subscription """ expo_journals = ['FEERCEL', 'FEEWS', 'FEERCELP'] for rec in self.filtered(lambda x: x.company_id.account_fiscal_country_id.code == "AR" and x.journal_id.type == 'sale' and x.l10n_latam_use_documents and x.partner_id.l10n_ar_afip_responsibility_type_id): res_code = rec.partner_id.l10n_ar_afip_responsibility_type_id.code domain = [('company_id', '=', rec.company_id.id), ('l10n_latam_use_documents', '=', True), ('type', '=', 'sale')] journal = self.env['account.journal'] msg = False if res_code in ['9', '10'] and rec.journal_id.l10n_ar_afip_pos_system not in expo_journals: # if partner is foregin and journal is not of expo, we try to change to expo journal journal = journal.search(domain + [('l10n_ar_afip_pos_system', 'in', expo_journals)], limit=1) msg = _('You are trying to create an invoice for foreign partner but you don\'t have an exportation journal') elif res_code not in ['9', '10'] and rec.journal_id.l10n_ar_afip_pos_system in expo_journals: # if partner is NOT foregin and journal is for expo, we try to change to local journal journal = journal.search(domain + [('l10n_ar_afip_pos_system', 'not in', expo_journals)], limit=1) msg = _('You are trying to create an invoice for domestic partner but you don\'t have a domestic market journal') if journal: rec.journal_id = journal.id elif msg: # Throw an error to user in order to proper configure the journal for the type of operation action = self.env.ref('account.action_account_journal_form') raise RedirectWarning(msg, action.id, _('Go to Journals')) def _post(self, soft=True): ar_invoices = self.filtered(lambda x: x.company_id.account_fiscal_country_id.code == "AR" and x.l10n_latam_use_documents) # We make validations here and not with a constraint because we want validation before sending electronic # data on l10n_ar_edi ar_invoices._check_argentinean_invoice_taxes() posted = super()._post(soft=soft) posted_ar_invoices = posted & ar_invoices posted_ar_invoices._set_afip_responsibility() posted_ar_invoices._set_afip_rate() posted_ar_invoices._set_afip_service_dates() return posted def _reverse_moves(self, default_values_list=None, cancel=False): if not default_values_list: default_values_list = [{} for move in self] for move, default_values in zip(self, default_values_list): default_values.update({ 'l10n_ar_afip_service_start': move.l10n_ar_afip_service_start, 'l10n_ar_afip_service_end': move.l10n_ar_afip_service_end, }) return super()._reverse_moves(default_values_list=default_values_list, cancel=cancel) @api.onchange('l10n_latam_document_type_id', 'l10n_latam_document_number') def _inverse_l10n_latam_document_number(self): super()._inverse_l10n_latam_document_number() to_review = self.filtered(lambda x: ( x.journal_id.type == 'sale' and x.l10n_latam_document_type_id and x.l10n_latam_document_number and (x.l10n_latam_manual_document_number or not x.highest_name) and x.l10n_latam_document_type_id.country_id.code == 'AR' )) for rec in to_review: number = rec.l10n_latam_document_type_id._format_document_number(rec.l10n_latam_document_number) current_pos = int(number.split("-")[0]) if current_pos != rec.journal_id.l10n_ar_afip_pos_number: invoices = self.search([('journal_id', '=', rec.journal_id.id), ('posted_before', '=', True)], limit=1) # If there is no posted before invoices the user can change the POS number (x.l10n_latam_document_number) if (not invoices): rec.journal_id.l10n_ar_afip_pos_number = current_pos rec.journal_id._onchange_set_short_name() # If not, avoid that the user change the POS number else: raise UserError(_('The document number can not be changed for this journal, you can only modify' ' the POS number if there is not posted (or posted before) invoices')) def _get_formatted_sequence(self, number=0): return "%s %05d-%08d" % (self.l10n_latam_document_type_id.doc_code_prefix, self.journal_id.l10n_ar_afip_pos_number, number) def _get_starting_sequence(self): """ If use documents then will create a new starting sequence using the document type code prefix and the journal document number with a 8 padding number """ if self.journal_id.l10n_latam_use_documents and self.company_id.account_fiscal_country_id.code == "AR": if self.l10n_latam_document_type_id: return self._get_formatted_sequence() return super()._get_starting_sequence() def _get_last_sequence(self, relaxed=False, with_prefix=None, lock=True): """ If use share sequences we need to recompute the sequence to add the proper document code prefix """ res = super()._get_last_sequence(relaxed=relaxed, with_prefix=with_prefix, lock=lock) if res and self.journal_id.l10n_ar_share_sequences and self.l10n_latam_document_type_id.doc_code_prefix not in res: res = self._get_formatted_sequence(number=self._l10n_ar_get_document_number_parts( res.split()[-1], self.l10n_latam_document_type_id.code)['invoice_number']) return res def _get_last_sequence_domain(self, relaxed=False): where_string, param = super(AccountMove, self)._get_last_sequence_domain(relaxed) if self.company_id.account_fiscal_country_id.code == "AR" and self.l10n_latam_use_documents: if not self.journal_id.l10n_ar_share_sequences: where_string += " AND l10n_latam_document_type_id = %(l10n_latam_document_type_id)s" param['l10n_latam_document_type_id'] = self.l10n_latam_document_type_id.id or 0 elif self.journal_id.l10n_ar_share_sequences: where_string += " AND l10n_latam_document_type_id in %(l10n_latam_document_type_ids)s" param['l10n_latam_document_type_ids'] = tuple(self.l10n_latam_document_type_id.search( [('l10n_ar_letter', '=', self.l10n_latam_document_type_id.l10n_ar_letter)]).ids) return where_string, param def _l10n_ar_get_amounts(self, company_currency=False): """ Method used to prepare data to present amounts and taxes related amounts when creating an electronic invoice for argentinean and the txt files for digital VAT books. Only take into account the argentinean taxes """ self.ensure_one() amount_field = company_currency and 'balance' or 'price_subtotal' # if we use balance we need to correct sign (on price_subtotal is positive for refunds and invoices) sign = -1 if (company_currency and self.is_inbound()) else 1 # if we are on a document that works invoice and refund and it's a refund, we need to export it as negative sign = -sign if self.move_type in ('out_refund', 'in_refund') and\ self.l10n_latam_document_type_id.code in self._get_l10n_ar_codes_used_for_inv_and_ref() else sign tax_lines = self.line_ids.filtered('tax_line_id') vat_taxes = tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id.l10n_ar_vat_afip_code) vat_taxable = self.env['account.move.line'] for line in self.invoice_line_ids: if any(tax.tax_group_id.l10n_ar_vat_afip_code and tax.tax_group_id.l10n_ar_vat_afip_code not in ['0', '1', '2'] for tax in line.tax_ids): vat_taxable |= line profits_tax_group = self.env.ref('l10n_ar.tax_group_percepcion_ganancias') return {'vat_amount': sign * sum(vat_taxes.mapped(amount_field)), # For invoices of letter C should not pass VAT 'vat_taxable_amount': sign * sum(vat_taxable.mapped(amount_field)) if self.l10n_latam_document_type_id.l10n_ar_letter != 'C' else self.amount_untaxed, 'vat_exempt_base_amount': sign * sum(self.invoice_line_ids.filtered(lambda x: x.tax_ids.filtered(lambda y: y.tax_group_id.l10n_ar_vat_afip_code == '2')).mapped(amount_field)), 'vat_untaxed_base_amount': sign * sum(self.invoice_line_ids.filtered(lambda x: x.tax_ids.filtered(lambda y: y.tax_group_id.l10n_ar_vat_afip_code == '1')).mapped(amount_field)), # used on FE 'not_vat_taxes_amount': sign * sum((tax_lines - vat_taxes).mapped(amount_field)), # used on BFE + TXT 'iibb_perc_amount': sign * sum(tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id.l10n_ar_tribute_afip_code == '07').mapped(amount_field)), 'mun_perc_amount': sign * sum(tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id.l10n_ar_tribute_afip_code == '08').mapped(amount_field)), 'intern_tax_amount': sign * sum(tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id.l10n_ar_tribute_afip_code == '04').mapped(amount_field)), 'other_taxes_amount': sign * sum(tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id.l10n_ar_tribute_afip_code == '99').mapped(amount_field)), 'profits_perc_amount': sign * sum(tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id == profits_tax_group).mapped(amount_field)), 'vat_perc_amount': sign * sum(tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id.l10n_ar_tribute_afip_code == '06').mapped(amount_field)), 'other_perc_amount': sign * sum(tax_lines.filtered(lambda r: r.tax_line_id.tax_group_id.l10n_ar_tribute_afip_code == '09' and r.tax_line_id.tax_group_id != profits_tax_group).mapped(amount_field)), } def _get_vat(self): """ Applies on wsfe web service and in the VAT digital books """ # if we are on a document that works invoice and refund and it's a refund, we need to export it as negative sign = -1 if self.move_type in ('out_refund', 'in_refund') and\ self.l10n_latam_document_type_id.code in self._get_l10n_ar_codes_used_for_inv_and_ref() else 1 res = [] vat_taxable = self.env['account.move.line'] # get all invoice lines that are vat taxable for line in self.line_ids: if any(tax.tax_group_id.l10n_ar_vat_afip_code and tax.tax_group_id.l10n_ar_vat_afip_code not in ['0', '1', '2'] for tax in line.tax_line_id) and line['price_subtotal']: vat_taxable |= line for tax_group in vat_taxable.mapped('tax_group_id'): base_imp = sum(self.invoice_line_ids.filtered(lambda x: x.tax_ids.filtered(lambda y: y.tax_group_id.l10n_ar_vat_afip_code == tax_group.l10n_ar_vat_afip_code)).mapped('price_subtotal')) imp = sum(vat_taxable.filtered(lambda x: x.tax_group_id.l10n_ar_vat_afip_code == tax_group.l10n_ar_vat_afip_code).mapped('price_subtotal')) res += [{'Id': tax_group.l10n_ar_vat_afip_code, 'BaseImp': sign * base_imp, 'Importe': sign * imp}] # Report vat 0% vat_base_0 = sum(self.invoice_line_ids.filtered(lambda x: x.tax_ids.filtered(lambda y: y.tax_group_id.l10n_ar_vat_afip_code == '3')).mapped('price_subtotal')) if vat_base_0: res += [{'Id': '3', 'BaseImp': vat_base_0, 'Importe': 0.0}] return res if res else [] def _get_name_invoice_report(self): self.ensure_one() if self.l10n_latam_use_documents and self.company_id.account_fiscal_country_id.code == 'AR': return 'l10n_ar.report_invoice_document' return super()._get_name_invoice_report() def _l10n_ar_get_invoice_totals_for_report(self): self.ensure_one() tax_ids_filter = tax_line_id_filter = None include_vat = self._l10n_ar_include_vat() if include_vat: tax_ids_filter = (lambda aml, tax: not bool(tax.tax_group_id.l10n_ar_vat_afip_code)) tax_line_id_filter = (lambda aml, tax: not bool(tax.tax_group_id.l10n_ar_vat_afip_code)) tax_lines_data = self._prepare_tax_lines_data_for_totals_from_invoice( tax_ids_filter=tax_ids_filter, tax_line_id_filter=tax_line_id_filter) if include_vat: amount_untaxed = self.currency_id.round( self.amount_total - sum([x['tax_amount'] for x in tax_lines_data if 'tax_amount' in x])) else: amount_untaxed = self.amount_untaxed return self._get_tax_totals(self.partner_id, tax_lines_data, self.amount_total, amount_untaxed, self.currency_id) def _l10n_ar_include_vat(self): self.ensure_one() return self.l10n_latam_document_type_id.l10n_ar_letter in ['B', 'C', 'X', 'R']
63.802817
22,650
912
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResCountry(models.Model): _inherit = 'res.country' l10n_ar_afip_code = fields.Char('AFIP Code', size=3, help='This code will be used on electronic invoice') l10n_ar_natural_vat = fields.Char( 'Natural Person VAT', size=11, help="Generic VAT number defined by AFIP in order to recognize partners from" " this country that are natural persons") l10n_ar_legal_entity_vat = fields.Char( 'Legal Entity VAT', size=11, help="Generic VAT number defined by AFIP in order to recognize partners from this" " country that are legal entity") l10n_ar_other_vat = fields.Char( 'Other VAT', size=11, help="Generic VAT number defined by AFIP in order to recognize partners from this" " country that are not natural persons or legal entities")
48
912
7,061
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api, _ from odoo.exceptions import ValidationError, RedirectWarning class AccountJournal(models.Model): _inherit = "account.journal" l10n_ar_afip_pos_system = fields.Selection( selection='_get_l10n_ar_afip_pos_types_selection', string='AFIP POS System') l10n_ar_afip_pos_number = fields.Integer( 'AFIP POS Number', help='This is the point of sale number assigned by AFIP in order to generate invoices') company_partner = fields.Many2one('res.partner', related='company_id.partner_id') l10n_ar_afip_pos_partner_id = fields.Many2one( 'res.partner', 'AFIP POS Address', help='This is the address used for invoice reports of this POS', domain="['|', ('id', '=', company_partner), '&', ('id', 'child_of', company_partner), ('type', '!=', 'contact')]" ) l10n_ar_share_sequences = fields.Boolean( 'Unified Book', help='Use same sequence for documents with the same letter') def _get_l10n_ar_afip_pos_types_selection(self): """ Return the list of values of the selection field. """ return [ ('II_IM', _('Pre-printed Invoice')), ('RLI_RLM', _('Online Invoice')), ('BFERCEL', _('Electronic Fiscal Bond - Online Invoice')), ('FEERCELP', _('Export Voucher - Billing Plus')), ('FEERCEL', _('Export Voucher - Online Invoice')), ('CPERCEL', _('Product Coding - Online Voucher')), ] def _get_journal_letter(self, counterpart_partner=False): """ Regarding the AFIP responsibility of the company and the type of journal (sale/purchase), get the allowed letters. Optionally, receive the counterpart partner (customer/supplier) and get the allowed letters to work with him. This method is used to populate document types on journals and also to filter document types on specific invoices to/from customer/supplier """ self.ensure_one() letters_data = { 'issued': { '1': ['A', 'B', 'E', 'M'], '3': [], '4': ['C'], '5': [], '6': ['C', 'E'], '9': ['I'], '10': [], '13': ['C', 'E'], '99': [] }, 'received': { '1': ['A', 'B', 'C', 'E', 'M', 'I'], '3': ['B', 'C', 'I'], '4': ['B', 'C', 'I'], '5': ['B', 'C', 'I'], '6': ['A', 'B', 'C', 'I'], '9': ['E'], '10': ['E'], '13': ['A', 'B', 'C', 'I'], '99': ['B', 'C', 'I'] }, } if not self.company_id.l10n_ar_afip_responsibility_type_id: action = self.env.ref('base.action_res_company_form') msg = _('Can not create chart of account until you configure your company AFIP Responsibility and VAT.') raise RedirectWarning(msg, action.id, _('Go to Companies')) letters = letters_data['issued' if self.type == 'sale' else 'received'][ self.company_id.l10n_ar_afip_responsibility_type_id.code] if counterpart_partner: counterpart_letters = letters_data['issued' if self.type == 'purchase' else 'received'].get( counterpart_partner.l10n_ar_afip_responsibility_type_id.code, []) letters = list(set(letters) & set(counterpart_letters)) return letters def _get_journal_codes(self): self.ensure_one() if self.type != 'sale': return [] return self._get_codes_per_journal_type(self.l10n_ar_afip_pos_system) @api.model def _get_codes_per_journal_type(self, afip_pos_system): usual_codes = ['1', '2', '3', '6', '7', '8', '11', '12', '13'] mipyme_codes = ['201', '202', '203', '206', '207', '208', '211', '212', '213'] invoice_m_code = ['51', '52', '53'] receipt_m_code = ['54'] receipt_codes = ['4', '9', '15'] expo_codes = ['19', '20', '21'] if afip_pos_system == 'II_IM': # pre-printed invoice return usual_codes + receipt_codes + expo_codes + invoice_m_code + receipt_m_code elif afip_pos_system in ['RAW_MAW', 'RLI_RLM']: # electronic/online invoice return usual_codes + receipt_codes + invoice_m_code + receipt_m_code + mipyme_codes elif afip_pos_system in ['CPERCEL', 'CPEWS']: # invoice with detail return usual_codes + invoice_m_code elif afip_pos_system in ['BFERCEL', 'BFEWS']: # Bonds invoice return usual_codes + mipyme_codes elif afip_pos_system in ['FEERCEL', 'FEEWS', 'FEERCELP']: return expo_codes @api.constrains('type', 'l10n_ar_afip_pos_system', 'l10n_ar_afip_pos_number', 'l10n_ar_share_sequences', 'l10n_latam_use_documents') def _check_afip_configurations(self): """ Do not let the user update the journal if it already contains confirmed invoices """ journals = self.filtered(lambda x: x.company_id.account_fiscal_country_id.code == "AR" and x.type in ['sale', 'purchase']) invoices = self.env['account.move'].search([('journal_id', 'in', journals.ids), ('posted_before', '=', True)], limit=1) if invoices: raise ValidationError( _("You can not change the journal's configuration if it already has validated invoices") + ' (' + ', '.join(invoices.mapped('journal_id').mapped('name')) + ')') @api.constrains('l10n_ar_afip_pos_number') def _check_afip_pos_number(self): to_review = self.filtered( lambda x: x.type == 'sale' and x.l10n_latam_use_documents and x.company_id.account_fiscal_country_id.code == "AR") if to_review.filtered(lambda x: x.l10n_ar_afip_pos_number == 0): raise ValidationError(_('Please define an AFIP POS number')) if to_review.filtered(lambda x: x.l10n_ar_afip_pos_number > 99999): raise ValidationError(_('Please define a valid AFIP POS number (5 digits max)')) @api.onchange('l10n_ar_afip_pos_system') def _onchange_l10n_ar_afip_pos_system(self): """ On 'Pre-printed Invoice' the usual is to share sequences. On other types, do not share """ self.l10n_ar_share_sequences = bool(self.l10n_ar_afip_pos_system == 'II_IM') @api.onchange('l10n_ar_afip_pos_number', 'type') def _onchange_set_short_name(self): """ Will define the AFIP POS Address field domain taking into account the company configured in the journal The short code of the journal only admit 5 characters, so depending on the size of the pos_number (also max 5) we add or not a prefix to identify sales journal. """ if self.type == 'sale' and self.l10n_ar_afip_pos_number: self.code = "%05i" % self.l10n_ar_afip_pos_number
49.725352
7,061
2,997
py
PYTHON
15.0
from odoo import models, api, fields, _ from odoo.exceptions import UserError class L10nLatamDocumentType(models.Model): _inherit = 'l10n_latam.document.type' l10n_ar_letter = fields.Selection( selection='_get_l10n_ar_letters', string='Letters', help='Letters defined by the AFIP that can be used to identify the' ' documents presented to the government and that depends on the' ' operation type, the responsibility of both the issuer and the' ' receptor of the document') purchase_aliquots = fields.Selection( [('not_zero', 'Not Zero'), ('zero', 'Zero')], help='Raise an error if a vendor bill is miss encoded. "Not Zero"' ' means the VAT taxes are required for the invoices related to this document type, and those with "Zero" means' ' that only "VAT Not Applicable" tax is allowed.') def _get_l10n_ar_letters(self): """ Return the list of values of the selection field. """ return [ ('A', 'A'), ('B', 'B'), ('C', 'C'), ('E', 'E'), ('M', 'M'), ('T', 'T'), ('R', 'R'), ('X', 'X'), ('I', 'I'), # used for mapping of imports ] def _format_document_number(self, document_number): """ Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it """ self.ensure_one() if self.country_id.code != "AR": return super()._format_document_number(document_number) if not document_number: return False msg = "'%s' " + _("is not a valid value for") + " '%s'.<br/>%s" if not self.code: return document_number # Import Dispatch Number Validator if self.code in ['66', '67']: if len(document_number) != 16: raise UserError(msg % (document_number, self.name, _('The number of import Dispatch must be 16 characters'))) return document_number # Invoice Number Validator (For Eg: 123-123) failed = False args = document_number.split('-') if len(args) != 2: failed = True else: pos, number = args if len(pos) > 5 or not pos.isdigit(): failed = True elif len(number) > 8 or not number.isdigit(): failed = True document_number = '{:>05s}-{:>08s}'.format(pos, number) if failed: raise UserError(msg % (document_number, self.name, _( 'The document number must be entered with a dash (-) and a maximum of 5 characters for the first part' 'and 8 for the second. The following are examples of valid numbers:\n* 1-1\n* 0001-00000001' '\n* 00001-00000001'))) return document_number
39.434211
2,997
1,360
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class AccountMoveLine(models.Model): _inherit = 'account.move.line' def _l10n_ar_prices_and_taxes(self): self.ensure_one() invoice = self.move_id included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else False if not included_taxes: price_unit = self.tax_ids.with_context(round=False).compute_all( self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id) price_unit = price_unit['total_excluded'] price_subtotal = self.price_subtotal else: price_unit = included_taxes.compute_all( self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)['total_included'] price = self.price_unit * (1 - (self.discount or 0.0) / 100.0) price_subtotal = included_taxes.compute_all( price, invoice.currency_id, self.quantity, self.product_id, invoice.partner_id)['total_included'] price_net = price_unit * (1 - (self.discount or 0.0) / 100.0) return { 'price_unit': price_unit, 'price_subtotal': price_subtotal, 'price_net': price_net, }
45.333333
1,360
1,142
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class AccountTaxGroup(models.Model): _inherit = 'account.tax.group' # values from http://www.afip.gob.ar/fe/documentos/otros_Tributos.xlsx l10n_ar_tribute_afip_code = fields.Selection([ ('01', '01 - National Taxes'), ('02', '02 - Provincial Taxes'), ('03', '03 - Municipal Taxes'), ('04', '04 - Internal Taxes'), ('06', '06 - VAT perception'), ('07', '07 - IIBB perception'), ('08', '08 - Municipal Taxes Perceptions'), ('09', '09 - Other Perceptions'), ('99', '99 - Others'), ], string='Tribute AFIP Code', index=True, readonly=True) # values from http://www.afip.gob.ar/fe/documentos/OperacionCondicionIVA.xls l10n_ar_vat_afip_code = fields.Selection([ ('0', 'Not Applicable'), ('1', 'Untaxed'), ('2', 'Exempt'), ('3', '0%'), ('4', '10.5%'), ('5', '21%'), ('6', '27%'), ('8', '5%'), ('9', '2,5%'), ], string='VAT AFIP Code', index=True, readonly=True)
35.6875
1,142
416
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class AccountFiscalPositionTemplate(models.Model): _inherit = 'account.fiscal.position.template' l10n_ar_afip_responsibility_type_ids = fields.Many2many( 'l10n_ar.afip.responsibility.type', 'l10n_ar_afip_reponsibility_type_fiscal_pos_temp_rel', string='AFIP Responsibility Types')
37.818182
416
1,675
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, api, _ from odoo.exceptions import ValidationError import logging _logger = logging.getLogger(__name__) try: from stdnum.ar.cbu import validate as validate_cbu except ImportError: import stdnum _logger.warning("stdnum.ar.cbu is avalaible from stdnum >= 1.6. The one installed is %s" % stdnum.__version__) def validate_cbu(number): def _check_digit(number): """Calculate the check digit.""" weights = (3, 1, 7, 9) check = sum(int(n) * weights[i % 4] for i, n in enumerate(reversed(number))) return str((10 - check) % 10) number = stdnum.util.clean(number, ' -').strip() if len(number) != 22: raise ValidationError('Invalid Length') if not number.isdigit(): raise ValidationError('Invalid Format') if _check_digit(number[:7]) != number[7]: raise ValidationError('Invalid Checksum') if _check_digit(number[8:-1]) != number[-1]: raise ValidationError('Invalid Checksum') return number class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' @api.model def _get_supported_account_types(self): """ Add new account type named cbu used in Argentina """ res = super()._get_supported_account_types() res.append(('cbu', _('CBU'))) return res @api.model def retrieve_acc_type(self, acc_number): try: validate_cbu(acc_number) except Exception: return super().retrieve_acc_type(acc_number) return 'cbu'
34.183673
1,675
2,456
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api, _ from odoo.exceptions import ValidationError class ResCompany(models.Model): _inherit = "res.company" l10n_ar_gross_income_number = fields.Char( related='partner_id.l10n_ar_gross_income_number', string='Gross Income Number', readonly=False, help="This field is required in order to print the invoice report properly") l10n_ar_gross_income_type = fields.Selection( related='partner_id.l10n_ar_gross_income_type', string='Gross Income', readonly=False, help="This field is required in order to print the invoice report properly") l10n_ar_afip_responsibility_type_id = fields.Many2one( domain="[('code', 'in', [1, 4, 6])]", related='partner_id.l10n_ar_afip_responsibility_type_id', readonly=False) l10n_ar_company_requires_vat = fields.Boolean(compute='_compute_l10n_ar_company_requires_vat', string='Company Requires Vat?') l10n_ar_afip_start_date = fields.Date('Activities Start') @api.onchange('country_id') def onchange_country(self): """ Argentinean companies use round_globally as tax_calculation_rounding_method """ for rec in self.filtered(lambda x: x.country_id.code == "AR"): rec.tax_calculation_rounding_method = 'round_globally' @api.depends('l10n_ar_afip_responsibility_type_id') def _compute_l10n_ar_company_requires_vat(self): recs_requires_vat = self.filtered(lambda x: x.l10n_ar_afip_responsibility_type_id.code == '1') recs_requires_vat.l10n_ar_company_requires_vat = True remaining = self - recs_requires_vat remaining.l10n_ar_company_requires_vat = False def _localization_use_documents(self): """ Argentinean localization use documents """ self.ensure_one() return self.account_fiscal_country_id.code == "AR" or super()._localization_use_documents() @api.constrains('l10n_ar_afip_responsibility_type_id') def _check_accounting_info(self): """ Do not let to change the AFIP Responsibility of the company if there is already installed a chart of account and if there has accounting entries """ if self.env['account.chart.template'].existing_accounting(self): raise ValidationError(_( 'Could not change the AFIP Responsibility of this company because there are already accounting entries.'))
55.818182
2,456
284
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResCurrency(models.Model): _inherit = "res.currency" l10n_ar_afip_code = fields.Char('AFIP Code', size=4, help='This code will be used on electronic invoice')
31.555556
284
263
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Uom(models.Model): _inherit = 'uom.uom' l10n_ar_afip_code = fields.Char('AFIP Code', help='This code will be used on electronic invoice')
29.222222
263
3,544
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, api, _ from odoo.exceptions import UserError from odoo.http import request class AccountChartTemplate(models.Model): _inherit = 'account.chart.template' def _get_fp_vals(self, company, position): res = super()._get_fp_vals(company, position) if company.country_id.code == "AR": res['l10n_ar_afip_responsibility_type_ids'] = [ (6, False, position.l10n_ar_afip_responsibility_type_ids.ids)] return res def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None): """ In case of an Argentinean CoA, we modify the default values of the sales journal to be a preprinted journal""" res = super()._prepare_all_journals(acc_template_ref, company, journals_dict=journals_dict) if company.country_id.code == "AR": for vals in res: if vals['type'] == 'sale': vals.update({ "name": "Ventas Preimpreso", "code": "0001", "l10n_ar_afip_pos_number": 1, "l10n_ar_afip_pos_partner_id": company.partner_id.id, "l10n_ar_afip_pos_system": 'II_IM', "l10n_ar_share_sequences": True, "refund_sequence": False }) return res @api.model def _get_ar_responsibility_match(self, chart_template_id): """ return responsibility type that match with the given chart_template_id """ match = { self.env.ref('l10n_ar.l10nar_base_chart_template').id: self.env.ref('l10n_ar.res_RM'), self.env.ref('l10n_ar.l10nar_ex_chart_template').id: self.env.ref('l10n_ar.res_IVAE'), self.env.ref('l10n_ar.l10nar_ri_chart_template').id: self.env.ref('l10n_ar.res_IVARI'), } return match.get(chart_template_id) def _load(self, sale_tax_rate, purchase_tax_rate, company): """ Set companies AFIP Responsibility and Country if AR CoA is installed, also set tax calculation rounding method required in order to properly validate match AFIP invoices. Also, raise a warning if the user is trying to install a CoA that does not match with the defined AFIP Responsibility defined in the company """ self.ensure_one() coa_responsibility = self._get_ar_responsibility_match(self.id) if coa_responsibility: company_responsibility = company.l10n_ar_afip_responsibility_type_id company.write({ 'l10n_ar_afip_responsibility_type_id': coa_responsibility.id, 'country_id': self.env['res.country'].search([('code', '=', 'AR')]).id, 'tax_calculation_rounding_method': 'round_globally', }) # set CUIT identification type (which is the argentinean vat) in the created company partner instead of # the default VAT type. company.partner_id.l10n_latam_identification_type_id = self.env.ref('l10n_ar.it_cuit') res = super()._load(sale_tax_rate, purchase_tax_rate, company) # If Responsable Monotributista remove the default purchase tax if self == self.env.ref('l10n_ar.l10nar_base_chart_template') or \ self == self.env.ref('l10n_ar.l10nar_ex_chart_template'): company.account_purchase_tax_id = self.env['account.tax'] return res
47.891892
3,544
602
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class L10nArAfipResponsibilityType(models.Model): _name = 'l10n_ar.afip.responsibility.type' _description = 'AFIP Responsibility Type' _order = 'sequence' name = fields.Char(required=True, index=True) sequence = fields.Integer() code = fields.Char(required=True, index=True) active = fields.Boolean(default=True) _sql_constraints = [('name', 'unique(name)', 'Name must be unique!'), ('code', 'unique(code)', 'Code must be unique!')]
33.444444
602
2,318
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api, _ class AccountFiscalPosition(models.Model): _inherit = 'account.fiscal.position' l10n_ar_afip_responsibility_type_ids = fields.Many2many( 'l10n_ar.afip.responsibility.type', 'l10n_ar_afip_reponsibility_type_fiscal_pos_rel', string='AFIP Responsibility Types', help='List of AFIP responsibilities where this fiscal position ' 'should be auto-detected') @api.model def get_fiscal_position(self, partner_id, delivery_id=None): """ Take into account the partner afip responsibility in order to auto-detect the fiscal position """ company = self.env.company if company.country_id.code == "AR": PartnerObj = self.env['res.partner'] partner = PartnerObj.browse(partner_id) # if no delivery use invoicing if delivery_id: delivery = PartnerObj.browse(delivery_id) else: delivery = partner # partner manually set fiscal position always win if delivery.property_account_position_id or partner.property_account_position_id: return delivery.property_account_position_id or partner.property_account_position_id domain = [ ('auto_apply', '=', True), ('l10n_ar_afip_responsibility_type_ids', '=', self.env['res.partner'].browse( partner_id).l10n_ar_afip_responsibility_type_id.id), ('company_id', '=', company.id), ] return self.sudo().search(domain, limit=1) return super().get_fiscal_position(partner_id, delivery_id=delivery_id) @api.onchange('l10n_ar_afip_responsibility_type_ids', 'country_group_id', 'country_id', 'zip_from', 'zip_to') def _onchange_afip_responsibility(self): if self.company_id.account_fiscal_country_id.code == "AR": if self.l10n_ar_afip_responsibility_type_ids and any(['country_group_id', 'country_id', 'zip_from', 'zip_to']): return {'warning': { 'title': _("Warning"), 'message': _('If use AFIP Responsibility then the country / zip codes will be not take into account'), }}
49.319149
2,318
6,558
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api, _ from odoo.exceptions import UserError, ValidationError import stdnum.ar import re import logging _logger = logging.getLogger(__name__) class ResPartner(models.Model): _inherit = 'res.partner' l10n_ar_vat = fields.Char( compute='_compute_l10n_ar_vat', string="VAT", help='Computed field that returns VAT or nothing if this one' ' is not set for the partner') l10n_ar_formatted_vat = fields.Char( compute='_compute_l10n_ar_formatted_vat', string="Formatted VAT", help='Computed field that will convert the' ' given VAT number to the format {person_category:2}-{number:10}-{validation_number:1}') l10n_ar_gross_income_number = fields.Char('Gross Income Number') l10n_ar_gross_income_type = fields.Selection( [('multilateral', 'Multilateral'), ('local', 'Local'), ('exempt', 'Exempt')], 'Gross Income Type', help='Type of gross income: exempt, local, multilateral') l10n_ar_afip_responsibility_type_id = fields.Many2one( 'l10n_ar.afip.responsibility.type', string='AFIP Responsibility Type', index=True, help='Defined by AFIP to' ' identify the type of responsibilities that a person or a legal entity could have and that impacts in the' ' type of operations and requirements they need.') l10n_ar_special_purchase_document_type_ids = fields.Many2many( 'l10n_latam.document.type', 'res_partner_document_type_rel', 'partner_id', 'document_type_id', string='Other Purchase Documents', help='Set here if this partner can issue other documents further than' ' invoices, credit notes and debit notes') @api.depends('l10n_ar_vat') def _compute_l10n_ar_formatted_vat(self): """ This will add some dash to the CUIT number (VAT AR) in order to show in his natural format: {person_category}-{number}-{validation_number} """ recs_ar_vat = self.filtered('l10n_ar_vat') for rec in recs_ar_vat: try: rec.l10n_ar_formatted_vat = stdnum.ar.cuit.format(rec.l10n_ar_vat) except Exception as error: rec.l10n_ar_formatted_vat = rec.l10n_ar_vat _logger.runbot("Argentinean VAT was not formatted: %s", repr(error)) remaining = self - recs_ar_vat remaining.l10n_ar_formatted_vat = False @api.depends('vat', 'l10n_latam_identification_type_id') def _compute_l10n_ar_vat(self): """ We add this computed field that returns cuit (VAT AR) or nothing if this one is not set for the partner. This Validation can be also done by calling ensure_vat() method that returns the cuit (VAT AR) or error if this one is not found """ recs_ar_vat = self.filtered(lambda x: x.l10n_latam_identification_type_id.l10n_ar_afip_code == '80' and x.vat) for rec in recs_ar_vat: rec.l10n_ar_vat = stdnum.ar.cuit.compact(rec.vat) remaining = self - recs_ar_vat remaining.l10n_ar_vat = False @api.constrains('vat', 'l10n_latam_identification_type_id') def check_vat(self): """ Since we validate more documents than the vat for Argentinean partners (CUIT - VAT AR, CUIL, DNI) we extend this method in order to process it. """ # NOTE by the moment we include the CUIT (VAT AR) validation also here because we extend the messages # errors to be more friendly to the user. In a future when Odoo improve the base_vat message errors # we can change this method and use the base_vat.check_vat_ar method.s l10n_ar_partners = self.filtered(lambda x: x.l10n_latam_identification_type_id.l10n_ar_afip_code) l10n_ar_partners.l10n_ar_identification_validation() return super(ResPartner, self - l10n_ar_partners).check_vat() @api.model def _commercial_fields(self): return super()._commercial_fields() + ['l10n_ar_afip_responsibility_type_id'] def ensure_vat(self): """ This method is a helper that returns the VAT number is this one is defined if not raise an UserError. VAT is not mandatory field but for some Argentinean operations the VAT is required, for eg validate an electronic invoice, build a report, etc. This method can be used to validate is the VAT is proper defined in the partner """ self.ensure_one() if not self.l10n_ar_vat: raise UserError(_('No VAT configured for partner [%i] %s') % (self.id, self.name)) return self.l10n_ar_vat def _get_validation_module(self): self.ensure_one() if self.l10n_latam_identification_type_id.l10n_ar_afip_code in ['80', '86']: return stdnum.ar.cuit elif self.l10n_latam_identification_type_id.l10n_ar_afip_code == '96': return stdnum.ar.dni def l10n_ar_identification_validation(self): for rec in self.filtered('vat'): try: module = rec._get_validation_module() except Exception as error: module = False _logger.runbot("Argentinean document was not validated: %s", repr(error)) if not module: continue try: module.validate(rec.vat) except module.InvalidChecksum: raise ValidationError(_('The validation digit is not valid for "%s"', rec.l10n_latam_identification_type_id.name)) except module.InvalidLength: raise ValidationError(_('Invalid length for "%s"', rec.l10n_latam_identification_type_id.name)) except module.InvalidFormat: raise ValidationError(_('Only numbers allowed for "%s"', rec.l10n_latam_identification_type_id.name)) except Exception as error: raise ValidationError(repr(error)) def _get_id_number_sanitize(self): """ Sanitize the identification number. Return the digits/integer value of the identification number If not vat number defined return 0 """ self.ensure_one() if not self.vat: return 0 if self.l10n_latam_identification_type_id.l10n_ar_afip_code in ['80', '86']: # Compact is the number clean up, remove all separators leave only digits res = int(stdnum.ar.cuit.compact(self.vat)) else: id_number = re.sub('[^0-9]', '', self.vat) res = int(id_number) return res
51.234375
6,558
705
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class AccountInvoiceReport(models.Model): _inherit = 'account.invoice.report' l10n_ar_state_id = fields.Many2one('res.country.state', 'State', readonly=True) date = fields.Date(readonly=True, string="Accounting Date") _depends = { 'account.move': ['partner_id', 'date'], 'res.partner': ['state_id'], } def _select(self): return super()._select() + ", contact_partner.state_id as l10n_ar_state_id, move.date" def _from(self): return super()._from() + " LEFT JOIN res_partner contact_partner ON contact_partner.id = move.partner_id"
33.571429
705
451
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { "name": "Fetchmail Outlook", "version": "1.0", "category": "Hidden", "description": "OAuth authentication for incoming Outlook mail server", "depends": [ "microsoft_outlook", "fetchmail", ], "data": [ "views/fetchmail_server_views.xml", ], "auto_install": True, "license": "LGPL-3", }
25.055556
451
2,186
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from unittest.mock import ANY, Mock, patch from odoo.exceptions import UserError from odoo.tests.common import TransactionCase class TestFetchmailOutlook(TransactionCase): @patch('odoo.addons.fetchmail.models.fetchmail.IMAP4_SSL') def test_connect(self, mock_imap): """Test that the connect method will use the right authentication method with the right arguments. """ mock_connection = Mock() mock_imap.return_value = mock_connection mail_server = self.env['fetchmail.server'].create({ 'name': 'Test server', 'use_microsoft_outlook_service': True, 'user': '[email protected]', 'microsoft_outlook_access_token': 'test_access_token', 'microsoft_outlook_access_token_expiration': time.time() + 1000000, 'password': '', 'server_type': 'imap', 'is_ssl': True, }) mail_server.connect() mock_connection.authenticate.assert_called_once_with('XOAUTH2', ANY) args = mock_connection.authenticate.call_args[0] self.assertEqual(args[1](None), '[email protected]\1auth=Bearer test_access_token\1\1', msg='Should use the right access token') mock_connection.select.assert_called_once_with('INBOX') def test_constraints(self): """Test the constraints related to the Outlook mail server.""" with self.assertRaises(UserError, msg='Should ensure that the password is empty'): self.env['fetchmail.server'].create({ 'name': 'Test server', 'use_microsoft_outlook_service': True, 'password': 'test', 'server_type': 'imap', }) with self.assertRaises(UserError, msg='Should ensure that the server type is IMAP'): self.env['fetchmail.server'].create({ 'name': 'Test server', 'use_microsoft_outlook_service': True, 'password': '', 'server_type': 'pop', })
37.050847
2,186
2,273
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _, api, models from odoo.exceptions import UserError class FetchmailServer(models.Model): """Add the Outlook OAuth authentication on the incoming mail servers.""" _name = 'fetchmail.server' _inherit = ['fetchmail.server', 'microsoft.outlook.mixin'] _OUTLOOK_SCOPE = 'https://outlook.office.com/IMAP.AccessAsUser.All' @api.constrains('use_microsoft_outlook_service', 'server_type', 'password', 'is_ssl') def _check_use_microsoft_outlook_service(self): for server in self: if not server.use_microsoft_outlook_service: continue if server.server_type != 'imap': raise UserError(_('Outlook mail server %r only supports IMAP server type.') % server.name) if server.password: raise UserError(_( 'Please leave the password field empty for Outlook mail server %r. ' 'The OAuth process does not require it') % server.name) if not server.is_ssl: raise UserError(_('SSL is required .') % server.name) @api.onchange('use_microsoft_outlook_service') def _onchange_use_microsoft_outlook_service(self): """Set the default configuration for a IMAP Outlook server.""" if self.use_microsoft_outlook_service: self.server = 'imap.outlook.com' self.server_type = 'imap' self.is_ssl = True self.port = 993 else: self.microsoft_outlook_refresh_token = False self.microsoft_outlook_access_token = False self.microsoft_outlook_access_token_expiration = False def _imap_login(self, connection): """Authenticate the IMAP connection. If the mail server is Outlook, we use the OAuth2 authentication protocol. """ self.ensure_one() if self.use_microsoft_outlook_service: auth_string = self._generate_outlook_oauth2_string(self.user) connection.authenticate('XOAUTH2', lambda x: auth_string) connection.select('INBOX') else: super()._imap_login(connection)
39.189655
2,273
874
py
PYTHON
15.0
{ "name": "Malaysia - Accounting", "author": "Odoo PS", "version": "1.0", "category": "Accounting/Localizations/Account Charts", "description": """ This is the base module to manage the accounting chart for Malaysia in Odoo. ============================================================================== """, "depends": [ "account", "l10n_multilang", ], "data": [ "data/l10n_my_chart_data.xml", "data/account.account.template.csv", "data/account_chart_template_data.xml", "data/account.tax.group.csv", "data/account_tax_template_data.xml", "data/account_chart_template_configure_data.xml", ], 'demo': [ 'demo/demo_company.xml', ], "icon": "/base/static/img/country_flags/my.png", "post_init_hook": "load_translations", "license": "LGPL-3", }
31.214286
874
926
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Portal Rating', 'category': 'Hidden', 'version': '1.0', 'description': """ Bridge module adding rating capabilities on portal. It includes notably inclusion of rating directly within the customer portal discuss widget. """, 'depends': [ 'portal', 'rating', ], 'data': [ 'views/rating_views.xml', 'views/portal_templates.xml', 'views/rating_templates.xml', ], 'auto_install': True, 'assets': { 'web.assets_frontend': [ 'portal_rating/static/src/scss/portal_rating.scss', 'portal_rating/static/src/js/portal_chatter.js', 'portal_rating/static/src/js/portal_composer.js', 'portal_rating/static/src/js/portal_rating_composer.js', ], }, 'license': 'LGPL-3', }
29.870968
926
373
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class IrHttp(models.AbstractModel): _inherit = 'ir.http' @classmethod def _get_translation_frontend_modules_name(cls): mods = super(IrHttp, cls)._get_translation_frontend_modules_name() return mods + ['portal_rating']
28.692308
373