Skip to main content

PRD: Billing and Balance Management System

📋 Implementation Issue: Issue #202 - Add a Billing Page to display balance and consumption

📘 Technical Design: TDD: Billing System Implementation

Overview

This document outlines the product requirements for implementing a comprehensive billing and balance management system in the Construction Code Expert application. The system will enable monetization of the service while providing users with transparent cost tracking, account balance management, and payment processing capabilities.

  • Issue #200: Task Cost Tracking (parent functionality)
  • Issue #202: Billing Page Implementation (this feature)

Problem Statement

Current State

  • Application tracks costs for long-running AI tasks (Issue #200)
  • No mechanism to monetize the service
  • Users cannot see their account balance or transaction history
  • No payment processing system in place
  • No cost control to prevent overuse

User Pain Points

  1. Lack of Transparency: Users don't know how much they're spending or what their available balance is
  2. No Cost Control: System can't prevent task execution when user has insufficient funds
  3. No Payment Method: Users can't top up their balance to continue using the service
  4. Missing Transaction History: Users can't review past charges or payments
  5. No Monetization: Service provider has no way to charge for usage

User Impact

Without a billing system:

  • Users may be surprised by charges when billing is eventually implemented
  • Service provider cannot sustain operational costs (API fees, infrastructure)
  • No clear value proposition for different user tiers (trial vs. paid)
  • Risk of abuse without balance limits

Goals

Primary Goals

  1. Enable Monetization: Implement payment processing to charge users for service usage
  2. Cost Transparency: Provide users clear visibility into costs, balance, and transaction history
  3. Balance Management: Track user balances and grant complimentary trial credits
  4. Cost Control: Prevent task execution when insufficient balance exists
  5. Audit Trail: Maintain complete financial transaction history for compliance

Secondary Goals

  1. Stripe Integration: Establish foundation for full Stripe payment processing
  2. Multi-Tier Support: Enable subscription tiers (Trial, Basic, Professional, Enterprise)
  3. Project-Level Reporting: Show expense breakdown by project
  4. Usage Analytics: Track total spending, task execution counts, monthly spend

Non-Goals (Explicitly Out of Scope)

  1. ❌ Subscription billing (recurring charges) - Future phase
  2. ❌ Multiple payment methods (credit card, PayPal, etc.) - Start with Stripe only
  3. ❌ Invoice generation and emailing - Future phase
  4. ❌ Tax calculation and compliance - Future phase
  5. ❌ Multi-currency support - USD only initially
  6. ❌ Team billing and shared accounts - Future phase
  7. ❌ Discount codes and promotions - Future phase

User Stories

Story 1: View Account Balance

As a registered user
I want to see my account balance displayed prominently in the top app bar
So that I always know how much credit I have available

Acceptance Criteria:

  • Balance displays in top-right corner of app bar
  • Shows dollar amount in USD format (e.g., "$300.00")
  • Updates in real-time after transactions
  • Includes tooltip showing last updated timestamp
  • Shows warning indicator when balance is low (< $10)

Story 2: Receive Welcome Bonus Credits

As a new user registering for the first time
I want to automatically receive $300 in complimentary credits
So that I can try the service without immediate payment

Acceptance Criteria:

  • $300 credits granted automatically on first login
  • Transaction recorded as "Welcome bonus - complimentary credits"
  • Transaction type marked as COMPLIMENTARY
  • Credits available immediately for use
  • Welcome transaction visible in transaction history

Story 3: View Transaction History

As a user
I want to see a complete history of all my account transactions
So that I can track my payments and spending over time

Acceptance Criteria:

  • Transaction history page accessible from top app bar
  • Shows transaction date, type, description, amount, and resulting balance
  • Transactions sorted by date (most recent first)
  • Different visual indicators for credit vs. debit transactions
  • Pagination support for users with many transactions
  • Filter by transaction type (all, credits, debits, refunds)

Story 4: View Expense History by Project

As a user working on multiple projects
I want to see my spending broken down by project
So that I can understand which projects are consuming the most resources

Acceptance Criteria:

  • Expense history tab on billing page
  • Shows project name, total cost, and number of tasks
  • Sorted by total cost (highest first)
  • Shows recent transactions for each project
  • Click on project to see detailed task-level breakdown
  • Empty state when no expenses exist

Story 5: Understand Task Costs Before Execution

As a user initiating a long-running task
I want to be notified if I have insufficient balance
So that I can top up my account before wasting time

Acceptance Criteria:

  • Balance check performed before task execution
  • Clear error message if insufficient balance
  • Message shows current balance and required amount
  • Link to billing page to add funds
  • No partial task execution if balance is insufficient

Story 6: Top Up Account Balance (Future Phase 2)

As a user with low balance
I want to add funds to my account via Stripe
So that I can continue using the service

Acceptance Criteria (Phase 2):

  • "Add Funds" button on billing page
  • Select amount or enter custom amount
  • Stripe payment form integration
  • Confirmation after successful payment
  • Transaction immediately reflected in balance
  • Email receipt sent after payment

Story 7: View Subscription Tier

As a user
I want to see what subscription tier I'm on
So that I understand my account status and benefits

Acceptance Criteria:

  • Tier displayed on billing page (Trial, Basic, Professional, Enterprise)
  • Shows tier benefits and limitations
  • Indicates when trial credits will expire (future)
  • Link to upgrade tier (future)

Technical Requirements (High-Level)

Proto Schema

Define interface contracts for billing data structures:

// User billing profile with balance and subscription information
message UserBillingProfile {
string user_email = 1;
google.type.Money available_balance = 2;
SubscriptionTier subscription_tier = 3;
google.type.Money complimentary_credits = 4;
google.protobuf.Timestamp created_at = 5;
google.protobuf.Timestamp updated_at = 6;
string stripe_customer_id = 7;
BillingUsageStats usage_stats = 8;
}

// Transaction record for balance changes
message BillingTransaction {
string transaction_id = 1;
string user_email = 2;
TransactionType type = 3;
google.type.Money amount = 4;
google.type.Money balance_before = 5;
google.type.Money balance_after = 6;
string description = 7;
google.protobuf.Timestamp created_at = 8;
oneof related_entity {
string task_id = 9;
string stripe_payment_intent_id = 10;
}
TransactionMetadata metadata = 11;
}

enum TransactionType {
TRANSACTION_TYPE_UNSPECIFIED = 0;
CREDIT = 1; // Balance top-up
DEBIT = 2; // Task cost deduction
REFUND = 3; // Payment refund
ADJUSTMENT = 4; // Manual adjustment
COMPLIMENTARY = 5; // Free credits
}

📘 Complete Schemas: See TDD: Billing for complete proto definitions

Component Architecture

Backend Services

  • BillingService (gRPC)

    • User profile management
    • Transaction recording
    • Balance checking and deduction
    • Expense history queries
    • Stripe integration (Phase 2)
  • StripeService (Java)

    • Mock implementation (Phase 1)
    • Real Stripe API integration (Phase 2)
    • Customer management
    • Payment intent creation

Frontend Components

  • Balance Display Component (Angular)

    • Shows balance in top app bar
    • Real-time updates via gRPC
    • Low balance warnings
  • Billing Page Component (Angular)

    • Transaction history table
    • Project expense breakdown
    • Payment methods (Phase 2)
    • Account overview cards

Data Storage

  • Firestore Collections

    • billing_profiles/{userEmail} - User billing profiles
    • billing_transactions/{transactionId} - Transaction records
    • billing_cache/{userEmail} - Cached transaction summaries (optional)
  • Firestore Indexes

    • userEmail + createdAt (descending) - Transaction history
    • userEmail + type + createdAt - Filtered transaction queries
    • metadata.taskCompletion.projectId + createdAt - Project expenses

API Endpoints (gRPC + REST)

All endpoints exposed via gRPC with REST transcoding through gRPC-Gateway:

  • GET /v1/billing/profile - Get user billing profile
  • POST /v1/billing/top-up - Initiate balance top-up (Phase 2)
  • GET /v1/billing/transactions - Get transaction history
  • GET /v1/billing/expenses - Get expense history by project
  • GET /v1/billing/projects/{projectId}/expenses - Project-specific expenses
  • POST /v1/billing/check-balance - Check sufficient balance

📘 Complete API Specifications: See TDD: Billing - API Reference

Security and Privacy Considerations

Data Minimization

  • Rely on Firebase Auth for user identity - don't duplicate PII
  • Rely on Stripe for payment information - don't store credit card data
  • Store only necessary financial data in Firestore - balance, transactions, metadata

Authentication and Authorization

  • All billing endpoints require Firebase Auth token
  • Users can only access their own billing data
  • Project owners can view project-level expense reports
  • Admin-only endpoints for manual adjustments (future)

Audit Trail

  • Every transaction recorded with timestamp and source
  • Transaction IDs are unique and immutable
  • Balance changes always recorded with before/after amounts
  • Transaction metadata includes task/project context

Compliance Considerations

  • GDPR: Users can request data export/deletion
  • PCI DSS: Stripe handles all payment card processing
  • SOC 2: Audit logs for all financial operations
  • Data Retention: Transaction history retained per legal requirements

Cost Analysis and Pricing

Complimentary Trial Credits

  • $300 per new user
  • Typical usage: 20-30 large architectural plan reviews
  • Estimated trial period: 1-2 months for active users
  • Cost to company: Absorbed as customer acquisition cost

Pricing Model (Future)

  • Pay-as-you-go: Charge per task execution based on actual costs
  • Credit burndown: Users pre-pay, credits deducted per task
  • Subscription tiers (future):
    • Trial: $300 complimentary (one-time)
    • Basic: $50/month + $0.50/task overage
    • Professional: $200/month + $0.30/task overage
    • Enterprise: Custom pricing

Cost Structure

  • Vertex AI Costs: $0.50-$5.00 per architectural plan page (varies by complexity)
  • Firestore Costs: ~$0.01/month per active user (reads/writes minimal)
  • Cloud Run Costs: ~$0.10/month per active user (billed execution time)
  • Stripe Processing Fee: 2.9% + $0.30 per transaction (future)

Estimated Revenue (Month 1 with 100 Active Users)

  • Trial users (50): $0 revenue (using complimentary credits)
  • Basic subscribers (30): $1,500/month
  • Professional subscribers (15): $3,000/month
  • Enterprise (5): $5,000/month (estimated)
  • Total: ~$9,500/month

Break-Even Analysis

  • Infrastructure costs: ~$2,000/month (Vertex AI, Cloud Run, Firestore)
  • Complimentary credits: $15,000 (50 new users × $300)
  • Break-even: ~150 paying subscribers in month 2

Testing Strategy (Scope)

Unit Testing

  • Billing service methods (balance checks, transaction creation)
  • Money arithmetic (addition, subtraction, comparisons)
  • Transaction type validation
  • Stripe service mock responses

Integration Testing

  • End-to-end transaction flow (credit → debit)
  • Firestore read/write operations
  • gRPC API endpoint calls
  • Authentication and authorization checks

UI Testing

  • Balance display updates after transactions
  • Transaction history pagination
  • Expense breakdown by project
  • Low balance warnings
  • Error messages for insufficient balance

Manual Testing Checklist

  • New user receives $300 welcome bonus
  • Balance displayed correctly in top app bar
  • Transaction history shows all transactions
  • Task execution blocked when insufficient balance
  • Balance updates after task completion
  • Project expense breakdown accurate
  • Firestore security rules prevent unauthorized access
  • API endpoints require authentication

📘 Complete Test Specifications: See TDD: Billing - Testing

Success Metrics

User Engagement Metrics

  • Balance Check Rate: % of users checking billing page weekly
    • Target: 60% of active users
  • Transaction History Views: Average views per user per month
    • Target: 3-5 views/month
  • Low Balance Response: % of users topping up after low balance warning
    • Target: 70% conversion (Phase 2)

System Performance Targets

  • Balance Lookup Latency: Time to fetch user balance
    • Target: < 100ms (p95)
  • Transaction Recording: Time to record transaction
    • Target: < 200ms (p95)
  • Billing Page Load: Time to load billing dashboard
    • Target: < 1 second with 50 transactions

Business KPIs

  • Trial Credit Utilization: Average % of $300 credits used
    • Target: 40-60% (indicates good product-market fit)
  • Conversion Rate: % of trial users who pay after credits exhausted
    • Target: 20-30% (Phase 2)
  • Average Transaction Value: Mean top-up amount per user
    • Target: $100-$200 (Phase 2)
  • Monthly Recurring Revenue (MRR): From subscription tiers
    • Target: $10,000 by end of Q2 (Phase 2+)
  • Customer Lifetime Value (CLV): Revenue per user over 12 months
    • Target: $500-$1,000 (Phase 2+)

Monitoring and Alerting

  • Alert when transaction creation fails (error rate > 1%)
  • Alert when balance lookup latency exceeds 500ms
  • Daily report of new trial credit distributions
  • Weekly report of users approaching zero balance

Future Enhancements

Phase 2: Stripe Payment Integration (Q2)

  • Real Stripe API integration (replace mock)
  • Payment method management (add/remove cards)
  • One-click top-up for returning users
  • 3D Secure authentication support
  • Payment confirmation emails
  • Receipt generation

Estimated Effort: 2-3 weeks development + 1 week testing

Phase 3: Subscription Tiers (Q3)

  • Monthly subscription billing
  • Tier-based pricing (Basic, Professional, Enterprise)
  • Automatic credit top-ups for subscribers
  • Upgrade/downgrade flows
  • Proration for mid-cycle changes
  • Subscription management UI

Estimated Effort: 3-4 weeks development + 2 weeks testing

Phase 4: Advanced Reporting (Q4)

  • Downloadable transaction CSV exports
  • Monthly spending reports via email
  • Budget alerts and notifications
  • Cost forecasting based on usage trends
  • Project-level budget controls
  • Admin dashboard for customer support

Estimated Effort: 2-3 weeks development + 1 week testing

Phase 5: Enterprise Features (Q4+)

  • Team billing and shared accounts
  • Multi-user access to billing data
  • Purchase orders and invoicing
  • Custom payment terms (NET-30, NET-60)
  • Dedicated account management
  • Service Level Agreements (SLAs)

Estimated Effort: 4-6 weeks development + 2 weeks testing

Future Considerations

  • Multi-currency support (EUR, GBP, CAD)
  • Alternative payment methods (ACH, wire transfer)
  • Discount codes and promotional campaigns
  • Referral program with credit rewards
  • Charity donation matching
  • Carbon offset options

Implementation Phases

Phase 1: Core Billing Infrastructure (Current)

Scope: Transaction tracking, balance display, complimentary credits

Deliverables:

  • ✅ Proto schemas for billing entities
  • ✅ BillingService gRPC implementation
  • ✅ Firestore collections and indexes
  • ✅ Balance display in app bar
  • ✅ Billing page with transaction history
  • ✅ $300 welcome bonus for new users
  • ✅ Expense history by project
  • ✅ Cost deduction on task completion
  • ✅ Balance check before task execution

Status: Implementation complete, deployment in progress

Phase 2: Stripe Integration (Next)

Scope: Real payment processing

Prerequisites:

  • Stripe account and API keys
  • PCI compliance review
  • Payment flow UX design
  • Email receipt templates

Phase 3: Subscription Billing (Future)

Scope: Recurring charges and tier management

Prerequisites:

  • Phase 2 complete
  • Tier pricing finalized
  • Subscription management UX
  • Billing cycle definitions

Dependencies

External Dependencies

  • Stripe API: Payment processing (Phase 2+)

    • Account setup required
    • API keys and webhooks
    • Testing in Stripe test mode
  • Firebase Auth: User authentication (existing)

    • No additional setup required
  • Firestore: Data storage (existing)

    • New collections and indexes required
    • Security rules updates

Internal Dependencies

  • Issue #200: Task Cost Tracking

    • Provides cost data for billing
    • Must be complete before billing can deduct costs
  • Task Execution Service: Must call billing service

    • Check balance before task execution
    • Deduct cost after task completion

Infrastructure Dependencies

  • Firestore indexes deployed (automated)
  • gRPC-Gateway configuration updated
  • API documentation regenerated

Risk Assessment

High Risk

  1. Data Consistency: Ensuring Firestore and Stripe stay in sync

    • Mitigation: Use Firestore as cache, Stripe as source of truth
    • Mitigation: Regular reconciliation jobs (Phase 2)
  2. Payment Fraud: Risk of stolen credit cards or chargebacks

    • Mitigation: Rely on Stripe's fraud detection
    • Mitigation: Monitor unusual usage patterns
    • Mitigation: Require email verification before high-value tasks

Medium Risk

  1. Trial Credit Abuse: Users creating multiple accounts for free credits

    • Mitigation: Track by email domain and payment method
    • Mitigation: Rate limiting on account creation
    • Mitigation: Require phone verification (future)
  2. Cost Estimation Accuracy: Task costs may vary from estimates

    • Mitigation: Conservative estimates (slight overcharge)
    • Mitigation: Automatic refunds for overcharges > 20%
    • Mitigation: Cost monitoring and adjustment over time

Low Risk

  1. UI Confusion: Users may not understand transaction types
    • Mitigation: Clear labels and descriptions
    • Mitigation: Help text and tooltips
    • Mitigation: Onboarding tour (future)

Open Questions

  1. Trial Credit Expiration: Should complimentary credits expire after a certain period?

    • Recommendation: No expiration for now, revisit in Phase 2
  2. Minimum Top-Up Amount: What should the minimum payment be?

    • Recommendation: $20 minimum (covers Stripe fees)
  3. Refund Policy: What's the policy for task failures or user dissatisfaction?

    • Recommendation: Automatic refund for system failures, manual review for others
  4. Tax Handling: Do we need to collect sales tax?

    • Recommendation: Consult with legal/finance team before Phase 2
  5. International Users: How do we handle non-US users and regulations?

    • Recommendation: USD only initially, expand in Phase 4+

References

Internal Documentation

External References

Competitive Analysis

  • AWS Cost Explorer: Provides detailed cost tracking and forecasting
  • Azure Cost Management: Offers budget alerts and optimization recommendations
  • OpenAI API Billing: Simple credit-based system with usage dashboard
  • Anthropic Claude Billing: Pay-as-you-go with transparent per-token pricing

Compliance Resources


Document Version: 1.0
Last Updated: October 18, 2025
Author: AI Assistant
Reviewers: TBD
Status: Ready for Implementation (Phase 1 Complete)