# PROJECT CURRENT STATE

## 1) Database Structure

### vehicles
- Purpose:
  - Core sellable inventory records used in public listing, seller listing, admin listing, checkout, and order items.
- Key columns (from create + subsequent migrations and model fillable):
  - id, seller_id, auction_car_id, make_id, model_id
  - make, model, model_code, rec_no, chassis, grade
  - year, registration_year, manufacture_year, mileage
  - price, discount_percentage, discount_amount
  - condition, vehicle_type, color, transmission, fuel_type, engine_capacity
  - length_m, width_m, height_m, volume_m3, seats, doors
  - location, stock_country, country_id
  - primary_image
  - stock_status (available/sold), status (draft/published/reserved/sold)
  - is_featured, is_clearance, is_ready_for_sale
- Relationships:
  - belongsTo users via seller_id
  - belongsTo auction_cars via auction_car_id (unique constraint on auction_car_id in vehicles)
  - belongsTo makes via make_id
  - belongsTo models via model_id
  - belongsTo shipping_countries via country_id (through Country model)
  - hasMany vehicle_images, vehicle_documents, order_items-linked usage, vehicle_attribute_values, vehicle_reservations
  - hasOne active vehicle_reservation (status active + expires_at > now)
- Features depending on vehicles:
  - Public vehicle catalog and detail
  - Seller and admin vehicle management
  - Checkout, order creation, payment settlement side effects (mark sold)
  - Reservation system (activeReservation display and reserve eligibility)

### auction_cars
- Purpose:
  - Auction intake source of truth for auction purchase and logistics pricing; influences vehicle readiness and purchase mode.
- Key columns (from create + refine migrations + model fillable):
  - id, make_id, model_id, chassis_no
  - purchase_date
  - auction_price, auction_fee, inspection, transportation, h_charge, van, insurance, freight, extra, shipper, storage
  - total, selling_price
  - vessel, sailing_date, region, city, auction_house
  - admin_notes, status (pending/completed)
- Relationships:
  - belongsTo makes via make_id
  - belongsTo models via model_id
  - hasOne vehicle via vehicles.auction_car_id
- Features depending on auction_cars:
  - Admin auction intake listing/editor
  - Vehicle derived price (vehicle price accessor prioritizes auction selling_price)
  - Vehicle purchase_mode derivation (completed -> direct_purchase, otherwise inquiry_only)
  - Vehicle is_ready_for_sale sync after auction save

### vehicle_reservations
- Purpose:
  - Time-bound reservation records for inquiry_only vehicles.
- Key columns (migration 2026_04_21_120000):
  - id, vehicle_id, user_id
  - reserved_at, expires_at
  - status (active/expired/converted)
  - timestamps
- Indexes:
  - vehicle_id + status
  - user_id + status
  - expires_at
  - vehicle_id + status + expires_at (named vr_vehicle_status_expires_idx)
- Relationships:
  - belongsTo vehicle
  - belongsTo user
- Features depending on vehicle_reservations:
  - Seller reservation API endpoint
  - Seller vehicles table reservation badge/button behavior
  - Public vehicle detail reserved-until indicator
  - Scheduled expiration command reservations:expire

### users
- Purpose:
  - Authentication identity and role partitioning (admin/seller/customer), plus profile and order-related data.
- Key columns:
  - id, name, email, password, role
  - phone, address, country
  - standard auth/session/team fields
- Relationships:
  - hasMany vehicles (as seller)
  - hasMany orders
  - hasMany vehicle_reservations
  - hasMany carts, consignees, remitters, payment_histories
- Features depending on users:
  - Role middleware access control for route groups
  - Seller ownership checks in vehicle/reservation flows
  - Customer eligibility checks for reservation (completedPurchaseCount)

### orders
- Purpose:
  - Purchase contract and financial snapshot record for customer vehicle purchases.
