=== Australcode DTE & Stock Sync for Bsale ===
Contributors: australcode
Tags: woocommerce, facturacion electronica, sii, boleta, bsale
Requires at least: 6.0
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 3.7.3
License: GPL-2.0-or-later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Issue SII boletas, facturas and credit notes from WooCommerce via Bsale — real-time webhook stock sync and credit notes free, no per-document fees.

== Description ==

**Australcode DTE & Stock Sync** makes SII-compliant tax document emission (boletas, facturas, credit notes, dispatch guides) automatic for any WooCommerce store in Chile. Real-time sync of products, stock and prices from Bsale to WooCommerce. The Free version already includes real-time webhook stock updates, credit notes, and on-demand stock audit — with no per-document or per-boleta fees. Mature plugin in production since 2023, now part of the Australcode family.

It covers the full lifecycle of a Chilean e-commerce transaction: from product catalog sync to manual or automatic emission of the SII-compliant tax document required for each WooCommerce order.

*Australcode is an independent developer. This plugin is a third-party integration for Bsale and WooCommerce; it is not affiliated with, endorsed by, or sponsored by Bsale, Defontana SpA, or the WooCommerce/Automattic trademark holders.*

= Free version =

Everything you need to run a typical Chilean e-commerce store with WooCommerce + Bsale:

* **Product sync** — One-way synchronization from Bsale to WooCommerce. Imports product catalog including variants, SKUs, prices, and stock levels.
* **Single-office stock** — Stock from one configured Bsale office, with optional reserve buffer for in-person sales.
* **Real-time stock updates via webhooks** — Bsale stock changes propagate to WooCommerce in seconds.
* **Manual emission of boleta and factura** — Issue documents from the order admin screen. Document type auto-detected from customer billing data (RUT empresa → factura, otherwise boleta).
* **Credit notes (notas de crédito)** — Manual emission for refunds.
* **Chilean checkout fields** — Adds RUT field with module-11 validation. Compatible with both Block-based Checkout and Classic Checkout.
* **Order metabox** — Per-order Bsale status, PDF link, document type, and re-emit controls.
* **Email PDF to customer** — Automatic dispatch of the emitted document to the customer's email.
* **Stock audit (on-demand)** — Run-when-needed audit comparing WooCommerce and Bsale stock. Discrepancy detection and traceability.
* **Diagnostics** — Dashboard with API/webhook status, logs viewer with filters and retention policy, traceability ledger (read-only).
* **HPOS compatible** — Declares compatibility with WooCommerce High-Performance Order Storage and Cart/Checkout Blocks.

= Pro version =

Adds workflow automation, multi-warehouse support, and advanced B2B features:

* **Auto-emission post-payment** — Documents emitted automatically when WooCommerce orders reach configurable statuses (processing, completed, etc.). The killer time-saver.
* **Multi-office stock aggregation** — Sum stock across multiple Bsale offices.
* **Stock transfer modes** — Auto-move stock to main office via internal transfer or dispatch guide (guía de despacho) when an order requires stock from a secondary office.
* **Sales notes (nota de venta) + automatic credit notes from refunds** — Full B2B workflow automation.
* **Dispatch guides (guías de despacho)** — Inter-office stock transfers with electronic dispatch document.
* **Dynamic document attributes** — Custom attributes (e.g. WooCommerce order number) injected into each emitted document.
* **Scheduled audits** — Up to 3 daily automatic audit runs comparing WooCommerce ↔ Bsale stock, with optional auto-correction and email notifications.
* **Custom field mapping** — Map WooCommerce custom checkout fields (from third-party plugins) to Bsale invoice fields (rut_empresa, razón social, giro, dirección, comuna, ciudad).
* **Stock-per-office display on frontend** — Optional product page widget showing available stock per office.
* **Per-shipping-method office routing** — Emit documents from a specific Bsale office based on the WooCommerce shipping method (multi-warehouse).
* **Daily auto-link by SKU** — Cron job that auto-links unlinked WooCommerce products to Bsale variants by SKU match.

= Pricing =

Pro is sold as an annual subscription with 1 site activation per license. Multi-site licenses available.

Learn more and purchase at https://bsale.australcode.io

= Requirements =

* WooCommerce 7.0 or later
* A Bsale account with API access
* WordPress 6.0 or later, PHP 7.4 or later

= Bsale =

Bsale is a Chilean SaaS platform for POS, inventory, and electronic tax document emission compliant with SII (Servicio de Impuestos Internos, the Chilean tax authority). It is the de-facto choice for many Chilean small and medium e-commerce businesses to handle their day-to-day operations and tax compliance.

This plugin is an unaffiliated third-party integration. "Bsale" is a trademark of its respective owner.

== External services ==

This plugin connects to two third-party services. Both are used only for the features described, and only as a result of an action you take (entering your Bsale API token, or activating a Pro license). No data is sent on a fresh install before you configure these features.

= Bsale API (bsale.io / bsale.cl) =

What it is: Bsale is the Chilean POS and electronic invoicing platform this plugin integrates with. The plugin is an unaffiliated third-party integration.

Data sent and when:

* Your Bsale API access token is sent with every request, to authenticate.
* Product, variant, SKU, price and stock queries are sent when you sync your catalog or when Bsale stock webhooks arrive.
* When a tax document is emitted (boleta, factura, credit note, dispatch guide), the order data required by the SII (customer RUT, razón social, line items, amounts) is sent to Bsale so it can issue the legal document.

This happens because the plugin's purpose is to mirror your Bsale catalog into WooCommerce and to emit SII-compliant documents through Bsale. The connection is configured by you: you enter your own Bsale API token under "Australcode Bsale → Configuración".

