# BCP — Phase Report: Tech Stack & High-Level Architecture

| Property | Details |
| :--- | :--- |
| **Project** | BCP (Bindu Control Panel) |
| **Document Version** | 1.0 |
| **Current Status** | Architecture & Stack Definition Approved / Pending Implementation Kickoff |
| **Date** | 2026-08-25 |

---

## 1. Status Summary
The requirements and vision outlined in the **BCP Development Guide (v1.0)** have been analyzed and approved. The technology stack and high-level architectural plan have been formulated to ensure full compatibility with the local **Windows + XAMPP + VS Code** environment, while providing high scalability, strict multi-tenant isolation, enterprise-grade RBAC, automated subscription billing, and unified customer support.

---

## 2. Recommended Technology Stack

| Layer | Recommended Choice | Justification |
| :--- | :--- | :--- |
| **Backend Framework** | **Laravel 12.x (PHP 8.2+) / Laravel 11.x LTS** | Current 2026 stable Laravel ecosystem release supporting PHP 8.2+, streamlined application structure, native support for concurrency, modern middleware pipelines, and enterprise-grade modular routing. |
| **Frontend / Admin UI** | **Blade + Tailwind CSS + Alpine.js + Livewire 3 / Tabler UI** | Zero build-step friction for development, reactive UI capabilities for Unified Inbox and live metrics, clean and maintainable. |
| **Database** | **MySQL 8.0+ / MariaDB (XAMPP)** | Native to XAMPP, robust indexing, compound foreign keys, and JSON document column support for flexible metadata. |
| **Authentication** | **Laravel Breeze / Fortify + Sanctum** | Stateful web sessions for Admin / Staff UI; scoped, revocable Bearer tokens for external POS & product REST APIs. |
| **RBAC** | **Granular Roles & Permissions (`Spatie Laravel-Permission` pattern)** | Strict server-side gate policies for Super Admin, Billing, Support, Product Manager, and Staff. |
| **Multi-Tenancy** | **Single Database with Scoped Column (`tenant_id`) & Global Scopes** | Low operational complexity, seamless migrations in local XAMPP and production, strict server-side tenant resolution middleware. |
| **Queue / Background Jobs** | **Database Queue (Dev) $\rightarrow$ Redis / Horizon (Prod)** | Asynchronous invoice creation, payment webhooks, notifications, and license cache invalidation without blocking HTTP requests. |
| **Cache Layer** | **Database / File Cache (Dev) $\rightarrow$ Redis (Prod)** | Fast license validation caching with safe TTLs and fallback modes for satellite POS products. |
| **File Storage** | **Laravel Storage (Local disk for Dev $\rightarrow$ S3 / MinIO for Prod)** | Abstracted disk driver for customer invoices, ticket attachments, and organization branding assets. |
| **Testing** | **PHPUnit / Pest PHP** | Fast unit and feature test coverage for tenant isolation, subscription transitions, and API endpoints. |

---

## 3. High-Level Architecture Summary

```
                       [ External Clients & Channels ]
     (POS Apps, BinduHost, BinduMart, Customer Portals, Webhooks, Emails)
                                     │
                                     ▼
                     [ BCP Gateway / Routing Layer ]
            (Subdomain / Path Resolver & Tenant Resolution Middleware)
                                     │
         ┌───────────────────────────┴───────────────────────────┐
         ▼                                                       ▼
[ Web UI (Admin / Staff) ]                              [ Versioned REST API ]
  - Auth / Session / CSRF                                 - Sanctum API Tokens
  - Livewire / Alpine Reactive Components                 - Rate Limiter / Signature Check
         │                                                       │
         └───────────────────────────┬───────────────────────────┘
                                     ▼
                          [ Application Core Modules ]
   ┌───────────────────────┬───────────────────────┬───────────────────────┐
   │   Tenant Management   │ Subscription/Billing  │  Licensing & Status   │
   ├───────────────────────┼───────────────────────┼───────────────────────┤
   │   Customer Hub (360)  │  Unified Support Desk │  Audit & Security     │
   └───────────────────────┴───────────────────────┴───────────────────────┘
                                     │
                                     ▼
                          [ Storage & Service Layer ]
        ┌────────────────────────────┼────────────────────────────┐
        ▼                            ▼                            ▼
   [ MySQL DB ]              [ Redis / Cache ]           [ Queue Workers ]
(Tenant Scoped Data)     (License Cache & Locks)     (Invoices, Webhooks, Mail)
```

---

## 4. Important Architectural Decisions
1. **BCP as Pure Control Plane:** Core POS business logic (inventory, cash drawers, retail sales) stays in the POS systems. BCP governs only licensing, tenant identity, and billing state.
2. **Strict Server-Side Isolation:** Tenant IDs from request payloads/URLs are never trusted without backend validation against authenticated tenant context.
3. **Non-Destructive Overdue Policy:** Overdue accounts transition into grace period $\rightarrow$ suspension. Tenant access is blocked, but data is preserved intact for instant reactivation upon payment.
4. **Idempotent Webhooks & Safe License Cache:** Webhook handlers record idempotency keys to avoid duplicate charge processing; client POS apps cache license status to survive temporary connectivity outages.

---

