MTS BigCommerce AI Commerce Intelligence Next steps
Standalone complete documentation · we develop

MTS BigCommerce AI
Commerce Intelligence

Everything about this application in one self-contained file: what it does, how it is built, what MageTech Solutions provides, develops, maintains and creates from scratch, and exactly what you receive at handover. A multi-tenant analytics and decision platform for BigCommerce merchants — explainable AI, real store integration, enterprise access control, and a delivery model measured in weeks.

MageTech Solutions · monorepo mts-bigcommerce-intelligence · Next.js 15 · NestJS 11 · PostgreSQL 16 · Redis 7 · Prisma 6 · BullMQ 5 · TypeScript 5

Section 01

In one page

MTS BigCommerce AI Commerce Intelligence is a finished, running product — not a proposal. You can log in today and use every module. This document covers everything: what the application does, how it is engineered, what MageTech Solutions provides, and precisely what you receive.

▣

What it is

A multi-tenant analytics and decision platform for BigCommerce merchants. Sales, customers, products, inventory and marketing in one warehouse, with explainable AI insights, threshold alerts, an AI copilot and scheduled reports, served through a role-aware web application.

◧

How it works

BigCommerce sync by OAuth or API token, normalised into PostgreSQL, then metrics, a deterministic rule engine and an optional LLM copilot turn that data into dashboards, alerts, recommendations and exports.

✦

Why it is different

Explainable by design. Every insight carries its evidence, severity and recommended action, computed from the merchant's own data — with strict privacy modes and a full audit trail, not black-box scoring.

Product
MTS BigCommerce AI Commerce Intelligence
Built and supported by
MageTech Solutions
Applications
3 — web, API, worker
Shared packages
6 — shared, database, ai, bigcommerce, analytics, config
REST surface
64 endpoints · 18 controllers
Data layer
32 models · 30 enums · PostgreSQL 16
Automation
5 queues · 5 scheduled jobs
Access control
7 roles · 25 permissions · tenant isolation
AI
7 detectors · recommendation builder · copilot tool calls
Quality gates
Types · lint · 10 browser E2E tests · CI on every push
Demo data
1,284 products · 12,450 customers · 8,420 orders
Deployment
Docker-ready · environment-driven · 43 documented variables

The one-line difference

Most vendors sell a dashboard, a report or a model. We hand over a working commerce platform, the engineering capability to extend it indefinitely, and a delivery model where a working version is in your hands in weeks — with the code, the documentation and the knowledge to make it entirely yours.

Section 02

Who we are

MageTech Solutions is a software product engineering company. We take ideas from discovery to a supported, running product, and we stay accountable for it afterwards. This application is the proof.

What that means in practice

  • We build products, not just features. A complete, working, supported application — which is why this platform exists and runs today.
  • We own outcomes. We are measured on whether the platform answers your questions, whether the data is right, and whether your team can use it without us.
  • We hand over properly. Source code, documentation, environment definition, CI pipeline, training and support handover. No lock-in, no proprietary black boxes.
  • We stay after go-live. Maintenance, monitoring, upgrades and a roadmap you can influence as the business changes.
  • We are technology specialists. TypeScript, modern web frameworks, API architecture, data platforms, cloud delivery and AI engineering are our craft, not a subcontracted skill.

How this document is organised

  • Sections 1–5 — the product: what it is, who uses it, and how it differs.
  • Sections 6–22 — the engineering: stack, architecture, data, API, AI, integration, jobs, security, delivery, testing, configuration, demo data.
  • Sections 23–29 — the relationship: how we demo, what we deliver, what we develop, maintain and build from scratch, our services, expertise, pricing and engagement models.
  • Sections 30–32 — outcomes, quality commitments, roadmap, next steps and reference appendix.

The platform as our proof

We could describe our capability. It is faster to show it. This application is the reference implementation of how we work: structured, opinionated, complete and running.

MTS BigCommerce AI Commerce Intelligence — dashboard
$284.5KRevenue
8,420Orders
12,450Customers
7AI insights

Every figure above is computed from the warehouse by the same services that run in production. The demo is the product, not a mock-up.

We do not ask you to trust a slide deck. We ask you for thirty minutes with a working system.
MageTech Solutions · demo philosophy
Section 03

The problem we solve

BigCommerce merchants have the data but not the answers. The control panel reports what happened; nobody joins sales, customers, stock and marketing into a single decision view.

Where it hurts todayWhat it costsWhat this platform does
Sales in the control panel, stock in a grid, marketing in ad toolsDecisions made on one slice of the businessOne warehouse and one joined view across all ten modules
Stockouts and churn discovered after the revenue is goneLost margin and lost repeat customersDaily insight engine, coverage maths, at-risk segments, threshold alerts
Weekly exports rebuilt by handHours of labour, inconsistent numbers, no audit trailParameterised CSV reports, scheduled delivery, retained history
Generic AI tools with no access to store dataConfident answers with invented numbersDeterministic rules first, optional LLM explanation second, every figure traceable
Merchant data leaving the business for third-party AIPrivacy exposure and compliance riskAI_PROVIDER=rule runs fully local; strict privacy mode blocks context sharing
Nobody can answer "who changed this, and when?"Trust failures and audit findingsRole-based access, tenant isolation, and a full audit trail with actor and IP
Reporting depends on one analyst's spreadsheetA single point of failureGoverned exports, documented data dictionary, self-serve module access

Lost revenue

Stockouts on priority SKUs, lapsing high-value customers, budget sitting in campaigns that do not return revenue. All three are visible in the platform before they become losses.

Lost time

Analysts and operations staff rebuilding the same exports every week. Generated reports and scheduled delivery replace that work with a review step.

Lost trust

Numbers nobody can reproduce, AI answers nobody can defend, access nobody can govern. Each is closed with an explicit mechanism, not a promise.

Section 04

Who uses it and what they get

One platform, five operating personas, each with a scoped view of the same tenant data — enforced on the server, not just hidden in the interface.

O
Store ownerOne number for revenue, orders, margin risk and customer value. Full administration of team, plan and integration.
A
Operations managerCoverage, low-stock and reorder signals early enough to act on, per variant and per location, with alert rules they own.
S
Sales managerPipeline by status, channel contribution, AOV movement and order-level detail, plus report exports for the commercial review.
M
Marketing managerCampaign spend, attributed revenue, ROAS, CTR and conversion — compared against store-wide performance, not in isolation.
A
AnalystFull read across modules, generated insights, report creation and the copilot for ad-hoc questions.
V
Finance, agency or stakeholderA safe, read-only seat: dashboards and report downloads, with no access to configuration or integration secrets.

Why we demo roles, not just screens

Anyone can show a chart. Showing the same screen to two people and letting them see different things — enforced server-side — is how we prove the platform is enterprise-ready. In every demo we sign in as two roles so the customer notices the difference themselves.

Section 05

How it differs from the alternatives

An honest comparison against what a merchant already considers: native reporting, general BI, spreadsheets, plug-in AI assistants and custom agency builds.

CapabilityBigCommerce nativeGeneral BISpreadsheetsGeneric AI chatThis platform
Time to first insightMinutes, but surface-levelWeeks of pipeline buildHours per reportInstant but uninformedInstant on a synced or seeded store
Cross-domain view (sales + stock + customers + marketing)Partial, siloedYesManual joinsNoYes — one warehouse, on-read metrics
Explainable AI insightsNoNoNoOpaque, prompt-dependentRule detectors with evidence and severity
Works with no data leaving the infrastructuren/aDependsYesNoYes — local provider, strict privacy mode
Automated alerts and scheduled reportsBasicExtra toolingManualNoYes — queued schedules, CSV exports, notifications
Role-based access and audit trailLimitedExtra toolingFile permissionsNoYes — 7 roles, 25 permissions, audited actions
Time to deploy and cost to ownIncluded but limitedHighLow tech, high labourSubscription, no contextDocker-ready monorepo; demo mode runs in minutes
Who stands behind itPlatform vendorTool vendorInternalModel vendorMageTech Solutions — build, hosting, roadmap

Not another dashboard

Dashboards report. This platform also decides what deserves attention, why it matters, and what to do — then tells the right role and records the outcome.

Not a black box

Every insight has evidence, every recommendation has a priority, every number is computed from stored records. If finance disputes a figure, we can show the query path.

Not a dependency

Source, documentation, infrastructure definition and CI are handed over. Keeping the platform running without us is a deliberate design constraint, not a failure mode.

Section 06

Technology stack — end to end

A TypeScript-first monorepo: one language across the API, the worker, the shared packages and the web client, with PostgreSQL as the system of record and Redis as the job and cache layer.

