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
21,089
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import zipfile import io import re import logging import email import email.policy import dateutil import pytz from lxml import etree from datetime import datetime from xmlrpc import client as xmlrpclib from odoo import api, fields, models, tools, _ from odoo.exceptions import ValidationError, UserError from odoo.addons.l10n_it_edi.tools.remove_signature import remove_signature _logger = logging.getLogger(__name__) class FetchmailServer(models.Model): _name = 'fetchmail.server' _inherit = 'fetchmail.server' l10n_it_is_pec = fields.Boolean('PEC server', help="If PEC Server, only mail from '...@pec.fatturapa.it' will be processed.") l10n_it_last_uid = fields.Integer(string='Last message UID IT', default=1) def _search_edi_invoice(self, att_name, send_state=False): """ Search sent l10n_it_edi fatturaPA invoices """ conditions = [ ('move_id', "!=", False), ('edi_format_id.code', '=', 'fattura_pa'), ('attachment_id.name', '=', att_name), ] if send_state: conditions.append(('move_id.l10n_it_send_state', '=', send_state)) return self.env['account.edi.document'].search(conditions, limit=1).move_id @api.constrains('l10n_it_is_pec', 'server_type') def _check_pec(self): for record in self: if record.l10n_it_is_pec and record.server_type != 'imap': raise ValidationError(_("PEC mail server must be of type IMAP.")) def fetch_mail(self): """ WARNING: meant for cron usage only - will commit() after each email! """ MailThread = self.env['mail.thread'] for server in self.filtered(lambda s: s.l10n_it_is_pec): _logger.info('start checking for new emails on %s PEC server %s', server.server_type, server.name) count, failed = 0, 0 imap_server = None try: imap_server = server.connect() imap_server.select() # Only download new emails email_filter = ['(UID %s:*)' % (server.l10n_it_last_uid)] # The l10n_it_edi.fatturapa_bypass_incoming_address_filter prevents the sender address check on incoming email. bypass_incoming_address_filter = self.env['ir.config_parameter'].get_param('l10n_it_edi.bypass_incoming_address_filter', False) if not bypass_incoming_address_filter: email_filter.append('(FROM "@pec.fatturapa.it")') data = imap_server.uid('search', None, *email_filter)[1] new_max_uid = server.l10n_it_last_uid for uid in data[0].split(): if int(uid) <= server.l10n_it_last_uid: # We get always minimum 1 message. If no new message, we receive the newest already managed. continue result, data = imap_server.uid('fetch', uid, '(RFC822)') if not data[0]: continue message = data[0][1] # To leave the mail in the state in which they were. if "Seen" not in data[1].decode("utf-8"): imap_server.uid('STORE', uid, '+FLAGS', '(\\Seen)') else: imap_server.uid('STORE', uid, '-FLAGS', '(\\Seen)') # See details in message_process() in mail_thread.py if isinstance(message, xmlrpclib.Binary): message = bytes(message.data) if isinstance(message, str): message = message.encode('utf-8') msg_txt = email.message_from_bytes(message, policy=email.policy.SMTP) try: self._attachment_invoice(msg_txt) new_max_uid = max(new_max_uid, int(uid)) except Exception: _logger.info('Failed to process mail from %s server %s.', server.server_type, server.name, exc_info=True) failed += 1 self._cr.commit() count += 1 server.write({'l10n_it_last_uid': new_max_uid}) _logger.info("Fetched %d email(s) on %s server %s; %d succeeded, %d failed.", count, server.server_type, server.name, (count - failed), failed) except Exception: _logger.info("General failure when trying to fetch mail from %s server %s.", server.server_type, server.name, exc_info=True) finally: if imap_server: imap_server.close() imap_server.logout() server.write({'date': fields.Datetime.now()}) return super(FetchmailServer, self.filtered(lambda s: not s.l10n_it_is_pec)).fetch_mail() def _attachment_invoice(self, msg_txt): parsed_values = self.env['mail.thread']._message_parse_extract_payload(msg_txt) body, attachments = parsed_values['body'], parsed_values['attachments'] from_address = msg_txt.get('from') for attachment in attachments: split_attachment = attachment.fname.rpartition('.') if len(split_attachment) < 3: _logger.info('E-invoice filename not compliant: %s', attachment.fname) continue attachment_name = split_attachment[0] attachment_ext = split_attachment[2] split_underscore = attachment_name.rsplit('_', 2) if len(split_underscore) < 2: _logger.info('E-invoice filename not compliant: %s', attachment.fname) continue if attachment_ext != 'zip': if split_underscore[1] in ['RC', 'NS', 'MC', 'MT', 'EC', 'SE', 'NE', 'DT']: # we have a receipt self._message_receipt_invoice(split_underscore[1], attachment) else: att_filename = attachment.fname match = re.search("[A-Z]{2}[A-Za-z0-9]{2,28}_[A-Za-z0-9]{0,5}.((?i:xml.p7m|xml))", att_filename) # If match, we have an invoice. if match: # If it's signed, the content has a bytes type and we just remove the signature's envelope if match.groups()[0].lower() == 'xml.p7m': att_content_data = remove_signature(attachment.content) # If the envelope cannot be removed, the remove_signature returns None, so we skip if not att_content_data: _logger.warning("E-invoice couldn't be read: %s", att_filename) continue att_filename = att_filename.replace('.xml.p7m', '.xml') else: # Otherwise, it should be an utf-8 encoded XML string att_content_data = attachment.content.encode() self._create_invoice_from_mail(att_content_data, att_filename, from_address) else: if split_underscore[1] == 'AT': # Attestazione di avvenuta trasmissione della fattura con impossibilità di recapito self._message_AT_invoice(attachment) else: _logger.info('New E-invoice in zip file: %s', attachment.fname) self._create_invoice_from_mail_with_zip(attachment, from_address) def _create_invoice_from_mail(self, att_content_data, att_name, from_address): """ Creates an invoice from the content of an email present in ir.attachments :param att_content_data: The 'utf-8' encoded bytes string representing the content of the attachment. :param att_name: The attachment's file name. :param from_address: The sender address of the email. """ invoices = self.env['account.move'] # Check if we already imported the email as an attachment existing = self.env['ir.attachment'].search([('name', '=', att_name), ('res_model', '=', 'account.move')]) if existing: _logger.info('E-invoice already exist: %s', att_name) return invoices # Create the new attachment for the file attachment = self.env['ir.attachment'].create({ 'name': att_name, 'raw': att_content_data, 'res_model': 'account.move', 'type': 'binary'}) # Decode the file. try: tree = etree.fromstring(att_content_data) except Exception: _logger.info('The xml file is badly formatted: %s', att_name) return invoices invoices = self.env.ref('l10n_it_edi.edi_fatturaPA')._create_invoice_from_xml_tree(att_name, tree) if not invoices: _logger.info('E-invoice not found in file: %s', att_name) return invoices invoices.l10n_it_send_state = "new" invoices.invoice_source_email = from_address for invoice in invoices: invoice.with_context(no_new_invoice=True, default_res_id=invoice.id) \ .message_post(body=(_("Original E-invoice XML file")), attachment_ids=[attachment.id]) self._cr.commit() _logger.info('New E-invoices (%s), ids: %s', att_name, [x.id for x in invoices]) return invoices def _create_invoice_from_mail_with_zip(self, attachment_zip, from_address): with zipfile.ZipFile(io.BytesIO(attachment_zip.content)) as z: for att_name in z.namelist(): existing = self.env['ir.attachment'].search([('name', '=', att_name), ('res_model', '=', 'account.move')]) if existing: # invoice already exist _logger.info('E-invoice in zip file (%s) already exist: %s', attachment_zip.fname, att_name) continue att_content = z.open(att_name).read() self._create_invoice_from_mail(att_content, att_name, from_address) def _message_AT_invoice(self, attachment_zip): with zipfile.ZipFile(io.BytesIO(attachment_zip.content)) as z: for attachment_name in z.namelist(): split_name_attachment = attachment_name.rpartition('.') if len(split_name_attachment) < 3: continue split_underscore = split_name_attachment[0].rsplit('_', 2) if len(split_underscore) < 2: continue if split_underscore[1] == 'AT': attachment = z.open(attachment_name).read() _logger.info('New AT receipt for: %s', split_underscore[0]) try: tree = etree.fromstring(attachment) except: _logger.info('Error in decoding new receipt file: %s', attachment_name) return elements = tree.xpath('//NomeFile') if elements and elements[0].text: filename = elements[0].text else: return related_invoice = self._search_edi_invoice(filename) if not related_invoice: _logger.info('Error: invoice not found for receipt file: %s', filename) return related_invoice.l10n_it_send_state = 'failed_delivery' info = self._return_multi_line_xml(tree, ['//IdentificativoSdI', '//DataOraRicezione', '//MessageId', '//PecMessageId', '//Note']) related_invoice.message_post( body=(_("ES certify that it has received the invoice and that the file \ could not be delivered to the addressee. <br/>%s") % (info)) ) def _message_receipt_invoice(self, receipt_type, attachment): try: tree = etree.fromstring(attachment.content.encode()) except: _logger.info('Error in decoding new receipt file: %s', attachment.fname) return {} elements = tree.xpath('//NomeFile') if elements and elements[0].text: filename = elements[0].text else: return {} if receipt_type == 'RC': # Delivery receipt # This is the receipt sent by the ES to the transmitting subject to communicate # delivery of the file to the addressee related_invoice = self._search_edi_invoice(filename, 'sent') if not related_invoice: _logger.info('Error: invoice not found for receipt file: %s', attachment.fname) return related_invoice.l10n_it_send_state = 'delivered' info = self._return_multi_line_xml(tree, ['//IdentificativoSdI', '//DataOraRicezione', '//DataOraConsegna', '//Note']) related_invoice.message_post( body=(_("E-Invoice is delivery to the destinatory:<br/>%s") % (info)) ) elif receipt_type == 'NS': # Rejection notice # This is the receipt sent by the ES to the transmitting subject if one or more of # the checks carried out by the ES on the file received do not have a successful result. related_invoice = self._search_edi_invoice(filename, 'sent') if not related_invoice: _logger.info('Error: invoice not found for receipt file: %s', attachment.fname) return related_invoice.l10n_it_send_state = 'invalid' error = self._return_error_xml(tree) related_invoice.message_post( body=(_("Errors in the E-Invoice :<br/>%s") % (error)) ) related_invoice.activity_schedule( 'mail.mail_activity_data_todo', summary='Rejection notice', user_id=related_invoice.invoice_user_id.id if related_invoice.invoice_user_id else self.env.user.id) elif receipt_type == 'MC': # Failed delivery notice # This is the receipt sent by the ES to the transmitting subject if the file is not # delivered to the addressee. related_invoice = self._search_edi_invoice(filename, 'sent') if not related_invoice: _logger.info('Error: invoice not found for receipt file: %s', attachment.fname) return info = self._return_multi_line_xml(tree, [ '//IdentificativoSdI', '//DataOraRicezione', '//Descrizione', '//MessageId', '//Note']) related_invoice.message_post( body=(_("The E-invoice is not delivered to the addressee. The Exchange System is\ unable to deliver the file to the Public Administration. The Exchange System will\ contact the PA to report the problem and request that they provide a solution. \ During the following 15 days, the Exchange System will try to forward the FatturaPA\ file to the Administration in question again. More information:<br/>%s") % (info)) ) elif receipt_type == 'NE': # Outcome notice # This is the receipt sent by the ES to the invoice sender to communicate the result # (acceptance or refusal of the invoice) of the checks carried out on the document by # the addressee. related_invoice = self._search_edi_invoice(filename, 'delivered') if not related_invoice: _logger.info('Error: invoice not found for receipt file: %s', attachment.fname) return elements = tree.xpath('//Esito') if elements and elements[0].text: if elements[0].text == 'EC01': related_invoice.l10n_it_send_state = 'delivered_accepted' elif elements[0].text == 'EC02': related_invoice.l10n_it_send_state = 'delivered_refused' info = self._return_multi_line_xml(tree, ['//Esito', '//Descrizione', '//IdentificativoSdI', '//DataOraRicezione', '//DataOraConsegna', '//Note' ]) related_invoice.message_post( body=(_("Outcome notice: %s<br/>%s") % (related_invoice.l10n_it_send_state, info)) ) if related_invoice.l10n_it_send_state == 'delivered_refused': related_invoice.activity_schedule( 'mail.mail_activity_todo', user_id=related_invoice.invoice_user_id.id if related_invoice.invoice_user_id else self.env.user.id, summary='Outcome notice: Refused') # elif receipt_type == 'MT': # Metadata file # This is the file sent by the ES to the addressee together with the invoice file, # containing the main reference data of the file useful for processing, including # the IdentificativoSDI. # Useless for Odoo elif receipt_type == 'DT': # Deadline passed notice # This is the receipt sent by the ES to both the invoice sender and the invoice # addressee to communicate the expiry of the maximum term for communication of # acceptance/refusal. related_invoice = self._search_edi_invoice(filename, 'delivered') if not related_invoice: _logger.info('Error: invoice not found for receipt file: %s', attachment.fname) return related_invoice.l10n_it_send_state = 'delivered_expired' info = self._return_multi_line_xml(tree, [ '//Descrizione', '//IdentificativoSdI', '//Note']) related_invoice.message_post( body=(_("Expiration of the maximum term for communication of acceptance/refusal:\ %s<br/>%s") % (filename, info)) ) def _return_multi_line_xml(self, tree, element_tags): output_str = "<ul>" for element_tag in element_tags: elements = tree.xpath(element_tag) if not elements: continue for element in elements: if element.text: text = " ".join(element.text.split()) output_str += "<li>%s: %s</li>" % (element.tag, text) return output_str + "</ul>" def _return_error_xml(self, tree): output_str = "<ul>" elements = tree.xpath('//Errore') if not elements: return for element in elements: descrizione = " ".join(element[1].text.split()) if descrizione: output_str += "<li>Errore %s: %s</li>" % (element[0].text, descrizione) return output_str + "</ul>" class IrMailServer(models.Model): _name = "ir.mail_server" _inherit = "ir.mail_server" def _get_test_email_addresses(self): self.ensure_one() company = self.env["res.company"].search([("l10n_it_mail_pec_server_id", "=", self.id)], limit=1) if not company: # it's not a PEC server return super()._get_test_email_addresses() email_from = self.smtp_user if not email_from: raise UserError(_('Please configure Username for this Server PEC')) email_to = company.l10n_it_address_recipient_fatturapa if not email_to: raise UserError(_('Please configure Government PEC-mail in company settings')) return email_from, email_to def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): if self.env.context.get('wo_bounce_return_path') and headers: headers['Return-Path'] = email_from return super(IrMailServer, self).build_email(email_from, email_to, subject, body, email_cc=email_cc, email_bcc=email_bcc, reply_to=reply_to, attachments=attachments, message_id=message_id, references=references, object_id=object_id, subtype=subtype, headers=headers, body_alternative=body_alternative, subtype_alternative=subtype_alternative)
48.589862
21,088
42,636
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields, _ from odoo.tests.common import Form from odoo.exceptions import UserError from odoo.addons.l10n_it_edi.tools.remove_signature import remove_signature from odoo.osv.expression import OR, AND from lxml import etree from datetime import datetime import re import logging import json _logger = logging.getLogger(__name__) DEFAULT_FACTUR_ITALIAN_DATE_FORMAT = '%Y-%m-%d' class AccountEdiFormat(models.Model): _inherit = 'account.edi.format' # ------------------------------------------------------------------------- # Helpers # ------------------------------------------------------------------------- @api.model def _l10n_it_edi_generate_electronic_invoice_filename(self, invoice): '''Returns a name conform to the Fattura pa Specifications: See ES documentation 2.2 ''' a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" # Each company should have its own filename sequence. If it does not exist, create it n = self.env['ir.sequence'].with_company(invoice.company_id).next_by_code('l10n_it_edi.fattura_filename') if not n: # The offset is used to avoid conflicts with existing filenames offset = 62 ** 4 sequence = self.env['ir.sequence'].sudo().create({ 'name': 'FatturaPA Filename Sequence', 'code': 'l10n_it_edi.fattura_filename', 'company_id': invoice.company_id.id, 'number_next': offset, }) n = sequence._next() # The n is returned as a string, but we require an int n = int(''.join(filter(lambda c: c.isdecimal(), n))) progressive_number = "" while n: (n, m) = divmod(n, len(a)) progressive_number = a[m] + progressive_number return '%(country_code)s%(codice)s_%(progressive_number)s.xml' % { 'country_code': invoice.company_id.country_id.code, 'codice': self.env['res.partner']._l10n_it_normalize_codice_fiscale(invoice.company_id.l10n_it_codice_fiscale), 'progressive_number': progressive_number.zfill(5), } def _l10n_it_edi_check_invoice_configuration(self, invoice): errors = self._l10n_it_edi_check_ordinary_invoice_configuration(invoice) if not errors: errors = self._l10n_it_edi_check_simplified_invoice_configuration(invoice) return errors def _l10n_it_edi_is_self_invoice(self, invoice): """ Italian EDI requires Vendor bills coming from EU countries to be sent as self-invoices. We recognize these cases based on the taxes that target the VJ tax grids, which imply the use of VAT External Reverse Charge. """ report_lines_xmlids = invoice.line_ids.tax_tag_ids.tax_report_line_ids.mapped(lambda x: x.get_external_id().get(x.id, '')) return (invoice.is_purchase_document() and any([x.startswith("l10n_it.tax_report_line_vj") for x in report_lines_xmlids])) def _l10n_it_edi_check_ordinary_invoice_configuration(self, invoice): errors = [] seller = invoice.company_id buyer = invoice.commercial_partner_id is_self_invoice = self._l10n_it_edi_is_self_invoice(invoice) if is_self_invoice: seller, buyer = buyer, seller # <1.1.1.1> if not seller.country_id: errors.append(_("%s must have a country", seller.display_name)) # <1.1.1.2> if not invoice.company_id.vat: errors.append(_("%s must have a VAT number", seller.display_name)) if seller.vat and len(seller.vat) > 30: errors.append(_("The maximum length for VAT number is 30. %s have a VAT number too long: %s.", seller.display_name, seller.vat)) # <1.2.1.2> if not is_self_invoice and not seller.l10n_it_codice_fiscale: errors.append(_("%s must have a codice fiscale number", seller.display_name)) # <1.2.1.8> if not is_self_invoice and not seller.l10n_it_tax_system: errors.append(_("The seller's company must have a tax system.")) # <1.2.2> if not seller.street and not seller.street2: errors.append(_("%s must have a street.", seller.display_name)) if not seller.zip: errors.append(_("%s must have a post code.", seller.display_name)) elif len(seller.zip) != 5 and seller.country_id.code == 'IT': errors.append(_("%s must have a post code of length 5.", seller.display_name)) if not seller.city: errors.append(_("%s must have a city.", seller.display_name)) if not seller.country_id: errors.append(_("%s must have a country.", seller.display_name)) if not is_self_invoice and seller.l10n_it_has_tax_representative and not seller.l10n_it_tax_representative_partner_id.vat: errors.append(_("Tax representative partner %s of %s must have a tax number.", seller.l10n_it_tax_representative_partner_id.display_name, seller.display_name)) # <1.4.1> if not buyer.vat and not buyer.l10n_it_codice_fiscale and buyer.country_id.code == 'IT': errors.append(_("The buyer, %s, or his company must have a VAT number and/or a tax code (Codice Fiscale).", buyer.display_name)) if is_self_invoice and self._l10n_it_edi_services_or_goods(invoice) == 'both': errors.append(_("Cannot apply Reverse Charge to a bill which contains both services and goods.")) if is_self_invoice and not buyer.partner_id.l10n_it_pa_index: errors.append(_("Vendor bills sent as self-invoices to the SdI require a valid PA Index (Codice Destinatario) on the company's contact.")) # <2.2.1> for invoice_line in invoice.invoice_line_ids: if not invoice_line.display_type and len(invoice_line.tax_ids) != 1: errors.append(_("In line %s, you must select one and only one tax by line.", invoice_line.name)) for tax_line in invoice.line_ids.filtered(lambda line: line.tax_line_id): if not tax_line.tax_line_id.l10n_it_kind_exoneration and tax_line.tax_line_id.amount == 0: errors.append(_("%s has an amount of 0.0, you must indicate the kind of exoneration.", tax_line.name)) return errors def _l10n_it_edi_is_simplified(self, invoice): """ Simplified Invoices are a way for the invoice issuer to create an invoice with limited data. Example: a consultant goes to the restaurant and wants the invoice instead of the receipt, to be able to deduct the expense from his Taxes. The Italian State allows the restaurant to issue a Simplified Invoice with the VAT number only, to speed up times, instead of requiring the address and other informations about the buyer. Only invoices under the threshold of 400 Euroes are allowed, to avoid this tool be abused for bigger transactions, that would enable less transparency to tax institutions. """ buyer = invoice.commercial_partner_id return all([ self.env.ref('l10n_it_edi.account_invoice_it_simplified_FatturaPA_export', raise_if_not_found=False), not self._l10n_it_edi_is_self_invoice(invoice), self._l10n_it_edi_check_buyer_invoice_configuration(invoice), not buyer.country_id or buyer.country_id.code == 'IT', buyer.l10n_it_codice_fiscale or (buyer.vat and (buyer.vat[:2].upper() == 'IT' or buyer.vat[:2].isdecimal())), invoice.amount_total <= 400, ]) def _l10n_it_edi_check_simplified_invoice_configuration(self, invoice): return [] if self._l10n_it_edi_is_simplified(invoice) else self._l10n_it_edi_check_buyer_invoice_configuration(invoice) def _l10n_it_edi_partner_in_eu(self, partner): europe = self.env.ref('base.europe', raise_if_not_found=False) country = partner.country_id return not europe or not country or country in europe.country_ids def _l10n_it_edi_services_or_goods(self, invoice): """ Services and goods have different tax grids when VAT is Reverse Charged, and they can't be mixed in the same invoice, because the TipoDocumento depends on which which kind of product is bought and it's unambiguous. """ scopes = [] for line in invoice.invoice_line_ids.filtered(lambda l: not l.display_type): tax_ids_with_tax_scope = line.tax_ids.filtered(lambda x: x.tax_scope) if tax_ids_with_tax_scope: scopes += tax_ids_with_tax_scope.mapped('tax_scope') else: scopes.append(line.product_id and line.product_id.type or 'consu') if set(scopes) == set(['consu', 'service']): return "both" return scopes and scopes.pop() def _l10n_it_edi_check_buyer_invoice_configuration(self, invoice): errors = [] buyer = invoice.commercial_partner_id # <1.4.2> if not buyer.street and not buyer.street2: errors.append(_("%s must have a street.", buyer.display_name)) if not buyer.country_id: errors.append(_("%s must have a country.", buyer.display_name)) if not buyer.zip: errors.append(_("%s must have a post code.", buyer.display_name)) elif len(buyer.zip) != 5 and buyer.country_id.code == 'IT': errors.append(_("%s must have a post code of length 5.", buyer.display_name)) if not buyer.city: errors.append(_("%s must have a city.", buyer.display_name)) for tax_line in invoice.line_ids.filtered(lambda line: line.tax_line_id): if not tax_line.tax_line_id.l10n_it_kind_exoneration and tax_line.tax_line_id.amount == 0: errors.append(_("%s has an amount of 0.0, you must indicate the kind of exoneration.", tax_line.name)) return errors def _l10n_it_goods_in_italy(self, invoice): """ There is a specific TipoDocumento (Document Type TD19) and tax grid (VJ3) for goods that are phisically in Italy but are in a VAT deposit, meaning that the goods have not passed customs. """ report_lines_xmlids = invoice.line_ids.tax_tag_ids.tax_report_line_ids.mapped(lambda x: x.get_external_id().get(x.id, '')) return any([x == "l10n_it.tax_report_line_vj3" for x in report_lines_xmlids]) def _l10n_it_document_type_mapping(self): return { 'TD01': dict(move_types=['out_invoice'], import_type='in_invoice', downpayment=False), 'TD02': dict(move_types=['out_invoice'], import_type='in_invoice', downpayment=True), 'TD04': dict(move_types=['out_refund'], import_type='in_refund'), 'TD07': dict(move_types=['out_invoice'], import_type='in_invoice', simplified=True), 'TD08': dict(move_types=['out_refund'], import_type='in_refund', simplified=True), 'TD09': dict(move_types=['out_invoice'], import_type='in_invoice', simplified=True), 'TD17': dict(move_types=['in_invoice', 'in_refund'], import_type='in_invoice', self_invoice=True, services_or_goods="service"), 'TD18': dict(move_types=['in_invoice', 'in_refund'], import_type='in_invoice', self_invoice=True, services_or_goods="consu", partner_in_eu=True), 'TD19': dict(move_types=['in_invoice', 'in_refund'], import_type='in_invoice', self_invoice=True, services_or_goods="consu", goods_in_italy=True), } def _l10n_it_get_document_type(self, invoice): is_simplified = self._l10n_it_edi_is_simplified(invoice) is_self_invoice = self._l10n_it_edi_is_self_invoice(invoice) services_or_goods = self._l10n_it_edi_services_or_goods(invoice) goods_in_italy = services_or_goods == 'consu' and self._l10n_it_goods_in_italy(invoice) partner_in_eu = self._l10n_it_edi_partner_in_eu(invoice.commercial_partner_id) for code, infos in self._l10n_it_document_type_mapping().items(): info_services_or_goods = infos.get('services_or_goods', "both") info_partner_in_eu = infos.get('partner_in_eu', False) if all([ invoice.move_type in infos.get('move_types', False), # Only check downpayment if the key is specified in the document_type_mapping entry # If it's not specified, the get() will return None and the condition will be True infos.get('downpayment') in (None, invoice._is_downpayment()), is_self_invoice == infos.get('self_invoice', False), is_simplified == infos.get('simplified', False), info_services_or_goods in ("both", services_or_goods), info_partner_in_eu in (False, partner_in_eu), goods_in_italy == infos.get('goods_in_italy', False), ]): return code return None def _l10n_it_is_simplified_document_type(self, document_type): return self._l10n_it_document_type_mapping().get(document_type, {}).get('simplified', False) # ------------------------------------------------------------------------- # Export # ------------------------------------------------------------------------- def _is_embedding_to_invoice_pdf_needed(self): # OVERRIDE self.ensure_one() return True if self.code == 'fattura_pa' else super()._is_embedding_to_invoice_pdf_needed() def _is_compatible_with_journal(self, journal): # OVERRIDE self.ensure_one() if self.code != 'fattura_pa': return super()._is_compatible_with_journal(journal) return journal.type in ('sale', 'purchase') and journal.country_code == 'IT' def _l10n_it_edi_is_required_for_invoice(self, invoice): """ Is the edi required for this invoice based on the method (here: PEC mail) Deprecated: in future release PEC mail will be removed. TO OVERRIDE """ return ((invoice.is_sale_document() or self._l10n_it_get_document_type(invoice)) and invoice.country_code == 'IT' and invoice.l10n_it_send_state not in ('sent', 'delivered', 'delivered_accepted')) def _is_required_for_invoice(self, invoice): # OVERRIDE self.ensure_one() if self.code != 'fattura_pa': return super()._is_required_for_invoice(invoice) return self._l10n_it_edi_is_required_for_invoice(invoice) def _post_fattura_pa(self, invoices): # TO OVERRIDE invoice = invoices # no batching ensure that we only have one invoice invoice.l10n_it_send_state = 'other' invoice._check_before_xml_exporting() if invoice.l10n_it_einvoice_id and invoice.l10n_it_send_state not in ['invalid', 'to_send']: return {'error': _("You can't regenerate an E-Invoice when the first one is sent and there are no errors")} if invoice.l10n_it_einvoice_id: invoice.l10n_it_einvoice_id.unlink() res = invoice.invoice_generate_xml() 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.")) ) else: invoice.l10n_it_send_state = 'to_send' if 'attachment' in res: res['success'] = True return {invoice: res} def _post_invoice_edi(self, invoices): # OVERRIDE self.ensure_one() edi_result = super()._post_invoice_edi(invoices) if self.code != 'fattura_pa': return edi_result return self._post_fattura_pa(invoices) # ------------------------------------------------------------------------- # Import # ------------------------------------------------------------------------- def _check_filename_is_fattura_pa(self, filename): return re.search("[A-Z]{2}[A-Za-z0-9]{2,28}_[A-Za-z0-9]{0,5}.((?i:xml.p7m|xml))", filename) def _is_fattura_pa(self, filename, tree=None): return self.code == 'fattura_pa' and self._check_filename_is_fattura_pa(filename) def _create_invoice_from_xml_tree(self, filename, tree, journal=None): self.ensure_one() if self._is_fattura_pa(filename, tree): return self._import_fattura_pa(tree, self.env['account.move']) return super()._create_invoice_from_xml_tree(filename, tree, journal=journal) def _update_invoice_from_xml_tree(self, filename, tree, invoice): self.ensure_one() if self._is_fattura_pa(filename, tree): if len(tree.xpath('//FatturaElettronicaBody')) > 1: invoice.message_post(body='The attachment contains multiple invoices, this invoice was not updated from it.', message_type='comment', subtype_xmlid='mail.mt_note', author_id=self.env.ref('base.partner_root').id) else: return self._import_fattura_pa(tree, invoice) return super()._update_invoice_from_xml_tree(filename, tree, invoice) def _decode_p7m_to_xml(self, filename, content): decoded_content = remove_signature(content) if not decoded_content: return None try: # Some malformed XML are accepted by FatturaPA, this expends compatibility parser = etree.XMLParser(recover=True) xml_tree = etree.fromstring(decoded_content, parser) except Exception as e: _logger.exception("Error when converting the xml content to etree: %s", e) return None if xml_tree is None or len(xml_tree) == 0: return None return xml_tree def _create_invoice_from_binary(self, filename, content, extension): self.ensure_one() if extension.lower() == '.xml.p7m' and self._is_fattura_pa(filename): decoded_content = self._decode_p7m_to_xml(filename, content) if decoded_content is not None: return self._import_fattura_pa(decoded_content, self.env['account.move']) return super()._create_invoice_from_binary(filename, content, extension) def _update_invoice_from_binary(self, filename, content, extension, invoice): self.ensure_one() if extension.lower() == '.xml.p7m' and self._is_fattura_pa(filename): decoded_content = self._decode_p7m_to_xml(filename, content) if decoded_content is not None: return self._import_fattura_pa(decoded_content, invoice) return super()._update_invoice_from_binary(filename, content, extension, invoice) def _convert_date_from_xml(self, xsdate_str): """ Dates in FatturaPA are ISO 8601 date format, pattern '[-]CCYY-MM-DD[Z|(+|-)hh:mm]' """ xsdate_str = xsdate_str.strip() xsdate_pattern = r"^-?(?P<date>-?\d{4}-\d{2}-\d{2})(?P<tz>[zZ]|[+-]\d{2}:\d{2})?$" try: match = re.match(xsdate_pattern, xsdate_str) converted_date = datetime.strptime(match.group("date"), DEFAULT_FACTUR_ITALIAN_DATE_FORMAT).date() except Exception: converted_date = False return converted_date def _import_fattura_pa(self, tree, invoice): """ Decodes a fattura_pa invoice into an invoice. :param tree: the fattura_pa tree to decode. :param invoice: the invoice to update or an empty recordset. :returns: the invoice where the fattura_pa data was imported. """ invoices = self.env['account.move'] first_run = True # possible to have multiple invoices in the case of an invoice batch, the batch itself is repeated for every invoice of the batch for body_tree in tree.xpath('//FatturaElettronicaBody'): if not first_run or not invoice: # make sure all the iterations create a new invoice record (except the first which could have already created one) invoice = self.env['account.move'] first_run = False # Type must be present in the context to get the right behavior of the _default_journal method (account.move). # journal_id must be present in the context to get the right behavior of the _default_account method (account.move.line). elements = tree.xpath('//CessionarioCommittente//IdCodice') company = elements and self.env['res.company'].search([('vat', 'ilike', elements[0].text)], limit=1) if not company: elements = tree.xpath('//CessionarioCommittente//CodiceFiscale') company = elements and self.env['res.company'].search([('l10n_it_codice_fiscale', 'ilike', elements[0].text)], limit=1) if not company: # Only invoices with a correct VAT or Codice Fiscale can be imported _logger.warning('No company found with VAT or Codice Fiscale like %r.', elements[0].text) continue # Refund type. # TD01 == invoice # TD02 == advance/down payment on invoice # TD03 == advance/down payment on fee # TD04 == credit note # TD05 == debit note # TD06 == fee # TD07 == simplified invoice # TD08 == simplified credit note # TD09 == simplified debit note # For unsupported document types, just assume in_invoice, and log that the type is unsupported elements = tree.xpath('//DatiGeneraliDocumento/TipoDocumento') document_type = elements[0].text if elements else '' move_type = self._l10n_it_document_type_mapping().get(document_type, {}).get('import_type', False) if not move_type: move_type = "in_invoice" _logger.info('Document type not managed: %s. Invoice type is set by default.', document_type) simplified = self._l10n_it_is_simplified_document_type(document_type) # Setup the context for the Invoice Form invoice_ctx = invoice.with_company(company) \ .with_context(default_move_type=move_type) # move could be a single record (editing) or be empty (new). with Form(invoice_ctx) as invoice_form: message_to_log = [] # Partner (first step to avoid warning 'Warning! You must first select a partner.'). <1.2> elements = tree.xpath('//CedentePrestatore//IdCodice') partner = elements and self.env['res.partner'].search(['&', ('vat', 'ilike', elements[0].text), '|', ('company_id', '=', company.id), ('company_id', '=', False)], limit=1) if not partner: elements = tree.xpath('//CedentePrestatore//CodiceFiscale') if elements: codice = elements[0].text domains = [[('l10n_it_codice_fiscale', '=', codice)]] if re.match(r'^[0-9]{11}$', codice): domains.append([('l10n_it_codice_fiscale', '=', 'IT' + codice)]) elif re.match(r'^IT[0-9]{11}$', codice): domains.append([('l10n_it_codice_fiscale', '=', self.env['res.partner']._l10n_it_normalize_codice_fiscale(codice))]) partner = elements and self.env['res.partner'].search( AND([OR(domains), OR([[('company_id', '=', company.id)], [('company_id', '=', False)]])]), limit=1) if not partner: elements = tree.xpath('//DatiTrasmissione//Email') partner = elements and self.env['res.partner'].search(['&', '|', ('email', '=', elements[0].text), ('l10n_it_pec_email', '=', elements[0].text), '|', ('company_id', '=', company.id), ('company_id', '=', False)], limit=1) if partner: invoice_form.partner_id = partner else: message_to_log.append("%s<br/>%s" % ( _("Vendor not found, useful informations from XML file:"), invoice._compose_info_message( tree, './/CedentePrestatore'))) # Numbering attributed by the transmitter. <1.1.2> elements = tree.xpath('//ProgressivoInvio') if elements: invoice_form.payment_reference = elements[0].text elements = body_tree.xpath('.//DatiGeneraliDocumento//Numero') if elements: invoice_form.ref = elements[0].text # Currency. <2.1.1.2> elements = body_tree.xpath('.//DatiGeneraliDocumento/Divisa') if elements: currency_str = elements[0].text currency = self.env.ref('base.%s' % currency_str.upper(), raise_if_not_found=False) if currency != self.env.company.currency_id and currency.active: invoice_form.currency_id = currency # Date. <2.1.1.3> elements = body_tree.xpath('.//DatiGeneraliDocumento/Data') if elements: document_date = self._convert_date_from_xml(elements[0].text) if document_date: invoice_form.invoice_date = document_date else: message_to_log.append("%s<br/>%s" % ( _("Document date invalid in XML file:"), invoice._compose_info_message(elements[0], '.') )) # Dati Bollo. <2.1.1.6> elements = body_tree.xpath('.//DatiGeneraliDocumento/DatiBollo/ImportoBollo') if elements: invoice_form.l10n_it_stamp_duty = float(elements[0].text) # Comment. <2.1.1.11> elements = body_tree.xpath('.//DatiGeneraliDocumento//Causale') for element in elements: invoice_form.narration = '%s%s<br/>' % (invoice_form.narration or '', element.text) # Informations relative to the purchase order, the contract, the agreement, # the reception phase or invoices previously transmitted # <2.1.2> - <2.1.6> for document_type in ['DatiOrdineAcquisto', 'DatiContratto', 'DatiConvenzione', 'DatiRicezione', 'DatiFattureCollegate']: elements = body_tree.xpath('.//DatiGenerali/' + document_type) if elements: for element in elements: message_to_log.append("%s %s<br/>%s" % (document_type, _("from XML file:"), invoice._compose_info_message(element, '.'))) # Dati DDT. <2.1.8> elements = body_tree.xpath('.//DatiGenerali/DatiDDT') if elements: message_to_log.append("%s<br/>%s" % ( _("Transport informations from XML file:"), invoice._compose_info_message(body_tree, './/DatiGenerali/DatiDDT'))) # Due date. <2.4.2.5> elements = body_tree.xpath('.//DatiPagamento/DettaglioPagamento/DataScadenzaPagamento') if elements: date_str = elements[0].text.strip() if date_str: due_date = self._convert_date_from_xml(date_str) if due_date: invoice_form.invoice_date_due = fields.Date.to_string(due_date) else: message_to_log.append("%s<br/>%s" % ( _("Payment due date invalid in XML file:"), invoice._compose_info_message(elements[0], '.') )) # Total amount. <2.4.2.6> elements = body_tree.xpath('.//ImportoPagamento') amount_total_import = 0 for element in elements: amount_total_import += float(element.text) if amount_total_import: message_to_log.append(_("Total amount from the XML File: %s") % ( amount_total_import)) # Bank account. <2.4.2.13> if invoice_form.move_type not in ('out_invoice', 'in_refund'): elements = body_tree.xpath('.//DatiPagamento/DettaglioPagamento/IBAN') if elements: if invoice_form.partner_id and invoice_form.partner_id.commercial_partner_id: bank = self.env['res.partner.bank'].search([ ('acc_number', '=', elements[0].text), ('partner_id', '=', invoice_form.partner_id.commercial_partner_id.id), ('company_id', 'in', [invoice_form.company_id.id, False]) ], order='company_id', limit=1) else: bank = self.env['res.partner.bank'].search([ ('acc_number', '=', elements[0].text), ('company_id', 'in', [invoice_form.company_id.id, False]) ], order='company_id', limit=1) if bank: invoice_form.partner_bank_id = bank else: message_to_log.append("%s<br/>%s" % ( _("Bank account not found, useful informations from XML file:"), invoice._compose_multi_info_message( body_tree, ['.//DatiPagamento//Beneficiario', './/DatiPagamento//IstitutoFinanziario', './/DatiPagamento//IBAN', './/DatiPagamento//ABI', './/DatiPagamento//CAB', './/DatiPagamento//BIC', './/DatiPagamento//ModalitaPagamento']))) else: elements = body_tree.xpath('.//DatiPagamento/DettaglioPagamento') if elements: message_to_log.append("%s<br/>%s" % ( _("Bank account not found, useful informations from XML file:"), invoice._compose_info_message(body_tree, './/DatiPagamento'))) # Invoice lines. <2.2.1> if not simplified: elements = body_tree.xpath('.//DettaglioLinee') else: elements = body_tree.xpath('.//DatiBeniServizi') if elements: for element in elements: with invoice_form.invoice_line_ids.new() as invoice_line_form: # Sequence. line_elements = element.xpath('.//NumeroLinea') if line_elements: invoice_line_form.sequence = int(line_elements[0].text) # Product. elements_code = element.xpath('.//CodiceArticolo') if elements_code: for element_code in elements_code: type_code = element_code.xpath('.//CodiceTipo')[0] code = element_code.xpath('.//CodiceValore')[0] if type_code.text == 'EAN': product = self.env['product.product'].search([('barcode', '=', code.text)]) if product: invoice_line_form.product_id = product break if partner: product_supplier = self.env['product.supplierinfo'].search([('name', '=', partner.id), ('product_code', '=', code.text)], limit=2) if product_supplier and len(product_supplier) == 1 and product_supplier.product_id: invoice_line_form.product_id = product_supplier.product_id break if not invoice_line_form.product_id: for element_code in elements_code: code = element_code.xpath('.//CodiceValore')[0] product = self.env['product.product'].search([('default_code', '=', code.text)], limit=2) if product and len(product) == 1: invoice_line_form.product_id = product break # Label. line_elements = element.xpath('.//Descrizione') if line_elements: invoice_line_form.name = " ".join(line_elements[0].text.split()) # Quantity. line_elements = element.xpath('.//Quantita') if line_elements: invoice_line_form.quantity = float(line_elements[0].text) else: invoice_line_form.quantity = 1 # Taxes percentage = None price_subtotal = 0 if not simplified: tax_element = element.xpath('.//AliquotaIVA') if tax_element and tax_element[0].text: percentage = float(tax_element[0].text) else: amount_element = element.xpath('.//Importo') if amount_element and amount_element[0].text: amount = float(amount_element[0].text) tax_element = element.xpath('.//Aliquota') if tax_element and tax_element[0].text: percentage = float(tax_element[0].text) price_subtotal = amount / (1 + percentage / 100) else: tax_element = element.xpath('.//Imposta') if tax_element and tax_element[0].text: tax_amount = float(tax_element[0].text) price_subtotal = amount - tax_amount percentage = round(tax_amount / price_subtotal * 100) natura_element = element.xpath('.//Natura') invoice_line_form.tax_ids.clear() if percentage is not None: if natura_element and natura_element[0].text: l10n_it_kind_exoneration = natura_element[0].text tax = self.env['account.tax'].search([ ('company_id', '=', invoice_form.company_id.id), ('amount_type', '=', 'percent'), ('type_tax_use', '=', 'purchase'), ('amount', '=', percentage), ('l10n_it_kind_exoneration', '=', l10n_it_kind_exoneration), ], limit=1) else: tax = self.env['account.tax'].search([ ('company_id', '=', invoice_form.company_id.id), ('amount_type', '=', 'percent'), ('type_tax_use', '=', 'purchase'), ('amount', '=', percentage), ], limit=1) l10n_it_kind_exoneration = '' if tax: invoice_line_form.tax_ids.add(tax) else: if l10n_it_kind_exoneration: message_to_log.append(_("Tax not found with percentage: %s and exoneration %s for the article: %s") % ( percentage, l10n_it_kind_exoneration, invoice_line_form.name)) else: message_to_log.append(_("Tax not found with percentage: %s for the article: %s") % ( percentage, invoice_line_form.name)) # Price Unit. if not simplified: line_elements = element.xpath('.//PrezzoUnitario') if line_elements: invoice_line_form.price_unit = float(line_elements[0].text) else: invoice_line_form.price_unit = price_subtotal # Discounts discount_elements = element.xpath('.//ScontoMaggiorazione') if discount_elements: discount_element = discount_elements[0] discount_percentage = discount_element.xpath('.//Percentuale') # Special case of only 1 percentage discount if discount_percentage and len(discount_elements) == 1: discount_type = discount_element.xpath('.//Tipo') discount_sign = 1 if discount_type and discount_type[0].text == 'MG': discount_sign = -1 invoice_line_form.discount = discount_sign * float(discount_percentage[0].text) # Discounts in cascade summarized in 1 percentage else: total = float(element.xpath('.//PrezzoTotale')[0].text) discount = 100 - (100 * total) / (invoice_line_form.quantity * invoice_line_form.price_unit) invoice_line_form.discount = discount # Global discount summarized in 1 amount discount_elements = body_tree.xpath('.//DatiGeneraliDocumento/ScontoMaggiorazione') if discount_elements: taxable_amount = float(json.loads(invoice_form.tax_totals_json)['amount_untaxed']) discounted_amount = taxable_amount for discount_element in discount_elements: discount_type = discount_element.xpath('.//Tipo') discount_sign = 1 if discount_type and discount_type[0].text == 'MG': discount_sign = -1 discount_amount = discount_element.xpath('.//Importo') if discount_amount: discounted_amount -= discount_sign * float(discount_amount[0].text) continue discount_percentage = discount_element.xpath('.//Percentuale') if discount_percentage: discounted_amount *= 1 - discount_sign * float(discount_percentage[0].text) / 100 general_discount = discounted_amount - taxable_amount sequence = len(elements) + 1 with invoice_form.invoice_line_ids.new() as invoice_line_global_discount: invoice_line_global_discount.tax_ids.clear() invoice_line_global_discount.sequence = sequence invoice_line_global_discount.name = 'SCONTO' if general_discount < 0 else 'MAGGIORAZIONE' invoice_line_global_discount.price_unit = general_discount new_invoice = invoice_form.save() new_invoice.l10n_it_send_state = "other" elements = body_tree.xpath('.//Allegati') if elements: for element in elements: name_attachment = element.xpath('.//NomeAttachment')[0].text attachment_64 = str.encode(element.xpath('.//Attachment')[0].text) attachment_64 = self.env['ir.attachment'].create({ 'name': name_attachment, 'datas': attachment_64, 'type': 'binary', 'res_model': 'account.move', 'res_id': new_invoice.id, }) # no_new_invoice to prevent from looping on the message_post that would create a new invoice without it new_invoice.with_context(no_new_invoice=True).message_post( body=(_("Attachment from XML")), attachment_ids=[attachment_64.id] ) for message in message_to_log: new_invoice.message_post(body=message) invoices += new_invoice return invoices
54.943299
42,636
22,972
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import zipfile import io import logging import re from datetime import date, datetime from lxml import etree from odoo import api, fields, models, _ from odoo.tools import float_repr, float_compare from odoo.exceptions import UserError, ValidationError from odoo.addons.base.models.ir_mail_server import MailDeliveryException from odoo.tests.common import Form _logger = logging.getLogger(__name__) DEFAULT_FACTUR_ITALIAN_DATE_FORMAT = '%Y-%m-%d' class AccountMove(models.Model): _inherit = 'account.move' l10n_it_send_state = fields.Selection([ ('new', 'New'), ('other', 'Other'), ('to_send', 'Not yet send'), ('sent', 'Sent, waiting for response'), ('invalid', 'Sent, but invalid'), ('delivered', 'This invoice is delivered'), ('delivered_accepted', 'This invoice is delivered and accepted by destinatory'), ('delivered_refused', 'This invoice is delivered and refused by destinatory'), ('delivered_expired', 'This invoice is delivered and expired (expiry of the maximum term for communication of acceptance/refusal)'), ('failed_delivery', 'Delivery impossible, ES certify that it has received the invoice and that the file \ could not be delivered to the addressee') # ok we must do nothing ], default='to_send', copy=False, string="FatturaPA Send State") l10n_it_stamp_duty = fields.Float(default=0, string="Dati Bollo", readonly=True, states={'draft': [('readonly', False)]}) l10n_it_ddt_id = fields.Many2one('l10n_it.ddt', string='DDT', readonly=True, states={'draft': [('readonly', False)]}, copy=False) l10n_it_einvoice_name = fields.Char(compute='_compute_l10n_it_einvoice') l10n_it_einvoice_id = fields.Many2one('ir.attachment', string="Electronic invoice", compute='_compute_l10n_it_einvoice') @api.depends('edi_document_ids', 'edi_document_ids.attachment_id') def _compute_l10n_it_einvoice(self): fattura_pa = self.env.ref('l10n_it_edi.edi_fatturaPA') for invoice in self: einvoice = invoice.edi_document_ids.filtered(lambda d: d.edi_format_id == fattura_pa) invoice.l10n_it_einvoice_id = einvoice.attachment_id invoice.l10n_it_einvoice_name = einvoice.attachment_id.name def _check_before_xml_exporting(self): # DEPRECATED use AccountEdiFormat._l10n_it_edi_check_invoice_configuration instead errors = self.env['account.edi.format']._l10n_it_edi_check_invoice_configuration(self) if errors: raise UserError(self.env['account.edi.format']._format_error_message(_("Invalid configuration:"), errors)) def invoice_generate_xml(self): self.ensure_one() report_name = self.env['account.edi.format']._l10n_it_edi_generate_electronic_invoice_filename(self) data = "<?xml version='1.0' encoding='UTF-8'?>" + str(self._export_as_xml()) description = _('Italian invoice: %s', self.move_type) attachment = self.env['ir.attachment'].create({ 'name': report_name, 'res_id': self.id, 'res_model': self._name, 'raw': data.encode(), 'description': description, 'type': 'binary', }) self.message_post( body=(_("E-Invoice is generated on %s by %s") % (fields.Datetime.now(), self.env.user.display_name)) ) return {'attachment': attachment} def _is_commercial_partner_pa(self): """ Returns True if the destination of the FatturaPA belongs to the Public Administration. """ return len(self.commercial_partner_id.l10n_it_pa_index or '') == 6 def _l10n_it_edi_prepare_fatturapa_line_details(self, reverse_charge_refund=False, is_downpayment=False, convert_to_euros=True): """ Returns a list of dictionaries passed to the template for the invoice lines (DettaglioLinee) """ invoice_lines = [] lines = self.invoice_line_ids.filtered(lambda l: not l.display_type) for num, line in enumerate(lines): sign = -1 if line.move_id.is_inbound() else 1 price_subtotal = (line.balance * sign) if convert_to_euros else line.price_subtotal # The price_subtotal should be inverted when the line is a reverse charge refund. if reverse_charge_refund: price_subtotal = -price_subtotal # Unit price price_unit = 0 if line.quantity and line.discount != 100.0: price_unit = price_subtotal / ((1 - (line.discount or 0.0) / 100.0) * abs(line.quantity)) else: price_unit = line.price_unit description = line.name if not is_downpayment: if line.price_subtotal < 0: moves = line._get_downpayment_lines().move_id if moves: description += ', '.join([move.name for move in moves]) line_dict = { 'line': line, 'line_number': num + 1, 'description': description or 'NO NAME', 'unit_price': price_unit, 'subtotal_price': price_subtotal, } invoice_lines.append(line_dict) return invoice_lines def _l10n_it_edi_prepare_fatturapa_tax_details(self, tax_details, reverse_charge_refund=False): """ Returns an adapted dictionary passed to the template for the tax lines (DatiRiepilogo) """ for _tax_name, tax_dict in tax_details['tax_details'].items(): # The assumption is that the company currency is EUR. base_amount = tax_dict['base_amount'] base_amount_currency = tax_dict['base_amount_currency'] tax_amount = tax_dict['tax_amount'] tax_amount_currency = tax_dict['tax_amount_currency'] tax_rate = tax_dict['tax'].amount expected_base_amount_currency = tax_amount_currency * 100 / tax_rate if tax_rate else False expected_base_amount = tax_amount * 100 / tax_rate if tax_rate else False # Constraints within the edi make local rounding on price included taxes a problem. # To solve this there is a <Arrotondamento> or 'rounding' field, such that: # taxable base = sum(taxable base for each unit) + Arrotondamento if tax_dict['tax'].price_include and tax_dict['tax'].amount_type == 'percent': if expected_base_amount_currency and float_compare(base_amount_currency, expected_base_amount_currency, 2): tax_dict['rounding'] = base_amount_currency - (tax_amount_currency * 100 / tax_rate) tax_dict['base_amount_currency'] = base_amount_currency - tax_dict['rounding'] if expected_base_amount and float_compare(base_amount, expected_base_amount, 2): tax_dict['rounding_euros'] = base_amount - (tax_amount * 100 / tax_rate) tax_dict['base_amount'] = base_amount - tax_dict['rounding_euros'] if not reverse_charge_refund: balance_multiplicator = -1 if self.is_inbound() else 1 if tax_dict['base_amount'] != 0: # We shouldn't change 0 into -0 tax_dict['base_amount'] *= balance_multiplicator if tax_dict['base_amount_currency'] != 0: tax_dict['base_amount_currency'] *= balance_multiplicator if tax_dict['tax_amount'] != 0: tax_dict['tax_amount'] *= balance_multiplicator if tax_dict['tax_amount_currency'] != 0: tax_dict['tax_amount_currency'] *= balance_multiplicator return tax_details def _prepare_fatturapa_export_values(self): self.ensure_one() def format_date(dt): # Format the date in the italian standard. dt = dt or datetime.now() return dt.strftime(DEFAULT_FACTUR_ITALIAN_DATE_FORMAT) def format_monetary(number, currency): # Format the monetary values to avoid trailing decimals (e.g. 90.85000000000001). return float_repr(number, min(2, currency.decimal_places)) def format_numbers(number): #format number to str with between 2 and 8 decimals (event if it's .00) number_splited = str(number).split('.') if len(number_splited) == 1: return "%.02f" % number cents = number_splited[1] if len(cents) > 8: return "%.08f" % number return float_repr(number, max(2, len(cents))) def format_numbers_two(number): #format number to str with 2 (event if it's .00) return "%.02f" % number def discount_type(discount): return 'SC' if discount > 0 else 'MG' def format_phone(number): if not number: return False number = number.replace(' ', '').replace('/', '').replace('.', '') if len(number) > 4 and len(number) < 13: return number return False def get_vat_number(vat): if vat[:2].isdecimal(): return vat.replace(' ', '') return vat[2:].replace(' ', '') def get_vat_country(vat): if vat[:2].isdecimal(): return 'IT' return vat[:2].upper() def format_alphanumeric(text_to_convert): return text_to_convert.encode('latin-1', 'replace').decode('latin-1') if text_to_convert else False formato_trasmissione = "FPA12" if self._is_commercial_partner_pa() else "FPR12" # Flags in_eu = self.env['account.edi.format']._l10n_it_edi_partner_in_eu is_self_invoice = self.env['account.edi.format']._l10n_it_edi_is_self_invoice(self) document_type = self.env['account.edi.format']._l10n_it_get_document_type(self) if self.env['account.edi.format']._l10n_it_is_simplified_document_type(document_type): formato_trasmissione = "FSM10" document_type = self.env['account.edi.format']._l10n_it_get_document_type(self) # Represent if the document is a reverse charge refund in a single variable reverse_charge = document_type in ['TD17', 'TD18', 'TD19'] is_downpayment = document_type in ['TD02'] reverse_charge_refund = self.move_type == 'in_refund' and reverse_charge convert_to_euros = self.currency_id.name != 'EUR' # b64encode returns a bytestring, the template tries to turn it to string, # but only gets the repr(pdf) --> "b'<base64_data>'" pdf = self.env.ref('account.account_invoices')._render_qweb_pdf(self.id)[0] pdf = base64.b64encode(pdf).decode() pdf_name = re.sub(r'\W+', '', self.name) + '.pdf' # tax map for 0% taxes which have no tax_line_id tax_map = dict() for line in self.line_ids: for tax in line.tax_ids: if tax.amount == 0.0: tax_map[tax] = tax_map.get(tax, 0.0) + line.price_subtotal tax_details = self._prepare_edi_tax_details( filter_to_apply=lambda l: l['tax_repartition_line_id'].factor_percent >= 0 ) company = self.company_id partner = self.commercial_partner_id buyer = partner if not is_self_invoice else company seller = company if not is_self_invoice else partner codice_destinatario = ( (is_self_invoice and company.partner_id.l10n_it_pa_index) or partner.l10n_it_pa_index or (partner.country_id.code == 'IT' and '0000000') or 'XXXXXXX') # Self-invoices are technically -100%/+100% repartitioned # but functionally need to be exported as 100% document_total = self.amount_total if is_self_invoice: document_total += sum([abs(v['tax_amount_currency']) for k, v in tax_details['tax_details'].items()]) if reverse_charge_refund: document_total = -abs(document_total) # Reference line for finding the conversion rate used in the document conversion_line = self.invoice_line_ids.sorted(lambda l: abs(l.balance), reverse=True)[0] if self.invoice_line_ids else None conversion_rate = float_repr( abs(conversion_line.balance / conversion_line.amount_currency), precision_digits=5, ) if convert_to_euros and conversion_line else None invoice_lines = self._l10n_it_edi_prepare_fatturapa_line_details(reverse_charge_refund, is_downpayment, convert_to_euros) tax_details = self._l10n_it_edi_prepare_fatturapa_tax_details(tax_details, reverse_charge_refund) # Create file content. template_values = { 'record': self, 'company': company, 'sender': company, 'sender_partner': company.partner_id, 'partner': partner, 'buyer': buyer, 'buyer_partner': partner if not is_self_invoice else company.partner_id, 'buyer_is_company': is_self_invoice or partner.is_company, 'seller': seller, 'seller_partner': company.partner_id if not is_self_invoice else partner, 'currency': self.currency_id or self.company_currency_id if not convert_to_euros else self.env.ref('base.EUR'), 'document_total': document_total, 'representative': company.l10n_it_tax_representative_partner_id, 'codice_destinatario': codice_destinatario, 'regime_fiscale': company.l10n_it_tax_system if not is_self_invoice else 'RF18', 'is_self_invoice': is_self_invoice, 'partner_bank': self.partner_bank_id, 'format_date': format_date, 'format_monetary': format_monetary, 'format_numbers': format_numbers, 'format_numbers_two': format_numbers_two, 'format_phone': format_phone, 'format_alphanumeric': format_alphanumeric, 'discount_type': discount_type, 'formato_trasmissione': formato_trasmissione, 'document_type': document_type, 'pdf': pdf, 'pdf_name': pdf_name, 'tax_map': tax_map, 'tax_details': tax_details, 'abs': abs, 'normalize_codice_fiscale': partner._l10n_it_normalize_codice_fiscale, 'get_vat_number': get_vat_number, 'get_vat_country': get_vat_country, 'in_eu': in_eu, 'rc_refund': reverse_charge_refund, 'invoice_lines': invoice_lines, 'conversion_rate': conversion_rate, } return template_values def _export_as_xml(self): '''DEPRECATED : this will be moved to AccountEdiFormat in a future version. Create the xml file content. :return: The XML content as str. ''' template_values = self._prepare_fatturapa_export_values() if not self.env['account.edi.format']._l10n_it_is_simplified_document_type(template_values['document_type']): content = self.env.ref('l10n_it_edi.account_invoice_it_FatturaPA_export')._render(template_values) else: content = self.env.ref('l10n_it_edi.account_invoice_it_simplified_FatturaPA_export')._render(template_values) self.message_post(body=_("A simplified invoice was created instead of an ordinary one. This is because the invoice \ is a domestic invoice with a total amount of less than or equal to 400€ and the customer's address is incomplete.")) return content def _post(self, soft=True): # OVERRIDE posted = super()._post(soft=soft) for move in posted.filtered(lambda m: m.l10n_it_send_state == 'to_send' and m.move_type in ['out_invoice', 'out_refund'] and m.company_id.country_id.code == 'IT'): move.send_pec_mail() return posted def send_pec_mail(self): self.ensure_one() allowed_state = ['to_send', 'invalid'] if ( not self.company_id.l10n_it_mail_pec_server_id or not self.company_id.l10n_it_mail_pec_server_id.active or not self.company_id.l10n_it_address_send_fatturapa ): self.message_post( body=(_("Error when sending mail with E-Invoice: Your company must have a mail PEC server and must indicate the mail PEC that will send electronic invoice.")) ) self.l10n_it_send_state = 'invalid' return if self.l10n_it_send_state not in allowed_state: raise UserError(_("%s isn't in a right state. It must be in a 'Not yet send' or 'Invalid' state.") % (self.display_name)) message = self.env['mail.message'].create({ 'subject': _('Sending file: %s') % (self.l10n_it_einvoice_name), 'body': _('Sending file: %s to ES: %s') % (self.l10n_it_einvoice_name, self.env.company.l10n_it_address_recipient_fatturapa), 'author_id': self.env.user.partner_id.id, 'email_from': self.env.company.l10n_it_address_send_fatturapa, 'reply_to': self.env.company.l10n_it_address_send_fatturapa, 'mail_server_id': self.env.company.l10n_it_mail_pec_server_id.id, 'attachment_ids': [(6, 0, self.l10n_it_einvoice_id.ids)], }) mail_fattura = self.env['mail.mail'].sudo().with_context(wo_bounce_return_path=True).create({ 'mail_message_id': message.id, 'email_to': self.env.company.l10n_it_address_recipient_fatturapa, }) try: mail_fattura.send(raise_exception=True) self.message_post( body=(_("Mail sent on %s by %s") % (fields.Datetime.now(), self.env.user.display_name)) ) self.l10n_it_send_state = 'sent' except MailDeliveryException as error: self.message_post( body=(_("Error when sending mail with E-Invoice: %s") % (error.args[0])) ) self.l10n_it_send_state = 'invalid' def _compose_info_message(self, tree, element_tags): output_str = "" elements = tree.xpath(element_tags) for element in elements: output_str += "<ul>" for line in element.iter(): if line.text: text = " ".join(line.text.split()) if text: output_str += "<li>%s: %s</li>" % (line.tag, text) output_str += "</ul>" return output_str def _compose_multi_info_message(self, tree, element_tags): output_str = "<ul>" for element_tag in element_tags: elements = tree.xpath(element_tag) if not elements: continue for element in elements: text = " ".join(element.text.split()) if text: output_str += "<li>%s: %s</li>" % (element.tag, text) return output_str + "</ul>" class AccountTax(models.Model): _name = "account.tax" _inherit = "account.tax" l10n_it_vat_due_date = fields.Selection([ ("I", "[I] IVA ad esigibilità immediata"), ("D", "[D] IVA ad esigibilità differita"), ("S", "[S] Scissione dei pagamenti")], default="I", string="VAT due date") l10n_it_has_exoneration = fields.Boolean(string="Has exoneration of tax (Italy)", help="Tax has a tax exoneration.") l10n_it_kind_exoneration = fields.Selection(selection=[ ("N1", "[N1] Escluse ex art. 15"), ("N2", "[N2] Non soggette"), ("N2.1", "[N2.1] Non soggette ad IVA ai sensi degli artt. Da 7 a 7-septies del DPR 633/72"), ("N2.2", "[N2.2] Non soggette – altri casi"), ("N3", "[N3] Non imponibili"), ("N3.1", "[N3.1] Non imponibili – esportazioni"), ("N3.2", "[N3.2] Non imponibili – cessioni intracomunitarie"), ("N3.3", "[N3.3] Non imponibili – cessioni verso San Marino"), ("N3.4", "[N3.4] Non imponibili – operazioni assimilate alle cessioni all’esportazione"), ("N3.5", "[N3.5] Non imponibili – a seguito di dichiarazioni d’intento"), ("N3.6", "[N3.6] Non imponibili – altre operazioni che non concorrono alla formazione del plafond"), ("N4", "[N4] Esenti"), ("N5", "[N5] Regime del margine / IVA non esposta in fattura"), ("N6", "[N6] Inversione contabile (per le operazioni in reverse charge ovvero nei casi di autofatturazione per acquisti extra UE di servizi ovvero per importazioni di beni nei soli casi previsti)"), ("N6.1", "[N6.1] Inversione contabile – cessione di rottami e altri materiali di recupero"), ("N6.2", "[N6.2] Inversione contabile – cessione di oro e argento puro"), ("N6.3", "[N6.3] Inversione contabile – subappalto nel settore edile"), ("N6.4", "[N6.4] Inversione contabile – cessione di fabbricati"), ("N6.5", "[N6.5] Inversione contabile – cessione di telefoni cellulari"), ("N6.6", "[N6.6] Inversione contabile – cessione di prodotti elettronici"), ("N6.7", "[N6.7] Inversione contabile – prestazioni comparto edile esettori connessi"), ("N6.8", "[N6.8] Inversione contabile – operazioni settore energetico"), ("N6.9", "[N6.9] Inversione contabile – altri casi"), ("N7", "[N7] IVA assolta in altro stato UE (vendite a distanza ex art. 40 c. 3 e 4 e art. 41 c. 1 lett. b, DL 331/93; prestazione di servizi di telecomunicazioni, tele-radiodiffusione ed elettronici ex art. 7-sexies lett. f, g, art. 74-sexies DPR 633/72)")], string="Exoneration", help="Exoneration type", default="N1") l10n_it_law_reference = fields.Char(string="Law Reference", size=100) @api.constrains('l10n_it_has_exoneration', 'l10n_it_kind_exoneration', 'l10n_it_law_reference', 'amount', 'l10n_it_vat_due_date') def _check_exoneration_with_no_tax(self): for tax in self: if tax.l10n_it_has_exoneration: if not tax.l10n_it_kind_exoneration or not tax.l10n_it_law_reference or tax.amount != 0: raise ValidationError(_("If the tax has exoneration, you must enter a kind of exoneration, a law reference and the amount of the tax must be 0.0.")) if tax.l10n_it_kind_exoneration == 'N6' and tax.l10n_it_vat_due_date == 'S': raise UserError(_("'Scissione dei pagamenti' is not compatible with exoneration of kind 'N6'"))
49.852174
22,932
6,660
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 TAX_SYSTEM = [ ("RF01", "[RF01] Ordinario"), ("RF02", "[RF02] Contribuenti minimi (art.1, c.96-117, L. 244/07)"), ("RF04", "[RF04] Agricoltura e attività connesse e pesca (artt.34 e 34-bis, DPR 633/72)"), ("RF05", "[RF05] Vendita sali e tabacchi (art.74, c.1, DPR. 633/72)"), ("RF06", "[RF06] Commercio fiammiferi (art.74, c.1, DPR 633/72)"), ("RF07", "[RF07] Editoria (art.74, c.1, DPR 633/72)"), ("RF08", "[RF08] Gestione servizi telefonia pubblica (art.74, c.1, DPR 633/72)"), ("RF09", "[RF09] Rivendita documenti di trasporto pubblico e di sosta (art.74, c.1, DPR 633/72)"), ("RF10", "[RF10] Intrattenimenti, giochi e altre attività di cui alla tariffa allegata al DPR 640/72 (art.74, c.6, DPR 633/72)"), ("RF11", "[RF11] Agenzie viaggi e turismo (art.74-ter, DPR 633/72)"), ("RF12", "[RF12] Agriturismo (art.5, c.2, L. 413/91)"), ("RF13", "[RF13] Vendite a domicilio (art.25-bis, c.6, DPR 600/73)"), ("RF14", "[RF14] Rivendita beni usati, oggetti d’arte, d’antiquariato o da collezione (art.36, DL 41/95)"), ("RF15", "[RF15] Agenzie di vendite all’asta di oggetti d’arte, antiquariato o da collezione (art.40-bis, DL 41/95)"), ("RF16", "[RF16] IVA per cassa P.A. (art.6, c.5, DPR 633/72)"), ("RF17", "[RF17] IVA per cassa (art. 32-bis, DL 83/2012)"), ("RF18", "[RF18] Altro"), ("RF19", "[RF19] Regime forfettario (art.1, c.54-89, L. 190/2014)"), ] class ResCompany(models.Model): _name = 'res.company' _inherit = 'res.company' l10n_it_codice_fiscale = fields.Char(string="Codice Fiscale", size=16, related='partner_id.l10n_it_codice_fiscale', store=True, readonly=False, help="Fiscal code of your company") l10n_it_tax_system = fields.Selection(selection=TAX_SYSTEM, string="Tax System", help="Please select the Tax system to which you are subjected.") # PEC server l10n_it_mail_pec_server_id = fields.Many2one('ir.mail_server', string="Server PEC", help="Configure your PEC-mail server to send electronic invoices.") l10n_it_address_recipient_fatturapa = fields.Char(string="Government PEC-mail", help="Enter Government PEC-mail address. Ex: sdi01@pec.fatturapa.it") l10n_it_address_send_fatturapa = fields.Char(string="Company PEC-mail", help="Enter your company PEC-mail address. Ex: yourcompany@pec.mail.it") # Economic and Administrative Index l10n_it_has_eco_index = fields.Boolean(default=False, help="The seller/provider is a company listed on the register of companies and as\ such must also indicate the registration data on all documents (art. 2250, Italian\ Civil Code)") l10n_it_eco_index_office = fields.Many2one('res.country.state', domain="[('country_id','=','IT')]", string="Province of the register-of-companies office") l10n_it_eco_index_number = fields.Char(string="Number in register of companies", size=20, help="This field must contain the number under which the\ seller/provider is listed on the register of companies.") l10n_it_eco_index_share_capital = fields.Float(default=0.0, string="Share capital actually paid up", help="Mandatory if the seller/provider is a company with share\ capital (SpA, SApA, Srl), this field must contain the amount\ of share capital actually paid up as resulting from the last\ financial statement") l10n_it_eco_index_sole_shareholder = fields.Selection( [ ("NO", "Not a limited liability company"), ("SU", "Socio unico"), ("SM", "Più soci")], string="Shareholder") l10n_it_eco_index_liquidation_state = fields.Selection( [ ("LS", "The company is in a state of liquidation"), ("LN", "The company is not in a state of liquidation")], string="Liquidation state") # Tax representative l10n_it_has_tax_representative = fields.Boolean(default=False, help="The seller/provider is a non-resident subject which\ carries out transactions in Italy with relevance for VAT\ purposes and which takes avail of a tax representative in\ Italy") l10n_it_tax_representative_partner_id = fields.Many2one('res.partner', string='Tax representative partner') @api.constrains('l10n_it_has_eco_index', 'l10n_it_eco_index_office', 'l10n_it_eco_index_number', 'l10n_it_eco_index_liquidation_state') def _check_eco_admin_index(self): for record in self: if (record.l10n_it_has_eco_index and (not record.l10n_it_eco_index_office or not record.l10n_it_eco_index_number or not record.l10n_it_eco_index_liquidation_state)): raise ValidationError(_("All fields about the Economic and Administrative Index must be completed.")) @api.constrains('l10n_it_has_eco_index', 'l10n_it_eco_index_share_capital', 'l10n_it_eco_index_sole_shareholder') def _check_eco_incorporated(self): """ If the business is incorporated, both these fields must be present. We don't know whether the business is incorporated, but in any case the fields must be both present or not present. """ for record in self: if (record.l10n_it_has_eco_index and bool(record.l10n_it_eco_index_share_capital) ^ bool(record.l10n_it_eco_index_sole_shareholder)): raise ValidationError(_("If one of Share Capital or Sole Shareholder is present, " "then they must be both filled out.")) @api.constrains('l10n_it_has_tax_representative', 'l10n_it_tax_representative_partner_id') def _check_tax_representative(self): for record in self: if not record.l10n_it_has_tax_representative: continue if not record.l10n_it_tax_representative_partner_id: raise ValidationError(_("You must select a tax representative.")) if not record.l10n_it_tax_representative_partner_id.vat: raise ValidationError(_("Your tax representative partner must have a tax number.")) if not record.l10n_it_tax_representative_partner_id.country_id: raise ValidationError(_("Your tax representative partner must have a country."))
56.347458
6,649
2,351
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from stdnum.it import codicefiscale, iva from odoo import api, fields, models, _ from odoo.exceptions import UserError import re class ResPartner(models.Model): _name = 'res.partner' _inherit = 'res.partner' l10n_it_pec_email = fields.Char(string="PEC e-mail") l10n_it_codice_fiscale = fields.Char(string="Codice Fiscale", size=16) l10n_it_pa_index = fields.Char(string="PA index", size=7, help="Must contain the 6-character (or 7) code, present in the PA\ Index in the information relative to the electronic invoicing service,\ associated with the office which, within the addressee administration, deals\ with receiving (and processing) the invoice.") _sql_constraints = [ ('l10n_it_codice_fiscale', "CHECK(l10n_it_codice_fiscale IS NULL OR l10n_it_codice_fiscale = '' OR LENGTH(l10n_it_codice_fiscale) >= 11)", "Codice fiscale must have between 11 and 16 characters."), ('l10n_it_pa_index', "CHECK(l10n_it_pa_index IS NULL OR l10n_it_pa_index = '' OR LENGTH(l10n_it_pa_index) >= 6)", "PA index must have between 6 and 7 characters."), ] @api.model def _l10n_it_normalize_codice_fiscale(self, codice): if codice and re.match(r'^IT[0-9]{11}$', codice): return codice[2:13] return codice @api.onchange('vat', 'country_id') def _l10n_it_onchange_vat(self): if not self.l10n_it_codice_fiscale and self.vat and (self.country_id.code == "IT" or self.vat.startswith("IT")): self.l10n_it_codice_fiscale = self._l10n_it_normalize_codice_fiscale(self.vat) elif self.country_id.code not in [False, "IT"]: self.l10n_it_codice_fiscale = "" @api.constrains('l10n_it_codice_fiscale') def validate_codice_fiscale(self): for record in self: if record.l10n_it_codice_fiscale and (not codicefiscale.is_valid(record.l10n_it_codice_fiscale) and not iva.is_valid(record.l10n_it_codice_fiscale)): raise UserError(_("Invalid Codice Fiscale '%s': should be like 'MRTMTT91D08F205J' for physical person and '12345670546' or 'IT12345670546' for businesses.", record.l10n_it_codice_fiscale))
46.098039
2,351
567
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Event Attendees SMS Marketing', 'category': 'Hidden', 'version': '1.0', 'description': """ SMS Marketing on event attendees ================================ Bridge module adding UX requirements to ease SMS marketing o, event attendees. """, 'depends': [ 'event', 'mass_mailing', 'mass_mailing_sms', 'sms', ], 'data': [ ], 'auto_install': True, 'license': 'LGPL-3', }
22.68
567
828
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class Event(models.Model): _inherit = "event.event" def action_mass_mailing_attendees(self): # Minimal override: set form view being the one mixing sms and mail (not prioritized one) action = super(Event, self).action_mass_mailing_attendees() action['view_id'] = self.env.ref('mass_mailing_sms.mailing_mailing_view_form_mixed').id return action def action_invite_contacts(self): # Minimal override: set form view being the one mixing sms and mail (not prioritized one) action = super(Event, self).action_invite_contacts() action['view_id'] = self.env.ref('mass_mailing_sms.mailing_mailing_view_form_mixed').id return action
41.4
828
2,069
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Indian - Accounting', 'version': '2.0', 'description': """ Indian Accounting: Chart of Account. ==================================== Indian accounting chart and localization. Odoo allows to manage Indian Accounting by providing Two Formats Of Chart of Accounts i.e Indian Chart Of Accounts - Standard and Indian Chart Of Accounts - Schedule VI. Note: The Schedule VI has been revised by MCA and is applicable for all Balance Sheet made after 31st March, 2011. The Format has done away with earlier two options of format of Balance Sheet, now only Vertical format has been permitted Which is Supported By Odoo. """, 'category': 'Accounting/Localizations/Account Charts', 'depends': [ 'account_tax_python', 'base_vat', ], 'data': [ 'security/l10n_in_security.xml', 'security/ir.model.access.csv', 'data/account_tax_group_data.xml', 'data/l10n_in_chart_data.xml', 'data/account.account.template.csv', 'data/l10n_in_chart_post_data.xml', 'data/account_tax_template_data.xml', 'data/account_fiscal_position_data.xml', 'data/l10n_in.port.code.csv', 'data/res_country_state_data.xml', 'data/uom_data.xml', 'views/account_invoice_views.xml', 'views/account_journal_views.xml', 'views/res_config_settings_views.xml', 'views/product_template_view.xml', 'views/port_code_views.xml', 'views/report_invoice.xml', 'views/res_country_state_view.xml', 'views/res_partner_views.xml', 'views/account_tax_views.xml', 'views/uom_uom_views.xml', 'views/report_template.xml', 'data/account_chart_template_data.xml' ], 'demo': [ 'demo/demo_company.xml', 'demo/res_partner_demo.xml', 'demo/product_demo.xml', 'demo/account_payment_demo.xml', 'demo/account_invoice_demo.xml', ], 'license': 'LGPL-3', }
36.946429
2,069
265
py
PYTHON
15.0
# -*- coding: utf-8 -*- import odoo def migrate(cr, version): registry = odoo.registry(cr.dbname) from odoo.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_in')
33.125
265
292
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 CountryState(models.Model): _inherit = 'res.country.state' l10n_in_tin = fields.Char('TIN Number', size=2, help="TIN number-first two digits")
29.2
292
473
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class ProductTemplate(models.Model): _inherit = 'product.template' l10n_in_hsn_code = fields.Char(string="HSN/SAC Code", help="Harmonized System Nomenclature/Services Accounting Code") l10n_in_hsn_description = fields.Char(string="HSN/SAC Description", help="HSN/SAC description is required if HSN/SAC code is not provided.")
43
473
7,493
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, RedirectWarning class AccountMove(models.Model): _inherit = "account.move" amount_total_words = fields.Char("Total (In Words)", compute="_compute_amount_total_words") l10n_in_gst_treatment = fields.Selection([ ('regular', 'Registered Business - Regular'), ('composition', 'Registered Business - Composition'), ('unregistered', 'Unregistered Business'), ('consumer', 'Consumer'), ('overseas', 'Overseas'), ('special_economic_zone', 'Special Economic Zone'), ('deemed_export', 'Deemed Export') ], string="GST Treatment", compute="_compute_l10n_in_gst_treatment", store=True, readonly=False, copy=True) l10n_in_state_id = fields.Many2one('res.country.state', string="Location of supply") l10n_in_gstin = fields.Char(string="GSTIN") # For Export invoice this data is need in GSTR report l10n_in_shipping_bill_number = fields.Char('Shipping bill number', readonly=True, states={'draft': [('readonly', False)]}) l10n_in_shipping_bill_date = fields.Date('Shipping bill date', readonly=True, states={'draft': [('readonly', False)]}) l10n_in_shipping_port_code_id = fields.Many2one('l10n_in.port.code', 'Port code', states={'draft': [('readonly', False)]}) l10n_in_reseller_partner_id = fields.Many2one('res.partner', 'Reseller', domain=[('vat', '!=', False)], help="Only Registered Reseller", readonly=True, states={'draft': [('readonly', False)]}) @api.depends('amount_total') def _compute_amount_total_words(self): for invoice in self: invoice.amount_total_words = invoice.currency_id.amount_to_text(invoice.amount_total) @api.depends('partner_id') def _compute_l10n_in_gst_treatment(self): for record in self: record.l10n_in_gst_treatment = record.partner_id.l10n_in_gst_treatment @api.model def _l10n_in_get_indian_state(self, partner): """In tax return filing, If customer is not Indian in that case place of supply is must set to Other Territory. So we set Other Territory in l10n_in_state_id when customer(partner) is not Indian Also we raise if state is not set in Indian customer. State is big role under GST because tax type is depend on.for more information check this https://www.cbic.gov.in/resources//htdocs-cbec/gst/Integrated%20goods%20&%20Services.pdf""" if partner.country_id and partner.country_id.code == 'IN' and not partner.state_id: raise ValidationError(_("State is missing from address in '%s'. First set state after post this invoice again.", partner.name)) elif partner.country_id and partner.country_id.code != 'IN': return self.env.ref('l10n_in.state_in_ot') return partner.state_id @api.model def _get_tax_grouping_key_from_tax_line(self, tax_line): # OVERRIDE to group taxes also by product. res = super()._get_tax_grouping_key_from_tax_line(tax_line) if tax_line.move_id.journal_id.company_id.account_fiscal_country_id.code == 'IN': res['product_id'] = tax_line.product_id.id res['product_uom_id'] = tax_line.product_uom_id.id return res @api.model def _get_tax_grouping_key_from_base_line(self, base_line, tax_vals): # OVERRIDE to group taxes also by product. res = super()._get_tax_grouping_key_from_base_line(base_line, tax_vals) if base_line.move_id.journal_id.company_id.account_fiscal_country_id.code == 'IN': res['product_id'] = base_line.product_id.id res['product_uom_id'] = base_line.product_uom_id.id return res @api.model def _get_tax_key_for_group_add_base(self, line): # DEPRECATED: TO BE REMOVED IN MASTER tax_key = super(AccountMove, self)._get_tax_key_for_group_add_base(line) tax_key += [ line.product_id.id, line.product_uom_id.id, ] return tax_key def _l10n_in_get_shipping_partner(self): """Overwrite in sale""" self.ensure_one() return self.partner_id @api.model def _l10n_in_get_shipping_partner_gstin(self, shipping_partner): """Overwrite in sale""" return shipping_partner.vat def _post(self, soft=True): """Use journal type to define document type because not miss state in any entry including POS entry""" posted = super()._post(soft) gst_treatment_name_mapping = {k: v for k, v in self._fields['l10n_in_gst_treatment']._description_selection(self.env)} for move in posted.filtered(lambda m: m.country_code == 'IN'): """Check state is set in company/sub-unit""" company_unit_partner = move.journal_id.l10n_in_gstin_partner_id or move.journal_id.company_id if not company_unit_partner.state_id: msg = _("Your company %s needs to have a correct address in order to validate this invoice.\n" "Set the address of your company (Don't forget the State field)") % (company_unit_partner.name) action = { "view_mode": "form", "res_model": "res.company", "type": "ir.actions.act_window", "res_id" : move.company_id.id, "views": [[self.env.ref("base.view_company_form").id, "form"]], } raise RedirectWarning(msg, action, _('Go to Company configuration')) elif move.journal_id.type == 'purchase': move.l10n_in_state_id = company_unit_partner.state_id shipping_partner = move._l10n_in_get_shipping_partner() # In case of shipping address does not have GSTN then also check customer(partner_id) GSTN # This happens when Bill-to Ship-to transaction where shipping(Ship-to) address is unregistered and customer(Bill-to) is registred. move.l10n_in_gstin = move._l10n_in_get_shipping_partner_gstin(shipping_partner) or move.partner_id.vat if not move.l10n_in_gstin and move.l10n_in_gst_treatment in ['regular', 'composition', 'special_economic_zone', 'deemed_export']: raise ValidationError(_( "Partner %(partner_name)s (%(partner_id)s) GSTIN is required under GST Treatment %(name)s", partner_name=shipping_partner.name, partner_id=shipping_partner.id, name=gst_treatment_name_mapping.get(move.l10n_in_gst_treatment) )) if move.journal_id.type == 'sale': move.l10n_in_state_id = self._l10n_in_get_indian_state(shipping_partner) if not move.l10n_in_state_id: move.l10n_in_state_id = self._l10n_in_get_indian_state(move.partner_id) #still state is not set then assumed that transaction is local like PoS so set state of company unit if not move.l10n_in_state_id: move.l10n_in_state_id = company_unit_partner.state_id return posted def _l10n_in_get_warehouse_address(self): """Return address where goods are delivered/received for Invoice/Bill""" # TO OVERRIDE self.ensure_one() return False
54.693431
7,493
340
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 UoM(models.Model): _inherit = "uom.uom" # As per GST Rules you need to Specify UQC given by GST. l10n_in_code = fields.Char("Indian GST UQC", help="Unique Quantity Code (UQC) under GST")
30.909091
340
626
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 L10nInPortCode(models.Model): """Port code must be mentioned in export and import of goods under GST.""" _name = 'l10n_in.port.code' _description = "Indian port code" _rec_name = 'code' code = fields.Char(string="Port Code", required=True) name = fields.Char(string="Port", required=True) state_id = fields.Many2one('res.country.state', string="State") _sql_constraints = [ ('code_uniq', 'unique (code)', 'The Port Code must be unique!') ]
32.947368
626
355
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' group_l10n_in_reseller = fields.Boolean(implied_group='l10n_in.group_l10n_in_reseller', string="Manage Reseller(E-Commerce)")
35.5
355
2,178
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, _ TEST_GST_NUMBER = "36AABCT1332L011" class ResPartner(models.Model): _inherit = 'res.partner' l10n_in_gst_treatment = fields.Selection([ ('regular', 'Registered Business - Regular'), ('composition', 'Registered Business - Composition'), ('unregistered', 'Unregistered Business'), ('consumer', 'Consumer'), ('overseas', 'Overseas'), ('special_economic_zone', 'Special Economic Zone'), ('deemed_export', 'Deemed Export'), ], string="GST Treatment") @api.onchange('company_type') def onchange_company_type(self): res = super().onchange_company_type() if self.country_id and self.country_id.code == 'IN': self.l10n_in_gst_treatment = (self.company_type == 'company') and 'regular' or 'consumer' return res @api.onchange('country_id') def _onchange_country_id(self): res = super()._onchange_country_id() if self.country_id and self.country_id.code != 'IN': self.l10n_in_gst_treatment = 'overseas' elif self.country_id and self.country_id.code == 'IN': self.l10n_in_gst_treatment = (self.company_type == 'company') and 'regular' or 'consumer' return res @api.onchange('vat') def onchange_vat(self): if self.vat and self.check_vat_in(self.vat): state_id = self.env['res.country.state'].search([('l10n_in_tin', '=', self.vat[:2])], limit=1) if state_id: self.state_id = state_id @api.model def _commercial_fields(self): res = super()._commercial_fields() return res + ['l10n_in_gst_treatment'] def check_vat_in(self, vat): """ This TEST_GST_NUMBER is used as test credentials for EDI but this is not a valid number as per the regular expression so TEST_GST_NUMBER is considered always valid """ if vat == TEST_GST_NUMBER: return True return super().check_vat_in(vat)
38.210526
2,178
1,715
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class AccountChartTemplate(models.Model): _inherit = 'account.chart.template' def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None): res = super(AccountChartTemplate, self)._prepare_all_journals(acc_template_ref, company, journals_dict=journals_dict) if self == self.env.ref('l10n_in.indian_chart_template_standard'): for journal in res: if journal.get('type') in ('sale','purchase'): journal['l10n_in_gstin_partner_id'] = company.partner_id.id return res def _load(self, sale_tax_rate, purchase_tax_rate, company): """ Set Opening Date and Fiscal Year End in Indian localization""" res = super(AccountChartTemplate, self)._load(sale_tax_rate, purchase_tax_rate, company) if self == self.env.ref("l10n_in.indian_chart_template_standard"): company.write({ 'account_opening_date': fields.Date.context_today(self).replace(month=4, day=1), 'fiscalyear_last_month': '3', }) return res class AccountTaxTemplate(models.Model): _inherit = 'account.tax.template' l10n_in_reverse_charge = fields.Boolean("Reverse charge", help="Tick this if this tax is reverse charge. Only for Indian accounting") def _get_tax_vals(self, company, tax_template_to_tax): val = super(AccountTaxTemplate, self)._get_tax_vals(company, tax_template_to_tax) if self.tax_group_id: val['l10n_in_reverse_charge'] = self.l10n_in_reverse_charge return val
45.131579
1,715
2,758
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 import tools class AccountJournal(models.Model): _inherit = "account.journal" # Use for filter import and export type. l10n_in_gstin_partner_id = fields.Many2one('res.partner', string="GSTIN Unit", ondelete="restrict", help="GSTIN related to this journal. If empty then consider as company GSTIN.") def name_get(self): """ Add GSTIN number in name as suffix so user can easily find the right journal. Used super to ensure nothing is missed. """ result = super().name_get() result_dict = dict(result) indian_journals = self.filtered(lambda j: j.company_id.account_fiscal_country_id.code == 'IN' and j.l10n_in_gstin_partner_id and j.l10n_in_gstin_partner_id.vat) for journal in indian_journals: name = result_dict[journal.id] name += "- %s" % (journal.l10n_in_gstin_partner_id.vat) result_dict[journal.id] = name return list(result_dict.items()) class AccountMoveLine(models.Model): _inherit = "account.move.line" def init(self): tools.create_index(self._cr, 'account_move_line_move_product_index', self._table, ['move_id', 'product_id']) @api.depends('move_id.line_ids', 'move_id.line_ids.tax_line_id', 'move_id.line_ids.debit', 'move_id.line_ids.credit') def _compute_tax_base_amount(self): aml = self.filtered(lambda l: l.company_id.account_fiscal_country_id.code == 'IN' and l.tax_line_id and l.product_id) for move_line in aml: base_lines = move_line.move_id.line_ids.filtered(lambda line: move_line.tax_line_id in line.tax_ids and move_line.product_id == line.product_id) move_line.tax_base_amount = abs(sum(base_lines.mapped('balance'))) remaining_aml = self - aml if remaining_aml: return super(AccountMoveLine, remaining_aml)._compute_tax_base_amount() class AccountTax(models.Model): _inherit = 'account.tax' l10n_in_reverse_charge = fields.Boolean("Reverse charge", help="Tick this if this tax is reverse charge. Only for Indian accounting") def get_grouping_key(self, invoice_tax_val): """ Returns a string that will be used to group account.invoice.tax sharing the same properties""" key = super(AccountTax, self).get_grouping_key(invoice_tax_val) if self.company_id.account_fiscal_country_id.code == 'IN': key += "-%s-%s"% (invoice_tax_val.get('l10n_in_product_id', False), invoice_tax_val.get('l10n_in_uom_id', False)) return key
46.745763
2,758
9,393
py
PYTHON
15.0
# -*- coding:utf-8 -*- #az Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools class L10nInPaymentReport(models.AbstractModel): _name = "l10n_in.payment.report" _description = "Indian accounting payment report" account_move_id = fields.Many2one('account.move', string="Account Move") payment_id = fields.Many2one('account.payment', string='Payment') currency_id = fields.Many2one('res.currency', string="Currency") amount = fields.Float(string="Amount") payment_amount = fields.Float(string="Payment Amount") partner_id = fields.Many2one('res.partner', string="Customer") payment_type = fields.Selection([('outbound', 'Send Money'), ('inbound', 'Receive Money')], string='Payment Type') journal_id = fields.Many2one('account.journal', string="Journal") company_id = fields.Many2one(related="journal_id.company_id", string="Company") place_of_supply = fields.Char(string="Place of Supply") supply_type = fields.Char(string="Supply Type") l10n_in_tax_id = fields.Many2one('account.tax', string="Tax") tax_rate = fields.Float(string="Rate") igst_amount = fields.Float(compute="_compute_tax_amount", string="IGST amount") cgst_amount = fields.Float(compute="_compute_tax_amount", string="CGST amount") sgst_amount = fields.Float(compute="_compute_tax_amount", string="SGST amount") cess_amount = fields.Float(compute="_compute_tax_amount", string="CESS amount") gross_amount = fields.Float(compute="_compute_tax_amount", string="Gross advance") def _compute_l10n_in_tax(self, taxes, price_unit, currency=None, quantity=1.0, product=None, partner=None): """common method to compute gst tax amount base on tax group""" res = {'igst_amount': 0.0, 'sgst_amount': 0.0, 'cgst_amount': 0.0, 'cess_amount': 0.0} AccountTaxRepartitionLine = self.env['account.tax.repartition.line'] tax_report_line_igst = self.env.ref('l10n_in.tax_report_line_igst', False) tax_report_line_cgst = self.env.ref('l10n_in.tax_report_line_cgst', False) tax_report_line_sgst = self.env.ref('l10n_in.tax_report_line_sgst', False) tax_report_line_cess = self.env.ref('l10n_in.tax_report_line_cess', False) filter_tax = taxes.filtered(lambda t: t.type_tax_use != 'none') tax_compute = filter_tax.compute_all(price_unit, currency=currency, quantity=quantity, product=product, partner=partner) for tax_data in tax_compute['taxes']: tax_report_lines = AccountTaxRepartitionLine.browse(tax_data['tax_repartition_line_id']).mapped('tag_ids.tax_report_line_ids') if tax_report_line_sgst in tax_report_lines: res['sgst_amount'] += tax_data['amount'] if tax_report_line_cgst in tax_report_lines: res['cgst_amount'] += tax_data['amount'] if tax_report_line_igst in tax_report_lines: res['igst_amount'] += tax_data['amount'] if tax_report_line_cess in tax_report_lines: res['cess_amount'] += tax_data['amount'] res.update(tax_compute) return res #TO BE OVERWRITTEN @api.depends('currency_id') def _compute_tax_amount(self): """Calculate tax amount base on default tax set in company""" def _select(self): return """SELECT aml.id AS id, aml.move_id as account_move_id, ap.id AS payment_id, ap.payment_type, tax.id as l10n_in_tax_id, tax.amount AS tax_rate, am.partner_id, am.amount_total AS payment_amount, am.journal_id, aml.currency_id, (CASE WHEN ps.l10n_in_tin IS NOT NULL THEN concat(ps.l10n_in_tin,'-',ps.name) WHEN p.id IS NULL and cps.l10n_in_tin IS NOT NULL THEN concat(cps.l10n_in_tin,'-',cps.name) ELSE '' END) AS place_of_supply, (CASE WHEN ps.id = cp.state_id or p.id IS NULL THEN 'Intra State' WHEN ps.id != cp.state_id and p.id IS NOT NULL THEN 'Inter State' END) AS supply_type""" def _from(self): return """FROM account_move_line aml JOIN account_move am ON am.id = aml.move_id JOIN account_payment ap ON ap.id = aml.payment_id JOIN account_account AS ac ON ac.id = aml.account_id JOIN account_journal AS aj ON aj.id = am.journal_id JOIN res_company AS c ON c.id = aj.company_id JOIN account_tax AS tax ON tax.id = ( CASE WHEN ap.payment_type = 'inbound' THEN c.account_sale_tax_id ELSE c.account_purchase_tax_id END) JOIN res_partner p ON p.id = aml.partner_id LEFT JOIN res_country_state ps ON ps.id = p.state_id LEFT JOIN res_partner cp ON cp.id = COALESCE(aj.l10n_in_gstin_partner_id, c.partner_id) LEFT JOIN res_country_state cps ON cps.id = cp.state_id """ def _where(self): return """WHERE aml.payment_id IS NOT NULL AND tax.tax_group_id in (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('igst_group','gst_group')) AND ac.internal_type IN ('receivable', 'payable') AND am.state = 'posted'""" def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute("""CREATE or REPLACE VIEW %s AS ( %s %s %s)""" % (self._table, self._select(), self._from(), self._where())) class AdvancesPaymentReport(models.Model): _name = "l10n_in.advances.payment.report" _inherit = 'l10n_in.payment.report' _description = "Advances Payment Analysis" _auto = False date = fields.Date(string="Payment Date") reconcile_amount = fields.Float(string="Reconcile amount in Payment month") @api.depends('payment_amount', 'reconcile_amount', 'currency_id') def _compute_tax_amount(self): """Calculate tax amount base on default tax set in company""" account_move_line = self.env['account.move.line'] for record in self: base_amount = record.payment_amount - record.reconcile_amount taxes_data = self._compute_l10n_in_tax( taxes=record.l10n_in_tax_id, price_unit=base_amount, currency=record.currency_id or None, quantity=1, partner=record.partner_id or None) record.igst_amount = taxes_data['igst_amount'] record.cgst_amount = taxes_data['cgst_amount'] record.sgst_amount = taxes_data['sgst_amount'] record.cess_amount = taxes_data['cess_amount'] record.gross_amount = taxes_data['total_excluded'] def _select(self): select_str = super(AdvancesPaymentReport, self)._select() select_str += """, am.date as date, (SELECT sum(amount) FROM account_partial_reconcile AS apr WHERE (apr.credit_move_id = aml.id OR apr.debit_move_id = aml.id) AND (to_char(apr.max_date, 'MM-YYYY') = to_char(aml.date, 'MM-YYYY')) ) AS reconcile_amount, (am.amount_total - (SELECT (CASE WHEN SUM(amount) IS NULL THEN 0 ELSE SUM(amount) END) FROM account_partial_reconcile AS apr WHERE (apr.credit_move_id = aml.id OR apr.debit_move_id = aml.id) AND (to_char(apr.max_date, 'MM-YYYY') = to_char(aml.date, 'MM-YYYY')) )) AS amount""" return select_str class L10nInAdvancesPaymentAdjustmentReport(models.Model): _name = "l10n_in.advances.payment.adjustment.report" _inherit = 'l10n_in.payment.report' _description = "Advances Payment Adjustment Analysis" _auto = False date = fields.Date('Reconcile Date') @api.depends('amount', 'currency_id', 'partner_id') def _compute_tax_amount(self): account_move_line = self.env['account.move.line'] for record in self: taxes_data = self._compute_l10n_in_tax( taxes=record.l10n_in_tax_id, price_unit=record.amount, currency=record.currency_id or None, quantity=1, partner=record.partner_id or None) record.igst_amount = taxes_data['igst_amount'] record.cgst_amount = taxes_data['cgst_amount'] record.sgst_amount = taxes_data['sgst_amount'] record.cess_amount = taxes_data['cess_amount'] record.gross_amount = taxes_data['total_excluded'] def _select(self): select_str = super(L10nInAdvancesPaymentAdjustmentReport, self)._select() select_str += """, apr.max_date AS date, apr.amount AS amount """ return select_str def _from(self): from_str = super(L10nInAdvancesPaymentAdjustmentReport, self)._from() from_str += """ JOIN account_partial_reconcile apr ON apr.credit_move_id = aml.id OR apr.debit_move_id = aml.id """ return from_str def _where(self): where_str = super(L10nInAdvancesPaymentAdjustmentReport, self)._where() where_str += """ AND (apr.max_date > aml.date) """ return where_str
47.923469
9,393
4,276
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools class L10nInExemptedReport(models.Model): _name = "l10n_in.exempted.report" _description = "Exempted Gst Supplied Statistics" _auto = False account_move_id = fields.Many2one('account.move', string="Account Move") partner_id = fields.Many2one('res.partner', string="Customer") out_supply_type = fields.Char(string="Outward Supply Type") in_supply_type = fields.Char(string="Inward Supply Type") nil_rated_amount = fields.Float("Nil rated supplies") exempted_amount = fields.Float("Exempted") non_gst_supplies = fields.Float("Non GST Supplies") date = fields.Date("Date") company_id = fields.Many2one('res.company', string="Company") journal_id = fields.Many2one('account.journal', string="Journal") def _select(self): select_str = """SELECT aml.id AS id, aml.partner_id AS partner_id, am.date, aml.balance * (CASE WHEN aj.type = 'sale' THEN -1 ELSE 1 END) AS price_total, am.journal_id, aj.company_id, aml.move_id as account_move_id, (CASE WHEN p.state_id = cp.state_id THEN (CASE WHEN p.vat IS NOT NULL THEN 'Intra-State supplies to registered persons' ELSE 'Intra-State supplies to unregistered persons' END) WHEN p.state_id != cp.state_id THEN (CASE WHEN p.vat IS NOT NULL THEN 'Inter-State supplies to registered persons' ELSE 'Inter-State supplies to unregistered persons' END) END) AS out_supply_type, (CASE WHEN p.state_id = cp.state_id THEN 'Intra-State supplies' WHEN p.state_id != cp.state_id THEN 'Inter-State supplies' END) AS in_supply_type, (CASE WHEN ( SELECT MAX(account_tax_id) FROM account_move_line_account_tax_rel JOIN account_tax at ON at.id = account_tax_id WHERE account_move_line_id = aml.id AND at.tax_group_id IN ((SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name='nil_rated_group')) ) IS NOT NULL THEN aml.balance * (CASE WHEN aj.type = 'sale' THEN -1 ELSE 1 END) ELSE 0 END) AS nil_rated_amount, (CASE WHEN ( SELECT MAX(account_tax_id) FROM account_move_line_account_tax_rel JOIN account_tax at ON at.id = account_tax_id WHERE account_move_line_id = aml.id AND at.tax_group_id IN ((SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name='exempt_group')) ) IS NOT NULL THEN aml.balance * (CASE WHEN aj.type = 'sale' THEN -1 ELSE 1 END) ELSE 0 END) AS exempted_amount, (CASE WHEN ( SELECT MAX(account_tax_id) FROM account_move_line_account_tax_rel WHERE account_move_line_id = aml.id ) IS NULL THEN aml.balance * (CASE WHEN aj.type = 'sale' THEN -1 ELSE 1 END) ELSE 0 END) AS non_gst_supplies """ return select_str def _from(self): from_str = """FROM account_move_line aml JOIN account_move am ON am.id = aml.move_id JOIN account_account aa ON aa.id = aml.account_id JOIN account_journal aj ON aj.id = am.journal_id JOIN res_company c ON c.id = aj.company_id LEFT JOIN res_partner cp ON cp.id = COALESCE(aj.l10n_in_gstin_partner_id, c.partner_id) LEFT JOIN res_partner p ON p.id = am.partner_id LEFT JOIN res_country pc ON pc.id = p.country_id WHERE aa.internal_type = 'other' and aml.tax_line_id IS NULL """ return from_str def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self._cr.execute("""CREATE OR REPLACE VIEW %s AS (%s %s)""" % ( self._table, self._select(), self._from()))
45.010526
4,276
6,653
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools class L10nInProductHsnReport(models.Model): _name = "l10n_in.product.hsn.report" _description = "Product HSN Statistics" _auto = False _order = 'date desc' account_move_id = fields.Many2one('account.move', string="Account Move") partner_id = fields.Many2one('res.partner', string="Customer") product_id = fields.Many2one("product.product", string="Product") uom_id = fields.Many2one('uom.uom', string="UOM") quantity = fields.Float(string="Product Qty") date = fields.Date(string="Date") price_total = fields.Float(string='Taxable Value') total = fields.Float(string="Total Value") igst_amount = fields.Float(string="Integrated Tax Amount") cgst_amount = fields.Float(string="Central Tax Amount") sgst_amount = fields.Float(string="State/UT Tax Amount") cess_amount = fields.Float(string="Cess Amount") company_id = fields.Many2one('res.company', string="Company") journal_id = fields.Many2one('account.journal', string="Journal") hsn_code = fields.Char(string="HSN") hsn_description = fields.Char(string="HSN description") l10n_in_uom_code = fields.Char(string="UQC") def _select(self): select_str = """SELECT aml.id AS id, aml.move_id AS account_move_id, aml.partner_id AS partner_id, aml.product_id, aml.product_uom_id AS uom_id, am.date, am.journal_id, aj.company_id, CASE WHEN pt.l10n_in_hsn_code IS NULL THEN '' ELSE pt.l10n_in_hsn_code END AS hsn_code, CASE WHEN pt.l10n_in_hsn_description IS NULL THEN '' ELSE pt.l10n_in_hsn_description END AS hsn_description, CASE WHEN uom.l10n_in_code IS NULL THEN '' ELSE uom.l10n_in_code END AS l10n_in_uom_code, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_sgst', 'tax_report_line_sgst_rc')) OR at.l10n_in_reverse_charge = True THEN 0 ELSE aml.quantity END * (CASE WHEN am.move_type in ('in_refund','out_refund') THEN -1 ELSE 1 END) AS quantity, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_igst', 'tax_report_line_igst_rc')) THEN aml.balance * (CASE WHEN aj.type = 'sale' and am.move_type != 'out_refund' THEN -1 ELSE 1 END) ELSE 0 END * (CASE WHEN am.move_type in ('in_refund','out_refund') THEN -1 ELSE 1 END) AS igst_amount, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_cgst', 'tax_report_line_cgst_rc')) THEN aml.balance * (CASE WHEN aj.type = 'sale' and am.move_type != 'out_refund' THEN -1 ELSE 1 END) ELSE 0 END * (CASE WHEN am.move_type in ('in_refund','out_refund') THEN -1 ELSE 1 END) AS cgst_amount, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_sgst', 'tax_report_line_sgst_rc')) THEN aml.balance * (CASE WHEN aj.type = 'sale' and am.move_type != 'out_refund' THEN -1 ELSE 1 END) ELSE 0 END * (CASE WHEN am.move_type in ('in_refund','out_refund') THEN -1 ELSE 1 END) AS sgst_amount, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_cess', 'tax_report_line_cess_rc')) THEN aml.balance * (CASE WHEN aj.type = 'sale' and am.move_type != 'out_refund' THEN -1 ELSE 1 END) ELSE 0 END * (CASE WHEN am.move_type in ('in_refund','out_refund') THEN -1 ELSE 1 END) AS cess_amount, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_sgst', 'tax_report_line_sgst_rc')) THEN 0 ELSE (CASE WHEN aml.tax_line_id IS NOT NULL THEN aml.tax_base_amount ELSE aml.balance * (CASE WHEN aj.type = 'sale' THEN -1 ELSE 1 END) END) END * (CASE WHEN am.move_type in ('in_refund','out_refund') THEN -1 ELSE 1 END) AS price_total, ((CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_sgst', 'tax_report_line_sgst_rc')) THEN 0 ELSE (CASE WHEN aml.tax_line_id IS NOT NULL THEN aml.tax_base_amount ELSE 1 END) END) + (aml.balance * (CASE WHEN aj.type = 'sale' and am.move_type != 'out_refund' THEN -1 ELSE 1 END)) )* (CASE WHEN am.move_type in ('in_refund','out_refund') THEN -1 ELSE 1 END) AS total """ return select_str def _from(self): from_str = """FROM account_move_line aml JOIN account_move am ON am.id = aml.move_id JOIN account_account aa ON aa.id = aml.account_id JOIN account_journal aj ON aj.id = am.journal_id JOIN product_product pp ON pp.id = aml.product_id JOIN product_template pt ON pt.id = pp.product_tmpl_id LEFT JOIN account_tax at ON at.id = aml.tax_line_id LEFT JOIN account_account_tag_account_move_line_rel aat_aml_rel ON aat_aml_rel.account_move_line_id = aml.id LEFT JOIN account_account_tag aat ON aat.id = aat_aml_rel.account_account_tag_id LEFT JOIN account_tax_report_line_tags_rel tag_rep_ln ON aat.id = tag_rep_ln.account_account_tag_id LEFT JOIN account_move_line_account_tax_rel mt ON mt.account_move_line_id = aml.id LEFT JOIN uom_uom uom ON uom.id = aml.product_uom_id WHERE aa.internal_type = 'other' AND (aml.tax_line_id IS NOT NULL OR mt.account_tax_id IS NULL) AND am.state = 'posted' """ return from_str def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute("""CREATE OR REPLACE VIEW %s AS (%s %s)""" % ( self._table, self._select(), self._from()))
59.401786
6,653
16,526
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools class L10nInAccountInvoiceReport(models.Model): _name = "l10n_in.account.invoice.report" _description = "Account Invoice Statistics" _auto = False _order = 'date desc' account_move_id = fields.Many2one('account.move', string="Account Move") company_id = fields.Many2one('res.company', string="Company") date = fields.Date(string="Accounting Date") name = fields.Char(string="Invoice Number") partner_id = fields.Many2one('res.partner', string="Customer") is_reverse_charge = fields.Char("Reverse Charge") l10n_in_gst_treatment = fields.Selection([ ('regular', 'Registered Business - Regular'), ('composition', 'Registered Business - Composition'), ('unregistered', 'Unregistered Business'), ('consumer', 'Consumer'), ('overseas', 'Overseas'), ('special_economic_zone', 'Special Economic Zone'), ('deemed_export', 'Deemed Export'), ], string="GST Treatment") journal_id = fields.Many2one('account.journal', string="Journal") state = fields.Selection([('draft', 'Unposted'), ('posted', 'Posted')], string='Status') igst_amount = fields.Float(string="IGST Amount") cgst_amount = fields.Float(string="CGST Amount") sgst_amount = fields.Float(string="SGST Amount") cess_amount = fields.Float(string="Cess Amount") price_total = fields.Float(string='Total Without Tax') total = fields.Float(string="Invoice Total") reversed_entry_id = fields.Many2one('account.move', string="Refund Invoice", help="From where this Refund is created") shipping_bill_number = fields.Char(string="Shipping Bill Number") shipping_bill_date = fields.Date(string="Shipping Bill Date") shipping_port_code_id = fields.Many2one('l10n_in.port.code', string='Shipping port code') ecommerce_partner_id = fields.Many2one('res.partner', string="E-commerce") move_type = fields.Selection(selection=[ ('entry', 'Journal Entry'), ('out_invoice', 'Customer Invoice'), ('out_refund', 'Customer Credit Note'), ('in_invoice', 'Vendor Bill'), ('in_refund', 'Vendor Credit Note'), ('out_receipt', 'Sales Receipt'), ('in_receipt', 'Purchase Receipt')]) partner_vat = fields.Char(string="Customer GSTIN") ecommerce_vat = fields.Char(string="E-commerce GSTIN") tax_rate = fields.Float(string="Rate") place_of_supply = fields.Char(string="Place of Supply") is_pre_gst = fields.Char(string="Is Pre GST") is_ecommerce = fields.Char(string="Is E-commerce") b2cl_is_ecommerce = fields.Char(string="B2CL Is E-commerce") b2cs_is_ecommerce = fields.Char(string="B2CS Is E-commerce") supply_type = fields.Char(string="Supply Type") export_type = fields.Char(string="Export Type") # String from GSTR column. refund_export_type = fields.Char(string="UR Type") # String from GSTR column. b2b_type = fields.Char(string="B2B Invoice Type") refund_invoice_type = fields.Char(string="Document Type") gst_format_date = fields.Char(string="Formated Date") gst_format_refund_date = fields.Char(string="Formated Refund Date") gst_format_shipping_bill_date = fields.Char(string="Formated Shipping Bill Date") tax_id = fields.Many2one('account.tax', string="Tax") def _select(self): select_str = """ SELECT min(sub.id) as id, sub.move_id, sub.account_move_id, sub.name, sub.state, sub.partner_id, sub.date, sub.l10n_in_gst_treatment, sub.ecommerce_partner_id, sub.shipping_bill_number, sub.shipping_bill_date, sub.shipping_port_code_id, sub.total * sub.b2cs_refund_sign as total, sub.journal_id, sub.company_id, sub.move_type, sub.reversed_entry_id, sub.partner_vat, sub.ecommerce_vat, sub.tax_rate as tax_rate, (CASE WHEN count(sub.is_reverse_charge) > 0 THEN 'Y' ELSE 'N' END) AS is_reverse_charge, sub.place_of_supply, sub.is_pre_gst, sub.is_ecommerce, sub.b2cl_is_ecommerce, sub.b2cs_is_ecommerce, sub.supply_type, sub.export_type, sub.refund_export_type, sub.b2b_type, sub.refund_invoice_type, sub.gst_format_date, sub.gst_format_refund_date, sub.gst_format_shipping_bill_date, sum(sub.igst_amount) * sub.amount_sign * sub.b2cs_refund_sign AS igst_amount, sum(sub.cgst_amount) * sub.amount_sign * sub.b2cs_refund_sign AS cgst_amount, sum(sub.sgst_amount) * sub.amount_sign * sub.b2cs_refund_sign AS sgst_amount, avg(sub.cess_amount) * sub.amount_sign * sub.b2cs_refund_sign AS cess_amount, sum(sub.price_total) * sub.amount_sign * sub.b2cs_refund_sign AS price_total, sub.tax_id """ return select_str def _sub_select(self): sub_select_str = """ SELECT aml.id AS id, aml.move_id, aml.partner_id, am.id AS account_move_id, am.name, am.state, am.date, am.l10n_in_gst_treatment AS l10n_in_gst_treatment, am.l10n_in_reseller_partner_id AS ecommerce_partner_id, am.l10n_in_shipping_bill_number AS shipping_bill_number, am.l10n_in_shipping_bill_date AS shipping_bill_date, am.l10n_in_shipping_port_code_id AS shipping_port_code_id, ABS(am.amount_total_signed) AS total, am.journal_id, aj.company_id, am.move_type AS move_type, am.reversed_entry_id AS reversed_entry_id, am.l10n_in_gstin AS partner_vat, CASE WHEN rp.vat IS NULL THEN '' ELSE rp.vat END AS ecommerce_vat, (CASE WHEN at.l10n_in_reverse_charge = True THEN True ELSE NULL END) AS is_reverse_charge, (CASE WHEN ps.l10n_in_tin IS NOT NULL THEN concat(ps.l10n_in_tin,'-',ps.name) WHEN ps.id IS NULL and cps.l10n_in_tin IS NOT NULL THEN concat(cps.l10n_in_tin,'-',cps.name) ELSE '' END) AS place_of_supply, (CASE WHEN am.move_type in ('out_refund', 'in_refund') and refund_am.date <= to_date('2017-07-01', 'YYYY-MM-DD') THEN 'Y' ELSE 'N' END) as is_pre_gst, (CASE WHEN am.l10n_in_reseller_partner_id IS NOT NULL THEN 'Y' ELSE 'N' END) as is_ecommerce, (CASE WHEN am.l10n_in_reseller_partner_id IS NOT NULL THEN 'Y' ELSE 'N' END) as b2cl_is_ecommerce, (CASE WHEN am.l10n_in_reseller_partner_id IS NOT NULL THEN 'E' ELSE 'OE' END) as b2cs_is_ecommerce, (CASE WHEN am.l10n_in_state_id = cp.state_id or p.id IS NULL THEN 'Intra State' WHEN am.l10n_in_state_id != cp.state_id and p.id IS NOT NULL THEN 'Inter State' END) AS supply_type, (CASE WHEN am.l10n_in_gst_treatment in ('deemed_export', 'overseas') and am.amount_tax > 0.00 THEN 'EXPWP' WHEN am.l10n_in_gst_treatment in ('deemed_export', 'overseas') and am.amount_tax <= 0.00 THEN 'EXPWOP' ELSE '' END) AS export_type, (CASE WHEN am.l10n_in_gst_treatment in ('deemed_export', 'overseas') and am.amount_tax > 0.00 THEN 'EXPWP' WHEN am.l10n_in_gst_treatment in ('deemed_export', 'overseas') and am.amount_tax <= 0.00 THEN 'EXPWOP' ELSE 'B2CL' END) AS refund_export_type, (CASE WHEN am.l10n_in_gst_treatment = 'regular' THEN 'Regular' WHEN am.l10n_in_gst_treatment = 'deemed_export' THEN 'Deemed' WHEN am.l10n_in_gst_treatment = 'overseas' and am.amount_tax > 0.00 THEN 'Export with IGST' WHEN am.l10n_in_gst_treatment = 'special_economic_zone' and am.amount_tax > 0.00 THEN 'SEZ with IGST payment' WHEN am.l10n_in_gst_treatment = 'special_economic_zone' and am.amount_tax <= 0.00 THEN 'SEZ without IGST payment' END) AS b2b_type, (CASE WHEN am.move_type = 'out_refund' THEN 'C' WHEN am.move_type = 'in_refund' THEN 'D' ELSE '' END) as refund_invoice_type, (CASE WHEN am.date IS NOT NULL THEN TO_CHAR(am.date, 'DD-MON-YYYY') ELSE '' END) as gst_format_date, (CASE WHEN refund_am.date IS NOT NULL THEN TO_CHAR(refund_am.date, 'DD-MON-YYYY') ELSE '' END) as gst_format_refund_date, (CASE WHEN am.l10n_in_shipping_bill_date IS NOT NULL THEN TO_CHAR(am.l10n_in_shipping_bill_date, 'DD-MON-YYYY') ELSE '' END) as gst_format_shipping_bill_date, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_igst', 'tax_report_line_igst_rc')) THEN aml.balance ELSE 0 END AS igst_amount, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_cgst', 'tax_report_line_cgst_rc')) THEN aml.balance ELSE 0 END AS cgst_amount, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_sgst', 'tax_report_line_sgst_rc')) THEN aml.balance ELSE 0 END AS sgst_amount, (WITH account_tax_temp_table AS ( SELECT account_account_tag_id FROM account_tax_report_line_tags_rel WHERE account_tax_report_line_id IN (SELECT res_id FROM ir_model_data where module='l10n_in' AND name in ('tax_report_line_cess', 'tax_report_line_cess_rc')) ) SELECT sum(temp_aml.balance) from account_move_line temp_aml JOIN account_account_tag_account_move_line_rel aat_aml_rel_temp ON aat_aml_rel_temp.account_move_line_id = temp_aml.id JOIN account_account_tag aat_temp ON aat_temp.id = aat_aml_rel_temp.account_account_tag_id JOIN account_tax_temp_table tag_rep_ln_temp ON aat_temp.id = tag_rep_ln_temp.account_account_tag_id where temp_aml.move_id = aml.move_id and temp_aml.product_id = aml.product_id ) AS cess_amount, CASE WHEN tag_rep_ln.account_tax_report_line_id IN (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_sgst', 'tax_report_line_sgst_rc')) THEN NULL ELSE (CASE WHEN aml.tax_base_amount <> 0 THEN aml.tax_base_amount * (CASE WHEN aml.balance < 0 THEN -1 ELSE 1 END) ELSE NULL END) END AS price_total, (CASE WHEN (aj.type = 'sale' AND am.move_type != 'out_refund') or (aj.type = 'purchase' AND at.l10n_in_reverse_charge AND am.move_type != 'in_refund') THEN -1 ELSE 1 END) AS amount_sign, (CASE WHEN am.move_type in ('in_refund','out_refund') AND p.vat IS NULL AND am.l10n_in_gst_treatment != 'overseas' AND (ABS(am.amount_total_signed) <= 250000 OR (ps.id = cp.state_id OR p.id IS NULL)) THEN -1 ELSE 1 END) AS b2cs_refund_sign, (CASE WHEN atr.parent_tax IS NOT NULL THEN atr.parent_tax ELSE at.id END) AS tax_id, (CASE WHEN atr.parent_tax IS NOT NULL THEN parent_at.amount ELSE at.amount END) AS tax_rate """ return sub_select_str def _from(self): from_str = """ FROM account_move_line aml JOIN account_move am ON am.id = aml.move_id JOIN account_journal aj ON aj.id = am.journal_id JOIN res_company c ON c.id = aj.company_id LEFT JOIN account_tax at ON at.id = aml.tax_line_id JOIN account_account_tag_account_move_line_rel aat_aml_rel ON aat_aml_rel.account_move_line_id = aml.id JOIN account_account_tag aat ON aat.id = aat_aml_rel.account_account_tag_id JOIN account_tax_report_line_tags_rel tag_rep_ln ON aat.id = tag_rep_ln.account_account_tag_id LEFT JOIN res_partner cp ON cp.id = COALESCE(aj.l10n_in_gstin_partner_id, c.partner_id) LEFT JOIN res_country_state cps ON cps.id = cp.state_id LEFT JOIN account_move refund_am ON refund_am.id = am.reversed_entry_id LEFT JOIN res_partner p ON p.id = aml.partner_id LEFT JOIN res_country_state ps ON ps.id = am.l10n_in_state_id LEFT JOIN res_partner rp ON rp.id = am.l10n_in_reseller_partner_id LEFT JOIN account_tax_filiation_rel atr ON atr.child_tax = at.id LEFT JOIN account_tax parent_at ON parent_at.id = atr.parent_tax """ return from_str def _where(self): return """ WHERE am.state = 'posted' AND tag_rep_ln.account_tax_report_line_id in (SELECT res_id FROM ir_model_data WHERE module='l10n_in' AND name in ('tax_report_line_igst', 'tax_report_line_cgst', 'tax_report_line_sgst', 'tax_report_line_zero_rated', 'tax_report_line_igst_rc', 'tax_report_line_cgst_rc', 'tax_report_line_sgst_rc')) """ def _group_by(self): group_by_str = """ GROUP BY sub.move_id, sub.account_move_id, sub.name, sub.state, sub.partner_id, sub.date, sub.l10n_in_gst_treatment, sub.ecommerce_partner_id, sub.shipping_bill_number, sub.shipping_bill_date, sub.shipping_port_code_id, sub.total, sub.journal_id, sub.company_id, sub.move_type, sub.reversed_entry_id, sub.partner_vat, sub.ecommerce_vat, sub.place_of_supply, sub.is_pre_gst, sub.is_ecommerce, sub.b2cl_is_ecommerce, sub.b2cs_is_ecommerce, sub.supply_type, sub.export_type, sub.refund_export_type, sub.b2b_type, sub.refund_invoice_type, sub.gst_format_date, sub.gst_format_refund_date, sub.gst_format_shipping_bill_date, sub.amount_sign, sub.tax_id, sub.tax_rate, sub.b2cs_refund_sign """ return group_by_str def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute("""CREATE or REPLACE VIEW %s AS ( %s FROM ( %s %s %s ) AS sub %s)""" % (self._table, self._select(), self._sub_select(), self._from(), self._where(), self._group_by()))
50.078788
16,526
681
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'CRM Livechat', 'category': 'Sales/CRM', 'summary': 'Create lead from livechat conversation', 'data': [ 'data/utm_data.xml', ], 'depends': [ 'crm', 'im_livechat' ], 'description': 'Create new lead with using /lead command in the channel', 'auto_install': True, 'license': 'LGPL-3', 'assets': { 'mail.assets_discuss_public': [ 'crm_livechat/static/src/models/*/*.js', ], 'web.assets_backend': [ 'crm_livechat/static/src/models/*/*.js', ], }, }
26.192308
681
3,951
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.crm.tests.common import TestCrmCommon from odoo.addons.mail.tests.common import mail_new_test_user from odoo.tests.common import users class TestLivechatLead(TestCrmCommon): @classmethod def setUpClass(cls): super(TestLivechatLead, cls).setUpClass() cls.user_anonymous = mail_new_test_user( cls.env, login='user_anonymous', name='Anonymous Website', email=False, company_id=cls.company_main.id, notification_type='inbox', groups='base.group_public', ) cls.user_portal = mail_new_test_user( cls.env, login='user_portal', name='Paulette Portal', email='user_portal@test.example.com', company_id=cls.company_main.id, notification_type='inbox', groups='base.group_portal', ) @users('user_sales_leads') def test_crm_lead_creation_guest(self): """ Test customer set on lead: not if public, guest if not public """ # public: should not be set as customer channel = self.env['mail.channel'].create({ 'name': 'Chat with Visitor', 'channel_partner_ids': [(4, self.user_anonymous.partner_id.id)] }) lead = channel._convert_visitor_to_lead(self.env.user.partner_id, '/lead TestLead command') self.assertEqual( channel.channel_partner_ids, self.user_sales_leads.partner_id | self.user_anonymous.partner_id ) self.assertEqual(lead.name, 'TestLead command') self.assertEqual(lead.partner_id, self.env['res.partner']) # public user: should not be set as customer # 'base.public_user' is archived by default self.assertFalse(self.env.ref('base.public_user').active) channel = self.env['mail.channel'].create({ 'name': 'Chat with Visitor', 'channel_partner_ids': [(4, self.env.ref('base.public_partner').id)] }) lead = channel._convert_visitor_to_lead(self.env.user.partner_id, '/lead TestLead command') self.assertEqual( channel.channel_last_seen_partner_ids.partner_id, self.user_sales_leads.partner_id | self.env.ref('base.public_partner') ) self.assertEqual(lead.name, 'TestLead command') self.assertEqual(lead.partner_id, self.env['res.partner']) # public + someone else: no customer (as he was anonymous) channel.write({ 'channel_partner_ids': [(4, self.user_sales_manager.partner_id.id)] }) lead = channel._convert_visitor_to_lead(self.env.user.partner_id, '/lead TestLead command') self.assertEqual(lead.partner_id, self.env['res.partner']) # portal: should be set as customer channel = self.env['mail.channel'].create({ 'name': 'Chat with Visitor', 'channel_partner_ids': [(4, self.user_portal.partner_id.id)] }) lead = channel._convert_visitor_to_lead(self.env.user.partner_id, '/lead TestLead command') self.assertEqual( channel.channel_partner_ids, self.user_sales_leads.partner_id | self.user_portal.partner_id ) self.assertEqual(lead.partner_id, self.user_portal.partner_id) # another operator invited: internal user should not be customer if portal is present channel.write({ 'channel_partner_ids': [(4, self.user_sales_manager.partner_id.id)] }) lead = channel._convert_visitor_to_lead(self.env.user.partner_id, '/lead TestLead command') self.assertEqual( channel.channel_partner_ids, self.user_sales_leads.partner_id | self.user_portal.partner_id | self.user_sales_manager.partner_id ) self.assertEqual(lead.partner_id, self.user_portal.partner_id)
42.031915
3,951
2,366
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.tools import html2plaintext, html_escape class MailChannel(models.Model): _inherit = 'mail.channel' def execute_command_lead(self, **kwargs): partner = self.env.user.partner_id key = kwargs['body'] if key.strip() == '/lead': msg = _('Create a new lead (/lead lead title)') else: lead = self._convert_visitor_to_lead(partner, key) msg = _('Created a new lead: <a href="#" data-oe-id="%s" data-oe-model="crm.lead">%s</a>') % (lead.id, html_escape(lead.name)) self._send_transient_message(partner, msg) def _convert_visitor_to_lead(self, partner, key): """ Create a lead from channel /lead command :param partner: internal user partner (operator) that created the lead; :param key: operator input in chat ('/lead Lead about Product') """ description = ''.join( '%s: %s<br/>' % (message.author_id.name or self.anonymous_name, html2plaintext(message.body)) for message in self.message_ids.sorted('id') ) # converting message body back to plaintext for correct data formating in description # if public user is part of the chat: consider lead to be linked to an # anonymous user whatever the participants. Otherwise keep only share # partners (no user or portal user) to link to the lead. customers = self.env['res.partner'] for customer in self.with_context(active_test=False).channel_partner_ids.filtered(lambda p: p != partner and p.partner_share): if customer.user_ids and all(user._is_public() for user in customer.user_ids): customers = self.env['res.partner'] break else: customers |= customer utm_source = self.env.ref('crm_livechat.utm_source_livechat', raise_if_not_found=False) return self.env['crm.lead'].create({ 'name': html2plaintext(key[5:]), 'partner_id': customers[0].id if customers else False, 'user_id': False, 'team_id': False, 'description': description, 'referred': partner.name, 'source_id': utm_source and utm_source.id, })
47.32
2,366
1,209
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Skills Management', 'category': 'Human Resources/Employees', 'sequence': 270, 'version': '1.0', 'summary': 'Manage skills, knowledge and resumé of your employees', 'description': """ Skills and Resumé for HR ======================== This module introduces skills and resumé management for employees. """, 'depends': ['hr'], 'data': [ 'security/ir.model.access.csv', 'security/hr_skills_security.xml', 'views/hr_views.xml', 'data/hr_resume_data.xml', ], 'demo': [ 'data/hr_resume_demo.xml', 'data/hr.employee.skill.csv', 'data/hr.resume.line.csv', ], 'installable': True, 'application': True, 'assets': { 'web.assets_backend': [ 'hr_skills/static/src/css/hr_skills.scss', 'hr_skills/static/src/js/resume_widget.js', ], 'web.qunit_suite_tests': [ 'hr_skills/static/tests/**/*', ], 'web.assets_qweb': [ 'hr_skills/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
27.409091
1,206
661
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 User(models.Model): _inherit = ['res.users'] resume_line_ids = fields.One2many(related='employee_id.resume_line_ids', readonly=False) employee_skill_ids = fields.One2many(related='employee_id.employee_skill_ids', readonly=False) @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + ['resume_line_ids', 'employee_skill_ids'] @property def SELF_WRITEABLE_FIELDS(self): return super().SELF_WRITEABLE_FIELDS + ['resume_line_ids', 'employee_skill_ids']
36.722222
661
2,385
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 Employee(models.Model): _inherit = 'hr.employee' resume_line_ids = fields.One2many('hr.resume.line', 'employee_id', string="Resumé lines") employee_skill_ids = fields.One2many('hr.employee.skill', 'employee_id', string="Skills") @api.model_create_multi def create(self, vals_list): res = super(Employee, self).create(vals_list) resume_lines_values = [] for employee in res: line_type = self.env.ref('hr_skills.resume_type_experience', raise_if_not_found=False) resume_lines_values.append({ 'employee_id': employee.id, 'name': employee.company_id.name or '', 'date_start': employee.create_date.date(), 'description': employee.job_title or '', 'line_type_id': line_type and line_type.id, }) self.env['hr.resume.line'].create(resume_lines_values) return res class EmployeePublic(models.Model): _inherit = 'hr.employee.public' resume_line_ids = fields.One2many('hr.resume.line', 'employee_id', string="Resumé lines") employee_skill_ids = fields.One2many('hr.employee.skill', 'employee_id', string="Skills") class ResumeLine(models.Model): _name = 'hr.resume.line' _description = "Resumé line of an employee" _order = "line_type_id, date_end desc, date_start desc" employee_id = fields.Many2one('hr.employee', required=True, ondelete='cascade') name = fields.Char(required=True) date_start = fields.Date(required=True) date_end = fields.Date() description = fields.Text(string="Description") line_type_id = fields.Many2one('hr.resume.line.type', string="Type") # Used to apply specific template on a line display_type = fields.Selection([('classic', 'Classic')], string="Display Type", default='classic') _sql_constraints = [ ('date_check', "CHECK ((date_start <= date_end OR date_end = NULL))", "The start date must be anterior to the end date."), ] class ResumeLineType(models.Model): _name = 'hr.resume.line.type' _description = "Type of a resumé line" _order = "sequence" name = fields.Char(required=True) sequence = fields.Integer('Sequence', default=10)
37.793651
2,381
2,430
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class Skill(models.Model): _name = 'hr.skill' _description = "Skill" name = fields.Char(required=True) skill_type_id = fields.Many2one('hr.skill.type', ondelete='cascade') class EmployeeSkill(models.Model): _name = 'hr.employee.skill' _description = "Skill level for an employee" _rec_name = 'skill_id' _order = "skill_level_id" employee_id = fields.Many2one('hr.employee', required=True, ondelete='cascade') skill_id = fields.Many2one('hr.skill', required=True) skill_level_id = fields.Many2one('hr.skill.level', required=True) skill_type_id = fields.Many2one('hr.skill.type', required=True) level_progress = fields.Integer(related='skill_level_id.level_progress') _sql_constraints = [ ('_unique_skill', 'unique (employee_id, skill_id)', "Two levels for the same skill is not allowed"), ] @api.constrains('skill_id', 'skill_type_id') def _check_skill_type(self): for record in self: if record.skill_id not in record.skill_type_id.skill_ids: raise ValidationError(_("The skill %(name)s and skill type %(type)s doesn't match", name=record.skill_id.name, type=record.skill_type_id.name)) @api.constrains('skill_type_id', 'skill_level_id') def _check_skill_level(self): for record in self: if record.skill_level_id not in record.skill_type_id.skill_level_ids: raise ValidationError(_("The skill level %(level)s is not valid for skill type: %(type)s", level=record.skill_level_id.name, type=record.skill_type_id.name)) class SkillLevel(models.Model): _name = 'hr.skill.level' _description = "Skill Level" _order = "level_progress desc" skill_type_id = fields.Many2one('hr.skill.type', ondelete='cascade') name = fields.Char(required=True) level_progress = fields.Integer(string="Progress", help="Progress from zero knowledge (0%) to fully mastered (100%).") class SkillType(models.Model): _name = 'hr.skill.type' _description = "Skill Type" name = fields.Char(required=True) skill_ids = fields.One2many('hr.skill', 'skill_type_id', string="Skills") skill_level_ids = fields.One2many('hr.skill.level', 'skill_type_id', string="Levels")
39.836066
2,430
1,254
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Employee Contracts', 'version': '1.0', 'category': 'Human Resources/Contracts', 'sequence': 335, 'description': """ Add all information on the employee form to manage contracts. ============================================================= * Contract * Place of Birth, * Medical Examination Date * Company Vehicle You can assign several contracts per employee. """, 'website': 'https://www.odoo.com/app/employees', 'depends': ['hr'], 'data': [ 'security/security.xml', 'security/ir.model.access.csv', 'data/hr_contract_data.xml', 'report/hr_contract_history_report_views.xml', 'views/hr_contract_views.xml', 'views/hr_employee_views.xml', 'views/hr_employee_public_views.xml', 'views/resource_calendar_views.xml', 'wizard/hr_departure_wizard_views.xml', ], 'demo': ['data/hr_contract_demo.xml'], 'installable': True, 'auto_install': False, 'application': True, 'assets': { 'web.assets_backend': [ 'hr_contract/static/src/**/*', ], }, 'license': 'LGPL-3', }
29.162791
1,254
3,267
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.fields import Datetime, Date from odoo.addons.hr_contract.tests.common import TestContractCommon class TestContractCalendars(TestContractCommon): @classmethod def setUpClass(cls): super(TestContractCalendars, cls).setUpClass() cls.calendar_richard = cls.env['resource.calendar'].create({'name': 'Calendar of Richard'}) cls.employee.resource_calendar_id = cls.calendar_richard cls.calendar_35h = cls.env['resource.calendar'].create({'name': '35h calendar'}) cls.calendar_35h._onchange_hours_per_day() # update hours/day cls.contract_cdd = cls.env['hr.contract'].create({ 'date_end': Date.to_date('2015-11-15'), 'date_start': Date.to_date('2015-01-01'), 'name': 'First CDD Contract for Richard', 'resource_calendar_id': cls.calendar_35h.id, 'wage': 5000.0, 'employee_id': cls.employee.id, 'state': 'close', }) def test_contract_state_incoming_to_open(self): # Employee's calendar should change self.assertEqual(self.employee.resource_calendar_id, self.calendar_richard) self.contract_cdd.state = 'open' self.assertEqual(self.employee.resource_calendar_id, self.contract_cdd.resource_calendar_id, "The employee should have the calendar of its contract.") def test_contract_transfer_leaves(self): def create_calendar_leave(start, end, resource=None): return self.env['resource.calendar.leaves'].create({ 'name': 'leave name', 'date_from': start, 'date_to': end, 'resource_id': resource.id if resource else None, 'calendar_id': self.employee.resource_calendar_id.id, 'time_type': 'leave', }) start = Datetime.to_datetime('2015-11-17 07:00:00') end = Datetime.to_datetime('2015-11-20 18:00:00') leave1 = create_calendar_leave(start, end, resource=self.employee.resource_id) start = Datetime.to_datetime('2015-11-25 07:00:00') end = Datetime.to_datetime('2015-11-28 18:00:00') leave2 = create_calendar_leave(start, end, resource=self.employee.resource_id) # global leave start = Datetime.to_datetime('2015-11-25 07:00:00') end = Datetime.to_datetime('2015-11-28 18:00:00') leave3 = create_calendar_leave(start, end) self.calendar_richard.transfer_leaves_to(self.calendar_35h, resources=self.employee.resource_id, from_date=Date.to_date('2015-11-21')) self.assertEqual(leave1.calendar_id, self.calendar_richard, "It should stay in Richard's calendar") self.assertEqual(leave3.calendar_id, self.calendar_richard, "Global leave should stay in original calendar") self.assertEqual(leave2.calendar_id, self.calendar_35h, "It should be transfered to the other calendar") # Transfer global leaves self.calendar_richard.transfer_leaves_to(self.calendar_35h, resources=None, from_date=Date.to_date('2015-11-21')) self.assertEqual(leave3.calendar_id, self.calendar_35h, "Global leave should be transfered")
47.347826
3,267
4,617
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, date from odoo.exceptions import ValidationError from odoo.addons.hr_contract.tests.common import TestContractCommon class TestHrContracts(TestContractCommon): @classmethod def setUpClass(cls): super(TestHrContracts, cls).setUpClass() cls.contracts = cls.env['hr.contract'].with_context(tracking_disable=True) def create_contract(self, state, kanban_state, start, end=None): return self.env['hr.contract'].create({ 'name': 'Contract', 'employee_id': self.employee.id, 'state': state, 'kanban_state': kanban_state, 'wage': 1, 'date_start': start, 'date_end': end, }) def test_incoming_overlapping_contract(self): start = datetime.strptime('2015-11-01', '%Y-%m-%d').date() end = datetime.strptime('2015-11-30', '%Y-%m-%d').date() self.create_contract('open', 'normal', start, end) # Incoming contract with self.assertRaises(ValidationError, msg="It should not create two contract in state open or incoming"): start = datetime.strptime('2015-11-15', '%Y-%m-%d').date() end = datetime.strptime('2015-12-30', '%Y-%m-%d').date() self.create_contract('draft', 'done', start, end) def test_pending_overlapping_contract(self): start = datetime.strptime('2015-11-01', '%Y-%m-%d').date() end = datetime.strptime('2015-11-30', '%Y-%m-%d').date() self.create_contract('open', 'normal', start, end) # Pending contract with self.assertRaises(ValidationError, msg="It should not create two contract in state open or pending"): start = datetime.strptime('2015-11-15', '%Y-%m-%d').date() end = datetime.strptime('2015-12-30', '%Y-%m-%d').date() self.create_contract('open', 'blocked', start, end) # Draft contract -> should not raise start = datetime.strptime('2015-11-15', '%Y-%m-%d').date() end = datetime.strptime('2015-12-30', '%Y-%m-%d').date() self.create_contract('draft', 'normal', start, end) def test_draft_overlapping_contract(self): start = datetime.strptime('2015-11-01', '%Y-%m-%d').date() end = datetime.strptime('2015-11-30', '%Y-%m-%d').date() self.create_contract('open', 'normal', start, end) # Draft contract -> should not raise even if overlapping start = datetime.strptime('2015-11-15', '%Y-%m-%d').date() end = datetime.strptime('2015-12-30', '%Y-%m-%d').date() self.create_contract('draft', 'normal', start, end) def test_overlapping_contract_no_end(self): # No end date self.create_contract('open', 'normal', datetime.strptime('2015-11-01', '%Y-%m-%d').date()) with self.assertRaises(ValidationError): start = datetime.strptime('2015-11-15', '%Y-%m-%d').date() end = datetime.strptime('2015-12-30', '%Y-%m-%d').date() self.create_contract('draft', 'done', start, end) def test_overlapping_contract_no_end2(self): start = datetime.strptime('2015-11-01', '%Y-%m-%d').date() end = datetime.strptime('2015-12-30', '%Y-%m-%d').date() self.create_contract('open', 'normal', start, end) with self.assertRaises(ValidationError): # No end self.create_contract('draft', 'done', datetime.strptime('2015-01-01', '%Y-%m-%d').date()) def test_set_employee_contract_create(self): contract = self.create_contract('open', 'normal', date(2018, 1, 1), date(2018, 1, 2)) self.assertEqual(self.employee.contract_id, contract) def test_set_employee_contract_write(self): contract = self.create_contract('draft', 'normal', date(2018, 1, 1), date(2018, 1, 2)) contract.state = 'open' self.assertEqual(self.employee.contract_id, contract) def test_first_contract_date(self): self.create_contract('open', 'normal', date(2018, 1, 1), date(2018, 1, 31)) self.assertEqual(self.employee.first_contract_date, date(2018, 1, 1)) # New contract, no gap self.create_contract('open', 'normal', date(2017, 1, 1), date(2017, 12, 31)) self.assertEqual(self.employee.first_contract_date, date(2017, 1, 1)) # New contract, with gap self.create_contract('open', 'normal', date(2016, 1, 1), date(2016, 1, 31)) self.assertEqual(self.employee.first_contract_date, date(2017, 1, 1))
44.825243
4,617
467
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestContractCommon(TransactionCase): @classmethod def setUpClass(cls): super(TestContractCommon, cls).setUpClass() cls.employee = cls.env['hr.employee'].create({ 'name': 'Richard', 'gender': 'male', 'country_id': cls.env.ref('base.be').id, })
27.470588
467
2,930
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, datetime from dateutil.relativedelta import relativedelta from odoo.addons.hr_contract.tests.common import TestContractCommon class TestHrContracts(TestContractCommon): @classmethod def setUpClass(cls): super(TestHrContracts, cls).setUpClass() cls.contracts = cls.env['hr.contract'].with_context(tracking_disable=True) cls.test_contract = dict(name='Test', wage=1, employee_id=cls.employee.id, state='open') def test_employee_contractwarning(self): self.assertEqual(self.employee.contract_warning, True) def apply_cron(self): self.env.ref('hr_contract.ir_cron_data_contract_update_state').method_direct_trigger() def test_contract_enddate(self): self.test_contract.update(dict(date_end=datetime.now() + relativedelta(days=100))) self.contract = self.contracts.create(self.test_contract) self.apply_cron() self.assertEqual(self.contract.state, 'open') self.assertEqual(self.contract.kanban_state, 'normal') self.assertEqual(self.employee.contract_warning, False) self.test_contract.update(dict(date_end=datetime.now() + relativedelta(days=5))) self.contract.write(self.test_contract) self.apply_cron() self.assertEqual(self.contract.state, 'open') self.assertEqual(self.contract.kanban_state, 'blocked') self.test_contract.update({ 'date_start': datetime.now() + relativedelta(days=-50), 'date_end': datetime.now() + relativedelta(days=-1), 'state': 'open', 'kanban_state': 'blocked', }) self.contract.write(self.test_contract) self.apply_cron() self.assertEqual(self.contract.state, 'close') def test_contract_pending_visa_expire(self): self.employee.visa_expire = date.today() + relativedelta(days=30) self.test_contract.update(dict(date_end=False)) self.contract = self.contracts.create(self.test_contract) self.apply_cron() self.assertEqual(self.contract.state, 'open') self.assertEqual(self.contract.kanban_state, 'blocked') self.employee.visa_expire = date.today() + relativedelta(days=-5) self.test_contract.update({ 'date_start': datetime.now() + relativedelta(days=-50), 'state': 'open', 'kanban_state': 'blocked', }) self.contract.write(self.test_contract) self.apply_cron() self.assertEqual(self.contract.state, 'close') def test_contract_start_date(self): self.test_contract.update(dict(date_start=datetime.now(), state='draft', kanban_state='done')) self.contract = self.contracts.create(self.test_contract) self.apply_cron() self.assertEqual(self.contract.state, 'open')
42.463768
2,930
1,161
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ from odoo.exceptions import UserError class HrDepartureWizard(models.TransientModel): _inherit = 'hr.departure.wizard' set_date_end = fields.Boolean(string="Set Contract End Date", default=True, help="Set the end date on the current contract.") def action_register_departure(self): """If set_date_end is checked, set the departure date as the end date to current running contract, and cancel all draft contracts""" current_contract = self.employee_id.contract_id if current_contract and current_contract.date_start > self.departure_date: raise UserError(_("Departure date can't be earlier than the start date of current contract.")) super(HrDepartureWizard, self).action_register_departure() if self.set_date_end: self.employee_id.contract_ids.filtered(lambda c: c.state == 'draft').write({'state': 'cancel'}) if current_contract: self.employee_id.contract_id.write({'date_end': self.departure_date})
46.44
1,161
740
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 ContractType(models.Model): _name = 'hr.contract.type' _description = 'Contract Type' name = fields.Char(required=True) class HrPayrollStructureType(models.Model): _name = 'hr.payroll.structure.type' _description = 'Salary Structure Type' name = fields.Char('Salary Structure Type') default_resource_calendar_id = fields.Many2one( 'resource.calendar', 'Default Working Hours', default=lambda self: self.env.company.resource_calendar_id) country_id = fields.Many2one('res.country', string='Country', default=lambda self: self.env.company.country_id)
35.238095
740
316
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class HrEmployeePublic(models.Model): _inherit = "hr.employee.public" first_contract_date = fields.Date(related='employee_id.first_contract_date', groups="base.group_user")
31.6
316
1,920
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from odoo import fields, models from odoo.osv.expression import AND class ResourceCalendar(models.Model): _inherit = 'resource.calendar' contracts_count = fields.Integer("# Contracts using it", compute='_compute_contracts_count', groups="hr_contract.group_hr_contract_manager") def transfer_leaves_to(self, other_calendar, resources=None, from_date=None): """ Transfer some resource.calendar.leaves from 'self' to another calendar 'other_calendar'. Transfered leaves linked to `resources` (or all if `resources` is None) and starting after 'from_date' (or today if None). """ from_date = from_date or fields.Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) domain = [ ('calendar_id', 'in', self.ids), ('date_from', '>=', from_date), ] domain = AND([domain, [('resource_id', 'in', resources.ids)]]) if resources else domain self.env['resource.calendar.leaves'].search(domain).write({ 'calendar_id': other_calendar.id, }) def _compute_contracts_count(self): count_data = self.env['hr.contract'].read_group( [('resource_calendar_id', 'in', self.ids)], ['resource_calendar_id'], ['resource_calendar_id']) mapped_counts = {cd['resource_calendar_id'][0]: cd['resource_calendar_id_count'] for cd in count_data} for calendar in self: calendar.contracts_count = mapped_counts.get(calendar.id, 0) def action_open_contracts(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("hr_contract.action_hr_contract") action.update({'domain': [('resource_calendar_id', '=', self.id)]}) return action
42.666667
1,920
5,210
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date from odoo import api, fields, models from odoo.osv import expression class Employee(models.Model): _inherit = "hr.employee" vehicle = fields.Char(string='Company Vehicle', groups="hr.group_hr_user") contract_ids = fields.One2many('hr.contract', 'employee_id', string='Employee Contracts') contract_id = fields.Many2one( 'hr.contract', string='Current Contract', groups="hr.group_hr_user", domain="[('company_id', '=', company_id), ('employee_id', '=', id)]", help='Current contract of the employee') calendar_mismatch = fields.Boolean(related='contract_id.calendar_mismatch') contracts_count = fields.Integer(compute='_compute_contracts_count', string='Contract Count') contract_warning = fields.Boolean(string='Contract Warning', store=True, compute='_compute_contract_warning', groups="hr.group_hr_user") first_contract_date = fields.Date(compute='_compute_first_contract_date', groups="hr.group_hr_user", store=True) def _get_first_contracts(self): self.ensure_one() return self.sudo().contract_ids.filtered(lambda c: c.state != 'cancel') def _get_first_contract_date(self, no_gap=True): self.ensure_one() def remove_gap(contracts): # We do not consider a gap of more than 4 days to be a same occupation # contracts are considered to be ordered correctly if not contracts: return self.env['hr.contract'] if len(contracts) == 1: return contracts current_contract = contracts[0] older_contracts = contracts[1:] current_date = current_contract.date_start for i, other_contract in enumerate(older_contracts): # Consider current_contract.date_end being false as an error and cut the loop gap = (current_date - (other_contract.date_end or date(2100, 1, 1))).days current_date = other_contract.date_start if gap >= 4: return older_contracts[0:i] + current_contract return older_contracts + current_contract contracts = self._get_first_contracts().sorted('date_start', reverse=True) if no_gap: contracts = remove_gap(contracts) return min(contracts.mapped('date_start')) if contracts else False @api.depends('contract_ids.state', 'contract_ids.date_start') def _compute_first_contract_date(self): for employee in self: employee.first_contract_date = employee._get_first_contract_date() @api.depends('contract_id', 'contract_id.state', 'contract_id.kanban_state') def _compute_contract_warning(self): for employee in self: employee.contract_warning = not employee.contract_id or employee.contract_id.kanban_state == 'blocked' or employee.contract_id.state != 'open' def _compute_contracts_count(self): # read_group as sudo, since contract count is displayed on form view contract_data = self.env['hr.contract'].sudo().read_group([('employee_id', 'in', self.ids)], ['employee_id'], ['employee_id']) result = dict((data['employee_id'][0], data['employee_id_count']) for data in contract_data) for employee in self: employee.contracts_count = result.get(employee.id, 0) def _get_contracts(self, date_from, date_to, states=['open'], kanban_state=False): """ Returns the contracts of the employee between date_from and date_to """ state_domain = [('state', 'in', states)] if kanban_state: state_domain = expression.AND([state_domain, [('kanban_state', 'in', kanban_state)]]) return self.env['hr.contract'].search( expression.AND([[('employee_id', 'in', self.ids)], state_domain, [('date_start', '<=', date_to), '|', ('date_end', '=', False), ('date_end', '>=', date_from)]])) def _get_incoming_contracts(self, date_from, date_to): return self._get_contracts(date_from, date_to, states=['draft'], kanban_state=['done']) @api.model def _get_all_contracts(self, date_from, date_to, states=['open']): """ Returns the contracts of all employees between date_from and date_to """ return self.search(['|', ('active', '=', True), ('active', '=', False)])._get_contracts(date_from, date_to, states=states) def write(self, vals): res = super(Employee, self).write(vals) if vals.get('contract_id'): for employee in self: employee.resource_calendar_id.transfer_leaves_to(employee.contract_id.resource_calendar_id, employee.resource_id) employee.resource_calendar_id = employee.contract_id.resource_calendar_id return res def action_open_contract_history(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id('hr_contract.hr_contract_history_view_form_action') action['res_id'] = self.id return action
49.150943
5,210
460
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 User(models.Model): _inherit = ['res.users'] vehicle = fields.Char(related="employee_id.vehicle") bank_account_id = fields.Many2one(related="employee_id.bank_account_id") @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + ['vehicle', 'bank_account_id']
30.666667
460
13,706
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import threading from datetime import date from dateutil.relativedelta import relativedelta from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.osv import expression import logging _logger = logging.getLogger(__name__) class Contract(models.Model): _name = 'hr.contract' _description = 'Contract' _inherit = ['mail.thread', 'mail.activity.mixin'] name = fields.Char('Contract Reference', required=True) active = fields.Boolean(default=True) structure_type_id = fields.Many2one('hr.payroll.structure.type', string="Salary Structure Type") employee_id = fields.Many2one('hr.employee', string='Employee', tracking=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") department_id = fields.Many2one('hr.department', compute='_compute_employee_contract', store=True, readonly=False, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", string="Department") job_id = fields.Many2one('hr.job', compute='_compute_employee_contract', store=True, readonly=False, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", string='Job Position') date_start = fields.Date('Start Date', required=True, default=fields.Date.today, tracking=True, help="Start date of the contract.", index=True) date_end = fields.Date('End Date', tracking=True, help="End date of the contract (if it's a fixed-term contract).") trial_date_end = fields.Date('End of Trial Period', help="End date of the trial period (if there is one).") resource_calendar_id = fields.Many2one( 'resource.calendar', 'Working Schedule', compute='_compute_employee_contract', store=True, readonly=False, default=lambda self: self.env.company.resource_calendar_id.id, copy=False, index=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") wage = fields.Monetary('Wage', required=True, tracking=True, help="Employee's monthly gross wage.") contract_wage = fields.Monetary('Contract Wage', compute='_compute_contract_wage') notes = fields.Html('Notes') state = fields.Selection([ ('draft', 'New'), ('open', 'Running'), ('close', 'Expired'), ('cancel', 'Cancelled') ], string='Status', group_expand='_expand_states', copy=False, tracking=True, help='Status of the contract', default='draft') company_id = fields.Many2one('res.company', compute='_compute_employee_contract', store=True, readonly=False, default=lambda self: self.env.company, required=True) company_country_id = fields.Many2one('res.country', string="Company country", related='company_id.country_id', readonly=True) country_code = fields.Char(related='company_country_id.code', readonly=True) contract_type_id = fields.Many2one('hr.contract.type', "Contract Type") """ kanban_state: * draft + green = "Incoming" state (will be set as Open once the contract has started) * open + red = "Pending" state (will be set as Closed once the contract has ended) * red = Shows a warning on the employees kanban view """ kanban_state = fields.Selection([ ('normal', 'Grey'), ('done', 'Green'), ('blocked', 'Red') ], string='Kanban State', default='normal', tracking=True, copy=False) currency_id = fields.Many2one(string="Currency", related='company_id.currency_id', readonly=True) permit_no = fields.Char('Work Permit No', related="employee_id.permit_no", readonly=False) visa_no = fields.Char('Visa No', related="employee_id.visa_no", readonly=False) visa_expire = fields.Date('Visa Expire Date', related="employee_id.visa_expire", readonly=False) hr_responsible_id = fields.Many2one('res.users', 'HR Responsible', tracking=True, help='Person responsible for validating the employee\'s contracts.') calendar_mismatch = fields.Boolean(compute='_compute_calendar_mismatch') first_contract_date = fields.Date(related='employee_id.first_contract_date') @api.depends('employee_id.resource_calendar_id', 'resource_calendar_id') def _compute_calendar_mismatch(self): for contract in self: contract.calendar_mismatch = contract.resource_calendar_id != contract.employee_id.resource_calendar_id def _expand_states(self, states, domain, order): return [key for key, val in type(self).state.selection] @api.depends('employee_id') def _compute_employee_contract(self): for contract in self.filtered('employee_id'): contract.job_id = contract.employee_id.job_id contract.department_id = contract.employee_id.department_id contract.resource_calendar_id = contract.employee_id.resource_calendar_id contract.company_id = contract.employee_id.company_id @api.onchange('company_id') def _onchange_company_id(self): if self.company_id: structure_types = self.env['hr.payroll.structure.type'].search([ '|', ('country_id', '=', self.company_id.country_id.id), ('country_id', '=', False)]) if structure_types: self.structure_type_id = structure_types[0] elif self.structure_type_id not in structure_types: self.structure_type_id = False @api.onchange('structure_type_id') def _onchange_structure_type_id(self): if self.structure_type_id.default_resource_calendar_id: self.resource_calendar_id = self.structure_type_id.default_resource_calendar_id @api.constrains('employee_id', 'state', 'kanban_state', 'date_start', 'date_end') def _check_current_contract(self): """ Two contracts in state [incoming | open | close] cannot overlap """ for contract in self.filtered(lambda c: (c.state not in ['draft', 'cancel'] or c.state == 'draft' and c.kanban_state == 'done') and c.employee_id): domain = [ ('id', '!=', contract.id), ('employee_id', '=', contract.employee_id.id), ('company_id', '=', contract.company_id.id), '|', ('state', 'in', ['open', 'close']), '&', ('state', '=', 'draft'), ('kanban_state', '=', 'done') # replaces incoming ] if not contract.date_end: start_domain = [] end_domain = ['|', ('date_end', '>=', contract.date_start), ('date_end', '=', False)] else: start_domain = [('date_start', '<=', contract.date_end)] end_domain = ['|', ('date_end', '>', contract.date_start), ('date_end', '=', False)] domain = expression.AND([domain, start_domain, end_domain]) if self.search_count(domain): raise ValidationError( _( 'An employee can only have one contract at the same time. (Excluding Draft and Cancelled contracts).\n\nEmployee: %(employee_name)s', employee_name=contract.employee_id.name ) ) @api.constrains('date_start', 'date_end') def _check_dates(self): for contract in self: if contract.date_end and contract.date_start > contract.date_end: raise ValidationError(_( 'Contract %(contract)s: start date (%(start)s) must be earlier than contract end date (%(end)s).', contract=contract.name, start=contract.date_start, end=contract.date_end, )) @api.model def update_state(self): from_cron = 'from_cron' in self.env.context contracts = self.search([ ('state', '=', 'open'), ('kanban_state', '!=', 'blocked'), '|', '&', ('date_end', '<=', fields.Date.to_string(date.today() + relativedelta(days=7))), ('date_end', '>=', fields.Date.to_string(date.today() + relativedelta(days=1))), '&', ('visa_expire', '<=', fields.Date.to_string(date.today() + relativedelta(days=60))), ('visa_expire', '>=', fields.Date.to_string(date.today() + relativedelta(days=1))), ]) for contract in contracts: contract.activity_schedule( 'mail.mail_activity_data_todo', contract.date_end, _("The contract of %s is about to expire.", contract.employee_id.name), user_id=contract.hr_responsible_id.id or self.env.uid) if contracts: contracts._safe_write_for_cron({'kanban_state': 'blocked'}, from_cron) contracts_to_close = self.search([ ('state', '=', 'open'), '|', ('date_end', '<=', fields.Date.to_string(date.today())), ('visa_expire', '<=', fields.Date.to_string(date.today())), ]) if contracts_to_close: contracts_to_close._safe_write_for_cron({'state': 'close'}, from_cron) contracts_to_open = self.search([('state', '=', 'draft'), ('kanban_state', '=', 'done'), ('date_start', '<=', fields.Date.to_string(date.today())),]) if contracts_to_open: contracts_to_open._safe_write_for_cron({'state': 'open'}, from_cron) contract_ids = self.search([('date_end', '=', False), ('state', '=', 'close'), ('employee_id', '!=', False)]) # Ensure all closed contract followed by a new contract have a end date. # If closed contract has no closed date, the work entries will be generated for an unlimited period. for contract in contract_ids: next_contract = self.search([ ('employee_id', '=', contract.employee_id.id), ('state', 'not in', ['cancel', 'new']), ('date_start', '>', contract.date_start) ], order="date_start asc", limit=1) if next_contract: contract._safe_write_for_cron({'date_end': next_contract.date_start - relativedelta(days=1)}, from_cron) continue next_contract = self.search([ ('employee_id', '=', contract.employee_id.id), ('date_start', '>', contract.date_start) ], order="date_start asc", limit=1) if next_contract: contract._safe_write_for_cron({'date_end': next_contract.date_start - relativedelta(days=1)}, from_cron) return True def _safe_write_for_cron(self, vals, from_cron=False): if from_cron: auto_commit = not getattr(threading.current_thread(), 'testing', False) for contract in self: try: with self.env.cr.savepoint(): contract.write(vals) except ValidationError as e: _logger.warning(e) else: if auto_commit: self.env.cr.commit() else: self.write(vals) def _assign_open_contract(self): for contract in self: contract.employee_id.sudo().write({'contract_id': contract.id}) @api.depends('wage') def _compute_contract_wage(self): for contract in self: contract.contract_wage = contract._get_contract_wage() def _get_contract_wage(self): self.ensure_one() return self[self._get_contract_wage_field()] def _get_contract_wage_field(self): return 'wage' def write(self, vals): res = super(Contract, self).write(vals) if vals.get('state') == 'open': self._assign_open_contract() if vals.get('state') == 'close': for contract in self.filtered(lambda c: not c.date_end): contract.date_end = max(date.today(), contract.date_start) calendar = vals.get('resource_calendar_id') if calendar: self.filtered(lambda c: c.state == 'open' or (c.state == 'draft' and c.kanban_state == 'done')).mapped('employee_id').write({'resource_calendar_id': calendar}) if 'state' in vals and 'kanban_state' not in vals: self.write({'kanban_state': 'normal'}) return res @api.model def create(self, vals): contracts = super(Contract, self).create(vals) if vals.get('state') == 'open': contracts._assign_open_contract() open_contracts = contracts.filtered(lambda c: c.state == 'open' or c.state == 'draft' and c.kanban_state == 'done') # sync contract calendar -> calendar employee for contract in open_contracts.filtered(lambda c: c.employee_id and c.resource_calendar_id): contract.employee_id.resource_calendar_id = contract.resource_calendar_id return contracts def _track_subtype(self, init_values): self.ensure_one() if 'state' in init_values and self.state == 'open' and 'kanban_state' in init_values and self.kanban_state == 'blocked': return self.env.ref('hr_contract.mt_contract_pending') elif 'state' in init_values and self.state == 'close': return self.env.ref('hr_contract.mt_contract_close') return super(Contract, self)._track_subtype(init_values) def action_open_contract_form(self): self.ensure_one() return { "type": "ir.actions.act_window", "res_model": "hr.contract", "views": [[False, "form"]], "res_id": self.id, }
48.431095
13,706
7,313
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools, _ from collections import defaultdict class ContractHistory(models.Model): _name = 'hr.contract.history' _description = 'Contract history' _auto = False _order = 'is_under_contract' # Even though it would have been obvious to use the reference contract's id as the id of the # hr.contract.history model, it turned out it was a bad idea as this id could change (for instance if a # new contract is created with a later start date). The hr.contract.history is instead closely linked # to the employee. That's why we will use this id (employee_id) as the id of the hr.contract.history. contract_id = fields.Many2one('hr.contract', readonly=True) display_name = fields.Char(compute='_compute_display_name') name = fields.Char('Contract Name', readonly=True) date_hired = fields.Date('Hire Date', readonly=True) date_start = fields.Date('Start Date', readonly=True) date_end = fields.Date('End Date', readonly=True) employee_id = fields.Many2one('hr.employee', string='Employee', readonly=True) active_employee = fields.Boolean('Active Employee', readonly=True) is_under_contract = fields.Boolean('Is Currently Under Contract', readonly=True) department_id = fields.Many2one('hr.department', string='Department', readonly=True) structure_type_id = fields.Many2one('hr.payroll.structure.type', string='Salary Structure Type', readonly=True) hr_responsible_id = fields.Many2one('res.users', string='HR Responsible', readonly=True) job_id = fields.Many2one('hr.job', string='Job Position', readonly=True) state = fields.Selection([ ('draft', 'New'), ('open', 'Running'), ('close', 'Expired'), ('cancel', 'Cancelled') ], string='Status', readonly=True) resource_calendar_id = fields.Many2one('resource.calendar', string="Working Schedule", readonly=True) wage = fields.Monetary('Wage', help="Employee's monthly gross wage.", readonly=True, group_operator="avg") company_id = fields.Many2one('res.company', string='Company', readonly=True) company_country_id = fields.Many2one('res.country', string="Company country", related='company_id.country_id', readonly=True) country_code = fields.Char(related='company_country_id.code', readonly=True) currency_id = fields.Many2one(string='Currency', related='company_id.currency_id', readonly=True) contract_type_id = fields.Many2one('hr.contract.type', 'Contract Type', readonly=True) contract_ids = fields.One2many('hr.contract', string='Contracts', compute='_compute_contract_ids', readonly=True) contract_count = fields.Integer(compute='_compute_contract_count', string="# Contracts") under_contract_state = fields.Selection([ ('done', 'Under Contract'), ('blocked', 'Not Under Contract') ], string='Contractual Status', compute='_compute_under_contract_state') activity_state = fields.Selection(related='contract_id.activity_state') @api.depends('contract_ids') def _compute_contract_count(self): for history in self: history.contract_count = len(history.contract_ids) @api.depends('is_under_contract') def _compute_under_contract_state(self): for history in self: history.under_contract_state = 'done' if history.is_under_contract else 'blocked' @api.depends('employee_id.name') def _compute_display_name(self): for history in self: history.display_name = _("%s's Contracts History", history.employee_id.name) @api.model def _get_fields(self): return ','.join('contract.%s' % name for name, field in self._fields.items() if field.store and field.type not in ['many2many', 'one2many', 'related'] and field.name not in ['id', 'contract_id', 'employee_id', 'date_hired', 'is_under_contract', 'active_employee']) def init(self): tools.drop_view_if_exists(self.env.cr, self._table) # Reference contract is the one with the latest start_date. self.env.cr.execute("""CREATE or REPLACE VIEW %s AS ( WITH contract_information AS ( SELECT DISTINCT employee_id, company_id, FIRST_VALUE(id) OVER w_partition AS id, MAX(CASE WHEN state='open' THEN 1 WHEN state='draft' AND kanban_state='done' THEN 1 ELSE 0 END) OVER w_partition AS is_under_contract FROM hr_contract AS contract WHERE contract.state <> 'cancel' AND contract.active = true WINDOW w_partition AS ( PARTITION BY contract.employee_id, contract.company_id ORDER BY CASE WHEN contract.state = 'open' THEN 0 WHEN contract.state = 'draft' THEN 1 WHEN contract.state = 'close' THEN 2 ELSE 3 END, contract.date_start DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) ) SELECT employee.id AS id, employee.id AS employee_id, employee.active AS active_employee, contract.id AS contract_id, contract_information.is_under_contract::bool AS is_under_contract, employee.first_contract_date AS date_hired, %s FROM hr_contract AS contract INNER JOIN contract_information ON contract.id = contract_information.id RIGHT JOIN hr_employee AS employee ON contract_information.employee_id = employee.id AND contract.company_id = employee.company_id WHERE employee.employee_type IN ('employee', 'student', 'trainee') )""" % (self._table, self._get_fields())) @api.depends('employee_id.contract_ids') def _compute_contract_ids(self): sorted_contracts = self.mapped('employee_id.contract_ids').sorted('date_start', reverse=True) mapped_employee_contracts = defaultdict(lambda: self.env['hr.contract']) for contract in sorted_contracts: if contract.state != 'cancel': mapped_employee_contracts[contract.employee_id] |= contract for history in self: history.contract_ids = mapped_employee_contracts[history.employee_id] def hr_contract_view_form_new_action(self): self.ensure_one() action = self.env['ir.actions.actions']._for_xml_id('hr_contract.action_hr_contract') action.update({ 'context': {'default_employee_id': self.employee_id.id}, 'view_mode': 'form', 'view_id': self.env.ref('hr_contract.hr_contract_view_form').id, 'views': [(self.env.ref('hr_contract.hr_contract_view_form').id, 'form')], }) return action
52.992754
7,313
561
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'MTO Sale <-> Purchase', 'version': '1.0', 'category': 'Hidden', 'summary': 'SO/PO relation in case of MTO', 'description': """ Add relation information between Sale Orders and Purchase Orders if Make to Order (MTO) is activated on one sold product. """, 'depends': ['sale_stock', 'purchase_stock', 'sale_purchase'], 'data': [], 'demo': [], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
31.166667
561
2,621
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from odoo.addons.sale_purchase.tests.common import TestCommonSalePurchaseNoChart @tagged('post_install', '-at_install') class TestAccessRights(TestCommonSalePurchaseNoChart): @classmethod def setUpClass(cls): super(TestAccessRights, cls).setUpClass() group_sale_user = cls.env.ref('sales_team.group_sale_salesman') cls.user_salesperson = cls.env['res.users'].with_context(no_reset_password=True).create({ 'name': 'Le Grand Jojo User', 'login': 'grand.jojo', 'email': 'grand.jojo@chansonbelge.com', 'groups_id': [(6, 0, [group_sale_user.id])] }) def test_access_saleperson_decreases_qty(self): """ Suppose a user who has no right on PO Suppose a PO linked to a SO The user decreases the qty on the SO This test ensures that an activity (warning) is added to the PO """ mto_route = self.env.ref('stock.route_warehouse0_mto') buy_route = self.env.ref('purchase_stock.route_warehouse0_buy') mto_route.active = True vendor = self.env['res.partner'].create({'name': 'vendor'}) seller = self.env['product.supplierinfo'].create({ 'name': vendor.id, 'price': 8, }) product = self.env['product.product'].create({ 'name': 'SuperProduct', 'type': 'product', 'seller_ids': [(6, 0, seller.ids)], 'route_ids': [(6, 0, (mto_route + buy_route).ids)] }) so = self.env['sale.order'].with_user(self.user_salesperson).create({ 'partner_id': self.partner_a.id, 'user_id': self.user_salesperson.id, }) so_line, _ = self.env['sale.order.line'].create([{ 'name': product.name, 'product_id': product.id, 'product_uom_qty': 1, 'product_uom': product.uom_id.id, 'price_unit': product.list_price, 'tax_id': False, 'order_id': so.id, }, { 'name': 'Super Section', 'display_type': 'line_section', 'order_id': so.id, }]) so.action_confirm() po = self.env['purchase.order'].search([('partner_id', '=', vendor.id)]) po.button_confirm() # salesperson writes on the SO so.write({ 'order_line': [(1, so_line.id, {'product_uom_qty': 0.9})] }) self.assertIn(so.name, po.activity_ids.note)
34.486842
2,621
1,386
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase, Form class TestSalePurchaseStockFlow(TransactionCase): def test_cancel_so_with_draft_po(self): """ Sell a MTO+Buy product -> a PO is generated Cancel the SO -> an activity should be added to the PO """ mto_route = self.env.ref('stock.route_warehouse0_mto') buy_route = self.env.ref('purchase_stock.route_warehouse0_buy') mto_route.active = True vendor = self.env['res.partner'].create({ 'name': 'Super Vendor' }) product = self.env['product.product'].create({ 'name': 'SuperProduct', 'type': 'product', 'route_ids': [(6, 0, (mto_route + buy_route).ids)], 'seller_ids': [(0, 0, { 'name': vendor.id, })], }) so_form = Form(self.env['sale.order']) so_form.partner_id = self.env.user.partner_id with so_form.order_line.new() as line: line.product_id = product so = so_form.save() so.action_confirm() po = self.env['purchase.order'].search([('partner_id', '=', vendor.id)]) so.action_cancel() self.assertTrue(po.activity_ids) self.assertIn(so.name, po.activity_ids.note)
32.232558
1,386
726
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 SaleOrder(models.Model): _inherit = 'sale.order' @api.depends('procurement_group_id.stock_move_ids.created_purchase_line_id.order_id', 'procurement_group_id.stock_move_ids.move_orig_ids.purchase_line_id.order_id') def _compute_purchase_order_count(self): super(SaleOrder, self)._compute_purchase_order_count() def _get_purchase_orders(self): return super(SaleOrder, self)._get_purchase_orders() | self.procurement_group_id.stock_move_ids.created_purchase_line_id.order_id | self.procurement_group_id.stock_move_ids.move_orig_ids.purchase_line_id.order_id
48.4
726
620
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 PurchaseOrder(models.Model): _inherit = 'purchase.order' @api.depends('order_line.move_dest_ids.group_id.sale_id', 'order_line.move_ids.move_dest_ids.group_id.sale_id') def _compute_sale_order_count(self): super(PurchaseOrder, self)._compute_sale_order_count() def _get_sale_orders(self): return super(PurchaseOrder, self)._get_sale_orders() | self.order_line.move_dest_ids.group_id.sale_id | self.order_line.move_ids.move_dest_ids.group_id.sale_id
41.333333
620
1,030
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'WMS Landed Costs', 'version': '1.1', 'summary': 'Landed Costs', 'description': """ Landed Costs Management ======================= This module allows you to easily add extra costs on pickings and decide the split of these costs among their stock moves in order to take them into account in your stock valuation. """, 'depends': ['stock_account', 'purchase_stock'], 'category': 'Inventory/Inventory', 'sequence': 16, 'demo': [ ], 'data': [ 'security/ir.model.access.csv', 'security/stock_landed_cost_security.xml', 'data/stock_landed_cost_data.xml', 'views/account_move_views.xml', 'views/product_views.xml', 'views/stock_landed_cost_views.xml', 'views/stock_valuation_layer_views.xml', 'views/res_config_settings_views.xml', ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
33.225806
1,030
22,881
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. """ Implementation of "INVENTORY VALUATION TESTS (With valuation layers)" spreadsheet. """ from odoo.tests import Form, tagged from odoo.addons.stock_landed_costs.tests.common import TestStockLandedCostsCommon class TestStockValuationLCCommon(TestStockLandedCostsCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.product1 = cls.env['product.product'].create({ 'name': 'product1', 'type': 'product', 'categ_id': cls.stock_account_product_categ.id, }) cls.productlc1 = cls.env['product.product'].create({ 'name': 'product1', 'type': 'service', 'categ_id': cls.stock_account_product_categ.id, }) def setUp(self): super().setUp() self.days = 0 def _get_stock_input_move_lines(self): return self.env['account.move.line'].search([ ('account_id', '=', self.company_data['default_account_stock_in'].id), ], order='id') def _get_stock_output_move_lines(self): return self.env['account.move.line'].search([ ('account_id', '=', self.company_data['default_account_stock_out'].id), ], order='id') def _get_stock_valuation_move_lines(self): return self.env['account.move.line'].search([ ('account_id', '=', self.company_data['default_account_stock_valuation'].id), ], order='id') def _get_payable_move_lines(self): return self.env['account.move.line'].search([ ('account_id', '=', self.company_data['default_account_payable'].id), ], order='id') def _get_expense_move_lines(self): return self.env['account.move.line'].search([ ('account_id', '=', self.company_data['default_account_expense'].id), ], order='id') def _make_lc(self, move, amount): picking = move.picking_id lc = Form(self.env['stock.landed.cost']) lc.account_journal_id = self.stock_journal lc.picking_ids.add(move.picking_id) with lc.cost_lines.new() as cost_line: cost_line.product_id = self.productlc1 cost_line.price_unit = amount lc = lc.save() lc.compute_landed_cost() lc.button_validate() return lc def _make_in_move(self, product, quantity, unit_cost=None, create_picking=False): """ Helper to create and validate a receipt move. """ unit_cost = unit_cost or product.standard_price in_move = self.env['stock.move'].create({ 'name': 'in %s units @ %s per unit' % (str(quantity), str(unit_cost)), 'product_id': product.id, 'location_id': self.env.ref('stock.stock_location_suppliers').id, 'location_dest_id': self.company_data['default_warehouse'].lot_stock_id.id, 'product_uom': self.env.ref('uom.product_uom_unit').id, 'product_uom_qty': quantity, 'price_unit': unit_cost, 'picking_type_id': self.company_data['default_warehouse'].in_type_id.id, }) if create_picking: picking = self.env['stock.picking'].create({ 'picking_type_id': in_move.picking_type_id.id, 'location_id': in_move.location_id.id, 'location_dest_id': in_move.location_dest_id.id, }) in_move.write({'picking_id': picking.id}) in_move._action_confirm() in_move._action_assign() in_move.move_line_ids.qty_done = quantity in_move._action_done() self.days += 1 return in_move.with_context(svl=True) def _make_out_move(self, product, quantity, force_assign=None, create_picking=False): """ Helper to create and validate a delivery move. """ out_move = self.env['stock.move'].create({ 'name': 'out %s units' % str(quantity), 'product_id': product.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'product_uom': self.env.ref('uom.product_uom_unit').id, 'product_uom_qty': quantity, 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, }) if create_picking: picking = self.env['stock.picking'].create({ 'picking_type_id': out_move.picking_type_id.id, 'location_id': out_move.location_id.id, 'location_dest_id': out_move.location_dest_id.id, }) out_move.write({'picking_id': picking.id}) out_move._action_confirm() out_move._action_assign() if force_assign: self.env['stock.move.line'].create({ 'move_id': out_move.id, 'product_id': out_move.product_id.id, 'product_uom_id': out_move.product_uom.id, 'location_id': out_move.location_id.id, 'location_dest_id': out_move.location_dest_id.id, }) out_move.move_line_ids.qty_done = quantity out_move._action_done() self.days += 1 return out_move.with_context(svl=True) @tagged('-at_install', 'post_install') class TestStockValuationLCFIFO(TestStockValuationLCCommon): def setUp(self): super(TestStockValuationLCFIFO, self).setUp() self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' def test_normal_1(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True) move2 = self._make_in_move(self.product1, 10, unit_cost=20) lc = self._make_lc(move1, 100) move3 = self._make_out_move(self.product1, 1) self.assertEqual(self.product1.value_svl, 380) self.assertEqual(self.product1.quantity_svl, 19) self.assertEqual(self.product1.standard_price, 20) def test_negative_1(self): self.product1.standard_price = 10 move1 = self._make_out_move(self.product1, 2, force_assign=True) move2 = self._make_in_move(self.product1, 10, unit_cost=15, create_picking=True) lc = self._make_lc(move2, 100) self.assertEqual(self.product1.value_svl, 200) self.assertEqual(self.product1.quantity_svl, 8) def test_alreadyout_1(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True) move2 = self._make_out_move(self.product1, 10) lc = self._make_lc(move1, 100) self.assertEqual(self.product1.value_svl, 0) self.assertEqual(self.product1.quantity_svl, 0) def test_alreadyout_2(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True) move2 = self._make_in_move(self.product1, 10, unit_cost=20) move2 = self._make_out_move(self.product1, 1) lc = self._make_lc(move1, 100) self.assertEqual(self.product1.value_svl, 380) self.assertEqual(self.product1.quantity_svl, 19) def test_alreadyout_3(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True) move2 = self._make_out_move(self.product1, 10) move1.move_line_ids.qty_done = 15 lc = self._make_lc(move1, 60) self.assertEqual(self.product1.value_svl, 70) self.assertEqual(self.product1.quantity_svl, 5) def test_fifo_to_standard_1(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10) move2 = self._make_in_move(self.product1, 10, unit_cost=15) move3 = self._make_out_move(self.product1, 5) lc = self._make_lc(move1, 100) self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' out_svl = self.product1.stock_valuation_layer_ids.sorted()[-2] in_svl = self.product1.stock_valuation_layer_ids.sorted()[-1] self.assertEqual(out_svl.value, -250) self.assertEqual(in_svl.value, 225) def test_rounding_1(self): """3@100, out 1, out 1, out 1""" move1 = self._make_in_move(self.product1, 3, unit_cost=20, create_picking=True) lc = self._make_lc(move1, 40) move2 = self._make_out_move(self.product1, 1) move3 = self._make_out_move(self.product1, 1) move4 = self._make_out_move(self.product1, 1) self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), [60.0, 40.0, -33.33, -33.34, -33.33]) self.assertEqual(self.product1.value_svl, 0) self.assertEqual(self.product1.quantity_svl, 0) def test_rounding_2(self): """3@98, out 1, out 1, out 1""" move1 = self._make_in_move(self.product1, 3, unit_cost=20, create_picking=True) lc = self._make_lc(move1, 38) move2 = self._make_out_move(self.product1, 1) move3 = self._make_out_move(self.product1, 1) move4 = self._make_out_move(self.product1, 1) self.assertEqual(move2.stock_valuation_layer_ids.value, -32.67) self.assertEqual(move3.stock_valuation_layer_ids.value, -32.67) self.assertAlmostEqual(move4.stock_valuation_layer_ids.value, -32.66, delta=0.01) # self.env.company.currency_id.round(-32.66) -> -32.660000000000004 self.assertEqual(self.product1.value_svl, 0) self.assertEqual(self.product1.quantity_svl, 0) def test_rounding_3(self): """3@4.85, out 1, out 1, out 1""" move1 = self._make_in_move(self.product1, 3, unit_cost=1, create_picking=True) lc = self._make_lc(move1, 1.85) move2 = self._make_out_move(self.product1, 1) move3 = self._make_out_move(self.product1, 1) move4 = self._make_out_move(self.product1, 1) self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), [3.0, 1.85, -1.62, -1.62, -1.61]) self.assertEqual(self.product1.value_svl, 0) self.assertEqual(self.product1.quantity_svl, 0) def test_in_and_out_1(self): move1 = self._make_in_move(self.product1, 10, unit_cost=100, create_picking=True) self.assertEqual(move1.stock_valuation_layer_ids[0].remaining_value, 1000) lc1 = self._make_lc(move1, 100) self.assertEqual(move1.stock_valuation_layer_ids[0].remaining_value, 1100) lc2 = self._make_lc(move1, 50) self.assertEqual(move1.stock_valuation_layer_ids[0].remaining_value, 1150) self.assertEqual(self.product1.value_svl, 1150) self.assertEqual(self.product1.quantity_svl, 10) move2 = self._make_out_move(self.product1, 1) self.assertEqual(move2.stock_valuation_layer_ids.value, -115) @tagged('-at_install', 'post_install') class TestStockValuationLCAVCO(TestStockValuationLCCommon): def setUp(self): super(TestStockValuationLCAVCO, self).setUp() self.product1.product_tmpl_id.categ_id.property_cost_method = 'average' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' def test_normal_1(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True) move2 = self._make_in_move(self.product1, 10, unit_cost=20) lc = self._make_lc(move1, 100) move3 = self._make_out_move(self.product1, 1) self.assertEqual(self.product1.value_svl, 380) def test_negative_1(self): self.product1.standard_price = 10 move1 = self._make_out_move(self.product1, 2, force_assign=True) move2 = self._make_in_move(self.product1, 10, unit_cost=15, create_picking=True) lc = self._make_lc(move2, 100) self.assertEqual(self.product1.value_svl, 200) self.assertEqual(self.product1.quantity_svl, 8) def test_alreadyout_1(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True) move2 = self._make_out_move(self.product1, 10) lc = self._make_lc(move1, 100) self.assertEqual(len(self.product1.stock_valuation_layer_ids), 2) self.assertEqual(self.product1.value_svl, 0) self.assertEqual(self.product1.quantity_svl, 0) def test_alreadyout_2(self): move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True) move2 = self._make_in_move(self.product1, 10, unit_cost=20) move2 = self._make_out_move(self.product1, 1) lc = self._make_lc(move1, 100) self.assertEqual(self.product1.value_svl, 375) self.assertEqual(self.product1.quantity_svl, 19) @tagged('-at_install', 'post_install') class TestStockValuationLCFIFOVB(TestStockValuationLCCommon): @classmethod def setUpClass(cls): super(TestStockValuationLCFIFOVB, cls).setUpClass() cls.vendor1 = cls.env['res.partner'].create({'name': 'vendor1'}) cls.vendor1.property_account_payable_id = cls.company_data['default_account_payable'] cls.vendor2 = cls.env['res.partner'].create({'name': 'vendor2'}) cls.vendor2.property_account_payable_id = cls.company_data['default_account_payable'] cls.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' cls.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' def test_vendor_bill_flow_anglo_saxon_1(self): """In anglo saxon accounting, receive 10@10 and invoice. Then invoice 1@50 as a landed costs and create a linked landed costs record. """ self.env.company.anglo_saxon_accounting = True # Create an RFQ for self.product1, 10@10 rfq = Form(self.env['purchase.order']) rfq.partner_id = self.vendor1 with rfq.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 10 po_line.price_unit = 10 po_line.taxes_id.clear() rfq = rfq.save() rfq.button_confirm() # Process the receipt receipt = rfq.picking_ids wiz = receipt.button_validate() wiz = Form(self.env['stock.immediate.transfer'].with_context(wiz['context'])).save().process() self.assertEqual(rfq.order_line.qty_received, 10) input_aml = self._get_stock_input_move_lines()[-1] self.assertEqual(input_aml.debit, 0) self.assertEqual(input_aml.credit, 100) valuation_aml = self._get_stock_valuation_move_lines()[-1] self.assertEqual(valuation_aml.debit, 100) self.assertEqual(valuation_aml.credit, 0) # Create a vendor bill for the RFQ action = rfq.action_create_invoice() vb = self.env['account.move'].browse(action['res_id']) vb.invoice_date = vb.date vb.action_post() input_aml = self._get_stock_input_move_lines()[-1] self.assertEqual(input_aml.debit, 100) self.assertEqual(input_aml.credit, 0) payable_aml = self._get_payable_move_lines()[-1] self.assertEqual(payable_aml.debit, 0) self.assertEqual(payable_aml.credit, 100) # Create a vendor bill for a landed cost product, post it and validate a landed cost # linked to this vendor bill. LC; 1@50 lcvb = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) lcvb.invoice_date = lcvb.date lcvb.partner_id = self.vendor2 with lcvb.invoice_line_ids.new() as inv_line: inv_line.product_id = self.productlc1 inv_line.price_unit = 50 inv_line.is_landed_costs_line = True with lcvb.invoice_line_ids.edit(0) as inv_line: inv_line.tax_ids.clear() lcvb = lcvb.save() lcvb.action_post() input_aml = self._get_stock_input_move_lines()[-1] self.assertEqual(input_aml.debit, 50) self.assertEqual(input_aml.credit, 0) payable_aml = self._get_payable_move_lines()[-1] self.assertEqual(payable_aml.debit, 0) self.assertEqual(payable_aml.credit, 50) action = lcvb.button_create_landed_costs() lc = Form(self.env[action['res_model']].browse(action['res_id'])) lc.picking_ids.add(receipt) lc = lc.save() lc.button_validate() self.assertEqual(lc.cost_lines.price_unit, 50) self.assertEqual(lc.cost_lines.product_id, self.productlc1) input_aml = self._get_stock_input_move_lines()[-1] self.assertEqual(input_aml.debit, 0) self.assertEqual(input_aml.credit, 50) valuation_aml = self._get_stock_valuation_move_lines()[-1] self.assertEqual(valuation_aml.debit, 50) self.assertEqual(valuation_aml.credit, 0) # Check reconciliation of input aml of lc lc_input_aml = lc.account_move_id.line_ids.filtered(lambda aml: aml.account_id == self.company_data['default_account_stock_in']) self.assertTrue(len(lc_input_aml.full_reconcile_id), 1) self.assertEqual(self.product1.quantity_svl, 10) self.assertEqual(self.product1.value_svl, 150) def test_vendor_bill_flow_anglo_saxon_2(self): """In anglo saxon accounting, receive 10@10 and invoice with the addition of 1@50 as a landed costs and create a linked landed costs record. """ self.env.company.anglo_saxon_accounting = True # Create an RFQ for self.product1, 10@10 rfq = Form(self.env['purchase.order']) rfq.partner_id = self.vendor1 with rfq.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 10 po_line.price_unit = 10 po_line.taxes_id.clear() rfq = rfq.save() rfq.button_confirm() # Process the receipt receipt = rfq.picking_ids wiz = receipt.button_validate() wiz = Form(self.env['stock.immediate.transfer'].with_context(wiz['context'])).save() wiz.process() self.assertEqual(rfq.order_line.qty_received, 10) input_aml = self._get_stock_input_move_lines()[-1] self.assertEqual(input_aml.debit, 0) self.assertEqual(input_aml.credit, 100) valuation_aml = self._get_stock_valuation_move_lines()[-1] self.assertEqual(valuation_aml.debit, 100) self.assertEqual(valuation_aml.credit, 0) # Create a vendor bill for the RFQ and add to it the landed cost vb = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) vb.partner_id = self.vendor1 vb.invoice_date = vb.date with vb.invoice_line_ids.new() as inv_line: inv_line.product_id = self.productlc1 inv_line.price_unit = 50 inv_line.is_landed_costs_line = True vb = vb.save() vb.action_post() action = vb.button_create_landed_costs() lc = Form(self.env[action['res_model']].browse(action['res_id'])) lc.picking_ids.add(receipt) lc = lc.save() lc.button_validate() # Check reconciliation of input aml of lc lc_input_aml = lc.account_move_id.line_ids.filtered(lambda aml: aml.account_id == self.company_data['default_account_stock_in']) self.assertTrue(len(lc_input_aml.full_reconcile_id), 1) def test_vendor_bill_flow_continental_1(self): """In continental accounting, receive 10@10 and invoice. Then invoice 1@50 as a landed costs and create a linked landed costs record. """ self.env.company.anglo_saxon_accounting = False # Create an RFQ for self.product1, 10@10 rfq = Form(self.env['purchase.order']) rfq.partner_id = self.vendor1 with rfq.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 10 po_line.price_unit = 10 po_line.taxes_id.clear() rfq = rfq.save() rfq.button_confirm() # Process the receipt receipt = rfq.picking_ids wiz = receipt.button_validate() wiz = Form(self.env['stock.immediate.transfer'].with_context(wiz['context'])).save().process() self.assertEqual(rfq.order_line.qty_received, 10) input_aml = self._get_stock_input_move_lines()[-1] self.assertEqual(input_aml.debit, 0) self.assertEqual(input_aml.credit, 100) valuation_aml = self._get_stock_valuation_move_lines()[-1] self.assertEqual(valuation_aml.debit, 100) self.assertEqual(valuation_aml.credit, 0) # Create a vebdor bill for the RFQ action = rfq.action_create_invoice() vb = self.env['account.move'].browse(action['res_id']) vb.invoice_date = vb.date vb.action_post() expense_aml = self._get_expense_move_lines()[-1] self.assertEqual(expense_aml.debit, 100) self.assertEqual(expense_aml.credit, 0) payable_aml = self._get_payable_move_lines()[-1] self.assertEqual(payable_aml.debit, 0) self.assertEqual(payable_aml.credit, 100) # Create a vendor bill for a landed cost product, post it and validate a landed cost # linked to this vendor bill. LC; 1@50 lcvb = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) lcvb.partner_id = self.vendor2 lcvb.invoice_date = lcvb.date with lcvb.invoice_line_ids.new() as inv_line: inv_line.product_id = self.productlc1 inv_line.price_unit = 50 inv_line.is_landed_costs_line = True with lcvb.invoice_line_ids.edit(0) as inv_line: inv_line.tax_ids.clear() lcvb = lcvb.save() lcvb.action_post() expense_aml = self._get_expense_move_lines()[-1] self.assertEqual(expense_aml.debit, 50) self.assertEqual(expense_aml.credit, 0) payable_aml = self._get_payable_move_lines()[-1] self.assertEqual(payable_aml.debit, 0) self.assertEqual(payable_aml.credit, 50) action = lcvb.button_create_landed_costs() lc = Form(self.env[action['res_model']].browse(action['res_id'])) lc.picking_ids.add(receipt) lc = lc.save() lc.button_validate() self.assertEqual(lc.cost_lines.price_unit, 50) self.assertEqual(lc.cost_lines.product_id, self.productlc1) input_aml = self._get_stock_input_move_lines()[-1] self.assertEqual(input_aml.debit, 0) self.assertEqual(input_aml.credit, 50) valuation_aml = self._get_stock_valuation_move_lines()[-1] self.assertEqual(valuation_aml.debit, 50) self.assertEqual(valuation_aml.credit, 0) self.assertEqual(self.product1.quantity_svl, 10) self.assertEqual(self.product1.value_svl, 150)
42.688433
22,881
2,776
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon class TestStockLandedCostsCommon(ValuationReconciliationTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) # Objects cls.Product = cls.env['product.product'] cls.Picking = cls.env['stock.picking'] cls.Move = cls.env['stock.move'] cls.LandedCost = cls.env['stock.landed.cost'] cls.CostLine = cls.env['stock.landed.cost.lines'] # References cls.warehouse = cls.company_data['default_warehouse'] cls.supplier_id = cls.env['res.partner'].create({'name': 'My Test Supplier'}).id cls.customer_id = cls.env['res.partner'].create({'name': 'My Test Customer'}).id cls.supplier_location_id = cls.env.ref('stock.stock_location_suppliers').id cls.customer_location_id = cls.env.ref('stock.stock_location_customers').id cls.categ_all = cls.stock_account_product_categ cls.categ_manual_periodic = cls.env.ref('product.product_category_all').copy({ "property_valuation": "manual_periodic", "property_cost_method": "fifo" }) cls.categ_real_time = cls.env.ref('product.product_category_all').copy({ "property_valuation": "real_time", "property_cost_method": "average" }) cls.expenses_journal = cls.company_data['default_journal_purchase'] cls.stock_journal = cls.env['account.journal'].create({ 'name': 'Stock Journal', 'code': 'STJTEST', 'type': 'general', }) # Create product refrigerator & oven cls.product_refrigerator = cls.Product.create({ 'name': 'Refrigerator', 'type': 'product', 'standard_price': 1.0, 'weight': 10, 'volume': 1, 'categ_id': cls.categ_real_time.id}) cls.product_oven = cls.Product.create({ 'name': 'Microwave Oven', 'type': 'product', 'standard_price': 1.0, 'weight': 20, 'volume': 1.5, 'categ_id': cls.categ_real_time.id}) # Create service type product 1.Labour 2.Brokerage 3.Transportation 4.Packaging cls.landed_cost = cls.Product.create({'name': 'Landed Cost', 'type': 'service'}) cls.brokerage_quantity = cls.Product.create({'name': 'Brokerage Cost', 'type': 'service'}) cls.transportation_weight = cls.Product.create({'name': 'Transportation Cost', 'type': 'service'}) cls.packaging_volume = cls.Product.create({'name': 'Packaging Cost', 'type': 'service'})
47.862069
2,776
22,434
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import unittest from odoo.addons.stock_landed_costs.tests.common import TestStockLandedCostsCommon from odoo.addons.stock_landed_costs.tests.test_stockvaluationlayer import TestStockValuationLCCommon from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data from odoo.tests import tagged, Form @tagged('post_install', '-at_install') class TestLandedCosts(TestStockLandedCostsCommon): def setUp(self): super(TestLandedCosts, self).setUp() # Create picking incoming shipment self.picking_in = self.Picking.create({ 'partner_id': self.supplier_id, 'picking_type_id': self.warehouse.in_type_id.id, 'location_id': self.supplier_location_id, 'location_dest_id': self.warehouse.lot_stock_id.id}) self.Move.create({ 'name': self.product_refrigerator.name, 'product_id': self.product_refrigerator.id, 'product_uom_qty': 5, 'product_uom': self.product_refrigerator.uom_id.id, 'picking_id': self.picking_in.id, 'location_id': self.supplier_location_id, 'location_dest_id': self.warehouse.lot_stock_id.id}) self.Move.create({ 'name': self.product_oven.name, 'product_id': self.product_oven.id, 'product_uom_qty': 10, 'product_uom': self.product_oven.uom_id.id, 'picking_id': self.picking_in.id, 'location_id': self.supplier_location_id, 'location_dest_id': self.warehouse.lot_stock_id.id}) # Create picking outgoing shipment self.picking_out = self.Picking.create({ 'partner_id': self.customer_id, 'picking_type_id': self.warehouse.out_type_id.id, 'location_id': self.warehouse.lot_stock_id.id, 'location_dest_id': self.customer_location_id}) self.Move.create({ 'name': self.product_refrigerator.name, 'product_id': self.product_refrigerator.id, 'product_uom_qty': 2, 'product_uom': self.product_refrigerator.uom_id.id, 'picking_id': self.picking_out.id, 'location_id': self.warehouse.lot_stock_id.id, 'location_dest_id': self.customer_location_id}) def test_00_landed_costs_on_incoming_shipment(self): """ Test landed cost on incoming shipment """ # # (A) Purchase product # Services Quantity Weight Volume # ----------------------------------------------------- # 1. Refrigerator 5 10 1 # 2. Oven 10 20 1.5 # (B) Add some costs on purchase # Services Amount Split Method # ------------------------------------------- # 1.labour 10 By Equal # 2.brokerage 150 By Quantity # 3.transportation 250 By Weight # 4.packaging 20 By Volume self.landed_cost.categ_id.property_valuation = 'real_time' # Process incoming shipment income_ship = self._process_incoming_shipment() # Create landed costs stock_landed_cost = self._create_landed_costs({ 'equal_price_unit': 10, 'quantity_price_unit': 150, 'weight_price_unit': 250, 'volume_price_unit': 20}, income_ship) # Compute landed costs stock_landed_cost.compute_landed_cost() valid_vals = { 'equal': 5.0, 'by_quantity_refrigerator': 50.0, 'by_quantity_oven': 100.0, 'by_weight_refrigerator': 50.0, 'by_weight_oven': 200, 'by_volume_refrigerator': 5.0, 'by_volume_oven': 15.0} # Check valuation adjustment line recognized or not self._validate_additional_landed_cost_lines(stock_landed_cost, valid_vals) # Validate the landed cost. stock_landed_cost.button_validate() self.assertTrue(stock_landed_cost.account_move_id, 'Landed costs should be available account move lines') account_entry = self.env['account.move.line'].read_group( [('move_id', '=', stock_landed_cost.account_move_id.id)], ['debit', 'credit', 'move_id'], ['move_id'])[0] self.assertEqual(account_entry['debit'], account_entry['credit'], 'Debit and credit are not equal') self.assertEqual(account_entry['debit'], 430.0, 'Wrong Account Entry') def test_00_landed_costs_on_incoming_shipment_without_real_time(self): chart_of_accounts = self.env.company.chart_template_id generic_coa = self.env.ref('l10n_generic_coa.configurable_chart_template') if chart_of_accounts != generic_coa: raise unittest.SkipTest('Skip this test as it works only with %s (%s loaded)' % (generic_coa.name, chart_of_accounts.name)) """ Test landed cost on incoming shipment """ # # (A) Purchase product # Services Quantity Weight Volume # ----------------------------------------------------- # 1. Refrigerator 5 10 1 # 2. Oven 10 20 1.5 # (B) Add some costs on purchase # Services Amount Split Method # ------------------------------------------- # 1.labour 10 By Equal # 2.brokerage 150 By Quantity # 3.transportation 250 By Weight # 4.packaging 20 By Volume self.product_refrigerator.write({"categ_id": self.categ_manual_periodic.id}) self.product_oven.write({"categ_id": self.categ_manual_periodic.id}) # Process incoming shipment income_ship = self._process_incoming_shipment() # Create landed costs stock_landed_cost = self._create_landed_costs({ 'equal_price_unit': 10, 'quantity_price_unit': 150, 'weight_price_unit': 250, 'volume_price_unit': 20}, income_ship) # Compute landed costs stock_landed_cost.compute_landed_cost() valid_vals = { 'equal': 5.0, 'by_quantity_refrigerator': 50.0, 'by_quantity_oven': 100.0, 'by_weight_refrigerator': 50.0, 'by_weight_oven': 200, 'by_volume_refrigerator': 5.0, 'by_volume_oven': 15.0} # Check valuation adjustment line recognized or not self._validate_additional_landed_cost_lines(stock_landed_cost, valid_vals) # Validate the landed cost. stock_landed_cost.button_validate() self.assertFalse(stock_landed_cost.account_move_id) def test_01_negative_landed_costs_on_incoming_shipment(self): """ Test negative landed cost on incoming shipment """ # # (A) Purchase Product # Services Quantity Weight Volume # ----------------------------------------------------- # 1. Refrigerator 5 10 1 # 2. Oven 10 20 1.5 # (B) Sale refrigerator's part of the quantity # (C) Add some costs on purchase # Services Amount Split Method # ------------------------------------------- # 1.labour 10 By Equal # 2.brokerage 150 By Quantity # 3.transportation 250 By Weight # 4.packaging 20 By Volume # (D) Decrease cost that already added on purchase # (apply negative entry) # Services Amount Split Method # ------------------------------------------- # 1.labour -5 By Equal # 2.brokerage -50 By Quantity # 3.transportation -50 By Weight # 4.packaging -5 By Volume self.landed_cost.categ_id.property_valuation = 'real_time' # Process incoming shipment income_ship = self._process_incoming_shipment() # Refrigerator outgoing shipment. self._process_outgoing_shipment() # Apply landed cost for incoming shipment. stock_landed_cost = self._create_landed_costs({ 'equal_price_unit': 10, 'quantity_price_unit': 150, 'weight_price_unit': 250, 'volume_price_unit': 20}, income_ship) # Compute landed costs stock_landed_cost.compute_landed_cost() valid_vals = { 'equal': 5.0, 'by_quantity_refrigerator': 50.0, 'by_quantity_oven': 100.0, 'by_weight_refrigerator': 50.0, 'by_weight_oven': 200.0, 'by_volume_refrigerator': 5.0, 'by_volume_oven': 15.0} # Check valuation adjustment line recognized or not self._validate_additional_landed_cost_lines(stock_landed_cost, valid_vals) # Validate the landed cost. stock_landed_cost.button_validate() self.assertTrue(stock_landed_cost.account_move_id, 'Landed costs should be available account move lines') # Create negative landed cost for previously incoming shipment. stock_negative_landed_cost = self._create_landed_costs({ 'equal_price_unit': -5, 'quantity_price_unit': -50, 'weight_price_unit': -50, 'volume_price_unit': -5}, income_ship) # Compute negative landed costs stock_negative_landed_cost.compute_landed_cost() valid_vals = { 'equal': -2.5, 'by_quantity_refrigerator': -16.67, 'by_quantity_oven': -33.33, 'by_weight_refrigerator': -10.00, 'by_weight_oven': -40.00, 'by_volume_refrigerator': -1.25, 'by_volume_oven': -3.75} # Check valuation adjustment line recognized or not self._validate_additional_landed_cost_lines(stock_negative_landed_cost, valid_vals) # Validate the landed cost. stock_negative_landed_cost.button_validate() self.assertEqual(stock_negative_landed_cost.state, 'done', 'Negative landed costs should be in done state') self.assertTrue(stock_negative_landed_cost.account_move_id, 'Landed costs should be available account move lines') account_entry = self.env['account.move.line'].read_group( [('move_id', '=', stock_negative_landed_cost.account_move_id.id)], ['debit', 'credit', 'move_id'], ['move_id'])[0] self.assertEqual(account_entry['debit'], account_entry['credit'], 'Debit and credit are not equal') move_lines = [ {'name': 'split by volume - Microwave Oven', 'debit': 3.75, 'credit': 0.0}, {'name': 'split by volume - Microwave Oven', 'debit': 0.0, 'credit': 3.75}, {'name': 'split by weight - Microwave Oven', 'debit': 40.0, 'credit': 0.0}, {'name': 'split by weight - Microwave Oven', 'debit': 0.0, 'credit': 40.0}, {'name': 'split by quantity - Microwave Oven', 'debit': 33.33, 'credit': 0.0}, {'name': 'split by quantity - Microwave Oven', 'debit': 0.0, 'credit': 33.33}, {'name': 'equal split - Microwave Oven', 'debit': 2.5, 'credit': 0.0}, {'name': 'equal split - Microwave Oven', 'debit': 0.0, 'credit': 2.5}, {'name': 'split by volume - Refrigerator: 2.0 already out', 'debit': 0.5, 'credit': 0.0}, {'name': 'split by volume - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 0.5}, {'name': 'split by weight - Refrigerator: 2.0 already out', 'debit': 4.0, 'credit': 0.0}, {'name': 'split by weight - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 4.0}, {'name': 'split by weight - Refrigerator', 'debit': 0.0, 'credit': 10.0}, {'name': 'split by weight - Refrigerator', 'debit': 10.0, 'credit': 0.0}, {'name': 'split by volume - Refrigerator', 'debit': 0.0, 'credit': 1.25}, {'name': 'split by volume - Refrigerator', 'debit': 1.25, 'credit': 0.0}, {'name': 'split by quantity - Refrigerator: 2.0 already out', 'debit': 6.67, 'credit': 0.0}, {'name': 'split by quantity - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 6.67}, {'name': 'split by quantity - Refrigerator', 'debit': 16.67, 'credit': 0.0}, {'name': 'split by quantity - Refrigerator', 'debit': 0.0, 'credit': 16.67}, {'name': 'equal split - Refrigerator: 2.0 already out', 'debit': 1.0, 'credit': 0.0}, {'name': 'equal split - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 1.0}, {'name': 'equal split - Refrigerator', 'debit': 2.5, 'credit': 0.0}, {'name': 'equal split - Refrigerator', 'debit': 0.0, 'credit': 2.5} ] if stock_negative_landed_cost.account_move_id.company_id.anglo_saxon_accounting: move_lines += [ {'name': 'split by volume - Refrigerator: 2.0 already out', 'debit': 0.5, 'credit': 0.0}, {'name': 'split by volume - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 0.5}, {'name': 'split by weight - Refrigerator: 2.0 already out', 'debit': 4.0, 'credit': 0.0}, {'name': 'split by weight - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 4.0}, {'name': 'split by quantity - Refrigerator: 2.0 already out', 'debit': 6.67, 'credit': 0.0}, {'name': 'split by quantity - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 6.67}, {'name': 'equal split - Refrigerator: 2.0 already out', 'debit': 1.0, 'credit': 0.0}, {'name': 'equal split - Refrigerator: 2.0 already out', 'debit': 0.0, 'credit': 1.0}, ] self.assertRecordValues( sorted(stock_negative_landed_cost.account_move_id.line_ids, key=lambda d: (d['name'], d['debit'])), sorted(move_lines, key=lambda d: (d['name'], d['debit'])), ) def _process_incoming_shipment(self): """ Two product incoming shipment. """ # Confirm incoming shipment. self.picking_in.action_confirm() # Transfer incoming shipment res_dict = self.picking_in.button_validate() wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict.get('context'))).save() wizard.process() return self.picking_in def _process_outgoing_shipment(self): """ One product Outgoing shipment. """ # Confirm outgoing shipment. self.picking_out.action_confirm() # Product assign to outgoing shipments self.picking_out.action_assign() # Transfer picking. res_dict = self.picking_out.button_validate() wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save() wizard.process() def _create_landed_costs(self, value, picking_in): return self.LandedCost.create(dict( picking_ids=[(6, 0, [picking_in.id])], account_journal_id=self.expenses_journal.id, cost_lines=[ (0, 0, { 'name': 'equal split', 'split_method': 'equal', 'price_unit': value['equal_price_unit'], 'product_id': self.landed_cost.id}), (0, 0, { 'name': 'split by quantity', 'split_method': 'by_quantity', 'price_unit': value['quantity_price_unit'], 'product_id': self.brokerage_quantity.id}), (0, 0, { 'name': 'split by weight', 'split_method': 'by_weight', 'price_unit': value['weight_price_unit'], 'product_id': self.transportation_weight.id}), (0, 0, { 'name': 'split by volume', 'split_method': 'by_volume', 'price_unit': value['volume_price_unit'], 'product_id': self.packaging_volume.id}) ], )) def _validate_additional_landed_cost_lines(self, stock_landed_cost, valid_vals): for valuation in stock_landed_cost.valuation_adjustment_lines: add_cost = valuation.additional_landed_cost split_method = valuation.cost_line_id.split_method product = valuation.move_id.product_id if split_method == 'equal': self.assertEqual(add_cost, valid_vals['equal'], self._error_message(valid_vals['equal'], add_cost)) elif split_method == 'by_quantity' and product == self.product_refrigerator: self.assertEqual(add_cost, valid_vals['by_quantity_refrigerator'], self._error_message(valid_vals['by_quantity_refrigerator'], add_cost)) elif split_method == 'by_quantity' and product == self.product_oven: self.assertEqual(add_cost, valid_vals['by_quantity_oven'], self._error_message(valid_vals['by_quantity_oven'], add_cost)) elif split_method == 'by_weight' and product == self.product_refrigerator: self.assertEqual(add_cost, valid_vals['by_weight_refrigerator'], self._error_message(valid_vals['by_weight_refrigerator'], add_cost)) elif split_method == 'by_weight' and product == self.product_oven: self.assertEqual(add_cost, valid_vals['by_weight_oven'], self._error_message(valid_vals['by_weight_oven'], add_cost)) elif split_method == 'by_volume' and product == self.product_refrigerator: self.assertEqual(add_cost, valid_vals['by_volume_refrigerator'], self._error_message(valid_vals['by_volume_refrigerator'], add_cost)) elif split_method == 'by_volume' and product == self.product_oven: self.assertEqual(add_cost, valid_vals['by_volume_oven'], self._error_message(valid_vals['by_volume_oven'], add_cost)) def _error_message(self, actucal_cost, computed_cost): return 'Additional Landed Cost should be %s instead of %s' % (actucal_cost, computed_cost) @tagged('post_install', '-at_install') class TestLandedCostsWithPurchaseAndInv(TestStockValuationLCCommon): def test_invoice_after_lc(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.price_diff_account = self.env['account.account'].create({ 'name': 'price diff account', 'code': 'price diff account', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, }) self.product1.property_account_creditor_price_difference = self.price_diff_account # Create PO po_form = Form(self.env['purchase.order']) po_form.partner_id = self.env['res.partner'].create({'name': 'vendor'}) with po_form.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 1 po_line.price_unit = 455.0 order = po_form.save() order.button_confirm() # Receive the goods receipt = order.picking_ids[0] receipt.move_lines.quantity_done = 1 receipt.button_validate() # Check SVL and AML svl = self.env['stock.valuation.layer'].search([('stock_move_id', '=', receipt.move_lines.id)]) self.assertAlmostEqual(svl.value, 455) aml = self.env['account.move.line'].search([('account_id', '=', self.company_data['default_account_stock_valuation'].id)]) self.assertAlmostEqual(aml.debit, 455) # Create and validate LC lc = self.env['stock.landed.cost'].create(dict( picking_ids=[(6, 0, [receipt.id])], account_journal_id=self.stock_journal.id, cost_lines=[ (0, 0, { 'name': 'equal split', 'split_method': 'equal', 'price_unit': 99, 'product_id': self.productlc1.id, }), ], )) lc.compute_landed_cost() lc.button_validate() # Check LC, SVL and AML self.assertAlmostEqual(lc.valuation_adjustment_lines.final_cost, 554) svl = self.env['stock.valuation.layer'].search([('stock_move_id', '=', receipt.move_lines.id)], order='id desc', limit=1) self.assertAlmostEqual(svl.value, 99) aml = self.env['account.move.line'].search([('account_id', '=', self.company_data['default_account_stock_valuation'].id)], order='id desc', limit=1) self.assertAlmostEqual(aml.debit, 99) # Create an invoice with the same price move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.invoice_date = move_form.date move_form.partner_id = order.partner_id move_form.purchase_id = order move = move_form.save() move.action_post() # Check nothing was posted in the price difference account price_diff_aml = self.env['account.move.line'].search([('account_id','=', self.price_diff_account.id), ('move_id', '=', move.id)]) self.assertEqual(len(price_diff_aml), 0, "No line should have been generated in the price difference account.")
53.287411
22,434
12,700
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock_landed_costs.tests.common import TestStockLandedCostsCommon from odoo.tests import tagged, Form @tagged('post_install', '-at_install') class TestStockLandedCostsRounding(TestStockLandedCostsCommon): def test_stock_landed_costs_rounding(self): # In order to test the rounding in landed costs feature of stock, I create 2 landed cost # Define undivisible units product_uom_unit_round_1 = self.env.ref('uom.product_uom_unit') product_uom_unit_round_1.write({ 'name': 'Undivisible Units', 'rounding': 1.0, }) # I create 2 products with different cost prices and configure them for real_time # valuation and real price costing method product_landed_cost_3 = self.env['product.product'].create({ 'name': "LC product 3", 'uom_id': product_uom_unit_round_1.id, }) product_landed_cost_3.product_tmpl_id.categ_id.property_cost_method = 'fifo' product_landed_cost_3.product_tmpl_id.categ_id.property_stock_account_input_categ_id = self.company_data['default_account_expense'] product_landed_cost_3.product_tmpl_id.categ_id.property_stock_account_output_categ_id = self.company_data['default_account_revenue'] product_landed_cost_4 = self.env['product.product'].create({ 'name': "LC product 4", 'uom_id': product_uom_unit_round_1.id, }) product_landed_cost_4.product_tmpl_id.categ_id.property_cost_method = 'fifo' product_landed_cost_4.product_tmpl_id.categ_id.property_valuation = 'real_time' product_landed_cost_4.product_tmpl_id.categ_id.property_stock_account_input_categ_id = self.company_data['default_account_expense'] product_landed_cost_4.product_tmpl_id.categ_id.property_stock_account_output_categ_id = self.company_data['default_account_revenue'] picking_default_vals = self.env['stock.picking'].default_get(list(self.env['stock.picking'].fields_get())) # I create 2 pickings moving those products vals = dict(picking_default_vals, **{ 'name': 'LC_pick_3', 'picking_type_id': self.warehouse.in_type_id.id, 'move_lines': [(0, 0, { 'product_id': product_landed_cost_3.id, 'product_uom_qty': 13, 'product_uom': product_uom_unit_round_1.id, 'location_id': self.ref('stock.stock_location_customers'), 'location_dest_id': self.warehouse.lot_stock_id.id, })], }) picking_landed_cost_3 = self.env['stock.picking'].new(vals) picking_landed_cost_3._onchange_picking_type() picking_landed_cost_3.move_lines._onchange_product_id() picking_landed_cost_3.move_lines.name = 'move 3' vals = picking_landed_cost_3._convert_to_write(picking_landed_cost_3._cache) picking_landed_cost_3 = self.env['stock.picking'].create(vals) vals = dict(picking_default_vals, **{ 'name': 'LC_pick_4', 'picking_type_id': self.warehouse.in_type_id.id, 'move_lines': [(0, 0, { 'product_id': product_landed_cost_4.id, 'product_uom_qty': 1, 'product_uom': self.ref('uom.product_uom_dozen'), 'location_id': self.ref('stock.stock_location_customers'), 'location_dest_id': self.warehouse.lot_stock_id.id, 'price_unit': 17.00 / 12.00, })], }) picking_landed_cost_4 = self.env['stock.picking'].new(vals) picking_landed_cost_4._onchange_picking_type() picking_landed_cost_4.move_lines._onchange_product_id() picking_landed_cost_4.move_lines.name = 'move 4' vals = picking_landed_cost_4._convert_to_write(picking_landed_cost_4._cache) picking_landed_cost_4 = self.env['stock.picking'].create(vals) # We perform all the tests for LC_pick_3 # I receive picking LC_pick_3, and check how many quants are created picking_landed_cost_3.move_lines.price_unit = 1.0 picking_landed_cost_3.action_confirm() picking_landed_cost_3.action_assign() picking_landed_cost_3._action_done() virtual_interior_design = self.env['product.product'].create({'name': 'Virtual Interior Design'}) # I create a landed cost for picking 3 default_vals = self.env['stock.landed.cost'].default_get(list(self.env['stock.landed.cost'].fields_get())) default_vals.update({ 'picking_ids': [picking_landed_cost_3.id], 'account_journal_id': self.expenses_journal, 'cost_lines': [(0, 0, {'product_id': virtual_interior_design.id})], 'valuation_adjustment_lines': [], }) stock_landed_cost_2 = self.env['stock.landed.cost'].new(default_vals) stock_landed_cost_2.cost_lines.onchange_product_id() stock_landed_cost_2.cost_lines.name = 'equal split' stock_landed_cost_2.cost_lines.split_method = 'equal' stock_landed_cost_2.cost_lines.price_unit = 15 vals = stock_landed_cost_2._convert_to_write(stock_landed_cost_2._cache) stock_landed_cost_2 = self.env['stock.landed.cost'].create(vals) # I compute the landed cost using Compute button stock_landed_cost_2.compute_landed_cost() # I check the valuation adjustment lines for valuation in stock_landed_cost_2.valuation_adjustment_lines: self.assertEqual(valuation.additional_landed_cost, 15) # I confirm the landed cost stock_landed_cost_2.button_validate() # I check that the landed cost is now "Closed" and that it has an accounting entry self.assertEqual(stock_landed_cost_2.state, 'done') self.assertTrue(stock_landed_cost_2.account_move_id) # We perform all the tests for LC_pick_4 # I receive picking LC_pick_4, and check how many quants are created picking_landed_cost_4.move_lines.price_unit = 17.0/12.0 picking_landed_cost_4.action_confirm() picking_landed_cost_4.action_assign() picking_landed_cost_4._action_done() # I create a landed cost for picking 4 default_vals = self.env['stock.landed.cost'].default_get(list(self.env['stock.landed.cost'].fields_get())) default_vals.update({ 'picking_ids': [picking_landed_cost_4.id], 'account_journal_id': self.expenses_journal, 'cost_lines': [(0, 0, {'product_id': virtual_interior_design.id})], 'valuation_adjustment_lines': [], }) stock_landed_cost_3 = self.env['stock.landed.cost'].new(default_vals) stock_landed_cost_3.cost_lines.onchange_product_id() stock_landed_cost_3.cost_lines.name = 'equal split' stock_landed_cost_3.cost_lines.split_method = 'equal' stock_landed_cost_3.cost_lines.price_unit = 11 vals = stock_landed_cost_3._convert_to_write(stock_landed_cost_3._cache) stock_landed_cost_3 = self.env['stock.landed.cost'].create(vals) # I compute the landed cost using Compute button stock_landed_cost_3.compute_landed_cost() # I check the valuation adjustment lines for valuation in stock_landed_cost_3.valuation_adjustment_lines: self.assertEqual(valuation.additional_landed_cost, 11) # I confirm the landed cost stock_landed_cost_3.button_validate() # I check that the landed cost is now "Closed" and that it has an accounting entry self.assertEqual(stock_landed_cost_3.state, 'done') self.assertTrue(stock_landed_cost_3.account_move_id) def test_stock_landed_costs_rounding_02(self): """ The landed costs should be correctly computed, even when the decimal accuracy of the deciaml price is increased. """ self.env.ref("product.decimal_price").digits = 4 fifo_pc = self.env['product.category'].create({ 'name': 'Fifo Category', 'parent_id': self.env.ref("product.product_category_all").id, 'property_valuation': 'real_time', 'property_cost_method': 'fifo', }) products = self.Product.create([{ 'name': 'Super Product %s' % price, 'categ_id': fifo_pc.id, 'type': 'product', 'standard_price': price, } for price in [0.91, 0.93, 75.17, 20.54]]) landed_product = self.Product.create({ 'name': 'Landed Costs', 'type': 'service', 'landed_cost_ok': True, 'split_method_landed_cost': 'by_quantity', 'standard_price': 1000.0, }) po = self.env['purchase.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [(0, 0, { 'product_id': product.id, 'product_qty': qty, 'price_unit': product.standard_price, }) for product, qty in zip(products, [6, 6, 3, 6])] }) po.button_confirm() res_dict = po.picking_ids.button_validate() validate_wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict.get('context'))).save() validate_wizard.process() lc_form = Form(self.LandedCost) lc_form.picking_ids.add(po.picking_ids) with lc_form.cost_lines.new() as line: line.product_id = landed_product lc = lc_form.save() lc.compute_landed_cost() self.assertEqual(sum(lc.valuation_adjustment_lines.mapped('additional_landed_cost')), 1000.0) def test_stock_landed_costs_rounding_03(self): """ Storable AVCO product Receive: 5 @ 5 5 @ 8 5 @ 7 20 @ 7.33 Add landed cost of $5 to each receipt (except the first one) Deliver: 23 2 10 At the end, the SVL value should be zero """ self.product_a.type = 'product' self.product_a.categ_id.property_cost_method = 'average' stock_location = self.warehouse.lot_stock_id supplier_location_id = self.ref('stock.stock_location_suppliers') customer_location_id = self.ref('stock.stock_location_customers') receipts = self.env['stock.picking'].create([{ 'picking_type_id': self.warehouse.in_type_id.id, 'location_id': supplier_location_id, 'location_dest_id': stock_location.id, 'move_lines': [(0, 0, { 'name': self.product_a.name, 'product_id': self.product_a.id, 'price_unit': price, 'product_uom': self.product_a.uom_id.id, 'product_uom_qty': qty, 'location_id': supplier_location_id, 'location_dest_id': stock_location.id, })] } for qty, price in [ (5, 5.0), (5, 8.0), (5, 7.0), (20, 7.33), ]]) receipts.action_confirm() for m in receipts.move_lines: m.quantity_done = m.product_uom_qty receipts.button_validate() landed_costs = self.env['stock.landed.cost'].create([{ 'picking_ids': [(6, 0, picking.ids)], 'account_journal_id': self.expenses_journal.id, 'cost_lines': [(0, 0, { 'name': 'equal split', 'split_method': 'equal', 'price_unit': 5.0, 'product_id': self.landed_cost.id })], } for picking in receipts[1:]]) landed_costs.compute_landed_cost() landed_costs.button_validate() self.assertEqual(self.product_a.standard_price, 7.47) deliveries = self.env['stock.picking'].create([{ 'picking_type_id': self.warehouse.out_type_id.id, 'location_id': stock_location.id, 'location_dest_id': customer_location_id, 'move_lines': [(0, 0, { 'name': self.product_a.name, 'product_id': self.product_a.id, 'product_uom': self.product_a.uom_id.id, 'product_uom_qty': qty, 'location_id': stock_location.id, 'location_dest_id': customer_location_id, })] } for qty in [23, 2, 10]]) deliveries.action_confirm() for m in deliveries.move_lines: m.quantity_done = m.product_uom_qty deliveries.button_validate() self.assertEqual(self.product_a.value_svl, 0)
44.250871
12,700
10,488
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock_landed_costs.tests.common import TestStockLandedCostsCommon from odoo.exceptions import ValidationError from odoo.tests import tagged from odoo import fields @tagged('post_install', '-at_install') class TestStockLandedCosts(TestStockLandedCostsCommon): def test_stock_landed_costs(self): # In order to test the landed costs feature of stock, # I create a landed cost, confirm it and check its account move created # I create 2 products with different volume and gross weight and configure # them for real_time valuation and fifo costing method product_landed_cost_1 = self.env['product.product'].create({ 'name': "LC product 1", 'weight': 10, 'volume': 1, 'categ_id': self.stock_account_product_categ.id, 'type': 'product', }) product_landed_cost_2 = self.env['product.product'].create({ 'name': "LC product 2", 'weight': 20, 'volume': 1.5, 'categ_id': self.stock_account_product_categ.id, 'type': 'product', }) self.assertEqual(product_landed_cost_1.value_svl, 0) self.assertEqual(product_landed_cost_1.quantity_svl, 0) self.assertEqual(product_landed_cost_2.value_svl, 0) self.assertEqual(product_landed_cost_2.quantity_svl, 0) picking_default_vals = self.env['stock.picking'].default_get(list(self.env['stock.picking'].fields_get())) # I create 2 picking moving those products vals = dict(picking_default_vals, **{ 'name': 'LC_pick_1', 'picking_type_id': self.warehouse.out_type_id.id, 'move_lines': [(0, 0, { 'product_id': product_landed_cost_1.id, 'product_uom_qty': 5, 'product_uom': self.ref('uom.product_uom_unit'), 'location_id': self.warehouse.lot_stock_id.id, 'location_dest_id': self.ref('stock.stock_location_customers'), })], }) picking_landed_cost_1 = self.env['stock.picking'].new(vals) picking_landed_cost_1._onchange_picking_type() picking_landed_cost_1.move_lines._onchange_product_id() picking_landed_cost_1.move_lines.name = 'move 1' vals = picking_landed_cost_1._convert_to_write(picking_landed_cost_1._cache) picking_landed_cost_1 = self.env['stock.picking'].create(vals) # Confirm and assign picking self.env.company.anglo_saxon_accounting = True picking_landed_cost_1.action_confirm() picking_landed_cost_1.action_assign() picking_landed_cost_1.move_lines.quantity_done = 5 picking_landed_cost_1.button_validate() vals = dict(picking_default_vals, **{ 'name': 'LC_pick_2', 'picking_type_id': self.warehouse.out_type_id.id, 'move_lines': [(0, 0, { 'product_id': product_landed_cost_2.id, 'product_uom_qty': 10, 'product_uom': self.ref('uom.product_uom_unit'), 'location_id': self.warehouse.lot_stock_id.id, 'location_dest_id': self.ref('stock.stock_location_customers'), })], }) picking_landed_cost_2 = self.env['stock.picking'].new(vals) picking_landed_cost_2._onchange_picking_type() picking_landed_cost_2.move_lines._onchange_product_id() picking_landed_cost_2.move_lines.name = 'move 2' vals = picking_landed_cost_2._convert_to_write(picking_landed_cost_2._cache) picking_landed_cost_2 = self.env['stock.picking'].create(vals) # Confirm and assign picking picking_landed_cost_2.action_confirm() picking_landed_cost_2.action_assign() picking_landed_cost_2.move_lines.quantity_done = 10 picking_landed_cost_2.button_validate() self.assertEqual(product_landed_cost_1.value_svl, 0) self.assertEqual(product_landed_cost_1.quantity_svl, -5) self.assertEqual(product_landed_cost_2.value_svl, 0) self.assertEqual(product_landed_cost_2.quantity_svl, -10) # I create a landed cost for those 2 pickings default_vals = self.env['stock.landed.cost'].default_get(list(self.env['stock.landed.cost'].fields_get())) virtual_home_staging = self.env['product.product'].create({ 'name': 'Virtual Home Staging', 'categ_id': self.stock_account_product_categ.id, }) default_vals.update({ 'picking_ids': [picking_landed_cost_1.id, picking_landed_cost_2.id], 'account_journal_id': self.expenses_journal, 'cost_lines': [ (0, 0, {'product_id': virtual_home_staging.id}), (0, 0, {'product_id': virtual_home_staging.id}), (0, 0, {'product_id': virtual_home_staging.id}), (0, 0, {'product_id': virtual_home_staging.id})], 'valuation_adjustment_lines': [], }) cost_lines_values = { 'name': ['equal split', 'split by quantity', 'split by weight', 'split by volume'], 'split_method': ['equal', 'by_quantity', 'by_weight', 'by_volume'], 'price_unit': [10, 150, 250, 20], } stock_landed_cost_1 = self.env['stock.landed.cost'].new(default_vals) for index, cost_line in enumerate(stock_landed_cost_1.cost_lines): cost_line.onchange_product_id() cost_line.name = cost_lines_values['name'][index] cost_line.split_method = cost_lines_values['split_method'][index] cost_line.price_unit = cost_lines_values['price_unit'][index] vals = stock_landed_cost_1._convert_to_write(stock_landed_cost_1._cache) stock_landed_cost_1 = self.env['stock.landed.cost'].create(vals) # I compute the landed cost using Compute button stock_landed_cost_1.compute_landed_cost() # I check the valuation adjustment lines for valuation in stock_landed_cost_1.valuation_adjustment_lines: if valuation.cost_line_id.name == 'equal split': self.assertEqual(valuation.additional_landed_cost, 5) elif valuation.cost_line_id.name == 'split by quantity' and valuation.move_id.name == "move 1": self.assertEqual(valuation.additional_landed_cost, 50) elif valuation.cost_line_id.name == 'split by quantity' and valuation.move_id.name == "move 2": self.assertEqual(valuation.additional_landed_cost, 100) elif valuation.cost_line_id.name == 'split by weight' and valuation.move_id.name == "move 1": self.assertEqual(valuation.additional_landed_cost, 50) elif valuation.cost_line_id.name == 'split by weight' and valuation.move_id.name == "move 2": self.assertEqual(valuation.additional_landed_cost, 200) elif valuation.cost_line_id.name == 'split by volume' and valuation.move_id.name == "move 1": self.assertEqual(valuation.additional_landed_cost, 5) elif valuation.cost_line_id.name == 'split by volume' and valuation.move_id.name == "move 2": self.assertEqual(valuation.additional_landed_cost, 15) else: raise ValidationError('unrecognized valuation adjustment line') # I confirm the landed cost stock_landed_cost_1.button_validate() # I check that the landed cost is now "Closed" and that it has an accounting entry self.assertEqual(stock_landed_cost_1.state, "done") self.assertTrue(stock_landed_cost_1.account_move_id) self.assertEqual(len(stock_landed_cost_1.account_move_id.line_ids), 48) lc_value = sum(stock_landed_cost_1.account_move_id.line_ids.filtered(lambda aml: aml.account_id.name.startswith('Expenses')).mapped('debit')) product_value = abs(product_landed_cost_1.value_svl) + abs(product_landed_cost_2.value_svl) self.assertEqual(lc_value, product_value) self.assertEqual(len(picking_landed_cost_1.move_lines.stock_valuation_layer_ids), 5) self.assertEqual(len(picking_landed_cost_2.move_lines.stock_valuation_layer_ids), 5) def test_aml_account_selection(self): """ Process a PO with a landed cost, then create and post the bill. The account of the landed cost AML should be: - Expense if the categ valuation is manual - Stock IN if the categ valuation is real time """ self.landed_cost.landed_cost_ok = True for valuation, account in [ ('manual_periodic', self.company_data['default_account_expense']), ('real_time', self.env.company.property_stock_account_input_categ_id), ]: self.landed_cost.categ_id.property_valuation = valuation po = self.env['purchase.order'].create({ 'partner_id': self.partner_a.id, 'currency_id': self.company_data['currency'].id, 'order_line': [ (0, 0, { 'name': self.product_a.name, 'product_id': self.product_a.id, 'product_qty': 1.0, 'product_uom': self.product_a.uom_po_id.id, 'price_unit': 100.0, 'taxes_id': False, }), (0, 0, { 'name': self.landed_cost.name, 'product_id': self.landed_cost.id, 'product_qty': 1.0, 'price_unit': 100.0, }), ], }) po.button_confirm() receipt = po.picking_ids receipt.move_lines.quantity_done = 1 receipt.button_validate() po.order_line[1].qty_received = 1 po.action_create_invoice() bill = po.invoice_ids bill.invoice_date = fields.Date.today() bill._post() landed_cost_aml = bill.invoice_line_ids.filtered(lambda l: l.product_id == self.landed_cost) self.assertEqual(bill.state, 'posted', 'Incorrect value with valuation %s' % valuation) self.assertEqual(landed_cost_aml.account_id, account, 'Incorrect value with valuation %s' % valuation)
49.471698
10,488
328
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 StockValuationLayer(models.Model): """Stock Valuation Layer""" _inherit = 'stock.valuation.layer' stock_landed_cost_id = fields.Many2one('stock.landed.cost', 'Landed Cost')
25.230769
328
3,746
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 AccountMove(models.Model): _inherit = 'account.move' landed_costs_ids = fields.One2many('stock.landed.cost', 'vendor_bill_id', string='Landed Costs') landed_costs_visible = fields.Boolean(compute='_compute_landed_costs_visible') @api.depends('line_ids', 'line_ids.is_landed_costs_line') def _compute_landed_costs_visible(self): for account_move in self: if account_move.landed_costs_ids: account_move.landed_costs_visible = False else: account_move.landed_costs_visible = any(line.is_landed_costs_line for line in account_move.line_ids) def button_create_landed_costs(self): """Create a `stock.landed.cost` record associated to the account move of `self`, each `stock.landed.costs` lines mirroring the current `account.move.line` of self. """ self.ensure_one() landed_costs_lines = self.line_ids.filtered(lambda line: line.is_landed_costs_line) landed_costs = self.env['stock.landed.cost'].create({ 'vendor_bill_id': self.id, 'cost_lines': [(0, 0, { 'product_id': l.product_id.id, 'name': l.product_id.name, 'account_id': l.product_id.product_tmpl_id.get_product_accounts()['stock_input'].id, 'price_unit': l.currency_id._convert(l.price_subtotal, l.company_currency_id, l.company_id, l.move_id.date), 'split_method': l.product_id.split_method_landed_cost or 'equal', }) for l in landed_costs_lines], }) action = self.env["ir.actions.actions"]._for_xml_id("stock_landed_costs.action_stock_landed_cost") return dict(action, view_mode='form', res_id=landed_costs.id, views=[(False, 'form')]) def action_view_landed_costs(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("stock_landed_costs.action_stock_landed_cost") domain = [('id', 'in', self.landed_costs_ids.ids)] context = dict(self.env.context, default_vendor_bill_id=self.id) views = [(self.env.ref('stock_landed_costs.view_stock_landed_cost_tree2').id, 'tree'), (False, 'form'), (False, 'kanban')] return dict(action, domain=domain, context=context, views=views) class AccountMoveLine(models.Model): _inherit = 'account.move.line' product_type = fields.Selection(related='product_id.detailed_type', readonly=True) is_landed_costs_line = fields.Boolean() @api.onchange('is_landed_costs_line') def _onchange_is_landed_costs_line(self): """Mark an invoice line as a landed cost line and adapt `self.account_id`. The default value can be set according to `self.product_id.landed_cost_ok`.""" if self.product_id: accounts = self.product_id.product_tmpl_id._get_product_accounts() aml_account = accounts['expense'] if self.product_type != 'service': self.is_landed_costs_line = False elif self.is_landed_costs_line: aml_account = (self.move_id.company_id.anglo_saxon_accounting and accounts['stock_input']) or aml_account self.account_id = aml_account @api.onchange('product_id') def _onchange_is_landed_costs_line_product(self): if self.product_id.landed_cost_ok: self.is_landed_costs_line = True else: self.is_landed_costs_line = False def _can_use_stock_accounts(self): return super()._can_use_stock_accounts() or (self.product_id.type == 'service' and self.product_id.landed_cost_ok)
48.649351
3,746
311
py
PYTHON
15.0
from odoo import api,models class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' def _prepare_account_move_line(self, move=False): res = super()._prepare_account_move_line(move) res.update({'is_landed_costs_line': self.product_id.landed_cost_ok}) return res
34.555556
311
252
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResCompany(models.Model): _inherit = 'res.company' lc_journal_id = fields.Many2one('account.journal')
22.909091
252
1,276
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ from odoo.addons.stock_landed_costs.models.stock_landed_cost import SPLIT_METHOD from odoo.exceptions import UserError class ProductTemplate(models.Model): _inherit = "product.template" landed_cost_ok = fields.Boolean('Is a Landed Cost', help='Indicates whether the product is a landed cost.') split_method_landed_cost = fields.Selection(SPLIT_METHOD, string="Default Split Method", help="Default Split Method when used for Landed Cost") def write(self, vals): for product in self: if (('type' in vals and vals['type'] != 'service') or ('landed_cost_ok' in vals and not vals['landed_cost_ok'])) and product.type == 'service' and product.landed_cost_ok: if self.env['account.move.line'].search_count([('product_id', 'in', product.product_variant_ids.ids), ('is_landed_costs_line', '=', True)]): raise UserError(_("You cannot change the product type or disable landed cost option because the product is used in an account move line.")) vals['landed_cost_ok'] = False return super().write(vals)
55.478261
1,276
354
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' lc_journal_id = fields.Many2one('account.journal', string='Default Journal', related='company_id.lc_journal_id', readonly=False)
32.181818
354
22,839
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from odoo import api, fields, models, tools, _ from odoo.exceptions import UserError from odoo.tools.float_utils import float_is_zero SPLIT_METHOD = [ ('equal', 'Equal'), ('by_quantity', 'By Quantity'), ('by_current_cost_price', 'By Current Cost'), ('by_weight', 'By Weight'), ('by_volume', 'By Volume'), ] class StockLandedCost(models.Model): _name = 'stock.landed.cost' _description = 'Stock Landed Cost' _inherit = ['mail.thread', 'mail.activity.mixin'] def _default_account_journal_id(self): """Take the journal configured in the company, else fallback on the stock journal.""" lc_journal = self.env['account.journal'] if self.env.company.lc_journal_id: lc_journal = self.env.company.lc_journal_id else: lc_journal = self.env['ir.property']._get("property_stock_journal", "product.category") return lc_journal name = fields.Char( 'Name', default=lambda self: _('New'), copy=False, readonly=True, tracking=True) date = fields.Date( 'Date', default=fields.Date.context_today, copy=False, required=True, states={'done': [('readonly', True)]}, tracking=True) target_model = fields.Selection( [('picking', 'Transfers')], string="Apply On", required=True, default='picking', copy=False, states={'done': [('readonly', True)]}) picking_ids = fields.Many2many( 'stock.picking', string='Transfers', copy=False, states={'done': [('readonly', True)]}) cost_lines = fields.One2many( 'stock.landed.cost.lines', 'cost_id', 'Cost Lines', copy=True, states={'done': [('readonly', True)]}) valuation_adjustment_lines = fields.One2many( 'stock.valuation.adjustment.lines', 'cost_id', 'Valuation Adjustments', states={'done': [('readonly', True)]}) description = fields.Text( 'Item Description', states={'done': [('readonly', True)]}) amount_total = fields.Monetary( 'Total', compute='_compute_total_amount', store=True, tracking=True) state = fields.Selection([ ('draft', 'Draft'), ('done', 'Posted'), ('cancel', 'Cancelled')], 'State', default='draft', copy=False, readonly=True, tracking=True) account_move_id = fields.Many2one( 'account.move', 'Journal Entry', copy=False, readonly=True) account_journal_id = fields.Many2one( 'account.journal', 'Account Journal', required=True, states={'done': [('readonly', True)]}, default=lambda self: self._default_account_journal_id()) company_id = fields.Many2one('res.company', string="Company", related='account_journal_id.company_id') stock_valuation_layer_ids = fields.One2many('stock.valuation.layer', 'stock_landed_cost_id') vendor_bill_id = fields.Many2one( 'account.move', 'Vendor Bill', copy=False, domain=[('move_type', '=', 'in_invoice')]) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') @api.depends('cost_lines.price_unit') def _compute_total_amount(self): for cost in self: cost.amount_total = sum(line.price_unit for line in cost.cost_lines) @api.onchange('target_model') def _onchange_target_model(self): if self.target_model != 'picking': self.picking_ids = False @api.model def create(self, vals): if vals.get('name', _('New')) == _('New'): vals['name'] = self.env['ir.sequence'].next_by_code('stock.landed.cost') return super().create(vals) def unlink(self): self.button_cancel() return super().unlink() def _track_subtype(self, init_values): if 'state' in init_values and self.state == 'done': return self.env.ref('stock_landed_costs.mt_stock_landed_cost_open') return super()._track_subtype(init_values) def button_cancel(self): if any(cost.state == 'done' for cost in self): raise UserError( _('Validated landed costs cannot be cancelled, but you could create negative landed costs to reverse them')) return self.write({'state': 'cancel'}) def button_validate(self): self._check_can_validate() cost_without_adjusment_lines = self.filtered(lambda c: not c.valuation_adjustment_lines) if cost_without_adjusment_lines: cost_without_adjusment_lines.compute_landed_cost() if not self._check_sum(): raise UserError(_('Cost and adjustments lines do not match. You should maybe recompute the landed costs.')) for cost in self: cost = cost.with_company(cost.company_id) move = self.env['account.move'] move_vals = { 'journal_id': cost.account_journal_id.id, 'date': cost.date, 'ref': cost.name, 'line_ids': [], 'move_type': 'entry', } valuation_layer_ids = [] cost_to_add_byproduct = defaultdict(lambda: 0.0) for line in cost.valuation_adjustment_lines.filtered(lambda line: line.move_id): remaining_qty = sum(line.move_id.stock_valuation_layer_ids.mapped('remaining_qty')) linked_layer = line.move_id.stock_valuation_layer_ids[:1] # Prorate the value at what's still in stock cost_to_add = (remaining_qty / line.move_id.product_qty) * line.additional_landed_cost if not cost.company_id.currency_id.is_zero(cost_to_add): valuation_layer = self.env['stock.valuation.layer'].create({ 'value': cost_to_add, 'unit_cost': 0, 'quantity': 0, 'remaining_qty': 0, 'stock_valuation_layer_id': linked_layer.id, 'description': cost.name, 'stock_move_id': line.move_id.id, 'product_id': line.move_id.product_id.id, 'stock_landed_cost_id': cost.id, 'company_id': cost.company_id.id, }) linked_layer.remaining_value += cost_to_add valuation_layer_ids.append(valuation_layer.id) # Update the AVCO product = line.move_id.product_id if product.cost_method == 'average': cost_to_add_byproduct[product] += cost_to_add # Products with manual inventory valuation are ignored because they do not need to create journal entries. if product.valuation != "real_time": continue # `remaining_qty` is negative if the move is out and delivered proudcts that were not # in stock. qty_out = 0 if line.move_id._is_in(): qty_out = line.move_id.product_qty - remaining_qty elif line.move_id._is_out(): qty_out = line.move_id.product_qty move_vals['line_ids'] += line._create_accounting_entries(move, qty_out) # batch standard price computation avoid recompute quantity_svl at each iteration products = self.env['product.product'].browse(p.id for p in cost_to_add_byproduct.keys()) for product in products: # iterate on recordset to prefetch efficiently quantity_svl if not float_is_zero(product.quantity_svl, precision_rounding=product.uom_id.rounding): product.with_company(cost.company_id).sudo().with_context(disable_auto_svl=True).standard_price += cost_to_add_byproduct[product] / product.quantity_svl move_vals['stock_valuation_layer_ids'] = [(6, None, valuation_layer_ids)] # We will only create the accounting entry when there are defined lines (the lines will be those linked to products of real_time valuation category). cost_vals = {'state': 'done'} if move_vals.get("line_ids"): move = move.create(move_vals) cost_vals.update({'account_move_id': move.id}) cost.write(cost_vals) if cost.account_move_id: move._post() if cost.vendor_bill_id and cost.vendor_bill_id.state == 'posted' and cost.company_id.anglo_saxon_accounting: all_amls = cost.vendor_bill_id.line_ids | cost.account_move_id.line_ids for product in cost.cost_lines.product_id: accounts = product.product_tmpl_id.get_product_accounts() input_account = accounts['stock_input'] all_amls.filtered(lambda aml: aml.account_id == input_account and not aml.reconciled).reconcile() return True def get_valuation_lines(self): self.ensure_one() lines = [] for move in self._get_targeted_move_ids(): # it doesn't make sense to make a landed cost for a product that isn't set as being valuated in real time at real cost if move.product_id.cost_method not in ('fifo', 'average') or move.state == 'cancel' or not move.product_qty: continue vals = { 'product_id': move.product_id.id, 'move_id': move.id, 'quantity': move.product_qty, 'former_cost': sum(move.stock_valuation_layer_ids.mapped('value')), 'weight': move.product_id.weight * move.product_qty, 'volume': move.product_id.volume * move.product_qty } lines.append(vals) if not lines: target_model_descriptions = dict(self._fields['target_model']._description_selection(self.env)) raise UserError(_("You cannot apply landed costs on the chosen %s(s). Landed costs can only be applied for products with FIFO or average costing method.", target_model_descriptions[self.target_model])) return lines def compute_landed_cost(self): AdjustementLines = self.env['stock.valuation.adjustment.lines'] AdjustementLines.search([('cost_id', 'in', self.ids)]).unlink() towrite_dict = {} for cost in self.filtered(lambda cost: cost._get_targeted_move_ids()): rounding = cost.currency_id.rounding total_qty = 0.0 total_cost = 0.0 total_weight = 0.0 total_volume = 0.0 total_line = 0.0 all_val_line_values = cost.get_valuation_lines() for val_line_values in all_val_line_values: for cost_line in cost.cost_lines: val_line_values.update({'cost_id': cost.id, 'cost_line_id': cost_line.id}) self.env['stock.valuation.adjustment.lines'].create(val_line_values) total_qty += val_line_values.get('quantity', 0.0) total_weight += val_line_values.get('weight', 0.0) total_volume += val_line_values.get('volume', 0.0) former_cost = val_line_values.get('former_cost', 0.0) # round this because former_cost on the valuation lines is also rounded total_cost += cost.currency_id.round(former_cost) total_line += 1 for line in cost.cost_lines: value_split = 0.0 for valuation in cost.valuation_adjustment_lines: value = 0.0 if valuation.cost_line_id and valuation.cost_line_id.id == line.id: if line.split_method == 'by_quantity' and total_qty: per_unit = (line.price_unit / total_qty) value = valuation.quantity * per_unit elif line.split_method == 'by_weight' and total_weight: per_unit = (line.price_unit / total_weight) value = valuation.weight * per_unit elif line.split_method == 'by_volume' and total_volume: per_unit = (line.price_unit / total_volume) value = valuation.volume * per_unit elif line.split_method == 'equal': value = (line.price_unit / total_line) elif line.split_method == 'by_current_cost_price' and total_cost: per_unit = (line.price_unit / total_cost) value = valuation.former_cost * per_unit else: value = (line.price_unit / total_line) if rounding: value = tools.float_round(value, precision_rounding=rounding, rounding_method='UP') fnc = min if line.price_unit > 0 else max value = fnc(value, line.price_unit - value_split) value_split += value if valuation.id not in towrite_dict: towrite_dict[valuation.id] = value else: towrite_dict[valuation.id] += value for key, value in towrite_dict.items(): AdjustementLines.browse(key).write({'additional_landed_cost': value}) return True def action_view_stock_valuation_layers(self): self.ensure_one() domain = [('id', 'in', self.stock_valuation_layer_ids.ids)] action = self.env["ir.actions.actions"]._for_xml_id("stock_account.stock_valuation_layer_action") return dict(action, domain=domain) def _get_targeted_move_ids(self): return self.picking_ids.move_lines def _check_can_validate(self): if any(cost.state != 'draft' for cost in self): raise UserError(_('Only draft landed costs can be validated')) for cost in self: if not cost._get_targeted_move_ids(): target_model_descriptions = dict(self._fields['target_model']._description_selection(self.env)) raise UserError(_('Please define %s on which those additional costs should apply.', target_model_descriptions[cost.target_model])) def _check_sum(self): """ Check if each cost line its valuation lines sum to the correct amount and if the overall total amount is correct also """ prec_digits = self.env.company.currency_id.decimal_places for landed_cost in self: total_amount = sum(landed_cost.valuation_adjustment_lines.mapped('additional_landed_cost')) if not tools.float_is_zero(total_amount - landed_cost.amount_total, precision_digits=prec_digits): return False val_to_cost_lines = defaultdict(lambda: 0.0) for val_line in landed_cost.valuation_adjustment_lines: val_to_cost_lines[val_line.cost_line_id] += val_line.additional_landed_cost if any(not tools.float_is_zero(cost_line.price_unit - val_amount, precision_digits=prec_digits) for cost_line, val_amount in val_to_cost_lines.items()): return False return True class StockLandedCostLine(models.Model): _name = 'stock.landed.cost.lines' _description = 'Stock Landed Cost Line' name = fields.Char('Description') cost_id = fields.Many2one( 'stock.landed.cost', 'Landed Cost', required=True, ondelete='cascade') product_id = fields.Many2one('product.product', 'Product', required=True) price_unit = fields.Monetary('Cost', required=True) split_method = fields.Selection( SPLIT_METHOD, string='Split Method', required=True, help="Equal : Cost will be equally divided.\n" "By Quantity : Cost will be divided according to product's quantity.\n" "By Current cost : Cost will be divided according to product's current cost.\n" "By Weight : Cost will be divided depending on its weight.\n" "By Volume : Cost will be divided depending on its volume.") account_id = fields.Many2one('account.account', 'Account', domain=[('deprecated', '=', False)]) currency_id = fields.Many2one('res.currency', related='cost_id.currency_id') @api.onchange('product_id') def onchange_product_id(self): self.name = self.product_id.name or '' self.split_method = self.product_id.product_tmpl_id.split_method_landed_cost or self.split_method or 'equal' self.price_unit = self.product_id.standard_price or 0.0 accounts_data = self.product_id.product_tmpl_id.get_product_accounts() self.account_id = accounts_data['stock_input'] class AdjustmentLines(models.Model): _name = 'stock.valuation.adjustment.lines' _description = 'Valuation Adjustment Lines' name = fields.Char( 'Description', compute='_compute_name', store=True) cost_id = fields.Many2one( 'stock.landed.cost', 'Landed Cost', ondelete='cascade', required=True) cost_line_id = fields.Many2one( 'stock.landed.cost.lines', 'Cost Line', readonly=True) move_id = fields.Many2one('stock.move', 'Stock Move', readonly=True) product_id = fields.Many2one('product.product', 'Product', required=True) quantity = fields.Float( 'Quantity', default=1.0, digits=0, required=True) weight = fields.Float( 'Weight', default=1.0, digits='Stock Weight') volume = fields.Float( 'Volume', default=1.0, digits='Volume') former_cost = fields.Monetary( 'Original Value') additional_landed_cost = fields.Monetary( 'Additional Landed Cost') final_cost = fields.Monetary( 'New Value', compute='_compute_final_cost', store=True) currency_id = fields.Many2one('res.currency', related='cost_id.company_id.currency_id') @api.depends('cost_line_id.name', 'product_id.code', 'product_id.name') def _compute_name(self): for line in self: name = '%s - ' % (line.cost_line_id.name if line.cost_line_id else '') line.name = name + (line.product_id.code or line.product_id.name or '') @api.depends('former_cost', 'additional_landed_cost') def _compute_final_cost(self): for line in self: line.final_cost = line.former_cost + line.additional_landed_cost def _create_accounting_entries(self, move, qty_out): # TDE CLEANME: product chosen for computation ? cost_product = self.cost_line_id.product_id if not cost_product: return False accounts = self.product_id.product_tmpl_id.get_product_accounts() debit_account_id = accounts.get('stock_valuation') and accounts['stock_valuation'].id or False # If the stock move is dropshipped move we need to get the cost account instead the stock valuation account if self.move_id._is_dropshipped(): debit_account_id = accounts.get('expense') and accounts['expense'].id or False already_out_account_id = accounts['stock_output'].id credit_account_id = self.cost_line_id.account_id.id or cost_product.categ_id.property_stock_account_input_categ_id.id if not credit_account_id: raise UserError(_('Please configure Stock Expense Account for product: %s.') % (cost_product.name)) return self._create_account_move_line(move, credit_account_id, debit_account_id, qty_out, already_out_account_id) def _create_account_move_line(self, move, credit_account_id, debit_account_id, qty_out, already_out_account_id): """ Generate the account.move.line values to track the landed cost. Afterwards, for the goods that are already out of stock, we should create the out moves """ AccountMoveLine = [] base_line = { 'name': self.name, 'product_id': self.product_id.id, 'quantity': 0, } debit_line = dict(base_line, account_id=debit_account_id) credit_line = dict(base_line, account_id=credit_account_id) diff = self.additional_landed_cost if diff > 0: debit_line['debit'] = diff credit_line['credit'] = diff else: # negative cost, reverse the entry debit_line['credit'] = -diff credit_line['debit'] = -diff AccountMoveLine.append([0, 0, debit_line]) AccountMoveLine.append([0, 0, credit_line]) # Create account move lines for quants already out of stock if qty_out > 0: debit_line = dict(base_line, name=(self.name + ": " + str(qty_out) + _(' already out')), quantity=0, account_id=already_out_account_id) credit_line = dict(base_line, name=(self.name + ": " + str(qty_out) + _(' already out')), quantity=0, account_id=debit_account_id) diff = diff * qty_out / self.quantity if diff > 0: debit_line['debit'] = diff credit_line['credit'] = diff else: # negative cost, reverse the entry debit_line['credit'] = -diff credit_line['debit'] = -diff AccountMoveLine.append([0, 0, debit_line]) AccountMoveLine.append([0, 0, credit_line]) if self.env.company.anglo_saxon_accounting: expense_account_id = self.product_id.product_tmpl_id.get_product_accounts()['expense'].id debit_line = dict(base_line, name=(self.name + ": " + str(qty_out) + _(' already out')), quantity=0, account_id=expense_account_id) credit_line = dict(base_line, name=(self.name + ": " + str(qty_out) + _(' already out')), quantity=0, account_id=already_out_account_id) if diff > 0: debit_line['debit'] = diff credit_line['credit'] = diff else: # negative cost, reverse the entry debit_line['credit'] = -diff credit_line['debit'] = -diff AccountMoveLine.append([0, 0, debit_line]) AccountMoveLine.append([0, 0, credit_line]) return AccountMoveLine
48.905782
22,839
3,061
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. ############################################################################## # # l10n_cr_account # First author: Carlos Vásquez <carlos.vasquez@clearcorp.co.cr> (ClearCorp S.A.) # Copyright (c) 2010-TODAY ClearCorp S.A. (http://clearcorp.co.cr). All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are # permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list # of conditions and the following disclaimer in the documentation and/or other materials # provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED # WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are those of the # authors and should not be interpreted as representing official policies, either expressed # or implied, of ClearCorp S.A.. # ############################################################################## { 'name': 'Costa Rica - Accounting', 'url': 'https://github.com/CLEARCORP/odoo-costa-rica', 'author': 'ClearCorp S.A.', 'website': 'http://clearcorp.co.cr', 'category': 'Accounting/Localizations/Account Charts', 'description': """ Chart of accounts for Costa Rica. ================================= Includes: --------- * account.account.template * account.tax.template * account.chart.template Everything is in English with Spanish translation. Further translations are welcome, please go to http://translations.launchpad.net/openerp-costa-rica. """, 'depends': ['account'], 'data': [ 'data/l10n_cr_res_partner_title.xml', 'data/l10n_cr_chart_data.xml', 'data/account.account.template.csv', 'data/account_tax_group_data.xml', 'data/account_chart_template_data.xml', 'data/account_tax_template_data.xml', 'data/account_chart_template_configure_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
44.347826
3,060
665
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'UTM Trackers', 'category': 'Hidden', 'description': """ Enable management of UTM trackers: campaign, medium, source. """, 'version': '1.1', 'depends': ['base', 'web'], 'data': [ 'data/utm_data.xml', 'views/utm_campaign_views.xml', 'views/utm_views.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/utm_demo.xml', ], 'auto_install': False, 'assets': { 'web.assets_backend': [ 'utm/static/src/**/*', ], }, 'license': 'LGPL-3', }
23.75
665
505
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.tagged('post_install', '-at_install') class TestRoutes(odoo.tests.HttpCase): def test_01_web_session_destroy(self): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') self.authenticate('demo', 'demo') res = self.opener.post(url=base_url + '/web/session/destroy', json={}) self.assertEqual(res.status_code, 200)
36.071429
505
1,081
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.http import request from odoo import models class IrHttp(models.AbstractModel): _inherit = 'ir.http' @classmethod def get_utm_domain_cookies(cls): return request.httprequest.host @classmethod def _set_utm(cls, response): if isinstance(response, Exception): return response # the parent dispatch might destroy the session if not request.db: return response domain = cls.get_utm_domain_cookies() for var, dummy, cook in request.env['utm.mixin'].tracking_fields(): if var in request.params and request.httprequest.cookies.get(var) != request.params[var]: response.set_cookie(cook, request.params[var], domain=domain) return response @classmethod def _dispatch(cls): response = super(IrHttp, cls)._dispatch() return cls._set_utm(response) @classmethod def _handle_exception(cls, exc): response = super(IrHttp, cls)._handle_exception(exc) return cls._set_utm(response)
30.885714
1,081
3,198
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.http import request class UtmMixin(models.AbstractModel): """ Mixin class for objects which can be tracked by marketing. """ _name = 'utm.mixin' _description = 'UTM Mixin' campaign_id = fields.Many2one('utm.campaign', 'Campaign', help="This is a name that helps you keep track of your different campaign efforts, e.g. Fall_Drive, Christmas_Special") source_id = fields.Many2one('utm.source', 'Source', help="This is the source of the link, e.g. Search Engine, another domain, or name of email list") medium_id = fields.Many2one('utm.medium', 'Medium', help="This is the method of delivery, e.g. Postcard, Email, or Banner Ad") @api.model def default_get(self, fields): values = super(UtmMixin, self).default_get(fields) # We ignore UTM for salesmen, except some requests that could be done as superuser_id to bypass access rights. if not self.env.is_superuser() and self.env.user.has_group('sales_team.group_sale_salesman'): return values for url_param, field_name, cookie_name in self.env['utm.mixin'].tracking_fields(): if field_name in fields: field = self._fields[field_name] value = False if request: # ir_http dispatch saves the url params in a cookie value = request.httprequest.cookies.get(cookie_name) # if we receive a string for a many2one, we search/create the id if field.type == 'many2one' and isinstance(value, str) and value: Model = self.env[field.comodel_name] records = Model.search([('name', '=', value)], limit=1) if not records: if 'is_auto_campaign' in records._fields: records = Model.create({'name': value, 'is_auto_campaign': True}) else: records = Model.create({'name': value}) value = records.id if value: values[field_name] = value return values def tracking_fields(self): # This function cannot be overridden in a model which inherit utm.mixin # Limitation by the heritage on AbstractModel # record_crm_lead.tracking_fields() will call tracking_fields() from module utm.mixin (if not overridden on crm.lead) # instead of the overridden method from utm.mixin. # To force the call of overridden method, we use self.env['utm.mixin'].tracking_fields() which respects overridden # methods of utm.mixin, but will ignore overridden method on crm.lead return [ # ("URL_PARAMETER", "FIELD_NAME_MIXIN", "NAME_IN_COOKIES") ('utm_campaign', 'campaign_id', 'odoo_utm_campaign'), ('utm_source', 'source_id', 'odoo_utm_source'), ('utm_medium', 'medium_id', 'odoo_utm_medium'), ]
52.42623
3,198
2,655
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from random import randint from odoo import fields, models, api, SUPERUSER_ID class UtmStage(models.Model): """Stage for utm campaigns. """ _name = 'utm.stage' _description = 'Campaign Stage' _order = 'sequence' name = fields.Char(required=True, translate=True) sequence = fields.Integer() class UtmMedium(models.Model): # OLD crm.case.channel _name = 'utm.medium' _description = 'UTM Medium' _order = 'name' name = fields.Char(string='Medium Name', required=True) active = fields.Boolean(default=True) class UtmCampaign(models.Model): # OLD crm.case.resource.type _name = 'utm.campaign' _description = 'UTM Campaign' name = fields.Char(string='Campaign Name', required=True, translate=True) user_id = fields.Many2one( 'res.users', string='Responsible', required=True, default=lambda self: self.env.uid) stage_id = fields.Many2one('utm.stage', string='Stage', ondelete='restrict', required=True, default=lambda self: self.env['utm.stage'].search([], limit=1), group_expand='_group_expand_stage_ids') tag_ids = fields.Many2many( 'utm.tag', 'utm_tag_rel', 'tag_id', 'campaign_id', string='Tags') is_auto_campaign = fields.Boolean(default=False, string="Automatically Generated Campaign", help="Allows us to filter relevant Campaigns") color = fields.Integer(string='Color Index') @api.model def _group_expand_stage_ids(self, stages, domain, order): """ Read group customization in order to display all the stages in the kanban view, even if they are empty """ stage_ids = stages._search([], order=order, access_rights_uid=SUPERUSER_ID) return stages.browse(stage_ids) class UtmSource(models.Model): _name = 'utm.source' _description = 'UTM Source' name = fields.Char(string='Source Name', required=True, translate=True) class UtmTag(models.Model): """Model of categories of utm campaigns, i.e. marketing, newsletter, ... """ _name = 'utm.tag' _description = 'UTM Tag' _order = 'name' def _default_color(self): return randint(1, 11) name = fields.Char(required=True, translate=True) color = fields.Integer( string='Color Index', default=lambda self: self._default_color(), help='Tag color. No color means no display in kanban to distinguish internal tags from public categorization tags.') _sql_constraints = [ ('name_uniq', 'unique (name)', "Tag name already exists !"), ]
33.1875
2,655
1,114
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Initial Setup Tools', 'version': '1.0', 'category': 'Hidden', 'description': """ This module helps to configure the system at the installation of a new database. ================================================================================ Shows you a list of applications features to install from. """, 'depends': ['base', 'web'], 'data': [ 'data/base_setup_data.xml', 'views/res_config_settings_views.xml', 'views/res_partner_views.xml', ], 'demo': [], 'installable': True, 'auto_install': False, 'assets': { 'web.assets_backend': [ 'base_setup/static/src/scss/settings.scss', 'base_setup/static/src/js/res_config_dev_tool.js', 'base_setup/static/src/js/res_config_edition.js', 'base_setup/static/src/js/res_config_invite_users.js', ], 'web.assets_qweb': [ 'base_setup/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
30.944444
1,114
4,232
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from odoo.tests.common import TransactionCase def just_raise(*args): raise Exception("We should not be here.") class TestResConfig(TransactionCase): def setUp(self): super(TestResConfig, self).setUp() self.user = self.env.ref('base.user_admin') self.company = self.env['res.company'].create({'name': 'oobO'}) self.user.write({'company_ids': [(4, self.company.id)], 'company_id': self.company.id}) Settings = self.env['res.config.settings'].with_user(self.user.id) self.config = Settings.create({}) def test_multi_company_res_config_group(self): # Enable/Disable a group in a multi-company environment # 1/ All the users should be added/removed from the group # and not only the users of the allowed companies # 2/ The changes should be reflected for new users (Default User Template) company = self.env['res.company'].create({'name': 'My Last Company'}) partner = self.env['res.partner'].create({ 'name': 'My User' }) user = self.env['res.users'].create({ 'login': 'My User', 'company_id': company.id, 'company_ids': [(4, company.id)], 'partner_id': partner.id, }) ResConfig = self.env['res.config.settings'] default_values = ResConfig.default_get(list(ResConfig.fields_get())) # Case 1: Enable a group default_values.update({'group_multi_currency': True}) ResConfig.create(default_values).execute() self.assertTrue(user in self.env.ref('base.group_multi_currency').sudo().users) new_partner = self.env['res.partner'].create({'name': 'New User'}) new_user = self.env['res.users'].create({ 'login': 'My First New User', 'company_id': company.id, 'company_ids': [(4, company.id)], 'partner_id': new_partner.id, }) self.assertTrue(new_user in self.env.ref('base.group_multi_currency').sudo().users) # Case 2: Disable a group default_values.update({'group_multi_currency': False}) ResConfig.create(default_values).execute() self.assertTrue(user not in self.env.ref('base.group_multi_currency').sudo().users) new_partner = self.env['res.partner'].create({'name': 'New User'}) new_user = self.env['res.users'].create({ 'login': 'My Second New User', 'company_id': company.id, 'company_ids': [(4, company.id)], 'partner_id': new_partner.id, }) self.assertTrue(new_user not in self.env.ref('base.group_multi_currency').sudo().users) def test_no_install(self): """Make sure that when saving settings, no modules are installed if nothing was set to install. """ # check that no module should be installed in the first place config_fields = self.config._get_classified_fields() for name, module in config_fields['module']: if int(self.config[name]): self.assertTrue(module.state != 'uninstalled', "All set modules should already be installed.") # if we try to install something, raise; so nothing should be installed with patch('odoo.addons.base.models.ir_module.Module._button_immediate_function', new=just_raise): self.config.execute() def test_install(self): """Make sure that the previous test is valid, i.e. when saving settings, it starts module install if something was set to install. """ config_fields = self.config._get_classified_fields() # set the first uninstalled module to install module_to_install = next(filter(lambda m: m[1].state == 'uninstalled', config_fields['module'])) self.config[module_to_install[0]] = True with patch('odoo.addons.base.models.ir_module.Module._button_immediate_function', new=just_raise): with self.assertRaisesRegex(Exception, "We should not be here."): self.config.execute()
44.083333
4,232
1,721
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import HttpCase, tagged import re @tagged('-standard', 'external', 'post_install', '-at_install') # nightly is not a real tag class TestResConfigDocLinks(HttpCase): """ Parse the 'res_config' view to extract all documentation links and check that every links are still valid. """ def setUp(self): """ Set-up the test environment """ super(TestResConfigDocLinks, self).setUp() self.re = re.compile("<a href=\"(\S+/documentation/\S+)\"") self.links = set() def test_01_links(self): """ Firs test: check that all documentation links in 'res_config_settings' views are not broken. """ self._parse_view(self.env.ref('base.res_config_settings_view_form')) for link in self.links: self._check_link(link) def _check_link(self, link): """ Try to open the link and check the response status code """ res = self.url_open(url=link) self.assertEqual( res.status_code, 200, "The following link is broken: '%s'" % (link) ) def _parse_view(self, view): """ Analyse the view to extract documentation links and store them in a set. Then, parse its children if any. """ # search the documentation links in the current view for match in re.finditer(self.re, view.arch): self.links.add(match.group(1)) # and then, search inside children for child in view.inherit_children_ids: self._parse_view(child)
30.192982
1,721
491
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.http import request class IrHttp(models.AbstractModel): _inherit = 'ir.http' def session_info(self): result = super(IrHttp, self).session_info() if request.env.user.has_group('base.group_user'): result['show_effect'] = request.env['ir.config_parameter'].sudo().get_param('base_setup.show_effect') return result
35.071429
491
895
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 ResUsers(models.Model): _inherit = 'res.users' @api.model def web_create_users(self, emails): # Reactivate already existing users if needed deactivated_users = self.with_context(active_test=False).search([('active', '=', False), '|', ('login', 'in', emails), ('email', 'in', emails)]) for user in deactivated_users: user.active = True new_emails = set(emails) - set(deactivated_users.mapped('email')) # Process new email addresses : create new users for email in new_emails: default_values = {'login': email, 'name': email.split('@')[0], 'email': email, 'active': True} user = self.with_context(signup_valid=True).create(default_values) return True
35.8
895
6,517
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 UserError class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company) user_default_rights = fields.Boolean( "Default Access Rights", config_parameter='base_setup.default_user_rights') external_email_server_default = fields.Boolean( "Custom Email Servers", config_parameter='base_setup.default_external_email_server') module_base_import = fields.Boolean("Allow users to import data from CSV/XLS/XLSX/ODS files") module_google_calendar = fields.Boolean( string='Allow the users to synchronize their calendar with Google Calendar') module_microsoft_calendar = fields.Boolean( string='Allow the users to synchronize their calendar with Outlook Calendar') module_mail_plugin = fields.Boolean( string='Allow integration with the mail plugins' ) module_google_drive = fields.Boolean("Attach Google documents to any record") module_google_spreadsheet = fields.Boolean("Google Spreadsheet") module_auth_oauth = fields.Boolean("Use external authentication providers (OAuth)") module_auth_ldap = fields.Boolean("LDAP Authentication") # TODO: remove in master module_base_gengo = fields.Boolean("Translate Your Website with Gengo") module_account_inter_company_rules = fields.Boolean("Manage Inter Company") module_pad = fields.Boolean("Collaborative Pads") module_voip = fields.Boolean("Asterisk (VoIP)") module_web_unsplash = fields.Boolean("Unsplash Image Library") module_partner_autocomplete = fields.Boolean("Partner Autocomplete") module_base_geolocalize = fields.Boolean("GeoLocalize") module_google_recaptcha = fields.Boolean("reCAPTCHA") report_footer = fields.Html(related="company_id.report_footer", string='Custom Report Footer', help="Footer text displayed at the bottom of all reports.", readonly=False) group_multi_currency = fields.Boolean(string='Multi-Currencies', implied_group='base.group_multi_currency', help="Allows to work in a multi currency environment") external_report_layout_id = fields.Many2one(related="company_id.external_report_layout_id", readonly=False) show_effect = fields.Boolean(string="Show Effect", config_parameter='base_setup.show_effect') company_count = fields.Integer('Number of Companies', compute="_compute_company_count") active_user_count = fields.Integer('Number of Active Users', compute="_compute_active_user_count") language_count = fields.Integer('Number of Languages', compute="_compute_language_count") company_name = fields.Char(related="company_id.display_name", string="Company Name") company_informations = fields.Text(compute="_compute_company_informations") profiling_enabled_until = fields.Datetime("Profiling enabled until", config_parameter='base.profiling_enabled_until') module_product_images = fields.Boolean("Get product pictures using barcode") def open_company(self): return { 'type': 'ir.actions.act_window', 'name': 'My Company', 'view_mode': 'form', 'res_model': 'res.company', 'res_id': self.env.company.id, 'target': 'current', 'context': { 'form_view_initial_mode': 'edit', }, } def open_default_user(self): action = self.env["ir.actions.actions"]._for_xml_id("base.action_res_users") if self.env.ref('base.default_user', raise_if_not_found=False): action['res_id'] = self.env.ref('base.default_user').id else: raise UserError(_("Default User Template not found.")) action['views'] = [[self.env.ref('base.view_users_form').id, 'form']] return action @api.model def _prepare_report_view_action(self, template): template_id = self.env.ref(template) return { 'type': 'ir.actions.act_window', 'res_model': 'ir.ui.view', 'view_mode': 'form', 'res_id': template_id.id, } def edit_external_header(self): if not self.external_report_layout_id: return False return self._prepare_report_view_action(self.external_report_layout_id.key) # NOTE: These fields depend on the context, if we want them to be computed # we have to make them depend on a field. This is because we are on a TransientModel. @api.depends('company_id') def _compute_company_count(self): company_count = self.env['res.company'].sudo().search_count([]) for record in self: record.company_count = company_count @api.depends('company_id') def _compute_active_user_count(self): active_user_count = self.env['res.users'].sudo().search_count([('share', '=', False)]) for record in self: record.active_user_count = active_user_count @api.depends('company_id') def _compute_language_count(self): language_count = len(self.env['res.lang'].get_installed()) for record in self: record.language_count = language_count @api.depends('company_id') def _compute_company_informations(self): informations = '%s\n' % self.company_id.street if self.company_id.street else '' informations += '%s\n' % self.company_id.street2 if self.company_id.street2 else '' informations += '%s' % self.company_id.zip if self.company_id.zip else '' informations += '\n' if self.company_id.zip and not self.company_id.city else '' informations += ' - ' if self.company_id.zip and self.company_id.city else '' informations += '%s\n' % self.company_id.city if self.company_id.city else '' informations += '%s\n' % self.company_id.state_id.display_name if self.company_id.state_id else '' informations += '%s' % self.company_id.country_id.display_name if self.company_id.country_id else '' vat_display = self.company_id.country_id.vat_label or _('VAT') vat_display = '\n' + vat_display + ': ' informations += '%s %s' % (vat_display, self.company_id.vat) if self.company_id.vat else '' for record in self: record.company_informations = informations
51.314961
6,517
2,136
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.exceptions import AccessError from odoo.http import request class BaseSetup(http.Controller): @http.route('/base_setup/data', type='json', auth='user') def base_setup_data(self, **kw): if not request.env.user.has_group('base.group_erp_manager'): raise AccessError(_("Access Denied")) cr = request.cr cr.execute(""" SELECT count(*) FROM res_users WHERE active=true AND share=false """) active_count = cr.dictfetchall()[0].get('count') cr.execute(""" SELECT count(u.*) FROM res_users u WHERE active=true AND share=false AND NOT exists(SELECT 1 FROM res_users_log WHERE create_uid=u.id) """) pending_count = cr.dictfetchall()[0].get('count') cr.execute(""" SELECT id, login FROM res_users u WHERE active=true AND share=false AND NOT exists(SELECT 1 FROM res_users_log WHERE create_uid=u.id) ORDER BY id desc LIMIT 10 """) pending_users = cr.fetchall() action_pending_users = request.env['res.users'].browse( [uid for (uid, login) in pending_users])._action_show() return { 'active_users': active_count, 'pending_count': pending_count, 'pending_users': pending_users, 'action_pending_users': action_pending_users, } @http.route('/base_setup/demo_active', type='json', auth='user') def base_setup_is_demo(self, **kwargs): # We assume that if there's at least one module with demo data active, then the db was # initialized with demo=True or it has been force-activated by the `Load demo data` button # in the settings dashboard. demo_active = bool(request.env['ir.module.module'].search_count([('demo', '=', True)])) return demo_active
36.20339
2,136
535
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "mail_bot_hr", 'summary': """Bridge module between hr and mailbot.""", 'description': """This module adds the OdooBot state and notifications in the user form modified by hr.""", 'website': "https://www.odoo.com/app/discuss", 'category': 'Productivity/Discuss', 'version': '1.0', 'depends': ['mail_bot', 'hr'], 'application': False, 'installable': True, 'auto_install': True, 'data': [ 'views/res_users_views.xml', ], 'license': 'LGPL-3', }
31.470588
535
1,212
py
PYTHON
15.0
{ 'name': 'Two-Factor Authentication (TOTP)', 'description': """ Two-Factor Authentication (TOTP) ================================ Allows users to configure two-factor authentication on their user account for extra security, using time-based one-time passwords (TOTP). Once enabled, the user will need to enter a 6-digit code as provided by their authenticator app before being granted access to the system. All popular authenticator apps are supported. Note: logically, two-factor prevents password-based RPC access for users where it is enabled. In order to be able to execute RPC scripts, the user can setup API keys to replace their main password. """, 'depends': ['web'], 'category': 'Extra Tools', 'auto_install': True, 'data': [ 'security/security.xml', 'security/ir.model.access.csv', 'data/ir_action_data.xml', 'views/res_users_views.xml', 'views/templates.xml', 'wizard/auth_totp_wizard_views.xml', ], 'assets': { 'web.assets_tests': [ 'auth_totp/static/tests/**/*', ], 'web.assets_backend': [ 'auth_totp/static/src/**/*', ], }, 'license': 'LGPL-3', }
32.756757
1,212
4,211
py
PYTHON
15.0
import json import time from xmlrpc.client import Fault from passlib.totp import TOTP from odoo import http from odoo.exceptions import AccessDenied from odoo.service import common as auth, model from odoo.tests import tagged, HttpCase, get_db_name from ..controllers.home import Home @tagged('post_install', '-at_install') class TestTOTP(HttpCase): def setUp(self): super().setUp() totp = None # might be possible to do client-side using `crypto.subtle` instead of # this horror show, but requires working on 64b integers, & BigInt is # significantly less well supported than crypto def totp_hook(self, secret=None): nonlocal totp if totp is None: totp = TOTP(secret) if secret: return totp.generate().token else: # on check, take advantage of window because previous token has been # "burned" so we can't generate the same, but tour is so fast # we're pretty certainly within the same 30s return totp.generate(time.time() + 30).token # because not preprocessed by ControllerType metaclass totp_hook.routing_type = 'json' self.env['ir.http']._clear_routing_map() # patch Home to add test endpoint Home.totp_hook = http.route('/totphook', type='json', auth='none')(totp_hook) # remove endpoint and destroy routing map @self.addCleanup def _cleanup(): del Home.totp_hook self.env['ir.http']._clear_routing_map() def test_totp(self): # 1. Enable 2FA self.start_tour('/web', 'totp_tour_setup', login='demo') # 2. Verify that RPC is blocked because 2FA is on. self.assertFalse( self.xmlrpc_common.authenticate(get_db_name(), 'demo', 'demo', {}), "Should not have returned a uid" ) self.assertFalse( self.xmlrpc_common.authenticate(get_db_name(), 'demo', 'demo', {'interactive': True}), 'Trying to fake the auth type should not work' ) uid = self.env.ref('base.user_demo').id with self.assertRaisesRegex(Fault, r'Access Denied'): self.xmlrpc_object.execute_kw( get_db_name(), uid, 'demo', 'res.users', 'read', [uid, ['login']] ) # 3. Check 2FA is required self.start_tour('/', 'totp_login_enabled', login=None) # 4. Check 2FA is not requested on saved device and disable it self.start_tour('/', 'totp_login_device', login=None) # 5. Finally, check that 2FA is in fact disabled self.start_tour('/', 'totp_login_disabled', login=None) # 6. Check that rpc is now re-allowed uid = self.xmlrpc_common.authenticate(get_db_name(), 'demo', 'demo', {}) self.assertEqual(uid, self.env.ref('base.user_demo').id) [r] = self.xmlrpc_object.execute_kw( get_db_name(), uid, 'demo', 'res.users', 'read', [uid, ['login']] ) self.assertEqual(r['login'], 'demo') def test_totp_administration(self): self.start_tour('/web', 'totp_tour_setup', login='demo') self.start_tour('/web', 'totp_admin_disables', login='admin') self.start_tour('/', 'totp_login_disabled', login=None) def test_totp_authenticate(self): """ Ensure that JSON-RPC authentication works and don't return the user id without TOTP check """ self.start_tour('/web', 'totp_tour_setup', login='demo') self.url_open('/web/session/logout') headers = { "Content-Type": "application/json", } payload = { "jsonrpc": "2.0", "method": "call", "id": 0, "params": { "db": get_db_name(), "login": "demo", "password": "demo", "context": {}, }, } response = self.url_open("/web/session/authenticate", data=json.dumps(payload), headers=headers) data = response.json() self.assertEqual(data['result']['uid'], None)
36.617391
4,211
2,922
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import functools import io import qrcode import re import werkzeug.urls from odoo import _, api, fields, models from odoo.addons.base.models.res_users import check_identity from odoo.exceptions import UserError from odoo.http import request from odoo.addons.auth_totp.models.totp import ALGORITHM, DIGITS, TIMESTEP compress = functools.partial(re.sub, r'\s', '') class TOTPWizard(models.TransientModel): _name = 'auth_totp.wizard' _description = "2-Factor Setup Wizard" user_id = fields.Many2one('res.users', required=True, readonly=True) secret = fields.Char(required=True, readonly=True) url = fields.Char(store=True, readonly=True, compute='_compute_qrcode') qrcode = fields.Binary( attachment=False, store=True, readonly=True, compute='_compute_qrcode', ) code = fields.Char(string="Verification Code", size=7) @api.depends('user_id.login', 'user_id.company_id.display_name', 'secret') def _compute_qrcode(self): # TODO: make "issuer" configurable through config parameter? global_issuer = request and request.httprequest.host.split(':', 1)[0] for w in self: issuer = global_issuer or w.user_id.company_id.display_name w.url = url = werkzeug.urls.url_unparse(( 'otpauth', 'totp', werkzeug.urls.url_quote(f'{issuer}:{w.user_id.login}', safe=':'), werkzeug.urls.url_encode({ 'secret': compress(w.secret), 'issuer': issuer, # apparently a lowercase hash name is anathema to google # authenticator (error) and passlib (no token) 'algorithm': ALGORITHM.upper(), 'digits': DIGITS, 'period': TIMESTEP, }), '' )) data = io.BytesIO() qrcode.make(url.encode(), box_size=4).save(data, optimise=True, format='PNG') w.qrcode = base64.b64encode(data.getvalue()).decode() @check_identity def enable(self): try: c = int(compress(self.code)) except ValueError: raise UserError(_("The verification code should only contain numbers")) if self.user_id._totp_try_setting(self.secret, c): self.secret = '' # empty it, because why keep it until GC? return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'type': 'success', 'message': _("2-Factor authentication is now enabled."), 'next': {'type': 'ir.actions.act_window_close'}, } } raise UserError(_('Verification failed, please double-check the 6-digit code'))
39.486486
2,922
2,026
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import hmac import struct import time # 160 bits, as recommended by HOTP RFC 4226, section 4, R6. # Google Auth uses 80 bits by default but supports 160. TOTP_SECRET_SIZE = 160 # The algorithm (and key URI format) allows customising these parameters but # google authenticator doesn't support it # https://github.com/google/google-authenticator/wiki/Key-Uri-Format ALGORITHM = 'sha1' DIGITS = 6 TIMESTEP = 30 class TOTP: def __init__(self, key): self._key = key def match(self, code, t=None, window=TIMESTEP, timestep=TIMESTEP): """ :param code: authenticator code to check against this key :param int t: current timestamp (seconds) :param int window: fuzz window to account for slow fingers, network latency, desynchronised clocks, ..., every code valid between t-window an t+window is considered valid """ if t is None: t = time.time() low = int((t - window) / timestep) high = int((t + window) / timestep) + 1 return next(( counter for counter in range(low, high) if hotp(self._key, counter) == code ), None) def hotp(secret, counter): # C is the 64b counter encoded in big-endian C = struct.pack(">Q", counter) mac = hmac.new(secret, msg=C, digestmod=ALGORITHM).digest() # the data offset is the last nibble of the hash offset = mac[-1] & 0xF # code is the 4 bytes at the offset interpreted as a 31b big-endian uint # (31b to avoid sign concerns). This effectively limits digits to 9 and # hard-limits it to 10: each digit is normally worth 3.32 bits but the # 10th is only worth 1.1 (9 digits encode 29.9 bits). code = struct.unpack_from('>I', mac, offset)[0] & 0x7FFFFFFF r = code % (10 ** DIGITS) # NOTE: use text / bytes instead of int? return r
36.178571
2,026
373
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models from odoo.http import request class IrHttp(models.AbstractModel): _inherit = 'ir.http' def session_info(self): info = super().session_info() # because frontend session_info uses this key and is embedded in # the view source info["user_id"] = request.session.uid, return info
28.692308
373
838
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models from odoo.addons.auth_totp.controllers.home import TRUSTED_DEVICE_AGE import logging _logger = logging.getLogger(__name__) class AuthTotpDevice(models.Model): # init is overriden in res.users.apikeys to create a secret column 'key' # use a different model to benefit from the secured methods while not mixing # two different concepts _name = "auth_totp.device" _inherit = "res.users.apikeys" _description = "Authentication Device" _auto = False @api.autovacuum def _gc_device(self): self._cr.execute(""" DELETE FROM auth_totp_device WHERE create_date < (NOW() AT TIME ZONE 'UTC' - INTERVAL '%s SECONDS') """, [TRUSTED_DEVICE_AGE]) _logger.info("GC'd %d totp devices entries", self._cr.rowcount)
32.230769
838
5,583
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import functools import logging import os import re from odoo import _, api, fields, models from odoo.addons.base.models.res_users import check_identity from odoo.exceptions import AccessDenied, UserError from odoo.http import request from odoo.addons.auth_totp.models.totp import TOTP, TOTP_SECRET_SIZE _logger = logging.getLogger(__name__) compress = functools.partial(re.sub, r'\s', '') class Users(models.Model): _inherit = 'res.users' totp_secret = fields.Char(copy=False, groups=fields.NO_ACCESS) totp_enabled = fields.Boolean(string="Two-factor authentication", compute='_compute_totp_enabled') totp_trusted_device_ids = fields.One2many('auth_totp.device', 'user_id', string="Trusted Devices") @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + ['totp_enabled', 'totp_trusted_device_ids'] def _mfa_type(self): r = super()._mfa_type() if r is not None: return r if self.totp_enabled: return 'totp' def _mfa_url(self): r = super()._mfa_url() if r is not None: return r if self._mfa_type() == 'totp': return '/web/login/totp' @api.depends('totp_secret') def _compute_totp_enabled(self): for r, v in zip(self, self.sudo()): r.totp_enabled = bool(v.totp_secret) def _rpc_api_keys_only(self): # 2FA enabled means we can't allow password-based RPC self.ensure_one() return self.totp_enabled or super()._rpc_api_keys_only() def _get_session_token_fields(self): return super()._get_session_token_fields() | {'totp_secret'} def _totp_check(self, code): sudo = self.sudo() key = base64.b32decode(sudo.totp_secret) match = TOTP(key).match(code) if match is None: _logger.info("2FA check: FAIL for %s %r", self, self.login) raise AccessDenied(_("Verification failed, please double-check the 6-digit code")) _logger.info("2FA check: SUCCESS for %s %r", self, self.login) def _totp_try_setting(self, secret, code): if self.totp_enabled or self != self.env.user: _logger.info("2FA enable: REJECT for %s %r", self, self.login) return False secret = compress(secret).upper() match = TOTP(base64.b32decode(secret)).match(code) if match is None: _logger.info("2FA enable: REJECT CODE for %s %r", self, self.login) return False self.sudo().totp_secret = secret if request: self.flush() # update session token so the user does not get logged out (cache cleared by change) new_token = self.env.user._compute_session_token(request.session.sid) request.session.session_token = new_token _logger.info("2FA enable: SUCCESS for %s %r", self, self.login) return True @check_identity def action_totp_disable(self): logins = ', '.join(map(repr, self.mapped('login'))) if not (self == self.env.user or self.env.user._is_admin() or self.env.su): _logger.info("2FA disable: REJECT for %s (%s) by uid #%s", self, logins, self.env.user.id) return False self.revoke_all_devices() self.sudo().write({'totp_secret': False}) if request and self == self.env.user: self.flush() # update session token so the user does not get logged out (cache cleared by change) new_token = self.env.user._compute_session_token(request.session.sid) request.session.session_token = new_token _logger.info("2FA disable: SUCCESS for %s (%s) by uid #%s", self, logins, self.env.user.id) return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'type': 'warning', 'message': _("Two-factor authentication disabled for the following user(s): %s", ', '.join(self.mapped('name'))), 'next': {'type': 'ir.actions.act_window_close'}, } } @check_identity def action_totp_enable_wizard(self): if self.env.user != self: raise UserError(_("Two-factor authentication can only be enabled for yourself")) if self.totp_enabled: raise UserError(_("Two-factor authentication already enabled")) secret_bytes_count = TOTP_SECRET_SIZE // 8 secret = base64.b32encode(os.urandom(secret_bytes_count)).decode() # format secret in groups of 4 characters for readability secret = ' '.join(map(''.join, zip(*[iter(secret)]*4))) w = self.env['auth_totp.wizard'].create({ 'user_id': self.id, 'secret': secret, }) return { 'type': 'ir.actions.act_window', 'target': 'new', 'res_model': 'auth_totp.wizard', 'name': _("Two-Factor Authentication Activation"), 'res_id': w.id, 'views': [(False, 'form')], 'context': self.env.context, } @check_identity def revoke_all_devices(self): self._revoke_all_devices() def _revoke_all_devices(self): self.totp_trusted_device_ids._remove() @api.model def change_password(self, old_passwd, new_passwd): self.env.user._revoke_all_devices() return super().change_password(old_passwd, new_passwd)
36.97351
5,583
2,960
py
PYTHON
15.0
# -*- coding: utf-8 -*- import re import odoo.addons.web.controllers.main from odoo import http, _ from odoo.exceptions import AccessDenied from odoo.http import request TRUSTED_DEVICE_COOKIE = 'td_id' TRUSTED_DEVICE_AGE = 90*86400 # 90 days expiration class Home(odoo.addons.web.controllers.main.Home): @http.route( '/web/login/totp', type='http', auth='public', methods=['GET', 'POST'], sitemap=False, website=True, multilang=False # website breaks the login layout... ) def web_totp(self, redirect=None, **kwargs): if request.session.uid: return request.redirect(self._login_redirect(request.session.uid, redirect=redirect)) if not request.session.pre_uid: return request.redirect('/web/login') error = None user = request.env['res.users'].browse(request.session.pre_uid) if user and request.httprequest.method == 'GET': cookies = request.httprequest.cookies key = cookies.get(TRUSTED_DEVICE_COOKIE) if key: checked_credentials = request.env['auth_totp.device']._check_credentials(scope="browser", key=key) if checked_credentials == user.id: request.session.finalize() return request.redirect(self._login_redirect(request.session.uid, redirect=redirect)) elif user and request.httprequest.method == 'POST' and kwargs.get('totp_token'): try: with user._assert_can_auth(): user._totp_check(int(re.sub(r'\s', '', kwargs['totp_token']))) except AccessDenied as e: error = str(e) except ValueError: error = _("Invalid authentication code format.") else: request.session.finalize() response = request.redirect(self._login_redirect(request.session.uid, redirect=redirect)) if kwargs.get('remember'): name = _("%(browser)s on %(platform)s", browser=request.httprequest.user_agent.browser.capitalize(), platform=request.httprequest.user_agent.platform.capitalize(), ) geoip = request.session.geoip if geoip: name += " (%s, %s)" % (geoip['city'], geoip['country_name']) key = request.env['auth_totp.device']._generate("browser", name) response.set_cookie( key=TRUSTED_DEVICE_COOKIE, value=key, max_age=TRUSTED_DEVICE_AGE, httponly=True, samesite='Lax' ) return response return request.render('auth_totp.auth_totp_form', { 'user': user, 'error': error, 'redirect': redirect, })
41.111111
2,960
24,640
py
PYTHON
15.0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import argparse import logging import os import pexpect import shutil import signal import subprocess import sys import tempfile import time import traceback from xmlrpc import client as xmlrpclib from glob import glob #---------------------------------------------------------- # Utils #---------------------------------------------------------- ROOTDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) TSTAMP = time.strftime("%Y%m%d", time.gmtime()) exec(open(os.path.join(ROOTDIR, 'odoo', 'release.py'), 'rb').read()) VERSION = version.split('-')[0].replace('saas~', '') GPGPASSPHRASE = os.getenv('GPGPASSPHRASE') GPGID = os.getenv('GPGID') DOCKERVERSION = VERSION.replace('+', '') INSTALL_TIMEOUT = 600 DOCKERUSER = """ RUN mkdir /var/lib/odoo && \ groupadd -g %(group_id)s odoo && \ useradd -u %(user_id)s -g odoo odoo -d /var/lib/odoo && \ mkdir /data && \ chown odoo:odoo /var/lib/odoo /data USER odoo """ % {'group_id': os.getgid(), 'user_id': os.getuid()} class OdooTestTimeoutError(Exception): pass class OdooTestError(Exception): pass def run_cmd(cmd, chdir=None, timeout=None): logging.info("Running command %s", cmd) return subprocess.run(cmd, cwd=chdir, timeout=timeout) def _rpc_count_modules(addr='http://127.0.0.1', port=8069, dbname='mycompany'): time.sleep(5) uid = xmlrpclib.ServerProxy('%s:%s/xmlrpc/2/common' % (addr, port)).authenticate( dbname, 'admin', 'admin', {} ) modules = xmlrpclib.ServerProxy('%s:%s/xmlrpc/2/object' % (addr, port)).execute( dbname, uid, 'admin', 'ir.module.module', 'search', [('state', '=', 'installed')] ) if len(modules) > 1: time.sleep(1) toinstallmodules = xmlrpclib.ServerProxy('%s:%s/xmlrpc/2/object' % (addr, port)).execute( dbname, uid, 'admin', 'ir.module.module', 'search', [('state', '=', 'to install')] ) if toinstallmodules: logging.error("Package test: FAILED. Not able to install dependencies of base.") raise OdooTestError("Installation of package failed") else: logging.info("Package test: successfuly installed %s modules" % len(modules)) else: logging.error("Package test: FAILED. Not able to install base.") raise OdooTestError("Package test: FAILED. Not able to install base.") def publish(args, pub_type, extensions): """Publish builded package (move builded files and generate a symlink to the latests) :args: parsed program args :pub_type: one of [deb, rpm, src, exe] :extensions: list of extensions to publish :returns: published files """ def _publish(release): build_path = os.path.join(args.build_dir, release) filename = release.split(os.path.sep)[-1] release_dir = os.path.join(args.pub, pub_type) release_path = os.path.join(release_dir, filename) os.renames(build_path, release_path) # Latest/symlink handler release_abspath = os.path.abspath(release_path) latest_abspath = release_abspath.replace(TSTAMP, 'latest') if os.path.islink(latest_abspath): os.unlink(latest_abspath) os.symlink(release_abspath, latest_abspath) return release_path published = [] for extension in extensions: release = glob("%s/odoo_*.%s" % (args.build_dir, extension)) if release: published.append(_publish(release[0])) return published # --------------------------------------------------------- # Generates Packages, Sources and Release files of debian package # --------------------------------------------------------- def gen_deb_package(args, published_files): # Executes command to produce file_name in path, and moves it to args.pub/deb def _gen_file(args, command, file_name, path): cur_tmp_file_path = os.path.join(path, file_name) with open(cur_tmp_file_path, 'w') as out: subprocess.call(command, stdout=out, cwd=path) shutil.copy(cur_tmp_file_path, os.path.join(args.pub, 'deb', file_name)) # Copy files to a temp directory (required because the working directory must contain only the # files of the last release) temp_path = tempfile.mkdtemp(suffix='debPackages') for pub_file_path in published_files: shutil.copy(pub_file_path, temp_path) commands = [ (['dpkg-scanpackages', '--multiversion', '.'], "Packages"), # Generate Packages file (['dpkg-scansources', '.'], "Sources"), # Generate Sources file (['apt-ftparchive', 'release', '.'], "Release") # Generate Release file ] # Generate files for command in commands: _gen_file(args, command[0], command[-1], temp_path) # Remove temp directory shutil.rmtree(temp_path) if args.sign: # Generate Release.gpg (= signed Release) # Options -abs: -a (Create ASCII armored output), -b (Make a detach signature), -s (Make a signature) subprocess.call(['gpg', '--default-key', GPGID, '--passphrase', GPGPASSPHRASE, '--yes', '-abs', '--no-tty', '-o', 'Release.gpg', 'Release'], cwd=os.path.join(args.pub, 'deb')) # --------------------------------------------------------- # Generates an RPM repo # --------------------------------------------------------- def rpm_sign(args, file_name): """Genereate a rpm repo in publish directory""" # Sign the RPM rpmsign = pexpect.spawn('/bin/bash', ['-c', 'rpm --resign %s' % file_name], cwd=os.path.join(args.pub, 'rpm')) rpmsign.expect_exact('Enter passphrase: ') rpmsign.send(GPGPASSPHRASE + '\r\n') rpmsign.expect(pexpect.EOF) def _prepare_build_dir(args, win32=False, move_addons=True): """Copy files to the build directory""" logging.info('Preparing build dir "%s"', args.build_dir) cmd = ['rsync', '-a', '--delete', '--exclude', '.git', '--exclude', '*.pyc', '--exclude', '*.pyo'] if win32 is False: cmd += ['--exclude', 'setup/win32'] run_cmd(cmd + ['%s/' % args.odoo_dir, args.build_dir]) if not move_addons: return for addon_path in glob(os.path.join(args.build_dir, 'addons/*')): if args.blacklist is None or os.path.basename(addon_path) not in args.blacklist: try: shutil.move(addon_path, os.path.join(args.build_dir, 'odoo/addons')) except shutil.Error as e: logging.warning("Warning '%s' while moving addon '%s", e, addon_path) if addon_path.startswith(args.build_dir) and os.path.isdir(addon_path): logging.info("Removing '{}'".format(addon_path)) try: shutil.rmtree(addon_path) except shutil.Error as rm_error: logging.warning("Cannot remove '{}': {}".format(addon_path, rm_error)) # Docker stuffs class Docker(): """Base Docker class. Must be inherited by specific Docker builder class""" arch = None def __init__(self, args): """ :param args: argparse parsed arguments """ self.args = args self.tag = 'odoo-%s-%s-nightly-tests' % (DOCKERVERSION, self.arch) self.container_name = None self.exposed_port = None dockerfiles = { 'tgz': os.path.join(args.build_dir, 'setup/package.dfsrc'), 'deb': os.path.join(args.build_dir, 'setup/package.dfdebian'), 'rpm': os.path.join(args.build_dir, 'setup/package.dffedora'), } self.dockerfile = dockerfiles[self.arch] self.test_log_file = '/data/src/test-%s.log' % self.arch self.build_image() def build_image(self): """Build the dockerimage by copying Dockerfile into build_dir/docker""" docker_dir = os.path.join(self.args.build_dir, 'docker') docker_file_path = os.path.join(docker_dir, 'Dockerfile') os.mkdir(docker_dir) shutil.copy(self.dockerfile, docker_file_path) with open(docker_file_path, 'a') as dockerfile: dockerfile.write(DOCKERUSER) shutil.copy(os.path.join(self.args.build_dir, 'requirements.txt'), docker_dir) run_cmd(["docker", "build", "--rm=True", "-t", self.tag, "."], chdir=docker_dir, timeout=1200).check_returncode() shutil.rmtree(docker_dir) def run(self, cmd, build_dir, container_name, user='odoo', exposed_port=None, detach=False, timeout=None): self.container_name = container_name docker_cmd = [ "docker", "run", "--user=%s" % user, "--name=%s" % container_name, "--rm", "--volume=%s:/data/src" % build_dir ] if exposed_port: docker_cmd.extend(['-p', '127.0.0.1:%s:%s' % (exposed_port, exposed_port)]) self.exposed_port = exposed_port if detach: docker_cmd.append('-d') # preserve logs in case of detached docker container cmd = '(%s) > %s 2>&1' % (cmd, self.test_log_file) docker_cmd.extend([ self.tag, "/bin/bash", "-c", "cd /data/src && %s" % cmd ]) run_cmd(docker_cmd, timeout=timeout).check_returncode() def is_running(self): dinspect = subprocess.run(['docker', 'container', 'inspect', self.container_name], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) return True if dinspect.returncode == 0 else False def stop(self): run_cmd(["docker", "stop", self.container_name]).check_returncode() def test_odoo(self): logging.info('Starting to test Odoo install test') start_time = time.time() while self.is_running() and (time.time() - start_time) < INSTALL_TIMEOUT: time.sleep(5) if os.path.exists(os.path.join(args.build_dir, 'odoo.pid')): try: _rpc_count_modules(port=self.exposed_port) finally: self.stop() return if self.is_running(): self.stop() raise OdooTestTimeoutError('Odoo pid file never appeared after %s sec' % INSTALL_TIMEOUT) raise OdooTestError('Error while installing/starting Odoo after %s sec.\nSee testlogs.txt in build dir' % int(time.time() - start_time)) def build(self): """To be overriden by specific builder""" pass def start_test(self): """To be overriden by specific builder""" pass class DockerTgz(Docker): """Docker class to build python src package""" arch = 'tgz' def build(self): logging.info('Start building python tgz package') self.run('python3 setup.py sdist --quiet --formats=gztar,zip', self.args.build_dir, 'odoo-src-build-%s' % TSTAMP) os.rename(glob('%s/dist/odoo-*.tar.gz' % self.args.build_dir)[0], '%s/odoo_%s.%s.tar.gz' % (self.args.build_dir, VERSION, TSTAMP)) os.rename(glob('%s/dist/odoo-*.zip' % self.args.build_dir)[0], '%s/odoo_%s.%s.zip' % (self.args.build_dir, VERSION, TSTAMP)) logging.info('Finished building python tgz package') def start_test(self): if not self.args.test: return logging.info('Start testing python tgz package') cmds = [ 'service postgresql start', 'pip3 install /data/src/odoo_%s.%s.tar.gz' % (VERSION, TSTAMP), 'su postgres -s /bin/bash -c "createuser -s odoo"', 'su postgres -s /bin/bash -c "createdb mycompany"', 'su odoo -s /bin/bash -c "odoo -d mycompany -i base --stop-after-init"', 'su odoo -s /bin/bash -c "odoo -d mycompany --pidfile=/data/src/odoo.pid"', ] self.run(' && '.join(cmds), self.args.build_dir, 'odoo-src-test-%s' % TSTAMP, user='root', detach=True, exposed_port=8069, timeout=300) self.test_odoo() logging.info('Finished testing tgz package') class DockerDeb(Docker): """Docker class to build debian package""" arch = 'deb' def build(self): logging.info('Start building debian package') # Append timestamp to version for the .dsc to refer the right .tar.gz cmds = ["sed -i '1s/^.*$/odoo (%s.%s) stable; urgency=low/' debian/changelog" % (VERSION, TSTAMP)] cmds.append('dpkg-buildpackage -rfakeroot -uc -us -tc') # As the packages are built in the parent of the buildir, we move them back to build_dir cmds.append('mv ../odoo_* ./') self.run(' && '.join(cmds), self.args.build_dir, 'odoo-deb-build-%s' % TSTAMP) logging.info('Finished building debian package') def start_test(self): if not self.args.test: return logging.info('Start testing debian package') cmds = [ 'service postgresql start', 'su postgres -s /bin/bash -c "createdb mycompany"', '/usr/bin/apt-get update -y', '/usr/bin/dpkg -i /data/src/odoo_%s.%s_all.deb ; /usr/bin/apt-get install -f -y' % (VERSION, TSTAMP), 'su odoo -s /bin/bash -c "odoo -d mycompany -i base --stop-after-init"', 'su odoo -s /bin/bash -c "odoo -d mycompany --pidfile=/data/src/odoo.pid"', ] self.run(' && '.join(cmds), self.args.build_dir, 'odoo-deb-test-%s' % TSTAMP, user='root', detach=True, exposed_port=8069, timeout=300) self.test_odoo() logging.info('Finished testing debian package') class DockerRpm(Docker): """Docker class to build rpm package""" arch = 'rpm' def build(self): logging.info('Start building fedora rpm package') self.run('python3 setup.py --quiet bdist_rpm', self.args.build_dir, 'odoo-rpm-build-%s' % TSTAMP) os.rename(glob('%s/dist/odoo-*.noarch.rpm' % self.args.build_dir)[0], '%s/odoo_%s.%s.rpm' % (self.args.build_dir, VERSION, TSTAMP)) logging.info('Finished building fedora rpm package') def start_test(self): if not self.args.test: return logging.info('Start testing rpm package') cmds = [ 'su postgres -c "/usr/bin/pg_ctl -D /var/lib/postgres/data start"', 'sleep 5', 'su postgres -c "createdb mycompany"', 'dnf install -d 0 -e 0 /data/src/odoo_%s.%s.rpm -y' % (VERSION, TSTAMP), 'su odoo -s /bin/bash -c "odoo -c /etc/odoo/odoo.conf -d mycompany -i base --stop-after-init"', 'su odoo -s /bin/bash -c "odoo -c /etc/odoo/odoo.conf -d mycompany --pidfile=/data/src/odoo.pid"', ] self.run(' && '.join(cmds), args.build_dir, 'odoo-rpm-test-%s' % TSTAMP, user='root', detach=True, exposed_port=8069, timeout=300) self.test_odoo() logging.info('Finished testing rpm package') def gen_rpm_repo(self, args, rpm_filepath): # Removes the old repodata shutil.rmtree(os.path.join(args.pub, 'rpm', 'repodata')) # Copy files to a temp directory (required because the working directory must contain only the # files of the last release) temp_path = tempfile.mkdtemp(suffix='rpmPackages') shutil.copy(rpm_filepath, temp_path) logging.info('Start creating rpm repo') self.run('createrepo /data/src/', temp_path, 'odoo-rpm-createrepo-%s' % TSTAMP) shutil.copytree(os.path.join(temp_path, "repodata"), os.path.join(args.pub, 'rpm', 'repodata')) # Remove temp directory shutil.rmtree(temp_path) # KVM stuffs class KVM(object): def __init__(self, args): self.args = args self.image = args.vm_winxp_image self.ssh_key = args.vm_winxp_ssh_key self.login = args.vm_winxp_login def timeout(self, signum, frame): logging.warning("vm timeout kill (pid: {})".format(self.kvm_proc.pid)) self.kvm_proc.terminate() def start(self): kvm_cmd = [ "kvm", "-cpu", "Skylake-Client,hypervisor=on,hle=off,rtm=off", "-smp", "2,sockets=2,cores=1,threads=1", "-net", "nic,model=e1000e,macaddr=52:54:00:d3:38:5e", "-net", "user,hostfwd=tcp:127.0.0.1:10022-:22,hostfwd=tcp:127.0.0.1:18069-:8069,hostfwd=tcp:127.0.0.1:15432-:5432", "-m", "2048", "-drive", f"if=virtio,file={self.image},snapshot=on", "-nographic", "-serial", "none", ] logging.info("Starting kvm: {}".format(" ".join(kvm_cmd))) self.kvm_proc = subprocess.Popen(kvm_cmd) try: self.wait_ssh(30) # give some time to the VM to start, otherwise the SSH server may not be ready signal.alarm(2400) signal.signal(signal.SIGALRM, self.timeout) self.run() finally: signal.signal(signal.SIGALRM, signal.SIG_DFL) self.kvm_proc.terminate() time.sleep(10) def ssh(self, cmd): run_cmd([ 'ssh', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-p', '10022', '-i', self.ssh_key, '%s@127.0.0.1' % self.login, cmd ]).check_returncode() def rsync(self, rsync_args, options=['--delete', '--exclude', '.git', '--exclude', '.tx', '--exclude', '__pycache__']): cmd = [ 'rsync', '-a', '-e', 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p 10022 -i %s' % self.ssh_key ] cmd.extend(options) cmd.extend(rsync_args) run_cmd(cmd).check_returncode() def wait_ssh(self, n): for i in range(n): try: self.ssh('exit') return except subprocess.CalledProcessError: time.sleep(10) raise Exception('Unable to conncect to the VM') def run(self): pass class KVMWinBuildExe(KVM): def run(self): logging.info('Start building Windows package') with open(os.path.join(self.args.build_dir, 'setup/win32/Makefile.version'), 'w') as f: f.write("VERSION=%s.%s\n" % (VERSION.replace('~', '_').replace('+', ''), TSTAMP)) with open(os.path.join(self.args.build_dir, 'setup/win32/Makefile.python'), 'w') as f: f.write("PYTHON_VERSION=%s\n" % self.args.vm_winxp_python_version) with open(os.path.join(self.args.build_dir, 'setup/win32/Makefile.servicename'), 'w') as f: f.write("SERVICENAME=%s\n" % nt_service_name) remote_build_dir = '/cygdrive/c/odoobuild/server/' self.ssh("mkdir -p build") logging.info("Syncing Odoo files to virtual machine...") self.rsync(['%s/' % self.args.build_dir, '%s@127.0.0.1:%s' % (self.login, remote_build_dir)]) self.ssh("cd {}setup/win32;time make allinone;".format(remote_build_dir)) self.rsync(['%s@127.0.0.1:%ssetup/win32/release/' % (self.login, remote_build_dir), '%s/' % self.args.build_dir]) logging.info('Finished building Windows package') class KVMWinTestExe(KVM): def run(self): logging.info('Start testing Windows package') setup_path = glob("%s/odoo_setup_*.exe" % self.args.build_dir)[0] setupfile = setup_path.split('/')[-1] setupversion = setupfile.split('odoo_setup_')[1].split('.exe')[0] self.rsync(['%s' % setup_path, '%s@127.0.0.1:' % self.login]) self.ssh("TEMP=/tmp ./%s /S" % setupfile) self.ssh('PGPASSWORD=openpgpwd /cygdrive/c/"Program Files"/"Odoo %s"/PostgreSQL/bin/createdb.exe -e -U openpg mycompany' % setupversion) self.ssh('netsh advfirewall set publicprofile state off') self.ssh('/cygdrive/c/"Program Files"/"Odoo {sv}"/python/python.exe \'c:\\Program Files\\Odoo {sv}\\server\\odoo-bin\' -d mycompany -i base --stop-after-init'.format(sv=setupversion)) _rpc_count_modules(port=18069) logging.info('Finished testing Windows package') def build_exe(args): KVMWinBuildExe(args).start() def test_exe(args): if args.test: KVMWinTestExe(args).start() def parse_args(): ap = argparse.ArgumentParser() build_dir = "%s-%s" % (ROOTDIR, TSTAMP) log_levels = {"debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARN, "error": logging.ERROR, "critical": logging.CRITICAL} ap.add_argument("-b", "--build-dir", default=build_dir, help="build directory (%(default)s)", metavar="DIR") ap.add_argument("-p", "--pub", default=None, help="pub directory %(default)s", metavar="DIR") ap.add_argument("--logging", action="store", choices=list(log_levels.keys()), default="info", help="Logging level") ap.add_argument("--build-deb", action="store_true") ap.add_argument("--build-rpm", action="store_true") ap.add_argument("--build-tgz", action="store_true") ap.add_argument("--build-win", action="store_true") # Windows VM ap.add_argument("--vm-winxp-image", default='/home/odoo/vm/win1036/win10_winpy36.qcow2', help="%(default)s") ap.add_argument("--vm-winxp-ssh-key", default='/home/odoo/vm/win1036/id_rsa', help="%(default)s") ap.add_argument("--vm-winxp-login", default='Naresh', help="Windows login %(default)s") ap.add_argument("--vm-winxp-python-version", default='3.7.7', help="Windows Python version installed in the VM (default: %(default)s)") ap.add_argument("-t", "--test", action="store_true", default=False, help="Test built packages") ap.add_argument("-s", "--sign", action="store_true", default=False, help="Sign Debian package / generate Rpm repo") ap.add_argument("--no-remove", action="store_true", help="don't remove build dir") ap.add_argument("--blacklist", nargs="*", help="Modules to blacklist in package") parsed_args = ap.parse_args() logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %I:%M:%S', level=log_levels[parsed_args.logging]) parsed_args.odoo_dir = ROOTDIR return parsed_args def main(args): try: if args.build_tgz: _prepare_build_dir(args) docker_tgz = DockerTgz(args) docker_tgz.build() try: docker_tgz.start_test() published_files = publish(args, 'tgz', ['tar.gz', 'zip']) except Exception as e: logging.error("Won't publish the tgz release.\n Exception: %s" % str(e)) if args.build_rpm: _prepare_build_dir(args) docker_rpm = DockerRpm(args) docker_rpm.build() try: docker_rpm.start_test() published_files = publish(args, 'rpm', ['rpm']) if args.sign: logging.info('Signing rpm package') rpm_sign(args, published_files[0]) logging.info('Generate rpm repo') docker_rpm.gen_rpm_repo(args, published_files[0]) except Exception as e: logging.error("Won't publish the rpm release.\n Exception: %s" % str(e)) if args.build_deb: _prepare_build_dir(args, move_addons=False) docker_deb = DockerDeb(args) docker_deb.build() try: docker_deb.start_test() published_files = publish(args, 'deb', ['deb', 'dsc', 'changes', 'tar.xz']) gen_deb_package(args, published_files) except Exception as e: logging.error("Won't publish the deb release.\n Exception: %s" % str(e)) if args.build_win: _prepare_build_dir(args, win32=True) build_exe(args) try: test_exe(args) published_files = publish(args, 'windows', ['exe']) except Exception as e: logging.error("Won't publish the exe release.\n Exception: %s" % str(e)) except Exception as e: logging.error('Something bad happened ! : {}'.format(e)) traceback.print_exc() finally: if args.no_remove: logging.info('Build dir "{}" not removed'.format(args.build_dir)) else: if os.path.exists(args.build_dir): shutil.rmtree(args.build_dir) logging.info('Build dir %s removed' % args.build_dir) if __name__ == '__main__': args = parse_args() if os.path.exists(args.build_dir): logging.error('Build dir "%s" already exists.', args.build_dir) sys.exit(1) main(args)
42.191781
24,640
12,566
py
PYTHON
15.0
#!/usr/bin/env python """ Checks versions from the requirements files against distribution-provided versions, taking distribution's Python version in account e.g. if checking against a release which bundles Python 3.5, checks the 3.5 version of requirements. * only shows requirements for which at least one release diverges from the matching requirements version * empty cells mean that specific release matches its requirement (happens when checking multiple releases: one of the other releases may mismatch the its requirements necessating showing the row) Only handles the subset of requirements files we're currently using: * no version spec or strict equality * no extras * only sys_platform and python_version environment markers """ import argparse import gzip import itertools import json import operator import re import string from abc import ABC, abstractmethod from pathlib import Path from urllib.request import urlopen from sys import stdout, stderr from typing import Dict, List, Set, Optional, Any, Tuple Version = Tuple[int, ...] def parse_version(vstring: str) -> Optional[Version]: if not vstring: return None return tuple(map(int, vstring.split('.'))) # shared beween debian and ubuntu SPECIAL = { 'pytz': 'tz', 'libsass': 'libsass-python', } def unfuck(s: str) -> str: """ Try to strip the garbage from the version string, just remove everything following the first `+`, `~` or `-` """ return re.match(r''' (?:\d+:)? # debian crud prefix (.*?) # the shit we actually want (?:~|\+|-|\.dfsg) .* ''', s, flags=re.VERBOSE)[1] class Distribution(ABC): def __init__(self, release): self._release = release @abstractmethod def get_version(self, package: str) -> Optional[Version]: ... def __str__(self): return f'{type(self).__name__.lower()} {self._release}' @classmethod def get(cls, name): try: return next( c for c in cls.__subclasses__() if c.__name__.lower() == name ) except StopIteration: raise ValueError(f"Unknown distribution {name!r}") class Debian(Distribution): def get_version(self, package): """ Try to find which version of ``package`` is in Debian release {release} """ package = SPECIAL.get(package, package) # try the python prefix first: some packages have a native of foreign $X and # either the bindings or a python equivalent at python-X, or just a name # collision for prefix in ['python-', '']: res = json.load(urlopen(f'https://sources.debian.org/api/src/{prefix}{package}')) if res.get('error') is None: break if res.get('error'): return return next( parse_version(unfuck(distr['version'])) for distr in res['versions'] if distr['area'] == 'main' if self._release in distr['suites'] ) class Ubuntu(Distribution): """ Ubuntu doesn't have an API, instead it has a huge text file """ def __init__(self, release): super().__init__(release) self._packages = {} # ideally we should request the proper Content-Encoding but PUC # apparently does not care, and returns a somewhat funky # content-encoding (x-gzip) anyway data = gzip.open( urlopen(f'https://packages.ubuntu.com/source/{release}/allpackages?format=txt.gz'), mode='rt', encoding='utf-8' ) for line in itertools.islice(data, 6, None): # first 6 lines is garbage header # ignore the restricted, security, universe, multiverse tags m = re.match(r'(\S+) \(([^)]+)\)', line.strip()) assert m, f"invalid line {line.strip()!r}" self._packages[m[1]] = m[2] def get_version(self, package): package = SPECIAL.get(package, package) for prefix in ['python3-', 'python-', '']: v = self._packages.get(f'{prefix}{package}') if v: return parse_version(unfuck(v)) return None class Markers: """ Simplistic RD parser for requirements env markers. Evaluation of the env markers is so basic it goes to brunch in uggs. """ def __init__(self, s=None): self.rules = False if s is not None: self.rules, rest = self._parse_marker(s) assert not rest def evaluate(self, context: Dict[str, Any]) -> bool: if not self.rules: return True return self._eval(self.rules, context) def _eval(self, rule, context): if rule[0] == 'OR': return self._eval(rule[1], context) or self._eval(rule[2], context) elif rule[0] == 'AND': return self._eval(rule[1], context) and self._eval(rule[2], context) elif rule[0] == 'ENV': return context[rule[1]] elif rule[0] == 'LIT': return rule[1] else: op, var1, var2 = rule var1 = self._eval(var1, context) var2 = self._eval(var2, context) # NOTE: currently doesn't follow PEP440 version matching at all if op == '==': return var1 == var2 elif op == '!=': return var1 != var2 elif op == '<': return var1 < var2 elif op == '<=': return var1 <= var2 elif op == '>': return var1 > var2 elif op == '>=': return var1 >= var2 else: raise NotImplementedError(f"Operator {op!r}") def _parse_marker(self, s): return self._parse_or(s) def _parse_or(self, s): sub1, rest = self._parse_and(s) expr, n = re.subn(r'^\s*or\b', '', rest, count=1) if not n: return sub1, rest sub2, rest = self._parse_and(expr) return ('OR', sub1, sub2), rest def _parse_and(self, s): sub1, rest = self._parse_expr(s) expr, n = re.subn(r'\s*and\b', '', rest, count=1) if not n: return sub1, rest sub2, rest = self._parse_expr(expr) return ('AND', sub1, sub2), rest def _parse_expr(self, s): expr, n = re.subn(r'^\s*\(', '', s, count=1) if n: sub, rest = self.parse_marker(expr) rest, n = re.subn(r'\s*\)', '', rest, count=1) assert n, f"expected closing parenthesis, found {rest}" return sub, rest var1, rest = self._parse_var(s) op, rest = self._parse_op(rest) var2, rest = self._parse_var(rest) return (op, var1, var2), rest def _parse_op(self, s): m = re.match(r''' \s* (<= | < | != | >= | > | ~= | ===? | in \b | not \s+ in \b) (.*) ''', s, re.VERBOSE) assert m, f"no operator in {s!r}" return m.groups() def _parse_var(self, s): python_str = re.escape(string.printable.translate(str.maketrans({ '"': '', "'": '', '\\': '', '-': '', }))) m = re.match(fr''' \s* (:? # TODO: add more envvars (?P<env>python_version | os_name | sys_platform) | " (?P<dquote>['{python_str}-]*) " | ' (?P<squote>["{python_str}-]*) ' ) (?P<rest>.*) ''', s, re.VERBOSE) assert m, f"failed to find marker var in {s}" if m['env']: return ('ENV', m['env']), m['rest'] return ('LIT', m['dquote'] or m['squote'] or ''), m['rest'] def parse_spec(line: str) -> (str, (Optional[str], Optional[str]), Markers): """ Parse a requirements specification (a line of requirements) Returns the package name, a version spec (operator and comparator) possibly None and a Markers object. Not correctly supported: * version matching, not all operators are implemented and those which are almost certainly don't match PEP 440 Not supported: * url requirements * multi-versions spec * extras * continuations Full grammar is at https://www.python.org/dev/peps/pep-0508/#complete-grammar """ # weirdly a distribution name can apparently start with a number name, rest = re.match(r'([\w\d](?:[._-]*[\w\d]+)*)\s*(.*)', line.strip()).groups() # skipping extras version_cmp = version = None versionspec = re.match(r''' (< | <= | != | == | >= | > | ~= | ===) \s* ([\w\d_.*+!-]+) \s* (.*) ''', rest, re.VERBOSE) if versionspec: version_cmp, version, rest = versionspec.groups() markers = Markers() if rest[:1] == ';': markers = Markers(rest[1:]) return name, (version_cmp, version), markers def parse_requirements(reqpath: Path) -> Dict[str, List[Tuple[str, Markers]]]: """ Parses a requirement file to a dict of {package: [(version, markers)]} The env markers express *whether* that specific dep applies. """ reqs = {} for line in reqpath.open('r', encoding='utf-8'): if line.isspace() or line.startswith('#'): continue name, (op, version), markers = parse_spec(line) assert op is None or op == '==', f"unexpected version comparator {op}" reqs.setdefault(name, []).append((version, markers)) return reqs def main(args): checkers = [ Distribution.get(distro)(release) for version in args.release for (distro, release) in [version.split(':')] ] stderr.write(f"Fetch Python versions...\n") pyvers = [ '.'.join(map(str, checker.get_version('python3-defaults')[:2])) for checker in checkers ] uniq = sorted(v for v in set(pyvers)) table = [ [''] + [f'req {v}' for v in uniq] + [f'{checker._release} ({version})' for checker, version in zip(checkers, pyvers)] ] reqs = parse_requirements((Path.cwd() / __file__).parent.parent / 'requirements.txt') tot = len(reqs) * len(checkers) def progress(n=iter(range(tot+1))): stderr.write(f"\rFetch requirements: {next(n)} / {tot}") progress() for req, options in reqs.items(): row = [req] byver = {} for pyver in uniq: # FIXME: when multiple options apply, check which pip uses # (first-matching. best-matching, latest, ...) for version, markers in options: if markers.evaluate({ 'python_version': pyver, 'sys_platform': 'linux', }): byver[pyver] = version break row.append(byver.get(pyver) or '') # this requirement doesn't apply, ignore if not byver: # normally the progressbar is updated when processing each # requirement against each checker, if the requirement doesn't apply # to any checker we still need to consider the requirement fetched / # resolved for each checker or our tally is incorrect for _ in checkers: progress() continue mismatch = False for i, c in enumerate(checkers): req_version = byver.get(pyvers[i], '') check_version = '.'.join(map(str, c.get_version(req.lower()) or ['<missing>'])) progress() if req_version != check_version: row.append(check_version) mismatch = True else: row.append('') # only show row if one of the items diverges from requirement if mismatch: table.append(row) stderr.write('\n') # evaluate width of columns sizes = [0] * (len(checkers) + len(uniq) + 1) for row in table: sizes = [ max(s, len(cell)) for s, cell in zip(sizes, row) ] # format table for row in table: stdout.write('| ') for cell, width in zip(row, sizes): stdout.write(f'{cell:<{width}} | ') stdout.write('\n') if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( 'release', nargs='+', help="Release to check against, should use the format '{distro}:{release}' e.g. 'debian:sid'" ) args = parser.parse_args() main(args)
33.331565
12,566
1,731
py
PYTHON
15.0
# WSGI Handler sample configuration file. # # Change the appropriate settings below, in order to provide the parameters # that would normally be passed in the command-line. # (at least conf['addons_path']) # # For generic wsgi handlers a global application is defined. # For uwsgi this should work: # $ uwsgi_python --http :9090 --pythonpath . --wsgi-file openerp-wsgi.py # # For gunicorn additional globals need to be defined in the Gunicorn section. # Then the following command should run: # $ gunicorn odoo:service.wsgi_server.application -c openerp-wsgi.py import odoo #---------------------------------------------------------- # Common #---------------------------------------------------------- odoo.multi_process = True # Nah! # Equivalent of --load command-line option odoo.conf.server_wide_modules = ['base', 'web'] conf = odoo.tools.config # Path to the OpenERP Addons repository (comma-separated for # multiple locations) conf['addons_path'] = '../../addons/trunk,../../web/trunk/addons' # Optional database config if not using local socket #conf['db_name'] = 'mycompany' #conf['db_host'] = 'localhost' #conf['db_user'] = 'foo' #conf['db_port'] = 5432 #conf['db_password'] = 'secret' #---------------------------------------------------------- # Generic WSGI handlers application #---------------------------------------------------------- application = odoo.service.wsgi_server.application odoo.service.server.load_server_wide_modules() #---------------------------------------------------------- # Gunicorn #---------------------------------------------------------- # Standard OpenERP XML-RPC port is 8069 bind = '127.0.0.1:8069' pidfile = '.gunicorn.pid' workers = 4 timeout = 240 max_requests = 2000
32.660377
1,731
1,501
py
PYTHON
15.0
#!/usr/bin/python # # Runme From the repo toplevel directory # from __future__ import print_function import subprocess import glob import re import pprint cla_glob = "doc/cla/*/*.md" cla = ''.join(open(f).read() for f in glob.glob(cla_glob)) cla = cla.lower() def cla_signed(email): if re.match('.*(odoo|openerp|tinyerp).com$',email): return True if cla.find(email) != -1: return True return False def blamestat(ext='py'): r = {} ok = 0 okl = [] ko = 0 kol = [] p = subprocess.Popen("git ls-tree -r -z --name-only HEAD | grep -z '.%s$' | xargs -0 -n1 git blame --line-porcelain HEAD |grep '^author-mail ' |sort |uniq -c|sort -nr" % ext, shell=True, stdout = subprocess.PIPE) for i in p.stdout.read().split('\n'): mo = re.search('(\d+) author-mail <([^ @<]+@[^ @<]+)>',i) if mo: lines = int(mo.group(1)) email = mo.group(2) if cla_signed(email): ok += lines okl.append(i) else: ko += lines kol.append(i) print('-'*60) print('Stats for ', ext) print('-'*60) print("\nCLA SIGNED %s/%s (%.0f%%)" % (ok, ok+ko, ok*100.0/(ok+ko))) for i in okl: print(i) print("\nCLA MISSING %s/%s (%.0f%%)\n" % (ko, ok+ko, ko*100.0/(ok+ko))) for i in kol: print(i) print() print() blamestat('md') blamestat('rst') blamestat('py') blamestat('js') blamestat('xml') blamestat('csv')
25.440678
1,501
725
py
PYTHON
15.0
# Copyright 2012-2013 Akretion Sébastien BEAU,David Beal,Alexis de Lattre # Copyright 2016 Sodexis # Copyright 2018 bloopark systems (<http://bloopark.de>) # Copyright 2019 Tecnativa - Cristina Martin R. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Scheduler Error Mailer", "version": "15.0.1.0.0", "category": "Extra Tools", "license": "AGPL-3", "author": "Akretion,Sodexis,Odoo Community Association (OCA)", "website": "https://github.com/OCA/server-tools", "depends": ["mail"], "data": ["data/ir_cron_email_tpl.xml", "views/ir_cron.xml"], "demo": ["demo/ir_cron_demo.xml"], "images": ["images/scheduler_error_mailer.jpg"], "installable": True, }
38.105263
724
1,649
py
PYTHON
15.0
# Copyright 2012-2013 Akretion Sébastien BEAU,David Beal,Alexis de Lattre # Copyright 2016 Sodexis # Copyright 2018 bloopark systems (<http://bloopark.de>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import _, api, fields, models from odoo.exceptions import UserError _logger = logging.getLogger(__name__) class IrCron(models.Model): _inherit = "ir.cron" email_template_id = fields.Many2one( comodel_name="mail.template", domain=[("model_id.model", "=", "ir.cron")], string="Error E-mail Template", help="Select the email template that will be sent when " "this scheduler fails.", ) @api.model def _handle_callback_exception( self, cron_name, server_action_id, job_id, job_exception ): res = super()._handle_callback_exception( cron_name, server_action_id, job_id, job_exception ) my_cron = self.browse(job_id) if my_cron.email_template_id: # we put the job_exception in context to be able to print it inside # the email template context = {"job_exception": str(job_exception), "dbname": self._cr.dbname} _logger.debug("Sending scheduler error email with context=%s", context) template = my_cron.email_template_id.with_context(**context).sudo() template.send_mail(my_cron.id, force_send=True) return res @api.model def _test_scheduler_failure(self): """This function is used to test and debug this module.""" raise UserError(_("Task failure with UID = %d.") % self._uid)
33.632653
1,648
1,878
py
PYTHON
15.0
# Copyright (C) 2021 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo import modules from odoo.tools import config _logger = logging.getLogger(__name__) _original_load_information_from_description_file = ( modules.module.load_information_from_description_file ) def split_strip(s): """Split string and strip each component sep by comma >>> split_strip("foo, bar,") ['foo', 'bar'] >>> split_strip("") [] >>> split_strip(None) [] """ s = (s or "").strip(" ,") if not s: return [] return [x.strip() for x in s.split(",")] def _overload_load_information_from_description_file(module, mod_path=None): res = _original_load_information_from_description_file(module, mod_path=None) auto_install = res.get("auto_install", False) modules_auto_install_enabled = split_strip( config.get("modules_auto_install_enabled") ) modules_auto_install_disabled = split_strip( config.get("modules_auto_install_disabled") ) if auto_install and module in modules_auto_install_disabled: _logger.info("Module '%s' has been marked as not auto installable." % module) res["auto_install"] = False if not auto_install and module in modules_auto_install_enabled: _logger.info("Module '%s' has been marked as auto installable." % module) res["auto_install"] = set(res["depends"]) return res def post_load(): _logger.info("Applying patch module_change_auto_intall") modules.module.load_information_from_description_file = ( _overload_load_information_from_description_file ) modules.load_information_from_description_file = ( _overload_load_information_from_description_file )
29.809524
1,878
617
py
PYTHON
15.0
# Copyright (C) 2021 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Change auto installable modules", "summary": "Customize auto installables modules by configuration", "version": "15.0.1.0.0", "category": "Tools", "maintainers": ["legalsylvain"], "author": "GRAP, Odoo Community Association (OCA)", "website": "https://github.com/OCA/server-tools", "installable": True, "depends": ["base"], "post_load": "post_load", "license": "AGPL-3", }
36.294118
617
510
py
PYTHON
15.0
# © 2013 Therp BV # © 2014 ACSONE SA/NV # Copyright 2018 Quartile Limited # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "dbfilter_from_header", "summary": "Filter databases with HTTP headers", "version": "15.0.1.0.0", "website": "https://github.com/OCA/server-tools", "author": "Therp BV, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Tools", "depends": ["web"], "auto_install": False, "installable": True, }
29.882353
508
792
py
PYTHON
15.0
# © 2013 Therp BV # © 2014 ACSONE SA/NV # Copyright 2018 Quartile Limited # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging import re from odoo import http from odoo.tools import config db_filter_org = http.db_filter def db_filter(dbs, httprequest=None): dbs = db_filter_org(dbs, httprequest) httprequest = httprequest or http.request.httprequest db_filter_hdr = httprequest.environ.get("HTTP_X_ODOO_DBFILTER") if db_filter_hdr: dbs = [db for db in dbs if re.match(db_filter_hdr, db)] return dbs if config.get("proxy_mode") and "dbfilter_from_header" in config.get( "server_wide_modules" ): _logger = logging.getLogger(__name__) _logger.info("monkey patching http.db_filter") http.db_filter = db_filter
27.241379
790
581
py
PYTHON
15.0
# Copyright 2019-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) { "name": "Conditional Images", "summary": "This module extends the functionality to support conditional images", "version": "15.0.1.0.0", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Misc", "depends": [ "base", ], "website": "https://github.com/OCA/server-tools", "data": [ "views/image_view.xml", "security/ir.model.access.csv", ], "installable": True, }
29.05
581
1,003
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import fields, models class ConditionalImage(models.Model): _name = "conditional.image" _description = "Conditional Image" _inherit = ["image.mixin"] name = fields.Char(required=True) model_name = fields.Char(required=True) selector = fields.Text( help="Python expression used as selector when multiple images are used" "for the same object. The variable `object` refers " "to the actual record on which the expression will be executed. " "An empty expression will always return `True`.", ) company_id = fields.Many2one( "res.company", "Company", help="Company related check. If inherited object does not have a " "`company_id` field, it will be ignored. " "The check will first take the records with a company then, " "if no match is found, the ones without a company.", )
37.148148
1,003
2,633
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import fields, models from odoo.tools.safe_eval import safe_eval class ConditionalImageConsumerMixin(models.AbstractModel): _name = "conditional.image.consumer.mixin" _description = "Mixin for conditional images consumers" _inherit = "image.mixin" image_1920 = fields.Image(compute="_compute_images", store=False, readonly=True) image_1024 = fields.Image(compute="_compute_images", store=False, readonly=True) image_512 = fields.Image(compute="_compute_images", store=False, readonly=True) image_256 = fields.Image(compute="_compute_images", store=False, readonly=True) image_128 = fields.Image(compute="_compute_images", store=False, readonly=True) def _conditional_image_evaluate_selector(self, conditional_image): self.ensure_one() if conditional_image.selector: if ( conditional_image.company_id == self.company_id or self.company_id and not conditional_image.company_id ): return bool( safe_eval(conditional_image.selector or "True", {"object": self}) ) return False def _compute_images(self): if "company_id" in self._fields: search_clause = [("model_name", "=", self._name)] else: # If inherited object doesn't have a `company_id` field, # remove the items with a company defined and the related checks search_clause = [ ("model_name", "=", self._name), ("company_id", "=", False), ] conditional_images = self.env["conditional.image"].search( search_clause, order="company_id, selector" ) for record in self: images_found = conditional_images.filtered( lambda img: record._conditional_image_evaluate_selector(img) ) values = { "image_1920": False, "image_1024": False, "image_512": False, "image_256": False, "image_128": False, } if images_found: image = images_found[0] values = { "image_1920": image.image_1920, "image_1024": image.image_1024, "image_512": image.image_512, "image_256": image.image_256, "image_128": image.image_128, } record.update(values)
39.298507
2,633
503
py
PYTHON
15.0
# Copyright (C) 2019-Today: GRAP (<http://www.grap.coop/>) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID, api def analyse_installed_modules(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) installed_modules = env["ir.module.module"].search( ["|", ("state", "=", "installed"), ("name", "=", "module_analysis")] ) installed_modules.button_analyse_code()
38.692308
503
1,167
py
PYTHON
15.0
# Copyright (C) 2019-Today: GRAP (<http://www.grap.coop/>) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Module Analysis", "summary": "Add analysis tools regarding installed modules" " to know which installed modules comes from Odoo Core, OCA, or are" " custom modules", "author": "GRAP, Odoo Community Association (OCA)", "website": "https://github.com/OCA/server-tools", "version": "15.0.1.1.1", "license": "AGPL-3", "depends": ["base"], "data": [ "security/ir.model.access.csv", "views/menu.xml", "views/view_base_module_update.xml", "views/view_ir_module_author.xml", "views/view_ir_module_type.xml", "views/view_ir_module_type_rule.xml", "views/view_ir_module_module.xml", "data/ir_cron.xml", "data/ir_config_parameter.xml", "data/ir_module_type.xml", "data/ir_module_type_rule.xml", ], "external_dependencies": { "python": ["pygount"], }, "post_init_hook": "analyse_installed_modules", "installable": True, }
35.363636
1,167
1,639
py
PYTHON
15.0
# Copyright (C) 2019-Today: GRAP (<http://www.grap.coop/>) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase, tagged @tagged("-at_install", "post_install") class TestModule(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.IrModuleModule = cls.env["ir.module.module"] # Remove lib because it breaks tests in case of installation of modules with # pip cls.env["ir.config_parameter"].set_param( "module_analysis.exclude_directories", "demo,test,tests,doc,description" ) cls.IrModuleModule.cron_analyse_code() def test_installed_modules(self): installed_modules = self.IrModuleModule.search( [("state", "=", "installed"), ("name", "not like", "_test")] ) for module in installed_modules: self.assertTrue( module.python_code_qty > 0 or module.xml_code_qty > 0 or module.js_code_qty > 0, "module '%s' doesn't have code analysed defined, whereas it is" " installed." % (module.name), ) def test_uninstalled_modules(self): uninstalled_modules = self.IrModuleModule.search([("state", "!=", "installed")]) for module in uninstalled_modules: self.assertTrue( module.python_code_qty == 0, "module '%s' has python lines defined, whereas it is" " not installed." % (module.name), )
39.97561
1,639
6,437
py
PYTHON
15.0
# Copyright (C) 2019-Today: GRAP (<http://www.grap.coop/>) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging import os from pathlib import Path from pygount import SourceAnalysis from odoo import api, fields, models from odoo.modules.module import get_module_path from odoo.tools.safe_eval import safe_eval _logger = logging.getLogger(__name__) class IrModuleModule(models.Model): _inherit = "ir.module.module" author_ids = fields.Many2many( string="Authors", comodel_name="ir.module.author", readonly=True, relation="ir_module_module_author_rel", ) module_type_id = fields.Many2one( string="Module Type", comodel_name="ir.module.type", readonly=True ) python_code_qty = fields.Integer(string="Python Code Quantity", readonly=True) xml_code_qty = fields.Integer(string="XML Code Quantity", readonly=True) js_code_qty = fields.Integer(string="JS Code Quantity", readonly=True) css_code_qty = fields.Integer(string="CSS Code Quantity", readonly=True) # Overloadable Section @api.model def _get_analyse_settings(self): """Return a dictionnary of data analysed Overload this function if you want to analyse other data { 'extension': { 'data_to_analyse': 'field_name', }, }, [...] extension: extension of the file, with the '.' data_to_analyse : possible value : code, documentation, empty, string field_name: Odoo field name to store the analysis """ return { ".py": {"code": "python_code_qty"}, ".xml": {"code": "xml_code_qty"}, ".js": {"code": "js_code_qty"}, ".css": {"code": "css_code_qty"}, } @api.model def _get_clean_analyse_values(self): """List of fields to unset when a module is uninstalled""" return { "author_ids": [(6, 0, [])], "module_type_id": False, "python_code_qty": False, "xml_code_qty": 0, "js_code_qty": 0, "css_code_qty": 0, } @api.model def _get_module_encoding(self, file_ext): return "utf-8" # Overload Section @api.model def update_list(self): res = super().update_list() if self.env.context.get("analyse_installed_modules", False): self.search([("state", "=", "installed")])._analyse_code() return res def write(self, vals): res = super().write(vals) if vals.get("state", False) == "uninstalled" and "module_analysis" not in [ x.name for x in self ]: self.write(self._get_clean_analyse_values()) return res # Public Section def button_analyse_code(self): self._analyse_code() @api.model def cron_analyse_code(self): self.search([("state", "=", "installed")])._analyse_code() # Custom Section def _analyse_code(self): IrModuleAuthor = self.env["ir.module.author"] IrModuleTypeRule = self.env["ir.module.type.rule"] rules = IrModuleTypeRule.search([]) cfg = self.env["ir.config_parameter"] val = cfg.get_param("module_analysis.exclude_directories", "") exclude_directories = [x.strip() for x in val.split(",") if x.strip()] val = cfg.get_param("module_analysis.exclude_files", "") exclude_files = [x.strip() for x in val.split(",") if x.strip()] for module in self: _logger.info("Analysing Code for module %s ..." % (module.name)) # Update Authors, based on manifest key authors = [] if module.author and module.author[0] == "[": author_txt_list = safe_eval(module.author) else: author_txt_list = (module.author and module.author.split(",")) or [] author_txt_list = [x.strip() for x in author_txt_list] author_txt_list = [x for x in author_txt_list if x] for author_txt in author_txt_list: authors.append(IrModuleAuthor._get_or_create(author_txt)) author_ids = [x.id for x in authors] module.author_ids = author_ids # Update Module Type, based on rules module_type_id = rules._get_module_type_id_from_module(module) module.module_type_id = module_type_id # Get Path of module folder and parse the code module_path = get_module_path(module.name) # Get Files analysed_datas = self._get_analyse_data_dict() file_extensions = analysed_datas.keys() file_list = self._get_files_to_analyse( module_path, file_extensions, exclude_directories, exclude_files ) for file_path, file_ext in file_list: file_res = SourceAnalysis.from_file( file_path, "", encoding=self._get_module_encoding(file_ext) ) for k, v in analysed_datas.get(file_ext).items(): v["value"] += getattr(file_res, k) # Update the module with the datas values = {} for analyses in analysed_datas.values(): for v in analyses.values(): values[v["field"]] = v["value"] module.write(values) @api.model def _get_files_to_analyse( self, path, file_extensions, exclude_directories, exclude_files ): res = [] if not path: return res for root, _, files in os.walk(path, followlinks=True): if set(Path(root).parts) & set(exclude_directories): continue for name in files: if name in exclude_files: continue filename, file_extension = os.path.splitext(name) if file_extension in file_extensions: res.append((os.path.join(root, name), file_extension)) return res @api.model def _get_analyse_data_dict(self): res_dict = self._get_analyse_settings().copy() for analyse_dict in res_dict.values(): for analyse_type, v in analyse_dict.items(): analyse_dict[analyse_type] = {"field": v, "value": 0} return res_dict
35.174863
6,437
947
py
PYTHON
15.0
# Copyright (C) 2019-Today: GRAP (<http://www.grap.coop/>) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class IrModuleType(models.Model): _name = "ir.module.type" _description = "Modules Types" _order = "sequence" name = fields.Char(required=True) sequence = fields.Integer() installed_module_ids = fields.One2many( string="Installed Modules", comodel_name="ir.module.module", inverse_name="module_type_id", ) installed_module_qty = fields.Integer( string="Modules Quantity", compute="_compute_installed_module_qty", store=True ) @api.depends("installed_module_ids.module_type_id") def _compute_installed_module_qty(self): for module_type in self: module_type.installed_module_qty = len(module_type.installed_module_ids)
31.566667
947