**MercuryPay**

**Cloud Layer**

Current System — Feature List

Prepared for: RFP 52-2026

System: CloudLayer-main (Elixir / Phoenix Framework)

June 2026

**1. System Overview**

The MercuryPay Cloud Layer (CloudLayer-main, internally da\_product\_app) is the central cloud-hosted API platform built on Elixir and the Phoenix web framework. It connects POS terminals, ERP/billing systems, QR payment providers, and the transaction switch into a unified cloud service. Its three primary responsibilities are: (1) QR payment orchestration — generating and pushing QR codes to physical terminals/Soundboxes via MQTT and polling providers for settlement; (2) Rules Engine — evaluating configurable per-merchant/per-terminal transaction rules to produce Allow/Decline decisions plus merchant receipt metadata; and (3) ERP/Billing Integration — accepting payment initiation requests from hospital and enterprise billing systems and orchestrating payment notification callbacks. The system also exposes a full Merchant Management REST API consumed by the TMS and Merchant Management portal, manages device OTA firmware updates, and provides a Phoenix LiveView admin web interface.

**2. QR Payment Processing**

**2.1 QR Payment Initiation**

|                                        |                                                                                                                                                                                                                                                                          |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Feature**                            | **Description**                                                                                                                                                                                                                                                          |
| **QR Transaction Initiate (v1)**       | POST /api/qr/initiate: authenticated endpoint to initiate a QR payment. Validates provider, amount, and device; generates QR code from the selected provider (Alipay/AANI); publishes QR code to POS terminal via MQTT; logs all steps as custom events for audit trail. |
| **QR Transaction Initiate (Legacy)**   | POST /api/device/initiate: older endpoint supporting both QR (txnType='QR') and card (txnType='card') transaction types. Generates a unique external reference number if not provided by caller.                                                                         |
| **Device API Initiate**                | POST /api/device: initiates a QR or card payment via device serial number lookup. Supports auto-generation of externalRefNumber for systems that do not supply their own reference ID.                                                                                   |
| **Morefun QR Initiate**                | POST /api/Iotmsgtest/createQrMf: dedicated public endpoint for Morefun POS terminal-initiated QR transactions. Device serial number used to look up provider and merchant hierarchy.                                                                                     |
| **QR Code Generation**                 | POST /api/generate\_qr / POST /api/qr: generates QR code payload for a given transaction, amount, and provider. Returns QR code ID to caller. Routes request to appropriate provider module via QRProviderFactory.                                                       |
| **Dynamic QR Per Transaction**         | Each QR payment generates a unique, single-use QR code containing the transaction reference ID, merchant ID, store, amount, and currency. QR codes are not reusable across transactions.                                                                                 |
| **Static QR Per Merchant Store**       | POST /api/merchant/store/qr: retrieves or generates a persistent static QR code for a merchant store. Static QR supports open-amount payments where the customer enters the amount on their wallet app.                                                                  |
| **External Reference Number Chaining** | Supports multiple external reference fields (externalRefNumber, externalRefNumber2, externalRefNumber4, externalRefNumbers) enabling billing systems to attach their own transaction IDs for reconciliation.                                                             |

**2.2 QR Payment Status & Notifications**

|                                              |                                                                                                                                                                                                                                                                                       |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                                  | **Description**                                                                                                                                                                                                                                                                       |
| **QR Payment Status Query**                  | POST /api/qr/status and POST /api/device/status: polls the provider for real-time payment status by transaction reference ID. Returns current state (pending/success/failed) for the calling system.                                                                                  |
| **Morefun Status Query**                     | POST /api/qrmorefun/status: Morefun terminal-specific status check for QR payments, returning current transaction outcome and provider response details.                                                                                                                              |
| **Alipay Payment Polling**                   | After Alipay QR generation, the system starts an asynchronous background task that polls Alipay's inquiryPayment API every 10 seconds for up to 12 attempts (2 minutes) until a PAYMENT\_SUCCESS or terminal failure state is detected.                                               |
| **Payment Success Notification to Soundbox** | POST /api/payment/notify-success: upon receiving a payment success callback from the bank/provider, the Cloud Layer publishes an MQTT message to the physical Soundbox/terminal containing the transaction amount, time, and request\_id for audible and visual payment confirmation. |
| **Alipay Webhook**                           | POST /api/alipay/notify\_payment: receives asynchronous payment notification from Alipay's servers. Updates transaction status in the database and triggers Soundbox notification.                                                                                                    |
| **Alipay Dummy Notify**                      | POST /api/alipay/dummy/notify: sandbox endpoint to simulate Alipay payment notifications for integration testing without a live Alipay connection.                                                                                                                                    |
| **Transaction Status Tracking**              | All QR transactions maintained in a dedicated transactions table with status lifecycle: pending → success / failed. Settlement date/time recorded when payment clears.                                                                                                                |