Experience
Next.js 15 App RouterReact 19, TypeScript strict, route groups for the marketing site and the authenticated application
Tailwind CSS 4 design systemBrand tokens, module accent colours, hand-rolled SVG charts, no chart dependency
Client data layerTyped fetch helpers, cookie sessions, cached reads, optimistic actions
Application
NestJS 11 API18 controllers, global /api prefix, guards, decorators, CORS allowlist, raw body for webhooks
NestJS 11 workerBullMQ processors and repeatable schedulers, no HTTP listener
Shared packagesZod environment schema, AES-256-GCM crypto, period and metric helpers, plan catalogue
Data and integrations
PostgreSQL 16 + Prisma 632 models, 30 enums, one committed migration, tenant-scoped client extensions
Redis 7 + BullMQ 55 queues, exponential-backoff retries, repeatable job schedulers
BigCommerce and AI providersOAuth 2.0, V2/V3 REST, signed JWT payloads, HMAC webhooks; OpenAI, Anthropic, Google optional
BrowserNext.js :3000Nest API :3001PostgreSQL / Redis
LayerTechnologyVersionRole in the platform
LanguageTypeScript^5.7.3Strict mode everywhere; shared types across API, worker, packages and web
RuntimeNode.js>=20 (CI on 20)API and worker runtimes; npm workspaces for the monorepo
Monoreponpm workspaces + Turborepo^2.4.4Dependency-ordered build, lint and typecheck; persistent dev tasks
WebNext.js / React / Tailwind^15.1.3 / ^19.0.0 / ^4.0.0Marketing site, authenticated app, SVG chart library, design system
APINestJS (common, core, platform-express)^11.0.1REST controllers, session and permission guards, metrics service
Worker@nestjs/bullmq / bullmq / ioredis^11.0.3 / ^5.58.0 / ^5.6.1Sync, insights, alerts, reports and scheduler processors
DataPrisma ORM / PostgreSQL^6.2.1 / 16Schema, migrations, typed client, tenant extensions, seeding
Cache and queuesRedis7-alpineBullMQ broker, stable job ids, repeatables
ValidationZod^3.24.1Environment schema and BigCommerce payload schemas
Auth cryptobcryptjs / node:crypto / jose^3.0.2 / built-in / ^5.9.6Password hashing, SHA-256 session tokens, AES-256-GCM secrets, HS256 JWT verification
AIRule engine + provider adaptersin-house / optionalDeterministic insights; OpenAI, Anthropic and Gemini adapters with fallback
QualityESLint, typescript-eslint, react-hooks, Playwright^9.39.5 / ^8.70.1 / ^5.2.0 / ^1.63.0Lint gate, type gate, ten browser E2E tests in CI
Section 07

System architecture

Three deployable applications and six shared packages, wired by npm workspaces and orchestrated by Turborepo. The API and worker share one Prisma client factory with tenant scoping, so isolation is structural rather than a convention.

