## Phase 1 Execution Plan: Data Integrity, Concurrency, and Financial Safety

### Summary
This plan executes a deep, non-mutating audit of financial and inventory-adjacent write paths, then produces a Phase 1 report with critical risks, exact file evidence, and full Laravel refactor code (method-level replacements) without changing repository files.

### Locked Decisions
1. Scope: **Runtime + Dormant**
2. Refactor format: **Full Methods**
3. Mutation policy: **No file edits** in this phase; report-only with patch-ready code blocks

### Public API / Interface Impact
1. HTTP routes: **No required route signature changes** for Phase 1 fixes.
2. Controller method signatures: keep existing signatures stable where possible.
3. Internal interface additions (proposed in refactor code only):
   - Transaction-safe service methods for invoice creation, quotation conversion, journal posting, and vehicle reservation.
   - Optional internal locking helpers (`lockForUpdate`-based) for idempotent conversion/reservation flows.
4. Schema-level recommendations (report-only):
   - Enforce integrity fields already present but unused (for example linking quotation conversion to `converted_to_invoice_id`).
   - Add/confirm unique and check constraints where race safety depends on DB guarantees.

### Execution Steps
1. Build the authoritative write-path inventory for Phase 1.
   - Primary runtime targets:
     - `app/Services/FinanceService.php`
     - `app/Http/Controllers/Admin/QuotationController.php`
     - `app/Http/Controllers/Admin/AccountingController.php`
     - `app/Http/Controllers/Admin/VehicleController.php`
     - `app/Http/Controllers/Admin/ExpenseController.php`
     - `app/Http/Controllers/Admin/HRController.php` (employee creation integrity check)
   - Dormant/inventory schema targets:
     - `database/migrations/2024_01_01_000008_create_logistics_tables.php`
     - `database/migrations/2026_02_16_160005_create_maintenance_commerce_contract_tables.php`
     - Related models (`Order`, `OrderItem`, `MaintenancePart`, `Product`)

2. ACID compliance audit per business flow.
   - Flow A: Invoice creation with items (`FinanceService::createInvoice`) for partial-write risk.
   - Flow B: Payment posting (`FinanceService::recordPayment`) to confirm lock and transactional correctness.
   - Flow C: Journal entry + items (`AccountingController::journalStore`) for partial ledger writes.
   - Flow D: Quotation create/convert/destroy (`QuotationController`) for multi-step financial transitions.
   - Flow E: Vehicle create/update related rows (`VehicleController`) for stock/sales integrity.
   - Flow F: Employee user+profile creation (`HRController::employeeStore`) for cross-table consistency risk.
   - Flow G: Expense write path (`ExpenseController::store`) for model/schema mismatch with financial recording.

3. Concurrency and race-condition audit.
   - Quotation conversion race: detect duplicate invoice issuance window; require row lock/idempotent update path.
   - Journal number race: `count()+1` generation collision under concurrent submissions.
   - Vehicle/VIN/stock race: identify absence of reservation and decrement locking for sales finalization.
   - Invoice payment race: validate existing pessimistic lock behavior and edge cases.
   - Dormant inventory race design: define required atomic decrement/reservation pattern for future activation.

4. Produce Phase 1 risk report (structured and severity-ranked).
   - Severity order: Critical, High, Medium.
   - For each finding include:
     - Exact path and line references.
     - Why it is a financial/data-integrity risk.
     - Concrete failure scenario.
     - Recommended control (transaction, lock, constraint, idempotency guard).

5. Provide full refactored code per critical/high finding.
   - Patch-ready full method replacements (not snippets) for impacted methods.
   - Refactors will enforce:
     - `DB::transaction(...)` around multi-table writes.
     - `lockForUpdate()` or atomic conditional updates for contested rows.
     - Idempotent conversion flow for quotation→invoice.
     - Deterministic/serialized journal numbering strategy.
     - Correct field mapping for financial transaction persistence.

6. Verification pack in the report.
   - Include exact test scenarios and expected outcomes for each fix.
   - Include concurrency scenarios with two simultaneous requests.
   - Include rollback assertions (parent row not persisted if child write fails).
   - Include financial invariant assertions:
     - `sum(invoice_items.total_price)` consistency
     - `invoice.paid_amount <= invoice.total_amount`
     - balanced journal entries only
     - single conversion per quotation

7. Phase closure behavior.
   - Deliver the full Phase 1 report.
   - End with explicit permission request to start Phase 2 (as per your protocol).

### Test Cases and Scenarios
1. Concurrent quotation conversion creates exactly one invoice and one conversion link.
2. Forced exception during invoice-item insert rolls back invoice header.
3. Forced exception during journal-item insert rolls back journal entry.
4. Parallel payments on same invoice never exceed remaining balance.
5. Vehicle reservation/sale simulation prevents duplicate VIN sell path.
6. Expense write persists valid financial record with correct identifiers/date mapping.
7. Cross-table create (employee user/profile) rolls back entirely on second write failure.

### Assumptions and Defaults
1. Database engine supports row-level locks with `SELECT ... FOR UPDATE` semantics.
2. UUID primary keys are stable and generated by model traits.
3. Existing gate/middleware auth remains unchanged for Phase 1.
4. No repo mutations are allowed in this phase; all fixes are delivered as report code blocks only.
5. Dormant inventory modules are assessed as latent production risk even if currently not routed.
