fusion.billing.import.wizard backfills NexaCloud into Odoo: read-only psycopg2 reader (_read_nexacloud_rows, DSN from ir.config_parameter) split from pure-Odoo writes (_import_rows/_do_import) so the logic is unit-tested headless. Maps users→partners+links (reusing _resolve_or_create_partner, stashing stripe_customer_id), plans→a cpu_seconds charge catalog (included_quota=cpu_seconds_quota, unit_batch=3600, $0.0075/core-hour, plan_id NULL), and deployments→one DRAFT shadow sale.order per deployment with the flat price set explicitly. Shadow-safe by construction: draft + no payment token + charge plan_id NULL (rating cron is a no-op). Idempotent re-runs; per-row savepoints isolate bad rows; dry-run rolls back. 11 tests, 50/50 green on odoo-trial.
316 lines
13 KiB
Python
316 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
|
# Copyright 2026 Nexa Systems Inc.
|
|
# License OPL-1
|
|
"""NexaCloud → Odoo billing importer (sub-project #2a).
|
|
|
|
One-time, re-runnable, read-only backfill: read the NexaCloud Postgres and create the
|
|
equivalent Odoo records (partners + links, a cpu_seconds charge catalog, one DRAFT
|
|
shadow ``sale.order`` per deployment). Shadow-safe by construction — see the design spec
|
|
``docs/superpowers/specs/2026-05-27-nexacloud-billing-importer-design.md``.
|
|
|
|
Logic lives in model methods so it is unit-testable headless; the wizard button only
|
|
calls ``_read_nexacloud_rows()`` → ``_import_rows()``.
|
|
"""
|
|
import json
|
|
import logging
|
|
|
|
from odoo import api, fields, models
|
|
from odoo.exceptions import UserError
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
NEXACLOUD_CODE = "nexacloud"
|
|
CPU_METRIC_CODE = "cpu_seconds"
|
|
CPU_RATE_PER_CORE_HOUR = 0.0075 # NexaCloud CPU rate, CAD per core-hour
|
|
CPU_SECONDS_PER_CORE_HOUR = 3600.0 # one core-hour = 3600 cpu-seconds
|
|
|
|
|
|
class FusionBillingImportWizard(models.TransientModel):
|
|
_name = "fusion.billing.import.wizard"
|
|
_description = "Fusion Billing — NexaCloud Importer"
|
|
|
|
dry_run = fields.Boolean(
|
|
default=True,
|
|
help="Read and report what would be imported, without writing anything.")
|
|
result_summary = fields.Text(readonly=True)
|
|
|
|
def action_run_import(self):
|
|
self.ensure_one()
|
|
data = self._read_nexacloud_rows()
|
|
summary = self._import_rows(data, dry_run=self.dry_run)
|
|
self.result_summary = json.dumps(summary, indent=2, default=str)
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"res_model": self._name,
|
|
"res_id": self.id,
|
|
"view_mode": "form",
|
|
"target": "new",
|
|
}
|
|
|
|
# ----- read side (the ONLY code that touches NexaCloud) ------------------
|
|
def _read_nexacloud_rows(self):
|
|
"""Open a READ-ONLY psycopg2 connection to the nexacloud Postgres (DSN in
|
|
ir.config_parameter 'fusion_billing.nexacloud_dsn') and return rows as dicts.
|
|
Raises UserError on a missing DSN or a failed connection."""
|
|
import psycopg2
|
|
import psycopg2.extras
|
|
|
|
dsn = self.env["ir.config_parameter"].sudo().get_param(
|
|
"fusion_billing.nexacloud_dsn")
|
|
if not dsn:
|
|
raise UserError(
|
|
"NexaCloud DSN not configured. Set the 'fusion_billing.nexacloud_dsn' "
|
|
"system parameter to a read-only Postgres connection string.")
|
|
try:
|
|
conn = psycopg2.connect(dsn)
|
|
except Exception as e: # noqa: BLE001 - surface as a user error
|
|
raise UserError("Could not connect to the NexaCloud database: %s" % e)
|
|
try:
|
|
conn.set_session(readonly=True)
|
|
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
|
data = {}
|
|
cur.execute(
|
|
"SELECT id, email, full_name, company, billing_email, billing_address, "
|
|
"billing_city, billing_state, billing_postal_code, billing_country, "
|
|
"tax_id, stripe_customer_id FROM users")
|
|
data["users"] = [dict(r) for r in cur.fetchall()]
|
|
cur.execute(
|
|
"SELECT id, name, price_monthly, price_yearly, cpu_seconds_quota, "
|
|
"is_active FROM plans")
|
|
data["plans"] = [dict(r) for r in cur.fetchall()]
|
|
cur.execute(
|
|
"SELECT id, user_id, deployment_id, plan_id, status, billing_cycle, "
|
|
"current_period_start, current_period_end FROM subscriptions")
|
|
data["subscriptions"] = [dict(r) for r in cur.fetchall()]
|
|
return data
|
|
finally:
|
|
conn.close()
|
|
|
|
# ----- import side (pure Odoo; unit-tested) ------------------------------
|
|
@api.model
|
|
def _import_rows(self, data, dry_run=False):
|
|
"""Upsert NexaCloud rows into Odoo. Idempotent. With dry_run=True the writes
|
|
happen inside a savepoint that is rolled back, so nothing persists (the summary
|
|
is still returned)."""
|
|
if not dry_run:
|
|
return self._do_import(data)
|
|
result = {}
|
|
|
|
class _Rollback(Exception):
|
|
pass
|
|
|
|
try:
|
|
with self.env.cr.savepoint():
|
|
result.update(self._do_import(data))
|
|
raise _Rollback()
|
|
except _Rollback:
|
|
pass
|
|
result["dry_run"] = True
|
|
return result
|
|
|
|
@api.model
|
|
def _do_import(self, data):
|
|
service = self._fc_service()
|
|
metric = self._fc_cpu_metric()
|
|
recurrence_plans = {
|
|
"monthly": self._fc_recurrence_plan("month"),
|
|
"yearly": self._fc_recurrence_plan("year"),
|
|
}
|
|
summary = {"created": {}, "updated": {}, "skipped": [], "failed": []}
|
|
partner_by_user = {}
|
|
plan_ctx_by_id = {}
|
|
|
|
for u in data.get("users", []):
|
|
try:
|
|
with self.env.cr.savepoint():
|
|
link, created = self._import_user(service, u)
|
|
partner_by_user[str(u["id"])] = link.partner_id
|
|
self._bump(summary, created, "partners")
|
|
except Exception as e: # noqa: BLE001 - per-row isolation
|
|
summary["failed"].append(
|
|
{"kind": "user", "id": str(u.get("id")), "error": str(e)})
|
|
|
|
for p in data.get("plans", []):
|
|
try:
|
|
with self.env.cr.savepoint():
|
|
ctx, created = self._import_plan(metric, p)
|
|
plan_ctx_by_id[str(p["id"])] = ctx
|
|
self._bump(summary, created, "plans")
|
|
except Exception as e: # noqa: BLE001
|
|
summary["failed"].append(
|
|
{"kind": "plan", "id": str(p.get("id")), "error": str(e)})
|
|
|
|
for s in data.get("subscriptions", []):
|
|
partner = partner_by_user.get(str(s.get("user_id") or ""))
|
|
ctx = plan_ctx_by_id.get(str(s.get("plan_id") or ""))
|
|
if not partner or not ctx:
|
|
summary["skipped"].append({
|
|
"kind": "subscription", "id": str(s.get("id")),
|
|
"reason": "unresolved %s" % ("user" if not partner else "plan")})
|
|
continue
|
|
try:
|
|
with self.env.cr.savepoint():
|
|
_order, created = self._import_subscription(
|
|
service, partner, ctx, recurrence_plans, s)
|
|
self._bump(summary, created, "subscriptions")
|
|
except Exception as e: # noqa: BLE001
|
|
summary["failed"].append(
|
|
{"kind": "subscription", "id": str(s.get("id")), "error": str(e)})
|
|
|
|
_logger.info("NexaCloud import summary: %s", summary)
|
|
return summary
|
|
|
|
# ----- find-or-create helpers --------------------------------------------
|
|
@api.model
|
|
def _fc_service(self):
|
|
Service = self.env["fusion.billing.service"]
|
|
svc = Service.search([("code", "=", NEXACLOUD_CODE)], limit=1)
|
|
return svc or Service.create({"name": "NexaCloud", "code": NEXACLOUD_CODE})
|
|
|
|
@api.model
|
|
def _fc_cpu_metric(self):
|
|
Metric = self.env["fusion.billing.metric"]
|
|
m = Metric.search([("code", "=", CPU_METRIC_CODE)], limit=1)
|
|
return m or Metric.create({
|
|
"name": "CPU seconds", "code": CPU_METRIC_CODE,
|
|
"aggregation": "sum", "unit_label": "CPU-seconds"})
|
|
|
|
@api.model
|
|
def _fc_recurrence_plan(self, unit):
|
|
Plan = self.env["sale.subscription.plan"]
|
|
plan = Plan.search(
|
|
[("billing_period_value", "=", 1), ("billing_period_unit", "=", unit)], limit=1)
|
|
if plan:
|
|
return plan
|
|
label = "Monthly" if unit == "month" else "Yearly"
|
|
return Plan.create(
|
|
{"name": label, "billing_period_value": 1, "billing_period_unit": unit})
|
|
|
|
@api.model
|
|
def _fc_resolve_country(self, value):
|
|
Country = self.env["res.country"]
|
|
if not value:
|
|
return Country.browse()
|
|
v = value.strip()
|
|
return Country.search(
|
|
["|", ("code", "=ilike", v), ("name", "=ilike", v)], limit=1)
|
|
|
|
@staticmethod
|
|
def _bump(summary, created, key):
|
|
bucket = "created" if created else "updated"
|
|
summary[bucket][key] = summary[bucket].get(key, 0) + 1
|
|
|
|
# ----- per-entity import --------------------------------------------------
|
|
@api.model
|
|
def _import_user(self, service, urow):
|
|
Link = self.env["fusion.billing.account.link"]
|
|
ext = str(urow["id"])
|
|
email = (urow.get("billing_email") or urow.get("email") or "").strip().lower() or None
|
|
name = urow.get("full_name") or urow.get("company") or email or ext
|
|
existed = bool(Link.search(
|
|
[("service_id", "=", service.id), ("external_id", "=", ext)], limit=1))
|
|
link = Link._resolve_or_create_partner(service, ext, name=name, email=email)
|
|
vals = {}
|
|
if urow.get("billing_address"):
|
|
vals["street"] = urow["billing_address"]
|
|
if urow.get("billing_city"):
|
|
vals["city"] = urow["billing_city"]
|
|
if urow.get("billing_postal_code"):
|
|
vals["zip"] = urow["billing_postal_code"]
|
|
if urow.get("tax_id"):
|
|
vals["vat"] = urow["tax_id"]
|
|
if urow.get("stripe_customer_id"):
|
|
vals["x_fc_stripe_customer_id"] = urow["stripe_customer_id"]
|
|
country = self._fc_resolve_country(urow.get("billing_country"))
|
|
if country:
|
|
vals["country_id"] = country.id
|
|
if vals:
|
|
link.partner_id.write(vals)
|
|
return link, not existed
|
|
|
|
@api.model
|
|
def _import_plan(self, metric, prow):
|
|
Product = self.env["product.product"]
|
|
Charge = self.env["fusion.billing.charge"]
|
|
plan_code = str(prow["id"])
|
|
name = prow.get("name") or plan_code
|
|
price_monthly = float(prow.get("price_monthly") or 0.0)
|
|
price_yearly = float(prow.get("price_yearly") or 0.0)
|
|
created = False
|
|
|
|
sub_code = "NC-PLAN-%s" % plan_code
|
|
sub_product = Product.search([("default_code", "=", sub_code)], limit=1)
|
|
if not sub_product:
|
|
sub_product = Product.create({
|
|
"name": "NexaCloud %s" % name, "default_code": sub_code,
|
|
"type": "service", "recurring_invoice": True,
|
|
"list_price": price_monthly})
|
|
created = True
|
|
|
|
ov_code = "NC-CPU-OVG-%s" % plan_code
|
|
ov_product = Product.search([("default_code", "=", ov_code)], limit=1)
|
|
if not ov_product:
|
|
ov_product = Product.create({
|
|
"name": "NexaCloud CPU overage (%s)" % name, "default_code": ov_code,
|
|
"type": "service", "list_price": 0.0})
|
|
|
|
charge_vals = {
|
|
"name": "NexaCloud CPU overage — %s" % name,
|
|
"plan_code": plan_code, "metric_id": metric.id, "product_id": ov_product.id,
|
|
"included_quota": float(prow.get("cpu_seconds_quota") or 0.0),
|
|
"price_per_unit": CPU_RATE_PER_CORE_HOUR,
|
|
"unit_batch": CPU_SECONDS_PER_CORE_HOUR,
|
|
"charge_model": "standard",
|
|
# plan_id intentionally omitted (NULL) — shadow safety guarantee #3
|
|
}
|
|
charge = Charge.search(
|
|
[("plan_code", "=", plan_code), ("metric_id", "=", metric.id)], limit=1)
|
|
if charge:
|
|
charge.write(charge_vals)
|
|
else:
|
|
charge = Charge.create(charge_vals)
|
|
created = True
|
|
return {
|
|
"sub_product": sub_product, "overage_product": ov_product, "charge": charge,
|
|
"price_monthly": price_monthly, "price_yearly": price_yearly,
|
|
}, created
|
|
|
|
@api.model
|
|
def _import_subscription(self, service, partner, plan_ctx, recurrence_plans, srow):
|
|
SaleOrder = self.env["sale.order"]
|
|
SaleOrderLine = self.env["sale.order.line"]
|
|
sub_ext = str(srow["id"])
|
|
cycle = (srow.get("billing_cycle") or "monthly").lower()
|
|
rec_plan = recurrence_plans["yearly"] if cycle == "yearly" else recurrence_plans["monthly"]
|
|
price = plan_ctx["price_yearly"] if cycle == "yearly" else plan_ctx["price_monthly"]
|
|
product = plan_ctx["sub_product"]
|
|
order_vals = {
|
|
"partner_id": partner.id, "plan_id": rec_plan.id,
|
|
"x_fc_nexacloud_subscription_id": sub_ext,
|
|
"x_fc_nexacloud_deployment_id": str(srow.get("deployment_id") or ""),
|
|
"x_fc_billing_service_id": service.id, "x_fc_shadow": True,
|
|
}
|
|
existing = SaleOrder.search(
|
|
[("x_fc_nexacloud_subscription_id", "=", sub_ext)], limit=1)
|
|
if existing:
|
|
existing.write(order_vals)
|
|
line = existing.order_line.filtered(lambda l: l.product_id == product)
|
|
line_vals = {"product_uom_qty": 1, "price_unit": price}
|
|
if line:
|
|
line.write(line_vals)
|
|
else:
|
|
SaleOrderLine.create(
|
|
dict(order_id=existing.id, product_id=product.id, **line_vals))
|
|
order = existing
|
|
created = False
|
|
else:
|
|
order_vals["order_line"] = [(0, 0, {
|
|
"product_id": product.id, "product_uom_qty": 1, "price_unit": price})]
|
|
order = SaleOrder.create(order_vals)
|
|
created = True
|
|
# guarantee the explicit price stuck (a pricelist compute may have overwritten it)
|
|
line = order.order_line.filtered(lambda l: l.product_id == product)
|
|
if line and line.price_unit != price:
|
|
line.price_unit = price
|
|
return order, created
|