Skip to main content

Store Module

The Store Module provides a comprehensive e-commerce and subscription management system, powered by Stripe integration, for selling digital marketing services to agencies and their sub-accounts. It orchestrates the complete commerce lifecycle from product catalog management through cart operations, checkout, subscription management, order fulfillment, and ongoing subscription lifecycle.

Module Overview​

The Store module serves as DashClicks' primary revenue engine, enabling agencies to:

  • Browse and purchase digital marketing services (Facebook Ads, Google Ads, Content, SEO, Websites)

  • Manage recurring subscriptions with flexible billing intervals

  • Track order fulfillment and onboarding progress

  • Apply promotional codes and loyalty discounts

  • Handle payment methods and billing operations

The Store service powers DashClicks commerce at /v1/store, orchestrating Stripe products, carts, subscriptions, orders, analytics, and discount tooling from a single Express router.

  • Create white-label storefronts with connected Stripe accounts

🎯 Overview​

Store Submodules​

🎯 Overview​

πŸ”„ Subscription Management​

The Store module is DashClicks' comprehensive e-commerce and subscription management system, providing a Stripe-integrated platform for selling digital services to agencies and their sub-accounts. It orchestrates the complete commerce lifecycle from product catalog browsing through cart management, checkout, subscription creation, order fulfillment, and ongoing subscription management.

Core Subscription Operations​

  • Entrypoint: internal/api/v1/store/index.js

  • Subscription creation with Stripe integration and application fee calculation

  • Subscription retrieval with filtering and website reactivation statusFile Path: internal/api/v1/store/- Key responsibilities:

  • Subscription upgrades, downgrades, and cancellations

  • Payment retry with rate limiting (3 attempts per 24 hours) - Maintain a Stripe-first catalog while mirroring products and prices into Mongo for fast reads.

  • Subscription feedback collection

  • Software downgrade with resource cleanup queuesPrimary Purpose: Enable agencies to purchase and manage recurring digital marketing services (Facebook Ads, Google Ads, Content, SEO, Websites, etc.) with support for complex pricing models, loyalty programs, bundles, and white-label fulfillment. - Orchestrate carts, invoice previews, and checkout flows for partners and their sub-accounts.

  • Bundle subscription management with atomic cancellation

  • Subscription notification preferences - Manage subscription lifecycles, downgrade workflows, and fulfilment queues backed by Stripe metadata.

πŸ›’ Cart Management​

Key Business Value: - Surface order progress, onboarding timelines, and revenue analytics.

Shopping Cart & Checkout Operations​

  • Multi-tiered pricing support (Partner vs Standard accounts)

  • Provide connected-account coupons, platform promo codes, wallet reloads, and payment method management

  • Add items to cart with validation and bundle support

  • Loyalty program integration with automatic discounts

  • Cart aggregation with Stripe invoice preview

  • Checkout processing with subscription creation and locking mechanism

  • Bundle management for package deals

πŸ“ Directory Structure​

  • Direct single-item purchase without cart

  • Promotional code application and validation

  • Connected Stripe account support for white-label storefronts

  • Sub-account creation during checkout

  • Onboarding workflow integration

  • Comprehensive order and subscription lifecycle management

  • Fulfillment job queueing

  • Automated fulfillment orchestration via queues and webhooks internal/api/v1/store/

πŸ“¦ Order Management​

β”œβ”€β”€ index.js # Router wiring + shared middleware

Order Tracking & Fulfillment​

