feat: prepaid credits endpoint#571
Merged
greatest0fallt1me merged 1 commit intoJun 28, 2026
Merged
Conversation
|
@rahimatonize Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
Add /api/billing/credits GET endpoint for prepaid balance tracking per developer. Changes: - Add credits table to schema with user_id, balance_usdc, timestamps - Create migration 0014_credits.sql with indexed user_id lookup - Implement CreditsRepository with findByUserId, getOrCreateByUserId, updateBalance - Add GET /api/billing/credits route with authentication and validation - Mount credits sub-router under /api/billing - Add comprehensive test suite (billing-credits.test.ts) with 90%+ coverage - Document endpoint in docs/billing-credits-endpoint.md Features: - Auto-creates zero balance for new users - Text-based balance storage for decimal precision (7 places) - Structured error responses with correlation IDs - Input validation via Zod schemas - Structured logging with user context Tests cover: - Authentication (JWT and x-user-id) - New user auto-creation - Existing user retrieval - Decimal precision handling - Error scenarios - Concurrent requests - Response format validation Closes CalloraOrg#512
4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Add /api/billing/credits endpoint for prepaid balance tracking
Overview
This PR implements a new REST endpoint for tracking prepaid credit balances per developer as part of the GrantFox campaign initiative. The endpoint provides secure, authenticated access to user credit balances with automatic record creation, precise decimal handling, and comprehensive error responses.
Implementation Summary
New Endpoint
GET /api/billing/creditsReturns the authenticated user's prepaid USDC balance. If no credits record exists, one is automatically created with a zero balance.
Request:
curl -X GET https://api.callora.com/api/billing/credits \ -H "Authorization: Bearer <jwt-token>"Response (200 OK):
{ "user_id": "user_123", "balance_usdc": "100.50", "created_at": "2024-01-15T10:30:00.000Z", "updated_at": "2024-01-20T14:22:00.000Z" }Architecture & Design Decisions
1. Database Schema
creditswith auto-increment primary keyuser_idto ensure one record per userbalance_usdcto maintain precision up to 7 decimal placesuser_idcolumn for fast lookupscreated_atandupdated_atusing Unix epoch2. Repository Pattern
Follows the existing repository pattern used throughout the codebase:
findByUserId,getOrCreateByUserId,updateBalance3. Route Implementation
requireAuthmiddleware (JWT or x-user-id)validatemiddleware4. Zero-Touch User Onboarding
New users automatically receive a credits record with zero balance on first request, eliminating manual setup requirements.
Files Changed
Created Files
migrations/0014_credits.sql(17 lines)src/repositories/creditsRepository.ts(78 lines)src/routes/billing/credits.ts(87 lines)src/__tests__/billing-credits.test.ts(344 lines)docs/billing-credits-endpoint.md(281 lines)Modified Files
src/db/schema.tscreditstable definitionCreditandNewCredittypessrc/routes/billing.tsKey Features
✅ Security
✅ Reliability
✅ Data Precision
✅ Developer Experience
Test Coverage
Test Categories (25+ test cases)
1. Authentication Tests
2. Balance Retrieval Tests
3. Error Handling Tests
4. Concurrency Tests
5. Response Format Tests
Running Tests
Documentation
API Documentation
Complete documentation added to
docs/billing-credits-endpoint.md:Code Documentation
Migration
Applying the Migration
Rollback (if needed)
The migration follows the existing pattern. A down migration can be created:
Security Considerations
Authentication & Authorization
Data Protection
Input Validation
Performance Considerations
Database
API
Caching (Future Enhancement)
Could add Redis caching for frequently accessed balances:
Error Handling
Standard Error Format
All errors follow the existing error response pattern:
{ "message": "Authentication required", "code": "UNAUTHORIZED", "requestId": "req_abc123", "details": [] }Error Codes
UNAUTHORIZED- Missing/invalid authenticationINVALID_AUTH_HEADER- Malformed Authorization headerVALIDATION_ERROR- Invalid query parametersINTERNAL_SERVER_ERROR- Database or server errorsCompatibility
Breaking Changes
None. This is a new endpoint with no impact on existing functionality.
Backwards Compatibility
Deployment Checklist
Future Enhancements
Phase 2 Features (not in this PR)
POST /api/billing/credits/topupGET /api/billing/credits/transactionsMonitoring Recommendations
Related Issues & PRs
Testing Instructions for Reviewers
1. Setup
2. Run Tests
npm test -- billing-credits3. Manual Testing
Test Case 1: New User
Test Case 2: x-user-id Header
Test Case 3: Missing Auth
curl -X GET http://localhost:3000/api/billing/credits # Expected: 401 UnauthorizedTest Case 4: Invalid Query Params
4. Database Verification
Code Quality
Linting
npm run lint # Expected: No errorsType Checking
npm run typecheck # Expected: No errorsTest Coverage
npm run test:coverage # Expected: >90% coverage for new filesReview Checklist
Code Review
Security Review
Testing Review
Documentation Review
This implementation follows the established patterns in the Callora Backend codebase:
src/repositories/developerRepository.tssrc/routes/billing.tssrc/errors/index.tsmigrations/0013_schema_versions.sql