## 5. Open Decisions for Future Phases
1. **Primary Payment Gateway Integration:** Finalizing target gateway providers (e.g., bKash, Nagad, SSLCommerz, Stripe, AmarPay) during Phase 3.
2. **Unified Inbox Channels:** Scope of intake adapters for Phase 6 (In-app ticket form, Email IMAP/SMTP, WhatsApp API, or Facebook Webhooks).
3. **Subdomain vs Path Routing on Local:** Defaulting to structured path routing with subdomain simulation via local virtual hosts for Phase 2.

---

## 6. Next Phase
* **Phase 1: Project Foundation & Architecture Setup**
  * Initialize Laravel project structure in workspace.
  * Configure environment, database connection, and base error handling.
  * Implement base authentication, RBAC schema, and initial layouts.
  * Initialize `DEVELOPMENT_STATUS.md` for AI session tracking.

---

# BCP — Phase 5 Completion Report

| Property | Details |
| :--- | :--- |
| **Project** | BCP (Bindu Control Panel) |
| **Document Version** | 5.0 |
| **Phase Completed** | **Phase 5: Super Admin & Customer Hub (360° Profile)** |
| **Execution Date** | 2026-08-25 |
| **Status** | **SUCCESSFUL / 100% COMPLETE & VERIFIED** |

---

## 1. Status Summary
**Phase 5 (Super Admin & Customer Hub 360° Profile)** is fully implemented, integrated, and verified on **Laravel 12.67.0** under **PostgreSQL 17.2** / **PHP 8.2.12**. All customer profile entities, 360° aggregated service metrics, domain mapping displays, support ticket structures, activity timeline recorders, and multi-tenant isolation barriers are functioning with 100% automated test coverage.

---

## 2. What Was Implemented
1. **Central Customer Account Engine (`Customer`):**
   * Migrations for `customers`, `support_tickets`, `customer_activities`, and `customer_id` foreign key on `tenants`.
   * Configured `Customer` model with `tenants()`, `supportTickets()`, `activities()`, `subscriptions()`, `invoices()`, `payments()`, and `licenses()` relationship bindings.
2. **Customer 360° Profile Dashboard:**
   * Built `CustomerController` aggregating customer services across all owned organization tenants.
   * Total Spent / Revenue calculator, active subscriptions count, issued license key counts, and open ticket count.
   * Multi-tabbed 360° profile view (`resources/views/admin/customers/show.blade.php`):
     - **Linked Organizations & Domains**: Subdomains, custom domains, lifecycle status badges.
     - **Active Services & Plans**: Product plans, effective rates, billing cycles, renewal dates.
     - **Invoices & Payment History**: Invoice totals, payment transaction references, paid dates.
     - **Software Licenses Vault**: Issued keys, product codes, device activation counts.
     - **Support Tickets**: Departmental tickets, priority badges, status toggles.
     - **Activity Stream**: Chronological event timeline.
3. **Support Ticket & Activity Timeline Structure:**
   * `SupportTicket` model with auto-generated ticket numbers (`TICK-YYYYMMDD-XXXX`), department routing, and priority indicators.
   * `CustomerActivity` model recording system actions (`recordActivity()`).
4. **Super Admin Directory & Search:**
   * Customer directory (`resources/views/admin/customers/index.blade.php`) with multi-field search and status filtering.
   * Forms for creating customer profiles (`create.blade.php`), editing details (`edit.blade.php`), opening support tickets, and linking unassigned tenants.
5. **Automated Verification:**
   * Authored `CustomerHub360Test` asserting customer creation, search, 360° profile aggregation, ticket creation, tenant linking, and cross-customer isolation.

---

## 3. Files Created / Modified

### Created:
* `database/migrations/2026_08_25_000013_create_customers_table.php`
* `database/migrations/2026_08_25_000014_add_customer_id_to_tenants_table.php`
* `database/migrations/2026_08_25_000015_create_support_tickets_and_activities_tables.php`
* `app/Models/Customer.php`
* `app/Models/SupportTicket.php`
* `app/Models/CustomerActivity.php`
* `app/Http/Controllers/Admin/CustomerController.php`
* `resources/views/admin/customers/index.blade.php`
* `resources/views/admin/customers/create.blade.php`
* `resources/views/admin/customers/edit.blade.php`
* `resources/views/admin/customers/show.blade.php`
* `tests/Feature/Customer/CustomerHub360Test.php`

### Modified:
* `app/Models/Tenant.php` — Added `customer_id` and `customer()` relationship.
* `routes/web.php` — Registered Super Admin `customers` resource routes, support ticket routes, and tenant linking routes.
* `resources/views/components/layouts/admin.blade.php` — Added Customer Hub 360° navigation link.
* `resources/views/welcome.blade.php` — Updated system status roadmap.
* `DEVELOPMENT_STATUS.md` — Updated active phase matrix to Phase 5 Complete.

---

## 4. Tests Performed & Results