πŸ“ Directory Structureβ”œβ”€β”€ Controllers/ # Feature controllers (Stripe + Mongo orchestration)​

  • Order retrieval with advanced filtering and pagination

  • Product-specific fulfillment timeline generationβ”‚ β”œβ”€β”€ product.js

  • Onboarding status tracking (pending β†’ verification β†’ approved)

  • Order invoice retrieval```β”‚ β”œβ”€β”€ price.js

  • Typeform integration for onboarding forms

  • Website reactivation eligibility checkinginternal/api/v1/store/β”‚ β”œβ”€β”€ cart.js

  • Order status progression tracking

β”œβ”€β”€ πŸ“„ index.js - Main router with middleware and route mountingβ”‚ β”œβ”€β”€ subscription.js

πŸ“‹ Product Management​

β”œβ”€β”€ πŸ“„ countryCodes.json - Country code reference dataβ”‚ β”œβ”€β”€ order.js

Product Catalog & Pricing​

β”œβ”€β”€ πŸ“„ README.md - Module documentationβ”‚ β”œβ”€β”€ reporting.js

  • Product catalog with loyalty program adjustments

  • Custom product creation for connected accountsβ”œβ”€β”€ πŸ“‚ Controllers/ - Business logic and Stripe orchestrationβ”‚ β”œβ”€β”€ paymentMethods.js

  • Price tier management and creation

  • Platform type filtering (dashclicks, default, custom)β”‚ β”œβ”€β”€ πŸ“„ product.js - Product catalog managementβ”‚ β”œβ”€β”€ payment-intent.js

  • Pricing type filtering (partner wholesale vs standard retail)

  • Product and price lifecycle managementβ”‚ β”œβ”€β”€ πŸ“„ price.js - Pricing tier managementβ”‚ β”œβ”€β”€ charge.js

  • Bundle and offer integration

  • Version management for API compatibilityβ”‚ β”œβ”€β”€ πŸ“„ cart.js - Shopping cart and checkout logicβ”‚ β”œβ”€β”€ coupon.js / promocode.js

Technical Architectureβ”‚ β”œβ”€β”€ πŸ“„ subscription.js - Subscription lifecycle managementβ”‚ └── …​

Directory Structureβ”‚ β”œβ”€β”€ πŸ“„ order.js - Order tracking and fulfillment└── Routes/ # Express routers + Joi schemas​


internal/api/v1/store/

β”œβ”€β”€ index.js # Main router with middlewareβ”‚ β”œβ”€β”€ πŸ“„ invoice.js - Invoice retrieval and management β”œβ”€β”€ cart.js

β”œβ”€β”€ README.md # Module documentation

β”œβ”€β”€ Controllers/ # Request handlers (22 controllers)β”‚ β”œβ”€β”€ πŸ“„ paymentMethods.js - Payment method CRUD β”œβ”€β”€ subscription.js

β”‚ β”œβ”€β”€ subscription.js # Subscription lifecycle (2000+ lines)

β”‚ β”œβ”€β”€ cart.js # Cart and checkout (3655 lines)β”‚ β”œβ”€β”€ πŸ“„ payment-intent.js - Payment intent handling β”œβ”€β”€ order.js

β”‚ β”œβ”€β”€ order.js # Order tracking (3197 lines)

β”‚ β”œβ”€β”€ product.js # Product catalog managementβ”‚ β”œβ”€β”€ πŸ“„ charge.js - Direct charge operations β”œβ”€β”€ reporting.js

β”‚ β”œβ”€β”€ price.js # Price tier management

β”‚ β”œβ”€β”€ customer.js # Stripe customer operationsβ”‚ β”œβ”€β”€ πŸ“„ coupon.js - Coupon management β”œβ”€β”€ paymentMethods.js / payment-intent.js / charge.js

β”‚ β”œβ”€β”€ paymentMethods.js # Payment method management

β”‚ β”œβ”€β”€ payment-intent.js # Payment intent handlingβ”‚ β”œβ”€β”€ πŸ“„ promocode.js - Promotional code handling └── coupon.js / promocode.js

β”‚ β”œβ”€β”€ charge.js # Direct charge operations

β”‚ β”œβ”€β”€ coupon.js # Coupon managementβ”‚ β”œβ”€β”€ πŸ“„ refund.js - Refund processing```

β”‚ β”œβ”€β”€ promocode.js # Promo code operations

β”‚ β”œβ”€β”€ refund.js # Refund processingβ”‚ β”œβ”€β”€ πŸ“„ dispute.js - Dispute management

