Architecture v1.0 is accepted as the architectural direction, but implementation is NOT approved yet. Before implementation, create Architecture v1.1 by resolving the foundational database and transactional decisions below. Do NOT create migrations, models, controllers, services, jobs, APIs, packages, or business logic yet. ============================================================ 1. IDENTIFIER STRATEGY ============================================================ Use: - BIGINT UNSIGNED as internal relational primary keys where appropriate. - ULID as externally exposed/public identifiers for major business resources. Examples: products orders customers/users payments shipments stores vendors integrations Document: - which tables need public IDs - ULID uniqueness/index strategy - why internal BIGINT IDs remain useful - why APIs must expose public IDs rather than sequential PKs - foreign keys should generally use internal BIGINT IDs Do not expose internal sequential IDs through public APIs unless explicitly justified. ============================================================ 2. MONEY STRATEGY ============================================================ Define one consistent money strategy. Prefer integer minor units where practical: $19.99 -> 1999 Store currency explicitly using ISO 4217 currency codes. Document handling for currencies whose minor unit is not 2 decimal places. Do not use FLOAT or DOUBLE for money. If DECIMAL is required for specific accounting/provider data, document exactly where and why. Pricing, orders, payments, refunds, discounts and taxes must use a consistent strategy. ============================================================ 3. INVENTORY QUANTITY SEMANTICS ============================================================ For Phase 1: Inventory represents sellable liquor units/bottles and uses integer quantities. Do not support fractional bottle inventory unless a confirmed business requirement appears. Define: on_hand reserved available Authoritative formula: available = on_hand - reserved MySQL is the authoritative inventory source. Clearly document whether available is computed or persisted. If persisted, explain how consistency is guaranteed. ============================================================ 4. INVENTORY CONCURRENCY ============================================================ Create a detailed concurrency design for inventory reservation. The architecture must prevent overselling when multiple checkout requests attempt to reserve the same final units. Document the exact transactional algorithm. Analyze use of: DB transactions SELECT ... FOR UPDATE atomic conditional updates unique constraints reservation records Example: BEGIN lock inventory level validate: on_hand - reserved >= requested quantity create reservation increment reserved COMMIT Do not rely on Redis locks as the primary inventory correctness mechanism. Redis may optimize operations later, but MySQL must protect transactional inventory correctness. Document: - deadlock handling - transaction retry strategy - lock ordering - concurrent carts - concurrent payment completion - cancellation - expired reservations - inventory adjustments during reservations ============================================================ 5. RESERVATION LIFECYCLE ============================================================ Do NOT hard-code a reservation duration yet. Make reservation policy configurable. Define reservation states, for example: ACTIVE COMMITTED RELEASED EXPIRED CANCELLED Document transitions. Example: Cart/Checkout -> ACTIVE reservation -> Payment successful -> COMMITTED -> Inventory sale ledger entry OR ACTIVE -> checkout timeout -> EXPIRED -> reserved quantity released Address payment methods that can remain pending beyond the normal checkout reservation period. ============================================================ 6. INVENTORY LEDGER ============================================================ Finalize inventory ledger semantics. Every stock mutation must be explainable through inventory transactions. Define transaction types and sign conventions. Examples: RECEIVING SALE RETURN ADJUSTMENT_IN ADJUSTMENT_OUT TRANSFER_IN TRANSFER_OUT DAMAGE SYNC_CORRECTION Clarify whether RESERVATION and RESERVATION_RELEASE belong in the stock ledger or reservation lifecycle/history. Avoid double-counting reserved stock and physical stock movement. Document how: inventory_levels relates to: inventory_transactions inventory_reservations Define reconciliation strategy if aggregate inventory differs from ledger-derived expectations. ============================================================ 7. ORDER STATE MACHINE ============================================================ Design an explicit Order state machine. Do not use arbitrary status strings. Separate order state from: payment state fulfillment state shipment state Propose Phase-1 order states and legal transitions. For each transition define: source state target state trigger guard conditions side effects event emitted who/what may perform it Include: cancellation partial fulfillment payment failure refund implications Do not overcomplicate with every hypothetical future state. ============================================================ 8. PAYMENT STATE MACHINE ============================================================ Create a separate payment lifecycle. Potential concepts: PENDING AUTHORIZED CAPTURED FAILED CANCELLED/VOIDED PARTIALLY_REFUNDED REFUNDED Validate these against the provider-independent payment model. Payment attempts and payment transactions must preserve immutable history. Never mutate a failed attempt into a successful attempt. Define webhook-driven transitions and idempotency requirements. ============================================================ 9. FULFILLMENT STATE MACHINE ============================================================ Define fulfillment lifecycle independently from order/payment. Support: one order multiple fulfillments multiple inventory locations partial fulfillment Define Phase-1 states and legal transitions. ============================================================ 10. SHIPMENT STATE MACHINE ============================================================ Define shipment lifecycle independently. Potential states may include: PENDING READY SHIPPED IN_TRANSIT DELIVERED FAILED CANCELLED RETURNED Do not assume all delivery providers expose identical statuses. Define normalization strategy from provider-specific statuses into internal statuses. Preserve raw provider status separately when useful. ============================================================ 11. IDEMPOTENCY ============================================================ Finalize idempotency architecture. Use: idempotency key + authenticated actor/integration scope + operation/route scope + request fingerprint/hash Document behavior when: same key + same request same key + different request request currently processing original request failed response needs replaying key expired Critical operations include: order creation payment initiation/capture refund inventory adjustment shipment creation external integration writes Define database constraints that prevent races between duplicate requests. ============================================================ 12. TRANSACTIONAL OUTBOX ============================================================ Finalize outbox architecture. Required lifecycle: PENDING PROCESSING if needed PROCESSED FAILED Document: retry policy backoff attempt limits failure reason manual replay worker crash recovery stuck processing recovery Do not add Kafka/RabbitMQ. Use the approved MySQL + Laravel Queue/Redis infrastructure. Database transaction: BEGIN domain mutation outbox insert COMMIT Queue worker processes committed outbox messages. Ensure consumers are idempotent. ============================================================ 13. DOMAIN EVENT CATALOG ============================================================ Finalize Phase-1 event catalog. For every event document: event name aggregate producer payload schema consumers sync/async idempotency requirement external webhook eligibility Do not publish entire Eloquent models as event payloads. Use explicit event schemas. ============================================================ 14. MULTI-STORE / SERVICEABILITY ============================================================ Finalize distinction between: Store InventoryLocation Address ServiceZone A store may be an inventory location, but do not tightly couple the concepts if that prevents future warehouse/location support. Customer location must NOT simply select the geographically nearest store. Availability should eventually consider: destination serviceability inventory compliance shipping method business priority Document a deterministic fulfillment candidate selection architecture. Do not implement complex optimization yet. ============================================================ 15. PRE-ARRIVAL MODEL ============================================================ Finalize incoming/pre-arrival inventory. Pre-arrival is NOT product type. Define: incoming inventory source/vendor destination location expected quantity reserved/pre-sold quantity expected arrival status Explain how pre-arrival reservations differ from physical stock reservations. Do not allow incoming stock to incorrectly inflate on_hand inventory. ============================================================ 16. VENDOR INVENTORY SOURCE OF TRUTH ============================================================ Clarify inventory ownership. Client-owned physical inventory: Our MySQL inventory ledger is authoritative. External vendor inventory: Vendor is authoritative for vendor availability. Our database stores a synchronized representation with: last_synced_at sync status provider quantity/availability Document stale-data behavior. Do NOT merge vendor quantity into physical store on_hand inventory. Fulfillment planning must know whether inventory belongs to: client location external vendor ============================================================ 17. TYPESENSE STRATEGY ============================================================ Do not finalize every catalog field yet. Finalize architectural strategy only: MySQL = canonical Typesense = projection Define: index event flow update flow delete flow failed indexing replay full rebuild schema versioning alias/swap strategy if supported zero/minimal downtime rebuild approach Catalog facets/fields remain subject to final Catalog schema approval. ============================================================ 18. AUDIT LOGGING ============================================================ Finalize audit policy. Audit logs should be append-oriented. Define: actor action resource before/after representation correlation ID IP user agent timestamp Define sensitive fields that MUST be redacted. Never store: passwords tokens API secrets payment credentials Define retention as configurable rather than hard-coding a duration until client/compliance policy is known. ============================================================ 19. API ERROR CONTRACT ============================================================ Finalize consistent API error format. Example direction: { "error": { "code": "INVENTORY_UNAVAILABLE", "message": "...", "details": {}, "request_id": "..." } } Define categories: VALIDATION_ERROR AUTHENTICATION_REQUIRED FORBIDDEN RESOURCE_NOT_FOUND CONFLICT INVENTORY_UNAVAILABLE INVALID_STATE_TRANSITION IDEMPOTENCY_CONFLICT RATE_LIMITED INTEGRATION_FAILURE INTERNAL_ERROR Do not expose stack traces/internal exceptions. ============================================================ 20. DATABASE CONSTRAINT REVIEW ============================================================ For every proposed table review: PK FK unique constraints indexes nullability check constraints soft delete behavior Especially review constraints for: inventory_levels inventory_reservations vendor_products prices orders order_items payments payment_attempts refunds fulfillments shipments idempotency_keys outbox_messages webhook_deliveries Do not depend only on application validation for critical invariants. ============================================================ 21. PHASE-1 TABLE CLASSIFICATION ============================================================ The current estimate is approximately 45-60 conceptual tables. Classify each proposed table: REQUIRED PHASE 1 FOUNDATION NOW DEFERRED Do not create tables simply because they might someday be useful. We want scalability without speculative schema complexity. ============================================================ 22. ARCHITECTURE DECISION RECORDS ============================================================ Create ADRs for the most important decisions: ADR-001 Modular Monolith ADR-002 Identifier Strategy ADR-003 Inventory Consistency ADR-004 Money Representation ADR-005 Transactional Outbox ADR-006 Provider Adapter Architecture ADR-007 Search Projection ADR-008 Order/Payment/Fulfillment Separation ADR-009 API Versioning and Contracts For each ADR include: Context Decision Alternatives Consequences Risks Future migration path ============================================================ OUTPUT ============================================================ Update Architecture v1.0 into Architecture v1.1. Create/update: docs/architecture/... Create: docs/architecture/decisions/ with the ADR files. Update: ERD.md ARCHITECTURE_REVIEW.md EVENT_CATALOG.md API_CONVENTIONS.md 21-open-decisions.md Resolve the decisions specified above. Keep genuinely business-dependent questions open. At the end respond: ARCHITECTURE V1.1 COMPLETE Then provide: 1. Decisions resolved 2. Remaining open business decisions 3. Table classification counts: - Required Phase 1 - Foundation - Deferred 4. Final proposed module list 5. Final critical database invariants 6. Inventory concurrency summary 7. State machine summary 8. Idempotency summary 9. Outbox/retry summary 10. Risks still requiring attention 11. Files created/modified 12. Confirmation that NO implementation/migrations/models/controllers/APIs were created STOP after Architecture v1.1. Implementation is still NOT approved.