# TSHIRTORDER-1655 — API notes for Frontend: import orders from a Shopify CSV

Backend is done. The frontend has nothing for this yet.

## Screen

### 1. Button on the Orders list

On the Orders list page `/app/orders` (`src/pages/order/list.js`, the "Skapa ny" button around line 302), add a button **"Importera CSV"** next to **"Skapa ny"**. It opens a **new page** `/app/orders/import-csv`.
If a channel is selected in the "Filter by channel" dropdown, pass it along (`/app/orders/import-csv?channelId=101`) so the page preselects it.

New route in `src/components/Layout/Layout.js`, next to `/app/orders/create` (put it **before** `/app/orders/:orderId/detail`). New page, e.g. `src/pages/order/import-csv.js`.

### 2. Import page `/app/orders/import-csv`

**Form (top of the page)**
- Link/button **"Ladda ner exempelfil"**: downloads the sample CSV (endpoint 1).
- **Channel** select, required. Use the same `AsyncSelectField` as the Orders list filter (`url="/channels?showOnDropdown=true"`), preselected from `?channelId`.
- **CSV file**, required: one `.csv` file, by picking or drag-and-drop (`react-dropzone` is already installed).
- Button **"Förhandsgranska"** (submit): calls **preview** (endpoint 2). If the channel or the file changes afterwards, clear the preview list.

**Preview list (after submit)**
- Summary line: `totalOrders` orders: `totalNew` new, `totalUpdate` to update, `totalSkip` skipped.
- A table with **all** orders of the file, no paging. One row per order, expandable to show its lines.
- One **checkbox** per order. Orders with `action = skip` can't be checked; show their `errors` in red.
- A **"Markera alla giltiga"** checkbox in the table header: checks/unchecks all valid orders (`action` ≠ `skip`). All valid orders are checked by default.
- Button **"Importera till databasen"** (disabled when nothing is checked): calls **import** (endpoint 3) with the channel, the same file and the checked `orderNr`s.

**Result (after import)**
- Show the created, updated and failed orders. Created and updated orders link to `/app/orders/{countNr}/detail`; failed ones show their `message`.
- Show a button "Tillbaka till orders" back to `/app/orders?channelId=...`, and one to start a new import (reset the form).

Notes:
- Disable "Importera till databasen" while the request runs, to avoid a double import. Importing many orders takes a while (~0.3 s per order), so show a spinner.
- The user can't edit any data in the preview: the import endpoint reads the file again on the server.

## Endpoints

Base: `{REACT_APP_BASE_URL_API}/orders`. All requests are `multipart/form-data` (`FormData`) except the sample download.

### 1. Download the sample file

`GET /orders/import-csv/sample`

- **No token needed.** A plain `<a href={`${REACT_APP_BASE_URL_API}/orders/import-csv/sample`}>` works.
- The server sends it as an attachment (`shopify_order_import_sample.csv`), so the browser downloads it. Don't rely on the `download` attribute: the API is on another domain, so the browser ignores it.

### 2. Preview (saves nothing)

`POST /orders/import-csv/preview`, header `Authorization: Bearer <token>`

| Field | Type | |
|---|---|---|
| `channelId` | number | selected channel, required |
| `file` | File | `.csv`, max 10 MB |

Response `200`:

```json
{
  "channelId": 101,
  "totalOrders": 3,
  "totalNew": 1,
  "totalUpdate": 1,
  "totalSkip": 1,
  "orders": [
    {
      "orderNr": "1002",
      "action": "create",
      "existingOrderId": null,
      "existingCountNr": null,
      "dateOrder": "2026-10-21 14:30:00",
      "email": "erik@example.com",
      "customerName": "Erik Svensson",
      "customerExists": false,
      "delivery": { "name": "Erik Svensson", "company": "Svensson AB", "address": "Kungsgatan 5", "postNr": "41119", "city": "Göteborg", "country": "SE", "phone": "+46709876543" },
      "financialStatus": "paid",
      "currency": "SEK",
      "subTotal": 720, "shippingFee": 0, "discount": 80, "totalTax": 144, "totalSum": 720,
      "taxRate": 0.25,
      "items": [
        { "itemId": "csv:HO-002-L:1", "sku": "HO-002-L", "name": "Hoodie", "size": "L", "quantity": 1, "price": 500, "priceExclTax": 400, "productExists": false },
        { "itemId": "csv:MUG-003:1", "sku": "MUG-003", "name": "Mug", "size": "", "quantity": 3, "price": 100, "priceExclTax": 80, "productExists": false }
      ],
      "errors": [],
      "warnings": []
    }
  ]
}
```

| Field | Meaning / how to show it |
|---|---|
| `action` | `create` = new order → badge **"Ny"** (green). `update` = this order was already imported from a CSV into the channel; its lines will be synced with the file → badge **"Uppdateras"** (orange), link to `existingCountNr`. `skip` = has `errors`, won't be imported → badge **"Hoppas över"** (grey/red), checkbox disabled |
| `errors` | why the order is skipped: bad data (empty SKU, total 0...), or the order number already exists in the channel and the order can't be changed (not imported from CSV, or already invoiced / completed / cancelled). Show in red |
| `warnings` | info only, the order can still be imported (e.g. totals don't match, no tax in the order, order cancelled in Shopify). Show in orange |
| `customerExists` / `productExists` | `false` = will be created automatically. Small hint only, not an error |
| money fields | as in the file, **incl. tax** (`priceExclTax` = price excl. tax). Shown in `currency` |

Suggested columns for the order row: checkbox, badge, Ordernr, Datum, Kund (name + email), Leverans (city, country), Antal rader, Totalt (`totalSum`), errors/warnings.
Suggested columns for the expanded lines: SKU, Namn, Storlek, Antal, Pris (incl. tax), "Ny produkt" when `productExists = false`.

Errors (`{ "message": "..." }`):

| Status | When |
|---|---|
| 400 | no file / not `.csv` / larger than 10 MB / not a Shopify orders export (missing columns) / empty file |
| 401 | bad token |
| 403 | guest user (`ROLE_CHANNEL`) |
| 404 | channel not found |

### 3. Import

`POST /orders/import-csv`, header `Authorization: Bearer <token>`

| Field | Type | |
|---|---|---|
| `channelId` | number | same as preview |
| `file` | File | **the same file** as in preview (keep the `File` object in state) |
| `orderNrs[]` | string, repeated | checked orders: `formData.append('orderNrs[]', orderNr)` per order. ⚠️ If you send none, the API imports **all** orders without errors, so always send the checked ones and disable the button when nothing is checked |

Response `200` (also when some orders failed):

```json
{
  "created": [ { "orderNr": "1002", "id": 14167, "countNr": 75281 } ],
  "updated": [ { "orderNr": "1001", "id": 14166, "countNr": 75280 } ],
  "failed":  [ { "orderNr": "1003", "message": "Total is 0" } ]
}
```

Same error statuses as preview.

## Example

```js
// src/api/orders.js
export const previewImportOrdersCsv = (channelId, file) => {
  const fd = new FormData();
  fd.append('channelId', channelId);
  fd.append('file', file);
  return axios.post('/orders/import-csv/preview', fd);
};

export const importOrdersCsv = (channelId, file, orderNrs) => {
  const fd = new FormData();
  fd.append('channelId', channelId);
  fd.append('file', file);
  orderNrs.forEach((nr) => fd.append('orderNrs[]', nr));
  return axios.post('/orders/import-csv', fd);
};
```

## Test

Use the sample file itself: preview gives 2 orders (`#1001` with 1 line, `#1002` with 2 lines and an 80 kr discount). After importing, order 1002 shows a total incl. tax of **720**. Import the same file again and both orders come back as `updated`, with nothing duplicated.
