All Point Retail · Platform Reference

Platform Explorer

Architecture, Entity Model, Relationships & Documentation — interactive reference for the All Point ecosystem.

Architecture Review

All Point Platform

21 Repositories + Public API Node.js 20–22 + TypeScript AWS · Prisma · MySQL · PostgreSQL · MSSQL · DynamoDB · MongoDB · Redis 91 Domain Entities
Layer 1 — Client Applications & Admin
🖥
Support Admin
repositories/support
Internal admin UI for managing both All Point Access (security, users, roles, scopes) and All Point Config (configs, secrets, environments, document types).
Astro 5 React 19 Tailwind SSR
🔐
Access Dashboard
repositories/access-dashboard
Self-service portal where authenticated users view all All Point applications they can access, manage their profile and account settings, and reset their password.
Astro 5 React 19 Tailwind SSR
🏪
Franchise Portal
repositories/franchise-portal
Primary user-facing Next.js 16 web app for franchise operators. 22+ business domains — products, orders, inventory, customers, uploads, reporting.
Next.js 16 React 19 MUI v7 Socket.io Prisma
🏗
Product Builder
repositories/product-builder
Full-stack product catalog app — bulk Excel imports, option/variant configuration, and catalog sync to Connect API via webhooks.
Next.js 14 Express MUI InversifyJS Webhooks
🔌
Integrations
Shopify · Teamwork · NetSuite · QBO · Yotpo
Productized integrations combining inbound connectors (source) and outbound connectors (destination) to sync entities with external platforms.
Inbound Connectors Outbound Connectors Webhooks SFTP

Support Admin — Deep Dive

An Astro 5 SSR application with React 19 components, Tailwind 4, and Radix UI primitives. Serves as the unified management UI for two Layer 2 platform services:

All Point Access Management

Security & Permissions: Users, Roles, Permissions, Scopes, Clients, Areas. General: Companies, Applications (OAuth/OIDC settings).

All Point Config Management

Configuration: Actors, Config Templates, Configs, Secrets, Document Types, Custom Units, Environments.

Key Dependencies
All Point Access (auth) All Point Config (config) @all-point/auth @all-point/logging TanStack Query Nanostores Radix UI

Access Dashboard — Deep Dive

An Astro 5 SSR application with React 19 components and Tailwind 4. Provides a central landing page for every authenticated user in the platform, showing personalised application tiles based on their role-based permissions.

Core Capabilities
Application launcher — personalised tiles for all permitted apps User profile management — name, email, avatar, contact details Account settings — notification preferences, locale, timezone Password reset — self-service flow via Cognito
Key Dependencies
All Point Access (Cognito OAuth + RBAC) @all-point/auth @all-point/logging TanStack Query Tailwind 4

Franchise Portal — Deep Dive

Next.js 16 full-stack application with React 19, MUI v7 (Data Grid Premium), and Emotion CSS-in-JS. Uses App Router with Server Actions for mutations. Covers 22+ business domains: customers, products, catalog (style/price/cost uploads), vendors, locations, purchase orders, transfer orders, stock adjustments, shipments, sales orders/receipts, employees, settings, reports (embedded Looker), and analytics. Authenticates via Cognito OAuth through All Point Access with per-user permission checks and franchise group filtering.

Service Integrations

Data API (REST via @all-point/ap-fetch with Bearer token), Access (Cognito OAuth + JWT sessions), Jobs Sidecar (socket.io WebSocket for real-time upload progress), Config Service (runtime config + CDN branding), S3 (file uploads via next-s3-upload).

Key Dependencies
@all-point/auth @all-point/ap-fetch @all-point/types @all-point/config @all-point/config-service-sdk @all-point/instrumentation MUI X Premium SWR React Hook Form

Product Builder — Deep Dive

A monorepo full-stack application (Express backend + Next.js 14 frontend) for product catalog management. Handles bulk Excel imports with schema validation, product option/variant configuration (color, size, etc. with dependency rules), and catalog synchronization to the Connect API. Uses a webhook-driven workflow — registers TransmitConfirmation webhooks at startup, and tracks sync status through IMPORT_PROCESSING → READY_FOR_SALE → ERROR lifecycle.

Key Capabilities
Excel bulk import + validation Product option groups & variants CatalogStyle sync to Connect API Webhook-driven status tracking Quick Ship product mapping Vendor catalog management
Key Dependencies
@all-point/document-db @all-point/ap-fetch @all-point/webapps-common @all-point/xlsx @all-point/types @all-point/config MUI v5 React Hook Form

Integrations — Connector Model

All Point uses a connector model for external system integration. An inbound connector (source) ingests data from an external system into All Point entities. An outbound connector (destination) pushes All Point entity changes to the external system. The combination of an inbound + outbound connector for a given platform forms a productized integration. Each connector extends the state machine framework from connectors-common.

