Skip to content

System Overview

Table of Contents


Business Objective

This is an Enterprise-grade e-commerce platform designed to manage both physical (POS) and online sales for multi-branch retail businesses. The system is a complete ecosystem of three integrated applications functioning as a Web-based Mini-ERP.

Key Business Problems Solved

ProblemImplemented Solution
Stock oversellingAtomic database transactions + reservation system with configurable TTL
Abandoned carts blocking inventoryCron Job that releases expired reservations and auto-cancels PENDING sales
Cart price fraudBackend recalculates ALL prices, discounts, taxes and shipping from scratch. The frontend is a "lying client"
Physical vs online sales inconsistency"Physical Priority" system: POS sales can override online reservations
International operationMulti-currency engine with automatic Geo-IP, local currency pricing and exchange rate snapshots per transaction
Traceability and auditingImmutable log of every stock movement, every admin action and every system error
ScalabilityValidated for 100+ concurrent users, 500+ active carts, with concurrency control and idempotency

The Three Pillars

1. Backend API (Node.js + Express + PostgreSQL)

Central REST API server handling all business logic, database operations, external integrations and real-time WebSocket communications.

  • 42 specialized services (sale, stock, currency, discount, event, backup, etc.)
  • 32 REST endpoint controllers
  • Automated Cron Jobs (backups, expired reservation cleanup)
  • WebSocket (Socket.IO) for real-time chat and notifications

2. Admin Panel (Next.js + React + TypeScript)

Complete administrative dashboard with 31 pages for staff to manage the entire platform without needing a programmer.

3. Customer Web / Frontend (Next.js + TailwindCSS)

Customer-facing e-commerce application with 21 pages, premium design with advanced animations, and complete shopping experience.


Complete Functional Scope

🏢 Multi-Branch Management

  • ✅ Support for multiple physical branches with independent inventory per branch.
  • ✅ Branches are created, edited and deactivated from the admin panel.
  • ✅ Each employee can be assigned to a specific branch.
  • ✅ POS sales are processed in the context of the operator's active branch.
  • ✅ Dashboard and reports filterable by branch.

💱 Multi-Currency & Internationalization

  • Dynamic currency engine: Support for 20+ currencies (ARS, USD, EUR, MXN, BRL, CLP, COP, GBP, etc.).
  • Automatic Geo-IP detection: Uses headers to determine visitor currency.
  • Conversion rule: Local client → configured base currency. Foreign client → USD automatically.
  • Configurable exchange rates: exchangeRateToBase defined per currency from the admin panel.
  • Smart PriceService: First looks for a manual price per currency (ProductPrice), if none exists, converts basePrice using the exchange rate.
  • Immutable snapshot: When creating a sale, a "photograph" of the exact exchange rate at the time of transaction is saved. If the dollar changes tomorrow, historical accounting is never altered.
  • Conditional taxes: Only applied if the buyer is from the country of origin (validated by IP).

📊 Audit & Action Logging

  • AuditService: Centralized log of ALL administrative actions: who, what, when, from which IP and technical diff of changes.
  • Error logging (ErrorLog): Every server error is saved with severity (CRITICAL, HIGH, MEDIUM, LOW), stack trace, JSON context and reference to affected user.
  • Immutable StockMovement: Every stock movement (sale, purchase, transfer, manual adjustment) is logged with type, quantity, resulting stock and responsible user.
  • Exploration panel: Integrated search with filters by administrator, action type and date range.

🚨 Alert System

  • ✅ Paginated list of server technical errors (ErrorLog).
  • ✅ Filters by severity (CRITICAL, HIGH, MEDIUM, LOW) and date range.
  • ✅ Detail dialog with stack trace and JSON context visualization.
  • ✅ "Resolve" action for incident tracking.
  • ✅ Low stock and critical stock alerts (configurable thresholds).

🔔 Notification System

  • Real-time notifications via WebSocket (Socket.IO).
  • Notification center in admin panel with bell icon, unread badge and history.
  • Email notifications: Order confirmation, password reset, welcome.
  • InAppNotificationService: Persistent database notifications with read states.