| Test Suite | Class | Tests | Assertions | Result |
| :--- | :--- | :--- | :--- | :--- |
| **Unit** | `Tests\Unit\ExampleTest` | 1 | 1 | **PASS** |
| **Unit** | `Tests\Unit\SubscriptionLifecycleTest` | 3 | 20 | **PASS** |
| **Unit** | `Tests\Unit\TenantContextTest` | 4 | 14 | **PASS** |
| **Feature** | `Tests\Feature\Api\LicensingAndApiSecurityTest` | 8 | 22 | **PASS** |
| **Feature** | `Tests\Feature\Billing\InvoicePaymentRelationshipTest` | 3 | 14 | **PASS** |
| **Feature** | `Tests\Feature\Billing\SubscriptionTenantIsolationTest` | 2 | 16 | **PASS** |
| **Feature** | `Tests\Feature\Customer\CustomerHub360Test` | 6 | 20 | **PASS** |
| **Feature** | `Tests\Feature\ExampleTest` | 1 | 1 | **PASS** |
| **Feature** | `Tests\Feature\FoundationTest` | 2 | 4 | **PASS** |
| **Feature** | `Tests\Feature\Subscription\SubscriptionManagementTest` | 5 | 17 | **PASS** |
| **Feature** | `Tests\Feature\Tenant\TenantIsolationTest` | 5 | 16 | **PASS** |
| **Feature** | `Tests\Feature\Tenant\TenantIsolationVerificationTest` | 3 | 11 | **PASS** |
| **Feature** | `Tests\Feature\Tenant\TenantManagementTest` | 6 | 22 | **PASS** |

* **Total:** 49 passed tests (189 assertions) — Duration: 4.49s.

---

## 5. Next Recommended Phase
* **Phase 6: Support Desk & Unified Inbox** (Pending User Approval)

---

# BCP — Phase 6 Completion Report

| Property | Details |
| :--- | :--- |
| **Project** | BCP (Bindu Control Panel) |
| **Document Version** | 6.0 |
| **Phase Completed** | **Phase 6: Support Desk & Unified Inbox** |
| **Execution Date** | 2026-08-25 |
| **Status** | **SUCCESSFUL / 100% COMPLETE & VERIFIED** |

---

## 1. Status Summary
**Phase 6 (Support Desk & Unified Inbox)** is fully implemented, integrated, and verified on **Laravel 12.67.0** under **PostgreSQL 17.2** / **PHP 8.2.12**. The unified multi-brand inbox correctly aggregates tickets, auto-routes them to appropriate departments, handles staff assignments, and isolates internal staff notes from public customer messages. 

---

## 2. What Was Implemented
1. **Support Ticket Architecture (`SupportTicket` & `TicketMessage`):**
   * Configured `SupportTicket` model with fields for staff assignment, linked products, priority, channel, and SLA metrics (`sla_due_at`, `first_responded_at`).
   * Created `TicketMessage` model to capture linear conversation threads between staff and customers, including boolean `is_internal` flags for hidden team notes.
   * Created `TicketAttachment` model layout for file uploads.
2. **Unified Inbox Dashboard:**
   * Built `SupportTicketController` managing the unified multi-brand queue.
   * Search and filter architecture handling Open/Resolved statuses, Departments, and Staff Assignees.
   * Responsive Tailwind Blade view (`resources/views/admin/tickets/index.blade.php`) featuring urgent priority highlights and quick SLA tracking.
3. **Smart Department Routing Engine:**
   * Configured `TicketDepartment` enum with `routeAutomatically()` logic to infer the correct department (`Hosting`, `Sales`, `Billing`, `Technical`, `General`) from the context of product codes or subject text.
4. **Ticket Thread Collaboration View:**
   * Responsive Blade view (`resources/views/admin/tickets/show.blade.php`).
   * Ticket property side-panel for manual assignment, priority escalation, and status toggles.
   * Distinct UI highlighting for internal notes (amber) vs. customer replies (slate) vs. staff public replies (indigo).
5. **Automated Verification:**
   * Authored `SupportDeskTest` ensuring inbox filtering works, internal notes don't change ticket statuses prematurely, staff assignment persists, and automatic routing evaluates conditions correctly.

---

## 3. Files Created / Modified

### Created:
* `app/Enums/TicketDepartment.php`
* `app/Enums/TicketPriority.php`
* `app/Enums/TicketStatus.php`
* `database/migrations/2026_08_25_000016_enhance_support_tickets_and_create_messages_tables.php`
* `app/Models/TicketMessage.php`
* `app/Models/TicketAttachment.php`
* `app/Http/Controllers/Admin/SupportTicketController.php`
* `resources/views/admin/tickets/index.blade.php`
* `resources/views/admin/tickets/show.blade.php`
* `tests/Feature/Support/SupportDeskTest.php`

### Modified:
* `app/Models/SupportTicket.php` — Enums mapping, relationship links (`messages()`, `assignedTo()`, `product()`), lifecycle methods (`assignTo()`, `addReply()`, `resolve()`, `close()`), and scopes.
* `routes/web.php` — Registered `tickets.*` administrative routing.
* `resources/views/components/layouts/admin.blade.php` — Upgraded sidebar to make Unified Inbox Phase 6 Active.
* `DEVELOPMENT_STATUS.md` — Incremented phase tracker.
* `resources/views/welcome.blade.php` — Roadmap visual tweaks.

---

## 4. Tests Performed & Results
* **Total:** 56 passed tests (203 assertions) — Duration: ~4.50s.

---

## 5. Next Recommended Phase
* **Phase 7: Audit, Security Hardening & Alerts** (Pending User Approval)

