yellowsapphire-sdk 1.0.7
The API
Keywords: OpenAPI, OpenAPI-Generator, The API

    This is the YellowSapphire Backend. Carefully read the rest of this document.   **Rate Limits**: 100 requests/minute (public), 1000 requests/minute (authenticated)  ## Authentication &amp; Authorization  **Token-Based Authentication**: All endpoints require JWT bearer tokens obtained via login endpoints.  **Access Control**: Role-based permissions with four distinct access levels:  &#x60;&#x60;&#x60; Admin      - System-wide access: User management, system configuration, all operations Customer   - Account-scoped: Product browsing, order placement, account management   Fulfillment - Order-scoped: Inventory management, order processing, product configuration Logistics  - Delivery-scoped: Shipping coordination, delivery tracking, route management &#x60;&#x60;&#x60;  **Get a Token**: 1. Authenticate via &#x60;/admin/login&#x60; or &#x60;/customer/login&#x60; endpoints 2. Copy pasta the token from a 200 auth response 3. Include in requests: &#x60;Authorization: Bearer &lt;token&gt;&#x60; 4. Use \&quot;Authorize\&quot; button above for interactive testing  ## Implementation Notes  - JSON responses with standardized error handling - Real-time with fcm/ws/mongochangestreams   - correlation IDs for request tracing - JWT auth with rbac - fulfillment workflow with qa - Global Error Handler middleware    ## Logging &amp; Monitoring **Structured Logging System**  Centralized logging with correlation ID tracking across API requests, database operations, performance metrics, and security events. JSON format optimized for log aggregation systems.  ### Status Indicators - **●** Request initiated / Processing started - **◐** Validation / Intermediate processing step - **✓** Operation completed successfully - **▲** Warning condition detected - **✗** Error or failure state - **⚡** Performance critical operation - **🔒** Security-related event  ### Request Tracing &amp; Correlation IDs  **End-to-End Request Tracking:** Each API request receives a unique correlation ID that propagates through all system layers for distributed tracing and debugging.  **Correlation ID Format**: &#x60;req-{32-character-hex}&#x60; (e.g., &#x60;req-309edd90d27d3ab635d57e98697bc47d&#x60;) - Generated at request entry point and returned in &#x60;X-Correlation-ID&#x60; header - Enables complete request tracing across all system layers  **Timestamp Format**: ISO 8601 with millisecond precision (&#x60;2025-07-02T21:24:32.847Z&#x60;)  ### Log Format Structured JSON log format compatible with log aggregation systems (ELK Stack, Splunk, Datadog).  **Standard Log Structure:** &#x60;&#x60;&#x60;json {   \&quot;@timestamp\&quot;: \&quot;2025-07-02T21:24:32.847Z\&quot;,   \&quot;@level\&quot;: \&quot;info\&quot;,   \&quot;service\&quot;: {     \&quot;name\&quot;: \&quot;yellowsapphire-backend\&quot;,     \&quot;version\&quot;: \&quot;2.2.0\&quot;,     \&quot;environment\&quot;: \&quot;production\&quot;   },   \&quot;location\&quot;: {     \&quot;source\&quot;: \&quot;controller\&quot;,     \&quot;module\&quot;: \&quot;CustomerController\&quot;,     \&quot;method\&quot;: \&quot;CustomerLogin\&quot;   },   \&quot;message\&quot;: \&quot;✓ [CUSTOMER.LOGIN.3] Customer authentication successful\&quot;,   \&quot;data\&quot;: {     \&quot;correlationId\&quot;: \&quot;req-309edd90d27d3ab635d57e98697bc47d\&quot;,     \&quot;ip\&quot;: \&quot;197.242.156.23\&quot;,     \&quot;userAgent\&quot;: \&quot;Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)\&quot;,     \&quot;engineering\&quot;: {       \&quot;functionName\&quot;: \&quot;CustomerLogin()\&quot;,       \&quot;operationResult\&quot;: \&quot;authentication_successful\&quot;,       \&quot;authenticationDuration\&quot;: \&quot;89ms\&quot;,       \&quot;databaseQueryDuration\&quot;: \&quot;12ms\&quot;,       \&quot;totalOperationDuration\&quot;: \&quot;156ms\&quot;,       \&quot;performanceCategory\&quot;: \&quot;acceptable\&quot;,       \&quot;securityEvent\&quot;: \&quot;customer_login_success\&quot;,       \&quot;customerId\&quot;: \&quot;60f7b8c...\&quot;,       \&quot;responseStatus\&quot;: 200,       \&quot;jwtTokenGenerated\&quot;: true,       \&quot;loginAttemptNumber\&quot;: 1     }   },   \&quot;metadata\&quot;: {     \&quot;processId\&quot;: 1954,     \&quot;hostname\&quot;: \&quot;api-server-prod-01\&quot;,     \&quot;memoryUsageMB\&quot;: 375,     \&quot;uptime\&quot;: \&quot;4h 18m 32s\&quot;,     \&quot;requestMethod\&quot;: \&quot;POST\&quot;,     \&quot;endpoint\&quot;: \&quot;/api/customer/login\&quot;,     \&quot;statusCode\&quot;: 200   } } &#x60;&#x60;&#x60;    ### Log Categories &amp; Workflow Steps  Each business operation is broken down into numbered steps that trace the complete workflow. This allows precise debugging and performance monitoring at each stage.  **Feedback Mechanisms &amp; Quality Assurance:** - **[CUSTOMER.RATING]**: Product and service rating submission with quality metrics - **[FEEDBACK.COLLECTION.1-4]**: Customer satisfaction surveys and feedback processing - **[QUALITY.REVIEW.1-3]**: Internal quality assurance workflows and improvement tracking - **[SUPPORT.TICKET.1-5]**: Customer support ticket lifecycle management - **[PERFORMANCE.FEEDBACK]**: System performance feedback loops and optimization triggers  **MongoDB Change Streams &amp; Real-time Events:**  | Change Stream | Collection | Event Types | Socket.IO Event | Purpose | |---------------|------------|-------------|-----------------|---------| | **Product Stream** | &#x60;products&#x60; | insert, update, delete | &#x60;inventory:product_update&#x60; | New product creation, price changes, description updates | | **Inventory Stream** | &#x60;products&#x60; | update (stock field) | &#x60;inventory:stock_change&#x60; | Stock level modifications, low stock alerts | | **Order Stream** | &#x60;orders&#x60; | insert, update | &#x60;orders:status_change&#x60; | Order creation, status transitions, delivery updates | | **Stock Reservation Stream** | &#x60;stockreservations&#x60; | insert, update, delete | &#x60;inventory:reservation_update&#x60; | Stock holds, reservation expiry, release events | | **Inventory Transaction Stream** | &#x60;inventorytransactions&#x60; | insert | &#x60;inventory:transaction&#x60; | Stock movements, audit trail, transaction analytics | | **Customer Stream** | &#x60;customers&#x60; | insert, update | &#x60;customer:profile_update&#x60; | Registration, profile changes, verification status | | **Admin Stream** | &#x60;admins&#x60; | insert, update, delete | &#x60;admin:user_management&#x60; | Admin user lifecycle, permission changes | | **Category Stream** | &#x60;categories&#x60; | insert, update, delete | &#x60;catalog:category_update&#x60; | Category structure changes, navigation updates | | **Banner Stream** | &#x60;adbanners&#x60; | insert, update, delete | &#x60;content:banner_update&#x60; | Marketing content changes, campaign updates |  **Change Stream Processing Workflow:** &#x60;&#x60;&#x60; 1. MongoDB Change Event → 2. Change Stream Processor → 3. Event Transformation → 4. Socket.IO Broadcast → 5. Client Handlers &#x60;&#x60;&#x60;  **Real-time Notification Triggers:** - **Low Stock Alert**: Triggered when product quantity ≤ reorder level - **Order Status Change**: Immediate notification on status transitions - **New Product Alert**: Admin notification for product additions - **Critical Stock**: Emergency alerts for zero inventory  ### MongoDB Transaction System &amp; ACID Compliance  **Transaction-Safe Order Processing:**  Critical business operations (order creation, inventory updates, payment processing) are wrapped in MongoDB transactions to ensure data consistency and ACID compliance.  **Transaction Service Features:** - **Automatic Retry Logic**: Exponential backoff for transient failures (network issues, write conflicts) - **Rollback Guarantee**: Automatic transaction rollback on any operation failure - **Correlation ID Tracking**: Complete transaction tracing through distributed systems - **Performance Monitoring**: Transaction duration and retry metrics - **Business-Friendly Logging**: Non-technical log messages for operations teams  **Transaction Log Categories:** - **[DATABASE.TRANSACTION.1-N]**: Individual transaction attempt tracking - **[DATABASE.SEQUENCE.1-N]**: Sequential operation execution within transactions - **[DATABASE.TRANSACTION.FAILED]**: Terminal transaction failures after all retries  **Supported Operations:** &#x60;&#x60;&#x60; • Order Creation (Customer + Order + Inventory Update) • Stock Reservations (Reserve + Timeout + Release) • Payment Processing (Payment + Order Status + Notification) • Inventory Adjustments (Stock + Transaction Log + Audit Trail) &#x60;&#x60;&#x60;  **Transaction Configuration:** - **Read Concern**: majority (consistent reads) - **Write Concern**: majority with journal acknowledgment - **Max Retries**: 3 attempts with exponential backoff - **Timeout**: 30 seconds per transaction - **Retry Delays**: 100ms, 200ms, 400ms  **Error Handling:** &#x60;&#x60;&#x60; Retryable Errors: TransientTransactionError, UnknownTransactionCommitResult, WriteConflict Non-Retryable: ValidationError, AuthenticationError, BusinessLogicError &#x60;&#x60;&#x60; - **Payment Confirmation**: Real-time order payment updates   #### **Order Management Workflows**  **Order Placement Flow:** &#x60;&#x60;&#x60;mermaid graph LR A[Customer Request] --&gt; B[ORDER.1 Validate] B --&gt; C[ORDER.2 Check Stock] C --&gt; D[ORDER.3 Process Payment] D --&gt; E[ORDER.4 Reserve Stock] E --&gt; F[ORDER.5 Create Order] F --&gt; G[ORDER.6 Notify Customer] &#x60;&#x60;&#x60;  **Admin Order Management:** &#x60;&#x60;&#x60;mermaid graph TD A[Admin Login] --&gt; B[ADMIN.ORDERS.1 Auth Check] B --&gt; C[ADMIN.ORDERS.2 Query Orders] C --&gt; D[ADMIN.ORDERS.3 Format Response] &#x60;&#x60;&#x60;  - **[CUSTOMER.ORDER.1-6]**: Complete order placement process - **[ADMIN.ORDERS.1-3]**: Order management operations - **[ADMIN.ORDER_GET.2]**: Order details retrieval by admin - **[ADMIN.ORDER_STATUS.2]**: Order status updates - **[ORDERS.GET]**: General order queries  #### **Product &amp; Inventory Management**  **Product Creation Flow:** &#x60;&#x60;&#x60; [Admin Request] --&gt; [PRODUCT.1 Validate]  --&gt; [PRODUCT.2 Barcode Lookup] --&gt; [PRODUCT.3 Process Data] --&gt; [PRODUCT.4 Save &amp; Initialize] &#x60;&#x60;&#x60;  **Inventory Update Flow:** &#x60;&#x60;&#x60; [Stock Request] --&gt; B[INVENTORY.1 Validate]   --&gt; [INVENTORY.2 Lock Transaction]  --&gt; [INVENTORY.3 Calculate] --&gt; [INVENTORY.4 Update DB] --&gt; INVENTORY.5 Notify] &#x60;&#x60;&#x60;  - **[ADMIN.PRODUCT.1-4]**: Product management workflow - **[INVENTORY.1-5]**: Stock operation tracking - **[ADMIN.PRODUCTS.1-2]**: Product catalog management - **[ADMIN.PRODUCT_GET.2]**: Individual product administration - **[ADMIN.BARCODE_LOOKUP]**: Product lookup via barcode scanning - **[ADMIN.CREATE_FROM_BARCODE.2]**: Product creation from barcode data - **[ADMIN.BULK_PRODUCTS]**: Bulk product operations - **[ADMIN.STOCK]**: Inventory level management - **[ADMIN.CATEGORY_CREATE.1]**: Product category creation  #### **Shopping &amp; E-commerce Workflows**  **Customer Shopping Journey:** &#x60;&#x60;&#x60;mermaid graph TD A[Browse Categories] --&gt; B[Search Products] B --&gt; C[View Product Details] C --&gt; D[Check Availability] D --&gt; E[Add to Cart] E --&gt; F[Checkout]  A -.-&gt; G[SHOP.CATEGORIES] B -.-&gt; H[SHOP.SEARCH] C -.-&gt; I[SHOP.DETAIL.1-3] D -.-&gt; J[SHOP.AVAILABILITY.2] E -.-&gt; K[CART.ADD] F -.-&gt; L[ORDER.1-6] &#x60;&#x60;&#x60;  **Offers &amp; Promotions Flow:** &#x60;&#x60;&#x60;mermaid graph LR A[Request Offers] --&gt; B[OFFERS.1 Validate PostCode] B --&gt; C[OFFERS.2 Query Active] C --&gt; D[OFFERS.3 Check Expiry] D --&gt; E[OFFERS.4-6 Return Results] &#x60;&#x60;&#x60;  - **[SHOP.SEARCH]**: Product search and filtering - **[SHOP.PRODUCT_DETAIL.1-3]**: Product detail retrieval with availability check - **[SHOP.CATEGORIES]**: Category browsing and navigation - **[SHOP.FEATURED.1-2]**: Featured products display - **[SHOP.OFFERS.1-6]**: Special offers and promotions workflow - **[SHOP.QUICK_DELIVERY.1-2]**: Express delivery options - **[SHOP.TOP_STORES.1-2]**: Popular store listings - **[SHOP.STORE_BY_ID.1-2]**: Individual store information - **[SHOP.PRODUCT_AVAILABILITY.2]**: Real-time stock checking  #### **Cart Management Workflows** - **[CART.GET]**: Cart contents retrieval - **[CART.DELETE_ITEM.1-5]**: Individual item removal from cart - **[CART.CLEAR.2-6]**: Complete cart clearance  #### **Customer Management Workflows**  **Customer Registration Flow:** &#x60;&#x60;&#x60;mermaid graph TD A[Registration Request] --&gt; B[SIGNUP.1 Validate] B --&gt; C[SIGNUP.2 Hash Password] C --&gt; D[SIGNUP.3 Check Email] D --&gt; E[SIGNUP.4 Create Account] E --&gt; F[SIGNUP.5 Generate JWT] F --&gt; G[SIGNUP.6 Notify Admins] G --&gt; H[SIGNUP.7 Send Welcome] H --&gt; I[SIGNUP.8 Return Response] I --&gt; J[SIGNUP.9 Log Complete] &#x60;&#x60;&#x60;  **Authentication &amp; Verification:** &#x60;&#x60;&#x60;mermaid graph LR A[Login Request] --&gt; B[LOGIN.1-3 Process] A --&gt; C[Google OAuth] C --&gt; D[GOOGLE_LOGIN] B --&gt; E[OTP Request] E --&gt; F[OTP.1-6 Generate] F --&gt; G[VERIFY.1-6 Validate] &#x60;&#x60;&#x60;  - **[CUSTOMER.SIGNUP.1-9]**: Complete customer registration process   - **[CUSTOMER.SIGNUP.1]**: Initial request processing - correlation ID generation and metadata capture   - **[CUSTOMER.SIGNUP.1.1]**: DTO validation using class-validator - email, phone, password, firstName, lastName format checks   - **[CUSTOMER.SIGNUP.1.2]**: Field-level validation - email normalization, phone format (10 digits), password strength (6-20 chars)   - **[CUSTOMER.SIGNUP.2]**: Cryptographic operations - bcrypt salt generation and password hashing with performance tracking   - **[CUSTOMER.SIGNUP.3]**: Email uniqueness validation - database query Customer.findOne({email}) to prevent duplicates   - **[CUSTOMER.SIGNUP.4]**: Customer account creation - MongoDB document with default values (verified: false, receivemarketing: true)   - **[CUSTOMER.SIGNUP.5]**: JWT token generation - 1-day expiration with customer ID, email, and verification status claims   - **[CUSTOMER.SIGNUP.6]**: FCM notification to admins - Firebase topic &#39;admin&#39; with new signup alert (non-blocking)   - **[CUSTOMER.SIGNUP.7]**: Welcome email dispatch - Brevo SMTP with Handlebars template to customer email (asynchronous)   - **[CUSTOMER.SIGNUP.8]**: Response preparation - 201 status with token, verified: false, email, and success message   - **[CUSTOMER.SIGNUP.9]**: Completion logging - total duration tracking and correlation ID logging - **[CUSTOMER.LOGIN.1-3]**: Customer authentication with OAuth support - **[CUSTOMER.GOOGLE_LOGIN]**: Google OAuth integration - **[CUSTOMER.OTP_REQUEST.1-6]**: OTP generation and delivery (SMS currently disabled) - **[CUSTOMER.VERIFY.1-6]**: Account verification process with OTP validation - **[CUSTOMER.PROFILE_GET.2]**: Customer profile retrieval - **[CUSTOMER.PROFILE_EDIT.1-4]**: Profile update operations - **[CUSTOMER.FIREBASE_TOKEN.1-4]**: Firebase token management for notifications - **[CUSTOMER.ORDER_GET.1]**: Customer order history - **[CUSTOMER.RATING]**: Product and service rating submission  #### **Admin Management Workflows** - **[ADMIN.CREATE]**: New admin account creation - **[ADMIN.UPDATE.1-4]**: Admin profile updates - **[ADMIN.DELETE]**: Admin account deletion - **[ADMIN.GET_BY_ID.1-2]**: Individual admin retrieval - **[ADMIN.LIST.1-2]**: Admin user listing - **[ADMIN.PASSWORD_RESET.1-5]**: Admin password reset process - **[ADMIN.CUSTOMER_LIST.1-3]**: Customer management operations - **[ADMIN.CUSTOMER_UPDATE.1-3]**: Customer profile administration - **[ADMIN.CUSTOMER_DELETE.2]**: Customer account removal - **[ADMIN.CUSTOMER_GET.2]**: Customer profile retrieval by admin   #### **Content Management Workflows** - **[ADMIN.BANNER_CREATE.1-3]**: Advertisement banner creation - **[ADMIN.BANNER_UPDATE.1-5]**: Banner content updates - **[ADMIN.BANNER_LIST.1-3]**: Banner management and listing  #### **Payment Processing Workflows** - **[PAYMENT.GATEWAY]**: Payment gateway integration - **[PAYMENT.GATEWAY.BANK]**: Bank transfer processing - **[PAYMENT.GATEWAY.GPAY]**: Google Pay integration - **[PAYMENT.GATEWAY.PO]**: Purchase order processing  #### **Communication &amp; Notifications** - **[EMAIL.1-5]**: Email delivery workflow - **[FCM.1-2]**: Push notification delivery  #### **System Operations** - **[DB.1-3]**: Database operation monitoring  - **[RATE_LIMIT]**: Security event tracking - **[VALIDATION.OBJECTID]**: Input validation for database operations - **[CORRELATION.CLEANUP]**: Request context management  ### Performance Metrics &amp; Monitoring  **Execution Time Tracking:** Every operation includes precise timing data for performance analysis and optimization.  &#x60;&#x60;&#x60;json \&quot;engineering\&quot;: {   \&quot;authenticationDuration\&quot;: \&quot;89ms\&quot;,   \&quot;databaseQueryDuration\&quot;: \&quot;12ms\&quot;,   \&quot;totalOperationDuration\&quot;: \&quot;156ms\&quot;,   \&quot;performanceCategory\&quot;: \&quot;acceptable\&quot; } &#x60;&#x60;&#x60;  **Performance Classifications:** - **⚡ Optimal** (&lt;100ms): Lightning fast, minimal resource usage   - *Target*: Authentication, simple queries, cache hits   - *Example*: &#x60;[CUSTOMER.PROFILE.2] Profile data retrieved (43ms) - optimal&#x60;  - **✓ Acceptable** (100-500ms): Good performance within normal range   - *Target*: Complex queries, order processing, payment validation   - *Example*: &#x60;[ORDER.CREATE.3] Payment processing completed (287ms) - acceptable&#x60;  - **▲ Slow** (500ms-2s): Requires attention, may impact user experience   - *Action*: Investigate query optimization, caching opportunities   - *Example*: &#x60;[INVENTORY.2] Stock calculation completed (743ms) - slow&#x60;  - **✗ Critical** (&gt;2s): Unacceptable performance, immediate optimization required   - *Action*: Emergency investigation, potential timeout issues   - *Example*: &#x60;[EMAIL.4] SMTP delivery attempt (2.1s) - critical&#x60;  **System Resource Monitoring:** - **Memory Usage**: V8 heap utilization and garbage collection patterns - **Database Performance**: Connection pool status, query execution times - **External APIs**: Response times for barcode lookups, payment processors - **Security Operations**: Cryptographic operation timing (bcrypt, JWT) - **Network Operations**: SMTP delivery, FCM push notifications  ### Security &amp; Privacy Protection  **Data Sanitization Standards:** All sensitive data is automatically sanitized before logging to prevent accidental exposure.  &#x60;&#x60;&#x60; Passwords      → password: [HIDDEN]      (Authentication tracking without credentials) JWT Tokens     → authorization: [HIDDEN] (Security without token exposure) API Keys       → apikey: [HIDDEN]        (Access tracking without key exposure) Email Addresses → email: [HIDDEN]        (User identification with privacy protection) Phone Numbers  → phone: [HIDDEN]         (Contact tracking without number exposure) &#x60;&#x60;&#x60;  **Security Event Tracking:** - **Authentication Events**: Login attempts, failures, security violations - **Authorization Events**: Permission checks, role validations, access denials - **Rate Limiting**: Request frequency monitoring and abuse detection - **Input Validation**: Malicious input detection and sanitization - **Session Management**: Token lifecycle, expiration, and invalidation  **Compliance &amp; Auditing:** - **GDPR Compliance**: No personal data in logs, sanitized identifiers only - **Security Auditing**: All authentication and authorization events tracked - **Incident Response**: Correlation IDs enable complete request tracing - **Performance Auditing**: System performance tracking for SLA compliance  ### Error Handling &amp; Recovery  **Environment-Specific Error Reporting:** - **Development**: Detailed stack traces, variable states, debugging context - **Production**: Sanitized error messages with correlation IDs for internal tracking  **Error Categories &amp; Response Strategies:**  | Error Type | Log Pattern | Recovery Action | User Impact | |------------|-------------|-----------------|-------------| | Validation Errors | &#x60;[VALIDATION.ERROR]&#x60; | Return 400 with specific field errors | Immediate feedback for correction | | Authentication Failures | &#x60;[AUTH.ERROR]&#x60; | Return 401, log security event | Redirect to login, rate limit protection | | Authorization Violations | &#x60;[AUTHZ.ERROR]&#x60; | Return 403, audit trail | Access denied with support contact | | Database Errors | &#x60;[DB.ERROR]&#x60; | Retry logic, fallback queries | Temporary service degradation notice | | External API Failures | &#x60;[API.ERROR]&#x60; | Circuit breaker, cached responses | Graceful degradation or retry prompts | | Business Logic Errors | &#x60;[BUSINESS.ERROR]&#x60; | Transaction rollback, state recovery | Clear error message with resolution steps |  **Error Context Preservation:** &#x60;&#x60;&#x60;json {   \&quot;error\&quot;: {     \&quot;message\&quot;: \&quot;Validation failed for customer profile\&quot;,     \&quot;code\&quot;: \&quot;VALIDATION_ERROR\&quot;,     \&quot;details\&quot;: {       \&quot;field\&quot;: \&quot;email\&quot;,       \&quot;reason\&quot;: \&quot;Invalid email format\&quot;,       \&quot;providedValue\&quot;: \&quot;user...@invalid\&quot;     }   } } &#x60;&#x60;&#x60;  ### Security Headers - **X-Content-Type-Options**: Prevents MIME type sniffing - **X-Frame-Options**: Protects against clickjacking attacks   - **X-XSS-Protection**: Enables browser XSS filtering - **Content-Security-Policy**: Restricts resource loading   ### Company Information **Website**: [yellowsapphire.co.za](https://yellowsapphire.co.za)   **Business**: Computer Equipment   **Location**: Fourways, Johannesburg  ## Timezone  - **Format**: ISO 8601 with timezone offset (e.g., &#x60;2025-06-22T16:30:45.123+02:00&#x60;)  ## Error Handling &amp; Response Format **Structured Error Response System**  All API errors follow a consistent, structured format for predictable error handling and debugging.  ### Standard Error Response Format &#x60;&#x60;&#x60;json {   \&quot;error\&quot;: \&quot;VALIDATION_FAILED\&quot;,   \&quot;message\&quot;: \&quot;Human-readable error description\&quot;,   \&quot;correlationId\&quot;: \&quot;req-b54f0f5afc234b1239cc5ff6bc8f1bdc\&quot;,   \&quot;timestamp\&quot;: \&quot;2025-07-03T02:32:17.941Z\&quot;,   \&quot;details\&quot;: [     {       \&quot;field\&quot;: \&quot;email\&quot;,       \&quot;constraint\&quot;: \&quot;required\&quot;,       \&quot;value\&quot;: \&quot;\&quot;,       \&quot;message\&quot;: \&quot;Email is required\&quot;     }   ] } &#x60;&#x60;&#x60;  ### Error Types &amp; HTTP Status Codes  | Error Type | HTTP Status | Description | Use Case | |------------|-------------|-------------|----------| | &#x60;VALIDATION_FAILED&#x60; | 400 | Invalid input data or missing required fields | Form validation, parameter validation | | &#x60;AUTHENTICATION_FAILED&#x60; | 401 | Invalid or missing authentication credentials | Login failures, expired tokens | | &#x60;AUTHORIZATION_FAILED&#x60; | 403 | Insufficient permissions for requested resource | Role-based access control violations | | &#x60;RESOURCE_NOT_FOUND&#x60; | 404 | Requested resource does not exist | Invalid IDs, deleted resources | | &#x60;CONFLICT&#x60; | 409 | Resource conflict or duplicate data | Duplicate email registration, concurrent modifications | | &#x60;BUSINESS_ERROR&#x60; | 422 | Business rule violation | Insufficient stock, order cancellation rules | | &#x60;INTERNAL_SERVER_ERROR&#x60; | 500 | Unexpected server error | Database failures, external service errors |   ### Business Logic Errors (422) Include business rule context and error codes: &#x60;&#x60;&#x60;json {   \&quot;error\&quot;: \&quot;BUSINESS_ERROR\&quot;,   \&quot;message\&quot;: \&quot;Order cannot be cancelled. Current status: shipped\&quot;,   \&quot;code\&quot;: \&quot;ORDER_NOT_CANCELLABLE\&quot;,   \&quot;correlationId\&quot;: \&quot;req-def456...\&quot;,   \&quot;timestamp\&quot;: \&quot;2025-07-03T02:32:17.941Z\&quot; } &#x60;&#x60;&#x60;  ### Error Response Headers All error responses include these headers: - &#x60;X-Correlation-ID&#x60;: Request correlation ID for tracing - &#x60;Content-Type&#x60;: &#x60;application/json&#x60; - &#x60;X-RateLimit-*&#x60;: Rate limiting information (when applicable)  ### Client Error Handling Best Practices 1. **Always check the &#x60;error&#x60; field** for programmatic error handling 2. **Use &#x60;correlationId&#x60;** when reporting issues to support 3. **Parse &#x60;details&#x60; array** for field-specific validation errors 4. **Display &#x60;message&#x60;** to users for human-readable feedback 5. **Implement retry logic** for 5xx errors with exponential backoff  ## Real-time Events (Socket.IO) Real-time event streaming via Socket.IO WebSocket connections for inventory and order updates.  ### Connection Endpoint &#x60;&#x60;&#x60;javascript // Connect to Socket.IO server const socket &#x3D; io(&#39;https://yellowsapphire-backend-826925162454.africa-south1.run.app&#39;);  // Authenticate connection socket.emit(&#39;authenticate&#39;, &#39;your_jwt_token&#39;); &#x60;&#x60;&#x60;  ### Real-time Event Categories  #### Inventory Events 1. **inventory:product_update** - New product creation 2. **inventory:stock_change** - Stock level and reservation changes   3. **inventory:transaction** - Inventory transaction analytics 4. **inventory:reservation_update** - Stock reservation lifecycle  #### Order Events   1. **orders:status_change** - Order status transitions  #### FCM Push Notifications 1. **admin_notifications** - New order alerts 2. **inventory_alerts** - Low/critical stock alerts  ### Event Payload Structure All events include: - **timestamp**: ISO 8601 event time - **correlationId**: Request correlation tracking - **type**: Specific event type (e.g., &#39;product_created&#39;, &#39;stock_change&#39;) - **data**: Event-specific payload  ### Authentication Socket.IO connections require JWT authentication via the &#39;authenticate&#39; event. Failed authentication triggers &#39;authentication_error&#39; event.  ## API Versioning &amp; Compatibility  **Current Version**: 2.2.0  **Version Strategy**: Semantic versioning (MAJOR.MINOR.PATCH) - **MAJOR**: Breaking changes requiring client updates - **MINOR**: New features with backward compatibility   - **PATCH**: Bug fixes and security updates  **Deprecation Policy**:  - 6-month notice for breaking changes - Legacy endpoint support for 2 major versions - Migration guides provided for deprecated features  ## Data Models &amp; Relationships  **Core Entities:**  | Entity | Primary Key | Relationships | Change Stream | |--------|-------------|---------------|---------------| | **Customer** | &#x60;_id&#x60; | → Orders, Ratings | &#x60;customer:profile_update&#x60; | | **Admin** | &#x60;_id&#x60; | → Created Products, Orders | &#x60;admin:user_management&#x60; | | **Product** | &#x60;_id&#x60; | ← Categories, → Inventory | &#x60;inventory:product_update&#x60; | | **Order** | &#x60;_id&#x60; | ← Customer, → OrderItems | &#x60;orders:status_change&#x60; | | **Category** | &#x60;_id&#x60; | → Products | &#x60;catalog:category_update&#x60; | | **StockReservation** | &#x60;_id&#x60; | ← Product, ← Order | &#x60;inventory:reservation_update&#x60; | | **InventoryTransaction** | &#x60;_id&#x60; | ← Product, ← Admin | &#x60;inventory:transaction&#x60; | | **AdBanner** | &#x60;_id&#x60; | ← Admin Created | &#x60;content:banner_update&#x60; |  **Data Consistency Rules:** - Stock reservations auto-expire after 15 minutes - Order cancellation allowed only in &#39;pending&#39; or &#39;confirmed&#39; status - Inventory transactions maintain audit trail integrity - Customer verification required for high-value orders  ## Business Rules &amp; Constraints  **Order Management Rules:** &#x60;&#x60;&#x60;yaml Order Lifecycle:   - pending → confirmed → processing → shipped → delivered   - Cancellation: Only &#39;pending&#39; and &#39;confirmed&#39; statuses   - Refunds: Within 30 days of delivery   - Stock: Reserved during &#39;pending&#39;, committed on &#39;confirmed&#39;  Inventory Rules:   - Minimum stock alerts at reorder level   - Negative stock prevention with real-time validation   - Automatic stock reservation for 15-minute checkout window   - Bulk operations require admin approval  Customer Rules:   - Email verification required for orders &gt; R5000   - Phone verification for new accounts   - Rate limiting: 5 login attempts per 15 minutes   - Password complexity: 8+ characters, mixed case &#x60;&#x60;&#x60;  **Business Validation Constraints:** - Product prices must be positive decimals - Order quantities limited to available stock + buffer - Customer profiles require validated South African phone numbers - Admin permissions hierarchical (read → write → admin → super)  ## Performance Optimization  **Caching Strategy:** - **Product Catalog**: Redis cache with 1-hour TTL - **Category Navigation**: In-memory cache with change stream invalidation - **Featured Products**: Database view with scheduled refresh - **User Sessions**: JWT stateless authentication  **Database Optimization:** - Compound indexes on frequent query patterns - Aggregation pipeline optimization for analytics - Connection pooling with 10 concurrent connections - Read replicas for reporting and analytics queries  **Response Time Targets:**  | Endpoint Category | Target Response Time | Monitoring Alert | |-------------------|---------------------|------------------| | Authentication | &lt; 200ms | &gt; 500ms | | Product Catalog | &lt; 300ms | &gt; 800ms | | Order Creation | &lt; 1000ms | &gt; 2000ms | | Admin Reports | &lt; 2000ms | &gt; 5000ms | | Real-time Events | &lt; 50ms | &gt; 200ms |  ## Security Implementation  **Authentication &amp; Authorization Matrix:**  | Role | Product Management | Order Management | User Management | System Config | |------|-------------------|------------------|-----------------|---------------| | **Customer** | Read Only | Own Orders Only | Own Profile | None | | **Fulfillment** | Read/Update Stock | All Orders | None | None | | **Logistics** | Read Only | Update Shipping | None | None | | **Admin** | Full Access | Full Access | Customer Management | Limited | | **Super Admin** | Full Access | Full Access | Full Access | Full Access |  **Security Headers &amp; Policies:** &#x60;&#x60;&#x60;http Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39; &#39;unsafe-inline&#39; X-Content-Type-Options: nosniff X-Frame-Options: DENY   X-XSS-Protection: 1; mode&#x3D;block Referrer-Policy: strict-origin-when-cross-origin &#x60;&#x60;&#x60;  **Rate Limiting Configuration:** - **Authentication endpoints**: 5 requests/15 minutes per IP - **Password reset**: 3 requests/hour per account - **Product search**: 100 requests/minute per user - **Order creation**: 10 requests/minute per customer - **Admin operations**: 1000 requests/minute per admin  ## Integration Ecosystem  **External API Integrations:**  | Service | Purpose | Endpoint Pattern | Timeout | Retry Policy | |---------|---------|------------------|---------|--------------| | **Brevo SMTP** | Email delivery | &#x60;/v3/smtp/email&#x60; | 30s | 3 attempts | | **Firebase FCM** | Push notifications | &#x60;/fcm/send&#x60; | 10s | 2 attempts | | **Cloudinary** | Image processing | &#x60;/v1_1/{cloud}/upload&#x60; | 60s | 1 attempt | | **Barcode Lookup** | Product data | &#x60;/barcode/{ean}&#x60; | 15s | 2 attempts | | **Payment Gateway** | Transaction processing | &#x60;/payment/process&#x60; | 45s | 3 attempts |  **Integration Monitoring:** - Circuit breaker pattern for external failures - Fallback responses for non-critical integrations - Health checks for dependency monitoring - SLA tracking and alerting thresholds  ## Deployment Architecture  **Environment Configuration:**  | Environment | Server | Database | Monitoring | CDN | |-------------|--------|----------|------------|-----| | **Development** | Local Node.js | MongoDB Atlas | Console logs | Local static | | **Staging** | Google Cloud Run | MongoDB Atlas | Cloud Logging | Cloud CDN | | **Production** | Google Cloud Run | MongoDB Atlas | Cloud Operations | Cloud CDN |  **Infrastructure Components:** &#x60;&#x60;&#x60;yaml Load Balancer:   - Health check: /health endpoint   - SSL termination with automatic renewal   - Geographic routing for performance  Application Layer:   - Horizontal auto-scaling (2-10 instances)   - Zero-downtime deployments   - Blue-green deployment strategy  Data Layer:   - MongoDB Atlas M10+ clusters   - Automated backups every 6 hours   - Point-in-time recovery capability   - Read replicas for analytics  Monitoring Stack:   - Google Cloud Operations Suite   - Custom dashboards for business metrics   - Alert policies for SLA violations   - Log aggregation and analysis &#x60;&#x60;&#x60;  ## DevOps &amp; CI/CD Pipeline  **Continuous Integration:** &#x60;&#x60;&#x60;mermaid graph LR A[Git Push] --&gt; B[GitHub Actions] B --&gt; C[Lint &amp; Test] C --&gt; D[Build Docker Image] D --&gt; E[Security Scan] E --&gt; F[Deploy to Staging] F --&gt; G[Integration Tests] G --&gt; H[Deploy to Production] &#x60;&#x60;&#x60;  **Deployment Checklist:** - ✅ All tests passing (unit, integration, e2e) - ✅ Security vulnerability scan complete - ✅ Database migration scripts validated - ✅ Environment variables updated - ✅ Monitoring alerts configured - ✅ Rollback plan documented  **Health Check Endpoints:** - &#x60;/health&#x60; - Basic server health - &#x60;/health/detailed&#x60; - Component status - &#x60;/health/dependencies&#x60; - External service status - &#x60;/metrics&#x60; - Prometheus-compatible metrics  ## Analytics &amp; Business Intelligence  **Key Performance Indicators (KPIs):**  | Metric Category | KPI | Target | Alert Threshold | |-----------------|-----|--------|-----------------| | **Performance** | API Response Time | &lt; 500ms | &gt; 1000ms | | **Availability** | Uptime | 99.9% | &lt; 99.5% | | **Business** | Order Conversion | &gt; 15% | &lt; 10% | | **Customer** | Registration Rate | &gt; 5/day | &lt; 2/day | | **Inventory** | Stock Turnover | &gt; 80% | &lt; 60% |  **Analytics Data Flow:** &#x60;&#x60;&#x60; User Actions → Event Logging → Data Pipeline → Analytics Dashboard → Business Insights &#x60;&#x60;&#x60;  **Reporting Capabilities:** - Real-time inventory levels and alerts - Customer behavior analytics and patterns - Order fulfillment metrics and bottlenecks - Revenue tracking and forecasting - System performance and reliability metrics  ## Disaster Recovery &amp; Business Continuity  **Backup Strategy:** - **Database**: Automated daily backups with 30-day retention - **Application Code**: Git repository with multiple remotes - **Configuration**: Infrastructure as Code (Terraform) - **Secrets**: Encrypted backup in secure vault  **Recovery Time Objectives (RTO):** - **Critical Services**: 15 minutes - **Full System**: 2 hours - **Data Recovery**: 1 hour  **Recovery Point Objectives (RPO):** - **Transactional Data**: 5 minutes - **Configuration Changes**: 1 hour - **Analytics Data**: 24 hours  **Incident Response Procedures:** 1. **Detection**: Automated monitoring alerts 2. **Assessment**: Severity classification (P0-P4) 3. **Response**: Escalation matrix activation 4. **Communication**: Status page updates 5. **Resolution**: Root cause analysis 6. **Post-mortem**: Process improvement  ## Developer Experience &amp; Onboarding  **Development Environment Setup:** &#x60;&#x60;&#x60;bash # Clone repository git clone https://github.com/company/yellowsapphire-backend  # Install dependencies npm install  # Configure environment cp .env.example .env.local  # Start development server npm run dev  # Run tests npm test &#x60;&#x60;&#x60;  **API Testing Tools:** - **Postman Collections**: Pre-configured request collections - **Newman CLI**: Automated API testing - **Swagger UI**: Interactive API documentation - **Jest**: Unit and integration testing - **Supertest**: HTTP assertion testing  **Code Quality Standards:** - **TypeScript**: Strict type checking enabled - **ESLint**: Consistent code style enforcement - **Prettier**: Automatic code formatting - **Husky**: Pre-commit hooks for quality gates - **SonarQube**: Code quality and security analysis  ## Troubleshooting Guide  **Common Issues &amp; Solutions:**  | Issue | Symptoms | Root Cause | Solution | |-------|----------|------------|----------| | **High Response Time** | API calls &gt; 2s | Database connection pool exhaustion | Restart service, check connection limits | | **Authentication Failures** | 401 errors increasing | JWT token expiration | Verify token generation and expiry settings | | **Stock Inconsistency** | Negative inventory | Race condition in concurrent updates | Review transaction isolation levels | | **Failed Email Delivery** | Emails not sending | SMTP service disruption | Check Brevo service status and credentials | | **Real-time Events Down** | Socket.IO disconnections | WebSocket connection limits | Scale Socket.IO instances |  **Debug Information Collection:** &#x60;&#x60;&#x60;bash # System health check curl http://localhost:3000/health/detailed  # Application logs docker logs yellowsapphire-backend --tail&#x3D;100  # Database connection status mongosh --eval \&quot;db.adminCommand(&#39;connPoolStats&#39;)\&quot;  # Memory usage analysis node --inspect app.js # Enable debugger &#x60;&#x60;&#x60;  **Monitoring &amp; Alerting:** - **Error Rate**: &gt; 5% triggers immediate alert - **Response Time**: &gt; 1s average triggers warning - **Database**: Connection pool &gt; 80% triggers alert - **Memory**: Heap usage &gt; 90% triggers critical alert - **Disk Space**: &lt; 10% free triggers urgent alert  ## Feature Flags Configuration   **Environment Variables Reference:**  | Variable | Type | Default | Description | Required | |----------|------|---------|-------------|----------| | &#x60;NODE_ENV&#x60; | string | development | Runtime environment | ✅ | | &#x60;PORT&#x60; | number | 3000 | Server listening port | ✅ | | &#x60;MONGODB_URI&#x60; | string | - | MongoDB connection string | ✅ | | &#x60;JWT_SECRET&#x60; | string | - | JWT signing secret (256-bit) | ✅ | | &#x60;JWT_EXPIRES_IN&#x60; | string | 24h | Token expiration time | ❌ | | &#x60;BCRYPT_ROUNDS&#x60; | number | 12 | Password hashing rounds | ❌ | | &#x60;RATE_LIMIT_WINDOW&#x60; | number | 900000 | Rate limit window (15 min) | ❌ | | &#x60;RATE_LIMIT_MAX&#x60; | number | 100 | Max requests per window | ❌ | | &#x60;BREVO_API_KEY&#x60; | string | - | Email service API key | ✅ | | &#x60;FIREBASE_PROJECT_ID&#x60; | string | - | Firebase project identifier | ✅ | | &#x60;CLOUDINARY_CLOUD_NAME&#x60; | string | - | Image service cloud name | ✅ | | &#x60;SOCKET_IO_CORS_ORIGIN&#x60; | string | * | WebSocket CORS origins | ❌ | | &#x60;LOG_LEVEL&#x60; | string | info | Logging verbosity level | ❌ |  **Feature Flags &amp; Toggles:** &#x60;&#x60;&#x60;json {   \&quot;features\&quot;: {     \&quot;realTimeInventory\&quot;: true,     \&quot;advancedAnalytics\&quot;: true,     \&quot;multiCurrencySupport\&quot;: false,     \&quot;socialAuthentication\&quot;: false,     \&quot;advancedSearch\&quot;: true,     \&quot;bulkOperations\&quot;: true,     \&quot;webhookNotifications\&quot;: false,     \&quot;experimentalFeatures\&quot;: false   },   \&quot;limits\&quot;: {     \&quot;maxOrderItems\&quot;: 50,     \&quot;maxFileUploadSize\&quot;: \&quot;10MB\&quot;,     \&quot;maxConcurrentConnections\&quot;: 1000,     \&quot;maxBulkOperationSize\&quot;: 100   } } &#x60;&#x60;&#x60;  ##Security Features  **Input