👥 Role System (RBAC)

  • 4 hierarchical roles: SUPER_ADMIN > ADMIN > EMPLOYEE > CLIENT.
  • ✅ Granular access control on every backend endpoint (authorize middleware).
  • ✅ SUPER_ADMIN: Full access, system configuration, cannot be deleted.
  • ✅ ADMIN: Manages products, sales, stock, discounts, suppliers. Cannot create other ADMINs.
  • ✅ EMPLOYEE: Operates POS, views inventory, handles chat. Cannot modify products or prices.
  • ✅ CLIENT: Browses, shops, manages profile and favorites. No admin panel access.

📦 Product Management with Variants

  • Product-SKU model: Each base product can have multiple variants (SKUs) with attribute combinations (size, color, material, etc.).
  • ✅ Each SKU has its own stock, price, barcode and internal code.
  • Dynamic variant options (VariantOption): Free-form name and value (e.g.: "Color: Red", "Size: 42").
  • ✅ Visibility flags: isTrending, isRecommended, isNew for featured sections.
  • ✅ Differentiation between physical and digital products.
  • ✅ Multiple image uploads via Cloudinary.
  • ✅ Hierarchical categories (parent-child) with SEO metadata.

📊 Stock Management

  • Inventory per branch (BranchInventory): Each SKU has independent stock per branch.
  • ✅ Manual stock adjustments with automatic StockMovement logging.
  • Physical Priority: POS sales can override online purchase reservations.
  • ✅ Web safety stock: When stock drops to a certain level, the product is hidden from the frontend to prioritize in-store sales.
  • ✅ Low and critical stock alerts with configurable thresholds.
  • ✅ Configurable overselling prevention.

🔄 Inter-Branch Stock Transfers

  • ✅ Create transfer with source and destination branch.
  • ✅ Add items (SKU + quantity).
  • ✅ Status flow: PENDING → COMPLETED.
  • ✅ Automatic stock adjustment in both branches upon receipt.
  • StockMovement logged as TRANSFER_OUT and TRANSFER_IN.
  • ✅ Full audit trail for each transfer.

📈 Dashboard & Reports

  • Real-time dashboard: KPIs (Gross revenue, order count, average ticket).
  • ✅ Interactive charts with Recharts (sales by day/week/month).
  • ✅ Low stock alerts visible on dashboard.
  • Exportable reports: Sales by date/branch/employee, top-selling products, inventory valuation, movement history.
  • PDF and CSV export of tables and data.
  • ✅ Employee performance (number of sales processed).

🏭 Suppliers, Purchase Orders & Payments

  • Supplier CRUD: Name, email, phone, address, notes.
  • SKU-Supplier linking: Each SKU can have an assigned supplier with cost price (SupplierSKU).
  • Purchase orders: Create PO with supplier selection → add items (SKU + quantity + cost) → flow PENDING → PAID → RECEIVED.
  • Merchandise reception: When marking a PO as received, stock is automatically incremented in the selected branch with StockMovement type PURCHASE.
  • Supplier payments: Partial or full payment tracking with pending balance.
  • ✅ Purchase and payment history per supplier.

🛒 Advanced Sales Management

  • Point of Sale (POS): Search by name/barcode scanner, variant selection, automatic discounts, multiple payment methods.
  • Multi-step online checkout: Identification → Delivery (shipping or pickup) → Payment (MercadoPago, Stripe, PayPal) → Confirmation.
  • Idempotency: Prevents duplicate sales by checking if a similar sale was created recently.
  • Controlled concurrency: Atomic Prisma transactions ($transaction) for stock reservations. The system deducts stock within the same transaction that creates the sale, eliminating race conditions.
  • TTL reservations: Stock is temporarily reserved; if payment is not completed, StockCleanupService releases units automatically.
  • Automatic cleanup: cleanupAbandonedSales() finds PENDING sales older than 1 hour and cancels them, releasing reservations and reverting stock.
  • ✅ Status flow: PENDING → CONFIRMED → SHIPPED → DELIVERED / CANCELLED.
  • ✅ Shipping status updates (PREPARING, SHIPPED, DELIVERED).

🧾 Invoice & Ticket Printing

  • PDF invoice generation with PDFKit: Includes business data, detailed items, discounts, taxes and totals.
  • 80mm thermal ticket: Optimized format for point-of-sale thermal printers.
  • ✅ Invoice download from customer purchase history and admin panel.
  • ✅ Automatic invoice generation on sale confirmation (configurable).

