# Habib Shop — Exhaustive Technology-Agnostic Backend Specification **Document Version:** 1.0.0 **Status:** Approved Technical Specification **Target Codebase:** `c:\Users\sajjadi\projects\habib shop\habib-shop` **Frontend Architecture:** Mobile-First React 19 SPA, Vite 8, React Router v7, TypeScript 7 **Scope:** 100% Frontend Source Traceability, 20 Canonical Entities, PostgreSQL DDL, JSON Schemas, 66 REST API Endpoints across 13 Functional Domains, WebSocket Contracts, and Authentication Protocols --- ## 1. Executive Summary & System Architecture ### 1.1 Architectural Purpose & Philosophy This document constitutes the definitive, technology-agnostic engineering specification for the `habib-shop` backend platform. It translates every visual layout, user interaction, client-side state variable, and static mock dataset discovered across the frontend codebase into normalized, production-grade backend contracts. The backend is architected to remain strictly **technology-agnostic**: - **Database Layer:** Standard ANSI SQL / PostgreSQL relational schema with typed primary keys, explicit foreign keys, referential cascade constraints, unique indexes, and domain enumerations. - **Document / NoSQL Representation:** JSON Schema (Draft-07) specifications for document-store implementations (MongoDB, Couchbase, PostgreSQL JSONB). - **Application Interface Layer:** RESTful HTTP API operating under `/api/v1` with standardized JSON success/paginated/error envelopes. - **Real-Time Messaging:** Bidirectional event-driven WebSocket / SSE protocol for merchant-to-customer storefront messaging, delivery receipts, and failure retry handling. ### 1.2 Mobile Viewport & Shell Constraints The frontend is built as a mobile-optimized marketplace adhering to the standard 375px mobile viewport canvas. - **Base Canvas:** 375px fixed layout width rendered via `src/components/layout/MobileShell.tsx` and `.habib-mobile-viewport` in `src/index.css`. - **Query Parameter Integration:** - `?bare=1`: Strips desktop mockup wrapping, test headers, and viewport borders (`borderRadius: 0px`). Used for embedded mobile apps or headless screenshot verification. - `?embed=1`: Configures minimal frame presentation for native container hosting. - **Responsive Handling:** Fluid vertical scrolling with fixed headers (`src/components/layout/TopHeader.tsx`), bottom navigation bar (`src/components/layout/BottomNavBar.tsx`), and sticky CTAs (`src/components/layout/StickyFooterBar.tsx`). --- ## 2. Frontend Architecture & Codebase Traceability (R1) ### 2.1 100% Source File Traceability Table (All 57 Files in `src/`) Every single source and asset file located within `c:\Users\sajjadi\projects\habib shop\habib-shop\src/` is cataloged below with its architectural role, exported identifiers, associated client routes, backend entity mappings, and required backend operations. | # | File Relative Path | Category / Architectural Role | Exported Components & Types | Associated Routes | Backend Entity Mappings | Required Backend Operations | |---|---|---|---|---|---|---| | 1 | `src/main.tsx` | App Entry Point | None (Root DOM mount) | All routes | `users`, `shopping_carts` | Session hydration, local cart token initialization | | 2 | `src/App.tsx` | Root Router & Route Declarations | `App` (default & named) | All 22 routes + fallback | All entities | Declarative routing resolution, URL param parsing | | 3 | `src/index.css` | Global CSS Reset & Tokens | None (CSS declarations) | All routes | None | Layout styling, 375px viewport enforcement | | 4 | `src/App.css` | Demo & Development Styles | None (CSS declarations) | Dev / Default | None | Utility flex styles and dev overlays | | 5 | `src/styles/tokens.css` | Design Tokens & CSS Variables | CSS Custom Properties | All routes | None | Theme palette (gold `#d78e06`, dark `#1f1f1f`) | | 6 | `src/assets/hero.png` | Static Hero Image Asset | Binary PNG | Asset Pipeline | `marketing_banners` | Static promotional fallback graphic | | 7 | `src/assets/react.svg` | Static Framework Vector | Binary SVG | Asset Pipeline | None | Framework brand icon | | 8 | `src/assets/vite.svg` | Static Bundler Vector | Binary SVG | Asset Pipeline | None | Development build tool icon | | 9 | `src/data/catalogData.ts` | Catalog Mock Registries & Models | `QuickCategoryItem`, `CompactProductItem`, `GridProductItem`, `CategoryTileItem`, `HOME_QUICK_CATEGORIES`, `HOME_POPULAR_PRODUCTS`, `HOME_NEW_STORES_PRODUCTS`, `TWO_COLUMN_GRID_PRODUCTS`, `CATEGORY_GRID_TILES` | `/shop-home`, `/shop-category`, `/shop-catitems`, `/shop-single-page`, `/shop-booth` | `categories`, `products`, `store_booths`, `wishlist_bookmarks` | Category tree queries, featured lists, product filtering | | 10 | `src/data/checkoutData.ts` | Checkout Mock Data & Schemas | `CartItemData`, `OrderSummaryBgItemData`, `OrderSummaryLineItem`, `ShippingAddressOption`, `PaymentMethodItem`, `PaymentReviewItem`, `CART_ITEMS_MAIN`, `ORDER_SUMMARY_BG_ITEMS`, `ORDER_SUMMARY_ROWS`, `BUY01_ADDRESSES`, `PAYMENT_METHODS_LIST`, `PAYMENT_REVIEW_ITEMS` | `/shop-cart`, `/shop-order-summery`, `/shop-buy01`, `/shop-payment`, `/shop-payment-methods`, `/shop-adreess` | `shopping_carts`, `cart_items`, `user_addresses`, `orders`, `order_shipments` | Cart CRUD, address selection, payment gateway list | | 11 | `src/data/ordersData.ts` | Orders & Support Data Models | `OrderFilterTabItem`, `OrderCardData`, `ShipmentCardData`, `SupportSubjectOption`, `ORDER_FILTER_TABS`, `ORDERS_LIST_CARDS`, `ORDER_DETAIL_SHIPMENTS`, `SUPPORT_SUBJECT_OPTIONS` | `/shop-orders`, `/shop-order-detail`, `/shop-support` | `orders`, `order_shipments`, `order_shipment_items`, `support_tickets`, `support_ticket_attachments` | Status filtering, 4-step stepper, dispute creation | | 12 | `src/data/accountData.ts` | User Profile & Provider Schemas | `OrderStatusCounterItem`, `AccountMenuRowItem`, `ProviderBadgeCardItem`, `ACCOUNT_ORDER_COUNTERS`, `SHOP_ACCOUNT_MENU_ROWS`, `PROVIDER_BADGE_CARDS`, `PROVIDER_SETTINGS_MENU_ROWS`, `PROVIDER_INFO_MENU_ROWS` | `/shop-account`, `/provider-requst`, `/language-setting` | `users`, `provider_applications`, `habib_coin_transactions`, `donation_campaigns` | Profile info, order counters, provider status | | 13 | `src/data/routesRegistry.ts` | Screen Registry & QA Scenarios | `ScreenRouteEntry`, `ALL_IMPLEMENTED_ROUTES` | `/test`, `PixelVerificationModal`, `TestDirectoryPage` | None (Metadata) | Screen dimension catalogs, visual regression metadata | | 14 | `src/components/layout/MobileShell.tsx` | Viewport Canvas Shell | `MobileShell` | All 19 mobile screens | None | Query parameter detection (`bare=1`, `embed=1`) | | 15 | `src/components/layout/BottomNavBar.tsx` | Sticky Bottom Navigation Bar | `BottomNavBar`, `BottomNavTab` | `/shop-home`, `/shop-category`, `/shop-account`, `/shop-cart`, `/shop-order-summery`, `/shop-payment-methods` | `shopping_carts`, `users` | Unread notifications count, active cart item count | | 16 | `src/components/layout/StatusBar.tsx` | iOS Status Bar Emulator | `StatusBar` | `/shop-home`, `/shop-single-page`, `/shop-booth`, `/shop-order-summery`, `/shop-payment-methods` | None | Client clock rendering and mobile device UI simulation | | 17 | `src/components/layout/TopHeader.tsx` | Reusable Standard Page Header | `StandardPageHeader` | `/shop-catitems`, `/shop-buy01`, `/shop-payment`, `/shop-payresult`, `/shop-orders`, `/shop-order-detail`, `/shop-support`, `/shop-adreess` | None | Navigation back button, title bar presentation | | 18 | `src/components/layout/StickyFooterBar.tsx` | Sticky Price & Action Bar | `StickyFooterBar` | `/shop-cart`, `/shop-order-summery`, `/shop-buy01`, `/shop-payment`, `/shop-payment-methods` | `shopping_carts`, `orders` | Dynamic subtotal rendering, checkout progression CTA | | 19 | `src/components/common/SearchBar.tsx` | Search Input & Filter Button | `SearchBar` | `/shop-home`, `/shop-category`, `/shop-catitems` | `products`, `store_booths`, `categories` | Unified search query, filter bottom sheet trigger | | 20 | `src/components/common/CategoryCard.tsx` | Category Grid Tile Card | `CategoryCard` | `/shop-category` | `categories` | Category selection, product count presentation | | 21 | `src/components/common/CompactProductCard.tsx` | Horizontal Product Carousel Card | `CompactProductCard` | `/shop-home`, `/shop-single-page` | `products`, `wishlist_bookmarks` | Product preview, price badge, wishlist bookmark toggle | | 22 | `src/components/common/GridProductCard.tsx` | 2-Column Product Grid Card | `GridProductCard` | `/shop-catitems`, `/shop-booth` | `products`, `wishlist_bookmarks` | Catalog grid item display, bookmark toggle, navigation | | 23 | `src/components/checkout/CartItemCard.tsx` | Main Cart Item & Steppers | `MainCartItemCard`, `OrderSummaryBgItemCard` | `/shop-cart`, `/shop-order-summery`, `/shop-payment-methods` | `cart_items`, `products`, `store_booths` | Stepper quantity update, line item deletion | | 24 | `src/components/checkout/OrderSummaryRows.tsx` | Price Breakdown Rows | `OrderSummaryRows` | `/shop-order-summery`, `/shop-payment` | `shopping_carts`, `orders` | Calculation of subtotal, shipping fee, grand total | | 25 | `src/components/checkout/AddressCard.tsx` | Shipping Address Selector Card | `AddressCard`, `AddNewAddressCard` | `/shop-buy01`, `/shop-adreess` | `user_addresses` | Address selection radio, edit/delete actions | | 26 | `src/components/checkout/PaymentMethodCard.tsx` | Payment Gateway Selector Card | `PaymentMethodCard` | `/shop-payment-methods` | `orders` | Gateway selection (Google Pay, PayPal, Mastercard) | | 27 | `src/components/checkout/ReviewItemCard.tsx` | Final Order Review Item Card | `ReviewItemCard` | `/shop-payment` | `cart_items`, `products` | Order review snapshot, unit price & quantity display | | 28 | `src/components/orders/OrderFilterTabs.tsx` | Segmented Tab Switcher | `OrderFilterTabs` | `/shop-orders` | `orders` | Segmented filter selection (Current, Delivered, Canceled) | | 29 | `src/components/orders/OrderListCard.tsx` | Order Summary List Card | `OrderListCard` | `/shop-orders` | `orders`, `order_shipments` | Order card rendering, multi-item thumbnail stacks | | 30 | `src/components/orders/ShipmentStatusCard.tsx` | 4-Stage Shipment Stepper Card | `ShipmentStatusCard` | `/shop-order-detail` | `order_shipments`, `store_booths` | Multi-vendor shipment progress (1..4 steps), tracking | | 31 | `src/components/account/OrderCounterCard.tsx` | Account Metric Counter Card | `OrderCounterCard` | `/shop-account` | `orders` | Metrics count display (In Progress, Delivered, Returned) | | 32 | `src/components/account/AccountMenuRow.tsx` | Account Settings Row Item | `AccountMenuRow` | `/shop-account`, `/provider-requst` | `users` | Settings navigation, unread badge counter display | | 33 | `src/components/account/ProviderBadgeCard.tsx` | Provider Verification Badge | `ProviderBadgeCard` | `/provider-requst` | `provider_applications` | Status display (Under Review, Request Denied, Approved) | | 34 | `src/components/account/HabibCoinsBanner.tsx` | Habib Coins Balance Card | `HabibCoinsBanner` | `/provider-requst` | `users`, `habib_coin_transactions` | Virtual coin balance display, coin purchase trigger | | 35 | `src/components/dev-click-to-component.tsx` | Alt-Click Dev IDE Bridge | `DevClickToComponent` | Dev mode global overlay | None (Local dev middleware) | POST `/api/open-in-ide` code navigation | | 36 | `src/pages/home/ShopHomePage.tsx` | Marketplace Home Screen | `ShopHomePage` | `/`, `/shop-home` | `categories`, `products`, `marketing_banners` | Home feed aggregation, quick categories, popular carousel | | 37 | `src/pages/catalog/ShopCategoryPage.tsx` | Full Categories Catalog | `ShopCategoryPage` | `/shop-category` | `categories` | 12-tile category grid query, category selection | | 38 | `src/pages/catalog/ShopCatItemsPage.tsx` | Category Product Listing | `ShopCatItemsPage` | `/shop-catitems` | `categories`, `products` | Category-filtered product grid query, sorting | | 39 | `src/pages/catalog/ShopSinglePage.tsx` | Single Product Detail Screen | `ShopSinglePage` | `/shop-single-page` | `products`, `store_booths`, `wishlist_bookmarks` | Product details, info/review tab toggle, add to cart | | 40 | `src/pages/catalog/ShopBoothPage.tsx` | Merchant Storefront View | `ShopBoothPage` | `/shop-booth` | `store_booths`, `products` | Merchant profile, stats (response time, delivery), products | | 41 | `src/pages/chat/ShopChatPage.tsx` | Direct Store Messaging | `ShopChatPage` | `/shop-chat` | `chat_conversations`, `chat_messages` | Message history, send message, retry failed, attachments | | 42 | `src/pages/checkout/ShopCartPage.tsx` | Shopping Cart Screen | `ShopCartPage` | `/shop-cart` | `shopping_carts`, `cart_items` | Multi-shop cart view, clear cart, checkout routing | | 43 | `src/pages/checkout/ShopOrderSummaryPage.tsx` | Order Summary Modal Sheet | `ShopOrderSummaryPage` | `/shop-order-summery` | `shopping_carts`, `cart_items` | Price breakdown computation, continue checkout | | 44 | `src/pages/checkout/ShopBuy01Page.tsx` | Delivery Address Selection | `ShopBuy01Page` | `/shop-buy01` | `user_addresses`, `orders` | Address selection, shipping rate selection, checkout session | | 45 | `src/pages/checkout/ShopPaymentPage.tsx` | Order Review & Confirm | `ShopPaymentPage` | `/shop-payment` | `orders`, `cart_items`, `user_addresses` | Final review of items, address, and cost totals | | 46 | `src/pages/checkout/ShopPaymentMethodsPage.tsx` | Payment Method Modal Sheet | `ShopPaymentMethodsPage` | `/shop-payment-methods` | `orders` | Gateway selection, order placement submission | | 47 | `src/pages/checkout/ShopPayResultPage.tsx` | Payment Receipt Confirmation | `ShopPayResultPage` | `/shop-payresult` | `orders` | Order confirmation receipt display, order tracking link | | 48 | `src/pages/orders/ShopOrdersPage.tsx` | Customer Orders History | `ShopOrdersPage` | `/shop-orders` | `orders`, `order_shipments` | Filtered order listing (Current, Delivered, Canceled) | | 49 | `src/pages/orders/ShopOrderDetailPage.tsx` | Multi-Shipment Stepper Screen | `ShopOrderDetailPage` | `/shop-order-detail` | `order_shipments`, `store_booths` | Multi-shipment tracking cards, carrier tracking details | | 50 | `src/pages/orders/ShopSupportPage.tsx` | Dispute Filing Form Screen | `ShopSupportPage` | `/shop-support` | `support_tickets`, `support_ticket_attachments` | 6 dispute subjects, description, media evidence upload | | 51 | `src/pages/account/ShopAccountPage.tsx` | Account Profile Dashboard | `ShopAccountPage` | `/shop-account`, `/shop-category-4214-345` | `users`, `orders` | Profile summary, order counters, settings menu rows | | 52 | `src/pages/account/ShopAddressPage.tsx` | Address Book Manager Screen | `ShopAddressPage` | `/shop-adreess` | `user_addresses` | Address list, create new address, edit/delete address | | 53 | `src/pages/account/ProviderRequestPage.tsx` | Provider Hub & Settings | `ProviderRequestPage` | `/provider-requst` | `users`, `provider_applications`, `habib_coin_transactions` | Provider profile form, status badges, coins banner, delete user | | 54 | `src/pages/account/LanguageSettingPage.tsx` | Language, Azan & Charity Hub | `LanguageSettingPage` | `/language-setting` | `users`, `donation_campaigns`, `provider_applications` | Language select, Azan city, donate campaign banner | | 55 | `src/pages/standalone/StandaloneNodesPage.tsx` | Standalone Figma Node Views | `StandaloneNodesPage`, `StandaloneNodeSlug` | `/node/:slug`, `/node/boxicons-user-filled`, etc. | None (Design verification) | Isolated UI component rendering | | 56 | `src/pages/test/PixelVerificationModal.tsx` | Visual QA Comparison Modal | `PixelVerificationModal` | Modal on `/test` | None (Test harness) | Screenshot comparison (onion-skin, side-by-side) | | 57 | `src/pages/test/TestDirectoryPage.tsx` | Screen Directory & QA Hub | `TestDirectoryPage` | `/test` | None (Test harness) | Route catalog index, filter by category | --- ### 2.2 Route Hierarchy & Navigation State Graph #### Complete Route Registry (22 Routes) | Route Path | Aliases | Target Component | Dimensions (W×H) | Modals / Overlays | Query Parameters | |---|---|---|---|---|---| | `/test` | None | `TestDirectoryPage` | 1280×Auto | `PixelVerificationModal` | `?bare=1` | | `/shop-home` | `/` | `ShopHomePage` | 375×1150 | None | `?bare=1`, `?embed=1` | | `/shop-category` | None | `ShopCategoryPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-catitems` | None | `ShopCatItemsPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-single-page` | None | `ShopSinglePage` | 375×1233 | None | `?bare=1`, `?embed=1` | | `/shop-booth` | None | `ShopBoothPage` | 375×1233 | None | `?bare=1`, `?embed=1` | | `/shop-chat` | None | `ShopChatPage` | 375×814 | 3-Dots Dropdown Menu | `?bare=1`, `?embed=1` | | `/shop-cart` | None | `ShopCartPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-order-summery`| None | `ShopOrderSummaryPage` | 375×814 | Bottom Sheet Modal | `?bare=1`, `?embed=1` | | `/shop-buy01` | None | `ShopBuy01Page` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-payment` | None | `ShopPaymentPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-payment-methods` | None | `ShopPaymentMethodsPage` | 375×814 | Bottom Sheet Modal | `?bare=1`, `?embed=1` | | `/shop-payresult` | None | `ShopPayResultPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-orders` | None | `ShopOrdersPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-order-detail`| None | `ShopOrderDetailPage` | 375×1061 | None | `?bare=1`, `?embed=1` | | `/shop-support` | None | `ShopSupportPage` | 375×1061 | None | `?bare=1`, `?embed=1` | | `/shop-account` | `/shop-category-4214-345` | `ShopAccountPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/shop-adreess` | None | `ShopAddressPage` | 375×814 | None | `?bare=1`, `?embed=1` | | `/provider-requst` | None | `ProviderRequestPage` | 375×1768 | None | `?bare=1`, `?embed=1` | | `/language-setting` | None | `LanguageSettingPage` | 375×813 | None | `?bare=1`, `?embed=1` | | `/node/:slug` | 6 node routes | `StandaloneNodesPage` | Dynamic | None | `:slug` path param | | `*` (Catch-All) | None | Redirect `/test` | — | None | Fallback | #### Complete Navigation State Machine ``` [ Marketplace Entry: /shop-home ] │ ├──► Search / Filter ───────────► /shop-category ├──► Quick Category Pills ──────► /shop-catitems (or /shop-category for 'More') ├──► Product Cards ─────────────► /shop-single-page ├──► Storefront 'See more' ─────► /shop-booth └──► Bottom Navigation Bar: ├──► Home: /shop-home ├──► Category: /shop-category ├──► Account: /shop-account └──► Cart: /shop-cart [ Category & Catalog Flow ] /shop-category (12 Grid Tiles) ──► /shop-catitems (Filtered Grid) ──► /shop-single-page [ Product & Merchant Store Flow ] /shop-single-page ──► Store Row: /shop-booth ──► Response Card: /shop-chat ──► Moderation: /shop-support └── Sticky 'Add to Cart' CTA: /shop-cart [ Cart, Breakdown & Checkout Flow ] /shop-cart ──► 'Total 4 item ^' trigger ──► /shop-order-summery (Modal Sheet) └── 'Checkout' CTA ────────────► /shop-buy01 (Delivery Address Selection) │ ├──► 'Change Adress' / 'Add New' ──► /shop-adreess └──► 'Continue' CTA ───────────────► /shop-payment (Review & Confirm) │ └──► 'Payment' CTA ──► /shop-payment-methods (Modal Sheet) │ └──► 'Purchase' CTA ──► /shop-payresult ├──► 'Track Order' ──► /shop-order-detail └──► 'Continue' ────► /shop-home [ Orders & Dispute Support Flow ] /shop-account ──► Order Status Counters / Notifications ──► /shop-orders (Current / Delivered / Canceled tabs) │ └──► 'View Details' ──► /shop-order-detail (Multi-Shipment Stepper Cards) │ └──► 'Order support' CTA ──► /shop-support (Support Ticket Form) [ Account, Provider Hub & Virtual Economy Flow ] /shop-account ──► 'Adresses' ──────────────────────────► /shop-adreess (Saved Addresses) ──► 'Edit Profile' / 'FAQ' ──────────────► /provider-requst (Provider profile, badges, wallet) ──► 'Language' / 'Become a provider' ───► /language-setting (Language overview, provider status) ──► 'Notifications' ─────────────────────► /shop-orders ──► 'Support & Requests' ────────────────► /shop-support ``` --- ## 3. Domain Data Models & Relational Database Schema (R2) ### 3.1 20 Canonical Entities & Bounded Contexts 1. **`users`**: Platform user accounts supporting customers, merchants/sellers, support agents, and admins. Stores authentication credentials, virtual coin balances, provider earnings wallet balances, and preferences. 2. **`user_addresses`**: Physical shipping and billing addresses linked to users, with support for recipient name, formatted address strings, and a strict single default address constraint. 3. **`store_booths`**: Merchant storefronts and vendor profiles with business credentials, ratings, review counts, sales history, response times, and fulfillment metric percentages. 4. **`categories`**: Hierarchical product taxonomy supporting nested categories, display icons, item counts, quick-access flags, and custom display orders. 5. **`products`**: Sellable inventory items with pricing, discounts, origin country/vendor metadata, condition indicators, processing times, and category/booth references. 6. **`product_gallery_images`**: Multi-image gallery attachments for product showcase carousels. 7. **`wishlist_bookmarks`**: User-saved product bookmarks for favorites tracking. 8. **`shopping_carts`**: Active shopping baskets supporting both authenticated users (`user_id`) and guest sessions (`session_token`). 9. **`cart_items`**: Line items inside shopping carts with quantity steppers, unit price snapshots, and product associations. 10. **`orders`**: Finalized customer orders containing order codes (e.g. `ORD-28465`), financial totals, payment status, and shipping address references. 11. **`order_shipments`**: Multi-vendor fulfillment packages splitting orders across distinct merchant booths, each tracking independent 4-step progress steppers and carrier tracking numbers. 12. **`order_shipment_items`**: Immutable product snapshots assigned to a specific shipment package. 13. **`support_tickets`**: Customer dispute claims filed against orders/products with structured subject taxonomy and resolution lifecycle states. 14. **`support_ticket_attachments`**: Multimedia evidence files (images, MP4/MPEG videos) attached to support tickets. 15. **`chat_conversations`**: 1-on-1 direct messaging threads established between users and merchant booths. 16. **`chat_messages`**: Real-time chat messages with delivery status (`sent`, `delivered`, `read`, `failed`), media attachment URLs, and voice note recordings. 17. **`provider_applications`**: Merchant onboarding applications across platform services (`habib_shop`, `habib_talk`, `hussainiyah`, `habib_meet`) with independent approval states. 18. **`habib_coin_transactions`**: Double-entry ledger recording virtual coin credits, debits, purchases, and reward distributions. 19. **`marketing_banners`**: Promotional carousel banners displayed on the marketplace home screen. 20. **`donation_campaigns`**: Philanthropic crowdfunding campaigns (such as "Donate Habib") with financial targets and current progress. --- ### 3.2 Exhaustive Field Constraints & Type Mapping Matrix | Entity | Field Name | SQL Data Type | Nullable | Default Value | Constraints & Validation | UI Source & Usage | |---|---|---|---|---|---|---| | `users` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | Session identifier | | `users` | `full_name` | `VARCHAR(120)` | No | None | Min length 2 | `ProviderRequestPage.tsx:112` | | `users` | `email` | `VARCHAR(255)` | No | None | Unique, Valid Email RFC 5322 | `ProviderRequestPage.tsx:174` | | `users` | `country_code` | `VARCHAR(5)` | No | `'+23'` | E.164 dial code prefix | `ProviderRequestPage.tsx:265` | | `users` | `phone_number` | `VARCHAR(25)` | No | None | Unique, digits only | `ProviderRequestPage.tsx:242` | | `users` | `password_hash` | `VARCHAR(255)` | No | None | Argon2id / bcrypt hash | Authentication | | `users` | `avatar_url` | `VARCHAR(500)` | Yes | Default avatar path | URI format | `ShopAccountPage.tsx:47` | | `users` | `role` | `user_role_enum` | No | `'customer'` | `'customer','seller','support_agent','admin'` | Authorization control | | `users` | `habib_coins_balance` | `INTEGER` | No | `21` | Check `>= 0` | `HabibCoinsBanner.tsx:55` | | `users` | `wallet_balance` | `DECIMAL(12, 2)`| No | `24.00` | Check `>= 0.00` | `ProviderRequestPage.tsx:442` | | `users` | `preferred_language` | `VARCHAR(10)` | No | `'en'` | ISO 639-1 code | `LanguageSettingPage.tsx:645` | | `users` | `location` | `VARCHAR(100)` | Yes | `'Tehran'` | City name | `LanguageSettingPage.tsx:734` | | `users` | `azan_location` | `VARCHAR(100)` | Yes | `'Tehran'` | City name | `LanguageSettingPage.tsx:688` | | `users` | `unread_notifications_count`| `INTEGER` | No | `2` | Check `>= 0` | `ShopHomePage.tsx:153` | | `users` | `is_active` | `BOOLEAN` | No | `TRUE` | Account status | Login check | | `user_addresses` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `AddressCard.tsx:14` | | `user_addresses` | `user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE CASCADE | Owner link | | `user_addresses` | `recipient_name` | `VARCHAR(120)` | No | None | Non-empty | `AddressCard.tsx:42` | | `user_addresses` | `street_address` | `VARCHAR(255)` | No | None | Non-empty | `AddressCard.tsx:67` | | `user_addresses` | `city` | `VARCHAR(100)` | No | None | Non-empty | `AddressCard.tsx:67` | | `user_addresses` | `state_province` | `VARCHAR(100)` | No | None | Non-empty | `AddressCard.tsx:67` | | `user_addresses` | `postal_code` | `VARCHAR(20)` | No | None | Postal code pattern | `AddressCard.tsx:67` | | `user_addresses` | `country` | `VARCHAR(100)` | No | `'United States'` | ISO country name | `AddressCard.tsx:67` | | `user_addresses` | `full_address_text`| `TEXT` | No | None | Formatted single-line text | `checkoutData.ts:137` | | `user_addresses` | `is_default` | `BOOLEAN` | No | `FALSE` | Partial unique index per user | `AddressCard.tsx:75` | | `store_booths` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShopBoothPage.tsx:11` | | `store_booths` | `owner_user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE RESTRICT | Merchant owner | | `store_booths` | `name` | `VARCHAR(150)` | No | None | Legal / Display Name | `ShopBoothPage.tsx:238` | | `store_booths` | `slug` | `VARCHAR(160)` | No | None | Unique URL slug | Routing | | `store_booths` | `avatar_url` | `VARCHAR(500)` | No | Default booth avatar | Image URI | `ShopBoothPage.tsx:210` | | `store_booths` | `banner_url` | `VARCHAR(500)` | Yes | Default booth banner | Image URI | `ShopBoothPage.tsx:150` | | `store_booths` | `country` | `VARCHAR(80)` | No | `'Iran'` | Origin country | `ShopBoothPage.tsx:254` | | `store_booths` | `city` | `VARCHAR(80)` | No | `'Tehran'` | Origin city | `ShopBoothPage.tsx:254` | | `store_booths` | `rating` | `DECIMAL(2, 1)` | No | `4.4` | Check `0.0 <= rating <= 5.0` | `ShopBoothPage.tsx:273` | | `store_booths` | `reviews_count` | `INTEGER` | No | `608` | Check `>= 0` | `ShopBoothPage.tsx:288` | | `store_booths` | `member_since_year` | `INTEGER` | No | `2008` | Year `> 1990` | `ShopBoothPage.tsx:294` | | `store_booths` | `total_sales_count` | `INTEGER` | No | `60` | Check `>= 0` | `ShopBoothPage.tsx:300` | | `store_booths` | `avg_response_time` | `VARCHAR(20)` | No | `'2h'` | Text duration | `ShopBoothPage.tsx:334` | | `store_booths` | `on_time_delivery_rate` | `DECIMAL(5, 2)`| No | `87.00` | Percentage `0.00 <= rate <= 100.00` | `ShopBoothPage.tsx:396` | | `store_booths` | `satisfaction_rate` | `DECIMAL(5, 2)`| No | `98.00` | Percentage `0.00 <= rate <= 100.00` | `ShopBoothPage.tsx:460` | | `store_booths` | `about_text` | `TEXT` | No | None | Merchant biography | `ShopBoothPage.tsx:516` | | `store_booths` | `is_verified` | `BOOLEAN` | No | `TRUE` | Verification badge flag | `ShopBoothPage.tsx:242` | | `categories` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `CategoryCard.tsx:14` | | `categories` | `parent_id` | `UUID` | Yes | `NULL` | Foreign Key -> `categories(id)` ON DELETE SET NULL | Category hierarchy | | `categories` | `name` | `VARCHAR(100)` | No | None | Category title | `catalogData.ts:51` | | `categories` | `slug` | `VARCHAR(120)` | No | None | Unique URL slug | Routing | | `categories` | `icon_small_url` | `VARCHAR(500)` | Yes | `NULL` | Quick category icon | `catalogData.ts:49` | | `categories` | `icon_large_url` | `VARCHAR(500)` | Yes | `NULL` | Grid category icon | `catalogData.ts:106` | | `categories` | `product_count` | `INTEGER` | No | `24` | Item count metric | `catalogData.ts:102` | | `categories` | `is_quick_access` | `BOOLEAN` | No | `FALSE` | Featured on home pills | `catalogData.ts:67` | | `categories` | `display_order` | `INTEGER` | No | `0` | Sort sequence | Grid sorting | | `categories` | `target_route` | `VARCHAR(255)` | No | `'/shop-catitems'` | Route path | `catalogData.ts:50` | | `products` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `CompactProductCard.tsx:13` | | `products` | `booth_id` | `UUID` | No | None | Foreign Key -> `store_booths(id)` ON DELETE CASCADE | Seller association | | `products` | `category_id` | `UUID` | No | None | Foreign Key -> `categories(id)` ON DELETE RESTRICT | Taxonomy association | | `products` | `title` | `VARCHAR(255)` | No | None | Non-empty | `catalogData.ts:65` | | `products` | `slug` | `VARCHAR(280)` | No | None | Unique URL slug | Search & URLs | | `products` | `introduction` | `TEXT` | Yes | `NULL` | Detailed description | `ShopSinglePage.tsx:645` | | `products` | `origin_country` | `VARCHAR(80)` | No | `'Iran'` | Country of origin | `catalogData.ts:67` | | `products` | `origin_vendor` | `VARCHAR(120)` | No | `'Mahan Golden'` | Supplier / Brand | `catalogData.ts:67` | | `products` | `primary_image_url` | `VARCHAR(500)` | No | None | Main image URI | `catalogData.ts:58` | | `products` | `price` | `DECIMAL(10, 2)`| No | None | Check `price >= 0.00` | `catalogData.ts:70` | | `products` | `old_price` | `DECIMAL(10, 2)`| Yes | `NULL` | Check `old_price > price` | `catalogData.ts:69` | | `products` | `discount_percentage` | `DECIMAL(5, 2)`| Yes | `NULL` | Range `0.00 <= pct <= 100.00` | `catalogData.ts:71` | | `products` | `currency` | `VARCHAR(3)` | No | `'USD'` | ISO 4217 code | Currency formatting | | `products` | `rating` | `DECIMAL(2, 1)` | Yes | `4.4` | Check `0.0 <= rating <= 5.0` | `catalogData.ts:60` | | `products` | `reviews_count` | `INTEGER` | No | `0` | Check `>= 0` | `ShopSinglePage.tsx:602` | | `products` | `condition` | `product_condition_enum`| No | `'in_stock'` | `'in_stock','out_of_stock','pre_order'` | `ShopSinglePage.tsx:312` | | `products` | `processing_time` | `VARCHAR(50)` | No | `'2–3 Days'` | Vendor lead time | `ShopSinglePage.tsx:372` | | `products` | `product_type` | `VARCHAR(80)` | No | `'Bag'` | Item category classification | `ShopSinglePage.tsx:422` | | `products` | `stock_quantity` | `INTEGER` | No | `50` | Check `>= 0` | Inventory control | | `products` | `is_popular` | `BOOLEAN` | No | `FALSE` | Featured on home carousel | `catalogData.ts:115` | | `products` | `is_new_store_product`| `BOOLEAN` | No | `FALSE` | Featured in new stores section | `catalogData.ts:172` | | `products` | `is_active` | `BOOLEAN` | No | `TRUE` | Public visibility flag | Catalog filter | | `shopping_carts` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShopCartPage.tsx:12` | | `shopping_carts` | `user_id` | `UUID` | Yes | `NULL` | Foreign Key -> `users(id)` ON DELETE CASCADE | Authenticated owner | | `shopping_carts` | `session_token` | `VARCHAR(255)` | Yes | `NULL` | Unique guest token | Anonymous basket | | `cart_items` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `CartItemCard.tsx:14` | | `cart_items` | `cart_id` | `UUID` | No | None | Foreign Key -> `shopping_carts(id)` ON DELETE CASCADE | Basket link | | `cart_items` | `product_id` | `UUID` | No | None | Foreign Key -> `products(id)` ON DELETE CASCADE | Inventory link | | `cart_items` | `quantity` | `INTEGER` | No | `1` | Check `quantity > 0` | `CartItemCard.tsx:210` | | `cart_items` | `unit_price` | `DECIMAL(10, 2)`| No | None | Price snapshot | `CartItemCard.tsx:150` | | `orders` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShopPayResultPage.tsx:9` | | `orders` | `order_code` | `VARCHAR(30)` | No | None | Unique code, e.g. `'ORD-28465'` | `ordersData.ts:199` | | `orders` | `user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE RESTRICT | Purchasing user | | `orders` | `shipping_address_id`| `UUID` | No | None | Foreign Key -> `user_addresses(id)` ON DELETE RESTRICT (immutable snapshot in shipping_address_snapshot) | Delivery target | | `orders` | `status` | `order_status_enum`| No | `'current'` | `'current','delivered','canceled'` | `ordersData.ts:184` | | `orders` | `subtotal_amount` | `DECIMAL(10, 2)`| No | None | Check `>= 0.00` | `checkoutData.ts:114` | | `orders` | `shipping_fee` | `DECIMAL(10, 2)`| No | `5.00` | Check `>= 0.00` | `checkoutData.ts:121` | | `orders` | `total_amount` | `DECIMAL(10, 2)`| No | None | Check `>= 0.00` | `checkoutData.ts:128` | | `orders` | `currency` | `VARCHAR(3)` | No | `'USD'` | ISO currency code | Currency formatting | | `orders` | `payment_provider` | `payment_provider_enum`| No | `'google_pay'` | `'google_pay','paypal','mastercard'` | `checkoutData.ts:153` | | `orders` | `payment_status` | `payment_status_enum`| No | `'authorized'` | `'pending','authorized','captured','failed'` | Financial reconciliation | | `orders` | `items_count` | `INTEGER` | No | `3` | Total item count | `ordersData.ts:204` | | `orders` | `shops_count` | `INTEGER` | No | `2` | Number of distinct vendor booths | `ordersData.ts:205` | | `order_shipments` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShipmentStatusCard.tsx:14` | | `order_shipments` | `order_id` | `UUID` | No | None | Foreign Key -> `orders(id)` ON DELETE CASCADE | Parent order | | `order_shipments` | `booth_id` | `UUID` | No | None | Foreign Key -> `store_booths(id)` ON DELETE RESTRICT | Fulfilling booth | | `order_shipments` | `status` | `shipment_status_enum`| No | `'packed'` | `'order_placed','packed','shipping','delivered','returned'` | `ordersData.ts:217` | | `order_shipments` | `completed_steps` | `INTEGER` | No | `2` | Range `1 <= steps <= 4` | `ordersData.ts:241` | | `order_shipments` | `tracking_code` | `VARCHAR(80)` | Yes | `NULL` | Carrier tracking number (e.g. `'A256542321'`) | `ordersData.ts:236` | | `order_shipments` | `shipping_carrier`| `VARCHAR(80)` | Yes | `'Standard Carrier'` | Logistics partner name | Shipping provider | | `order_shipments` | `estimated_delivery_date`| `DATE` | Yes | `NULL` | Estimated arrival date | `ordersData.ts:236` | | `order_shipment_items` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ordersData.ts:229` | | `order_shipment_items` | `shipment_id` | `UUID` | No | None | Foreign Key -> `order_shipments(id)` ON DELETE CASCADE | Parent package | | `order_shipment_items` | `product_id` | `UUID` | No | None | Foreign Key -> `products(id)` ON DELETE RESTRICT | Product reference | | `order_shipment_items` | `product_title_snapshot` | `VARCHAR(255)`| No | None | Frozen title at purchase | Snapshot | | `order_shipment_items` | `product_image_snapshot` | `VARCHAR(500)`| No | None | Frozen image at purchase | `ordersData.ts:229` | | `order_shipment_items` | `quantity` | `INTEGER` | No | `1` | Check `quantity > 0` | Quantity | | `order_shipment_items` | `unit_price` | `DECIMAL(10, 2)`| No | None | Unit price at purchase | Price snapshot | | `order_shipment_items` | `total_price` | `DECIMAL(10, 2)`| No | None | `quantity * unit_price` | Line item total | | `support_tickets` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShopSupportPage.tsx:10` | | `support_tickets` | `order_id` | `UUID` | No | None | Foreign Key -> `orders(id)` ON DELETE CASCADE | Associated order | | `support_tickets` | `product_id` | `UUID` | Yes | `NULL` | Foreign Key -> `products(id)` ON DELETE SET NULL | Disputed item | | `support_tickets` | `user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE CASCADE | Complainant | | `support_tickets` | `subject` | `support_subject_enum`| No | `'counterfeit'` | 6 standard dispute subjects | `ordersData.ts:246` | | `support_tickets` | `description` | `TEXT` | No | None | Customer explanation | `ShopSupportPage.tsx:372` | | `support_tickets` | `status` | `support_ticket_status_enum`| No | `'received'` | `'received','under_review','investigating','resolved','closed'` | Lifecycle tracking | | `support_ticket_attachments`| `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | Evidence asset | | `support_ticket_attachments`| `ticket_id` | `UUID` | No | None | Foreign Key -> `support_tickets(id)` ON DELETE CASCADE | Parent ticket | | `support_ticket_attachments`| `file_url` | `VARCHAR(500)` | No | None | Storage CDN URL | `ShopSupportPage.tsx:442` | | `support_ticket_attachments`| `file_type` | `VARCHAR(50)` | No | None | MIME type (`video/mp4`, `image/jpeg`) | Supported media formats | | `support_ticket_attachments`| `file_size_bytes`| `BIGINT` | No | None | Byte count | Max 50MB limit | | `chat_conversations` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShopChatPage.tsx:8` | | `chat_conversations` | `user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE CASCADE | Customer participant | | `chat_conversations` | `booth_id` | `UUID` | No | None | Foreign Key -> `store_booths(id)` ON DELETE CASCADE | Merchant participant | | `chat_messages` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShopChatPage.tsx:126` | | `chat_messages` | `conversation_id`| `UUID` | No | None | Foreign Key -> `chat_conversations(id)` ON DELETE CASCADE | Conversation thread | | `chat_messages` | `sender_type` | `chat_sender_type_enum`| No | None | `'user','booth','support_agent'` | Sender classification | | `chat_messages` | `sender_id` | `UUID` | No | None | Sender user or booth ID | Sender identifier | | `chat_messages` | `message_text` | `TEXT` | No | None | Message content | `ShopChatPage.tsx:288` | | `chat_messages` | `attachment_url` | `VARCHAR(500)` | Yes | `NULL` | Media attachment URL | `ShopChatPage.tsx:714` | | `chat_messages` | `voice_note_url` | `VARCHAR(500)` | Yes | `NULL` | Audio recording URL | `ShopChatPage.tsx:726` | | `chat_messages` | `status` | `chat_message_status_enum`| No | `'sent'` | `'sent','delivered','read','failed'` | `ShopChatPage.tsx:454` | | `provider_applications`| `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ProviderBadgeCard.tsx:14` | | `provider_applications`| `user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE CASCADE | Applicant | | `provider_applications`| `service_type` | `provider_service_type_enum`| No | None | `'habib_shop','habib_talk','hussainiyah','habib_meet'` | `accountData.ts:177` | | `provider_applications`| `status` | `provider_application_status_enum`| No | `'pending'` | `'pending','under_review','approved','denied'` | `accountData.ts:314` | | `habib_coin_transactions`| `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | Ledger entry | | `habib_coin_transactions`| `user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE CASCADE | Account link | | `habib_coin_transactions`| `type` | `coin_tx_type_enum`| No | None | `'purchase','reward','order_spent','donation','adjustment'` | Transaction category | | `habib_coin_transactions`| `amount` | `INTEGER` | No | None | Signed integer (positive credit, negative debit) | Ledger amount | | `habib_coin_transactions`| `balance_after` | `INTEGER` | No | None | Check `balance_after >= 0` | Post-transaction balance | | `habib_coin_transactions`| `description` | `VARCHAR(255)` | No | None | Transaction reason | Audit description | | `marketing_banners` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `ShopHomePage.tsx:190` | | `marketing_banners` | `title` | `VARCHAR(200)` | No | None | Banner headline | Campaign header | | `marketing_banners` | `banner_image_url`| `VARCHAR(500)` | No | None | Image CDN URL | `hero.png` | | `marketing_banners` | `cta_target_route`| `VARCHAR(255)` | No | `'/shop-catitems'` | Route path | Action trigger | | `marketing_banners` | `is_active` | `BOOLEAN` | No | `TRUE` | Display toggle | Active carousel filter | | `donation_campaigns` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | `LanguageSettingPage.tsx:284` | | `donation_campaigns` | `title` | `VARCHAR(150)` | No | `'Donate Habib'` | Campaign name | Campaign title | | `donation_campaigns` | `subtitle` | `VARCHAR(255)` | No | `'Help Habib''s Large-Scale project'` | Campaign tagline | `LanguageSettingPage.tsx:322` | | `donation_campaigns` | `target_amount` | `DECIMAL(12, 2)`| Yes | `100000.00` | Fundraising goal | Financial goal | | `donation_campaigns` | `current_amount`| `DECIMAL(12, 2)`| No | `14200.00` | Amount raised so far | Progress bar | | `product_gallery_images` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | Carousel gallery image ID | | `product_gallery_images` | `product_id` | `UUID` | No | None | Foreign Key -> `products(id)` ON DELETE CASCADE | Parent product association | | `product_gallery_images` | `image_url` | `VARCHAR(500)` | No | None | Valid image asset URI | `CompactProductCard.tsx:13` | | `product_gallery_images` | `display_order` | `INTEGER` | No | `0` | Sort sequence | Carousel display order | | `product_gallery_images` | `created_at` | `TIMESTAMPTZ` | No | `CURRENT_TIMESTAMP` | Timestamp | Audit timestamp | | `wishlist_bookmarks` | `id` | `UUID` | No | `uuid_generate_v4()` | Primary Key | Wishlist bookmark record ID | | `wishlist_bookmarks` | `user_id` | `UUID` | No | None | Foreign Key -> `users(id)` ON DELETE CASCADE | Bookmark owner | | `wishlist_bookmarks` | `product_id` | `UUID` | No | None | Foreign Key -> `products(id)` ON DELETE CASCADE | Saved favorite product | | `wishlist_bookmarks` | `created_at` | `TIMESTAMPTZ` | No | `CURRENT_TIMESTAMP` | Timestamp | Bookmark creation date | | `orders` | `shipping_address_snapshot` | `JSONB` | No | None | Immutable address snapshot captured at order creation | `ShopPayResultPage.tsx:9` | #### 3.2.1 Mock Data Field Discard & Presentation Reconciliation Table The 5 centralized mock data files in `src/data/*.ts` declare presentation-specific layout coordinates, pixel dimensions, and client UI styling tokens from original Figma viewport slices. The table below documents all 91 client-side layout and styling fields, detailing their UI rendering role and the architectural rationale for omitting them from persistent backend relational tables and canonical document schemas: | Source File | TypeScript Interface | Field Name | TypeScript Data Type | Classification | Discard Rationale & Presentation Handling | |---|---|---|---|---|---| | `accountData.ts` | `OrderStatusCounterItem` | `relX` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `OrderStatusCounterItem` | `labelWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `OrderStatusCounterItem` | `bgColor` | `string` | Client-Side UI Presentation / Styling Token | Client-side theme color token or CSS background fill; determined by frontend Tailwind design tokens, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `y` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `AccountMenuRowItem` | `titleWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `AccountMenuRowItem` | `titleColor` | `string` | Client-Side UI Presentation / Styling Token | Client-side theme color token or CSS background fill; determined by frontend Tailwind design tokens, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `subtitleWidth` | `number` | Client-Side UI Presentation / Styling Token | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `AccountMenuRowItem` | `iconBoxBg` | `string` | Client-Side UI Presentation / Styling Token | Client-side theme color token or CSS background fill; determined by frontend Tailwind design tokens, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `iconLeft` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `iconTop` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `iconWidth` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `iconHeight` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `badgeCount` | `string` | Client-Side UI Presentation / Styling Token | Client UI display string for mock count pill; replaced by dynamic SQL count aggregate in backend API responses, discarded from table schema. | | `accountData.ts` | `AccountMenuRowItem` | `badgeAbsX` | `number` | Client-Side Figma Layout Coordinate | Absolute pixel offset for notification or status badge on mobile viewport; handled via Tailwind flexbox/grid, discarded from database. | | `accountData.ts` | `AccountMenuRowItem` | `badgeAbsY` | `number` | Client-Side Figma Layout Coordinate | Absolute pixel offset for notification or status badge on mobile viewport; handled via Tailwind flexbox/grid, discarded from database. | | `accountData.ts` | `AccountMenuRowItem` | `rightIconType` | `'edit-path' | 'arrow-right' | 'external-link' | 'none'` | Client-Side UI Presentation / Styling Token | Client UI navigation icon discriminator; determined by static client route configuration rather than user profile record. | | `accountData.ts` | `AccountMenuRowItem` | `rightIconLeft` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `AccountMenuRowItem` | `rightIconTop` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `ProviderBadgeCardItem` | `y` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `ProviderBadgeCardItem` | `innerLeft` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `ProviderBadgeCardItem` | `innerWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `ProviderBadgeCardItem` | `statusWidth` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `accountData.ts` | `ProviderBadgeCardItem` | `titleWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `accountData.ts` | `ProviderBadgeCardItem` | `gradientBg` | `string` | Client-Side UI Presentation / Styling Token | Client-side theme color token or CSS background fill; determined by frontend Tailwind design tokens, discarded from database persistence. | | `accountData.ts` | `ProviderBadgeCardItem` | `iconLeft` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `ProviderBadgeCardItem` | `iconTop` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `ProviderBadgeCardItem` | `iconWidth` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `accountData.ts` | `ProviderBadgeCardItem` | `iconHeight` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `catalogData.ts` | `QuickCategoryItem` | `relX` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `QuickCategoryItem` | `labelLeft` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `QuickCategoryItem` | `labelWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `CompactProductItem` | `relX` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `CompactProductItem` | `relY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `CompactProductItem` | `ratingPillWidth` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `CompactProductItem` | `ratingStarLeft` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `CompactProductItem` | `ratingTextLeft` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `CompactProductItem` | `ratingTextWidth` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `CompactProductItem` | `originRelY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `GridProductItem` | `relX` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `GridProductItem` | `relY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `GridProductItem` | `imageRadius` | `number` | Client-Side Figma Layout Coordinate | Client-side border radius pixel value; styled via Tailwind CSS class rounded-lg. | | `catalogData.ts` | `GridProductItem` | `ratingPillWidth` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `GridProductItem` | `ratingStarLeft` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `GridProductItem` | `ratingTextLeft` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `GridProductItem` | `ratingTextWidth` | `number` | Client-Side Figma Layout Coordinate | Client-side pixel offset or width for SVG star and rating pill geometry; dynamically calculated in DOM/CSS, discarded from backend models. | | `catalogData.ts` | `GridProductItem` | `originRelY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `CategoryTileItem` | `y` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `CategoryTileItem` | `isRightCol` | `boolean` | Client-Side Figma Layout Coordinate | Grid column alternating index token; computed dynamically via CSS grid / flexbox modulo in React component. | | `catalogData.ts` | `CategoryTileItem` | `countBadgeLeft` | `number` | Client-Side Figma Layout Coordinate | Absolute pixel offset for notification or status badge on mobile viewport; handled via Tailwind flexbox/grid, discarded from database. | | `catalogData.ts` | `CategoryTileItem` | `innerLeft` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `CategoryTileItem` | `labelRelY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `catalogData.ts` | `CategoryTileItem` | `iconLeft` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `catalogData.ts` | `CategoryTileItem` | `iconWidth` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `catalogData.ts` | `CategoryTileItem` | `iconHeight` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `checkoutData.ts` | `CartItemData` | `y` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `CartItemData` | `titleHeight` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `CartItemData` | `titleLineHeight` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `CartItemData` | `originRelY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `OrderSummaryBgItemData` | `y` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `OrderSummaryBgItemData` | `leftIconSrc` | `string` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `checkoutData.ts` | `OrderSummaryLineItem` | `relY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `OrderSummaryLineItem` | `labelWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `ShippingAddressOption` | `relY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `ShippingAddressOption` | `nameWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `PaymentMethodItem` | `relY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `checkoutData.ts` | `PaymentReviewItem` | `relY` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `OrderFilterTabItem` | `relX` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `OrderFilterTabItem` | `labelLeft` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `OrderFilterTabItem` | `labelWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `OrderFilterTabItem` | `badgeLeft` | `number` | Client-Side Figma Layout Coordinate | Absolute pixel offset for notification or status badge on mobile viewport; handled via Tailwind flexbox/grid, discarded from database. | | `ordersData.ts` | `OrderFilterTabItem` | `hasGradientFill` | `boolean` | Client-Side Figma Layout Coordinate | Client-side theme color token or CSS background fill; determined by frontend Tailwind design tokens, discarded from database persistence. | | `ordersData.ts` | `OrderCardData` | `y` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `ShipmentCardData` | `y` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `ShipmentCardData` | `height` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `ShipmentCardData` | `innerHeight` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `ShipmentCardData` | `statusBadgeLeft` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `ShipmentCardData` | `statusBadgeWidth` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `ShipmentCardData` | `statusIconSrc` | `string` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `ShipmentCardData` | `statusIconLeft` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `ShipmentCardData` | `statusIconTop` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `ShipmentCardData` | `statusIconSize` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `ShipmentCardData` | `statusTextLeft` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `ShipmentCardData` | `statusTextWidth` | `number` | Client-Side Figma Layout Coordinate | Mobile screen coordinate or pixel dimension for order stepper status badge and icon positioning; rendered via CSS flexbox, discarded from backend. | | `ordersData.ts` | `SupportSubjectOption` | `relX` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `SupportSubjectOption` | `labelLeft` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `SupportSubjectOption` | `labelWidth` | `number` | Client-Side Figma Layout Coordinate | Absolute or relative canvas layout coordinate; discarded in favor of responsive CSS component styling in React. | | `ordersData.ts` | `SupportSubjectOption` | `iconLeft` | `number` | Client-Side Figma Layout Coordinate | Fixed pixel offset or dimension for SVG icon bounding box; replaced by responsive SVG/CSS classes, discarded from database persistence. | | `routesRegistry.ts` | `ScreenRouteEntry` | `figmaNodeId` | `string` | Client-Side Figma Layout Coordinate | Figma design canvas frame identifier and export viewport dimension; used solely by design documentation and Vite demo canvas, discarded from backend persistence. | | `routesRegistry.ts` | `ScreenRouteEntry` | `figmaName` | `string` | Client-Side Figma Layout Coordinate | Figma design canvas frame identifier and export viewport dimension; used solely by design documentation and Vite demo canvas, discarded from backend persistence. | | `routesRegistry.ts` | `ScreenRouteEntry` | `height` | `number` | Client-Side Figma Layout Coordinate | Figma design canvas frame identifier and export viewport dimension; used solely by design documentation and Vite demo canvas, discarded from backend persistence. | | `routesRegistry.ts` | `ScreenRouteEntry` | `refImage` | `string` | Client-Side Figma Layout Coordinate | Figma design canvas frame identifier and export viewport dimension; used solely by design documentation and Vite demo canvas, discarded from backend persistence. | --- ### 3.3 Relational Entity-Relationship (ER) Architecture & Cardinalities ``` [ users ] 1 ─── N [ user_addresses ] │ ├── 1 ─── N [ store_booths ] │ │ │ ├── 1 ─── N [ products ] 1 ─── N [ product_gallery_images ] │ │ │ │ │ ├── 1 ─── N [ wishlist_bookmarks ] N ─── 1 [ users ] │ │ ├── 1 ─── N [ cart_items ] N ─── 1 [ shopping_carts ] │ │ └── 1 ─── N [ order_shipment_items ] │ │ │ ├── 1 ─── N [ order_shipments ] │ │ │ │ │ └── 1 ─── N [ order_shipment_items ] │ │ │ └── 1 ─── N [ chat_conversations ] 1 ─── N [ chat_messages ] │ │ │ └── N ─── 1 [ users ] │ ├── 1 ─── 1 [ shopping_carts ] ├── 1 ─── N [ orders ] 1 ─── N [ order_shipments ] │ │ │ └── 1 ─── N [ support_tickets ] 1 ─── N [ support_ticket_attachments ] │ │ │ └── N ─── 1 [ products ] │ ├── 1 ─── N [ provider_applications ] └── 1 ─── N [ habib_coin_transactions ] [ categories ] 1 ─── N [ categories ] (Hierarchical Parent-Child Self-Reference) │ └── 1 ─── N [ products ] ``` #### Referential Cardinality & Cascade Rules 1. `users` $\rightarrow$ `user_addresses`: **1 to Many (1:N)**. Deleting a user cascade-deletes their address book (`ON DELETE CASCADE`). An order maintains an immutable address snapshot or restricts deletion of active addresses (`ON DELETE RESTRICT`). 2. `users` $\rightarrow$ `store_booths`: **1 to Many (1:N)**. An owner user owns one or more vendor booths. Restricts deletion if merchant booth has active orders (`ON DELETE RESTRICT`). 3. `categories` $\rightarrow$ `categories`: **1 to Many (1:N)**. Parent category self-reference. Deleting a parent category sets children's parent reference to null (`ON DELETE SET NULL`). 4. `store_booths` $\rightarrow$ `products`: **1 to Many (1:N)**. Products belong to a specific merchant booth (`ON DELETE CASCADE`). 5. `categories` $\rightarrow$ `products`: **1 to Many (1:N)**. Products belong to a primary taxonomy category (`ON DELETE RESTRICT`). 6. `products` $\rightarrow$ `product_gallery_images`: **1 to Many (1:N)**. Deleting a product cascade-deletes its gallery records (`ON DELETE CASCADE`). 7. `users` $\times$ `products` $\rightarrow$ `wishlist_bookmarks`: **Many to Many (M:N)**. Distinct composite unique key on `(user_id, product_id)`. 8. `shopping_carts` $\rightarrow$ `cart_items`: **1 to Many (1:N)**. Deleting a cart cascade-deletes all line items. Unique constraint on `(cart_id, product_id)`. 9. `orders` $\rightarrow$ `order_shipments`: **1 to Many (1:N)**. An order is fulfilled across multiple shipments partitioned by merchant booth (`ON DELETE CASCADE`). 10. `order_shipments` $\rightarrow$ `order_shipment_items`: **1 to Many (1:N)**. Each shipment contains immutable snapshots of the ordered products and quantities. 11. `orders` $\rightarrow$ `support_tickets`: **1 to Many (1:N)**. A customer may file dispute claims against an order or individual shipment items. 12. `support_tickets` $\rightarrow$ `support_ticket_attachments`: **1 to Many (1:N)**. Evidence files attached to a dispute ticket (`ON DELETE CASCADE`). 13. `users` $\times$ `store_booths` $\rightarrow$ `chat_conversations`: **Many to Many (M:N)**. One thread per customer-booth pair (`UNIQUE(user_id, booth_id)`). 14. `chat_conversations` $\rightarrow$ `chat_messages`: **1 to Many (1:N)**. Message stream ordered by `sent_at` timestamp. 15. `users` $\rightarrow$ `provider_applications`: **1 to Many (1:N)**. A user can apply for multiple independent service badges (`UNIQUE(user_id, service_type)`). 16. `users` $\rightarrow$ `habib_coin_transactions`: **1 to Many (1:N)**. Immutable transaction audit ledger. --- ### 3.4 Complete PostgreSQL Relational DDL (Migration-Ready) ```sql -- ============================================================================= -- HABIB SHOP RELATIONAL SCHEMA DEFINITION (PostgreSQL 14+ DDL) -- ============================================================================= CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- ----------------------------------------------------------------------------- -- DOMAIN ENUM TYPES -- ----------------------------------------------------------------------------- CREATE TYPE user_role_enum AS ENUM ('customer', 'seller', 'support_agent', 'admin'); CREATE TYPE order_status_enum AS ENUM ('current', 'delivered', 'canceled'); CREATE TYPE shipment_status_enum AS ENUM ('order_placed', 'packed', 'shipping', 'delivered', 'returned'); CREATE TYPE payment_status_enum AS ENUM ('pending', 'authorized', 'captured', 'failed', 'refunded'); CREATE TYPE payment_provider_enum AS ENUM ('google_pay', 'paypal', 'mastercard', 'apple_pay', 'cod'); CREATE TYPE support_subject_enum AS ENUM ( 'not_received', 'damaged', 'wrong_item', 'delivery_issue', 'counterfeit', 'other' ); CREATE TYPE support_ticket_status_enum AS ENUM ('received', 'under_review', 'investigating', 'resolved', 'closed'); CREATE TYPE provider_service_type_enum AS ENUM ('habib_shop', 'habib_talk', 'hussainiyah', 'habib_meet'); CREATE TYPE provider_application_status_enum AS ENUM ('pending', 'under_review', 'approved', 'denied'); CREATE TYPE chat_sender_type_enum AS ENUM ('user', 'booth', 'support_agent'); CREATE TYPE chat_message_status_enum AS ENUM ('sent', 'delivered', 'read', 'failed'); CREATE TYPE product_condition_enum AS ENUM ('in_stock', 'out_of_stock', 'pre_order', 'back_order'); CREATE TYPE coin_tx_type_enum AS ENUM ('purchase', 'reward', 'order_spent', 'donation', 'adjustment'); -- ----------------------------------------------------------------------------- -- 1. USERS & PROFILES TABLE -- ----------------------------------------------------------------------------- CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), full_name VARCHAR(120) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, country_code VARCHAR(5) NOT NULL DEFAULT '+23', phone_number VARCHAR(25) NOT NULL UNIQUE, password_hash VARCHAR(255) NOT NULL, avatar_url VARCHAR(500) DEFAULT '/assets/images/icon-account-avatar-gold.svg', role user_role_enum NOT NULL DEFAULT 'customer', habib_coins_balance INTEGER NOT NULL DEFAULT 21 CHECK (habib_coins_balance >= 0), wallet_balance DECIMAL(12, 2) NOT NULL DEFAULT 24.00 CHECK (wallet_balance >= 0.00), preferred_language VARCHAR(10) NOT NULL DEFAULT 'en', location VARCHAR(100) DEFAULT 'Tehran', azan_location VARCHAR(100) DEFAULT 'Tehran', unread_notifications_count INTEGER NOT NULL DEFAULT 2 CHECK (unread_notifications_count >= 0), is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_users_phone ON users(phone_number); -- ----------------------------------------------------------------------------- -- 2. USER ADDRESSES TABLE -- ----------------------------------------------------------------------------- CREATE TABLE user_addresses ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, recipient_name VARCHAR(120) NOT NULL, street_address VARCHAR(255) NOT NULL, city VARCHAR(100) NOT NULL, state_province VARCHAR(100) NOT NULL, postal_code VARCHAR(20) NOT NULL, country VARCHAR(100) NOT NULL DEFAULT 'United States', additional_notes VARCHAR(255), full_address_text TEXT NOT NULL, is_default BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_addresses_user ON user_addresses(user_id); CREATE UNIQUE INDEX idx_default_address_per_user ON user_addresses (user_id) WHERE is_default = TRUE; -- ----------------------------------------------------------------------------- -- 3. STORE BOOTHS (MERCHANTS) TABLE -- ----------------------------------------------------------------------------- CREATE TABLE store_booths ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), owner_user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, name VARCHAR(150) NOT NULL, slug VARCHAR(160) NOT NULL UNIQUE, avatar_url VARCHAR(500) NOT NULL DEFAULT '/assets/images/avatar-tashakol-booth.png', banner_url VARCHAR(500) DEFAULT '/assets/images/bg-booth-calligraphy-header.png', country VARCHAR(80) NOT NULL DEFAULT 'Iran', city VARCHAR(80) NOT NULL DEFAULT 'Tehran', flag_icon_url VARCHAR(500) DEFAULT '/assets/images/icon-flag-iran-19.svg', rating DECIMAL(2, 1) NOT NULL DEFAULT 4.4 CHECK (rating >= 0.0 AND rating <= 5.0), reviews_count INTEGER NOT NULL DEFAULT 608 CHECK (reviews_count >= 0), member_since_year INTEGER NOT NULL DEFAULT 2008, total_sales_count INTEGER NOT NULL DEFAULT 60 CHECK (total_sales_count >= 0), avg_response_time VARCHAR(20) NOT NULL DEFAULT '2h', on_time_delivery_rate DECIMAL(5, 2) NOT NULL DEFAULT 87.00 CHECK (on_time_delivery_rate >= 0.00 AND on_time_delivery_rate <= 100.00), satisfaction_rate DECIMAL(5, 2) NOT NULL DEFAULT 98.00 CHECK (satisfaction_rate >= 0.00 AND satisfaction_rate <= 100.00), about_text TEXT NOT NULL, is_verified BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_booths_slug ON store_booths(slug); CREATE INDEX idx_booths_owner ON store_booths(owner_user_id); -- ----------------------------------------------------------------------------- -- 4. CATEGORIES (TAXONOMY) TABLE -- ----------------------------------------------------------------------------- CREATE TABLE categories ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), parent_id UUID REFERENCES categories(id) ON DELETE SET NULL, name VARCHAR(100) NOT NULL, slug VARCHAR(120) NOT NULL UNIQUE, description TEXT, icon_small_url VARCHAR(500), icon_large_url VARCHAR(500), product_count INTEGER NOT NULL DEFAULT 24 CHECK (product_count >= 0), is_quick_access BOOLEAN NOT NULL DEFAULT FALSE, display_order INTEGER NOT NULL DEFAULT 0, target_route VARCHAR(255) NOT NULL DEFAULT '/shop-catitems', created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_categories_slug ON categories(slug); CREATE INDEX idx_categories_parent ON categories(parent_id); -- ----------------------------------------------------------------------------- -- 5. PRODUCTS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE products ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), booth_id UUID NOT NULL REFERENCES store_booths(id) ON DELETE CASCADE, category_id UUID NOT NULL REFERENCES categories(id) ON DELETE RESTRICT, title VARCHAR(255) NOT NULL, slug VARCHAR(280) NOT NULL UNIQUE, introduction TEXT, origin_country VARCHAR(80) NOT NULL DEFAULT 'Iran', origin_vendor VARCHAR(120) NOT NULL DEFAULT 'Mahan Golden', primary_image_url VARCHAR(500) NOT NULL, price DECIMAL(10, 2) NOT NULL CHECK (price >= 0.00), old_price DECIMAL(10, 2) CHECK (old_price IS NULL OR old_price > price), discount_percentage DECIMAL(5, 2) CHECK (discount_percentage IS NULL OR (discount_percentage >= 0.00 AND discount_percentage <= 100.00)), currency VARCHAR(3) NOT NULL DEFAULT 'USD', rating DECIMAL(2, 1) DEFAULT 4.4 CHECK (rating IS NULL OR (rating >= 0.0 AND rating <= 5.0)), reviews_count INTEGER NOT NULL DEFAULT 0 CHECK (reviews_count >= 0), condition product_condition_enum NOT NULL DEFAULT 'in_stock', processing_time VARCHAR(50) NOT NULL DEFAULT '2–3 Days', product_type VARCHAR(80) NOT NULL DEFAULT 'Bag', stock_quantity INTEGER NOT NULL DEFAULT 50 CHECK (stock_quantity >= 0), is_popular BOOLEAN NOT NULL DEFAULT FALSE, is_new_store_product BOOLEAN NOT NULL DEFAULT FALSE, is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_products_booth ON products(booth_id); CREATE INDEX idx_products_category ON products(category_id); CREATE INDEX idx_products_popular ON products(is_popular) WHERE is_popular = TRUE; CREATE INDEX idx_products_price ON products(price); -- ----------------------------------------------------------------------------- -- 6. PRODUCT GALLERY IMAGES TABLE -- ----------------------------------------------------------------------------- CREATE TABLE product_gallery_images ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), product_id UUID NOT NULL REFERENCES products(id) ON DELETE CASCADE, image_url VARCHAR(500) NOT NULL, display_order INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_gallery_product ON product_gallery_images(product_id); -- ----------------------------------------------------------------------------- -- 7. WISHLIST BOOKMARKS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE wishlist_bookmarks ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, product_id UUID NOT NULL REFERENCES products(id) ON DELETE CASCADE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE(user_id, product_id) ); CREATE INDEX idx_wishlist_user ON wishlist_bookmarks(user_id); -- ----------------------------------------------------------------------------- -- 8. SHOPPING CARTS & CART ITEMS -- ----------------------------------------------------------------------------- CREATE TABLE shopping_carts ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID REFERENCES users(id) ON DELETE CASCADE, session_token VARCHAR(255) UNIQUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT chk_cart_owner CHECK (user_id IS NOT NULL OR session_token IS NOT NULL), CONSTRAINT uq_shopping_carts_user UNIQUE (user_id) ); CREATE TABLE cart_items ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), cart_id UUID NOT NULL REFERENCES shopping_carts(id) ON DELETE CASCADE, product_id UUID NOT NULL REFERENCES products(id) ON DELETE CASCADE, quantity INTEGER NOT NULL DEFAULT 1 CHECK (quantity > 0), unit_price DECIMAL(10, 2) NOT NULL CHECK (unit_price >= 0.00), created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE(cart_id, product_id) ); CREATE INDEX idx_cart_items_cart ON cart_items(cart_id); -- ----------------------------------------------------------------------------- -- 9. ORDERS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE orders ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), order_code VARCHAR(30) NOT NULL UNIQUE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, shipping_address_id UUID NOT NULL REFERENCES user_addresses(id) ON DELETE RESTRICT, -- Address Snapshotting: Immutable address snapshot captured at order creation to preserve delivery history if user_addresses is modified shipping_address_snapshot JSONB NOT NULL, status order_status_enum NOT NULL DEFAULT 'current', subtotal_amount DECIMAL(10, 2) NOT NULL CHECK (subtotal_amount >= 0.00), shipping_fee DECIMAL(10, 2) NOT NULL DEFAULT 5.00 CHECK (shipping_fee >= 0.00), total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0.00), currency VARCHAR(3) NOT NULL DEFAULT 'USD', payment_provider payment_provider_enum NOT NULL DEFAULT 'google_pay', payment_status payment_status_enum NOT NULL DEFAULT 'authorized', payment_reference VARCHAR(100), items_count INTEGER NOT NULL DEFAULT 3 CHECK (items_count > 0), shops_count INTEGER NOT NULL DEFAULT 2 CHECK (shops_count > 0), placed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_orders_user ON orders(user_id); CREATE INDEX idx_orders_code ON orders(order_code); CREATE INDEX idx_orders_status ON orders(status); -- ----------------------------------------------------------------------------- -- 10. ORDER SHIPMENTS TABLE (MULTI-VENDOR SPLIT) -- ----------------------------------------------------------------------------- CREATE TABLE order_shipments ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), order_id UUID NOT NULL REFERENCES orders(id) ON DELETE CASCADE, booth_id UUID NOT NULL REFERENCES store_booths(id) ON DELETE RESTRICT, status shipment_status_enum NOT NULL DEFAULT 'packed', completed_steps INTEGER NOT NULL DEFAULT 2 CHECK (completed_steps BETWEEN 1 AND 4), tracking_code VARCHAR(80), shipping_carrier VARCHAR(80) DEFAULT 'Standard Carrier', order_date DATE NOT NULL DEFAULT CURRENT_DATE, estimated_delivery_date DATE, actual_delivery_date DATE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_shipments_order ON order_shipments(order_id); CREATE INDEX idx_shipments_booth ON order_shipments(booth_id); -- ----------------------------------------------------------------------------- -- 11. ORDER SHIPMENT ITEMS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE order_shipment_items ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), shipment_id UUID NOT NULL REFERENCES order_shipments(id) ON DELETE CASCADE, product_id UUID NOT NULL REFERENCES products(id) ON DELETE RESTRICT, product_title_snapshot VARCHAR(255) NOT NULL, product_image_snapshot VARCHAR(500) NOT NULL, quantity INTEGER NOT NULL CHECK (quantity > 0), unit_price DECIMAL(10, 2) NOT NULL CHECK (unit_price >= 0.00), total_price DECIMAL(10, 2) NOT NULL CHECK (total_price >= 0.00), created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_shipment_items_shipment ON order_shipment_items(shipment_id); -- ----------------------------------------------------------------------------- -- 12. SUPPORT TICKETS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE support_tickets ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), order_id UUID NOT NULL REFERENCES orders(id) ON DELETE CASCADE, product_id UUID REFERENCES products(id) ON DELETE SET NULL, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, subject support_subject_enum NOT NULL DEFAULT 'counterfeit', description TEXT NOT NULL, status support_ticket_status_enum NOT NULL DEFAULT 'received', resolution_notes TEXT, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_support_tickets_order ON support_tickets(order_id); CREATE INDEX idx_support_tickets_user ON support_tickets(user_id); -- ----------------------------------------------------------------------------- -- 13. SUPPORT TICKET ATTACHMENTS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE support_ticket_attachments ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), ticket_id UUID NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE, file_url VARCHAR(500) NOT NULL, file_type VARCHAR(50) NOT NULL, file_size_bytes BIGINT NOT NULL, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_support_attachments_ticket ON support_ticket_attachments(ticket_id); -- ----------------------------------------------------------------------------- -- 14. CHAT CONVERSATIONS & MESSAGES -- ----------------------------------------------------------------------------- CREATE TABLE chat_conversations ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, booth_id UUID NOT NULL REFERENCES store_booths(id) ON DELETE CASCADE, last_message_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE(user_id, booth_id) ); CREATE TABLE chat_messages ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), conversation_id UUID NOT NULL REFERENCES chat_conversations(id) ON DELETE CASCADE, sender_type chat_sender_type_enum NOT NULL, sender_id UUID NOT NULL, message_text TEXT NOT NULL, attachment_url VARCHAR(500), voice_note_url VARCHAR(500), status chat_message_status_enum NOT NULL DEFAULT 'sent', sent_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_chat_messages_conv ON chat_messages(conversation_id); CREATE INDEX idx_chat_messages_time ON chat_messages(sent_at); -- ----------------------------------------------------------------------------- -- 15. PROVIDER MULTI-SERVICE APPLICATIONS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE provider_applications ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, service_type provider_service_type_enum NOT NULL, status provider_application_status_enum NOT NULL DEFAULT 'pending', applied_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, reviewed_at TIMESTAMP WITH TIME ZONE, reviewer_notes TEXT, UNIQUE(user_id, service_type) ); CREATE INDEX idx_provider_apps_user ON provider_applications(user_id); -- ----------------------------------------------------------------------------- -- 16. HABIB COIN TRANSACTIONS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE habib_coin_transactions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, type coin_tx_type_enum NOT NULL, amount INTEGER NOT NULL, balance_after INTEGER NOT NULL CHECK (balance_after >= 0), description VARCHAR(255) NOT NULL, reference_id VARCHAR(100), created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_coin_tx_user ON habib_coin_transactions(user_id); -- ----------------------------------------------------------------------------- -- 17. MARKETING BANNERS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE marketing_banners ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), campaign_tag VARCHAR(100) NOT NULL DEFAULT 'Habib Shop', title VARCHAR(200) NOT NULL, subtitle VARCHAR(255), banner_image_url VARCHAR(500) NOT NULL, cta_label VARCHAR(60) NOT NULL DEFAULT 'Explore Products', cta_target_route VARCHAR(255) NOT NULL DEFAULT '/shop-catitems', display_order INTEGER NOT NULL DEFAULT 1, is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); -- ----------------------------------------------------------------------------- -- 18. DONATION CAMPAIGNS TABLE -- ----------------------------------------------------------------------------- CREATE TABLE donation_campaigns ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), title VARCHAR(150) NOT NULL DEFAULT 'Donate Habib', subtitle VARCHAR(255) NOT NULL DEFAULT 'Help Habib''s Large-Scale project', icon_url VARCHAR(500) DEFAULT '/assets/images/icon-donate-heart-gold.svg', cta_label VARCHAR(50) NOT NULL DEFAULT 'Donate', target_amount DECIMAL(12, 2) DEFAULT 100000.00, current_amount DECIMAL(12, 2) DEFAULT 14200.00, is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); ``` --- ### 3.5 Technology-Agnostic JSON Schemas (Draft-07) All 20 canonical domain entities are formally specified below as technology-agnostic JSON Schemas conforming strictly to Draft-07 (`http://json-schema.org/draft-07/schema#`). These models define the valid document structures exchanged across REST endpoints, WebSocket events, and persistence boundaries without placeholders, ellipsis truncations, or undefined fields. #### 1. User Document Schema (users) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "UserDocument", "type": "object", "required": [ "id", "fullName", "email", "countryCode", "phoneNumber", "role", "habibCoinsBalance", "walletBalance", "preferredLanguage", "unreadNotificationsCount", "isActive", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "fullName": { "type": "string", "minLength": 2, "maxLength": 120 }, "email": { "type": "string", "format": "email" }, "countryCode": { "type": "string", "maxLength": 5 }, "phoneNumber": { "type": "string", "pattern": "^[0-9+]+$", "maxLength": 25 }, "avatarUrl": { "type": [ "string", "null" ] }, "role": { "type": "string", "enum": [ "customer", "seller", "support_agent", "admin" ] }, "habibCoinsBalance": { "type": "integer", "minimum": 0 }, "walletBalance": { "type": "number", "minimum": 0 }, "preferredLanguage": { "type": "string", "maxLength": 10 }, "location": { "type": [ "string", "null" ] }, "azanLocation": { "type": [ "string", "null" ] }, "unreadNotificationsCount": { "type": "integer", "minimum": 0 }, "isActive": { "type": "boolean" }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 2. User Address Document Schema (user_addresses) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "UserAddressDocument", "type": "object", "required": [ "id", "userId", "recipientName", "streetAddress", "city", "stateProvince", "postalCode", "country", "fullAddressText", "isDefault", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "userId": { "type": "string", "format": "uuid" }, "recipientName": { "type": "string", "minLength": 1, "maxLength": 120 }, "streetAddress": { "type": "string", "minLength": 1, "maxLength": 255 }, "city": { "type": "string", "minLength": 1, "maxLength": 100 }, "stateProvince": { "type": "string", "minLength": 1, "maxLength": 100 }, "postalCode": { "type": "string", "minLength": 1, "maxLength": 20 }, "country": { "type": "string", "maxLength": 100 }, "fullAddressText": { "type": "string" }, "isDefault": { "type": "boolean" }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 3. Store Booth Document Schema (store_booths) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "StoreBoothDocument", "type": "object", "required": [ "id", "ownerUserId", "name", "slug", "avatarUrl", "country", "city", "rating", "reviewsCount", "memberSinceYear", "totalSalesCount", "avgResponseTime", "onTimeDeliveryRate", "satisfactionRate", "aboutText", "isVerified", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "ownerUserId": { "type": "string", "format": "uuid" }, "name": { "type": "string", "minLength": 1, "maxLength": 150 }, "slug": { "type": "string", "minLength": 1, "maxLength": 160 }, "avatarUrl": { "type": "string" }, "bannerUrl": { "type": [ "string", "null" ] }, "country": { "type": "string", "maxLength": 80 }, "city": { "type": "string", "maxLength": 80 }, "rating": { "type": "number", "minimum": 0, "maximum": 5 }, "reviewsCount": { "type": "integer", "minimum": 0 }, "memberSinceYear": { "type": "integer", "minimum": 1990 }, "totalSalesCount": { "type": "integer", "minimum": 0 }, "avgResponseTime": { "type": "string", "maxLength": 20 }, "onTimeDeliveryRate": { "type": "number", "minimum": 0, "maximum": 100 }, "satisfactionRate": { "type": "number", "minimum": 0, "maximum": 100 }, "aboutText": { "type": "string" }, "isVerified": { "type": "boolean" }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 4. Category Document Schema (categories) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "CategoryDocument", "type": "object", "required": [ "id", "name", "slug", "productCount", "isQuickAccess", "displayOrder", "targetRoute", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "parentId": { "type": [ "string", "null" ] }, "name": { "type": "string", "minLength": 1, "maxLength": 100 }, "slug": { "type": "string", "minLength": 1, "maxLength": 120 }, "iconSmallUrl": { "type": [ "string", "null" ] }, "iconLargeUrl": { "type": [ "string", "null" ] }, "productCount": { "type": "integer", "minimum": 0 }, "isQuickAccess": { "type": "boolean" }, "displayOrder": { "type": "integer" }, "targetRoute": { "type": "string", "maxLength": 255 }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 5. Product Document Schema (products) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ProductDocument", "type": "object", "required": [ "id", "title", "slug", "price", "currency", "condition", "booth", "category" ], "properties": { "id": { "type": "string", "format": "uuid" }, "title": { "type": "string", "minLength": 1, "maxLength": 255 }, "slug": { "type": "string" }, "introduction": { "type": "string" }, "origin": { "type": "object", "required": [ "country", "vendor" ], "properties": { "country": { "type": "string" }, "vendor": { "type": "string" } } }, "images": { "type": "object", "required": [ "primary" ], "properties": { "primary": { "type": "string" }, "gallery": { "type": "array", "items": { "type": "string" } } } }, "price": { "type": "number", "minimum": 0 }, "oldPrice": { "type": [ "number", "null" ] }, "discountPercentage": { "type": [ "number", "null" ] }, "currency": { "type": "string", "default": "USD" }, "rating": { "type": [ "number", "null" ], "minimum": 0, "maximum": 5 }, "reviewsCount": { "type": "integer", "minimum": 0 }, "condition": { "type": "string", "enum": [ "in_stock", "out_of_stock", "pre_order", "back_order" ] }, "processingTime": { "type": "string" }, "productType": { "type": "string" }, "stockQuantity": { "type": "integer", "minimum": 0 }, "isPopular": { "type": "boolean" }, "isNewStoreProduct": { "type": "boolean" }, "hasBookmark": { "type": "boolean" }, "category": { "type": "object", "required": [ "id", "name", "slug" ], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "slug": { "type": "string" } } }, "booth": { "type": "object", "required": [ "id", "name", "avatarUrl" ], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "avatarUrl": { "type": "string" }, "location": { "type": "string" }, "rating": { "type": "number" } } } } } ``` #### 6. Product Gallery Image Document Schema (product_gallery_images) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ProductGalleryImageDocument", "type": "object", "required": [ "id", "productId", "imageUrl", "displayOrder", "createdAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "productId": { "type": "string", "format": "uuid" }, "imageUrl": { "type": "string" }, "displayOrder": { "type": "integer", "minimum": 0 }, "createdAt": { "type": "string", "format": "date-time" } } } ``` #### 7. Wishlist Bookmark Document Schema (wishlist_bookmarks) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "WishlistBookmarkDocument", "type": "object", "required": [ "id", "userId", "productId", "createdAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "userId": { "type": "string", "format": "uuid" }, "productId": { "type": "string", "format": "uuid" }, "createdAt": { "type": "string", "format": "date-time" } } } ``` #### 8. Shopping Cart Document Schema (shopping_carts) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ShoppingCartDocument", "type": "object", "required": [ "id", "items", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "userId": { "type": [ "string", "null" ] }, "sessionToken": { "type": [ "string", "null" ] }, "items": { "type": "array", "items": { "type": "object", "required": [ "id", "cartId", "productId", "quantity", "unitPrice", "totalPrice" ], "properties": { "id": { "type": "string" }, "cartId": { "type": "string" }, "productId": { "type": "string" }, "title": { "type": "string" }, "imageSrc": { "type": "string" }, "quantity": { "type": "integer", "minimum": 1 }, "unitPrice": { "type": "number", "minimum": 0 }, "totalPrice": { "type": "number", "minimum": 0 } } } }, "subtotal": { "type": "number", "minimum": 0 }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 9. Cart Item Document Schema (cart_items) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "CartItemDocument", "type": "object", "required": [ "id", "cartId", "productId", "quantity", "unitPrice", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "cartId": { "type": "string", "format": "uuid" }, "productId": { "type": "string", "format": "uuid" }, "quantity": { "type": "integer", "minimum": 1 }, "unitPrice": { "type": "number", "minimum": 0 }, "totalPrice": { "type": "number", "minimum": 0 }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 10. Order Document Schema (orders) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "OrderDocument", "type": "object", "required": [ "id", "orderCode", "userId", "status", "financials", "payment", "shippingAddress", "shipments" ], "properties": { "id": { "type": "string", "format": "uuid" }, "orderCode": { "type": "string" }, "userId": { "type": "string", "format": "uuid" }, "status": { "type": "string", "enum": [ "current", "delivered", "canceled" ] }, "placedAt": { "type": "string", "format": "date-time" }, "financials": { "type": "object", "required": [ "subtotal", "shippingFee", "total", "currency" ], "properties": { "subtotal": { "type": "number", "minimum": 0 }, "shippingFee": { "type": "number", "minimum": 0 }, "total": { "type": "number", "minimum": 0 }, "currency": { "type": "string" } } }, "payment": { "type": "object", "required": [ "provider", "status" ], "properties": { "provider": { "type": "string", "enum": [ "google_pay", "paypal", "mastercard", "apple_pay", "cod" ] }, "status": { "type": "string", "enum": [ "pending", "authorized", "captured", "failed", "refunded" ] }, "reference": { "type": [ "string", "null" ] } } }, "shippingAddress": { "type": "object", "required": [ "recipientName", "streetAddress", "city", "state", "postalCode", "country" ], "properties": { "recipientName": { "type": "string" }, "streetAddress": { "type": "string" }, "city": { "type": "string" }, "state": { "type": "string" }, "postalCode": { "type": "string" }, "country": { "type": "string" }, "formattedAddress": { "type": "string" } } }, "shipments": { "type": "array", "items": { "type": "object", "required": [ "id", "boothId", "boothName", "status", "completedSteps", "items" ], "properties": { "id": { "type": "string" }, "boothId": { "type": "string" }, "boothName": { "type": "string" }, "boothAvatar": { "type": "string" }, "status": { "type": "string", "enum": [ "order_placed", "packed", "shipping", "delivered", "returned" ] }, "completedSteps": { "type": "integer", "minimum": 1, "maximum": 4 }, "trackingCode": { "type": [ "string", "null" ] }, "shippingCarrier": { "type": [ "string", "null" ] }, "estimatedDelivery": { "type": [ "string", "null" ] }, "items": { "type": "array", "items": { "type": "object", "required": [ "productId", "title", "imageSrc", "quantity", "unitPrice", "totalPrice" ], "properties": { "productId": { "type": "string" }, "title": { "type": "string" }, "imageSrc": { "type": "string" }, "quantity": { "type": "integer", "minimum": 1 }, "unitPrice": { "type": "number", "minimum": 0 }, "totalPrice": { "type": "number", "minimum": 0 } } } } } } } } } ``` #### 11. Order Shipment Document Schema (order_shipments) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "OrderShipmentDocument", "type": "object", "required": [ "id", "orderId", "boothId", "status", "completedSteps", "items", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "orderId": { "type": "string", "format": "uuid" }, "boothId": { "type": "string", "format": "uuid" }, "status": { "type": "string", "enum": [ "order_placed", "packed", "shipping", "delivered", "returned" ] }, "completedSteps": { "type": "integer", "minimum": 1, "maximum": 4 }, "trackingCode": { "type": [ "string", "null" ] }, "shippingCarrier": { "type": [ "string", "null" ] }, "estimatedDeliveryDate": { "type": [ "string", "null" ] }, "items": { "type": "array", "items": { "type": "object", "required": [ "id", "productId", "productTitleSnapshot", "productImageSnapshot", "quantity", "unitPrice", "totalPrice" ], "properties": { "id": { "type": "string" }, "productId": { "type": "string" }, "productTitleSnapshot": { "type": "string" }, "productImageSnapshot": { "type": "string" }, "quantity": { "type": "integer", "minimum": 1 }, "unitPrice": { "type": "number", "minimum": 0 }, "totalPrice": { "type": "number", "minimum": 0 } } } }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 12. Order Shipment Item Document Schema (order_shipment_items) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "OrderShipmentItemDocument", "type": "object", "required": [ "id", "shipmentId", "productId", "productTitleSnapshot", "productImageSnapshot", "quantity", "unitPrice", "totalPrice", "createdAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "shipmentId": { "type": "string", "format": "uuid" }, "productId": { "type": "string", "format": "uuid" }, "productTitleSnapshot": { "type": "string", "minLength": 1, "maxLength": 255 }, "productImageSnapshot": { "type": "string" }, "quantity": { "type": "integer", "minimum": 1 }, "unitPrice": { "type": "number", "minimum": 0 }, "totalPrice": { "type": "number", "minimum": 0 }, "createdAt": { "type": "string", "format": "date-time" } } } ``` #### 13. Support Ticket Document Schema (support_tickets) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "SupportTicketDocument", "type": "object", "required": [ "id", "orderId", "userId", "subject", "description", "status", "attachments", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "orderId": { "type": "string", "format": "uuid" }, "productId": { "type": [ "string", "null" ] }, "userId": { "type": "string", "format": "uuid" }, "subject": { "type": "string", "enum": [ "counterfeit", "not_received", "damaged", "wrong_item", "billing_issue", "other" ] }, "description": { "type": "string", "minLength": 1 }, "status": { "type": "string", "enum": [ "received", "under_review", "investigating", "resolved", "closed" ] }, "attachments": { "type": "array", "items": { "type": "object", "required": [ "id", "fileUrl", "fileType", "fileSizeBytes" ], "properties": { "id": { "type": "string" }, "fileUrl": { "type": "string" }, "fileType": { "type": "string" }, "fileSizeBytes": { "type": "integer", "minimum": 1 } } } }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 14. Support Ticket Attachment Document Schema (support_ticket_attachments) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "SupportTicketAttachmentDocument", "type": "object", "required": [ "id", "ticketId", "fileUrl", "fileType", "fileSizeBytes", "createdAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "ticketId": { "type": "string", "format": "uuid" }, "fileUrl": { "type": "string" }, "fileType": { "type": "string", "enum": [ "image/jpeg", "image/png", "image/webp", "video/mp4", "video/mpeg", "application/pdf" ] }, "fileSizeBytes": { "type": "integer", "minimum": 1, "maximum": 52428800 }, "createdAt": { "type": "string", "format": "date-time" } } } ``` #### 15. Chat Conversation Document Schema (chat_conversations) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ChatConversationDocument", "type": "object", "required": [ "id", "userId", "boothId", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "userId": { "type": "string", "format": "uuid" }, "boothId": { "type": "string", "format": "uuid" }, "lastMessage": { "type": [ "object", "null" ], "properties": { "id": { "type": "string" }, "messageText": { "type": "string" }, "senderType": { "type": "string" }, "sentAt": { "type": "string", "format": "date-time" } } }, "unreadCount": { "type": "integer", "minimum": 0 }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 16. Chat Message Document Schema (chat_messages) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ChatMessageDocument", "type": "object", "required": [ "id", "conversationId", "senderType", "senderId", "messageText", "status", "createdAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "conversationId": { "type": "string", "format": "uuid" }, "senderType": { "type": "string", "enum": [ "user", "booth", "support_agent" ] }, "senderId": { "type": "string", "format": "uuid" }, "messageText": { "type": "string" }, "attachmentUrl": { "type": [ "string", "null" ] }, "voiceNoteUrl": { "type": [ "string", "null" ] }, "status": { "type": "string", "enum": [ "sent", "delivered", "read", "failed" ] }, "createdAt": { "type": "string", "format": "date-time" } } } ``` #### 17. Provider Application Document Schema (provider_applications) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ProviderApplicationDocument", "type": "object", "required": [ "id", "userId", "serviceType", "status", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "userId": { "type": "string", "format": "uuid" }, "serviceType": { "type": "string", "enum": [ "habib_shop", "habib_talk", "hussainiyah", "habib_meet" ] }, "status": { "type": "string", "enum": [ "pending", "under_review", "approved", "denied" ] }, "submittedData": { "type": [ "object", "null" ] }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` #### 18. Habib Coin Transaction Document Schema (habib_coin_transactions) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "HabibCoinTransactionDocument", "type": "object", "required": [ "id", "userId", "type", "amount", "balanceAfter", "description", "createdAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "userId": { "type": "string", "format": "uuid" }, "type": { "type": "string", "enum": [ "purchase", "reward", "order_spent", "donation", "adjustment" ] }, "amount": { "type": "integer" }, "balanceAfter": { "type": "integer", "minimum": 0 }, "description": { "type": "string", "maxLength": 255 }, "createdAt": { "type": "string", "format": "date-time" } } } ``` #### 19. Marketing Banner Document Schema (marketing_banners) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "MarketingBannerDocument", "type": "object", "required": [ "id", "title", "bannerImageUrl", "ctaTargetRoute", "isActive", "createdAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "title": { "type": "string", "minLength": 1, "maxLength": 200 }, "bannerImageUrl": { "type": "string" }, "ctaTargetRoute": { "type": "string", "maxLength": 255 }, "isActive": { "type": "boolean" }, "createdAt": { "type": "string", "format": "date-time" } } } ``` #### 20. Donation Campaign Document Schema (donation_campaigns) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "DonationCampaignDocument", "type": "object", "required": [ "id", "title", "subtitle", "currentAmount", "createdAt", "updatedAt" ], "properties": { "id": { "type": "string", "format": "uuid" }, "title": { "type": "string", "minLength": 1, "maxLength": 150 }, "subtitle": { "type": "string", "minLength": 1, "maxLength": 255 }, "targetAmount": { "type": [ "number", "null" ], "minimum": 0 }, "currentAmount": { "type": "number", "minimum": 0 }, "createdAt": { "type": "string", "format": "date-time" }, "updatedAt": { "type": "string", "format": "date-time" } } } ``` --- ## 4. REST API Endpoint Contracts (R3) ### 4.1 Global Conventions & Envelope Standard All endpoints are namespaced under `/api/v1`. Communication is strictly HTTPS JSON with UTF-8 encoding. Standard authentication headers follow the Bearer JWT convention: `Authorization: Bearer `. #### Standard Success Response ```json { "success": true, "data": {}, "meta": { "timestamp": "2026-10-28T08:00:00.000Z", "requestId": "req_847294819" } } ``` #### Standard Paginated Response ```json { "success": true, "data": [], "pagination": { "page": 1, "limit": 10, "totalItems": 48, "totalPages": 5, "hasNextPage": true, "hasPrevPage": false }, "meta": { "timestamp": "2026-10-28T08:00:00.000Z", "requestId": "req_847294820" } } ``` #### Standard Error Response ```json { "success": false, "error": { "code": "RESOURCE_NOT_FOUND", "message": "The requested entity was not found.", "details": [ { "field": "addressId", "issue": "Address addr-999 does not exist for this account." } ] }, "meta": { "timestamp": "2026-10-28T08:00:00.000Z", "requestId": "req_847294821" } } ``` ### 4.2 Standard HTTP Status Code & Error Taxonomy | Status Code | Error Code Identifier | Meaning & Application Scenario | |---|---|---| | `200 OK` | `SUCCESS` | Request succeeded; response contains requested data payload. | | `201 Created` | `CREATED` | Resource successfully created (address, order, review, support ticket). | | `400 Bad Request` | `VALIDATION_FAILED` | Malformed body, missing required fields, or illegal argument. | | `401 Unauthorized` | `UNAUTHORIZED` | Missing, expired, or invalid Bearer authentication token. | | `403 Forbidden` | `ACTION_FORBIDDEN` | Authenticated user lacks permission to access or modify resource. | | `404 Not Found` | `RESOURCE_NOT_FOUND` | Target entity ID does not exist in the database. | | `409 Conflict` | `STATE_CONFLICT` | Resource collision (e.g. email in use, concurrent cart mutation). | | `413 Payload Too Large`| `PAYLOAD_TOO_LARGE` | Uploaded image or video exceeds max allowed size (50MB). | | `415 Unsupported Media`| `UNSUPPORTED_MEDIA`| Attachment MIME type is not allowed (must be mp4, mpeg, jpeg, png). | | `422 Unprocessable` | `BUSINESS_RULE_VIOLATION`| Semantically invalid request (e.g. deleting default address). | | `500 Server Error` | `INTERNAL_SERVER_ERROR` | Unhandled platform error or database failure. | --- ### 4.3 Domain 1: Authentication & User Profile Management ### Endpoint 1: `POST /api/v1/auth/login` - **Domain:** Authentication & Session - **Purpose:** Authenticate user account using phone OTP or email credentials. - **Frontend Callers:** Login Modal, `ShopAccountPage.tsx:151`. - **Request Body JSON Schema:** ```json { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": ["identifier", "authMethod"], "properties": { "identifier": { "type": "string" }, "authMethod": { "type": "string", "enum": ["phone_otp", "password"] }, "otp": { "type": "string" }, "password": { "type": "string" } } } ``` - **Request Example:** ```json { "identifier": "09102036523", "authMethod": "phone_otp", "otp": "491823" } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3ItMTAxIn0.sample_signature", "refreshToken": "rt_live_948271049281729", "user": { "id": "usr-101", "fullName": "Habib shoper", "phone": "+2309102036523", "email": "Ahdart14@gmail.com", "avatarUrl": "/assets/images/avatar-provider-ahd-art.png" } } } ``` - **Error States:** `400 VALIDATION_FAILED`, `401 INVALID_CREDENTIALS`. ### Endpoint 2: `POST /api/v1/auth/logout` - **Domain:** Authentication & Session - **Purpose:** Invalidate active Bearer session and revoke refresh token. - **Frontend Callers:** `ShopAccountPage.tsx:151` ("Sign out" menu row), `ProviderRequestPage.tsx:68`. - **Request Parameters:** None (Bearer token in header). - **Response Example (200 OK):** ```json { "success": true, "data": { "message": "User session invalidated successfully." } } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 3: `POST /api/v1/auth/refresh` - **Domain:** Authentication & Session - **Purpose:** Issue a new short-lived access token using a valid refresh token. - **Frontend Callers:** API Client Token Interceptor. - **Request Body Example:** ```json { "refreshToken": "rt_live_948271049281729" } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.newToken123.sample", "expiresIn": 3600 } } ``` - **Error States:** `401 TOKEN_EXPIRED_OR_INVALID`. ### Endpoint 4: `GET /api/v1/users/me/profile` - **Domain:** User Profile - **Purpose:** Retrieve full profile of authenticated user including balances and preferences. - **Frontend Callers:** `ShopAccountPage.tsx:15`, `ProviderRequestPage.tsx:16`, `LanguageSettingPage.tsx:8`. - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "usr-101", "fullName": "Habib shoper", "email": "Ahdart14@gmail.com", "countryCode": "+23", "phoneNumber": "09102036523", "avatarUrl": "/assets/images/avatar-provider-ahd-art.png", "role": "customer", "habibCoinsBalance": 21, "walletBalance": 24.00, "unreadNotificationsCount": 2, "preferences": { "language": "en", "location": "Tehran", "azanLocation": "Tehran" } } } ``` - **Error States:** `401 UNAUTHORIZED`, `404 RESOURCE_NOT_FOUND`. ### Endpoint 5: `PUT /api/v1/users/me/profile` - **Domain:** User Profile - **Purpose:** Update user personal information (full name, phone, email). - **Frontend Callers:** `ProviderRequestPage.tsx:112-296`. - **Request Body Example:** ```json { "fullName": "Habib shoper", "email": "Ahdart14@gmail.com", "countryCode": "+23", "phoneNumber": "09102036523" } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "usr-101", "fullName": "Habib shoper", "email": "Ahdart14@gmail.com", "countryCode": "+23", "phoneNumber": "09102036523", "updatedAt": "2026-10-28T08:15:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED`, `409 STATE_CONFLICT` (email or phone already registered). ### Endpoint 6: `POST /api/v1/users/me/avatar` - **Domain:** User Profile - **Purpose:** Upload and associate a new user avatar photo. - **Frontend Callers:** `ProviderRequestPage.tsx:68` (camera edit badge). - **Request Format:** `multipart/form-data` with field `file`. - **Response Example (200 OK):** ```json { "success": true, "data": { "avatarUrl": "https://cdn.habibshop.com/avatars/usr-101-avatar.png" } } ``` - **Error States:** `400 VALIDATION_FAILED`, `413 PAYLOAD_TOO_LARGE` (max 5MB), `415 UNSUPPORTED_MEDIA`. ### Endpoint 7: `PATCH /api/v1/users/me/preferences` - **Domain:** User Profile & Localization - **Purpose:** Update language and prayer/Azan calculation location. - **Frontend Callers:** `LanguageSettingPage.tsx:623-771`. - **Request Body Example:** ```json { "preferredLanguage": "en", "location": "Tehran", "azanLocation": "Tehran" } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "preferredLanguage": "en", "location": "Tehran", "azanLocation": "Tehran", "updatedAt": "2026-10-28T08:16:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED`. ### Endpoint 8: `DELETE /api/v1/users/me` - **Domain:** User Profile & Account Lifecycle - **Purpose:** Permanently close account and schedule GDPR data erasure. - **Frontend Callers:** `ProviderRequestPage.tsx:516-586` ("Delete Account" row). - **Request Body:** `{}` (Authenticated request). - **Response Example (200 OK):** ```json { "success": true, "data": { "message": "Account has been scheduled for permanent deletion." } } ``` - **Error States:** `401 UNAUTHORIZED`, `403 ACTION_FORBIDDEN` (active unfulfilled orders). --- ### 4.4 Domain 2: Shipping Addresses Management ### Endpoint 9: `GET /api/v1/users/me/addresses` - **Domain:** Shipping Addresses - **Purpose:** Retrieve all saved shipping addresses for current account. - **Frontend Callers:** `ShopAddressPage.tsx:13`, `ShopBuy01Page.tsx:12`, `ShopPaymentPage.tsx:132`. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "addr-1", "recipientName": "Ali Ghaderi", "streetAddress": "250 Park Avenue South", "city": "New York", "stateProvince": "NY", "postalCode": "10003", "country": "United States", "fullAddressText": "250 Park Avenue South, New York, NY 10003 United States", "isDefault": true }, { "id": "addr-2", "recipientName": "Sina Sajjadi", "streetAddress": "250 Park Avenue South, right hand straight", "city": "New York", "stateProvince": "NY", "postalCode": "10003", "country": "United States", "fullAddressText": "250 Park Avenue South, New York, NY 10003 United States right hand strahgt", "isDefault": false } ] } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 10: `POST /api/v1/users/me/addresses` - **Domain:** Shipping Addresses - **Purpose:** Create a new delivery address entry. - **Frontend Callers:** `ShopAddressPage.tsx:50`, `ShopBuy01Page.tsx:93` ("Add New adress"). - **Request Body Example:** ```json { "recipientName": "Sina Sajjadi", "streetAddress": "250 Park Avenue South", "city": "New York", "stateProvince": "NY", "postalCode": "10003", "country": "United States", "additionalNotes": "Leave at front desk", "isDefault": false } ``` - **Response Example (201 Created):** ```json { "success": true, "data": { "id": "addr-3", "recipientName": "Sina Sajjadi", "fullAddressText": "250 Park Avenue South, New York, NY 10003 United States", "isDefault": false, "createdAt": "2026-10-28T08:18:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED` (missing recipientName or streetAddress). ### Endpoint 11: `GET /api/v1/users/me/addresses/{id}` - **Domain:** Shipping Addresses - **Purpose:** Fetch a single shipping address by unique identifier. - **Frontend Callers:** `ShopAddressPage.tsx:40`. - **Path Parameters:** `id` (UUID or string address ID). - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "addr-1", "recipientName": "Ali Ghaderi", "streetAddress": "250 Park Avenue South", "city": "New York", "stateProvince": "NY", "postalCode": "10003", "country": "United States", "fullAddressText": "250 Park Avenue South, New York, NY 10003 United States", "isDefault": true } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 12: `PUT /api/v1/users/me/addresses/{id}` - **Domain:** Shipping Addresses - **Purpose:** Update existing shipping address fields. - **Frontend Callers:** `ShopAddressPage.tsx:40` (address edit action). - **Request Body Example:** ```json { "recipientName": "Ali Ghaderi", "streetAddress": "250 Park Avenue South, Suite 400", "city": "New York", "stateProvince": "NY", "postalCode": "10003", "country": "United States", "isDefault": true } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "addr-1", "recipientName": "Ali Ghaderi", "fullAddressText": "250 Park Avenue South, Suite 400, New York, NY 10003 United States", "isDefault": true, "updatedAt": "2026-10-28T08:20:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED`, `404 RESOURCE_NOT_FOUND`. ### Endpoint 13: `DELETE /api/v1/users/me/addresses/{id}` - **Domain:** Shipping Addresses - **Purpose:** Remove a saved address from the address book. - **Frontend Callers:** `ShopAddressPage.tsx:40` (address delete action). - **Response Example (200 OK):** ```json { "success": true, "data": { "message": "Address addr-2 removed successfully." } } ``` - **Error States:** `400 BUSINESS_RULE_VIOLATION` (cannot delete only default address), `404 RESOURCE_NOT_FOUND`. ### Endpoint 14: `PATCH /api/v1/users/me/addresses/{id}/default` - **Domain:** Shipping Addresses - **Purpose:** Promote an address to the active default shipping address. - **Frontend Callers:** `ShopBuy01Page.tsx:85-91` (radio card selection). - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "addr-1", "isDefault": true } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. --- ### 4.5 Domain 3: Categories & Catalog Discovery ### Endpoint 15: `GET /api/v1/categories` - **Domain:** Catalog Discovery - **Purpose:** Retrieve the full 12-tile category catalog with item counts. - **Frontend Callers:** `ShopCategoryPage.tsx:14-18`, `CategoryCard.tsx:14`. - **Query Parameters:** `includeCounts` (boolean, default: `true`). - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "cat-bag", "slug": "bag", "name": "Bag", "itemCount": 24, "iconSrc": "/assets/images/icon-cat-bag-large.svg", "displayOrder": 1, "targetRoute": "/shop-catitems" }, { "id": "cat-home-living", "slug": "home-living", "name": "Home & Living", "itemCount": 24, "iconSrc": "/assets/images/icon-cat-refrigerator-large.svg", "displayOrder": 2, "targetRoute": "/shop-catitems" }, { "id": "cat-beauty", "slug": "beauty", "name": "Beauty", "itemCount": 24, "iconSrc": "/assets/images/icon-cat-cosmetic-large.svg", "displayOrder": 3, "targetRoute": "/shop-catitems" }, { "id": "cat-art-handicrafts", "slug": "art-handicrafts", "name": "Art & Handicrafts", "itemCount": 24, "iconSrc": "/assets/images/icon-cat-palette-large.svg", "displayOrder": 4, "targetRoute": "/shop-catitems" } ] } ``` - **Error States:** None. ### Endpoint 16: `GET /api/v1/categories/{id}` - **Domain:** Catalog Discovery - **Purpose:** Retrieve single category metadata and child subcategory tree. - **Frontend Callers:** `ShopCatItemsPage.tsx:11`. - **Path Parameters:** `id` (UUID or slug, e.g. `cat-home-living`). - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "cat-home-living", "name": "Home & Living", "slug": "home-living", "itemCount": 24, "iconLargeUrl": "/assets/images/icon-cat-refrigerator-large.svg", "subcategories": [] } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 17: `GET /api/v1/catalog/quick-categories` - **Domain:** Catalog Discovery - **Purpose:** Return the 5 circular quick categories for home screen shortcuts. - **Frontend Callers:** `ShopHomePage.tsx:345-402`. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "cat-bag", "label": "Bag", "iconSrc": "/assets/images/icon-cat-bag-small.svg", "targetRoute": "/shop-catitems" }, { "id": "cat-beauty", "label": "Beauty & ...", "iconSrc": "/assets/images/icon-cat-cosmetic-small.svg", "targetRoute": "/shop-catitems" }, { "id": "cat-home", "label": "Home & Living", "iconSrc": "/assets/images/icon-cat-refrigerator-small.svg", "targetRoute": "/shop-catitems" }, { "id": "cat-art", "label": "Art & Handicrafts", "iconSrc": "/assets/images/icon-cat-palette-small.svg", "targetRoute": "/shop-catitems" }, { "id": "cat-more", "label": "More", "iconSrc": "/assets/images/icon-cat-more-dots.svg", "targetRoute": "/shop-category" } ] } ``` - **Error States:** None. --- ### 4.6 Domain 4: Product Catalog, Search & Bookmarks ### Endpoint 18: `GET /api/v1/products` - **Domain:** Product Catalog - **Purpose:** Paginated product listing filtered by category, vendor booth, or search query. - **Frontend Callers:** `ShopCatItemsPage.tsx:21-33`, `GridProductCard.tsx:14`. - **Query Parameters:** - `categoryId` (string, optional) - `boothId` (string, optional) - `sortBy` (`popularity`, `price_asc`, `price_desc`, `rating`, `newest`, default: `popularity`) - `page` (integer, default: 1) - `limit` (integer, default: 6) - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "grid-1", "title": "Islam in the Biblebran Transfer Book", "titleLines": 2, "origin": "Iran | Mahan Golden", "originCountry": "Iran", "originVendor": "Mahan Golden", "imageSrc": "/assets/images/product-brown-leather-bag.png", "price": "$24.00", "priceAmount": 24.00, "currency": "USD", "oldPrice": null, "discountBadge": null, "rating": "5", "ratingValue": 5.0, "hasBookmark": true }, { "id": "grid-2", "title": "Boby Bag", "titleLines": 1, "origin": "Iran | Mahan Golden", "originCountry": "Iran", "originVendor": "Mahan Golden", "imageSrc": "/assets/images/product-black-tshirt-flat.png", "price": "$24.00", "priceAmount": 24.00, "currency": "USD", "oldPrice": "$28.50", "discountBadge": "20%", "rating": "1.5", "ratingValue": 1.5, "hasBookmark": true } ], "pagination": { "page": 1, "limit": 6, "totalItems": 24, "totalPages": 4, "hasNextPage": true, "hasPrevPage": false } } ``` - **Error States:** None (returns empty array if no items match). ### Endpoint 19: `GET /api/v1/products/popular` - **Domain:** Product Catalog - **Purpose:** Retrieve curated popular products for home and product detail carousels. - **Frontend Callers:** `ShopHomePage.tsx:406-484`, `ShopSinglePage.tsx:738-816`. - **Query Parameters:** `limit` (integer, default: 3). - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "pop-1", "title": "Islam in the Biblebran Transfer Book", "origin": "Iran | Mahan Golden", "imageSrc": "/assets/images/product-brown-leather-bag.png", "price": "$24.00", "rating": "5", "hasBookmark": true }, { "id": "pop-2", "title": "Boby Bag", "origin": "Iran | Mahan Golden", "imageSrc": "/assets/images/product-boby-backpack.png", "price": "$24.00", "oldPrice": "$28.50", "discountBadge": "20%", "rating": "1.5", "hasBookmark": true } ] } ``` - **Error States:** None. ### Endpoint 20: `GET /api/v1/products/new-stores` - **Domain:** Product Catalog - **Purpose:** Retrieve showcase products from newly onboarded merchant booths. - **Frontend Callers:** `ShopHomePage.tsx:487-566`. - **Query Parameters:** `limit` (integer, default: 3). - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "store-1", "title": "Espoong Black Tshirt", "origin": "Iran | Mahan Golden", "imageSrc": "/assets/images/product-black-tshirt-model.png", "price": "$24.00", "oldPrice": "$28.50", "discountBadge": "20%", "rating": "4.8", "hasBookmark": true } ] } ``` - **Error States:** None. ### Endpoint 21: `GET /api/v1/catalog/search` - **Domain:** Catalog Discovery - **Purpose:** Multi-facet unified search across products, merchant booths, and categories. - **Frontend Callers:** `SearchBar.tsx:12`, `ShopHomePage.tsx:184`, `ShopCatItemsPage.tsx:18`. - **Query Parameters:** `q` (string, required), `type` (`all`, `products`, `stores`, `categories`, default: `all`), `limit` (default: 10). - **Response Example (200 OK):** ```json { "success": true, "data": { "products": [ { "id": "prod-101", "title": "Islam in the Bible Book", "price": "$24.00", "imageSrc": "/assets/images/product-grey-tshirt-model.png" } ], "stores": [ { "id": "store-al-hujjah", "name": "Al-Hujjah Books", "avatarUrl": "/assets/images/avatar-al-hujjah-books.png" } ], "categories": [ { "id": "cat-art-handicrafts", "name": "Art & Handicrafts" } ] } } ``` - **Error States:** `400 VALIDATION_FAILED` (empty query). ### Endpoint 22: `GET /api/v1/products/{id}` - **Domain:** Product Catalog - **Purpose:** Full single product details, hero gallery, attributes, and merchant booth card. - **Frontend Callers:** `ShopSinglePage.tsx:11-951`. - **Path Parameters:** `id` (product UUID or string). - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "prod-single-001", "title": "Islam in the Bible Book", "breadcrumbs": "Leather accessories and supplies / Leather bags", "heroImages": [ "/assets/images/product-duffel-bag-hero.png" ], "price": "$24.00", "oldPrice": "$28.50", "discountBadge": "20%", "rating": "4.4", "reviewsCount": 3, "hasBookmark": true, "condition": "In Stock", "processingTime": "2–3 Days", "productType": "Bag", "booth": { "id": "store-al-hujjah", "name": "Al-Hujjah Books", "avatarUrl": "/assets/images/avatar-al-hujjah-books.png", "location": "Qom, Iran", "rating": 4.2, "memberSince": "Since 2008" }, "information": { "category": "Art & Handicrafts", "introduction": "Mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit." } } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 23: `GET /api/v1/products/{id}/reviews` - **Domain:** Product Catalog & Reviews - **Purpose:** Retrieve customer reviews and star ratings for a specific product. - **Frontend Callers:** `ShopSinglePage.tsx:599-616` (Review tab). - **Path Parameters:** `id` (product ID). - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "rev-1", "author": "Mohammad R.", "rating": 5, "date": "2026-03-10", "comment": "Exceptional quality and authentic print." } ] } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 24: `POST /api/v1/products/{id}/reviews` - **Domain:** Product Catalog & Reviews - **Purpose:** Submit user review rating and comment text. - **Frontend Callers:** Product Review Modal. - **Request Body Example:** ```json { "rating": 5, "comment": "Exceptional quality and authentic print." } ``` - **Response Example (201 Created):** ```json { "success": true, "data": { "id": "rev-1", "rating": 5, "createdAt": "2026-10-28T08:25:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED`, `401 UNAUTHORIZED`. ### Endpoint 25: `GET /api/v1/bookmarks` - **Domain:** Wishlist & Bookmarks - **Purpose:** Fetch the user's saved wishlist products. - **Frontend Callers:** `ShopAccountPage.tsx`, Wishlist View. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "productId": "prod-101", "title": "Islam in the Bible Book", "imageSrc": "/assets/images/product-brown-leather-bag.png", "price": "$24.00" } ] } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 26: `POST /api/v1/bookmarks/{productId}` - **Domain:** Wishlist & Bookmarks - **Purpose:** Save a product to user wishlist bookmarks. - **Frontend Callers:** `CompactProductCard.tsx:53`, `GridProductCard.tsx:53`, `ShopSinglePage.tsx:184`. - **Response Example (200 OK):** ```json { "success": true, "data": { "productId": "prod-101", "bookmarked": true } } ``` - **Error States:** `401 UNAUTHORIZED`, `404 RESOURCE_NOT_FOUND`. ### Endpoint 27: `DELETE /api/v1/bookmarks/{productId}` - **Domain:** Wishlist & Bookmarks - **Purpose:** Remove product from wishlist bookmarks. - **Frontend Callers:** `CompactProductCard.tsx:53`, `ShopSinglePage.tsx:184`. - **Response Example (200 OK):** ```json { "success": true, "data": { "productId": "prod-101", "bookmarked": false } } ``` - **Error States:** `401 UNAUTHORIZED`, `404 RESOURCE_NOT_FOUND`. --- ### 4.7 Domain 5: Storefront & Merchant Booths ### Endpoint 28: `GET /api/v1/stores` - **Domain:** Merchant Storefronts - **Purpose:** Directory list of active merchant booths. - **Frontend Callers:** Merchant Discovery Directory. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "store-al-hujjah", "name": "Al-Hujjah Books", "avatarUrl": "/assets/images/avatar-al-hujjah-books.png", "rating": 4.4, "totalSales": 60 } ] } ``` - **Error States:** None. ### Endpoint 29: `GET /api/v1/stores/{id}` - **Domain:** Merchant Storefronts - **Purpose:** Detailed merchant profile, response time, delivery rate, and satisfaction score. - **Frontend Callers:** `ShopBoothPage.tsx:11-574`. - **Path Parameters:** `id` (booth UUID or slug). - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "store-al-hujjah", "name": "TashakolFarzandan Rohhallah", "displayName": "Al-Hujjah Books", "avatarUrl": "/assets/images/avatar-tashakol-booth.png", "bannerUrl": "/assets/images/bg-booth-calligraphy-header.png", "country": "Iran", "city": "Tehran", "flagIconUrl": "/assets/images/icon-flag-iran-19.svg", "rating": 4.4, "reviewsCount": 608, "membershipDuration": "+1 year membership", "totalSales": "+60 sales", "metrics": { "avgResponseTime": "2h", "onTimeDeliveryRate": "87%", "satisfactionRate": "98%" }, "about": "In this room, we are going to talk about raising children from the perspective of Islam and the Ahl al-Bayt..." } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 30: `GET /api/v1/stores/{id}/products` - **Domain:** Merchant Storefronts - **Purpose:** Paginated product catalog belonging to a specific merchant booth. - **Frontend Callers:** `ShopBoothPage.tsx:558-571`. - **Query Parameters:** `page`, `limit` (default: 6). - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "grid-1", "title": "Islam in the Biblebran Transfer Book", "imageSrc": "/assets/images/product-brown-leather-bag.png", "price": "$24.00", "rating": "5" } ], "pagination": { "page": 1, "limit": 6, "totalItems": 6, "totalPages": 1, "hasNextPage": false, "hasPrevPage": false } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. --- ### 4.8 Domain 6: Real-Time Store Chat & Messaging ### Endpoint 31: `GET /api/v1/chat/conversations` - **Domain:** In-App Chat - **Purpose:** Retrieve list of user's active direct chat threads with merchant booths. - **Frontend Callers:** Chat Inbox / Header Message Counter. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "conversationId": "conv-8491", "booth": { "id": "store-al-hujjah", "name": "Al-Hujjah Books", "avatarUrl": "/assets/images/avatar-al-hujjah-books.png" }, "lastMessage": { "text": "Hey, How are you?", "timestamp": "2026-10-28T08:12:00.000Z", "unread": false } } ] } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 32: `GET /api/v1/chat/conversations/{conversationId}/messages` - **Domain:** In-App Chat - **Purpose:** Retrieve historical chat message stream grouped by date with delivery receipts. - **Frontend Callers:** `ShopChatPage.tsx:126-424`. - **Query Parameters:** `beforeMessageId` (string, optional), `limit` (integer, default: 30). - **Response Example (200 OK):** ```json { "success": true, "data": { "store": { "id": "store-al-hujjah", "name": "Al-Hujjah Books", "location": "Qom, Iran", "avatarUrl": "/assets/images/avatar-al-hujjah-books.png" }, "messages": [ { "id": "msg-1", "sender": "booth", "text": "Hey, How are you?", "timestamp": "2026-10-27T22:13:00.000Z", "timeDisplay": "22:13", "dateGroup": "Yesterday", "status": "delivered" }, { "id": "msg-4", "sender": "user", "text": "are you?", "timestamp": "2026-10-28T22:13:00.000Z", "timeDisplay": "22:13", "dateGroup": "Today", "status": "sent" }, { "id": "msg-5", "sender": "user", "text": "Hey, How are you?", "timestamp": "2026-10-28T22:13:00.000Z", "timeDisplay": "22:13", "dateGroup": "Today", "status": "failed", "error": "Message delivery timed out." } ] } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 33: `POST /api/v1/chat/conversations/{conversationId}/messages` - **Domain:** In-App Chat - **Purpose:** Send a new chat message to a merchant booth. - **Frontend Callers:** `ShopChatPage.tsx:740-752` (orange send button). - **Request Body Example:** ```json { "messageText": "Are you able to deliver the transfer book by next Monday?", "attachmentUrl": null, "voiceNoteUrl": null } ``` - **Response Example (201 Created):** ```json { "success": true, "data": { "id": "msg-6", "conversationId": "conv-8491", "senderType": "user", "messageText": "Are you able to deliver the transfer book by next Monday?", "status": "delivered", "sentAt": "2026-10-28T08:30:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED` (empty text and no attachment), `403 ACTION_FORBIDDEN`. ### Endpoint 34: `POST /api/v1/chat/messages/{messageId}/resend` - **Domain:** In-App Chat - **Purpose:** Retry dispatch of a previously failed chat message. - **Frontend Callers:** `ShopChatPage.tsx:427-466` ("Try Again" button in red bubble). - **Path Parameters:** `messageId` (string). - **Response Example (200 OK):** ```json { "success": true, "data": { "id": "msg-5", "status": "delivered", "sentAt": "2026-10-28T08:31:00.000Z" } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 35: `POST /api/v1/chat/attachments` - **Domain:** In-App Chat - **Purpose:** Upload chat media file or voice note recording. - **Frontend Callers:** `ShopChatPage.tsx:714-738` (paperclip and mic action buttons). - **Request Format:** `multipart/form-data` with `file`. - **Response Example (200 OK):** ```json { "success": true, "data": { "attachmentUrl": "https://cdn.habibshop.com/chat/audio_record_9281.mp3", "mimeType": "audio/mp3", "fileSizeBytes": 184920 } } ``` - **Error States:** `413 PAYLOAD_TOO_LARGE` (max 25MB), `415 UNSUPPORTED_MEDIA`. ### Endpoint 36: `PATCH /api/v1/chat/conversations/{conversationId}/read` - **Domain:** In-App Chat - **Purpose:** Mark all incoming messages in a conversation as read. - **Frontend Callers:** `ShopChatPage.tsx:8` (component mount). - **Response Example (200 OK):** ```json { "success": true, "data": { "markedReadCount": 3 } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. --- ### 4.9 Domain 7: Shopping Cart Operations ### Endpoint 37: `GET /api/v1/cart` - **Domain:** Shopping Cart - **Purpose:** Retrieve active cart, items grouped across merchant booths, and subtotal. - **Frontend Callers:** `ShopCartPage.tsx:12-83`, `ShopOrderSummaryPage.tsx:58-75`. - **Response Example (200 OK):** ```json { "success": true, "data": { "cartId": "cart-8491", "totalItemsCount": 4, "uniqueShopsCount": 2, "summaryText": "3 item from 2 Shops", "items": [ { "id": "cart-item-1", "productId": "prod-book-01", "title": "Islam in the Bible Book", "origin": "Iran | Mahan Golden", "imageSrc": "/assets/images/product-grey-tshirt-model.png", "quantity": 1, "price": "$24.00", "unitPrice": 24.00, "totalPrice": 24.00, "boothId": "store-mahan" }, { "id": "cart-item-2", "productId": "prod-bag-02", "title": "Islam in the Bible transfer Bookly bag", "origin": "Iran | Mahan Golden", "imageSrc": "/assets/images/product-brown-leather-bag.png", "quantity": 3, "price": "$24.00", "unitPrice": 24.00, "totalPrice": 72.00, "boothId": "store-mahan" } ], "subtotal": 70.50, "discount": 0.00, "estimatedShipping": 5.00, "total": 70.50 } } ``` - **Error States:** None. ### Endpoint 38: `GET /api/v1/cart/count` - **Domain:** Shopping Cart - **Purpose:** Lightweight item counter for navigation tab badge ("2"). - **Frontend Callers:** `BottomNavBar.tsx:280-311`, `TopHeader.tsx`. - **Response Example (200 OK):** ```json { "success": true, "data": { "itemsCount": 2 } } ``` - **Error States:** None. ### Endpoint 39: `POST /api/v1/cart/items` - **Domain:** Shopping Cart - **Purpose:** Add product to shopping cart from product details screen. - **Frontend Callers:** `ShopSinglePage.tsx:900-948` ("Add to Cart" sticky CTA). - **Request Body Example:** ```json { "productId": "prod-single-001", "quantity": 1 } ``` - **Response Example (201 Created):** ```json { "success": true, "data": { "cartItemId": "cart-item-3", "totalItemsCount": 5, "cartSubtotal": 94.50 } } ``` - **Error States:** `400 BUSINESS_RULE_VIOLATION` (out of stock), `404 RESOURCE_NOT_FOUND`. ### Endpoint 40: `PATCH /api/v1/cart/items/{itemId}` - **Domain:** Shopping Cart - **Purpose:** Increment or decrement line item quantity via steppers. - **Frontend Callers:** `CartItemCard.tsx:183-250` (+ and - stepper triggers). - **Request Body Example:** ```json { "quantity": 2 } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "itemId": "cart-item-1", "quantity": 2, "itemTotal": 48.00, "cartSubtotal": 94.50 } } ``` - **Error States:** `400 BUSINESS_RULE_VIOLATION` (requested quantity exceeds stock), `404 RESOURCE_NOT_FOUND`. ### Endpoint 41: `DELETE /api/v1/cart/items/{itemId}` - **Domain:** Shopping Cart - **Purpose:** Remove a single item from the cart. - **Frontend Callers:** `CartItemCard.tsx:116-138` (X button). - **Response Example (200 OK):** ```json { "success": true, "data": { "message": "Cart item removed successfully.", "cartSubtotal": 70.50 } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 42: `DELETE /api/v1/cart` - **Domain:** Shopping Cart - **Purpose:** Empty the shopping cart completely. - **Frontend Callers:** `ShopCartPage.tsx:40-55` ("Clear all" button). - **Response Example (200 OK):** ```json { "success": true, "data": { "message": "Cart cleared.", "totalItemsCount": 0 } } ``` - **Error States:** None. --- ### 4.10 Domain 8: Checkout, Payment & Order Finalization ### Endpoint 43: `GET /api/v1/checkout/summary` - **Domain:** Checkout - **Purpose:** Retrieve price breakdown rows for Order Summary bottom sheet modal. - **Frontend Callers:** `ShopOrderSummaryPage.tsx:160-168`, `ShopPaymentPage.tsx:241-261`. - **Response Example (200 OK):** ```json { "success": true, "data": { "lineItems": [ { "id": "row-items", "label": "Items (2)", "value": "$70.50", "amount": 70.50 }, { "id": "row-book-1", "label": "Islam in the Bible Transfer Book", "value": "$70.50", "amount": 70.50 }, { "id": "row-book-2", "label": "Transfer Book", "value": "$70.50", "amount": 70.50 } ], "total": 70.50, "formattedTotal": "$70.50" } } ``` - **Error States:** `400 BUSINESS_RULE_VIOLATION` (cart is empty). ### Endpoint 44: `GET /api/v1/checkout/shipping-methods` - **Domain:** Checkout - **Purpose:** List available shipping carriers and calculated rates. - **Frontend Callers:** `ShopBuy01Page.tsx:148-268`. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "ship-std", "name": "Standard shiping", "deliveryTime": "2-3 business day", "price": 5.00, "formattedPrice": "$5,00", "iconSrc": "/assets/images/icon-delivery-truck-grey-24.svg", "isDefault": true } ] } ``` - **Error States:** None. ### Endpoint 45: `POST /api/v1/checkout/session` - **Domain:** Checkout - **Purpose:** Lock checkout state with selected shipping address and delivery option. - **Frontend Callers:** `ShopBuy01Page.tsx:302-315` ("Continue" CTA). - **Request Body Example:** ```json { "addressId": "addr-1", "shippingMethodId": "ship-std" } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "checkoutSessionId": "cs_live_948271049", "addressId": "addr-1", "shippingMethodId": "ship-std", "subtotal": 70.50, "shippingFee": 5.00, "totalPayable": 70.50 } } ``` - **Error States:** `400 VALIDATION_FAILED`, `404 RESOURCE_NOT_FOUND`. ### Endpoint 46: `GET /api/v1/payment/methods` - **Domain:** Payment - **Purpose:** List enabled payment gateways for payment method selector sheet. - **Frontend Callers:** `ShopPaymentMethodsPage.tsx:174-182`. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "pm-google", "label": "Google Pay", "iconSrc": "/assets/images/icon-payment-google.svg", "enabled": true }, { "id": "pm-paypal", "label": "PayPal", "iconSrc": "/assets/images/icon-payment-paypal.svg", "enabled": true }, { "id": "pm-mastercard", "label": "Master Card", "iconSrc": "/assets/images/icon-payment-mastercard.svg", "enabled": true } ] } ``` - **Error States:** None. ### Endpoint 47: `POST /api/v1/orders` - **Domain:** Orders & Checkout Finalization - **Purpose:** Authorize payment and place customer order. - **Frontend Callers:** `ShopPaymentMethodsPage.tsx:186-271` ("Purchase $24.00" CTA). - **Request Body Example:** ```json { "checkoutSessionId": "cs_live_948271049", "paymentMethodId": "pm-paypal", "currency": "USD" } ``` - **Response Example (201 Created):** ```json { "success": true, "data": { "orderId": "ord-28465-uuid", "orderCode": "ORD-28465", "totalPaid": 70.50, "paymentMethod": "PayPal", "orderDate": "Mar 15,2025 | 9:41 PM", "status": "confirmed", "receiptUrl": "/api/v1/orders/ord-28465-uuid/receipt" } } ``` - **Error States:** `402 PAYMENT_DECLINED`, `409 STATE_CONFLICT` (item price modified). ### Endpoint 48: `GET /api/v1/orders/{orderId}/receipt` - **Domain:** Orders & Confirmation - **Purpose:** Fetch purchase confirmation receipt. - **Frontend Callers:** `ShopPayResultPage.tsx:82-420`. - **Response Example (200 OK):** ```json { "success": true, "data": { "orderCode": "ORD-28465", "totalPaid": "$70.50", "paymentMethod": "PayPal", "orderDate": "Mar 15,2025 | 9:41 PM", "status": "Payment Successful", "confirmationMessage": "Thank you for your purchase. your order has been places and is now being processed" } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. --- ### 4.11 Domain 9: Orders History & Multi-Shipment Tracking ### Endpoint 49: `GET /api/v1/orders` - **Domain:** Orders - **Purpose:** List user orders filtered by status tabs (Current, Delivered, Canceled). - **Frontend Callers:** `ShopOrdersPage.tsx:24-35`, `OrderFilterTabs.tsx:49`. - **Query Parameters:** - `status` (`current`, `delivered`, `canceled`, default: `current`) - `page` (integer, default: 1) - `limit` (integer, default: 10) - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "order-card-1", "orderCode": "ORD-28465", "price": "$24.00", "amount": 24.00, "date": "Mar 15,2025", "itemsCountText": "3 item", "shopsCountText": "2 shop", "deliveryProgressText": "1 / 3 Delivery", "thumbnails": [ { "src": "/assets/images/product-black-tshirt-model.png" }, { "src": "/assets/images/product-grey-tshirt-model.png" }, { "src": "/assets/images/product-brown-leather-bag.png" } ], "moreCountBadge": null }, { "id": "order-card-2", "orderCode": "ORD-28465", "price": "$24.00", "amount": 24.00, "date": "Mar 15,2025", "itemsCountText": "8 item", "shopsCountText": "2 shop", "deliveryProgressText": "1 / 8 Delivery", "thumbnails": [ { "src": "/assets/images/product-black-tshirt-model.png" }, { "src": "/assets/images/product-grey-tshirt-model.png" }, { "src": "/assets/images/product-brown-leather-bag.png" } ], "moreCountBadge": "+3" } ], "meta": { "tabCounts": { "current": 2, "delivered": 5, "canceled": 0 } } } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 50: `GET /api/v1/orders/counters` - **Domain:** Orders - **Purpose:** Retrieve account dashboard metric counters (In Progress: 4, Delivered: 4, Returned: 4). - **Frontend Callers:** `ShopAccountPage.tsx:118-129`, `OrderCounterCard.tsx:14`. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "cnt-progress", "label": "In Progress", "count": 4, "countText": "4 Orders" }, { "id": "cnt-delivered", "label": "Delivered", "count": 4, "countText": "4 Orders" }, { "id": "cnt-returned", "label": "Returned", "count": 4, "countText": "4 Orders" } ] } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 51: `GET /api/v1/orders/{orderId}` - **Domain:** Orders & Fulfillment - **Purpose:** Detailed order view with multi-shipment tracking cards and 4-step progress steppers. - **Frontend Callers:** `ShopOrderDetailPage.tsx:11-343`, `ShipmentStatusCard.tsx:14`. - **Path Parameters:** `orderId` (UUID or code, e.g. `ORD-28465`). - **Response Example (200 OK):** ```json { "success": true, "data": { "orderCode": "ORD-28465", "totalPrice": "$24.00", "date": "Mar 15,2025", "itemsCount": "3 item", "shopsCount": "1 shop", "deliveryProgress": "1 / 3 Delivery", "shipments": [ { "id": "shipment-packed", "boothName": "Al-Hujjah Books", "boothAvatar": "/assets/images/avatar-al-hujjah-books.png", "statusType": "packed", "statusLabel": "Packed", "statusColor": "#d78e06", "statusBg": "rgba(239, 196, 126, 0.2)", "completedSteps": 2, "thumbnails": [ "/assets/images/product-black-tshirt-model.png", "/assets/images/product-grey-tshirt-model.png" ], "infoRows": [ { "label": "Delivery", "value": "Mar 15,2025", "iconSrc": "/assets/images/icon-delivery-truck-grey-18.svg" } ] }, { "id": "shipment-delivered", "boothName": "Al-Hujjah Books", "boothAvatar": "/assets/images/avatar-al-hujjah-books.png", "statusType": "delivered", "statusLabel": "Delivered", "statusColor": "#0eb13c", "statusBg": "rgba(14, 177, 60, 0.2)", "completedSteps": 4, "thumbnails": [ "/assets/images/product-black-tshirt-model.png", "/assets/images/product-grey-tshirt-model.png" ], "infoRows": [ { "label": "Delivery", "value": "Mar 15,2025", "iconSrc": "/assets/images/icon-delivered-box-check-grey-18.svg" } ] }, { "id": "shipment-shipping", "boothName": "Al-Hujjah Books", "boothAvatar": "/assets/images/avatar-al-hujjah-books.png", "statusType": "shipping", "statusLabel": "Shiping", "statusColor": "#d78e06", "statusBg": "rgba(239, 196, 126, 0.2)", "completedSteps": 3, "thumbnails": [ "/assets/images/product-black-tshirt-model.png", "/assets/images/product-grey-tshirt-model.png" ], "infoRows": [ { "label": "Order", "value": "Mar 15,2025", "iconSrc": "/assets/images/icon-date-time-grey-18.svg" }, { "label": "Tracking code", "value": "A256542321", "iconSrc": "/assets/images/icon-delivery-truck-grey-18.svg" } ] } ] } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 52: `GET /api/v1/orders/{orderId}/shipments/{shipmentId}` - **Domain:** Orders & Fulfillment - **Purpose:** Granular milestone tracking events for an individual shipment package. - **Frontend Callers:** Shipment Tracker Modal. - **Response Example (200 OK):** ```json { "success": true, "data": { "shipmentId": "shipment-shipping", "carrier": "Standard Carrier", "trackingCode": "A256542321", "completedSteps": 3, "events": [ { "step": "Order", "timestamp": "2026-03-15T09:41:00Z", "completed": true }, { "step": "Packed", "timestamp": "2026-03-15T11:20:00Z", "completed": true }, { "step": "Shiping", "timestamp": "2026-03-15T14:05:00Z", "completed": true }, { "step": "Delivery", "timestamp": null, "completed": false } ] } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. ### Endpoint 53: `POST /api/v1/orders/{orderId}/cancel` - **Domain:** Orders - **Purpose:** Request order cancellation before shipment begins. - **Frontend Callers:** Order Detail Actions. - **Response Example (200 OK):** ```json { "success": true, "data": { "orderCode": "ORD-28465", "status": "canceled" } } ``` - **Error States:** `400 BUSINESS_RULE_VIOLATION` (order already dispatched). --- ### 4.12 Domain 10: Customer Support & Dispute Resolution ### Endpoint 54: `GET /api/v1/support/subjects` - **Domain:** Customer Support - **Purpose:** Retrieve the 6 predefined customer dispute subject tiles. - **Frontend Callers:** `ShopSupportPage.tsx:275-330`. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "subj-not-received", "label": "Not Received", "iconSrc": "/assets/images/icon-support-missing-item.svg" }, { "id": "subj-damaged", "label": "Damaged", "iconSrc": "/assets/images/icon-support-damaged-item.svg" }, { "id": "subj-wrong-item", "label": "Wrong Item", "iconSrc": "/assets/images/icon-support-wrong-product.svg" }, { "id": "subj-delivery-issue", "label": "Delivery Issue", "iconSrc": "/assets/images/icon-support-late-delivery.svg" }, { "id": "subj-counterfeit", "label": "Counterfeit Item", "iconSrc": "/assets/images/icon-support-fake-product.svg" }, { "id": "subj-other", "label": "Other", "iconSrc": "/assets/images/icon-support-other-dots.svg" } ] } ``` - **Error States:** None. ### Endpoint 55: `POST /api/v1/support/attachments` - **Domain:** Customer Support - **Purpose:** Upload evidence images or videos (`mp4`, `mpeg`, `h24`, `jpeg`, `png`). - **Frontend Callers:** `ShopSupportPage.tsx:420-483` (dropzone upload trigger). - **Request Format:** `multipart/form-data` with `file`. - **Response Example (200 OK):** ```json { "success": true, "data": { "evidenceUrl": "https://cdn.habibshop.com/support/evidence_8271.mp4", "mimeType": "video/mp4", "sizeBytes": 4819200 } } ``` - **Error States:** `413 PAYLOAD_TOO_LARGE` (max 50MB), `415 UNSUPPORTED_MEDIA`. ### Endpoint 56: `POST /api/v1/support/tickets` - **Domain:** Customer Support - **Purpose:** File formal dispute ticket with selected subject, description, and proof attachments. - **Frontend Callers:** `ShopSupportPage.tsx:486-544` ("Submit Order" button). - **Request Body Example:** ```json { "orderId": "ord-28465", "productId": "prod-grey-tshirt-model", "subjectId": "subj-counterfeit", "description": "Item received is counterfeit; missing publisher hologram stamp.", "evidenceUrls": [ "https://cdn.habibshop.com/support/evidence_8271.mp4" ] } ``` - **Response Example (201 Created):** ```json { "success": true, "data": { "ticketId": "tick-94819", "status": "Under Review", "notice": "We’ve received your support request and will follow up on it. Rest assured, our team will take care of it.", "createdAt": "2026-10-28T08:35:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED` (missing subject or description). ### Endpoint 57: `GET /api/v1/support/tickets` - **Domain:** Customer Support - **Purpose:** Retrieve user's filed dispute history. - **Frontend Callers:** `ShopAccountPage.tsx` ("Support & Requests" menu row). - **Response Example (200 OK):** ```json { "success": true, "data": [ { "ticketId": "tick-94819", "orderCode": "ORD-28465", "subject": "counterfeit", "status": "under_review", "createdAt": "2026-10-28T08:35:00.000Z" } ] } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 58: `GET /api/v1/support/tickets/{id}` - **Domain:** Customer Support - **Purpose:** Inspect status and resolution notes of a specific dispute ticket. - **Frontend Callers:** Support Ticket Viewer. - **Response Example (200 OK):** ```json { "success": true, "data": { "ticketId": "tick-94819", "status": "under_review", "description": "Item received is counterfeit; missing publisher hologram stamp.", "resolutionNotes": null } } ``` - **Error States:** `404 RESOURCE_NOT_FOUND`. --- ### 4.13 Domain 11: Provider Hub & Applications ### Endpoint 59: `GET /api/v1/providers/me/status` - **Domain:** Merchant & Provider Onboarding - **Purpose:** Retrieve provider service badges (Habib Talk, Hussainiyah, Habib Meet). - **Frontend Callers:** `ProviderRequestPage.tsx:332-335`, `LanguageSettingPage.tsx:130-281`. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "prov-talk", "platform": "Habib Talk", "status": "under_review", "statusText": "Under Review", "badgeType": "review" }, { "id": "prov-hussainiyah", "platform": "Hussainiyah", "status": "denied", "statusText": "Request Denied", "badgeType": "denied" }, { "id": "prov-meet", "platform": "Habib Meet", "status": "approved", "statusText": "Provider in", "badgeType": "approved" } ] } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 60: `POST /api/v1/providers/apply` - **Domain:** Merchant & Provider Onboarding - **Purpose:** Apply to become an authorized service provider. - **Frontend Callers:** `ProviderRequestPage.tsx:340-394`, `LanguageSettingPage.tsx:467-521`. - **Request Body Example:** ```json { "serviceType": "habib_meet", "businessName": "Ahd Art", "contactPhone": "+2309102036523" } ``` - **Response Example (201 Created):** ```json { "success": true, "data": { "applicationId": "app-8491", "serviceType": "habib_meet", "status": "pending", "submittedAt": "2026-10-28T08:38:00.000Z" } } ``` - **Error States:** `400 VALIDATION_FAILED`, `409 STATE_CONFLICT` (already applied). --- ### 4.14 Domain 12: Virtual Coins & Merchant Wallet ### Endpoint 61: `GET /api/v1/coins/balance` - **Domain:** Virtual Economy - **Purpose:** Fetch current Habib Coins balance. - **Frontend Callers:** `HabibCoinsBanner.tsx:55-72`, `LanguageSettingPage.tsx:416-433`. - **Response Example (200 OK):** ```json { "success": true, "data": { "coinsBalance": 21, "displayLabel": "21 Habib Coins" } } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 62: `GET /api/v1/coins/packages` - **Domain:** Virtual Economy - **Purpose:** List purchasable coin packages. - **Frontend Callers:** Coin Purchase Sheet. - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "coin-pkg-10", "coins": 10, "price": 4.99 }, { "id": "coin-pkg-25", "coins": 25, "price": 9.99 }, { "id": "coin-pkg-50", "coins": 50, "price": 18.99 } ] } ``` - **Error States:** None. ### Endpoint 63: `POST /api/v1/coins/purchase` - **Domain:** Virtual Economy - **Purpose:** Purchase a Habib coin bundle. - **Frontend Callers:** `HabibCoinsBanner.tsx:75-104` ("Buy Coins" CTA). - **Request Body Example:** ```json { "packageId": "coin-pkg-25", "paymentMethodId": "pm-google" } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "newCoinsBalance": 46, "transactionId": "tx-coin-94819" } } ``` - **Error States:** `402 PAYMENT_DECLINED`. ### Endpoint 64: `GET /api/v1/wallet` - **Domain:** Merchant Wallet - **Purpose:** Get vendor wallet earnings and income breakdown. - **Frontend Callers:** `ProviderRequestPage.tsx:397-478`, `LanguageSettingPage.tsx:524-606`. - **Response Example (200 OK):** ```json { "success": true, "data": { "balance": 24.00, "currency": "USD", "displayBalance": "$24.00", "sourceLabel": "Habib Income", "pendingSettlements": 0.00 } } ``` - **Error States:** `401 UNAUTHORIZED`. --- ### 4.15 Domain 13: Philanthropy, Notifications & System Feeds ### Endpoint 65: `POST /api/v1/donations` - **Domain:** Philanthropy & Crowdfunding - **Purpose:** Submit user donation to Habib Community projects. - **Frontend Callers:** `LanguageSettingPage.tsx:343-371` ("Donate" button on Donate Habib banner). - **Request Body Example:** ```json { "amount": 10.00, "currency": "USD", "project": "Habib Large-Scale Project" } ``` - **Response Example (200 OK):** ```json { "success": true, "data": { "donationId": "don-84912", "amount": 10.00, "status": "completed" } } ``` - **Error States:** `400 VALIDATION_FAILED`. ### Endpoint 66: `GET /api/v1/notifications` - **Domain:** Notifications - **Purpose:** Retrieve user notifications list. - **Frontend Callers:** `ShopHomePage.tsx:153` (Bell icon), `ShopAccountPage.tsx:122`. - **Query Parameters:** `page` (default: 1), `limit` (default: 10). - **Response Example (200 OK):** ```json { "success": true, "data": [ { "id": "notif-1", "title": "Order Shipped", "body": "Shipment for ORD-28465 is on its way.", "read": false, "createdAt": "2026-10-28T07:45:00.000Z" } ] } ``` - **Error States:** `401 UNAUTHORIZED`. ### Endpoint 67: `GET /api/v1/notifications/unread-count` - **Domain:** Notifications - **Purpose:** Retrieve unread notification count badge (displaying "2"). - **Frontend Callers:** `ShopHomePage.tsx:153`, `ShopAccountPage.tsx:133`, `ProviderRequestPage.tsx:286`. - **Response Example (200 OK):** ```json { "success": true, "data": { "unreadCount": 2 } } ``` - **Error States:** None. --- ## 5. Real-Time Communication & WebSockets Specification ### 5.1 Protocol Architecture Direct merchant-to-customer chat on `/shop-chat` requires a persistent, bi-directional communication channel. The backend must expose a WebSocket gateway at `/ws/chat` secured via JWT ticket handshake. ### 5.2 Handshake & Connection Lifecycle 1. **Client Upgrade Request:** ```http GET /ws/chat?token= HTTP/1.1 Host: api.habibshop.com Upgrade: websocket Connection: Upgrade ``` 2. **Server Handshake Response:** ```http HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade ``` 3. **Heartbeat Protocol:** Client sends `{ "event": "ping" }` every 30 seconds; server replies with `{ "event": "pong" }`. ### 5.3 Event Payload Definitions #### 1. Outgoing Message Dispatch (`client -> server`) ```json { "event": "message:send", "data": { "clientMessageId": "local-temp-msg-9921", "conversationId": "conv-8491", "recipientBoothId": "store-al-hujjah", "messageText": "Are you able to deliver the transfer book by next Monday?", "attachmentUrl": null } } ``` #### 2. Message Delivery Receipt (`server -> client`) ```json { "event": "message:delivered", "data": { "clientMessageId": "local-temp-msg-9921", "serverMessageId": "msg-6", "timestamp": "2026-10-28T08:42:00.000Z", "status": "delivered" } } ``` #### 3. Incoming Message (`server -> client`) ```json { "event": "message:received", "data": { "id": "msg-7", "conversationId": "conv-8491", "sender": "booth", "text": "Yes, we dispatch with express delivery tomorrow morning.", "timestamp": "2026-10-28T08:43:00.000Z" } } ``` #### 4. Delivery Failure Notification (`server -> client`) Triggers the red chat bubble with the "Try Again" action button in `ShopChatPage.tsx:427-466`. ```json { "event": "message:failed", "data": { "clientMessageId": "local-temp-msg-9921", "reason": "Merchant offline and message buffer timed out.", "canRetry": true } } ``` --- ## 6. Security, Authentication & Session Architecture ### 6.1 Token Lifecycle & Storage - **Access Tokens:** Standard RS256 JWT with 15-minute expiration window containing `sub` (User UUID), `role` (`customer`, `seller`, `admin`), and `iss` (`habib-shop-auth`). - **Refresh Tokens:** High-entropy cryptographically secure random tokens stored in database with 30-day sliding window expiration and automatic reuse detection revocation. - **CSRF & Cookie Protection:** For web browsers, refresh tokens are passed via `__Host-` prefixed `HttpOnly`, `SameSite=Strict`, `Secure` cookies. ### 6.2 Phone OTP Verification Flow - **Generation:** Cryptographically secure 6-digit numeric OTP. - **Rate Limiting:** Maximum 3 OTP requests per phone number per hour. - **Validity:** OTP expires in exactly 120 seconds. Maximum 3 failed submission attempts before lockout. ### 6.3 Role-Based Access Control (RBAC) Matrix | Resource / Action | Customer | Seller / Merchant | Support Agent | Administrator | |---|---|---|---|---| | Browse Catalog & Categories | Allowed | Allowed | Allowed | Allowed | | Place Order & Manage Cart | Allowed | Allowed | Read Only | Allowed | | Edit Merchant Storefront | Denied | Own Store Only | Read Only | Allowed | | Reply in Store Chat | As User | As Merchant | Moderation | Full Audit | | View Customer Orders | Own Orders | Sold Items | Assigned Tickets | All Orders | | File Support Dispute | Own Orders | Counter-claim | Assigned Tickets | Full Access | | Manage System Banners | Denied | Denied | Denied | Allowed | | Process User Deletion | Own Account | Own Account | Denied | Allowed | --- ## 7. Verification, Compliance & Quality Assurance ### 7.1 Automated Verification Check This specification is programmatically verified against the target frontend codebase using `scripts/verify-backend-spec.mjs`. To verify compliance: ```powershell node scripts/verify-backend-spec.mjs ``` ### 7.2 Quality Gates & Criteria 1. **100% Citation of All 57 Files in `src/`:** Every file from `src/main.tsx` through `src/pages/test/TestDirectoryPage.tsx` must be explicitly cited and mapped. 2. **Zero Unresolved Placeholders:** Strict absence of unfinished placeholder tags and lazy code-block ellipsis truncations. 3. **20 Canonical Data Entities:** All 20 canonical relational models defined with complete field definitions and PostgreSQL DDL. 4. **Exhaustive REST Endpoints:** At least 62 RESTful endpoint contracts documented across all 13 functional domains with full JSON schemas and examples. 5. **Real Concrete Fixtures:** Every endpoint example and mock schema reflects authentic data from the frontend design tokens and mock catalogs. ### 7.3 Production Integration & Flutter WebView Bridge Module Citations The production SPA integration inside `src/` adds parameterized routing, live Habib Django REST API bindings (`/api/shop/*`), global shopping cart and account state hydration, interactive overlay bottom sheets, and full `window.FlutterChannel` host bridge parity (`web_ready`, `HABIB_TOKEN`, `HABIB_COINS`, `HABIB_VIEW_PADDINGS`, `handleBackButton`, `buy_coin`, `pick_manual_location`, `upload_file`, and `open_external_url`). Every production source module in `src/` is mapped below: | Source File Path | Architectural Role & Backend / Host Integration Responsibility | |---|---| | `src/types/window.d.ts` | Global TypeScript declarations for `window.FlutterChannel`, `window.HABIB_TOKEN`, `window.HABIB_COINS`, `window.HABIB_VIEW_PADDINGS`, `window.onFlutterResponse`, and `window.handleBackButton`. | | `src/lib/cookies.ts` | Cookie persistence utilities managing `HABIB_TOKEN`, `USER_LANGUAGE`, and guest cart session token `HABIB_SHOP_GUEST`. | | `src/lib/auth-bridge.ts` | Habib host authentication token resolver (`getToken`), asynchronous Flutter login handshake (`ensureToken`), and local session sign-out helper (`signOutLocal`). | | `src/lib/view-paddings.ts` | Safe-area inset listener binding `window.HABIB_VIEW_PADDINGS` and `habib:view-paddings-changed` events to CSS custom properties `--safe-top` through `--safe-left`. | | `src/lib/webview-actions.ts` | Typed Flutter WebView bridge actions for `close`, `open_external_url`, `copy_to_clipboard`, `download_file`, `buy_coin`, `pick_manual_location`, and `upload_file`. | | `src/lib/routes.ts` | Parameterized production URL builders (`ROUTES`) and `?bare=1` / `?embed=1` Figma snapshot detection (`isBareMode`). | | `src/lib/http.ts` | Fetch client (`shopRequest`) injecting `Authorization: Token `, `X-Shop-Session: `, and `Accept-Language: ` headers plus media URL resolution (`resolveMediaUrl`). | | `src/lib/shopApi.ts` | Strongly typed TypeScript API client covering home feed, categories, products, reviews, store booths, cart, promo codes, shipping/payment methods, orders, shipment tracking, profile, addresses, bookmarks, provider requests, support tickets, and store chat. | | `src/lib/mappers.ts` | Pure data adapters transforming backend REST DTOs into the UI presentation props consumed by `CompactProductCard`, `GridProductCard`, `CategoryCard`, `AddressCard`, `OrderListCard`, and `ShipmentOrderCard`. | | `src/hooks/use-hardware-back-handler.ts` | LIFO Android hardware back-button handler stack invoked by `window.handleBackButton()` so open bottom sheets close before route history pops. | | `src/hooks/use-habib-web-ready.ts` | Lifecycle hook posting `{ action: "web_ready" }` to `window.FlutterChannel` after initial hydration and double `requestAnimationFrame` paint. | | `src/hooks/useSmartBack.ts` | Safe in-app back navigation hook tracking internal SPA transitions and falling back to deterministic parent routes on deep-linked entry. | | `src/context/ShopAppContext.tsx` | Application-wide React context hydrating guest/authenticated cart, saved addresses, shipping/payment selections, bookmarks, shopper profile, order counters, Habib Coin balance, language preference, and toast notifications. | | `src/components/bridge/HabibBridgeProviders.tsx` | Root router-level bridge provider installing global hardware back handling, safe-area padding synchronization, scroll restoration, and status toasts. | | `src/components/modals/OrderSummarySheet.tsx` | True overlay bottom sheet for `/cart` order pricing breakdown and promo code application, registered on the LIFO hardware back stack. | | `src/components/modals/PaymentMethodsSheet.tsx` | True overlay bottom sheet for `/checkout/review` payment method selection including live Habib Coins balance validation. | | `src/components/modals/AddressFormSheet.tsx` | True overlay bottom sheet for `/checkout/shipping` and `/account/addresses` address creation/editing with optional Flutter `pick_manual_location` pin selection. | | `src/components/modals/ShipmentTrackingSheet.tsx` | True overlay bottom sheet for `/orders/:orderId` carrier tracking code copy and chronological shipment milestone timeline. | | `src/components/common/ShimmerSkeletons.tsx` | Dynamic-only shimmer skeleton loaders (`ShimmerBox`, `CompactCarouselShimmer`, `HomeFeedShimmer`, `CategoryGridShimmer`, `ProductGridShimmer`, `OrdersListShimmer`, `OrderDetailShimmer`, `ChatThreadShimmer`, `CartItemsShimmer`), tactile `InlineSpinner`, and network `RetryBanner`. | | `src/lib/shopQueries.ts` | TanStack Query v5 query client, canonical cache keys, query hooks, and optimistic/invalidating mutation hooks for all `/api/shop/*` resources. | | `src/lib/phone.ts` | International phone number parsing, validation, and display formatting helpers powered by `google-libphonenumber`. | | `src/hooks/use-animated-presence.ts` | Mount/unmount animation lifecycle hook coordinating CSS exit transitions for overlay modals and bottom sheets. | | `src/components/common/PhoneNumberInput.tsx` | Country-code selector and validated phone number input control used in address and profile forms. | | `src/components/modals/LoginRequiredModal.tsx` | Modal prompt requesting Habib authentication via `window.FlutterChannel` or browser token sign-in before protected actions. |