β”‚ β”œβ”€β”€ dispute.js # Dispute handling

β”‚ β”œβ”€β”€ invoice.js # Invoice managementβ”‚ β”œβ”€β”€ πŸ“„ reporting.js - Revenue and subscription analytics> πŸ›‘οΈ Every route layers `verifyAuthorization`, `verifyAccessAndStatus`, and scope checks before reaching controller logic. Several routes also inject loyalty tier context via `getLoyaltyProgramTier`.

β”‚ β”œβ”€β”€ reporting.js # Revenue analytics

β”‚ β”œβ”€β”€ webhook.js # Stripe webhook handlersβ”‚ β”œβ”€β”€ πŸ“„ account.js - Account-level store configuration

β”‚ β”œβ”€β”€ import.js # Bulk data import

β”‚ β”œβ”€β”€ account.js # Store configurationβ”‚ β”œβ”€β”€ πŸ“„ webhook.js - Stripe webhook event handling## �️ MongoDB Collections

β”‚ β”œβ”€β”€ stripe-subscription.js # Stripe-specific operations

β”‚ └── ... # Additional controllersβ”‚ └── πŸ“„ import.js - Bulk data import utilities

β”œβ”€β”€ Routes/ # Route definitions with validation

β”‚ β”œβ”€β”€ subscription.js # Subscription routes with Joi schemas└── πŸ“‚ Routes/ - Express route definitions with validation> πŸ“š **Schema details** live in the shared models under `/shared/models`. This section highlights how the Store module uses each collection.

β”‚ β”œβ”€β”€ cart.js # Cart routes with validation

β”‚ β”œβ”€β”€ order.js # Order routes β”œβ”€β”€ πŸ“„ product.js - Product API routes

β”‚ └── ... # Other route modules

β”œβ”€β”€ models/ # Copied from /shared/models (Git-ignored) β”œβ”€β”€ πŸ“„ cart.js - Cart API routes| Collection | Model | Primary use |

β”‚ β”œβ”€β”€ store-subscription.js

β”‚ β”œβ”€β”€ store-order.js β”œβ”€β”€ πŸ“„ subscription.js - Subscription API routes| --- | --- | --- |

β”‚ β”œβ”€β”€ store-cart.js

β”‚ β”œβ”€β”€ store-product.js β”œβ”€β”€ πŸ“„ order.js - Order API routes| `_store.products` | `shared/models/store-product.js` | Stripe product mirror with catalog metadata and bundle flags. |

β”‚ β”œβ”€β”€ store-price.js

β”‚ └── ... # 10+ store models β”œβ”€β”€ πŸ“„ paymentMethods.js - Payment method routes| `_store.prices` | `shared/models/store-price.js` | Stripe price mirror, loyalty-aware metadata, recurring intervals. |

└── utilities/ # Copied from /shared/utilities (Git-ignored)

β”œβ”€β”€ stripe.js └── πŸ“‚ schemas/ - Joi validation schemas| `_store.cart` | `shared/models/store-cart.js` | Pending cart rows, promo placeholders, onboarding invite settings, checkout lock. |

β”œβ”€β”€ webhooks.js

└── ... # Shared utilities```| `_store.subscriptions` | `shared/models/store-subscription.js` | Subscription snapshot enriched with action metadata for fulfilment. |

| _store.orders | shared/models/store-order.js | Order lifecycle, onboarding state, fulfilment tasks, Stripe invoice linkage. |

⚠️ CRITICAL: The models/ and utilities/ folders in this service are:

  • Automatically copied from /shared/models/ and /shared/utilities/## πŸ—„οΈ MongoDB Collections| _store.invoices | shared/models/store-invoice.js | Paid invoice mirror used for reporting and order history. |

  • Listed in .gitignore - changes are NOT tracked by Git

  • Overwritten on every build or shared file copy operation| _store.coupons / _store.promo.codes | shared/models/store-coupon.js, shared/models/store-promo-code.js | Connected-account coupons and platform promotion codes. |

  • NEVER edit these folders directly - always edit /shared/ instead

