# Task D.7.1 – Setup Blueprint & Seed Specification

## Objective

Create a complete implementation blueprint for the ALLA OS Initial Setup, Seed Framework, CSV Import, Reset/Reseed, and Verification workflow before starting code implementation.

This task must convert the Phase 1/2 audit from Task D.7 into a precise technical specification that can be implemented safely without guessing, duplicating seed logic, or breaking existing CRM, RBAC, approval, document sequence, storage, or PDF behavior.

No production code implementation should begin in this task except documentation/specification files and optional CSV template drafts.

---

# Scope

## In Scope

- Complete Seed Matrix
- CSV Template Specification
- CSV Import Mapping
- Setup Wizard Flow Specification
- Setup State Machine
- Verification Matrix
- Reset/Reseed Matrix
- Seed Version Strategy
- Seed Manifest Strategy
- Setup Plugin Architecture
- Implementation Slice Plan for D.7.2+

## Out of Scope

- Building the final Setup Wizard UI
- Building the CSV import engine
- Running destructive reset logic
- Changing existing seed behavior
- Changing production CRM business logic
- Adding unsupported first-class domains without schema decision

---

# Phase 1 — Review Existing Audit

Start from the existing Task D.7 Phase 1/2 audit report.

Review:

- `plans/task-d.7.md`
- Task D.7 audit output
- `AGENTS.md`
- `docs/standards/*`
- `docs/adr/*`
- `src/db/schema.ts`
- `src/db/seeds/**/*`
- `scripts/seed-system.ts`
- `scripts/seed-uat.ts`
- `scripts/seed-reset.ts`
- `scripts/db/reset-database.ts`
- `src/features/foundation/**/*`
- `src/features/crm/**/*`
- `src/features/setup/**/*`

Do not repeat the same audit. Extend it into a blueprint.

---

# Phase 2 — Complete Seed Matrix

Create a complete seed matrix covering all known setup-related tables and concepts.

Output file:

```text
docs/setup/seed-matrix.md
```

Required columns:

```text
Module
Entity
Table / Storage
Seed Type
Required For First Login
Required For CRM
Required For Quotation
CSV Importable
Wizard Editable
Auto Generated
Source of Truth
Dependencies
Import Order
Reset Scope
Notes
```

Seed Type values:

```text
foundation
organization
business
demo_uat
runtime_generated
runtime_only
unsupported_pending_schema
```

Example row:

```text
Foundation | Branch | ms_options(category=crm_branch) | organization | yes | yes | yes | yes | yes | no | CSV/Wizard | organization, created_by_user | 08 | organization_reset | Branch is currently modeled as master option, not a branch table.
```

The matrix must explicitly include:

- users
- organizations
- memberships
- CRM role profiles
- CRM user role assignments
- ms_options
- crm_branch options
- crm_product_type options
- document sequences
- approval workflows
- approval steps
- approval matrices
- document templates
- document template versions
- document template mappings
- document libraries
- notification templates
- report definitions
- customers
- contacts
- contact shares
- leads
- opportunities
- quotations
- quotation items
- quotation topics
- quotation topic items
- quotation project parties
- followups
- audit logs
- notification events
- generated PDFs / document artifacts
- uploaded files / attachments
- setup state
- seed manifests

Also include unsupported or ambiguous items:

- departments
- teams
- warehouses
- sites
- price books
- services
- tax rate table if not first-class
- email provider config if not first-class

---

# Phase 3 — CSV Template Specification

Create CSV template specification.

Output file:

```text
docs/setup/csv-template-spec.md
```

For each supported CSV, define:

```text
File Name
Purpose
Target Table / Service
Seed Type
Required Columns
Optional Columns
Generated Columns
Validation Rules
Relationship Resolution
Duplicate Detection
Upsert Key
Import Order
Example Rows
Error Examples
```

Required CSV specs:

```text
organizations.csv
users.csv
memberships.csv
crm-role-assignments.csv
master-options.csv
branches.csv
product-types.csv
document-sequences.csv
approval-workflows.csv
approval-steps.csv
approval-matrix.csv
customers.csv
contacts.csv
contact-shares.csv
leads.csv
opportunities.csv
opportunity-parties.csv
quotations.csv
quotation-items.csv
quotation-parties.csv
quotation-topics.csv
quotation-topic-items.csv
```

