Veltacode
★ Featured

BiTi E-Commerce Platform

BiTi E-Commerce Platform is a robust, production-ready, full-stack e-commerce solution built with a monorepo. It encompasses a highly secure Spring Boot backend API, two Next.js web applications (an Admin Console and a Customer Storefront), and a cross-platform Flutter mobile app. The platform covers the full commerce lifecycle — from product catalog and multi-gateway payments, through marketing automation and CMS, to analytics and customer support — designed following Clean Architecture and Domain-Driven Design principles.

BiTi E-Commerce Platform

Project Details

System Architecture

The system operates across four deeply integrated applications using RESTful APIs, real-time WebSocket/STOMP, and Server-Sent Events. All core business logic, security, and persistence are centralized in the backend.

Admin Console  ─┐
Storefront     ├─ REST / WebSocket / SSE ──► Spring Boot Backend ──► PostgreSQL (Flyway through V098)
Mobile App     ─┘                                   │
                                                    ├─ Redis           OTP, token revocation, rate limiting, Spring Cache
                                                    ├─ WebSocket/STOMP Real-time admin notifications (/ws)
                                                    ├─ SSE             Live order status push (/api/orders/stream)
                                                    ├─ Storage         Local / Google Cloud Storage / Supabase
                                                    ├─ Stripe          Card payments + webhooks
                                                    ├─ PayPal          Redirect + capture + webhooks
                                                    ├─ Bakong KHQR     Cambodia QR payments (NBC)
                                                    ├─ ABA PayWay      Cambodia QR payments
                                                    └─ SMTP            Transactional email + PDF invoices + outbound webhooks

Core Operations

Identity & Security

  • JWT authentication (jjwt 0.12.6) with ROLE_* + PERM_* authority model and @PreAuthorize method security.
  • Role hierarchy: ROLE_SYSTEM_ADMIN > ROLE_ADMIN — super admin bypasses all role and permission checks.
  • IP-based rate limiting on auth endpoints via Bucket4j (Redis-backed in production; configurable capacity and refill window).
  • OTP-based email verification and password reset (memory or Redis backend, configurable TTL from admin settings).
  • Token refresh endpoint (/api/auth/refresh) — old JTI revoked in Redis on refresh.
  • Token revocation on logout — JTI stored in Redis until token expiry.
  • Google OAuth 2.0 sign-in for customers — backend verifies ID token with Google, auto-creates account, auto-verifies email; OAuth users can optionally add a local password.
  • AES-256-GCM encryption (EncryptionService) for all sensitive credentials stored in the database (payment gateway API keys, SMTP password) — zero plaintext secrets at rest.
  • Security headers filter, stateless sessions, BCrypt password hashing.
  • Admin user invite flow: admin creates user → invite link with expiring token → invitee sets own password.

Catalog & Inventory

  • Products with SKU, multi-image gallery, pricing, and flags (isNew/isFeatured/isSale).
  • Full product variant system: per-attribute values (color, size, etc.), per-variant pricing, stock, images, color codes, and description overrides.
  • Hierarchical category tree with slug-based access.
  • Inventory management with per-product stock quantities and configurable minimum stock thresholds.
  • Supplier purchase orders that auto-update inventory on receipt.
  • Product reviews and ratings from verified customers.
  • SEO meta fields (metaTitle, metaDescription) on products and blog posts; generateMetadata server layouts for Next.js SSR SEO.
  • Product Bundles — group products into discounted bundles; bundlesEnabled feature flag in store settings.

Cart & Checkout

  • Unified cart for authenticated users (/api/cart) and guests (localStorage + /api/orders/guest).
  • Multi-step checkout: Shipping → Payment → Review.
  • Configurable checkout fields: admins can enable/disable, relabel, reorder, and add custom fields per order; custom values persisted per order.
  • Coupon code validation at checkout: PERCENT or FIXED discount, min-order threshold, min-quantity, max-discount cap, usage limits, date windows.
  • Auto-applied promotions at checkout: BOGO, PERCENT_OFF, FIXED_OFF — scoped to product or category; usage tracked per customer.
  • Flash sale per-item discounts applied at checkout.
  • Backend enforces all pricing, tax, and shipping calculations from StoreSettings.
  • Saved address book — authenticated customers manage multiple shipping addresses (/api/customers/me/addresses): auto-default on first save, default promotion on delete, per-customer isolation; checkout prefills the default address.

