Skip to content
bender-tech-ltdaPublic

About

A comprehensive SaaS billing platform featuring complex recurrence rules, multi-tier pricing, and perfect monetary accuracy. Built with TypeScript, featuring enterprise-grade error handling, comprehensive testing, and production-ready deployment.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

38 Commits

Folders and files

Repository files navigation

πŸ”₯ BillForge - Production-Ready SaaS Billing Platform

Live Demo: UI | API

A comprehensive SaaS billing platform featuring complex recurrence rules, multi-tier pricing, and perfect monetary accuracy. Built with TypeScript, featuring enterprise-grade error handling, comprehensive testing, and production-ready deployment.

πŸš€ Development Roadmap

BillForge is evolving from a functional SaaS billing proof of concept into a modular, extensible, and developer-friendly open-source billing platform.

The next development phase will focus on improving the existing architecture, expanding usage-based billing capabilities, introducing advanced pricing and simulation features, and strengthening the platform's reliability and scalability.

The roadmap represents approximately 400 hours of planned independent development work, organized into eight phases.

πŸ“‹ Planned Development Phases

Phase Scope Estimated Hours
1 Architecture review, test improvements, and billing engine refactoring 40
2 Multi-tenant architecture and logical data isolation 60
3 Usage event processing pipeline, deduplication, and aggregation 70
4 Extensible pricing engine and configurable business rules 65
5 Contract simulation and pricing model comparison 45
6 API enhancements, TypeScript SDK, and external integrations 45
7 Concurrency testing, property-based testing, and edge-case validation 45
8 Documentation, examples, observability, and stabilization 30
Total 400

🎯 Key Development Objectives

Phase 1 β€” Architecture & Core Refactoring

  • Review and improve the existing billing engine architecture.
  • Refactor core domain components for better extensibility and maintainability.
  • Expand automated test coverage.
  • Establish clear boundaries between billing, pricing, and usage metering.

Phase 2 β€” Multi-Tenant Architecture

  • Introduce tenant-aware domain models and APIs.
  • Implement logical data isolation between tenants.
  • Add tenant-specific billing configurations.
  • Establish authorization and data access boundaries.

Phase 3 β€” Usage Metering & Event Processing

  • Build a reliable pipeline for ingesting usage events.
  • Implement event deduplication and idempotent processing.
  • Support configurable aggregation windows.
  • Handle out-of-order events, retries, and concurrent processing.
  • Provide consistent usage summaries for billing calculations.

Phase 4 β€” Extensible Pricing Engine

  • Introduce a modular pricing rules architecture.
  • Support configurable pricing strategies and complex billing conditions.
  • Expand tiered, volume-based, and hybrid pricing models.
  • Improve handling of discounts, credits, and pricing adjustments.
  • Ensure deterministic calculations and monetary precision.

Phase 5 β€” Billing Simulation & Analytics

  • Implement billing simulations using synthetic usage datasets.
  • Allow developers to compare alternative pricing strategies.
  • Support what-if analysis for subscription and contract changes.
  • Provide estimated revenue and usage breakdowns.
  • Build interfaces for visualizing simulation results.

Phase 6 β€” APIs, SDKs & Integrations

  • Expand the public API for billing and usage management.
  • Develop a TypeScript SDK for application integration.
  • Introduce event-driven notifications and webhooks.
  • Improve API validation, versioning, and error handling.
  • Provide integration examples for common SaaS architectures.

Phase 7 β€” Reliability & Advanced Testing

  • Introduce property-based testing for billing calculations.
  • Expand concurrency and idempotency tests.
  • Validate edge cases involving recurrence, time zones, and proration.
  • Implement load and performance tests for usage ingestion.
  • Improve error recovery and consistency guarantees.

Phase 8 β€” Documentation & Stabilization

  • Expand developer documentation and API references.
  • Create end-to-end integration examples.
  • Improve structured logging, metrics, and observability.
  • Refine local development and deployment workflows.
  • Prepare a stable open-source release.

πŸ”­ Long-Term Vision

The roadmap supports three complementary directions that can evolve independently or work together:

  1. Extensible SaaS Billing Engine: A flexible, reusable foundation for subscription billing, configurable pricing, and billing lifecycle management.
  2. Usage Metering & Pricing Infrastructure: A reliable event-processing and pricing layer for applications with complex consumption-based billing requirements.
  3. Billing Simulation & Revenue Analytics: Tools for evaluating pricing strategies, simulating contract changes, and forecasting revenue using synthetic datasets.

The initial focus is on strengthening the existing billing engine and establishing the foundations for reliable usage metering and extensible pricing.

