feat(billing): idempotent usage ingestion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
gsinghpal
2026-05-27 02:52:05 -04:00
parent 1e34a67384
commit eb1ee85d24
3 changed files with 56 additions and 1 deletions

View File

@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1
from odoo import fields, models
from odoo import api, fields, models
class FusionBillingUsage(models.Model):
@@ -37,3 +37,24 @@ class FusionBillingUsage(models.Model):
_idempotency_uniq = models.Constraint(
"unique(idempotency_key)", "Usage idempotency key must be unique.",
)
@api.model
def _record_usage(self, subscription, metric_code, quantity, period_start, period_end, idem=None):
"""Upsert one aggregated usage row. Same idempotency key updates in place (no double-count)."""
metric = self.env['fusion.billing.metric'].search([('code', '=', metric_code)], limit=1)
if not metric:
raise ValueError("Unknown metric code: %s" % metric_code)
vals = {
'subscription_id': subscription.id,
'metric_id': metric.id,
'period_start': period_start,
'period_end': period_end,
'quantity': quantity,
'idempotency_key': idem,
}
if idem:
existing = self.search([('idempotency_key', '=', idem)], limit=1)
if existing:
existing.write({'quantity': quantity})
return existing
return self.create(vals)