cloudleak-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cloudleak/money.py ADDED
@@ -0,0 +1,78 @@
1
+ """Exact decimal handling.
2
+
3
+ DuckDB computes in DECIMAL(38,12), Python receives decimal.Decimal, and JSON
4
+ receives strings. Parquet inputs can already contain binary floating amounts.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from decimal import ROUND_HALF_EVEN, Decimal, localcontext
11
+ from functools import wraps
12
+ from typing import ParamSpec, TypeVar
13
+
14
+ SCALE = 12
15
+ SQL_MONEY = f"DECIMAL(38,{SCALE})"
16
+ ZERO = Decimal(0)
17
+ P = ParamSpec("P")
18
+ T = TypeVar("T")
19
+
20
+
21
+ def money_context(func: Callable[P, T]) -> Callable[P, T]:
22
+ """Preserve DECIMAL(38,12) sums and intermediate quantity/rate products."""
23
+ @wraps(func)
24
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> T:
25
+ with localcontext() as ctx:
26
+ ctx.prec = max(ctx.prec, 128)
27
+ return func(*args, **kwargs)
28
+ return wrapped
29
+
30
+
31
+ def to_decimal(value: object) -> Decimal:
32
+ if value is None:
33
+ return ZERO
34
+ if isinstance(value, Decimal):
35
+ return value
36
+ if isinstance(value, int):
37
+ return Decimal(value)
38
+ if isinstance(value, str):
39
+ return Decimal(value)
40
+ raise TypeError(f"refusing to convert {type(value).__name__} to money")
41
+
42
+
43
+ def fmt(value: Decimal | None) -> str | None:
44
+ """Canonical string form: no exponent, trailing zeros trimmed, at least 2 dp."""
45
+ if value is None:
46
+ return None
47
+ value = to_decimal(value)
48
+ if value == 0:
49
+ return "0.00"
50
+ text = format(value, "f")
51
+ if "." not in text:
52
+ return text + ".00"
53
+ whole, frac = text.split(".")
54
+ frac = frac.rstrip("0")
55
+ if len(frac) < 2:
56
+ frac = frac.ljust(2, "0")
57
+ return f"{whole}.{frac}"
58
+
59
+
60
+ def display(value: Decimal | None, currency: str | None = None, places: int = 2) -> str:
61
+ """Human display, rounded half-even. Never used for arithmetic."""
62
+ if value is None:
63
+ return "n/a"
64
+ value = to_decimal(value)
65
+ q = Decimal(1).scaleb(-places)
66
+ with localcontext() as ctx:
67
+ ctx.prec = max(80, value.adjusted() + places + 2)
68
+ rounded = value.quantize(q, rounding=ROUND_HALF_EVEN)
69
+ text = f"{rounded:,.{places}f}"
70
+ if text.startswith("-0.") and rounded == 0:
71
+ text = text[1:]
72
+ return f"{text} {currency}" if currency else text
73
+
74
+
75
+ def pct(part: Decimal, whole: Decimal) -> str:
76
+ if whole == 0:
77
+ return "n/a"
78
+ return f"{(to_decimal(part) / to_decimal(whole) * 100).quantize(Decimal('0.1'), rounding=ROUND_HALF_EVEN)}%"
@@ -0,0 +1,19 @@
1
+ """Provider detection. Each adapter scores a header set; the best score wins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from cloudleak.providers import aws, azure, focus, gcp
6
+ from cloudleak.providers.base import Columns, Mapping
7
+
8
+ ADAPTERS = {"focus": focus, "aws": aws, "azure": azure, "gcp": gcp}
9
+
10
+
11
+ def detect(cols: Columns) -> tuple[str | None, float]:
12
+ scores = {name: mod.score(cols) for name, mod in ADAPTERS.items()}
13
+ best = max(scores, key=lambda k: scores[k])
14
+ if scores[best] <= 0:
15
+ return None, 0.0
16
+ return best, round(scores[best], 3)
17
+
18
+
19
+ __all__ = ["ADAPTERS", "Columns", "Mapping", "detect"]
@@ -0,0 +1,133 @@
1
+ """AWS Cost and Usage Report adapter (legacy CUR and CUR 2.0 / Data Exports).
2
+
3
+ Both generations normalize to the same snake_case names
4
+ (``lineItem/UnblendedCost`` -> ``line_item_unblended_cost``), so one adapter
5
+ serves both. AWS-delivered FOCUS exports go through the FOCUS adapter.
6
+
7
+ Accounting notes encoded here:
8
+ * ``line_item_unblended_cost`` summed over *all* line item types (usage,
9
+ tax, credits, refunds, discounts, fees) is the invoiced amount. CloudLeak's
10
+ primary cost is therefore unblended cost with basis ``billed``.
11
+ * ``bill_invoice_id`` stays blank until AWS finalizes the billing period.
12
+ * Effective (amortized) cost follows the documented CUR formula and is only
13
+ computed when every column it needs is present; otherwise it is NULL rather
14
+ than a guess.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from cloudleak.providers.base import NULL_MONEY, Columns, Mapping, json_object_from_columns, month_start
20
+
21
+ SIGNATURE = ("line_item_unblended_cost", "line_item_usage_account_id", "line_item_line_item_type",
22
+ "line_item_product_code", "bill_payer_account_id")
23
+
24
+
25
+ def score(cols: Columns) -> float:
26
+ hits = sum(1 for c in SIGNATURE if c in cols.by_norm)
27
+ return hits / len(SIGNATURE) if "line_item_unblended_cost" in cols.by_norm or hits >= 3 else 0.0
28
+
29
+
30
+ CHARGE_MAP = """CASE {t}
31
+ WHEN 'Usage' THEN 'usage'
32
+ WHEN 'DiscountedUsage' THEN 'usage'
33
+ WHEN 'SavingsPlanCoveredUsage' THEN 'usage'
34
+ WHEN 'Tax' THEN 'tax'
35
+ WHEN 'Credit' THEN 'credit'
36
+ WHEN 'Refund' THEN 'refund'
37
+ WHEN 'Fee' THEN 'fee'
38
+ WHEN 'RIFee' THEN 'purchase'
39
+ WHEN 'SavingsPlanRecurringFee' THEN 'purchase'
40
+ WHEN 'SavingsPlanUpfrontFee' THEN 'purchase'
41
+ WHEN 'SavingsPlanNegation' THEN 'discount'
42
+ WHEN 'BundledDiscount' THEN 'discount'
43
+ WHEN 'EdpDiscount' THEN 'discount'
44
+ WHEN 'PrivateRateDiscount' THEN 'discount'
45
+ WHEN 'DistributorDiscount' THEN 'discount'
46
+ WHEN 'SppDiscount' THEN 'discount'
47
+ WHEN 'Discount' THEN 'discount'
48
+ ELSE CASE WHEN {t} IS NULL THEN 'usage' ELSE 'unknown' END
49
+ END"""
50
+
51
+
52
+ def build(cols: Columns) -> Mapping:
53
+ c = cols
54
+ unblended = c.money("line_item_unblended_cost")
55
+ ltype = c.text("line_item_line_item_type")
56
+ is_cur2 = "line_item_unblended_cost" in c.by_norm and c.by_norm["line_item_unblended_cost"].islower()
57
+
58
+ tag_cols = c.prefixed("resource_tags_")
59
+ if "resource_tags" in c.by_norm: # CUR 2.0: JSON map in one column
60
+ tags = f"CASE WHEN json_valid({c.text('resource_tags')}) AND {c.text('resource_tags')} NOT IN ('{{}}') " \
61
+ f"THEN {c.text('resource_tags')} END"
62
+ else: # legacy: one column per activated tag, e.g. resourceTags/user:Owner
63
+ def key_of(original: str) -> str:
64
+ return original.split("/", 1)[1] if "/" in original else original
65
+ tags = json_object_from_columns(c, tag_cols, key_of)
66
+
67
+ # Amortized cost, per the AWS CUR documentation. Needs RI and SP columns
68
+ # only when such rows exist; NULL when a required column is absent.
69
+ unused_ri = (f"({c.money('reservation_unused_amortized_upfront_fee_for_billing_period')} "
70
+ f"+ {c.money('reservation_unused_recurring_fee')})")
71
+ fee = (f"CASE WHEN {c.text('reservation_reservation_arn')} IS NOT NULL THEN 0 ELSE {unblended} END"
72
+ if c.has("reservation_reservation_arn") else NULL_MONEY)
73
+ effective = f"""CASE {ltype}
74
+ WHEN 'SavingsPlanCoveredUsage' THEN {c.money('savings_plan_savings_plan_effective_cost')}
75
+ WHEN 'SavingsPlanRecurringFee' THEN {c.money('savings_plan_total_commitment_to_date')}
76
+ - {c.money('savings_plan_used_commitment')}
77
+ WHEN 'SavingsPlanNegation' THEN 0
78
+ WHEN 'SavingsPlanUpfrontFee' THEN 0
79
+ WHEN 'DiscountedUsage' THEN {c.money('reservation_effective_cost')}
80
+ WHEN 'RIFee' THEN {unused_ri}
81
+ WHEN 'Fee' THEN {fee}
82
+ ELSE {unblended}
83
+ END"""
84
+ unused_commit = f"CASE WHEN {ltype} = 'RIFee' AND {unused_ri} > 0 THEN 'unused' END"
85
+
86
+ pricing = f"""CASE
87
+ WHEN {ltype} IN ('DiscountedUsage','SavingsPlanCoveredUsage','RIFee','SavingsPlanRecurringFee',
88
+ 'SavingsPlanUpfrontFee','SavingsPlanNegation') THEN 'commitment'
89
+ WHEN lower(COALESCE({c.text('pricing_term')}, '')) = 'spot'
90
+ OR {c.text('line_item_usage_type')} ILIKE '%SpotUsage%' THEN 'spot'
91
+ WHEN {ltype} = 'Usage' THEN 'on_demand'
92
+ ELSE 'unknown' END"""
93
+
94
+ period_start = c.ts("bill_billing_period_start_date")
95
+ charge_start = c.ts("line_item_usage_start_date")
96
+ m = Mapping(
97
+ provider="aws",
98
+ dataset="aws_cur2" if is_cur2 else "aws_cur_legacy",
99
+ cost_basis="billed",
100
+ cost_raw=c.text("line_item_unblended_cost"),
101
+ cost=unblended,
102
+ effective_cost=effective,
103
+ list_cost=c.money("pricing_public_on_demand_cost"),
104
+ billing_account_id=c.text("bill_payer_account_id"),
105
+ sub_account_id=c.text("line_item_usage_account_id"),
106
+ sub_account_name=c.text("line_item_usage_account_name"),
107
+ invoice_id=c.text("bill_invoice_id"),
108
+ invoice_issuer=c.text("bill_invoicing_entity"),
109
+ billing_period_start=f"COALESCE({month_start(period_start)}, {month_start(charge_start)})",
110
+ charge_start=charge_start,
111
+ charge_end=c.ts("line_item_usage_end_date"),
112
+ currency=c.text("line_item_currency_code", "bill_billing_currency"),
113
+ charge_raw=ltype,
114
+ charge_category=CHARGE_MAP.format(t=ltype),
115
+ service=c.text("line_item_product_code", "product_servicecode", "product_product_name"),
116
+ sku=c.text("line_item_usage_type", "product_usagetype"),
117
+ sku_detail=c.text("line_item_operation", "line_item_line_item_description"),
118
+ resource_id=c.text("line_item_resource_id"),
119
+ region=c.text("product_region_code", "product_region", "line_item_availability_zone", "product_location"),
120
+ usage_quantity=c.money("line_item_usage_amount"),
121
+ usage_unit=c.text("pricing_unit", "line_item_pricing_unit"),
122
+ tags=tags,
123
+ pricing_model=pricing,
124
+ commitment_status=unused_commit,
125
+ )
126
+ m.capabilities = {
127
+ "invoice_id": c.has("bill_invoice_id"),
128
+ "resource_id": c.has("line_item_resource_id"),
129
+ "tags": bool(tag_cols) or c.has("resource_tags"),
130
+ "effective_cost": False, # engine verifies coverage on the actual rows
131
+ "split_cost_allocation": bool(c.prefixed("split_line_item_")),
132
+ }
133
+ return m
@@ -0,0 +1,163 @@
1
+ """Azure Cost Management export adapter (EA, MCA, CSP; actual and amortized).
2
+
3
+ Azure writes actual and amortized costs to *separate* exports with nearly
4
+ identical columns. Summing both double counts, so CloudLeak records which
5
+ basis each file carries and never mixes bases in one total.
6
+
7
+ Azure amortized exports can legitimately contain rows that are identical in
8
+ every column. They are kept: blind de-duplication silently halves spend.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from cloudleak.providers.base import NULL_MONEY, Columns, Mapping, month_start, norm
14
+
15
+ SIGNATURE = ("cost_in_billing_currency", "pre_tax_cost", "meter_category", "subscription_id",
16
+ "resource_group", "meter_sub_category", "charge_type", "subscription_guid")
17
+
18
+
19
+ def score(cols: Columns) -> float:
20
+ if not cols.has("cost_in_billing_currency", "pre_tax_cost", "cost", "cost_in_usd"):
21
+ return 0.0
22
+ hits = sum(1 for c in SIGNATURE if c in cols.by_norm)
23
+ return hits / len(SIGNATURE) if hits >= 2 and cols.has("meter_category", "meter_id", "meter_name") else 0.0
24
+
25
+
26
+ CHARGE_MAP = """CASE lower({t})
27
+ WHEN 'usage' THEN 'usage'
28
+ WHEN 'purchase' THEN 'purchase'
29
+ WHEN 'refund' THEN 'refund'
30
+ WHEN 'unusedreservation' THEN 'usage'
31
+ WHEN 'unusedsavingsplan' THEN 'usage'
32
+ WHEN 'roundingadjustment' THEN 'adjustment'
33
+ WHEN 'adjustment' THEN 'adjustment'
34
+ WHEN 'tax' THEN 'tax'
35
+ WHEN 'credit' THEN 'credit'
36
+ ELSE CASE WHEN {t} IS NULL THEN 'usage' ELSE 'unknown' END
37
+ END"""
38
+
39
+
40
+ def basis_from_name(name: str) -> str | None:
41
+ # Accept provider export names (ActualCost / AmortizedCost) and tokens
42
+ # such as "azure-actual", without inferring a basis from "contractual".
43
+ tokens = set(norm(name).split("_"))
44
+ actual = bool(tokens & {"actual", "actualcost"})
45
+ amortized = bool(tokens & {"amortized", "amortised", "amortizedcost", "amortisedcost"})
46
+ if actual and amortized:
47
+ return "conflict"
48
+ if actual:
49
+ return "billed"
50
+ return "amortized" if amortized else None
51
+
52
+
53
+ def list_cost_sql(c: Columns) -> str:
54
+ billing = c.text("billing_currency", "billing_currency_code", "currency")
55
+ pricing = c.text("pricing_currency", "pricing_currency_code")
56
+ rate = c.money("exchange_rate_pricing_to_billing")
57
+ price = c.money("pay_g_price", "payg_price")
58
+ quantity = c.money("quantity", "usage_quantity")
59
+ derived = NULL_MONEY
60
+ if c.has("pay_g_price", "payg_price") and c.has("quantity", "usage_quantity"):
61
+ fx = (f"CASE WHEN {billing} IS NULL THEN NULL WHEN upper({billing}) = upper({pricing}) THEN 1 "
62
+ f"WHEN {rate} > 0 THEN {rate} END")
63
+ # Narrow the intermediate precision only when exact. A raw three-way
64
+ # DECIMAL(38,12) product has just two integral digits in DuckDB.
65
+ derived = (f"(SELECT cl_money(CAST(TRY(subtotal * fx) AS VARCHAR)) "
66
+ f"FROM (SELECT cl_money(CAST(TRY(price * qty) AS VARCHAR)) AS subtotal, fx "
67
+ f"FROM (SELECT {price} AS price, {quantity} AS qty, {fx} AS fx)))")
68
+ direct = c.text("payg_cost_in_billing_currency", "pay_g_cost_in_billing_currency")
69
+ return f"CASE WHEN {direct} IS NOT NULL THEN cl_money({direct}) ELSE {derived} END"
70
+
71
+
72
+ def build(cols: Columns, *, basis_hint: str | None = None) -> Mapping:
73
+ c = cols
74
+ ctype = c.text("charge_type")
75
+ cost_col = c.first("cost_in_billing_currency", "pre_tax_cost", "cost")
76
+ cost_raw = c.text(cost_col) if cost_col else c.text("cost_in_usd")
77
+ basis = basis_hint or "unknown"
78
+ if cost_col is None:
79
+ basis = "unknown"
80
+
81
+ # Tags: EA writes `"k": "v","k2": "v2"` without braces; MCA writes a JSON object.
82
+ raw_tags = c.text("tags")
83
+ tags = (
84
+ f"CASE WHEN {raw_tags} IS NULL THEN NULL "
85
+ f"WHEN json_valid({raw_tags}) THEN NULLIF(CAST({raw_tags} AS VARCHAR), '{{}}') "
86
+ f"WHEN json_valid('{{' || {raw_tags} || '}}') THEN '{{' || {raw_tags} || '}}' "
87
+ f"ELSE json_object('_unparsed', {raw_tags}) END"
88
+ )
89
+ pricing = c.text("pricing_model")
90
+ date = c.ts("date", "usage_date", "usage_date_time")
91
+ period = c.ts("billing_period_start_date")
92
+ m = Mapping(
93
+ provider="azure",
94
+ dataset="azure_" + {"billed": "actual", "amortized": "amortized"}.get(basis, "unknown_basis"),
95
+ cost_basis=basis,
96
+ cost_raw=cost_raw,
97
+ cost=f"cl_money({cost_raw})",
98
+ effective_cost=f"cl_money({cost_raw})" if basis == "amortized" else "CAST(NULL AS DECIMAL(38,12))",
99
+ list_cost=list_cost_sql(c),
100
+ billing_account_id=c.text("billing_account_id", "billing_profile_id", "enrollment_number"),
101
+ sub_account_id=c.text("subscription_id", "subscription_guid"),
102
+ sub_account_name=c.text("subscription_name"),
103
+ invoice_id=c.text("invoice_id", "invoice"),
104
+ invoice_issuer=c.text("invoice_issuer_name"),
105
+ billing_period_start=f"COALESCE({month_start(period)}, {month_start(date)})",
106
+ charge_start=date,
107
+ charge_end=f"{date} + INTERVAL 1 DAY",
108
+ currency=c.text("billing_currency", "billing_currency_code", "currency"),
109
+ charge_raw=ctype,
110
+ charge_category=CHARGE_MAP.format(t=ctype),
111
+ service=c.text("meter_category", "service_name", "consumed_service", "product_name"),
112
+ sku=(
113
+ f"concat_ws(' / ', {c.text('meter_sub_category')}, {c.text('meter_name')})"
114
+ if c.has("meter_sub_category", "meter_name") else c.text("product_name")
115
+ ),
116
+ sku_detail=c.text("product_name", "meter_id", "product"),
117
+ resource_id=c.text("resource_id", "instance_id", "instance_name", "resource_name"),
118
+ region=c.text("resource_location", "location", "meter_region"),
119
+ usage_quantity=c.money("quantity", "usage_quantity"),
120
+ usage_unit=c.text("unit_of_measure"),
121
+ tags=tags if c.has("tags") else "CAST(NULL AS VARCHAR)",
122
+ pricing_model=(
123
+ f"CASE lower(COALESCE({pricing}, '')) WHEN 'ondemand' THEN 'on_demand' "
124
+ f"WHEN 'reservation' THEN 'commitment' WHEN 'savingsplan' THEN 'commitment' "
125
+ f"WHEN 'spot' THEN 'spot' ELSE 'unknown' END"
126
+ ),
127
+ commitment_status=(
128
+ f"CASE WHEN lower({ctype}) IN ('unusedreservation','unusedsavingsplan') THEN 'unused' END"
129
+ ),
130
+ )
131
+ m.capabilities = {
132
+ "invoice_id": c.has("invoice_id"),
133
+ "resource_id": c.has("resource_id", "instance_id"),
134
+ "tags": c.has("tags"),
135
+ "effective_cost": basis == "amortized",
136
+ }
137
+ if basis == "unknown":
138
+ m.notes.append(
139
+ "Could not tell whether this Azure export is actual or amortized cost. "
140
+ "Name the file or folder with 'actual' or 'amortized' so totals are never mixed."
141
+ )
142
+ return m
143
+
144
+
145
+ def infer_basis_sql(table: str, cols: Columns) -> str | None:
146
+ """SQL returning 'amortized' / 'billed' / NULL from charge-type evidence.
147
+
148
+ Amortized exports carry UnusedReservation/UnusedSavingsPlan rows; actual
149
+ exports carry Purchase rows with non-zero cost.
150
+ """
151
+ if not cols.has("charge_type"):
152
+ return None
153
+ cost_col = cols.first("cost_in_billing_currency", "pre_tax_cost", "cost")
154
+ if cost_col is None:
155
+ return None
156
+ ct, cost = cols.text("charge_type"), cols.money(cost_col)
157
+ unused = f"bool_or(lower({ct}) IN ('unusedreservation','unusedsavingsplan'))"
158
+ purchase = f"bool_or(lower({ct}) = 'purchase' AND {cost} <> 0)"
159
+ return f"""SELECT CASE
160
+ WHEN {unused} AND {purchase} THEN 'conflict'
161
+ WHEN {unused} THEN 'amortized'
162
+ WHEN {purchase} THEN 'billed'
163
+ ELSE NULL END FROM "{table}" """
@@ -0,0 +1,244 @@
1
+ """Shared machinery for provider adapters.
2
+
3
+ Adapters never touch row data in Python. Each one inspects a raw table's
4
+ column names and returns SQL expressions that DuckDB evaluates. Raw tables
5
+ hold every source column as VARCHAR, so no value is ever coerced through a
6
+ float or silently guessed by type inference.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from functools import lru_cache
14
+
15
+ from cloudleak.money import SQL_MONEY
16
+
17
+ NULL_STR = "CAST(NULL AS VARCHAR)"
18
+ NULL_MONEY = f"CAST(NULL AS {SQL_MONEY})"
19
+
20
+ _CAMEL_1 = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
21
+ _CAMEL_2 = re.compile(r"(?<=[A-Z])(?=[A-Z][a-z])")
22
+ _NON_ALNUM = re.compile(r"[^0-9a-zA-Z]+")
23
+
24
+
25
+ @lru_cache(maxsize=65536)
26
+ def norm(name: str) -> str:
27
+ """Normalize a column name across vendor spellings.
28
+
29
+ ``lineItem/UnblendedCost`` and ``line_item_unblended_cost`` both become
30
+ ``line_item_unblended_cost``; ``service.description`` becomes
31
+ ``service_description``; ``CostInBillingCurrency`` and
32
+ ``costInBillingCurrency`` both become ``cost_in_billing_currency``.
33
+ """
34
+ text = name.strip().lstrip("")
35
+ text = _CAMEL_1.sub("_", text)
36
+ text = _CAMEL_2.sub("_", text)
37
+ text = _NON_ALNUM.sub("_", text).strip("_").lower()
38
+ text = re.sub(r"_+", "_", text)
39
+ # AWS CUR 2.0 spells ARN columns as a_r_n.
40
+ return text.replace("_a_r_n", "_arn")
41
+
42
+
43
+ def quote_ident(name: str) -> str:
44
+ return '"' + name.replace('"', '""') + '"'
45
+
46
+
47
+ def sql_str(value: str) -> str:
48
+ return "'" + value.replace("'", "''") + "'"
49
+
50
+
51
+ @dataclass
52
+ class Columns:
53
+ """Column lookup for one raw table, by normalized name."""
54
+
55
+ original: list[str]
56
+ by_norm: dict[str, str] = field(default_factory=dict)
57
+ collisions: list[tuple[str, str]] = field(default_factory=list)
58
+
59
+ @classmethod
60
+ def from_names(cls, names: list[str]) -> Columns:
61
+ cols = cls([n for n in names if n != "__cl_row"])
62
+ for name in cols.original:
63
+ key = norm(name)
64
+ if key in cols.by_norm:
65
+ cols.collisions.append((cols.by_norm[key], name))
66
+ continue
67
+ cols.by_norm[key] = name
68
+ return cols
69
+
70
+ @property
71
+ def normalized(self) -> set[str]:
72
+ return set(self.by_norm)
73
+
74
+ def has(self, *names: str) -> bool:
75
+ return any(n in self.by_norm for n in names)
76
+
77
+ def first(self, *names: str) -> str | None:
78
+ for n in names:
79
+ if n in self.by_norm:
80
+ return n
81
+ return None
82
+
83
+ def ref(self, name: str) -> str:
84
+ return quote_ident(self.by_norm[name])
85
+
86
+ def text(self, *names: str) -> str:
87
+ """First non-blank value among the given columns, as trimmed VARCHAR."""
88
+ parts = [f"NULLIF(TRIM({self.ref(n)}), '')" for n in names if n in self.by_norm]
89
+ if not parts:
90
+ return NULL_STR
91
+ return parts[0] if len(parts) == 1 else f"COALESCE({', '.join(parts)})"
92
+
93
+ def raw(self, name: str) -> str:
94
+ return self.ref(name) if name in self.by_norm else NULL_STR
95
+
96
+ def money(self, *names: str) -> str:
97
+ expr = self.text(*names)
98
+ return NULL_MONEY if expr == NULL_STR else f"cl_money({expr})"
99
+
100
+ def ts(self, *names: str) -> str:
101
+ expr = self.text(*names)
102
+ return "CAST(NULL AS TIMESTAMP)" if expr == NULL_STR else f"cl_ts({expr})"
103
+
104
+ def prefixed(self, prefix: str) -> list[str]:
105
+ return sorted(n for n in self.by_norm if n.startswith(prefix))
106
+
107
+
108
+ @dataclass
109
+ class Mapping:
110
+ """SQL expressions producing the canonical columns for one source."""
111
+
112
+ provider: str
113
+ dataset: str
114
+ cost_basis: str # billed | amortized | unknown
115
+ cost_raw: str # VARCHAR expression of the primary cost column (for parse diagnostics)
116
+ cost: str # money expression
117
+ billed_precision: str = "'decimal'"
118
+ gross_cost: str | None = None
119
+ effective_cost: str = NULL_MONEY
120
+ list_cost: str = NULL_MONEY
121
+ billing_account_id: str = NULL_STR
122
+ sub_account_id: str = NULL_STR
123
+ sub_account_name: str = NULL_STR
124
+ invoice_id: str = NULL_STR
125
+ invoice_issuer: str = NULL_STR
126
+ billing_period_start: str = "CAST(NULL AS DATE)"
127
+ charge_start: str = "CAST(NULL AS TIMESTAMP)"
128
+ charge_end: str = "CAST(NULL AS TIMESTAMP)"
129
+ currency: str = NULL_STR
130
+ charge_raw: str = NULL_STR
131
+ charge_category: str = "'unknown'"
132
+ charge_class: str = NULL_STR
133
+ service: str = NULL_STR
134
+ sku: str = NULL_STR
135
+ sku_detail: str = NULL_STR
136
+ resource_id: str = NULL_STR
137
+ region: str = NULL_STR
138
+ usage_quantity: str = NULL_MONEY
139
+ usage_unit: str = NULL_STR
140
+ tags: str = NULL_STR # JSON object text or NULL
141
+ pricing_model: str = "'unknown'"
142
+ commitment_status: str = NULL_STR
143
+ notes: list[str] = field(default_factory=list)
144
+ focus_version: str | None = None
145
+ capabilities: dict[str, bool] = field(default_factory=dict)
146
+ provider_sql: str | None = None # per-row provider expression (FOCUS files name their provider)
147
+
148
+ def select_sql(self, table: str, source_id: int) -> str:
149
+ gross = self.gross_cost or self.cost
150
+ fields = {
151
+ "source_id": str(int(source_id)),
152
+ "source_row": "__cl_row",
153
+ "provider": self.provider_sql or sql_str(self.provider),
154
+ "dataset": sql_str(self.dataset),
155
+ "cost_basis": sql_str(self.cost_basis),
156
+ "billing_account_id": self.billing_account_id,
157
+ "sub_account_id": self.sub_account_id,
158
+ "sub_account_name": self.sub_account_name,
159
+ "invoice_id": self.invoice_id,
160
+ "invoice_issuer": self.invoice_issuer,
161
+ "billing_period_start": self.billing_period_start,
162
+ "charge_start": self.charge_start,
163
+ "charge_end": self.charge_end,
164
+ "currency": f"UPPER({self.currency})",
165
+ "cost_raw": self.cost_raw,
166
+ "cost": self.cost,
167
+ "billed_precision": self.billed_precision,
168
+ "gross_cost": gross,
169
+ "effective_cost": self.effective_cost,
170
+ "list_cost": self.list_cost,
171
+ "charge_raw": self.charge_raw,
172
+ "charge_category": self.charge_category,
173
+ "charge_class": self.charge_class,
174
+ "service": self.service,
175
+ "sku": self.sku,
176
+ "sku_detail": self.sku_detail,
177
+ "resource_id": self.resource_id,
178
+ "region": self.region,
179
+ "usage_quantity": self.usage_quantity,
180
+ "usage_unit": self.usage_unit,
181
+ "tags": self.tags,
182
+ "pricing_model": self.pricing_model,
183
+ "commitment_status": self.commitment_status,
184
+ }
185
+ body = ",\n ".join(f"{expr} AS {name}" for name, expr in fields.items())
186
+ return f"SELECT\n {body}\nFROM {quote_ident(table)}"
187
+
188
+
189
+ CANONICAL_TYPES: dict[str, str] = {
190
+ "source_id": "INTEGER",
191
+ "source_row": "BIGINT",
192
+ "provider": "VARCHAR",
193
+ "dataset": "VARCHAR",
194
+ "cost_basis": "VARCHAR",
195
+ "billing_account_id": "VARCHAR",
196
+ "sub_account_id": "VARCHAR",
197
+ "sub_account_name": "VARCHAR",
198
+ "invoice_id": "VARCHAR",
199
+ "invoice_issuer": "VARCHAR",
200
+ "billing_period_start": "DATE",
201
+ "charge_start": "TIMESTAMP",
202
+ "charge_end": "TIMESTAMP",
203
+ "currency": "VARCHAR",
204
+ "cost_raw": "VARCHAR",
205
+ "cost": SQL_MONEY,
206
+ "billed_precision": "VARCHAR",
207
+ "gross_cost": SQL_MONEY,
208
+ "effective_cost": SQL_MONEY,
209
+ "list_cost": SQL_MONEY,
210
+ "charge_raw": "VARCHAR",
211
+ "charge_category": "VARCHAR",
212
+ "charge_class": "VARCHAR",
213
+ "service": "VARCHAR",
214
+ "sku": "VARCHAR",
215
+ "sku_detail": "VARCHAR",
216
+ "resource_id": "VARCHAR",
217
+ "region": "VARCHAR",
218
+ "usage_quantity": SQL_MONEY,
219
+ "usage_unit": "VARCHAR",
220
+ "tags": "VARCHAR",
221
+ "pricing_model": "VARCHAR",
222
+ "commitment_status": "VARCHAR",
223
+ }
224
+
225
+
226
+ def month_start(expr: str) -> str:
227
+ return f"CAST(date_trunc('month', {expr}) AS DATE)"
228
+
229
+
230
+ def json_object_from_columns(cols: Columns, names: list[str], key_of) -> str:
231
+ """Build a JSON object from separate tag columns, omitting blank values."""
232
+ if not names:
233
+ return NULL_STR
234
+ pairs = []
235
+ for n in names:
236
+ key = key_of(cols.by_norm[n])
237
+ pairs.append(f"{sql_str(key)}, NULLIF(TRIM({cols.ref(n)}), '')")
238
+ obj = f"json_object({', '.join(pairs)})"
239
+ any_value = ", ".join(f"NULLIF(TRIM({cols.ref(n)}), '')" for n in names)
240
+ # json_merge_patch drops null members, so an all-blank row reads as untagged.
241
+ return (
242
+ f"CASE WHEN COALESCE({any_value}) IS NULL THEN NULL "
243
+ f"ELSE CAST(json_merge_patch('{{}}', {obj}) AS VARCHAR) END"
244
+ )