Future development will prioritize modularity, correctness, performance, and ease of integration while keeping the project open-source and accessible to developers.


πŸš€ COMPLETED & DEPLOYED

βœ… All must-have requirements implemented and tested (97/97 tests passing) βœ… Live production deployment on Render platform βœ… 13 invoices successfully generated with complex pricing calculations βœ… Date calculation edge cases resolved (month boundaries, leap years)

Business Context

BillForge handles enterprise SaaS subscription billing with sophisticated pricing models:

  • πŸ”„ Flat Recurring Fee: $99 monthly (customizable billing dates)
  • πŸ“Š Tiered Metered Usage:
    • Tier 1: 0-1,000 calls = FREE
    • Tier 2: 1,001-1,000,000 calls = $0.002/call
    • Tier 3: 1,000,001+ calls = $0.001/call
  • πŸ’° Minimum Commit: Prepaid 10,000 calls monthly ($20)
  • 🎯 Smart Discounts: 20% off first 3 billing cycles
  • πŸ’³ Credit Management: Manual credits, refunds, and adjustments
  • ⚑ Mid-Cycle Changes: Plan upgrades with precise proration
  • πŸ—“οΈ Complex Schedules: RFC 5545 RRULE support (monthly, quarterly, custom)
  • πŸ”’ Audit Trail: Complete financial transaction logging

πŸ“š Documentation

Document Description
πŸ“‹ Business Rules & Requirements Complete business logic and pricing rules
πŸ”§ Functional Requirements Detailed technical requirements and success criteria
πŸ“… Implementation Plan Development phases and execution strategy
πŸ€– AI Usage Report Transparent AI assistance tracking
🎯 Phase Summaries Detailed progress reports for each development phase

βœ… Production Readiness & Quality Metrics

🎯 100% Requirements Completion

Category Status Details
Correctness βœ… 97/97 tests passing Invoices, credits, and billing jobs are mathematically accurate and idempotent
Data Design βœ… Production-ready Normalized PostgreSQL schema with proper indexes, constraints, and ACID compliance
Algorithmic Rigor βœ… Edge-case tested Date arithmetic handles leap years, month boundaries, timezone transitions
Code Quality βœ… TypeScript strict mode Clean architecture, domain separation, comprehensive error handling
Frontend βœ… Responsive UI Real-time billing dashboard with invoice management and job monitoring
Observability βœ… Full audit trail Structured logging, SQL traces, billing job progress tracking
Deployment βœ… Live on Render Production environment with managed PostgreSQL and container orchestration
Documentation βœ… Comprehensive Business rules, API docs, deployment guides, and AI transparency

🌟 Production Features

πŸ’Ž Core Billing Engine

  • Perfect Monetary Accuracy: Uses decimal.js for 6-decimal precision financial calculations
  • Enterprise Recurrence: Full RFC 5545 RRULE support (monthly, quarterly, yearly, custom intervals)
  • Multi-Tier Pricing: Flat fees + tiered usage + minimum commits with accurate proration
  • Real-Time Usage: Metered API call tracking with microsecond precision timestamps
  • Smart Discounts: Time-limited promotional discounts with automatic expiration
  • Credit System: Manual credits, refunds, adjustments with partial consumption tracking

πŸ—οΈ Technical Excellence

  • TypeScript Monorepo: Shared types, validation, and utilities across all services
  • PostgreSQL + Prisma: Production-grade database with migrations and type safety
  • Idempotent Jobs: Billing runs are safe to retry without duplicate charges
  • Comprehensive Testing: 97 tests covering edge cases, proration, and date arithmetic
  • Docker Containerized: Ready for orchestration and horizontal scaling
  • Structured Logging: JSON logs with correlation IDs for distributed tracing

🎨 User Experience

  • Real-Time Dashboard: Live billing job monitoring with progress indicators
  • Invoice Management: Detailed line items, credits applied, and payment status
  • Customer Portal: Balance tracking, usage analytics, and invoice history
  • Responsive Design: Mobile-friendly interface built with Tailwind CSS

πŸ› οΈ Tech Stack

Backend

  • Runtime: Node.js 18+ with Fastify (high-performance web framework)
  • Language: TypeScript (strict mode) with comprehensive type safety
  • Database: PostgreSQL with Prisma ORM (migrations, type generation)
  • Testing: Jest with 97 comprehensive test cases
  • Validation: Zod schemas for runtime type checking

Frontend

  • Framework: Next.js 14 with React 18 (App Router)
  • Styling: Tailwind CSS with responsive design
  • State: React Query for server state management
  • UI Components: Custom components with accessibility features