**2.3 QR Payment Operations**

|                                         |                                                                                                                                                                                                                     |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                             | **Description**                                                                                                                                                                                                     |
| **QR Payment Cancel**                   | POST /api/cancelPayment: cancels an in-progress QR payment. Routes cancel request to the appropriate provider (Alipay/AANI) and updates transaction status to cancelled.                                            |
| **QR Payment Refund**                   | POST /api/refundPayment: initiates a refund for a completed QR transaction. Refund reference ID stored against the original transaction for tracking. Routes to provider refund API.                                |
| **Middle Layer Transaction Processing** | POST /api/processTransaction: QR middle layer controller that orchestrates the full QR payment flow — device lookup, hierarchy resolution, provider call, polling, and response assembly — in a single API call.    |
| **New Middle Layer Transaction**        | POST /api/processNewMiddleTransaction: enhanced version of the QR middle layer with additional validation, dual-database hierarchy support, and improved error codes (MERCURY\_XXXXXXX format).                     |
| **Receipt Reprint**                     | POST /api/reprint\_last: retrieves the last completed transaction for a given merchant ID, terminal ID, and optional serial number — enabling POS terminals to reprint the last receipt without storing it locally. |
| **Transaction Refund Details**          | POST /api/merchant/transactionRefundDetails: returns full refund details for a given transaction ID, including refund reference, amount, status, and provider confirmation.                                         |

**3. QR Payment Providers**

|                                         |                                                                                                                                                                                                                                                                                                         |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                             | **Description**                                                                                                                                                                                                                                                                                         |
| **Alipay+ Integration**                 | Full Alipay+ payment provider integration: QR code generation via POST to open-sea-global.alipayplus.com, RSA256-signed API calls with client-id and request-time headers, payment inquiry, and webhook notification handling. Supports transaction and settlement currency separation (e.g., AED/USD). |
| **AANI Integration (UAE Central Bank)** | AANI (Oman/UAE Central Bank instant payment network) QR provider integration: QR registration with group code, bank user ID, merchant tag, payment category/purpose, and QR code status query. Supports sandbox and production URL switching.                                                           |
| **WeChat+ Integration**                 | WeChat+ QR payment provider stub integration, generating device-specific QR codes. Configured for future full integration with WeChat Pay API for tourist-focused payments.                                                                                                                             |
| **QR Provider Abstraction**             | QRProvider behaviour (interface) allows all QR providers (Alipay, AANI, WeChat) to implement a uniform generate/2 and status/1 API. QRProviderFactory selects the correct provider at runtime based on the device's associated provider configuration.                                                  |
| **Provider Registration — Alipay**      | Alipay merchant registration API integration: submits merchant details (business name, registration number, MCC, address, business type) to Alipay's merchant onboarding API with RSA256 signature. Business types mapped to Alipay enums (RETAIL, SERVICE, RESTAURANT, ECOMMERCE → ENTERPRISE).        |
| **Provider Registration — AANI**        | AANI merchant registration via AaniProvider: sends merchant details to AANI's onboarding endpoint; supports inquiry of registration status via referenceMerchantId.                                                                                                                                     |
| **Provider Routing**                    | MerchantRegistration.ProviderRouter routes generic registration/inquiry requests to the appropriate provider module (AANI or Alipay) based on the provider parameter, enabling consistent API for all provider onboarding workflows.                                                                    |
| **Multi-Currency Support**              | Transactions support separate transaction currency and settlement currency (e.g., AED transaction settling in USD). Amount conversion to provider-smallest-unit handles AED (÷100), JPY (×1), and AANI (no conversion) appropriately.                                                                   |

**4. Soundbox & Device Integration**