πŸ“š Detailed Schema: See Database Collections Documentation| _store.disputes / _store.refunds | shared/models/store-dispute.js, shared/models/store-refund.js | Adjustments that feed Store analytics. |

MongoDB Collections Overview​

| _store.onebalance, _store.onebalance-usage_logs | Wallet balance + audit trail for reloads. |

The Store module interacts with 10+ MongoDB collections:

_store.products| _accounts, crm.contacts | Account hierarchy, buyers, and contact context used across carts, orders, and subscriptions. |​

Core Store Collections​

  • Purpose: Product catalog mirroring Stripe products with enriched metadata| queues | shared/models/queues.js | Async jobs spawned during subscription changes, downgrades, or fulfilment hand-offs. |

| Collection | Model File | Purpose |

|------------|-----------|---------|- Model: shared/models/store-product.js

| _store.products | shared/models/store-product.js | Product catalog with metadata |

| _store.prices | shared/models/store-price.js | Pricing tiers with billing intervals |- Primary Use: Store product listings, bundle definitions, platform/custom product types## πŸ—οΈ Architecture Overview

| _store.subscriptions | shared/models/store-subscription.js | Active subscriptions with Stripe mirrors |

| _store.orders | shared/models/store-order.js | Order records linking subscriptions to fulfillment |

| _store.cart | shared/models/store-cart.js | Shopping cart items and promo codes |

| _store.invoices | shared/models/store-invoice.js | Invoice records and payment history |### _store.pricesKey responsibilities

| _store.promo.codes | shared/models/store-promo-code.js | Promotional codes and coupons |

| _store.subscription-feedback | shared/models/store-subscription-feedback.js | Cancellation feedback |- Purpose: Price tiers for products with loyalty and setup fee metadata

| _store.reporting | shared/models/store-reporting.js | Revenue metrics and analytics |

| _store.dispute | shared/models/store-dispute.js | Stripe dispute records |- Model: shared/models/store-price.js- Provide a Stripe-first commerce layer that still works for partners without direct Stripe access (via connected accounts).

| Collection | Purpose |- Enforce account scoping, loyalty tier adjustments, and bundle integrity consistently across endpoints.

|------------|---------|

| _accounts, crm.contacts | Account hierarchy and contact information |### _store.cart- Emit onboarding, downgrade, and provisioning tasks over queues and Pub/Sub when subscription state changes.

| stripe.keys | Connected account Stripe credentials |

| _loyalty.program.orders | Loyalty program order tracking |- Purpose: Temporary cart items during shopping session

| projects-typeforms | Onboarding form requests |

| queues | Background fulfillment jobs |- Model: shared/models/store-cart.jsDesign decisions

Key System Capabilities- Primary Use: Cart management, invoice preview aggregation, checkout locking​

Multi-Tenant Commerce- Stripe-first mutations: Controllers talk to Stripe first, then persist mirrorsβ€”ensuring Stripe remains the source of truth.​

  • Account Hierarchy: Parent-child relationships with permission inheritance### _store.subscriptions- Account-aware filtering: Queries always scope by account_id, pricing_type, and platform_type to avoid data leaks between agencies.

  • Pricing Tiers: Partner (wholesale) vs Standard (retail) pricing

  • Platform Types: DashClicks platform, default templates, custom products- Purpose: Active and historical subscriptions with Stripe mirror data- Shared utilities: Helpers such as getLoyaltyProgramTier, generateFilterObj, and withTransaction keep business rules centralized.

  • Connected Accounts: White-label storefronts with Stripe Connect

  • Model: shared/models/store-subscription.js- Checkout locking: A sentinel cart document prevents concurrent checkouts, reducing race conditions with Stripe invoices.

