# ICOMAN Digital Membership and Identity Verification System

## Phase 1 architecture baseline

Repository inspection on 2026-09-19 found an empty workspace. There are no application files, Git metadata, dependency manifests, routes, models, migrations, authentication configuration, UI components, API definitions, or deployment files to inspect.

Consequently, no existing implementation can yet be reused. This document defines a proposed architecture that should be applied incrementally once the intended application repository is present or initialized. It does **not** authorize Phase 2 feature implementation.

## Existing architecture

| Area | Current finding |
| --- | --- |
| Framework / PHP version | Not present / not determinable |
| Frontend framework | Not present |
| Database | Not configured |
| Dependencies | No Composer or JavaScript manifest present |
| Routes / API | Not present |
| Models / migrations | Not present |
| Authentication | Not present |
| UI components | Not present |
| Deployment | Not present |

## Recommended system architecture

Use a Laravel modular monolith with a server-rendered administrative application and a versioned JSON API. Laravel is well suited to PHP membership workflows, queues, policies, notifications, storage, audit trails, and database migrations while keeping operational complexity low at this stage.

Recommended baseline:

| Concern | Recommendation |
| --- | --- |
| Backend | Laravel 12 on a supported PHP version (target PHP 8.3+) |
| Admin frontend | Laravel Livewire 3 + Blade + Tailwind CSS |
| Public verification | Blade/Livewire pages, backed by narrowly scoped public endpoints |
| Database | PostgreSQL 16+ (MySQL 8+ acceptable if organizational operations require it) |
| Cache, queues, sessions | Redis |
| Files | Private object storage compatible with Amazon S3; local disk only for development |
| Authentication | Laravel Fortify-compatible login, password reset, MFA; Sanctum for API tokens |
| Authorization | Laravel policies plus role/permission assignments and organizational scope |
| Background work | Laravel queues with Redis and Horizon |
| Observability | Structured application logs, health checks, error tracking, metrics, immutable audit records |

The application should remain a modular monolith. Separate deployment services only where infrastructure requires it: web application, queue workers, scheduler, database, Redis, and object storage.

## Application layers

Organize code by bounded domain rather than by generic technical folders alone:

1. **Presentation**: web routes, API routes, Livewire components, Blade views, request validation, resources.
2. **Application**: use-case actions/services that coordinate transactions and domain policies, such as `ApproveMembership` and `IssueIdCard`.
3. **Domain**: models, value objects, workflow states, events, authorization rules, and invariants.
4. **Infrastructure**: repositories only where justified, storage adapters, QR/barcode generation, printers, external mail/SMS providers, queues, and integrations.

Use database transactions for all approval, issuance, and bulk-import state changes. Dispatch side effects only after a successful commit.

## Database architecture

PostgreSQL should be the authoritative transactional datastore. Use Laravel migrations, foreign keys, check constraints, unique indexes, and soft deletion only where business retention requires it.

Core entities proposed for later phases:

- Organizational hierarchy: `regions`, `states`, `chapters` (if applicable), and scoped administrator assignments.
- Identity and access: `users`, roles, permissions, MFA/recovery metadata, API tokens.
- Membership: `members`, `membership_applications`, `membership_status_history`, `member_documents`, `membership_numbers` or a constrained membership-number field.
- Governance: `board_of_trustees`, appointments, terms, and supporting documents.
- ID cards: `id_card_requests`, `id_cards`, `id_card_print_jobs`, and issuance/revocation history.
- Verification: opaque verification tokens, lookup/rate-limit records, and verification events.
- Operations: `notifications`, `audit_logs`, `imports`, `import_rows`, and reports/export jobs.

Membership numbers must be unique, immutable after issuance except under an explicitly audited correction flow, and never derived from a mutable record ID. Public identifiers and QR payloads must be high-entropy opaque tokens; do not expose sequential primary keys or personal data in codes.

## Authentication architecture

Use separate authentication concerns for staff and public users:

- Staff authenticate with email/username and password, verified email, password-reset workflow, throttling, secure sessions, and MFA for elevated roles.
- Public verification is anonymous and does not create an authenticated session.
- External/API clients authenticate using short-lived Sanctum token abilities or OAuth2 only if third-party delegated access becomes necessary.

Require strong password hashing, secure cookies, CSRF protection for browser actions, session rotation on login, login throttling, and forced re-authentication for high-risk actions such as role changes, approvals, and card revocations.

## Authorization architecture