|                                         |                                                                                                                                                                                                                                                                                        |
| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                             | **Description**                                                                                                                                                                                                                                                                        |
| **MQTT QR Code Push**                   | QR codes are delivered to physical Soundbox/POS devices via MQTT publish on topic /ota/{clientId}/{deviceId}/update. The QR payload includes the encoded QR image, transaction reference, amount, and timestamp for immediate display on the device screen.                            |
| **MQTT Device Online/Offline Tracking** | MQTT connection/disconnection events (Tortoise.Handler callbacks) update DeviceRegistry in real time. DeviceRegistry.track\_online/track\_offline maintain a live map of connected devices, enabling the cloud layer to verify device availability before initiating a QR transaction. |
| **MQTT ACK Receipt**                    | Devices publish acknowledgement messages on topic /ack/qr-device/{deviceId} upon successfully receiving a QR payload. The MQTT handler broadcasts the ACK to Phoenix PubSub channel qr:ack:{deviceId} so the initiating API request can be resolved with delivery confirmation.        |
| **MQTT OTA Update Delivery**            | Software/firmware updates are pushed to devices via MQTT with a request\_id. The MQTT handler receives ACK responses with update status (success/failed) and updates the cloud\_transaction record for the OTA event — enabling status tracking of each device's update lifecycle.     |
| **Payment Notification via MQTT**       | Upon payment success, the Cloud Layer publishes a structured MQTT notification payload (broadcast\_type=1, money, biz\_type=1, datetime, ctime, request\_id) to the device topic. Physical Soundboxes play an audio alert and display the payment amount upon receiving this message.  |
| **Device Status Query**                 | POST /api/device/status: checks whether a specific device is currently online and reachable. Returns device connectivity status by querying DeviceRegistry, allowing callers to verify device availability before pushing a QR transaction.                                            |
| **Device Registry**                     | DaProductApp.DeviceRegistry maintains a supervised in-memory registry of online/offline device states using ETS tables. Registry is consulted before every MQTT publish to avoid sending QR codes to offline devices.                                                                  |
| **MQTT Client Supervisor**              | DaProductApp.MQTT.Supervisor manages the Tortoise MQTT client lifecycle — automatic reconnection on broker disconnection, subscription to device ACK and OTA response topics, and QoS 1 message delivery guarantee.                                                                    |

**5. Rules Engine**

|                                       |                                                                                                                                                                                                                                                                                                               |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                           | **Description**                                                                                                                                                                                                                                                                                               |
| **Transaction Rules Evaluation API**  | POST /v1/transaction-rules/evaluate: the Rules Engine endpoint consumed by the Transaction Switch (jpos-main) before every financial transaction. Accepts merchant\_id, terminal\_id, amount, transaction type, STAN, RRN, timestamp, and context (channel, acquirer\_id).                                    |
| **Allow / Decline Decision**          | The evaluate endpoint returns a structured JSON response with a decision field of 'ALLOW' or 'DECLINE', a reason code, message, and the normalised amount. The Transaction Switch honours this decision — DECLINE terminates the transaction without contacting the acquirer.                                 |
| **Administrative Transaction Bypass** | LOGON, SETTLEMENT, batch close, and key exchange transactions (detected by transaction type or absent merchant\_id) bypass rule evaluation and receive an immediate ALLOW response with default merchant metadata.                                                                                            |
| **BIN Validation**                    | Every financial transaction's card BIN is validated against supported ranges: Visa (400000–599999) and Mastercard (222100–272000). Cards with BINs outside these ranges are declined with code 31 and message 'Card BIN not supported' — configurable without code changes.                                   |
| **Rule Scope Hierarchy**              | Rules are evaluated in priority order: terminal-specific rules first, then merchant-level rules, then global rules. Lower priority number = higher precedence. Scope values: :terminal, :merchant, :global, :user. Deleted (soft-delete via deleted\_at) and disabled rules are excluded.                     |
| **VELOCITY\_COUNT Rule**              | Declines a transaction if the number of transactions from a terminal exceeds a configured maximum within a sliding time window. Counts all transaction attempts (pending + completed) to prevent rapid-fire abuse.                                                                                            |
| **VELOCITY\_AMOUNT Rule**             | Declines a transaction if the total transaction amount from a terminal within a configured time window exceeds a threshold. Prevents high-value fraud via repeated small transactions.                                                                                                                        |
| **DAILY\_TOTAL Rule**                 | Declines transactions when the cumulative transaction amount for the current calendar day at a terminal or merchant exceeds a configured daily cap. Resets at midnight UTC.                                                                                                                                   |
| **WEEKLY\_TOTAL Rule**                | Weekly cumulative spend limit enforcement: declines transactions when the terminal's weekly transaction total exceeds the configured weekly threshold.                                                                                                                                                        |
| **MONTHLY\_TOTAL Rule**               | Monthly cumulative spend limit enforcement: declines transactions when the terminal's monthly transaction total exceeds the configured monthly cap. Supports high-value merchant monthly volume limits.                                                                                                       |
| **REFUND\_VELOCITY Rule**             | Limits the number of refunds a terminal can process within a given period. Declines refund requests when the refund count exceeds the configured maximum, protecting against refund fraud.                                                                                                                    |
| **Merchant Info Resolution**          | For every transaction, the rules engine resolves merchant name, address, logo, receipt message, and receipt description by joining pos\_terminals → stores → addresses and querying merchant\_configuration in the ShukriaMms database via merchant reference number.                                         |
| **Merchant Configuration Settings**   | merchant\_configuration settings map includes keys: BASE\_MERCHANT\_NAME (legal name override), TOMS\_FLY\_RECEIPT (receipt generation flag), model\_name (device model flag for MF919 Soundbox), and cardholder\_name\_enabled. Settings are merged with global defaults when per-merchant config is absent. |
| **Receipt Metadata in Rule Response** | Every ALLOW response includes full receipt header (logo, merchant\_name, merchant\_address) and footer (message, description) so the Transaction Switch can pass these to ReceiptGenerator in DE-63 without a separate database lookup.                                                                       |
| **Cardholder Name Flag**              | show\_cardholder\_name flag in the rules response controls whether the POS terminal prints the cardholder name on the receipt — configurable per merchant in merchant\_configuration.                                                                                                                         |
| **Idempotency Key Support**           | The evaluate endpoint accepts an Idempotency-Key request header for deduplication. Duplicate requests with the same idempotency key within a processing window return the cached result without re-evaluating rules.                                                                                          |
| **Request Tracking**                  | Every rules evaluation request is assigned an X-Request-Id (generated if not provided). All log entries reference this ID, enabling end-to-end tracing of each transaction through the rules engine.                                                                                                          |