📱 QR & Barcode

  • QR code per product (qr field in Product model).
  • Barcode per SKU (barcode field in SKU model).
  • Bulk PDF export: code-export controller generates a PDF with label grid (3x7 = 21 per page) using bwip-js.
  • ✅ Support for QR Code and Code128 formats.
  • ✅ Filters: export all, by category or by manual selection.

👤 Advanced User Management

  • ✅ List users with role filter, search and pagination.
  • ✅ Change user roles (requires permissions).
  • ✅ Suspend/reactivate accounts.
  • ✅ View user purchase history.
  • ✅ Assign users to branches.
  • ✅ Side panel user details without losing context.

🏷️ Advanced Product & Category Management

  • ✅ Complete product form with images, variants (SKUs), prices, stock per branch.
  • ✅ Hierarchical categories with parent-child relationships (tree).
  • ✅ Icon assignment and SEO metadata per category.
  • ✅ Visibility flags: trending, recommended, new.
  • ✅ Bulk stock operations.

🎫 Coupons & Discounts

  • Coupons: Alphanumeric code (e.g.: "SUMMER2026"), PERCENTAGE or FIXED type, with restrictions: minimum amount, max uses per customer, total max uses, expiration date.
  • Discounts: By product, by category, global, by payment method, by minimum quantity, by minimum amount.
  • Priority system: Product > Category > Global.
  • Stackable vs non-stackable: Control whether discounts combine.
  • Overlap protection: System validates that total discount sum doesn't exceed 100%.

🎪 Event System

  • Temporary events with start and end dates that override standard system configuration.
  • ✅ An event can modify: which payment methods are enabled, which shipping methods, whether coupons are accepted, whether points apply, whether taxes are collected.
  • Custom visual content: Each event can have its own hero banners, marquee text, secondary ads and promotional messages.
  • Event-specific discounts: Discounts linked to an event have priority over standard discounts.
  • Single active event rule: Only one event can be active at a time (others are automatically deactivated).

🚚 Shipping by City/State

  • Configurable shipping zones: Create zones (e.g.: "Downtown", "South Zone", "Interior") with base cost.
  • ✅ Optional weight-based pricing levels.
  • Configurable free shipping threshold.
  • ✅ Enable/disable shipping globally.
  • ✅ Zone selection at checkout with automatic cost calculation.

💳 Payment Gateways

  • Payment Factory Pattern: PaymentFactory dynamically delegates to MercadoPagoStrategy, PayPalStrategy or StripeStrategy.
  • ✅ Enable/disable each gateway from panel configuration.
  • Secure webhooks: Endpoints reacting to asynchronous notifications from gateways to mutate states automatically.
  • ✅ Support for cash, card and bank transfer payments.
  • ✅ Currency association management per gateway from the Gateways settings page.

💬 Comments & Reviews Management

  • ✅ Customers can leave product reviews with rating scores.
  • ✅ Comment management panel in admin.
  • ✅ Comment moderation.

⭐ Loyalty Points System

  • Configurable earn rate: How many points are earned per currency unit spent.
  • Configurable redemption rate: Monetary value of 1 point.
  • Checkout redemption: Customers can use points as partial or full discount.
  • Automatic granting: processPostPaymentActions grants points only after the sale is fully paid.
  • ✅ Points movement history visible in customer profile.
  • ✅ Global toggles to enable/disable the entire system.

📐 Measurement Unit System

  • measurementUnit field on Product model: supports "UNIT", "KG", "METER", "LITER" and more.
  • allowFractional flag for products sold by weight or measure (allows quantities like 0.5, 1.75).
  • ✅ Customizable units from system configuration.

🎨 Web Content Editing (CMS)

  • Promotional banners: Hero banner management with images and text.
  • Secondary ads: Configurable advertising slots.
  • Marquee text: Customizable scrolling ribbon at the top of the web store.
  • Store logo: Corporate logo upload and management.
  • Blog: SEO-friendly articles with full editor, managed from admin panel.
  • Business hours: Standardized for each day of the week.

💬 Real-Time Chat System

  • Customer-admin chat: Bidirectional WebSocket (Socket.IO) between frontend and admin panel.
  • Zendesk-style CX Inbox: Administrators and employees see an inbox of incoming chats with history.
  • Presence detection: System detects if an administrator or employee is online. If nobody is available, the automatic bot responds.
  • Manageable auto-responses: Auto-responses of the chatbot can be configured from the panel (triggers, responses, priorities).

