Executive Summary
Four pillars that power the Regen Therapy commerce infrastructure
Unified Order Intake
Centralizes orders from admin dashboard, tenant portals, Shopify, WooCommerce, and custom channel APIs into a single processing pipeline with validation, SKU resolution, and tenant context.
Payment Resilience
Routes payments through NMI as primary processor with Authorize.net failover. Circuit breaker patterns, idempotency keys, and automatic timeout reconciliation prevent duplicate charges.
Inventory + SKU Control
Maps tenant SKUs to platform SKUs, manages warehouse-level stock, handles reservations atomically, supports private-label catalogs, and prevents overselling through real-time availability checks.
Fulfillment Orchestration
Routes orders to internal warehouses or 3PL partners via a pluggable adapter system. Supports EasyPost and ShipStation for shipping with automatic tracking synchronization.
What This Platform Is
The Regen Therapy Gateway is not a clinical platform, EHR, telehealth system, or patient-care application. It is a commerce operations gateway for:
System Architecture
TechnicalSix-layer architecture powering the commerce gateway
Channel Layer
Entry points for all commerce activity
- Admin Dashboard (Next.js)
- Tenant Portal (Multi-tenant)
- Shopify Webhook Integration
- WooCommerce REST API
- Custom Channel APIs
- Mobile API Support
Gateway Layer
Request processing and security
- API Routes (/api/v1/*)
- JWT Authentication
- RBAC Guard (18 roles)
- Tenant Context Middleware
- Rate Limiting (Upstash Redis)
- Request Validation (Zod)
Commerce Services
Business logic and orchestration
- Order Processing Service
- SKU Resolution Engine
- Tenant Pricing Service
- Commission Calculator
- Field Mapping Profiles
- Promotion Engine
Payment Layer
Payment processing with failover
- NMI Primary Gateway
- Authorize.net Backup
- Circuit Breaker Pattern
- Idempotency Service
- Timeout Reconciliation
- Refund/Void Workflows
Inventory + Fulfillment
Stock management and shipping
- Atomic Reservations
- Warehouse Routing
- 3PL Adapter System
- EasyPost Integration
- ShipStation Integration
- Tracking Webhooks
Data + Observability
Storage, caching, and monitoring
- Neon PostgreSQL (90 tables)
- Upstash Redis (caching)
- Vercel Blob (files)
- Audit Log System
- OpenTelemetry Tracing
- Sentry Error Monitoring
Data Flow Architecture
TechnicalHow data moves through the system from request to response
Inbound Request Flow
From client to database
1. Client Request
HTTP request arrives via Vercel Edge Network with automatic TLS termination and geographic routing
2. Auth Middleware
JWT token validation, session verification, RBAC permission check, tenant context extraction
3. Request Validation
Zod schema validation, rate limit check via Redis, idempotency key verification for mutations
4. Service Layer
Business logic execution with RLS-enabled database queries ensuring tenant isolation
Order Processing Flow
Complete order data journey
1Order Ingestion
- Channel identifies order source (admin/tenant/Shopify/WooCommerce)
- Tenant context loaded from JWT or API key
- Field mapping transforms external data
- Order validation against business rules
2Processing Pipeline
- SKU resolution maps tenant SKUs to platform SKUs
- Pricing engine applies tenant-specific rates
- Promotion/discount validation and application
- Commission calculation based on margin rules
3Fulfillment Routing
- Payment authorized via gateway orchestrator
- Inventory atomically reserved per warehouse
- Fulfillment adapter routes to warehouse/3PL
- Webhooks notify external systems of status
Webhook Event Flow
Outbound event delivery system
Event Trigger
System action generates webhook event
Payload Build
Event data serialized with HMAC signature
Delivery Attempt
HTTP POST to registered endpoint
Retry Logic
Exponential backoff on failure (6 attempts)
DLQ Capture
Failed events stored for manual replay
Order Lifecycle
Complete journey of an order through the system
Order Received
Order enters the system from any supported channel
- Admin portal direct entry
- Tenant portal submission
- Shopify webhook ingestion
- WooCommerce REST API
- Custom channel API call
Tenant Resolved
Platform identifies tenant context and configuration
- JWT token contains tenant ID
- API key maps to tenant
- Pricing rules loaded
- Catalog configuration applied
- Fulfillment rules determined
SKU Mapped
Tenant SKUs translated to platform SKUs
- SKU resolver queries mapping table
- Private-label SKUs supported
- Unknown SKUs flagged as exceptions
- Product metadata enriched
Payment Authorized
Payment routed through configured gateway
- Primary gateway (NMI) attempted
- Circuit breaker monitors failures
- Fallback to Authorize.net if needed
- Idempotency key prevents duplicates
- Authorization stored with order
Inventory Reserved
Stock atomically reserved at warehouse level
- Availability check per line item
- Atomic reservation transaction
- Backorder created if unavailable
- Warehouse allocation by rules
Fulfillment Submitted
Order dispatched to fulfillment destination
- Internal warehouse assignment
- 3PL adapter creates shipment
- Shipping label generated
- Carrier manifested
Tracking Synchronized
Carrier updates flow back to platform
- EasyPost webhook receives updates
- Tracking status normalized
- Customer notification triggered
- Order status updated
Reporting Updated
Financial and operational data recorded
- Revenue attributed to channel
- Commission calculated and accrued
- Inventory movement logged
- Audit trail complete
Core Platform Capabilities
8 ModulesComprehensive feature set powering commerce operations
Multi-Tenant Commerce Engine
Complete tenant isolation with configurable business rules per organization.
- Tenant-specific pricing tiers and discount rules
- Custom product catalogs with private-label support
- Per-tenant fulfillment configuration
- Isolated views for partners and internal users
- Row-level security across all 90 database tables
- Tenant-aware API authentication
SKU Resolution Engine
Intelligent mapping between external and internal product identifiers.
- Tenant SKU to platform SKU mapping
- Private-label SKU aliasing
- Catalog normalization across channels
- Unknown SKU exception handling
- Bulk SKU import/export support
- Automatic mapping suggestions
Order Orchestration
Unified order processing pipeline across all sales channels.
- Internal admin order creation
- Tenant portal self-service orders
- Shopify/WooCommerce webhook ingestion
- Custom channel API integration
- Unified order status model
- Order validation and business rules
Payment Gateway Layer
Resilient payment processing with automatic failover.
- NMI primary payment gateway
- Authorize.net backup gateway
- Circuit breaker failover pattern
- Transaction state tracking
- Refund and void workflows
- Timeout reconciliation service
Inventory Management
Real-time stock tracking with atomic reservation system.
- Available vs reserved inventory
- Warehouse-level stock tracking
- Atomic reservation transactions
- Backorder handling and alerts
- Inventory adjustment audit log
- Low stock notifications
Fulfillment Routing
Flexible fulfillment with pluggable adapter architecture.
- Internal warehouse fulfillment
- Generic 3PL adapter interface
- EasyPost carrier integration
- ShipStation multi-carrier support
- Automatic tracking sync
- Returns management
Commission Engine
Flexible commission calculation with full audit trail.
- Profit-based commission rules
- Tiered rate structures
- Sales rep attribution
- Channel-based commission
- Commission audit trail
- NACHA payout file generation
Field Mapping Profiles
Transform external data to match internal schema.
- Per-tenant transformation rules
- External channel normalization
- Custom payload mapping
- Import/export flexibility
- JSON path field selection
- Default value configuration
API Gateway + Integration Layer
REST APIStructured API routes with comprehensive security and monitoring
The gateway exposes versioned API routes for order ingestion, tenant configuration, SKU resolution, payment workflow coordination, inventory visibility, shipping workflows, and fulfillment status updates.
Authentication
- JWT access + refresh tokens
- API key authentication
- OAuth 2.0 / OIDC SSO
- MFA (TOTP + Email OTP)
Rate Limiting
- Per-tenant request quotas
- Sliding window algorithm
- Redis-backed counters
- 429 response with retry-after
Monitoring
- OpenTelemetry tracing
- Sentry error tracking
- Request/response logging
- Health check endpoints
API Reference
124 EndpointsComplete endpoint documentation organized by domain
Orders API
Order creation, retrieval, and management
/api/v1/orders/api/v1/ordersList orders with filtering, pagination, and tenant scope
/api/v1/ordersCreate new order with validation and SKU resolution
/api/v1/orders/validateValidate order payload without creating
/api/orders/[id]Get single order with line items and status history
/api/orders/[id]Update order details or status
Payments API
Payment processing and refund workflows
/api/payments/api/payments/chargeAuthorize and capture payment with gateway failover
/api/payments/refundProcess full or partial refund
/api/admin/reconciliationPayment reconciliation dashboard data
Inventory API
Stock levels, reservations, and adjustments
/api/v1/inventory/api/v1/inventoryList inventory levels by SKU and warehouse
/api/inventory/adjustAdjust inventory with reason tracking
/api/inventory/alertsLow stock and reorder alerts
/api/inventory/forecastDemand forecasting and reorder suggestions
Shipping API
Rate shopping, label generation, and tracking
/api/shipping/api/shipping/quoteGet shipping rates from multiple carriers
/api/shipping/buy-labelPurchase shipping label and create shipment
/api/shipping/batch/create-labelsBulk label generation for multiple orders
/api/shipping/tracking/[orderId]Get tracking status and history
/api/shipping/validate-addressValidate and normalize shipping address
/api/shipping/return-labelGenerate return shipping label
SKU Mapping API
Tenant-to-platform SKU resolution
/api/v1/mappings/skus/api/v1/mappings/skusList all SKU mappings for tenant
/api/v1/mappings/skusCreate new SKU mapping
/api/v1/mappings/skus/resolveResolve tenant SKU to platform SKU
/api/v1/mappings/skus/bulkBulk import SKU mappings
Authentication API
User authentication and session management
/api/auth/api/auth/loginAuthenticate user and issue tokens
/api/auth/refreshRefresh access token using refresh token
/api/auth/logoutInvalidate session and tokens
/api/auth/mfa/setupInitialize MFA enrollment
/api/auth/mfa/verifyVerify MFA code during login
/api/auth/sso/[provider]Initiate SSO flow (Google, Microsoft, Okta)
Webhooks API
Event subscriptions and delivery management
/api/v1/webhooks/api/v1/webhooksList registered webhook endpoints
/api/v1/webhooksRegister new webhook endpoint
/api/admin/webhooks/dlqView dead letter queue entries
/api/admin/webhooks/dlq/[id]/replayReplay failed webhook delivery
Authentication System
SecurityMulti-factor authentication with SSO support
Authentication Flow
1Credential Validation
User submits email/password. Password verified against bcrypt hash with constant-time comparison to prevent timing attacks.
2MFA Challenge (if enabled)
TOTP code validated against shared secret, or email OTP sent and verified. 6-digit codes with 30-second windows.
3Token Issuance
JWT access token (15min) + refresh token (7 days) issued. Tokens contain user ID, tenant ID, and role claims.
4Session Tracking
Active sessions stored in database with device fingerprint, IP, and last activity timestamp for audit and revocation.
RBAC Role Hierarchy
SUPER_ADMINAll platform operationsPLATFORM_ADMINManage tenants and usersOPERATIONS_ADMINFulfillment and shippingFINANCE_ADMINPayments and commissionsFINANCERead-only financial dataAUDITORRead-only system-wideTENANT_ADMINManage tenant settingsTENANT_USERStandard tenant accessWAREHOUSE_STAFFInventory operationsSALES_REPOrder and commission viewSUPPORTRead-only customer supportPayment Processing System
Critical PathEnterprise-grade payment handling with failover and reconciliation
Gateway Architecture
Payment Orchestrator
lib/payments/orchestrator.ts
NMI Primary
First attempt via NMI gateway with full tokenization
Circuit Breaker Check
Monitor failure rate, open circuit after threshold
Authorize.net Failover
Automatic retry via backup gateway
Transaction Integrity
Idempotency Keys
Every payment request includes a unique idempotency key stored in Redis. Duplicate requests within 24 hours return cached result.
Timeout Reconciliation
Pending transactions table tracks in-flight payments. Cron job polls gateways for stuck transactions, auto-voids or confirms.
Settlement Reconciliation
Daily job matches gateway settlements against internal records. Discrepancies flagged for manual review.
PCI Compliance Strategy
The platform minimizes PCI scope by never storing raw card data:
Stored
- • Gateway customer ID
- • Payment token
- • Transaction ID
- • Auth code
Masked Only
- • Last 4 digits
- • Card brand
- • Expiry (MM/YY)
Never Stored
- • Full card number
- • CVV/CVC
- • Track data
Inventory Management System
Core ModuleAtomic reservations with warehouse-level tracking
Stock Levels
- On Hand - Total physical inventory
- Available - On Hand minus Reserved
- Reserved - Held for pending orders
- Committed - Allocated to shipments
- Backordered - Negative availability
Warehouse Routing
- Multi-warehouse inventory
- Geographic routing rules
- Priority-based allocation
- Split shipment support
- Internal vs 3PL routing
Alerts & Automation
- Low stock threshold alerts
- Reorder point triggers
- Demand forecasting
- Backorder notifications
- Stock adjustment audit
Atomic Reservation Flow
Prevents overselling with transactional guarantees
Availability Check
Query available quantity across all warehouses for SKU
Transactional Lock
BEGIN transaction with SELECT FOR UPDATE on inventory rows
Reserve Stock
Decrement available, increment reserved within transaction
Commit or Rollback
COMMIT on success, ROLLBACK on any error - atomic operation
Fulfillment Orchestration
ExtensiblePluggable adapter architecture for flexible fulfillment routing
Adapter Architecture
The fulfillment system uses a pluggable adapter pattern. Each fulfillment destination implements a common interface, allowing new 3PL integrations without changing core logic.
interface FulfillmentAdapter {
createShipment(order: Order): Promise<ShipmentResult>
cancelShipment(shipmentId: string): Promise<void>
getTrackingInfo(shipmentId: string): Promise<TrackingInfo>
syncInventory(): Promise<InventoryUpdate[]>
handleWebhook(payload: unknown): Promise<void>
}Available Adapters
Internal Warehouse
ActiveDirect integration with internal warehouse management. Orders flow directly to picking queue.
Generic 3PL Adapter
ReadyStub adapter ready for future 3PL integration. Implements full interface with mock responses.
Shipping Providers
ActiveEasyPost and ShipStation for carrier rate shopping, label generation, and tracking.
Shipping Carriers
Shipping APIs
Fulfillment Features
Platform Integrations
Connected systems powering the commerce ecosystem
Ecommerce Channels
Payment Gateways
Shipping Providers
Infrastructure
Reliability + Operational Controls
Enterprise-grade transaction integrity and exception handling
Payment Integrity
- Idempotent payment requests (Redis-backed)
- Duplicate charge prevention
- Gateway failover with circuit breaker
- Authorization/capture state tracking
- Refund and void audit trail
- Timeout reconciliation service
Inventory Integrity
- Atomic stock reservation workflow
- Warehouse-level availability tracking
- Inventory adjustment audit log
- Real-time reconciliation support
- Oversell prevention logic
- Backorder automation
Webhook Reliability
- HMAC-SHA256 signature verification
- Exponential backoff retry (6 attempts)
- Dead letter queue for failed events
- Event replay console
- Endpoint health monitoring
- Bulk replay support
Audit + Compliance
- User activity audit log
- Order change history
- Payment event tracking
- Inventory movement logs
- Tenant configuration history
- GDPR data export/delete
Access Control
- 18 granular user roles
- Tenant-scoped permissions
- Finance read-only access
- Auditor system-wide view
- API key scoped access
- SSO integration (OIDC)
Exception Handling
- Operations exception dashboard
- Stuck order detection
- Failed payment alerts
- Fulfillment exception queue
- Inventory discrepancy flags
- Automated resolution workflows
Security + Access Governance
SecurityDefense-in-depth security architecture
The platform is designed around secure access, tenant-aware authorization, API controls, password protection, and operational auditability for commerce workflows.
- JWT + Refresh tokens
- bcrypt password hashing
- Constant-time comparison
- Role-based access control
- Tenant-aware authorization
- Row-level security
- API key authentication
- Scoped token permissions
- Key rotation support
- Comprehensive audit logs
- Request/response logging
- User activity tracking
Commerce Data Model
90 Tables90-table PostgreSQL schema designed for multi-tenant commerce
The platform is backed by a structured PostgreSQL data model designed around tenants, users, products, SKUs, orders, payments, inventory, commissions, shipping, fulfillment, field mappings, and audit events.
Tenancy
- Tenant
- User
- Role
- Permission
- Session
- ApiKey
Catalog
- Product
- TenantProduct
- SkuMapping
- PricingRule
- Category
Orders
- Order
- OrderLineItem
- OrderStatus
- OrderEvent
- Return
Payments
- Payment
- Transaction
- Refund
- PendingTransaction
- Settlement
Inventory
- Inventory
- Warehouse
- Reservation
- Adjustment
- BackorderItem
Fulfillment
- Shipment
- ShippingLabel
- Tracking
- FulfillmentConfig
Finance
- Commission
- Payout
- PlatformFee
- DropshipFee
- MarginRecord
Integrations
- Channel
- FieldMapping
- WebhookEndpoint
- WebhookDelivery
- WebhookDLQ
Developer Hub
DevelopersResources for integrating with the Regen Therapy Gateway
API Documentation
Complete REST API reference with request/response examples, authentication guides, and error handling.
View API DocsAPI Playground
Interactive API explorer to test endpoints with your credentials. Try requests and see live responses.
Open PlaygroundWebhook Guide
Learn to receive real-time events. Includes signature verification, retry handling, and event types.
Webhook DocsQuick Start Example
Create an order via API
curl -X POST https://gateway.regentherapy.com/api/v1/orders \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"externalId": "ORD-12345",
"customer": {
"email": "customer@example.com",
"name": "John Doe"
},
"lineItems": [
{ "sku": "TENANT-SKU-001", "quantity": 2 }
],
"shippingAddress": {
"street": "123 Main St",
"city": "Austin",
"state": "TX",
"zip": "78701",
"country": "US"
}
}'Technology Foundation
Modern stack built for scalability and developer experience
Platform Focus
Operational Control
Centralize orders, payments, inventory, fulfillment, and tenant configuration in a single platform with complete visibility and control.
Channel Flexibility
Support internal portals, ecommerce storefronts, custom APIs, and private-label partner workflows through unified integration layer.
Transaction Integrity
Design around payment accuracy, inventory correctness, webhook reliability, auditability, and exception recovery for enterprise operations.