**6. ERP & Billing System Integration**

|                                          |                                                                                                                                                                                                                                                                                                                                            |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Feature**                              | **Description**                                                                                                                                                                                                                                                                                                                            |
| **ERP Payment Initiation**               | Cloud Layer accepts payment initiation requests from third-party ERP and hospital billing systems. The transaction schema includes fields specific to enterprise billing: patient\_name, uhid (unique health ID), charge\_rate, location\_id, transaction\_location, and credentials\_user/credentials\_key for ERP system authentication. |
| **Billing System Credentials**           | Each ERP-initiated transaction carries credentials\_user and credentials\_key fields allowing the Cloud Layer to authenticate the call back to the billing system's response endpoint. This supports billing systems that require mutual authentication on the callback.                                                                   |
| **Return URL & Response URL**            | Payment initiation accepts return\_url and response\_url fields: return\_url is used for browser redirect flows; response\_url is the ERP webhook endpoint to receive the payment result notification upon transaction completion.                                                                                                         |
| **Pay Mode Tracking**                    | pay\_mode field on transactions records the payment mode selected by the billing system (QR, card, etc.), enabling billing system reconciliation of payment method mix across locations.                                                                                                                                                   |
| **Cloud Transaction Record**             | All ERP/billing-initiated transactions are stored in cloud\_transaction table with complete ERP context (uhid, location, credentials, reference IDs) plus payment outcome fields (status, payment\_reference\_id, settlement\_date\_time, refund\_reference\_id).                                                                          |
| **External Reference Numbers**           | Supports up to four external reference number fields (externalRefNumber through externalRefNumber4) to carry ERP system identifiers, encounter numbers, invoice numbers, and appointment IDs simultaneously for reconciliation.                                                                                                            |
| **Account Label Support**                | accountLabel field identifies the billing department or cost centre within the enterprise, enabling billing system-side reconciliation by department.                                                                                                                                                                                      |
| **Customer Contact Capture**             | customer\_mobile\_number and email fields on transactions allow customer receipts and payment notifications to be delivered to the patient/customer directly via SMS or email from the ERP system.                                                                                                                                         |
| **Transaction Search by Email**          | GET /api/getTransactionDetailFromEmail: allows billing systems to retrieve transaction details by customer email address, supporting customer service and refund workflows in hospital/enterprise contexts.                                                                                                                                |
| **Location-Based Device Selection**      | location\_id maps to a physical location (ward, counter, clinic), allowing the ERP system to push a payment to the device assigned to that specific location without needing to know the device serial number.                                                                                                                             |
| **Transaction Webhook (Non-CSRF Route)** | POST /transaction\_post: non-CSRF-protected route accepting transaction posts from external ERP systems that cannot include CSRF tokens. Processes the payment record and acknowledges receipt.                                                                                                                                            |
| **Processing ID Idempotency**            | processing\_id field on cloud\_transaction supports idempotent transaction lookup: CloudTransaction.get\_transaction\_by\_processing\_id/1 retrieves an existing transaction by the ERP's processing reference, preventing duplicate payments.                                                                                             |