Unsupported/deferred specs must be marked clearly:

```text
departments.csv
teams.csv
warehouses.csv
sites.csv
services.csv
price-books.csv
tax-rates.csv
attachments.csv
email-settings.csv
```

Each CSV section must include at least one example row.

Example:

```csv
organization_code,organization_name,slug,tax_id,default_currency,status
ALLA,ALLA Public Company Limited,alla,0107558000393,THB,active
```

---

# Phase 4 — Import Mapping Specification

Create import mapping specification.

Output file:

```text
docs/setup/import-mapping.md
```

For every supported CSV, define:

```text
CSV Column
Target Field
Transform
Validation
Required
Reference Resolver
Fallback
Notes
```

Important mappings:

## branches.csv

Must map to:

```text
ms_options
category = crm_branch
organization_id = selected organization
value/code = branch_code
label = branch_name
metadata = prefix, address, tax info if applicable
```

## product-types.csv

Must map to:

```text
ms_options
category = crm_product_type
value/code = product_type_code
label = product_type_name
metadata = document_prefix
```

## document-sequences.csv

Must resolve:

```text
organization_code
branch_code
product_type_code
document_type
period_format
prefix
current_number
```

## users.csv + memberships.csv

Must clarify whether user creation and organization membership are separate or combined.

## crm-role-assignments.csv

Must resolve:

```text
user_email
organization_code
crm_role_code
branch_code
product_type_code
```

## customers.csv

Must resolve:

```text
organization_code
owner_user_email
customer_type
customer_group
```

## leads/opportunities/quotations

Must resolve:

```text
organization_code
customer_code
contact_email
branch_code
product_type_code
owner_user_email
created_by_email
```

---

# Phase 5 — Setup Wizard Blueprint

Create wizard blueprint.

Output file:

```text
docs/setup/setup-wizard-blueprint.md
```

Define:

```text
Step Number
Step Name
Purpose
Inputs
Validation
Actions
APIs
Can Skip
Can Go Back
Resume Behavior
Error Handling
Output
```

Required wizard steps:

1. System Readiness
2. Foundation Install
3. Organization Setup
4. Branch & Product Type Setup
5. Administrator Setup
6. Document Sequence Setup
7. Approval Workflow Setup
8. CSV Import
9. Verification
10. Finish & Report

Each step must define required fields.

Example:

```text
Organization Setup Inputs

organization_name: required
organization_code: required, uppercase, unique
slug: required, lowercase, unique
tax_id: optional
phone: optional
email: optional email format
address: optional
default_currency: required, default THB
timezone: required, default Asia/Bangkok
logo: optional
```

---

# Phase 6 — Setup State Machine

Create setup state specification.

Output file:

```text
docs/setup/setup-state-machine.md
```

Define state model:

```text
not_started
readiness_checked
foundation_installed
organization_created
administrator_created
scope_configured
sequences_configured
approval_configured
csv_validated
csv_imported
verified
completed
failed
cancelled
```

Define events:

```text
CHECK_READINESS
INSTALL_FOUNDATION
CREATE_ORGANIZATION
CREATE_ADMIN
CONFIGURE_SCOPE
CONFIGURE_SEQUENCES
CONFIGURE_APPROVAL
VALIDATE_CSV
IMPORT_CSV
RUN_VERIFICATION
COMPLETE_SETUP
FAIL_STEP
CANCEL_SETUP
RESUME_SETUP
RESET_STEP
```

Define persistence strategy.

If no setup table exists, propose new table:

```text
setup_runs
setup_run_steps
seed_manifests
seed_manifest_items
```

Do not implement migrations in this task unless explicitly approved.

---

# Phase 7 — Verification Matrix

Create verification matrix.

Output file:

```text
docs/setup/verification-matrix.md
```

Required columns:

```text
Check ID
Area
Check Name
Purpose
Required For
Method
Pass Condition
Warning Condition
Fail Condition
Suggested Fix
API / Service
```

Checks must include:

- environment variable presence
- database connectivity
- migration status
- storage read/write/delete smoke test
- upload directory readiness
- first administrator exists
- administrator membership exists
- administrator CRM role assignment resolves
- organization active
- branch option exists
- product type option exists
- document sequence preview works
- quotation approval workflow resolves
- approval matrix resolves
- PDF template exists
- PDF template version active
- PDF mapping exists
- notification templates exist
- report definitions exist
- email configuration optional dry-run