- Key columns (base + subsequent migrations and model fillable):
  - user_id, consignee_id, remitter_id
  - status, customer_status
  - total_price, vehicle_price, freight_cost, inspection_fee, insurance_fee, cif_total
  - discount_amount, paid_amount, remaining_balance
  - min_ship_deposit_percentage, deposit_percentage, min_deposit_amount
  - shipping_country_id, shipping_port_id, shipping_type
  - inspection_enabled, insurance_enabled
  - shipping_cost_reason, shipping_address, from_port, arrival_port
  - tracking_number, order_date, buy_date, shipped_at, delivered_at, departure_date, arrival_date, dhl_date
  - snapshot fields for consignee/remitter name/email/phone/address/country
  - documents (array)
- Relationships:
  - belongsTo user
  - belongsTo consignee and remitter
  - hasMany order_items, payments, shipments, payment_allocations, payment_histories
- Features depending on orders:
  - Customer order timeline and detail screens
  - Payment lifecycle and balance tracking
  - Shipping and document flows

### order_items
- Purpose:
  - Line items linking orders to vehicles.
- Key columns:
  - order_id, vehicle_id, quantity, price, discount_applied
- Relationships:
  - belongsTo order
  - belongsTo vehicle
- Features depending on order_items:
  - Cart checkout conversion to order
  - Payment and fulfillment context

### payments
- Purpose:
  - Payment attempt/confirmation records for orders.
- Key columns:
  - order_id, bank_account_id, approved_by
  - payment_method, transaction_id, amount, status, payment_data
  - payment_proof, bank_reference, paid_at
- Relationships:
  - belongsTo order
  - linked to payment_allocations and payment_history ecosystem
- Features depending on payments:
  - Payment processing, reconciliation, approval, refund handling
  - Sold-state transition via PaymentService when remaining balance reaches zero

### Related catalog and logistics tables
- makes, models:
  - Vehicle taxonomy used by both vehicles and auction_cars.
- attributes, attribute_values, model_attributes, vehicle_attribute_values:
  - Dynamic vehicle feature/attribute system.
- shipping_countries (Country model table), ports, shipping_rates:
  - Shipping pricing and destination configuration.
- consignees, remitters:
  - Reusable customer party profiles for order snapshots.
- carts:
  - Customer pre-checkout basket before order creation.

## 2) Vehicle Flow

- Vehicle creation paths:
  - Seller path: Seller VehicleController store creates vehicles with seller_id = authenticated seller.
  - Admin path: Admin VehicleController store creates vehicles, optional linking from auction_cars via auction_car_id.
- Auction linkage:
  - vehicles.auction_car_id is nullable but unique, enforcing one vehicle per auction car when linked.
  - Admin create action can be entered with auction_car_id and validates auction record readiness (make/model/chassis present, no existing linked vehicle).
- Runtime linkage behavior:
  - Vehicle model syncAuctionCarLifecycle runs on saved/deleted and triggers auction side lifecycle sync.
  - AuctionCar model syncLinkedVehicleSaleReadiness updates linked vehicle.is_ready_for_sale based on auction status.
- Duplicated fields currently present:
  - vehicles retains make/model text and also make_id/model_id catalog references.
  - vehicles has price, but runtime getter may override with auction selling_price when available.
  - vehicles maintains both stock_country text and country_id reference.

## 3) Auction Flow

- Creation and update:
  - Admin AuctionCarController handles creation, update, and batchUpdate for intake rows.
- Stored data domain:
  - Auction purchase values, logistics component costs, totals, selling_price, voyage/location metadata, and admin_notes.
- Status transitions:
  - AuctionCar model computes status in syncDerivedFields on saving:
    - completed when has linked vehicle and selling_price is not null
    - otherwise pending
- Auction effect on vehicle behavior:
  - Vehicle getPurchaseModeAttribute returns direct_purchase only when linked auction status is completed.
  - Otherwise vehicle is inquiry_only (checkout blocked; reservation path used).

## 4) Pricing System

- Price source priority:
  - Vehicle getPriceAttribute prefers auction_cars.selling_price if auction relation exists and selling_price is present.
  - Falls back to vehicles.price.
- Listing and filtering usage:
  - Admin and seller listing queries use SQL COALESCE(listing_auction_cars.selling_price, vehicles.price) for price sorting/filtering.
  - Public pages display auction selling_price first, then vehicle price.