**7. Merchant Management API**

|                                    |                                                                                                                                                                                                                                                                        |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                        | **Description**                                                                                                                                                                                                                                                        |
| **Merchant Hierarchy API**         | GET /api/merchant/hierarchy: returns the complete merchant hierarchy — group (chain) → brand → store → device structure — for a given merchant reference ID. Used by TMS and Merchant Management portal to build navigation and device assignment workflows.           |
| **Group / Chain Management**       | POST /api/chain (create) and PUT /api/chain (update): manage merchant chain/group entities with name, code, and metadata. Groups are the top level of the merchant hierarchy.                                                                                          |
| **Brand Management**               | GET /api/merchant/brands: retrieves all brands associated with a merchant group. Brands are the second level of the hierarchy, grouping related stores under a single trading name.                                                                                    |
| **Store Management**               | POST/PUT/DELETE /api/store: full CRUD for merchant stores. Each store is linked to a brand, has a unique code, and references an address record for receipt and compliance purposes.                                                                                   |
| **Store & Address Save**           | POST /api/merchant/saveStoreAndAddress: atomic operation creating a store and its address in a single API call, preventing orphaned store records without address data.                                                                                                |
| **Group and Brand Creation**       | POST /api/merchant/createGroupAndBrand: creates a new group and brand atomically — used during merchant onboarding to establish the full hierarchy in one step.                                                                                                        |
| **Device / Terminal Registration** | POST /api/merchant/saveDevice: registers a new POS terminal/Soundbox against a store. Records serial number, device type, terminal ID, provider ID, and store assignment.                                                                                              |
| **Device Update**                  | POST /api/merchant/updateDevice: updates device details. POST /api/merchant/forceUpdateDevice: forces an update even if the device is currently in an active transaction.                                                                                              |
| **Merchant Reference Update**      | POST /api/merchant/updateMerchantReference: updates the merchant reference number on a device, used when merchant identifiers change after onboarding.                                                                                                                 |
| **Shukria Terminal Management**    | POST /api/merchant/getShukriaTerminalsDetails, createShukriaTerminalsDetails, checkDuplicateShukriaTerminal: manage Shukria-specific terminal records in the ShukriaMms database, supporting multi-database terminal operations.                                       |
| **TID/MID Duplicate Checking**     | POST /api/merchant/checkDuplicateTidMid, checkDuplicateMid, checkDuplicateYspTidMid: validation endpoints preventing duplicate terminal/merchant ID assignments across the system and at the YSP acquirer level.                                                       |
| **Provider Management**            | GET /api/merchant/providers: retrieves QR payment providers available to a merchant. POST /api/merchant/getProvidersByAlias: lookup by alias. POST /api/merchant/updateShukriaProviderMidTid and updateShukriaYspMidTid: update provider-specific TID/MID assignments. |
| **AANI Terminal Check**            | POST /api/merchant/checkExistingAnniShukriaTerminal: checks if a terminal is already registered on the AANI QR network, preventing duplicate AANI registrations.                                                                                                       |
| **Store Details API**              | GET /api/storeDetails and GET /api/merchantStores: retrieve store details with address, brand, and neo\_merchant\_id. Supports multiple query modes (by merchantRefId and by store\_id).                                                                               |
| **Device Details API**             | GET /api/merchantDevices, GET /api/deviceDetails, GET /api/merchantDeviceDetails, GET /api/uniqueDeviceDetails: comprehensive device detail APIs for terminal lookup by serial number, provider ID, and store ID.                                                      |
| **MCC Code Management**            | POST /api/addMCCCode: adds Merchant Category Codes (MCC) to the system. MCC codes (e.g., 5411 for grocery) are used in QR payment requests to classify merchant type for network routing.                                                                              |
| **Batch Number Management**        | POST /api/merchant/saveMerchantBatchNumber: records the current settlement batch number for a merchant terminal, synchronising batch state between the Transaction Switch and Cloud Layer.                                                                             |

**8. Transaction Reporting & Analytics**

