@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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