Stripe-First Architecture​

  • Primary Use: Subscription lifecycle, cancellations, upgrades/downgrades, fulfillment metadata- Guarded bundles & software SKUs: Special metadata flags enforce mutual exclusivity and downstream provisioning rules.

  • Mutation Pattern: All changes made in Stripe first, then mirrored to MongoDB

  • Webhook Sync: Stripe webhooks keep MongoDB in sync with Stripe state

  • Application Fees: Automatic calculation for connected accounts

  • Invoice Preview: Real-time invoice calculation from Stripe### _store.orders## πŸ”— Submodules

Advanced Features- Purpose: Order records linking subscriptions to fulfillment workflows​

  • Loyalty Programs: Automatic discount application based on account tier- Model: shared/models/store-order.js### Core commerce flows

  • Bundle Management: Multi-product packages with atomic operations

  • Checkout Locking: Prevents concurrent checkouts creating duplicate subscriptions- Primary Use: Track onboarding progress, fulfillment status, order history

  • Software Exclusivity: Enforces single active software subscription per account

  • Payment Retry: Rate-limited retry attempts (3 per 24 hours)- πŸ“˜ products.md β€” Product and price APIs, catalog visibility rules, loyalty adjustments.

  • Downgrade Queues: Resource cleanup jobs for service downgrades

_store.invoices- πŸ“— pricing.md β€” Price CRUD details, account pricing types, setup fee handling.​

Core Data Flows​

  • Purpose: Invoice mirror from Stripe for reporting and history- πŸ›’ cart.md β€” Cart aggregation, invoice previews, checkout helper internals.

Purchase Flow​

  • Model: shared/models/store-invoice.js- πŸ’³ checkout.md β€” Payment method CRUD, wallet reloads, digital wallet setup.

graph TD- **Primary Use**: Financial reporting, invoice history, payment tracking- πŸ” **[`subscriptions.md`](./subscriptions)** β€” Stripe subscription creation, change management, downgrade workflows.

A[Browse Products] --> B[Add to Cart]

B --> C[View Cart with Invoice Preview]

C --> D{Apply Promo?}

D -->|Yes| E[Validate Promo Code]### `_store.promo.codes`### Supporting surfaces

D -->|No| F[Proceed to Checkout]

E --> F- **Purpose**: Promotional codes for discounts during checkout

F --> G[Create Checkout Lock]

G --> H{New Business?}- **Model**: `shared/models/store-promo-code.js`- πŸ“¦ **[`orders.md`](./orders)** β€” Order listings, onboarding timelines, status updates, resend flows.

H -->|Yes| I[Create Sub-Account]

H -->|No| J[Group by Billing Interval]- **Primary Use**: Apply promo codes to carts, track promo usage- 🎟️ **[`discounts.md`](./discounts)** β€” Coupon and promo code management for connected accounts.

I --> J

J --> K[Create Stripe Subscriptions]- πŸ“ˆ **[`analytics.md`](./analytics)** β€” Revenue and subscription reporting aggregates.

K --> L[Apply Loyalty Discounts]

L --> M[Generate Orders]## πŸ—οΈ Architecture Overview- πŸ“¦ **[`inventory.md`](./inventory)** β€” Catalog import helpers used by partner storefronts.

M --> N[Queue Fulfillment Jobs]

N --> O[Send Onboarding Invites]

O --> P[Clear Cart & Lock]

P --> Q[Return Subscriptions]The Store module follows a **Controller-Route pattern** with Stripe-first mutations and MongoDB mirrors for fast queries.## πŸ”„ Data Flow

Subscription Lifecycle​