Payments (4 Gateways)

  • Stripe — Stripe Elements (clientSecret flow), webhook-confirmed completion at /api/webhooks/stripe.
  • PayPal — redirect approval URL, manual or webhook capture at /api/webhooks/paypal.
  • Bakong KHQR — Cambodia National Bank QR standard; QR code generated, status polled at /api/payments/{id}/khqr/status.
  • ABA PayWay — ABA Bank QR payments; status polled at /api/payments/{id}/aba-payway/status.
  • All four gateways have matching guest endpoints at /api/payments/guest/**.
  • Gateway credentials managed securely via admin UI — encrypted at rest with AES-256-GCM; secret fields (secretKey, webhookSecret, apiKey, token) masked in the UI.
  • Refunds and payment cancellation supported across all gateways.
  • PDF invoices generated via iText 7 and emailed on payment completion.

Marketing & Promotions

  • Coupons — code-based discounts (PERCENT/FIXED) with full configuration including min-quantity guard.
  • Flash Sales — time-bounded category or product discounts; isCurrentlyActive() enforced at checkout.
  • Promotions — auto-apply rules (BOGO, PERCENT_OFF, FIXED_OFF); usage tracked per customer.
  • Deal of the Day — single active highlighted deal with countdown timer and custom deal image.
  • Banners — homepage hero/promo banners with image upload.
  • Abandoned cart recovery — automatic hourly emails to customers who left items in cart.
  • Wishlist notifications — daily emails when wishlisted products drop in price or come back in stock.

Branding & Appearance

  • Store logo upload — logo stored via pluggable storage; displayed dynamically in storefront header and mobile about page.
  • Admin panel branding — separate admin logo upload and custom admin panel name (shown in sidebar and browser tab).
  • Admin primary color — 8 presets + native color picker + hex input; applied at runtime via createAppTheme() factory without redeploy.
  • Storefront primary color — separate brand color for the customer-facing site; injected as --brand-primary and --brand-primary-rgb CSS variables via BrandColorInjector.
  • Sidebar theme — DARK or LIGHT mode toggle for the admin sidebar, persisted in StoreSettings.
  • Feature Bar (Trust Badges) — 4 configurable homepage trust badges; each badge has an icon (selected from the DB-backed icon_options table), title, description, and individual enable/disable toggle.

Analytics & Reporting

  • Dashboard — live KPI stats (orders, revenue, customers, products), revenue area chart (configurable day range), top-products bar chart, order-status pie chart (Recharts).
  • Reports — date-range filtered reports: Sales, Products, Customers, Payments, Inventory, Promotions.
  • Export — all reports available as CSV; Sales reports also as PDF (iText 7).

Blog CMS

  • Full blog content management: title, slug (auto-generated from title), excerpt, full rich-text content, cover image, author, category, DRAFT/PUBLISHED status, published date, view count.
  • TipTap rich text editor (v3) in admin — toolbar supports bold, italic, underline, headings, lists, blockquote, text alignment, links, inline image upload, undo/redo.
  • Blog images uploaded to /api/blog/content-image; stored via pluggable storage.
  • Dynamic blog categories — fetched from /api/blog/categories; admin can add new categories inline.
  • SEO meta fields (metaTitle, metaDescription) on every post.
  • Public read at /api/blog/public/**; full CRUD requires admin auth.

Contact & Support

  • Contact Messages — customers submit contact or support form submissions (source: CONTACT or SUPPORT); stored in contact_messages table.
  • Admin contact inbox at /dashboard/contact-messages — read/unread management, reply via mailto, delete; unread count badge in header.
  • Support Tickets — authenticated or guest ticket submission with subject, category, priority (LOW/MEDIUM/HIGH/CRITICAL).
  • Status lifecycle: OPENIN_PROGRESSRESOLVEDCLOSED.
  • Threaded messages per ticket for admin ↔ customer conversation.
  • Live chat — Tawk.to widget (property ID + chat ID configurable from admin Integrations settings, rendered by TawkToWidget component).

Notifications & Real-time

  • Transactional email via Spring Mail — SMTP host, port, username, and password (AES-256-GCM encrypted at rest) configurable at runtime from admin settings; no redeploy needed.
  • Notification flagsemailNotifications, pushNotifications, and orderUpdates flags in StoreSettings guard all email dispatch and in-app notification creation.
  • Outbound webhooks — configurable URL for order created, payment success, and status changes.
  • SSE — live order status push at /api/orders/stream?token=....
  • WebSocket/STOMP — SockJS endpoint at /ws with /topic broker; admin panel subscribes for real-time bell notifications, and per-user notifications are pushed to /topic/notifications/{userId} (consumed by the admin bell and the mobile app).
  • In-app notifications — persistent Notification records per user; surfaced in the admin header bell and the mobile notifications screen, delivered live over STOMP.
  • Newsletter — email capture with fully configurable section (title, subtitle, perks, stats, community text) managed entirely from admin settings.

Shipping, Tax & Currency

  • Shipping zones — JSONB country lists, base rate, per-kg rate, free-above threshold.
  • Country tax rates — per-country rate overrides stored in the database.
  • Global fallbacks — flat rate, free-shipping threshold, and global tax rate in StoreSettings.
  • Multi-currency — currency code, symbol, and position (BEFORE/AFTER) configurable per store; exchange rates managed in the database; storefront CurrencyContext converts prices client-side.
  • Language switcherLanguageContext groundwork in storefront for full i18n.

Scheduled Automation

  • Abandoned cart recovery — hourly.
  • Low stock alerts (email admin + create persistent admin notification) — hourly.
  • Wishlist price-drop and restock notifications — daily at 9 AM.

Automation Testing & Quality (All Four Apps)

  • Backend — Maven Surefire runs fast unit/slice tests (*Test); Failsafe runs Docker-backed integration tests (*IT) on Testcontainers PostgreSQL, validating Flyway migrations from an empty database. Shared infrastructure provides MockMvc auth helpers, DB cleanup, reusable test data, and deterministic fakes for storage, mail, Redis token/OTP paths, websocket notifications, and payment gateways. JaCoCo enforces a coverage ratchet gate that cannot regress.
  • Admin & Storefront — Vitest + React Testing Library for unit/component tests (jsdom, v8 coverage with seeded ratchet thresholds) and Playwright for hermetic end-to-end journeys (login/validation, checkout navigation) on the pinned dev ports.
  • Mobileflutter_test + mocktail cover fromJson parsing, domain services, and ChangeNotifier controller state transitions; an integration_test smoke harness validates on-device boot.
  • Hermetic by design — real Stripe, PayPal, ABA PayWay, KHQR, GCS/Supabase/S3, SMTP, Redis, webhook, and websocket calls are mocked or faked; frontend/mobile network is stubbed.
  • CI — four path-filtered GitHub Actions workflows (backend, admin, storefront, mobile), each gating its app and uploading coverage/test-report artifacts. Strategy documented in docs/testing-strategy.md.

Multi-store & RBAC

  • Multi-storeStore domain; products and data are scoped per store.
  • Dynamic sidebar menus — menus and sub-menus stored in the database, linked to required permissions; admin sidebar built from /api/menus/tree/my filtered per user's roles.
  • Hyper-granular permissions — 70+ PERM_* authorities across catalog, orders, payments, reports, settings, and more; roles are fully configurable from the admin UI.

Tech Stack

1. Backend (/backend)

LayerTechnology
CoreJava 21, Spring Boot 3.5.6, Spring Security, Spring Data JPA
DatabasePostgreSQL 16, Flyway migrations through V098, Hibernate + vladmihalcea JSONB
CacheRedis (OTP, token revocation, Bucket4j rate-limit buckets, Spring Cache)
SecurityJWT (jjwt 0.12.6), Bucket4j 8.10.1, AES-256-GCM (EncryptionService), BCrypt
Real-timeSpring WebSocket/STOMP (SockJS), Server-Sent Events
PaymentsStripe SDK 26, PayPal SDK 2.0, Bakong KHQR, ABA PayWay
StorageGoogle Cloud Storage 2.42, Supabase, Local FS (pluggable via StorageService)
EmailSpring Mail (SMTP, runtime-configurable)
PDFiText 7.2.5 (invoices + report exports)
API DocsSpringdoc OpenAPI 2.6 (Swagger UI at /swagger)
TestingJUnit 5, Mockito, Spring Security Test, Testcontainers PostgreSQL, Surefire/Failsafe, JaCoCo ratchet
CIGitHub Actions backend workflow with JUnit and JaCoCo artifacts
DXMapStruct 1.6.3, Lombok 1.18.34, Sentry, Spring Actuator

2. Admin Console (/admin)

LayerTechnology
FrameworkNext.js 16.0.10 (App Router), React 19, TypeScript
UIMaterial UI v7, Emotion
ChartsRecharts 2
EditorTipTap v3 (rich text: blog content with image upload)
State & DataTanStack Query 5, Zustand 5, Axios
FormsReact Hook Form 7, Zod 4
Real-timeSTOMP.js 7, SockJS
Error TrackingSentry (@sentry/nextjs)
TestingVitest + React Testing Library (unit/component), Playwright (E2E)

3. Customer Storefront (/storefront)

LayerTechnology
FrameworkNext.js 16.0.10 (App Router), React 19, TypeScript
UITailwind CSS v4, Framer Motion 12, Lucide React
CarouselsSwiper 12
State & DataTanStack Query 5, Axios
PaymentsStripe React JS + Stripe.js
Brand ThemingBrandColorInjector injects --brand-primary CSS vars from store settings
Live ChatTawk.to widget (TawkToWidget)
Error TrackingSentry (@sentry/nextjs)
TestingVitest + React Testing Library (unit/component), Playwright (E2E)

4. Mobile App (/mobile)

LayerTechnology
FrameworkFlutter SDK >=3.3.4, Dart
StateProvider + ChangeNotifier controllers (flutter_bloc also available)
ArchitectureClean Architecture, get_it, injectable, dartz
NetworkingDio 5
Storageflutter_secure_storage, shared_preferences
Paymentsflutter_stripe 9
Navigationgo_router 14
Mediacached_network_image, image_picker, webview_flutter
Modelsfreezed, json_serializable
QR & Real-timeqr_flutter (KHQR/ABA QR), stomp_dart_client (STOMP), SSE order stream
Error TrackingSentry (sentry_flutter)
Testingflutter_test + mocktail (unit/controller), integration_test (smoke)

Mobile feature parity: full checkout across all gateways — Stripe, PayPal, Bakong KHQR & ABA PayWay (in-app QR sheet with live status polling), and Cash on Delivery; backend-backed saved address book; live order tracking via SSE; real-time notifications via STOMP (/topic/notifications/{userId}); FAQ + Contact Us; secure token storage with automatic 401 refresh; build-time API base URL via --dart-define.


How to Use It

Default admin login (seeded): [email protected] / sysadmin@2026

Mobile: Open /mobile in an IDE with Flutter configured. Point the API base URL to your machine's LAN IP (e.g., http://192.168.x.x:1221) and run flutter run.


Production Deployment

The platform is containerised end-to-end and ships with first-class self-hosting:

  • Single-VPS deploy (Hostinger Ubuntu / any Docker host) — all four services behind a Caddy reverse proxy with automatic Let's Encrypt HTTPS on three subdomains (api / admin / store). Postgres and Redis are bound to loopback only; the public surface is just ports 80/443. Uploads persist on a named volume. Full runbook in docs/DEPLOY_VPS.md.
  • One-command, data-safe deploysdeploy.sh pulls the latest code, rebuilds the images, waits on the backend healthcheck, and prunes dangling layers without ever touching the Postgres or uploads volumes. Production overlay: docker-compose.prod.yml.
  • Real-time-aware proxying — the Caddy config explicitly proxies the SSE order stream (/api/orders/stream) and the WebSocket/STOMP endpoint (/ws) unbuffered, so live order status and the admin notification bell work through TLS.
  • Optional GHCR CI/CD — on a version tag (v*) or manual dispatch, a GitHub Actions matrix builds and pushes the three images to GitHub Container Registry; the server then runs prebuilt, SHA-tagged images (docker-compose.deploy.yml) for zero-build, instant-rollback releases. Documented in docs/DEPLOY_CICD.md.
  • Managed alternative — Render (backend) + Vercel (frontends) via render.yaml / GUIDE.md, and a Cloudflare-fronted variant.

Roadmap & Enhancements

The BiTi E-Commerce Platform is feature-complete and production-ready. Identified areas for future enterprise growth:

  • Advanced Shipping Integration — dynamic carrier rates via EasyPost/ShipStation to complement the existing zone-based shipping engine.
  • Automated Tax Calculation — Stripe Tax or TaxJar integration for real-time location-based tax on top of the existing country rate overrides.
  • Analytics Expansion — customer acquisition funnels, conversion rate analysis, and cohort reporting in the admin analytics section.
  • Global Localization — full i18n translation files (the LanguageContext groundwork is already in place in the storefront) and live exchange rate API integration for dynamic currency switching.
  • Mobile Push Notifications — FCM/APNs push for order status updates as a complement to the existing in-app and email notifications.