# Store Operations Expansion Migration Plan

## Overview

**Objective:** Expand the admin "Store Operations" section to provide comprehensive store storefront management capabilities, allowing administrators to manage store operations on their behalf.

**Scope:** Products, Inventory, Orders, Shipping, and Customers management from the admin panel.

**Status:** In Progress

---

## Current State

The admin sidebar has a "Store Operations" section (formerly "Product Catalog") with:

| Feature | Status | Description |
|---------|--------|-------------|
| Marketplace Products | ✅ Complete | View/manage products from marketplace imports |
| Store Products | ✅ Complete | View/manage store-specific products |
| Customers | ✅ Complete | Customer management (moved from Platform Admin) |
| Inventory | ✅ Complete | Admin API + UI with stock adjustments |
| Orders | ✅ Complete | Order management, status updates, fulfillment |
| Shipping | 🔲 Planned | Tracking, carriers, shipping rules |

---

## Target Architecture

### Admin Sidebar Structure

```
Store Operations
├── Marketplace Products  (/admin/marketplace-products)
├── Store Products       (/admin/store-products)
├── Customers             (/admin/customers)
├── Inventory             (/admin/inventory)        [Phase 2]
├── Orders                (/admin/orders)           [Phase 3]
└── Shipping              (/admin/shipping)         [Phase 4]
```

### Design Principles

1. **Store Selection Pattern**: All pages should support store filtering/selection
2. **Bulk Operations**: Admin should be able to perform bulk actions across stores
3. **Audit Trail**: All admin actions on behalf of stores should be logged
4. **Permission Granularity**: Future support for role-based access to specific features

---

## Phase 1: Foundation (Completed)

### 1.1 Sidebar Restructure ✅

- [x] Rename "Product Catalog" to "Store Operations"
- [x] Update section key from `productCatalog` to `storeOps`
- [x] Move Customers from "Platform Administration" to "Store Operations"
- [x] Add placeholder comments for future menu items

### 1.2 Files Modified

| File | Changes |
|------|---------|
| `app/templates/admin/partials/sidebar.html` | Section rename, Customers move |
| `static/admin/js/init-alpine.js` | Section key update, page mapping |

---

## Phase 2: Inventory Management (Planned)

### 2.1 Features

| Feature | Priority | Description |
|---------|----------|-------------|
| Stock Overview | High | Dashboard showing stock levels across stores |
| Stock Adjustments | High | Manual stock adjustments with reason codes |
| Low Stock Alerts | Medium | Configurable thresholds and notifications |
| Stock History | Medium | Audit trail of all stock changes |
| Bulk Import/Export | Low | CSV import/export for stock levels |

### 2.2 Database Changes

```sql
-- New table for stock adjustment history
CREATE TABLE inventory_adjustments (
    id SERIAL PRIMARY KEY,
    store_id INTEGER NOT NULL REFERENCES stores(id),
    product_id INTEGER NOT NULL REFERENCES store_products(id),
    adjustment_type VARCHAR(50) NOT NULL,  -- 'manual', 'sale', 'return', 'correction'
    quantity_change INTEGER NOT NULL,
    quantity_before INTEGER NOT NULL,
    quantity_after INTEGER NOT NULL,
    reason VARCHAR(500),
    adjusted_by INTEGER REFERENCES users(id),
    created_at TIMESTAMP DEFAULT NOW()
);

-- Low stock alert configuration
CREATE TABLE low_stock_thresholds (
    id SERIAL PRIMARY KEY,
    store_id INTEGER NOT NULL REFERENCES stores(id),
    product_id INTEGER REFERENCES store_products(id),  -- NULL = store default
    threshold INTEGER NOT NULL DEFAULT 10,
    notification_enabled BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);
```

### 2.3 API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/v1/admin/inventory` | List inventory across stores |
| GET | `/api/v1/admin/inventory/stores/{id}` | Store-specific inventory |
| POST | `/api/v1/admin/inventory/adjust` | Create stock adjustment |
| GET | `/api/v1/admin/inventory/low-stock` | Low stock alerts |
| PATCH | `/api/v1/admin/inventory/thresholds` | Update alert thresholds |

### 2.4 Frontend Components

| Component | Description |
|-----------|-------------|
| `inventory.html` | Main inventory page with store selector |
| `inventory.js` | Alpine.js controller |
| `inventory-table.html` | Stock levels table partial |
| `adjustment-modal.html` | Stock adjustment form modal |

---

## Phase 3: Order Management (Planned)

### 3.1 Features

| Feature | Priority | Description |
|---------|----------|-------------|
| Order List | High | View all orders across stores |
| Order Details | High | Full order information and history |
| Status Updates | High | Change order status on behalf of store |
| Order Notes | Medium | Internal notes for admin/store communication |
| Refund Processing | Medium | Handle refunds and cancellations |
| Order Export | Low | Export orders to CSV/Excel |

### 3.2 Database Changes

