# Task D.7 Initial System Setup Wizard and Seed Framework - Phase 1/2 Audit

Date: 2026-07-02
Status: Phase 1 and Phase 2 audit complete. Implementation intentionally not started.

## Scope

Task D.7 asks for a production initialization framework for a brand-new ALLA OS installation, including seed dependency analysis, CSV templates, a reusable CSV import engine, Setup Wizard, verification, reset/reseed support, and documentation.

The task contract explicitly says no implementation should begin until the current system audit and seed dependency report are complete. This document records that required first pass.

## Documents Reviewed

- `AGENTS.md`
- `plans/task-d.7.md`
- `docs/standards/task-contract-template.md`
- `docs/standards/task-catalog.md`
- `docs/standards/project-foundations.md`
- `docs/standards/architecture-rules.md`
- `docs/standards/ui-ux-rules.md`
- `docs/standards/task-review-checklist.md`
- `docs/adr/*.md`
- `docs/business/*.md`
- `docs/security/*.md`
- existing implementation notes under `docs/implementation/**`

## Code Areas Reviewed

- `src/db/schema.ts`
- `drizzle/*.sql`
- `src/db/seeds/**`
- `scripts/seed-system.ts`
- `scripts/seed-uat.ts`
- `scripts/seed-reset.ts`
- `scripts/db/reset-database.ts`
- `scripts/lib/seed-utils.ts`
- `src/features/foundation/**`
- `src/features/crm/**`
- `src/features/setup/components/setup-wizard.tsx`
- existing API routes under `src/app/api/**`
- existing dashboard routes under `src/app/dashboard/**`
- `src/config/nav-config.ts`

## Existing Seed and Reset Inventory

| Area | Existing file | Current behavior | Reuse decision |
| --- | --- | --- | --- |
| Super admin | `scripts/seed-super-admin.js` | Creates or updates the bootstrap admin from environment variables. | Reuse. Wizard should call or wrap this behavior server-side. |
| System seed runner | `scripts/seed-system.ts` | Runs super admin, system organization, foundation seed, and PDF template reseed. | Reuse as foundation install orchestration baseline. |
| System organization | `src/db/seeds/system-organization.seed.ts` | Creates deterministic `ALLA Demo` organization and super-admin membership. | Reuse logic, but D.7 needs user-provided organization inputs instead of hardcoded demo values. |
| Foundation data | `src/db/seeds/foundation.seed.ts` | Idempotently seeds master options, document sequences, approval workflows/matrices, document templates, document libraries, notification templates, and report definitions per organization. | Reuse and split into callable services before wizard execution. |
| UAT users | `src/db/seeds/uat-users.seed.ts` | Seeds marketing, sales, manager, CEO, and admin UAT users with CRM role assignments. | Reuse for Demo/UAT mode only. Do not mix with production foundation seed. |
| CRM UAT data | `src/db/seeds/crm-uat.seed.ts` | Seeds customers, contacts, leads, opportunities, quotations, approval requests/actions, followups, project parties, and sequence bumps. | Reuse for Demo/UAT mode only. Needs transaction wrapper and import/report output. |
| UAT runner | `scripts/seed-uat.ts` | Runs UAT users then CRM UAT data. | Reuse as demo seed orchestration baseline. |
| Seed reset | `scripts/seed-reset.ts` | Guarded full database reset, migrate, system seed, UAT seed. | Extend rather than duplicate. D.7 needs narrower reset scopes. |
| DB reset | `scripts/db/reset-database.ts` | Guarded schema drop/recreate, blocked in production and unsafe targets. | Keep guard contract. D.7 reset engine must preserve explicit confirmation and production blocking. |

## Existing Setup UI

`src/features/setup/components/setup-wizard.tsx` already exists, but it is a client-only template onboarding helper. It generates `.env.local` values and points users to example dashboards.

It does not currently provide:

- dashboard administration route
- server readiness checks
- seed execution API
- CSV template generation
- CSV upload, preview, validation, or rollback
- organization/branch/product type initialization
- document sequence setup
- administrator creation through app-owned services
- verification report
- setup resume state

Reuse decision: treat it as historical UI prototype only. D.7 should build a dashboard-native Administration Setup Wizard using `PageContainer`, shadcn/ui primitives, server route handlers, and setup feature services.

## Seed Classification

### Required Foundation Seed

These are required for a production install to operate:

- users and initial super admin
- organizations
- memberships
- CRM role profiles
- CRM user role assignments for the first administrator
- master options in `ms_options`
- branch options in `ms_options` category `crm_branch`
- product type options in `ms_options` category `crm_product_type`
- currencies, units, statuses, priorities, lead channels, lost reasons, job titles, project party roles
- document sequences for customer, lead, opportunity, quotation, and approval-related numbering
- approval workflows
- approval steps
- approval matrices
- document templates and template versions
- document template mappings and table columns
- document libraries and library versions
- notification templates
- report definitions

### Optional Configuration Seed

These may be required by deployment policy but are not always required before first login:

- Sentry configuration
- email provider configuration
- storage provider configuration beyond local defaults
- PDF visual assets or organization-specific logos
- additional document libraries
- additional branch/team/warehouse abstractions once modeled as first-class domains
- price books, tax rates, and product/service catalogs, because current schema has only the generic `products` table and CRM quotation items use free-form item data plus master options

### Demo / UAT Seed

These are already represented by `uat-users.seed.ts` and `crm-uat.seed.ts`:

- Marketing user
- Sales users by product type
- Sales manager
- CEO/top manager
- CRM admin
- customers
- contacts
- leads
- opportunities
- quotations across approved, rejected, pending, returned, sent, cancelled, won/lost/no-quotation scenarios
- followups
- approval requests and actions
- quotation items, project parties, topics

### Generated Runtime Data

These should not be manually seeded except through controlled fixture generation:

- audit logs, except explicit UAT followup/audit fixture rows
- notification events, dispatches, deliveries
- approval requests and approval actions in production
- document artifacts for generated approved PDFs
- quotation approved snapshots
- sequence current numbers, except after deterministic demo data creation

### Runtime Only

These are produced by application behavior and should not be foundation seed inputs:

- active user sessions
- notification deliveries
- audit security-denial events
- generated PDFs and immutable approved artifacts
- uploaded binary attachment storage objects
- report export output files

## Dependency Graph

```text
Environment
  -> Database migration status
  -> Storage/PDF/email configuration checks
  -> Super admin user
    -> Organization
      -> Membership
        -> CRM role profiles
          -> CRM user role assignments
      -> Master options
        -> Branch scope options
        -> Product type options
        -> Currency/unit/status/priority/job title/project party options
      -> Document sequences
        -> Customer codes
        -> Lead codes
        -> Opportunity codes
        -> Quotation codes
      -> Approval workflows
        -> Approval steps
        -> Approval matrices
      -> Document templates
        -> Template versions
        -> Template mappings
        -> Table-column mappings
      -> Document libraries
        -> Library versions
        -> Storage provider objects
      -> Notification templates
      -> Report definitions

Demo/UAT:
Organization foundation
  -> UAT users
    -> UAT memberships
    -> UAT CRM role assignments
  -> Customers
    -> Customer owner history
    -> Contacts
      -> Contact sharing, optional
    -> Leads
      -> Lead followup audit rows
      -> Opportunities
        -> Opportunity project parties
        -> Opportunity followups
        -> Quotations
          -> Quotation items
          -> Quotation project parties
          -> Quotation topics
          -> Quotation topic items
          -> Quotation followups
          -> Approval requests
            -> Approval actions
          -> Document sequence bumps
```

## Recommended Seed Order

1. Validate environment: `AUTH_SECRET`, `DATABASE_URL`, storage, upload directory, PDF template assets, email settings.
2. Validate migrations are applied.
3. Create first system administrator.
4. Create organization from wizard input.
5. Create administrator membership in the organization.
6. Seed CRM role profiles for the organization.
7. Assign CRM administrator role assignment to first administrator.
8. Seed master options, including branch and product type options.
9. Seed document sequences using organization, branch, product type, document type, and period scope.
10. Seed approval workflows and steps.
11. Seed approval matrices.
12. Seed document templates, versions, mappings, and table columns.
13. Seed document libraries through the storage provider.
14. Seed notification templates.
15. Seed report definitions.
16. Optionally import CSV master/business data.
17. Optionally run Demo/UAT seed.
18. Run verification checks and persist setup summary/report.

## Circular Dependency Check

No hard circular dependency was found in the existing seed flow.

Important dependency edges:

- Foundation seed requires at least one organization and `created_by` user.
- Document sequence seed requires branch/product type options from master options.
- UAT user role assignments require role profiles and branch/product type options.
- CRM UAT data requires UAT users, master options, branches, approval workflow, customers, contacts, leads, opportunities, and quotations in order.
- Approval actions require approval requests.
- Document library seed writes storage objects and therefore depends on storage provider readiness.

Potential soft cycle to avoid:

- First administrator creation needs permissions/role assignment, but role profiles are organization-scoped and need an organization. Resolve by creating user, organization, membership, then role profiles, then role assignment.

## Existing Coverage Matrix