📝 Blog Management

  • ✅ Blog article CRUD from admin panel.
  • ✅ Public blog on frontend with magazine-style design.
  • ✅ SEO-friendly: titles, meta descriptions, friendly URLs.

📥 Table & PDF Downloads

  • Table export: CSV data download from admin panel listings.
  • PDF generation: Invoices, tickets, sales reports, barcode/QR labels.
  • Report export: Financial, inventory, stock movements.

💾 Automatic Database Backups

  • BackupService: Extracts all database tables to JSON format and compresses into a ZIP file.
  • Configurable Cron Job: Runs daily at 02:00 AM and checks configured frequency (DAILY, WEEKLY, MONTHLY).
  • Manual backup: Endpoint to generate and download a backup ZIP on demand.
  • ✅ Enable/disable automatic backups from system configuration.

⚙️ System Configuration

  • Business identity: Name, email, phone, address, social media.
  • Business hours per day of the week.
  • Measurement units: Customizable ("Kg", "Mts", "Packs", etc.).
  • Payment methods: Enable/disable cash, card, transfer, MercadoPago, PayPal, Stripe.
  • Base currency and USD exchange rate.
  • Taxes: Configurable global rate (e.g.: 21%).
  • Shipping: Enable/disable, free shipping threshold, shipping zones.
  • Loyalty points: Enable/disable, earn and redemption rates.
  • Branches: Enable/disable multi-branch support.
  • Stock control: Low and critical stock thresholds, overselling prevention, web safety stock.
  • Maintenance mode: Global switch that blocks public store access with custom page.

🛒 Point of Sale (POS) - Concurrency System

  • Atomic transactions: prisma.$transaction() ensures stock reservation and sale creation occur in the same database transaction, eliminating race conditions.
  • Idempotency: findRecentDuplicate() checks if an identical sale was created in the last few minutes, preventing duplicates from double-clicks or repeated submissions.
  • Physical Priority: POS sales can force stock deduction even if there are online reservations, ensuring a cashier can never be blocked from selling.
  • TTL reservations: Stock is temporarily reserved; if payment isn't completed, StockCleanupService automatically releases the units.
  • Automatic cleanup: cleanupAbandonedSales() finds PENDING sales older than 1 hour and cancels them, releasing reservations and reverting stock.
  • Bidirectional validation: Even though the frontend sends prices, the backend ignores them and recalculates everything (prices, discounts, taxes, shipping) from scratch, eliminating any possibility of fraud.

User Roles and Permissions (RBAC)

RoleAccessMain Capabilities
SUPER_ADMINFullSystem configuration, all user management, audit logs, security. Cannot be deleted.
ADMINHighProducts, sales, stock, discounts, suppliers, reports. Cannot create other ADMINs.
EMPLOYEELimitedPOS, view inventory, handle chat. Cannot modify products or prices.
CLIENTBasicBrowse, shop, profile, favorites, points. No admin panel access.

Permission Matrix

ModuleSUPER_ADMINADMINEMPLOYEECLIENT
Dashboard
Products / Categories
Sales (History)
Point of Sale (POS)
Inventory / Stock
Transfers
Purchases
Suppliers / Payments
Discounts / Coupons
Promotional Events
Shipping
Users
Reports
Web Content (CMS)
Chat / Support
System Alerts
Audit
Currencies / Gateways
General Settings

Backend API Modules

Core Services (42 services)