Key Responsibilities```mermaid​


graph TDflowchart TD

A[Active Subscription] --> B{Action}

B -->|Upgrade| C[Change to Higher Tier]1. **Product Catalog Management**: Maintain Stripe product/price catalog with platform-specific visibility A[Dashboard UI] -->|Add item| B[/v1/store/cart]

B -->|Downgrade| D[Schedule Downgrade]

B -->|Cancel| E[Set cancel_at_period_end]2. **Cart & Checkout Orchestration**: Multi-item cart with invoice preview, promo codes, and checkout locking B --> C[cartController.newCartItem]

B -->|Payment Failed| F[Mark past_due]

C --> G[Immediate Change in Stripe]3. **Subscription Lifecycle**: Create, upgrade, downgrade, cancel, and reactivate subscriptions C --> D[_store.cart]

D --> H[Queue Resource Cleanup]

E --> I{Undo Cancel?}4. **Order Fulfillment**: Link subscriptions to orders with onboarding and setup tracking D -->|Preview| E[cartController.getCartItems]

F --> J[Retry Payment 3x]

I -->|Yes| K[Clear cancel_at_period_end]5. **Payment Processing**: Handle payment methods, payment intents, charges, refunds E --> F[/v1/store/cart/checkout]

I -->|No| L[Cancel at Period End]

J -->|Success| A6. **Webhook Integration**: Sync Stripe events to local database and trigger fulfillment workflows F --> G[cartController.checkout]

J -->|Failure| M[Subscription Canceled]

```7. **Reporting & Analytics**: Revenue, MRR, churn, and subscription metrics G --> H((Stripe))



### Order Fulfillment Flow H --> I[_store.subscriptions]



```mermaid### Design Decisions H --> J[_store.orders]

graph TD

A[Order Created] --> B{Requires Onboarding?} I --> K[queues downgrade/offboarding]

B -->|Yes| C[Create Typeform Request]

B -->|No| D[Queue Fulfillment Job]**Stripe-First Architecture** J --> L[NotificationQueue / PubSub]

C --> E[Send Onboarding Invite]

E --> F{Form Submitted?}- All mutations happen in Stripe first, then mirrored to MongoDB```

F -->|No| G[Status: pending]

F -->|Yes| H[Status: verification]- Stripe remains source of truth for billing and payment state

H --> I{Issues Found?}

I -->|Yes| J[Status: issues, Request Revision]- Local mirrors enable fast queries without Stripe API rate limits## πŸ” Configuration & Dependencies

I -->|No| K[Status: approved]

J --> F

K --> D

D --> L[Process by Product Type]**Multi-Tenancy via Platform Types**| Variable | Description | Required |

L --> M[Update Timeline]

M --> N[Complete Fulfillment]- `dashclicks`: Platform products available to all agencies| --- | --- | --- |

  • default: White-label products from parent accounts| STRIPE_SECRET_KEY | Platform Stripe key for main accounts. | βœ… |

Configuration​

  • custom: Custom products created by agencies| SETUP_PRODUCT | Stripe product ID used for setup fee invoice items. | βœ… |

Environment Variables​

| BASE_CURRENCY | Base currency for OneBalance conversions. | βœ… |


# Stripe Configuration**Pricing Type Flexibility**| `APP_SECRET` | JWT signing secret for temporary checkout tokens. | βœ… |

STRIPE_SECRET_KEY=sk_live_xxx # Platform Stripe key

STRIPE_WEBHOOK_SECRET=whsec_xxx # Webhook signature secret- `partner`: Wholesale pricing for agencies| `API_BASE_URL` | Internal API base URL used for Twilio number search and service calls. | βœ… |



# Application Fees (Connected Accounts)- `standard`: Retail pricing for end clients

ADDITIONAL_APP_FEE_PERCENTAGE=0.029 # 2.9% platform fee

ADDITIONAL_APP_FEE_SUBSCRIPTION_PERCENTAGE=0.001 # 0.1% subscription fee- Setup fees vary by pricing typeDependencies of note: `stripe`, `axios`, `moment`, `jsonwebtoken`, `@google-cloud/pubsub`, and shared utilities under `/shared/utilities`.



# Cart Configuration

MAX_CART_ITEMS=60 # Maximum items per cart

**Checkout Locking Mechanism**## πŸš€ Quick Start

# Payment Retry

MAX_PAYMENT_RETRY_ATTEMPTS=3 # Maximum retry attempts- Sentinel document prevents concurrent checkout operations

PAYMENT_RETRY_WINDOW_HOURS=24 # Retry window in hours

- Reduces race conditions with Stripe invoice creation- Run `npm run dev:build` at the repo root to link shared utilities and models.