* Terms of Service: https://www.bsale.cl/sheet/condiciones-uso
* Privacy Policy: https://www.bsale.cl/sheet/politica-privacidad

= Freemius (freemius.com) =

What it is: Freemius is the Merchant of Record and licensing provider used to manage the optional Pro license (checkout, activation, account, and updates).

Data sent and when:

* When you opt in (optional — you can skip it), your admin email and site URL are sent to Freemius so it can manage your account and license. The plugin is fully functional without opting in.
* Your license key and site URL are sent to Freemius when you activate, validate, or deactivate a Pro license through the native Freemius account screens, and periodically while a Pro license is active to re-check its status and deliver updates.
* The free version does not require an account and works without contacting Freemius.

* Terms of Service: https://freemius.com/terms/
* Privacy Policy: https://freemius.com/privacy/

== Installation ==

1. Upload the plugin folder to `/wp-content/plugins/australcode-bsale`.
2. Activate the plugin from the WordPress admin "Plugins" menu.
3. Navigate to **Australcode Bsale → Configuration**.
4. Enter your Bsale API access token (available in your Bsale account).
5. Select your default office (sucursal) and configure document type preferences.
6. Configure the Bsale webhook URL in your Bsale account to enable real-time stock updates.

To unlock Pro features, go to **Australcode Bsale → Upgrade** and complete checkout through Freemius. Your Pro license activates automatically after purchase.

== Frequently Asked Questions ==

= Do I need a Bsale account? =

Yes, you need an active Bsale account with API access. The plugin connects to your existing Bsale account via API token.

= What's the difference between Free and Pro? =

Free covers everything a typical Chilean e-commerce store needs: product/stock sync, manual emission of boletas and facturas, RUT validation, single-office stock, on-demand audit, real-time webhook updates. Pro adds workflow automation (auto-emission post-payment, scheduled audits, daily SKU auto-link), multi-warehouse support (multi-office stock aggregation, stock transfer between offices, per-shipping-method routing), and advanced B2B features (custom field mapping, dynamic document attributes, sales notes, automatic credit notes from refunds). The Pro features are distributed as a separate plugin (from australcode.io) and are not included in this free version.

