You are acting as the Principal Software Architect and Senior Backend Engineer for this project, with 11+ years of production experience designing Laravel applications, high-scale commerce systems, inventory platforms, distributed integrations, payment systems, and API-first architectures. We are starting a new production-grade liquor commerce platform from scratch. Your responsibility is NOT simply to make the application work. Your responsibility is to design a clean, scalable, maintainable architecture that can support the business for years without requiring major database or application rewrites as stores, vendors, delivery partners, integrations, traffic, inventory, orders, and operational complexity increase. ============================================================ CRITICAL INSTRUCTION ============================================================ DO NOT start implementing migrations, models, controllers, services, repositories, APIs, jobs, or business logic yet. FIRST perform architecture analysis and create Architecture v1.0 documentation. I want to review and approve the architecture before implementation begins. Do not make unnecessary assumptions. If an important business rule is unknown and materially affects architecture, document it under: OPEN DECISIONS / QUESTIONS instead of silently choosing an implementation. Do not over-engineer Phase 1 with microservices. Use a MODULAR MONOLITH architecture with strict module boundaries and provider abstractions so modules can be extracted later if scale requires it. ============================================================ PROJECT ============================================================ Enterprise Headless Liquor Commerce & Inventory Management Platform. This is not a generic ecommerce template. The client currently owns a physical liquor store and wants to sell liquor online. Products can come from: 1. Client-owned physical store inventory 2. SGProof vendor inventory 3. Future liquor vendors 4. Pre-arrival/incoming inventory The client may expand to multiple physical liquor stores in different locations. When that happens: - Each store must maintain independent inventory. - Product availability may vary by store/location. - Customer purchasing options must depend on serviceability and location. - Pickup availability may depend on store. - Delivery methods may depend on customer location. - Fulfillment may come from different inventory locations. - One order may eventually require multiple fulfillments/shipments. - Inventory transfers between locations may be required. - POS synchronization may be introduced later. Do NOT build speculative unrelated businesses such as accessories, subscription boxes, marketplaces, etc. Keep the architecture focused on liquor commerce. ============================================================ TECHNOLOGY STACK ============================================================ Backend: Laravel 13 Customer storefront: Next.js 16 Super Admin: Next.js 16 Database: MySQL 8 Cache: Redis Queue infrastructure: Laravel Queues + Redis Scheduling: Laravel Scheduler Search: Typesense Object Storage: S3-compatible object storage CDN / Edge: Cloudflare Vendor browser automation where necessary: Playwright API documentation: OpenAPI 3.x / Swagger Deployment: Container-ready architecture with CI/CD support. IMPORTANT: Do not introduce Elasticsearch, Kafka, RabbitMQ, Kubernetes, microservices, GraphQL, MongoDB, or additional infrastructure unless there is a concrete requirement. Design extension points so infrastructure can evolve later. ============================================================ ARCHITECTURAL PRINCIPLES ============================================================ Design around: 1. API-first architecture 2. Modular monolith 3. Domain-oriented module boundaries 4. Provider/adapter pattern for third-party integrations 5. Event-driven internal workflows 6. Transactional outbox for reliable asynchronous events 7. Idempotent write operations 8. Multi-store/location-aware inventory 9. Complete inventory auditability 10. Payment/order separation 11. Fulfillment/order separation 12. Search engine as projection, not source of truth 13. Secure integration credential handling 14. OpenAPI contracts 15. API versioning 16. Audit logging 17. Observability 18. Security by design 19. Liquor compliance extensibility 20. AI/automation-ready APIs without implementing AI in Phase 1 ============================================================ NON-NEGOTIABLE DOMAIN RULES ============================================================ PRODUCT != INVENTORY PRODUCT != PRICE PRODUCT != VENDOR PRODUCT ORDER != PAYMENT ORDER != SHIPMENT STORE != INVENTORY VENDOR != PRODUCT PRE-ARRIVAL != PRODUCT TYPE SGPROOF != CORE DOMAIN FEDEX/UPS/etc. != CORE SHIPPING DOMAIN STRIPE/etc. != CORE PAYMENT DOMAIN External providers must never dictate our core database architecture. ============================================================ PROPOSED DOMAIN MODULES ============================================================ Analyze and refine these boundaries: Identity Catalog Store Inventory Location / Serviceability Pricing Promotion Cart Checkout Order Fulfillment Shipping Payment Vendor Compliance CMS SEO Search Integration Notification Media Audit For every module document: - Responsibility - What it owns - Tables/entities it owns - Public interfaces/contracts - Events emitted - Events consumed - Dependencies on other modules - What it must NOT own Avoid circular dependencies. ============================================================ CATALOG ============================================================ Design a proper liquor catalog. Potential concepts include: products product_variants brands categories collections attributes attribute_values product media tags Liquor-specific characteristics may include: - alcohol type - wine/spirit category - producer - country - region - appellation - vintage - ABV - bottle size - varietal - rating - SKU - UPC/EAN where applicable Do NOT blindly create every property as a nullable products column. Determine which characteristics deserve: - normalized entities - dedicated columns - configurable attributes - metadata based on: searching, filtering, SEO, reporting, data integrity, performance. Explain the decision. Products may have variants. Inventory, pricing, vendor offers and fulfillment should reference the sellable unit/variant where appropriate. ============================================================ MULTI-STORE MODEL ============================================================ The client currently has one store but architecture must support multiple stores. Design: stores addresses inventory locations service zones location/serviceability rules Do NOT store product quantity on products. Inventory belongs to a location. Example: Product Variant A Store NY: 20 Store CA: 50 Store TX: 0 Customer availability should eventually be calculated using: customer destination service zone store/location inventory shipping methods compliance fulfillment rules Do NOT assume nearest geographic store is automatically the fulfillment source. Serviceability and business rules must determine eligibility. ============================================================ INVENTORY ENGINE ============================================================ This is a critical domain. Design at minimum: inventory_locations inventory_levels inventory_transactions inventory_reservations Potential future: inventory_transfers inventory_transfer_items stock_receipts stock_adjustments Track concepts such as: on_hand reserved available But explicitly define whether `available` is: - persisted, - generated, - calculated, - cached, and explain consistency implications. Inventory mutations must be auditable. Inventory transaction types may include: RECEIVING SALE RETURN ADJUSTMENT TRANSFER_IN TRANSFER_OUT RESERVATION RESERVATION_RELEASE DAMAGE SYNC_CORRECTION Do not rely on direct quantity updates without ledger/history. Design concurrency handling to prevent overselling. Analyze: - DB transactions - atomic updates - row locking where appropriate - reservation expiry - checkout race conditions - payment failures - cancellation - refunds - vendor inventory synchronization Define the source of truth for client-owned stock versus vendor-reported availability. ============================================================ PRE-ARRIVAL ============================================================ Pre-arrival is NOT a separate product type. The same product may simultaneously have: Store A: 5 bottles Store B: 0 bottles Incoming: 100 bottles expected September 15 Design an incoming inventory/procurement model. Consider: incoming_inventory expected quantity reserved quantity expected arrival date source/vendor destination location status Pre-arrival purchasing/reservation rules must remain configurable. ============================================================ VENDOR ENGINE ============================================================ SGProof is the first external liquor vendor. The client has an authenticated SGProof merchant account. SGProof has declined to provide an API, so browser automation may be required, subject to the client's authorization and SGProof's applicable terms. DO NOT create the core architecture around SGProof. Define a provider contract such as: VendorConnector Capabilities might include: authenticate() fetchCatalog() fetchProduct() fetchInventory() fetchPrices() healthCheck() Do not force every provider to implement capabilities it cannot support; consider capability interfaces where appropriate. Possible implementations: SGProofConnector ApiVendorConnector CsvVendorConnector FutureVendorConnector Possible vendor tables: vendors vendor_accounts vendor_products vendor_offers vendor_sync_runs vendor_sync_errors We need to distinguish: OUR canonical product from VENDOR'S representation of the product. Vendor mapping should support: vendor product ID vendor SKU canonical variant mapping vendor price vendor availability vendor metadata last synchronization sync state Do NOT create: products.sgproof_id products.sgproof_stock products.sgproof_price Provider-specific raw/staging data may be stored separately if justified. Credentials must not be stored as plaintext. Document recommended secrets management strategy. ============================================================ PRICING ENGINE ============================================================ Design pricing independently from products. Potential requirements: retail pricing sale pricing store-specific pricing pre-arrival pricing vendor cost bulk pricing future wholesale pricing scheduled pricing Consider: price_lists prices Clearly separate: base/catalog pricing from promotion evaluation. Use DECIMAL for money. Never FLOAT/DOUBLE. Document currency strategy. ============================================================ PROMOTION ENGINE ============================================================ The platform may support: coupons bulk deals flash sales scheduled promotions free shipping quantity discounts collection/category promotions Design: promotions promotion_rules promotion_actions coupons promotion_redemptions But do not build an unnecessarily complex rules language for Phase 1. Define an extensible model and identify what belongs in Phase 1 versus later. ============================================================ CART & CHECKOUT ============================================================ Design: carts cart_items and checkout workflow. Checkout must eventually consider: product availability inventory reservation customer location serviceability compliance pricing promotions tax shipping options payment fulfillment Define checkout orchestration responsibilities. Do not place all logic inside a single controller or giant CheckoutService. ============================================================ ORDER ENGINE ============================================================ Design: orders order_items order_addresses order_status_history Orders must preserve historical snapshots. If a product name, price, tax, address or product metadata changes later, historical order data must remain correct. Explain which order fields require snapshots. Use a clear state machine / transition model. Avoid uncontrolled status strings. ============================================================ FULFILLMENT & SHIPMENTS ============================================================ One order may eventually be fulfilled from multiple locations. Example: Order #1001 Store A: 3 items Store B: 2 items Vendor: 1 item Still ONE customer order. Design: fulfillments fulfillment_items shipments shipment_items shipment_tracking_events Clearly distinguish: order fulfillment shipment Support partial fulfillment. ============================================================ SHIPPING ENGINE ============================================================ Future delivery providers may include: UPS FedEx USPS local delivery services same-day providers Do not bind checkout/order logic directly to any provider SDK. Define: ShippingProvider / ShippingRateProvider / TrackingProvider or capability-based contracts if better. Potential operations: quote() createShipment() cancelShipment() track() Potential tables: shipping_providers shipping_methods shipping_zones shipping_rates Provider configuration should be replaceable. Location/serviceability + compliance + shipping must work together. ============================================================ PAYMENT ENGINE ============================================================ Provider based. Possible future providers: Stripe PayPal others Define contracts for: authorize capture refund void webhook verification/processing Design: payments payment_attempts payment_transactions refunds payment_webhook_events One order may have: failed attempt another failed attempt successful payment partial refund another refund Never overwrite financial history. Money must use DECIMAL or minor units based on an explicitly documented strategy. Webhook processing must be: signature verified idempotent auditable ============================================================ COMPLIANCE ============================================================ This is a liquor platform. Do not hard-code legal assumptions. Build an extensible Compliance Engine capable of evaluating configured rules supplied/approved by the client's legal/compliance requirements. Potential inputs: customer age/verification state billing/shipping destination store product/category shipping provider delivery method jurisdiction time/date where applicable Potential concepts: compliance_rules jurisdictions product restrictions shipping restrictions age verification provider Actual regulatory rules must be confirmed separately. Architecture should allow future third-party age/identity verification providers through adapters. ============================================================ INTEGRATION ARCHITECTURE ============================================================ Third-party integrations must use contracts/adapters. Examples: VendorConnector PaymentGateway ShippingProvider TaxProvider AgeVerificationProvider NotificationProvider SearchProvider StorageProvider Business modules must depend on contracts, not concrete SDKs. Example: BAD: OrderService -> FedEx SDK GOOD: Order/Fulfillment Module -> Shipping Contract -> Shipping Engine -> FedEx Adapter Same for payments, vendors, tax, age verification, notifications, etc. ============================================================ INTEGRATION REGISTRY ============================================================ Analyze whether we need: integrations integration_credentials integration_settings integration_logs integration_sync_runs Credentials must be encrypted and preferably reference a secret store. Define how integration health/status is monitored. ============================================================ API ARCHITECTURE ============================================================ All important business capabilities must be API accessible. Use versioning from Day 1: /api/v1/ Potential organization: /api/v1/catalog /api/v1/products /api/v1/search /api/v1/cart /api/v1/checkout /api/v1/orders /api/v1/stores /api/v1/availability /api/v1/admin/... /api/v1/integrations/... Define: - request conventions - response envelope - validation errors - domain errors - pagination - filtering - sorting - sparse fields if appropriate - correlation/request IDs - rate limiting - API versioning - deprecation strategy Create OpenAPI 3.x documentation as a first-class artifact. Do not expose Eloquent models directly as API responses. Use explicit API Resources/DTOs. ============================================================ AUTHENTICATION & AUTHORIZATION ============================================================ Do not assume one auth mechanism serves every consumer. Design separately for: 1. Customer authentication 2. Admin authentication 3. Third-party integration authentication Evaluate: secure session/cookie based auth versus short-lived access tokens + refresh/session management for first-party Next.js applications. For external integrations evaluate: OAuth 2.x scoped API credentials Potential scopes: products:read inventory:read inventory:write orders:read orders:write shipments:write Super Admin requires: RBAC fine-grained permissions 2FA readiness audit logging session management ============================================================ IDEMPOTENCY ============================================================ Critical write operations must support idempotency. Examples: POST /orders POST /payments POST /refunds POST /inventory/adjustments POST /shipments Design: idempotency_keys and document: scope request hash response persistence expiry concurrency behavior Retrying the same operation must not create duplicate orders, payments, refunds, shipments or inventory mutations. ============================================================ EVENT ARCHITECTURE ============================================================ Define domain events such as: ProductCreated ProductUpdated InventoryReserved InventoryReleased InventoryAdjusted InventoryLow OrderPlaced OrderCancelled PaymentAuthorized PaymentCaptured PaymentFailed PaymentRefunded FulfillmentCreated ShipmentCreated ShipmentDelivered VendorSyncCompleted VendorSyncFailed CustomerRegistered For every event document: producer payload consumers synchronous vs asynchronous retry behavior idempotency expectations Do not use events to hide critical business invariants. ============================================================ TRANSACTIONAL OUTBOX ============================================================ Use transactional outbox for reliable events crossing transaction boundaries. Example: BEGIN Create Order Reserve Inventory Write Outbox Message COMMIT Worker processes outbox. Design: outbox_messages Potential fields: id event_id event_type aggregate_type aggregate_id payload status attempts available_at processed_at created_at Document retry and dead-letter/failure handling. ============================================================ WEBHOOK ENGINE ============================================================ Design external webhooks. Potential tables: webhook_endpoints webhook_subscriptions webhook_deliveries Webhook requirements: event ID timestamp signed payload secret rotation retry policy delivery status attempt count response status idempotency disable unhealthy endpoint after configurable failures Potential events: order.created order.cancelled inventory.updated product.updated payment.captured shipment.created shipment.delivered ============================================================ SEARCH ============================================================ MySQL is the source of truth. Typesense is a search projection. Flow: MySQL -> domain event/outbox -> SearchIndexJob -> Typesense Typesense failure must never corrupt transactional commerce data. Search index must be rebuildable from MySQL. Document: collection/schema strategy indexing partial updates deletes rebuilds zero/minimal downtime reindexing filter/facet strategy ============================================================ CMS ============================================================ CMS should be independent from commerce. Potential concepts: pages page_versions content_sections menus menu_items banners blog_posts blog_categories site_settings theme_settings Homepage must be dynamically configurable from Super Admin. Potential sections: Hero Featured Collections Products Deals Pre-arrivals Banners Blogs Custom content Sections may support: enable/disable ordering content media configuration scheduling visibility Do not allow arbitrary executable code from admin CMS configuration. ============================================================ SEO ============================================================ Design centralized SEO metadata attachable to: products categories collections pages blogs Potential: seo_metadata Fields may include: title description canonical robots OpenGraph data structured data configuration Also design: redirects sitemap generation robots management breadcrumbs strategy Avoid duplicate/canonical conflicts for location-specific catalog pages. ============================================================ AUDIT ============================================================ Admin actions must be traceable. Design audit_logs capturing: actor action resource before state after state request/correlation ID IP user agent timestamp Audit important operations such as: price changes inventory adjustments order status changes refunds integration configuration changes role/permission changes CMS publishing ============================================================ OBSERVABILITY ============================================================ Define architecture for: structured logs request IDs correlation IDs queue/job monitoring failed jobs integration failures vendor sync failures webhook failures payment failures inventory anomalies health checks Do not tie architecture to a single monitoring vendor unless necessary. ============================================================ DATABASE REQUIREMENTS ============================================================ Use MySQL 8. For every table define: table name purpose columns data types nullable/not nullable defaults primary key foreign keys unique constraints indexes check constraints where appropriate soft delete policy timestamps ownership module Use proper precision for: money quantities percentages Do not use FLOAT for money. Avoid database ENUMs for statuses likely to evolve unless you provide strong justification. Use application enums/value objects where appropriate. Design indexes based on actual expected query patterns. ============================================================ IDENTIFIERS ============================================================ Evaluate: BIGINT internal PK + ULID/UUIDv7 public identifier versus another strategy. Public APIs should not depend on sequential database IDs. Explain: performance index size foreign key implications security/guessability distributed generation and make a recommendation. ============================================================ LARAVEL CODE ARCHITECTURE ============================================================ Propose a clean module structure. Example direction: app/ Modules/ Catalog/ Domain/ Application/ Infrastructure/ Http/ Inventory/ Pricing/ Orders/ Payments/ Shipping/ Vendors/ Stores/ Compliance/ CMS/ SEO/ Integrations/ Do not blindly implement repository interfaces for every model. Use repositories only where they provide meaningful domain/infrastructure abstraction. Use: Actions / Commands DTOs Value Objects Domain Services Policies Events Listeners Jobs Contracts Adapters where justified. Avoid: God Services Fat Controllers business logic in Eloquent models cross-module model mutation global helper-driven business logic unnecessary abstractions ============================================================ SUPER ADMIN ============================================================ Super Admin is a separate Next.js 16 application. It must manage: products categories collections inventory stores vendors pricing promotions orders fulfillments shipping payments/refunds CMS SEO users roles/permissions integrations webhooks vendor sync status logs reports settings The admin should consume Laravel APIs. Do not put business rules only inside Next.js. Every important admin operation must be representable through the backend API. This is important for future automation and AI agents. ============================================================ AI / AGENT READINESS ============================================================ DO NOT implement AI agents or MCP in Phase 1. But design APIs so they can be safely consumed by automation later. Requirements: documented APIs predictable JSON stable resource identifiers idempotent mutations fine-grained permissions audit trails structured errors OpenAPI contracts webhooks/events This should allow a future MCP server or AI automation layer to wrap the existing APIs without rewriting business logic. ============================================================ SECURITY ============================================================ Architecture must consider: OWASP API risks CSRF where applicable XSS SQL injection SSRF mass assignment rate limiting brute-force protection secure cookies/tokens 2FA readiness secret management webhook signatures file upload validation authorization boundaries admin privilege escalation sensitive data redaction in logs Never log: passwords access tokens API secrets payment credentials sensitive authentication data ============================================================ TESTING STRATEGY ============================================================ Define testing architecture for: unit tests domain tests feature/API tests integration tests contract tests provider adapter tests inventory concurrency tests payment idempotency tests webhook tests queue tests search indexing tests Third-party providers should be mockable through contracts. ============================================================ ARCHITECTURE DOCUMENTS TO CREATE ============================================================ Before writing implementation code, create: docs/architecture/README.md docs/architecture/01-system-overview.md docs/architecture/02-domain-boundaries.md docs/architecture/03-database-architecture.md docs/architecture/04-catalog.md docs/architecture/05-inventory.md docs/architecture/06-pricing-promotions.md docs/architecture/07-orders-fulfillment.md docs/architecture/08-payments.md docs/architecture/09-shipping.md docs/architecture/10-vendors.md docs/architecture/11-compliance.md docs/architecture/12-api-standards.md docs/architecture/13-events-outbox.md docs/architecture/14-webhooks-integrations.md docs/architecture/15-auth-security.md docs/architecture/16-search.md docs/architecture/17-cms-seo.md docs/architecture/18-observability.md docs/architecture/19-testing.md docs/architecture/20-deployment.md docs/architecture/21-open-decisions.md Also create: docs/architecture/ERD.md docs/architecture/EVENT_CATALOG.md docs/architecture/API_CONVENTIONS.md docs/architecture/INTEGRATION_CONTRACTS.md Use Mermaid diagrams where useful. ============================================================ ERD REQUIREMENTS ============================================================ ERD must include at minimum: Identity Catalog Stores Inventory Pricing Promotions Cart Orders Fulfillments Shipping Payments Vendors Integrations CMS SEO Audit Show: PK FK cardinality important unique constraints If the complete diagram becomes unreadable, create: 1. Master ERD 2. Catalog ERD 3. Inventory ERD 4. Commerce ERD 5. Integration ERD 6. CMS/SEO ERD ============================================================ ARCHITECTURE REVIEW REPORT ============================================================ At the end create: docs/architecture/ARCHITECTURE_REVIEW.md Include: 1. Executive summary 2. Architecture decisions 3. Domain boundaries 4. Database strategy 5. Inventory consistency strategy 6. Multi-store strategy 7. Vendor integration strategy 8. Shipping provider strategy 9. Payment provider strategy 10. Compliance strategy 11. API strategy 12. Event/outbox strategy 13. Security strategy 14. Search strategy 15. Scaling strategy 16. Risks 17. Trade-offs 18. Phase 1 decisions 19. Deferred decisions 20. Open questions For every major architecture decision explain: DECISION WHY ALTERNATIVES CONSIDERED TRADE-OFF FUTURE IMPACT ============================================================ PHASE 1 VS FUTURE ============================================================ Clearly classify requirements into: REQUIRED NOW ARCHITECTURAL FOUNDATION NOW, IMPLEMENT LATER FUTURE / DEFERRED Do not implement hypothetical features simply because architecture supports them. Examples: Multiple store architecture: FOUNDATION NOW Actual second store: FUTURE Vendor abstraction: FOUNDATION NOW SGProof implementation: separate approved integration phase Shipping provider abstraction: FOUNDATION NOW Five delivery partners: FUTURE AI/MCP: FUTURE Microservices: NOT REQUIRED NOW Kafka: NOT REQUIRED NOW POS: FUTURE ============================================================ QUALITY BAR ============================================================ Treat this as a platform expected to process real: orders payments refunds inventory customer information Architecture must prioritize: correctness data integrity security auditability maintainability extensibility over cleverness. Do not over-engineer. Do not under-engineer critical financial/inventory workflows. ============================================================ YOUR FIRST TASK ============================================================ 1. Inspect the existing repository completely. 2. Determine whether this is: - empty/new project - partially implemented project - existing architecture 3. Do NOT delete or rewrite existing working code. 4. Compare the repository with the requirements above. 5. Create Architecture v1.0 documentation. 6. Produce the complete proposed ERD. 7. Produce module boundaries. 8. Produce integration contracts. 9. Produce API conventions. 10. Produce event catalog. 11. Produce architecture review report. 12. List every assumption and unresolved question. 13. Identify any contradictions in the requirements. 14. Identify architectural risks. 15. Recommend corrections where necessary. 16. STOP. DO NOT create migrations. DO NOT create Eloquent models. DO NOT implement controllers. DO NOT implement APIs. DO NOT install unnecessary packages. DO NOT implement SGProof scraping. DO NOT implement business logic. Wait for architecture approval before implementation. ============================================================ RESPONSE FORMAT ============================================================ After completing the architecture documents, respond with: ARCHITECTURE V1.0 COMPLETE Then provide: 1. Files created/modified 2. Architecture summary 3. Proposed modules 4. Proposed database/table count 5. Critical architectural decisions 6. Open questions 7. Risks 8. Phase-1 vs deferred scope 9. Any requirements you recommend changing 10. Confirmation that no implementation/migrations were created Do not simply tell me everything looks good. Act as a senior architect. Challenge requirements that create technical debt, data-integrity problems, security issues, scalability issues, or unnecessary complexity. When uncertain, document the uncertainty instead of inventing requirements.