feat(billing): idempotent usage ingestion
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user