=== Invoicing Integration for iFirma and WooCommerce ===
Contributors: devikit
Tags: woocommerce, invoice, ifirma, vat, poland
Requires at least: 5.8
Tested up to: 7.0
Stable tag: 1.0.27
Requires PHP: 7.4
License: GPLv3
License URI: https://www.gnu.org/licenses/gpl-3.0.html

Seamless integration between WooCommerce and iFirma accounting system for Polish businesses.

== Description ==

**Invoicing Integration for iFirma and WooCommerce** connects your WooCommerce store with the iFirma accounting system.

Generate invoices from the order screen, download PDFs, and let customers download documents from My Account. The plugin supports WooCommerce Blocks checkout and HPOS.

https://youtu.be/XJUJdKuv8CA

= Key Features (FREE) =

* **Manual Invoice Generation** - Create invoices directly from WooCommerce order edit screen
* **Customer Synchronization** - Sync customer data with iFirma contractors
* **NIP Field Support** - Add NIP number field to checkout (compatible with nip-field-woocommerce plugin)
* **WooCommerce Blocks Support** - Compatibility with Gutenberg checkout blocks
* **Advanced VAT Mapping** - Map WooCommerce tax classes to iFirma VAT codes/rates (23%, 8%, 5%, zw, 0%)
* **Lump Sum (Ryczałt) Support** - Add lump sum tax rate (ryczałt) to invoice positions (global default + per product/variation)
* **Invoice Download** - Download PDFs directly from WordPress admin
* **Customer Download** - Allow customers to download invoices from My Account → View Order
* **Detailed Logging** - Track API communications for debugging
* **HPOS Compatible** - Full support for WooCommerce High-Performance Order Storage

= PRO Features =

* **Automatic Invoice Generation** - Create invoices automatically on order status change
* **Automatic Proforma Invoices** - Issue proformas automatically for selected statuses
* **Rachunki Support** - Generate non-VAT documents (rachunki) when applicable
* **Email with PDF Attachments** - Send documents to customers as PDF attachments
* **Bulk Operations** - Generate documents and download PDFs for multiple orders with progress tracking
* **GTU / PKWiU / Units** - Product-level fields + global defaults in settings
* **Global Invoice Notes** - Define global invoice notes in settings (supports placeholders)
* **Priority Support** - Direct access to our support team
* **Automatic Updates** - Get new features and fixes automatically