# Checkout Configuration

CHECKOUT_LOCK_TIMEOUT_MINUTES=10 # Checkout lock expiration- Use the β€œStart All” VS Code launch configuration to boot the Store service alongside dependencies.

πŸ”— Submodules- Ensure the .env includes the Stripe credentials above before exercising cart or subscription flows.​

Middleware Chain​

The Store router applies these middlewares to all routes:

Core Commerce Services## ⚠️ Operational Guardrails​


router.use(- πŸ“˜ **Product Management *(link removed - file does not exist)*** - Catalog browsing, product CRUD, visibility rules

verifyAuthorization, // JWT authentication

verifyAccessAndStatus, // Account status check- πŸ“— **[Cart Management](./cart.md)** - Add to cart, aggregation, invoice preview, checkout- Payment endpoints enforce `PAYMENTS_NOT_ENABLED`, `STRIPE_ACCOUNT_NOT_FOUND`, or `STORE MISCONFIGURED` before hitting Stripe.

getLoyaltyProgramTier // Loyalty tier resolution

);- πŸ” **[Subscription Management](./subscriptions.md)** - Create, update, cancel, reactivate subscriptions- Bundle metadata enforces single occurrence per buyer, and software SKUs clear competing cart rows.

  • πŸ“¦ Order Management (link removed - file does not exist) - Order listing, timeline tracking, fulfillment status- Checkout locks prevent overlapping Stripe invoice calls; callers must clear locks via clearCartAfterPayment on completion.

Getting Started​

  • πŸ’³ Customer Management - Stripe customer operations- Connected accounts inherit loyalty data from their parent via getLoyaltyProgramTier so invoices and totals stay consistent.

Quick Navigation​

Each submodule contains detailed documentation including:

  • API Endpoints: Complete endpoint listings with request/response schemas

  • Service Methods: Detailed method documentation with business logic### Payment Services

  • Workflows: Visual workflow diagrams showing process flows

  • Technical Implementation: Architecture details and patterns- πŸ’³ Payment Methods - Payment method CRUD operations- ./cart.md Β· ./checkout.md for purchase orchestration.

  • MongoDB Collections: Database schema and relationships

  • πŸ’΅ Payment Intents - Payment intent handling- ./subscriptions.md for lifecycle management and downgrade queues.

Common Use Cases​

  • πŸ’Έ Charges - Direct charge operations- ./analytics.md for revenue and churn reporting built on Store data.

Setting Up Product Catalog​

  • πŸ”„ Refunds - Refund processing
  1. Platform Products: Browse products via Product Management

  2. Custom Products: Create custom products for white-label stores

  3. Price Tiers: Configure pricing with partner/standard tiers### Discount & Pricing

  4. Bundles: Create product bundles for package deals- 🎟️ Coupons - Coupon management

  • 🏷️ Promo Codes - Promotional code handling
  1. Cart Management: Add items through Cart Management### Analytics & Admin

  2. Invoice Preview: View calculated totals with discounts- πŸ“Š Reporting - Revenue and subscription analytics

  3. Checkout: Process payment and create subscriptions- πŸ”” Webhooks (link removed - file does not exist) - Stripe webhook event handling

  4. Order Tracking: Monitor fulfillment via Order Management- πŸ“₯ Import - Bulk data import utilities

Managing Subscriptions​

