Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,99 @@
# OpenSpec Change: enterprise-api-plugin-inventory
- **Change ID**: enterprise-api-plugin-inventory
- **Package**: `@suaveplan/api-plugin-inventory`
- **Category**: api/logistics
- **Target path**: `api/logistics/api-plugin-inventory`
- **Status**: PROPOSED
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/api-plugin-inventory.md`
---
## Summary
Deliver `@suaveplan/api-plugin-inventory` on the genesis branch from scratch at enterprise quality. The main-branch package has 0% test coverage, no tenant isolation, no auth, no idempotency, no audit, and the advertised `procurement:grn:completed` auto-integration is a log statement only. Genesis delivers the full implementation: item catalog, multi-warehouse stock tracking, stock movements (receive/issue/transfer) with FIFO/LIFO/average/specific-ID costing (corrected and tested), lot + expiry tracking, physical-count adjustment workflow, low-stock/expiring-stock/valuation reports, real `procurement:grn:completed` subscription that creates stock movements, tenant isolation on every query, and full enterprise cross-cutting (auth/idempotency/audit/rate-limit). Routes under `/inventory`. Per-table SurrealQL.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/api` (`workspace:^`) | `definePlugin` |
| `@suaveplan/api-shared` (`workspace:^`) | Helpers |
| `@suaveplan/api-plugin-auth` (`workspace:^`) | `requireAuth`, permissions |
| `@suaveplan/api-plugin-database` (`workspace:^`) | SurrealDB |
| `@suaveplan/events` (`workspace:^`) | Bus; subscribe to `procurement:grn:completed` |
| `@suaveplan/error` (`workspace:^`) | `InventoryError` hierarchy |
| `@suaveplan/idempotency` (`workspace:^`) | Stock movement guard |
| `@suaveplan/audit-logging` (`workspace:^`) | Adjustment + disposal audit |
| `@suaveplan/rate-limiter` (`workspace:^`) | Rate limits |
| `decimal.js` (catalog) | Monetary precision |
| `hono` + `@hono/zod-openapi` + `zod` | Routes |
| `@opentelemetry/api` | OTel |
---
## Public API surface
```ts
function createInventoryPlugin(config?: InventoryConfig): PluginDescriptor<InventoryConfig>
// Types (preserved + corrected)
InventoryItem, CreateItemInput, UpdateItemInput, StockMovement, Warehouse
StockLevel, LotInfo, CostingMethod, AdjustmentRecord
// Services: ItemService, WarehouseService, StockService, MovementService,
// AdjustmentService, CostingService, ReportService
// Routes: /inventory/items, /inventory/warehouses, /inventory/stock,
// /inventory/movements, /inventory/adjustments, /inventory/reports
```
### Error codes
```ts
type InventoryErrorCode =
| "INVENTORY_ITEM_NOT_FOUND"
| "INVENTORY_WAREHOUSE_NOT_FOUND"
| "INVENTORY_INSUFFICIENT_STOCK"
| "INVENTORY_LOT_EXPIRED"
| "INVENTORY_ADJUSTMENT_CONFLICT"
| "INVENTORY_COSTING_ERROR"
```
---
## Genesis additions vs main-branch
1. **100% test coverage** on all costing methods (FIFO/LIFO/average/specific-ID).
2. **Real `procurement:grn:completed` subscription** in `onReady` — creates stock movements, not just logs.
3. **`onClose` teardown** — detach bus subscription.
4. **`InventoryConfigSchema`** expanded with `basePath`, `defaultCostingMethod`, `lowStockThreshold`.
5. **Remove `ctx.eventBus.on("procurement:grn:completed" as never, ...)`** — proper EventMap declaration.
6. **Per-table SurrealQL** — split single `inventory.surql` into per-entity files.
7. **Auth + tenant isolation** on every route and query.
8. **Idempotency** on stock movements.
9. **Audit logging** on adjustments and disposals.
---
## File layout
```text
api/logistics/api-plugin-inventory/
package.json tsconfig.json vitest.config.ts
surql/ (inventory_item, warehouse, stock_level, stock_movement, lot, adjustment tables)
src/
index.ts events.ts types/ errors/
services/item/ services/warehouse/ services/stock/
services/movement/ services/adjustment/ services/costing/ services/report/
routes/inventory/
tests/integration.test.ts
```
---
## Impact
Prerequisites: `@suaveplan/api`, `@suaveplan/api-plugin-auth`, `@suaveplan/api-plugin-database`, `@suaveplan/events`, `@suaveplan/idempotency`, `@suaveplan/audit-logging`. Downstream: `@suaveplan/api-plugin-warehouse-ops` (stock queries), `@suaveplan/api-plugin-store` (stock reservation).

View File

@@ -0,0 +1,65 @@
# Tasks: enterprise-api-plugin-inventory
**Change ID**: enterprise-api-plugin-inventory
**Package**: `@suaveplan/api-plugin-inventory`
**Target path**: `api/logistics/api-plugin-inventory`
**Prerequisite packages on Verdaccio**: `@suaveplan/api`, `@suaveplan/api-shared`, `@suaveplan/api-plugin-auth`, `@suaveplan/api-plugin-database`, `@suaveplan/events`, `@suaveplan/idempotency`, `@suaveplan/audit-logging`, `@suaveplan/rate-limiter`, `@suaveplan/error`
---
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Scaffold + types + errors + events
- [ ] Create `api/logistics/api-plugin-inventory/`; `package.json` v0.0.0; standard tooling. Include `decimal.js` in deps (Bun catalog).
- [ ] Types: `InventoryItem`, `CreateItemInput`, `UpdateItemInput`, `StockMovement`, `Warehouse`, `StockLevel`, `LotInfo`, `CostingMethod` enum, `AdjustmentRecord`, `InventoryConfig` (Zod; expanded with basePath, defaultCostingMethod, lowStockThreshold).
- [ ] Errors: 6-code union + registration. Test + doc.
- [ ] Events: `InventoryEventMap` (inventory:stock:received, inventory:stock:issued, inventory:stock:low, inventory:adjustment:created). Module augmentation — no `as never`.
---
## 2. SurrealQL
- [ ] `inventory_item.surql`, `warehouse.surql`, `stock_level.surql`, `stock_movement.surql`, `lot.surql`, `adjustment.surql`. All with tenantId indexes.
---
## 3. Services (all `.test.ts` + `.md`)
- [ ] **ItemService**: `createItem`, `updateItem`, `deleteItem`, `getItem`, `listItems` (paginated, filterable).
- [ ] **WarehouseService**: `createWarehouse`, `updateWarehouse`, `deleteWarehouse`, `getWarehouse`, `listWarehouses`.
- [ ] **StockService**: `getStockLevel(itemId, warehouseId)`, `listStockLevels(itemId)`, `isLowStock(itemId)`.
- [ ] **MovementService**: `receive`, `issue`, `transfer`. All idempotent; emit `inventory:stock:received` / `:issued`.
- [ ] **CostingService**: `calculateCost(itemId, quantity, method)` — FIFO/LIFO/average/specific-ID. Use `decimal.js` for all arithmetic. Fully tested edge cases.
- [ ] **AdjustmentService**: `createAdjustment` (physical-count discrepancy); audit-logged; emit event.
- [ ] **ReportService**: `getLowStockReport()`, `getExpiringStockReport()`, `getValuationReport()`.
---
## 4. `procurement:grn:completed` subscription
- [ ] In `onReady`: subscribe to `procurement:grn:completed` event on bus; for each GRN line item, call `MovementService.receive()` to create stock movement. Properly typed — no `as never` cast.
- [ ] `onClose`: detach bus subscription.
- [ ] Integration test: emit `procurement:grn:completed` → verify stock movement created.
---
## 5. Routes
- [ ] Full CRUD for items, warehouses; stock queries; movement creation; adjustments; reports.
- [ ] All write routes: `requireAuth` + permission gates + idempotency + audit where applicable.
- [ ] Route `.test.ts` + `.md`.
---
## 6. Plugin factory + integration tests + publish
- [ ] `createInventoryPlugin`: `definePlugin`, `dependencies: ["database", "auth"]`, `migrationsPath: "./surql"`.
- [ ] Integration: receive stock → issue stock → FIFO costing → low stock alert → adjustment (real SurrealDB).
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/api-plugin-inventory` — green; 100% coverage.
- [ ] `bun scripts/publish.ts --package @suaveplan/api-plugin-inventory`.
- [ ] Archive → `openspec/archive/2026-04-24-enterprise-api-plugin-inventory/`.