# TSHIRTORDER-1655 — Import order từ CSV (format Shopify) trên giao diện Orders

## Yêu cầu gốc

> **TSHIRTORDER-1655 Import order from csv - add function in front**
>
> create order import full standard
>
> add button next to create - - after select channel
>
> show list before import
>
> Use shopify format csv , show all

Kèm ảnh chụp màn hình trang Orders hiện tại khi đã chọn channel (xem `files/orders-list-channel-selected.png`).

Bổ sung từ trao đổi: backend phải tạo 1 file **sample CSV** để bên FE cho user click download file mẫu về.

---

## Tổng quan

Thêm chức năng **import order từ file CSV export Orders của Shopify** cho 1 channel được chọn. User bấm nút **Importera CSV** cạnh **Skapa ny** trên trang Orders → page import: chọn channel + file, **xem danh sách tất cả order trong file**, tick order muốn import, bấm import thì hệ thống tạo/cập nhật order theo **đúng luồng import Shopify hiện có** (`OrderService::importFromWPData()`).

**Phạm vi ticket này: chỉ API backend.** Frontend (repo `D:\work\projects\frontend-ts-new-order-system`) do bên FE làm. Bên mình chỉ dùng FE để kiểm tra giao diện. Mục [Frontend](#frontend-tham-khảo-cho-fe-không-thuộc-phạm-vi) bên dưới ghi lại để FE tham khảo.

### Cách hiểu yêu cầu (đã xác nhận)

| Yêu cầu gốc | Hiểu là |
|---|---|
| *Import order from csv - add function in front* | Hiện import CSV chỉ chạy bằng command đọc SFTP. Ticket này làm **API** để import từ giao diện. |
| *create order import full standard* | Order import đi qua luồng import Shopify chuẩn: tạo customer, tạo product nếu chưa có, size/sub-product, giá theo `importPrice`, trừ kho, Tryck tự thêm, kickback. |
| *add button next to create - - after select channel* | Nút đặt cạnh **Skapa ny** trên trang Orders, mở page import riêng có ô chọn channel (chọn sẵn channel đang lọc ở list nếu có). **Order import vào channel đã chọn** (bắt buộc `channelId`). |
| *show list before import* | Có API **preview** trả danh sách order đọc được (không ghi DB). User xác nhận rồi mới gọi API **import**. |
| *Use shopify format csv , show all* | Đầu vào là CSV export Orders chuẩn của Shopify. "show all" = **hiện tất cả order trong file** ở bước preview, trước khi import. |

### Đã xác nhận

| # | Câu hỏi | Trả lời | Ghi chú kỹ thuật |
|---|---------|---------|-------------------|
| a | "show all" là gì? | Hiện tất cả danh sách order trước khi import | API preview trả về toàn bộ order, không phân trang |
| b | Số order lấy từ đâu? | Giữ nguyên `Name` của Shopify (`#1001` → `1001`). Khi import phải chọn channel để import vào | `orderNr` = `Name` bỏ `#`; `orderCountNr` vẫn tự tăng như mọi order (`add()`) |
| c | SKU chưa có product trong channel? | Tự tạo product, giống logic của các import khác | Dùng nhánh tạo product của `importFromWPData()` (`OrderService.php:3587-3613`) |
| d | Order đã tồn tại? | Theo logic Shopify | Xem [Logic Shopify hiện có](#logic-import-shopify-hiện-có-áp-dụng-cho-csv) — order cùng channel + `orderNr` đã có thì **cập nhật item**, không tạo mới. Ngoại lệ (bổ sung khi review, xem [Review](#review-code--test-lại-api--fe)): order **không do import CSV tạo**, hoặc đã **xuất hoá đơn / Completed / huỷ** → `skip` |
| e | SKU rỗng? | Báo lỗi khi preview | Order có dòng SKU rỗng → `action = skip` + `errors`, không import |
| f | Thuế xử lý thế nào? | Làm giống Shopify. Order không có thuế (Taxes = 0): giữ cách tính, thêm cảnh báo trong preview (cách 2) | Giá item + phí ship coi là **gồm thuế**, chia `1 + rate` — xem [Thuế](#thuế-import-shopify-hiện-tại-làm-thế-nào) |
| g | Có lấy discount không? | Lấy discount luôn, làm giống Shopify | `Discount Amount` → `discount` của `importFromWPData()` (coi là gồm thuế, chia `1 + taxDefault`) |
| h | File mẫu? | Backend tạo 1 file sample CSV, FE cho user click download | File tĩnh trong repo + API `GET /orders/import-csv/sample` trả file dạng attachment — xem [File mẫu](#get-ordersimport-csvsample--tải-file-mẫu) |

### ⚠️ Phát hiện quan trọng: đã có sẵn 2 luồng import liên quan

| Hạng mục | File | Trạng thái |
|---|---|---|
| **Import order Shopify (qua API Shopify)**: map order Shopify → mảng chuẩn, rồi tạo/cập nhật order | `ShopifyService::generateOrderDataFromJson()` `src/Service/ShopifyService.php:705`, `OrderService::importFromWPData()` `src/Service/OrderService.php:3354`, cronjob `ShopifyCloneOrderCommand` | ✅ Có. **Tái sử dụng `importFromWPData()` cho CSV** |
| Import CSV format Shopify (Olamerlin/Nakata/Boltic, đọc SFTP) | `OrderService::importCsvData()` `:2201`, `FileService::importOrderReadFileContent()` `:572` | ✅ Có, nhưng channel hard-code theo `synId`, đọc theo chữ cột, có `dd()` và nhiều lỗi mapping (bên dưới). **Không dùng lại** |
| Tạo order chuẩn `add()` / `update()` | `OrderService.php:1377`, `:1553` | ✅ Có (được `importFromWPData()` gọi) |
| Tryck tự thêm khi lưu item | `OrderService::addTryckOrderProducts()` `:928` | ✅ Có. `importFromWPData()` gọi `update()` ở cuối nên Tryck tự có |
| Setting `importPrice` của channel | `Channel::isImportPrice()` | ✅ Có |
| Đọc CSV bằng PhpSpreadsheet | `FileService.php:572` | ✅ Có mẫu |
| API preview / import CSV cho channel bất kỳ | — | ❌ Chưa có |

→ **Không cần entity mới, không cần migration.**

---

## Logic import Shopify hiện có (áp dụng cho CSV)

`importFromWPData([$orderItem])` (`OrderService.php:3354-3778`), được cronjob Shopify gọi với dữ liệu từ `generateOrderDataFromJson()`:

1. **Channel**: tìm theo `synId` = `$data['channel_id']`. ⚠️ Channel user chọn có thể không có `synId` → đã thêm `$data['channel_entity_id']` (tìm channel theo id).
2. **Customer**: tìm theo email **trong channel**. Không có email thì dùng `{orderNr}@no.email`. Không tìm thấy thì tạo customer mới (tên = first + last + company của billing, type/status mặc định).
3. **Order**: tìm theo **`channelId` + `orderNr`** (chưa xoá):
   - **Chưa có** → `add()` với `createdFrom = import_from`, địa chỉ giao hàng lấy từ shipping, `contactEmail`, `shippingFee`, `discount`, `dateOrderString`, payment type theo tên (chưa có thì tạo `StatusList`).
   - **Đã có** → **không tạo mới, không sửa header** (địa chỉ, ngày... giữ nguyên). Chỉ cập nhật `shopifyOrderId/Shop`, rồi **đồng bộ item theo `item_id`**.
4. **Item** (với từng dòng):
   - Tìm product theo SKU **trong channel** (`show_product_children = yes`). Không có thì **tạo product** (sku, name, giá excl. tax, `priceEcomIncTax`, `taxCode`). Có thì cập nhật `taxCode`.
   - `size` có giá trị → tìm/tạo `StatusList` size, tìm/tạo sub-product `{sku}_{sizeId}`.
   - `OrderProduct` cùng `item_id` đã có → cập nhật giá/tên/SL/màu/size. Chưa có → tạo mới, copy thông tin production, **trừ kho** (`updateStock`).
   - Giá: `importPrice !== false` thì lấy giá trong file, ngược lại lấy giá product.
5. Cuối cùng: **xoá item cũ không còn trong file** (theo `item_id`), rồi `update($orderId, generateItem($order))` (tính tổng + Tryck), `updatePriceKickback()`. *(Trước TSHIRTORDER-1655 thứ tự ngược lại → tổng sai, xem mục "Lỗi có sẵn ... đã sửa".)*
6. Từ `generateOrderDataFromJson()`: bỏ qua order `totalPrice <= 0`. Bỏ qua cả order nếu có dòng thiếu product/variant/giá. Giá Shopify **gồm thuế** được quy về **chưa thuế**: `price / (1 + taxRate)`. Phí ship cũng vậy.

### Hệ quả khi import lại cùng file / file mới hơn

- Cùng order, cùng dòng → cập nhật, **không nhân đôi**. Điều kiện là `item_id` sinh ra ổn định (xem mapping).
- Dòng bị bỏ khỏi file → **bị xoá khỏi order**, tổng tiền tính lại.
- Chỉ áp dụng cho order do import CSV tạo (`createdFrom = shopify_csv`) và chưa xuất hoá đơn / Completed / huỷ; order khác → `skip`.
- ⚠️ Item cũ bị xoá hoặc SL thay đổi **không hoàn kho** (logic Shopify hiện tại cũng vậy). Ghi nhận, không sửa trong ticket này.

---

## Mapping CSV Shopify → `$orderItem`

Đọc theo **tên header** (không theo chữ cột). Các dòng cùng `Name` gộp thành 1 order. Các trường của order **chỉ có ở dòng đầu** của order đó.

| `$orderItem` | Cột CSV Shopify | Ghi chú |
|---|---|---|
| `channel_entity_id` | — | id channel user chọn (thay cho `channel_id` = `synId` của Shopify API) |
| `order_nr` | `Name` | bỏ `#` |
| `import_from` | — | **`shopify_csv`** (KHÔNG dùng `shopify`, xem bẫy #1) |
| `date_created` | `Created at` (rỗng thì `Paid at`) | `2026-10-20 10:15:00 +0200` → `Y-m-d H:i:s` (giữ giờ địa phương của shop) |
| `currency` | `Currency` | |
| `subtotal` / `tax` / `total` | `Subtotal` / `Taxes` / `Total` | `Total <= 0` thì bỏ qua (giống Shopify) |
| `shipping_fee` | `Shipping` | quy về chưa thuế (xem bẫy #3) |
| `discount` | `Discount Amount` | |
| `taxDefault` | `Tax 1 Name` (vd `VAT 25%`) | parse %, không có thì dùng `tax_default` |
| `payment.title` | — | để trống như Shopify API import → `add()` lấy payment type mặc định của channel/customer (không tạo `StatusList` payment type mới như "Shopify Payments") |
| `payment.method` | `Payment Method` | chỉ vào **Kommentar** của order (`"{method} - {title}"` → `Shopify Payments -`) |
| `comment` | `Notes` | đưa vào `intoText` |
| `billing_address.*` | `Billing Name` (cả tên vào `firstname`, `lastname` rỗng), `Billing Company`, `Billing Street` (rỗng thì `Address1` + `Address2`), `Billing Zip`, `Billing City`, `Billing Country`, `Billing Phone` (rỗng thì `Phone`), `Email` | `importFromWPData()` ghép `firstname lastname company` làm tên |
| `shipping_address.*` | như billing, với các cột `Shipping *` | |
| `items[].item_id` | — | **sinh ổn định**: `csv:{sku}:{n}` (n = lần xuất hiện thứ n của SKU trong order) |
| `items[].sku` | `Lineitem sku` | |
| `items[].name` / `size` | `Lineitem name` | Shopify ghi dạng `Title - Variant`: tách ở ` - ` **cuối cùng**, không có thì size rỗng |
| `items[].quantity` | `Lineitem quantity` | |
| `items[].price` / `priceEcomIncTax` | `Lineitem price` | coi là gồm thuế (giống Shopify): `price = Lineitem price / (1 + rate)`, `priceEcomIncTax = Lineitem price` |
| `items[].taxRate` | như `taxDefault` | |

Không set `shopifyOrderId` / `shopifyShop` / `sync_url` (CSV không phải order đồng bộ Shopify).

#### ⚠️ Lưu ý bẫy quan trọng

1. **`createdFrom = 'shopify'` sẽ đẩy fulfillment ngược lên Shopify** khi order chuyển Completed (`postOrderUpdateComplete()` `OrderService.php:4932` → `resyncOrderToShopify()`). Order từ CSV **phải** dùng `shopify_csv`. Khi đó order rơi vào nhánh WP, `resyncUrlIntegration` rỗng nên dừng, giống order tạo tay.
2. **Channel tìm theo `synId`** trong `importFromWPData()`. Cần cho phép truyền thẳng id channel (vd `$data['channel_entity_id']`). Giữ nguyên hành vi cũ khi không truyền, để không ảnh hưởng cronjob Shopify/WP.
3. **Giá gồm hay chưa gồm thuế**: xem mục [Thuế](#thuế-import-shopify-hiện-tại-làm-thế-nào) bên dưới.
4. **SKU rỗng** (đã chốt #e): Shopify sync dùng product id thay SKU, nhưng CSV không có product id → **báo lỗi trong preview, order `skip`**.
5. Tiền Shopify dùng dấu `.` thập phân, delimiter `,`. File có thể có BOM UTF-8.
6. `importFromWPData()` bắt `\Exception` và trả 500. Gọi từng order riêng để 1 order lỗi không chặn các order khác. Nếu EntityManager bị đóng sau lỗi Doctrine thì dừng và báo phần còn lại là chưa import.
7. `Name` trùng với order **ở channel khác** → **không** coi là trùng (lọc theo channel). Đây chính là lỗi của `importCsvData()` cũ.

#### Thuế: import Shopify hiện tại làm thế nào

Code: `ShopifyService::generateOrderDataFromJson()` `ShopifyService.php:732-745`, `:818-833` + `OrderService::importFromWPData()`.

| Phần | Shopify API import đang làm | Ghi chú |
|---|---|---|
| Giá item | **Luôn coi là gồm thuế**: `price = variant.price / (1 + taxLines[0].rate)` | Không kiểm tra setting `taxesIncluded` của shop. Lấy giá **hiện tại của variant**, không phải giá bán trên dòng order (giảm giá theo dòng bị mất) |
| Thuế suất item | `taxLines[0].rate` của từng dòng (vd `0.25`) | Ghi vào `taxCode` của product (`rate * 100`), product đã có cũng bị ghi đè `taxCode` |
| `priceEcomIncTax` | = `variant.price` | |
| Phí ship | `totalShippingPrice / (1 + rate)`, rate = `shippingLine.taxLines[0].rate` | ⚠️ Bug: fallback dùng `$currentTaxLines` chưa khai báo (đúng ra là `$order['currentTaxLines']`) → ship không có tax line thì rate = 0, phí ship giữ nguyên **gồm thuế** |
| Subtotal / Taxes / Total | Có đọc nhưng **không dùng** | `update()` tự tính lại tổng từ item + thuế suất product |
| Discount | Không truyền → `0` | `importFromWPData()` có hỗ trợ `discount` (gồm thuế, chia `1 + taxDefault`) nhưng Shopify không gửi |

**Đã chốt (#f, #g) cho CSV: làm giống Shopify**, chỉ đổi nguồn dữ liệu:

- `Lineitem price` coi là **gồm thuế** → chia `1 + rate`.
- `rate` lấy từ `Tax 1 Name` (vd `VAT 25%` → `0.25`), không có thì dùng `tax_default` (`0.25`). ⚠️ Chỉ **1 thuế suất / order** (CSV không có thuế suất theo dòng như API): order có nhiều mức thuế (vd 25% + 12%) sẽ tính hết theo `Tax 1`.
- Phí ship `Shipping` chia `1 + rate` (không mắc bug fallback = 0 như trên).
- `Discount Amount` truyền vào `discount` (khác Shopify API vì CSV có sẵn cột này; đã chốt #g). `importFromWPData()` coi discount là gồm thuế → `discountExclTax = discount / (1 + taxDefault)`.
- Order **không có thuế** (`Taxes = 0`, vd bán ra ngoài EU): **giữ nguyên** cách tính (vẫn chia `1 + tax_default`, tổng order sẽ thấp hơn Shopify 20%), preview **cảnh báo** `No tax in this order (Taxes = 0)...`. Không dùng rate 0 vì `importFromWPData()` sẽ ghi đè thuế suất product thành 0% (đã chốt cách 2).
- Subtotal/Total chỉ dùng để hiển thị trong preview; tổng order do `update()` tính lại. Preview **cảnh báo** (`warnings`) nếu `Σ(SL × Lineitem price) + Shipping − Discount` lệch `Total` trong file > 1 kr (dấu hiệu shop để giá chưa gồm thuế).

#### Lỗi của `importCsvData()` cũ (lý do không dùng lại)

Tìm order trùng theo `orderNr` **trên toàn hệ thống** (`:2342`). `deliveryCountry` lấy Billing Country (`AG`). `shippingMethod` bị ép `(float)`. Ngày lấy `Paid at`. Đọc theo chữ cột. SKU rỗng thì tạo product giả `99`. Có `dd()`. Gọi `update()` lại mỗi dòng.

---

## API contract

Prefix `/api/v1/orders`, header `Authorization: Bearer <token>`, `getToken($authorization, true, false, true)` để có `$user`. Khai báo **trước** các route `/{id}` trong `order.yaml`.

### `POST /orders/import-csv/preview` (multipart/form-data)

Chỉ đọc file, **không ghi DB**.

| Field | Type | Ghi chú |
|---|---|---|
| `channelId` | int | bắt buộc |
| `file` | file `.csv` | Shopify Orders export |

Response 200:

```json
{
  "channelId": 101,
  "totalOrders": 3,
  "totalNew": 1,
  "totalUpdate": 1,
  "totalSkip": 1,
  "orders": [
    {
      "orderNr": "1001",
      "action": "create",
      "existingOrderId": null,
      "dateOrder": "2026-10-20 10:15:00",
      "email": "a@b.se",
      "customerName": "Anna Andersson",
      "customerExists": true,
      "delivery": { "name": "Anna Andersson", "company": "", "address": "Gatan 1", "postNr": "11122", "city": "Stockholm", "country": "SE", "phone": "" },
      "financialStatus": "paid",
      "currency": "SEK",
      "subTotal": 400.0, "shippingFee": 49.0, "discount": 0, "totalTax": 89.8, "totalSum": 449.0,
      "taxRate": 0.25,
      "items": [
        { "itemId": "csv:TS-001-M:1", "sku": "TS-001-M", "name": "T-shirt", "size": "M", "quantity": 2, "price": 250.0, "priceExclTax": 200.0, "productExists": true }
      ],
      "errors": [],
      "warnings": []
    },
    { "orderNr": "1000", "action": "update", "existingOrderId": 80001, "existingCountNr": 50400, "...": "...", "warnings": ["Order already exists in this channel, its lines will be synced with the file"] },
    { "orderNr": "0999", "action": "skip", "errors": ["Total is 0"], "items": [] }
  ]
}
```

- `action`: `create` (chưa có trong channel), `update` (đã có, do import CSV tạo → đồng bộ item theo logic Shopify), `skip` (có `errors`: dữ liệu sai, hoặc order đã có nhưng không do CSV tạo / đã xuất hoá đơn / Completed / huỷ).
- `warnings`: chỉ là thông tin, vẫn import được (tổng lệch `Total`, order không có thuế, order đã huỷ bên Shopify (`Canceled at`), order sẽ được cập nhật).
- `productExists: false` → product sẽ được tạo tự động (chỉ là thông tin, không phải lỗi).
- 400: thiếu file / không phải `.csv` / > 10 MB / file rỗng / thiếu header bắt buộc (`Name`, `Email`, `Lineitem quantity`, `Lineitem name`, `Lineitem price`, `Lineitem sku`). 401: token sai. 403: guest `ROLE_CHANNEL`. 404: channel không tồn tại.

### `POST /orders/import-csv` (multipart/form-data)

| Field | Type | Ghi chú |
|---|---|---|
| `channelId` | int | bắt buộc |
| `file` | file `.csv` | cùng file đã preview |
| `orderNrs[]` | string[] | order user chọn. Không gửi = tất cả order không bị `skip` |

Backend **đọc lại file và kiểm tra lại** (kể cả order bị khoá), không nhận dữ liệu order từ FE. Mỗi order chạy trong transaction riêng + advisory lock theo channel + `orderNr`.

Response 200:

```json
{
  "created": [ { "orderNr": "1001", "id": 80123, "countNr": 50421 } ],
  "updated": [ { "orderNr": "1000", "id": 80001, "countNr": 50400 } ],
  "failed":  [ { "orderNr": "0999", "message": "Total is 0" } ]
}
```

### `GET /orders/import-csv/sample` — tải file mẫu

- **Không cần token**: file mẫu không có dữ liệu thật. FE chỉ cần `<a href="{REACT_APP_BASE_URL_API}/orders/import-csv/sample">`, không phải tải blob bằng axios kèm Bearer.
- Trả `BinaryFileResponse` với `Content-Type: text/csv; charset=UTF-8` và `Content-Disposition: attachment; filename="shopify_order_import_sample.csv"`. Dùng attachment để trình duyệt **tải về** thay vì mở file. Thuộc tính `download` của thẻ `<a>` bị bỏ qua khi khác domain (FE `localhost:3000` / API `ts_new_order_system.loc`), nên không dựa vào nó được.
- File nằm trong repo: `resources/import/shopify_order_import_sample.csv`. ⚠️ **Không** để trong `public/csv/` vì thư mục này bị `public/.gitignore` bỏ qua, nên file sẽ không được deploy.

**Nội dung file mẫu**:
- Đủ **toàn bộ header** theo đúng thứ tự và cách viết trong tài liệu Shopify [Exporting orders](https://help.shopify.com/en/manual/orders/manage-orders/exporting-orders) (79 cột: `Tax # Name/Value` mở thành `Tax 1..5`, có cả cột `Phone` lặp lại ở cuối như tài liệu), để user so với file export thật của họ.
- **2 order**: 1 order 1 dòng; 1 order 2 dòng có discount. Dòng thứ 2 của order chỉ có `Name`, `Email`, `Created at` và các cột `Lineitem *`, giống file Shopify thật.
- Số liệu khớp với quy tắc thuế đã chốt: giá gồm 25% VAT, `Subtotal` là tổng **sau** discount (đúng như Shopify), `Taxes = Total × 0.2`.

```csv
Name,Phone,Email,Financial Status,Paid at,Fulfillment Status,Fulfilled at,Accepts Marketing,Currency,Subtotal,Shipping,Taxes,Total,Discount Code,Discount Amount,Shipping Method,Created at,Lineitem quantity,Lineitem name,Lineitem price,Lineitem compare-at price,Lineitem SKU,Lineitem requires shipping,Lineitem taxable,Lineitem fulfillment status,Billing Name,Billing Street,Billing Address1,Billing Address2,Billing Company,Billing City,Billing Zip,Billing Province,Billing Province Name,Billing Country,Billing Phone,Shipping Name,Shipping Street,Shipping Address1,Shipping Address2,Shipping Company,Shipping City,Shipping Zip,Shipping Province,Shipping Province Name,Shipping Country,Shipping Phone,Notes,Note Attributes,Canceled at,Payment Method,Payment Reference,Payment References,Refunded Amount,Vendor,Outstanding Balance,Employee,Location,Device ID,Id,Tags,Risk Level,Source,Lineitem discount,Tax 1 Name,Tax 1 Value,Tax 2 Name,Tax 2 Value,Tax 3 Name,Tax 3 Value,Tax 4 Name,Tax 4 Value,Tax 5 Name,Tax 5 Value,Phone,Payment ID,Payment terms,Next payment due at,Checkout fees
#1001,+46701234567,anna@example.com,paid,"2026-10-20 10:15:00 +0200",unfulfilled,,no,SEK,500.00,49.00,109.80,549.00,,0.00,Standard,"2026-10-20 10:15:00 +0200",2,"T-shirt - M",250.00,,TS-001-M,true,true,pending,"Anna Andersson","Storgatan 1","Storgatan 1",,,Stockholm,11122,,,SE,+46701234567,"Anna Andersson","Storgatan 1","Storgatan 1",,,Stockholm,11122,,,SE,+46701234567,"Leave at the door",,,"Shopify Payments",,,0.00,,0.00,,,,,,Low,web,0.00,"VAT 25%",109.80,,,,,,,,,,,,,
#1002,+46709876543,erik@example.com,paid,"2026-10-21 14:30:00 +0200",unfulfilled,,no,SEK,720.00,0.00,144.00,720.00,WELCOME10,80.00,"Free shipping","2026-10-21 14:30:00 +0200",1,"Hoodie - L",500.00,,HO-002-L,true,true,pending,"Erik Svensson","Kungsgatan 5","Kungsgatan 5",,"Svensson AB",Göteborg,41119,,,SE,+46709876543,"Erik Svensson","Kungsgatan 5","Kungsgatan 5",,"Svensson AB",Göteborg,41119,,,SE,+46709876543,,,,"Shopify Payments",,,0.00,,0.00,,,,,,Low,web,50.00,"VAT 25%",144.00,,,,,,,,,,,,,
#1002,,erik@example.com,,,,,,,,,,,,,,"2026-10-21 14:30:00 +0200",3,Mug,100.00,,MUG-003,true,true,pending,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,30.00,,,,,,,,,,,,,,,
```

> File thật `resources/import/shopify_order_import_sample.csv` có đúng nội dung trên: 79 cột mỗi dòng, UTF-8 có BOM, xuống dòng CRLF. Đã test bằng chính API preview/import.

---

## TODO List

### Backend — Service

- [x] Service mới `src/Service/ShopifyCsvOrderImportService.php`:
  - [x] `parse(string $path): array`: đọc CSV bằng `fgetcsv` (không dùng PhpSpreadsheet vì nó biến SKU/zip dạng số như `0099` thành `99`), tự nhận `,` hoặc `;`, bỏ BOM, file ANSI chuyển sang UTF-8, nhận cả `,` thập phân, map theo tên header, kiểm tra header bắt buộc, gộp theo `Name`.
  - [x] `toOrderItem(array $group, int $channelId): array`: tạo `$orderItem` đúng format `generateOrderDataFromJson()` theo bảng mapping. Gồm tách `Title - Variant`, `item_id` ổn định, giá/ship gồm thuế chia `1 + rate` (rate từ `Tax 1 Name`), `import_from = 'shopify_csv'`.
  - [x] `validate()`: Total ≤ 0, SKU rỗng, tên rỗng, SL ≤ 0, giá không phải số → `errors`. `lockedReason()`: order đã có nhưng không do CSV tạo / đã xuất hoá đơn / Completed / huỷ.
  - [x] `preview(Channel $channel, string $path): array`: thêm `action` create/update/skip (tìm order theo `channelId` + `orderNr` + `dateDeleted IS NULL`), `customerExists`, `productExists`. Không ghi DB.
  - [x] `import(Channel $channel, string $path, ?array $orderNrs, ?User $user): array`: với từng order hợp lệ gọi `OrderService::importFromWPData([$orderItem], $user)` trong **transaction riêng** (lỗi → rollback order đó), `em->clear()` sau mỗi order, gom kết quả `created/updated/failed`.
- [x] `OrderService::importFromWPData()`:
  - [x] Nhận channel theo id khi có `$data['channel_entity_id']`, giữ nguyên tìm theo `synId` khi không có.
  - [x] Trả thêm `id`/`countNr`/`isAddNew` trong `data` (hiện chỉ trả `'message' => 'Done'`). Cronjob Shopify/WP chỉ đọc `status_code` + `message` nên không ảnh hưởng.
  - [x] Gán `createdByUserId` khi import từ UI: truyền `$user` vào `add()` (tham số mới `importFromWPData($requestData, $user = null)`, cronjob không truyền → như cũ). Có `$user` thì `add()` cũng lấy payment type / var reference mặc định của channel như order tạo tay.

### Backend — Controller & Routing

- [x] `OrderController::importCsvPreview()` và `importCsv()` (dùng chung `checkImportCsvRequest()`): auth, kiểm tra `channelId` tồn tại, file (`$request->files->get('file')`, đuôi `.csv`, tối đa 10 MB; không kiểm tra mime vì Excel/Windows gửi mime khác nhau), gọi service, trả `['data', 'status_code']`.
- [x] `src/Application/ApiBundle/Resources/config/route/order.yaml`: thêm `api_order_import_csv_preview` (`/import-csv/preview`, POST), `api_order_import_csv` (`/import-csv`, POST) và `api_order_import_csv_sample` (`/import-csv/sample`, GET), đặt trước `/{id}`.
- [x] Chặn `ROLE_CHANNEL` (guest) dùng 2 API này.
- [x] File mẫu `resources/import/shopify_order_import_sample.csv` (nội dung như mục [File mẫu](#get-ordersimport-csvsample--tải-file-mẫu): 79 cột, UTF-8 BOM).
- [x] `OrderController::importCsvSample()`: không check token, trả `BinaryFileResponse` + `Content-Disposition: attachment`. Route `api_order_import_csv_sample` (`/import-csv/sample`, GET), đặt trước `/{id}` (nếu không, `GET /{id}` sẽ bắt `import-csv` làm id).

### Docs

- [x] Cập nhật `docs/spec/06-api-bundle.md` (2 route mới) và `docs/spec/09-tich-hop-ben-thu-ba.md` (import CSV Shopify, `createdFrom = shopify_csv`).
- [x] Ghi chú API cho FE: `frontend-api-notes.md`.

### Test / kiểm tra

- [ ] File export Shopify thật: 1 order 1 dòng, 1 order nhiều dòng, nhiều order, order có discount, order miễn phí (Total = 0 → skip).
- [x] Import 2 lần cùng file → lần 2 toàn bộ là `update`, không nhân đôi item, không nhân đôi order.
- [x] Bỏ 1 dòng khỏi file rồi import lại → dòng đó bị xoá khỏi order.
- [x] `Name` trùng order ở channel khác → vẫn `create` ở channel đang chọn (preview file mẫu vào channel 100 → 2 `create`).
- [x] `Name` trùng order **không do CSV tạo** trong cùng channel → `skip`.
- [ ] SKU chưa có → tạo product + sub-product size đúng. SKU là sub-product sẵn có → khớp đúng.
- [ ] Product có Tryck → order có dòng Tryck tự thêm. Kickback đúng (spec 13).
- [ ] Channel `importPrice` bật/tắt. Channel prepaid → payment type Förskott.
- [ ] Shop giá gồm thuế và chưa gồm thuế → giá excl. tax đúng.
- [ ] Order import chuyển Completed → **không** gọi Shopify (mới suy ra từ code).
- [ ] Cronjob `cronjob:shopify_clone_order` vẫn chạy như cũ (regression `importFromWPData`).
- [x] File sai format / thiếu header / rỗng / BOM / ký tự åäö.
- [x] File mẫu: tải bằng link không cần token → trình duyệt tải về đúng tên file; mở bằng Excel không lỗi åäö; đưa chính file mẫu vào preview → 2 order `create`, đọc đủ 3 dòng, discount 80, tổng tính lại khớp `Total`.

---

## Frontend (tham khảo cho FE, không thuộc phạm vi)

👉 **Note gửi FE (màn hình, endpoint, request/response): `frontend-api-notes.md`**

UI hiện tại khi đã chọn channel (`files/orders-list-channel-selected.png`): góc phải có **Åtgärdsmodell** (BULK leverans / Massredigering), **Skapa bulkorder**, **Skapa ny**. Filter channel nằm ở hàng dưới.

- `src/pages/order/list.js:302-309`: thêm nút **Importera CSV** cạnh **Skapa ny** → mở **page mới** `/app/orders/import-csv` (truyền `?channelId` nếu list đang lọc channel).
- Page import: link **Ladda ner exempelfil** (`GET /orders/import-csv/sample`) + form chọn **channel** + **file CSV** → submit gọi preview.
- Kết quả preview: bảng **tất cả order** (badge Ny / Uppdateras / Hoppas över, mở rộng xem dòng SP), **checkbox từng order** + checkbox **chọn tất cả order hợp lệ** → nút **Importera till databasen** gọi `POST /orders/import-csv` với `orderNrs[]` đã chọn → hiện kết quả (link `/app/orders/{countNr}/detail`).
- `src/api/orders.js`: 2 hàm gửi `FormData`.

---

## Kết quả làm (backend)

Đã làm xong API backend, test trên DB local channel 101 (Fiskbar 17 Shop) bằng chính file mẫu:

| Test | Kết quả |
|---|---|
| `GET /orders/import-csv/sample` không token | ✅ 200, `Content-Disposition: attachment; filename=shopify_order_import_sample.csv`, nội dung giống file trong repo |
| Preview file mẫu | ✅ 2 order `create`, 3 dòng, tách `T-shirt - M` → `T-shirt` + size `M`, giá excl. tax 200/400/80, không warning lệch tổng |
| Import file mẫu | ✅ tạo order 1001 (#75280) + 1002 (#75281), `createdFrom = shopify_csv`, `createdByUserEmail` = user login, customer + product + sub-product size tự tạo. Tổng: 439.20 + thuế 109.80 = **549** ✔; (400 + 240 − 64) = 576 + thuế 144 = **720** ✔ (khớp `Total` trong file) |
| Import lại cùng file | ✅ cả 2 là `updated`, không nhân đôi order/dòng |
| Bỏ dòng Mug rồi import lại | ✅ dòng Mug bị xoá khỏi order (nhưng xem lỗi tổng tiền bên dưới) |
| SKU rỗng / Total = 0 | ✅ preview `skip` + lỗi `Line 2 (Mug): SKU is empty` / `Total is 0`; import trả về `failed` |
| `orderNrs[]` chỉ chọn một số order (có/không `#`) | ✅ chỉ import order được chọn |
| Thiếu header / đuôi `.txt` / thiếu file / sai channel / không token | ✅ 400 / 400 / 400 / 404 / 401 |
| File Excel Thụy Điển (`;`, `250,00`, BOM) | ✅ đọc đúng như file gốc |
| `sub_total = 0` trên order import | ℹ️ bình thường: 383/383 order Shopify hiện có cũng `sub_total = 0` (`importFromWPData()` không ghi cột này) |

Chưa test: product có Tryck, channel prepaid/`importPrice` tắt, file export thật của khách, order import chuyển Completed (chỉ suy ra từ code: `shopify_csv` rơi vào nhánh WP, `resyncUrlIntegration` rỗng → dừng).

#### ✅ Lỗi có sẵn của logic Shopify phát hiện khi test — đã sửa

Khi order đã có và file **bớt dòng**, dòng thừa bị xoá nhưng **tổng tiền order không tính lại**: `importFromWPData()` gọi `update()` (tính tổng) **trước** khi xoá dòng cũ. Lỗi này cũng xảy ra với cronjob Shopify.

**Đã sửa** (đồng ý sửa luôn trong `importFromWPData()`, áp dụng cho cả cronjob Shopify/WP): xoá dòng cũ **trước**, rồi mới `refresh` + `generateItem()` + `update()`.

| Test | Trước khi sửa | Sau khi sửa |
|---|---|---|
| Order 1002 bỏ dòng Mug | 1 dòng, `total_sum` **576** (sai) | 1 dòng, `total_sum` **336** + thuế 84 = 420 = 500 − 80 discount ✔ |
| Thêm lại dòng Mug | — | 2 dòng, 576 + thuế 144 = 720 ✔ |

Lợi ích thêm: dòng Tryck tự thêm của dòng bị xoá giờ cũng bị dọn theo. `addProducts()` bỏ qua dòng Tryck gửi lên (`OrderService.php:1182-1186`) và xoá mọi dòng không có trong `$itemIds` (`:1360`); dòng cha đã bị xoá thì dòng Tryck con không được thêm lại vào `$itemIds`. Trước đây dòng cha bị xoá **sau** `update()` nên dòng Tryck con bị bỏ lại. ⚠️ Chưa test thực tế vì DB local không có product Tryck giá > 0.

---

## Review code + test lại (API + FE)

### Đã sửa thêm

| # | Vấn đề | Sửa | Test |
|---|---|---|---|
| 1 | Import lại file export cũ sẽ **đồng bộ lại dòng của order đã xuất hoá đơn / đã Completed** (Shopify cronjob chỉ lấy order chưa fulfill nên không gặp, CSV thì có thể chứa order bất kỳ) | `lockedReason()`: order đã có mà **invoiced**, **Completed** (`order_status_complete_id`) hoặc **huỷ** (`update()` vốn từ chối) → preview `skip` + lỗi, import `failed` | ✅ đặt tạm 1001 invoiced, 1002 cancel → cả 2 `skip`/`failed` |
| 2 | Bấm import 2 lần cùng lúc (double click / 2 người) → cả 2 request không thấy order → **tạo trùng** | `pg_advisory_xact_lock(crc32(channel + orderNr))` trong transaction của từng order | ✅ 3 request song song cùng file → 1 `created` + 2 `updated`, DB có đúng 1 order |
| 3 | `importFromWPData()` bỏ qua kết quả `update()` → nếu `update()` lỗi vẫn trả "Done" (order thiếu tổng/Tryck) | trả lỗi khi `update()` ≠ 200 → CSV rollback cả order. ⚠️ Ảnh hưởng nhẹ cronjob Shopify: trường hợp này giờ được log là lỗi thay vì "Done" | ✅ regression các case thường vẫn 200 |
| 4 | File lớn: import ~0.2 s/order → 1000 order vượt `max_execution_time` (120 s local) và dừng giữa chừng | `set_time_limit(0)` trong `import()`. ⚠️ Timeout của web server (nginx/Apache) vẫn có thể cắt — production nên kiểm tra | Preview 1000 order: **5.2 s** |
| 5 | Ô **Kommentar** của order hiện `-` (vì `"{method} - {title}"` đều rỗng, Shopify API cũng vậy) | đưa `Payment Method` vào `payment.method` (chỉ vào comment, không tạo payment type) | ✅ Kommentar = `Shopify Payments -`, không có `StatusList` "Shopify Payments" mới |
| 6 | **Order trùng số nhưng không do CSV tạo** (order tạo tay / WordPress có số `1001`, hoặc order Shopify sync cùng channel): `importFromWPData()` sẽ **thêm dòng CSV vào order của người khác**, hoặc với order Shopify sync thì **xoá dòng Shopify** (item_id khác) rồi thêm dòng CSV và trừ kho lần nữa | `lockedReason()`: order đã có mà `createdFrom` ≠ `shopify_csv` → `skip` với lỗi `Order number already used in this channel by an order not imported from CSV (manual, #75283)` | ✅ đổi tạm `created_from` order 3002 = NULL → preview `skip`, import `failed` |

### Kiểm tra giao diện FE (order đã import, channel Fiskbar 17 Shop)

- Danh sách Orders: 3 order import hiện đúng khách, email, tổng (439.20 / 576.00), ngày order theo `Created at`.
- Chi tiết #75281 (1002): 2 dòng `HO-002-L` (Hoodie, size L, 400) + `MUG-003` (Mug, 80); Rabatt exkl. moms 64, moms 16; Total moms 144; **Total inkl. moms 720** = `Total` trong file ✔.
- Chi tiết #75280 (1001): Fraktavgift exkl moms 39.2, Notes → "Information till kund", Total 549 ✔. "Skapad av" = user import.

### ⚠️ Lỗi có sẵn phát hiện thêm (không thuộc import, chưa sửa)

- **Momsdelning sai với order có discount**: `OrderService::getTaxDescription()` (`:4046`) tính thuế discount = `discount × rate`, nhưng `discount` lưu **gồm thuế** → order 1002 hiện `25% = 140.00 kr` trong khi Total moms 144.00 (đúng: 80 − 64 = 16, không phải 20). Ảnh hưởng **mọi order có discount**, không riêng import → nên tách ticket.
- Tên khách/người nhận ghép thêm công ty (`Erik Svensson Svensson AB`): `importFromWPData()` ghép `firstname lastname company` — giống Shopify API import, giữ nguyên.
- `importFromWPData()` không hoàn kho khi dòng bị xoá / đổi số lượng lúc import lại (giống Shopify).

---

## Đối chiếu format CSV Shopify ("Use shopify format csv")

Đối chiếu với tài liệu chính thức [Shopify Help — Exporting orders](https://help.shopify.com/en/manual/orders/manage-orders/exporting-orders):

| Điểm | Tài liệu Shopify | Trước | Đã sửa |
|---|---|---|---|
| Tên cột SKU | `Lineitem SKU` | so header **phân biệt hoa/thường** với `Lineitem sku` → file thật bị báo *missing columns* | so header **không phân biệt hoa/thường**, coi `-`/`_` như dấu cách (`canonicalColumn()`) → nhận cả `Lineitem sku` và `Lineitem SKU` |
| Ngày huỷ | `Canceled at` (kiểu Mỹ) | đọc `Cancelled at` → cảnh báo order huỷ không chạy | nhận cả 2 cách viết |
| `Lineitem compare-at price` | có gạch nối | file mẫu viết `compare at` | file mẫu theo tài liệu (cột này không dùng) |
| `Phone` | xuất hiện **2 lần** (cột 2 và gần cuối) | cột sau (rỗng) ghi đè cột trước | header trùng: giá trị rỗng không ghi đè giá trị đã có |
| Thứ tự cột | `Phone` sau `Name`, `Province Name` cạnh `Province`, có `Payment References`, `Checkout fees` | file mẫu theo thứ tự cũ | file mẫu theo đúng thứ tự tài liệu; code đọc theo tên nên thứ tự không ảnh hưởng |
| Order nhiều dòng | mỗi dòng sản phẩm 1 dòng, các cột của order để trống ở dòng sau | ✅ đúng | — |
| `Tax # Name` / `Tax # Value` | tối đa 5 thuế (`Tax 1 Name`...) | ✅ đọc `Tax 1 Name` | — |

Tài liệu Shopify **không ghi** `Lineitem price` gồm hay chưa gồm thuế, và `Subtotal` trước hay sau discount → giữ cách đã chốt (#f) và dựa vào cảnh báo lệch tổng trong preview. Vẫn nên thử với **1 file export thật** của khách.

Test sau khi sửa (preview vào channel 100, không ghi DB): file mẫu mới (`Lineitem SKU`), file mẫu cũ (`Lineitem sku`), file Excel `;` → đều đọc đủ 2 order / 3 dòng, `Phone` đúng; file có `Canceled at` + `Taxes = 0` → 2 cảnh báo. Import file mẫu mới vào channel 101 → tổng vẫn 549 / 720.

---

## Các file liên quan

| File | Mục đích |
|------|----------|
| `src/Service/ShopifyCsvOrderImportService.php` | **mới**: đọc CSV, preview, map sang `$orderItem`, import từng order trong transaction |
| `resources/import/shopify_order_import_sample.csv` | **mới**: file mẫu (79 cột, UTF-8 BOM) |
| `src/Service/OrderService.php:3354` | `importFromWPData()`: luồng import Shopify chuẩn, tái sử dụng. Sửa: `channel_entity_id`, tham số `$user`, trả `id`/`countNr`/`isAddNew`, xoá dòng cũ trước `update()`, trả lỗi khi `update()` lỗi |
| `src/Service/ShopifyService.php:705` | `generateOrderDataFromJson()`: format `$orderItem` + quy tắc bỏ qua order |
| `src/Command/Cronjob/ShopifyCloneOrderCommand.php` | cách cronjob gọi `importFromWPData()` từng order |
| `src/Service/OrderService.php:4908` | `postOrderUpdateComplete()`: lý do không dùng `createdFrom = 'shopify'` |
| `src/Service/OrderService.php:2201` | `importCsvData()` cũ: chỉ tham khảo, có lỗi |
| `src/Service/OrderService.php:928` | `addTryckOrderProducts()` |
| `src/Application/ApiBundle/Controller/OrderController.php` | thêm 3 action + `checkImportCsvRequest()` |
| `src/Application/ApiBundle/Resources/config/route/order.yaml` | thêm 3 route |
| `docs/issues/TSHIRTORDER-1655-import-order-csv/frontend-api-notes.md` | note cho FE |
| `docs/spec/13-tryck-products.md` | quy tắc Tryck |
| FE `src/pages/order/list.js:302-309` | vị trí nút Skapa ny |