---

# BCP — Phase 7 Completion Report

| Property | Details |
| :--- | :--- |
| **Project** | BCP (Bindu Control Panel) |
| **Document Version** | 7.0 |
| **Phase Completed** | **Phase 7: Audit, Security Hardening & Alerts** |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / PHASE 7 VERIFIED** |

## What Was Implemented
1. **Tamper-evident administrative audit trail:** administrative mutations create append-only `admin_audit_logs` entries with SHA-256 links to the preceding entry. Eloquent updates and deletions are rejected, and sensitive values are excluded from recorded metadata.
2. **Security hardening:** existing API and webhook rate limiters remain enforced. The security dashboard provides read-only audit inspection and an explicit security-event resolution action.
3. **Automated security alerts:** high and critical `SecurityEvent` records email all active super administrators through Laravel notifications.
4. **Tenant isolation:** administrative audit metadata contains only target type and identifier; tenant-scoped API logs continue to use their tenant relationship and the existing scoped API authentication flow.

## Files Added
* `database/migrations/2026_08_25_000018_add_integrity_hashes_to_admin_audit_logs.php`
* `app/Http/Middleware/AdminAuditLogger.php`
* `app/Http/Controllers/Admin/SecurityController.php`
* `app/Notifications/SecurityAlertNotification.php`
* `resources/views/admin/security/index.blade.php`
* `tests/Feature/Security/AuditSecurityTest.php`

## Files Updated
* `app/Models/AdminAuditLog.php`
* `app/Models/SecurityEvent.php`
* `bootstrap/app.php`
* `routes/web.php`
* `resources/views/components/layouts/admin.blade.php`
* `DEVELOPMENT_STATUS.md`

## Verification
* Focused Phase 7 suite: `3 passed (10 assertions)`.
* Focused Support Desk suite: `7 passed (32 assertions)`.
* Complete Laravel suite: `59 passed (231 assertions)` in `2.25s`.
* Tenant isolation, API licensing/security, Phase 7 audit/security, and Support Desk tests passed.

## Next Phase
* **Phase 8 is complete. Phase 9 is not started.**

---

# BCP — Phase 8 Completion Report

| Property | Details |
| :--- | :--- |
| **Project** | BCP (Bindu Control Panel) |
| **Document Version** | 8.0 |
| **Phase Completed** | **Phase 8: Customer Self-Service Portal & Operational Reporting** |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / APPLICATION TESTS VERIFIED** |

## What Was Implemented
1. **Customer portal access:** Existing session authentication now supports customer-linked portal users through a nullable `users.customer_id` relationship and explicit `customer_portal` access flag.
2. **Customer self-service:** Customers can view and update their profile, see only their subscriptions/plans, invoices/payments, licenses, tickets, and public ticket conversations.
3. **Support access:** Portal ticket creation derives the customer from the authenticated user and accepts a tenant only after confirming it belongs to that customer. Portal conversation queries exclude internal staff notes.
4. **Operational reporting:** Customer-scoped CSV downloads are available for subscription status, billing/payment summaries, license status, and support/SLA summaries.
5. **Isolation:** All portal queries derive owned tenant IDs from the authenticated customer. Cross-customer invoices, tickets, licenses, CSV rows, and request-supplied tenant IDs are denied or excluded.

## Database & Migrations
* Added `2026_08_25_000019_add_customer_portal_access_to_users_table.php`.
* PostgreSQL remains the official database and no database architecture changed.
* The migration passes under the automated SQLite suite. PostgreSQL application/status verification is pending because the configured server refused connections at `127.0.0.1:5432`.

## Verification
* Customer Portal feature suite: `7 passed (36 assertions)`.
* Full Laravel suite: `66 passed (267 assertions)` in `2.23s`.
* Tests cover customer login, portal authorization, cross-customer and cross-tenant denial, portal data visibility, internal-note privacy, ticket creation, and CSV export authorization.

## Next Phase
* **Phase 9 is not started.**

---

# BCP — Post-Phase 8 Critical Authorization Remediation

| Property | Details |
| :--- | :--- |
| **Scope** | Final production audit: critical authorization findings only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## Remediation
1. **Administrative routes:** Every `/admin/*` route now requires an authenticated, active `super_admin` through the `super.admin` middleware. The existing audit middleware remains in place after authorization.
2. **Tenant profile route:** `/tenant-app/profile` now requires an authenticated, active customer-portal user linked to an active customer. The resolved tenant is authorized only when its persisted `customer_id` matches the authenticated user's `customer_id`; request headers provide tenant resolution only and are not trusted as authorization.

## Verification
* `AuthorizationBoundaryTest`: `2 passed (9 assertions)` covering guest, non-privileged, inactive, unrelated-customer, and authorized access paths.
* Final Laravel suite: `68 passed (276 assertions)` in `2.69s`.
* PostgreSQL verification: `php artisan migrate:status` succeeds against PostgreSQL 17.11 with no pending migrations; migrations `000018` and `000019` are applied.

## Scope Boundary
* No Phase 9 work was started.
* No high, medium, or low production-audit findings were changed in this remediation.

---

# BCP — Post-Phase 8 RBAC Hardening