- Checkout usage:
  - CustomerPurchaseService and CheckoutController build CIF totals using vehicle pricing plus shipping/inspection/insurance.
  - Order snapshots persist vehicle_price and logistics fields to lock purchase-time economics.

## 5) Reservation System

- Core implementation:
  - VehicleReservation model with active scope: status active and expires_at > now.
  - Vehicle has activeReservation relationship with same active criteria.
- Who creates reservations:
  - Seller route seller.reservations.store via Seller VehicleReservationController.
  - Controller validates vehicle_id and user_id and delegates to VehicleReservationService.
- Reservation conditions enforced in VehicleReservationService:
  - Vehicle row is reloaded with lockForUpdate inside DB transaction.
  - Linked auction must exist and status must not be completed.
  - Vehicle status must be published or pending.
  - Authenticated seller must own the vehicle.
  - Customer must have at least 10 completed purchases.
  - Customer must not already have another active reservation.
  - Vehicle must not already have an active reservation.
- Expiry logic:
  - Stale active records on same vehicle are marked expired before uniqueness check.
  - Scheduled command reservations:expire runs hourly from routes/console.php and marks overdue active records as expired.
- UI usage:
  - Seller Vehicles Index displays reservation state and opens reservation modal.
  - Public VehicleShow shows Reserved until timestamp when active_reservation exists.

## 6) User Roles

- Access model:
  - RoleMiddleware enforces exact role string on route groups: admin, seller, customer.

### Admin capabilities (primary controllers/actions)
- Admin VehicleController:
  - List/filter vehicles, create/edit/delete vehicles, optional auction-linked creation.
- Admin AuctionCarController:
  - Manage auction intake list and batch updates.
- Admin PaymentController, Admin OrderController, Admin ShipmentController:
  - Payment approvals/status, order management, shipment operations.
- Admin master/config controllers:
  - countries, ports, shipping rates, pricing rules, bank accounts, users, makes/models/attributes.

### Seller capabilities (primary controllers/actions)
- Seller VehicleController:
  - Seller-scoped vehicle CRUD and listing.
- Seller VehicleReservationController:
  - Create reservations for customers on eligible vehicles.
- Seller CustomerSearchController:
  - Search customer records for reservation modal.
- Seller OrderController:
  - Seller view/update order state.

### Customer capabilities (primary controllers/actions)
- Customer CheckoutController:
  - Single-vehicle purchase flow and cart checkout flow.
- Customer OrderController:
  - View orders and documents; legacy store endpoint also exists.
- Customer PaymentController:
  - Process payments and view payment history.
- Customer cart/consignee/remitter controllers:
  - Cart management and party profile management.

## 7) Current Selling Flow

- Public browsing:
  - PublicController lists published vehicles and serves vehicle detail.
- Direct purchase gate:
  - purchase_mode derived from auction status controls purchase eligibility.
  - If inquiry_only, customer checkout endpoints abort 403 with vehicle not ready message.
- Single vehicle purchase:
  - CheckoutController purchase/storePurchase delegates transaction to CustomerPurchaseService.
  - Service locks vehicle, validates availability and purchase_mode, computes shipping and CIF pricing, creates order and order_item, then creates payment.
- Cart checkout:
  - CheckoutController store computes CIF for cart items, creates order + order_items, creates payment when paymentAmount > 0, updates vehicle status for reserve/full paths per current flow.
- After payment:
  - PaymentService syncOrderPaymentTotals recalculates paid/remaining and updates order status progression.
  - When remaining balance <= 0, order item vehicles are marked stock_status sold and status sold.
- Orders and checkout state:
  - Orders, order items, payments, and shipment links are implemented and used in customer/admin/seller order pages.

## 8) Frontend Structure

- Main vehicle pages:
  - Seller Vehicles Index: tabular vehicle management, reservation column, reservation modal, customer search, reserve submit.
  - Seller Vehicle Show: detailed seller-side vehicle detail.
  - Admin Vehicles Index: table + filter heavy catalog management page.
  - Public VehicleShow: customer-facing detail, purchase eligibility message, active reservation indicator.
