# Mahsanei Hashmal (מחסני חשמל) — Webhook

## Endpoint

`POST /api/machsaneyHashmal/tracking`

- **Auth:** header `Authorization: Bearer <token>` — token must match env `MACHSANEY_HASHMAL_WEBHOOK_KEY` (same shared secret; only the header name/format changed).
- **Body:** JSON with root `order` (see product spec). Required fields include `orderNumber`, `supplierCode` (קוד ספק), `customer`, `items`.

## Importer mapping

`order.supplierCode` (sent in the webhook by Mahsanei Hashmal) must match `UserSupplier.storeId` for an enabled integration with `integrationKey: mahsanei-hashmal`.

In the admin UI this field is labeled **"Store ID"** (the same label used for every other platform). The matching is **case-insensitive** and is enforced both at lookup time (collation) and at write time (unique partial index `integrationKey_1_storeId_1_unique_ci` on `UserSupplier`) — so the same `storeId` cannot be claimed by two different importers.

## Item classification (`order.items[]`)

Each item is classified by its `name` (Hebrew, `String.includes`):

| Marker in `name` | Treated as | Kept in cart? | Effect on order |
| --- | --- | --- | --- |
| Contains `איסוף עצמי` | Self-pickup marker | No | `deliveryType = self-pickup`, `shippingPriceL = 0`. Wins over `הובלה` if both appear. |
| Contains `הובלה` | Shipping line | No | Adds the active price field (see Pricing) to `shippingPriceL` (sum of all shipping lines). `deliveryType = 199`. |
| Anything else | Real product | Yes | Mapped into the cart with `sku = makat`. |

If the payload contains **no** `הובלה` and **no** `איסוף עצמי` items, the order falls back to `self-pickup` with `shippingPriceL = 0` (preserves the previous default).

## Cart mapping

- `sku` is taken from `item.makat`. The generic `enrichCartWithProductIds` (in `utils/orderHelper.js`) matches it against the importer's catalog. Unmatched SKUs raise the existing `PRODUCT_NOT_FOUND` flow.
- **Item price fields are line totals** (already `unit price × line quantity`), not unit prices. The mapper uses the active field directly as the line total and derives the unit price as `totalPrice / quantity`.
- **Duplicate `makat` rows are merged** into a single cart line by summing both `quantity` and the active price field across rows. Both webhook formats produce the same cart row (example assumes prices include VAT):
  - `[{ makat: "X", quantity: "1", priceWithVat: "48" }, { makat: "X", quantity: "1", priceWithVat: "48" }]`
  - `[{ makat: "X", quantity: "2", priceWithVat: "96" }]`
  → `{ sku: "X", quantity: 2, price: 48, totalPrice: 96 }`.
- Items without a `makat` are not merged (kept separate so they're still reported as `(ריק)` missing-SKU).

## Pricing

The webhook sends each item's price in two parallel fields — `priceWithVat` and `priceWithoutVat` — and the order-level `finalPriceWithVat` / `finalPriceWithoutVat`. The flag `order.VatExemptionEilat` selects which one represents the price that should be stored:

| `VatExemptionEilat` | Active item field | Active order total |
| --- | --- | --- |
| `0` (default — VAT applies) | `priceWithVat` | `finalPriceWithVat` |
| `1` (Eilat exemption — no VAT) | `priceWithoutVat` | `finalPriceWithoutVat` |

The flag is interpreted loosely (`1` / `"1"` / `true` → exempt). All places below use the active field consistently:

- Cart line totals (and the unit price derived from them).
- `shippingPriceL` — sum of the active price field across all shipping lines (`name` contains `הובלה`). Like product lines, the value is already a line total, so it is summed directly without multiplying by `quantity`.
- `finalPrice` is taken from the active order total field; `subPrice` is `finalPrice − shippingPriceL`. `createOrder` then recomputes `subPrice` / `finalPrice` from the cart (`subPrice = sum(line totals)`, `finalPrice = subPrice + shippingPriceL`); because the payload is internally consistent (`sum(items[priceField]) === order[totalField]`), both calculations match.

`customerNotes` is left empty for Mahsanei Hashmal orders — webhook metadata (`orderNumberClient`, `supplierCode`, `codeBranchStore`, `VatExemptionEilat`, `createdAt`) is intentionally not stored as customer-facing notes.

## Cancellation (`is_cancel`)

Every webhook payload now carries `order.is_cancel` (`0` = regular order, `1` = cancellation). The flag is interpreted loosely (`1` / `"1"` / `true` → cancellation).

- `is_cancel = 0` (or missing) → processed as a new order (`processNewOrder`).
- `is_cancel = 1` → routed to `processCancellation`, which finds the existing order (matched by `orderNumber` + `orderSource: MAHSANEY_HASHMAL` + owner) and moves it to status `cancellation`. The default sub-status `cancellation-new` (חדש-ביטול) is set automatically by `_handleSubStatusTransitions` (first sub-status by `order` in the cancellation category).
- If the order does not exist yet, the webhook is acknowledged and a `not_found` result is logged — we never auto-create an order from a cancellation payload.
- If the order is already in `cancellation`, the webhook is a no-op (`already_cancelled`).

The legacy detection signals (`event === 'cancel' | 'cancellation'`, root-level `cancelled === true`, `order.status === 'cancelled'`, `order.cancelled`, `order.isCancelled`) are still recognised for backward compatibility.

## Env

See [../../.env.example](../../.env.example) — `MACHSANEY_HASHMAL_WEBHOOK_KEY`.