The request path

  1. BrowserCredentialed request; the session travels in the mts_session cookie — HttpOnly, SameSite=Lax, Secure in production.
  2. Next.js proxyThe typed client routes /api/* to the Nest API. Server components fetch without a base URL; client components resolve it from the environment.
  3. GuardsSessionGuard resolves the hashed token to a live session and attaches tenant, user and role; PermissionsGuard enforces declared permission keys.
  4. Controller and serviceControllers validate and delegate; business rules live in services and shared packages. Nothing heavy runs inline.
  5. Tenant-scoped PrismaQueries run through the extended client; tenant models are filtered by tenantId at the client layer, with additional assertions in sensitive service paths.

The background path

  1. SchedulerFive repeatable jobs register on boot: sync dispatch, nightly full sync, daily insights, alert sweep and report delivery.
  2. QueueJobs land on dedicated BullMQ queues with a stable job id per entity, so repeated triggers collapse instead of duplicating work.
  3. ProcessorThe worker executes sync (paged fetch, upsert, checkpoint), insights (metrics, detectors, persistence), alerts (rules, notifications) and reports (CSV materialisation).
  4. Result surfaceOutputs land in the database and on disk: insights, recommendations, notifications, sync-run records and storage/reports/<tenant>/<report>.csv.

Why one Prisma client factory

Both applications import @mts/database, which is marked server-only; the web client may only import type from it. One factory means one place controls pooling, tenant extension and disconnect behaviour — a requirement for container and serverless-style deployment targets.

Section 07.1

End-to-end journeys

The three paths a merchant actually walks, from installation to an AI-assisted decision. These are also the paths we follow in every demo.

Journey A

Install and first sync

  1. Create the workspaceSign-up produces a tenant, an owner account and a trial subscription.
  2. AuthenticateSign in with the session cookie, or start the BigCommerce OAuth flow from Settings.
  3. Connect the storeOAuth callback, or paste a store hash and access token for a staff API account.
  4. Queue the workA sync run is created and enqueued; the dispatch scheduler picks up pending runs.
  5. Watch progressSettings shows entity-level status, item counts, checkpoints and errors.
Journey B

Analyse the business

  1. Open the dashboardRevenue, orders, AOV, customers and alerts for the selected period.
  2. Drill into a moduleSales trends, customer segments, product performance, inventory coverage, campaign ROI.
  3. Read the insight feedGenerated findings with severity, evidence, impact and a recommended action.
  4. Ask the copilotNatural-language questions route to tool calls over the same metrics.
  5. ExportGenerate a report and download the CSV for finance and planning.
Journey C

Act on an alert

  1. Get notifiedAn in-app notification arrives when a rule's threshold is crossed.
  2. Assess impactOpen the alert to see the rule, the breached metric and the evidence.
  3. Apply a recommendationFollow the suggested action: reorder, win-back, promotion review or stock review.
  4. Close the loopMark it read or resolved; the audit log records who did what and when.
Section 08

Repository structure

The monorepo is the product: every module, migration, test and environment key lives in one versioned tree with a predictable shape.

mts-bigcommerce-intelligence/
├── apps/
│   ├── web/                      # Next.js 15 app — marketing + authenticated application
│   │   ├── src/app/(marketing)/  # home, features, pricing, about, contact, install, how-it-works, login, signup
│   │   ├── src/app/(app)/        # dashboard, sales, customers, products, inventory, marketing, insights, reports, alerts, settings
│   │   ├── src/components/       # app-shell, ui, data, charts, notification-bell, copilot
│   │   ├── src/lib/              # brand tokens, API client, hooks, formatting
│   │   └── public/               # logo and favicon assets
│   ├── api/                      # NestJS REST API
│   │   ├── src/modules/          # 18 controllers + services (auth … webhooks)
│   │   ├── src/common/           # guards, decorators, filters, interceptors
│   │   ├── src/app.module.ts     # module wiring, CORS, raw body
│   │   └── prisma/seed/          # demo workspace generation
│   └── worker/                   # NestJS BullMQ worker
│       ├── src/processors/        # sync, insights, alerts, reports, scheduler
│       └── src/worker.module.ts   # queues and repeatables
├── packages/
│   ├── shared/                   # zod env schema, crypto, periods, constants, plan catalogue
│   ├── database/                 # prisma/schema.prisma, client + tenant extension, seed
│   ├── ai/                       # rule engine, copilot tools, provider adapters, usage metering
│   ├── bigcommerce/              # API client (rate limit, retries), OAuth JWT, webhook verification
│   ├── analytics/                # shared metric computation for API, insights and reports
│   └── config/                   # shared tsconfig and eslint bases
├── e2e/                          # Playwright specs: auth, app, bigcommerce
├── docs/                         # ARCHITECTURE.md, API.md, DEVELOPMENT.md
├── storage/reports/              # generated CSV reports, tenant-partitioned
├── infrastructure/docker-compose.yml  # postgres:16-alpine, redis:7-alpine, adminer (tools profile)
├── turbo.json                    # task graph and caching
├── playwright.config.ts          # dev-server reuse, storage-state auth
├── .github/workflows/ci.yml      # verify → build/lint/typecheck; e2e → services + seed + Playwright
└── .env.example                  # 43 documented variables

Conventions that keep the tree predictable

Every feature follows the same shape: Prisma model and migration in packages/database; rules in a shared package; a thin controller plus service in apps/api; a processor in apps/worker if asynchronous; a page and components in apps/web; an end-to-end assertion in e2e; and documentation updated in the same change. That is why the second feature costs less than the first.

Section 09

Data model

32 models and 30 enums in a single tenant-rooted schema. Every business record carries a tenantId, and the tenant client extension enforces that boundary on all scoped models.

Identity

Tenant, User, Role, Permission, Session, AuditLog, Subscription, Plan.

Commerce

Order, OrderItem, Customer, Product, ProductVariant, Category, Brand, InventoryLevel, InventorySnapshot.

Analytics

SalesSnapshot, CustomerSegment, Campaign, Insight, Recommendation, CopilotMessage, AiUsage.

Operations

AlertRule, Alert, Notification, Report, ReportSchedule, SyncRun, BigCommerceConnection, WebhookEvent.

AreaKey modelsDesign notes
TenancyTenant to all scoped models30 of 32 models are tenant-scoped; the client extension injects tenantId automatically and services may still assert it for defence in depth.
Identity and accessUser, Role, Permission, SessionUsers carry a role; roles own a permission set; 25 stable permission keys are seeded. Sessions store a SHA-256 hash of the token, never the token.
OrdersOrder, OrderItemOrders keep external ids, status, channel, totals, customer and timestamps. Items snapshot product, variant and price at purchase time, so historical revenue never shifts when a catalogue price changes.
CustomersCustomer, CustomerSegmentOrder count, lifetime value and last order are denormalised for fast segmentation; segments store rules as JSON with member counts.
CatalogueProduct, ProductVariant, Category, BrandProducts carry channel mapping, status, pricing and lifecycle fields; variants carry SKU, barcode, cost and dimensions; categories and brands map to BigCommerce channels 1–7.
InventoryInventoryLevel, InventorySnapshotCurrent level plus location and reorder data; snapshots provide the coverage trend behind days-remaining and stockout risk.
AnalyticsSalesSnapshotOne row per tenant per day per channel: revenue, orders, units, AOV. Pre-aggregation keeps dashboards fast at any realistic scale.
MarketingCampaignSpend, clicks, impressions, attributed revenue and derived ROAS, CTR and conversion rate, with channel and status enums.
IntelligenceInsight, Recommendation, CopilotMessage, AiUsageInsights persist type, severity, title, message, evidence JSON and status. Recommendations dedupe on category plus action with high, medium or low priority. Copilot turns and provider usage are logged per tenant and user.
AutomationAlertRule, Alert, Notification, Report, ReportScheduleRules store operator, threshold and window; alerts record metric, value, threshold and status; reports track type, parameters, file path and generation time.
IntegrationBigCommerceConnection, SyncRun, WebhookEventConnection stores encrypted credentials, status, last sync and installed scope set. Sync runs track entity, status, counts, checkpoint and error. Webhook events are idempotent by event hash.

Representative enums

Core

RoleKey OWNER, ADMIN, ANALYST, SALES_MANAGER, OPERATIONS_MANAGER, MARKETING_MANAGER, VIEWER · PlanKey STARTER, GROWTH, PROFESSIONAL, ENTERPRISE

Commerce

OrderStatus, ChannelType (web, pos, phone, marketplace, offline, store, kiosk), ProductStatus, PaymentStatus, FulfillmentStatus

Intelligence

InsightType, InsightSeverity, RecommendationType, RecommendationPriority, AlertType, CopilotIntent, AiProvider

Operations

SyncStatus, SyncEntity (categories, brands, products, customers, orders, inventory, settings), AlertOperator, NotificationType, ReportType

Migration discipline

The schema ships with a single initial migration creating all tables, indexes and enums. Additive changes follow the same path: edit the schema, generate a timestamped migration, review the SQL, keep the seed idempotent. Historical correctness is treated as a feature, not an afterthought.

Section 10

Modules and capabilities

Ten product modules sharing one design language, one data layer and one permission model. Each module owns an accent colour used consistently in navigation, page headers, cards and charts.

▦
Dashboard

The 60-second view

Revenue, orders, AOV, customer count, low-stock and open-alert counters; revenue and order trends; channel mix; top products; latest AI insights; recent activity.

◔
Sales

Revenue quality

Order pipeline by status, revenue trend against the previous period, channel contribution, AOV movement, order-level detail with customer context.

◎
Customers

Segments and retention

VIP, high-value, at-risk and inactive segments with counts and value at stake; lifetime value distribution; segment explorer; win-back targeting.

◫
Products

Catalogue health

Performance by revenue and units, status mix, category and brand breakdowns, price and margin view, and a product health score for assortment decisions.

▤
Inventory

Stock coverage

Days-remaining coverage, low-stock and out-of-stock queues, reorder points, stock-level trends and valuation, with variant-level drill-down.

◈
Marketing

Campaign ROI

Spend, attributed revenue, ROAS, CTR and conversion per campaign, channel efficiency comparison, and revenue trend in campaign context.

✦
Insights

Intelligence and copilot

Generated insights with evidence and severity, prioritised recommendations, full insight history, and the AI copilot for natural-language questions.

▤
Reports

Exports and schedules

Sales, inventory, customer and full-dataset reports, parameterised date ranges, CSV download, scheduled delivery and generation history.

◉
Alerts

Threshold monitoring

Rules for revenue drops, order anomalies, AOV shifts, low stock and churn; triggered alerts with metric, value and threshold; in-app notification feed.

⚙
Settings

Administration

BigCommerce connection and sync history, team and roles, subscription and plan, AI provider configuration, notification preferences, audit log.

What runs underneath every module

BigCommerce sync

OAuth install or API-account connect; paged, resumable sync of categories, brands, products, customers, orders, inventory and settings; signed webhooks; visible checkpoints.

Analytics engine

Shared metric computation — revenue, orders, AOV, growth, channel mix, stock cover, customer aggregates — used identically by the API, the insight engine and reports.

Background automation

Five job queues and five schedules: dispatch syncs, nightly full sync, daily insights, alert sweeps and report delivery. Nothing heavy runs on a user request.

Governance

Seven roles, 25 permissions, tenant-scoped data access, hashed session tokens, encrypted integration secrets and an audit trail of every administrative action.

Section 11

Roles and permissions

Seven roles, 25 seeded permission keys and a decorator-based guard. Roles are the unit of assignment; permissions are the unit of enforcement.

RoleTypical holderCapabilitiesSees
OwnerFounding merchant principalEverything, including team, plan and integration administrationAll modules and settings
AdminOperations or IT leadAll analytics, alerts and reports; manages the team and alert rulesAll modules except ownership-level plan changes
AnalystData analystFull read across modules; creates insights and reportsAll analytics modules
Sales managerSales leadSales, customers, products read; report generation; alert managementSales, Customers, Products, Reports, Alerts
Operations managerFulfilment or supply leadInventory and products focus; alert rules; report generationDashboard, Products, Inventory, Alerts, Reports
Marketing managerGrowth or acquisition leadMarketing and sales focus; report generation; alert viewingDashboard, Sales, Marketing, Reports, Alerts
ViewerFinance, agency, stakeholderRead-only dashboards and report downloadsDashboard, Sales, Customers, Products, Inventory, Marketing, Reports

How enforcement works

  • @RequirePermission('key') on a controller or handler; PermissionsGuard resolves the session user's role and compares it against the permission set.
  • @Public() marks the ten endpoints reachable without a session: health, authentication, the BigCommerce install entry point, the plan catalogue and the documented webhooks.
  • 54 endpoints require a session; 51 additionally require a permission — a deliberate split so "logged in" and "allowed to act" stay distinguishable in the audit log.
  • Guards attach tenant, user and role to the request context, so controllers never accept a tenant id from the client.

Permission key families

Analytics

analytics:read, sales:read, customers:read, products:read, inventory:read, marketing:read

Intelligence

insights:read, insights:generate, ai:copilot

Execution

reports:read, reports:generate, alerts:read, alerts:manage

Administration

settings:read, settings:manage, team:read, team:manage, bigcommerce:connect, bigcommerce:sync, audit:read

Keys are seeded data rather than hard-coded constants, so a merchant's role model can be extended without a schema change.

Section 12

API reference

64 endpoints across 18 controllers, mounted under a global /api prefix on port 3001. JSON in, JSON out; session-cookie authentication; a consistent status-code contract.

Base URL (dev)
http://localhost:3001/api
Authentication
Cookie mts_session (HttpOnly, SameSite=Lax)
Prefix
/api — no version segment
Public endpoints
10
Session-protected
54 (51 also permission-guarded)
Webhooks
Signed, raw-body verified, idempotent
Health
GET /api/health — liveness and dependency status
Validation
DTO and Zod schemas at the boundary
ControllerBase pathResponsibilitiesSample endpoints
AuthauthRegistration, login, session inspection, logoutPOST /auth/register · POST /auth/login · GET /auth/me · POST /auth/logout
HealthhealthService liveness and dependency checksGET /health
AnalyticsanalyticsDashboard summary, trends, channel mix, top productsGET /analytics/dashboard · GET /analytics/trends
SalessalesOrder pipeline, revenue trend, channel performanceGET /sales/orders · GET /sales/revenue
CustomerscustomersSegments, value distribution, segment membersGET /customers/segments · GET /customers/:id
ProductsproductsCatalogue performance, health, product detailGET /products · GET /products/:id
InventoryinventoryLevels, low stock, coverage, snapshotsGET /inventory/levels · GET /inventory/low-stock
MarketingmarketingCampaign performance and channel efficiencyGET /marketing/campaigns
InsightsinsightsList, generate, summary; recommendationsGET /insights · POST /insights/generate · GET /insights/recommendations
AI / CopilotaiCopilot turns and provider configurationPOST /ai/copilot · GET /ai/config
ReportsreportsList, generate, download, schedulesPOST /reports/generate · GET /reports/:id/download
AlertsalertsRules, triggered alerts, acknowledge and resolveGET /alerts/rules · POST /alerts/rules · GET /alerts
NotificationsnotificationsIn-app feed, unread count, mark readGET /notifications · POST /notifications/:id/read · POST /notifications/read-all
SettingssettingsTenant profile, team, roles, preferences, audit logGET /settings · GET /settings/team · GET /settings/audit
BigCommercebigcommerceInstall entry, OAuth callback, connect, sync trigger, status, disconnect, webhookGET /bigcommerce/install · GET /bigcommerce/callback · POST /bigcommerce/connect · POST /bigcommerce/sync · POST /bigcommerce/webhooks
PlansplansPlan catalogue and current subscriptionGET /plans · GET /plans/subscription
AuditauditTenant audit trail with actor, action, entity and IPGET /audit
Users (admin)usersTeam member invitations and role changesGET /users · PATCH /users/:id

Conventions

  • Collection routes are plural nouns; list endpoints accept a period (7, 30, 90 days or a custom range) plus pagination.
  • Mutations return the created or updated resource, or a compact acknowledgement for actions.
  • List responses wrap records with pagination metadata where a dataset can grow without bound.
  • Errors use standard status codes: 400 validation, 401 unauthenticated, 403 forbidden, 404 missing, 409 conflict, 501 not yet implemented.

Example: session lifecycle

POST /api/auth/login
{ "email": "admin@magetech.demo", "password": "MTS-demo-2026!" }
→ 200 { "user": {…}, "tenant": {…}, "expiresAt": "…" }
   Set-Cookie: mts_session=<opaque token>; HttpOnly; SameSite=Lax

GET /api/auth/me
Cookie: mts_session=<opaque token>
→ 200 { "user": {…}, "tenant": {…}, "role": { "key": "owner" } }

Only a SHA-256 hash of the token is stored. The raw token exists in the browser cookie and in transit — never in the database.

Section 13

The AI engine

A deterministic rule engine is the product's intelligence; language models are an optional presentation layer. Findings are computed from the tenant's own metrics, ranked, and stored as first-class records.

Rule engine pipeline

  1. Gather metricsThe analytics package computes revenue, orders, AOV, growth, channel mix, stock cover and customer aggregates for the requested window.
  2. Run detectorsRevenue, product, inventory, customer, segment, order and marketing detectors evaluate configured thresholds and return findings with type, severity, title, message and evidence.
  3. Build recommendationsFindings become concrete actions — reorder, win-back, promotion review, stock review — deduplicated by category plus action and ranked high, medium or low.
  4. PersistInsights and recommendations are written with status and impact, feeding the dashboard, the insight feed and the alert engine.

Default thresholds

SignalDefaultMeaning
Revenue move±5%Period-over-period revenue change worth investigating
Order move±5%Order volume anomaly
AOV move±5%Basket-size shift — a pricing or mix signal
At-risk customers30 daysRecency threshold for churn risk
Critical low stock7 days coverStockout imminent
Warning low stock14 days coverReorder planning window
Overstock90 days coverCapital tied up in slow-moving stock

Copilot

The copilot classifies a question into a typed intent, maps it to a tool call over the same metrics, and returns a grounded answer with supporting numbers.

  • Revenue and order questions for a period, compared to the previous window
  • Top products and best-performing channels
  • Inventory risk and low-stock questions
  • Customer segment and lifetime-value questions
  • Campaign and ROAS questions
  • "What should we do?" — answered with current recommendations, not a new invention

Provider configuration

Providers
rule (default, fully local) · openai · anthropic · google
Privacy mode
strict blocks context sharing · balanced sends redacted summaries · connected permits full context
Budget
AI_MAX_REQUESTS_PER_MONTH=500, with per-tenant usage recorded
Fallback
Any provider error transparently falls back to the local rule engine

Quality properties

  • No hallucinated numbers. Figures come from the metrics service, not from the model.
  • Explainable. Every insight carries readable evidence.
  • Auditable. Provider, tokens and request counts are logged per tenant and user.
  • Cost-aware. A monthly budget and per-tenant metering make AI spend attributable.

Known gap, stated honestly

The provider adapters assemble their request payloads, but the assembled business facts are not yet serialised into the external provider payload; today external calls are reserved for phrasing, while all figures still originate from the rule engine. This is on the roadmap and is a deliberate correctness-first choice.

Section 14

BigCommerce integration

Two supported connection paths, seven synced entities, resumable paged fetches, signed idempotent webhooks and encrypted credential storage. Written against the V2 and V3 REST APIs with V2 as the current compatibility baseline.

Connection paths

  1. Install entryGET /api/bigcommerce/install returns or redirects to the authorisation URL with state and the requested scope set.
  2. Merchant consentThe store owner authorises the app in BigCommerce; we never impersonate a merchant or store their password.
  3. CallbackGET /api/bigcommerce/callback exchanges the code for tokens, validates state, stores credentials encrypted and records installed scope.
  4. VerificationSignatures are verified; the connection status becomes connected and the first sync is queued.

Why read-only by design

Scopes are requested and stored as a set, and the product's stated purpose is analytics. Nothing in the platform writes back to the store. If a future roadmap item needs write access, it is an explicit, separately consented scope change — never a silent extension.

What is synced

EntityShapeDetail
CategoriesTreeHierarchy and visibility, mapped to channel 1–7
BrandsFlatName, slug and image reference
ProductsFlat with variantsStatus, pricing, channel mapping, lifecycle, images, variants with SKU, cost and dimensions
CustomersFlatContact, groups, order count, lifetime value, last order date
OrdersFlat with itemsStatus, channel, totals, timestamps, line items with price-at-purchase
InventoryBy locationLevels, reorder points, snapshot history for coverage maths
SettingsSingleStore profile and timezone context for reporting

Client behaviour

  • Rate limiting. Requests are paced against the store's limits rather than optimistically fired.
  • Retries. Transient failures back off exponentially instead of failing a run.
  • Paging. Large collections are fetched page by page with a checkpoint after each page, so an interrupted run resumes instead of restarting.
  • Upserts. Records are matched on external id and updated in place, making repeat syncs idempotent.
  • Auth signing. BigCommerce login JWT payloads are signed correctly rather than hand-built, which is a frequent cause of silent 401s in custom integrations.

Webhooks

Order, product and customer events are accepted on a raw-body route, signature-verified, de-duplicated by event hash, and then applied as a targeted partial sync of the affected entity — so a new order appears without a full nightly refresh.

Stated honestly

The integration path is complete and exercised against the demo seed. A first live store connection needs real store credentials and a publicly reachable OAuth callback URL; until a merchant store is connected, the platform runs on the seeded workspace so every screen, report and insight is still demonstrable end to end.

Section 15

Queues, workers and schedules

All heavy work happens in the worker. Five BullMQ queues, five repeatable schedules, stable job ids so repeated triggers collapse instead of duplicating, and retries with exponential backoff.

Queue 01

Sync

Fetches each entity from BigCommerce in pages, upserts records, writes a checkpoint after every page, and records per-entity counts and errors on the sync run.

Queue 02

Insights

Computes the metric window, runs the seven detectors, builds and dedupes recommendations, then persists insights and recommendations with severity and impact.

Queue 03

Alerts

Evaluates every enabled rule against current metrics, creates alerts when a threshold is crossed, suppresses duplicates in the same window and raises notifications.

Queue 04

Reports

Materialises a parameterised report to CSV in tenant-partitioned storage, records the file path and generation time, and hands delivery to the scheduler.

Queue 05

Scheduler

Holds the repeatable job definitions and dispatches work — it is the clock, not the workload.

Reliability behaviour

Failed jobs retain their error for inspection, retry with backoff, and never partially corrupt state: sync checkpoints, report files and insight writes are all idempotent.

The five scheduled jobs

ScheduleTriggersPurpose
Sync dispatchRecurringPicks up pending or failed sync runs and enqueues them, so a manual trigger or a webhook never depends on a user request finishing
Nightly full syncDailyFull reconciliation of all seven entities for every connected tenant — the safety net under incremental updates
Daily insightsDailyRegenerates the insight and recommendation set for each tenant
Alert sweepRecurringRe-evaluates rules so a metric that drifts out of band is noticed even without user activity
Report deliveryRecurringRuns due report schedules and delivers generated files to the configured recipients

Why this matters commercially

Because the worker owns the schedule, the platform's value does not depend on someone remembering to open a dashboard. A stockout risk is detected at 02:00 and a report is waiting before the morning stand-up — which is the difference between an analytics tool and an operations system.

Section 16

Reports, exports and retention

Generated CSV exports with a documented data dictionary, plus scheduled delivery — so finance and planning get the same numbers the dashboards show, without a screenshot or a manual rebuild.

Report types

TypeContentsUsed by
SalesOrders with status, channel, totals, items, customer and timestamps for a date rangeFinance, commercial review
InventoryVariant-level stock, cost, price, reorder point and locationOperations, buying
CustomersSegments, lifetime value, order count, recency and contact detailsMarketing, retention
Full datasetProducts and variants with performance attributesMerchandising, analysis

Lifecycle

  1. RequestType, date range and optional filters are validated, then a report record is created with status pending.
  2. GenerateThe worker materialises the CSV to storage/reports/<tenant>/<report>.csv — tenant-partitioned from the first line.
  3. DownloadGET /api/reports/:id/download streams the file after a permission and ownership check.
  4. ScheduleA schedule repeats the request on a cadence and delivers the file automatically.
  5. RetainGeneration history is preserved, so a number quoted last quarter can be traced to the report that produced it.

Export conventions

  • Columns are explicit and documented, not positional — a column reorder cannot silently corrupt a downstream import.
  • Currency and date formats are normalised on export, so a spreadsheet in another locale reads correctly.
  • Empty and null values are written explicitly rather than left ambiguous.
  • Filenames carry tenant, report type and generation timestamp for auditability.
  • Large datasets stream rather than buffer, so memory stays flat as the store grows.

The commercial point

Exports are where analytics platforms usually lose trust: a number in a deck that nobody can reproduce. Here the export is generated by the same service that renders the dashboard, from the same tenant-scoped queries, and it is retained. When finance asks where a figure came from, there is an answer with a timestamp.

Data dictionary (extract)

order_date        Date      Local store date of the order
status            Enum      Order status at export time
channel           Enum      web | pos | phone | marketplace | …
gross_revenue     Decimal   Order total before discounts
net_revenue       Decimal   After discounts and shipping
aov               Decimal   net_revenue ÷ orders
units             Integer   Sum of item quantities
discount_rate     Decimal   1 − (net ÷ gross)
customer_segment  Enum      vip | high_value | at_risk | inactive
stock_on_hand     Integer   Current level by variant and location
days_of_cover     Decimal   stock_on_hand ÷ average_daily_units
Section 17

Design system and standards

Brand tokens, module accent colours, hand-rolled SVG charts and one spacing and motion scale — applied identically across the marketing site, the authenticated application, the exports and this document.

Core palette

Commerce Navy#071A3D
Commerce Blue#1E5EFF
MTS Orange#F97316
Orange Dark#EA580C
AI Indigo#6366F1
AI Cyan#22D3EE
AI Purple#8B5CF6
Success#16A34A
Warning#F59E0B
Error#DC2626
CTA Gradientorange → dark
Signaturecyan → indigo → orange

Module accent colours

Each module owns one accent, used in its navigation item, page header, cards, chart series and badges — so a user learns the colour language once.

Sales#F97316
Customers#8B5CF6
Products#06B6D4
Inventory#16A34A
Marketing#EC4899
Reports#2563EB
Alerts#F59E0B
Insightsblue → indigo

Type, spacing and shape

  • Inter-led system sans stack for UI and marketing; a monospace stack for identifiers, SKUs, endpoints, tokens and code.
  • One spacing scale, one radius scale, one elevation scale — defined as tokens, never ad-hoc values.
  • Navy headings on light surfaces, white headings on navy and gradient surfaces; body copy in a muted ink for comfortable long reading.
  • Tables use uppercase micro-headers on a navy band; dense data is a first-class layout, not an afterthought.
  • Empty, loading, error and stale states are designed for every data view, not improvised later.

Charts without a chart library

The visualisation layer is hand-built SVG — area and bar charts, donut segments, sparklines and stat tiles. No charting dependency means no bundle bloat, full control of the brand gradient, and charts that render identically in the app, on the marketing site and in a printed report.

Motion

  • Motion is purposeful: it explains hierarchy, direction and change — never it decorates.
  • Reveals, card lifts, gradient sweeps and count-ups run on a shared easing curve so the interface feels like one system.
  • Staggered delays give a group a reading order instead of a single noisy entrance.
  • Looping background animation is low-contrast and slow; it never competes with content.
  • prefers-reduced-motion is honoured everywhere — animation is a preference, not a requirement.

Accessibility as a build gate

Focus-visible outlines, keyboard-reachable controls, aria labelling on icon-only buttons, semantic tables with header scopes, sufficient contrast on every text/background pair, and responsive layouts tested at mobile width. Accessibility is checked, not asserted.

The same contribution rules every time

The reason a codebase stays maintainable is that every change obeys the same rules. These are the rules we apply to this platform and to every project we hand over — they do not change per project, per team or per deadline.

Design rules
  • Reuse an existing token, component or pattern before creating a new one. Duplication is a defect with a delayed invoice.
  • One accent colour per module, applied consistently across navigation, headers, cards, charts and badges.
  • Never hard-code a colour, radius, spacing value or font size in a component — read it from a token.
  • Every screen ships all four states: loading, empty, error and populated.
  • Responsive and reduced-motion behaviour is part of the component, not a follow-up ticket.
  • Charts use the same series colours and the same number formatting as the rest of the product.
Code contribution rules
  • TypeScript strict mode; no implicit any, no untyped API boundaries.
  • Feature branches, small reviewable diffs, and a passing lint and typecheck before review.
  • Controllers stay thin; business rules live in services or shared packages where they can be reused and tested.
  • No business logic in the web client that also exists in the API — the API is the single source of truth.
  • Every schema change ships with a reviewed migration and an idempotent seed update.
  • Comments explain why; the code already says what.
Security contribution rules
  • Never commit a secret; everything sensitive is environment-driven and validated at boot by a Zod schema.
  • All tenant-scoped queries go through the tenant-aware client; explicit tenant assertions on sensitive reads.
  • New endpoints declare their permission key explicitly, or are explicitly marked public with a reason.
  • Input validated at the boundary; output encoded; no string-built SQL anywhere.
  • Administrative actions write an audit entry with actor, action, entity and IP.
Testing contribution rules
  • A new user-facing path ships with an end-to-end assertion; a new metric ships with a case that pins the number.
  • Tests assert behaviour and contracts, not implementation detail, so refactoring does not break the suite.
  • Seeded demo data is deterministic, so a failure is a real regression rather than a data artefact.
  • CI is the definition of done: build, lint, typecheck, migrate, seed, test.
  • No test is skipped to make a pipeline green; a flake is a bug with a deadline.
Delivery and documentation rules
  • Behaviour changes arrive with documentation in the same change — API, configuration and runbook.
  • Environment changes update .env.example in the same commit.
  • Nothing is "known broken" without a tracked item; nothing is improvised without a decision record.
  • Handover is a phase of every project, planned from day one, not a scramble at the end.
  • The customer can run the system without us — that is the acceptance test for the whole codebase.
AI contribution rules
  • Numbers come from the metrics service, never from a model. The model may explain, never invent.
  • Every insight carries evidence and severity; an insight that cannot be evidenced is not shipped.
  • AI features have a deterministic fallback so the product never depends on a third-party response.
  • Privacy mode is enforced in code: strict mode does not send tenant context to a provider.
  • Provider usage, tokens and requests are logged per tenant for cost and audit.
Section 18

Security model

Multi-tenancy enforced at the data layer, sessions by hashed opaque tokens, secrets encrypted at rest, every administrative action audited, and AI context governed by an explicit privacy mode.

Authentication

Email and password with bcrypt hashing plus an optional pepper. The browser holds an opaque session token in an HttpOnly, SameSite=Lax cookie, Secure in production. Only a SHA-256 hash of the token is stored.

Authorisation

A global session guard plus a permission guard driven by seeded permission keys and @RequirePermission declarations. Controllers never trust a client-supplied tenant or user id.

Tenant isolation

Thirty of thirty-two models are tenant-scoped. The Prisma client extension injects tenantId on scoped operations, so a missing filter is a code-review concern rather than a data-leak path.

Secrets at rest

BigCommerce access tokens are encrypted with AES-256-GCM and only decrypted inside the integration path. JWTs, webhook secrets and API keys come from the environment and are validated at boot.

Webhooks

BigCommerce webhooks are accepted on a raw-body route, signature-verified before parsing, and de-duplicated by event hash so a replayed event cannot double-apply.

AI data governance

strict privacy mode blocks tenant context from leaving the infrastructure. balanced sends redacted summaries; connected is the only mode that permits full context, and it is opt-in.

Audit trail

Sign-ins, connection changes, sync triggers, role changes, alert-rule edits and settings changes are recorded with actor, action, entity, IP and timestamp.

Input and output

Validated at the boundary with DTOs and Zod schemas, parameterised queries through Prisma, encoded output, and standard status codes instead of leaking internals.

Least data exposure

Read-only store scopes, no store writes, no password storage, and a documented rule that merchant data is used to answer the merchant's questions — nothing else.

Transport, headers and CORS

  • TLS in production. The application is built to sit behind a TLS-terminating proxy or load balancer; the secure cookie flag is enabled with NODE_ENV=production.
  • CORS allowlist. The API accepts only the configured web origins; it is not an open wildcard.
  • Raw body preserved. Registered before JSON parsing so webhook signature verification is genuine rather than reconstructed.
  • Session expiry. SESSION_TTL_SECONDS defaults to 24 hours; expired sessions fail closed.
  • Rate-limit awareness. Outbound store requests are paced; inbound sensitive endpoints are the natural place for a future limiter.
  • No client-side secrets. The browser never receives a store hash, token or provider key.
  • Environment validation. A Zod schema fails the boot on an invalid or missing value rather than defaulting silently to an insecure one.
  • Dependency hygiene. Pinned versions, a lockfile, and an explicit allowlist of runtime dependencies in each package.

Stated honestly

We implement the controls above and verify them in code review and tests. We do not claim certifications the company does not hold. If a customer requires SOC 2, ISO 27001 or a penetration test as a contractual precondition, that is scoped and scheduled explicitly with a qualified third party — not implied by this document.

Section 19

DevOps and delivery

Infrastructure as configuration, a two-stage CI pipeline, one command per task, and the same environment variables in local development, CI and production.

Local infrastructure

Two services and an optional tool, defined in infrastructure/docker-compose.yml and started with one command:

npm run infra:up     # postgres:16-alpine + redis:7-alpine
npm run infra:down
ServiceImageDetail
PostgreSQLpostgres:16-alpinePort 5432, database mts_intelligence, named volume, pg_isready healthcheck
Redisredis:7-alpinePort 6379, appendonly yes, named volume, redis-cli ping healthcheck
Admineradminer:4Port 8080, behind the tools profile, waits for a healthy database

Commands

CommandPurpose
npm run devRun web, API and worker together through Turborepo
npm run dev:web · dev:api · dev:workerRun one application in isolation
npm run build · lint · typecheck · testDependency-ordered pipeline tasks across the monorepo
npm run db:generate · db:migrate · db:deploy · db:seed · db:studioPrisma client, migration, deployment, demo seed, browser data studio
npm run test:e2e · e2e:installPlaywright suite and Chromium provisioning
npm run formatPrettier across the repository

CI pipeline

Two jobs on every push and pull request to main, with concurrency cancellation so superseded runs do not consume capacity.

  1. verifyNode 20 with npm caching, npm ci, then the dependency-ordered build, lint and typecheck across all workspaces.
  2. e2eRuns only after verify passes. Starts PostgreSQL 16 and Redis 7 as managed services with health checks, exports the environment with AI_PROVIDER=rule, AI_PRIVACY_MODE=strict and MTS_DEMO=1.
  3. Database lifecyclePrisma client generation, migrations deployed, demo data seeded — so the test run exercises a real schema and realistic data, not mocks.
  4. Browser testsChromium installed with dependencies, then npm run test:e2e with the GitHub reporter, HTML report, trace and failure screenshots retained.

Why the order matters

Nothing reaches the browser test stage on a green lie: a type error, a lint violation, a failed migration or a missing seed fails the pipeline first. For a client, this is the difference between a predictable release and a release that consumes support time.

Deployment shape

  • Three deployables — web (Next.js), api (NestJS), worker (BullMQ) — scaled independently.
  • Stateless application tier: the only durable state is PostgreSQL, Redis and the report volume.
  • Container-ready: each app has a production start script and no build-time coupling to the others.
  • Environment-driven throughout, so promotion from staging to production is a configuration change, not a rebuild.
  • LOG_LEVEL and an optional SENTRY_DSN are already wired for production observability.
Section 20

Testing and quality

Four quality layers: types, lint, unit and integration tests, and ten browser end-to-end tests against a seeded database. The suite is part of the definition of done.

Gate 01

Typecheck

tsc --noEmit in strict mode across web, API, worker and every shared package, so an untyped boundary fails the pipeline.

Gate 02

Lint

ESLint 9 flat config with typescript-eslint and the react-hooks plugin, plus a shared base config every package extends.

Gate 03

Unit and integration

Test and test:unit / test:int tasks run per package, so pure rules and helpers are verified without a database.

Gate 04

End to end

Playwright against the real application with a real schema and the deterministic demo seed, serialised on one worker for stability.

The ten browser tests

SpecTestWhat it protects
auth.spec.tsUnauthenticated visitors are redirected to loginRoute protection on the application surface
Demo credentials sign in and load the dashboardThe single most important commercial path in the product
Invalid credentials surface an errorFailure handling is designed, not accidental
app.spec.tsDashboard shows core metricsSeeded figures render, so the metrics service is genuinely wired
Orders list paginates seeded dataPagination over a real dataset, not a mock array
Insights page lists insights and answers copilot questionsThe insight engine and copilot round trip end to end
Settings tabs load account dataAdministration surfaces, role gating and tab navigation
Period switcher updates the URLShareable, bookmarkable analysis state
marketing.spec.tsLanding page renders the hero and links to pricingFirst impression and the primary call to action
Feature and how-it-works pages renderThe pages a prospect visits before the demo

Test configuration

  • 60-second per-test timeout, 15-second assertion timeout.
  • Serial execution with one worker — no flakes from shared-database contention.
  • Existing dev servers reused locally; CI starts its own API and web, with a 120s and 180s readiness allowance.
  • Trace retained on failure and screenshots on failure, uploaded as artefacts.
  • One retry in CI, none locally, so a flake is visible in the pipeline rather than hidden.
  • E2E_SKIP_SERVERS=1 runs the suite against already-running services.

The honest test philosophy

A suite that only asserts rendering proves very little. These tests deliberately touch the risky parts — authentication, real seeded data through real queries, the copilot round trip and settings authorisation — because those are the paths a client actually depends on.

Known gap, stated honestly

Coverage is currently strongest on the browser journey layer. A dedicated unit and integration suite for the rule engine and metrics package is a defined roadmap item; the detectors are exercised through the insights path in the meantime.

Section 21

Configuration reference

43 environment variables, documented in .env.example, validated by a Zod schema at boot, and shared by web, API and worker. The same file works locally, in CI and in production.

VariableDefaultPurpose
NODE_ENVdevelopmentEnvironment mode; enables secure cookies and production behaviour when production
WEB_URLhttp://localhost:3000Canonical web origin; used for CORS allowlisting and link generation
API_URLhttp://localhost:3001API base URL used by the web data layer
WORKER_PORT3002Worker health port for orchestration probes
DATABASE_URLlocal PostgresPrisma connection string for PostgreSQL 16
REDIS_URLredis://localhost:6379BullMQ broker and cache connection
JWT_SECRET—HS256 signing secret; minimum 32 characters, validated at boot
SESSION_TTL_SECONDS86400Session lifetime; 24 hours by default
SESSION_COOKIE_NAMEmts_sessionSession cookie name
SESSION_COOKIE_DOMAINemptyOptional cookie domain for shared parent domains
ENCRYPTION_KEY—AES-256-GCM key for encrypting stored integration secrets
PASSWORD_PEPPER—Optional additional secret mixed into password hashing
REPORTS_DIRstorage/reportsTenant-partitioned report output location
LOG_LEVELinfoApplication log verbosity
MTS_DEMO1Enables the seeded demo workspace and demo sign-in

How configuration is enforced

Every variable is declared once in a shared Zod schema with a type, a default where sensible, and a documented purpose. Web, API and worker import the same schema, so a missing or malformed value fails at boot with a clear message instead of surfacing as a runtime bug hours later. Adding a variable is a single change plus a documentation update.

Section 22

The demo workspace

A deterministic, seeded tenant — NovaCart Commerce — with a year of realistic trading history, deliberate seasonality, genuine low-stock situations and underperforming campaigns. Not mock-ups: computed records.

Sign in

Workspace
NovaCart Commerce
URL
https://novacart.demo.mts
Email
admin@magetech.demo
Password
MTS-demo-2026!
Role
Owner
Plan
Growth

What is in it

EntityVolumeShape
Products & variants1,284Curated catalogue plus generated depth, across categories and brands with status and pricing variety
Customers12,450Order counts, lifetime value, recency and groups producing four distinct segments
Orders8,420A year of history with weekly seasonality, growth trend and status variety
Order items21,160Multi-item baskets, so AOV and product mix are meaningful
Revenue$284.5KDerived from order totals, never entered directly
InventoryPer variantLevels engineered to produce critical, warning and healthy coverage states
CampaignsMultipleSpend, clicks, impressions and attributed revenue including deliberately weak performers
InsightsGeneratedProduced on demand by the rule engine from the data above

Why the data is designed

  • Seasonality, not a straight line. Weekly and monthly variation means trend comparisons are meaningful and the "versus previous period" logic is visible.
  • Deliberate problems. Some variants are close to stockout, some campaigns underperform, some customer cohorts have gone quiet — so the insight engine has genuine findings to report.
  • Volume with a point. 8,420 orders with 21,160 line items is enough to make pagination, filtering and export real work rather than decoration.
  • Deterministic. The seed is idempotent and reproducible, so a demo, a screenshot and a test all show the same numbers.
  • Safe by default. AI_PROVIDER=rule and AI_PRIVACY_MODE=strict: the full intelligence layer runs with no external call and no data leaving the machine.

Run it yourself

  1. Start infrastructurenpm run infra:up brings up PostgreSQL 16 and Redis 7.
  2. Prepare the databasenpm run db:generate, then npm run db:deploy to apply migrations.
  3. Seed the workspacenpm run db:seed creates the tenant, roles, permissions, users and a year of commerce data.
  4. Start the applicationsnpm run dev runs web, API and worker together.
  5. Sign inOpen http://localhost:3000 and use the credentials above.

Time to a working demo

On a machine with Node 20, the sequence above produces a fully populated, fully interactive system. That is the same claim we make in a client proposal — and it is the reason we can offer a working version rather than a promise of one.

Section 23

How we present it

A thirty-minute run of show that starts with the merchant's problem and ends with a system they can log into themselves. We do not open with architecture.

The thirty minutes

  • 0–3 minTheir situation, in their words"What do you currently not know about your store that you wish you did?" We write the answers on the screen and use them as the agenda.
  • 3–7 minSign in as two rolesOwner and operations manager. The identical screen, different data and different actions. Access control is proven, not claimed.
  • 7–12 minDashboard in sixty secondsRevenue, orders, AOV, customers, low-stock and open alerts — with the previous-period comparison that makes a number meaningful.
  • 12–18 minDrill to the answerFrom the dashboard into Sales, then Customers, then the specific cohort or product that explains the movement.
  • 18–23 minThe insight, and its evidenceOpen one real insight: severity, the evidence behind it, the recommended action — and ask them to judge whether it is useful.
  • 23–26 minAsk the copilotThey phrase the question. It returns grounded numbers. The credibility of the whole platform usually settles in this moment.
  • 26–28 minThe alert that arrives at 02:00Show a rule, show the alert, show the notification. This is when "tool" becomes "system".
  • 28–30 minThe handover question"What would you want to see on day one of your own instance?" Then we show the deliverables, not a brochure.

How we run it

  • Their data if they have it. A read-only sandbox store turns the demo into their own business; the seeded workspace is the fallback.
  • No slides after minute three. The system is the presentation material.
  • One question at a time. We pause at the insight screen and let them interrogate it.
  • Silence is useful. If a screen is confusing we stop and fix the explanation, not the screen.
  • Recorded follow-up. The questions we could not answer become the roadmap conversation, in writing.
How long does the first sync take, and what happens to our history?

Categories, brands, products, customers, orders, inventory and settings sync on a paged, resumable basis with per-entity checkpoints, so an interrupted run continues rather than restarting. For a first load we agree a backfill window with you; historical depth is a plan decision, and we can start with a fixed period and extend it.

What if BigCommerce changes its API?

All platform access is isolated in one client package with a rate-limit-aware, retrying client and response schemas. An upstream change is a change in one package, not a rewrite of the platform.

Do we need to change anything in our store?

No. Read-only scopes only. The app is installed or an API account is created, and the platform never writes back to the store.

Section 24

Deliverables on handover

Everything below exists already and is handed over as standard. Nothing on this list is a future promise, and nothing is withheld as a commercial lever.

Complete source code

  • Full monorepo: web, API, worker and all six shared packages
  • All 32 Prisma models and reviewed migrations
  • Ten Playwright end-to-end tests in the repository
  • No proprietary runtime, no licence server, no crippled build

Infrastructure definition

  • PostgreSQL 16 and Redis 7 compose stack with health checks
  • Container-ready deployables for web, API and worker
  • Environment template with all 43 documented variables
  • Backup and retention guidance for the data volumes

CI/CD pipeline

  • Two-stage GitHub Actions workflow: verify, then end-to-end
  • Build, lint, typecheck, migrate, seed, test on every push
  • Failure traces and screenshots retained as artefacts
  • Traces retained on failure for immediate diagnosis

Data and integration layer

  • Resumable BigCommerce sync for seven entities
  • OAuth and API-account connection paths
  • Signed, idempotent webhook handling
  • Demo seed that reproduces a year of trading data

Intelligence layer

  • Seven insight detectors with evidence and severity
  • Recommendation builder with priorities
  • Copilot tool calls over computed metrics
  • Provider adapters with local rule-engine fallback

Documentation

  • Architecture, API and development guides in the repository
  • Data dictionary for every exported column
  • Runbook for operations, sync and recovery
  • This document, updated as the product changes

Brand and design assets

  • Logo, favicon, app icon and wordmark variants
  • Colour tokens including per-module accents
  • Typography, spacing and motion standards
  • Reusable UI and chart component patterns

Access model and audit

  • Seven roles and 25 permission keys, seeded and extensible
  • Tenant-scoped data access at the client layer
  • Audit log with actor, action, entity and IP
  • Role matrix documentation

Training and handover sessions

  • Administrator session: team, roles, integration, schedules
  • Operator sessions per persona: insights, alerts, reports
  • Developer session: architecture, conventions, extension points
  • Recorded walkthroughs for future team members

Support and roadmap

  • Agreed support window with defined response targets
  • Prioritised roadmap, with your priorities weighted first
  • Known gaps listed explicitly rather than discovered later
  • Optional ongoing development and managed service

Source

Yours outright, with the full history. We are not licensing the right to use our own product in your business.

Documentation

Written for the engineer who joins in year two, not for the person who wrote it.

Independence

The handover test is whether your team can deploy a change without calling us. That is the goal, stated at the start.

Section 25

Develop, maintain, build from scratch

Three ways clients engage us. The same engineering standards apply to all three, and the same handover expectation: your team can run what we build.

Extending a live platform

New modules, new metrics, new detectors, new report types, new integrations — added without destabilising what runs. This is the normal shape of a long relationship: the platform is a foundation, not a finished brief.

  • New product modules following the existing model, route and permission pattern
  • New insight detectors and recommendation categories in the shared rule engine
  • New report types with schedule support and retention
  • New external integrations through the same rate-limited, checkpointed client pattern
  • Performance work on real query paths with measurement before and after

What makes extension cheap

  • Six shared packages already hold the reusable logic, so features compose instead of duplicate.
  • Permission keys are data, so a new capability ships with its access control rather than a follow-up.
  • The sync engine, job infrastructure and report pipeline are generic, not module-specific.
  • The design system and chart library are already established, so a new screen looks native on day one.
  • The test harness, CI pipeline and seed data are reusable infrastructure for every new feature.

The compounding effect

Because the first feature built the pattern, the tenth costs a fraction of the first. That is the difference between a codebase you extend and a codebase you fight — and it is why the second year of a relationship is faster than the first.

Section 26

Service catalogue

What MageTech Solutions sells, in plain terms. Every service is delivered by the same engineering team that built this platform, under the same standards shown in Section 17.

▣
01

Custom application development

End-to-end product engineering: discovery, architecture, build, hardening, handover. Web applications, internal tools, portals, dashboards and operational systems — delivered as working software with source code.

◈
02

BigCommerce development and integration

Storefront and app development, OAuth and API-account integrations, data synchronisation, webhooks, catalogue and checkout work, and migration from spreadsheets or legacy systems onto a proper data foundation.

✦
03

AI engineering and automation

Insight engines, recommendation systems, copilots grounded in real data, classification and forecasting, alert automation and workflow replacement — with privacy modes and cost control designed in.

▤
04

Data engineering and analytics

Warehousing and normalisation, metric layers, dashboards, scheduled reporting, data dictionaries, retention and the export discipline that keeps finance and engineering arguing with the same numbers.

⟳
05

DevOps, CI/CD and cloud delivery

Pipeline design, infrastructure as configuration, containerisation, environment strategy, observability, backup and recovery practice, and release processes a team can trust on a Friday afternoon.

◉
06

Security and hardening

Authentication and authorisation design, tenant isolation, secret management, webhook verification, input validation, dependency hygiene, audit trails and security-focused review before handover.

◈
07

Design systems and front-end engineering

Brand-aligned design systems, token architecture, component libraries, accessible interfaces, data visualisation and motion that carries meaning rather than decoration.

⚑
08

Maintenance, monitoring and support

Managed support with defined response targets, dependency and security maintenance, incident response, performance work, monitoring and a documented recovery path.

▣
09

White-label and multi-tenant platforms

Platforms delivered under a client's brand and offered to that client's customers: configurable modules, entitlements, tenant isolation, plan catalogues and a reusable foundation.

◔
10

Technical consulting and audits

Architecture review, code and performance audit, delivery assessment, technology selection and pragmatic advice with a written outcome — including the option to do nothing when nothing is wrong.

▤
11

Documentation and knowledge transfer

Architecture, API and development documentation, data dictionaries, runbooks, recorded training and hands-on sessions so the owning team is never dependent on the author.

✚
12

Team extension

Senior engineers embedded with your team, working in your repository, your tooling and your ceremonies — with our standards and our handover discipline, at your direction.

How we scope work

Every service above is delivered under the same commercial discipline: an agreed outcome, an agreed definition of done, a visible plan, a fixed review cadence, and a handover that leaves the client independent. If a service does not apply to your situation, we say so rather than sell it.

Section 27

Technology expertise

Depth where it matters, judgement about what not to use. This platform is the evidence: every technology below is exercised in production code, not listed on a slide.

TypeScript and Node.js

Strict-mode services and applications, npm workspaces, Turborepo task graphs, shared types across every tier. One language from database extension to user interface.

React, Next.js and modern front-end

App Router, server components, streaming, route groups, caching and typed data layers. Accessible, responsive interfaces built on tokens rather than ad-hoc values.

Node APIs and service architecture

NestJS module design, guards and decorators, DTO validation, CORS and raw-body handling, versioning strategy, error contracts and clean service boundaries.

PostgreSQL and Prisma

Relational modelling, composite indexes, migration discipline, seeded reproducible environments, client extensions for tenancy, and queries designed for realistic volume.

Redis, queues and background processing

BullMQ queues, repeatable schedulers, stable job ids, retry and backoff, idempotent processors, and the discipline of keeping heavy work off user requests.

Commerce and BigCommerce

OAuth 2.0 install flows, staff API accounts, V2 and V3 REST, signed JWT auth payloads, paged resumable sync, webhooks, catalogue, checkout and store operations.

Applied AI

Deterministic rule engines, evidence-backed insight generation, tool-calling copilots over real metrics, provider abstraction, prompt and budget control, privacy modes and local fallback.

DevOps, CI/CD and quality engineering

GitHub Actions pipelines, infrastructure as configuration, containerisation, health checks, artefact retention, Playwright browser testing and dependency hygiene.

Data modelling and warehousing

Entity design that survives real business change, pre-aggregation for speed, historical correctness, and snapshots where a trend is the requirement.

Security engineering

Session design, hashed tokens, encryption at rest, permission models, tenant isolation, signature verification and audit trails — implemented, documented and reviewed.

Design systems and accessibility

Token architecture, component libraries, SVG data visualisation, motion standards, keyboard and screen-reader support, and reduced-motion compliance.

Performance engineering

Query-level optimisation, caching strategy, worker offloading, streaming exports, and measurement before and after so improvements are claims with evidence.

Technical writing and documentation

Architecture decisions, API references, data dictionaries, runbooks and training material that let a new engineer become productive without the original author.

Product and delivery judgement

Scoping honestly, sequencing work so a working version exists early, and telling a client when the right answer is a smaller product.

What we deliberately do not claim

No certification badges, no partner logos we do not hold, no client list we cannot evidence, and no benchmark numbers we have not measured. A capability claim in this document is always traceable to code in this repository.

Section 28

Pricing and engagement models

MageTech Solutions is not only a product. We are a BigCommerce development, customisation, integration, AI and managed-services partner — so a single bug fix, one new module and a multi-year platform programme are all straightforward to buy. Seven ways to work with us, and every figure below is a starting point, because the right price depends on scope, existing systems and integration complexity.

01

Hourly development

$25/ hour

A specific requirement, bug fix, enhancement or small integration where the scope is not yet fixed.

02

Dedicated resource

$1,500/ month

One continuous senior resource on your team, part-time or full-time, for ongoing development and support.

03

Module development

$1,000from

Build or enhance one defined module or integration. The natural way to adopt this platform piece by piece.

04

Fixed-price project

$5,000from

A clearly defined deliverable with agreed scope, acceptance criteria and a fixed price.

05

Maintenance & support

$299/ month

Keep an existing application reliable with monitoring, fixes, small enhancements and technical reviews.

06

Dedicated team

$6,000/ month

A complete MageTech engineering team — developer, backend, frontend, QA and lead — as an extension of your organisation.

07

Enterprise & custom engagement

Tell us what you need — we will design the right engagement

Enterprise implementations, AI commerce programmes, complex or multi-store integrations, ERP and CRM connectivity, data migration, custom BigCommerce applications and long-term product engineering. Scoped individually, with a written proposal before any work begins.

How to read these numbers

Every amount is a starting-from figure, not a fixed price. Final effort depends on your existing systems, the number of integrations, data volume, customisation and how much of the work is already reusable. We confirm effort, timeline, team and price in a written proposal before starting, and we do not invoice against an open-ended assumption.

01 — Hourly and task-based development

For customers with a specific requirement, bug fix, enhancement or small integration. Work is tracked, prioritised with you, and reported against the agreed estimate.

ServiceRecommended rateTypical work
BigCommerce development$25–$40 / hourStorefront and app changes, catalogue, checkout, theme work
AI / commerce intelligence development$35–$60 / hourInsight detectors, copilots, recommendation and forecast logic
Integration / API development$30–$50 / hourBigCommerce, ERP, CRM, webhook and third-party connectivity
UI / frontend development$25–$40 / hourDesign systems, components, data visualisation, accessibility
QA / testing$20–$30 / hourFunctional, regression and browser end-to-end testing
Technical consultation$40–$75 / hourArchitecture review, audits, technology selection, advice

India-focused engagements: an equivalent starting range of ₹1,500–₹4,500 / hour, depending on skill level and complexity.

How to choose — the hybrid model

We do not price only by hours, because that positions us as a staffing supplier rather than a technology partner. The right model follows the shape of the requirement.

Small task

Hourly

A fix, an enhancement, a question, something undefined. Model 01 from $25/hour.

Known feature

Module or fixed price

A defined module, integration or report with a known outcome. Models 03 and 04 from $1,000 and $5,000.

Large implementation

Project price

A full implementation with scope, milestones and acceptance criteria. Model 04 from $5,000, typically $10,000–$30,000+.

Continuous development

Dedicated resource or team

An ongoing roadmap needing steady capacity. Model 02 from $1,500/month or model 06 from $6,000/month.

Existing application

Monthly maintenance

Something already works and must keep working. Model 05 from $299/month.

Enterprise

Custom engagement

Multi-store, ERP and CRM, migration, AI programmes, long-term product engineering. Model 07, scoped individually.

The commercial principle

We recommend the model that fits the requirement, not the one that maximises revenue. A client who starts with a $1,500 module and a good experience comes back for the platform; a client over-committed to a large fixed scope does not.

How we work

  • Step 01RequirementYou share the requirement, the constraint and the outcome you need. A conversation, a document, a call recording — whatever is easiest.

Ask for a customised proposal

Enterprise implementations, AI commerce projects, complex or multi-store integrations, ERP and CRM connectivity, custom BigCommerce applications, data migration and long-term product engineering all start with the same sentence: tell us what you need, and we will design the right engagement model.

Go to next steps · www.magetechsol.com

We publish our prices because we would rather compete on the work than on the opacity of the quote.
MageTech Solutions · commercial principle
Section 29

Engagement and support

Four engagement shapes, one way of working: a defined outcome, a visible plan, a fixed review cadence, and a handover that leaves the client independent.

Fixed-scope project

Agreed deliverables, agreed timeline, agreed price. Best when the requirement is genuinely known. Milestone-based with acceptance criteria per phase.

Time-and-materials

Capacity committed, work prioritised jointly, transparent tracking. Best when the requirement is emerging and speed of iteration matters more than certainty.

Retained team

A continuing team on a rolling basis with a roadmap you influence: extension, new modules, and steady maintenance under one relationship.

Managed service or advisory

We operate and monitor the platform, or we advise and review. Support tiers with defined response targets, escalation paths and an agreed exit.

How the first four weeks run

  • Week 0Discovery and accessGoals, constraints, stakeholders, data sources, environments and access. A written outcome definition we both agree on before any code.
  • Week 1Architecture and first sliceData model and boundaries decided; a thin end-to-end path running against real data and demonstrable.

Communication and governance

  • One written source of truth for scope, decisions and open questions, so requirements are not remembered differently by different people.
  • Weekly working session and demonstration — progress shown, not described.
  • Decision log including the reasoning, so a later team understands why, not just what.
  • Escalation path agreed before it is needed, with named contacts and response targets.
  • Change control for scope changes, with the trade-off stated in writing rather than absorbed silently.

Exit terms are part of the agreement

Source code, documentation, infrastructure definition, environment configuration and data export are returned at any point on request — including at the end of the relationship. That is not a concession; it is the design constraint that keeps our work honest.

Section 30

Outcomes, quality and roadmap

What we hold ourselves to, and what is still to come — stated with the same precision as what already works.

Outcomes we target

  • A working version early. A demonstrable end-to-end path in the first weeks, not a design document in a quarter.
  • Decisions without spreadsheet archaeology. The question that took an afternoon of exports answered from a screen in seconds.
  • Problems caught before they cost money. Stockout risk, churn risk and revenue anomalies surfaced while there is still time to act.
  • Reporting that reproduces. Every exported figure traceable to a generated report with a timestamp.
  • Hours returned. Manual weekly reporting replaced by generated, scheduled exports.
  • Ownership transferred. The client's team can deploy, extend and support the system without us.

Quality commitments

CommitmentHow it is enforced
No type or lint regressionsCI gates on every push and pull request
No unvalidated input at a boundaryDTO and Zod schemas, code review rule
No tenant data crossing a boundaryClient extension plus explicit service assertions
No AI-produced numbersFigures sourced from the metrics service only
No undocumented behaviour changeDocumentation updated in the same change
No handover surpriseKnown gaps listed explicitly, in writing

Roadmap

  • DeliveredFoundation and productMonorepo, 32-model schema, 64-endpoint API, 10 modules, 7 roles, BigCommerce sync with resume and webhooks, insight engine, copilot, alerts, reports, worker with 5 queues and 5 schedules, CI and 10 browser tests.
  • DeliveredBrand and experienceDesign tokens, module accents, SVG chart library, responsive layouts, marketing and application surfaces, accessibility pass.

Why we publish the gaps

A vendor who claims everything is finished has either not tested it or is hiding the cost of fixing it later. Both of these items are real, both are small compared to the platform, and both are stated here so nobody discovers them during a deadline.

Section 31

Next steps

Three ways forward, in ascending order of commitment. All three start with a conversation, and none of them require a decision today.

Option A

See it with your own questions

A thirty-minute session on the seeded workspace, or on a read-only sandbox of your own store. Bring the questions your team actually asks; we will answer them in the product.

Commitment: one hour.

Option B

Scoped first version

We agree an outcome, a first set of requirements and a two-to-three week delivery of a working slice against real data — with acceptance criteria agreed before we start.

Commitment: a scoped project.

Option C

Adopt the platform as it stands

Deploy this platform now, connect a store, and extend it from there. The fastest route to value when the existing modules already match the requirement.

Commitment: onboarding and configuration.

What we need from you to start

  • The decision-maker and the person who will use the system daily — ideally the same meeting.
  • Read-only access to a store, or agreement to use the seeded workspace.
  • The three questions your team cannot answer quickly today.
  • Any constraint we should design around: hosting, data residency, timeline, budget shape.

A short readiness checklist

  • Product runs todayAll ten modules, live on the seeded workspace.
  • Documentation existsArchitecture, API, development, configuration and this document.
  • Handover artefacts readySource, infrastructure, CI, seed, brand assets, training plan.

Talk to MageTech Solutions

We would rather answer a hard technical question now than win a project and disappoint you later. Bring the awkward one.

  • Website: www.magetechsol.com
  • Product: MTS BigCommerce AI Commerce Intelligence
  • Demo workspace: NovaCart Commerce — admin@magetech.demo
The first version of this platform existed because we wanted to prove a claim we were tired of making.
MageTech Solutions · product philosophy
Readiness — what exists versus what a store connection needs

Product, documentation, handover artefacts, CI and demo data — complete

Store credentials and a public OAuth callback — required only to go live on a real store

Section 32

Appendix

Reference material: terminology, the numbers quoted in this document, the repository map, and how each claim can be verified.

TermMeaning in this platform
TenantOne merchant workspace. The root of all data isolation; every scoped record belongs to exactly one.
WarehouseThe PostgreSQL schema that normalises BigCommerce data for analytics. Not a data lake; a queryable, purpose-built store.
CheckpointThe last successfully completed page of a sync, so an interrupted run resumes instead of restarting.
InsightA generated finding with type, severity, title, message and evidence, persisted for review and alerting.
DetectorA rule in the insight engine that evaluates a metric against a threshold and emits an insight.
RecommendationA concrete action derived from insights, deduplicated and prioritised high, medium or low.
CopilotThe natural-language interface that classifies an intent and calls the same metrics services as the dashboards.
Privacy modestrict, balanced or connected — how much tenant context may leave the infrastructure.
Days of coverStock on hand divided by average daily units sold; the basis for stockout and overstock risk.
AOVAverage order value — net revenue divided by order count for a period.
EntitlementA capability granted by a plan. Configuration and seed data, not hard-coded interface behaviour.
Stable job idA deterministic BullMQ job id so repeated triggers of the same work collapse rather than duplicate.