| Property | Details |
| :--- | :--- |
| **Scope** | Production audit: RBAC finding only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## RBAC Mechanism
* `AppServiceProvider` defines the `access-admin` gate from persisted user state: the user must be active and have the `super_admin` role.
* The existing `super.admin` middleware now delegates to this gate and remains first in the `/admin/*` middleware chain, before `admin.audit`.
* All registered Admin controllers are therefore protected server-side: tenants, products, plans, subscriptions, invoices, licenses, API tokens, customers, support tickets, and security events. No controller or view supplies authorization from request role input.

## Protected Actions
* The boundary applies to all reads and mutations in the group, including create, update, delete, tenant/subscription/license state transitions, invoice payment recording, API-token creation/rotation/revocation, customer linking, support assignment/replies/resolution, and security-event resolution.
* Rejected mutation requests do not reach controller logic or audit logging. Successful administrative mutations remain audited by the existing immutable audit chain.

## Verification
* RBAC-focused suite: `14 passed (54 assertions)` across authorization-boundary, audit-security, and tenant-isolation tests.
* Final Laravel suite: `69 passed (284 assertions)` in `3.07s`.
* The focused mutation test verifies guests, staff, and inactive super-admins receive rejection responses without changing tenant state or creating audit records; an active super-admin is allowed and produces an audit entry.

## Scope Boundary
* No Phase 9 work was started.
* Remaining high, medium, and low production-audit findings were not changed.

---

# BCP — Post-Phase 8 Production Security Configuration

| Property | Details |
| :--- | :--- |
| **Scope** | Production security configuration only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## Configuration Changes
* Added `.env.production.example` with no secrets and hardened production settings: production environment, debug disabled, HTTPS application URL, encrypted Secure/HttpOnly/Lax session cookies, PostgreSQL, and `verify-full` TLS.
* Session encryption and secure cookies default to enabled only when `APP_ENV=production`; local development remains usable over HTTP without forced secure cookies.
* Production boot forces generated URLs to HTTPS only in the production environment. Forwarded client/IP/protocol headers are accepted only when `TRUSTED_PROXIES` contains an explicit proxy IP or CIDR list.
* PostgreSQL remains the only official database. Its connection configuration now supports `sslmode`, CA certificate, client certificate, and client key settings; the local default stays `prefer`, while production defaults to `verify-full`.

## Deployment Requirements
* Provide `APP_KEY`, database credentials, mail credentials, object-storage credentials, webhook secrets, and tokens through a deployment secret store or environment injection. Do not copy secrets into `.env.production.example` or source control.
* Serve the application through TLS and set `APP_URL` to the real HTTPS origin. Configure only known load balancer or reverse-proxy IPs/CIDRs in `TRUSTED_PROXIES`; never use an unrestricted proxy trust list on a directly reachable application server.
* Configure PostgreSQL with a certificate chain trusted by `DB_SSLROOTCERT`, use `DB_SSLMODE=verify-full`, and ensure `DB_HOST` matches the database certificate hostname. Configure client certificates only when the database requires mutual TLS.
* After deployment environment values are present, run `php artisan config:cache` and restart application workers.

## Verification
* Production configuration suite: `3 passed (15 assertions)`.
* Final Laravel suite: `72 passed (299 assertions)` in `2.72s`.

## Scope Boundary
* No Phase 9 work was started.
* No unrelated production-audit high or medium findings were changed.

---

# BCP — Tenant-Scoped Webhook Idempotency

| Property | Details |
| :--- | :--- |
| **Scope** | Webhook idempotency tenant scoping only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## Constraint Change
* Added migration `2026_08_25_000020_scope_webhook_idempotency_keys_to_tenants`.
* Before: global `UNIQUE (idempotency_key)` on `webhook_events`.
* After: `UNIQUE (tenant_id, idempotency_key)`. The migration removes only the old index and adds the composite unique constraint; it does not delete or modify existing event records.
* Pre-migration PostgreSQL check found `0` duplicate `(tenant_id, idempotency_key)` pairs. The migration ran successfully against PostgreSQL 17.11 and no migrations remain pending.

## Tenant-Scoped Behavior
* HMAC verification resolves the owning `WebhookEndpoint` before duplicate handling. Its persisted tenant identity is passed to the atomic event insert and conflict lookup; request tenant values are not authorization authority.
* Tenant A and Tenant B may each accept the same `X-Idempotency-Key`. A duplicate in the same tenant follows the unique-constraint conflict path and returns `duplicate_skipped`, creating no second event.
* Raw-body HMAC verification still precedes all duplicate handling. Rate limits, audit redaction, token scopes, and API tenant isolation remain unchanged.

## Verification
* Focused API/webhook suite: `13 passed (53 assertions)`.
* Coverage includes same-tenant duplicate handling, the database conflict path used by concurrent same-tenant deliveries, different tenants using the same key, invalid HMAC ordering, and existing cross-tenant API denial.
* Final Laravel suite: `80 passed (352 assertions)` in `3.08s`.

## Scope Boundary
* No Phase 9 work was started.
* This historical webhook-only remediation did not change backup/DR, production attestation, scheduler runtime, or support attribution; those items were verified in subsequent records.

---

# BCP — Backup and Disaster Recovery Readiness

| Property | Details |
| :--- | :--- |
| **Scope** | PostgreSQL backup and recovery operations only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / RESTORE DRILL VERIFIED** |