Implement roles and permissions with explicit organizational scope. Suggested roles are National Administrator, National Membership Officer, National ID Officer, Regional Administrator, State Administrator, Approval Officer, Print Officer, Auditor, and Read-only Reporter.

Authorization has two checks:

1. A capability permission, for example `members.approve` or `id-cards.print`.
2. A policy scope, ensuring the actor may act only on records in the actor's national, regional, or state jurisdiction.

National-only actions include global configuration, membership-number rules, national reports, role assignment, and Board of Trustees administration. Never rely on UI visibility as authorization; enforce policies in actions/controllers/API endpoints.

## Membership workflow

Proposed state flow:

`draft -> submitted -> under_review -> approved | rejected | returned_for_correction -> active`

Suspension, resignation, expiry (if applicable), and deactivation are separate auditable transitions from active status. Application submission validates required identity, organization, location, and supporting documents. Reviewers may request correction with a reason. Approval assigns a membership number once, logs the decision, and queues notifications. Only approved, active members may proceed to ID-card issuance.

## ID-card workflow

Proposed state flow:

`not_requested -> requested -> identity_review -> approved -> generated -> queued_for_print -> printed -> issued`

`rejected`, `revoked`, `lost`, `replaced`, and `expired` are terminal or exception states with linked reasons. Card generation should create an immutable card serial, QR verification token, barcode value, and print-ready artifact. Print operators may advance only approved cards. Issuance must record who handed over the card, when, and which card version was issued. Replacement revokes the prior card's verification status.

## Verification architecture

Expose a public verification page and API endpoint that accept one of: QR token, barcode/card serial, or membership number. The response must minimize personal data: verification status, member display name as policy permits, membership status, card status, issuing scope, and expiry where applicable.

QR codes should resolve to a canonical URL containing an opaque signed or random token. Barcode values should be non-guessable card identifiers where scanner compatibility permits. Membership-number lookups require strict rate limits, abuse monitoring, normalized input, and a generic response for unknown values. All verification attempts are logged without retaining unnecessary request data.

## API architecture

Provide API routes under `/api/v1`, returning JSON through Laravel API Resources and a consistent error schema. Protect staff endpoints with token abilities and policy checks. Keep public verification endpoints separate and read-only. Use Form Requests for validation, pagination for collections, idempotency keys for import/issue operations, OpenAPI documentation, per-client rate limits, and API versioning from the first release.

Do not expose Eloquent models directly. API actions must invoke the same application-layer use cases as the web interface.

## File storage architecture

Store member documents, profile photographs, generated card assets, and report exports in private object storage. Database records store object key, content type, byte size, checksum, uploader, document classification, and retention metadata; never store raw files in database columns.

Use temporary signed downloads for staff and explicitly authorized viewers. Malware scanning, file-type allowlists, size limits, image transformation, and storage lifecycle/retention policies are required before production. Public verification must not provide direct document access.

## Queue architecture

Run Redis-backed queues with named queues: `default`, `notifications`, `imports`, `cards`, `reports`, and `security`. Use Horizon to monitor throughput, failures, retries, and runtime. Jobs must be idempotent, bounded by timeouts, retry-safe, and dispatched after transactions commit. Failed jobs require alerting and a controlled replay procedure.

The scheduler should trigger periodic expiry reviews, notification delivery, report cleanup, import cleanup, audit archival/export, and health tasks.

## Notification architecture

Use Laravel Notifications with database notifications as the durable in-app record and queued email/SMS channels. Define templated, localized messages for application submission, correction requests, approvals/rejections, ID-card status, printing/issuance, replacement/revocation, and security events.

Delivery preferences, consent, provider response IDs, delivery status, retry history, and opt-out handling must be retained. Keep templates free of sensitive data and link recipients to authenticated pages where detailed information is needed.

## Audit architecture

Create an append-only audit log for all security-sensitive and business-critical events: authentication, role changes, configuration changes, member edits, status transitions, document access, import decisions, card lifecycle events, print operations, verification abuse signals, and exports.

Each audit event should capture actor, action, subject type/identifier, organization scope, timestamp, request/correlation ID, source IP/user agent as permitted by policy, before/after summaries with sensitive fields redacted, and reason where required. Prevent ordinary application roles from editing or deleting audit records. Define retention and access policies with legal counsel.

## Deployment architecture

Deploy a single Laravel release artifact to production with separate process roles:

- HTTPS web instances behind a reverse proxy/load balancer.
- Queue worker/Horizon instances.
- Scheduler instance (one active scheduler).
- Managed PostgreSQL with automated backups and tested restore procedures.
- Managed Redis and S3-compatible private object storage.

