Open History to see the last commit
1import {
2 parseUsagePriceForm,
3 usagePriceForm,
4 USAGE_PRICE_FIELDS,
5 type UsagePriceForm,
6} from "./usagePriceForm";
7import type { UsagePriceChange, UsagePriceTarget } from "./usagePriceTargets";
8
9export type UsagePriceField = (typeof USAGE_PRICE_FIELDS)[number]["key"];
10
11export interface UsagePriceDraft {
12 readonly id: string;
13 readonly model: string;
14 readonly isNew: boolean;
15 readonly values: Partial<Pick<UsagePriceForm, UsagePriceField>>;
16 /** Edited "Map to" model. Absent keeps each environment's mapping; blank removes it. */
17 readonly alias?: string;
18 readonly removed?: boolean;
19}
20
21export function isEmptyUsagePriceDraft(draft: UsagePriceDraft) {
22 return (
23 draft.isNew &&
24 draft.model.trim() === "" &&
25 (draft.alias ?? "").trim() === "" &&
26 Object.values(draft.values).every((value) => value.trim() === "")
27 );
28}
29
30function modelPrice(target: UsagePriceTarget, model: string) {
31 return target.prices && Object.hasOwn(target.prices, model) ? target.prices[model] : undefined;
32}
33
34function modelAlias(target: UsagePriceTarget, model: string) {
35 return target.aliases && Object.hasOwn(target.aliases, model) ? target.aliases[model] : undefined;
36}
37
38export function usageAliasCell(targets: readonly UsagePriceTarget[], model: string) {
39 if (targets.some((target) => target.aliases === null))
40 return { value: "", placeholder: "Unavailable" };
41 const values = targets.map((target) => modelAlias(target, model) ?? "");
42 if (values.some((value) => value !== values[0])) return { value: "", placeholder: "Mixed" };
43 return { value: values[0] ?? "", placeholder: "None" };
44}
45
46export function usagePriceCell(
47 targets: readonly UsagePriceTarget[],
48 model: string,
49 field: UsagePriceField,
50) {
51 const optional = USAGE_PRICE_FIELDS.find((entry) => entry.key === field)!.optional;
52 const values = targets.map((target) =>
53 modelPrice(target, model) ? usagePriceForm(model, modelPrice(target, model))[field] : null,
54 );
55 if (targets.some((target) => target.prices === null))
56 return { value: "", placeholder: "Unavailable" };
57 if (values.some((value) => value !== values[0])) return { value: "", placeholder: "Mixed" };
58 return {
59 value: values[0] ?? "",
60 placeholder: values[0] === null ? "Automatic" : optional ? "Input rate" : "0.00",
61 };
62}
63
64export function usagePriceTableChanges(
65 target: UsagePriceTarget,
66 drafts: readonly UsagePriceDraft[],
67) {
68 const changes: UsagePriceChange[] = [];
69 const errors = new Map<string, string>();
70 for (const draft of drafts) {
71 if (isEmptyUsagePriceDraft(draft)) continue;
72 const model = draft.model.trim();
73 const currentAlias = modelAlias(target, model);
74 if (draft.removed) {
75 if (modelPrice(target, model)) changes.push({ model, price: null });
76 if (currentAlias !== undefined) changes.push({ model, alias: null });
77 continue;
78 }
79 const alias = (draft.alias ?? currentAlias ?? "").trim();
80 if (alias !== "") {
81 if (draft.alias === undefined && Object.keys(draft.values).length > 0) {
82 errors.set(
83 draft.id,
84 `${target.label} maps this model. Remove it from "Apply to" or clear its mapping first.`,
85 );
86 continue;
87 }
88 if (model === "") errors.set(draft.id, "Enter a model ID.");
89 else if (alias === model) errors.set(draft.id, "Map to a different model.");
90 else {
91 if (alias !== currentAlias) changes.push({ model, alias });
92 if (modelPrice(target, model)) changes.push({ model, price: null });
93 }
94 continue;
95 }
96 if (currentAlias !== undefined) {
97 changes.push({ model, alias: null });
98 if (
99 !modelPrice(target, model) &&
100 Object.values(draft.values).every((value) => value.trim() === "")
101 )
102 continue;
103 }
104 const original = usagePriceForm(model, modelPrice(target, model));
105 const form = { ...original, ...draft.values };
106 const parsed = parseUsagePriceForm(form);
107 if (parsed === null) {
108 const missing = USAGE_PRICE_FIELDS.find(
109 (field) => !field.optional && form[field.key].trim() === "",
110 );
111 errors.set(
112 draft.id,
113 model === ""
114 ? "Enter a model ID."
115 : missing
116 ? `${missing.label} is required on ${target.label}.`
117 : "Use non-negative numbers for prices.",
118 );
119 continue;
120 }
121 const next = usagePriceForm(model, parsed.price);
122 if (USAGE_PRICE_FIELDS.some((field) => original[field.key] !== next[field.key]))
123 changes.push(parsed);
124 }
125 // Check the final batch so clearing a mapping and reversing it in one save stays valid.
126 const aliases = new Map(Object.entries(target.aliases ?? {}));
127 for (const change of changes) {
128 if (!("alias" in change)) continue;
129 if (change.alias === null) aliases.delete(change.model);
130 else aliases.set(change.model, change.alias);
131 }
132 for (const draft of drafts) {
133 if (draft.removed || errors.has(draft.id)) continue;
134 let model = draft.model.trim();
135 const seen = new Set<string>();
136 while (aliases.has(model)) {
137 if (seen.has(model)) {
138 errors.set(draft.id, `Model mappings cannot form a cycle on ${target.label}.`);
139 break;
140 }
141 seen.add(model);
142 model = aliases.get(model)!;
143 }
144 }
145 return { changes, errors };
146}
147
148export function usagePriceTableErrors(
149 targets: readonly UsagePriceTarget[],
150 drafts: readonly UsagePriceDraft[],
151) {
152 return new Map(
153 targets
154 .filter((target) => target.unavailable === null && target.prices !== null)
155 .flatMap((target) => [...usagePriceTableChanges(target, drafts).errors]),
156 );
157}