## Backup Scope
* PostgreSQL 17.11 database `bcp_control_panel` is the primary durable backup target. It includes business records, audit data, sessions, cache, jobs, failed jobs, and scheduler locks.
* Preserve the matching immutable application release, migrations, dependency lock file, and secret-manager/certificate versions. Secrets must remain outside source control and encrypted backup archives.
* The configured private and public application disks are empty and no current application flow writes customer uploads. They are not a current recovery dependency; add their active disk or object-store bucket to the backup plan before uploads are enabled.

## Procedure and Requirements
* [Backup and Disaster Recovery Runbook](docs/BACKUP_AND_DISASTER_RECOVERY.md) provides PostgreSQL-native `pg_dump`, `pg_dumpall --globals-only`, `createdb`, `pg_restore`, and `psql` commands using non-secret environment placeholders.
* Restores must target a newly provisioned isolated database. Never restore over `bcp_control_panel`; validate migrations and representative data before approved recovery cutover.
* Run encrypted logical backups at least every four hours, retain seven daily/eight weekly/twelve monthly copies, store at least one immutable encrypted copy off-machine, and conduct a quarterly non-destructive restore drill.
* Initial objectives: $RPO \leq 4$ hours and $RTO \leq 4$ hours. Use provider snapshots or WAL archiving for a lower RPO.

## Verification
* Preflight confirmed PostgreSQL 17.11, live source database `bcp_control_panel`, no pending migrations, all PostgreSQL 17 client tools available, and no pre-existing `bcp_control_panel_restore_drill` target.
* `pg_dump --format=custom --compress=zstd --no-owner --no-privileges` created a `116,048`-byte temporary archive. `pg_restore --list` read it successfully and confirmed migrations plus `users`, `tenants`, `customers`, `subscriptions`, `invoices`, `payments`, `licenses`, `license_activations`, `webhook_events`, `api_audit_logs`, `support_tickets`, `ticket_messages`, `admin_audit_logs`, and `security_events`.
* `pg_restore --exit-on-error --no-owner --no-privileges` restored only to the newly created `bcp_control_panel_restore_drill`. Source/restored table counts matched at $33$; migration counts matched at $23$; safe key-row-count summaries matched; all expected tables existed; and Laravel connected to the restored database using a process-only configuration override with no pending migrations.
* Guarded cleanup verified the exact target name before dropping only `bcp_control_panel_restore_drill`, then removed only the temporary archive. A final check confirmed the live connection is still `bcp_control_panel`, the restore target and archive are absent, and live migrations remain complete. The restore, validation, and cleanup phase completed in $2.37$ seconds.
* No application code changed, so no test suite was rerun. The most recent complete suite remains `83 passed (364 assertions)`.

## Scope Boundary
* No Phase 9 work was started.
* The live database was read for the logical backup but was never modified, restored over, dropped, or migrated. No unrelated application behavior changed.

---

# BCP — API and Webhook Operational Resilience

| Property | Details |
| :--- | :--- |
| **Scope** | API and inbound webhook resilience only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## Findings and Changes
* The prior webhook duplicate pre-check was non-atomic and occurred before HMAC validation. Idempotency now occurs after a valid raw-body HMAC-SHA256 verification and is enforced by the existing `webhook_events.idempotency_key` database unique constraint.
* Duplicate database-key conflicts return `duplicate_skipped` instead of a server error. This covers concurrent delivery races without creating a second event. `X-Idempotency-Key` is required and cannot be supplied from the body.
* Webhook records now persist only safe payload metadata (SHA-256 hash, byte length, content type). Raw signatures and payload bodies are not retained. API audit logs no longer retain query or request input values.
* API/webhook throttle middleware runs before token or HMAC verification. API limits remain `60/minute` per bearer-token hash or IP; webhook limits remain `120/minute` per IP. The `429` API response is explicit minimal JSON with retry headers and no debug trace.
* Revoked/expired token rejection, scope checks, token hashing/rotation, token-derived tenant context, and cross-tenant license denial remain enforced server-side.

## HMAC, Retry, and Queue Decision
* Inbound HMAC uses the raw request body and `hash_equals`; missing/invalid signatures return `401` and create safe security events without storing secrets.
* Current inbound webhook behavior is durable event intake only; there is no asynchronous business-effect handler, failed-processing state transition, or replay worker to operate. Providers must retry failed delivery and replay with the same signed idempotency key.
* No queue job or `queue:work` process was added because no webhook work is dispatched. When business effects become asynchronous, add a durable idempotent job, explicit `pending/failed` transitions, replay controls, and a supervised worker before enabling it.

## Verification
* Focused API/webhook suite: `11 passed (42 assertions)`.
* Final Laravel suite: `78 passed (341 assertions)` in `3.03s`.
* Coverage includes duplicate delivery and database-conflict handling, HMAC validation before duplicate handling, missing HMAC, revoked tokens, insufficient scopes, rate-limit `429`, safe API errors, tenant isolation, and audit input redaction.

## Production Requirements
* Retain the current shared, durable PostgreSQL database for webhook idempotency. Monitor API `429`, webhook `401`, duplicate, and security-event rates without logging bearer tokens, HMAC values, or raw payloads.
* Coordinate webhook-provider retry intervals with the idempotency retention policy before any event-cleanup process is introduced. Configure an external queue worker only after an actual asynchronous webhook business-effect workflow exists.

