Skip to content

feat(billing): add generic BillingUsage model for quota tracking#3273

Merged
PierreBrisorgueil merged 2 commits intomasterfrom
feat/billing-usage-model
Mar 18, 2026
Merged

feat(billing): add generic BillingUsage model for quota tracking#3273
PierreBrisorgueil merged 2 commits intomasterfrom
feat/billing-usage-model

Conversation

@PierreBrisorgueil
Copy link
Contributor

@PierreBrisorgueil PierreBrisorgueil commented Mar 18, 2026

Summary

  • Add BillingUsage Mongoose model with organizationId, month (YYYY-MM), and free-form counters (Mixed), with compound unique index on { organizationId, month }
  • Add repository with get, increment (atomic $inc with upsert), and reset operations
  • Add service layer that auto-computes current month and delegates to repository
  • Add Zod validation schema for BillingUsage
  • Add 11 unit tests covering schema validation, upsert creation, atomic increment, empty counters fallback, and reset

Closes #3269

Test plan

  • npm run lint passes (0 errors)
  • All 227 unit tests pass (14 suites)
  • New billing.usage.unit.tests.js — 11 tests covering schema + service layer

Summary by CodeRabbit

  • New Features

    • Added billing usage tracking functionality to monitor organizational consumption metrics on a monthly basis.
    • Enabled retrieval, increment, and reset operations for usage counters.
  • Tests

    • Added comprehensive unit tests for billing usage validation and tracking operations.

Copilot AI review requested due to automatic review settings March 18, 2026 20:40
@coderabbitai
Copy link

coderabbitai bot commented Mar 18, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 52 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b29ca87a-e3bc-485f-97b9-6a322acedca6

📥 Commits

Reviewing files that changed from the base of the PR and between d2d42b2 and f588da1.

📒 Files selected for processing (5)
  • modules/billing/models/billing.usage.model.mongoose.js
  • modules/billing/models/billing.usage.schema.js
  • modules/billing/repositories/billing.usage.repository.js
  • modules/billing/services/billing.usage.service.js
  • modules/billing/tests/billing.usage.unit.tests.js

Walkthrough

A new generic billing usage tracking system is introduced with a Mongoose model, Zod validation schema, repository data-access layer, service coordinator, and comprehensive unit tests. Supports atomic counter increments per organization and month without project-specific logic.

Changes

Cohort / File(s) Summary
Model & Schema Definitions
modules/billing/models/billing.usage.model.mongoose.js, modules/billing/models/billing.usage.schema.js
Mongoose schema with organizationId (indexed, required), month (indexed, required), and counters (free-form object). Compound unique index on (organizationId, month). Zod schema validates organizationId as 24-character hex ObjectId, month as YYYY-MM format, and counters as string-to-number record.
Data Access Layer
modules/billing/repositories/billing.usage.repository.js
Three repository functions: get() retrieves usage by org and month; increment() performs atomic $inc on nested counters with upsert; reset() clears counters to empty object. All validate organizationId as ObjectId.
Service Layer
modules/billing/services/billing.usage.service.js
Service wraps repository with month-aware API: currentMonth() computes YYYY-MM, increment(orgId, key, amount) increments counter for current month, get(orgId) returns usage or default empty counters, reset(orgId) clears current month's counters.
Unit Tests
modules/billing/tests/billing.usage.unit.tests.js
Comprehensive test suite covering schema validation (ObjectId/month format, defaults), service behavior (mocked repository), increment/get/reset operations, and atomic counter mechanics with before/after setup.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a generic BillingUsage model for quota tracking, which is the primary objective of this PR.
Description check ✅ Passed The description covers all key sections: summary of changes, linked issue reference, and test validation results. All major deliverables are documented.
Linked Issues check ✅ Passed All coding requirements from issue #3269 are met: BillingUsage model with organizationId, month, and counters [#3269]; atomic increment with upsert [#3269]; repository with get/increment/reset [#3269]; service layer with auto-computed month [#3269]; Zod schema and 11 tests [#3269].
Out of Scope Changes check ✅ Passed All changes align with issue #3269 objectives: model definition, repository layer, service layer, schema validation, and unit tests. No out-of-scope modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/billing-usage-model
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a generic billing usage/quota tracking layer to the billing module, providing a monthly bucketed BillingUsage model with atomic counter increments and a thin service wrapper for downstream quota enforcement.

Changes:

  • Introduces BillingUsage Mongoose model (organizationId, month, counters) with a compound unique index for per-org monthly usage.
  • Adds repository + service APIs to get, increment (atomic $inc with upsert), and reset usage counters.
  • Adds Zod schema validation and a new unit test suite covering schema defaults/validation and service delegation behavior.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
