backbone-catalog 0.7.0

Canonical product/service identity: Item, Item Group, UOM (Indonesia-first)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Guarded route composition — the RECOMMENDED way to mount the catalog module.
//!
//! Hand-authored (user-owned; see `metaphor.codegen.yaml`). Closes the CRUD-bypass: the generated
//! `routes()` exposes full mutable CRUD on every entity, backed by generic services with NO domain
//! validation. That lets a caller create an Item pointing at a missing item-group/UOM or an Item
//! with no usage flag — corrupting the product identity every downstream module projects.
//!
//! Tenant-agnostic (ADR-0029): the handlers carry no tenancy plumbing. Request scoping is the
//! composing host's concern — its auth middleware mounts the org request scope and the fence
//! rides the request-dedicated connection.
//!
//! Guarded surface:
//!   - **Item / ItemGroup**: READ + **validated create** via `CatalogWriteService`.
//!     Generic update/delete/upsert/bulk are intentionally NOT mounted here.
//!   - **Uom**: READ + validated create (tree root or child, ADR-0023) + validated re-parent
//!     + validated retire (`POST /uoms/delete`): module-seeded (protected) units refuse deletion
//!     with a typed error; user-created units archive once nothing leans on them (UM-4).
//!     Conversion itself is application-side (`CatalogWriteService::convert_quantity`) and is not
//!     an HTTP endpoint — consumers compose the service.
//!   - **UomConversion**: READ only. Conversion is carried by the UoM parent-store tree since the
//!     ADR-0023 rewrite; the pairwise table stays readable for legacy data and a future
//!     item-specific layer, with no validated write path.

use std::sync::Arc;

use axum::{extract::{Path, State}, http::StatusCode, response::IntoResponse, routing::{get, post}, Json, Router};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::domain::entity::CatalogStatus;

use std::collections::BTreeMap;

use crate::application::service::catalog_write_service::{
    CatalogWriteError, CatalogWriteService, NewAttribute, NewAttributeValue, NewBrand, NewItem,
    NewItemGroup, NewItemVariant, NewUom,
};
use crate::CatalogModule;

use super::{
    create_attribute_read_routes, create_attribute_value_read_routes, create_brand_read_routes,
    create_item_group_read_routes, create_item_read_routes, create_item_variant_read_routes,
    create_uom_conversion_read_routes, create_uom_read_routes,
};

#[derive(Debug, Serialize)]
struct ErrorBody {
    error: &'static str,
    message: String,
}
#[derive(Debug, Serialize)]
struct IdResponse {
    id: Uuid,
}

fn err_response(e: CatalogWriteError) -> axum::response::Response {
    let status = StatusCode::from_u16(e.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    (status, Json(ErrorBody { error: e.code(), message: e.to_string() })).into_response()
}

// ── ItemGroup ─────────────────────────────────────────────────────────────────
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateItemGroupBody {
    code: String,
    name: String,
    #[serde(default)]
    parent_id: Option<Uuid>,
    #[serde(default)]
    is_group: bool,
}

async fn create_item_group(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<CreateItemGroupBody>,
) -> axum::response::Response {
    match svc
        .create_item_group(NewItemGroup {
            code: b.code, name: b.name, parent_id: b.parent_id, is_group: b.is_group,
        })
        .await
    {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err_response(e),
    }
}

// ── Item ──────────────────────────────────────────────────────────────────────
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateItemBody {
    item_code: String,
    name: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    barcode: Option<String>,
    #[serde(default)]
    brand_id: Option<Uuid>,
    item_group_id: Uuid,
    default_uom_id: Uuid,
    #[serde(default)]
    item_type: Option<String>,
    #[serde(default = "default_true")]
    is_sales_item: bool,
    #[serde(default = "default_true")]
    is_purchase_item: bool,
    #[serde(default = "default_true")]
    is_stock_item: bool,
    #[serde(default)]
    hsn_code: Option<String>,
    #[serde(default = "default_true")]
    is_taxable: bool,
    #[serde(default)]
    weight_per_unit: Option<Decimal>,
    /// Standard unit cost for margin math. Absent = NULL = cost unknown (never zero);
    /// selling snapshots it at order-confirm time.
    #[serde(default)]
    standard_cost: Option<Decimal>,
    #[serde(default)]
    tags: Option<serde_json::Value>,
    #[serde(default)]
    data: Option<serde_json::Value>,
}
fn default_true() -> bool {
    true
}

async fn create_item(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<CreateItemBody>,
) -> axum::response::Response {
    match svc
        .create_item(NewItem {
            item_code: b.item_code,
            name: b.name,
            description: b.description,
            barcode: b.barcode,
            brand_id: b.brand_id,
            item_group_id: b.item_group_id,
            default_uom_id: b.default_uom_id,
            item_type: b.item_type,
            is_sales_item: b.is_sales_item,
            is_purchase_item: b.is_purchase_item,
            is_stock_item: b.is_stock_item,
            hsn_code: b.hsn_code,
            is_taxable: b.is_taxable,
            weight_per_unit: b.weight_per_unit,
            standard_cost: b.standard_cost,
            tags: b.tags,
            data: b.data,
        })
        .await
    {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err_response(e),
    }
}

// ── Attribute + AttributeValue ──────────────────────────────────────────────────
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateAttributeBody {
    code: String,
    name: String,
    #[serde(default)]
    attribute_type: Option<String>,
}

async fn create_attribute(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<CreateAttributeBody>,
) -> axum::response::Response {
    match svc
        .create_attribute(NewAttribute {
            code: b.code, name: b.name, attribute_type: b.attribute_type,
        })
        .await
    {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err_response(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateAttributeValueBody {
    attribute_id: Uuid,
    code: String,
    label: String,
    #[serde(default)]
    label_en: Option<String>,
    #[serde(default)]
    swatch_hex: Option<String>,
    #[serde(default)]
    sort_order: i32,
}

async fn create_attribute_value(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<CreateAttributeValueBody>,
) -> axum::response::Response {
    match svc
        .create_attribute_value(NewAttributeValue {
            attribute_id: b.attribute_id,
            code: b.code,
            label: b.label,
            label_en: b.label_en,
            swatch_hex: b.swatch_hex,
            sort_order: b.sort_order,
        })
        .await
    {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err_response(e),
    }
}

// ── ItemVariant ─────────────────────────────────────────────────────────────────
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateItemVariantBody {
    item_id: Uuid,
    sku: String,
    #[serde(default)]
    variant_label: Option<String>,
    #[serde(default)]
    options: BTreeMap<String, String>,
    #[serde(default)]
    barcode: Option<String>,
    #[serde(default)]
    is_default: bool,
    #[serde(default)]
    weight_per_unit: Option<Decimal>,
}

async fn create_item_variant(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<CreateItemVariantBody>,
) -> axum::response::Response {
    match svc
        .create_item_variant(NewItemVariant {
            item_id: b.item_id,
            sku: b.sku,
            variant_label: b.variant_label,
            options: b.options,
            barcode: b.barcode,
            is_default: b.is_default,
            weight_per_unit: b.weight_per_unit,
        })
        .await
    {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err_response(e),
    }
}

// ── Uom + Brand (validated create; generic delete/patch are NOT mounted so a referenced
//    Uom/Brand can't be soft-deleted out from under items — council 2026-07-01) ──────────
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateUomBody {
    code: String,
    name: String,
    #[serde(default)]
    uom_type: Option<String>,
    #[serde(default)]
    decimal_places: i32,
    /// Reference (parent) unit — omit to create a tree root (ADR-0023).
    #[serde(default)]
    relative_uom_id: Option<Uuid>,
    /// Ratio to the parent unit (required exactly when relativeUomId is set):
    /// 1 of the new unit = relativeFactor of the parent unit.
    #[serde(default)]
    relative_factor: Option<Decimal>,
}

async fn create_uom(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<CreateUomBody>,
) -> axum::response::Response {
    match svc
        .create_uom(NewUom {
            code: b.code, name: b.name, uom_type: b.uom_type, decimal_places: b.decimal_places,
            relative_uom_id: b.relative_uom_id, relative_factor: b.relative_factor,
        })
        .await
    {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err_response(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SetUomRelativeBody {
    /// Omit or send null to detach the unit (it becomes a tree root).
    relative_uom_id: Option<Uuid>,
    #[serde(default)]
    relative_factor: Option<Decimal>,
}

/// Re-parent a unit on the parent-store tree (or detach it to a root with `null`).
/// The stored factors of the unit and its subtree are re-derived in the same transaction.
async fn set_uom_relative(
    State(svc): State<Arc<CatalogWriteService>>,
    Path(id): Path<Uuid>,
    Json(b): Json<SetUomRelativeBody>,
) -> axum::response::Response {
    let relative = match (b.relative_uom_id, b.relative_factor) {
        (None, None) => None,
        (Some(parent), Some(rf)) => Some((parent, rf)),
        (Some(_), None) | (None, Some(_)) => {
            return err_response(CatalogWriteError::RelativeShapeMismatch)
        }
    };
    match svc.set_uom_relative(id, relative).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => err_response(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DeleteUomBody {
    id: Uuid,
}

/// Retire a unit of measure through the validated path. Module-seeded (protected)
/// units refuse with a typed error; user-created units archive once nothing leans on
/// them (no live children, no live item defaulting to the unit).
async fn delete_uom(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<DeleteUomBody>,
) -> axum::response::Response {
    match svc.delete_uom(b.id).await {
        Ok(()) => (StatusCode::OK, Json(IdResponse { id: b.id })).into_response(),
        Err(e) => err_response(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateBrandBody {
    code: String,
    name: String,
    #[serde(default)]
    short_description: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    logo_url: Option<String>,
    #[serde(default)]
    sort_order: i32,
}

async fn create_brand(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<CreateBrandBody>,
) -> axum::response::Response {
    match svc
        .create_brand(NewBrand {
            code: b.code,
            name: b.name,
            short_description: b.short_description,
            description: b.description,
            logo_url: b.logo_url,
            sort_order: b.sort_order,
        })
        .await
    {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err_response(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DeleteItemVariantBody {
    id: Uuid,
}

async fn delete_item_variant(
    State(svc): State<Arc<CatalogWriteService>>,
    Json(b): Json<DeleteItemVariantBody>,
) -> axum::response::Response {
    match svc.delete_item_variant(b.id).await {
        Ok(()) => (StatusCode::OK, Json(IdResponse { id: b.id })).into_response(),
        Err(e) => err_response(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ChangeItemStatusBody {
    status: String,
}

/// Transition an Item's lifecycle status through the validated write path — enforces the
/// CatalogStatus state machine (`discontinued` is terminal). Body: `{"status":"inactive"}`.
async fn change_item_status(
    State(svc): State<Arc<CatalogWriteService>>,
    Path(id): Path<Uuid>,
    Json(b): Json<ChangeItemStatusBody>,
) -> axum::response::Response {
    let target = match b.status.parse::<CatalogStatus>() {
        Ok(s) => s,
        Err(_) => {
            return (StatusCode::UNPROCESSABLE_ENTITY, Json(ErrorBody {
                error: "invalid_status",
                message: format!("unknown CatalogStatus: {}", b.status),
            }))
                .into_response();
        }
    };
    match svc.transition_item_status(id, target).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => err_response(e),
    }
}

/// Resolve a scanned barcode/SKU to a sellable item (scan → item, step 1 of the counter journey).
async fn lookup_item(State(svc): State<Arc<CatalogWriteService>>, Path(code): Path<String>) -> axum::response::Response {
    match svc.lookup_item(&code).await {
        Ok(Some(hit)) => (StatusCode::OK, Json(hit)).into_response(),
        Ok(None) => (StatusCode::NOT_FOUND, Json(ErrorBody { error: "item_not_found", message: format!("no item for code '{code}'") })).into_response(),
        Err(e) => err_response(e),
    }
}

fn create_catalog_write_routes(svc: Arc<CatalogWriteService>) -> Router {
    Router::new()
        .route("/item-groups", post(create_item_group))
        .route("/items", post(create_item))
        .route("/items/:id/status", post(change_item_status))
        .route("/item-lookup/:code", get(lookup_item))
        .route("/uoms", post(create_uom))
        .route("/uoms/:id/relative", post(set_uom_relative))
        .route("/uoms/delete", post(delete_uom))
        .route("/brands", post(create_brand))
        .route("/attributes", post(create_attribute))
        .route("/attribute-values", post(create_attribute_value))
        .route("/item-variants", post(create_item_variant))
        .route("/item-variants/delete", post(delete_item_variant))
        .with_state(svc)
}

/// Mount the catalog module with write paths locked to validated services.
/// **Prefer this over `CatalogModule::routes()` for any real deployment.**
pub fn create_guarded_catalog_routes(m: &CatalogModule) -> Router {
    Router::new()
        // Invariant-bearing entities: read + validated create only.
        .merge(create_item_read_routes(m.item_service.clone()))
        .merge(create_item_group_read_routes(m.item_group_service.clone()))
        .merge(create_uom_conversion_read_routes(m.uom_conversion_service.clone()))
        .merge(create_attribute_read_routes(m.attribute_service.clone()))
        .merge(create_attribute_value_read_routes(m.attribute_value_service.clone()))
        .merge(create_item_variant_read_routes(m.item_variant_service.clone()))
        // Uom + Brand: READ-ONLY generic + validated create. They are FK parents of Item /
        // UomConversion, so generic soft-delete/patch would orphan referencing rows (the FK never
        // fires on a soft delete, but every validated read filters deleted_at) — council 2026-07-01.
        .merge(create_uom_read_routes(m.uom_service.clone()))
        .merge(create_brand_read_routes(m.brand_service.clone()))
        // Validated writers for the locked entities.
        .merge(create_catalog_write_routes(m.catalog_write_service.clone()))
}