Shared Libraries

  • Types: Zod schemas shared between frontend and backend
  • Money: decimal.js for precise financial calculations
  • Dates: RRULE.js for complex recurrence patterns
  • Validation: Shared business rules and constraints

Infrastructure

  • Containers: Docker with multi-stage builds
  • Development: Docker Compose for local environment
  • Production: Render platform with managed PostgreSQL
  • CI/CD: GitHub Actions (ready for automated deployment)

Project Structure

billforge/
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ backend/          # Fastify API server
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ prisma/       # Database schema and migrations
β”‚   β”‚   └── Dockerfile
β”‚   └── frontend/         # Next.js web application
β”œβ”€β”€ packages/
β”‚   └── shared/           # Shared types and utilities
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ types.ts      # Zod schemas and TypeScript types
β”‚       β”‚   └── utils/
β”‚       β”‚       β”œβ”€β”€ money.ts      # Monetary calculations
β”‚       β”‚       └── recurrence.ts # RRULE utilities
β”œβ”€β”€ docker-compose.yml    # Development environment
└── package.json          # Workspace configuration

Getting Started

Prerequisites

  • Node.js 18+
  • npm 9+
  • Docker and Docker Compose (for local development)

Installation

  1. Install dependencies:

    npm install
  2. Set up environment variables:

    cp apps/backend/.env.example apps/backend/.env
    # Edit the .env file with your database configuration
  3. Start the development environment:

    # Start PostgreSQL and backend services
    docker-compose up -d
    
    # Run database migrations
    npm run db:migrate
    
    # Start frontend development server
    npm run dev --workspace=@billforge/frontend
  4. Seed the database with demo data:

    cd apps/backend
    npx tsx prisma/seed.ts
  5. Access the application:

🎯 Quick Demo

  1. View Demo Data: Open http://localhost:3000 to see 50 customers with contracts
  2. Run Billing: Click "Run Billing" to generate invoices for due contracts
  3. Check Results: See generated invoices with detailed pricing breakdowns
  4. Explore API: Visit http://localhost:3001/documentation for interactive API docs

Development

Available Scripts

  • npm run dev - Start both frontend and backend in development mode
  • npm run build - Build all applications
  • npm run test - Run tests across all packages
  • npm run lint - Lint all packages
  • npm run format - Format code with Prettier
  • npm run db:generate - Generate Prisma client
  • npm run db:migrate - Run database migrations
  • npm run db:studio - Open Prisma Studio

Database Schema

The enhanced database schema includes:

  • Customers: Customer information, billing details, and credit balances
  • Contracts: Subscription contracts with pricing configuration and RRULE support
  • Price Books: Pricing plans with tiered structures (Basic, Pro, Enterprise)
  • Usage Events: Individual API call tracking with metadata
  • Invoices: Generated invoices with detailed line items
  • Credits: Manual credits and adjustments with audit trail
  • Payments: Payment tracking for future integration
  • Billing Jobs: Job tracking for idempotent billing operations

πŸ“Š Live Database Schema

Status: βœ… All Phases Complete - Production database with 13 generated invoices

  • πŸ“Š Customers: 50 demo customers with realistic usage patterns
  • πŸ“‹ Contracts: Active subscriptions with varied pricing plans
  • πŸ’° Invoices: Real invoices generated with complex pricing calculations
  • ⚑ Usage Events: 97,663 API call events over 30 days
  • πŸ’³ Credits: 15 customer credits (manual, refund, promotional)
  • πŸ”„ Billing Jobs: Idempotent job execution with progress tracking

Key Concepts

Monetary Precision

All monetary calculations use decimal.js to ensure perfect accuracy:

import { createMoney, addMoney, formatMoney } from '@billforge/shared'

const price = createMoney('29.99', 'USD')
const tax = createMoney('2.40', 'USD')
const total = addMoney(price, tax)
console.log(formatMoney(total)) // $32.39

Recurrence Rules

Billing schedules use RFC 5545 RRULE format:

import { BillingRules, getNextBillingDates } from '@billforge/shared'

// Monthly billing on the 15th
const rrule = BillingRules.monthly(15)
const nextDates = getNextBillingDates(rrule, new Date(), 12)

// Quarterly billing
const quarterlyRule = BillingRules.quarterly(1)

Deployment

The application is configured for deployment on Render:

  1. Backend: Deploy as a Docker service
  2. Frontend: Deploy as a static site or Node.js service
  3. Database: Use Render's managed PostgreSQL

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Run npm run lint and npm run format
  6. Submit a pull request

πŸ€– AI Contribution Analysis

Development Breakdown