Use environment-based configuration and a secrets manager; never commit `.env` files or credentials. CI should run static analysis, tests, dependency/security checks, migration checks, and build frontend assets. Release steps should use maintenance-safe migrations, cache warming, health checks, rollback guidance, centralized logs, uptime alerts, backup monitoring, and documented disaster recovery targets.

## Phased implementation roadmap

### Phase 1 — Architecture and repository baseline (current)

Document the architecture, confirm the actual codebase and hosting constraints, select supported PHP/Laravel versions, establish data classification/retention requirements, and approve the domain model. No major feature implementation.

### Phase 2 — Foundation and security

Initialize or align the Laravel application, environment configuration, database/Redis/storage, authentication, MFA for privileged roles, roles/permissions/scopes, audit framework, base layouts, CI, quality gates, health checks, and deployment skeleton.

### Phase 3 — Organization and membership

Implement regions/states/chapter scope, member registration, document uploads, validation, review queues, approval/correction/rejection workflows, membership-number allocation, staff dashboards, and notifications.

### Phase 4 — ID cards and public verification

Implement card requests/approvals, photo and document review, card serials, QR/barcode generation, print artifacts and print queues, issuance/replacement/revocation, plus secure public verification.

### Phase 5 — Operations and integrations

Implement bulk imports with preview/validation/error export, reporting/export jobs, Board of Trustees management, notification-provider integrations, documented `/api/v1`, and operator workflows.

### Phase 6 — Production readiness

Perform performance and security testing, threat modeling, access review, backup/restore drills, monitoring/alerting validation, data migration rehearsal, user acceptance testing, staff training, deployment, and post-launch support.

## Files to modify after the repository exists

Exact filenames cannot be identified until an application repository is supplied. For a conventional Laravel baseline, expect to modify:

- `composer.json`, `package.json`, `.env.example`, and deployment environment templates.
- `config/auth.php`, `config/filesystems.php`, `config/queue.php`, `config/services.php`, `config/permissions.php` (if used), and `bootstrap/app.php`.
- `routes/web.php`, `routes/api.php`, `routes/console.php`.
- Application providers, middleware registration, base layouts, navigation, and CI/deployment manifests.

## Files and directories to create in later phases

- `app/Domain/Membership/`, `app/Domain/Identity/`, `app/Domain/Organization/`, `app/Domain/Governance/`, `app/Domain/Verification/`, and `app/Domain/Audit/`.
- `app/Actions/`, `app/Policies/`, `app/Jobs/`, `app/Notifications/`, `app/Http/Requests/`, `app/Http/Resources/`, and `app/Livewire/`.
- Database migrations, factories, seeders, and feature/unit tests for each domain.
- `docs/API.md`, `docs/SECURITY.md`, `docs/OPERATIONS.md`, `docs/DATA_RETENTION.md`, and an OpenAPI specification.
- Container/deployment configuration, CI workflows, queue/scheduler process definitions, monitoring dashboards, and incident/runbook documentation.

## Reuse assessment

No reusable code or configuration was present in the inspected workspace. Once the actual repository is supplied, re-evaluate existing authentication, domain models, migrations, design system, routes, API conventions, tests, and deployment assets before adding parallel mechanisms.

## Risks and dependencies

Principal risks are absence of the intended codebase; unclear state/regional governance and approval authority; personal-data protection and retention obligations; identity-document fraud; membership-number/card replacement rules; printer/card-stock vendor constraints; SMS/email provider reliability and cost; public lookup abuse; import data quality; operational staff training; and untested backups.

Key dependencies are approved identity/document requirements, organization hierarchy and role matrix, legal/privacy policy, member-number format, card layout and printer integration, hosting provider, domain/DNS/TLS, PostgreSQL/Redis/object storage, email/SMS vendors, and a product owner empowered to resolve workflow policy decisions.

## Recommended implementation order

1. Obtain or initialize the actual repository and confirm technology constraints.
2. Approve this architecture, role/scope matrix, data model, retention policy, and workflow states.
3. Implement foundation, authentication, authorization, audit logging, and deployment/CI.
4. Implement organization hierarchy and membership lifecycle.
5. Implement ID-card lifecycle and verification.
6. Implement imports, reports, governance, notifications, and API.
7. Complete security, performance, backup/restore, and acceptance validation before launch.

**Phase 2 must not begin until the architecture, scope rules, and workflow decisions above are reviewed and approved.**