[**Get PRO Version**](https://devikit.pl/produkt/ifirma-woocommerce-pro/)

= Requirements =

* WordPress 5.8 or higher
* WooCommerce 5.0 or higher
* PHP 7.4 or higher
* Active iFirma account with API access

== Installation ==

1. Upload the plugin files to `/wp-content/plugins/invoicing-integration-for-ifirma-and-woocommerce/`
2. Activate the plugin through the 'Plugins' menu in WordPress
3. Go to WooCommerce → iFirma
4. Enter your iFirma API keys and test the connection
5. Configure VAT mapping and invoice settings

== Frequently Asked Questions ==

= Where do I find my iFirma API keys? =

Log in to your iFirma account and generate/copy the keys in: Configuration → Extensions and integrations → API.

= Does this work with WooCommerce Blocks? =

Yes, the plugin is compatible with both classic checkout and WooCommerce Blocks checkout.

= Can customers download their invoices? =

Yes, customers can download invoices from the My Account → View Order page after an invoice has been created.

= Is this compatible with NIP Field WooCommerce plugin? =

Yes. The plugin detects popular NIP field plugin and avoids duplicating the field.

== External services ==

This plugin connects to two third-party/external services: iFirma API (for invoicing) and NBP API (for exchange rates).

= What is iFirma API? =

iFirma is a Polish online accounting system that provides invoicing and accounting services for businesses. This plugin uses their official API to:
*   Create and manage customers (contractors) in your iFirma account.
*   Generate invoices (FREE).
*   Generate proformas and rachunki (PRO).
*   Download document PDFs.

= What data is sent and when? =

The plugin sends the following data to iFirma API (`https://api.ifirma.pl/`) in these situations:

**When you click "Create Invoice" (or when automation triggers document generation in PRO version):**
*   Customer billing information: first name, last name, company name, VAT number (NIP), email, phone number, billing address (street, city, postal code, country).
*   Order information: order items (product names, quantities, prices, VAT rates), shipping details, payment method, order date, order total.

**When the plugin connects to iFirma API (on settings page load or when needed):**
*   Your API credentials entered in the plugin settings (for authentication).
*   Requests to retrieve data required for issuing documents (e.g. templates/series/settings where applicable).

**No data is sent automatically without your action in FREE version.** The plugin communicates with iFirma API when:
*   You manually create an invoice from the order screen.
*   You open the plugin settings page (to test the connection and load configuration).
*   You enable automatic document generation in PRO version (if installed).

= Service provider information =

*   **Service name:** iFirma API
*   **Service URL:** https://www.ifirma.pl/
*   **API documentation:** https://api.ifirma.pl/
*   **Terms of Service:** https://pomoc.ifirma.pl/pomoc-kategoria/oferta-serwisu-ifirma/regulaminy/
*   **Privacy Policy:** https://www.ifirma.pl/rodo/polityka-prywatnosci-ifirma-pl/

= What is NBP API? =

NBP (Narodowy Bank Polski) API is the Polish National Bank's public API that provides official exchange rates for foreign currencies. This plugin uses it to obtain exchange rates when generating invoices in foreign currencies (e.g. EUR, USD) or when issuing WDT/OSS documents with non-PLN amounts. The rate is needed to convert amounts to PLN for iFirma according to Polish accounting rules.

= What data is sent to NBP and when? =

**When you create an invoice in a foreign currency** (or when automation triggers it in PRO):
*   The plugin sends a GET request to NBP API with the currency code (e.g. EUR, USD) and the invoice/order date in the URL. No personal data, customer data, or order details are sent.
*   Example URL: `https://api.nbp.pl/api/exchangerates/rates/A/EUR/2024-01-15/?format=json`
*   The response (exchange rate) is cached for 24 hours to reduce requests.

**No data is sent to NBP without creating a document that requires a foreign currency rate.** The request happens only when an invoice (or proforma/rachunek in PRO) is being generated and the order currency is not PLN.

= NBP service provider information =

*   **Service name:** NBP API (Narodowy Bank Polski)
*   **Service URL:** https://api.nbp.pl/
*   **API documentation:** https://api.nbp.pl/
*   **Privacy Policy:** https://nbp.pl/o-nbp/kontakt/regulaminy/

By using this plugin, you acknowledge that customer and order data will be transmitted to iFirma for invoice generation purposes, and that currency codes and dates may be sent to NBP API to obtain exchange rates. You are responsible for ensuring compliance with applicable data protection laws (including GDPR) and informing your customers about this data processing.

== Screenshots ==

1. Plugin settings
2. Plugin settings
3. Plugin settings
4. Plugin settings
5. Plugin settings
6. Plugin settings
7. Plugin settings
8. Plugin settings
9. Plugin settings
10. Plugin settings

== Changelog ==

= 1.0.27 =
* Fix: prevent duplicate invoices when an invoice is already linked to the order
* Fix: add per-order creation lock to block concurrent invoice requests
* Fix: verify invoice meta is saved after a successful iFirma API response; show a clear admin error if the order link fails instead of leaving Create Invoice visible
* Fix: write the success order note only after the invoice link is confirmed in order meta

= 1.0.26 =
* Add: Devikit Care banner in WordPress admin with dismiss options
* Add: Devikit Care sidebar widget on plugin settings page
* Add: Devikit Care dashboard widget
* Fix: Pro upgrade banner restyled to match Care banner style

= 1.0.25 =
* Fix: accounting month sync targets sale date (DataSprzedazy) again, per iFirma support guidance — issue date (DataWystawienia) stays as today for backlog invoices; only sale date must match the active accounting month, numbering chronology follows the issue date.

= 1.0.24 =
* Fix: backlog invoices for past-month orders now keep DataWystawienia as today while DataSprzedazy stays as the order date — iFirma requires chronological issue dates within a numbering series, so backdating the issue date fails when later invoices already exist.
* Fix: accounting month sync now targets the issue date (DataWystawienia) instead of the sale date — keeps the active accounting month aligned with the issue date when issuing backlog documents.

= 1.0.23 =
* Fix: country name lookup now uses WooCommerce's full country list (all ISO codes, respects site locale) — previously only 11 countries were hardcoded, causing e.g. Romania to be sent as "RO" instead of the full name in invoice payloads.
* Fix: Ulica (street) field is now truncated to 65 characters in all payloads — prevents "Kontrahent.Ulica może zawierać maksymalnie 65 znaków" error for customers with long addresses.

= 1.0.22 =
* Fix: DataWystawienia is now set to sale_date when the order is from a past month — iFirma requires the issue date to match the active accounting month, so backdated invoices no longer fail with "Data wystawienia musi być zgodna z miesiącem i rokiem księgowym".
* Fix: contractor search URL no longer causes 404 for tax IDs containing dots or slashes (e.g. Brazilian CNPJ) — the search phrase is now cleaned the same way as the stored NIP.
* Fix: Miejscowosc (city) field falls back to the country name when the billing city is empty (e.g. Singapore, Dubai) — prevents API rejections due to a missing required city field.
* Fix: Miejscowosc in contractor sync is now truncated to 50 characters to satisfy the kontrahenci endpoint limit.
* Fix: AdresZagraniczny=true is now explicitly set for non-Polish contractors in the kontrahenci payload — recommended by iFirma support to make address fields optional for foreign addresses.

= 1.0.21 =
* Fix: PRO upgrade banner and in-settings PRO notices styling for WordPress 7.0 admin refresh.

= 1.0.20 =
* Fix: NIP field now saves correctly in WP Admin user profile and synchronises with My Account edit address (bidirectional sync).
* Fix: NIP is now populated when selecting a customer or clicking "Load billing address" in admin order edit screen.

= 1.0.19 =
* Tested up to WordPress 7.0.

= 1.0.18 =
* Fix: sync accounting month based on sale date (DataSprzedazy), not issue date — iFirma validates the sale date against the active accounting month, so syncing to today's date was a no-op for backdated orders.

= 1.0.17 =
* Fix: automatically sync iFirma accounting month before creating any document (invoice, proforma, rachunek, WDT, foreign, OSS) so backdated orders are recorded in the correct accounting period instead of the current one.

= 1.0.16 =
* Docs: minor readme updates.

= 1.0.15 =
* Docs: minor readme updates.

= 1.0.14 =
* Fix: contractor sync and invoices — empty billing postcode (`KodPocztowy`) rejected by iFirma API (“adres.kodPocztowy nie może być puste”) while WooCommerce often has no postcode (e.g. UAE/Dubai and other countries, or omitted at checkout); we now substitute a configurable non-empty placeholder (default `-`). Override via WordPress filter `devikit_ifirma_empty_postcode_placeholder`.

= 1.0.13 =
* Fix: OSS invoices — iFirma rejects `KrajDostawy` / `Kontrahent.KodKraju` **GR** (“Nieprawidłowy kraj dostawy… dwuliterowy kod ISO kraju z UE”); WooCommerce uses **GR** for Greece but the EU/VAT code expected in these fields is **EL** — same normalization as for `PrefiksUE`. Contractor `KodKraju` on sync also maps **GR → EL**.

= 1.0.12 =
* Docs: readme screenshots section updated for WordPress.org asset screenshots (screenshot-1 through screenshot-10).

= 1.0.11 =
* Fix: contractor sync / WDT — Greek customers billing as **GR**: iFirma requires EU VAT prefix **EL**, not ISO `GR`; `Kontrahent.PrefiksUE` is now normalized (fixes "Podana wartość Kontrahent.PrefiksUE przyjmuje nieprawidłową wartość" when only a numeric tax/VAT-like ID is entered).

= 1.0.10 =
* Fix: invoices for customers from Romania (RO) and Portugal (PT) failed with "Podana wartość pola Jezyk przyjmuje nieprawidłową wartość" — iFirma API does not support `ro` or `pt` language codes; both now fall back to `en` (English).

= 1.0.9 =
* New: append "Reverse charge" (translatable) to invoice notes for orders billed **outside Poland** and **outside the EU** when a tax identifier (NIP / EU VAT / Tax ID) is saved on the order.
* Fix: customer **My Account** invoice PDF download uses the same iFirma document type as the admin button (`_ifirma_invoice_type`: foreign, OSS, WDT), not always domestic.

= 1.0.8 =
* Fix: when WooCommerce prices are entered **including tax**, send gross unit prices to iFirma with `LiczOd` BRT (domestic, proforma, foreign currency, OSS, WDT, rachunek, corrections). Aligns document totals and VAT split with order totals charged at checkout.

= 1.0.7 =
* Fix: non-Poland billing addresses use `fakturawaluta` (not domestic `fakturakraj`) even when the order is in PLN — avoids issuing Polish domestic invoices for foreign companies.
* Fix: `fakturawaluta` in PLN — do not send exchange-rate related fields (e.g. `KursWalutyWidoczny`, NBP rate); fixes iFirma error about exchange rate only applying to non-PLN invoices.

= 1.0.6 =
* Fix: WDT invoices — add required API field Waluta and NBP rate when the document currency is not PLN.
* Fix: contractors and WDT — send Kontrahent.PrefiksUE only for valid EU member-state VAT prefixes; avoid invalid values for non-EU customers or non-EU tax IDs (iFirma API validation).

= 1.0.5 =
* Compatibility: resolve order tax identifier (NIP / EU VAT / foreign Tax ID) from multiple order meta keys so values saved by third-party plugins (WooCommerce EU VAT Number, nip-field-for-woocommerce, custom checkout fields, etc.) are sent to iFirma under the NIP label.
* New filters: `devikit_ifirma_order_tax_id_meta_keys` (customize the list of checked meta keys) and `devikit_ifirma_order_tax_id` (override the resolved value).

= 1.0.4 =
* Fix: save_admin_order_nip - handle WP_Post passed by woocommerce_process_shop_order_meta in some WooCommerce versions

= 1.0.3 =
* Plugin title: Invoicing Integration for iFirma and WooCommerce

= 1.0.2 =
* Editable NIP field in order meta (admin order edit screen)

= 1.0.1 =
* 5-minute delay for automatic invoice email (KSeF processing)
* Order column: total mismatch indicator (order vs document sum) with tooltip
* Compiled translations (pl_PL.mo)

= 1.0.0 =
* Initial release
* Manual invoice generation
* Customer synchronization
* Advanced VAT mapping
* Customer invoice download
* NIP field support with compatibility
* HPOS compatibility
* WooCommerce Blocks checkout support

== Upgrade Notice ==

= 1.0.25 =
Poprawka zaległych faktur wg wytycznych supportu iFirma: miesiąc księgowy = data sprzedaży, data wystawienia = dziś.

= 1.0.24 =
Ważna poprawka dla zaległych faktur z poprzedniego miesiąca — data wystawienia pozostaje dzisiejsza, data sprzedaży z zamówienia, sync miesiąca księgowego do daty wystawienia.

= 1.0.23 =
Poprawia nazwę kraju dla wszystkich krajów spoza listy podstawowej (np. Rumunia, Chorwacja) oraz obcina zbyt długie adresy (Ulica) do 65 znaków.

= 1.0.22 =
Ważna aktualizacja: poprawia wystawianie faktur za poprzednie miesiące (DataWystawienia), błąd 404 przy synchronizacji kontrahenta z CNPJ/NIP zawierającym znaki specjalne, oraz fallback dla pustego pola Miejscowość.

= 1.0.19 =
Tested up to WordPress 7.0; no functional changes.

= 1.0.18 =
Poprawka krytyczna dla użytkowników z zamówieniami z poprzednich miesięcy: sync miesiąca księgowego działał od 1.0.17, ale był oparty o datę wystawienia (dziś) zamiast datę sprzedaży — teraz działa poprawnie.

= 1.0.17 =
Ważna poprawka dla użytkowników wystawiających faktury dla starszych zamówień: wtyczka teraz automatycznie ustawia miesiąc księgowy iFirma przed każdym dokumentem, dzięki czemu trafia on do właściwego okresu rozliczeniowego.

= 1.0.16 =
Minor readme updates; no functional changes.

= 1.0.15 =
Minor readme updates; no functional changes.

= 1.0.14 =
Empty postcode is sent as a harmless placeholder (`-`) so iFirma API accepts overseas addresses; customizable via filter.

= 1.0.13 =
OSS: Greece delivery country now sent as EL (not GR) so iFirma accepts KrajDostawy.

= 1.0.12 =
Readme screenshots updated; no functional changes.

= 1.0.11 =
Greece (GR): iFirma `PrefiksUE` now uses VAT prefix EL so contractor sync succeeds when billing country is Greece.

= 1.0.9 =
Reverse-charge note for selected third-country B2B orders; correct PDF endpoint on My Account for non-domestic invoices.

= 1.0.8 =
Better rounding alignment for shops that enter catalog prices with tax included.

= 1.0.7 =
Correct foreign-company document type in PLN, and fakturawaluta payload without NBP/visibility when Waluta is PLN.

= 1.0.6 =
Fixes for WDT invoice currency (Waluta) and EU-only PrefiksUE when syncing contractors to iFirma.

= 1.0.5 =
NIP on invoices now also reads EU VAT ID and foreign Tax ID from meta fields of third-party plugins (e.g. WooCommerce EU VAT Number).

= 1.0.4 =
Fix NIP save when WooCommerce passes WP_Post instead of WC_Order.

= 1.0.3 =
Plugin title update.

= 1.0.2 =
Editable NIP field in order meta box.

= 1.0.1 =
5-minute email delay for KSeF, order column mismatch indicator, compiled translations.

= 1.0.0 =
Initial release of the plugin.