Component AI Contribution Human Contribution Notes
Architecture & Design 20% 80% Human-driven domain modeling, AI assisted with structure
Database Schema 40% 60% AI generated base schema, human refined for business rules
Core Billing Logic 60% 40% AI implemented algorithms, human designed business logic
Date/Proration Math 70% 30% AI handled complex calculations, human verified edge cases
API Development 80% 20% AI generated endpoints, human designed architecture
Frontend Components 75% 25% AI built UI components, human designed UX flow
Testing Strategy 50% 50% Human designed test cases, AI implemented tests
Documentation 85% 15% AI generated docs, human provided domain expertise
Deployment Config 90% 10% AI configured infrastructure, human validated setup
Bug Fixes & Debug 30% 70% Human diagnosed issues, AI assisted with solutions
  • Total Implementation Time: 16 pomodoros

Key Human Contributions

  • Business logic design and domain modeling
  • Architecture decisions and technology choices
  • Test case design and edge case identification
  • Code review and quality assurance
  • Production deployment validation
  • Performance optimization and debugging

πŸš€ Deployment Guide

Quick Deploy to Render

  1. Fork this repository to your GitHub account

  2. Create Render account at render.com

  3. Deploy Database:

    • Create new PostgreSQL database
    • Copy connection string
  4. Deploy Backend:

    # render.yaml (backend)
    services:
      - type: web
        name: billforge-backend
        env: docker
        dockerfilePath: ./apps/backend/Dockerfile
        envVars:
          - key: DATABASE_URL
            value: [your-postgres-url]
          - key: PORT
            value: 3001
  5. Deploy Frontend:

    # render.yaml (frontend)
    services:
      - type: web
        name: billforge-frontend
        env: node
        buildCommand: npm install && npm run build
        startCommand: npm start
        envVars:
          - key: NEXT_PUBLIC_API_URL
            value: [your-backend-url]
  6. Initialize Database:

    # After backend deploys
    npx prisma migrate deploy
    npx tsx prisma/seed.ts

Local Development

See Development Setup section below.


πŸ’­ Future Enhancements (If More Time Available)

Phase 6: Advanced Features (Next 2-3 weeks)

  • Multi-Currency Support: USD, EUR, GBP with real-time exchange rates
  • Advanced Analytics: Revenue forecasting, churn analysis, usage trends
  • Webhook System: Real-time notifications for invoice events
  • Payment Integration: Stripe/PayPal processing with automated reconciliation
  • Dunning Management: Automated retry logic for failed payments

Phase 7: Enterprise Features (1-2 months)

  • Multi-Tenant Architecture: Isolated customer environments
  • Advanced Reporting: Custom dashboards, scheduled reports, data exports
  • API Rate Limiting: Usage quotas and fair use policies
  • Audit & Compliance: SOX, PCI DSS compliance features
  • Performance Optimization: Database partitioning, caching layers

Phase 8: Scale & Operations (2-3 months)

  • Microservices Architecture: Service decomposition for scale
  • Event Sourcing: Complete audit trail with event replay
  • Kubernetes Deployment: Auto-scaling, health checks, service mesh
  • Monitoring & Alerting: Prometheus, Grafana, on-call automation
  • Disaster Recovery: Multi-region deployment, automated backups

πŸ“‹ Documentation Reference

Core Documentation

File Purpose
README.md Main project overview, setup, and deployment guide
docs/BUSINESS_RULES.md Complete business logic, pricing rules, and calculations
docs/FUNCTIONAL_REQUIREMENTS.md Technical requirements and must-have feature specifications
docs/IMPLEMENTATION_PLAN.md Development phases, timeline, and execution strategy
docs/AI_USAGE.md Detailed AI contribution tracking and human oversight

Phase Documentation

File Covers
docs/phases/PHASE1_FOUNDATION.md Database schema, core setup, initial structure
docs/phases/PHASE2_RECURRENCE.md RRULE implementation, date handling, scheduling
docs/phases/PHASE3_PRICING.md Pricing engines, calculation logic, proration
docs/phases/PHASE4_SUMMARY.md Core billing implementation completion
docs/phases/PHASE5_SUMMARY.md Advanced features: discounts, credits, UI enhancements

Technical Documentation

Location Content
apps/backend/docs/ API documentation, database migrations, deployment configs
apps/frontend/README.md Frontend setup, component library, styling guide
packages/shared/README.md Shared utilities, types, and validation schemas

πŸ“ž Support & Contact


πŸ“„ License

MIT License - This project is open source and available under the MIT License.

About

A comprehensive SaaS billing platform featuring complex recurrence rules, multi-tier pricing, and perfect monetary accuracy. Built with TypeScript, featuring enterprise-grade error handling, comprehensive testing, and production-ready deployment.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages