# Orders Seed

E-commerce order management domain demonstrating advanced ADL features including
decimal/money types, component objects, repeaters, computed fields, composite
primary keys, versioning, bulk import/export, caching, and custom operations.

## Resources

### Customer

Buyer profile with UUID primary key.

| Field      | Type     | Notes                     |
|------------|----------|---------------------------|
| id         | uuid     | Primary key               |
| firstName  | string   | Required, max 100         |
| lastName   | string   | Required, max 100         |
| email      | email    | Required, unique          |
| phone      | phone    |                           |
| createdAt  | datetime | Auto-set on create        |
| updatedAt  | datetime | Auto-set on update        |

**Computed fields:**
- `fullName` (virtual) -- concatenation of firstName and lastName, calculated on read, never stored.

**Features:** search

### Product

Catalog item with pricing. Read-heavy reference data with TTL caching.

| Field       | Type    | Notes                        |
|-------------|---------|------------------------------|
| id          | uuid    | Primary key                  |
| sku         | string  | Required, unique, max 50     |
| name        | string  | Required, max 200            |
| description | text    |                              |
| unitPrice   | decimal | Required, precision 19 / scale 4, min 0 |
| stockQty    | integer | Default 0                    |
| isActive    | boolean | Default true                 |
| createdAt   | datetime| Auto-set on create           |
| updatedAt   | datetime| Auto-set on update           |

**Features:** search, caching (300s TTL), import, export

### Order

The primary resource. Stores a complete order with inline shipping address
(component) and line items (repeater).

| Field           | Type      | Notes                            |
|-----------------|-----------|----------------------------------|
| id              | uuid      | Primary key                      |
| customerId      | uuid      | Required, immutable (FK)         |
| customerName    | string    | Denormalized display name        |
| status          | enum      | OrderStatus, default "pending"   |
| notes           | text      |                                  |
| shippingAddress | component | Inline Address object            |
| lineItems       | repeater  | Array of product line items      |
| discountCode    | string    | Max 50                           |
| discountAmount  | decimal   | Default 0                        |
| createdAt       | datetime  | Auto-set on create               |
| updatedAt       | datetime  | Auto-set on update               |

**Computed fields:**
- `orderTotal` (materialized aggregation) -- sum of all related OrderItem subtotals. Recalculated on item create/update/delete.

**Features:** versioning, audit, export

**Audit tracking:** status, discountCode, discountAmount, notes, shippingAddress

**Custom operations:**
- `POST /:id/duplicate` -- clones an order with a new ID, resets status to pending.
- `POST /:id/apply-discount` -- validates and applies a discount code from the Discount resource.

### OrderItem

Line item in an order. Uses a composite primary key (orderId + productId).

| Field     | Type    | Notes                              |
|-----------|---------|------------------------------------|
| orderId   | uuid    | Composite PK part 1, immutable     |
| productId | uuid    | Composite PK part 2, immutable     |
| quantity  | integer | Required, min 1                    |
| unitPrice | decimal | Required, precision 19 / scale 4   |
| createdAt | datetime| Auto-set on create                 |
| updatedAt | datetime| Auto-set on update                 |

**Computed fields:**
- `subtotal` (materialized) -- quantity * unitPrice, recalculated on write when quantity or unitPrice changes.

### Discount

Coupon or discount code applied to orders via the `apply-discount` custom operation.

| Field     | Type    | Notes                         |
|-----------|---------|-------------------------------|
| id        | uuid    | Primary key                   |
| code      | string  | Required, unique, uppercase   |
| type      | enum    | DiscountType (percentage/fixed)|
| value     | decimal | Required, min 0               |
| maxUses   | integer | Null means unlimited          |
| usedCount | integer | Default 0, immutable (engine-managed) |
| expiresAt | datetime|                               |
| isActive  | boolean | Default true                  |
| createdAt | datetime| Auto-set on create            |
| updatedAt | datetime| Auto-set on update            |

## Relationships

```
Customer 1──* Order          (Customer.orders hasMany Order)
Order    *──1 Customer       (Order.customer belongsTo Customer)
Order    1──* OrderItem      (Order.orderItems hasMany OrderItem, cascade delete)
OrderItem *──1 Order         (OrderItem.order belongsTo Order, cascade delete)
OrderItem *──1 Product       (OrderItem.product belongsTo Product)
```

## Enums

### OrderStatus

A seven-state lifecycle for orders:

| Value      | Label      | Color   |
|------------|------------|---------|
| pending    | Pending    | #f59e0b |
| confirmed  | Confirmed  | #3b82f6 |
| processing | Processing | #8b5cf6 |
| shipped    | Shipped    | #10b981 |
| delivered  | Delivered  | #22c55e |
| cancelled  | Cancelled  | #ef4444 |
| refunded   | Refunded   | #6b7280 |

### DiscountType

| Value      | Label      |
|------------|------------|
| percentage | Percentage |
| fixed      | Fixed      |

## Shared Objects

- **Timestamp** -- `createdAt` (auto on create) and `updatedAt` (auto on update), merged into all resources.
- **Address** -- street, city, state, postalCode, country; used as a component in Order.shippingAddress.

## Roles and Permissions

| Role       | Description                                          |
|------------|------------------------------------------------------|
| admin      | Full system access, can manage all resources and delete orders |
| customer   | End user, can place orders and view own records      |
| staff      | Internal staff, can view all orders and manage products |

**Permission matrix (summary):**

| Resource   | list            | read            | create         | update          | delete |
|------------|-----------------|-----------------|----------------|-----------------|--------|
| Customer   | customer,admin,staff | customer,admin,staff | authenticated | customer,admin,staff | admin |
| Product    | *               | *               | admin,staff    | admin,staff     | admin  |
| Order      | customer,admin,staff | customer,admin,staff | authenticated | customer,admin,staff | admin |
| OrderItem  | customer,admin,staff | customer,admin,staff | customer,admin,staff | customer,admin,staff | customer,admin,staff |
| Discount   | admin,staff     | admin,staff     | admin          | admin           | admin  |

## Seed Data

The seed file (`seed.yaml`) provisions:

- **3 roles:** admin, customer, staff
- **5 users:** admin (Admin123!), alice, bob, carol, diana (Demo123!)
- **5 products:** WIDGET-001, WIDGET-002, GADGET-001, GADGET-002, SERVICE-001
- **2 discounts:** SAVE10 (10% off), FLAT5 ($5 off)
- **2 customers:** Alice Johnson, Bob Smith
- **4 orders:** covering delivered, pending, confirmed, and cancelled statuses with varying line items

## Usage

Point your kalosd config at this seed:

```json
{
  "adl": {
    "domain_file": "seeds/orders/domain.yaml"
  },
  "seeder": {
    "seed_file": "seeds/orders/seed.yaml"
  }
}
```