|                                         |                                                                                                                                                                                                                                                                    |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Feature**                             | **Description**                                                                                                                                                                                                                                                    |
| **Admin Success Transactions**          | GET /api/admin/successTransactions: unified view of all successful QR + card transactions across all merchants, joined with device and store details. Filterable by date range. Shows provider, payment mode, settlement status, and merchant hierarchy.           |
| **Admin Failed Transactions**           | GET /api/admin/failedTransactions: retrieves all declined and failed transactions (QR + card) system-wide with failure reason, response code, and device/store context.                                                                                            |
| **Admin Pending Transactions**          | GET /api/admin/pendingTransactions: lists transactions in a pending/in-progress state that may require intervention — identifies orphaned QR payments and stuck authorisations.                                                                                    |
| **Admin Reversal Transactions**         | GET /api/admin/reversalTransactions: retrieves all card transaction reversals from the pos\_transaction\_reversal table, showing reversal status, retry count, and reason.                                                                                         |
| **Admin Total Stores & Devices**        | GET /api/admin/totalStores and GET /api/admin/totalDevices: aggregate counts of registered stores and devices for operations dashboards.                                                                                                                           |
| **Merchant QR Transactions**            | GET /api/merchant/statusTransactions: filterable merchant-level view of QR transactions by status. Separate endpoints for Alipay (/merchant/alipayTransactions), AANI (/merchant/annipayTransactions), and static QR (/merchant/staticTransactions) payment types. |
| **Merchant Card Transactions**          | GET /api/merchant/cardTransactions: retrieves card (ISO 8583) transactions for a specific merchant with date-range and status filtering, reading from the jPOS middleware database via the shared pos\_transactions view.                                          |
| **All Card Transactions**               | GET /api/getAllCardTransaction: retrieves card transactions across all merchants with optional filtering by merchant\_id and date range. Unions pos\_transaction, pos\_failed\_transaction, and pos\_temp\_transaction tables for a complete view.                 |
| **Card Transaction by ID**              | GET /api/getCardTransactionById/:id: retrieves a single card transaction by database ID with full field details including encrypted PAN, proc\_code, approval\_code, response\_code, and metadata.                                                                 |
| **Reversal Transaction by ID**          | GET /api/getReversalCardTransactionById/:id: retrieves a specific reversal transaction record with status, retry count, and original transaction linkage.                                                                                                          |
| **Device Detail by Serial/Terminal ID** | GET /api/getDeviceDetailFromDeviceIdTerminalId and /api/getCardDeviceDetailFromDeviceIdProviderId: look up device configuration by serial number + terminal ID or serial number + provider ID combinations.                                                        |
| **Static QR Transactions**              | POST /api/staticqrtransactions: retrieves transactions initiated via store-level static QR codes, enabling merchants to reconcile static QR revenue separately from dynamic QR and card payments.                                                                  |
| **Transaction Custom Log Query**        | GET /api/getCustomLogFromTxnId: retrieves the full event audit trail for a specific transaction — all lifecycle events (initiate, MQTT publish, provider response, ACK) stored in custom\_event\_log.                                                              |

**9. Software & OTA Device Management**

|                                 |                                                                                                                                                                                                                                          |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                     | **Description**                                                                                                                                                                                                                          |
| **Software Catalogue**          | Software schema maintains a catalogue of deployable software components (name, slug, last\_updated) with associated versions. Provides the foundation for OTA update management across the terminal fleet.                               |
| **Software Version Management** | SoftwareVersion schema tracks individual release versions per software component — version number, release notes, and deployment date — enabling version history and rollback tracking.                                                  |
| **OTA Update via MQTT**         | Firmware/software updates are pushed to individual terminals via MQTT OTA topics. Cloud Layer publishes update payload with request\_id; device downloads and applies the update, then sends an ACK.                                     |
| **OTA Status Tracking**         | cloud\_transaction records are used to track OTA update lifecycle: cloud\_transaction is created when the OTA update is dispatched, and updated with status (success/failed) and acknowledgement flag when the device responds via MQTT. |
| **Software LiveView**           | Phoenix LiveView /software route provides an authenticated web interface for administrators to browse the software catalogue, view version history, and track deployment status across the terminal fleet.                               |
| **SBOM Component Viewer**       | SbomComponentLive provides a Software Bill of Materials (SBOM) viewer at /sbomcomponent showing all third-party software components included in the system, supporting compliance and security audit requirements.                       |

**10. User Management & Authentication**