Active Integrations
Shopify (connectors-shopify) — bidirectional Teamwork CHQ (connectors-teamwork) — bidirectional, 20+ in / 14+ out QuickBooks Online (connectors-qbo) — outbound financial docs NetSuite Yotpo (loyalty) SFTP file-based
Layer 2 — Platform Services & Public Gateway
🔐
All Point Access
repositories/all-point-access
Central OAuth 2.0 SSO provider, user management, and RBAC engine. Issues JWE-encrypted tokens. Multi-tenant with per-environment roles.
Next.js 14 AWS Cognito OAuth 2.0 InversifyJS RBAC
⚙️
All Point Config
repositories/config-service + repositories/config
NestJS 11 configuration service with versioning, rollout rules, Redis caching, and SNS/SQS invalidation. Client library (@all-point/config) provides DI-friendly access.
NestJS 11 Prisma + Postgres Redis Rollout Rules Versioning JWT Auth
🌐
Public API
planned / in design
Externally-facing REST API for third-party integrations, franchise partners, and marketplace consumers. Authenticated and scoped via All Point Access OAuth tokens.
OAuth 2.0 Scopes Rate Limiting API Keys Versioned Endpoints

All Point Config — Deep Dive

A two-part system: config-service (NestJS 11 backend on PostgreSQL 17 + Redis 7) provides versioned config management with rollout rules, JSON Schema validation, percentage-based targeting, and multi-tenancy. @all-point/config (client library) provides lightweight DI-friendly access to configs and AWS Secrets Manager from any service. Cache invalidation propagates via SNS/SQS. Every service in the platform consumes Config for runtime settings, feature flags, environment resolution, and document type definitions.

Managed Entities
Actors Config Templates Configs (versioned) Config Variants (A/B) Secrets (versioned) Document Types Custom Units Environments Rollout Rules
Key Capabilities

Version history with rollback, percentage-based rollouts with condition targeting (ANY_OF/NONE_OF), ETag-based conflict detection, Redis caching with 5-minute TTL, SNS/SQS distributed invalidation, JWT + API key authentication, Kubernetes health probes.

Public API — Design Overview

The public-facing gateway for external consumers. Authenticates every request by validating JWE tokens issued by All Point Access, then enforces scope-based authorization to gate access to specific resources and operations. Proxies authorized requests down to Layer 3 services (Data API, IMC, Jobs Sidecar) without exposing internal service topology. Responsible for rate limiting, API key management, versioned endpoint contracts, and request/response transformation between the public contract and internal service formats.

Auth Flow

External consumer authenticates against All Point Access → receives scoped OAuth token → passes token on each Public API request → Public API validates JWE signature and checks granted scopes against the requested resource/operation → proxies to internal services.

Responsibilities
Token validation (JWE) Scope enforcement Rate limiting API key management Versioned contracts Request transformation Audit logging

All Point Access — Deep Dive

Next.js 14 application serving as both SSO provider and User Management API. Implements Authorization Code Grant with AWS Cognito as identity provider. Features per-application session management (multiple apps with independent login states), hierarchical RBAC with base and client-specific roles, and per-environment franchise-based access control. URL-based application validation enforces multi-tenant isolation. Integrates with Shopify OAuth and Looker for analytics provisioning.

Architecture Pattern

Controller → Service → Repository → DocumentDB, all wired through InversifyJS DI. Route handlers use a routeCallbackWrapper that provides DI container management, standardized error handling, and consistent HTTP status mapping.

Key Dependencies
@all-point/document-db @all-point/auth @all-point/config @all-point/logging @all-point/types aws-jwt-verify better-auth
Layer 3 — Domain Services
📦
Inventory Service
in-monolith · Data API
Real-time stock positions, movements, adjustments, transfers, and physical counts across all locations.
ItemStock StockAdjustment StockTransfer TransferOrder StockTake
🏷️
Product Service
in-monolith · Data API
Master product catalog, pricing, and merchandising — styles, variants, classifications, pricing/costing, promotions, catalogs, product groups, and menus.
Product Item Classification PriceLevel Catalog Promotion
💵
Sales Service
in-monolith · Data API
Order lifecycle — sales orders, fulfillment, shipping, and completed sale transactions with payment capture.
SalesOrder Sale Fulfillment Shipment SalesChannel
🧾
Purchasing Service
in-monolith · Data API
Procurement lifecycle — purchase orders, ASN, goods receipt, vendor invoices, three-way match, and vendor management.
PurchaseOrder GoodsReceipt VendorInvoice Vendor ASN
📒
Stock Ledger Service
in-monolith · Data API
Append-only immutable ledger recording every stock movement. Consumes events from Inventory, Purchasing, and Sales for fiscal compliance and audit.
StockLedger
💬
Messaging Service
in-monolith · Data API
Platform communication — chat channels, email templates, delivery logs, and calendar events with franchise-scoped visibility.
ChatChannel EmailTemplate EmailLog CalendarEvent
🏢
Organization Service
in-monolith · Data API + Access
Organizational hierarchy — organizations, companies, business entities, locations, markets, employees, and franchise groups.
Organization Company Location Market Employee

Inventory Service — Domain Boundary

Owns all real-time inventory state and movement operations. Tracks on-hand, committed, incoming, reserved, safety stock, damaged, and QC quantities per Item × Location. Emits domain events consumed by the Stock Ledger Service for immutable audit trail.

Owned Entities (11)
Item Stock Stock Adjustment Stock Adjustment Reason Stock Take Transfer Order Stock Transfer Stock Transfer Carton Stock Transfer Reason Stock Transfer Reject Reason Item Stock Group Stock Limit Group
Cross-Service Dependencies
Product Service → Item (referenced entity) Organization Service → Location (stock position scope) Stock Ledger Service → emits StockAdjusted, TransferPosted events Sales Service → Sale (triggers inventory decrement) Purchasing Service → Goods Receipt (triggers inventory increment)
Deployment Status

In monolith — currently housed in the Connectors Data API. Candidate for extraction as an independent microservice.

Product Service — Domain Boundary

Master product catalog, pricing, and merchandising. Defines the product hierarchy (Product → Item), classification taxonomy (Department → Class → Subclass), configurable dimensions (Attributes, Options), all pricing/costing (price levels, cost levels, adjustments, promotions, discounts, coupons, audit ledgers), and merchandising (catalogs, product groups, menus for channel publication).

Owned Entities (27)
Product Item Classification Classification Department Classification Class Classification Subclass Attribute Option Brand Season Product Type Country Of Origin Hs Code Price Level Price Rule Cost Level Price Adjustment Cost Adjustment Price Ledger Cost Ledger Promotion Discount Coupon Tax Class Catalog Product Group Product Menu
Cross-Service Dependencies
Inventory Service → ItemStock (stock positions per Item) Sales Service → Sale, SalesOrder (promotions applied at checkout) Organization Service → Market (currency, default price/cost levels, market-specific catalogs)
Deployment Status

In monolith — currently housed in the Connectors Data API.

Sales Service — Domain Boundary

End-to-end order and fulfillment lifecycle. Captures sales intent (SalesOrder), orchestrates fulfillment (FulfillmentOrder → ShipOrder → Shipment), and records completed revenue transactions (Sale). Integrates with payment processing and triggers inventory decrements.

Owned Entities (12)
Sales Channel Sales Order Fulfillment Order Ship Order Fulfillment Shipment Shipment Carton Sale Ship Reject Reason Shipping Method Loyalty Program Customer
Cross-Service Dependencies
Product Service → Item, Promotion, Discount (line items, pricing at checkout) Inventory Service → ItemStock (availability check, decrement on sale) Stock Ledger Service → StockLedger (emits FulfillmentCompleted, SalePosted events) Organization Service → Location, Employee (cashier, sales persons)
Deployment Status

In monolith — currently housed in the Connectors Data API.

Purchasing Service — Domain Boundary

Complete procurement lifecycle from purchase order creation through goods receipt and three-way invoice matching. Manages vendor relationships, payment terms, and cost tracking. ASN (Advance Shipping Notice) support for pre-receipt visibility.

Owned Entities (13)
Vendor Vendor Payment Term Purchase Order Advanced Shipping Notice Advanced Shipping Notice Carton Goods Receipt Purchase Vendor Invoice Vendor Credit Purchasing Fee Bill Matched Invoice Set Purchase Order Acknowledgement
Cross-Service Dependencies
Product Service → Item (line items on PO) Inventory Service → Goods Receipt triggers stock increment Organization Service → Location (receiving location) Organization Service → Employee (buyer)
Deployment Status

In monolith — currently housed in the Connectors Data API.

Stock Ledger Service — Domain Boundary

Append-only immutable ledger recording every stock movement across the platform. Consumes domain events (StockAdjusted, GoodsReceived, FulfillmentCompleted, TransferPosted) from Inventory, Purchasing, and Sales services. Provides point-in-time inventory reconstruction, valuation queries, and the audit trail required for fiscal compliance.

Owned Entities (1)
Stock Ledger
Event Sources (upstream)
Inventory Service → StockAdjusted, TransferPosted, StockTakeReconciled Purchasing Service → GoodsReceived Sales Service → FulfillmentCompleted, SalePosted
Deployment Status

In monolith — currently housed in the Connectors Data API. Candidate for early extraction due to clear event-driven boundary and no synchronous dependencies.

Messaging Service — Domain Boundary

Platform communication hub. Chat channels support direct, group, and broadcast messaging with franchise-group-scoped visibility. Email templates with merge-field interpolation trigger automated transactional emails via AWS SES. Calendar events support attendees, recurrence, and entity linking.

Owned Entities (5)
Chat Channel Chat Message Email Template Email Log Calendar Event
Cross-Service Dependencies
Organization Service → User (participants, senders, attendees) Sales Service → SalesOrder (email triggers on state transitions)
Deployment Status

In monolith — currently housed in the Connectors Data API.

Organization Service — Domain Boundary

Platform organizational hierarchy and physical presence. Organizations contain Companies, which scope all commerce operations. Locations are the atomic unit for inventory and sales. Markets define fiscal rules (currency, tax, pricing). Franchise Groups drive data isolation and visibility filtering.

Owned Entities (10)
Organization Company Application Business Entity Franchise Group Location StockBin Market Employee Employee Role
Cross-Service Dependencies
Access Service → User, Role (identity and permissions) Config Service → Environment, Config (per-company settings) All other services → Location, Company (scoping context)
Deployment Status

Split — Organization/Company entities in Data API; Application/User entities in All Point Access.

Layer 4 — Core Infrastructure Services
📊
Connectors Data API
repositories/connectors-data-api
Central data service — REST CRUD for all domain entities: products, orders, inventory, customers, shipments. MySQL via Prisma + MongoDB.
Express Prisma 6 MySQL CQRS InversifyJS 50+ models
🔀
Connectors IMC
repositories/connectors-imc
Intermediate Message Connector — validates, routes, and queues documents to downstream connector services via SQS. Dynamic routing via AWS Service Discovery.
Express SQS Service Discovery CatchAll State Machine
Jobs Sidecar
repositories/jobs-sidecar
Background job processor — handles heavy-lift work: Excel/CSV imports, media processing, report generation. Worker threads with real-time WebSocket progress.
socket.io Worker Threads Puppeteer Sharp Zod 4
🛒
Connectors Shopify
repositories/connectors-shopify
Bi-directional Shopify connector — products & customers via GraphQL Admin API. Primary/worker cluster architecture with multi-store support, webhook processing, and circuit breakers.
GraphQL Cluster Workers SQS FIFO Webhooks Prisma + Postgres
📧
Email Lambda
repositories/email-lambda
AWS Lambda that processes SES email delivery status events from SNS/SQS and forwards tracking updates to the Data API.
AWS Lambda SES Events SNS/SQS
🏢
Connectors Teamwork
repositories/connectors-teamwork
Bidirectional CHQ/Teamwork connector — 20+ inbound & 14+ outbound document types. Async Initiation/Continuation pattern, augmentation services, Prisma + MSSQL for RDB queries.
Bidirectional Prisma + MSSQL MongoDB 100+ DI bindings
💰
Connectors QBO
repositories/connectors-qbo
Outbound financial document connector to QuickBooks Online — Bills, Vendor Credits, Journal Entries, Transfers. OAuth2 token management with rate limiting.
Outbound Only OAuth2 Rate Limit 8/sec 2-Tier SM

Connectors Data API — Deep Dive

The largest service — a 4-tier Express application (Controller → Service → BusinessLogic → Repository). Uses CQRS-like separation with distinct CommandService and QueryService base classes. The inversify.config.ts registers 160+ DI bindings. Houses 35+ DocumentBusinessLogic classes for domain entities and 18+ lookup business logic classes. Features CLI tools for bulk imports (products, lookups) via ExcelJS/CSV.

Database Strategy

Dual database: MySQL via Prisma (50+ relational models with compound indexes, soft-delete) for structured data, plus MongoDB via @all-point/document-db for document storage. S3 for file storage, SQS for async messaging.

Key Dependencies
Prisma 6.19 @all-point/document-db @all-point/store (S3) @all-point/queue (SQS) @all-point/types ExcelJS Puppeteer OpenTelemetry

Connectors IMC — Deep Dive

A lightweight routing service that sits between AWS Lambda triggers and downstream connector services. Uses a CatchAllDocumentStateMachine (from connectors-common) that accepts any document type, validates it, then queries AWS Service Discovery to find all active connectors-* services. Documents are fanned out to each matching SQS queue in parallel. Supports partial failure — a message only fails if ALL target queues reject it. Service cache refreshes every 60 seconds. Runs on a 1-minute cron schedule.

Key Dependencies
@all-point/connectors-common @all-point/queue @aws-sdk/client-servicediscovery

Jobs Sidecar — Deep Dive

A WebSocket-based microservice that offloads heavy processing from the Franchise Portal. Clients connect via socket.io, submit jobs, and receive real-time progress updates. A WorkerPoolService manages Node.js worker threads (CPU-aware auto-scaling). Uses a Factory pattern — 5 factory maps (config, mapper, parser, schemaValidator, validator) resolve the correct processing pipeline at runtime by upload type. The UploadProcessorServiceBase provides an 8-step pipeline: S3 download → parse → structure validate → schema validate → domain validate → duplicate check → batch DAPI send → result export.

Supported Job Types

CatalogStyle, Product, Employee, PurchaseOrder, TransferOrder, StockAdjustment uploads, plus media processing (sharp for images, ffmpeg for video) and PDF generation (Puppeteer).

Connectors Shopify — Deep Dive

Enterprise-grade bi-directional Shopify connector using a primary/worker cluster architecture. The primary process runs the HTTP server, state machines (OutboundProduct, OutboundCustomer, InboundProduct, InboundCustomer, etc.), supervisor jobs, and webhook processing. Worker processes poll SQS FIFO queues and execute sync tasks against Shopify's GraphQL Admin API. Supports multi-store per client — a single connector instance maps AllPoint locations to multiple Shopify store domains.

Key Capabilities

Adaptive rate limiting per store, entity circuit breaker (triggers bulk API fallback on variant quota exhaustion), three-way merge for webhook conflicts, echo prevention (2-minute window), GenericChangeDetector with nested collection tracking, allowlist-based webhook business rules, SNS/SQS FIFO task fanout, DynamoDB for state docs, PostgreSQL for sync coordination.

Inbound/Outbound Pattern

Outbound (AllPoint → Shopify): State machines consume DynamoDB docs, filter by status + sales channel, map to Shopify ProductSetInput/CustomerInput, publish tasks to SQS FIFO, workers execute via GraphQL. Inbound (Shopify → AllPoint): Webhooks received → change detection → business rules → REVERT/PROPAGATE/INGEST/IGNORE actions → queue to IMC for AllPoint ingestion.

Email Lambda — Deep Dive

A lightweight AWS Lambda that listens for SES email delivery status events via SNS/SQS. Filters by client/environment tags, transforms SES events to a standardized EmailStatusUpdateEvent, and POSTs them to the Data API via internal DNS resolution. Enables email delivery tracking within the platform.

Connectors Teamwork — Deep Dive

The most complex connector in the platform — a bidirectional CHQ/Teamwork integration handling 20+ inbound and 14+ outbound document types. Uses an Initiation/Continuation async pattern for long-running CHQ API operations: sends an initiation request, then polls for completion with exponential backoff (max 20 checks). Augmentation services enrich CHQ data exports by querying the CHQ RDB directly via Prisma + SQL Server (MSSQL). MongoDB handles transient request/cache state. 100+ Inversify DI bindings. Includes full-sync scripts, custom table support, and franchise-based location isolation.

Document Types

Inbound: Products, Customers, SalesOrders, PurchaseOrders, TransferOrders, Employees, Vendors, StockAdjustments, Shipments, Locations, and 10+ lookup/dictionary types. Outbound: CatalogStyles, Products, Prices, PurchaseOrders, TransferOrders, Employees, Vendors, Customers, StockAdjustments, and more.

Key Dependencies
@all-point/connectors-common @all-point/document-db (DynamoDB) Prisma + MSSQL (CHQ RDB) MongoDB (transient state) @all-point/queue @all-point/types Node.js 22 · v8.4.3

Connectors QBO — Deep Dive

An outbound-only financial document connector that pushes Bills, Vendor Credits, Journal Entries, Transfers, and Financial Summaries to QuickBooks Online. Uses a two-tier state machine pattern: the AllPoint state machine detects entity changes, then the QBO state machine handles the API submission lifecycle. OAuth2 token management with 55-minute cache, per-company semaphore for concurrent token refresh, and DynamoDB-backed token persistence. Rate limiting enforces 8 requests/sec and 4 concurrent operations. Client hooks extensibility via @ap-client-hooks/qbo allows per-client customization of mapping logic.

Key Dependencies
@all-point/connectors-common @all-point/document-db (DynamoDB) @all-point/queue @all-point/types OAuth2 token management YAML config files Node.js 22 · Port 8081
Layer 5 — Shared Libraries & Contracts
🧩
Connectors Common
repositories/connectors-common
State machine framework for all connector services — document lifecycle (NEW→PROCESSING→SUCCESS/ERROR/FAILED), batch processing, retry with backoff, job scheduling.
State Machine Backoff JobScheduler IMapper
📐
Types
repositories/types
Centralized type library — Zod schemas as source of truth for all 74 domain entities. Runtime validation and compile-time types from a single definition.
Zod Schemas z.infer Validators PreCalcs
Code Quality
repositories/code-quality
Company-wide config package — ESLint, Prettier, TypeScript base, Vitest config, and package version validation. Enforces consistent standards across all repos.
ESLint Flat Prettier tsconfig.base Vitest
📋
Logging
repositories/logging
Multi-transport logging library wrapping winston and pino. Environment-aware log levels, structured JSON output, and CloudWatch/console transports.
Winston Pino Multi-Transport Structured JSON
📬
Queue
repositories/queue
SQS producer/consumer abstraction with typed message envelopes, batch operations, FIFO support, and dead-letter queue handling.
SQS Producer SQS Consumer FIFO DLQ
🔧
Webapps Common
repositories/webapps-common
Shared Express/InversifyJS base classes for all web applications — DocumentDB wrapper, auth middleware, error handling, health checks, and DI bootstrapping.
Express Base InversifyJS DocumentDB Auth Middleware
🗃️
Document-db
repositories/document-db
DynamoDB abstraction library — CRUD with auto-compression (>400KB), batch state doc management with leasing & TTL, LRU cache decorator, and sliding-window rate limiting.
DynamoDB Compression State Docs LRU Cache 9+ consumers
📡
Instrumentation
repositories/instrumentation
OpenTelemetry wrapper — @traceClass/@traceClassMethod decorators, auto-instrumentations (HTTP, Express, AWS SDK, Prisma, Undici), environment-aware sampling.
OpenTelemetry Decorators Auto-Instrument OTLP

Connectors Common — Deep Dive

The backbone library for reliable document processing. Implements two state machine patterns: DocumentStateMachine (individual docs with 6-state flow, per-document metadata, orphan detection) and BatchDocumentStateMachine (batch processing with lease tracking, memory-safe generators). Includes a BackoffCalculator (exponential/linear/logarithmic), JobScheduler (cron-based), REST controllers for retry/health/job management, and instrumentation decorators. AWS ECS integration for instance tracking and Service Discovery registration.

Key Interfaces
IDocumentStateMachine<T> IBatchDocumentStateMachine<T> IMapper<I,O,C> IWorkflow IBackoffCalculator

Types — Deep Dive

Schema-first design: Zod schemas in validation/ define shape + constraints, then TypeScript types in all-point/ are derived via z.infer<>. Entity hierarchy: Identifiable → EntityDetail → BaseDocument → OperationalDocument → OperationalSubDocument. Covers the full retail domain: products/catalog, customers, sales orders/receipts, purchase orders/receipts, transfer orders, stock adjustments, shipments, vendors, employees, financial summaries, and 30+ dictionary/lookup types. PreCalcs types use Omit<> to strip calculated fields for pre-processing contexts.

Modules
all-point (core domain) validation (Zod + Validators) document-logic (PreCalcs) utility (TS helpers) netsuite teamwork / gen2 quickbooks-online yotpo data-api

Code Quality — Deep Dive

Exports named configurations: eslintConfig (TypeScript-first with Google TS Style inspiration, JSON property sorting, no describe.only/it.only), prettierConfig (120 width, 4-space tabs, avoid arrow parens, Prisma plugin), vitestConfig (Istanbul coverage, JUnit XML for Bitbucket), and tsconfig.base.json (strict, ESNext, decorators, source maps). Also ships a package-version-validator CLI that blocks caret/tilde/star versions for @all-point/* and inversify* packages.

Logging — Deep Dive

A multi-transport logging library that wraps both winston and pino with a unified API. Provides structured JSON output for production (CloudWatch-compatible) and human-readable console output for development. Environment-aware log level configuration (DEBUG in dev, INFO in prod). Used by every service in the platform for consistent, searchable log output across all layers.

Key Features
Winston + Pino dual engine Structured JSON logs CloudWatch transport Environment-aware levels Correlation ID propagation

Queue — Deep Dive

An SQS abstraction layer providing typed producer/consumer patterns with message envelope handling. Supports both standard and FIFO queues, batch send/receive operations, dead-letter queue integration, and message visibility timeout management. The producer serializes typed message payloads into SQS-compatible envelopes; the consumer deserializes and dispatches to registered handlers. Used by IMC for fan-out, connectors for task distribution, and Data API for async event processing.

Key Capabilities
Typed message envelopes Batch send/receive FIFO + deduplication DLQ integration Visibility timeout management

Webapps Common — Deep Dive

Shared foundation for all Express-based web applications. Provides base classes for InversifyJS DI container bootstrapping, DocumentDB (MongoDB) client wrapper with connection pooling, auth middleware for JWT token validation, standardized error handling middleware, health check endpoints (liveness + readiness), and request context propagation. Reduces boilerplate when standing up new services — a new microservice inherits auth, logging, DB access, and health probes out of the box.

Key Exports
BaseApplication (DI bootstrap) DocumentDB client wrapper Auth middleware (JWT) Error handler middleware Health check controller Request context (AsyncLocalStorage)

Document-db — Deep Dive

The platform's DynamoDB abstraction layer, used by 9+ services. Provides four repository patterns: DocumentRepository (CRUD with auto-compression via compress-json for documents >400KB), BatchDocumentRepository (state document management with leasing, TTL, partitioned queries, and status filtering via StateDocumentStatus enum), CachedDocumentRepository (LRU in-memory cache decorator wrapping any DocumentRepository), and CapacityTracker (sliding-window rate limiting with EWMA smoothing for DynamoDB throughput management).

Table Naming Convention

${AP_CLIENT}.${AP_ENVIRONMENT}.${AP_COMPONENT_NAME}.${collection} — ensures multi-tenant isolation at the DynamoDB table level. State document statuses: New, Processing, Success, Failed, Error, Deleted, Discarded.

Key Exports
DocumentRepository (CRUD) BatchDocumentRepository (state docs) CachedDocumentRepository (LRU) CapacityTracker (rate limiting) compress-json (>400KB) v4.0.27-dev.0

Instrumentation — Deep Dive

A centralized OpenTelemetry wrapper that provides consistent distributed tracing across all platform services. Features @traceClass and @traceClassMethod decorators for automatic span creation, plus traceFunction() for standalone functions. Auto-instruments HTTP, Express, AWS SDK, Prisma, and Undici libraries. Uses AsyncLocalStorageContextManager for trace context propagation across async boundaries. Environment-aware: 10% sampling in production (BatchSpanProcessor) vs 100% in development (SimpleSpanProcessor). Also supports Next.js via a dedicated initNextjsOtelInstrumentation entry point.

Key Features
@traceClass / @traceClassMethod @ignoreClassMethodTrace Auto-instrumentations (5 libs) OTLP HTTP exporter Sensitive field protection Next.js support v0.2.5-dev.2
Layer 6 — Infrastructure & Cloud Services
☁️
AWS Cloud
us-east-1
Cognito (IdP) · SQS (queues) · S3 (files) · ECR (containers) · ECS (compute) · Service Discovery · Secrets Manager · CodeArtifact (npm) · CloudWatch
Cognito SQS S3 ECS ECR CloudWatch
🗄
Databases
Managed services
MySQL (Data API — relational entities), PostgreSQL 17 (Config Service, Shopify sync), MSSQL/SQL Server (Teamwork CHQ RDB), MongoDB (webapps-common — documents, auth), DynamoDB (@all-point/document-db — state docs, connector storage), Redis 7 (config caching).
MySQL 8 PostgreSQL 17 MSSQL MongoDB DynamoDB Redis 7 Prisma 6
📡
Observability
OpenTelemetry + CloudWatch
OTLP exporter with environment-aware sampling (10% prod, 100% dev). Tracing decorators across all services. Batch span processor.
OpenTelemetry OTLP Instrumentation

📐 Schema-First Contract Layer

The @all-point/types package is the platform's contract layer. Zod schemas define both runtime validation rules and compile-time TypeScript types from a single source. Every service depends on this package, ensuring the 74 domain entities are consistently validated and typed across the entire ecosystem. The entity hierarchy (Identifiable → EntityDetail → BaseDocument → OperationalDocument) cleanly separates master data from transactional documents.

🔐 Centralized Auth with Multi-Tenant RBAC

All Point Access is the single authentication gateway. It implements OAuth 2.0 Authorization Code flow with AWS Cognito, issuing JWE-encrypted tokens. The RBAC model supports per-environment, per-client role hierarchies with franchise-based access control. Per-application session management allows users to maintain independent login states across multiple All Point applications simultaneously.

🔀 State Machine Document Processing

connectors-common provides the reliability backbone. Two state machine patterns — individual (6-state with per-document tracking) and batch (lease-based with memory-safe generators) — handle all document processing with configurable retry algorithms, orphaned document detection, and full transaction step recording. Every connector service inherits this framework, ensuring consistent error handling and observability.

📊 CQRS-Aligned Data API

The Connectors Data API separates read and write concerns through distinct CommandService and QueryService base classes. A factory-driven BusinessLogic layer handles domain validation, RDB↔domain mapping, and Prisma includes per entity. The dual-database strategy uses MySQL (Prisma, 50+ models) for relational product/inventory data and MongoDB for flexible document storage, with S3 for files and SQS for async messaging.

⚙️ Background Processing with Real-Time Feedback

Jobs Sidecar solves the heavy-lift problem with a WebSocket (socket.io) server backed by Node.js worker threads. The Factory pattern (5 factory maps) resolves the entire processing pipeline at runtime by upload type. The UploadProcessorServiceBase provides an 8-step pipeline covering S3 download through batch DAPI submission, with real-time progress streamed back to the Franchise Portal UI.

🧩 InversifyJS Everywhere

Every service uses InversifyJS for dependency injection with Symbol-based bindings. This provides constructor injection, lifecycle management (singleton vs transient), and testability through interface-based contracts. The Data API alone registers 160+ bindings. Combined with the shared code-quality config (ESLint, Prettier, tsconfig, Vitest), this creates a remarkably consistent development experience across all repositories.

⚙️ Centralized Configuration with Rollout Rules

All Point Config is a two-part system: a NestJS 11 backend (PostgreSQL 17 + Redis 7) managing versioned configs with JSON Schema validation and percentage-based rollout targeting, plus a lightweight client library (@all-point/config) consumed via DI across all services. Cache invalidation propagates via SNS/SQS. Every service depends on Config for runtime settings, feature flags, environment resolution, and document type definitions.

🔌 Connector & Integration Model

All Point uses a connector model for external system integration. An inbound connector (source) ingests data from an external system into All Point entities. An outbound connector (destination) pushes entity changes to the external system. The combination of inbound + outbound for a given platform forms a productized integration. Each connector extends the state machine framework from connectors-common, ensuring consistent lifecycle management, retry logic, and observability across all integrations.

🔧 Shared Library Foundation

Eight foundational libraries underpin the platform: @all-point/types (74 Zod-validated entities), @all-point/connectors-common (state machine framework), @all-point/document-db (DynamoDB abstraction), @all-point/instrumentation (OpenTelemetry tracing), @all-point/queue (SQS producer/consumer), @all-point/logging (winston/pino multi-transport), @all-point/webapps-common (Express/Inversify/MongoDB base classes), and @all-point/code-quality (ESLint/Prettier/tsconfig/Vitest). This layered approach means a new microservice inherits auth, logging, DB access, queuing, tracing, validation, and health probes out of the box.

🗃️ DynamoDB Storage Layer (document-db)

@all-point/document-db is a DynamoDB abstraction used by 9+ services. It provides four repository patterns: DocumentRepository (CRUD with auto-compression >400KB), BatchDocumentRepository (state document management with leasing, TTL, and partitioned queries), CachedDocumentRepository (LRU in-memory cache decorator), and CapacityTracker (sliding-window rate limiting with EWMA smoothing). Multi-tenant table naming (client.env.component.collection) ensures data isolation. Note: this is distinct from webapps-common's DocumentDB wrapper, which targets MongoDB.

📡 Distributed Tracing (Instrumentation)

@all-point/instrumentation provides consistent OpenTelemetry-based distributed tracing across all services. Decorator-driven (@traceClass, @traceClassMethod) for automatic span creation, with auto-instrumentations for HTTP, Express, AWS SDK, Prisma, and Undici. Environment-aware sampling (10% production, 100% development) balances observability cost with debugging capability. OTLP HTTP exporter ships traces to the observability backend. Sensitive field protection ensures PII is excluded from trace arguments.

🏢 Six-Database Architecture

The platform uses six distinct database technologies, each chosen for its strengths: MySQL (Data API — relational product/inventory via Prisma), PostgreSQL (Config Service, Shopify sync coordination), MSSQL/SQL Server (Teamwork CHQ RDB queries via Prisma), MongoDB (webapps-common — documents, auth state), DynamoDB (@all-point/document-db — connector state docs, product builder storage), and Redis (config caching via cache-manager). Prisma serves as the ORM for three of these (MySQL, PostgreSQL, MSSQL).

Inbound Connector Flow (Source → All Point)

1

External System Event (Source)

A change occurs in the source system (Shopify, Teamwork, NetSuite, etc.) — new order, product update, inventory adjustment. This triggers a webhook or scheduled poll via the inbound connector.

2

Lambda → IMC (Intermediate Connector)

Lambda posts the document payload to the IMC's /documents endpoint. The CatchAllStateMachine validates structure, then queries AWS Service Discovery for all active connectors-* services.

3

IMC → SQS Fan-Out

IMC sends the validated document to each matching connector's SQS queue in parallel. Partial failure is tolerated — a document only fails if ALL queues reject it.

4

Connector State Machine Processing

Each connector service (extending connectors-common) picks up the SQS message. The DocumentStateMachine transitions it through NEW → PROCESSING, runs IMapper transforms, validates via @all-point/types, then writes to the Data API.

5

Data API Persistence

The Data API's CommandService validates the document against its BusinessLogic layer, maps to the Prisma RDB model, and writes to MySQL. Any document-db records (state, audit) go to MongoDB. Files to S3.

Upload / Import Flow (Franchise Portal)

1

User Uploads File

A franchise operator uploads an Excel/CSV file (products, purchase orders, stock transfers, etc.) through the Franchise Portal UI. The file is stored in S3.

2

WebSocket Job Creation

The Franchise Portal emits a jobCreated event via socket.io to the Jobs Sidecar. The JobService creates a PENDING job record in document-db.

3

Worker Thread Processing

WorkerPoolService dispatches to a worker thread. The appropriate UploadProcessor (resolved by factory) downloads from S3, parses Excel, validates structure → schema → domain, checks duplicates, then batch-sends to the Data API.

4

Real-Time Progress

Worker threads emit WorkerProgressEvent at each stage. JobService relays these as JOB_UPDATED_EVENT via socket.io to the Portal, which updates its UI in real time. On completion, a JOB_FINISHED_EVENT is emitted with the final result summary.

Outbound Connector Flow (All Point → Destination)

1

Entity Change in All Point

A product, customer, or other entity is created or updated in the Data API — either by a user action in the Franchise Portal, an inbound connector sync, or a bulk upload via Jobs Sidecar.

2

Outbound State Machine Detection

The outbound connector's state machine (e.g., OutboundProduct, OutboundCustomer) detects the change via DynamoDB state documents. Filters by status, sales channel, and business rules to determine if sync is required.

3

Entity Mapping & Task Publishing

The IMapper transforms the All Point entity into the destination system's format (e.g., Shopify ProductSetInput). Tasks are published to SQS FIFO queues with deduplication for reliable delivery.

4

Worker Execution to Destination

Cluster worker processes consume SQS tasks and execute API calls to the destination system (e.g., Shopify GraphQL Admin API). Adaptive rate limiting per store, circuit breakers for quota exhaustion, and three-way merge for webhook conflict resolution ensure reliable delivery.

Languages & Runtime
  • TypeScript 5.x (strict mode)
  • Node.js 20–22
  • ESM modules
Web Frameworks
  • Next.js 14–16 (Access, Portal)
  • NestJS 11 (Config Service)
  • Astro 5 (Support)
  • Express (Data API, IMC)
  • inversify-express-utils
UI Libraries
  • React 18–19
  • Tailwind CSS 4
  • MUI v7 (Data Grid Premium)
  • Radix UI
  • TanStack Query
  • SWR / React Hook Form
Dependency Injection
  • InversifyJS 6
  • Symbol-based bindings
  • reflect-metadata
Databases & Caching
  • MySQL 8 (via Prisma 6)
  • PostgreSQL 17 (Config, Shopify)
  • MSSQL / SQL Server (Teamwork CHQ)
  • MongoDB (webapps-common wrapper)
  • DynamoDB (@all-point/document-db)
  • Redis 7 (cache-manager)
  • LRU Cache (in-memory)
Validation
  • Zod (types v29, sidecar v4)
  • StandardValidator framework
  • Joi (Access API)
AWS Services
  • Cognito (identity)
  • SQS / SQS FIFO (queuing)
  • SNS (pub/sub notifications)
  • S3 (storage)
  • Lambda (email, triggers)
  • SES (email delivery)
  • ECS / ECR (compute)
  • DynamoDB (connector state)
  • Service Discovery
  • Secrets Manager
  • CodeArtifact (npm)
  • CloudWatch (logs)
Messaging & Real-Time
  • SQS / SNS (async messaging)
  • socket.io (WebSocket)
  • Worker threads (workerpool)
  • Node.js Cluster (primary/worker)
  • Shopify GraphQL Admin API
  • Teamwork CHQ REST API
  • QuickBooks Online REST API
Observability
  • @all-point/instrumentation (OTel wrapper)
  • @traceClass / @traceClassMethod decorators
  • Auto-instrument: HTTP, Express, AWS SDK, Prisma, Undici
  • OTLP HTTP exporter (10% prod / 100% dev)
  • @all-point/logging (winston + pino)
  • CloudWatch (logs)
Auth & Security
  • OAuth 2.0 (Authorization Code)
  • JWE encrypted tokens
  • Passport JWT (Config Service)
  • better-auth (Access)
  • AWS Cognito (IdP)
  • RBAC + Scope-based auth
Build & CI/CD
  • Bitbucket Pipelines
  • Docker (Alpine)
  • pnpm / npm
  • tsc --build
  • Blue-Green deploy
Testing
  • Vitest 3–4
  • Istanbul coverage
  • JUnit XML (Pipelines)
File Processing
  • ExcelJS / read-excel-file
  • csv-parse
  • Puppeteer (PDF gen)
  • Sharp (images)
  • fluent-ffmpeg (video)