| Requirement from Task D.7 | Current coverage | Gap |
| --- | --- | --- |
| Foundation seed | Strong script coverage in `foundation.seed.ts`. | Not exposed as service/API/wizard step. |
| Roles and permissions | `src/lib/auth/rbac.ts`, role profiles, assignments. | Wizard needs first-admin role assignment flow. |
| Master options | Strong coverage through `ms_options`. | CSV template/import for governed options missing. |
| Branch scope | Implemented as `ms_options` category `crm_branch`. | Wizard asks branch/department/team/warehouse, but only branch is modeled. Department/team/warehouse need scope decision. |
| Product type scope | Implemented as `ms_options` category `crm_product_type`. | Wizard needs product-type-aware sequence setup UI. |
| Document sequence | Strong foundation and APIs exist. | Wizard orchestration and verification missing. |
| Approval workflow | Strong foundation and settings APIs exist. | Wizard initialization/verification missing. |
| Storage | Foundation exists. | Readiness check and seed report integration missing. |
| PDF configuration | Foundation and audit docs exist. | Setup verification should call template inventory/mapping checks. |
| Report foundation | Existing definitions and services. | Setup should verify report definitions seeded. |
| Demo/UAT seed | Strong script coverage. | Needs deterministic report, transaction boundary, and wizard separation from production seed. |
| CSV templates | Not present. | Need `/setup/templates/*.csv` generator or checked-in templates. |
| Generic CSV import engine | Not present. | Need reusable setup/import foundation. |
| Setup Wizard route | Prototype component only. | Need dashboard admin page, route handlers, state persistence. |
| Verification engine | Not present as setup feature. | Need checks for login, permissions, org, branch, sequences, approval, storage, PDF, email. |
| Reset/reseed engine | Full reset exists. | Need scoped reset: foundation, organization, demo, business data. |

## Missing or Ambiguous Seed Data

- `branches.csv` can map to `ms_options` today, not a first-class branch table.
- `departments.csv`, `teams.csv`, and `warehouses.csv` have no obvious first-class schema in the reviewed model.
- `roles.csv` and `permissions.csv` should map to CRM role profiles and static permission definitions; permissions are code-defined in `src/lib/auth/rbac.ts`, not a database table.
- `products.csv`, `services.csv`, `price-books.csv`, `tax-rates.csv`, and `sites.csv` are not fully represented as CRM-owned first-class schemas. Current quotation item/product behavior does not equal a production price book.
- Attachments have metadata tables, but upload/storage transport is not a generic CSV-importable business seed.
- Email configuration appears environment/provider-driven; no dedicated setup table was identified.
- There is no setup state table for resume setup or setup summary persistence.

## Recommended Architecture for Next Phase

Create a setup feature that wraps existing foundations instead of duplicating them:

```text
src/features/setup/
  api/
    types.ts
    service.ts
    queries.ts
    mutations.ts
  server/
    readiness.service.ts
    seed.service.ts
    csv-template.service.ts
    csv-import.service.ts
    verification.service.ts
    reset.service.ts
  components/
    setup-wizard.tsx
    import-preview-table.tsx
    verification-summary.tsx
```

Route handlers should live under:

```text
src/app/api/setup/readiness/route.ts
src/app/api/setup/foundation/route.ts
src/app/api/setup/templates/route.ts
src/app/api/setup/import/preview/route.ts
src/app/api/setup/import/commit/route.ts
src/app/api/setup/verify/route.ts
src/app/api/setup/reset/route.ts
```

Dashboard page:

```text
src/app/dashboard/administration/setup/page.tsx
```

Key rules for implementation:

- service layer owns business logic
- route handlers remain thin
- seed execution must be transaction-aware where database writes happen
- storage writes need compensation/reporting because they cannot participate in the DB transaction
- CSV import must preview and validate before commit
- reset operations must preserve the existing explicit confirmation and production-safety guard
- CRM authorization must use existing resolved access helpers, not raw role branching
- audit setup mutations using the audit foundation once setup APIs exist

## CSV Template Scope Recommendation

Start with templates that map to existing schema and foundations:

- `organizations.csv`
- `users.csv`
- `memberships.csv`
- `crm-role-assignments.csv`
- `master-options.csv`
- `branches.csv` as a typed `master-options` template for `crm_branch`
- `product-types.csv` as a typed `master-options` template for `crm_product_type`
- `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`

Defer or mark as unsupported until schema is clarified:

- `departments.csv`
- `teams.csv`
- `warehouses.csv`
- `sites.csv`
- `services.csv`
- `price-books.csv`
- `tax-rates.csv`

## Verification Checks Needed

- environment variable presence and secrecy checks
- database connectivity
- migration table/status check
- storage provider write/read/delete smoke test
- upload directory readiness for local provider
- PDF template inventory and mapping coverage
- email provider configuration and optional dry-run
- first admin login readiness
- active organization on first admin
- membership and CRM role assignment resolution
- branch and product type scope resolution
- document sequence preview for customer, lead, opportunity, quotation
- approval workflow and matrix resolution for quotation
- report definition availability
- notification template availability

## Implementation Boundary

No code implementation was started in this pass because Task D.7 requires the audit and dependency report first. The safest next implementation slice is:

1. Extract current seed script logic into setup-callable server services without changing behavior.
2. Add setup readiness and verification read-only APIs.
3. Add checked-in CSV templates for entities already represented in schema.
4. Build CSV preview validation before commit support.
5. Replace the existing prototype setup wizard with a dashboard-native wizard that calls the setup APIs.

## Notes

- `rtk` was requested by repository instructions, but it was not available in this shell session. Raw PowerShell commands were used for the audit.
- Existing seed scripts include Thai strings that appeared mojibake in terminal output. This audit did not modify those files.
