ShopCore — Enterprise Persian e-commerce platform
A reusable Persian-first commerce platform I architected end-to-end (first deployed for RedAccessory): variant catalog, multi-location inventory ledger, online gateway & card-to-card payments, capability RBAC, and dynamic CMS.
Year
2026
Role
Founder / Full-stack
Stack
Next.js • TypeScript • PostgreSQL
Context
ShopCore is a reusable Persian-first e-commerce platform I architected from the ground up—first deployed for RedAccessory—to unify storefront discovery, multi-location stock ledgers, dual-rail online and card-to-card payments, capability-based RBAC, and dynamic CMS operations inside one modular monolith.
What needed to work
- 01Prevent overselling and stock drift under concurrent checkouts using an immutable multi-location inventory ledger and time-bounded reservations.
- 02Support both online PSP gateways and manual card-to-card bank transfers with private receipt evidence, reconciliation, and versioned bank destinations.
- 03Enforce strict capability-based RBAC (55+ permissions), dual-token rotation with replay detection, TOTP 2FA, and step-up re-authentication for staff.
- 04Deliver a reusable Persian-first architecture with search normalization, Jalali dates, integer BigInt Rial arithmetic, transactional outbox jobs, and dynamic CMS.
What I built
Modular storefront and catalog with Persian search normalization, multi-option variants, bundles, promotions, and versioned home-builder CMS.
Transactional checkout intents, stock reservation ledger, weighted-average cost allocation, dual-rail gateway/receipt payments, and returns inspection.
Dual-token session rotation, Argon2id + TOTP 2FA, 55+ RBAC capabilities, pg-boss outbox, append-only audit triggers, and automated CI/CD.
My role
I architected and built ShopCore end-to-end as a reusable Persian commerce platform (first deployed for RedAccessory), spanning domain modeling, PostgreSQL schema, security architecture, admin and storefront UI, automated verification, and Docker CI/CD. The detailed report below documents the architecture and its boundaries.
The result
- A reusable modular-monolith commerce core powering storefront discovery, checkout, fulfillment, returns inspection, support tickets, and CMS.
- Strict financial and inventory invariants backed by PostgreSQL 18 transactions, append-only audit triggers, and a pg-boss transactional outbox.
- Verified across unit, serial PostgreSQL integration, API contract, entry-point guard, and fa-IR Playwright browser suites with automated Docker CI/CD.
Inside ShopCore: product and engineering report
A deep look at how I architected a reusable Persian-first e-commerce platform—first deployed for RedAccessory—connecting storefront discovery, variant catalogs, multi-location inventory ledgers, dual-rail payments, RBAC, and CMS operations in one modular monolith.
Product and source reviewed on November 17, 2026. Storefront and admin screenshots were captured locally from the RedAccessory reference installation using seeded demo data; they contain no live customer, staff, or payment records. Results below describe verified implemented behavior without inventing traffic, revenue, or benchmark claims.
One connected commerce lifecycle
- 1
Discover with Persian search
- 2
Select variants and reserve stock
- 3
Verify intent and quote
- 4
Pay via gateway or receipt
- 5
Pick, pack, and ship
- 6
Audit, support, and retain
01 — The product problem and architectural vision
Most custom online stores fail in the gap between the storefront and daily operations: catalog models cannot represent multi-option variants or bundles cleanly, stock counts drift under concurrent checkouts, card-to-card bank transfers live in chat threads instead of auditable ledgers, and staff share one all-or-nothing admin password.
I designed and built ShopCore as a reusable Persian-first commerce platform—with RedAccessory as its first production-grade installation—organized as a strict modular monolith. Domain logic is partitioned into focused modules under src/modules/ (catalog, inventory, checkout, orders, payments, fulfillment, promotions, returns, customers, content, marketing, authorization, audit, reporting, settings, and shared) backed by a shared platform layer under src/platform/.
The platform serves shoppers browsing and tracking orders on mobile or desktop, warehouse and fulfillment operators packing shipments, finance staff reconciling bank receipts and refunds, content editors managing the home-builder and blog, support agents resolving tickets, and shop owners governing roles and system health.
02 — Storefront discovery, Persian search normalization, and SEO
The public storefront is built on Next.js App Router with server-rendered catalog, category, collection, product, blog, FAQ, and CMS pages. Visitors can filter by hierarchical categories, curated or rule-based collections, price ranges, stock availability, discounts, and dynamic product attributes.
Because Persian search inputs frequently mix Arabic and Persian character variants, a dedicated search normalizer unifies Kaf/Yeh forms, Teh Marbuta, Persian/Arabic/Latin digits, and zero-width non-joiners before matching against products, SKUs, and categories. Out-of-stock items support back-in-stock subscriptions alongside authenticated wishlists.
Search engine hygiene is treated as first-class infrastructure: dynamic sitemaps, robots policies, OpenGraph image generation, and database-backed 301/302 URL redirects (cached in memory for 30 seconds at the request proxy) keep slug changes from breaking indexed links. Production environment validation explicitly enforces HTTPS URLs and indexing controls.
03 — Catalog modeling: options, variants, attributes, and bundles
Products move through explicit DRAFT, PUBLISHED, and ARCHIVED lifecycles. Each product supports structured options and option values (such as color, size, or finish) that resolve into concrete ProductVariant rows with unique SKUs, barcode/weight metadata, compare-at pricing, and integer BigInt Iranian Rial prices.
Beyond single variants, the schema models BundleComponent relationships so multi-item gift sets or kits reference underlying component SKUs, alongside typed AttributeDefinition records (TEXT, NUMBER, SELECT) for structured technical specifications and faceted filtering.
Customer reviews follow a moderated workflow (PENDING, APPROVED, REJECTED) linked to verified product records, while product media separates public catalog assets from private operational files.
04 — Multi-location inventory ledger and cost allocation
Stock is never mutated with naive increment/decrement counters. ShopCore tracks StockItem balances per variant and StockLocation using three explicit quantities—onHand, reserved, and committed—enforcing the invariant that available = onHand - reserved - committed with all quantities constrained non-negative.
Every change appends an immutable InventoryMovement record (RECEIPT, RESERVATION, RELEASE, SALE, DISPATCH, RETURN_RESTOCK, DAMAGE, TRANSFER, ADJUSTMENT) protected by a unique idempotencyKey so retries cannot double-count stock. Reorder thresholds surface low-stock alerts directly on the operations dashboard.
Supplier purchasing is integrated through Supplier, PurchaseReceipt, and PurchaseLine records, feeding a CostAllocation ledger that maintains weighted-average unit costs in integer Rials for accurate inventory valuation and margin reporting.
05 — Authoritative cart, checkout intents, and order state machines
Guest and authenticated carts persist on the server via HttpOnly cart cookies and merge cleanly on sign-in. Moving to checkout creates a CheckoutIntent that progresses through DRAFT, VERIFIED, FINALIZED, or ABANDONED states, requiring OTP phone verification (VerifiedIntentGrant) when guest phone ownership has not yet been established.
Before order creation, the server computes an authoritative Quote snapping item prices, shipping costs, and promotion discounts. Finalization runs inside a PostgreSQL transaction protected by an IdempotencyRecord and creates time-bounded stock Reservations so concurrent buyers cannot oversell the last unit.
Once placed, orders are governed by explicit state machines separating financial OrderState (AWAITING_PAYMENT, CONFIRMED, CANCELLED, COMPLETED, EXCEPTION) from physical FulfillmentState (UNFULFILLED, PICKING, PACKED, PARTIALLY_SHIPPED, SHIPPED, DELIVERED), ensuring illegal transitions are rejected at the domain boundary.
06 — Dual-rail payments: online gateway and card-to-card receipts
Iranian e-commerce routinely requires both online PSP gateways and manual card-to-card bank transfers. ShopCore models both rails uniformly under PaymentAttempt and PaymentEvent, tracking states across CREATED, PENDING, UNDER_REVIEW, SUCCEEDED, FAILED, REJECTED, EXPIRED, and UNKNOWN.
Online payments run through an isolated gateway adapter (with a full SandboxPaymentGatewayAdapter for local/CI verification of success, failure, unknown/timeout reconciliation, and callbacks) so live PSP credentials can be swapped in without touching checkout or order logic.
For card-to-card transfers, destination bank cards are versioned via BankDestinationRevision so historical orders retain the exact account shown at checkout. Customers upload transfer receipts into private, non-cacheable media storage; finance staff inspect the receipt queue and approve or reject submissions atomically, while Refund records track post-payment reversals.
07 — Promotions engine, coupons, and campaign placements
All monetary calculations use integer BigInt Rial arithmetic, with percentage discounts expressed in integer basis points (100 bps = 1%) and optional maximum discount caps to prevent rounding drift or negative totals.
The promotions module supports both coupon codes and automatic cart discounts across fixed-amount, percentage, and free-shipping rules, with targeting by category or product, first-order-only eligibility, minimum basket thresholds, and global or per-customer usage limits. Checkout holds an atomic PromotionReservation that converts into a PromotionRedemption only when the order commits.
Marketing campaigns use versioned CampaignRevision records scheduled across TOPBAR, POPUP, and INLINE_BANNER placements, recording CampaignImpression and CampaignInteraction events for conversion visibility.
08 — Fulfillment, shipping revisions, and returns inspection
Shipping methods and pricing rules are versioned through ShippingMethodRevision so rate updates never alter existing order snapshots. Warehouse operators work from order detail views and printable packing slips to move shipments through picking, packing, partial or full dispatch, and delivery.
Each Shipment links specific ShipmentLine quantities to carrier TrackingEvent records, allowing multi-package or partial fulfillment without losing item-level traceability.
Post-delivery returns follow an explicit ReturnRequest lifecycle (REQUESTED, APPROVED, REJECTED, IN_TRANSIT, RECEIVED, INSPECTED, RESOLVED) with ReturnLine items and structured ReturnInspection outcomes that decide whether returned units restock into sellable inventory or are written off as damaged.
09 — Customer accounts, order tracking, and support tickets
Authenticated customers manage saved Iranian addresses, security sessions, notification preferences, returns, and order history under /account/*. Marketing consent is tracked explicitly in CustomerConsent rather than implied from placing an order.
Guests who check out without creating a full profile can still track orders and upload card-to-card receipts via /track-order using a cryptographically hashed viewTokenHash capability stored on the order.
Customer support is built into the same relational model: Ticket and TicketMessage threads categorize inquiries by priority and topic, while internal CustomerNote records let staff record operational context without exposing private notes to shoppers.
10 — Dynamic CMS, home-builder, and versioned settings
Rather than hardcoding promotional landing blocks, ShopCore includes a HomeLayout and HomeLayoutRevision builder in /admin/home-builder where editors compose ordered HomeSection blocks and preview or publish changes cleanly.
Static pages, navigation menus, FAQ entries, and blog articles use revisioned models (PageRevision, ArticleRevision, SettingsRevision) with DRAFT, PUBLISHED, and ARCHIVED states. Long-form content uses a TipTap rich-text editor paired with server-side HTML sanitization before rendering.
Storefront configuration—brand identity, contact details, bank destinations, and operational policies—follows the same draft-and-publish discipline so configuration changes are auditable and reversible.
11 — Dual-token authentication, TOTP 2FA, and step-up re-auth
Customer and staff sessions use separate namespaces and dual-token lifecycles: 15-minute HMAC-SHA256 signed access tokens verified with timingSafeEqual, paired with 256-bit opaque refresh tokens stored in PostgreSQL as keyed HMAC-SHA256 digests. Cookies use __Host- prefixes on HTTPS with HttpOnly and SameSite=Strict for staff.
Refresh token rotation is serialized with a 10-second concurrent-tab grace window (prevRefreshTokenHash + rotatedAt). Any replay of a spent refresh token outside that grace window immediately revokes the entire tokenFamilyId and writes a REFRESH_TOKEN_REUSE_DETECTED security event.
Staff accounts hash passwords with Argon2id (@node-rs/argon2), support TOTP two-factor authentication (otpauth) with single-use recovery codes, and enforce a 10-minute step-up re-authentication window (lastReauthAt) before sensitive actions such as role changes or backup operations.
12 — Capability-based RBAC and request security pipeline
Authorization is governed by 55+ granular capability keys grouped across 14 operational domains and 6 system role presets (Owner, Manager, CatalogEditor, FulfillmentAgent, SupportAgent, MarketingEditor). Every protected staff request reloads live effective capabilities and checks authzRevision so role revocations take effect immediately without waiting for token expiry.
The request proxy (src/proxy.ts) attaches request correlation IDs, security headers (X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy, Permissions-Policy), silent token rotation, and route guards for /admin/* and /account/*.
Mutating endpoints enforce same-origin CSRF checks (Sec-Fetch-Site and Origin/Referer validation), hybrid in-memory + PostgreSQL sliding-window rate limiting (RateLimitBucket), and binary magic-byte image signature verification (rejecting executables and script payloads) on all media uploads.
13 — Transactional outbox, background jobs, and append-only audit
Business mutations never fire external SMS, email, or webhook side effects inline inside a database transaction. Instead, committed transactions write an OutboxEvent with a unique dedupeKey; a pg-boss background worker relays pending events with retry and dead-letter handling.
Sensitive domain actions append to AuditEvent, which is protected at the PostgreSQL layer by a database trigger that rejects UPDATE and DELETE statements, preserving a tamper-evident operational trail.
Operations tooling includes automated SQL and media tar backup engines with scheduled execution and email delivery, alongside liveness and readiness health endpoints (/api/v1/health/*) for container orchestration.
14 — Persian-first localization, Jalali calendar, and PWA
Every interface—from storefront filters to admin tables and packing slips—is built natively for Persian RTL typography, Persian digit formatting, and Tehran timezone boundaries.
Shared domain utilities handle Jalali calendar conversions, Iran province/city hierarchies, and whole-Rial/Toman display formatting consistently across server-rendered pages, transactional emails, and client components.
A web app manifest and dedicated /offline route provide installable PWA entry points while keeping authenticated dashboards, checkout mutations, and private receipts strictly online-only.
15 — Verification, entry-point contracts, and CI/CD delivery
The repository enforces automated verification across four layers using Vitest and Playwright: 342 unit tests covering domain math, state machines, normalizers, and security helpers; 111 serial PostgreSQL 18 integration tests exercising real transactions, locks, and triggers; API contract checks; and 23 authenticated fa-IR browser workflows.
Custom static checks verify that every API route and server entry point declares explicit auth/CSRF guards (check:entrypoints) and that architecture documentation stays synchronized with code (check:docs).
GitHub Actions CI spins up PostgreSQL 18, runs typecheck, lint, unit, integration, build, and Playwright suites, and on main pushes triggers a self-hosted CD pipeline that builds a non-root Node 24 standalone Docker image, runs Prisma migrations, and health-checks the live container.
16 — What ShopCore demonstrates and extension boundaries
ShopCore demonstrates end-to-end ownership of an enterprise-grade commerce system: from a 1,896-line PostgreSQL schema and transactional inventory/payment state machines to capability-based RBAC, dual-token rotation, dynamic CMS, and automated CI/CD.
The codebase is intentionally structured as a reusable commerce core rather than a one-off store: replacing the sandbox SMS and payment gateway adapters with live Iranian PSP and SMS provider credentials requires implementing only the adapter interfaces while keeping checkout, reconciliation, and ledger invariants intact.
Explicit scope boundaries are documented honestly: the current model targets a single-storefront deployment per instance rather than multi-tenant SaaS, and all numbers or workflows shown here reflect verified code and seeded local demo captures rather than claimed live store traffic.
A closer look
Captured Nov 17, 2026
Storefront home 1 / 12
Synthetic demo dataStorefront and admin screens were captured locally from the RedAccessory reference installation of ShopCore using seeded demo data; they contain no live customer, staff, or payment records.
Working on a similar challenge?
Introduce your idea or current product so we can discuss the work you need.