# Phase 9: ERP Integration (NAV Product Sync)

**Status:** ⏳ Todo
**Progress:** 0/10 tasks (0%)
**Started:** -
**Completed:** -
**Assigned to:** -

---

## Overview

Implement NAV ERP product sync API endpoint: receive product data pushed from NAV ERP, validate, and upsert into local database.

**Goal:** NAV ERP can push products to our API, keeping product catalog up-to-date.

---

## Dependencies

- ✅ Phase 2: Database (products table needed)
- ⚠️ **Required:** API key for NAV ERP authentication

---

## Tasks

### Schema & Validation

- [ ] Create NAV ERP product schema (Zod)
  - File: `server/utils/schemas/navProduct.ts`
  - Fields: navProductId, name, description, price, stockQuantity, category, active
  - Validation rules: required fields, price > 0, stock >= 0
  - Export: `navProductSchema`, `NavProductData` type

### API Endpoint

- [ ] Create /api/erp/products.post.ts endpoint
  - Body: { products: NavProductData[] } (array of products)
  - Validate API key from header: `Authorization: Bearer <API_KEY>`
  - Validate product data with Zod
  - Upsert products in DB (insert if new, update if exists)
  - Return: { success: true, upserted: count, errors: [] }

### Authentication

- [ ] Implement API key authentication
  - Middleware: `server/middleware/erpAuth.ts`
  - Check Authorization header
  - Validate API key against NAV_ERP_API_KEY env var
  - Return 401 if invalid/missing
  - Only apply to /api/erp/\* routes

### Business Logic

- [ ] Implement product validation
  - Validate required fields
  - Validate data types and formats
  - Validate price is positive
  - Validate stock quantity is non-negative
  - Return detailed errors for invalid products

- [ ] Implement product upsert logic
  - Check if product exists by navProductId (unique key)
  - If exists: Update name, description, price, stock, category, active, updated_at
  - If not exists: Insert new product with all fields
  - Use Drizzle's `.onConflictDoUpdate()` or manual check
  - Return count of upserted products

### Error Handling

- [ ] Add error handling & logging
  - Log all incoming requests (timestamp, product count)
  - Log validation errors with details
  - Log DB errors
  - Return structured errors to NAV ERP
  - Example: `{ success: false, errors: [{ product: '...', message: '...' }] }`

### Testing

- [ ] Test product sync (mock data)
  - Create sample NAV product data (JSON)
  - POST to /api/erp/products with valid API key
  - Verify products are created in DB
  - POST again with updated data
  - Verify products are updated in DB
  - Test with invalid data → verify validation errors

- [ ] Test API key auth
  - Test without Authorization header → expect 401
  - Test with invalid API key → expect 401
  - Test with valid API key → expect 200

- [ ] Add rate limiting
  - Limit NAV ERP endpoint to prevent abuse
  - Example: 100 requests / hour per API key
  - Use `server/middleware/rate-limit.ts` (extend from Phase 3)
  - Return 429 if limit exceeded

- [ ] Document ERP integration
  - Document API endpoint spec (request/response format)
  - Document authentication method (API key in header)
  - Document product data schema
  - Document error codes and messages
  - Document rate limits
  - Create example curl commands for NAV team

---

## Acceptance Criteria

- [x] NAV product schema is defined with Zod
- [x] /api/erp/products endpoint is implemented
- [x] API key authentication works correctly
- [x] Product validation works (Zod schema)
- [x] Product upsert logic works (insert new, update existing)
- [x] Error handling returns structured errors
- [x] Logging captures all requests and errors
- [x] Can sync products successfully with mock data
- [x] API key auth prevents unauthorized access
- [x] Rate limiting protects endpoint from abuse
- [x] ERP integration is documented for NAV team

---

## Notes

- **Push Model:** NAV ERP pushes to us (we don't pull)
- **Batch Sync:** NAV can send multiple products in one request
- **Idempotent:** Repeated syncs with same data should be safe (upsert)
- **API Key Storage:** Store NAV_ERP_API_KEY in .env (dev/prod)
- **NAV Contact:** Coordinate with NAV team for API key and sync schedule

---

## Blockers

- ⚠️ **API Key:** Need to generate/agree on API key with NAV team
- ⚠️ **NAV Schema:** Need exact product schema from NAV team (may differ from assumption)

---

## Related Documentation

- [docs/PRD.md: F-011](../docs/PRD.md#f-011-nav-erp-push-endpunkt)
- [docs/ARCHITECTURE.md: NAV ERP Integration](../docs/ARCHITECTURE.md#33-nav-erp-product-sync)
- [CLAUDE.md: Important Constraints](../CLAUDE.md#important-constraints)