ServicePurpose
sale.service.jsComplete sales processing (1198 lines): idempotency, reservations, checkout, cleanup
price.service.jsMulti-currency price resolution (manual → automatic conversion)
currency.service.jsMulti-currency engine with Geo-IP (20+ currencies)
discount.service.jsDiscount engine with priorities and stacking rules
event.service.jsTemporary events that override system configuration
stock-movement.service.jsImmutable stock movement log
stock-transfer.service.jsInter-branch transfers
stock-cleanup.service.jsExpired reservation cleanup
payment.service.js + strategiesFactory Pattern for MercadoPago, PayPal, Stripe
payment-webhook.service.jsAsynchronous gateway webhook processing
invoice.service.jsPDF invoice generation
backup.service.jsFull database ZIP backups
audit.service.jsAdministrative action logging
logger.service.jsError logging with severity levels
blog.service.jsBlog article management
chat.service.jsReal-time chat system
in-app-notification.service.jsPersistent DB notifications
notification.service.jsEmail notifications
coupon.service.jsCoupon management and validation
shipping.service.jsZone-based shipping cost calculation
purchase.service.jsSupplier purchase orders
supplier.service.jsSupplier management
supplier-payment.service.jsSupplier payments
report.service.jsReport generation
cart.service.jsServer-side cart management
branch.service.jsBranch management
upload.service.jsCloudinary file uploads
category.service.jsHierarchical categories
product.service.jsProduct CRUD
sku.service.jsVariant management (SKUs)
comment.service.jsReviews and comments
user.service.jsUser management
auth.service.jsJWT authentication with refresh tokens

Special Controllers

ControllerPurpose
code-export.controller.jsBulk QR and barcode export to PDF (bwip-js)
webhook.controller.jsMercadoPago/Stripe/PayPal webhook reception
auto-response.controller.jsChatbot auto-response CRUD
system.controller.jsHealth checks and system status

Cron Jobs

CronFrequencyFunction
backup.cron.jsDaily 02:00 AMChecks config (DAILY/WEEKLY/MONTHLY) and executes backup ZIP
Stock CleanupPeriodicReleases expired reservations and cancels abandoned sales

Admin Panel Modules

31 Pages Organized by Section

Operations

  • /management - Dashboard with real-time KPIs
  • /sales - Point of Sale (POS) with search and scanner
  • /management/sales - Sales history with filters and details
  • /management/stock-control - Inventory control per branch
  • /management/transfers - Inter-branch stock transfers
  • /management/purchases - Supplier purchase orders
  • /management/supplier-payments - Supplier payments

Catalog

  • /management/products - Product listing and management
  • /management/products/[id] - Product detail and editing with SKUs
  • /management/categories - Hierarchical category tree
  • /management/suppliers - Supplier management

Commercial

  • /management/discounts - Discount engine with rules
  • /management/coupons - Coupon management
  • /management/events - Temporary promotional events
  • /management/shipping - Shipping zones and costs

Management

  • /management/users - User and role administration
  • /management/comments - Comment moderation
  • /management/reports - Reports and exports

Content (CMS)

  • /management/content - Banners, ads, marquee
  • /management/content/blog - Blog articles
  • /management/content/bot - Chatbot auto-responses
  • /management/content/chat - Real-time support (CX Inbox)

System

  • /management/settings - General business configuration
  • /management/settings/branches - Branch management
  • /management/settings/currencies - Currencies and exchange rates
  • /management/settings/gateways - Payment gateways
  • /management/system/alerts - System alerts and errors
  • /management/system/audit - Audit log

Frontend Features (Web Store)

Design & Visual Experience

  • 🎨 Premium design moving away from traditional minimalism, with gradients, glassmorphism and vibrant colors.
  • Advanced animations with Framer Motion in transitions, hover effects and micro-interactions.
  • 🎵 Ambient music player integrated into the experience.
  • 📱 Mobile-First design completely responsive.

Pages & Features (21 pages)

Home (/)

  • Animated Hero banner with promotional slider.
  • Product sections: Trending, New Arrivals, Recommended.
  • Featured reviews.
  • Navigation with real-time search.

Catalog (/products)

  • Advanced filtering: By category (tree), price range, attributes (size, color), search.
  • Sorting: lowest price, highest price, newest.
  • Responsive grid with entrance animations.

Product Detail (/products/[slug])

  • Image gallery with zoom.
  • Variant selector (color, size) with real-time stock.
  • Dynamic pricing with discount if applicable.
  • Related products.

Favorites (/favorites)

  • Add/remove favorite products.
  • Persistent wishlist.

User Profile (/profile)

  • Profile data: Personal information editing.
  • My purchases: Order history with statuses and PDF invoice download.
  • Points history: Loyalty points movements with current balance.
  • Comments and reviews: Published review history.

Cart (/cart)

  • Real-time synchronization with backend to prevent fraud and inconsistencies.
  • Redeem loyalty points as discount.
  • Apply discount coupons.
  • Select shipping type (pickup or home delivery with zone).
  • Select payment type (Stripe, PayPal, MercadoPago).
  • Stock verification before proceeding to checkout.