```sql
-- Admin notes on orders
CREATE TABLE order_admin_notes (
    id SERIAL PRIMARY KEY,
    order_id INTEGER NOT NULL REFERENCES orders(id),
    admin_id INTEGER NOT NULL REFERENCES users(id),
    note TEXT NOT NULL,
    is_internal BOOLEAN DEFAULT true,  -- false = visible to store
    created_at TIMESTAMP DEFAULT NOW()
);

-- Order status change history
CREATE TABLE order_status_history (
    id SERIAL PRIMARY KEY,
    order_id INTEGER NOT NULL REFERENCES orders(id),
    previous_status VARCHAR(50),
    new_status VARCHAR(50) NOT NULL,
    changed_by INTEGER REFERENCES users(id),
    change_reason VARCHAR(500),
    created_at TIMESTAMP DEFAULT NOW()
);
```

### 3.3 API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/v1/admin/orders` | List all orders with filters |
| GET | `/api/v1/admin/orders/{id}` | Order details |
| PATCH | `/api/v1/admin/orders/{id}/status` | Update order status |
| POST | `/api/v1/admin/orders/{id}/notes` | Add admin note |
| POST | `/api/v1/admin/orders/{id}/refund` | Process refund |

---

## Phase 4: Shipping Management (Planned)

### 4.1 Features

| Feature | Priority | Description |
|---------|----------|-------------|
| Shipment Tracking | High | Track shipments across carriers |
| Carrier Management | Medium | Configure available carriers per store |
| Shipping Rules | Medium | Weight-based, zone-based pricing rules |
| Label Generation | Low | Integration with carrier APIs |
| Delivery Reports | Low | Delivery success rates, timing analytics |

### 4.2 Database Changes

```sql
-- Shipping carriers
CREATE TABLE shipping_carriers (
    id SERIAL PRIMARY KEY,
    code VARCHAR(50) UNIQUE NOT NULL,  -- 'dhl', 'ups', 'post_lu'
    name VARCHAR(100) NOT NULL,
    tracking_url_template VARCHAR(500),
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Store carrier configuration
CREATE TABLE store_shipping_carriers (
    id SERIAL PRIMARY KEY,
    store_id INTEGER NOT NULL REFERENCES stores(id),
    carrier_id INTEGER NOT NULL REFERENCES shipping_carriers(id),
    account_number VARCHAR(100),
    is_default BOOLEAN DEFAULT false,
    is_enabled BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(store_id, carrier_id)
);

-- Shipping rules
CREATE TABLE shipping_rules (
    id SERIAL PRIMARY KEY,
    store_id INTEGER NOT NULL REFERENCES stores(id),
    name VARCHAR(100) NOT NULL,
    rule_type VARCHAR(50) NOT NULL,  -- 'weight', 'price', 'zone'
    conditions JSONB NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    is_active BOOLEAN DEFAULT true,
    priority INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT NOW()
);
```

### 4.3 API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/v1/admin/shipping/carriers` | List carriers |
| GET | `/api/v1/admin/shipping/stores/{id}` | Store shipping config |
| PATCH | `/api/v1/admin/shipping/stores/{id}` | Update store shipping |
| GET | `/api/v1/admin/shipping/rules` | List shipping rules |
| POST | `/api/v1/admin/shipping/rules` | Create shipping rule |

---

## Implementation Checklist

### Phase 1: Foundation ✅
- [x] Sidebar restructure
- [x] Move Customers to Store Operations
- [x] Update Alpine.js configuration
- [x] Create migration plan documentation

### Phase 2: Inventory ✅
- [x] Database migrations (inventory table exists)
- [x] Create `InventoryService`
- [x] API endpoints
- [x] Admin inventory page
- [x] Stock adjustment modal
- [x] Low stock alerts (via filtering)

### Phase 3: Orders ✅
- [x] Database migrations (orders table exists)
- [x] Add admin methods to `OrderService`
- [x] API endpoints
- [x] Admin orders page
- [x] Order detail view
- [x] Status update functionality

### Phase 4: Shipping
- [ ] Database migrations
- [ ] Create `ShippingService`
- [ ] API endpoints
- [ ] Admin shipping page
- [ ] Carrier configuration
- [ ] Shipping rules builder

---

## Testing Requirements

### Unit Tests
- Service layer tests for each new service
- Model validation tests

### Integration Tests
- API endpoint tests with authentication
- Database constraint tests
- Transaction rollback tests

### E2E Tests (Future)
- Admin workflow tests
- Store operation scenarios

---

## Rollback Plan

Each phase is independent and can be rolled back:

1. **Database**: Each phase has its own migration file with down migration
2. **API**: New endpoints don't affect existing ones
3. **Frontend**: Menu items can be hidden by commenting out in sidebar.html

---

## Related Documentation

- [Database Migrations Guide](database-migrations.md)
- [Architecture Rules](../architecture-rules.md)
- [Naming Conventions](../naming-conventions.md)
