Conversation
Refactors tax total calculation to sum values based on rate with taxes multiplied by quantity, ensuring more accurate tax totals. Updates relevant field refreshes and changes the data type of the tax rate field to currency for better monetary handling.
Enhances user experience by auto-formatting and validating Brazilian postal codes (CEP) and automatically fetching address details using ViaCEP API. Reduces manual data entry and potential errors for delivery address fields. Updates type definitions for improved field clarity and consistency.
Introduces new whitelisted API functions to create NFe invoices via an external Go service and to check their statuses. Improves error handling, user feedback, and integrates invoice updates with API responses. Deprecates the previous internal invoice creation method in favor of a more robust, service-based approach.
Introduces buttons for creating NFe invoices, checking their status, and viewing the generated PDF directly from the invoice form. Enhances user workflow by enabling quick access to key NFe actions based on the document's state.
- Added `create_invoice`, `get_invoice_details`, `update_invoice_status`, and `bulk_create_invoices` endpoints in `api.py`. - Developed a complete test suite in `test_api.py` with 27 test cases covering various scenarios including basic API functionality and tax calculations. - Updated frontend integration to use `process_invoice` method for creating NFe invoices. - Created detailed README documentation outlining API usage, endpoints, authentication, and test instructions. - Initialized `package-lock.json` for package management.
- Added complete workflow system for Invoices with states: Created, Processing, Contingency, Submitted, Rejected, Cancelled, and Unused. - Defined workflow transitions and actions for managing invoice lifecycle. - Created fixtures for workflow states, actions, and the workflow itself to be loaded during app installation. - Enhanced invoice tests to include real item creation with NCM codes and detailed item data. - Updated test setup to ensure clean state and isolation for invoice tests. - Improved invoice item structure to include item_code, item_name, description, quantity, rate, amount, and NCM. - Verified successful execution of all tests with comprehensive coverage of invoice scenarios.
- Translate all field labels in Tax DocType from Portuguese to English - Translate all field labels in Invoices DocType from Portuguese to English - Translate select options for operation types, freight modalities, tax statuses - Update ICMS, IPI, COFINS, and PIS related field labels - Translate address, client, and product section labels - Keep technical terms like ICMS, IPI, FCP, DIFAL, CST, NCM as-is - Improve consistency and internationalization support
- Translate all ICMS CST/CSOSN options (tax codes 00-900) - Translate all IPI CST options (entry/exit codes) - Translate all COFINS CST options (operation types) - Translate all PIS CST options (operation and acquisition types) - Maintain tax code numbers for compliance - Complete internationalization of tax-related fields
Breaking change: Database fieldnames internationalized Tax DocType fieldname translations: - aliq_icms → icms_rate - aliq_fcp → fcp_rate - calcular_automaticamente_* → calculate_automatically_* - adiciona_* → add_* - aplicar_aliq_auto_icms → apply_auto_rate_icms - substituição_tributária_section → tax_substitution_section - credito_trib → credit_trib - reducao_trib → reduction_trib - partilha_icms → icms_sharing - valor_da_base_de_calculo_* → *_calc_base_value_* - aliq_do_icms_* → icms_rate_* - aliq_fundo_pobre → poverty_fund_rate - base_de_calculo_* → *_calculation_base - valor_do_* → *_value - cod_enquadramento → framework_code - aliquota_* → *_rate Invoices DocType fieldname translations: - contribuinte_icms → icms_taxpayer - inscricao_estadual → state_registration - produto_section → product_section - dados_adicionais_section → additional_data_section - totais_section → totals_section - endereço_section → address_section - eventos_sefaz_section → sefaz_events_section Updated all Python and JavaScript references to use new fieldnames.
- Update fieldname from invoices_table to invoice_items_table in Invoices DocType - Update all Python references in invoices.py - Update all JavaScript references in invoices.js - Improve clarity: table contains invoice items, not invoices
- Add is_template checkbox and template_name fields to tax.json - Add validation in tax.py: template_name required when is_template=1, must be empty otherwise - Update invoices.json tax_template field with custom query - Add get_tax_template_query function to filter only templates (is_template=1) - Query displays template_name in search results
- Use Portuguese parameter names (contribuinte_icms, inscricao_estadual) that match function signature - Map to English DocType field names (icms_taxpayer, state_registration) - Resolves undefined variable errors
- Add 'Troca em Garantia' (Exchange under warranty) template - Add 'Reparo em Garantia' (Repair under warranty) template - Both templates use real Brazilian tax codes (CST) for warranty operations - ICMS and IPI set to calculate automatically - All tax rates set to 0% as per warranty operation rules
- Remessa em Garantia: MUST have ICMS/IPI highlighted with rates * CST ICMS 00 (Fully taxed) at 18% * CST IPI 50 (Exit taxed) at 10% * PIS/COFINS CST 01 with standard rates (1.65%/7.6%) * Includes all expenses in ICMS calculation base - Remessa para Conserto: WITHOUT tax highlights (non-taxed) * CST ICMS 41 (Not taxed) * CST IPI 53 (Exit non-taxed) * PIS/COFINS CST 49 (Other operations) at 0% * CFOP 5.915 operation Warranty shipments differ from repairs: warranty must charge taxes at original operation rates, while repair shipments are non-taxed.
- Add validate_automatic_calculation method in tax.py - Enforce: if calculate_automatically is enabled, rate MUST be 0 - Apply validation to ICMS, IPI, COFINS, and PIS Update tax templates: - Remessa em Garantia: set ICMS/IPI rates to 0 (will be calculated) - Remessa para Conserto: disable calculate_automatically for all taxes since they are non-taxed operations This ensures correct behavior: - Auto-calculation only when rate is 0 (system calculates) - Manual rates only when auto-calculation is disabled
Add invoice items lock: - Prevent changes to invoice_items_table at Processing status and forward - Only allow modifications in Draft or Created status - Check for item additions, removals, and modifications Implement automatic tax calculation: - Calculate ICMS automatically when tax template requires it - Calculate IPI automatically based on NCM codes - Only run calculations in Draft or Created status ICMS Calculation: - Account for interstate vs same-state operations - Hardcoded rates for now (18% same state, 12% interstate) - Include freight, insurance, and other expenses in base if configured - TODO: Integrate with external API (IBPT, PlugNotas, NFe.io, BrasilAPI) IPI Calculation: - Hardcoded rates by NCM: * 85044090 (INVERSOR): 9.75% * 85049090 (INSUMOS): 6.50% * 85437099 (SMART ENERGY): 6.50% - Calculate per item based on NCM code - Support both formatted (8504.40.90) and raw (85044090) NCM formats
- Create nfeio.py module for NFe.io API integration - Move calculate_taxes_with_nfeio logic to nfeio.calculate_taxes() - Move _calculate_taxes_fallback logic to nfeio.calculate_taxes_fallback() - Organize helper functions: _get_company_state, _prepare_items_for_api, etc. - Add comprehensive documentation and API references - Clean up invoices.py by separating concerns Benefits: - Better code organization and maintainability - Easier to test tax calculation logic independently - Cleaner invoices.py focused on invoice business logic - NFe.io integration centralized in one module API Configuration: - Set 'nfeio_api_key' in site_config.json - Set 'nfeio_company_id' in site_config.json
- Add TestInvoiceCreationWithTaxCalculation test class - Test automatic ICMS calculation with NFe.io API integration - Test automatic IPI calculation with NFe.io API integration - Create complete test setup with items, serial numbers, carriers, and tax templates - Use proper English values for all select fields (operation_type, client_type, freight_modality, contribuinte_icms) - Fix cleanup test to only delete invoices with test tokens - Add phone number country codes (+55 for Brazil) - Verify invoice creation and tax template linkage Tests validate: - Invoice creation with Growatt brand - Complete customer and delivery information - Tax template application - Invoice items with serial numbers - Automatic tax calculation preparation (requires NFe.io API for full calculation) Note: Tax values will be calculated when NFe.io API credentials are configured in site_config.json
- Set COFINS rate to 7.6% (non-cumulative regime) - Set PIS rate to 1.65% (non-cumulative regime) - Keep automatic calculation disabled (manual rates) - These taxes are not calculated by NFe.io API, so using standard rates
- Remove manual specification of item_code, item_name, ncm, description, quantity, rate, amount - Only pass serial_no in invoice_items_table - Let the system auto-fill item details based on serial number - Cleaner test code following ERP best practices
The ItemInvoice controller has no auto-fill logic, so all fields must be populated manually from the serial number's item data. This includes item_code, item_name, ncm, quantity, rate, and amount.
- Added auto-fill logic in Invoice.process_invoice_items() to populate item fields from serial number - Auto-fills: item_code, item_name, rate, ncm, description, amount from serial number -> item - Enforces quantity = 1 when serial_number is provided (serial numbers are unique) - Validation throws error if quantity != 1 when serial_number exists - Added amount field (Currency, read-only, auto-calculated as rate × quantity) - Added description field (fetch from item_code.description) - Updated NCM field to fetch from item_code.ncm (not ncm_code) - Fixed test data creation to use 'ncm' field name (matches ERPNext Item schema) - Simplified test invoice creation to only pass serial_number, system auto-fills all other fields - All tests passing with proper auto-fill validation
…ulation test - Merged test_create_invoice_with_automatic_icms_calculation and test_create_invoice_with_automatic_ipi_calculation - New test: test_create_invoice_with_automatic_tax_calculation validates both ICMS and IPI - Reduced test count from 4 to 3 tests - Validates both tax types in a single invoice creation - All assertions for ICMS and IPI calculation still present
Two-stage auto-fill strategy: - Stage 1: serial_number → item_code - Stage 2: item_code → all other fields (item_name, rate, ncm, description, amount) Benefits: - Works with serial_number: serial_number → item_code → other fields - Works without serial_number: item_code → other fields - Quantity can be > 1 when no serial_number provided - Quantity enforced to 1 when serial_number is provided Changes: - Updated Invoice.process_invoice_items() with two-stage logic - Updated ItemInvoice._auto_fill_from_serial_number() and _auto_fill_from_item() - Added test_create_invoice_with_item_code_only() to validate item_code-only use case - All 4 tests passing
- Add helper functions: - generate_random_address(): generates random Brazilian address and phone data - print_invoice_details(): standardized invoice details display - Add TestInvoiceProcessing class with 2 tests: - test_create_invoice_processing_with_2_items: validates 2-item invoice with serial numbers - test_create_invoice_processing_with_3_items: validates 3-item invoice (6 units) with item codes - Comprehensive validation: - Auto-fill functionality for multiple items - Total calculations (product value, freight, insurance, discount) - Weight calculations (gross and net) - Quantity validation for serial number vs item code scenarios - Phone format updated to +55-XXXXXXXXXXX pattern - All 6 tests passing (2 Created, 2 Processing, 1 item_code_only, 1 summary)
- Add validate_responsible() method in Invoice DocType - Validates Responsible (delivery_supervisor) field is mandatory for Created, Processing, Submitted, Rejected, Contingency, and Unused statuses - Prevents invoices from moving to these statuses without a responsible person - Prevents clearing the field once set in these statuses - Add delivery_supervisor to all test invoices - Updated test_create_invoice_with_automatic_tax_calculation - Updated test_create_invoice_with_item_code_only - Updated test_create_invoice_processing_with_2_items - Updated test_create_invoice_processing_with_3_items - Add TestResponsibleValidation test class with 2 tests: - test_invoice_requires_responsible_for_created_status: validates invoice cannot move to Created status without responsible field - test_invoice_cannot_clear_responsible_after_created: validates responsible field cannot be cleared once invoice is in Created status - All 8 tests passing - Ensures accountability by requiring a responsible person for all active invoices
- Replace manually specified address fields with generate_random_address() in: - test_create_invoice_with_automatic_tax_calculation - test_create_invoice_with_item_code_only - test_invoice_requires_responsible_for_created_status - test_invoice_cannot_clear_responsible_after_created - Eliminates code duplication - Ensures consistent phone number format (+55-XX9XXXXXXXX) - Makes tests more maintainable and less error-prone
- Add unit field to Item Invoice child table DocType - Configure unit field to fetch from item_code.stock_uom - Update process_invoice_items() to auto-fill unit from Item.stock_uom - Unit field auto-populates when item_code is selected
- Add operation_nature field (Data) for operation description (e.g., 'VENDA DE MERCADORIA') - Change operation_type field from Data to Select with Incoming/Outgoing options - Add operation_nature to Tax doctype template (mandatory for templates) - Update operation_type in Tax doctype to Select with direction options - Modify set_operation_type_from_template() to fetch operation_nature from template - Update _build_invoice_data_from_doc() to use separate fields correctly Breaking Change: - operation_type now represents direction (Incoming/Outgoing) instead of nature - operation_nature now holds the operation description text
- Add operation_type and operation_nature to test invoice creation - Set operation_type='Outgoing' for test invoices - Set operation_nature='VENDA DE MERCADORIA' for test invoices - Update create_invoice() API to accept operation_nature parameter
- Add cfop_interstate field (Int) for interstate operations - Add cfop_intrastate field (Int) for intrastate operations - Make template fields mandatory when is_template=1: - template_name - operation_nature (already mandatory) - cfop_interstate - cfop_intrastate - operation_type - Both CFOP fields visible only when is_template=1
- Add is_test_invoice checkbox field in Internal tab - Default value: 0 (unchecked) - Used to determine which NFe.io config to use for API operations
- Add company_state field (Select) with all Brazilian state codes - Positioned between company_name and company_id - Required for determining intrastate vs interstate operations - Used in CFOP calculation logic
- Update _get_nfeio_config() in nfeio.py to filter by is_test_config=0 - Update _get_nfeio_config() in tax.py to filter by is_test_config=0 - Update _get_valid_nfeio_config() in nfeio.py to filter by is_test_config=0 - All functions now order by usage_priority DESC - Remove unnecessary secondary sort by name - Test code filters by is_test_config=1 to use test configs only This ensures: - Production code only uses production configs (is_test_config=0) - Test code only uses test configs (is_test_config=1) - Highest priority config is always selected within each category
- Calculate CFOP based on company state vs delivery state comparison - Use cfop_intrastate when states match (same state operation) - Use cfop_interstate when states differ (interstate operation) - Fetch NFe.io config filtered by is_test_invoice flag - Validate CFOP is defined before invoice issuance - Provide helpful error message if CFOP missing CFOP (Código Fiscal de Operações e Prestações) is required for Brazilian fiscal invoices and varies based on operation location.
- Add operation_nature field to both tax templates - Add cfop_intrastate and cfop_interstate to both templates - 'Remessa em Garantia': 5949 (intrastate) / 6949 (interstate) - 'Remessa para Conserto': 5915 (intrastate) / 6915 (interstate) CFOP codes based on Brazilian fiscal legislation: - 5xxx: Operations within same state - 6xxx: Operations between different states
- Remove 'VENDA' default fallback for operation_nature field - operation_nature is now mandatory and should always be provided - This ensures proper validation and prevents silent defaults
- Update imports to use _test suffix versions: - get_serial_no_array_test - tax_array_test - carriers_test - Ensures test isolation and prevents conflicts with production data
Breaking change protection and backward compatibility: 1. CFOP Field Validation: - Validate company_state exists in NFe.io config before CFOP calculation - Validate cfop_intrastate and cfop_interstate exist in Tax template - Provide clear error messages guiding users to fix config issues 2. Backward Compatibility for is_test_config: - Treat None/empty is_test_config as production config (0) - Prevents breaking existing NFe.io configs without is_test_config field - Production queries now accept both is_test_config=0 and None/empty 3. Clear Error Messages: - Explains what field is missing and where to fix it - Helps users migrate existing data without confusion This prevents silent failures and data corruption while maintaining backward compatibility with existing configurations.
- Move get_nfeio_config() to utils.py to avoid circular imports - Remove tax_template_name parameter from calculate_invoice_taxes() - Tax template now read from invoice document's tax_template field - Simplify calculate_taxes() function signature - Remove _get_nfeio_config() and _get_valid_nfeio_config() duplicates - Update all callers to use utils.get_nfeio_config() - Update test files to match new function signatures
…detection - Add item-level tax fields to Item Invoice: * Tax rates: icms_rate, ipi_rate, ii_rate, pis_rate, cofins_rate (Percent) * Tax values: icms_value, ipi_value, ii_value, pis_value, cofins_value (Currency) * Rates editable only when no tax_template selected * Values are read-only (calculated) - Add ii_value field to Product Invoice doctype for Import Tax totals - Implement automatic tax calculation workflow: * Runs on save for Non Processed status with tax_template selected * Smart change detection using MD5 hashing to prevent unnecessary API calls * Calculates taxes via NFe.io API and applies to individual items * Aggregates item-level taxes to invoice-level totals * Comprehensive error logging without blocking save - Refactor NFe.io tax API endpoints: * Rename calculate_invoice_taxes() to calculate_product_invoice_taxes() * Change from document-based to API parameter-based (issuer, recipient, items) * Remove build_product_invoice_from_invoice() (unused) - Refactor tax calculation module: * New standalone calculate() function for direct API calls * Keep calculate_taxes() as backward-compatible wrapper * Remove fallback logic (use_fallback parameter removed) - Update tax validation for Processing status: * Validate all items have 5 required tax values (ICMS, IPI, II, PIS, COFINS) * Provide detailed error messages showing which items are missing taxes * Block transition to Processing if any item lacks tax calculations - Update invoice total calculations: * Include ii_value in total_of_taxes calculation * Sum item-level tax values to set invoice-level totals
- Use **dict unpacking pattern for all test data creation helpers - Apply to create_test_item, create_test_serial_no, create_test_carrier, create_test_tax_template - Improves code readability and maintainability - Follows DRY principles consistently across test setup
- Remove operation_type field from Tax doctype (should be set at Product Invoice level) - Translate substituição_tributária_section to tax_substitution_section - Clean up test data removing operation_type references from tax templates
…thod - Add cfop field to Item Invoice (read-only when tax_template is set) - Update CFOP logic to use item-level CFOP or fall back to tax template - Remove set_operation_type_from_template() method (operation_nature auto-fetched via fetch_from) - Update test to use tax_template for automatic operation_nature and CFOP - Fix test data: correct CST values for IPI, COFINS, and PIS - Fix create_test_tax_template to use correct doctype name 'Tax'
- Add reqd=1 to company_state field in NFeIO doctype - Ensures all NFe.io configurations have company state for CFOP calculation - Prevents configuration errors during invoice processing
…ion selection - Fix test_helpers.py to set is_test_invoice=1 for test invoices instead of 0 - Add is_test_invoice parameter to get_product_invoice_pdf() and get_product_invoice_xml() functions - Update webhook handlers to properly pass is_test_invoice flag from invoice documents - Add is_test_invoice parameter to _get_events_from_invoice() for consistent config selection - Add comprehensive debug logging for API authentication and configuration selection - Update utils.get_nfeio_config() with enhanced debug output This ensures that: - Test invoices properly use test NFeIO configurations (is_test_config=1) - Production invoices use production configurations (is_test_config=0) - All API calls (issue, PDF, XML, events) use consistent configuration - Real API tests pass with proper test environment setup Fixes issue where invoices created via tests were incorrectly using production configs with placeholder tokens, causing 'Invalid API token' authentication errors.
- Add Link field to select NFe.io configuration - Field filters based on is_test_invoice flag - Ordered by usage_priority DESC - Read-only after Non Processed status
- Add get_nfeio_config_query() to filter configs dynamically - Add validate_nfeio_config() to enforce field is mandatory after Non Processed - Update create_invoice() to accept and set nfeio_config parameter - Update move_to_processing() to use selected nfeio_config
- Add nfeio_config_name parameter to all API methods - Remove fallback to auto-fetch config, return error instead - Ensures explicit config selection is enforced - Updated methods: issue_product_invoice, get_product_invoice_by_id, query_product_invoice_events, get_product_invoice_pdf, get_product_invoice_xml
- Retrieve nfeio_config from Product Invoice document - Pass config through all webhook helper functions - Updated: handle_invoice_status_update, handle_invoice_issued_status, handle_invoice_error_status, _get_events_from_invoice, _get_error_from_events
- Auto-select test config in create_test_invoice_with_token() - Pass nfeio_config explicitly in test_001_create_and_issue - Ensures tests use correct NFe.io configuration
- Add mandatory_depends_on to state_registration field based on icms_taxpayer - Mandatory when icms_taxpayer is 'Taxpayer' (Contribuinte do ICMS) - Optional when icms_taxpayer is 'NonTaxpayer' (Não Contribuinte) - Optional when icms_taxpayer is 'Exempt' (Isento) - Add validate_state_registration method to prevent IE field from being filled when icms_taxpayer is 'Exempt' (Isento) - Exempt taxpayers are dispensed from state registration by SEFAZ - Throws ValidationError with clear message if IE is filled for Exempt status Business rules implemented: - Taxpayer: ALWAYS has IE (mandatory) - Exempt: NEVER has IE (validation blocks it) - NonTaxpayer: MAY have IE (optional, depends on SEFAZ and operation)
- Add _strip_query_params helper function to remove query strings from URLs - Apply URL cleanup to invoice_pdf_url and invoice_xml_url fields - Ensures consistent URL storage without temporary tokens or parameters
- Set calculate_automatically_cofins to 1 in 'Remessa em Garantia' template - Set calculate_automatically_pis to 1 in 'Remessa em Garantia' template - Ensures consistent tax calculation behavior in test scenarios
- Remove mandatory_depends_on from client_id_number field - Field is already marked as required (reqd: 1) for all cases - Simplifies validation logic and ensures CPF/CNPJ is always collected
- Add placeholder test_product_invoice.py for basic unit tests - Improve test documentation in test_product_invoice_real_api.py - Add comprehensive workflow description for test_001_create_and_issue - Improve code formatting and consistency - Clarify operation types and expected results in test docstrings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.