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.
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.
| 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 |
- 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.
- Introduce tenant-aware domain models and APIs.
- Implement logical data isolation between tenants.
- Add tenant-specific billing configurations.
- Establish authorization and data access boundaries.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
The roadmap supports three complementary directions that can evolve independently or work together:
- Extensible SaaS Billing Engine: A flexible, reusable foundation for subscription billing, configurable pricing, and billing lifecycle management.
- Usage Metering & Pricing Infrastructure: A reliable event-processing and pricing layer for applications with complex consumption-based billing requirements.
- 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.
β 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)
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
| 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 |
| 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 |
- 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
- 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
- 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
- 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
- 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
- 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
- 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)
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
- Node.js 18+
- npm 9+
- Docker and Docker Compose (for local development)
-
Install dependencies:
npm install
-
Set up environment variables:
cp apps/backend/.env.example apps/backend/.env # Edit the .env file with your database configuration -
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
-
Seed the database with demo data:
cd apps/backend npx tsx prisma/seed.ts -
Access the application:
- π¨ Frontend: http://localhost:3000
- π Backend API: http://localhost:3001
- π Database Studio:
npm run db:studio - π API Documentation: http://localhost:3001/documentation
- π Trigger Billing: POST http://localhost:3001/api/billing/run
- View Demo Data: Open http://localhost:3000 to see 50 customers with contracts
- Run Billing: Click "Run Billing" to generate invoices for due contracts
- Check Results: See generated invoices with detailed pricing breakdowns
- Explore API: Visit http://localhost:3001/documentation for interactive API docs
npm run dev- Start both frontend and backend in development modenpm run build- Build all applicationsnpm run test- Run tests across all packagesnpm run lint- Lint all packagesnpm run format- Format code with Prettiernpm run db:generate- Generate Prisma clientnpm run db:migrate- Run database migrationsnpm run db:studio- Open Prisma Studio
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
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
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.39Billing 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)The application is configured for deployment on Render:
- Backend: Deploy as a Docker service
- Frontend: Deploy as a static site or Node.js service
- Database: Use Render's managed PostgreSQL
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Run
npm run lintandnpm run format - Submit a pull request
| 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
- 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
-
Fork this repository to your GitHub account
-
Create Render account at render.com
-
Deploy Database:
- Create new PostgreSQL database
- Copy connection string
-
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
-
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]
-
Initialize Database:
# After backend deploys npx prisma migrate deploy npx tsx prisma/seed.ts
See Development Setup section below.
- 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
- 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
- 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
| 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 |
| 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 |
| 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 |
- Live Demo: https://billforge-frontend.onrender.com
- API Docs: https://billforge-backend.onrender.com/documentation
- GitHub: https://github.com/[username]/billforge
MIT License - This project is open source and available under the MIT License.