- Data passing pattern:
  - Controllers load relations with Inertia and pass paginated/structured props.
  - Seller index currently receives vehicles, filters, statusCounts.
  - Public show receives vehicle with auctionCar, images, attributes, activeReservation.
- Reservation UI locations:
  - Seller Vehicles Index: reserve button and modal flow.
  - Public VehicleShow: reserved-until indicator and inquiry/direct-purchase call-to-action switch.
  - Customer Checkout/Cart/Purchase pages include purchase_mode-based blocking indicators.

## 9) Dependency Map (Key Files)

- app/Models/Vehicle.php
  - Core vehicle model, price accessor preference, purchase_mode derivation, reservation relationship, auction lifecycle sync trigger.
- app/Models/AuctionCar.php
  - Auction intake model, derived status/total logic, linked vehicle readiness sync.
- app/Models/VehicleReservation.php
  - Reservation entity and active scope.
- app/Services/VehicleReservationService.php
  - Reservation validation/locking transaction and state transitions (reserve/release/convert).
- app/Services/CustomerPurchaseService.php
  - Core single-vehicle purchase transaction and order/payment creation orchestration.
- app/Services/PaymentService.php
  - Payment creation, reconciliation, order totals/status sync, sold-state transition.
- app/Http/Controllers/PublicController.php
  - Public vehicle list/detail data shaping.
- app/Http/Controllers/Seller/VehicleController.php
  - Seller vehicle listing and CRUD with reservation relation preloading.
- app/Http/Controllers/Admin/VehicleController.php
  - Admin vehicle listing/filtering and auction-linked create path.
- app/Http/Controllers/Admin/AuctionCarController.php
  - Auction intake CRUD and batch operations.
- app/Http/Controllers/Seller/VehicleReservationController.php
  - Reservation API endpoint used by seller UI modal.
- app/Http/Controllers/Customer/CheckoutController.php
  - Customer purchase and cart checkout endpoints; purchase_mode guard points.
- routes/web.php
  - Role-segmented route map and reservation/customer search route bindings.
- routes/console.php and app/Console/Commands/ExpireVehicleReservations.php
  - Reservation expiry scheduler and command.
- resources/js/Pages/Seller/Vehicles/Index.vue
  - Seller listing table with reservation UI and modal flow.
- resources/js/Pages/Admin/Vehicles/Index.vue
  - Admin listing/filter table implementation.
- resources/js/Pages/Public/VehicleShow.vue
  - Public purchasing state messaging and active reservation indicator.

## 10) Current Limitations / Gaps (Observed State)

- Schema snapshot mismatch:
  - Provided SQL dump jetstream_stable_db.sql includes vehicles/orders/payments but does not include auction_cars or vehicle_reservations create statements, while migrations/models/controllers actively use both tables.
- Mixed legacy/current order assumptions:
  - Orders migration removed vehicle_id from orders, but Customer OrderController store method still creates orders with vehicle_id in payload.
- Mixed view path conventions:
  - Admin VehicleController edit currently renders Vehicles/Edit while most admin pages use Admin-prefixed view paths.
- Ongoing dual-field model state:
  - Vehicles currently carry both text and relational catalog/location representations (make/model vs make_id/model_id, stock_country vs country_id).
- Role restriction strictness:
  - RoleMiddleware only accepts exact single-role match per route group (no multi-role expression in one middleware parameter).

## 11) Summary

- Current architecture type:
  - Role-segmented auction-driven vehicle marketplace with Inertia/Vue frontend and Laravel service-oriented transaction logic.
- What is already solid:
  - Auction-to-vehicle readiness coupling
  - Derived purchase_mode gating across backend and frontend
  - Reservation workflow with lockForUpdate, uniqueness checks, and scheduled expiry
  - Snapshot-based order pricing and payment reconciliation
- What is incomplete or uneven in current state:
  - SQL snapshot and runtime migrations are not fully aligned for auction/reservation tables
  - Some legacy controller/view references remain alongside newer model/migration structure
