# Create Product API (TSHIRTORDER-1653)

Creates a product, optionally with size variants (sub-products), images, production info and add-ons.

| | |
|---|---|
| **Method / URL** | `POST /api/v1/products/` |
| **Auth** | `Authorization: Bearer <access token>` (32 chars, `[0-9a-z]`) |
| **Content-Type** | `application/json`, or `multipart/form-data` when uploading files |
| **Controller** | `ProductController::add()` → `ProductService::add()` |

> Request data is the merge of JSON body, form body and query string.
> With multipart, send booleans as `"true"` / `"false"` — both are converted correctly.

## Authentication

- Missing / malformed / unknown / expired token → `401 {"message": "Invalid token authorization"}`.
- A token flagged `lockForOnlyIntegration` is rejected.
- If the token belongs to a user with role **CHANNEL** (guest portal): `brandId` is forced to the user's brand
  (when the user has one) and a "new product from guest" email is sent after creation.

## Request body

### Required

| Field | Type | Notes |
|---|---|---|
| `name` | string | NotNull |
| `sku` | string | NotNull. **Not checked for uniqueness** on the parent product (only `subProducts[].sku` is) |

### Basic / pricing

| Field | Type | Notes |
|---|---|---|
| `slug`, `description`, `description2`, `fabric`, `washingInstructions`, `color`, `modelNr`, `link` | string | |
| `weight` | float | |
| `active` | bool | |
| `price` | float | Sales price (ex. tax) |
| `purchasePriceExcTax` | float | |
| `priceEcomIncTax`, `priceEcomOriginal` | float | Webshop price (inc. tax) / original price |
| `taxCode` | int | Percent, e.g. `25`. Defaults to `tax_default * 100` |
| `exportAccount`, `exportSaleAccount` | int | Accounting accounts |
| `noKickback` | bool | |
| `procentage`, `fixSum` | float | Kickback percentage / fixed sum |

### Classification