πŸ”„ Data Flow​

  1. Subscription Creation: Created during checkout process

  2. Upgrades/Downgrades: Manage via Subscription Management### Purchase Flow

  3. Payment Issues: Handle failed payments with retry logic```mermaid

  4. Cancellations: Cancel subscriptions with feedback collectionflowchart TD

    A[🌐 Agency Dashboard] -->|Browse Catalog| B[GET /store/products]

White-Label Operations B --> C[Product Controller]​

C -->|Apply loyalty adjustments| D[Return Products]
  1. Connected Accounts: Link Stripe Connect accounts

  2. Custom Products: Create agency-specific products A -->|Add to Cart| E[POST /store/cart]

  3. Pricing Configuration: Set partner vs standard pricing E --> F[Cart Controller]

  4. Application Fees: Automatic fee calculation on subscriptions F -->|Validate & Insert| G[(MongoDB _store.cart)]

System Statistics A -->|View Cart| H[GET /store/cart]​

H -->|Aggregate cart| F
  • 22+ Controllers managing all store operations F -->|Preview invoice| I((Stripe API))

  • 10+ MongoDB Collections for comprehensive data management I -->|Invoice totals| F

  • 50+ API Endpoints across all store features

  • Stripe-First Architecture with webhook synchronization A -->|Checkout| J[POST /store/cart/checkout]

  • Multi-Tenant Support with account hierarchy J -->|Lock checkout| F

  • Loyalty Program Integration with automatic discounts F -->|Create subscriptions| I

  • Bundle Management with atomic operations I -->|Success| K[Webhook Handler]

  • Advanced Analytics with revenue reporting K -->|Mirror subscription| L[(MongoDB _store.subscriptions)]

    K -->|Generate order| M[(MongoDB _store.orders)]

Integration Points K -->|Queue fulfillment| N[(MongoDB queues)]​

External Services style I fill:#635bff​

style K fill:#00d924
  • Stripe API: Payment processing, subscriptions, invoices, webhooks```

  • Typeform: Onboarding form management

  • Email Service: Transactional emails and notifications## πŸ” Configuration & Dependencies

  • Queue Manager: Background job processing

  • External APIs: Twilio (phone numbers), Listing services### Environment Variables

Internal Services| Variable | Description | Required |​

|----------|-------------|----------|

  • Account Service: Account management and relationships| STRIPE_SECRET_KEY | Stripe platform secret key | βœ… |

  • CRM Service: Contact and business management| SETUP_PRODUCT | Stripe product ID for setup fee line items | βœ… |

  • Notification Service: Email and SMS notifications| APP_SECRET | JWT signing secret | βœ… |

  • Project Service: Task and project management| API_BASE_URL | Internal API base URL | βœ… |

  • Analytics Service: Reporting and metrics

Dependencies​

External Services: Stripe API, Google Cloud Pub/Sub, Twilio

  • Subscription Management - Complete subscription lifecycle documentationInternal Services: External API, Queue Manager, Notification Service

  • Cart Management (link removed - file does not exist) - Shopping cart and checkout operationsKey Libraries: stripe, mongoose, joi, axios, moment-timezone, jsonwebtoken

  • Order Management - Order tracking and fulfillment

  • Product Management - Product catalog and pricing## πŸš€ Quick Start

  • Shared Models - Database schema definitions

  • API Documentation - Complete API reference1. Install dependencies: npm run dev:build

  1. Configure .env with Stripe credentials
  2. Start services via VS Code "Start All" debug configuration
  3. Test via provided API endpoints

⚠️ Important Notes​

Critical Business Rules​

  • 🚨 Software Subscriptions: Only one active software subscription per account
  • 🚨 Bundle Integrity: Bundle items must be purchased together
  • 🚨 Checkout Locking: Only one checkout can proceed at a time
  • 🚨 Pricing Type Consistency: Partner vs Standard affects all calculations
  • 🚨 Loyalty Programs: Auto-applied based on account tier

Common Errors​

  • PAYMENTS_NOT_ENABLED: Account lacks store feature
  • STRIPE_ACCOUNT_NOT_FOUND: Connected account not configured
  • RESOURCE_NOT_FOUND: Product/price/subscription doesn't exist
  • DUPLICATE_ITEM: Item already in cart
  • CHECKOUT_IN_PROGRESS: Concurrent checkout attempted

Last Updated: 2025-01-08

πŸ’¬

Documentation Assistant

Ask me anything about the docs

Hi! I'm your documentation assistant. Ask me anything about the docs!

I can help you with:
- Code examples
- Configuration details
- Troubleshooting
- Best practices

Try asking: How do I configure the API?
09:31 AM