From 7b3edd3e51e60f197514367ab5ea65e380704612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Arturo=20Garci=CC=81a?= Date: Sun, 30 Aug 2026 18:28:13 -0400 Subject: [PATCH] Homologate fiscal management with Tryton 8.0 --- CHANGELOG | 12 + __init__.py | 10 +- configuration.py | 31 +- doc/index.rst | 81 +- importer.py | 333 ++++++ importer.xml | 26 + invoice.fodt | 32 +- invoice.py | 787 ++++++++------ invoice.xml | 12 - locale/es.po | 711 +++++++++++++ locale/es_419.po | 1518 ++++++++++++++++++--------- locale/es_DO.po | 198 ++++ message.xml | 143 ++- ncf_manager.py | 542 +++++++++- ncf_manager.xml | 44 +- party.py | 32 +- report.py | 20 - sequence.py | 215 ++-- sequence.xml | 6 - setup.py | 8 +- tests/test_module.py | 826 ++++++++++++++- tests/test_sequence_helpers.py | 94 ++ tox.ini | 2 +- tryton.cfg | 9 +- user.py | 17 + user.xml | 10 + view/invoice_form.xml | 33 +- view/invoice_tree.xml | 10 + view/ncf_import_start_form.xml | 16 + view/ncf_manager_form.xml | 47 +- view/ncf_manager_sequence_form.xml | 14 - view/ncf_manager_sequence_tree.xml | 9 - view/ncf_manager_sequences_form.xml | 53 +- view/ncf_manager_sequences_tree.xml | 8 + view/ncf_manager_tree.xml | 2 + view/sequence_list.xml | 10 - view/user_form.xml | 9 + 37 files changed, 4782 insertions(+), 1148 deletions(-) create mode 100644 CHANGELOG create mode 100644 importer.py create mode 100644 importer.xml create mode 100644 locale/es.po create mode 100644 locale/es_DO.po delete mode 100644 report.py create mode 100644 tests/test_sequence_helpers.py create mode 100644 user.py create mode 100644 user.xml create mode 100644 view/ncf_import_start_form.xml delete mode 100644 view/ncf_manager_sequence_form.xml delete mode 100644 view/ncf_manager_sequence_tree.xml delete mode 100644 view/sequence_list.xml create mode 100644 view/user_form.xml diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..ae7fe60 --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,12 @@ +Version 7.0.3 - 2026-08-30 +========================== + +* Homologación funcional con la serie 8.0 manteniendo el registro y el + empaquetado propios de Tryton 7.0. +* Flujo protegido de autorizaciones y rangos NCF, importador DGII idempotente, + auditoría de activación y cierre, y restricciones por usuario. +* Validaciones de prefijo, rango, solapamiento por dirección, numeración, + notas de crédito/débito y cancelación fiscal. +* Corrección de búsquedas de montos por tipo de producto y compatibilidad con + nombres Unicode de secuencias electrónicas. + diff --git a/__init__.py b/__init__.py index 4570639..cb8edce 100644 --- a/__init__.py +++ b/__init__.py @@ -1,10 +1,11 @@ from trytond.pool import Pool from . import invoice +from . import importer from . import ncf_manager from . import sequence from . import configuration from . import party -from . import report +from . import user def register(): Pool.register( @@ -17,7 +18,12 @@ def register(): configuration.DefaultNcfType, party.PartyNcfType, party.Party, + user.User, + importer.ImportNCFStart, module='ncf_manager', type_='model') Pool.register( - report.InvoiceReport, + importer.ImportNCF, + module='ncf_manager', type_='wizard') + Pool.register( + invoice.InvoiceReport, module='ncf_manager', type_='report') diff --git a/configuration.py b/configuration.py index 80dcfa5..e43644e 100644 --- a/configuration.py +++ b/configuration.py @@ -2,6 +2,7 @@ # this repository contains the full copyright notices and license terms. import logging +from trytond import backend from trytond.model import fields, ModelSQL from trytond.modules.company.model import CompanyValueMixin from trytond.pool import PoolMeta, Pool @@ -12,6 +13,11 @@ from trytond.modules.ncf_manager.ncf_manager import NCF_TYPE logger = logging.getLogger(__name__) +def _backend_name(): + name = backend.name + return name() if callable(name) else name + + class Configuration(metaclass=PoolMeta): 'Account Configuration' __name__ = 'account.configuration' @@ -80,6 +86,9 @@ class DefaultNcfType(ModelSQL, CompanyValueMixin): @classmethod def _ncf_column_exists(cls, cursor, table_name, column_name): + if _backend_name() == 'sqlite': + cursor.execute(f'PRAGMA table_info("{table_name}")') + return any(row[1] == column_name for row in cursor.fetchall()) cursor.execute(""" SELECT 1 FROM information_schema.columns @@ -90,6 +99,12 @@ class DefaultNcfType(ModelSQL, CompanyValueMixin): @classmethod def _ncf_column_udt_name(cls, cursor, table_name, column_name): + if _backend_name() == 'sqlite': + cursor.execute(f'PRAGMA table_info("{table_name}")') + for row in cursor.fetchall(): + if row[1] == column_name: + return (row[2] or '').lower() + return None cursor.execute(""" SELECT udt_name FROM information_schema.columns @@ -129,7 +144,7 @@ class DefaultNcfType(ModelSQL, CompanyValueMixin): udt_name = cls._ncf_column_udt_name( cursor, table_name, old_column) - if udt_name in {'int2', 'int4', 'int8'}: + if udt_name in {'int2', 'int4', 'int8', 'integer'}: logger.info( "Renaming legacy %s.%s integer column to %s before " "Tryton creates the new Selection column", @@ -221,6 +236,14 @@ class DefaultNcfType(ModelSQL, CompanyValueMixin): # avoid converting a value such as '31' again. if not cls._ncf_column_exists(cursor, table_name, new_column): continue + if _backend_name() == 'sqlite': + logger.info( + "Skipping PostgreSQL-style text fallback migration for " + "%s.%s on SQLite", + table_name, + new_column, + ) + continue udt_name = cls._ncf_column_udt_name(cursor, table_name, new_column) if udt_name not in {'varchar', 'text', 'bpchar'}: @@ -246,14 +269,14 @@ class DefaultNcfType(ModelSQL, CompanyValueMixin): WHERE config.{new_column} IS NOT NULL AND config.{new_column} <> '' AND config.{new_column} ~ '^[0-9]+$' - AND config.{new_column} NOT IN %s + AND config.{new_column} != ALL(%s) AND config.{new_column}::integer = seq.id AND seq.ncf_type IS NOT NULL AND seq.ncf_type <> '' - """, (valid_ncf_type_codes,)) + """, (list(valid_ncf_type_codes),)) logger.info( "Migrated %s text rows for account configuration field %s", cursor.rowcount, new_column, - ) \ No newline at end of file + ) diff --git a/doc/index.rst b/doc/index.rst index 78423b9..2c7869b 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -1,9 +1,78 @@ -################## -Ncf Manager Module +NCF Manager Module ################## -.. toctree:: - :maxdepth: 2 +The ncf_manager module manages Dominican Republic fiscal receipt numbers +for Tryton invoices. - usage - design +It provides NCF/e-CF types, fiscal sequence management, invoice fiscal fields, +NCF assignment on posting, and fiscal preparation for debit and credit notes. + +Installing +********** + +Install the package and activate the module in the database:: + + pip install solutema_ncf_manager + trytond-admin -d -u ncf_manager + +Publishing +********** + +The included Gitea Actions workflow builds and publishes the package to the +Gitea PyPI registry from version-series branches such as ``7.0``. + +Configure this repository secret: + +* ``REGISTRY_PASSWORD`` + +The module assigns fiscal numbers transactionally from ``ir.sequence.strict``. +It does not sign or transmit e-CF documents; transmission remains the explicit +responsibility of an electronic invoicing connector. + +Version compatibility +********************* + +The 7.0 and 8.0 series share the same fiscal models, workflows, importer, +validations and tests. Only the module registration, packaging metadata and +report XML required by each Tryton series remain version-specific. + +Authorization workflow +********************** + +NCF authorizations follow the protected workflow ``Draft → Active → +Finished``. Create the authorization and its fiscal lines in draft, then use +the **Activate** button. A line can select an existing strict sequence or ask +the module to create one on activation from its authorized range. Activation +checks company, fiscal type, prefix, padding, validity, availability and range +overlap. Incoming supplier documents and outgoing customer documents use +independent numbering authorities, so overlap is enforced only within the +same document direction. The last issued number automatically finishes the +line. Finishing an authorization closes every remaining active line without +reusing numbers. + +Legacy migration lines keep their original technical sequence immutable after +activation. Prefix selection is enforced while a line is in draft and fiscal +activation performs the same server-side validation; closing a protected +historical line therefore does not invalidate already-linked invoices. + +Electronic fiscal numbers are only reserved by this module. Activating an +E-series authorization never signs or transmits an e-CF to DGII. + +Importing DGII authorizations +***************************** + +Use **NCF Manager → Import DGII Authorization** to load an authorization +downloaded from the DGII Virtual Office. XML, CSV and the HTML table exported +with an ``.xls`` extension are supported and detected from their content. +The importer creates an independent workflow record for every ``NUM_AUTOR``. +The same ``NUM_SOL`` may therefore appear in several records without modifying +an authorization that is already active; file names are not used as fiscal +identifiers. It validates +approval status, company name, NCF type, prefix, range and approved quantity, +and stores the original file, SHA-256, user and import date for audit. + +Imports are idempotent. Reimporting an equivalent CSV, XML or XLS record does +not create another line, while different fiscal data for an existing +authorization is rejected. The safe default leaves the result in draft so +the first number can be reviewed. Immediate activation is explicit and still +does not transmit electronic documents. diff --git a/importer.py b/importer.py new file mode 100644 index 0000000..122afb8 --- /dev/null +++ b/importer.py @@ -0,0 +1,333 @@ +import csv +import datetime +import hashlib +from html.parser import HTMLParser +import json +import re +import unicodedata +import xml.etree.ElementTree as ET + +from trytond.exceptions import UserError +from trytond.i18n import gettext +from trytond.model import ModelView, fields +from trytond.pool import Pool +from trytond.transaction import Transaction +from trytond.wizard import Button, StateTransition, StateView, Wizard + +from .ncf_manager import NCF_SEQUENCE_TYPE_IDS, ncf_padding, ncf_prefix + + +REQUIRED_COLUMNS = { + 'NUM_SOL', 'NUM_AUTOR', 'FECHA_AUTOR', 'OBSERVACIONES', + 'NUMERO_DESDE', 'NUMERO_HASTA', 'CODTIPO', 'FECHA_SOLICITUD', + 'ESTATUS', 'CANTIDAD_APROBADA', +} + +SUPPLIER_NCF_TYPES = frozenset({'11', '13', '17', '41', '43', '47'}) +MAX_IMPORT_SIZE = 5 * 1024 * 1024 + + +def _text(value): + return (value or '').replace('\xa0', ' ').strip() + + +def _normalized_name(value): + value = unicodedata.normalize('NFKD', _text(value).upper()) + return ''.join(character for character in value + if character.isalnum()) + + +def _parse_datetime(value): + value = _text(value) + if not value: + return None + try: + return datetime.datetime.fromisoformat(value).replace(tzinfo=None) + except ValueError: + pass + for pattern in ('%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M'): + try: + return datetime.datetime.strptime(value, pattern) + except ValueError: + continue + raise ValueError(f'Invalid date: {value}') + + +class _HTMLTableParser(HTMLParser): + def __init__(self): + super().__init__() + self.rows = [] + self._row = None + self._cell = None + + def handle_starttag(self, tag, attrs): + if tag == 'tr': + self._row = [] + elif tag in {'td', 'th'} and self._row is not None: + self._cell = [] + + def handle_data(self, data): + if self._cell is not None: + self._cell.append(data) + + def handle_endtag(self, tag): + if tag in {'td', 'th'} and self._cell is not None: + self._row.append(_text(''.join(self._cell))) + self._cell = None + elif tag == 'tr' and self._row: + self.rows.append(self._row) + self._row = None + + +def _parse_xml(data): + root = ET.fromstring(data) + rows = [] + for element in list(root): + row = { + child.tag.rsplit('}', 1)[-1]: _text(child.text) + for child in list(element) + } + if row: + rows.append(row) + return rows + + +def _parse_html(data): + parser = _HTMLTableParser() + parser.feed(data.decode('utf-8-sig', errors='replace')) + if len(parser.rows) < 2: + return [] + header = parser.rows[0] + return [dict(zip(header, row)) for row in parser.rows[1:]] + + +def _parse_csv(data): + # DGII does not always quote DETALLE_LOG even when it contains commas. + # Splitting at most len(header)-1 times preserves that final field. + text = data.decode('utf-8-sig', errors='strict') + lines = [line for line in text.splitlines() if line.strip()] + if len(lines) < 2: + return [] + header = next(csv.reader([lines[0]])) + rows = [] + for line in lines[1:]: + values = line.split(',', len(header) - 1) + rows.append(dict(zip(header, values))) + return rows + + +def parse_dgii_authorizations(data): + data = bytes(data) + if not data or len(data) > MAX_IMPORT_SIZE: + raise UserError(gettext('ncf_manager.msg_dgii_import_invalid_size')) + stripped = data.lstrip() + try: + if stripped.startswith(b'<'): + if re.search(br'<\s*(?:\w+:)?SolicitudNCF\b', stripped[:500]): + rows = _parse_xml(data) + source_format = 'xml' + elif re.search(br'<\s*(?:html|div|table)\b', stripped[:500], re.I): + rows = _parse_html(data) + source_format = 'xls_html' + else: + raise ValueError('Unsupported XML/HTML document') + else: + rows = _parse_csv(data) + source_format = 'csv' + except (UnicodeDecodeError, ET.ParseError, ValueError) as exception: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_read_error', error=str(exception))) + if not rows or not REQUIRED_COLUMNS.issubset(rows[0]): + raise UserError(gettext('ncf_manager.msg_dgii_import_invalid_file')) + return source_format, [{key: _text(value) for key, value in row.items()} + for row in rows] + + +def normalize_dgii_row(row): + if row['ESTATUS'].upper() != 'APROBADA': + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_not_approved', + authorization=row['NUM_AUTOR'])) + ncf_type = row['CODTIPO'].lstrip('0') + if ncf_type not in NCF_SEQUENCE_TYPE_IDS: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_unknown_type', type=ncf_type)) + start = row['NUMERO_DESDE'].upper() + end = row['NUMERO_HASTA'].upper() + prefix = ncf_prefix(ncf_type) + padding = ncf_padding(ncf_type) + pattern = rf'{re.escape(prefix)}(\d{{{padding}}})' + start_match = re.fullmatch(pattern, start) + end_match = re.fullmatch(pattern, end) + if not start_match or not end_match: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_invalid_range', + authorization=row['NUM_AUTOR'])) + from_number = int(start_match.group(1)) + until_number = int(end_match.group(1)) + approved = int(row['CANTIDAD_APROBADA']) + if from_number < 1 or until_number < from_number: + raise UserError(gettext('ncf_manager.msg_ncf_invalid_range')) + if approved != until_number - from_number + 1: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_quantity_mismatch', + authorization=row['NUM_AUTOR'])) + try: + requested = int(row.get('CANTIDAD_SOLICITADA') or 0) or None + authorization_date = _parse_datetime(row['FECHA_AUTOR']) + application_date = _parse_datetime(row['FECHA_SOLICITUD']) + expiration = _parse_datetime(row.get('FECHA_VIGENCIA')) + except ValueError as exception: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_read_error', error=str(exception))) + if not application_date or not authorization_date: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_missing_dates', + authorization=row['NUM_AUTOR'])) + normalized = { + 'application_number': row['NUM_SOL'], + 'authorization_number': row['NUM_AUTOR'], + 'application_date': application_date, + 'authorization_date': authorization_date, + 'company_name': row.get('OBSERVACIONES', ''), + 'ncf_type': ncf_type, + 'invoice_type': ('invoice_supplier' + if ncf_type in SUPPLIER_NCF_TYPES else 'invoice_customer'), + 'from_number': from_number, + 'until_number': until_number, + 'approved_quantity': approved, + 'requested_quantity': requested, + 'expiration_date': expiration.date() if expiration else None, + 'usage_type': row.get('TIPO_USO', ''), + 'status': row['ESTATUS'].upper(), + 'detail': row.get('DETALLE_LOG', ''), + } + fingerprint_values = {key: value.isoformat() + if isinstance(value, (datetime.date, datetime.datetime)) else value + for key, value in normalized.items() + if key not in {'detail', 'company_name'}} + normalized['fingerprint'] = hashlib.sha256(json.dumps( + fingerprint_values, ensure_ascii=False, sort_keys=True, + separators=(',', ':')).encode()).hexdigest() + return normalized + + +def import_dgii_authorizations(company, data, filename, activate=False): + pool = Pool() + Manager = pool.get('ncf.manager') + Line = pool.get('ncf.manager.sequence') + data = bytes(data) + _source_format, rows = parse_dgii_authorizations(data) + normalized_rows = [normalize_dgii_row(row) for row in rows] + + company_name = _normalized_name(company.party.name) + for row in normalized_rows: + supplied_name = _normalized_name(row['company_name']) + if supplied_name and supplied_name != company_name: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_company_mismatch', + company=row['company_name'])) + + file_hash = hashlib.sha256(data).hexdigest() + managers_to_activate = [] + imported_lines = [] + for row in normalized_rows: + duplicates = Line.search([ + ('pos.company', '=', company.id), + ('auth_number', '=', row['authorization_number']), + ], limit=1) + if duplicates: + if duplicates[0].import_fingerprint != row['fingerprint']: + raise UserError(gettext( + 'ncf_manager.msg_dgii_import_conflict', + authorization=row['authorization_number'])) + continue + + # A DGII request number may appear in more than one downloaded + # authorization. Keep every NUM_AUTOR in its own workflow record so + # importing a later authorization never mutates an active one. + manager, = Manager.create([{ + 'company': company.id, + 'app_number': row['application_number'], + 'app_date': row['application_date'].date(), + 'source_filename': filename, + 'source_hash': file_hash, + 'source_file': data, + 'imported_by': Transaction().user, + 'imported_at': datetime.datetime.now(), + }]) + line, = Line.create([{ + 'pos': manager.id, + 'auth_number': row['authorization_number'], + 'authorization_date': row['authorization_date'], + 'ncf_type': row['ncf_type'], + 'invoice_type': row['invoice_type'], + 'sequence_mode': 'create', + 'from_number': row['from_number'], + 'number_next': row['from_number'], + 'until_number': row['until_number'], + 'expiration_date': row['expiration_date'], + 'dgii_status': row['status'], + 'requested_quantity': row['requested_quantity'], + 'approved_quantity': row['approved_quantity'], + 'usage_type': row['usage_type'], + 'dgii_detail': row['detail'], + 'import_fingerprint': row['fingerprint'], + 'source_filename': filename, + 'source_hash': file_hash, + 'source_file': data, + 'imported_by': Transaction().user, + 'imported_at': datetime.datetime.now(), + }]) + imported_lines.append(line) + managers_to_activate.append(manager) + + if activate and managers_to_activate: + Manager.activate(managers_to_activate) + return managers_to_activate, imported_lines + + +class ImportNCFStart(ModelView): + 'Import DGII NCF Authorization' + __name__ = 'ncf.import.start' + + company = fields.Many2One( + 'company.company', 'Company', required=True) + file_ = fields.Binary('DGII File', required=True, filename='filename') + filename = fields.Char('Filename', required=True) + activate = fields.Boolean( + 'Activate Imported Authorization', + help='Creates the strict sequence and activates it immediately. ' + 'Leave disabled when numbers may already have been issued outside ' + 'Tryton so the first number can be reviewed.') + + @staticmethod + def default_company(): + return Transaction().context.get('company') + + @staticmethod + def default_activate(): + return False + + +class ImportNCF(Wizard): + 'Import DGII NCF Authorization' + __name__ = 'ncf.import' + + start = StateView('ncf.import.start', + 'ncf_manager.ncf_import_start_view_form', [ + Button('Cancel', 'end', 'tryton-cancel'), + Button('Import', 'import_', 'tryton-ok', default=True), + ]) + import_ = StateTransition() + + def transition_import_(self): + import_dgii_authorizations( + self.start.company, self.start.file_, self.start.filename, + activate=self.start.activate) + return 'end' + + +__all__ = [ + 'ImportNCF', 'ImportNCFStart', 'import_dgii_authorizations', + 'normalize_dgii_row', 'parse_dgii_authorizations'] diff --git a/importer.xml b/importer.xml new file mode 100644 index 0000000..a860fe0 --- /dev/null +++ b/importer.xml @@ -0,0 +1,26 @@ + + + + + + ncf.import.start + form + ncf_import_start_form + + + + Import DGII Authorization + ncf.import + + + + + + + + + + diff --git a/invoice.fodt b/invoice.fodt index 4855077..fcebb8b 100644 --- a/invoice.fodt +++ b/invoice.fodt @@ -4,28 +4,28 @@ LibreOffice/26.2.1.2$MacOSX_X86_64 LibreOffice_project/8399f6259d8c87f40e7255cdb3c9b958f5e089482012-11-15T15:00:351P0D - 54878 + 53 0 - 37102 - 16522 + 28942 + 15201 true false view2 - 21911 - 65701 + 19632 + 3383 0 - 54878 - 37100 - 71399 + 53 + 28940 + 15252 0 1 false 100 false false - -1884,161,1920,1017;1;,,,; + 0,66,1512,916;4;,,,; false false false @@ -92,7 +92,7 @@ false true false - 7691572 + 7570580 0 false @@ -1521,7 +1521,7 @@ - + @@ -1535,7 +1535,7 @@ - <invoice.company.rec_name><invoice.company.party.tax_identifier.type_string>: <invoice.company.party.tax_identifier.code><invoice.company.party.addresses[0].street> <invoice.company.party.addresses[0].name><invoice.company.party.addresses[0].neighborhood.rec_name>. <invoice.company.party.addresses[0].borough.rec_name>, <invoice.company.party.addresses[0].subdivision.rec_name>. <invoice.company.party.addresses[0].country.rec_name>. <invoice.company.party.addresses[0].postal_code><invoice.company.party.email><invoice.company.party.website><invoice.company.party.phone> + <invoice.company.rec_name><invoice.company.party.tax_identifier.type_string>: <invoice.company.party.tax_identifier.code><invoice.company.party.addresses[0].street_unstructured><invoice.company.party.addresses[0].city>, <invoice.company.party.addresses[0].subdivision.rec_name>. <invoice.company.party.addresses[0].country.rec_name>. <invoice.company.party.addresses[0].postal_code><invoice.company.party.email><invoice.company.party.website><invoice.company.party.phone> <if test="invoice.type == 'in'"> @@ -1750,7 +1750,7 @@ <format_currency(line.amount, invoice.party.lang, invoice.currency)> - <format_currency(line.itbis, invoice.party.lang, invoice.currency)> + <format_currency(line.itbis_invoiced_line, invoice.party.lang, invoice.currency)> @@ -2539,7 +2539,7 @@ <format_currency(line.amount, invoice.party.lang, invoice.currency)> - <format_currency(line.itbis, invoice.party.lang, invoice.currency)> + <format_currency(line.itbis_invoiced_line, invoice.party.lang, invoice.currency)> @@ -2844,7 +2844,7 @@ Propina: - <format_currency(invoice.cdt_invoiced, invoice.party.lang, invoice.currency)> + <format_currency(invoice.tip, invoice.party.lang, invoice.currency)> @@ -3258,4 +3258,4 @@ </if> - \ No newline at end of file + diff --git a/invoice.py b/invoice.py index e05328f..715fd21 100755 --- a/invoice.py +++ b/invoice.py @@ -3,13 +3,14 @@ # this repository contains the full copyright notices and license terms. from decimal import Decimal from datetime import date +import re from sql.aggregate import Sum from sql.conditionals import Coalesce from sql.functions import Round from trytond import backend -from trytond.model import fields +from trytond.model import ModelView, Workflow, fields from trytond.pool import Pool, PoolMeta -from trytond.pyson import Eval, If, And +from trytond.pyson import Eval, If, And, Bool from trytond.transaction import Transaction from trytond.exceptions import UserError from trytond.i18n import gettext @@ -19,6 +20,11 @@ import logging logger = logging.getLogger(__name__) +def _backend_name(): + name = backend.name + return name() if callable(name) else name + + _REVENUE_TYPE = [ ('', ''), ('01', "01 - Ingresos por Operaciones (No Financieros)"), @@ -66,6 +72,7 @@ _ISR_WITHHOLDING_TYPE = [ ('06', "06 - Intereses Pagados a Personas Físicas Residentes"), ('07', "07 - Retención por Proveedores del Estado"), ('08', "08 - Juegos Telefónicos"), + ('09', "09 - Retenciones Subsector Ganadería de Carne Bovina"), ] _CANCELLATION_TYPE = [ @@ -84,8 +91,9 @@ _CANCELLATION_TYPE = [ _ZERO = Decimal('0.00') -_CREDIT_NOTE_CODES = ('4', '34') _DEBIT_NOTE_CODES = ('3', '33') +_CREDIT_NOTE_CODES = ('4', '34') +_MODIFIED_NOTE_CODES = _DEBIT_NOTE_CODES + _CREDIT_NOTE_CODES _ECF_ORIGIN_CODES = ( '31', '32', '33', '34', @@ -97,6 +105,14 @@ _ECF_CODES = [ '41', '43', '44', '45', '46', '47', ] +_ELECTRONIC_INVOICE_MODULES = ( + 'account_invoice_electronic', + 'account_invoice_electronic_do', + 'dgii_electronic_invoice', + 'electronic_invoice_do', + 'ncf_electronic', +) + class Invoice(metaclass=PoolMeta): __name__ = 'account.invoice' @@ -169,6 +185,13 @@ class Invoice(metaclass=PoolMeta): 'invisible': ~Eval('itbis_withholding', 0), }), 'on_change_with_itbis_withholding', searcher='search_itbis_withholding') + itbis_withholding_acquirer = fields.Function(Monetary( + "ITBIS Withholding Acquirer", currency='currency', digits='currency', + states={ + 'invisible': ~Eval('itbis_withholding_acquirer', 0), + }), 'on_change_with_itbis_withholding_acquirer', + searcher='search_itbis_withholding_acquirer') + isc_invoiced = fields.Function(Monetary( "ISC Invoiced", currency='currency', digits='currency', states={ @@ -271,25 +294,42 @@ class Invoice(metaclass=PoolMeta): isr_withholding_type_string = isr_withholding_type.translated( 'isr_withholding_type') - # itbis_taken_cost = fields.Function(Monetary( - # "ITBIS Taken Cost", currency='currency', digits='currency'), - # 'get_itbis_taken_cost', searcher='search_itbis_taken_cost') + ncf_cancellation_type = fields.Selection( + _CANCELLATION_TYPE, 'NCF Cancellation Type', + states={ + 'required': ( + (Eval('state') == 'cancelled') + & (Eval('type') == 'out') + & Bool(Eval('ncf_number')) + & ~Eval('context', {}).get('invoice_force_cancel', False)), + 'readonly': Eval('state') == 'cancelled', + 'invisible': Eval('type') == 'in', + }, + depends=['state', 'type', 'ncf_number']) - # untaxed_amount_invoiced = fields.Function(fields.Numeric( - # 'Untaxed Invoiced', digits=(16, - # Eval('currency_digits', 2)), depends=['currency_digits']), - # 'get_untaxed_amount_invoiced') + ncf_cancellation_type_string = ncf_cancellation_type.translated( + 'ncf_cancellation_type') - # itbis_amount_invoiced = fields.Function(fields.Numeric( - # 'ITBIS Invoiced', digits=(16, - # Eval('currency_digits', 2)), depends=['currency_digits']), - # 'get_itbis_amount_invoiced') - - # total_amount_invoiced = fields.Function(fields.Numeric( - # 'Total Invoiced', digits=(16, - # Eval('currency_digits', 2)), depends=['currency_digits']), - # 'get_total_amount_invoiced') + ncf_cancellation_reason = fields.Text( + 'NCF Cancellation Reason', + states={ + 'required': ( + (Eval('state') == 'cancelled') + & (Eval('type') == 'out') + & Bool(Eval('ncf_number')) + & ~Eval('context', {}).get('invoice_force_cancel', False)), + 'readonly': Eval('state') == 'cancelled', + 'invisible': Eval('type') == 'in', + }, + depends=['state', 'type', 'ncf_number']) + @classmethod + def __setup__(cls): + super().__setup__() + cls._check_modify_exclude.update({ + 'ncf_cancellation_type', + 'ncf_cancellation_reason', + }) @classmethod def __register__(cls, module_name): @@ -306,9 +346,13 @@ class Invoice(metaclass=PoolMeta): cls._ncf_prepare_legacy_invoice_ncf_type_column() super().__register__(module_name) cls._ncf_migrate_invoice_ncf_type_from_legacy_column() + cls._ncf_migrate_legacy_cancellation_fields() @classmethod def _ncf_column_exists(cls, cursor, table_name, column_name): + if _backend_name() == 'sqlite': + cursor.execute(f'PRAGMA table_info("{table_name}")') + return any(row[1] == column_name for row in cursor.fetchall()) cursor.execute(""" SELECT 1 FROM information_schema.columns @@ -320,6 +364,12 @@ class Invoice(metaclass=PoolMeta): @classmethod def _ncf_column_udt_name(cls, cursor, table_name, column_name): + if _backend_name() == 'sqlite': + cursor.execute(f'PRAGMA table_info("{table_name}")') + for row in cursor.fetchall(): + if row[1] == column_name: + return (row[2] or '').lower() + return None cursor.execute(""" SELECT udt_name FROM information_schema.columns @@ -353,7 +403,7 @@ class Invoice(metaclass=PoolMeta): udt_name = cls._ncf_column_udt_name(cursor, table_name, old_column) - if udt_name in {'int2', 'int4', 'int8'}: + if udt_name in {'int2', 'int4', 'int8', 'integer'}: logger.info( "Renaming legacy %s.%s integer column to %s before Tryton " "creates the new Selection column", @@ -436,6 +486,35 @@ class Invoice(metaclass=PoolMeta): unmatched, ) + @classmethod + def _ncf_migrate_legacy_cancellation_fields(cls): + """ + Copy data from the former account_invoice_cancel_reason module. + + The old module used generic cancellation_type/cancellation_reason + columns. ncf_manager stores those values as fiscal DGII cancellation + data so they can later feed the NCF annulment report. + """ + cursor = Transaction().connection.cursor() + table_name = 'account_invoice' + field_pairs = ( + ('cancellation_type', 'ncf_cancellation_type'), + ('cancellation_reason', 'ncf_cancellation_reason'), + ) + + for old_column, new_column in field_pairs: + if not cls._ncf_column_exists(cursor, table_name, old_column): + continue + if not cls._ncf_column_exists(cursor, table_name, new_column): + continue + cursor.execute(f""" + UPDATE {table_name} + SET {new_column} = {old_column} + WHERE {old_column} IS NOT NULL + AND {old_column} <> '' + AND ({new_column} IS NULL OR {new_column} = '') + """) + @classmethod def search_rec_name(cls, name, clause): domain = super().search_rec_name(name, clause) @@ -660,8 +739,8 @@ class Invoice(metaclass=PoolMeta): def _ncf_get_party_default_ncf_type(self): """ - Return the NCF type for the selected party according to the current - invoice type. + Return the default NCF type configured on the selected party according + to the current invoice type. Mapping: - invoice.type = 'out' -> party.customer_ncf_type @@ -680,55 +759,16 @@ class Invoice(metaclass=PoolMeta): else: return None - party_ncf_type = self._ncf_get_party_configured_ncf_type(field_name) - if party_ncf_type: - return party_ncf_type + company_id = self.company.id if self.company else Transaction().context.get('company') - return self._ncf_get_configuration_default_ncf_type(field_name) + if getattr(self.party, 'id', None) and company_id: + Party = Pool().get('party.party') - def _ncf_get_party_configured_ncf_type(self, field_name): - """ - Return only the value explicitly saved for the party. - - Reading the MultiValue field directly also applies the model default. - For NCF types that would make every party look as if it had the - configured global default. The invoice must distinguish a party - override from the account configuration fallback. - """ - if not getattr(self.party, 'id', None): - return getattr(self.party, field_name, None) or None - - PartyNcfType = Pool().get('party.party.ncf_type') - records = PartyNcfType.search([ - ('party', '=', self.party.id), - ], limit=1) - - if records: - return getattr(records[0], field_name, None) or None - - return None - - def _ncf_get_configuration_default_ncf_type(self, field_name): - "Return the NCF type configured globally for parties without override." - Configuration = Pool().get('account.configuration') - config = Configuration(1) - - if field_name == 'customer_ncf_type': - config_field = 'default_customer_ncf_type' - elif field_name == 'supplier_ncf_type': - config_field = 'default_supplier_ncf_type' - else: - return None - - company_id = ( - self.company.id if self.company - else Transaction().context.get('company')) - - if company_id: with Transaction().set_context(company=company_id): - return config.get_multivalue(config_field) or None + party = Party(self.party.id) + return getattr(party, field_name, None) or None - return config.get_multivalue(config_field) or None + return getattr(self.party, field_name, None) or None def _ncf_apply_party_default_ncf_type(self): """ @@ -980,48 +1020,13 @@ class Invoice(metaclass=PoolMeta): @classmethod def get_amount_invoiced_services(cls, invoices, names): - pool = Pool() - InvoiceTax = pool.get('account.invoice.tax') - Move = pool.get('account.move') - MoveLine = pool.get('account.move.line') - cursor = Transaction().connection.cursor() - - # untaxed_amount = dict((i.id, _ZERO) for i in invoices) - amount_invoiced_services = dict((i.id, _ZERO) for i in invoices) - tax_amount = dict((i.id, _ZERO) for i in invoices) - total_amount = dict((i.id, _ZERO) for i in invoices) - - invoices_move = set() - invoices_no_move = set() + amount_invoiced_services = {i.id: _ZERO for i in invoices} for invoice in invoices: - if invoice.move: - invoices_move.add(invoice.id) - else: - invoices_no_move.add(invoice.id) - invoices_move = cls.browse(invoices_move) - invoices_no_move = cls.browse(invoices_no_move) - - for invoice in invoices_move: amount_invoiced_services[invoice.id] = sum( (line.amount for line in invoice.lines - if line.type == 'line' and line.product_type == 'service'), _ZERO) - total_amount[invoice.id] = ( - amount_invoiced_services[invoice.id] + tax_amount[invoice.id]) - - for invoice in invoices_no_move: - amount_invoiced_services[invoice.id] = sum( - (line.amount for line in invoice.lines - if line.type == 'line' and line.product_type == 'service'), _ZERO) - total_amount[invoice.id] = ( - amount_invoiced_services[invoice.id] + tax_amount[invoice.id]) - - result = { - 'amount_invoiced_services': amount_invoiced_services, - 'tax_amount': tax_amount, - 'total_amount': total_amount, - } - for key in list(result.keys()): - return result + if line.type == 'line' and line.product_type == 'service'), + _ZERO) + return {'amount_invoiced_services': amount_invoiced_services} @classmethod def search_amount_invoiced_services(cls, name, clause): @@ -1051,10 +1056,12 @@ class Invoice(metaclass=PoolMeta): template = Template.__table__() _, operator, value = clause + if value is None: + return [] invoice_query = Rule.query_get('account.invoice') Operator = fields.SQL_OPERATORS[operator] # SQLite uses float for sum - if backend.name == 'sqlite': + if _backend_name() == 'sqlite': value = float(value) query = (line.join(invoice, condition=(invoice.id == line.invoice)) @@ -1074,60 +1081,37 @@ class Invoice(metaclass=PoolMeta): @classmethod def get_amount_invoiced_goods(cls, invoices, names): - pool = Pool() - InvoiceTax = pool.get('account.invoice.tax') - Move = pool.get('account.move') - MoveLine = pool.get('account.move.line') - cursor = Transaction().connection.cursor() - - # untaxed_amount = dict((i.id, _ZERO) for i in invoices) - amount_invoiced_goods = dict((i.id, _ZERO) for i in invoices) - tax_amount = dict((i.id, _ZERO) for i in invoices) - total_amount = dict((i.id, _ZERO) for i in invoices) - - invoices_move = set() - invoices_no_move = set() + amount_invoiced_goods = {i.id: _ZERO for i in invoices} for invoice in invoices: - if invoice.move: - invoices_move.add(invoice.id) - else: - invoices_no_move.add(invoice.id) - invoices_move = cls.browse(invoices_move) - invoices_no_move = cls.browse(invoices_no_move) - - for invoice in invoices_move: amount_invoiced_goods[invoice.id] = sum( (line.amount for line in invoice.lines - if line.type == 'line' and line.product_type == 'goods'), _ZERO) - total_amount[invoice.id] = ( - amount_invoiced_goods[invoice.id] + tax_amount[invoice.id]) - - for invoice in invoices_no_move: - amount_invoiced_goods[invoice.id] = sum( - (line.amount for line in invoice.lines - if line.type == 'line' and line.product_type == 'goods'), _ZERO) - total_amount[invoice.id] = ( - amount_invoiced_goods[invoice.id] + tax_amount[invoice.id]) - - result = { - 'amount_invoiced_goods': amount_invoiced_goods, - 'tax_amount': tax_amount, - 'total_amount': total_amount, - } - for key in list(result.keys()): - return result + if line.type == 'line' and line.product_type == 'goods'), + _ZERO) + return {'amount_invoiced_goods': amount_invoiced_goods} def get_id_type(self, name): - if self.party: - if not self.party_tax_identifier: - return None - code_length = len(self.party_tax_identifier.code) - if code_length == 9: - return 1 - elif code_length == 11: - return 2 - else: - return 3 + if not self.party or not self.party_tax_identifier: + return None + + identifier = self.party_tax_identifier + identifier_type = getattr(identifier, 'type', None) + if identifier_type in {'do_rnc', 'do_vat'}: + return 1 + if identifier_type == 'do_cedula': + return 2 + + # Tryton 8.0 stores a formatted display code (for example + # ``1-01-01063-2`` or ``001-1391820-5``). Use code_compact when + # available and still normalize it for migrated records whose compact + # value may retain the old formatting. + code = (getattr(identifier, 'code_compact', None) + or getattr(identifier, 'code', None) or '') + digits = re.sub(r'\D', '', code) + if len(digits) == 9: + return 1 + if len(digits) == 11: + return 2 + return 3 @fields.depends('taxes', 'lines') def on_change_with_itbis_invoiced(self, name=None): @@ -1162,9 +1146,17 @@ class Invoice(metaclass=PoolMeta): for tax_line in self.taxes: if tax_line.tax and tax_line.tax.tax_kind == 'itbis_withholding': itbis_withholding += tax_line.amount - return abs(itbis_withholding) + @fields.depends('taxes', 'lines') + def on_change_with_itbis_withholding_acquirer(self, name=None): + total = _ZERO + for tax_line in self.taxes: + if (tax_line.tax + and tax_line.tax.tax_kind == 'itbis_withholding_acquirer'): + total += tax_line.amount + return abs(total) + @fields.depends('taxes', 'lines') def on_change_with_isr_withholding(self, name=None): isr_withholding = _ZERO @@ -1184,141 +1176,71 @@ class Invoice(metaclass=PoolMeta): return abs(tip) @classmethod - def search_itbis_invoiced(cls, name, clause): + def _search_tax_amount_by_kind(cls, field, tax_kind, clause): pool = Pool() Rule = pool.get('ir.rule') - Tax = pool.get('account.invoice.tax') - type_name = cls.itbis_invoiced._field.sql_type().base - tax = Tax.__table__() + InvoiceTax = pool.get('account.invoice.tax') + AccountTax = pool.get('account.tax') + type_name = field.sql_type().base + invoice_tax = InvoiceTax.__table__() + account_tax = AccountTax.__table__() _, operator, value = clause invoice_query = Rule.query_get('account.invoice') Operator = fields.SQL_OPERATORS[operator] - # SQLite uses float for sum - if backend.name == 'sqlite': - value = float(value) - query = tax.select(tax.invoice, - where=tax.invoice.in_(invoice_query), - group_by=tax.invoice, - having=Operator(Coalesce(Sum(tax.amount), 0).cast(type_name), - value)) + query = invoice_tax.join( + account_tax, + condition=(account_tax.id == invoice_tax.tax), + ).select( + invoice_tax.invoice, + where=( + invoice_tax.invoice.in_(invoice_query) + & (account_tax.tax_kind == tax_kind) + ), + group_by=invoice_tax.invoice, + having=Operator( + Coalesce(Sum(invoice_tax.amount), 0).cast(type_name), + value, + ), + ) return [('id', 'in', query)] + @classmethod + def search_itbis_invoiced(cls, name, clause): + return cls._search_tax_amount_by_kind( + cls.itbis_invoiced._field, 'itbis', clause) + @classmethod def search_itbis_withholding(cls, name, clause): - pool = Pool() - Rule = pool.get('ir.rule') - Tax = pool.get('account.invoice.tax') - type_name = cls.itbis_withholding._field.sql_type().base - tax = Tax.__table__() + return cls._search_tax_amount_by_kind( + cls.itbis_withholding._field, 'itbis_withholding', clause) - _, operator, value = clause - invoice_query = Rule.query_get('account.invoice') - Operator = fields.SQL_OPERATORS[operator] - # SQLite uses float for sum - if backend.name == 'sqlite': - value = float(value) - - query = tax.select(tax.invoice, - where=tax.invoice.in_(invoice_query), - group_by=tax.invoice, - having=Operator(Coalesce(Sum(tax.amount), 0).cast(type_name), - value)) - return [('id', 'in', query)] + @classmethod + def search_itbis_withholding_acquirer(cls, name, clause): + return cls._search_tax_amount_by_kind( + cls.itbis_withholding_acquirer._field, + 'itbis_withholding_acquirer', clause) @classmethod def search_isc_invoiced(cls, name, clause): - pool = Pool() - Rule = pool.get('ir.rule') - Tax = pool.get('account.invoice.tax') - type_name = cls.isc_invoiced._field.sql_type().base - tax = Tax.__table__() - - _, operator, value = clause - invoice_query = Rule.query_get('account.invoice') - Operator = fields.SQL_OPERATORS[operator] - # SQLite uses float for sum - if backend.name == 'sqlite': - value = float(value) - - query = tax.select(tax.invoice, - where=tax.invoice.in_(invoice_query), - group_by=tax.invoice, - having=Operator(Coalesce(Sum(tax.amount), 0).cast(type_name), - value)) - return [('id', 'in', query)] + return cls._search_tax_amount_by_kind( + cls.isc_invoiced._field, 'isc', clause) @classmethod def search_cdt_invoiced(cls, name, clause): - pool = Pool() - Rule = pool.get('ir.rule') - Tax = pool.get('account.invoice.tax') - type_name = cls.cdt_invoiced._field.sql_type().base - tax = Tax.__table__() - - _, operator, value = clause - invoice_query = Rule.query_get('account.invoice') - Operator = fields.SQL_OPERATORS[operator] - # SQLite uses float for sum - if backend.name == 'sqlite': - value = float(value) - - query = tax.select(tax.invoice, - where=tax.invoice.in_(invoice_query), - group_by=tax.invoice, - having=Operator(Coalesce(Sum(tax.amount), 0).cast(type_name), - value)) - return [('id', 'in', query)] + return cls._search_tax_amount_by_kind( + cls.cdt_invoiced._field, 'cdt', clause) @classmethod def search_isr_withholding(cls, name, clause): - pool = Pool() - Rule = pool.get('ir.rule') - Tax = pool.get('account.invoice.tax') - type_name = cls.isr_withholding._field.sql_type().base - tax = Tax.__table__() - - _, operator, value = clause - invoice_query = Rule.query_get('account.invoice') - Operator = fields.SQL_OPERATORS[operator] - # SQLite uses float for sum - if backend.name == 'sqlite': - value = float(value) - - query = tax.select(tax.invoice, - where=tax.invoice.in_(invoice_query), - group_by=tax.invoice, - having=Operator(Coalesce(Sum(tax.amount), 0).cast(type_name), - value)) - return [('id', 'in', query)] + return cls._search_tax_amount_by_kind( + cls.isr_withholding._field, 'isr_withholding', clause) @classmethod def search_tip(cls, name, clause): - pool = Pool() - Rule = pool.get('ir.rule') - Tax = pool.get('account.invoice.tax') - type_name = cls.tip._field.sql_type().base - tax = Tax.__table__() - - _, operator, value = clause - invoice_query = Rule.query_get('account.invoice') - Operator = fields.SQL_OPERATORS[operator] - # SQLite uses float for sum - if backend.name == 'sqlite': - value = float(value) - - query = tax.select(tax.invoice, - where=tax.invoice.in_(invoice_query), - group_by=tax.invoice, - having=Operator(Coalesce(Sum(tax.amount), 0).cast(type_name), - value)) - return [('id', 'in', query)] - - @classmethod - def search_amount_invoiced_services(cls, name, clause): - return cls._search_amount_invoiced_by_product_type( - name, clause, 'service') + return cls._search_tax_amount_by_kind( + cls.tip._field, 'tip', clause) @classmethod def _ncf_invoice_type(cls, invoice): @@ -1354,18 +1276,12 @@ class Invoice(metaclass=PoolMeta): @classmethod def _ncf_resolve_credit_note_code(cls, origin): """ - Resolve which NCF/e-NCF type must be used for the credit note. + Resolve the preferred NCF/e-NCF type for a credit note. - - If the issuing company has e-CF enabled, use 34 even when the - affected invoice is a legacy NCF such as B01. - - Otherwise, if the original invoice is electronic, use 34. - - Otherwise use 4. + Electronic credit notes are only allowed when the electronic invoicing + module is active. """ - if getattr(origin.company, 'ecf_engine_enabled', False): - return '34' - - origin_code = cls._ncf_code(origin) - if origin_code in _ECF_ORIGIN_CODES: + if cls._ncf_electronic_invoicing_enabled(): return '34' return '4' @@ -1373,18 +1289,12 @@ class Invoice(metaclass=PoolMeta): @classmethod def _ncf_resolve_debit_note_code(cls, origin): """ - Resolve which NCF/e-NCF type must be used for the debit note. + Resolve the preferred NCF/e-NCF type for a debit note. - - If the issuing company has e-CF enabled, use 33 even when the - affected invoice is a legacy NCF such as B01. - - Otherwise, if the original invoice is electronic, use 33. - - Otherwise use 3. + Electronic debit notes are only allowed when the electronic invoicing + module is active. """ - if getattr(origin.company, 'ecf_engine_enabled', False): - return '33' - - origin_code = cls._ncf_code(origin) - if origin_code in _ECF_ORIGIN_CODES: + if cls._ncf_electronic_invoicing_enabled(): return '33' return '3' @@ -1440,6 +1350,59 @@ class Invoice(metaclass=PoolMeta): return None + @classmethod + def _ncf_electronic_invoicing_enabled(cls): + """ + Return whether electronic invoicing is enabled for NCF selection. + + ncf_manager alone must only issue physical B NCFs. Electronic E NCFs + are enabled by an electronic invoicing module. A concrete electronic + invoicing module may also override this hook if its technical name is + not in _ELECTRONIC_INVOICE_MODULES. + """ + Module = Pool().get('ir.module') + return bool(Module.search([ + ('name', 'in', list(_ELECTRONIC_INVOICE_MODULES)), + ('state', '=', 'activated'), + ], limit=1)) + + + @classmethod + def _ncf_note_code_candidates(cls, origin, electronic_code, physical_code): + """ + Return note NCF codes in preference order. + + ncf_manager alone issues B notes. When electronic invoicing is active, + E notes are preferred and B notes remain a fallback. + """ + if not cls._ncf_electronic_invoicing_enabled(): + return [physical_code] + + preferred = ( + electronic_code + if cls._ncf_code(origin) in _ECF_ORIGIN_CODES + else physical_code) + candidates = [electronic_code, physical_code] + if preferred in candidates: + candidates.remove(preferred) + candidates.insert(0, preferred) + return candidates + + + @classmethod + def _ncf_find_note_sequence( + cls, origin, note, electronic_code, physical_code): + """ + Return the selected NCF code and active sequence for a debit/credit note. + """ + for ncf_code in cls._ncf_note_code_candidates( + origin, electronic_code, physical_code): + sequence = cls._ncf_find_active_sequence(note, ncf_code) + if sequence: + return ncf_code, sequence + return None, None + + @classmethod def _ncf_prepare_credit_note_from_origin(cls, origin, credit_note): """ @@ -1447,7 +1410,7 @@ class Invoice(metaclass=PoolMeta): This is the specific fiscal responsibility of ncf_manager: - Set ncf_number_modified from the original invoice ncf_number. - - Assign the correct credit-note NCF type: 4 or 34. + - Assign the correct credit-note NCF type: 34 or 4. - Set fiscal payment method to credit note when available. """ if not origin.ncf_number: @@ -1455,19 +1418,18 @@ class Invoice(metaclass=PoolMeta): credit_note.ncf_number_modified = origin.ncf_number - ncf_code = cls._ncf_resolve_credit_note_code(origin) + ncf_code, sequence = cls._ncf_find_note_sequence( + origin, credit_note, '34', '4') + + if not sequence: + raise UserError(gettext( + 'ncf_manager.msg_missing_credit_note_sequence', + ncf_type='/'.join(cls._ncf_note_code_candidates( + origin, '34', '4')), + company=credit_note.company.rec_name)) + credit_note.ncf_type = ncf_code - - if credit_note.type == 'out': - sequence = cls._ncf_find_active_sequence(credit_note, ncf_code) - - if not sequence: - raise UserError(gettext( - 'ncf_manager.msg_missing_credit_note_sequence', - ncf_type=ncf_code, - company=credit_note.company.rec_name)) - - credit_note.ncf_sequence = sequence + credit_note.ncf_sequence = sequence if hasattr(credit_note, 'payment_method'): credit_note.payment_method = '06' @@ -1476,42 +1438,57 @@ class Invoice(metaclass=PoolMeta): credit_note.revenue_type = credit_note.revenue_type or '01' @classmethod - def _ncf_prepare_debit_note_from_origin(cls, origin, debit_note, values=None): + def _ncf_prepare_debit_note_from_origin(cls, origin, debit_note): """ Fiscal preparation for debit notes generated from an existing invoice. + + This is the specific fiscal responsibility of ncf_manager: + - Set ncf_number_modified from the original invoice ncf_number. + - Assign the correct debit-note NCF type: 33 or 3. + - Preserve fiscal report fields from the original invoice when present. """ if not origin.ncf_number: return - values = values or {} - debit_note.ncf_number_modified = origin.ncf_number - ncf_code = cls._ncf_resolve_debit_note_code(origin) + ncf_code, sequence = cls._ncf_find_note_sequence( + origin, debit_note, '33', '3') + + if not sequence: + raise UserError(gettext( + 'ncf_manager.msg_missing_debit_note_sequence', + ncf_type='/'.join(cls._ncf_note_code_candidates( + origin, '33', '3')), + company=debit_note.company.rec_name)) + debit_note.ncf_type = ncf_code + debit_note.ncf_sequence = sequence - if debit_note.type == 'out': - sequence = cls._ncf_find_active_sequence(debit_note, ncf_code) - - if not sequence: - raise UserError(gettext( - 'ncf_manager.msg_missing_debit_note_sequence', - ncf_type=ncf_code, - company=debit_note.company.rec_name)) - - debit_note.ncf_sequence = sequence - - strict_sequence = sequence.ncf_sequences - if strict_sequence and not getattr(debit_note, 'expiration_date', None): - debit_note.expiration_date = strict_sequence.expiration_date + if hasattr(debit_note, 'payment_method'): + debit_note.payment_method = getattr(origin, 'payment_method', None) if hasattr(debit_note, 'revenue_type') and debit_note.type == 'out': - debit_note.revenue_type = debit_note.revenue_type or '01' + debit_note.revenue_type = ( + getattr(origin, 'revenue_type', None) + or debit_note.revenue_type + or '01') + + if hasattr(debit_note, 'expense_type') and debit_note.type == 'in': + debit_note.expense_type = ( + getattr(origin, 'expense_type', None) + or debit_note.expense_type) + + if hasattr(debit_note, 'isr_withholding_type'): + debit_note.isr_withholding_type = getattr( + origin, 'isr_withholding_type', None) @classmethod def _debit_prepare_note_from_origin(cls, origin, debit_note, values): - super()._debit_prepare_note_from_origin(origin, debit_note, values) - cls._ncf_prepare_debit_note_from_origin(origin, debit_note, values) + super_method = getattr(super(), '_debit_prepare_note_from_origin', None) + if super_method: + super_method(origin, debit_note, values) + cls._ncf_prepare_debit_note_from_origin(origin, debit_note) @classmethod def credit(cls, invoices, refund=False, **values): @@ -1580,7 +1557,7 @@ class Invoice(metaclass=PoolMeta): ncf_code = invoice.ncf_type - if invoice.type == 'in' and ncf_code == '99': + if ncf_code == '99': continue ncf_sequence = invoice.ncf_sequence or cls._ncf_find_active_sequence( @@ -1589,8 +1566,8 @@ class Invoice(metaclass=PoolMeta): if not ncf_sequence: raise UserError(gettext( 'ncf_manager.msg_missing_ncf_sequence', - ncf_type=ncf_code, - company=invoice.company.rec_name)) + invoice=invoice.rec_name, + )) strict_sequence = ncf_sequence.ncf_sequences @@ -1620,8 +1597,8 @@ class Invoice(metaclass=PoolMeta): if not ncf_sequence: raise UserError(gettext( 'ncf_manager.msg_missing_ncf_sequence', - ncf_type=self.ncf_type, - company=self.company.rec_name)) + invoice=self.rec_name, + )) strict_sequence = ncf_sequence.ncf_sequences @@ -1644,7 +1621,17 @@ class Invoice(metaclass=PoolMeta): raise UserError(gettext( 'ncf_manager.msg_ncf_sequence_expired')) - return strict_sequence.get(), strict_sequence.id + number = strict_sequence.get() + StrictSequence = Pool().get('ir.sequence.strict') + ManagerSequence = Pool().get('ncf.manager.sequence') + strict_sequence = StrictSequence(strict_sequence.id) + if (strict_sequence.until_number is not None + and strict_sequence.number_next is not None + and strict_sequence.number_next + > strict_sequence.until_number + and ncf_sequence.state == 'active'): + ManagerSequence.complete([ncf_sequence]) + return number, strict_sequence.id def check_credit_note(self): @@ -1688,14 +1675,26 @@ class Invoice(metaclass=PoolMeta): raise UserError(gettext( 'ncf_manager.msg_no_expiration_date')) + @classmethod + def _ncf_check_fiscal_classification(cls, invoice): + """ + Validate fiscal classification fields in DGII-friendly order. + """ + if invoice.type == 'out': + invoice.check_revenue_type() + else: + invoice.check_expense_type() + invoice.check_isr_withholding_type() + invoice.check_payment_method() + def check_ncf_number_modified(self): """ - Validate modified NCF only for fiscal/electronic credit notes. + Validate modified NCF only for fiscal/electronic debit/credit notes. """ if not self.ncf_type: return - if self.ncf_type not in _CREDIT_NOTE_CODES: + if self.ncf_type not in _MODIFIED_NOTE_CODES: return if not self.ncf_number_modified: @@ -1717,6 +1716,73 @@ class Invoice(metaclass=PoolMeta): raise UserError(gettext( 'ncf_manager.msg_incorrect_lenght_ncf_number_modified')) + @staticmethod + def _ncf_normalize_number(number): + return (number or '').strip().upper() + + @classmethod + def _ncf_validate_number(cls, invoice): + number = cls._ncf_normalize_number(invoice.ncf_number) + if not number: + return + legacy_supplier_ncf = ( + getattr(invoice, 'type', None) == 'in' + and re.fullmatch(r'[A-Z]\d{18}', number)) + if not legacy_supplier_ncf and not re.fullmatch( + r'(?:B\d{10}|E\d{12})', number): + raise UserError(gettext( + 'ncf_manager.msg_invalid_ncf_structure', number=number)) + if legacy_supplier_ncf: + invoice.ncf_number = number + return + expected = ('E' if invoice.ncf_type in _ECF_CODES else 'B') + \ + invoice.ncf_type.zfill(2) + if invoice.ncf_type != '99' and not number.startswith(expected): + raise UserError(gettext( + 'ncf_manager.msg_invalid_ncf_type_prefix', + number=number, prefix=expected)) + invoice.ncf_number = number + + @classmethod + def _ncf_check_duplicate(cls, invoice): + if not invoice.ncf_number: + return + domain = [ + ('id', '!=', invoice.id), + ('company', '=', invoice.company.id), + ('ncf_number', '=', invoice.ncf_number), + ] + # Supplier NCF sequences are unique per issuer, not globally. + if invoice.type == 'in': + domain.extend([ + ('type', '=', 'in'), + ('party', '=', invoice.party.id), + ]) + else: + domain.append(('type', '=', 'out')) + if cls.search(domain, limit=1): + raise UserError(gettext( + 'ncf_manager.msg_duplicated_ncf_number_invoice')) + + @staticmethod + def _ncf_is_fiscal_cancellation_required(invoice): + return ( + invoice.type == 'out' + and bool(getattr(invoice, 'ncf_number', None))) + + @classmethod + def _ncf_check_cancellation_information(cls, invoice): + if not cls._ncf_is_fiscal_cancellation_required(invoice): + return + if not invoice.ncf_cancellation_type: + raise UserError(gettext( + 'ncf_manager.msg_missing_ncf_cancellation_type', + invoice=invoice.rec_name)) + if not invoice.ncf_cancellation_reason: + raise UserError(gettext( + 'ncf_manager.msg_missing_ncf_cancellation_reason', + invoice=invoice.rec_name)) + @classmethod def copy(cls, invoices, default=None): if default is None: @@ -1730,6 +1796,8 @@ class Invoice(metaclass=PoolMeta): default.setdefault('ncf_number_modified', None) default.setdefault('expiration_date', None) default.setdefault('security_code', None) + default.setdefault('ncf_cancellation_type', None) + default.setdefault('ncf_cancellation_reason', None) return super(Invoice, cls).copy(invoices, default=default) @@ -1746,39 +1814,48 @@ class Invoice(metaclass=PoolMeta): ('/form/notebook/page[@id="tax_information"]/separator[@id="expense"]', 'states', { 'invisible': Eval('type') == 'out', }), - ('/form/notebook/page[@id="cancel_reason"]', 'states', { - 'invisible': Eval('type') == 'in', + ('/form/notebook/page[@id="ncf_cancellation"]', 'states', { + 'invisible': ( + (Eval('type') == 'in') | ~Bool(Eval('ncf_number'))), }), ] + @classmethod + @ModelView.button + @Workflow.transition('cancelled') + def cancel(cls, invoices): + if not Transaction().context.get('invoice_force_cancel'): + for invoice in invoices: + cls._ncf_check_cancellation_information(invoice) + super().cancel(invoices) @classmethod def _post(cls, invoices): - """ - Validate and assign NCF before posting. - """ cls.set_ncf_number(invoices) for invoice in invoices: - if not invoice.ncf_type: - raise UserError(gettext('ncf_manager.msg_no_ncf_type')) - + cls._ncf_validate_number(invoice) + cls._ncf_check_duplicate(invoice) ncf_code = invoice.ncf_type + is_debit_note = cls._ncf_is_debit_note(invoice) is_credit_note = cls._ncf_is_credit_note(invoice) + is_modified_note = is_debit_note or is_credit_note is_without_ncf = ncf_code == '99' if invoice.type == 'out': + if not is_without_ncf: + invoice._ncf_validate_selected_sequence() if is_credit_note: invoice.check_credit_note() invoice.check_ncf_number_modified() + cls._ncf_check_fiscal_classification(invoice) invoice.check_payment_term() - invoice.check_payment_method() - invoice.check_revenue_type() else: invoice.check_invoice() + if is_modified_note: + invoice.check_ncf_number_modified() + cls._ncf_check_fiscal_classification(invoice) invoice.check_payment_term() - invoice.check_payment_method() - invoice.check_revenue_type() else: if is_without_ncf: @@ -1787,13 +1864,29 @@ class Invoice(metaclass=PoolMeta): if is_credit_note: invoice.check_credit_note() invoice.check_ncf_number_modified() + invoice.check_no_expiration_date() + cls._ncf_check_fiscal_classification(invoice) invoice.check_payment_term() - invoice.check_payment_method() - invoice.check_expense_type() else: + if is_modified_note: + invoice.check_ncf_number_modified() + invoice.check_no_expiration_date() + cls._ncf_check_fiscal_classification(invoice) invoice.check_payment_term() - invoice.check_expense_type() - invoice.check_isr_withholding_type() - invoice.check_payment_method() super()._post(invoices) + + +class InvoiceReport(metaclass=PoolMeta): + __name__ = 'account.invoice' + + @classmethod + def get_context(cls, records, header, data): + context = super().get_context(records, header, data) + invoice = context.get('invoice') + ncf_type_map = dict(NCF_TYPE) + ncf_type_name = '' + if invoice and invoice.ncf_type: + ncf_type_name = ncf_type_map.get(invoice.ncf_type, '') + context['ncf_type_name'] = ncf_type_name + return context diff --git a/invoice.xml b/invoice.xml index 7747954..cb9ca43 100755 --- a/invoice.xml +++ b/invoice.xml @@ -16,18 +16,6 @@ this repository contains the full copyright notices and license terms. --> invoice_tree - - account.invoice.line - - invoice_line_form - - - - account.invoice.line - - invoice_line_tree - - Factura diff --git a/locale/es.po b/locale/es.po new file mode 100644 index 0000000..d5c6c32 --- /dev/null +++ b/locale/es.po @@ -0,0 +1,711 @@ +# +msgid "" +msgstr "" +"Project-Id-Version: ncf_manager 8.0\n" +"PO-Revision-Date: 2026-07-23 00:00-0400\n" +"Last-Translator: Automatically generated\n" +"Language-Team: Spanish\n" +"Language: es\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" + +msgctxt "field:account.configuration.default_ncf_type,default_customer_ncf_type:" +msgid "Default Customer NCF Type" +msgstr "Tipo NCF predeterminado de cliente" + +msgctxt "field:account.configuration.default_ncf_type,default_supplier_ncf_type:" +msgid "Default Supplier NCF Type" +msgstr "Tipo NCF predeterminado de proveedor" + +msgctxt "field:account.invoice,expense_type:" +msgid "Expense Type" +msgstr "Tipo de gasto" + +msgctxt "field:account.invoice,expense_type_string:" +msgid "expense_type" +msgstr "expense_type" + +msgctxt "field:account.invoice,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:account.invoice,id_type:" +msgid "ID Type" +msgstr "Tipo de identificación" + +msgctxt "field:account.invoice,isr_withholding_type:" +msgid "ISR Withholding Type" +msgstr "Tipo de retención ISR" + +msgctxt "field:account.invoice,isr_withholding_type_string:" +msgid "isr_withholding_type" +msgstr "isr_withholding_type" + +msgctxt "field:account.invoice,ncf_cancellation_reason:" +msgid "NCF Cancellation Reason" +msgstr "Motivo de cancelación NCF" + +msgctxt "field:account.invoice,ncf_cancellation_type:" +msgid "NCF Cancellation Type" +msgstr "Tipo de cancelación NCF" + +msgctxt "field:account.invoice,ncf_cancellation_type_string:" +msgid "ncf_cancellation_type" +msgstr "ncf_cancellation_type" + +msgctxt "field:account.invoice,ncf_number:" +msgid "NCF Number" +msgstr "Número NCF" + +msgctxt "field:account.invoice,ncf_number_modified:" +msgid "NCF Modified" +msgstr "NCF modificado" + +msgctxt "field:account.invoice,ncf_sequence:" +msgid "Tipo NCF" +msgstr "Tipo NCF" + +msgctxt "field:account.invoice,ncf_type:" +msgid "NCF Type" +msgstr "Tipo NCF" + +msgctxt "field:account.invoice,ncf_type_code:" +msgid "NCF Type Code" +msgstr "Código de tipo NCF" + +msgctxt "field:account.invoice,payment_method:" +msgid "Method of Payment" +msgstr "Forma de pago" + +msgctxt "field:account.invoice,payment_method_string:" +msgid "payment_method" +msgstr "payment_method" + +msgctxt "field:account.invoice,revenue_type:" +msgid "Revenue Type" +msgstr "Tipo de ingreso" + +msgctxt "field:account.invoice,revenue_type_string:" +msgid "revenue_type" +msgstr "revenue_type" + +msgctxt "field:account.invoice,security_code:" +msgid "Security Code" +msgstr "Código de seguridad" + +msgctxt "field:ir.sequence,approved_qty:" +msgid "Approved Quantity" +msgstr "Cantidad aprobada" + +msgctxt "field:ir.sequence,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ir.sequence,from_number:" +msgid "From Number" +msgstr "Número inicial" + +msgctxt "field:ir.sequence,remaining_qty:" +msgid "Remaining Quantity" +msgstr "Cantidad restante" + +msgctxt "field:ir.sequence,until_number:" +msgid "Until Number" +msgstr "Número final" + +msgctxt "field:ncf.manager,app_date:" +msgid "Application Date" +msgstr "Fecha de solicitud" + +msgctxt "field:ncf.manager,app_number:" +msgid "Application Number" +msgstr "Número de solicitud" + +msgctxt "field:ncf.manager,auth_number:" +msgid "Authorization Number" +msgstr "Número de autorización" + +msgctxt "field:ncf.manager,company:" +msgid "Company" +msgstr "Empresa" + +msgctxt "field:ncf.manager,ncf_sequences:" +msgid "pos" +msgstr "pos" + +msgctxt "field:ncf.manager,state:" +msgid "State" +msgstr "Estado" + +msgctxt "field:ncf.manager,state_string:" +msgid "state" +msgstr "state" + +msgctxt "field:ncf.manager.sequence,invoice_type:" +msgid "Invoice Type" +msgstr "Tipo de factura" + +msgctxt "field:ncf.manager.sequence,ncf_sequences:" +msgid "NCF Sequences" +msgstr "Secuencias NCF" + +msgctxt "field:ncf.manager.sequence,ncf_type:" +msgid "NCF Type" +msgstr "Tipo NCF" + +msgctxt "field:ncf.manager.sequence,ncf_type_string:" +msgid "ncf_type" +msgstr "ncf_type" + +msgctxt "field:ncf.manager.sequence,pos:" +msgid "Point of Sale" +msgstr "Punto de venta" + +msgctxt "field:ncf.manager.sequence,state:" +msgid "State" +msgstr "Estado" + +msgctxt "field:ncf.manager.sequence,state_string:" +msgid "state" +msgstr "state" + +msgctxt "field:party.party.ncf_type,party:" +msgid "Party" +msgstr "Tercero" + +msgctxt "field:res.user,digital_signature:" +msgid "Digital Signature" +msgstr "Firma digital" + +msgctxt "field:res.user,z_digital_signature:" +msgid "Digital Signature" +msgstr "Firma digital" + +msgctxt "model:account.configuration,string:" +msgid "Account Configuration" +msgstr "Configuración contable" + +msgctxt "model:account.configuration.default_ncf_type,string:" +msgid "Account Configuration Default NCF Type" +msgstr "Tipo NCF predeterminado de configuración contable" + +msgctxt "model:ir.action,name:account_invoice.report_invoice" +msgid "Invoice" +msgstr "Factura" + +msgctxt "model:ir.action,name:act_ncf_manager" +msgid "NCF Manager" +msgstr "Gestor de NCF" + +msgctxt "model:ir.message,text:msg_amount_credit_note_negative" +msgid "The Total Amount of the Credit Note must be Negative." +msgstr "El importe total de la nota de crédito debe ser negativo." + +msgctxt "model:ir.message,text:msg_amount_invoice_no_negative" +msgid "The Total Amount of the Invoice not must be Negative." +msgstr "El importe total de la factura no debe ser negativo." + +msgctxt "model:ir.message,text:msg_duplicated_ncf_number_invoice" +msgid "You are adding an invoice with an already registered NCF." +msgstr "Está agregando una factura con un NCF ya registrado." + +msgctxt "model:ir.message,text:msg_inactive_ncf_manager" +msgid "The NCF Manager (point of sale) for invoice \"%(invoice)s\" is inactive." +msgstr "El gestor NCF (punto de venta) de la factura \"%(invoice)s\" está inactivo." + +msgctxt "model:ir.message,text:msg_inactive_ncf_sequence" +msgid "The NCF sequence selected for invoice \"%(invoice)s\" is inactive." +msgstr "La secuencia NCF seleccionada para la factura \"%(invoice)s\" está inactiva." + +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_greater_11_under_13" +msgid "You have added the NCF an incorrect characters length greater 11 and under 13." +msgstr "El NCF indicado tiene una longitud incorrecta mayor que 11 y menor que 13 caracteres." + +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_greater_13_under_19" +msgid "You have added the NCF an incorrect characters length greater 13 and under 19." +msgstr "El NCF indicado tiene una longitud incorrecta mayor que 13 y menor que 19 caracteres." + +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_modified" +msgid "You have added an incorrect characters length the modified NCF." +msgstr "El NCF modificado indicado tiene una longitud incorrecta." + +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_under_11" +msgid "You have added the NCF an incorrect characters length under 11." +msgstr "El NCF indicado tiene una longitud incorrecta menor que 11 caracteres." + +msgctxt "model:ir.message,text:msg_invalid_encf_number" +msgid "NCF: \"%(number)s\" is not correct or does not correspond to this RNC." +msgstr "El NCF \"%(number)s\" no es correcto o no corresponde a este RNC." + +msgctxt "model:ir.message,text:msg_invalid_ncf_number" +msgid "NCF: \"%(number)s\" is not correct or does not correspond to this RNC." +msgstr "El NCF \"%(number)s\" no es correcto o no corresponde a este RNC." + +msgctxt "model:ir.message,text:msg_invalid_ncf_sequence_invoice_type" +msgid "The NCF sequence invoice type does not match invoice \"%(invoice)s\"." +msgstr "El tipo de factura de la secuencia NCF no coincide con la factura \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_invalid_ncf_sequence_type" +msgid "The NCF type on the sequence does not match the NCF type selected on invoice \"%(invoice)s\"." +msgstr "El tipo NCF de la secuencia no coincide con el tipo NCF seleccionado en la factura \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_missing_credit_note_sequence" +msgid "No active credit note sequence available for type \"%(ncf_type)s\" in company \"%(company)s\"." +msgstr "No hay secuencia activa de nota de crédito para el tipo \"%(ncf_type)s\" en la empresa \"%(company)s\"." + +msgctxt "model:ir.message,text:msg_missing_debit_note_sequence" +msgid "No active debit note sequence available for type \"%(ncf_type)s\" in company \"%(company)s\"." +msgstr "No hay secuencia activa de nota de débito para el tipo \"%(ncf_type)s\" en la empresa \"%(company)s\"." + +msgctxt "model:ir.message,text:msg_missing_ncf_cancellation_reason" +msgid "You must enter a DGII cancellation reason before cancelling fiscal invoice \"%(invoice)s\"." +msgstr "Debe indicar un motivo de cancelación DGII antes de cancelar la factura fiscal \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_missing_ncf_cancellation_type" +msgid "You must select a DGII cancellation type before cancelling fiscal invoice \"%(invoice)s\"." +msgstr "Debe seleccionar un tipo de cancelación DGII antes de cancelar la factura fiscal \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_missing_ncf_sequence" +msgid "No active NCF sequence available for invoice \"%(invoice)s\"." +msgstr "No hay secuencia NCF activa disponible para la factura \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_missing_strict_sequence" +msgid "No strict sequence configured in the selected NCF sequence for invoice \"%(invoice)s\"." +msgstr "No hay secuencia estricta configurada en la secuencia NCF seleccionada para la factura \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_ncf_running_out" +msgid "There are only \\\"%(remaining_ncf)s\\\" vouchers for this sequence." +msgstr "There are only \\\"%(remaining_ncf)s\\\" vouchers for this sequence." + +msgctxt "model:ir.message,text:msg_ncf_sequence_expired" +msgid "This sequence is expired." +msgstr "Esta secuencia está vencida." + +msgctxt "model:ir.message,text:msg_ncf_sequence_finished" +msgid "The NCF sequence is exhausted. No more numbers are available." +msgstr "La secuencia NCF está agotada. No hay más números disponibles." + +msgctxt "model:ir.message,text:msg_no_expense_type" +msgid "No Expense Type Selected." +msgstr "No se seleccionó tipo de gasto." + +msgctxt "model:ir.message,text:msg_no_expiration_date" +msgid "No have added NCF Expiration Date." +msgstr "No se ha indicado fecha de vencimiento del NCF." + +msgctxt "model:ir.message,text:msg_no_isr_withholding_type" +msgid "No ISR Withholding Type Selected." +msgstr "No se seleccionó tipo de retención ISR." + +msgctxt "model:ir.message,text:msg_no_method_payment" +msgid "No Method Payment Selected." +msgstr "No se seleccionó forma de pago." + +msgctxt "model:ir.message,text:msg_no_ncf_number" +msgid "You have not added the NCF Number." +msgstr "No ha indicado el número NCF." + +msgctxt "model:ir.message,text:msg_no_ncf_number_modified" +msgid "You have not added the modified NCF." +msgstr "No ha indicado el NCF modificado." + +msgctxt "model:ir.message,text:msg_no_ncf_type" +msgid "No NCF Type Selected." +msgstr "No se seleccionó tipo NCF." + +msgctxt "model:ir.message,text:msg_no_payment_term" +msgid "No Payment Term Selected." +msgstr "No se seleccionó término de pago." + +msgctxt "model:ir.message,text:msg_no_revenue_type" +msgid "No Revenue Type Selected." +msgstr "No se seleccionó tipo de ingreso." + +msgctxt "model:ir.message,text:msg_no_security_code" +msgid "You have not added the security code." +msgstr "No ha indicado el código de seguridad." + +msgctxt "model:ir.message,text:msg_not_ncf_available" +msgid "There are no more vouchers available for this sequence." +msgstr "No hay más comprobantes disponibles para esta secuencia." + +msgctxt "model:ir.message,text:msg_partial_credit_note_refund_not_allowed" +msgid "Partial credit note refund is not allowed." +msgstr "No se permite devolución parcial de nota de crédito." + +msgctxt "model:ir.sequence.strict,string:" +msgid "Sequence Strict" +msgstr "Secuencia estricta" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_credit_note_04" +msgid "Nota de Crédito" +msgstr "Nota de Crédito" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_credit_note_34" +msgid "Nota de Crédito Electrónica" +msgstr "Nota de Crédito Electrónica" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_01" +msgid "Factura de Crédito Fiscal" +msgstr "Factura de Crédito Fiscal" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_02" +msgid "Factura de Consumo" +msgstr "Factura de Consumo" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_03" +msgid "Nota de Débito" +msgstr "Nota de Débito" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_11" +msgid "Comprobante de Compras" +msgstr "Comprobante de Compras" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_12" +msgid "Registro Único de Ingreso" +msgstr "Registro Único de Ingreso" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_13" +msgid "Comprobante para Gasto Menor" +msgstr "Comprobante para Gasto Menor" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_14" +msgid "Comprobante de Regímen Especial" +msgstr "Comprobante de Regímen Especial" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_15" +msgid "Comprobante Gubernamental" +msgstr "Comprobante Gubernamental" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_16" +msgid "Comprobante para exportaciones" +msgstr "Comprobante para exportaciones" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_17" +msgid "Comprobante para Pagos al Exterior" +msgstr "Comprobante para Pagos al Exterior" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_31" +msgid "Factura de Crédito Fiscal Electrónica" +msgstr "Factura de Crédito Fiscal Electrónica" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_32" +msgid "Factura de Consumo Electrónica" +msgstr "Factura de Consumo Electrónica" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_33" +msgid "Nota de Débito Electrónica" +msgstr "Nota de Débito Electrónica" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_41" +msgid "Compras Electrónico" +msgstr "Compras Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_43" +msgid "Gastos Menores Electrónico" +msgstr "Gastos Menores Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_44" +msgid "Regímenes Especiales Electrónico" +msgstr "Regímenes Especiales Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_45" +msgid "Gubernamental Electrónico" +msgstr "Gubernamental Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_46" +msgid "Exportación Electrónico" +msgstr "Exportación Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_47" +msgid "Pagos al Exterior Electrónico" +msgstr "Pagos al Exterior Electrónico" + +msgctxt "model:ir.ui.menu,name:main_menu_ncf_manager" +msgid "NCF Manager" +msgstr "Gestor de NCF" + +msgctxt "model:ir.ui.menu,name:menu_ncf_manager" +msgid "NCF Manager" +msgstr "Gestor de NCF" + +msgctxt "model:ir.ui.view,name:configuration_view_form" +msgid "configuration_form" +msgstr "configuration_form" + +msgctxt "model:ir.ui.view,name:invoice_view_form" +msgid "invoice_form" +msgstr "invoice_form" + +msgctxt "model:ir.ui.view,name:invoice_view_tree" +msgid "invoice_tree" +msgstr "invoice_tree" + +msgctxt "model:ir.ui.view,name:ncf_manager_sequences_view_form" +msgid "ncf_manager_sequences_form" +msgstr "ncf_manager_sequences_form" + +msgctxt "model:ir.ui.view,name:ncf_manager_sequences_view_tree" +msgid "ncf_manager_sequences_tree" +msgstr "ncf_manager_sequences_tree" + +msgctxt "model:ir.ui.view,name:ncf_manager_view_form" +msgid "ncf_manager_form" +msgstr "ncf_manager_form" + +msgctxt "model:ir.ui.view,name:ncf_manager_view_tree" +msgid "ncf_manager_tree" +msgstr "ncf_manager_tree" + +msgctxt "model:ir.ui.view,name:party_view_form" +msgid "party_form" +msgstr "party_form" + +msgctxt "model:ir.ui.view,name:sequence_view_form" +msgid "sequence_form" +msgstr "sequence_form" + +msgctxt "model:ir.ui.view,name:user_view_form" +msgid "user_form" +msgstr "user_form" + +msgctxt "model:ncf.manager,string:" +msgid "NCF Manager" +msgstr "Gestor de NCF" + +msgctxt "model:ncf.manager.sequence,string:" +msgid "NCF Manager Sequences" +msgstr "Secuencias del gestor de NCF" + +msgctxt "model:party.party.ncf_type,string:" +msgid "Party Ncf Type" +msgstr "Tipo NCF de tercero" + +msgctxt "selection:ncf.manager,state:active" +msgid "Active" +msgstr "Activo" + +msgctxt "selection:ncf.manager,state:draft" +msgid "Draft" +msgstr "Borrador" + +msgctxt "selection:ncf.manager,state:finished" +msgid "Finished" +msgstr "Finalizado" + +msgctxt "selection:ncf.manager.sequence,invoice_type:invoice_customer" +msgid "Customer Invoice" +msgstr "Factura de cliente" + +msgctxt "selection:ncf.manager.sequence,invoice_type:invoice_supplier" +msgid "Supplier Invoice" +msgstr "Factura de proveedor" + +msgctxt "selection:ncf.manager.sequence,state:active" +msgid "Active" +msgstr "Activo" + +msgctxt "selection:ncf.manager.sequence,state:draft" +msgid "Draft" +msgstr "Borrador" + +msgctxt "selection:ncf.manager.sequence,state:finished" +msgid "Finished" +msgstr "Finalizado" + +msgctxt "field:ncf.manager,activated_by:" +msgid "Activated By" +msgstr "Activada por" + +msgctxt "field:ncf.manager,activated_at:" +msgid "Activated At" +msgstr "Fecha de activación" + +msgctxt "field:ncf.manager,finished_by:" +msgid "Finished By" +msgstr "Finalizada por" + +msgctxt "field:ncf.manager,finished_at:" +msgid "Finished At" +msgstr "Fecha de finalización" + +msgctxt "field:ncf.manager.sequence,sequence_mode:" +msgid "Sequence Configuration" +msgstr "Configuración de secuencia" + +msgctxt "field:ncf.manager.sequence,ncf_sequences:" +msgid "Fiscal Sequence" +msgstr "Secuencia fiscal" + +msgctxt "field:ncf.manager.sequence,expected_prefix:" +msgid "Expected Prefix" +msgstr "Prefijo esperado" + +msgctxt "field:ncf.manager.sequence,expected_padding:" +msgid "Expected Padding" +msgstr "Longitud del consecutivo" + +msgctxt "field:ncf.manager.sequence,from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,effective_from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,effective_until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,effective_number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,effective_expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,tree_from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,tree_until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,tree_number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,tree_expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,availability:" +msgid "Availability" +msgstr "Disponibilidad" + +msgctxt "selection:ncf.manager.sequence,sequence_mode:existing" +msgid "Select Existing Sequence" +msgstr "Seleccionar secuencia existente" + +msgctxt "selection:ncf.manager.sequence,sequence_mode:create" +msgid "Create Sequence on Activation" +msgstr "Crear secuencia al activar" + +msgctxt "selection:ncf.manager.sequence,availability:available" +msgid "Available" +msgstr "Disponible" + +msgctxt "selection:ncf.manager.sequence,availability:low" +msgid "Running Low" +msgstr "Próxima a agotarse" + +msgctxt "selection:ncf.manager.sequence,availability:expired" +msgid "Expired" +msgstr "Vencida" + +msgctxt "selection:ncf.manager.sequence,availability:exhausted" +msgid "Exhausted" +msgstr "Agotada" + +msgctxt "model:ir.model.button,string:ncf_manager_activate_button" +msgid "Activate" +msgstr "Activar" + +msgctxt "model:ir.model.button,string:ncf_manager_finish_button" +msgid "Finish" +msgstr "Finalizar" + +msgctxt "model:ir.model.button,string:ncf_sequence_finish_button" +msgid "Finish Sequence" +msgstr "Finalizar secuencia" + +msgctxt "view:ncf.manager:" +msgid "Authorized Fiscal Sequences" +msgstr "Secuencias fiscales autorizadas" + +msgctxt "field:ncf.import.start,company:" +msgid "Company" +msgstr "Empresa" + +msgctxt "field:ncf.import.start,file_:" +msgid "DGII File" +msgstr "Archivo de la DGII" + +msgctxt "field:ncf.import.start,filename:" +msgid "Filename" +msgstr "Nombre del archivo" + +msgctxt "field:ncf.import.start,activate:" +msgid "Activate Imported Authorization" +msgstr "Activar autorización importada" + +msgctxt "field:ncf.manager,source_filename:" +msgid "Source Filename" +msgstr "Nombre del archivo fuente" + +msgctxt "field:ncf.manager,source_hash:" +msgid "Source SHA-256" +msgstr "SHA-256 del archivo fuente" + +msgctxt "field:ncf.manager,source_file:" +msgid "DGII Source File" +msgstr "Archivo fuente de la DGII" + +msgctxt "field:ncf.manager,imported_by:" +msgid "Imported By" +msgstr "Importado por" + +msgctxt "field:ncf.manager,imported_at:" +msgid "Imported At" +msgstr "Fecha de importación" + +msgctxt "field:ncf.manager.sequence,auth_number:" +msgid "Authorization Number" +msgstr "Número de autorización" + +msgctxt "field:ncf.manager.sequence,authorization_date:" +msgid "Authorization Date" +msgstr "Fecha de autorización" + +msgctxt "field:ncf.manager.sequence,dgii_status:" +msgid "DGII Status" +msgstr "Estado en DGII" + +msgctxt "field:ncf.manager.sequence,requested_quantity:" +msgid "Requested Quantity" +msgstr "Cantidad solicitada" + +msgctxt "field:ncf.manager.sequence,approved_quantity:" +msgid "Approved Quantity" +msgstr "Cantidad aprobada" + +msgctxt "field:ncf.manager.sequence,usage_type:" +msgid "Usage Type" +msgstr "Tipo de uso" + +msgctxt "field:ncf.manager.sequence,dgii_detail:" +msgid "DGII Detail" +msgstr "Detalle de la DGII" + +msgctxt "model:ir.action,name:act_ncf_import" +msgid "Import DGII Authorization" +msgstr "Importar autorización de la DGII" + +msgctxt "model:ir.ui.menu,name:menu_ncf_import" +msgid "Import DGII Authorization" +msgstr "Importar autorización de la DGII" diff --git a/locale/es_419.po b/locale/es_419.po index d029381..9c07c0b 100644 --- a/locale/es_419.po +++ b/locale/es_419.po @@ -1,21 +1,233 @@ -# msgid "" msgstr "" -"Project-Id-Version: ncf_manager 7.0\n" -"PO-Revision-Date: 2026-07-15 00:00-0400\n" -"Last-Translator: Automatically generated\n" +"Project-Id-Version: ncf_manager 8.0\n" +"PO-Revision-Date: 2026-08-16 00:00-0400\n" +"Last-Translator: Fundación Un País Mejor\n" "Language-Team: Spanish (Latin America)\n" "Language: es_419\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -# Class: NCFManager -# Model: ncf.manager +msgctxt "field:account.configuration,default_customer_ncf_type:" +msgid "Default Customer NCF Type" +msgstr "Tipo NCF Cliente Predeterminado" -msgctxt "field:ncf.manager,company:" -msgid "Company" -msgstr "Empresa" +msgctxt "field:account.configuration,default_supplier_ncf_type:" +msgid "Default Supplier NCF Type" +msgstr "Tipo NCF Proveedor Predeterminado" + +msgctxt "field:account.configuration.default_ncf_type,default_customer_ncf_type:" +msgid "Default Customer NCF Type" +msgstr "Tipo NCF predeterminado de cliente" + +msgctxt "field:account.configuration.default_ncf_type,default_supplier_ncf_type:" +msgid "Default Supplier NCF Type" +msgstr "Tipo NCF predeterminado de proveedor" + +msgctxt "field:account.invoice,amount_invoiced_goods:" +msgid "Amount Invoiced in Goods" +msgstr "Monto Facturado en Bienes" + +msgctxt "field:account.invoice,amount_invoiced_services:" +msgid "Amount Invoiced in Services" +msgstr "Monto Facturado en Servicios" + +msgctxt "field:account.invoice,cdt_invoiced:" +msgid "CDT Invoiced" +msgstr "CDT Facturado" + +msgctxt "field:account.invoice,expense_type:" +msgid "Expense Type" +msgstr "Tipo de Gasto" + +msgctxt "field:account.invoice,expense_type_string:" +msgid "expense_type" +msgstr "expense_type" + +msgctxt "field:account.invoice,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de Vencimiento" + +msgctxt "field:account.invoice,id_type:" +msgid "ID Type" +msgstr "Tipo ID" + +msgctxt "field:account.invoice,isc_invoiced:" +msgid "ISC Invoiced" +msgstr "ISC Facturado" + +msgctxt "field:account.invoice,isr_withholding:" +msgid "ISR Withholding" +msgstr "ISR Retenido" + +msgctxt "field:account.invoice,isr_withholding_type:" +msgid "ISR Withholding Type" +msgstr "Tipo de Retención en ISR" + +msgctxt "field:account.invoice,isr_withholding_type_string:" +msgid "isr_withholding_type" +msgstr "isr_withholding_type" + +msgctxt "field:account.invoice,itbis_amount_invoiced:" +msgid "ITBIS Invoiced" +msgstr "ITBIS Facturado" + +msgctxt "field:account.invoice,itbis_invoiced:" +msgid "ITBIS Invoiced" +msgstr "ITBIS Facturado" + +msgctxt "field:account.invoice,itbis_withholding:" +msgid "ITBIS Withholding" +msgstr "ITBIS Retenido" + +msgctxt "field:account.invoice,itbis_withholding_acquirer:" +msgid "ITBIS Withholding Acquirer" +msgstr "ITBIS Retenido (Adquirentes)" + +msgctxt "field:account.invoice,ncf_cancellation_reason:" +msgid "NCF Cancellation Reason" +msgstr "Motivo de Anulación NCF" + +msgctxt "field:account.invoice,ncf_cancellation_type:" +msgid "NCF Cancellation Type" +msgstr "Tipo de Anulación NCF" + +msgctxt "field:account.invoice,ncf_cancellation_type_string:" +msgid "ncf_cancellation_type" +msgstr "ncf_cancellation_type" + +msgctxt "field:account.invoice,ncf_number:" +msgid "NCF" +msgstr "NCF" + +msgctxt "field:account.invoice,ncf_number:" +msgid "NCF Number" +msgstr "Número NCF" + +msgctxt "field:account.invoice,ncf_number_modified:" +msgid "NCF Modified" +msgstr "NCF Modificado" + +msgctxt "field:account.invoice,ncf_sequence:" +msgid "Tipo NCF" +msgstr "Tipo NCF" + +msgctxt "field:account.invoice,ncf_type:" +msgid "NCF Type" +msgstr "Tipo NCF" + +msgctxt "field:account.invoice,ncf_type_code:" +msgid "NCF Type Code" +msgstr "Código Tipo NCF" + +msgctxt "field:account.invoice,ncf_type_name:" +msgid "NCF Type" +msgstr "Tipo NCF" + +msgctxt "field:account.invoice,payment_method:" +msgid "Method of Payment" +msgstr "Forma de Pago" + +msgctxt "field:account.invoice,payment_method_barter:" +msgid "Barter" +msgstr "Permuta" + +msgctxt "field:account.invoice,payment_method_card:" +msgid "Credit/Debit Card" +msgstr "Tarjeta Crédito/Débito" + +msgctxt "field:account.invoice,payment_method_cash:" +msgid "Cash" +msgstr "Efectivo" + +msgctxt "field:account.invoice,payment_method_check:" +msgid "Checks/Transfers/Deposit" +msgstr "Cheques/Transferencias/Depósito" + +msgctxt "field:account.invoice,payment_method_credit_note:" +msgid "Credit Note" +msgstr "Nota de Crédito" + +msgctxt "field:account.invoice,payment_method_mixed_payment:" +msgid "Mixed Payment" +msgstr "Mixto" + +msgctxt "field:account.invoice,payment_method_purchase_on_credit:" +msgid "Purchase on Credit" +msgstr "Compra a Crédito" + +msgctxt "field:account.invoice,payment_method_string:" +msgid "payment_method" +msgstr "payment_method" + +msgctxt "field:account.invoice,revenue_type:" +msgid "Revenue Type" +msgstr "Tipo de Ingreso" + +msgctxt "field:account.invoice,revenue_type_string:" +msgid "revenue_type" +msgstr "revenue_type" + +msgctxt "field:account.invoice,security_code:" +msgid "Security Code" +msgstr "Código de Seguridad" + +msgctxt "field:account.invoice,tip:" +msgid "Tip" +msgstr "Propina" + +msgctxt "field:account.invoice,total_amount_invoiced:" +msgid "Total Invoiced" +msgstr "Total Facturado" + +msgctxt "field:account.invoice,untaxed_amount_invoiced:" +msgid "Untaxed Invoiced" +msgstr "Monto Facturado" + +msgctxt "field:account.invoice.line,itbis_withholding_line:" +msgid "ITBIS Withholding" +msgstr "ITBIS Retenido" + +msgctxt "field:ir.sequence,approved_qty:" +msgid "Approved Quantity" +msgstr "Cantidad Autorizada" + +msgctxt "field:ir.sequence,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de Vencimiento" + +msgctxt "field:ir.sequence,from_number:" +msgid "From Number" +msgstr "Número Inicial" + +msgctxt "field:ir.sequence,remaining_qty:" +msgid "Remaining Quantity" +msgstr "Cantidad Disponible" + +msgctxt "field:ir.sequence,until_number:" +msgid "Until Number" +msgstr "Número Final" + +msgctxt "field:ir.sequence.strict,approved_qty:" +msgid "Approved Quantity" +msgstr "Cantidad Autorizada" + +msgctxt "field:ir.sequence.strict,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de Vencimiento" + +msgctxt "field:ir.sequence.strict,from_number:" +msgid "From Number" +msgstr "Número Inicial" + +msgctxt "field:ir.sequence.strict,remaining_qty:" +msgid "Remaining Quantity" +msgstr "Cantidad Disponible" + +msgctxt "field:ir.sequence.strict,until_number:" +msgid "Until Number" +msgstr "Número Final" msgctxt "field:ncf.manager,app_date:" msgid "Application Date" @@ -29,244 +241,218 @@ msgctxt "field:ncf.manager,auth_number:" msgid "Authorization Number" msgstr "No. Autorización" +msgctxt "field:ncf.manager,company:" +msgid "Company" +msgstr "Empresa" + msgctxt "field:ncf.manager,ncf_sequences:" msgid "NCF Sequences" msgstr "Secuencias de NCF" +msgctxt "field:ncf.manager,ncf_sequences:" +msgid "pos" +msgstr "pos" + msgctxt "field:ncf.manager,state:" msgid "State" msgstr "Estado" -msgctxt "selection:ncf.manager,state:" -msgid "Active" -msgstr "Activa" - -msgctxt "selection:ncf.manager,state:" -msgid "Draft" -msgstr "Borrador" - -msgctxt "selection:ncf.manager,state:" -msgid "Finished" -msgstr "Terminada" - -# Class: NCFManagerSequences -# Model: ncf.manager.sequence - -msgctxt "field:ncf.manager.sequence,pos:" -msgid "Point of Sale" -msgstr "Punto de Venta" - -msgctxt "field:ncf.manager.sequence,ncf_type:" -msgid "NCF Type" -msgstr "Tipo de NCF" - -msgctxt "help:ncf.manager.sequence,ncf_type:" -msgid "Choose a NCF Type" -msgstr "Elija un Tipo de NCF" - -msgctxt "field:ncf.manager.sequence,ncf_sequences:" -msgid "NCF Sequences" -msgstr "Secuencias de NCF" +msgctxt "field:ncf.manager,state_string:" +msgid "state" +msgstr "state" msgctxt "field:ncf.manager.sequence,invoice_type:" msgid "Invoice Type" msgstr "Tipo de Factura" -msgctxt "selection:ncf.manager.sequence,invoice_type:" -msgid "Customer Invoice" -msgstr "Factura de Cliente" +msgctxt "field:ncf.manager.sequence,ncf_sequences:" +msgid "NCF Sequences" +msgstr "Secuencias de NCF" -msgctxt "selection:ncf.manager.sequence,invoice_type:" -msgid "Supplier Invoice" -msgstr "Factura de Proveedor" +msgctxt "field:ncf.manager.sequence,ncf_type:" +msgid "NCF Type" +msgstr "Tipo de NCF" + +msgctxt "field:ncf.manager.sequence,ncf_type_string:" +msgid "ncf_type" +msgstr "ncf_type" + +msgctxt "field:ncf.manager.sequence,pos:" +msgid "Point of Sale" +msgstr "Punto de Venta" msgctxt "field:ncf.manager.sequence,state:" msgid "State" msgstr "Estado" -msgctxt "selection:ncf.manager.sequence,state:" -msgid "Active" -msgstr "Activa" +msgctxt "field:ncf.manager.sequence,state_string:" +msgid "state" +msgstr "state" -msgctxt "selection:ncf.manager.sequence,state:" -msgid "Draft" -msgstr "Borrador" +msgctxt "field:party.party,customer_ncf_type:" +msgid "Customer NCF Type" +msgstr "Tipo NCF Cliente" -msgctxt "selection:ncf.manager.sequence,state:" -msgid "Finished" -msgstr "Terminada" +msgctxt "field:party.party,supplier_ncf_type:" +msgid "Supplier NCF Type" +msgstr "Tipo NCF Proveedor" + +msgctxt "field:party.party.ncf_type,party:" +msgid "Party" +msgstr "Tercero" + +msgctxt "field:res.user,digital_signature:" +msgid "Digital Signature" +msgstr "Firma Digital" + +msgctxt "field:res.user,z_digital_signature:" +msgid "Digital Signature" +msgstr "Firma Digital" + +msgctxt "help:account.configuration,default_customer_ncf_type:" +msgid "Default customer NCF type for new parties." +msgstr "Tipo de NCF de cliente predeterminado para nuevos terceros." + +msgctxt "help:account.configuration,default_supplier_ncf_type:" +msgid "Default supplier NCF type for new parties." +msgstr "Tipo de NCF de proveedor predeterminado para nuevos terceros." + +msgctxt "help:account.invoice,id_type:" +msgid "The identifier type of party in the invoice." +msgstr "El tipo de identificador del tercero en la factura." + +msgctxt "help:ncf.manager.sequence,ncf_type:" +msgid "Choose a NCF Type" +msgstr "Elija un Tipo de NCF" + +msgctxt "model:account.configuration,string:" +msgid "Account Configuration" +msgstr "Configuración contable" + +msgctxt "model:account.configuration.default_ncf_type,string:" +msgid "Account Configuration Default NCF Type" +msgstr "Tipo NCF predeterminado de configuración contable" + +msgctxt "model:ir.action,name:account_invoice.report_invoice" +msgid "Invoice" +msgstr "Factura" + +msgctxt "model:ir.action,name:act_ncf_manager" +msgid "NCF Manager" +msgstr "Gestor de NCF" msgctxt "model:ir.action,name:act_ncf_manager_form" msgid "NCF Manager" msgstr "Gestión de NCF" -msgctxt "model:ir.ui.menu,name:main_menu_ncf_manager" -msgid "NCF Manager" -msgstr "Gestión de NCF" - -msgctxt "model:ir.ui.menu,name:menu_ncf_manager" -msgid "NCF Manager" -msgstr "Gestión de NCF" - -msgctxt "model:ir.ui.menu,name:menu_ncf_manager_form" -msgid "NCF Manager" -msgstr "Gestión de NCF" - -msgctxt "model:ncf.manager,name:" -msgid "NCF Manager" -msgstr "Gestión de NCF" - -# Class: Invoice -# Model: account.invoice - msgctxt "model:ir.action,name:report_invoice" -msgid "Factura" +msgid "Invoice" msgstr "Factura" -msgctxt "field:account.invoice,expiration_date:" -msgid "Expiration Date" -msgstr "Fecha de Vencimiento" +msgctxt "model:ir.message,text:msg_amount_credit_note_negative" +msgid "The Total Amount of the Credit Note must be Negative." +msgstr "El Monto Total de la Nota de Crédito debe ser Negativo." -msgctxt "field:account.invoice,ncf_number:" -msgid "NCF" -msgstr "NCF" +msgctxt "model:ir.message,text:msg_amount_invoice_no_negative" +msgid "The Total Amount of the Invoice not must be Negative." +msgstr "El Monto Total de la Factura no debe ser Negativo." -msgctxt "field:account.invoice,ncf_number_modified:" -msgid "NCF Modified" -msgstr "NCF Modificado" +msgctxt "model:ir.message,text:msg_duplicated_ncf_number_invoice" +msgid "You are adding an invoice with an already registered NCF." +msgstr "Esta agregando una factura con un NCF ya registrado." -msgctxt "field:account.invoice,security_code:" -msgid "Security Code" -msgstr "Código de Seguridad" +msgctxt "model:ir.message,text:msg_inactive_ncf_manager" +msgid "The NCF Manager (point of sale) for invoice \"%(invoice)s\" is inactive." +msgstr "El NCF Manager (punto de venta) de la factura \"%(invoice)s\" está inactivo." -msgctxt "field:account.invoice,ncf_type:" -msgid "NCF Type" -msgstr "Tipo NCF" +msgctxt "model:ir.message,text:msg_inactive_ncf_sequence" +msgid "The NCF sequence selected for invoice \"%(invoice)s\" is inactive." +msgstr "La secuencia NCF seleccionada para la factura \"%(invoice)s\" está inactiva." -msgctxt "field:account.invoice,ncf_type_name:" -msgid "NCF Type" -msgstr "Tipo NCF" +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_greater_11_under_13" +msgid "You have added the NCF an incorrect characters length greater 11 and under 13." +msgstr "Ha agregado una longitud de caracteres incorrecta al NCF mayor a 11 e inferior a 13." -msgctxt "selection:account.invoice,ncf_type:" -msgid "Credit Note" -msgstr "Nota de Crédito" +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_greater_13_under_19" +msgid "You have added the NCF an incorrect characters length greater 13 and under 19." +msgstr "Ha agregado una longitud de caracteres incorrecta al NCF mayor a 13 e inferior a 19." -msgctxt "selection:account.invoice,ncf_type:" -msgid "Debit Note" -msgstr "Nota de Débito" +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_modified" +msgid "You have added an incorrect characters length the modified NCF." +msgstr "Ha agregado una longitud de caracteres incorrecta al NCF modificado." -msgctxt "selection:account.invoice,ncf_type:" -msgid "Government" -msgstr "Gubernamental" +msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_under_11" +msgid "You have added the NCF an incorrect characters length under 11." +msgstr "Ha agregado una longitud de caracteres incorrecta al NCF inferior a 11." -msgctxt "selection:account.invoice,ncf_type:" -msgid "Income Single Registry" -msgstr "Registro Único de Ingresos" +msgctxt "model:ir.message,text:msg_invalid_encf_number" +msgid "NCF: \"%(ncf)s\" is not correct or does not correspond to this RNC." +msgstr "NCF: \"%(ncf)s\" no es correcto o no corresponde a este RNC" -msgctxt "selection:account.invoice,ncf_type:" -msgid "Informal Provider Registry" -msgstr "Registro de Proveedor Informal" - -msgctxt "selection:account.invoice,ncf_type:" -msgid "Invoice for Final Consumer" -msgstr "Factura para consumidor Final" - -msgctxt "selection:account.invoice,ncf_type:" -msgid "Minor Expense Registry" -msgstr "Registro de Gastos Menores" - -msgctxt "selection:account.invoice,ncf_type:" -msgid "Special Regime of Taxation" -msgstr "Régimen Especial de Tributación" - -msgctxt "selection:account.invoice,ncf_type:" -msgid "Valid Invoice for Tax Credit" -msgstr "Factura Válida para Crédito Fiscal" - -msgctxt "view:account.fiscalyear:" -msgid "NCF Sequences" -msgstr "Secuencias de NCF" - -msgctxt "view:account.invoice:" -msgid "Tax Information" -msgstr "Información Fiscal" - -msgctxt "view:account.invoice:" -msgid "Revenue" -msgstr "Ingreso" - -msgctxt "view:account.invoice:" -msgid "Expense" -msgstr "Gasto" - -msgctxt "view:account.invoice:" -msgid "Method of Payment" -msgstr "Forma de pago" - -msgctxt "field:account.invoice,revenue_type:" -msgid "Revenue Type" -msgstr "Tipo de Ingreso" - -msgctxt "field:account.invoice,expense_type:" -msgid "Expense Type" -msgstr "Tipo de Gasto" - -msgctxt "field:account.invoice,payment_method:" -msgid "Method of Payment" -msgstr "Forma de Pago" - -msgctxt "field:account.invoice,payment_method_cash:" -msgid "Cash" -msgstr "Efectivo" - -msgctxt "field:account.invoice,payment_method_check:" -msgid "Checks/Transfers/Deposit" -msgstr "Cheques/Transferencias/Depósito" - -msgctxt "field:account.invoice,payment_method_card:" -msgid "Credit/Debit Card" -msgstr "Tarjeta Crédito/Débito" - -msgctxt "field:account.invoice,payment_method_purchase_on_credit:" -msgid "Purchase on Credit" -msgstr "Compra a Crédito" - -msgctxt "field:account.invoice,payment_method_barter:" -msgid "Barter" -msgstr "Permuta" - -msgctxt "field:account.invoice,payment_method_credit_note:" -msgid "Credit Note" -msgstr "Nota de Crédito" - -msgctxt "field:account.invoice,payment_method_mixed_payment:" -msgid "Mixed Payment" -msgstr "Mixto" +msgctxt "model:ir.message,text:msg_invalid_encf_number" +msgid "NCF: \"%(number)s\" is not correct or does not correspond to this RNC." +msgstr "El NCF \"%(number)s\" no es correcto o no corresponde a este RNC." msgctxt "model:ir.message,text:msg_invalid_ncf_number" msgid "NCF: \"%(number)s\" is not correct or does not correspond to this RNC." msgstr "NCF: \"%(number)s\" no es correcto o no corresponde a este RNC." -msgctxt "model:ir.message,text:msg_invalid_encf_number" -msgid "NCF: \"%(number)s\" is not correct or does not correspond to this RNC." -msgstr "NCF: \"%(number)s\" no es correcto o no corresponde a este RNC." +msgctxt "model:ir.message,text:msg_invalid_ncf_sequence_invoice_type" +msgid "The NCF sequence invoice type does not match invoice \"%(invoice)s\"." +msgstr "El tipo de factura de la secuencia NCF no coincide con la factura \"%(invoice)s\"." -msgctxt "model:ir.message,text:msg_no_ncf_type" -msgid "No NCF Type Selected." -msgstr "No ha seleccionado el Tipo de NCF." +msgctxt "model:ir.message,text:msg_invalid_ncf_sequence_type" +msgid "The NCF type on the sequence does not match the NCF type selected on invoice \"%(invoice)s\"." +msgstr "El tipo de NCF de la secuencia no coincide con el tipo de NCF seleccionado en la factura \"%(invoice)s\"." -msgctxt "model:ir.message,text:msg_no_payment_term" -msgid "No Payment Term Selected." -msgstr "No ha seleccionado el Término de Pago." +msgctxt "model:ir.message,text:msg_missing_credit_note_sequence" +msgid "No active credit note sequence available for type \"%(ncf_type)s\" in company \"%(company)s\"." +msgstr "No hay secuencia de nota de crédito activa para el tipo \"%(ncf_type)s\" en la empresa \"%(company)s\"." -msgctxt "model:ir.message,text:msg_no_revenue_type" -msgid "No Revenue Type Selected." -msgstr "No ha seleccionado el Tipo de Ingreso." +msgctxt "model:ir.message,text:msg_missing_debit_note_sequence" +msgid "No active debit note sequence available for type \"%(ncf_type)s\" in company \"%(company)s\"." +msgstr "No hay secuencia de nota de débito activa para el tipo \"%(ncf_type)s\" en la empresa \"%(company)s\"." + +msgctxt "model:ir.message,text:msg_missing_ncf_cancellation_reason" +msgid "You must enter a DGII cancellation reason before cancelling fiscal invoice \"%(invoice)s\"." +msgstr "Debe indicar un motivo de anulación DGII antes de cancelar la factura fiscal \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_missing_ncf_cancellation_type" +msgid "You must select a DGII cancellation type before cancelling fiscal invoice \"%(invoice)s\"." +msgstr "Debe seleccionar un tipo de anulación DGII antes de cancelar la factura fiscal \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_missing_ncf_sequence" +msgid "No active NCF sequence available for invoice \"%(invoice)s\"." +msgstr "No hay secuencia NCF activa disponible para la factura \"%(invoice)s\"." + +msgctxt "model:ir.message,text:msg_missing_strict_sequence" +msgid "No strict sequence configured in the selected NCF sequence for invoice \"%(invoice)s\"." +msgstr "La secuencia NCF seleccionada para la factura \"%(invoice)s\" no tiene una secuencia estricta configurada." + +msgctxt "model:ir.message,text:msg_ncf_running_out" +msgid "There are only \"%(remaining_ncf)s\" vouchers for this sequence." +msgstr "Solo quedan \"%(remaining_ncf)s\" comprobantes para esta secuencia." + +msgctxt "model:ir.message,text:msg_ncf_running_out" +msgid "There are only \\\"%(remaining_ncf)s\\\" vouchers for this sequence." +msgstr "There are only \\\"%(remaining_ncf)s\\\" vouchers for this sequence." + +msgctxt "model:ir.message,text:msg_ncf_sequence_expired" +msgid "This sequence is expired." +msgstr "Esta secuencia ha vencido." + +msgctxt "model:ir.message,text:msg_ncf_sequence_finished" +msgid "The NCF sequence is exhausted. No more numbers are available." +msgstr "La secuencia NCF se ha agotado. No hay más números disponibles." msgctxt "model:ir.message,text:msg_no_expense_type" msgid "No Expense Type Selected." msgstr "No ha seleccionado el Tipo de Gasto." +msgctxt "model:ir.message,text:msg_no_expiration_date" +msgid "No have added NCF Expiration Date." +msgstr "No se ha agregado la fecha de vencimiento del NCF." + msgctxt "model:ir.message,text:msg_no_isr_withholding_type" msgid "No ISR Withholding Type Selected." msgstr "No ha seleccionado el Tipo de Retención en ISR." @@ -283,273 +469,185 @@ msgctxt "model:ir.message,text:msg_no_ncf_number_modified" msgid "You have not added the modified NCF." msgstr "No ha agregado el NCF modificado." +msgctxt "model:ir.message,text:msg_no_ncf_type" +msgid "No NCF Type Selected." +msgstr "No ha seleccionado el Tipo de NCF." + +msgctxt "model:ir.message,text:msg_no_payment_term" +msgid "No Payment Term Selected." +msgstr "No ha seleccionado el Término de Pago." + +msgctxt "model:ir.message,text:msg_no_revenue_type" +msgid "No Revenue Type Selected." +msgstr "No ha seleccionado el Tipo de Ingreso." + msgctxt "model:ir.message,text:msg_no_security_code" msgid "You have not added the security code." msgstr "No ha agregado el código de seguridad." -msgctxt "model:ir.message,text:msg_no_expiration_date" -msgid "No have added NCF Expiration Date." -msgstr "No se ha agregado la fecha de vencimiento del NCF." - -msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_under_11" -msgid "You have added the NCF an incorrect characters length under 11." -msgstr "Ha agregado una longitud de caracteres incorrecta al NCF inferior a 11." - -msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_greater_11_under_13" -msgid "You have added the NCF an incorrect characters length greater 11 and under 13." -msgstr "Ha agregado una longitud de caracteres incorrecta al NCF mayor a 11 e inferior a 13." - -msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_greater_13_under_19" -msgid "You have added the NCF an incorrect characters length greater 13 and under 19." -msgstr "Ha agregado una longitud de caracteres incorrecta al NCF mayor a 13 e inferior a 19." - -msgctxt "model:ir.message,text:msg_incorrect_lenght_ncf_number_modified" -msgid "You have added an incorrect characters length the modified NCF." -msgstr "Ha agregado una longitud de caracteres incorrecta al NCF modificado." - -msgctxt "model:ir.message,text:msg_duplicated_ncf_number_invoice" -msgid "You are adding an invoice with an already registered NCF." -msgstr "Esta agregando una factura con un NCF ya registrado." - -msgctxt "model:ir.message,text:msg_amount_credit_note_negative" -msgid "The Total Amount of the Credit Note must be Negative." -msgstr "El Monto Total de la Nota de Crédito debe ser Negativo." - -msgctxt "model:ir.message,text:msg_amount_invoice_no_negative" -msgid "The Total Amount of the Invoice not must be Negative." -msgstr "El Monto Total de la Factura no debe ser Negativo." - -msgctxt "field:account.invoice,itbis_invoiced:" -msgid "ITBIS Invoiced" -msgstr "ITBIS Facturado" - -msgctxt "field:account.invoice,itbis_withholding:" -msgid "ITBIS Withholding" -msgstr "ITBIS Retenido" - -msgctxt "field:account.invoice,isc_invoiced:" -msgid "ISC Invoiced" -msgstr "ISC Facturado" - -msgctxt "field:account.invoice,cdt_invoiced:" -msgid "CDT Invoiced" -msgstr "CDT Facturado" - -msgctxt "field:account.invoice,isr_withholding:" -msgid "ISR Withholding" -msgstr "ISR Retenido" - -msgctxt "field:account.invoice,tip:" -msgid "Tip" -msgstr "Propina" - -msgctxt "field:account.invoice,amount_invoiced_services:" -msgid "Amount Invoiced in Services" -msgstr "Monto Facturado en Servicios" - -msgctxt "field:account.invoice,amount_invoiced_goods:" -msgid "Amount Invoiced in Goods" -msgstr "Monto Facturado en Bienes" - -msgctxt "field:account.invoice,untaxed_amount_invoiced:" -msgid "Untaxed Invoiced" -msgstr "Monto Facturado" - -msgctxt "field:account.invoice,itbis_amount_invoiced:" -msgid "ITBIS Invoiced" -msgstr "ITBIS Facturado" - -msgctxt "field:account.invoice,total_amount_invoiced:" -msgid "Total Invoiced" -msgstr "Total Facturado" - -msgctxt "field:account.invoice,isr_withholding_type:" -msgid "ISR Withholding Type" -msgstr "Tipo de Retención en ISR" - -msgctxt "field:account.invoice,id_type:" -msgid "ID Type" -msgstr "Tipo ID" - -msgctxt "help:account.invoice,id_type:" -msgid "The identifier type of party in the invoice." -msgstr "El tipo de identificador del tercero en la factura." - -msgctxt "field:account.configuration,default_customer_ncf_type:" -msgid "Default Customer NCF Type" -msgstr "Tipo de NCF de cliente por defecto" - -msgctxt "help:account.configuration,default_customer_ncf_type:" -msgid "Default customer NCF type for new parties." -msgstr "Tipo de NCF de cliente por defecto para nuevos terceros." - -msgctxt "field:account.configuration,default_supplier_ncf_type:" -msgid "Default Supplier NCF Type" -msgstr "Tipo de NCF de proveedor por defecto" - -msgctxt "help:account.configuration,default_supplier_ncf_type:" -msgid "Default supplier NCF type for new parties." -msgstr "Tipo de NCF de proveedor por defecto para nuevos terceros." - -msgctxt "field:account.configuration.default_ncf_type,default_customer_ncf_type:" -msgid "Default Customer NCF Type" -msgstr "Tipo de NCF de cliente por defecto" - -msgctxt "field:account.configuration.default_ncf_type,default_supplier_ncf_type:" -msgid "Default Supplier NCF Type" -msgstr "Tipo de NCF de proveedor por defecto" - -msgctxt "field:party.party,customer_ncf_type:" -msgid "Customer NCF Type" -msgstr "Tipo de NCF de cliente" - -msgctxt "field:party.party,supplier_ncf_type:" -msgid "Supplier NCF Type" -msgstr "Tipo de NCF de proveedor" - -msgctxt "field:party.party.ncf_type,party:" -msgid "Party" -msgstr "Tercero" - -msgctxt "field:party.party.ncf_type,customer_ncf_type:" -msgid "Customer NCF Type" -msgstr "Tipo de NCF de cliente" - -msgctxt "field:party.party.ncf_type,supplier_ncf_type:" -msgid "Supplier NCF Type" -msgstr "Tipo de NCF de proveedor" - -msgctxt "model:party.party.ncf_type,name:" -msgid "Party Ncf Type" -msgstr "Tipo de NCF del tercero" - -msgctxt "field:account.invoice,ncf_sequence:" -msgid "Tipo NCF" -msgstr "Tipo NCF" - -msgctxt "field:account.invoice,ncf_type_code:" -msgid "NCF Type Code" -msgstr "Código de tipo NCF" - -msgctxt "help:account.invoice,ncf_type:" -msgid "Fiscal receipt type resolved from the selected NCF sequence." -msgstr "Tipo de comprobante fiscal resuelto desde la secuencia NCF seleccionada." - -msgctxt "field:ir.sequence,from_number:" -msgid "From Number" -msgstr "Desde número" - -msgctxt "field:ir.sequence,until_number:" -msgid "Until Number" -msgstr "Hasta número" - -msgctxt "field:ir.sequence,approved_qty:" -msgid "Approved Quantity" -msgstr "Cantidad aprobada" - -msgctxt "field:ir.sequence,remaining_qty:" -msgid "Remaining Quantity" -msgstr "Cantidad restante" - -msgctxt "field:ir.sequence,expiration_date:" -msgid "Expiration Date" -msgstr "Fecha de vencimiento" - -msgctxt "field:ir.sequence.strict,from_number:" -msgid "From Number" -msgstr "Desde número" - -msgctxt "field:ir.sequence.strict,until_number:" -msgid "Until Number" -msgstr "Hasta número" - -msgctxt "field:ir.sequence.strict,approved_qty:" -msgid "Approved Quantity" -msgstr "Cantidad aprobada" - -msgctxt "field:ir.sequence.strict,remaining_qty:" -msgid "Remaining Quantity" -msgstr "Cantidad restante" - -msgctxt "field:ir.sequence.strict,expiration_date:" -msgid "Expiration Date" -msgstr "Fecha de vencimiento" - msgctxt "model:ir.message,text:msg_not_ncf_available" msgid "There are no more vouchers available for this sequence." msgstr "No hay más comprobantes disponibles para esta secuencia." -msgctxt "model:ir.message,text:msg_ncf_running_out" -msgid "There are only \"%(remaining_ncf)s\" vouchers for this sequence." -msgstr "Solo quedan \"%(remaining_ncf)s\" comprobantes para esta secuencia." - -msgctxt "model:ir.message,text:msg_ncf_sequence_expired" -msgid "This sequence is expired." -msgstr "Esta secuencia está vencida." - -msgctxt "model:ir.message,text:msg_missing_ncf_sequence" -msgid "No active NCF sequence was found for this invoice." -msgstr "No se encontró una secuencia NCF activa para esta factura." - -msgctxt "model:ir.message,text:msg_invalid_ncf_sequence_invoice_type" -msgid "The selected NCF sequence does not match the invoice type." -msgstr "La secuencia NCF seleccionada no corresponde al tipo de factura." - -msgctxt "model:ir.message,text:msg_invalid_ncf_sequence_type" -msgid "The selected NCF sequence does not match the NCF type." -msgstr "La secuencia NCF seleccionada no corresponde al tipo de NCF." - -msgctxt "model:ir.message,text:msg_inactive_ncf_sequence" -msgid "The selected NCF sequence is inactive." -msgstr "La secuencia NCF seleccionada está inactiva." - -msgctxt "model:ir.message,text:msg_inactive_ncf_manager" -msgid "The selected NCF manager is inactive." -msgstr "La gestión de NCF seleccionada está inactiva." - -msgctxt "model:ir.message,text:msg_ncf_sequence_finished" -msgid "This sequence has no available numbers." -msgstr "Esta secuencia no tiene números disponibles." - -msgctxt "model:ir.message,text:msg_missing_strict_sequence" -msgid "The selected NCF configuration has no strict sequence assigned." -msgstr "La configuración NCF seleccionada no tiene una secuencia estricta asignada." - msgctxt "model:ir.message,text:msg_partial_credit_note_refund_not_allowed" -msgid "Partial credit notes can not be posted as refunds automatically." -msgstr "Las notas de crédito parciales no pueden contabilizarse como reembolsos automáticamente." +msgid "Partial credit note refund is not allowed." +msgstr "No se permite el reembolso de nota de crédito parcial." -msgctxt "model:ir.message,text:msg_missing_credit_note_sequence" -msgid "No active credit note NCF sequence was found for type \"%(ncf_type)s\" and company \"%(company)s\"." -msgstr "No se encontró una secuencia NCF activa de nota de crédito para el tipo \"%(ncf_type)s\" y la empresa \"%(company)s\"." +msgctxt "model:ir.sequence.strict,string:" +msgid "Sequence Strict" +msgstr "Secuencia estricta" -msgctxt "model:ir.message,text:msg_missing_debit_note_sequence" -msgid "No active debit note NCF sequence was found for type \"%(ncf_type)s\" and company \"%(company)s\"." -msgstr "No se encontró una secuencia NCF activa de nota de débito para el tipo \"%(ncf_type)s\" y la empresa \"%(company)s\"." +msgctxt "model:ir.sequence.type,name:sequence_type_out_credit_note_04" +msgid "Nota de Crédito" +msgstr "Nota de Crédito" -msgctxt "selection:account.invoice,revenue_type:" -msgid "01 - Ingresos por Operaciones (No Financieros)" -msgstr "01 - Ingresos por Operaciones (No Financieros)" +msgctxt "model:ir.sequence.type,name:sequence_type_out_credit_note_34" +msgid "Nota de Crédito Electrónica" +msgstr "Nota de Crédito Electrónica" -msgctxt "selection:account.invoice,revenue_type:" -msgid "02 - Ingresos Financieros" -msgstr "02 - Ingresos Financieros" +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_01" +msgid "Factura de Crédito Fiscal" +msgstr "Factura de Crédito Fiscal" -msgctxt "selection:account.invoice,revenue_type:" -msgid "03 - Ingresos Extraordinarios" -msgstr "03 - Ingresos Extraordinarios" +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_02" +msgid "Factura de Consumo" +msgstr "Factura de Consumo" -msgctxt "selection:account.invoice,revenue_type:" -msgid "04 - Ingresos por Arrendamientos" -msgstr "04 - Ingresos por Arrendamientos" +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_03" +msgid "Nota de Débito" +msgstr "Nota de Débito" -msgctxt "selection:account.invoice,revenue_type:" -msgid "05 - Ingresos por Venta de Activo Depreciable" -msgstr "05 - Ingresos por Venta de Activo Depreciable" +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_11" +msgid "Comprobante de Compras" +msgstr "Comprobante de Compras" -msgctxt "selection:account.invoice,revenue_type:" -msgid "06 - Otros Ingresos" -msgstr "06 - Otros Ingresos" +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_12" +msgid "Registro Único de Ingreso" +msgstr "Registro Único de Ingreso" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_13" +msgid "Comprobante para Gasto Menor" +msgstr "Comprobante para Gasto Menor" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_14" +msgid "Comprobante de Regímen Especial" +msgstr "Comprobante de Regímen Especial" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_15" +msgid "Comprobante Gubernamental" +msgstr "Comprobante Gubernamental" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_16" +msgid "Comprobante para exportaciones" +msgstr "Comprobante para exportaciones" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_17" +msgid "Comprobante para Pagos al Exterior" +msgstr "Comprobante para Pagos al Exterior" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_31" +msgid "Factura de Crédito Fiscal Electrónica" +msgstr "Factura de Crédito Fiscal Electrónica" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_32" +msgid "Factura de Consumo Electrónica" +msgstr "Factura de Consumo Electrónica" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_33" +msgid "Nota de Débito Electrónica" +msgstr "Nota de Débito Electrónica" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_41" +msgid "Compras Electrónico" +msgstr "Compras Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_43" +msgid "Gastos Menores Electrónico" +msgstr "Gastos Menores Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_44" +msgid "Regímenes Especiales Electrónico" +msgstr "Regímenes Especiales Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_45" +msgid "Gubernamental Electrónico" +msgstr "Gubernamental Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_46" +msgid "Exportación Electrónico" +msgstr "Exportación Electrónico" + +msgctxt "model:ir.sequence.type,name:sequence_type_out_invoice_47" +msgid "Pagos al Exterior Electrónico" +msgstr "Pagos al Exterior Electrónico" + +msgctxt "model:ir.ui.menu,name:main_menu_ncf_manager" +msgid "NCF Manager" +msgstr "Gestión de NCF" + +msgctxt "model:ir.ui.menu,name:menu_ncf_manager" +msgid "NCF Manager" +msgstr "Gestión de NCF" + +msgctxt "model:ir.ui.menu,name:menu_ncf_manager_form" +msgid "NCF Manager" +msgstr "Gestión de NCF" + +msgctxt "model:ir.ui.view,name:configuration_view_form" +msgid "configuration_form" +msgstr "configuration_form" + +msgctxt "model:ir.ui.view,name:invoice_view_form" +msgid "invoice_form" +msgstr "invoice_form" + +msgctxt "model:ir.ui.view,name:invoice_view_tree" +msgid "invoice_tree" +msgstr "invoice_tree" + +msgctxt "model:ir.ui.view,name:ncf_manager_sequences_view_form" +msgid "ncf_manager_sequences_form" +msgstr "ncf_manager_sequences_form" + +msgctxt "model:ir.ui.view,name:ncf_manager_sequences_view_tree" +msgid "ncf_manager_sequences_tree" +msgstr "ncf_manager_sequences_tree" + +msgctxt "model:ir.ui.view,name:ncf_manager_view_form" +msgid "ncf_manager_form" +msgstr "ncf_manager_form" + +msgctxt "model:ir.ui.view,name:ncf_manager_view_tree" +msgid "ncf_manager_tree" +msgstr "ncf_manager_tree" + +msgctxt "model:ir.ui.view,name:party_view_form" +msgid "party_form" +msgstr "party_form" + +msgctxt "model:ir.ui.view,name:sequence_view_form" +msgid "sequence_form" +msgstr "sequence_form" + +msgctxt "model:ir.ui.view,name:user_view_form" +msgid "user_form" +msgstr "user_form" + +msgctxt "model:ncf.manager,name:" +msgid "NCF Manager" +msgstr "Gestión de NCF" + +msgctxt "model:ncf.manager,string:" +msgid "NCF Manager" +msgstr "Gestor de NCF" + +msgctxt "model:ncf.manager.sequence,string:" +msgid "NCF Manager Sequences" +msgstr "Secuencias del gestor de NCF" + +msgctxt "model:party.party.ncf_type,string:" +msgid "Party Ncf Type" +msgstr "Tipo NCF de tercero" msgctxt "selection:account.invoice,expense_type:" msgid "01 - Gastos de Personal" @@ -565,7 +663,7 @@ msgstr "03 - Arrendamientos" msgctxt "selection:account.invoice,expense_type:" msgid "04 - Gastos de Activos Fijo" -msgstr "04 - Gastos de Activos Fijo" +msgstr "04 - Gastos de Activos Fijos" msgctxt "selection:account.invoice,expense_type:" msgid "05 - Gastos de Representación" @@ -595,34 +693,6 @@ msgctxt "selection:account.invoice,expense_type:" msgid "11 - Gastos de Seguros" msgstr "11 - Gastos de Seguros" -msgctxt "selection:account.invoice,payment_method:" -msgid "01 - Efectivo" -msgstr "01 - Efectivo" - -msgctxt "selection:account.invoice,payment_method:" -msgid "02 - Cheques/Transferencias/Depósito" -msgstr "02 - Cheques/Transferencias/Depósito" - -msgctxt "selection:account.invoice,payment_method:" -msgid "03 - Tarjeta Crédito/Débito" -msgstr "03 - Tarjeta Crédito/Débito" - -msgctxt "selection:account.invoice,payment_method:" -msgid "04 - Compra a Crédito" -msgstr "04 - Compra a Crédito" - -msgctxt "selection:account.invoice,payment_method:" -msgid "05 - Permuta" -msgstr "05 - Permuta" - -msgctxt "selection:account.invoice,payment_method:" -msgid "06 - Nota de Crédito" -msgstr "06 - Nota de Crédito" - -msgctxt "selection:account.invoice,payment_method:" -msgid "07 - Mixto" -msgstr "07 - Mixto" - msgctxt "selection:account.invoice,isr_withholding_type:" msgid "01 - Alquileres" msgstr "01 - Alquileres" @@ -654,3 +724,503 @@ msgstr "07 - Retención por Proveedores del Estado" msgctxt "selection:account.invoice,isr_withholding_type:" msgid "08 - Juegos Telefónicos" msgstr "08 - Juegos Telefónicos" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "01 Deterioro de Factura Pre-Impresa" +msgstr "01 Deterioro de Factura Pre-Impresa" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "02 Errores de Impresión (Factura Pre-Impresa)" +msgstr "02 Errores de Impresión (Factura Pre-Impresa)" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "03 Impresión Defectuosa" +msgstr "03 Impresión Defectuosa" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "04 Corrección de la Información" +msgstr "04 Corrección de la Información" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "05 Cambio de Productos" +msgstr "05 Cambio de Productos" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "06 Devolución de Productos" +msgstr "06 Devolución de Productos" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "07 Omisión de Productos" +msgstr "07 Omisión de Productos" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "08 Errores en Secuencias de NCF" +msgstr "08 Errores en Secuencias de NCF" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "09 Por Cese de Operaciones" +msgstr "09 Por Cese de Operaciones" + +msgctxt "selection:account.invoice,ncf_cancellation_type:" +msgid "10 Pérdida O Hurto De Talonario(S)" +msgstr "10 Pérdida O Hurto De Talonario(S)" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Compras Electrónico" +msgstr "Compras Electrónico" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Comprobante Gubernamental" +msgstr "Comprobante Gubernamental" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Comprobante de Compras" +msgstr "Comprobante de Compras" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Comprobante de Regímenes Especiales" +msgstr "Comprobante de Regímenes Especiales" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Comprobante para Gastos Menores" +msgstr "Comprobante para Gastos Menores" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Comprobante para Pagos al Exterior" +msgstr "Comprobante para Pagos al Exterior" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Comprobante para exportaciones" +msgstr "Comprobante para exportaciones" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Credit Note" +msgstr "Nota de Crédito" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Debit Note" +msgstr "Nota de Débito" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Exportación Electrónico" +msgstr "Exportación Electrónico" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Factura de Consumo" +msgstr "Factura de Consumo" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Factura de Consumo Electrónica" +msgstr "Factura de Consumo Electrónica" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Factura de Crédito Fiscal" +msgstr "Factura de Crédito Fiscal" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Factura de Crédito Fiscal Electrónica" +msgstr "Factura de Crédito Fiscal Electrónica" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Factura sin NCF" +msgstr "Factura sin NCF" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Gastos Menores Electrónico" +msgstr "Gastos Menores Electrónico" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Government" +msgstr "Gubernamental" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Gubernamental Electrónico" +msgstr "Gubernamental Electrónico" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Income Single Registry" +msgstr "Registro Único de Ingresos" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Informal Provider Registry" +msgstr "Registro de Proveedor Informal" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Invoice for Final Consumer" +msgstr "Factura para consumidor Final" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Minor Expense Registry" +msgstr "Registro de Gastos Menores" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Nota de Crédito" +msgstr "Nota de Crédito" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Nota de Crédito Electrónica" +msgstr "Nota de Crédito Electrónica" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Nota de Débito" +msgstr "Nota de Débito" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Nota de Débito Electrónica" +msgstr "Nota de Débito Electrónica" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Pagos al Exterior Electrónico" +msgstr "Pagos al Exterior Electrónico" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Registro Único de Ingresos" +msgstr "Registro Único de Ingresos" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Regímenes Especiales Electrónico" +msgstr "Regímenes Especiales Electrónico" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Special Regime of Taxation" +msgstr "Régimen Especial de Tributación" + +msgctxt "selection:account.invoice,ncf_type:" +msgid "Valid Invoice for Tax Credit" +msgstr "Factura Válida para Crédito Fiscal" + +msgctxt "selection:account.invoice,payment_method:" +msgid "01 - Efectivo" +msgstr "01 - Efectivo" + +msgctxt "selection:account.invoice,payment_method:" +msgid "02 - Cheques/Transferencias/Depósito" +msgstr "02 - Cheques/Transferencias/Depósito" + +msgctxt "selection:account.invoice,payment_method:" +msgid "03 - Tarjeta Crédito/Débito" +msgstr "03 - Tarjeta Crédito/Débito" + +msgctxt "selection:account.invoice,payment_method:" +msgid "04 - Compra a Crédito" +msgstr "04 - Compra a Crédito" + +msgctxt "selection:account.invoice,payment_method:" +msgid "05 - Permuta" +msgstr "05 - Permuta" + +msgctxt "selection:account.invoice,payment_method:" +msgid "06 - Nota de Crédito" +msgstr "06 - Nota de Crédito" + +msgctxt "selection:account.invoice,payment_method:" +msgid "07 - Mixto" +msgstr "07 - Mixto" + +msgctxt "selection:account.invoice,revenue_type:" +msgid "01 - Ingresos por Operaciones (No Financieros)" +msgstr "01 - Ingresos por Operaciones (No Financieros)" + +msgctxt "selection:account.invoice,revenue_type:" +msgid "02 - Ingresos Financieros" +msgstr "02 - Ingresos Financieros" + +msgctxt "selection:account.invoice,revenue_type:" +msgid "03 - Ingresos Extraordinarios" +msgstr "03 - Ingresos Extraordinarios" + +msgctxt "selection:account.invoice,revenue_type:" +msgid "04 - Ingresos por Arrendamientos" +msgstr "04 - Ingresos por Arrendamientos" + +msgctxt "selection:account.invoice,revenue_type:" +msgid "05 - Ingresos por Venta de Activo Depreciable" +msgstr "05 - Ingresos por Venta de Activo Depreciable" + +msgctxt "selection:account.invoice,revenue_type:" +msgid "06 - Otros Ingresos" +msgstr "06 - Otros Ingresos" + +msgctxt "selection:ncf.manager,state:" +msgid "Active" +msgstr "Activa" + +msgctxt "selection:ncf.manager,state:" +msgid "Draft" +msgstr "Borrador" + +msgctxt "selection:ncf.manager,state:" +msgid "Finished" +msgstr "Terminada" + +msgctxt "selection:ncf.manager,state:active" +msgid "Active" +msgstr "Activo" + +msgctxt "selection:ncf.manager,state:draft" +msgid "Draft" +msgstr "Borrador" + +msgctxt "selection:ncf.manager,state:finished" +msgid "Finished" +msgstr "Finalizado" + +msgctxt "selection:ncf.manager.sequence,invoice_type:" +msgid "Customer Invoice" +msgstr "Factura de Cliente" + +msgctxt "selection:ncf.manager.sequence,invoice_type:" +msgid "Supplier Invoice" +msgstr "Factura de Proveedor" + +msgctxt "selection:ncf.manager.sequence,invoice_type:invoice_customer" +msgid "Customer Invoice" +msgstr "Factura de cliente" + +msgctxt "selection:ncf.manager.sequence,invoice_type:invoice_supplier" +msgid "Supplier Invoice" +msgstr "Factura de proveedor" + +msgctxt "selection:ncf.manager.sequence,state:" +msgid "Active" +msgstr "Activa" + +msgctxt "selection:ncf.manager.sequence,state:" +msgid "Draft" +msgstr "Borrador" + +msgctxt "selection:ncf.manager.sequence,state:" +msgid "Finished" +msgstr "Terminada" + +msgctxt "selection:ncf.manager.sequence,state:active" +msgid "Active" +msgstr "Activo" + +msgctxt "selection:ncf.manager.sequence,state:draft" +msgid "Draft" +msgstr "Borrador" + +msgctxt "selection:ncf.manager.sequence,state:finished" +msgid "Finished" +msgstr "Finalizado" + +msgctxt "view:account.fiscalyear:" +msgid "NCF Sequences" +msgstr "Secuencias de NCF" + +msgctxt "view:account.invoice:" +msgid "Expense" +msgstr "Gasto" + +msgctxt "view:account.invoice:" +msgid "Method of Payment" +msgstr "Forma de pago" + +msgctxt "view:account.invoice:" +msgid "NCF Cancellation" +msgstr "Anulación NCF" + +msgctxt "view:account.invoice:" +msgid "Revenue" +msgstr "Ingreso" + +msgctxt "view:account.invoice:" +msgid "Tax Information" +msgstr "Información Fiscal" + +msgctxt "field:ncf.manager,activated_by:" +msgid "Activated By" +msgstr "Activada por" + +msgctxt "field:ncf.manager,activated_at:" +msgid "Activated At" +msgstr "Fecha de activación" + +msgctxt "field:ncf.manager,finished_by:" +msgid "Finished By" +msgstr "Finalizada por" + +msgctxt "field:ncf.manager,finished_at:" +msgid "Finished At" +msgstr "Fecha de finalización" + +msgctxt "field:ncf.manager.sequence,sequence_mode:" +msgid "Sequence Configuration" +msgstr "Configuración de secuencia" + +msgctxt "field:ncf.manager.sequence,ncf_sequences:" +msgid "Fiscal Sequence" +msgstr "Secuencia fiscal" + +msgctxt "field:ncf.manager.sequence,expected_prefix:" +msgid "Expected Prefix" +msgstr "Prefijo esperado" + +msgctxt "field:ncf.manager.sequence,expected_padding:" +msgid "Expected Padding" +msgstr "Longitud del consecutivo" + +msgctxt "field:ncf.manager.sequence,from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,effective_from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,effective_until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,effective_number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,effective_expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,tree_from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,tree_until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,tree_number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,tree_expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,availability:" +msgid "Availability" +msgstr "Disponibilidad" + +msgctxt "selection:ncf.manager.sequence,sequence_mode:existing" +msgid "Select Existing Sequence" +msgstr "Seleccionar secuencia existente" + +msgctxt "selection:ncf.manager.sequence,sequence_mode:create" +msgid "Create Sequence on Activation" +msgstr "Crear secuencia al activar" + +msgctxt "selection:ncf.manager.sequence,availability:available" +msgid "Available" +msgstr "Disponible" + +msgctxt "selection:ncf.manager.sequence,availability:low" +msgid "Running Low" +msgstr "Próxima a agotarse" + +msgctxt "selection:ncf.manager.sequence,availability:expired" +msgid "Expired" +msgstr "Vencida" + +msgctxt "selection:ncf.manager.sequence,availability:exhausted" +msgid "Exhausted" +msgstr "Agotada" + +msgctxt "model:ir.model.button,string:ncf_manager_activate_button" +msgid "Activate" +msgstr "Activar" + +msgctxt "model:ir.model.button,string:ncf_manager_finish_button" +msgid "Finish" +msgstr "Finalizar" + +msgctxt "model:ir.model.button,string:ncf_sequence_finish_button" +msgid "Finish Sequence" +msgstr "Finalizar secuencia" + +msgctxt "view:ncf.manager:" +msgid "Authorized Fiscal Sequences" +msgstr "Secuencias fiscales autorizadas" + +msgctxt "field:ncf.import.start,company:" +msgid "Company" +msgstr "Empresa" + +msgctxt "field:ncf.import.start,file_:" +msgid "DGII File" +msgstr "Archivo de la DGII" + +msgctxt "field:ncf.import.start,filename:" +msgid "Filename" +msgstr "Nombre del archivo" + +msgctxt "field:ncf.import.start,activate:" +msgid "Activate Imported Authorization" +msgstr "Activar autorización importada" + +msgctxt "field:ncf.manager,source_filename:" +msgid "Source Filename" +msgstr "Nombre del archivo fuente" + +msgctxt "field:ncf.manager,source_hash:" +msgid "Source SHA-256" +msgstr "SHA-256 del archivo fuente" + +msgctxt "field:ncf.manager,source_file:" +msgid "DGII Source File" +msgstr "Archivo fuente de la DGII" + +msgctxt "field:ncf.manager,imported_by:" +msgid "Imported By" +msgstr "Importado por" + +msgctxt "field:ncf.manager,imported_at:" +msgid "Imported At" +msgstr "Fecha de importación" + +msgctxt "field:ncf.manager.sequence,auth_number:" +msgid "Authorization Number" +msgstr "Número de autorización" + +msgctxt "field:ncf.manager.sequence,authorization_date:" +msgid "Authorization Date" +msgstr "Fecha de autorización" + +msgctxt "field:ncf.manager.sequence,dgii_status:" +msgid "DGII Status" +msgstr "Estado en DGII" + +msgctxt "field:ncf.manager.sequence,requested_quantity:" +msgid "Requested Quantity" +msgstr "Cantidad solicitada" + +msgctxt "field:ncf.manager.sequence,approved_quantity:" +msgid "Approved Quantity" +msgstr "Cantidad aprobada" + +msgctxt "field:ncf.manager.sequence,usage_type:" +msgid "Usage Type" +msgstr "Tipo de uso" + +msgctxt "field:ncf.manager.sequence,dgii_detail:" +msgid "DGII Detail" +msgstr "Detalle de la DGII" + +msgctxt "model:ir.action,name:act_ncf_import" +msgid "Import DGII Authorization" +msgstr "Importar autorización de la DGII" + +msgctxt "model:ir.ui.menu,name:menu_ncf_import" +msgid "Import DGII Authorization" +msgstr "Importar autorización de la DGII" diff --git a/locale/es_DO.po b/locale/es_DO.po new file mode 100644 index 0000000..14c4f81 --- /dev/null +++ b/locale/es_DO.po @@ -0,0 +1,198 @@ +msgid "" +msgstr "" +"Project-Id-Version: ncf_manager 8.0\n" +"PO-Revision-Date: 2026-08-16 00:00-0400\n" +"Last-Translator: Fundación Un País Mejor\n" +"Language-Team: Spanish (Dominican Republic)\n" +"Language: es_DO\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" + +msgctxt "field:ncf.manager.sequence,sequence_mode:" +msgid "Sequence Configuration" +msgstr "Configuración de secuencia" + +msgctxt "field:ncf.manager.sequence,ncf_sequences:" +msgid "Fiscal Sequence" +msgstr "Secuencia fiscal" + +msgctxt "field:ncf.manager.sequence,expected_prefix:" +msgid "Expected Prefix" +msgstr "Prefijo esperado" + +msgctxt "field:ncf.manager.sequence,expected_padding:" +msgid "Expected Padding" +msgstr "Longitud del consecutivo" + +msgctxt "field:ncf.manager.sequence,from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,effective_from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,effective_until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,effective_number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,effective_expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,tree_from_number:" +msgid "Authorized From" +msgstr "Desde autorizado" + +msgctxt "field:ncf.manager.sequence,tree_until_number:" +msgid "Authorized Until" +msgstr "Hasta autorizado" + +msgctxt "field:ncf.manager.sequence,tree_number_next:" +msgid "Next Number to Issue" +msgstr "Siguiente número por emitir" + +msgctxt "field:ncf.manager.sequence,tree_expiration_date:" +msgid "Expiration Date" +msgstr "Fecha de vencimiento" + +msgctxt "field:ncf.manager.sequence,availability:" +msgid "Availability" +msgstr "Disponibilidad" + +msgctxt "selection:ncf.manager.sequence,sequence_mode:existing" +msgid "Select Existing Sequence" +msgstr "Seleccionar secuencia existente" + +msgctxt "selection:ncf.manager.sequence,sequence_mode:create" +msgid "Create Sequence on Activation" +msgstr "Crear secuencia al activar" + +msgctxt "selection:ncf.manager.sequence,availability:available" +msgid "Available" +msgstr "Disponible" + +msgctxt "selection:ncf.manager.sequence,availability:low" +msgid "Running Low" +msgstr "Próxima a agotarse" + +msgctxt "selection:ncf.manager.sequence,availability:expired" +msgid "Expired" +msgstr "Vencida" + +msgctxt "selection:ncf.manager.sequence,availability:exhausted" +msgid "Exhausted" +msgstr "Agotada" + +msgctxt "model:ir.model.button,string:ncf_manager_activate_button" +msgid "Activate" +msgstr "Activar" + +msgctxt "model:ir.model.button,string:ncf_manager_finish_button" +msgid "Finish" +msgstr "Finalizar" + +msgctxt "model:ir.model.button,string:ncf_sequence_finish_button" +msgid "Finish Sequence" +msgstr "Finalizar secuencia" + +msgctxt "view:ncf.manager:" +msgid "Authorized Fiscal Sequences" +msgstr "Secuencias fiscales autorizadas" + +msgctxt "field:ncf.import.start,company:" +msgid "Company" +msgstr "Empresa" + +msgctxt "field:ncf.import.start,file_:" +msgid "DGII File" +msgstr "Archivo de la DGII" + +msgctxt "field:ncf.import.start,filename:" +msgid "Filename" +msgstr "Nombre del archivo" + +msgctxt "field:ncf.import.start,activate:" +msgid "Activate Imported Authorization" +msgstr "Activar autorización importada" + +msgctxt "field:ncf.manager,source_filename:" +msgid "Source Filename" +msgstr "Nombre del archivo fuente" + +msgctxt "field:ncf.manager,source_hash:" +msgid "Source SHA-256" +msgstr "SHA-256 del archivo fuente" + +msgctxt "field:ncf.manager,source_file:" +msgid "DGII Source File" +msgstr "Archivo fuente de la DGII" + +msgctxt "field:ncf.manager,imported_by:" +msgid "Imported By" +msgstr "Importado por" + +msgctxt "field:ncf.manager,imported_at:" +msgid "Imported At" +msgstr "Fecha de importación" + +msgctxt "field:ncf.manager.sequence,auth_number:" +msgid "Authorization Number" +msgstr "Número de autorización" + +msgctxt "field:ncf.manager.sequence,authorization_date:" +msgid "Authorization Date" +msgstr "Fecha de autorización" + +msgctxt "field:ncf.manager.sequence,dgii_status:" +msgid "DGII Status" +msgstr "Estado en DGII" + +msgctxt "field:ncf.manager.sequence,requested_quantity:" +msgid "Requested Quantity" +msgstr "Cantidad solicitada" + +msgctxt "field:ncf.manager.sequence,approved_quantity:" +msgid "Approved Quantity" +msgstr "Cantidad aprobada" + +msgctxt "field:ncf.manager.sequence,usage_type:" +msgid "Usage Type" +msgstr "Tipo de uso" + +msgctxt "field:ncf.manager.sequence,dgii_detail:" +msgid "DGII Detail" +msgstr "Detalle de la DGII" + +msgctxt "model:ir.action,name:act_ncf_import" +msgid "Import DGII Authorization" +msgstr "Importar autorización de la DGII" + +msgctxt "model:ir.ui.menu,name:menu_ncf_import" +msgid "Import DGII Authorization" +msgstr "Importar autorización de la DGII" + +msgctxt "wizard_button:ncf.import,start,import_:" +msgid "Import" +msgstr "Importar" + +msgctxt "wizard_button:ncf.import,start,end:" +msgid "Cancel" +msgstr "Cancelar" diff --git a/message.xml b/message.xml index d535b2f..9b625b6 100644 --- a/message.xml +++ b/message.xml @@ -69,35 +69,134 @@ this repository contains the full copyright notices and license terms. --> This sequence is expired. - - No active NCF sequence was found for this invoice. - - - The selected NCF sequence does not match the invoice type. - - - The selected NCF sequence does not match the NCF type. - - - The selected NCF sequence is inactive. - - - The selected NCF manager is inactive. - - This sequence has no available numbers. + The NCF sequence is exhausted. No more numbers are available. + + + No active NCF sequence available for invoice "%(invoice)s". - The selected NCF configuration has no strict sequence assigned. - - - Partial credit notes can not be posted as refunds automatically. + No strict sequence configured in the selected NCF sequence for invoice "%(invoice)s". - No active credit note NCF sequence was found for type "%(ncf_type)s" and company "%(company)s". + No active credit note sequence available for type "%(ncf_type)s" in company "%(company)s". - No active debit note NCF sequence was found for type "%(ncf_type)s" and company "%(company)s". + No active debit note sequence available for type "%(ncf_type)s" in company "%(company)s". + + + You must select a DGII cancellation type before cancelling fiscal invoice "%(invoice)s". + + + You must enter a DGII cancellation reason before cancelling fiscal invoice "%(invoice)s". + + + The NCF sequence selected for invoice "%(invoice)s" is inactive. + + + The NCF Manager (point of sale) for invoice "%(invoice)s" is inactive. + + + The NCF sequence invoice type does not match invoice "%(invoice)s". + + + The NCF type on the sequence does not match the NCF type selected on invoice "%(invoice)s". + + + Partial credit note refund is not allowed. + + + The fiscal number "%(number)s" must have the DGII B + 10 digits or E + 12 digits structure. + + + The fiscal number "%(number)s" does not match the expected prefix "%(prefix)s". + + + The fiscal sequence and its authorization must belong to the same company. + + + The fiscal sequence must use prefix "%(prefix)s" for the selected NCF type. + + + The fiscal sequence must use a padding of %(padding)s digits. + + + The authorized fiscal range must start at 1 or greater and end at or after its start. + + + The next fiscal number cannot be before the authorized range. + + + Add at least one fiscal sequence before activating the authorization. + + + Application and authorization numbers are required before activation. + + + This authorization cannot be deleted because one of its fiscal sequences has been used on an invoice. + + + This fiscal sequence cannot be deleted because it has been used on an invoice. + + + The selected sequence type does not correspond to the selected NCF type. + + + The “Invoice without NCF” classification does not create a fiscal sequence. + + + Starting, ending and first issue numbers are required to create the fiscal sequence. + + + The authorized range overlaps an active range for the same company and NCF type. + + + The fiscal sequence is already assigned to another authorization line. + + + Only draft fiscal sequence lines can be deleted. + + + Only draft fiscal authorizations can be deleted. + + + Every fiscal sequence line requires its DGII authorization number. + + + The DGII file could not be read: %(error)s. + + + The file does not contain the required DGII authorization columns. + + + DGII authorization "%(authorization)s" is not approved and cannot be imported. + + + DGII NCF type "%(type)s" is not supported. + + + DGII authorization "%(authorization)s" has an invalid fiscal range or prefix. + + + The approved quantity for DGII authorization "%(authorization)s" does not match its range. + + + The DGII file belongs to "%(company)s", which does not match the selected company. + + + DGII authorization "%(authorization)s" already exists with different fiscal data. + + + DGII request "%(request)s" is no longer in draft and cannot receive another imported authorization. + + + DGII authorization number "%(authorization)s" is already registered for this company. + + + The DGII import file is empty or exceeds the 5 MB safety limit. + + + DGII authorization "%(authorization)s" does not contain the required request and authorization dates. diff --git a/ncf_manager.py b/ncf_manager.py index d0a4d55..fa74e8e 100644 --- a/ncf_manager.py +++ b/ncf_manager.py @@ -1,8 +1,14 @@ -# This file is part of ncf_manager module for Tryton. The COPYRIGHT file at the top level of -# this repository contains the full copyright notices and license terms. -from trytond.model import ModelView, ModelSQL, fields +import datetime + +# This file is part of ncf_manager module for Tryton. The COPYRIGHT file at +# the top level of this repository contains the full copyright notices and +# license terms. +from trytond.exceptions import UserError +from trytond.i18n import gettext + +from trytond.model import ModelView, ModelSQL, Workflow, fields, Unique from trytond.pool import Pool -from trytond.pyson import Eval, Id +from trytond.pyson import Eval, If from trytond.transaction import Transaction @@ -32,8 +38,48 @@ NCF_TYPE = [ ('99', 'Factura sin NCF'), ] +ELECTRONIC_NCF_TYPES = frozenset({ + '31', '32', '33', '34', '41', '43', '44', '45', '46', '47'}) -class NCFManager(ModelSQL, ModelView): +NCF_SEQUENCE_TYPE_IDS = { + '1': 'sequence_type_out_invoice_01', + '2': 'sequence_type_out_invoice_02', + '3': 'sequence_type_out_invoice_03', + '4': 'sequence_type_out_credit_note_04', + '11': 'sequence_type_out_invoice_11', + '12': 'sequence_type_out_invoice_12', + '13': 'sequence_type_out_invoice_13', + '14': 'sequence_type_out_invoice_14', + '15': 'sequence_type_out_invoice_15', + '16': 'sequence_type_out_invoice_16', + '17': 'sequence_type_out_invoice_17', + '31': 'sequence_type_out_invoice_31', + '32': 'sequence_type_out_invoice_32', + '33': 'sequence_type_out_invoice_33', + '34': 'sequence_type_out_credit_note_34', + '41': 'sequence_type_out_invoice_41', + '43': 'sequence_type_out_invoice_43', + '44': 'sequence_type_out_invoice_44', + '45': 'sequence_type_out_invoice_45', + '46': 'sequence_type_out_invoice_46', + '47': 'sequence_type_out_invoice_47', +} + + +def ncf_prefix(ncf_type): + if not ncf_type or ncf_type == '99': + return None + series = 'E' if ncf_type in ELECTRONIC_NCF_TYPES else 'B' + return f'{series}{ncf_type.zfill(2)}' + + +def ncf_padding(ncf_type): + if not ncf_type or ncf_type == '99': + return 0 + return 10 if ncf_type in ELECTRONIC_NCF_TYPES else 8 + + +class NCFManager(Workflow, ModelSQL, ModelView): 'NCF Manager' __name__ = 'ncf.manager' @@ -53,9 +99,16 @@ class NCFManager(ModelSQL, ModelView): app_number = fields.Char('Application Number', required=True, size=10, states=_states, depends=_depends) - auth_number = fields.Char('Authorization Number', required=True, size=10, + auth_number = fields.Char('Legacy Authorization Number', size=10, states=_states, depends=_depends) + source_filename = fields.Char('Source Filename', readonly=True) + source_hash = fields.Char('Source SHA-256', readonly=True) + source_file = fields.Binary( + 'DGII Source File', filename='source_filename', readonly=True) + imported_by = fields.Many2One('res.user', 'Imported By', readonly=True) + imported_at = fields.DateTime('Imported At', readonly=True) + ncf_sequences = fields.One2Many('ncf.manager.sequence', 'pos', 'NCF Sequences', context={'company': Eval('company', -1)}, states=_states, depends=_depends) @@ -64,10 +117,17 @@ class NCFManager(ModelSQL, ModelView): ('draft', 'Draft'), ('active', 'Active'), ('finished', 'Finished'), - ], "State", sort=False) + ], "State", readonly=True, required=True, sort=False) state_string = state.translated('state') + activated_by = fields.Many2One( + 'res.user', 'Activated By', readonly=True) + activated_at = fields.DateTime('Activated At', readonly=True) + finished_by = fields.Many2One( + 'res.user', 'Finished By', readonly=True) + finished_at = fields.DateTime('Finished At', readonly=True) + del _states, _depends @classmethod @@ -75,7 +135,30 @@ class NCFManager(ModelSQL, ModelView): super(NCFManager, cls).__setup__() cls._order = [ ('app_date', 'DESC'), + ('id', 'DESC'), ] + cls._transitions |= { + ('draft', 'active'), + ('active', 'finished'), + } + cls._buttons.update({ + 'activate': { + 'invisible': Eval('state') != 'draft', + 'depends': ['state'], + }, + 'finish': { + 'invisible': Eval('state') != 'active', + 'depends': ['state'], + }, + }) + + def get_rec_name(self, name): + parts = [] + if self.company: + parts.append(self.company.rec_name) + if self.app_number: + parts.append(self.app_number) + return ' - '.join(parts) if parts else str(self.id) @staticmethod def default_company(): @@ -85,8 +168,91 @@ class NCFManager(ModelSQL, ModelView): def default_state(): return 'draft' + @classmethod + @ModelView.button + @Workflow.transition('active') + def activate(cls, managers): + Line = Pool().get('ncf.manager.sequence') + now = datetime.datetime.now() + user = Transaction().user + lines = [] + for manager in managers: + if not manager.ncf_sequences: + raise UserError(gettext( + 'ncf_manager.msg_ncf_manager_without_sequences')) + manager._validate_authorization() + for line in manager.ncf_sequences: + line.prepare_sequence() + line._validate_fiscal_sequence() + line._validate_no_overlap() + lines.append(line) + if lines: + Line.save(lines) + Line.activate(lines) + cls.write(managers, { + 'activated_by': user, + 'activated_at': now, + }) -class NCFManagerSequences(ModelSQL, ModelView): + def _validate_authorization(self): + if not self.app_number.strip(): + raise UserError(gettext( + 'ncf_manager.msg_ncf_missing_authorization')) + for line in self.ncf_sequences: + if not line.auth_number: + if self.auth_number: + line.auth_number = self.auth_number + else: + raise UserError(gettext( + 'ncf_manager.msg_ncf_line_missing_authorization')) + + @classmethod + @ModelView.button + @Workflow.transition('finished') + def finish(cls, managers): + Line = Pool().get('ncf.manager.sequence') + lines = [line for manager in managers + for line in manager.ncf_sequences if line.state == 'active'] + if lines: + Line.complete(lines) + cls.write(managers, { + 'finished_by': Transaction().user, + 'finished_at': datetime.datetime.now(), + }) + + @classmethod + def delete(cls, managers): + if any(manager.state != 'draft' for manager in managers): + raise UserError(gettext( + 'ncf_manager.msg_ncf_authorization_delete_not_draft')) + Invoice = Pool().get('account.invoice') + if Invoice.search([ + ('ncf_sequence.pos', 'in', [m.id for m in managers]), + ], limit=1): + raise UserError(gettext( + 'ncf_manager.msg_ncf_authorization_used')) + super().delete(managers) + + @classmethod + def copy(cls, managers, default=None): + default = dict(default or {}) + default.update({ + 'state': 'draft', + 'ncf_sequences': None, + 'activated_by': None, + 'activated_at': None, + 'finished_by': None, + 'finished_at': None, + 'source_filename': None, + 'source_hash': None, + 'source_file': None, + 'imported_by': None, + 'imported_at': None, + }) + return super().copy(managers, default=default) + + +class NCFManagerSequences(Workflow, ModelSQL, ModelView): 'NCF Manager Sequences' __name__ = 'ncf.manager.sequence' @@ -107,11 +273,110 @@ class NCFManagerSequences(ModelSQL, ModelView): ncf_type_string = ncf_type.translated('ncf_type') - ncf_sequences = fields.Many2One('ir.sequence.strict', 'NCF Sequences', - domain=[ - ('company', '=', Eval( - 'context', {}).get('company', -1)), - ], states=_states, depends=_depends) + auth_number = fields.Char( + 'Authorization Number', size=10, states=_states, depends=_depends) + authorization_date = fields.DateTime( + 'Authorization Date', states=_states, depends=_depends) + dgii_status = fields.Char('DGII Status', readonly=True) + requested_quantity = fields.Integer('Requested Quantity', readonly=True) + approved_quantity = fields.Integer('Approved Quantity', readonly=True) + usage_type = fields.Char('Usage Type', readonly=True) + dgii_detail = fields.Text('DGII Detail', readonly=True) + import_fingerprint = fields.Char('Import Fingerprint', readonly=True) + source_filename = fields.Char('Source Filename', readonly=True) + source_hash = fields.Char('Source SHA-256', readonly=True) + source_file = fields.Binary( + 'DGII Source File', filename='source_filename', readonly=True) + imported_by = fields.Many2One('res.user', 'Imported By', readonly=True) + imported_at = fields.DateTime('Imported At', readonly=True) + + company = fields.Function( + fields.Many2One('company.company', 'Company'), + 'on_change_with_company') + + expected_prefix = fields.Function( + fields.Char('Expected Prefix'), 'on_change_with_expected_prefix') + expected_padding = fields.Function( + fields.Integer('Expected Padding'), + 'on_change_with_expected_padding') + + sequence_mode = fields.Selection([ + ('existing', 'Select Existing Sequence'), + ('create', 'Create Sequence on Activation'), + ], 'Sequence Configuration', required=True, states=_states, + depends=_depends, sort=False) + + ncf_sequences = fields.Many2One('ir.sequence.strict', 'Fiscal Sequence', + domain=[ + ('company', '=', Eval('company', -1)), + If(Eval('state') == 'draft', + ('prefix', '=', Eval('expected_prefix')), + ()), + ('active', '=', True), + ], + states={ + **_states, + 'required': Eval('sequence_mode') == 'existing', + 'invisible': Eval('sequence_mode') == 'create', + }, + depends=_depends + [ + 'company', + 'sequence_mode', 'expected_prefix', 'expected_padding']) + + from_number = fields.Integer( + 'Authorized From', states={ + **_states, + 'required': Eval('sequence_mode') == 'create', + 'invisible': Eval('sequence_mode') != 'create', + }, depends=_depends + ['sequence_mode']) + until_number = fields.Integer( + 'Authorized Until', states={ + **_states, + 'required': Eval('sequence_mode') == 'create', + 'invisible': Eval('sequence_mode') != 'create', + }, depends=_depends + ['sequence_mode']) + number_next = fields.Integer( + 'Next Number to Issue', states={ + **_states, + 'required': Eval('sequence_mode') == 'create', + 'invisible': Eval('sequence_mode') != 'create', + }, depends=_depends + ['sequence_mode']) + expiration_date = fields.Date( + 'Expiration Date', states={ + **_states, + 'invisible': Eval('sequence_mode') != 'create', + }, depends=_depends + ['sequence_mode']) + + effective_from_number = fields.Function( + fields.Integer('Authorized From', states={ + 'invisible': Eval('sequence_mode') == 'create', + }), 'get_effective_sequence_values') + effective_until_number = fields.Function( + fields.Integer('Authorized Until', states={ + 'invisible': Eval('sequence_mode') == 'create', + }), 'get_effective_sequence_values') + effective_number_next = fields.Function( + fields.Integer('Next Number to Issue', states={ + 'invisible': Eval('sequence_mode') == 'create', + }), + 'get_effective_sequence_values') + effective_expiration_date = fields.Function( + fields.Date('Expiration Date', states={ + 'invisible': Eval('sequence_mode') == 'create', + }), 'get_effective_sequence_values') + + # Tree-specific values must remain visible for both assisted draft lines + # and lines backed by an activated strict sequence. The effective fields + # above retain their form-only visibility rules. + tree_from_number = fields.Function( + fields.Integer('Authorized From'), 'get_effective_sequence_values') + tree_until_number = fields.Function( + fields.Integer('Authorized Until'), 'get_effective_sequence_values') + tree_number_next = fields.Function( + fields.Integer('Next Number to Issue'), + 'get_effective_sequence_values') + tree_expiration_date = fields.Function( + fields.Date('Expiration Date'), 'get_effective_sequence_values') invoice_type = fields.Selection([ ('invoice_customer', 'Customer Invoice'), @@ -123,17 +388,266 @@ class NCFManagerSequences(ModelSQL, ModelView): ('draft', 'Draft'), ('active', 'Active'), ('finished', 'Finished'), - ], "State", sort=False) + ], "State", readonly=True, required=True, sort=False) state_string = state.translated('state') + availability = fields.Function(fields.Selection([ + ('available', 'Available'), + ('low', 'Running Low'), + ('expired', 'Expired'), + ('exhausted', 'Exhausted'), + ], 'Availability', sort=False), 'get_availability') + availability_string = availability.translated('availability') + finished_by = fields.Many2One( + 'res.user', 'Finished By', readonly=True) + finished_at = fields.DateTime('Finished At', readonly=True) + del _states, _depends @staticmethod def default_state(): return 'draft' + @staticmethod + def default_sequence_mode(): + return 'existing' + + @fields.depends('pos', '_parent_pos.company') + def on_change_with_company(self, name=None): + return self.pos.company.id if self.pos and self.pos.company else None + + @fields.depends('ncf_type') + def on_change_with_expected_prefix(self, name=None): + return ncf_prefix(self.ncf_type) + + @fields.depends('ncf_type') + def on_change_with_expected_padding(self, name=None): + return ncf_padding(self.ncf_type) + + @fields.depends( + 'sequence_mode', 'ncf_type', 'ncf_sequences', + 'from_number', 'until_number', 'number_next', 'expiration_date') + def on_change_ncf_type(self): + if (self.ncf_sequences + and self.ncf_sequences.prefix != ncf_prefix(self.ncf_type)): + self.ncf_sequences = None + + @fields.depends( + 'ncf_sequences', 'from_number', 'until_number', 'number_next', + 'expiration_date') + def on_change_ncf_sequences(self): + if not self.ncf_sequences: + return + self.from_number = self.ncf_sequences.from_number + self.until_number = self.ncf_sequences.until_number + self.number_next = self.ncf_sequences.number_next + self.expiration_date = self.ncf_sequences.expiration_date + + @classmethod + def get_effective_sequence_values(cls, records, names): + values = {name: {} for name in names} + mapping = { + 'effective_from_number': 'from_number', + 'effective_until_number': 'until_number', + 'effective_number_next': 'number_next', + 'effective_expiration_date': 'expiration_date', + 'tree_from_number': 'from_number', + 'tree_until_number': 'until_number', + 'tree_number_next': 'number_next', + 'tree_expiration_date': 'expiration_date', + } + for record in records: + sequence = record.ncf_sequences + for name in names: + source = mapping[name] + value = (getattr(sequence, source, None) if sequence + else getattr(record, source, None)) + values[name][record.id] = value + return values + def get_rec_name(self, name): if not self.ncf_type_string: return '' return self.ncf_type_string.split('-')[0] + + @classmethod + def validate_fields(cls, records, field_names): + super().validate_fields(records, field_names) + if field_names & { + 'pos', 'ncf_sequences', 'ncf_type', 'auth_number'}: + for record in records: + record._validate_fiscal_sequence() + record._validate_unique_authorization() + + def _validate_unique_authorization(self): + if not self.auth_number or not self.pos or not self.pos.company: + return + if self.__class__.search([ + ('id', '!=', self.id), + ('pos.company', '=', self.pos.company.id), + ('auth_number', '=', self.auth_number), + ], limit=1): + raise UserError(gettext( + 'ncf_manager.msg_ncf_authorization_number_duplicate', + authorization=self.auth_number)) + + def _validate_fiscal_sequence(self): + sequence = self.ncf_sequences + if not sequence: + return + if self.ncf_type == '99': + raise UserError(gettext( + 'ncf_manager.msg_ncf_non_fiscal_sequence')) + if sequence.company != self.pos.company: + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_company_mismatch')) + expected_prefix = ncf_prefix(self.ncf_type) + if self.ncf_type != '99' and sequence.prefix != expected_prefix: + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_prefix_mismatch', + prefix=expected_prefix)) + if sequence.padding != ncf_padding(self.ncf_type): + raise UserError(gettext( + 'ncf_manager.msg_ncf_invalid_padding', + padding=ncf_padding(self.ncf_type))) + ModelData = Pool().get('ir.model.data') + expected_type = ModelData.get_id( + 'ncf_manager', NCF_SEQUENCE_TYPE_IDS[self.ncf_type]) + if sequence.sequence_type.id != expected_type: + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_type_mismatch')) + today = Transaction().context.get('date') or datetime.date.today() + if sequence.expiration_date and sequence.expiration_date < today: + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_expired')) + if (sequence.until_number is not None + and sequence.number_next is not None + and sequence.number_next > sequence.until_number): + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_finished')) + + def prepare_sequence(self): + if self.sequence_mode != 'create': + return + if self.ncf_type == '99': + raise UserError(gettext( + 'ncf_manager.msg_ncf_non_fiscal_sequence')) + self._validate_assisted_values() + pool = Pool() + ModelData = pool.get('ir.model.data') + Sequence = pool.get('ir.sequence.strict') + sequence_type = ModelData.get_id( + 'ncf_manager', NCF_SEQUENCE_TYPE_IDS[self.ncf_type]) + sequence, = Sequence.create([{ + 'name': f'{ncf_prefix(self.ncf_type)} - {self.auth_number}', + 'sequence_type': sequence_type, + 'company': self.pos.company.id, + 'prefix': ncf_prefix(self.ncf_type), + 'padding': ncf_padding(self.ncf_type), + 'number_increment': 1, + 'number_next': self.number_next, + 'from_number': self.from_number, + 'until_number': self.until_number, + 'expiration_date': self.expiration_date, + }]) + self.ncf_sequences = sequence + self.sequence_mode = 'existing' + + def _validate_assisted_values(self): + if None in (self.from_number, self.until_number, self.number_next): + raise UserError(gettext( + 'ncf_manager.msg_ncf_assisted_values_required')) + if not (1 <= self.from_number <= self.number_next + <= self.until_number): + raise UserError(gettext('ncf_manager.msg_ncf_invalid_range')) + + def _validate_no_overlap(self): + sequence = self.ncf_sequences + if not sequence: + return + candidates = self.__class__.search([ + ('id', '!=', self.id), + ('pos.company', '=', self.pos.company.id), + ('ncf_type', '=', self.ncf_type), + ('invoice_type', '=', self.invoice_type), + ('state', '=', 'active'), + ('ncf_sequences', '!=', None), + ]) + for candidate in candidates: + other = candidate.ncf_sequences + if None in (sequence.from_number, sequence.until_number, + other.from_number, other.until_number): + continue + if (sequence.from_number <= other.until_number + and other.from_number <= sequence.until_number): + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_overlap')) + + def get_availability(self, name): + sequence = self.ncf_sequences + if not sequence: + return 'available' + today = Transaction().context.get('date') or datetime.date.today() + if sequence.expiration_date and sequence.expiration_date < today: + return 'expired' + if (sequence.until_number is not None + and sequence.number_next is not None): + remaining = sequence.until_number - sequence.number_next + 1 + if remaining <= 0: + return 'exhausted' + approved = ((sequence.until_number - sequence.from_number + 1) + if sequence.from_number is not None else 0) + if remaining <= max(10, int(approved * .1)): + return 'low' + return 'available' + + @classmethod + def __setup__(cls): + super().__setup__() + table = cls.__table__() + cls._sql_constraints += [ + ('fiscal_sequence_unique', Unique(table, table.ncf_sequences), + 'ncf_manager.msg_ncf_sequence_already_assigned'), + ] + cls._transitions |= { + ('draft', 'active'), + ('active', 'finished'), + } + cls._buttons.update({ + 'finish': { + 'invisible': Eval('state') != 'active', + 'depends': ['state'], + }, + }) + + @classmethod + @Workflow.transition('active') + def activate(cls, lines): + pass + + @classmethod + @ModelView.button + def finish(cls, lines): + cls.complete(lines) + + @classmethod + @Workflow.transition('finished') + def complete(cls, lines): + cls.write(lines, { + 'finished_by': Transaction().user, + 'finished_at': datetime.datetime.now(), + }) + + @classmethod + def delete(cls, lines): + if any(line.state != 'draft' for line in lines): + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_delete_not_draft')) + Invoice = Pool().get('account.invoice') + if Invoice.search([ + ('ncf_sequence', 'in', [line.id for line in lines]), + ], limit=1): + raise UserError(gettext( + 'ncf_manager.msg_ncf_sequence_used')) + super().delete(lines) diff --git a/ncf_manager.xml b/ncf_manager.xml index 963b8f1..3834df5 100644 --- a/ncf_manager.xml +++ b/ncf_manager.xml @@ -41,15 +41,15 @@ this repository contains the full copyright notices and license terms. --> id="menu_ncf_manager" action="act_ncf_manager"/> - + ncf.manager - + - + ncf.manager @@ -57,6 +57,27 @@ this repository contains the full copyright notices and license terms. --> + + activate + Activate + ncf.manager + + + + + + + finish + Finish + ncf.manager + + + + + + ncf.manager.sequence form @@ -70,15 +91,15 @@ this repository contains the full copyright notices and license terms. --> - + ncf.manager.sequence - + - + ncf.manager.sequence @@ -86,5 +107,16 @@ this repository contains the full copyright notices and license terms. --> + + finish + Finish Sequence + ncf.manager.sequence + + + + + + diff --git a/party.py b/party.py index b5fee85..43e8b9e 100644 --- a/party.py +++ b/party.py @@ -6,6 +6,7 @@ from sql import Literal, Null from sql.aggregate import Sum from sql.conditionals import Coalesce +from trytond import backend from trytond.i18n import gettext from trytond.model import ModelSQL, ValueMixin, fields from trytond.modules.company.model import ( @@ -20,6 +21,12 @@ import logging logger = logging.getLogger(__name__) + +def _backend_name(): + name = backend.name + return name() if callable(name) else name + + customer_ncf_type = fields.Selection( NCF_TYPE, "Customer NCF Type", @@ -35,8 +42,6 @@ supplier_ncf_type = fields.Selection( class Party(metaclass=PoolMeta): __name__ = 'party.party' - ncf_types = fields.One2Many( - 'party.party.ncf_type', 'party', "NCF Types") customer_ncf_type = fields.MultiValue(customer_ncf_type) supplier_ncf_type = fields.MultiValue(supplier_ncf_type) @@ -49,11 +54,19 @@ class Party(metaclass=PoolMeta): @classmethod def default_customer_ncf_type(cls, **pattern): - return None + pool = Pool() + Configuration = pool.get('account.configuration') + config = Configuration(1) + return config.get_multivalue( + 'default_customer_ncf_type', **pattern) @classmethod def default_supplier_ncf_type(cls, **pattern): - return None + pool = Pool() + Configuration = pool.get('account.configuration') + config = Configuration(1) + return config.get_multivalue( + 'default_supplier_ncf_type', **pattern) class PartyNcfType(ModelSQL, ValueMixin): @@ -87,6 +100,9 @@ class PartyNcfType(ModelSQL, ValueMixin): @classmethod def _ncf_column_exists(cls, cursor, table_name, column_name): + if _backend_name() == 'sqlite': + cursor.execute(f'PRAGMA table_info("{table_name}")') + return any(row[1] == column_name for row in cursor.fetchall()) cursor.execute(""" SELECT 1 FROM information_schema.columns @@ -97,6 +113,12 @@ class PartyNcfType(ModelSQL, ValueMixin): @classmethod def _ncf_column_udt_name(cls, cursor, table_name, column_name): + if _backend_name() == 'sqlite': + cursor.execute(f'PRAGMA table_info("{table_name}")') + for row in cursor.fetchall(): + if row[1] == column_name: + return (row[2] or '').lower() + return None cursor.execute(""" SELECT udt_name FROM information_schema.columns @@ -131,7 +153,7 @@ class PartyNcfType(ModelSQL, ValueMixin): udt_name = cls._ncf_column_udt_name( cursor, table_name, old_column) - if udt_name in {'int2', 'int4', 'int8'}: + if udt_name in {'int2', 'int4', 'int8', 'integer'}: logger.info( "Renaming legacy %s.%s integer column to %s before " "Tryton creates the new Selection column", diff --git a/report.py b/report.py deleted file mode 100644 index eae9910..0000000 --- a/report.py +++ /dev/null @@ -1,20 +0,0 @@ -from trytond.pool import PoolMeta - - -class InvoiceReport(metaclass=PoolMeta): - """Add the NCF label required by the fiscal invoice template.""" - __name__ = 'account.invoice' - - @classmethod - def get_context(cls, records, header, data): - context = super().get_context(records, header, data) - invoice = context['invoice'] - context['ncf_type_name'] = cls._get_ncf_type_name(invoice) - return context - - @staticmethod - def _get_ncf_type_name(invoice): - if not invoice.ncf_type: - return '' - return invoice.__class__._ncf_type_label_map().get( - invoice.ncf_type, '') diff --git a/sequence.py b/sequence.py index de1d579..bec93e2 100644 --- a/sequence.py +++ b/sequence.py @@ -1,18 +1,43 @@ # This file is part of ncf_manager module for Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. -from string import Template -import time - -from sql import Literal, For +import unicodedata from trytond.exceptions import UserError -from trytond.model.exceptions import ValidationError -from trytond.model import ModelView, ModelSQL, DeactivableMixin, fields, Check -from trytond.pyson import Eval, And -from trytond.transaction import Transaction -from trytond.pool import Pool, PoolMeta +from trytond.model import fields +from trytond.pyson import Eval +from trytond.pool import PoolMeta from trytond.i18n import gettext -from trytond import backend + +# Maps sequence_type.name → (prefix, padding) +_NCF_TYPE_MAP = { + 'Factura de Crédito Fiscal': ('B01', 8), + 'Factura de Consumo': ('B02', 8), + 'Nota de Débito': ('B03', 8), + 'Nota de Crédito': ('B04', 8), + 'Comprobante de Compras': ('B11', 8), + 'Registro Único de Ingreso': ('B12', 8), + 'Comprobante para Gasto Menor': ('B13', 8), + 'Comprobante de Regímen Especial': ('B14', 8), + 'Comprobante Gubernamental': ('B15', 8), + 'Comprobante para exportaciones': ('B16', 8), + 'Comprobante para Pagos al Exterior': ('B17', 8), + 'Factura de Crédito Fiscal Electrónica': ('E31', 10), + 'Factura de Consumo Electrónica': ('E32', 10), + 'Nota de Débito Electrónica': ('E33', 10), + 'Nota de Crédito Electrónica': ('E34', 10), + 'Compras Electrónico': ('E41', 10), + 'Gastos Menores Electrónico': ('E43', 10), + 'Regímenes Especiales Electrónico': ('E44', 10), + 'Gubernamental Electrónico': ('E45', 10), + 'Exportación Electrónico': ('E46', 10), + 'Pagos al Exterior Electrónico': ('E47', 10), +} +NCF_PREFIXES = tuple(prefix for prefix, _padding in _NCF_TYPE_MAP.values()) + + +def _sequence_type_entry(sequence_type): + name = unicodedata.normalize('NFC', sequence_type.name or '') + return _NCF_TYPE_MAP.get(name) class Sequence(metaclass=PoolMeta): @@ -64,146 +89,23 @@ class Sequence(metaclass=PoolMeta): @fields.depends('sequence_type') def on_change_with_name(self, name=None): - if not self.sequence_type or not self.sequence_type.name: - return None - if self.sequence_type.name == 'Factura de Crédito Fiscal': - return 'Factura de Crédito Fiscal' - elif self.sequence_type.name == 'Factura de Consumo': - return 'Factura de Consumo' - elif self.sequence_type.name == 'Nota de Débito': - return 'Nota de Débito' - elif self.sequence_type.name == 'Nota de Crédito': - return 'Nota de Crédito' - elif self.sequence_type.name == 'Comprobante de Compras': - return 'Comprobante de Compras' - elif self.sequence_type.name == 'Registro Único de Ingreso': - return 'Registro Único de Ingreso' - elif self.sequence_type.name == 'Comprobante para Gasto Menor': - return 'Comprobante para Gasto Menor' - elif self.sequence_type.name == 'Comprobante de Regímen Especial': - return 'Comprobante de Regímen Especial' - elif self.sequence_type.name == 'Comprobante Gubernamental': - return 'Comprobante Gubernamental' - elif self.sequence_type.name == 'Comprobante para exportaciones': - return 'Comprobante para exportaciones' - elif self.sequence_type.name == 'Comprobante para Pagos al Exterior': - return 'Comprobante para Pagos al Exterior' - elif self.sequence_type.name == 'Factura de Crédito Fiscal Electrónica': - return 'Factura de Crédito Fiscal Electrónica' - elif self.sequence_type.name == 'Factura de Consumo Electrónica': - return 'Factura de Consumo Electrónica' - elif self.sequence_type.name == 'Nota de Débito Electrónica': - return 'Nota de Débito Electrónica' - elif self.sequence_type.name == 'Nota de Crédito Electrónica': - return 'Nota de Crédito Electrónica' - elif self.sequence_type.name == 'Compras Electrónico': - return 'Compras Electrónico' - elif self.sequence_type.name == 'Gastos Menores Electrónico': - return 'Gastos Menores Electrónico' - elif self.sequence_type.name == 'Regímenes Especiales Electrónico': - return 'Regímenes Especiales Electrónico' - elif self.sequence_type.name == 'Gubernamental Electrónico': - return 'Gubernamental Electrónico' - elif self.sequence_type.name == 'Exportación Electrónico': - return 'Exportación Electrónico' - elif self.sequence_type.name == 'Pagos al Exterior Electrónico': - return 'Pagos al Exterior Electrónico' - + if self.sequence_type: + return self.sequence_type.name + return None @fields.depends('sequence_type') def on_change_with_prefix(self, name=None): if not self.sequence_type or not self.sequence_type.name: - return None - if self.sequence_type.name == 'Factura de Crédito Fiscal': - return 'B01' - elif self.sequence_type.name == 'Factura de Consumo': - return 'B02' - elif self.sequence_type.name == 'Nota de Débito': - return 'B03' - elif self.sequence_type.name == 'Nota de Crédito': - return 'B04' - elif self.sequence_type.name == 'Comprobante de Compras': - return 'B11' - elif self.sequence_type.name == 'Registro Único de Ingreso': - return 'B12' - elif self.sequence_type.name == 'Comprobante para Gasto Menor': - return 'B13' - elif self.sequence_type.name == 'Comprobante de Regímen Especial': - return 'B14' - elif self.sequence_type.name == 'Comprobante Gubernamental': - return 'B15' - elif self.sequence_type.name == 'Comprobante para exportaciones': - return 'B16' - elif self.sequence_type.name == 'Comprobante para Pagos al Exterior': - return 'B17' - elif self.sequence_type.name == 'Factura de Crédito Fiscal Electrónica': - return 'E31' - elif self.sequence_type.name == 'Factura de Consumo Electrónica': - return 'E32' - elif self.sequence_type.name == 'Nota de Débito Electrónica': - return 'E33' - elif self.sequence_type.name == 'Nota de Crédito Electrónica': - return 'E34' - elif self.sequence_type.name == 'Compras Electrónico': - return 'E41' - elif self.sequence_type.name == 'Gastos Menores Electrónico': - return 'E43' - elif self.sequence_type.name == 'Regímenes Especiales Electrónico': - return 'E44' - elif self.sequence_type.name == 'Gubernamental Electrónico': - return 'E45' - elif self.sequence_type.name == 'Exportación Electrónico': - return 'E46' - elif self.sequence_type.name == 'Pagos al Exterior Electrónico': - return 'E47' - + return None + entry = _sequence_type_entry(self.sequence_type) + return entry[0] if entry else None @fields.depends('sequence_type') def on_change_with_padding(self, name=None): if not self.sequence_type or not self.sequence_type.name: return 0 - if self.sequence_type.name == 'Factura de Crédito Fiscal': - return 8 - elif self.sequence_type.name == 'Factura de Consumo': - return 8 - elif self.sequence_type.name == 'Nota de Débito': - return 8 - elif self.sequence_type.name == 'Nota de Crédito': - return 8 - elif self.sequence_type.name == 'Comprobante de Compras': - return 8 - elif self.sequence_type.name == 'Registro Único de Ingreso': - return 8 - elif self.sequence_type.name == 'Comprobante para Gasto Menor': - return 8 - elif self.sequence_type.name == 'Comprobante de Regímen Especial': - return 8 - elif self.sequence_type.name == 'Comprobante Gubernamental': - return 8 - elif self.sequence_type.name == 'Comprobante para exportaciones': - return 8 - elif self.sequence_type.name == 'Comprobante para Pagos al Exterior': - return 8 - elif self.sequence_type.name == 'Factura de Crédito Fiscal Electrónica': - return 10 - elif self.sequence_type.name == 'Factura de Consumo Electrónica': - return 10 - elif self.sequence_type.name == 'Nota de Débito Electrónica': - return 10 - elif self.sequence_type.name == 'Nota de Crédito Electrónica': - return 10 - elif self.sequence_type.name == 'Compras Electrónico': - return 10 - elif self.sequence_type.name == 'Gastos Menores Electrónico': - return 10 - elif self.sequence_type.name == 'Regímenes Especiales Electrónico': - return 10 - elif self.sequence_type.name == 'Gubernamental Electrónico': - return 10 - elif self.sequence_type.name == 'Exportación Electrónico': - return 10 - elif self.sequence_type.name == 'Pagos al Exterior Electrónico': - return 10 + entry = _sequence_type_entry(self.sequence_type) + return entry[1] if entry else 0 @fields.depends('from_number', 'until_number') def on_change_with_approved_qty(self, name=None): @@ -212,12 +114,41 @@ class Sequence(metaclass=PoolMeta): @fields.depends('number_next', 'until_number') def on_change_with_remaining_qty(self, name=None): - if self.until_number and self.number_next: + if self.until_number is not None and self.number_next is not None: return self.until_number - self.number_next + 1 + + @classmethod + def validate_fields(cls, records, field_names): + super().validate_fields(records, field_names) + if field_names & { + 'prefix', 'padding', 'from_number', 'until_number', + 'number_next'}: + for record in records: + record._validate_ncf_range() + + def _validate_ncf_range(self): + if self.prefix not in NCF_PREFIXES: + return + expected_padding = 10 if self.prefix.startswith('E') else 8 + if self.padding != expected_padding: + raise UserError(gettext( + 'ncf_manager.msg_ncf_invalid_padding', + padding=expected_padding)) + if self.from_number is None or self.until_number is None: + return + if self.from_number < 1 or self.until_number < self.from_number: + raise UserError(gettext('ncf_manager.msg_ncf_invalid_range')) + if (self.number_next is not None + and self.number_next < self.from_number): + raise UserError(gettext('ncf_manager.msg_ncf_next_before_range')) class SequenceStrict(Sequence): "Sequence Strict" __name__ = 'ir.sequence.strict' _table = None # Needed to reset Sequence._table _strict = True + + ncf_authorization_lines = fields.One2Many( + 'ncf.manager.sequence', 'ncf_sequences', 'NCF Authorizations', + readonly=True) diff --git a/sequence.xml b/sequence.xml index 349c8c2..c759b00 100644 --- a/sequence.xml +++ b/sequence.xml @@ -9,12 +9,6 @@ this repository contains the full copyright notices and license terms. --> sequence_form - - diff --git a/setup.py b/setup.py index 66ae055..a8e6e3e 100755 --- a/setup.py +++ b/setup.py @@ -6,7 +6,12 @@ from configparser import ConfigParser from setuptools import find_packages, setup -MODULE2PREFIX = {} +MODULE2PREFIX = { + 'account_do': 'unpaismejor', + 'account_credit_note': 'unpaismejor', + 'account_debit_note': 'unpaismejor', + 'account_invoice_do': 'unpaismejor', +} def read(fname): @@ -71,6 +76,7 @@ setup(name=name, version=version, description='This module implements the administration and management of tax receipt numbers.', long_description=read('README.rst'), + long_description_content_type='text/x-rst', author='Solutema SRL', author_email='info@solutema.com', url='https://www.solutema.com/', diff --git a/tests/test_module.py b/tests/test_module.py index 6503598..43b57ec 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -1,32 +1,824 @@ - +import datetime +from decimal import Decimal from pathlib import Path +from types import SimpleNamespace +import unittest -from trytond.tests.test_tryton import ModuleTestCase - -from trytond.modules.ncf_manager.report import InvoiceReport +from trytond.exceptions import UserError +from trytond.modules.ncf_manager.sequence import Sequence +from trytond.modules.ncf_manager.invoice import Invoice +from trytond.modules.ncf_manager.importer import import_dgii_authorizations +from trytond.pool import Pool +from trytond.tests.test_tryton import ModuleTestCase, with_transaction +from trytond.transaction import Transaction class NcfManagerTestCase(ModuleTestCase): "Test Ncf Manager module" module = 'ncf_manager' - def test_fiscal_report_overrides_single_invoice_action(self): - report_xml = (Path(__file__).parent.parent / 'invoice.xml').read_text() - self.assertIn('id="account_invoice.report_invoice"', report_xml) - self.assertIn('ncf_manager/invoice.fodt', report_xml) - self.assertNotIn('ir.action.keyword', report_xml) + def _create_company(self): + pool = Pool() + Company = pool.get('company.company') + Currency = pool.get('currency.currency') + Party = pool.get('party.party') - def test_fiscal_report_resolves_ncf_label(self): - class Invoice: - ncf_type = '31' + currency, = Currency.create([{ + 'name': 'Dominican Peso', + 'code': 'DOP', + 'symbol': 'RD$', + 'digits': 2, + 'rounding': '0.01', + }]) + party, = Party.create([{ + 'name': 'Empresa NCF', + 'addresses': [('create', [{}])], + }]) + company, = Company.create([{ + 'party': party.id, + 'currency': currency.id, + }]) + return company - @staticmethod - def _ncf_type_label_map(): - return {'31': 'Factura de Crédito Fiscal'} + def _create_chart(self, company): + pool = Pool() + Account = pool.get('account.account') + AccountTemplate = pool.get('account.account.template') + CreateChart = pool.get('account.create_chart', type='wizard') + Journal = pool.get('account.journal') + ModelData = pool.get('ir.model.data') + session_id, _start, _end = CreateChart.create() + chart = CreateChart(session_id) + chart.account.account_template = AccountTemplate(ModelData.get_id( + 'account_do', 'do_account_root_en')) + chart.account.company = company + chart.transition_create_account() + + receivable, = Account.search([ + ('company', '=', company.id), + ('code', '=', '110201'), + ], limit=1) + payable, = Account.search([ + ('company', '=', company.id), + ('code', '=', '210101'), + ], limit=1) + revenue, = Account.search([ + ('company', '=', company.id), + ('code', '=', '4102'), + ], limit=1) + chart.properties.company = company + chart.properties.account_receivable = receivable + chart.properties.account_payable = payable + with Transaction().set_context(company=company.id): + chart.transition_create_properties() + CreateChart.delete(session_id) + journal, = Journal.search([('type', '=', 'revenue')], limit=1) + return receivable, revenue, journal + + def _create_fiscalyear(self, company, today=None): + pool = Pool() + FiscalYear = pool.get('account.fiscalyear') + InvoiceSequence = pool.get('account.fiscalyear.invoice_sequence') + StrictSequence = pool.get('ir.sequence.strict') + SequenceType = pool.get('ir.sequence.type') + today = today or datetime.date.today() + year = today.year + + move_type, = SequenceType.search([ + ('name', '=', 'Account Move'), + ], limit=1) + invoice_type, = SequenceType.search([ + ('name', '=', 'Invoice'), + ], limit=1) + move_sequence, = StrictSequence.create([{ + 'name': 'FY 2026 Moves', + 'sequence_type': move_type.id, + 'company': company.id, + }]) + invoice_sequence, = StrictSequence.create([{ + 'name': 'FY 2026 Invoices', + 'sequence_type': invoice_type.id, + 'company': company.id, + }]) + fiscalyear, = FiscalYear.create([{ + 'name': str(year), + 'start_date': datetime.date(year, 1, 1), + 'end_date': datetime.date(year, 12, 31), + 'company': company.id, + 'move_sequence': move_sequence.id, + }]) + fiscalyear.invoice_sequences = [InvoiceSequence( + company=company, + in_invoice_sequence=invoice_sequence, + in_credit_note_sequence=invoice_sequence, + out_invoice_sequence=invoice_sequence, + out_credit_note_sequence=invoice_sequence)] + fiscalyear.save() + FiscalYear.create_period([fiscalyear]) + + def _create_payment_term(self): + PaymentTerm = Pool().get('account.invoice.payment_term') + term, = PaymentTerm.create([{ + 'name': 'Contado', + 'lines': [('create', [{'type': 'remainder'}])], + }]) + return term + + def _create_ncf_sequence(self, company, today=None): + pool = Pool() + ModelData = pool.get('ir.model.data') + Manager = pool.get('ncf.manager') + ManagerSequence = pool.get('ncf.manager.sequence') + StrictSequence = pool.get('ir.sequence.strict') + SequenceType = pool.get('ir.sequence.type') + today = today or datetime.date.today() + + sequence_type = SequenceType(ModelData.get_id( + 'ncf_manager', 'sequence_type_out_invoice_01')) + strict_sequence, = StrictSequence.create([{ + 'name': 'B01 Factura Credito Fiscal', + 'sequence_type': sequence_type.id, + 'company': company.id, + 'prefix': 'B01', + 'padding': 8, + 'number_next': 1, + 'number_increment': 1, + 'from_number': 1, + 'until_number': 2, + 'expiration_date': datetime.date(today.year, 12, 31), + }]) + manager, = Manager.create([{ + 'company': company.id, + 'app_date': datetime.date(today.year, 1, 1), + 'app_number': '0000000001', + 'auth_number': '0000000001', + 'state': 'active', + }]) + with Transaction().set_context(company=company.id): + sequence, = ManagerSequence.create([{ + 'pos': manager.id, + 'ncf_type': '1', + 'ncf_sequences': strict_sequence.id, + 'invoice_type': 'invoice_customer', + 'state': 'active', + }]) + return sequence + + def _create_active_e31_range(self, company, invoice_type, + from_number=1, until_number=100): + pool = Pool() + Manager = pool.get('ncf.manager') + ManagerSequence = pool.get('ncf.manager.sequence') + ModelData = pool.get('ir.model.data') + StrictSequence = pool.get('ir.sequence.strict') + SequenceType = pool.get('ir.sequence.type') + today = datetime.date.today() + + sequence_type = SequenceType(ModelData.get_id( + 'ncf_manager', 'sequence_type_out_invoice_31')) + strict_sequence, = StrictSequence.create([{ + 'name': f'E31 {invoice_type}', + 'sequence_type': sequence_type.id, + 'company': company.id, + 'prefix': 'E31', + 'padding': 10, + 'number_next': from_number, + 'number_increment': 1, + 'from_number': from_number, + 'until_number': until_number, + 'expiration_date': datetime.date(today.year + 1, 12, 31), + }]) + manager, = Manager.create([{ + 'company': company.id, + 'app_date': today, + 'app_number': 'APP0000001', + 'auth_number': 'AUT0000001', + 'state': 'active', + }]) + line, = ManagerSequence.create([{ + 'pos': manager.id, + 'ncf_type': '31', + 'ncf_sequences': strict_sequence.id, + 'invoice_type': invoice_type, + 'state': 'active', + }]) + return line + + @staticmethod + def _dgii_xml(ncf_type='31', authorization='6005423851', + start='E310000000001', end='E310000000100', quantity='100'): + return f''' + + 6009912073 + {authorization} + 2026-08-07T13:45:02-04:00 + FACTURA ELECTRÓNICA + Empresa NCF + {start} + {end} + {ncf_type} + 2026-08-07T13:36:23-04:00 + APROBADA + {quantity} + ELECTRÓNICA + {quantity} + 2027-12-31T00:00:00-04:00 + Autorizada por DGII + + '''.encode() + + @with_transaction() + def test_customer_invoice_post_assigns_b01_ncf(self): + 'Test full NCF assignment workflow on posted customer invoice' + pool = Pool() + Invoice = pool.get('account.invoice') + Party = pool.get('party.party') + + today = datetime.date.today() + company = self._create_company() + receivable, revenue, journal = self._create_chart(company) + self._create_fiscalyear(company, today=today) + payment_term = self._create_payment_term() + ncf_sequence = self._create_ncf_sequence(company, today=today) + party, = Party.create([{ + 'name': 'Cliente NCF', + 'addresses': [('create', [{}])], + }]) + + with Transaction().set_context( + company=company.id, date=today): + invoice, = Invoice.create([{ + 'type': 'out', + 'company': company.id, + 'party': party.id, + 'invoice_address': party.addresses[0].id, + 'account': receivable.id, + 'currency': company.currency.id, + 'invoice_date': today, + 'accounting_date': today, + 'journal': journal.id, + 'payment_term': payment_term.id, + 'ncf_type': '1', + 'ncf_sequence': ncf_sequence.id, + 'revenue_type': '01', + 'payment_method': '04', + 'lines': [('create', [{ + 'type': 'line', + 'description': 'Servicio', + 'quantity': 1, + 'unit_price': Decimal('500.00'), + 'account': revenue.id, + }])], + }]) + Invoice.post([invoice]) + invoice = Invoice(invoice.id) + + self.assertEqual(invoice.state, 'posted') + self.assertEqual(invoice.ncf_number, 'B0100000001') + self.assertEqual(invoice.ncf_sequence, ncf_sequence) self.assertEqual( - InvoiceReport._get_ncf_type_name(Invoice()), - 'Factura de Crédito Fiscal') + invoice.expiration_date, datetime.date(today.year, 12, 31)) + + @with_transaction() + def test_assisted_sequence_workflow(self): + pool = Pool() + Manager = pool.get('ncf.manager') + today = datetime.date.today() + company = self._create_company() + + manager, = Manager.create([{ + 'company': company.id, + 'app_date': today, + 'app_number': 'APP0000001', + 'auth_number': 'AUT0000001', + 'ncf_sequences': [('create', [{ + 'invoice_type': 'invoice_customer', + 'ncf_type': '1', + 'sequence_mode': 'create', + 'from_number': 100, + 'number_next': 100, + 'until_number': 109, + 'expiration_date': datetime.date(today.year, 12, 31), + }])], + }]) + + Manager.activate([manager]) + manager = Manager(manager.id) + line, = manager.ncf_sequences + self.assertEqual(manager.state, 'active') + self.assertEqual(line.state, 'active') + self.assertEqual(line.sequence_mode, 'existing') + self.assertEqual(line.ncf_sequences.prefix, 'B01') + self.assertEqual(line.ncf_sequences.padding, 8) + self.assertEqual(line.ncf_sequences.number_next, 100) + self.assertEqual(line.effective_from_number, 100) + self.assertEqual(line.effective_until_number, 109) + self.assertEqual(line.effective_number_next, 100) + self.assertEqual( + line.effective_expiration_date, + datetime.date(today.year, 12, 31)) + self.assertEqual(line.tree_from_number, 100) + self.assertEqual(line.tree_until_number, 109) + self.assertEqual(line.tree_number_next, 100) + self.assertEqual( + line.tree_expiration_date, + datetime.date(today.year, 12, 31)) + self.assertEqual(line.availability, 'low') + + Manager.finish([manager]) + manager = Manager(manager.id) + self.assertEqual(manager.state, 'finished') + self.assertEqual(manager.ncf_sequences[0].state, 'finished') + self.assertIsNotNone(manager.finished_at) + + @with_transaction() + def test_overlap_is_independent_by_invoice_direction(self): + 'A supplier range must not block the company outgoing authorization' + pool = Pool() + Manager = pool.get('ncf.manager') + company = self._create_company() + today = datetime.date.today() + + supplier_line = self._create_active_e31_range( + company, 'invoice_supplier', until_number=2_000_000_000) + manager, = Manager.create([{ + 'company': company.id, + 'app_date': today, + 'app_number': '6009912073', + 'auth_number': '6005423851', + 'ncf_sequences': [('create', [{ + 'invoice_type': 'invoice_customer', + 'ncf_type': '31', + 'sequence_mode': 'create', + 'from_number': 1, + 'number_next': 1, + 'until_number': 100, + 'expiration_date': datetime.date( + today.year + 1, 12, 31), + }])], + }]) + + Manager.activate([manager]) + + manager = Manager(manager.id) + self.assertEqual(manager.state, 'active') + self.assertEqual(manager.ncf_sequences[0].state, 'active') + self.assertEqual(supplier_line.state, 'active') + + @with_transaction() + def test_overlap_still_blocks_same_invoice_direction(self): + 'Two outgoing authorizations may not reserve the same E31 numbers' + pool = Pool() + Manager = pool.get('ncf.manager') + company = self._create_company() + today = datetime.date.today() + + self._create_active_e31_range( + company, 'invoice_customer', from_number=1, until_number=100) + manager, = Manager.create([{ + 'company': company.id, + 'app_date': today, + 'app_number': '6009912073', + 'auth_number': '6005423851', + 'ncf_sequences': [('create', [{ + 'invoice_type': 'invoice_customer', + 'ncf_type': '31', + 'sequence_mode': 'create', + 'from_number': 50, + 'number_next': 50, + 'until_number': 150, + 'expiration_date': datetime.date( + today.year + 1, 12, 31), + }])], + }]) + + with self.assertRaises(UserError): + Manager.activate([manager]) + + @with_transaction() + def test_finish_preserves_bound_legacy_migration_sequence(self): + 'Finishing must not invalidate an immutable historical sequence' + pool = Pool() + Manager = pool.get('ncf.manager') + StrictSequence = pool.get('ir.sequence.strict') + company = self._create_company() + + line = self._create_ncf_sequence(company) + strict_sequence = line.ncf_sequences + StrictSequence.write([strict_sequence], { + 'prefix': 'MIG1', + 'padding': 9, + }) + + Manager.finish([line.pos]) + + line = line.__class__(line.id) + self.assertEqual(line.state, 'finished') + self.assertEqual(line.ncf_sequences.id, strict_sequence.id) + self.assertEqual(line.ncf_sequences.prefix, 'MIG1') + + @with_transaction() + def test_import_dgii_authorization_is_idempotent(self): + pool = Pool() + Manager = pool.get('ncf.manager') + company = self._create_company() + data = self._dgii_xml() + + managers, lines = import_dgii_authorizations( + company, data, 'authorization.xml') + self.assertEqual(len(managers), 1) + self.assertEqual(len(lines), 1) + manager = managers[0] + line = lines[0] + self.assertEqual(manager.app_number, '6009912073') + self.assertEqual(line.auth_number, '6005423851') + self.assertEqual(line.ncf_type, '31') + self.assertEqual(line.from_number, 1) + self.assertEqual(line.until_number, 100) + self.assertEqual(line.expiration_date, datetime.date(2027, 12, 31)) + self.assertEqual(line.tree_from_number, 1) + self.assertEqual(line.tree_until_number, 100) + self.assertEqual(line.tree_number_next, 1) + self.assertEqual( + line.tree_expiration_date, datetime.date(2027, 12, 31)) + + managers, lines = import_dgii_authorizations( + company, data, 'authorization-again.xml') + self.assertEqual(managers, []) + self.assertEqual(lines, []) + self.assertEqual(Manager.search_count([ + ('app_number', '=', '6009912073')]), 1) + + @with_transaction() + def test_import_new_authorization_for_active_request(self): + 'A new NUM_AUTOR may reuse NUM_SOL without reopening the active one' + pool = Pool() + Manager = pool.get('ncf.manager') + Line = pool.get('ncf.manager.sequence') + company = self._create_company() + + first_data = self._dgii_xml() + first_managers, _ = import_dgii_authorizations( + company, first_data, 'authorization-31.xml', activate=True) + first_manager, = first_managers + self.assertEqual(Manager(first_manager.id).state, 'active') + + second_data = self._dgii_xml( + ncf_type='34', authorization='6005423852', + start='E340000000001', end='E340000001000', quantity='1000') + second_managers, second_lines = import_dgii_authorizations( + company, second_data, 'authorization-34.xml') + + self.assertEqual(len(second_managers), 1) + self.assertEqual(len(second_lines), 1) + self.assertNotEqual(second_managers[0].id, first_manager.id) + self.assertEqual(second_managers[0].state, 'draft') + self.assertEqual(second_lines[0].auth_number, '6005423852') + self.assertEqual(Manager(first_manager.id).state, 'active') + self.assertEqual(Manager.search_count([ + ('company', '=', company.id), + ('app_number', '=', '6009912073'), + ]), 2) + self.assertEqual(Line.search_count([ + ('pos.company', '=', company.id), + ('auth_number', 'in', ['6005423851', '6005423852']), + ]), 2) + + managers, lines = import_dgii_authorizations( + company, second_data, 'authorization-34-again.xml') + self.assertEqual(managers, []) + self.assertEqual(lines, []) del ModuleTestCase + + +class NcfManagerUnitTestCase(unittest.TestCase): + + @staticmethod + def invoice_with_identifier(code, type=None, code_compact=None): + identifier = SimpleNamespace(code=code, type=type) + if code_compact is not None: + identifier.code_compact = code_compact + return SimpleNamespace( + party=object(), party_tax_identifier=identifier) + + def test_id_type_accepts_formatted_rnc(self): + invoice = self.invoice_with_identifier('1-01-01063-2') + self.assertEqual(Invoice.get_id_type(invoice, 'id_type'), 1) + + def test_id_type_accepts_formatted_cedula(self): + invoice = self.invoice_with_identifier('001-1391820-5') + self.assertEqual(Invoice.get_id_type(invoice, 'id_type'), 2) + + def test_id_type_uses_dominican_identifier_type(self): + rnc = self.invoice_with_identifier('formatted', type='do_vat') + cedula = self.invoice_with_identifier('formatted', type='do_cedula') + self.assertEqual(Invoice.get_id_type(rnc, 'id_type'), 1) + self.assertEqual(Invoice.get_id_type(cedula, 'id_type'), 2) + + def test_id_type_normalizes_migrated_compact_code(self): + invoice = self.invoice_with_identifier( + 'display value', code_compact='001-1391820-5') + self.assertEqual(Invoice.get_id_type(invoice, 'id_type'), 2) + + def test_id_type_returns_none_without_identifier(self): + invoice = SimpleNamespace(party=object(), party_tax_identifier=None) + self.assertIsNone(Invoice.get_id_type(invoice, 'id_type')) + + def test_invoice_report_uses_current_tax_field_names(self): + path = Path(__file__).parents[1] / 'invoice.fodt' + template = path.read_text(encoding='utf-8') + + self.assertNotIn('line.itbis_line', template) + self.assertEqual(template.count('line.itbis_invoiced_line'), 2) + self.assertEqual(template.count('if test="invoice.tip'), 2) + self.assertEqual(template.count('format_currency(invoice.tip'), 2) + + def test_sequence_defaults_match_ncf_type(self): + sequence = SimpleNamespace( + sequence_type=SimpleNamespace(name='Factura de Crédito Fiscal')) + + self.assertEqual(Sequence.on_change_with_prefix(sequence), 'B01') + self.assertEqual(Sequence.on_change_with_padding(sequence), 8) + + def test_sequence_approved_and_remaining_quantities(self): + sequence = SimpleNamespace( + from_number=1, + until_number=10, + number_next=4) + + self.assertEqual(Sequence.on_change_with_approved_qty(sequence), 10) + self.assertEqual(Sequence.on_change_with_remaining_qty(sequence), 7) + + def test_ncf_structure_and_normalization(self): + invoice = SimpleNamespace( + ncf_number=' b0100000001 ', ncf_type='1') + Invoice._ncf_validate_number(invoice) + self.assertEqual(invoice.ncf_number, 'B0100000001') + + invoice.ncf_number = 'E310000000001' + invoice.ncf_type = '31' + Invoice._ncf_validate_number(invoice) + + def test_ncf_rejects_invalid_structure_or_type(self): + invoice = SimpleNamespace(ncf_number='B010001', ncf_type='1') + with self.assertRaises(UserError): + Invoice._ncf_validate_number(invoice) + + def test_legacy_supplier_ncf_is_preserved_for_migration(self): + invoice = SimpleNamespace( + type='in', ncf_number='A010010010100000001', ncf_type='1') + Invoice._ncf_validate_number(invoice) + self.assertEqual(invoice.ncf_number, 'A010010010100000001') + + invoice.ncf_number = 'B0200000001' + with self.assertRaises(UserError): + Invoice._ncf_validate_number(invoice) + + def test_fiscal_cancellation_requires_ncf_number(self): + fiscal_invoice = SimpleNamespace(type='out', ncf_number='B0100000001') + non_fiscal_invoice = SimpleNamespace(type='out', ncf_number=None) + supplier_invoice = SimpleNamespace(type='in', ncf_number='B1100000001') + + self.assertTrue( + Invoice._ncf_is_fiscal_cancellation_required(fiscal_invoice)) + self.assertFalse( + Invoice._ncf_is_fiscal_cancellation_required(non_fiscal_invoice)) + self.assertFalse( + Invoice._ncf_is_fiscal_cancellation_required(supplier_invoice)) + + def test_fiscal_cancellation_information_is_required(self): + invoice = SimpleNamespace( + type='out', + rec_name='INV/1', + ncf_number='B0100000001', + ncf_cancellation_type=None, + ncf_cancellation_reason=None) + + with self.assertRaises(UserError): + Invoice._ncf_check_cancellation_information(invoice) + + invoice.ncf_cancellation_type = '04' + with self.assertRaises(UserError): + Invoice._ncf_check_cancellation_information(invoice) + + invoice.ncf_cancellation_reason = 'Corrección de la información' + Invoice._ncf_check_cancellation_information(invoice) + + def test_debit_note_code_follows_origin_ncf_type(self): + original_enabled = Invoice._ncf_electronic_invoicing_enabled + Invoice._ncf_electronic_invoicing_enabled = classmethod( + lambda cls: False) + try: + physical = SimpleNamespace(ncf_type='1') + electronic = SimpleNamespace(ncf_type='31') + + self.assertEqual( + Invoice._ncf_resolve_debit_note_code(physical), '3') + self.assertEqual( + Invoice._ncf_resolve_debit_note_code(electronic), '3') + finally: + Invoice._ncf_electronic_invoicing_enabled = original_enabled + + def test_debit_note_preparation_uses_physical_without_electronic_module(self): + electronic_sequence = SimpleNamespace(ncf_type='33') + physical_sequence = SimpleNamespace(ncf_type='3') + original_find_active_sequence = Invoice._ncf_find_active_sequence + original_enabled = Invoice._ncf_electronic_invoicing_enabled + + def find_sequence(cls, invoice, ncf_code): + if ncf_code == '33': + return electronic_sequence + if ncf_code == '3': + return physical_sequence + return None + + Invoice._ncf_find_active_sequence = classmethod(find_sequence) + Invoice._ncf_electronic_invoicing_enabled = classmethod( + lambda cls: False) + try: + origin = SimpleNamespace( + ncf_number='B0100000001', + ncf_type='1', + payment_method='04', + revenue_type='01', + isr_withholding_type=None) + debit_note = SimpleNamespace( + company=SimpleNamespace(rec_name='Solutema'), + type='out', + ncf_number_modified=None, + ncf_type=None, + ncf_sequence=None, + payment_method=None, + revenue_type=None, + isr_withholding_type=None) + + Invoice._ncf_prepare_debit_note_from_origin(origin, debit_note) + finally: + Invoice._ncf_find_active_sequence = original_find_active_sequence + Invoice._ncf_electronic_invoicing_enabled = original_enabled + + self.assertEqual(debit_note.ncf_number_modified, 'B0100000001') + self.assertEqual(debit_note.ncf_type, '3') + self.assertEqual(debit_note.ncf_sequence, physical_sequence) + self.assertEqual(debit_note.payment_method, '04') + self.assertEqual(debit_note.revenue_type, '01') + + def test_debit_note_preparation_prefers_electronic_when_module_is_active(self): + electronic_sequence = SimpleNamespace(ncf_type='33') + original_find_active_sequence = Invoice._ncf_find_active_sequence + original_enabled = Invoice._ncf_electronic_invoicing_enabled + + def find_sequence(cls, invoice, ncf_code): + return electronic_sequence if ncf_code == '33' else None + + Invoice._ncf_find_active_sequence = classmethod(find_sequence) + Invoice._ncf_electronic_invoicing_enabled = classmethod( + lambda cls: True) + try: + origin = SimpleNamespace( + ncf_number='B0100000001', + ncf_type='1', + payment_method='04', + revenue_type='01', + isr_withholding_type=None) + debit_note = SimpleNamespace( + company=SimpleNamespace(rec_name='Solutema'), + type='out', + ncf_number_modified=None, + ncf_type=None, + ncf_sequence=None, + payment_method=None, + revenue_type=None, + isr_withholding_type=None) + + Invoice._ncf_prepare_debit_note_from_origin(origin, debit_note) + finally: + Invoice._ncf_find_active_sequence = original_find_active_sequence + Invoice._ncf_electronic_invoicing_enabled = original_enabled + + self.assertEqual(debit_note.ncf_number_modified, 'B0100000001') + self.assertEqual(debit_note.ncf_type, '33') + self.assertEqual(debit_note.ncf_sequence, electronic_sequence) + + def test_debit_note_preparation_falls_back_to_physical_sequence(self): + physical_sequence = SimpleNamespace(ncf_type='3') + original_find_active_sequence = Invoice._ncf_find_active_sequence + original_enabled = Invoice._ncf_electronic_invoicing_enabled + + def find_sequence(cls, invoice, ncf_code): + return physical_sequence if ncf_code == '3' else None + + Invoice._ncf_find_active_sequence = classmethod(find_sequence) + Invoice._ncf_electronic_invoicing_enabled = classmethod( + lambda cls: True) + try: + origin = SimpleNamespace( + ncf_number='B0100000001', + ncf_type='1', + payment_method='04', + revenue_type='01', + isr_withholding_type=None) + debit_note = SimpleNamespace( + company=SimpleNamespace(rec_name='Solutema'), + type='out', + ncf_number_modified=None, + ncf_type=None, + ncf_sequence=None, + payment_method=None, + revenue_type=None, + isr_withholding_type=None) + + Invoice._ncf_prepare_debit_note_from_origin(origin, debit_note) + finally: + Invoice._ncf_find_active_sequence = original_find_active_sequence + Invoice._ncf_electronic_invoicing_enabled = original_enabled + + self.assertEqual(debit_note.ncf_number_modified, 'B0100000001') + self.assertEqual(debit_note.ncf_type, '3') + self.assertEqual(debit_note.ncf_sequence, physical_sequence) + + def test_credit_note_preparation_uses_physical_for_b_origin(self): + electronic_sequence = SimpleNamespace(ncf_type='34') + physical_sequence = SimpleNamespace(ncf_type='4') + original_find_active_sequence = Invoice._ncf_find_active_sequence + original_enabled = Invoice._ncf_electronic_invoicing_enabled + + def find_sequence(cls, invoice, ncf_code): + if ncf_code == '34': + return electronic_sequence + if ncf_code == '4': + return physical_sequence + return None + + Invoice._ncf_find_active_sequence = classmethod(find_sequence) + Invoice._ncf_electronic_invoicing_enabled = classmethod( + lambda cls: True) + try: + origin = SimpleNamespace( + ncf_number='B0100000001', + ncf_type='1') + credit_note = SimpleNamespace( + company=SimpleNamespace(rec_name='Solutema'), + type='out', + ncf_number_modified=None, + ncf_type=None, + ncf_sequence=None, + payment_method=None, + revenue_type=None) + + Invoice._ncf_prepare_credit_note_from_origin(origin, credit_note) + finally: + Invoice._ncf_find_active_sequence = original_find_active_sequence + Invoice._ncf_electronic_invoicing_enabled = original_enabled + + self.assertEqual(credit_note.ncf_number_modified, 'B0100000001') + self.assertEqual(credit_note.ncf_type, '4') + self.assertEqual(credit_note.ncf_sequence, physical_sequence) + self.assertEqual(credit_note.payment_method, '06') + + def test_modified_ncf_validation_applies_to_debit_notes(self): + debit_note = SimpleNamespace( + ncf_type='3', + ncf_number_modified='B0100000001', + type='out') + + Invoice.check_ncf_number_modified(debit_note) + + def test_fiscal_classification_validation_order_for_customer_invoice(self): + calls = [] + invoice = SimpleNamespace( + type='out', + check_revenue_type=lambda: calls.append('revenue_type'), + check_expense_type=lambda: calls.append('expense_type'), + check_isr_withholding_type=lambda: calls.append( + 'isr_withholding_type'), + check_payment_method=lambda: calls.append('payment_method')) + + Invoice._ncf_check_fiscal_classification(invoice) + + self.assertEqual(calls, [ + 'revenue_type', + 'isr_withholding_type', + 'payment_method', + ]) + + def test_fiscal_classification_validation_order_for_supplier_invoice(self): + calls = [] + invoice = SimpleNamespace( + type='in', + check_revenue_type=lambda: calls.append('revenue_type'), + check_expense_type=lambda: calls.append('expense_type'), + check_isr_withholding_type=lambda: calls.append( + 'isr_withholding_type'), + check_payment_method=lambda: calls.append('payment_method')) + + Invoice._ncf_check_fiscal_classification(invoice) + + self.assertEqual(calls, [ + 'expense_type', + 'isr_withholding_type', + 'payment_method', + ]) diff --git a/tests/test_sequence_helpers.py b/tests/test_sequence_helpers.py new file mode 100644 index 0000000..d99040c --- /dev/null +++ b/tests/test_sequence_helpers.py @@ -0,0 +1,94 @@ +from types import SimpleNamespace +import inspect +import unittest + +from trytond.modules.ncf_manager.ncf_manager import ( + NCFManager, NCFManagerSequences) +from trytond.modules.ncf_manager.sequence import Sequence +from trytond.modules.ncf_manager.importer import ( + normalize_dgii_row, parse_dgii_authorizations) +from trytond.modules.ncf_manager.invoice import Invoice + + +class NcfManagerUnitTestCase(unittest.TestCase): + + HEADERS = ( + 'NUM_SOL,NUM_AUTOR,FECHA_AUTOR,COMP,OBSERVACIONES,NUMERO_DESDE,' + 'NUMERO_HASTA,CANTIDAD,CODTIPO,FECHA_SOLICITUD,ESTATUS,' + 'CANTIDAD_SOLICITADA,TIPO_USO,RNC_IMPRENTA,IMPRENTA,' + 'CANTIDAD_APROBADA,FECHA_VIGENCIA,DETALLE_LOG') + + ROW = ( + '6009912073,6005423851,07/08/2026 13:45:02,CRÉDITO ELECTRÓNICO,' + 'SOLUTEMA SRL,E310000000001,E310000000100,,31,' + '07/08/2026 13:36:23,APROBADA,1000,ELECTRÓNICA,,,100,' + '31/12/2027 0:00:00,Aviso, con comas') + + def test_manager_defaults_and_rec_name(self): + self.assertEqual(NCFManager.default_state(), 'draft') + manager = SimpleNamespace() + manager.id = 42 + manager.company = SimpleNamespace(rec_name='ACME') + manager.app_number = 'APP001' + self.assertEqual(NCFManager.get_rec_name(manager, 'name'), 'ACME - APP001') + + def test_sequence_defaults_and_rec_name(self): + self.assertEqual(NCFManagerSequences.default_state(), 'draft') + sequence = SimpleNamespace() + sequence.ncf_type_string = 'Factura de Credito Fiscal - B01' + self.assertEqual( + NCFManagerSequences.get_rec_name(sequence, 'name'), + 'Factura de Credito Fiscal ') + + def test_ir_sequence_on_change_values_for_ncf_type(self): + sequence = SimpleNamespace() + sequence.sequence_type = SimpleNamespace(name='Factura de Consumo') + self.assertEqual(Sequence.on_change_with_prefix(sequence), 'B02') + self.assertEqual(Sequence.on_change_with_padding(sequence), 8) + self.assertEqual(Sequence.on_change_with_name(sequence), 'Factura de Consumo') + + def test_ir_sequence_quantities(self): + sequence = SimpleNamespace() + sequence.from_number = 10 + sequence.until_number = 20 + sequence.number_next = 12 + self.assertEqual(Sequence.on_change_with_approved_qty(sequence), 11) + self.assertEqual(Sequence.on_change_with_remaining_qty(sequence), 9) + + def test_unknown_ncf_type_has_empty_sequence_defaults(self): + sequence = SimpleNamespace() + sequence.sequence_type = SimpleNamespace(name='Unknown') + self.assertIsNone(Sequence.on_change_with_prefix(sequence)) + self.assertEqual(Sequence.on_change_with_padding(sequence), 0) + + def test_decomposed_electronic_sequence_name_is_supported(self): + sequence = SimpleNamespace() + sequence.sequence_type = SimpleNamespace(name='Compras Electro\u0301nico') + self.assertEqual(Sequence.on_change_with_prefix(sequence), 'E41') + self.assertEqual(Sequence.on_change_with_padding(sequence), 10) + + def test_amount_searcher_filters_the_requested_product_type(self): + source = inspect.getsource( + Invoice._search_amount_invoiced_by_product_type) + self.assertIn('template.type == product_type', source) + self.assertIn("line.type == 'line'", source) + + def test_csv_parser_preserves_unquoted_detail(self): + source_format, rows = parse_dgii_authorizations( + f'{self.HEADERS}\r\n{self.ROW}\r\n'.encode()) + self.assertEqual(source_format, 'csv') + self.assertEqual(rows[0]['NUM_AUTOR'], '6005423851') + self.assertEqual(rows[0]['DETALLE_LOG'], 'Aviso, con comas') + normalized = normalize_dgii_row(rows[0]) + self.assertEqual(normalized['from_number'], 1) + self.assertEqual(normalized['until_number'], 100) + + def test_html_xls_parser(self): + cells = ''.join(f'{header}' + for header in self.HEADERS.split(',')) + values = self.ROW.split(',', len(self.HEADERS.split(',')) - 1) + row = ''.join(f'{value}' for value in values) + source_format, rows = parse_dgii_authorizations( + f'
{cells}{row}
'.encode()) + self.assertEqual(source_format, 'xls_html') + self.assertEqual(rows[0]['CODTIPO'], '31') diff --git a/tox.ini b/tox.ini index 0bf424f..b6f8304 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = {py37,py38,py39,py310}-{sqlite,postgresql} +envlist = {py311,py312,py313}-{sqlite,postgresql} [testenv] extras = test diff --git a/tryton.cfg b/tryton.cfg index 1d1a889..a75d4c5 100644 --- a/tryton.cfg +++ b/tryton.cfg @@ -1,11 +1,16 @@ [tryton] -version=7.0.2 +version=7.0.3 depends: + account_do account_invoice_do + account_credit_note + account_debit_note xml: sequence.xml configuration.xml ncf_manager.xml + importer.xml invoice.xml - party.xml + party.xml + user.xml message.xml diff --git a/user.py b/user.py new file mode 100644 index 0000000..77de8e4 --- /dev/null +++ b/user.py @@ -0,0 +1,17 @@ +from trytond.model import fields +from trytond.pool import PoolMeta + + +class User(metaclass=PoolMeta): + __name__ = 'res.user' + + digital_signature = fields.Binary( + 'Digital Signature', help='Signature image used on invoice reports.') + + # Alias used by invoice.fodt template + z_digital_signature = fields.Function( + fields.Binary('Digital Signature'), + 'get_z_digital_signature') + + def get_z_digital_signature(self, name): + return self.digital_signature diff --git a/user.xml b/user.xml new file mode 100644 index 0000000..954c73f --- /dev/null +++ b/user.xml @@ -0,0 +1,10 @@ + + + + + res.user + + user_form + + + diff --git a/view/invoice_form.xml b/view/invoice_form.xml index 4e69449..d17c2e0 100755 --- a/view/invoice_form.xml +++ b/view/invoice_form.xml @@ -4,6 +4,8 @@ this repository contains the full copyright notices and license terms. --> + + @@ -24,19 +26,29 @@ this repository contains the full copyright notices and license terms. --> - - diff --git a/view/invoice_tree.xml b/view/invoice_tree.xml index 379bef7..27385d1 100755 --- a/view/invoice_tree.xml +++ b/view/invoice_tree.xml @@ -9,4 +9,14 @@ this repository contains the full copyright notices and license terms. --> + + + + + + + + \ No newline at end of file diff --git a/view/ncf_import_start_form.xml b/view/ncf_import_start_form.xml new file mode 100644 index 0000000..34cd798 --- /dev/null +++ b/view/ncf_import_start_form.xml @@ -0,0 +1,16 @@ + + +
+