|                                 |                                                                                                                                                                                                                                                                                   |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                     | **Description**                                                                                                                                                                                                                                                                   |
| **User Registration**           | POST /users/register (LiveView): user sign-up with email and password. Bcrypt password hashing via bcrypt\_elixir. Email confirmation required before account activation.                                                                                                         |
| **User Login / Session**        | POST /users/log\_in: session-based authentication. User token stored in session. require\_authenticated\_user plug protects all admin routes.                                                                                                                                     |
| **Email Confirmation**          | GET /users/confirm/:token: confirms email address via time-limited token sent by the system. UserConfirmationLive handles the confirmation flow.                                                                                                                                  |
| **Password Reset**              | Forgot password flow via /users/reset\_password (request) and /users/reset\_password/:token (submit new password). Time-limited reset tokens managed in user\_tokens table.                                                                                                       |
| **User Settings**               | LiveView /users/settings: allows authenticated users to change email address and password. Email change requires re-confirmation of the new address.                                                                                                                              |
| **API Key Authentication**      | ApiKeyAuth plug validates a shared-secret API key in the Authorization header using Plug.Crypto.secure\_compare (constant-time comparison) for all protected REST API routes. Invalid or missing keys return 401 Unauthorized with structured JSON error.                         |
| **Role-Based Route Protection** | Router pipeline :require\_authenticated\_user enforces session authentication for all web dashboard routes; :api\_auth pipeline enforces API key auth for REST API routes. Public API endpoints (device initiate, QR Morefun, rules evaluate, merchant logo) are unauthenticated. |
| **User Invitation**             | Invite user email template (invite\_user.html.heex) supports email-based invitation workflow for onboarding new admin users without requiring self-registration.                                                                                                                  |

**11. Event Logging & Audit Trail**

|                                  |                                                                                                                                                                                                                                                 |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                      | **Description**                                                                                                                                                                                                                                 |
| **Custom Event Framework**       | All significant system events are stored in a custom\_events / custom\_event\_log two-table structure. Events are identified by name and alias (snake\_case of name), enabling event-type grouping and per-reference-ID log replay.             |
| **QR Lifecycle Event Logging**   | Every step of the QR payment lifecycle is logged: Initiate QR Txn Request, Response Received From Middle Layer, Request For Publish Txn In MQTT, Response From Publish Txn In MQTT, Response From Device Online Status, and provider responses. |
| **Structured Event Payloads**    | Each event log entry captures a structured payload: amount, device\_id, QR code ID, merchant reference, external reference number, provider name, and username. Payloads vary by event type and are stored as JSONB/map in the database.        |
| **Transaction-Linked Event Log** | Event log entries can be linked to a specific transaction\_id, enabling reconstruction of the complete event sequence for any given payment for support and dispute investigation.                                                              |
| **File-Based Logger**            | DaProductApp.FileLogger provides a weekly-rotating file log (rotated when week boundary crosses) alongside the standard Logger, ensuring no logs are lost during high-throughput periods.                                                       |
| **Event Log Query**              | GET /api/getCustomLogFromTxnId: retrieves the full event log for a transaction ID, allowing support teams to trace every step of a payment from initiation to settlement or failure.                                                            |

**12. Multi-Database Architecture**

|                                          |                                                                                                                                                                                                                                                                              |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                              | **Description**                                                                                                                                                                                                                                                              |
| **Primary Database (Main Repo)**         | DaProductApp.Repo connects to the main application database containing: transactions, cloud\_transactions, pos\_terminals, stores, brands, groups, addresses, software, providers, and custom event tables.                                                                  |
| **ShukriaMms Database (Secondary Repo)** | DaProductApp.Repos.ShukriaMmsRepo connects to the ShukriaMms (Merchant Management System) secondary database containing: transaction\_rules, user\_metadata, kyc\_requests, merchant\_configuration, and user tables. Enables rules engine and merchant portal data sharing. |
| **Device Middlelayer Database Views**    | device\_middlelayer module provides Ecto schemas (PosTransaction, PosFailedTransaction, PosTempTransaction, PosTransactionReversal) that map to the jPOS Transaction Switch database tables, giving the Cloud Layer read access to card transaction data.                    |
| **Merchant Reference Number Resolution** | merchant\_id values from API requests are resolved to internal user\_id by querying user\_metadata.merchant\_refrence\_number in ShukriaMmsRepo — enabling a single merchant reference to work across both databases.                                                        |
| **Dual-Database Rule Evaluation**        | Transaction rules evaluation queries both databases: terminal/store/address from Main Repo, and rules + merchant\_configuration + user\_metadata from ShukriaMmsRepo — results merged before returning the evaluate response.                                                |
| **Ecto Multi-Repo Queries**              | Separate Ecto repos with independent connection pools and configuration allow each database to have its own SSL, pool size, and timeout settings, preventing contention between OLTP payment processing and rule/config reads.                                               |

**13. Security & Compliance**

