=== Ultrafan ===
Contributors: @ultrafan
Tags: affiliate, tracking, conversion, woocommerce, marketing
Requires at least: 6.2
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 1.38.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Connects WooCommerce to the Ultrafan affiliate network - handles clicks, conversion pixels, COD payments, refunds, and sends reconciliation reports.

== Description ==

**Ultrafan** is the official WooCommerce integration for the [Ultrafan](https://ultrafan.world) affiliate network. It automates the full affiliate lifecycle inside your WooCommerce store without requiring any JavaScript snippets or external tag managers.

= Key Features =

* **Click tracking** — Captures `transaction_id`, `network_id`, `offer_id`, and all UTM parameters from affiliate landing URLs. Parameters are stored in first-party cookies so attribution survives the entire checkout journey.
* **Conversion pixel** — Fires `POST /conversion` to the Ultrafan server the moment an order is placed, with full order details (amount, currency, items, payment method).
* **COD settlement** — When a cash-on-delivery order's invoice is marked paid, the plugin fires `POST /conversion/settle` automatically.
* **Refund & cancellation webhooks** — On credit-memo creation or order cancellation the plugin notifies Ultrafan in real time (`POST /conversion/refund`).
* **Periodic reconciliation** — A configurable cron job (default: Monday 02:00) batches paid orders and refunds into a signed `POST /reconcile` report. A **Run Now** button in WP Admin lets you send ad-hoc reports for any date range.
* **Admin transparency** — A dedicated **Ultrafan → Reconciliation** menu in WP Admin shows every reconciliation run with status, record count, HTTP response, and the exact date range covered.
* **HPOS compatible** — Fully compatible with WooCommerce High-Performance Order Storage.

= External Service =

This plugin communicates with the **Ultrafan affiliate API** operated by NewPlay Technology:

* **Service URL:** `https://affiliate.newplay.tech` (production) / `https://test-affiliate.newplay.tech` (test&development)
* **Endpoints used:** `/conversion`, `/conversion/settle`, `/conversion/refund`, `/reconcile`
* **Data sent:** affiliate transaction ID, order ID, order total, currency, payment method (normalised to a short code), base64-encoded item list, delivery cost, subtotal, and discount amount.
* **Privacy policy:** https://www.ultrafan.world/privacy-policy
* **Terms of service:** https://www.ultrafan.world/terms-conditions

No personal data (name, email, address) is included in any outbound request. The plugin uses a pre-shared API key (stored in WP options) to authenticate with the server.

== Installation ==

**From the WordPress Plugin Directory (recommended):**

1. Go to **Plugins → Add New** in your WP Admin.
2. Search for "Ultrafan".
3. Click **Install Now** then **Activate**.
4. Go to **Ultrafan → Settings** to enter your credentials.

**Manual upload:**

1. Download the plugin zip from the WordPress Plugin Directory.
2. Go to **Plugins → Add New → Upload Plugin** and upload the zip.
3. Activate and configure as above.

**Configuration:**

After activation, navigate to **Ultrafan → Settings**:

| Setting                | Description                                                                                              |
| ---------------------- | -------------------------------------------------------------------------------------------------------- |
| Merchant ID            | Your `shop_id` from the Ultrafan server. Sent as `X-Merchant-ID` on reconciliation and settlement calls. |
| Merchant Name          | Display name included in reconciliation headers.                                                         |
| API Key                | Per-merchant secret provided by NewPlay Technology. Stored encrypted.                                    |
| Enable Reconciliation  | Enables or disables the automatic reconciliation cron job.                                               |
| Cron Schedule          | Standard cron expression — default `0 2 * * 1` (Monday 02:00).                                           |

== Frequently Asked Questions ==

= What affiliate network does this plugin support? =

This plugin is built exclusively for the **Ultrafan** affiliate network operated by NewPlay Technology. It is not a generic affiliate plugin.
The support is via email help@ultrafan.world.

= What data is sent to the Ultrafan server? =

Each conversion call includes: an anonymised affiliate transaction ID, the WooCommerce order ID, grand total, currency, normalised payment method code, base64-encoded item list (SKU, name, price, quantity), delivery cost, subtotal, and discount amount. No customer name, email, or shipping address is ever transmitted.

= Is the plugin compatible with WooCommerce HPOS? =

Yes. The plugin explicitly declares compatibility with WooCommerce High-Performance Order Storage (custom order tables).

= Can I trigger a reconciliation report manually? =

Yes. Go to **WooCommerce → Ultrafan → Reconciliation**, choose a date range, and click **Run Now**.

= What payment method codes are sent? =

| Code  | Meaning                                                 |
| ----- | ------------------------------------------------------- |
| `COD` | Cash on delivery / deferred payment                     |
| `WAL` | PayPal, Apple Pay, Google Pay, or other digital wallets |
| `CRC` | Credit/debit card (Stripe, Braintree, Adyen, etc.)      |
| `DEF` | Bank transfer                                           |
| `OTR` | Any unrecognised gateway                                |

= What happens if the Ultrafan server is unreachable? =

The plugin retries failed conversion and settlement calls. Reconciliation failures are logged in the **Reconciliation Runs** admin screen and will be retried on the next cron run (unreconciled records are never lost).

= Does this plugin set cookies? =

Yes. First-party cookies (`ultrafan_transaction_id`, `ultrafan_network_id`, UTM cookies) are set for 5–30 days when a visitor lands via an affiliate link. A long-lived `affiliate_ultrafan` cookie (365 days) is also set for returning-customer attribution. All cookies use `SameSite=Lax; Secure` attributes.

== Screenshots ==

1. **Settings page** — Configure Merchant ID, API Key, cron schedule, and product-feed options under Ultrafan → Settings.
2. **Reconciliation Runs** — History of every reconciliation attempt with status, record count, HTTP response, and date range.
3. **Order meta** — Affiliate tracking data (transaction ID, network, UTM params, conversion/settlement status) visible on the WooCommerce order detail page.

== Cookies & localStorage ==

Cookies and localStorage parameters are GDPR compliant, as they do not contain and client data, and they are in favour of the client.
The parameters are:
- transaction_id, user id (utm_conten t), conversion id (utm_term) - ultrafan affiliate parameters
- utm_source="ultrafan", utm_medium="affiliate", utm_campaign=... (not defined, future use) - the merchant to see, that this purchase is from affiliate
- network_id = whether it is prod/stage/test/dev

== Changelog ==

= 1.38.0 =
* No change to how the plugin behaves. The version number moves to 1.38.0 so that every UltraFan shop integration — WooCommerce, OpenCart, PrestaShop and Magento — carries the same version and implements the same published merchant specification (1.38.0). Until now the four ran on independent version numbers, so the version told you nothing about which rules a shop followed. Everything the release describes was already in place here: reconciliation has reported money movements from a permanent record of events since 1.37.0, and a cancellation has reported only what was actually collected since 1.37.7.

= 1.37.7 =
* Fixed: cancelling an order that had not been paid for — a cash-on-delivery order cancelled before delivery, for example — reported its full value to UltraFan as money returned. Because nothing had been collected in the first place, UltraFan saw a refund larger than the payment and set the order aside for manual review. A cancellation now reports only what was actually collected, so an unpaid order that is cancelled is correctly recorded as having moved no money. Cancelling an order that *was* paid for is unchanged.

= 1.37.6 =
* Each reconciliation batch now carries the run number it belongs to, so a run in this plugin lines up with the report UltraFan recorded.
* The run is recorded before the batch is sent, so a problem writing it is caught before any records leave rather than after UltraFan has accepted them.

= 1.37.5 =
* Fixed: card and wallet orders were left out of the reconciliation batch, so they never matched against the figures UltraFan had already recorded for them. They are now included from the moment the order is placed, matching how UltraFan counts them. Cash on delivery and bank transfer still wait until payment is confirmed.

= 1.37.4 =
* A reconciliation run that has nothing to send is now recorded on the Reconciliation Runs screen, with an explanation of why, instead of leaving no trace at all.
* The explanation reports how many affiliate events exist, how many are money movements, how many are still unreconciled and how many fall inside the run's period — so an unexpectedly empty run can be diagnosed without database access.

= 1.37.3 =
* Fixed: refunding specific line items failed and left the WooCommerce admin showing a spinner that never stopped, on a refund that had in fact been saved. Refunding by amount only was unaffected. The affiliate refund call is now sent correctly.

= 1.37.2 =
* Fixed: a failure while reporting an order to the affiliate network can no longer interrupt checkout, a settlement or a refund. The reason is written to the Ultrafan log and the shop operation completes normally.
* Each affiliate hook now records that it started, so a failed report can be traced from the Ultrafan log without server access.

= 1.37.1 =
* Fixed: issuing a refund could hang the WooCommerce admin with a spinner that never stopped, while the refund itself was already saved. Recording an affiliate event is bookkeeping and can no longer interrupt a refund, a settlement or checkout — if it fails, the reason is written to the Ultrafan log and the affiliate call still goes out.
* Fixed: real-time affiliate calls no longer retry, so they cannot multiply how long a refund or checkout takes. Retries are kept for the scheduled reconciliation run, where nobody is waiting; a call that fails is still reported by reconciliation.

= 1.37.0 =
* Reconciliation is now built from an immutable money-movement event ledger instead of the current state of each order, per UltraFan Merchant Integration Requirements v1.35.0 (build guide section 10).
* Fixed: paid_amount was sent net of refunds while the refund was also reported separately, so a 54.00 order refunded 20.00 reconciled as 14.00 against an online figure of 34.00 and never matched. The gross amount is now sent, with each refund as its own zeroed record.
* Fixed: orders awaiting cash-on-delivery payment were included in the batch, which made UltraFan classify them as unmatched rather than pending. An order that has not been paid now produces no record.
* Fixed: bank transfer and cheque orders reported payment_status "paid" at checkout even though no money had been received.
* Added: outbound calls now retry up to 3 times with backoff (never on a 4xx).
* Added: each reconciliation run stores the exact records it sent, viewable via a new "View" link on the Reconciliation Runs screen.
* Note on upgrading: the event ledger starts empty. Money movements from before this upgrade are not reconciled, and the reconciliation window is re-anchored to the upgrade time. Orders already reported are not resent.

= 1.36.2 =
* Fixed the **Ultrafan → Orders** screen listing every store order instead of only affiliate orders on sites using the legacy WordPress posts order storage. The grid now selects affiliate orders directly from order meta, so it behaves the same whether or not High-Performance Order Storage is enabled.
* Fixed the Orders screen pagination rendering a link for every page (hundreds of buttons on large stores); it now shows a compact, windowed pager.
* Fixed reconciliation re-sending orders it had already reconciled on sites using the legacy WordPress posts order storage. Already-reconciled orders are now skipped in code, so each paid order is reported to the affiliate server only once regardless of the storage backend.
* Reconciliation log entries now report how many candidate orders were eligible versus skipped (non-affiliate or already reconciled), instead of only the raw candidate count — so a "found N, sent 0" run is clear at a glance.

= 1.36.1 =
* Card and other off-site payments now record a conversion reliably. Previously the conversion pixel only fired when the shopper reached the order-received (thank-you) page, so orders paid through gateways that confirm payment by redirect or webhook (for example Stripe) could be missed. Conversion now also fires the moment payment completes.
* Conversions are no longer sent twice. A single order fires exactly one conversion across the thank-you and payment-completed triggers, and a conversion the affiliate server declines is no longer retried in a loop. The server's response is now recorded in the logs when a conversion is declined, to make troubleshooting easier.
* Settlement is now limited to cash-on-delivery and other offline methods (bank transfer, cheque), matching the Magento module. Card, wallet, and buy-now-pay-later orders — which are already reported as paid at checkout — no longer trigger a settlement call.

= 1.36.0 =
* Fixed automatic reconciliation never running: the first scheduled run used an empty time window so no orders were ever picked up. It now looks back over a real window and tracks its own progress cursor, independent of the run history.
* Fixed manual "Run Now" reconciliation corrupting the automatic schedule — a manual run over an arbitrary date range no longer drags the nightly job's progress backwards.
* Reconciliation now selects orders by last-modified date, so cash-on-delivery and other offline orders that are settled days after checkout are correctly reconciled instead of being missed.
* On-hold orders are no longer permanently frozen as unpaid on the affiliate server; their paid state is reported once they reach processing/completed.
* Reconciliation now back-stops refunds whose real-time refund webhook failed to send.
* Cancellations issued after a partial refund no longer double-count the already-refunded amount.
* The product feed is now written through the WordPress filesystem API.
* Plugin reactivation no longer risks clearing saved settings when only the internal version marker is missing.

= 1.35.1 =
* Fixed affiliate orders not appearing in the **Ultrafan → Orders** grid on stores using the block-based Checkout. Affiliate tracking (transaction_id, network_id, UTM params) is now persisted to order meta on both the classic and block/Store API checkout, so the Orders grid populates and the downstream conversion, settlement, refund, and reconciliation flows have the data they rely on.
* Cancellation webhooks now skip foreign (non-Ultrafan) affiliate orders, matching the conversion, settlement, and refund flows and the Magento module's behaviour.
* Added missing log entries across the settlement, refund, and cancellation flows (early-exit conditions and a pre-send "Firing…" entry) so every webhook attempt is traceable in **Ultrafan → Settings → Logs**.

= 1.35.0 =
* Refactored the plugin into a namespaced MVC + service-class architecture (Ultrafan\ namespace, PSR-4 autoloader) with `declare(strict_types=1)` on every file and consistent naming throughout. No change to tracking, conversion, settlement, refund, reconciliation, or feed behaviour, and existing settings/order data are preserved.
* Moved the settings screen out of the WooCommerce Integrations tab into a dedicated **Ultrafan → Settings** page (WordPress Settings API). The same option storage is reused, so existing configuration carries over automatically.
* Decoupled logging from WooCommerce's WC_Logger. The plugin now keeps its own log in a dedicated table, viewable under **Ultrafan → Settings → Logs** (with level filter and a clear action). Every log entry is written locally and, on a best-effort basis, also sent to the affiliate log endpoint.
* Fixed an in-request transaction_id hand-off that never took effect due to a mismatched global-variable name.

= 1.33.1 =
* Added missing assets

= 1.33.0 =
* S2S POST tracking: implemented the token-in-path contract. POST /ultrafan/tr stores the payload keyed by an opaque token; GET /ultrafan/tr/{TOKEN} resolves it, persists the affiliate cookies/session, and 302-redirects to the stored target_url. Fixes POST-tracked visitors landing on the shop home instead of the product page.
* Merges the product-feed feature with the token-based S2S tracking contract.
* Send X-Merchant-ID on every outbound call (conversion, settle, refund) so the affiliate server can enforce the per-merchant API key on /conversion too. Corrected the API Key setting help text.

= 1.31.3 =
* Ultrafan Orders grid and order meta box now display User ID (utm_content) and Conversion ID (utm_term) with a fallback to WooCommerce Order Attribution meta, so they show even when the Ultrafan copy is empty.

= 1.31.2 =
* Order attribution parity: affiliate orders now populate WooCommerce's native "Order attribution" panel server-side, so GET and S2S/POST tracking show identical attribution (previously POST orders showed "Direct").

= 1.31.1 =
* Product Feed screen: added a "Copy URL" button next to the latest feed URL (View/Download).

= 1.31.0 =
* Added Product Feed export: generates a Google Shopping style JSON feed of the WooCommerce catalogue.
* New "Enable Product Feed" checkbox in the General settings section and a "Product Feed" settings section (brand, default Google product category, feed title/description).
* New "Ultrafan Product Feed" admin screen (shown only when enabled) with export history, manual "Generate Feed Now" button, and view/download links.
* Daily WP-Cron export at 03:00 AM (site timezone) writing to wp-content/uploads/ultrafan-feed/.

= 1.30.1 =
* Added check for network id to avoid invalid captures

= 1.30.0 =
* Initial public release (aligned with other stores).
* Click tracking with first-party cookies (`transaction_id`, `network_id`, UTMs).
* Conversion webhook: `POST /conversion` with JSON body and API key authentication.
* COD settlement webhook: `POST /conversion/settle`.
* Refund and cancellation webhooks: `POST /conversion/refund`.
* Reconciliation cron: `POST /reconcile` with per-merchant API key, refund records included.
* Admin UI: Reconciliation Runs log with Run Now button.
* HPOS compatibility declaration.
* All cookies use `SameSite=Lax; Secure`.

== Upgrade Notice ==

= 1.38.0 =
Version alignment across the four UltraFan shop integrations. No behaviour change and nothing to reconfigure.

= 1.30.0 =
Initial release — not uploaded in WordPress Plugin Directory.
