Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usagePriceTable.ts

150 lines5.2 KB

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;
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 );
29​
30function modelPrice(target: UsagePriceTarget, model: string) {
31 return target.prices && Object.hasOwn(target.prices, model) ? target.prices[model] : undefined;
33​
34function modelAlias(target: UsagePriceTarget, model: string) {
35 return target.aliases && Object.hasOwn(target.aliases, model) ? target.aliases[model] : undefined;
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" };
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 };
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 (model === "") errors.set(draft.id, "Enter a model ID.");
82 else if (alias === model) errors.set(draft.id, "Map to a different model.");
83 else {
84 if (alias !== currentAlias) changes.push({ model, alias });
85 if (modelPrice(target, model)) changes.push({ model, price: null });
86 }
87 continue;
88 }
89 if (currentAlias !== undefined) {
90 changes.push({ model, alias: null });
91 if (
92 !modelPrice(target, model) &&
93 Object.values(draft.values).every((value) => value.trim() === "")
94 )
95 continue;
96 }
97 const original = usagePriceForm(model, modelPrice(target, model));
98 const form = { ...original, ...draft.values };
99 const parsed = parseUsagePriceForm(form);
100 if (parsed === null) {
101 const missing = USAGE_PRICE_FIELDS.find(
102 (field) => !field.optional && form[field.key].trim() === "",
103 );
104 errors.set(
105 draft.id,
106 model === ""
107 ? "Enter a model ID."
108 : missing
109 ? `${missing.label} is required on ${target.label}.`
110 : "Use non-negative numbers for prices.",
111 );
112 continue;
113 }
114 const next = usagePriceForm(model, parsed.price);
115 if (USAGE_PRICE_FIELDS.some((field) => original[field.key] !== next[field.key]))
116 changes.push(parsed);
117 }
118 // Check the final batch so clearing a mapping and reversing it in one save stays valid.
119 const aliases = new Map(Object.entries(target.aliases ?? {}));
120 for (const change of changes) {
121 if (!("alias" in change)) continue;
122 if (change.alias === null) aliases.delete(change.model);
123 else aliases.set(change.model, change.alias);
124 }
125 for (const draft of drafts) {
126 if (draft.removed || errors.has(draft.id)) continue;
127 let model = draft.model.trim();
128 const seen = new Set<string>();
129 while (aliases.has(model)) {
130 if (seen.has(model)) {
131 errors.set(draft.id, `Model mappings cannot form a cycle on ${target.label}.`);
132 break;
133 }
134 seen.add(model);
135 model = aliases.get(model)!;
136 }
137 }
138 return { changes, errors };
140​
141export function usagePriceTableErrors(
142 targets: readonly UsagePriceTarget[],
143 drafts: readonly UsagePriceDraft[],
144) {
145 return new Map(
146 targets
147 .filter((target) => target.unavailable === null && target.prices !== null)
148 .flatMap((target) => [...usagePriceTableChanges(target, drafts).errors]),
149 );