|                                             |                                                                                                                                                                                                                        |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                                 | **Description**                                                                                                                                                                                                        |
| **API Key Authentication (Secure Compare)** | API access controlled via shared secret in Authorization header. Plug.Crypto.secure\_compare performs constant-time comparison preventing timing attacks on API key validation.                                        |
| **RSA256 Signature for Provider APIs**      | Alipay+ API calls are signed with RSA256 private key. Signature construction: HTTP method + path + client\_id + request\_time + JSON body hash. Signature included in Authorization header per Alipay's specification. |
| **Input Validation**                        | DaProductApp.Security.InputValidator sanitizes and validates all incoming API parameters before processing, preventing injection attacks and malformed data from reaching business logic.                              |
| **QR Parameter Validation**                 | QRParamsValidator validates all QR initiation parameters: required fields (externalRefNumber, provider, deviceId, amount), amount format (must be positive decimal), and provider code enumeration.                    |
| **Content Security Policy**                 | Phoenix endpoint injects CSP headers on all browser responses: restricts script-src to self and ariticapp.com CDN, style-src to self and specified CDNs, and WebSocket connections to wss://ariticapp.com only.        |
| **CSRF Protection**                         | All browser-facing routes use Phoenix's built-in CSRF protection (protect\_from\_forgery plug). Transaction webhook route (/transaction\_post) uses a dedicated :non\_csrf pipeline for ERP system compatibility.      |
| **Session-Based User Auth**                 | Web dashboard users authenticated via Phoenix session tokens stored in the database (user\_tokens table) with expiry. get\_user\_by\_session\_token/1 validates token on every request.                                |
| **Bcrypt Password Hashing**                 | User passwords hashed with bcrypt via bcrypt\_elixir (Comeonin). Work factor configured to resist brute-force attacks. Passwords never stored in plaintext or logged.                                                  |

**14. Web Administration Interface**

|                                     |                                                                                                                                                                                                                              |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Feature**                         | **Description**                                                                                                                                                                                                              |
| **Dashboard**                       | Phoenix LiveView /dashboard: authenticated landing page showing current user context and navigation. Foundation for operational overview widgets (transaction counts, device status, alerts).                                |
| **Workflow Designer**               | Phoenix LiveView /workflow: visual workflow designer powered by jsPlumb for creating and editing payment workflow configurations. Enables no-code configuration of payment routing rules and provider assignment.            |
| **Software Management UI**          | Phoenix LiveView /software and /software/:id: software catalogue browser showing all deployable software packages, version history, and deployment targets. Allows initiating OTA updates to device groups.                  |
| **Transaction Detail View**         | Phoenix LiveView /transactions/:id: authenticated transaction detail page showing all fields, event log timeline, and provider response data for a specific payment.                                                         |
| **SBOM Component Browser**          | Phoenix LiveView /sbomcomponent: Software Bill of Materials browser with slide-over detail panels for each third-party component, supporting security and compliance audits.                                                 |
| **AG Grid / AG Charts Integration** | Web UI includes AG Grid Community/Enterprise and AG Charts for high-performance data grid display of transaction lists and analytical charts — enabling pagination, sorting, and filtering of large datasets in the browser. |
| **Phoenix LiveDashboard**           | /dev/dashboard-system (development only): Phoenix LiveDashboard providing real-time metrics — memory usage, process count, ETS table sizes, and database query performance — for development and staging environments.       |
| **Swoosh Mailbox Preview**          | /dev/mailbox (development only): Swoosh email preview interface for viewing and debugging all outgoing system emails (confirmations, invitations, password resets) without sending real email during development.            |

**15. Feature Summary**

The table below provides a high-level count of documented features by domain area.

|                                          |                   |           |
| ---------------------------------------- | ----------------- | --------- |
| **Domain**                               | **Feature Count** | **Notes** |
| **2. QR Payment Processing**             | 15                |           |
| **3. QR Payment Providers**              | 8                 |           |
| **4. Soundbox & Device Integration**     | 8                 |           |
| **5. Rules Engine**                      | 16                |           |
| **6. ERP & Billing System Integration**  | 12                |           |
| **7. Merchant Management API**           | 18                |           |
| **8. Transaction Reporting & Analytics** | 13                |           |
| **9. Software & OTA Device Management**  | 6                 |           |
| **10. User Management & Authentication** | 8                 |           |
| **11. Event Logging & Audit Trail**      | 6                 |           |
| **12. Multi-Database Architecture**      | 6                 |           |
| **13. Security & Compliance**            | 8                 |           |
| **14. Web Administration Interface**     | 8                 |           |
| **TOTAL**                                | **132**           |           |