Checkout (/checkout)

  • Multi-step flow: Identification → Delivery → Payment → Confirmation.
  • Result pages: /checkout/success, /checkout/failure, /checkout/pending.

Real-Time Chat

  • Floating chat widget with Zendesk-style support.
  • Smart detection: if an admin/employee is online, it connects; otherwise, the bot responds.
  • Contextualization: sends the agent what the customer has in their cart.

Notifications

  • In-app notification system with history.
  • Real-time order status updates.

Blog (/blog)

  • Article listing with magazine-style design.
  • Individual article pages (/blog/[slug]).

FAQ (/faq)

  • Frequently asked questions with interactive accordions.
  • Common question search.

Contact (/contact)

  • Nearest branch locator: Uses the user's real-time geolocation to compare coordinates with branches and display the nearest one.
  • Contact form.

About (/about)

  • Business institutional page.

Authentication

  • Login with email and password.
  • New user registration.
  • Password recovery: Email sending with reset link.

Maintenance Mode & Errors

  • Automatic maintenance mode if unable to connect to the API or network.
  • User-friendly error notification system (non-technical).
  • Error pages with consistent visual design.

Technology Stack

Backend API

TechnologyPurpose
Node.js 20+Runtime environment
Express.js 5Web framework
PostgreSQL 13+Relational database
Prisma 7ORM and query builder
Socket.IO 4Real-time communication
MercadoPago SDKLATAM payment gateway
Stripe SDKGlobal payment gateway
PayPal SDKGlobal payment gateway
PDFKitPDF invoice generation
bwip-jsQR and barcode generation
CloudinaryCloud image storage
NodemailerTransactional email sending
node-cronScheduled tasks (backups, cleanup)
ArchiverZIP compression for backups

Frontend & Admin

TechnologyPurpose
Next.js 16React framework (App Router)
React 19UI library
TypeScript 5Statically typed JavaScript
TailwindCSS 4CSS framework
Zustand 5Client state management
TanStack Query 5Server state (cache, sync)
shadcn/uiPre-built UI components
RechartsInteractive charts (dashboard)
Framer MotionAdvanced animations
react-to-printThermal ticket printing
ZodSchema validation
React Hook FormForm management

System Architecture

mermaid
flowchart TB
    subgraph Presentation["Presentation Layer"]
        AdminPanel["Admin Panel<br/>(Next.js 16 + React 19)"]
        FrontendWeb["Customer Web<br/>(Next.js + TailwindCSS)"]
    end
    
    subgraph Application["Application Layer (42 Services)"]
        API["Express.js API<br/>Port 8000"]
        Socket["Socket.IO Server<br/>Real-Time"]
        Cron["Cron Jobs<br/>(Backups, Cleanup)"]
    end
    
    subgraph Data["Data Layer"]
        PostgreSQL[("PostgreSQL<br/>30+ Tables")]
    end
    
    subgraph External["External Services"]
        Cloudinary["Cloudinary<br/>(Images)"]
        MercadoPago["MercadoPago<br/>(LATAM Payments)"]
        Stripe["Stripe<br/>(Global Payments)"]
        PayPal["PayPal<br/>(Global Payments)"]
        SMTP["SMTP Server<br/>(Emails)"]
    end
    
    AdminPanel <-->|REST API + WS| API
    FrontendWeb <-->|REST API + WS| API
    
    API <-->|Prisma ORM| PostgreSQL
    
    API -->|Upload Images| Cloudinary
    API -->|Process Payments| MercadoPago
    API -->|Process Payments| Stripe
    API -->|Process Payments| PayPal
    API -->|Send Emails| SMTP
    Cron -->|Backup ZIP| PostgreSQL

Next Steps

For detailed information on specific aspects, see:

  1. Architecture - Design patterns, middleware pipeline.
  2. Admin Panel - Complete admin panel guide.
  3. Frontend Web - Store documentation.
  4. API Reference - Documented REST endpoints.
  5. Data Model - Database schema and relationships.
  6. Authentication & Security - JWT, RBAC, security measures.
  7. Flows & Diagrams - Sequence diagrams.
  8. Deployment - Production guide.

Last Updated: March 3, 2026. Status: ✅ COMPLETE, SECURE AND PRODUCTION-READY.