=== NFER Emissor Fiscal ===
Contributors: nfermetecnologiafiscal, nfertecnologia
Tags: nfe, nfse, invoice, fiscal, electronic invoice, woocommerce, ncm, danfe, split fiscal, difal, b2b, icms-st, brazilian invoice
Requires at least: 6.0
Tested up to: 7.1
Requires PHP: 7.4
Stable tag: 1.2.5
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Automated Brazilian electronic invoice (NF-e and NFS-e) issuer for WooCommerce with hybrid fiscal split, e-books, B2B/B2C detection and automated cancellation.

== Description ==

**NFER Emissor Fiscal** seamlessly connects your WooCommerce store to the **NFER** fiscal intelligence cloud platform (https://nfer.me/?utm_source=woocommerce&utm_medium=plugin). Engineered under rigorous software standards and fully compatible with **WooCommerce HPOS (High-Performance Order Storage)**, the plugin eliminates complex manual REST API setups and unifies billing for physical products, digital goods, courses, services, and subscription clubs.

= National NFS-e (Service Invoices) Coverage =

NFER provides cloud infrastructure connected to the Brazilian Federal Revenue National Data Environment (ADN / Serpro) and municipal tax authorities:

* **MEI Coverage:** **100% of all 5,571 Brazilian municipalities** supported for Individual Microentrepreneurs (MEI) in compliance with federal legislation.
* **General Coverage (Simples Nacional, ME, EPP, Lucro Presumido, and Lucro Real):** **Over 2,875 active municipalities** with unified DPS standard emission and integrated municipal webservices.
* **Real-time City Status Query:** Check the status of any Brazilian city on the [NFS-e Integrated Municipalities](https://nfer.me/nfse/municipios-integrados?utm_source=woocommerce&utm_medium=plugin) directory.
* **Standardized Fields:** Full support for National Tax Code (`cTribNac`), itemized service descriptions, and municipal tax withholdings.

= Automated Cancellation & Smart Return (Devolução) =

* **Status-triggered Cancellation:** When an order is changed to `Cancelled` or `Refunded` in WooCommerce, the plugin automatically requests invoice cancellation via NFER.
* **24-Hour SEFAZ Smart Window:**
  * If the NF-e was authorized within the last 24 hours, an automated cancellation event (Evento 110111) is transmitted directly to SEFAZ.
  * If the legal 24-hour deadline has expired, NFER automatically issues a Return / Reversal NF-e (CFOP 1202) referencing the original invoice key, avoiding tax penalties and reversing ICMS/PIS/COFINS.
* **Manual Cancellation on Order Screen:** Admin button in order metabox with mandatory audited justification (15+ characters).

= Fiscal Intelligence for B2B and B2C Sales =

NFER automates Brazilian tax compliance complexities:

* **B2C Operations (Final Consumer):** Consumer sales with automated Final Consumer flag (`indFinal = 1`).
* **B2B Operations (Interstate CNPJ to CNPJ):** Corporate sales for resale or industrial manufacturing (`indFinal = 0`), handling DIFAL exemptions and applying Tax Substitution rules (ICMS-ST / MVA) and State Registration (IE) status.
* **Interstate DIFAL Sharing (EC 87/2015):** Automatic calculation of interstate tax differentials without maintaining manual tax tables.
* **Broad Tax Regime Compatibility:** Supports companies under **Simples Nacional** (CSOSN), **Lucro Presumido**, and **Lucro Real** (CST).

= Key Features =

* **Digital E-books Intelligence (NCM 4901):** Automatic recognition of digital books with NF-e (Model 55) emission under constitutional ICMS tax immunity (Art. 150 CF), even when set as Virtual in WooCommerce.
* **Hybrid Fiscal Split (Exclusive):** Dual simultaneous billing for a single order (e.g. 60% NF-e Merchandise/E-book + 40% NFS-e Service/Course), enabling legal tax optimization for digital creators.
* **Fiscal Data Product Tab:** NCM (8 digits), CEST (7 digits), Merchandise Fiscal Origin (0 to 8), Standardized Unit of Measurement (UN, PC, KG, etc.), and SPED Item Type. Supports simple and variable products with parent fallback.
* **Complete Brazilian Checkout Fields:** Injects CPF, CNPJ, Company Name (Razão Social), State Registration (Inscrição Estadual with Isento toggle), Address Number, and Neighborhood with dynamic input masks.
* **B2B Purchase Purpose Dropdown:** Lets corporate buyers select whether the purchase is for End Consumption, Resale, or Industrialization.
* **Compatibility with Brazilian Market Plugins:** Works out-of-the-box independently or seamlessly alongside *Brazilian Market on WooCommerce* (Claudio Sanches) without duplicating fields.
* **One-Click or 100% Automated Emission:** Configure automatic emission upon payment confirmation or issue manually via order actions or quick modal.
* **Instant Access to DANFE, NFS-e PDF & XML:** Direct buttons to download DANFE PDF and authorized XML from order list and customer account page.
* **Automated Customer Email:** Sends DANFE PDF and XML attachments to the buyer automatically upon SEFAZ authorization.

= How to Get Your NFER API Key =

1. Register with a 7-day free trial at https://nfer.me/?utm_source=woocommerce&utm_medium=plugin
2. Set up your company and A1 digital certificate, then navigate to **Settings > API** (https://nfer.me/dashboard/api?utm_source=woocommerce&utm_medium=plugin)
3. Copy your company's API Key and paste it into the plugin settings in WordPress.

= Third-Party Cloud Service Notice =

This plugin connects your WordPress store to the **NFER Cloud Platform** (https://nfer.me/?utm_source=woocommerce&utm_medium=plugin).
An active NFER account (7-day free trial available for new users) and a valid Brazilian A1 Digital Certificate are required to issue legally authorized invoices with SEFAZ and city halls.
* Official Website: https://nfer.me/?utm_source=woocommerce&utm_medium=plugin
* Terms of Service: https://nfer.me/termos?utm_source=woocommerce&utm_medium=plugin
* Privacy Policy: https://nfer.me/privacidade?utm_source=woocommerce&utm_medium=plugin

== Installation ==

1. Upload the plugin files to the `/wp-content/plugins/nfer-emissor-fiscal` directory, or install through the WordPress plugins screen.
2. Activate the plugin through the 'Plugins' screen in WordPress.
3. Navigate to **WooCommerce > Settings > NFER Emissor NF-e**.
4. Enter your **NFER API Key** and choose your environment (Production or Staging/Homologação).
5. Click **Save changes** and then use the **Test Connection** button.
6. Configure fiscal data (NCM, CEST, Origin) in your WooCommerce products.

== Frequently Asked Questions ==

= Do I need to create REST API keys in WooCommerce? =
No. NFER uses a push model: you only need to enter your NFER API Key in the WordPress settings.

= How does interstate shipping tax (DIFAL) work? =
On interstate transactions to non-taxpayer end consumers, NFER automatically calculates and highlights DIFAL according to Constitutional Amendment 87/2015.

= What if I sell to a business buyer for resale (B2B)? =
The buyer selects "Resale / Commercialization" at checkout. The plugin transmits `indFinal = 0` to NFER, applying DIFAL exemption and calculating ICMS-ST / MVA based on destination state and product NCM.

= Does it work with product variations? =
Yes. Each variation can define its own fiscal parameters (NCM, CEST, Origin) or automatically inherit from the parent product if left blank.

= Do I need another plugin for CPF/CNPJ checkout fields? =
Not required. The plugin includes built-in fields for CPF, CNPJ, State Registration, and Brazilian address fields. If *Brazilian Market on WooCommerce* is already installed, NFER automatically maps existing fields to prevent duplicates.

== Screenshots ==

1. General NFER settings in WooCommerce with live connection test.
2. Native Fiscal Data tab on product and variation edit screens.
3. Order list with status badges, quick modal, and DANFE/XML downloads.
4. B2B Purchase Purpose selector at checkout.

== Changelog ==

= 1.1.5 =
* Fiscal Profile & Item Type Transmission: Transmits item type (`tipoItem` - SPED Bloco 0200) from WooCommerce product fiscal settings to NFER API, enabling automatic activation of fiscal profiles (such as own manufacture / industrialization with CFOP 5101/6101).
* Contingency Status Handling: Added support for `nfe.contingencia` status across webhooks and order lists with warning indicators.
* UI & Brand Polish: Updated manual emission buttons to vibrant NFER brand green (`#00C853`) and refined modal link styling.
* Fast Modal Loading: Fiscal details modal now renders immediately from local order metadata without redundant network overhead.

= 1.1.4 =
* Product Fiscal Jump Button Fix: Enhanced the "Preencher Dados Fiscais" shortcut button on product edit screens with native fallback and dedicated admin asset loading, ensuring instant automatic switching to the "Dados Fiscais" tab with smooth scroll, auto-focus, and visual highlight on the NCM input field.

= 1.1.3 =
* Automated Direct Webhook (Zero Config): Automatic transmission of webhookUrl, orderId, and origem in all NF-e and NFS-e payloads, ensuring instant real-time order synchronization without requiring manual webhook registration on the NFER dashboard.
* Isolated Multi-Store Routing: Dispatches SEFAZ authorization events directly to the issuing store, preventing cross-store webhook collisions and 404 errors.
* Settings UI: Updated webhook description clarifying that synchronization is fully automated via API payload.

= 1.1.2 =
* SEFAZ Freight & Shipping Synchronization: Comprehensive support for order freight (valorFrete) and additional fees (valorOutras) with automatic modFrete assignment (0 for freight by recipient/remetente, 9 for no freight) and payment total balancing, resolving SEFAZ rejection error 610 ("A soma dos pagamentos deve ser igual ao valor total da nota").
* Settings Auto-Save on Test Connection: Testing the API connection automatically validates and persists all configuration fields from the NFER tab (API key, environment, document model, split percentages, trigger statuses, order status transitions, NFS-e tax code, and email dispatch) directly into WordPress options.
* Empty API Key Validation: Immediate visual warning and border highlight when testing or saving without an API key.
* WordPress.org Plugin Review Compliance: Full compatibility with WordPress 7.1, complete translators comments for all internationalized strings with placeholders, clean textdomain consistency, and removal of hidden repository files.

= 1.1.1 =
* Full support for invoice cancellation and rebilling: display of cancelled invoices with "Cancelled at SEFAZ" badge, cancelled number (#), access key, and XML download.
* Prominent "Issue New Invoice" button for cancelled orders, enabling rebilling with a new sequential number.
* Detailed fiscal history of cancelled invoices archived in order meta for accounting audit.
* Unlocked re-emission in order metabox and contextual options menu (⋮) after cancellation.
* Visual backend logs for real-time tracking of webhook deliveries.

= 1.1.0 =
* New "Fiscal Data" column in WooCommerce product list: green badge with formatted NCM for configured products and warning badge with direct link for missing NCMs.
* Fiscal modal height optimization: comfortably fits multiple invoices without triggering parent scrollbar.
* Smart re-emission preserving the same sequential invoice number (#) and fiscal series when re-transmitting rejected invoices.
* Detailed rejected invoice card with error reason, access key, and retry options.
* Full isolation for status badge click: rendered as an interactive button with native DOM event interception preventing unwanted navigation to order edit page.

= 1.0.9 =
* Strict separation of recipient data for CPF (Individual) vs CNPJ (Corporate).
* Smart handling of SEFAZ State Registration indicator (indicadorIe 1, 2, or 9).
* Explicit and canonical "environment" parameter ("homologacao" or "producao") in emission payloads.
* Updated sidebar order metabox title to "NFER: Fiscal Technology".

= 1.0.8 =
* Clean flat solid status badges for the "NF-e Status" column in WooCommerce order list.
* Prefix standardization: NF-e Issued, NFS-e Issued, Split Issued, and Return Issued.
* Dynamic icons: document icon for finalized statuses and animated loading spinner for "Processing" status.
* Quick options button with 3-dot icon (⋮) for direct modal opening.

= 1.0.7 =
* Clean modal layout for fiscal documents matching NFER specifications.
* Transparent auto-synchronization with SEFAZ upon opening modal or clicking "View".
* Scrollable invoice list for hybrid orders (NF-e, NFS-e, Return).
* 3-dot quick actions menu: Sync with SEFAZ, Issue Return, and Cancel at SEFAZ.
* Fix for SEFAZ payment method 99 (Other) requirement.
* Webhook support for HTTP development and staging environments.
* Mass batch emission in WooCommerce orders list via Bulk Actions.
* Single-order manual emission in order actions dropdown.

= 1.0.6 =
* Support for Hybrid Fiscal Split (1 Merchandise NF-e + 1 Service NFS-e per order).
* Quick modal for fiscal details and DANFE / XML downloads in order list.

= 1.0.5 =
* State Registration (Inscrição Estadual) checkout field for B2B orders.
* Transparent integration with "Brazilian Market on WooCommerce" plugin.
* Automatic PF / PJ detection at checkout.
* Pre-emission fiscal validations with descriptive error messages.

= 1.0.4 =
* Integration for NFS-e (Municipal Services) in over 2,875 Brazilian cities.
* Support for National Tax Code (cTribNac).
* Automatic mapping of WooCommerce payment methods to SEFAZ codes.

= 1.0.3 =
* Compact fiscal status column in WooCommerce order list.
* Quick "View" action button for instant fiscal document access.
* Detailed SEFAZ rejection error display.

= 1.0.2 =
* Direct SEFAZ cancellation with mandatory 15-character justification.
* Order notes logging with access key and direct document links.
* Full compatibility with WooCommerce HPOS (Custom Order Tables).

= 1.0.1 =
* Variable product support with NCM, CEST, and Origin inheritance.
* Checkout purchase purpose selector (End Consumption vs Resale).
* Live connection test in settings tab.

= 1.0.0 =
* Official release of NFER plugin for WooCommerce.
* Native HPOS support.
* Fiscal Data tab in products and variations.
* Masked checkout fields and B2B/B2C selector.
* Automated or manual 1-click invoice emission.