| Field | Type | Notes |
|---|---|---|
| `productKind` | string | `normal` or `tryck`; any other value → 400 `Invalid product kind`. See *Tryck products* below |
| `typeId` | int | `StatusList` type `product_type`. Defaults to the entry with `uniqueKey = default_type` |
| `brandId` | int | Active brand; fills `brandName` / `brandLogo`. Unknown id clears brand fields |
| `categories` | int[] | Ids of **active** product categories; unknown ids are skipped |
| `channelIds` | int[] (or JSON string) | Channels the product belongs to |
| `channelId` | int | Adds one more channel (also stored as the product's main `channelId`) |
| `supplierModelId` | int | `StatusList` type `supplier_model` |
| `supplierSKU`, `supplierName`, `supplierPrice`, `supplierComment` | mixed | |
| `productModelVariantId` | int | Fills model / variant name, nr and thumbnails automatically |

### Stock

| Field | Type | Notes |
|---|---|---|
| `stock` | int | |
| `manageStock` | bool | When true, sub-product `outStock` is derived from `stock <= 0` |
| `outStock` | bool | |
| `wooSyncStock` | bool | Include in WooCommerce stock export |

### Webshop (ecom)

| Field | Type | Notes |
|---|---|---|
| `showOnEcom` | bool | |
| `ecomFavorite`, `popularProduct`, `newProduct` | bool | |
| `ecomSortOrder` | int | |
| `dateReleaseString` | string | `Y-m-d H:i:s`. (`dateRelease` is ignored) |
| `relatedProductText` | string | |
| `relatedProductIds` | int[] | |
| `removeFromGuestPortal` | bool | |
| `printStatus` | bool | |

### Add-on products

| Field | Type | Notes |
|---|---|---|
| `addOnProduct` | bool | This product is itself an add-on |
| `addOnProductType` | string | |
| `addOnInputMaxLength` | int | |
| `addOnInputAllLetterInputCapital` | bool | |
| `addOnDefaultSupplierId` | int | |
| `addOnProductIds` | int[] | Add-ons attached to this product. Only ids of products with `addOnProduct = true` are kept |

### Production

| Field | Type | Notes |
|---|---|---|
| `productionId` | int | Main production; fills `productionSku/Price/Name/TypeId/TypeText` |
| `productions` | array | `[{ "productionId": int, "comment": string, "placements": string, "printFileId": string }]`. Inactive / unknown productions are skipped |

### Sub-products (sizes)

`subProducts[]` — every item needs **all four** fields:

| Field | Type | Notes |
|---|---|---|
| `sku` | string | Unique within the payload and across all active products |
| `stock` | int | |
| `ecomSortOrder` | int | |
| `sizeId` | int | Active `StatusList` of type `product_size`. If it does not resolve the item is skipped |

Missing field → 400 `{"subProducts": {"<index>": "Missing field <name>"}}`. Duplicate sku → 400 `Sku already existed`.
Sub-products inherit `channelId` / `channelName` / `channelShortName` from the parent; `name` and `size` come from the size entry.

### Files (multipart only)

| Field | Notes |
|---|---|
| `newImages[]` | Product gallery images |
| `thumbnail` | Single image |
| `printFile` | Print file (up to ~100 MB) |

### Tryck products

For `productKind = "tryck"`:

- `connectedProductIds` (int[]) links the Tryck product to normal products.
- The server **forces** (payload cannot override): `showOnEcom=false`, `manageStock=false`, `outStock=false`,
  `wooSyncStock=false`, `addOnProduct=false`, `noKickback=true`, `procentage=0`, `fixSum=0`.
- `removeFromGuestPortal` defaults to `true` unless sent explicitly.
- `tryckPrints` (max 4 prints, each = placement + print file) — see [Create Print Product](create-print-product-api.md)
  and [Prints on products](prints-on-products-api.md).
- See `docs/spec/13-tryck-products.md`.

## Example

```http
POST /api/v1/products/
Authorization: Bearer 0123456789abcdef0123456789abcdef
Content-Type: application/json

{
  "name": "Hoodie Black",
  "sku": "HOOD-BLK",
  "price": 299,
  "purchasePriceExcTax": 120,
  "taxCode": 25,
  "channelIds": [12],
  "categories": [3],
  "brandId": 4,
  "manageStock": true,
  "showOnEcom": true,
  "priceEcomIncTax": 374,
  "subProducts": [
    { "sku": "HOOD-BLK-S", "stock": 10, "ecomSortOrder": 1, "sizeId": 21 },
    { "sku": "HOOD-BLK-M", "stock": 10, "ecomSortOrder": 2, "sizeId": 22 }
  ],
  "productions": [
    { "productionId": 7, "comment": "Front print", "placements": "front", "printFileId": "" }
  ]
}
```

## Response

### 200 OK

Returns the product summary (`generateItem`). The collections `images`, `subProducts`, `productions`,
`addOnProducts`, `connectedProducts` are returned as **empty arrays** here — call
`GET /api/v1/products/{id}` for the full object.

```json
{
  "id": 5001,
  "countNr": "5001",
  "name": "Hoodie Black",
  "sku": "HOOD-BLK",
  "price": 299.0,
  "purchasePriceExcTax": 120.0,
  "priceEcomIncTax": 374.0,
  "taxCode": 25,
  "productKind": "normal",
  "typeId": 1,
  "type": "Default",
  "brandId": 4,
  "brandName": "…",
  "active": true,
  "manageStock": true,
  "showOnEcom": true,
  "noKickback": false,
  "categories": [ { "id": 3, "name": "…" } ],
  "channels":   [ { "id": 12, "channelName": "…", "channelShortName": "…" } ],
  "images": [],
  "subProducts": [],
  "productions": []
}
```

### Errors

| Status | Body | Cause |
|---|---|---|
| 400 | `{"name": "..."}` / `{"sku": "..."}` | Missing `name` or `sku` |
| 400 | `{"productKind": "Invalid product kind"}` | `productKind` not `normal` / `tryck` |
| 400 | `{"subProducts": {"0": "Missing field sizeId"}}` | Incomplete / duplicate sub-product |
| 401 | `{"message": "Invalid token authorization"}` | Bad token |
| 500 | `{"message": "<exception message>"}` | Unexpected error |

## Gotchas

- `countNr` is generated by the server (auto-counter `product`); any `countNr` in the payload is dropped.
- Unknown ids (`categories`, `channelIds`, `addOnProductIds`, `sizeId`, `connectedProductIds`, `productionId` in `productions[]`)
  are **silently skipped** — compare the full `GET` result with what you sent.
- The parent `sku` is not unique-checked; creating the same `sku` twice succeeds.
- Not atomic: the product is saved first, then images / add-ons / sub-products / productions. A failure later
  returns 500 but the product row may already exist.
- Not to be confused with `POST /products/quick-update`, `POST /products/list-price` (mass edit) and
  `POST /products/{id}` (update).

## Related files

| File | Purpose |
|---|---|
| `src/Application/ApiBundle/Resources/config/route/product.yaml` | Route definitions |
| `src/Application/ApiBundle/Controller/ProductController.php` | `add()` |
| `src/Service/ProductService.php` | `add()`, `generateUpdate()`, `validateData()`, `updateChildrenProducts()`, `updateAddOnProducts()`, `updateTryckConnections()`, `applyTryckDefaults()` |
| `src/Entity/Product.php` | Fields + validation constraints |
| `docs/spec/13-tryck-products.md` | Tryck product rules |