modules/billing/models/billing.usage.model.mongoose.js New Mongoose model for monthly per-organization usage counters with unique index.
modules/billing/models/billing.usage.schema.js New Zod schema for validating usage payloads and defaulting counters.
modules/billing/repositories/billing.usage.repository.js New data access layer for get/increment/reset usage documents.
modules/billing/services/billing.usage.service.js New service wrapper that computes current month and delegates to repository.
modules/billing/tests/billing.usage.unit.tests.js New unit tests for the Zod schema and service behavior via mocked repository.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@modules/billing/models/billing.usage.model.mongoose.js`:
- Around line 13-23: The schema currently defines separate indexes on
organizationId and month but also creates a compound unique index {
organizationId: 1, month: 1 }; remove the redundant individual index on
organizationId to avoid duplicate indexes and write overhead while keeping the
compound unique index and the individual index on month if you still need
month-only queries; update the billing usage schema by deleting the index: true
(or index definition) on the organizationId field (leave month.index if
required) and ensure the compound unique index ({ organizationId: 1, month: 1 })
remains defined.

In `@modules/billing/models/billing.usage.schema.js`:
- Line 13: The month field's regex in the billing usage schema (the month:
z.string().trim().regex(...) entry) only checks format and allows invalid months
like 00 or 13; update the validation to enforce that the MM portion is between
01 and 12 (i.e., restrict months to 01–12) and keep the YYYY- MM format, e.g.,
replace the current generic YYYY-MM pattern with one that constrains the month
range so downstream code can assume valid calendar months.

In `@modules/billing/repositories/billing.usage.repository.js`:
- Around line 29-33: The increment function interpolates the `key` directly into
the update path (`counters.${key}`) which allows dots or other characters to
create unintended nested documents; add validation/sanitization in the increment
function (or a shared validator used by BillingUsage repository) to reject or
normalize keys containing dots or other unsafe characters (e.g., allow only a
safe pattern like alphanumerics, underscore, hyphen) before calling
BillingUsage.findOneAndUpdate, and throw a clear error if the key is invalid so
callers cannot trigger nested paths via `counters.${key}`.
- Around line 29-33: The increment function omits ObjectId validation for
organizationId which can cause a Mongoose cast error on upsert; add the same
validation used in get/reset (e.g., using mongoose.Types.ObjectId.isValid or
mongoose.isValidObjectId) at the start of the increment function and throw or
return a rejected promise with a clear error when invalid, before calling
BillingUsage.findOneAndUpdate so BillingUsage.findOneAndUpdate({ organizationId,
month }, ...) is only invoked with a valid ObjectId.

In `@modules/billing/services/billing.usage.service.js`:
- Around line 10-15: The currentMonth function uses local time (new
Date().getMonth()) which is timezone-dependent; change currentMonth to construct
the date in UTC by using getUTCFullYear() and getUTCMonth() (add 1 and pad with
String(...).padStart(2,'0')) so the returned YYYY-MM is based on UTC and
consistent across servers and DST changes.
- Around line 31-34: The function get calls currentMonth() twice which can race
across a month boundary; capture the month once into a local variable (e.g.,
const month = currentMonth()) and use that variable in the call to
UsageRepository.get(organizationId, month) and in the fallback object ({
organizationId, month, counters: {} }) so both paths use the same month value;
update the get function to reference month instead of calling currentMonth()
again.

In `@modules/billing/tests/billing.usage.unit.tests.js`:
- Line 4: The test file imports jest, beforeEach, and afterEach but omits the
Jest globals used elsewhere; update the import from '@jest/globals' to also
import describe, test, and expect so the file explicitly imports describe, test,
expect (in addition to jest, beforeEach, afterEach) to match other tests and
avoid relying on implicit globals.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: cce0f1d6-e43c-473e-bd99-9df8745e9325

📥 Commits

Reviewing files that changed from the base of the PR and between 0eede6e and d2d42b2.

📒 Files selected for processing (5)
  • modules/billing/models/billing.usage.model.mongoose.js
  • modules/billing/models/billing.usage.schema.js
  • modules/billing/repositories/billing.usage.repository.js
  • modules/billing/services/billing.usage.service.js
  • modules/billing/tests/billing.usage.unit.tests.js

@PierreBrisorgueil
Copy link
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Mar 18, 2026

✅ Actions performed

Full review triggered.

- Validate organizationId in increment(), sanitize counter key against injection
- Handle E11000 duplicate key race on concurrent upserts (retry once)
- Add runValidators to reset() for consistency with increment()
- Tighten month regex to reject invalid months (00, 13)
- Use UTC for currentMonth() to avoid timezone-dependent boundaries
- Capture month once in get() to prevent cross-boundary inconsistency
- Remove redundant individual index on organizationId (compound covers it)
- Add missing Jest globals imports in test file
- Add tests for semantically invalid month values
@PierreBrisorgueil PierreBrisorgueil merged commit cf4763f into master Mar 18, 2026
3 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the feat/billing-usage-model branch March 18, 2026 21:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(billing): generic BillingUsage model for quota tracking

2 participants