TCG Platform Project Plan¶
Medusa Commerce Core · Custom TCG Operations Platform · April 2026
This document outlines the plan to design, build, and deploy a TCG operations platform purpose-built for a TCG (Trading Card Game) business running simultaneous e-commerce channels such as Shopee and Lazada, plus physical/event sales and social commerce channels such as Telegram, Instagram, and Carousell.
The platform uses Medusa as the commerce core for generic commerce primitives such as orders, inventory, stock locations, fulfillment, returns, and workflow orchestration, with all custom logic — connector orchestration, TCG-specific data models, finance, merchant/admin UX, and operational tooling — built as TypeScript custom modules inside Medusa (src/modules/, src/api/, src/subscribers/, src/jobs/). This is a single TypeScript codebase, a single deployable, and a single PostgreSQL database. There is no separate application service.
The MVP is designed and built as a single-tenant operations platform for one TCG business. All SaaS, multi-tenancy, and control-plane concerns are intentionally deferred and consolidated in a separate section at the end of this document (see Deferred: SaaS & Multi-Tenancy).
The project will be executed by a small team of 3 developers with uneven workload — a lead developer (D1) carrying most of the work, a mid-load developer (D2), and a lighter-load contributor (D3) — with work organized into sequential implementation phases rather than fixed time-boxed sprints.
Table of Contents¶
- Executive Summary
- Project Objectives
- Scope
- System Architecture
- What Medusa Covers
- What Must Be Implemented or Customized
- Data Ownership and Database Strategy
- Module Specifications
- Replacement Mapping
- Token and Connector Strategy
- Infrastructure and Hosting
- Testing Strategy
- Team & Delivery Structure
- Implementation Roadmap
- Developer Work Split
- Risk Register
- Non-Functional Requirements
- Deferred: SaaS & Multi-Tenancy (Post-MVP)
- Future Roadmap
Executive Summary¶
The platform is intended to become the central operating system for a TCG business that currently manages inventory, imports, pricing, order processing, social-channel sales, and finance through a mixture of spreadsheets, scripts, and separate operational tools. The product goal remains the same: unify orders, inventory, costing, fulfillment, event sales, and financial visibility into one coherent system.
The main architectural change is that the platform is no longer described as a fully custom commerce backend. Instead, Medusa is used as the system of record for standard commerce domains, while custom Medusa modules are built only where the domain is business-specific, TCG-specific, or marketplace-specific.
This hybrid approach reduces engineering scope, improves maintainability, and keeps the team focused on actual product differentiation: reliable channel connectors, TCG item semantics, DCA and batch costing, event/POS flows, finance visibility, and merchant operations UX.
Project Objectives¶
| # | Objective |
|---|---|
| 1 | Unified order management across Shopee, Lazada, and all offline/social channels. |
| 2 | Real-time, centralized inventory with automatic deductions and reversals. |
| 3 | Central product repository with cross-platform listing sync. |
| 4 | Automated DCA pricing engine with batch cost tracking. |
| 5 | Multi-location stock management for warehouse, event, and physical store. |
| 6 | Built-in POS to replace Loyverse for card show and event sales. |
| 7 | Full financial tracking including stakeholder equity, payouts, and profits per channel. |
| 8 | Offline order tracker for Telegram, Instagram, Carousell, and physical store. |
Scope¶
In scope for v1.0¶
- Shopee integration: orders, products, stock, pricing, and sync workflows using a custom connector layer.
- Lazada integration: orders, products, stock, pricing, and sync workflows using a custom connector layer.
- PayNow QR payment generation and confirmation in the custom Medusa module layer.
- Telegram Bot admin notifications, order alerts, and quick commands.
- Telegram Mini App for customer-facing and partner-facing TCG ordering flows.
- Product and inventory management using Medusa plus custom TCG metadata and costing logic.
- Import batch management with automatic DCA and custom landed-cost attribution.
- Unified order management across marketplaces and offline/manual channels, with Medusa as commerce core and custom orchestration on top.
- Multi-location stock with warehouse, event, and store workflows.
- Built-in POS for events and physical store use.
- Finance dashboard including cashflow, stakeholder equity, and profitability reporting.
- Single-tenant merchant user and role management (staff accounts, basic RBAC).
Out of scope for v1.0¶
- TikTok Shop integration.
- Multi-branch or full multi-warehouse enterprise distribution beyond the initial use cases.
- Customer loyalty program.
- Automated restock purchasing.
- Native mobile app.
- Advanced distributed background workers at day one if simpler scheduling is sufficient for MVP.
- Multi-tenancy, tenant provisioning, subscriptions/billing, and SaaS control-plane features — see Deferred: SaaS & Multi-Tenancy.
System Architecture¶
High-level architecture¶
The system is composed of five major layers.
| Layer | Technology | Purpose |
|---|---|---|
| Commerce Core + Custom Modules | Medusa v2 (TypeScript) — src/modules/, src/api/, src/subscribers/, src/jobs/ |
Orders, inventory, locations, fulfillment, products, workflows, plus all custom TCG logic, connectors, DCA, finance, auth, and ops tooling. |
| Frontend | Next.js 16 | Merchant/admin dashboard, POS UI, Telegram Mini App frontend. |
| Data | PostgreSQL 16 | Single instance; Medusa manages all migrations including custom module tables. |
Architecture diagram¶
flowchart TB
subgraph Clients["Clients & Channels"]
Shopee[Shopee]
Lazada[Lazada]
TG[Telegram Bot / Mini App]
POS[POS Tablet / Event]
Admin[Merchant Admin UI]
end
subgraph Frontend["Frontend — Next.js 16"]
AdminUI[Admin Dashboard]
POSUI[POS UI]
MiniApp[Telegram Mini App]
end
subgraph Medusa["Medusa Application (TypeScript)"]
subgraph Commerce["Commerce Core — Medusa v2 modules"]
Orders[Orders / OMS]
Inventory[Inventory / Reservations]
Locations[Stock Locations]
Fulfillment[Fulfillment / Returns]
Products[Products / Variants]
Workflows[Workflows]
end
subgraph Custom["Custom Modules — src/"]
Auth[Merchant Auth & RBAC]
Connectors[Connector Orchestration]
TCG[TCG Domain Module]
DCA[DCA / Costing Module]
Finance[Finance Module]
Ops[Ops / Exceptions]
API[Custom API Routes]
Subs[Subscribers & Jobs]
end
end
subgraph Data["Data & Ops"]
DB[(PostgreSQL — single DB)]
Queue[Queue / Workers]
EventStore[Raw Event Store]
end
Shopee --> Connectors
Lazada --> Connectors
TG --> MiniApp
POS --> POSUI
Admin --> AdminUI
AdminUI --> API
POSUI --> API
MiniApp --> API
Custom <--> Commerce
Connectors --> EventStore
Connectors --> Queue
Queue --> Commerce
Medusa --> DB
Architectural principle¶
The architectural boundary is simple:
Decision: TypeScript-only. All custom logic — connector orchestration, TCG metadata, DCA, finance, POS/event flows — is built as Medusa TypeScript modules in
src/. No separate FastAPI service. Single deployable, single database, full access to workflow hooks and transactional rollback.
- Medusa owns generic commerce. Orders, inventory, stock locations, fulfillment, returns, and base product/variant logic should live there.
- Custom Medusa modules own business differentiation. TCG-specific semantics, marketplace integrations, DCA, finance, POS/event flows, and ops tooling are built as TypeScript modules in
src/.
| Boundary | Medusa core modules | Custom src/ modules |
|---|---|---|
| Primary concern | Generic commerce primitives | Business differentiation |
| Owns data | Orders, inventory, locations, products | Connectors, TCG metadata, DCA, finance |
| Changes when | Upgrading commerce behavior | New channels, TCG rules, costing, ops needs |
| Upgrade risk | Must avoid core patching | Free to evolve independently |
Runtime components¶
| Component | Role |
|---|---|
| Medusa application | Single TypeScript process: commerce core + all custom modules. |
| Custom Medusa modules | src/modules/connectors/, src/modules/tcg/, src/modules/dca/, src/modules/finance/ — TCG domain logic, connector orchestration, costing, finance. |
| Custom API routes | src/api/ — merchant/admin REST endpoints served by Medusa. |
| Subscribers & jobs | src/subscribers/ and src/jobs/ — event reactions, polling, reconciliation, batch processing. |
| Frontend app | Merchant/admin interface, POS, Mini App UX. |
| PostgreSQL | Single database — Medusa core tables + custom module tables + link tables. |
| Queue/worker layer | Retries, replay, reconciliation, periodic sync, batch jobs. |
| Nginx / reverse proxy | TLS and service routing. |
What Medusa Covers¶
This section defines the standard commerce domains that should be handled by Medusa rather than rebuilt from scratch.
Orders and OMS primitives¶
Medusa should be the system of record for core order state, including line items, order lifecycle, order modifications, fulfillment linkage, and post-order constructs such as returns, claims, and exchanges. The platform should not maintain a parallel first-class custom OMS for generic commerce unless there is a proven gap that Medusa cannot cover cleanly.
Medusa covers:
- Order records.
- Line items.
- Order lifecycle state.
- Returns, claims, exchanges, swaps.
- Fulfillment linkage and core post-purchase flow.
Inventory and reservations¶
Medusa should own standard stock state, including inventory items, available quantities, reservations, and stock adjustments through order and fulfillment flows. This removes the need to build a fully bespoke inventory engine as the primary source of truth.
Medusa covers:
- Inventory quantities.
- Reservations and release behavior.
- Inventory flow participation in commerce workflows.
- Inventory updates triggered by orders, fulfillments, and returns.
Stock locations¶
Medusa provides support for stock-location concepts and multi-location inventory handling. This should be the base model for warehouse, event, and store locations, even if the business adds custom transfer rules and event behavior above it.
Medusa covers:
- Stock location records.
- Stock-by-location concepts.
- Availability logic tied to locations.
Fulfillment and returns¶
Medusa includes fulfillment providers and commerce support for fulfillments, returns, and related post-order flows. This should be used for shipment state and return/refund primitives, while marketplace sync logic remains external.
Medusa covers:
- Fulfillment records.
- Shipment-linked commerce state.
- Returns and related post-order entities.
Product and variant primitives¶
Medusa should own the generic product catalog structure including products, variants, and base extension flows. TCG-specific metadata is attached via a custom Medusa module (src/modules/tcg/) and a Module Link to productVariant — it lives in the Medusa database and is queried through Medusa's standard query API, with no cross-DB SKU join required.
Medusa covers:
- Product entity base model.
- Variant structure.
- Product workflows that can be extended by hooks and custom logic.
- Variant
metadataJSON field (for simple key-value attributes). - Module Link extension point for structured relational TCG attributes.
Pricing tiers¶
Medusa's Pricing module natively supports customer-group-based and quantity-based pricing via PriceRule. This covers the Partner, Streamer, and Bulk tiers without custom storage.
Medusa covers:
- Per-variant prices with customer group rules (
customer.groups.id). - Bulk pricing via
min_quantity/max_quantityprice tiers. - Price lists for date-gated or group-gated overrides.
The custom pricing engine's responsibility is: compute a suggested price from DCA, then write it to Medusa's Pricing API. Medusa stores and serves the result.
Sales channels¶
Medusa's Sales Channel module provides native channel attribution on every order record.
Medusa covers:
- One Sales Channel per external channel: Shopee, Lazada, Telegram, POS, Manual.
sales_channel_idon every ingested order — no App DB duplication needed.- Per-channel product visibility and inventory availability controls.
Workflow framework and extension points¶
Medusa workflows are suitable for composing multi-step operations involving both Medusa commerce modules and custom platform modules. This means the team should rely on Medusa workflows and official extension points for most commerce-related customization.
Medusa covers:
- Workflow orchestration framework.
- Hooks into existing commerce flows (
createOrderWorkflow.hooks.orderCreated, etc.). - Custom modules and modular extension patterns (
src/modules/,src/subscribers/,src/jobs/).
What Must Be Implemented or Customized¶
This section defines the domains that are not covered by Medusa or should remain intentionally custom because they represent business-specific product value.
Merchant auth and user management¶
The MVP is single-tenant, so auth is scoped to one merchant organization and its staff. No tenant routing, no subscriptions, no cross-merchant admin.
The application must implement:
- Staff user accounts for the merchant (login, password reset).
- Role-based access control (admin, ops, finance, event-staff).
- Session management and audit of sensitive admin actions.
Connectors and marketplace orchestration¶
Medusa does not natively solve Shopee or Lazada integration in the way this platform requires. The platform must implement and own all connector behavior.
The application must implement:
- Connector credentials and token refresh.
- Webhook ingestion and polling jobs.
- Raw payload logging.
- Canonical mapping from channel payloads to internal order and SKU semantics.
- Outbound stock, price, and shipment sync.
- Retry, replay, backoff, and dead-letter handling.
TCG item semantics¶
Medusa is generic commerce software and does not natively understand TCG-specific item semantics. The team must define and build the TCG domain model on top of Medusa's product and inventory primitives.
Implementation approach: Create a TCGVariantMetadata data model in src/modules/tcg/ and link it to productVariant via defineLink(). This places TCG metadata in the Medusa database, queried via fields: ["*", "tcg_variant_metadata.*"]. No cross-DB SKU join is needed.
The application must implement:
- TCG title/game.
- Language, set number, product family, variation semantics.
- Condition, grading, foil/non-foil, collectible-specific attributes.
- Serialized inventory semantics for one-of-one or near-unique singles.
- Channel listing mappings per SKU or collectible item.
Batch costing and DCA¶
DCA and import costing are central to the business but are not covered by Medusa's standard commerce modules. These should remain platform-owned domain services and tables.
The application must implement:
- Import batch and import batch item models.
- Landed cost allocation.
- DCA computation and consolidation rules.
- Cost-per-unit history.
- Margin targets and price suggestion logic.
- Contributor and repayment tracking tied to batches.
Finance and reporting¶
The platform's finance requirements go beyond standard commerce transaction storage and should remain custom. Medusa can provide the underlying order and inventory facts, but the finance layer must be built separately.
The application must implement:
- Cashflow ledger.
- Stakeholder equity and payout tracking.
- Per-order and per-channel profitability.
- Inventory valuation, receivables, and batch profitability.
- Reporting and export logic.
Offline, social, event, and POS workflows¶
The business handles Telegram, Instagram, Carousell, physical events, and POS operations that go beyond normal marketplace order ingestion. These are product workflows, not generic commerce primitives, so they remain custom.
The application must implement:
- Manual order entry and offline/social order workflows.
- Event objects and event lifecycle.
- Stock transfer workflows for events and store locations.
- POS interface and session handling.
- End-of-event reconciliation and variance review.
Ops, exception handling, and observability¶
Reliable operations across connectors require platform-owned audit, replay, and support capabilities. Medusa workflows help with orchestration, but the broader operational tooling must be custom.
The application must implement:
- Raw event store.
- Exception queues.
- Manual retry and replay tools.
- Reconciliation jobs.
- Observability and alerting dashboards.
- Internal support/debugging workflows.
Data Ownership and Database Strategy¶
The system uses a single PostgreSQL database. Medusa core module tables (orders, inventory, products, etc.) and custom module tables (TCG metadata, DCA, finance, connectors) all live in the same database. Module Links create join tables between custom models and Medusa models — no cross-database references.
flowchart LR
subgraph DB["Single PostgreSQL Database"]
subgraph MedusaTables["Medusa core tables"]
P[Products / Variants]
O[Orders / Line Items]
INV[Inventory / Reservations]
LOC[Stock Locations]
F[Fulfillments / Returns]
end
subgraph CustomTables["Custom module tables (src/modules/)"]
U[Merchant Users & Roles]
CR[Connector Credentials]
RE[Raw Events / Audit]
TCGM[TCG Metadata]
BATCH[Import Batches / DCA]
FIN[Finance / Cashflow]
EXC[Exception Queues]
end
TCGM -. Module Link .-> P
BATCH -. references .-> P
FIN -. derives from .-> O
RE -. feeds into .-> O
end
Custom module tables¶
The custom Medusa modules in src/ own their own tables (migrated by Medusa alongside core tables):
- Merchant staff users, roles, permissions.
- Connector credentials and token state.
- Raw event logs and audit trails.
- TCG-specific data models and metadata (linked to Medusa product variants via Module Link).
- Import batches, DCA, and costing state.
- Cashflow, stakeholders, payouts, and finance data.
- Exception queues and reconciliation state.
- Reporting/analytics staging.
Medusa-owned database¶
Medusa core tables¶
Medusa's own module tables own:
- Products and variants as the base catalog primitives.
- Orders and line-item commerce state.
- Inventory quantities and reservations.
- Stock locations.
- Fulfillments and returns.
Data strategy note¶
The earlier design centered on a completely custom set of inventory and order tables. In this plan, those domains should not be duplicated as primary sources of truth unless needed for denormalized reporting, caching, or specialized business audit views.
Module Specifications¶
Coverage summary¶
The table below shows, for every module, whether Medusa already provides the behavior out of the box, whether an adjustment/extension is needed, or whether the module must be built fully custom in src/.
| Module | Medusa Native | Needs Adjustment / Extension | Custom Platform Module | Notes |
|---|---|---|---|---|
| Product catalog (base) | ✅ | — | — | Products and variants from Medusa. |
| TCG metadata (condition, foil, grading, set) | — | ✅ | ✅ | Custom Medusa module in src/modules/tcg/ linked to productVariant via Module Link — no cross-DB join. |
| Inventory quantities & reservations | ✅ | — | — | Use Medusa inventory module directly. |
| Stock locations (base) | ✅ | — | — | Warehouse, event, store modeled as locations. |
| Stock transfers (event dedicated/shared modes) | — | ✅ | ✅ | Custom workflow above Medusa locations. |
| Order records & lifecycle | ✅ | — | — | Medusa is system of record. |
| Channel order ingestion (Shopee/Lazada) | — | — | ✅ | Connector workers normalize into Medusa orders. |
| Manual / social channel orders | — | ✅ | ✅ | Custom entry flow; persists via Medusa orders. |
| Fulfillment & returns primitives | ✅ | — | — | Medusa fulfillment module. |
| Marketplace shipment sync | — | — | ✅ | Outbound sync owned by connector layer. |
| Pricing (base price per variant) | ✅ | — | — | Medusa price lists. |
| Multi-tier pricing (Partner, Streamer, Bulk) | ✅ | ✅ | — | Medusa Customer Groups + Pricing Rules store and serve tier prices. Custom layer computes DCA-suggested prices and writes them via Medusa Pricing API. Audit trail remains custom. |
| Sales channel attribution (Shopee, Lazada, Telegram, POS, Manual) | ✅ | — | — | Medusa Sales Channels — each order carries sales_channel_id. |
| Import batch management | — | — | ✅ | Fully custom domain. |
| DCA / landed cost engine | — | — | ✅ | Fully custom domain. |
| Finance & cashflow ledger | — | — | ✅ | Derives facts from Medusa orders. |
| Stakeholder equity & payouts | — | — | ✅ | Fully custom. |
| Profitability reporting | — | — | ✅ | Custom reporting layer. |
| POS (UI + session) | — | — | ✅ | Custom app using Medusa primitives as backend. |
| Event lifecycle & reconciliation | — | — | ✅ | Fully custom. |
| Workflow orchestration framework | ✅ | — | — | Medusa workflows used by platform too. |
| Raw event store / replay tooling | — | — | ✅ | Application-owned. |
| Merchant auth & RBAC (single-tenant) | — | — | ✅ | Staff login, roles, session audit. |
Legend: ✅ Medusa native = out of the box. ✅ Adjustment = Medusa covers the base but requires extension/hooks/metadata. ✅ Custom = built entirely as custom Medusa modules in src/.
Out of scope for MVP: tenancy/provisioning, subscriptions/billing, cross-merchant admin tooling, and SaaS control-plane features. See Deferred: SaaS & Multi-Tenancy.
Product and inventory management¶
The platform should use Medusa's product, variant, inventory, and stock-location capabilities as the foundation. Custom TCG fields and metadata should be linked through Medusa extensions or platform sidecar models.
Medusa-owned base behavior:
- Core product/variant creation and maintenance.
- Inventory and reservation logic.
- Stock location management.
Custom behavior:
- TCG taxonomy and collectible semantics.
- Partner pricing visibility and Mini App display rules.
- Channel listing mapping and display status controls.
Import batch management and DCA engine¶
This module remains fully custom because it represents the business's unique costing model.
Custom behavior:
- Create import batch with supplier, original currency, total SGD paid, GST, and notes.
- Track per-SKU batch lines with quantity, remaining quantity, and margin targets.
- Trigger DCA on arrival status changes.
- Consolidate or recompute weighted cost according to business rules.
- Feed suggested selling prices into platform pricing logic and Medusa product/variant price updates where relevant.
Pricing engine¶
Medusa's Pricing module (Customer Groups + Pricing Rules) stores and serves tier prices. The custom pricing engine computes prices and writes them to Medusa — it does not maintain a parallel price store.
Medusa owns:
- Partner, Streamer, Standard, Shopee, Lazada price tiers via Customer Groups + Pricing Rules.
- Bulk pricing via quantity-based price tiers.
Custom behavior:
- Cost-plus-margin suggestion engine (driven by DCA output).
- Writing computed prices to Medusa's Pricing API.
- Price history and approval/audit trails (business-specific, not commerce-generic).
Order management¶
Order management is split across Medusa and the platform.
Medusa-owned behavior:
- Canonical order records.
- Line-item commerce state.
- Fulfillment-linked order transitions.
- Returns and post-order constructs.
Custom behavior:
- Channel order ingestion.
- Mapping external states to internal workflows.
- Manual and social-channel order creation.
- Order-level fee enrichment and profitability projection.
- Exception handling and replay.
Multi-location stock and transfers¶
Medusa should provide the base stock-location structure, but event and dedicated/shared transfer behavior remains platform-specific.
Medusa-owned behavior:
- Stock locations.
- Inventory association to locations.
Custom behavior:
- Event stock modes such as shared vs dedicated.
- Transfer workflow UX and approvals.
- Event-specific return-to-warehouse reconciliation.
- Marketplace sync behavior on transfer boundaries.
POS module¶
POS remains a custom application module using Medusa and platform inventory/order primitives as backend support.
Custom behavior:
- POS UI optimized for tablet/phone.
- Mixed item / misc-item line entry.
- Payment method handling.
- Event/store sales workflows and summaries.
Finance and reporting¶
This module remains custom.
Custom behavior:
- Per-order P&L.
- Channel profitability.
- Cashflow ledger.
- Stakeholder dashboard.
- Inventory asset valuation.
- Receivables and repayment tracking.
Replacement Mapping¶
| Current / Previous Tooling | New Platform Responsibility |
|---|---|
| Master Inventory sheet | Medusa products/variants plus custom TCG metadata services. |
| Imports sheet | Custom import batch and DCA module. |
| Additional Import Fees sheet | Custom batch contributors and cashflow tracking. |
| Orders sheet | Medusa orders plus platform-side connector/orchestration layer. |
| Cashflow sheet | Custom finance module. |
| Finance/PnL sheet | Custom reporting/dashboard layer. |
| Apps Script order processing | Connector workflows + platform orchestration + Medusa workflows. |
| Apps Script DCA workaround | Custom DCA service. |
| Loyverse POS | Custom POS module. |
Token and Connector Strategy¶
Connector rules¶
- Each marketplace connector manages its own tokens and auth lifecycle.
- No two independent systems should share a refresh-token lifecycle for the same app credentials where the platform invalidates itself on refresh.
- Raw payloads must be stored before processing for audit and replay.
- All outbound sync operations should use retry and backoff strategies.
Connector flow¶
- Receive webhook or poll event from Shopee/Lazada.
- Verify and persist raw payload.
- Normalize into platform canonical event shape.
- Dispatch Medusa workflow and platform-side domain steps.
- Record sync result and expose failures in exception tooling.
sequenceDiagram
participant MP as Marketplace (Shopee/Lazada)
participant CW as Connector Worker
participant ES as Raw Event Store
participant PL as Platform Services
participant MD as Medusa
participant EX as Exception Queue
MP->>CW: Webhook / poll event
CW->>ES: Persist raw payload
CW->>CW: Verify signature & normalize
CW->>PL: Canonical event
PL->>MD: Dispatch workflow (order / inventory)
MD-->>PL: Commerce state updated
PL->>MP: Outbound sync (stock / price / shipment)
alt Sync fails
PL->>EX: Enqueue exception for retry / replay
else Sync succeeds
PL->>ES: Record sync result
end
Infrastructure and Hosting¶
Baseline deployment¶
| Component | Detail |
|---|---|
| Hypervisor | Proxmox VE or equivalent self-hosted environment is acceptable for early deployment. |
| OS | Ubuntu 24.04 LTS. |
| Service packaging | Docker Compose initially. |
| Reverse proxy | Nginx. |
| Production separation | Separate production and staging environments. |
Early deployment principle¶
The team can start with a pragmatic self-hosted single-tenant deployment. The architecture should preserve clean boundaries between custom modules so that future restructuring (including the deferred SaaS path) is possible without rewrites.
Testing Strategy¶
Test pyramid¶
| Level | Tooling | Scope |
|---|---|---|
| Unit tests | jest / vitest | DCA logic, pricing rules, mapping logic, connector normalization, finance calculations. |
| Integration tests | jest/vitest + DB + Medusa | Medusa integration, connector ingestion, DB transactions, inventory correctness. |
| E2E tests | Playwright | Admin UI workflows, POS flows, channel operations. |
| Workflow tests | workflow/integration harness | Retry, replay, idempotency, reconciliation behavior. |
Required coverage areas¶
- Inventory correctness and reservation behavior.
- Channel order ingestion and replay handling.
- DCA and finance calculations.
- Event/POS reconciliation.
- Medusa customization safety and upgrade regression testing.
Team & Delivery Structure¶
Team roles¶
| Role | Responsibility |
|---|---|
| Backend/Application Dev | Custom Medusa modules (TypeScript): connectors, DCA, finance, ops tooling. |
| Commerce Dev | Medusa configuration, extensions, workflows, product/order/inventory setup. |
| Frontend Dev | Next.js admin UI, POS, Mini App UX. |
| QA/Tester | Test plans, regression testing, acceptance validation. |
With a 3-developer team of uneven capacity, responsibilities are assigned with D1 (Lead) carrying most scope, D2 taking a medium load, and D3 taking a lighter supporting load. See Suggested Developer Work Split.
Load distribution¶
| Developer | Role | Approx. share of effort | Primary focus |
|---|---|---|---|
| D1 — Lead | Tech lead / backend | ~55% | Architecture, custom Medusa modules, connectors, DCA, finance APIs, production ownership. |
| D2 — Mid | Commerce / frontend | ~30% | Medusa configuration and extensions, primary UI for core flows, integration plumbing. |
| D3 — Support | Frontend / QA / tooling | ~15% | Secondary UI, dashboards, tests, docs, runbooks, go-live support. |
Definition of Done¶
A phase deliverable is done only when: - Code is reviewed. - Relevant tests are written and passing. - No critical linting or CI issues remain. - API/workflow behavior is documented. - Feature is deployed to staging and smoke-tested. - Acceptance criteria are verified.
Implementation Roadmap¶
Work is organized as a sequence of phases. Phases are ordered by dependency, not by calendar time — each phase begins when the previous one reaches its Definition of Done. No fixed sprint cadence or deadlines are prescribed here.
Roadmap amendment — 2026-05-18
The original roadmap below is preserved for historical product intent, but implementation order changed after Phase 5. Phase 6 shipped the Shopee sandbox/live multi-environment toggle and Phase 7 shipped the Shopee connector overhaul (N-profile model, encrypted token storage, advisory-lock refresh, warehouse cache, diagnostics). The Lazada slice and Offline / Event / POS work remain product goals, but they are deferred to a later roadmap revision rather than the shipped Phase 6 / Phase 7 scopes. Treat the dedicated Phase 6 and Phase 7 docs as source of truth for current implementation.
flowchart LR
P1[Phase 1<br/>Foundation] --> P2[Phase 2<br/>Medusa Fit Validation]
P2 --> P3[Phase 3<br/>Shopee Slice]
P3 --> P4[Phase 4<br/>Costing / DCA]
P4 --> P5[Phase 5<br/>Merchant Ops UI v1]
P5 --> P6[Phase 6<br/>Lazada Slice]
P6 --> P7[Phase 7<br/>Offline / Event / POS]
P7 --> P8[Phase 8<br/>Finance & Reporting]
P8 --> P9[Phase 9<br/>Hardening]
P9 --> P10[Phase 10<br/>Go-live]
Phase breakdown¶
| Phase | Goal | Key Deliverables | Exit Criteria |
|---|---|---|---|
| 1. Foundation | Stand up the baseline environment. | Medusa project scaffold with custom module structure (src/modules/), Docker, merchant auth, CI/CD. |
A developer can run the Medusa application locally and in staging. |
| 2. Medusa fit validation | Prove Medusa can model TCG products and inventory. | TCG product/inventory modeling, custom metadata plan, stock location fit validation. | TCG taxonomy maps cleanly onto Medusa primitives with documented gaps. |
| 3. Shopee slice | End-to-end Shopee connector. | Connector ingestion, raw event log, workflow into Medusa orders/inventory. | A real Shopee order lands in Medusa via the connector. |
| 4. Costing / DCA | Implement business costing logic. | Import batches, DCA engine, pricing logic, linkage to Medusa variants/orders. | DCA output matches the existing spreadsheet for a reference batch. |
| 5. Merchant ops UI v1 | Give the merchant a usable daily-driver UI. | Order views, inventory views, exception queue, basic admin workflows. | Merchant ops staff can process a day of orders in the UI. |
| 6. Lazada slice | Second connector to validate the pattern. | Full Lazada connector, outbound stock/price sync, reconciliation jobs. | Lazada and Shopee run concurrently without inventory drift. |
| 7. Offline / Event / POS | Support manual and event-floor sales. | Manual orders, event transfers, POS base flows. | A mock event can run start-to-finish through the POS. |
| 8. Finance & reporting | Replace spreadsheet-based finance. | Cashflow, stakeholder dashboards, profitability views. | Finance dashboards match the existing spreadsheet month-end for one period. |
| 9. Hardening | Make it production-ready. | Observability, replay/retry tooling, UAT, migration prep. | UAT passes; runbooks exist for all major failure modes. |
| 10. Go-live | Production rollout and cutover. | Production rollout, monitoring, parallel run, cutover. | The merchant has fully cut over from the previous tooling. |
Suggested Developer Work Split¶
Each phase is split across three parallel tracks, with effort intentionally skewed: D1 (Lead) carries most of the scope and makes architectural decisions, D2 (Mid) handles commerce/frontend medium-weight work, and D3 (Support) picks up lighter tasks such as secondary UI, tests, tooling, and docs.
| Phase | D1 — Lead (Most) | D2 — Mid (Medium) | D3 — Support (Low) |
|---|---|---|---|
| 1. Foundation | Custom module scaffold (src/modules/ structure), merchant auth, architecture decisions. |
Medusa POC, Docker setup. | Frontend scaffold, CI/CD pipeline config. |
| 2. Medusa fit validation | TCG metadata and DCA domain design; gap analysis vs Medusa. | Medusa product/inventory modeling and extension validation. | Taxonomy documentation, shared test fixtures. |
| 3. Shopee slice | Shopee connector, raw event log, normalization, workflow dispatch. | Medusa workflow hooks, initial ops UI shell. | Connector test harness, fixtures, docs. |
| 4. Costing / DCA | DCA engine, batch APIs, finance linkage. | Batch/pricing UI. | DCA unit test fixtures, spreadsheet parity checks. |
| 5. Merchant ops UI v1 | Admin/order APIs, exception APIs, RBAC wiring. | Order/inventory dashboard UI core screens. | Secondary screens, UI polish, empty/error states. |
| 6. Lazada slice | Lazada connector, outbound stock/price sync, reconciliation jobs. | Reconciliation UI. | Exception/failure UI tooling, regression tests. |
| 7. Offline / Event / POS | POS/event backend flows, stock transfer workflows. | POS UI. | Event reporting views, scripted POS test runs. |
| 8. Finance & reporting | Finance APIs and reporting logic, P&L calculations. | Finance dashboards. | Exports (CSV/PDF), report QA, stakeholder walkthroughs. |
| 9. Hardening | Observability, migrations, replay/retry tooling, performance. | E2E test suite, staging/UAT support. | Runbooks, docs, smoke-test scripts. |
| 10. Go-live | Production deployment, cutover, incident ownership. | Go-live validation, parallel-run checks. | Post-launch support rota, monitoring dashboards. |
Effort share across phases¶
pie title Approximate effort share
"D1 — Lead" : 55
"D2 — Mid" : 30
"D3 — Support" : 15
Risk Register¶
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Connector API rate limits | Medium | High | Queueing, retry/backoff, local state tracking. |
| Platform API breaking changes | Low | High | Version pinning, abstraction layers, monitoring changelogs. |
| Inventory drift | Medium | High | Reservation-aware flows, reconciliation jobs, replay tools. |
| Deep Medusa customization drift | Medium | High | Use official modules, workflows, and hooks; avoid core patching. |
| Scope creep | High | Medium | Strict backlog control and sprint gating. |
| Data migration issues | Medium | High | Parallel run, validation scripts, rollback plan. |
| Event/POS reconciliation errors | Medium | High | Mandatory end-of-event reconciliation flow and operator review. |
| Premature SaaS abstractions leaking into MVP | Medium | Medium | Keep MVP strictly single-tenant; defer all SaaS concerns to the post-MVP section. |
Non-Functional Requirements¶
| Requirement | Target |
|---|---|
| API response time | < 300ms p95 where applicable. |
| Order sync latency | < 5 minutes from platform event to internal state update. |
| Uptime | 99.5% monthly for core workflows. |
| Stock accuracy | Zero untracked movements; auditability of all material changes. |
| Data retention | 7 years for financial records where required for compliance. |
| Security | HTTPS everywhere, secrets outside Git, access control, auditable admin actions. |
| Privacy | PDPA-aware handling of operational PII and right-to-erasure workflows where applicable. |
Deferred: SaaS & Multi-Tenancy (Post-MVP)¶
Everything in this section is intentionally out of scope for the MVP. The MVP is a single-tenant operations platform for one TCG business. SaaS commercialization is a separate future initiative that should only begin after the MVP is stable in production and the product fit for one merchant is proven.
This section exists so the SaaS intent is documented but does not leak into MVP scope, architecture decisions, sprint work, or data models.
Rationale for deferral¶
| Reason | Explanation |
|---|---|
| Product fit not yet proven | Multi-tenancy is expensive; it should only be built after the single-merchant product is validated in production. |
| Avoids premature abstraction | Tenant-aware data models, routing, and auth flows often ossify the wrong assumptions if built before real usage. |
| Reduces MVP surface area | Removing tenancy, subscriptions, and cross-merchant tooling frees significant engineering budget for TCG, connectors, DCA, and finance. |
| Keeps Medusa usage simple | Single-tenant deployments let the team adopt Medusa without immediately solving per-tenant isolation. |
Deferred capabilities¶
| Capability | Description |
|---|---|
| Tenants and merchant records | First-class tenant entity, provisioning lifecycle, soft-delete and archival. |
| Tenant-aware routing | Subdomain or path-based routing, per-tenant request scoping across all services. |
| Per-tenant data isolation | Row-level or schema-level isolation in both the application DB and Medusa DB. |
| Platform-level auth & RBAC | Cross-merchant identity, SSO, role hierarchies spanning tenants and internal staff. |
| Subscriptions & billing | Plans, usage metering, invoicing, dunning, Stripe (or equivalent) integration. |
| Internal support/admin tools | Cross-merchant admin UI for support staff, impersonation, audit, plan management. |
| Tenant onboarding flows | Self-service sign-up, guided setup, sample data, connector onboarding wizards. |
| Per-tenant connector credentials | Isolated Shopee/Lazada credentials, tokens, webhook endpoints per merchant. |
| Per-tenant observability & quotas | Metrics, rate limits, and alerting scoped to each tenant. |
| Compliance & DPA per tenant | Per-merchant data processing agreements, export/erasure flows, regional hosting. |
Architectural principles to preserve in the MVP¶
Even though SaaS is deferred, the MVP architecture should avoid actively painting itself into a corner:
| Principle | MVP behavior |
|---|---|
| Clean module boundaries | Keep custom module boundaries clean so future restructuring does not require rewrites. |
| No tenant-leaking assumptions | Do not hardcode the single merchant's ID, name, or config in code paths that a future tenant_id would need to scope. |
| Config over hardcoding | Environment and feature configuration stays in env/config files, not literals. |
| Auth abstraction | Merchant auth is real but simple; reserve space for a later identity provider swap. |
| Data model hygiene | Avoid globally-scoped foreign keys that would block future tenant_id introduction. |
When to revisit¶
SaaS work should be considered only when all of the following are true: - The MVP has run in production for the first merchant for a sustained period without major architectural rework. - At least one additional concrete merchant prospect exists and has validated willingness to pay. - The team has capacity for a dedicated SaaS initiative without degrading MVP support and operations. Until those conditions are met, any SaaS-shaped work should be refused or redirected back into this section.
Future Roadmap¶
Post-MVP enhancements unrelated to SaaS commercialization. SaaS-specific work is covered in the deferred section above.
| Feature | Rationale |
|---|---|
| TikTok Shop integration | Natural extension of connector pattern. |
| Carousell automated listing/integration | Reduce manual listing work. |
| Stronger worker/queue architecture | Improve scale and resilience once load grows. |
| Forecasting and restock suggestions | Sales velocity and lead-time insights. |
| CRM and customer loyalty | Cross-channel repeat buyer tracking. |
| Mobile app | Better event-floor operations. |
| GST registration support | Formal accounting and tax workflows if required later. |
Final Positioning¶
This platform should be described as a Medusa-powered TCG commerce operations platform for a single merchant rather than a fully custom commerce backend or a SaaS product. Medusa owns the standard commerce foundation, while the team builds the actual product moat in TCG semantics, connectors, costing, ops tooling, event/POS workflows, and finance. SaaS commercialization is a deliberate, deferred future chapter — not part of the MVP story.