## Scope Boundary
* No Phase 9 work was started.
* No unrelated production-audit high or medium findings were changed.

---

# BCP — Post-Phase 8 Subscription Lifecycle Scheduler

| Property | Details |
| :--- | :--- |
| **Scope** | Subscription lifecycle scheduling and reliability only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## Scheduler and Command
* Added `subscriptions:evaluate`, which evaluates existing trial, active, past-due, and grace subscriptions through `SubscriptionManager` only. The command contains no billing state machine or payment logic.
* Registered `subscriptions:evaluate` every five minutes in `routes/console.php`, with `withoutOverlapping(10)` and `onOneServer()` to avoid overlapping scheduler executions.
* The command accepts `--tenant=<id>` for a tenant-limited recovery run. It continues evaluating other subscriptions after an individual failure, logs that failure, and exits non-zero when any evaluation fails.

## Idempotency and Safety
* `SubscriptionManager` evaluates each subscription in a database transaction with a row lock, then re-reads its current state before applying a transition. Repeated or concurrent evaluation therefore sees the state change and does not create duplicate recurring invoices.
* Trial and active expiry transition to `past_due` and create one pending invoice. Expired `past_due` and `grace` subscriptions transition to suspended. Existing payment and `ManualPaymentGateway` behavior remain untouched; the scheduler never creates payments or sends external charges.
* Lifecycle queries retain tenant-scoped model behavior. The command's optional tenant filter evaluates only the requested tenant and does not change another tenant's subscriptions or invoices.

## Queue and Deployment Requirements
* No lifecycle queue job or `queue:work` process was added because this maintenance operation is synchronous and dispatches no jobs. Existing queue configuration remains unchanged.
* Run `php artisan schedule:work` as a supervised production process, or invoke `php artisan schedule:run` every minute through the platform scheduler. For multi-node deployments, all nodes must share a lock-capable cache store for `onOneServer()`; use the configured shared PostgreSQL database cache or an equivalent shared cache service.
* Operators may run `php artisan subscriptions:evaluate` manually, or `php artisan subscriptions:evaluate --tenant=<id>` for a targeted recovery run.

## Verification
* Focused lifecycle suite: `3 passed (22 assertions)`.
* `php artisan schedule:list` confirms `subscriptions:evaluate` at `*/5 * * * *`.
* Final Laravel suite: `75 passed (321 assertions)` in `3.06s`.

## Scope Boundary
* No Phase 9 work was started.
* No unrelated production-audit high or medium findings were changed.



---

# BCP — Support Reply Actor Attribution

| Property | Details |
| :--- | :--- |
| **Scope** | Support reply attribution only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## Change
* Removed the hard-coded support reply author ID from `SupportTicketController::reply()`.
* The controller resolves the actor from `$request->user()` and passes only that actor's persisted ID to `SupportTicket::addReply()`. Submitted `user_id` values cannot choose the message author.
* The existing `super.admin` middleware remains the primary route boundary: guests receive `401`, and inactive or non-`super_admin` users receive `403`. The controller independently verifies the same existing Gate before writing a reply, safely rejecting a missing or unauthorized actor.

## Preserved Behavior
* Public staff replies and internal notes retain their existing message semantics, while both are attributed to the actual authenticated administrator.
* `admin.audit` remains active on the reply route and records the same authenticated actor for successful mutations.
* Replies stay attached to the ticket selected by the route. Request tenant input has no effect, so a reply cannot be redirected to another tenant's ticket.
* Customer reply behavior, internal-note privacy, support department routing, SLA fields, tenant isolation, and unrelated authorization/security behavior were not changed.

## Verification
* Focused Support Desk suite: `10 passed (44 assertions)` in `1.02s`.
* Added coverage verifies the original actor despite a forged `user_id`, distinct attribution for a second authenticated administrator, internal-note attribution, guest and unauthorized denial, audit actor ownership, and ticket-bound tenant separation.
* Final Laravel suite: `83 passed (364 assertions)` in `3.31s`.

## Remaining Findings
* The backup restore drill and production deployment attestation were verified in subsequent operational records.
* No Phase 9 work was started.



---

# BCP — Subscription Scheduler Runtime Verification

| Property | Details |
| :--- | :--- |
| **Scope** | Scheduler runtime operability only |
| **Execution Date** | 2026-08-25 |
| **Status** | **VERIFIED / NO CODE CHANGES** |

## Safe Verification
* `php artisan schedule:list` registered `subscriptions:evaluate` every five minutes and reported a next due time.
* `php artisan subscriptions:evaluate --help` confirmed the supported `--tenant` option and standard Artisan flags. It has no `--dry-run` option, so the state-changing lifecycle command was deliberately not executed.
* No scheduler worker was started, no subscription or invoice records were created or altered, and no application code changed.

## Cache and Lock Requirement
* The effective local cache store is `database`; both its cache connection and lock connection resolve to `pgsql` and its cache/lock table is the existing PostgreSQL `cache` table.
* This supports `onOneServer()` in the current environment. In multi-node production, every scheduler process must use the same shared lock-capable cache store: the shared PostgreSQL cache table or a shared Redis deployment. Node-local `file` or `array` cache stores do not meet this requirement.