See the [Pro page](https://bsale.australcode.io) for the full comparison.

= Can I move from Free to Pro without losing my configuration? =

Yes. Your Bsale account connection and general settings (API connection, document types, tax options) are stored independently of the Pro features, so when you move to the Pro version your existing configuration carries over — no re-entry needed.

= What happens if I stop using Pro? =

The free version is fully functional on its own — it keeps handling product/stock sync and manual emission of boletas and facturas. The Pro features are provided by the separate Pro version and are not part of this free plugin.

= Is it compatible with the WooCommerce Block-based Checkout? =

Yes, the plugin is compatible with both the Block-based Checkout (WooCommerce 8.0+) and the Classic Checkout. Chilean tax fields (RUT, razón social, giro) are added to both.

= Can I emit boleta or factura selectively per order? =

Yes. The order metabox allows manual override of the document type per order, useful for B2B orders where the customer requests a factura instead of a boleta. This works in both Free and Pro.

= Does the plugin support multiple Bsale offices (sucursales)? =

Yes — in Pro. Free supports a single configured office. Pro adds multi-office stock aggregation (sum of available units across selected offices) plus stock transfer modes for inter-office logistics.

= What happens if a tax document emission fails? =

Failed emissions are logged with the error reason. The order metabox includes a "Re-emit" button to retry manually. The plugin also has an automatic retry mechanism (Pro feature, configurable, opt-in) for transient failures.

= Is the plugin HPOS compatible? =

Yes, the plugin declares compatibility with HPOS (High-Performance Order Storage) and uses the WooCommerce data abstraction layer for all order operations.

= Does the plugin work without Bsale (offline mode)? =

No. The plugin is a Bsale integration — it requires an active Bsale account and API access to function. The plugin's value is precisely the bidirectional sync between WooCommerce and Bsale.

= How does Pro licensing work? =

Pro is sold as an annual subscription through Freemius (Merchant of Record). After checkout your Pro license activates automatically; you can manage, sync or deactivate it from the native Freemius account screen. Freemius re-validates the license periodically while it is active. If Freemius is temporarily unreachable, your Pro features keep working — only an explicit change (refund, revocation, expiration) deactivates them.

= Where can I find the plugin's documentation? =

Visit https://bsale.australcode.io for plugin documentation, support, and source code.

= How does this plugin differ from other plugins that emit Chilean tax documents? =

Several plugins issue Chilean boletas or facturas from WooCommerce. Australcode Bsale differs on three concrete points:

* **Open-source under GPLv2** — the full source is on WordPress.org. You can audit, modify or fork it freely. No black box, no proprietary backend.
* **Pro tier sold as an annual subscription via Freemius (Merchant of Record)** — no pay-per-document and no per-boleta fees. Predictable cost at any volume.
* **Full bidirectional sync with Bsale** — not just emission: also syncs product catalog, multi-office stock, prices, stock audit ledger and movement traceability. Mature plugin in production since 2023.

= How much does Pro cost? =

Pro is sold as an annual subscription with one site activation per license. Multi-site licenses (3, 10, 25 sites) are also available. Current pricing is on [bsale.australcode.io](https://bsale.australcode.io).

== Screenshots ==

1. Plugin dashboard with sync status, stock health, and recent activity.
2. Configuration page with Bsale API connection, default office, and document type preferences.
3. Order metabox with Bsale document status, PDF link, and re-emit controls.
4. Stock audit interface showing discrepancies between WooCommerce and Bsale.
5. Upgrade page showing the Pro features (Australcode Bsale &rarr; Upgrade).

== Changelog ==

= 3.7.3 =

* **Security:** late-escape hardening. Action HTML in the admin page-header component and the 24-hour reliability sparkline on the Traceability screen are now filtered through `wp_kses()` with an explicit allowlist at output time (escaping late). Added an `is_callable()` guard before invoking an internal progress callback in the stock sync. No functional or visual change.

= 3.7.2 =

* **WordPress.org compliance:** the free version no longer includes any Pro feature code or license-based gating. The Pro features (auto-emission, multi-office, stock transfer, scheduled audits, custom field mapping, dynamic attributes, sales notes, dispatch guides, daily SKU auto-link) are fully separated into the Pro version. The free plugin is completely standalone and fully functional on its own.

= 3.6.1 =

* **Name:** the plugin name and slug no longer include "WooCommerce", per WordPress.org's restricted-term policy. The plugin still integrates with and requires WooCommerce (declared via the Requires Plugins header). No functional change.

= 3.6.0 =

* **Renamed** to "Australcode DTE & Stock Sync for Bsale" for a clearer, distinctive name. Same plugin and data — no action required.
* **Free / Pro packaging:** the optional Pro features (workflow automation and multi-warehouse) are not part of this free package and are distributed separately. The free version is fully functional on its own: manual boletas, facturas and credit notes, single-office stock, real-time webhook stock sync, and on-demand stock audit.
* **Compatibility:** declares WooCommerce as a required plugin.
* **Security:** hardened output escaping in a shared admin UI header component.

= 3.5.0 =

* **Stock traceability, reimagined:** the Traceability screen now opens with an at-a-glance health verdict — "Is your stock healthy?" — showing a large reliability score, a plain-language status (healthy / needs attention / has issues), and a 24-hour reliability sparkline. You can read the state of your Bsale ⇄ WooCommerce stock sync in seconds instead of scanning raw numbers; the detailed per-event tables are unchanged.

= 3.4.4 =

* **Compatibility:** fixed a potential fatal error on PHP 7.4 — `str_starts_with()` (PHP 8.0+) was called without a polyfill in the webhook URL builder, which could fatal when processing a webhook resource path on the plugin's declared minimum (PHP 7.4). Replaced with a 7.4-safe equivalent. Recommended update for any site running PHP 7.4. (No functional changes for PHP 8+ sites.)

= 3.4.3 =

* **Reliability:** the WP-CLI command registration is now null-safe against an unloaded licensing SDK, preventing a potential fatal on every `wp` command in environments where the SDK fails to load. No functional changes.

= 3.4.2 =

* **Spanish (Chile) polish:** the Upgrade panel and the document/traceability status labels (expired, failed, processing, provisional, severities) now render fully in Spanish instead of leaking English terms.
* **Admin UI:** the residual blue accent on nested settings sub-fields now matches the plugin's green brand color; configuration data tables (dashboard activity, audit history, stock-source events, document config) collapse cleanly into cards on mobile instead of clipping.
* **Motion:** admin transitions now use the design system's motion tokens for a consistent feel.
* **Internal:** license declared as SPDX `GPL-2.0-or-later`; menu icon style registration no longer triggers a Plugin Check "missing version" warning; minor packaging metadata hygiene.

= 3.4.1 =

* **Internal:** transactional email styling (stock-movement, SKU-not-found and stock-audit notifications) is now centralized in a single email-component helper instead of ~135 duplicated inline styles. Same emails, one source of truth. The "shipping guide" notice box now uses the same green accent palette as the other notices (was a slightly different green). Covered by golden-snapshot tests.

= 3.4.0 =

* **Fix (data loss):** saving Settings on a Free (or lapsed-Pro) license no longer wipes previously saved Pro configuration (additional offices, scheduled audits, SKU auto-linking, etc.) from storage. Your Pro setup is preserved and reactivates automatically when the license is active again.
* **Admin UI:** Pro-only blocks (additional offices, SKU auto-linking, scheduled audits) are presented with a clear, unobtrusive pointer to the separate Pro version. (Superseded in 3.6.0, which removes the Pro feature code from the free package entirely.)

= 3.3.2 =

* **Admin UI:** the residual admin styles (form controls, checklists, sub-tabs, mapping tables) now inherit the Admin Kit's neutral palette, corner radii and motion timing, so every screen shares one consistent visual system. Presentation-only; no markup or functional changes.

= 3.3.1 =

* **Admin UI:** the payment- and shipping-mapping tables in Settings now collapse into readable cards on small screens, matching the rest of the admin. Dynamically added shipping rows collapse too.
* **Branding:** transactional emails (document and stock-audit notifications) now use the Australcode green accent instead of the legacy orange, centralized via a single brand-color constant. No functional changes.

= 3.3.0 =

* **Admin UI:** every screen now uses the unified Australcode admin design system (Green Austral) — dashboard, products, documents, logs, order metabox, audit and traceability share one consistent look (headers, tables, badges, filters, KPIs, segmented tabs). No functional changes; same data, same actions.

= 3.2.0 =

* **Billing:** licensing moved from Lemon Squeezy to Freemius (Merchant of Record). Pro activation, account management and upgrades now use the native Freemius experience. Existing Pro features and the free/Pro boundary are unchanged.

= 3.1.5 — 2026-06-13 =

* **Fix (admin UI):** WordPress admin notices no longer overlap the plugin header — every screen now closes its header with the standard marker so notices render below it, full-width.
* **Enhancement (dashboard):** the pre-setup hero is context-aware — once Bsale is connected and only a final step remains (e.g. choosing a price list) it reads "Almost ready" with the exact remaining step, instead of "Connect Bsale to get started".
* **Enhancement (settings):** under the Pro "Additional offices" gate, the free plugin now shows a short office preview with a "+N more with Pro" hint instead of the full disabled list.
* **Polish (admin UI):** flattened danger buttons and metric cards (no hover lift or glow) for a calmer, more consistent surface, and gave the menu icon an explicit color so it stays legible.
* **Enhancement (license):** an expired or disabled Pro license now shows a dedicated state (with the expiry date) instead of the generic activation screen, so existing customers know to renew.

= 3.1.4 — 2026-06-05 =

* **Fix (sync):** the "Repair mappings" tool now deduplicates by the full (Bsale variant, WooCommerce product, variation) key instead of by Bsale variant alone, so it no longer collapses legitimate 1:N mappings (the same Bsale variant linked to several WooCommerce products) on multi-publication catalogs.
* **Enhancement (admin UI):** the system Logs screen is now a grouped activity stream — repeated events collapse into summary rows with an occurrence count and last-seen time, expandable to the latest detail, with a "Review connection" shortcut to Settings on Bsale API errors.
* **Robustness (audit):** the stock audit's Bsale fetch is now resumable — if a background run is interrupted it checkpoints its cursor and continues instead of restarting from zero. No partial writes: the audit table is only replaced after a complete fetch.
* **Hardening (API):** automatic pagination (`get_all`) gained a configurable safety cap that logs and stops runaway pagination instead of hanging the request; removed dead code.

= 3.1.3 — 2026-06-04 =

* **Fix (i18n):** resolved the `_load_textdomain_just_in_time` notice (WP 6.7+). Block checkout field registration is now deferred to `woocommerce_init` (WooCommerce's canonical hook for additional checkout fields) and the cron-schedule filter no longer translates labels before `init`. No translation now loads before `init`.
* **Fix (checkout):** the "factura incompleta" validation message is escaped at the throw site, clearing a Plugin Check `ExceptionNotEscaped` error.
* **Enhancement (admin UI):** refreshed admin design for a more consistent, premium look — a unified page header with version badge, lede and breadcrumb across all screens; flat primary buttons; a focused pre-setup dashboard with a single call to action; and a redesigned Stock Traceability screen (tokenized metrics cards, cleaner tables, collapsible recent-events list).
* **Housekeeping:** removed decorative emoji from admin and order-note strings, trimmed an over-limit upgrade notice, and regenerated the translation template (POT).

= 3.1.2 — 2026-06-01 =

* **Enhancement (audit):** the product audit now badges WooCommerce products with `private` post status in the "WC products without Bsale mapping" section, so intentionally-private items (e.g. discontinued products) are visually distinguishable and no longer read as problems. Presentation-only — audit coverage is unchanged.

= 3.1.1 — 2026-05-31 =

* **Fix (sync, critical follow-up to 3.1.0):** product sync no longer persists a spurious product mapping to the first Bsale variant. 3.1.0 fixed the stock/price path but the mapping-persistence path (`save_mapping`) still used the first variant, recreating a wrong-variant mapping row on every sync of a simple product mapped to a multi-variant Bsale item. The correct variant is now resolved by SKU (or the existing mapping) in both paths. Surfaced by live re-validation against a Bsale DEMO account.

= 3.1.0 — 2026-05-31 =

Live-QA remediation against a Bsale DEMO account surfaced pre-existing bugs; this release fixes the critical and high-severity ones.

* **Fix (sync, critical):** product sync on a simple WooCommerce product mapped to a multi-variant Bsale parent no longer applies the wrong variant's stock/price. The correct variant is now resolved by mapping/variant id or SKU instead of always taking the first variant.
* **Fix (sync):** product sync no longer overwrites the local WooCommerce product name with the Bsale parent name (same principle already applied to SKU — the local value wins).
* **Fix (documents):** when a stock-transfer dispatch guide fails, emission now aborts with an actionable "Retry" error instead of silently emitting the receipt without stock or guide (prevented a silent negative-stock risk).
* **Fix (webhooks):** successful `product.create/update` webhooks are now marked completed in one pass. They were missing a normalized return flag, which routed successes to the retry path and duplicated product mappings before failing.
* **Fix (checkout):** Chilean RUT (mod-11) validation now runs on the Block checkout. WooCommerce graduated the additional-field validation hook in 8.7.0; the plugin now hooks the current name so invalid RUTs are blocked.
* **Fix (documents, A4.C10):** partial credit notes now match refunded lines by SKU/variant id (not by position) and credit the shipping line correctly.
* **Perf/robustness:** skip price-list lookups when no list is configured (removes noisy 404s); resolve office names from a single preloaded catalog instead of one API call per stock line; use the WooCommerce setter for billing company; return HTTP 400 (not 500) on incomplete invoice fields.
* **Compliance:** removed the unsupported `placeholder` attribute from Block additional checkout fields (WooCommerce 8.6+ notice).

= 3.0.8 — 2026-05-26 =

* **WP.org Plugin Check pass.** The release ZIP now ships clean: dev-only artifacts (`phpcs.xml*`, `tests/`, `scripts/`, `composer.{json,lock}`, `phpunit.xml*`, `.phpunit.result.cache`, `vendor/`) are excluded from the build, closing the two `application_detected` errors that Plugin Check reported on 3.0.7.
* **Security hardening.** Tighter `phpcs:ignore` scoping on the WooCommerce-checkout `$_POST` reads (`validate_classic_checkout`, `save_classic_order_meta`) — WooCommerce verifies its own checkout nonce upstream; the annotations now document that explicitly. Same for the license form controller, where the nonce is verified through the `guard()` helper.
* **readme polish.** Upgrade Notice entries for 3.0.5, 3.0.6 and 3.0.7 trimmed to fit the WP.org 300-character display limit.
* **DX: codebase-wide `phpcs:disable` headers** added to the 18 files that own custom plugin tables (`wp_acbsl_*`) and to the 9 admin view templates, documenting that the SQL "InterpolatedNotPrepared / DirectQuery / NoCaching" reports and the "NonPrefixedVariableFound" reports are false positives in this codebase: table names are class-controlled constants, values pass through `$wpdb->prepare()`, and view-scope locals are not WordPress globals.
* No functional change in product sync, stock sync, document emission, license activation, traceability or admin UI. Pure compliance + dev-tooling release.

= 3.0.7 — 2026-05-26 =

* **Simplification: removed the `sku_locked` mapping flag introduced in 3.0.6.** It was over-engineering: the intended behavior is that the SKU of a WooCommerce product is *the* matching key and must never be overwritten by Bsale during sync, without opt-in/opt-out. There is no "Bsale as authority over SKU" mode. If a Bsale variant code diverges from the WC SKU, the existing Auditoría module reports the orphan for manual resolution.
* **DB cleanup**: the `sku_locked` column on `wp_acbsl_products` is dropped automatically (idempotent migration `acbsl_migration_sku_lock_removed`). The 3.0.6 migration flag `acbsl_migration_sku_lock_added` is cleared.
* `apply_variant_to_product()` simplified: never calls `set_sku()`. If WC SKU and Bsale variant code differ, logs an info entry "SKU divergente entre WC y Bsale; el SKU local se preserva" for diagnostics.
* The SKU-primary lookup and 1:N propagation in `sync_product()` introduced in 3.0.6 remain (those were correct). `get_mappings_by_sku()` and `get_mappings_by_bsale_id()` plural stay.
* No functional change for stock / price webhooks, license, or document emission.

= 3.0.6 — 2026-05-26 =

* **Fix: WooCommerce product SKU is no longer overwritten during Bsale syncs.** Previously, every product sync (manual, scheduled, or webhook-driven for product data) replaced the local WC SKU with the Bsale variant `code`, silently overwriting SKUs that stores intentionally diverged. This was a regression from the original "match by SKU" design. From now on, the SKU is preserved by default. When the Bsale `code` differs from the WC SKU, the sync logs an info entry ("SKU local conservado (lock activo)") for diagnostics. To restore the legacy behavior (Bsale as authority on SKU), set `sku_locked = 0` on the mapping row in `wp_acbsl_products`.
* **Fix: manual / scheduled product syncs now propagate to ALL mapped WooCommerce products** that share a Bsale variant SKU (1:N), not just the first one. Stock and price webhook flows already supported this pattern (since 2.50.0); now `sync_product()` does too. The lookup is primary by SKU with fallback by `bsale_product_id` for legacy mappings.
* **New schema column** `sku_locked TINYINT(1) DEFAULT 1` in `wp_acbsl_products`. Migration is automatic and idempotent — both existing and new mappings start locked (safe default). A future minor release will add a UI toggle to override per product.
* No functional change in stock / price webhook flows, license activation, or document emission.

= 3.0.5 — 2026-05-26 =

* **Polish: admin UI mobile.** The dashboard activity table now collapses to a stacked card layout on narrow screens (≤600px) instead of scrolling horizontally. Long messages remain fully readable without truncation. Closes the partial fix shipped in 3.0.4.
* **Polish: design-system consistency.** Two remaining WordPress-default buttons in Settings ("Agregar método manual" and "Agregar tipo") migrated to the brand button styles, completing the brand-override cleanup. "Limpiar huérfanos" on Products now uses a red outline (`danger-outline`) to communicate it is a destructive action. The "Última auditoría" stat value on the Audit screen now uses the monospace family, matching the other numeric KPIs.
* **Polish: maintainability.** Around 40 inline `style="…"` attributes in Traceability and Audit replaced by utility classes in the design system (`acbsl-kpi-label`, `acbsl-kpi-value`, `acbsl-card-legacy`, `acbsl-text-center`, `acbsl-mt-xl`, `acbsl-mb-lg`, etc.). Visual rendering unchanged.
* No functional changes — pure polish release.

= 3.0.4 — 2026-05-25 =

* **Polish + WordPress.org submission readiness.** WP.org Plugin Check now reports 0 errors. Translation template (.pot) regenerated to match the rebranded codebase. Multiple defensive `phpcs:ignore` comments added on canonical `$wpdb->prepare()` patterns (array-variadic IN clauses, gated `set_time_limit()`, `debug_backtrace` runtime heuristic in the stock tracer, gated `error_log` for tracer/reconciler internals) so that defensible style-warnings stop being reported as actionable.
* **Polish: admin UI.** Single primary CTA on the Products screen (the empty-state action is now secondary, matching the screen's primary header button). Brand-colored Filter/Clear/"Mark resolved" buttons on Traceability (no more default-blue colliding with the Bsale orange brand override). Activity log on mobile no longer truncates messages mid-word.
* **i18n: neutral Spanish.** One reconciler-alert string in Traceability moved from rioplatense Spanish ("Revisá, ejecutá") to neutral Spanish ("Revisa, ejecuta"). Internal change for translators; user-facing copy reads the same.
* No functional changes — pure polish, compliance and translation-template release.

= 3.0.3 — 2026-05-22 =

* **Fix: the license and stock-traceability data now migrate correctly during the rebrand.** The 3.0.0 rename map missed a few options that used the short legacy prefix (the stored license and the traceability history), so on some sites the plugin reverted to the free tier after upgrading even though a valid Pro license was present. The license was never lost — only disconnected — and is now reconnected automatically (idempotent, runs once). No action required.

= 3.0.2 — 2026-05-22 =

* **Fix: at-rest encryption of the Bsale token now applies on first activation too.** In 3.0.1 the one-time migration that encrypts the stored Bsale API token and webhook secret only ran on a version upgrade; on a clean activation that jumped straight to the current version it was skipped, leaving the token in clear text. The migration now also runs on activation and defensively on every load (idempotent, flag-gated), so the credentials are always encrypted at rest. No action required.

= 3.0.1 — 2026-05-22 =

* **Security hardening (pre-release).** Webhook resource fetches are restricted to Bsale hosts (prevents SSRF / token exfiltration); the Bsale API token and webhook secret are encrypted at rest with AES-256-GCM (same as license keys); the webhook bootstrap validates the Bsale company id (`cpnId`) against the connected account before trusting it; and non-idempotent API writes (document/stock emission) are no longer auto-retried on timeout/5xx, to avoid duplicate documents or stock movements.
* **Robustness.** Circuit breaker on the Bsale API client (fails fast during outages instead of hammering), idempotent webhook de-duplication (`dedup_hash`), safer legacy-cron cleanup (fixed hook list), a guarded table-rename migration (logs and retries on partial failure), and complete uninstall cleanup.
* No functional changes for the store operator.

= 3.0.0 — 2026-05-22 =

* **Rebrand to Australcode Bsale for WooCommerce.** The plugin is now part of the Australcode family. This is a major release because internal identifiers were renamed (PHP classes, functions, hooks, nonces, options, database tables, and order meta keys moved from the legacy `cb`/`CBSALE`/`conecta_bsale` prefixes to `acbsl`/`Australcode`).
* **Automatic, in-place data migration on upgrade.** Existing settings, product mappings, stock ledger, emitted documents, and order meta are migrated to the new names automatically — no manual action required. The migration is idempotent and runs once.
* **Bsale webhook URL is unchanged.** The REST endpoint stays at `/wp-json/conecta-bsale/v1/webhook`, so stock sync keeps working without reconfiguring anything on the Bsale side.
* No functional changes: every feature behaves exactly as in 2.53.0.

= 2.53.0 — 2026-05-21 =

* Fix: emission lock no longer collides across orders. The placeholder row that serializes concurrent emissions now uses a NULL sentinel instead of `0`, so two different orders emitting the same document type in the same burst no longer block each other.

= 2.52.0 — 2026-05-19 =

* **New: Free / Pro split** for commercial distribution. The Pro features (auto-emission post-payment, multi-office aggregation, stock transfer, scheduled audits, custom field mapping, dynamic document attributes, sales notes, dispatch guides, per-shipping-method routing, daily SKU auto-link) are offered in a separate Pro version. The free version retains all essentials for a typical Chilean e-commerce store.
* **New: License management page** (**Australcode Bsale → License**) with activate/validate/deactivate flows. License keys validated with the Lemon Squeezy licensing service.
* **New: Daily license revalidation cron** with graceful degradation.
* **Security: Webhook origin validation (cpnId).** The webhook endpoint authenticates each request by matching its Bsale company id (`cpnId`) against the connected account, rejecting foreign-origin payloads with HTTP 403. The expected `cpnId` auto-detects from the first webhook. An optional shared token (`?acbsl_token=` URL param or `X-CB-Token` header, paired with the `webhook_secret` setting) adds defense-in-depth. Note: Bsale does not sign its webhooks, so HMAC signature verification is not applicable.
* **Security: Webhook rate limiting** (60 req/min per IP) + payload size limit (1 MB), both filterable.
* **Security: License key leakage prevention** — error messages scrub keys before persisting/displaying.
* **Security: Variant validation hardened** — activations validated against known store_id + variant_id.
* **Security: Deleted operational repair script** (`repair-incomplete-documents.php`) that was web-accessible without auth.
* **Security: Exception messages escaped** — all thrown exception messages wrapped with `esc_html()` / `esc_html__()` (Plugin Check compliance: 0 errors).
* **Fix: Document emission TIMEZONE bug** — recovery flow uses Chile TZ (was server UTC). Previously caused duplicate documents in Bsale for orders emitted 21:00–23:59 Chile (SII compliance).
* **Fix: `unlimitedStock` variants handled correctly** — services/digitals no longer falsely rejected as "no stock" during emission or sync.
* **Fix: Stock transfer compensation** — if reception fails, plugin rolls back inventory automatically.
* **Fix: Email send verification** — stock-move and SKU-not-found emails check `wp_mail()` return + add order note on failure.
* **Fix: Document UNIQUE constraint** — `(bsale_document_id, document_type)` prevents duplicate rows from concurrent flows.
* **Fix: License activation orphan slot prevention** — Activator compensates LS activation when local persist fails.
* **Fix: Pro licenses activate out-of-the-box** — known variant/store IDs embedded as class defaults; activation no longer requires a per-site `CB_LICENSE_VARIANT_IDS` in wp-config (previously the strict-mode default rejected every license without it). Still override-able via constant/filter.
* **Fix: License decrypt failure visibility** — surfaces "License unreadable — re-activate" instead of silent downgrade.
* **Fix: Retry button clears permanent flag** — manual retry starts with clean slate.
* **Fix: Provisional NV locking** — blocks duplicate NV emissions in Bsale.
* **Fix: Bsale outage tolerance** — `has_pending_transfer_guide` fails-open during API outages.
* **Fix: `document.failed` webhook handler** — properly records rejected documents with admin notification.
* **Fix: Bulk handlers PHP 7+ Error catch** — webhooks no longer stuck on `TypeError`.
* **Fix: Settings option autoload disabled** — API token + webhook secret not loaded on every request.
* **Fix: Uninstall cleanup completeness** — uninstall drops all 11 plugin tables + options + post meta + transients, leaving zero residue (verified on a clean WordPress + WooCommerce sandbox).
* **Fix: Price sync honors the "Sync prices" toggle in the bulk path** — high-volume price webhook bursts (>50) no longer overwrite WooCommerce prices when price sync is disabled. The bulk path now (a) respects `sync_prices=false` like the individual path, (b) only updates the variants that actually triggered webhooks instead of the whole mapped catalog, and (c) the settings sanitizer clears the sale-price sub-flag when price sync is turned off.
* Internal: Helpers `CB_Pro_UI`, `cb_is_pro()`, `cb_is_unlimited_stock_variant()`, `CB_License_Activator::scrub_license_key()`.

= 2.51.16 — 2026-05-18 =

* New: `detail_ids` field now populated for all emitted document types (boleta, factura, credit note), not just nota de venta. Improves stock event correlation in the audit system.

= 2.51.15 — 2026-05-18 =

* Fix: severity classifier for unmapped Bsale variants now correctly distinguishes physical products from services, based on the `unlimitedStock` field returned by the Bsale API.

= 2.51.14 — 2026-05-16 =

* Fix: stock webhook events from Bsale now correctly populate the `bsale_variant_id` field in the audit ledger, enabling per-variant correlation in the reconciler. Resolves the gap where 100% of stock webhook events were stored with NULL variant ID.

= 2.51.13 — 2026-05-14 =

* Refactor: migrated all on-scale spacing values in `admin.css` (216 lines, both px and rem) to the `--cb-sp-*` token system. Visual output unchanged.

= 2.51.12 — 2026-05-14 =

* New: stock health mini-panel in the Audit → Stock tab. Shows synced products count, last audit timestamp, and active discrepancies count when no pending discrepancies exist.

= 2.51.11 — 2026-05-14 =

* UX: Inventory settings now organized in sub-tabs (Stock, Documents, Sync, Reservations, Audit, Advanced). Improves discoverability of configuration options.

= 2.51.10 — 2026-05-14 =

* Design system: documented the plugin's custom `--cb-*` token system and `cb-*` class prefix as a deliberate choice independent from the hub design system canon.

= 2.51.9 — 2026-05-14 =

* Fix: when a Bsale document webhook arrives, the plugin now removes any previously recorded `plugin_emit` ledger entry for the same document. Closes the race condition between the reconciler and the webhook processor.

= 2.51.8 — 2026-05-14 =

* UX: data tables in the admin UI are now responsive on mobile viewports via horizontal scroll. Affects audit, documents, and logs tables.

= 2.51.7 — 2026-05-14 =

* UX: tablet viewports now use a 2-column grid for cards in the dashboard. Traceability table column widths adjusted to fit common Chilean SKU formats.

= 2.51.6 — 2026-05-14 =

* UX: improved logs UI with severity vs context columns. Human-readable labels for internal states (e.g. `nv_provisional_stale` → "Pending NV expired"). Cleaner empty states across the admin UI. Sub-fields use design system tokens for the left border instead of hardcoded color values.

= 2.51.0 — 2026-05-13 =

* New: unified BEM-canonical status badge system across all admin views (9 canonical states with semantic colors).
* New: monospace font token `--cb-font-mono` applied to technical data (folios, SKUs, RUTs, timestamps, prices, Bsale IDs) for tabular alignment.

= 2.50.4 — 2026-05-13 =

* New: auto-resolver for stale stock discrepancies. Reconciler now closes discrepancies that have been resolved by the deferred sync pipeline but were not yet acknowledged. Three phases: SQL bulk (no API), API-limited (50 per run), and force-sync (20 per run).

= 2.50.3 — 2026-05-12 =

* New: `compute_delta_sign` heuristic for Bsale document webhooks. Correctly determines the sign of stock movement based on `codeSii`, document type, event type, and document state. Closes the gap where `bsale_document` events stored NULL `delta_expected`.

= 2.50.2 — 2026-05-11 =

* New: `bsale_variant_id` now resolved for events written from the webhook processor (previously only set for events from the reconciler).

= 2.50.1 — 2026-05-10 =

* Fix: tracer idempotency. Order status changes no longer record duplicate ledger events when the order transitions through custom intermediate statuses.

= 2.50.0 — 2026-05-09 =

* New: 1:N product mapping (one Bsale product can map to multiple WooCommerce products) with a daily cron job to keep SKU links consistent.

= 2.49.0 — 2026-05-08 =

* New: enriched traceability admin view with product names and SKUs alongside Bsale variant IDs. Pagination, filters, and per-cron health alerts added.

= 2.48.1 — 2026-05-07 =

* New: deduplication for `stock_mismatch` and `bsale_silent_movement` discrepancies. Index added on `created_at` of the audit ledger for query performance. UI button to acknowledge discrepancies. Dynamic severity for unmapped variants.

= 2.48.0 — 2026-04-29 =

* Baseline release of the deduplication and audit-ledger features.

== Upgrade Notice ==

= 3.7.3 =
Security hardening: late output escaping in admin UI components and a defensive callback guard. No functional change. Safe update for all sites.

= 3.5.0 =
New: the Traceability screen opens with an at-a-glance stock-health verdict and a 24-hour reliability sparkline. Backward-compatible, no data changes. Safe update for all sites.

= 3.4.4 =
Compatibility fix: resolves a potential PHP 7.4 fatal in webhook handling (str_starts_with is PHP 8.0+). Recommended for any site on PHP 7.4.

= 3.4.3 =
Reliability fix: WP-CLI command registration is now null-safe against an unloaded licensing SDK. No functional changes. Safe update for all sites.

= 3.4.2 =
Spanish (Chile) polish in the Upgrade panel and status labels, mobile-friendly configuration tables, consistent brand color and motion, plus packaging hygiene. Presentation-only, no functional changes. Safe update for all sites.

= 3.4.1 =
Internal cleanup: transactional email styles are now centralized (no functional change; notification emails look the same, with one alert box tweaked to a consistent green). Safe update for all sites.

= 3.4.0 =
Fixes a data-loss edge case: saving Settings on a Free/lapsed license no longer clears saved Pro configuration. Also refreshes the Pro upsell on gated multi-control blocks. Recommended for all sites.

= 3.3.2 =
Visual consistency polish: residual admin styles now match the Admin Kit's neutrals, radii and motion. Presentation-only, no functional changes. Safe update for all sites.

= 3.3.1 =
Minor polish: Settings mapping tables are now mobile-friendly and transactional emails match the Australcode green branding. No functional changes. Safe update for all sites.

= 3.3.0 =
Admin UI refresh: all screens now share one consistent Australcode design system. No functional changes — same data, same actions, cleaner and more coherent look. Recommended for all sites.

= 3.2.0 =
Pro licensing moved to Freemius (Merchant of Record). Your active Pro license stays valid and all Free/Pro features are unchanged — activation, renewals and account management now use the native Freemius experience. No action required for existing customers.

= 3.1.4 =
Reliability release: the Repair-mappings tool preserves 1:N mappings, the Logs screen groups repeated events with a connection shortcut, stock audits resume after interruption, and API pagination gains a runaway safety cap. Recommended for all sites.

= 3.1.3 =
Compliance and admin UI polish: clears the WP 6.7 translation-timing notice and a checkout escaping warning, refreshes the admin design (unified headers, redesigned Stock Traceability) and removes decorative emoji. Recommended for all sites.

= 3.1.2 =
Product audit now badges private-status products in the unmapped list so they no longer read as problems. Presentation-only, audit coverage unchanged. Safe update for all sites.

= 3.1.1 =
Critical follow-up to 3.1.0: product sync no longer creates a spurious mapping to the wrong Bsale variant for simple products mapped to multi-variant items. Recommended for all sites on 3.1.0.

= 3.1.0 =
Critical sync fix: simple products mapped to multi-variant Bsale items no longer get the wrong variant stock or price. Also fixes Block-checkout RUT validation, silent transfer-guide failures, duplicate webhook mappings, and partial credit-note matching.

= 3.0.8 =
WP.org Plugin Check pass: release ZIP now ships clean (dev artifacts excluded), nonce annotations tightened on WooCommerce checkout reads, Upgrade Notices trimmed to fit display limit. No functional change.

= 3.0.7 =
Simplification: the 3.0.6 `sku_locked` flag is removed. WooCommerce SKU is permanently the matching key and is never overwritten by Bsale. Column dropped automatically. SKU-primary lookup and 1:N propagation preserved.

= 3.0.6 =
**Behavior change**: WooCommerce SKUs are no longer overwritten by Bsale during sync. Manual and scheduled product syncs now propagate to ALL WooCommerce products sharing a Bsale variant SKU (1:N), matching stock/price webhook behavior.

= 3.0.5 =
Polish release: dashboard activity table collapses to cards on mobile, completes brand-override cleanup, "Limpiar huérfanos" marked danger-outline, "Última auditoría" stat in monospace, ~40 inline styles extracted. No functional changes.

= 3.0.4 =
Polish release: WP.org Plugin Check now reports 0 errors, regenerated .pot, single primary CTA on Products, brand-colored buttons on Traceability, fixed mobile mid-word truncation, and one Spanish string moved to neutral conjugation. No functional changes, no manual steps.

= 3.0.3 =
Fixes the rebrand migration so a stored Pro license (and traceability history) is reconnected after upgrading; some sites reverted to free in 3.0.0–3.0.2. Idempotent, automatic, no manual steps.

= 3.0.2 =
Ensures the Bsale token and webhook secret are encrypted at rest even on a clean activation (in 3.0.1 this only happened on a version upgrade). Idempotent, no functional changes, no manual steps.

= 3.0.1 =
Security + robustness hardening (anti-SSRF on webhook fetch, encrypted Bsale credentials at rest, validated webhook bootstrap, no duplicate documents on retry, API circuit breaker, webhook de-duplication). No functional changes. Recommended before going live.

= 3.0.0 =
Rebrand to Australcode Bsale. Existing data migrates automatically and in place on upgrade; the Bsale webhook URL is unchanged, so stock sync keeps working. No manual steps required.

= 2.53.0 =

Fixes an emission lock collision so two orders emitting the same document type at the same time no longer block each other. Recommended for high-volume stores.

= 2.52.0 =

Introduces Free / Pro split. Free keeps all essentials; Pro adds auto-emission, multi-office and B2B features. If you used Pro-only features before, activate a license to keep them. Your configuration is preserved.

= 2.51.16 =

This is a stability and traceability improvement release. Recommended for all users.