---

# Phase 8 — Reset / Reseed Matrix

Create reset/reseed specification.

Output file:

```text
docs/setup/reset-reseed-matrix.md
```

Define reset scopes:

```text
foundation_reset
organization_reset
business_reset
demo_uat_reset
full_reset
csv_import_rollback
setup_run_reset
```

For each scope define:

```text
Tables affected
Data retained
Data deleted
Safety guard
Requires confirmation
Allowed environment
Transaction behavior
Storage cleanup behavior
Audit behavior
Recommended command/API
```

Rules:

- Production destructive reset must be blocked.
- Reset must require explicit confirmation.
- Storage cleanup must be compensated and reported.
- Runtime generated approved artifacts must not be casually deleted outside explicit full reset/demo reset.

---

# Phase 9 — Seed Version and Manifest Strategy

Create seed lifecycle specification.

Output file:

```text
docs/setup/seed-version-manifest.md
```

Define:

```text
Seed Package
Version
Dependencies
Checksum
Applied At
Applied By
Target Organization
Source
Status
Report
```

Propose manifest format:

```json
{
  "name": "crm-foundation",
  "version": "1.0.0",
  "type": "foundation",
  "dependencies": ["system-core@1.0.0"],
  "items": [
    {
      "file": "master-options.csv",
      "checksum": "...",
      "required": true
    }
  ]
}
```

Define upgrade behavior:

```text
same version + same checksum = skip
same version + changed checksum = warn/block unless force
newer version = apply if compatible
older version = block unless rollback mode
```

---

# Phase 10 — Setup Plugin Architecture

Create plugin architecture proposal.

Output file:

```text
docs/setup/setup-plugin-architecture.md
```

Goal:

Future modules can register setup behavior without editing the core wizard.

Plugin contract should cover:

```text
module_id
display_name
setup_steps
csv_templates
seed_tasks
verification_checks
reset_scopes
dependencies
enabled_condition
```

Example modules:

```text
core
foundation
crm
quotation
approval
document
notification
reporting
future_asset
future_hr
```

No implementation required, but the design must be concrete enough for future implementation.

---

# Phase 11 — Implementation Plan for D.7.2+

Create implementation slice plan.

Output file:

```text
plans/task-d.7.2.md
```

Recommended slices:

## D.7.2

Setup Readiness and Verification APIs

## D.7.3

CSV Template Generator and Static Template Pack

## D.7.4

CSV Preview Validation Engine

## D.7.5

CSV Commit Import Engine

## D.7.6

Dashboard Setup Wizard UI

## D.7.7

Scoped Reset and Reseed Engine

## D.7.8

Seed Manifest and Setup State Persistence

Each slice must include:

```text
Objective
Files to review
Implementation scope
Out of scope
Acceptance criteria
Risk notes
```

---

# Deliverables

The task is complete only when the following files exist:

```text
docs/setup/seed-matrix.md
docs/setup/csv-template-spec.md
docs/setup/import-mapping.md
docs/setup/setup-wizard-blueprint.md
docs/setup/setup-state-machine.md
docs/setup/verification-matrix.md
docs/setup/reset-reseed-matrix.md
docs/setup/seed-version-manifest.md
docs/setup/setup-plugin-architecture.md
plans/task-d.7.2.md
```

Optional drafts:

```text
setup/templates/*.csv
```

---

# Acceptance Criteria

- The setup implementation can be started without guessing.
- Every setup-related entity is classified.
- Every supported CSV has required fields, validation, mapping, upsert key, and examples.
- Unsupported CSVs are clearly marked with the reason.
- Wizard steps have inputs, validation, actions, APIs, outputs, and resume behavior.
- Setup state machine is defined.
- Verification checks are actionable.
- Reset/reseed scopes are safe and explicit.
- Seed version and manifest behavior is defined.
- Future module setup plugin strategy is documented.
- No existing production behavior is changed.
 
---

# Implementation Log

## 2026-07-02 - Blueprint documentation completed

- Created complete setup blueprint/specification deliverables under `docs/setup/`.
- Created next implementation slice plan at `plans/task-d.7.2.md`.
- No production code behavior was changed.