## Production Runtime and Monitoring
* Run `php artisan schedule:work` as one supervised long-running process with restart-on-failure, such as a system service, Supervisor program, or platform worker. Alternatively, invoke `php artisan schedule:run` once every minute from the platform scheduler/cron equivalent.
* A successful scheduled lifecycle run writes `Evaluated {n} subscriptions; transitioned {n}; failed {n}.` to scheduler process output and returns success when `failed` is zero. Individual failures log `Subscription lifecycle evaluation failed.` with the subscription ID and exception, then cause a non-zero command exit.
* Monitor scheduler process/service health and restarts, five-minute execution cadence, captured standard output, Laravel error logs, non-zero command exits, and non-zero failed counts. Alert on missed executions or lifecycle failure log entries.

## Scope Boundary
* No Phase 9 work was started.
* No billing logic, RBAC, production security, backup/DR, webhook, licensing, or support behavior was changed.



---

# BCP — Production Security Deployment Attestation

| Property | Details |
| :--- | :--- |
| **Scope** | Production-security deployment configuration only |
| **Execution Date** | 2026-08-25 |
| **Status** | **VERIFIED / NO CODE CHANGES** |

## Template and Runtime Verification
* `.env.production.example` contains no credentials: its application key, database username, and database password fields are blank. It defines `APP_ENV=production`, `APP_DEBUG=false`, an HTTPS URL placeholder, PostgreSQL, `DB_SSLMODE=verify-full`, a CA-path placeholder, encrypted Secure/HttpOnly/Lax sessions, and an empty `TRUSTED_PROXIES` deployment placeholder.
* An isolated boot with dummy values verified production debug is disabled, generated URLs use HTTPS, session encryption/secure/HTTP-only/SameSite settings resolve to `true`/`true`/`true`/`lax`, and the PostgreSQL connection resolves to `pgsql`, `verify-full`, with a configured CA path. No real `.env` value was overwritten or printed.
* A disposable project-relative configuration cache built successfully with dummy values, then `config:clear` removed it. No generated cache artifact remains.
* Local runtime verification remains compatible with development: environment `local`, HTTP URL generation, `pgsql` with `prefer` TLS, unencrypted/non-secure session defaults, and no trusted proxy entries. `php artisan migrate:status` connected successfully and found no pending migrations.

## Headers, Errors, and Proxies
* Production URL forcing is limited to the production environment. Secure cookie and session-encryption defaults are likewise production-only, leaving local HTTP development unaffected.
* The bootstrap configuration accepts forwarding headers only when `TRUSTED_PROXIES` is explicitly populated with a comma-separated list of known proxy IPs/CIDRs. Actual proxy values were not guessed or configured during this attestation.
* API throttling returns only `error` and `status_code`; existing API resilience coverage asserts that the response omits a trace. With production debug disabled, Laravel does not render debug traces for normal application errors.

## Required Deployment Inputs and Procedure
* The operator must supply the real HTTPS origin and TLS termination configuration, exact trusted-proxy CIDRs/IPs, PostgreSQL hostname and CA certificate path for `verify-full`, any required PostgreSQL client certificate/key, and the secret-manager or environment-injection mechanism.
* Do not place credentials, tokens, webhook secrets, license keys, or private certificates in source control or `.env.production.example`.
* After injecting the real values during a release, run `php artisan config:clear`, then `php artisan config:cache`, then restart application workers/processes through the normal deployment mechanism. Verify the generated URL scheme, secure cookie attributes, database TLS connection, and absence of debug traces through the deployed HTTPS endpoint.

## Scope Boundary
* No application code or production data changed, so no test suite was rerun. The most recent complete suite remains `83 passed (364 assertions)`.
* The backup restore drill was verified in a subsequent operational record. No Phase 9 work was started.

---

# BCP — Phase 9 Manual Bank Payment Workflow

| Property | Details |
| :--- | :--- |
| **Scope** | Customer-submitted manual bank payments only |
| **Execution Date** | 2026-08-25 |
| **Status** | **COMPLETE / VERIFIED** |

## Implemented Behavior
* The customer portal accepts only a bank transaction reference for an unpaid invoice owned by the authenticated customer's persisted tenants. Submitted tenant, customer, and amount input is ignored.
* A submission creates a tenant-owned `manual` payment with `pending` status and the server-derived invoice total. It never settles the invoice at submission time.
* The existing globally unique payment transaction reference prevents duplicate bank-reference submission.
* Active super-admins can approve or reject pending manual payments from the invoice review screen. Both actions are recorded through the existing immutable admin audit log.
* Approval locks the payment and invoice in one database transaction, completes the payment, marks the invoice paid, and reactivates the linked subscription. Rejection marks only the pending payment as failed.
* Nested admin routes require the payment to belong to the routed invoice, preventing cross-invoice review actions.

## Verification
* Focused billing tests: `9 passed (48 assertions)`.
* Full Laravel suite: `89 passed (392 assertions)` in `3.51s`.

## Provider Boundary
* No bKash, Nagad, SurjoPay, or other external payment-provider integration, package, credential, API call, checkout, callback, or transaction was added.




