@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, 06:00 UTC

main
ts 441 lines 14.4 KB
Raw
1 import * as cloudchannel from "@distilled.cloud/gcp/cloudchannel_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Effect from "effect/Effect";
4 import * as Stream from "effect/Stream";
5
6 export const MAX_ORG_DISPLAY_NAME_LENGTH = 128;
7 export const MAX_DOMAIN_LABEL_LENGTH = 32;
8 export const DEFAULT_LANGUAGE = "en-US";
9 export const DEFAULT_REBILLING_BASIS = "COST_AT_LIST";
10 export const DEFAULT_ADJUSTMENT = "0.00";
11
12 export const DEFAULT_POSTAL_ADDRESS: cloudchannel.GoogleTypePostalAddress = {
13 regionCode: "US",
14 postalCode: "94105",
15 administrativeArea: "CA",
16 locality: "San Francisco",
17 addressLines: ["100 Market Street"],
18 };
19
20 export const lastSegment = (value: string) => {
21 const trimmed = value.replace(/\/+$/, "");
22 const parts = trimmed.split("/");
23 return parts[parts.length - 1] || trimmed;
24 };
25
26 export const parentOf = (name: string) => {
27 const parts = name.split("/").filter((part) => part.length > 0);
28 return parts.slice(0, -2).join("/");
29 };
30
31 export const normalizeName = (value: string) => value.replace(/\/+$/, "");
32
33 export const toAccountName = (value: string) => {
34 const trimmed = normalizeName(value);
35 if (trimmed.startsWith("accounts/")) {
36 const parts = trimmed.split("/").filter((part) => part.length > 0);
37 return `accounts/${parts[1] ?? trimmed}`;
38 }
39 return `accounts/${trimmed}`;
40 };
41
42 export const accountOf = (value: string) => {
43 const trimmed = normalizeName(value);
44 if (trimmed.length === 0) return "";
45 const parts = trimmed.split("/").filter((part) => part.length > 0);
46 if (parts[0] === "accounts" && parts[1]) {
47 return `accounts/${parts[1]}`;
48 }
49 return toAccountName(trimmed);
50 };
51
52 export const toCustomerName = (parent: string, customerId?: string) => {
53 if (customerId !== undefined && customerId.includes("/")) {
54 return normalizeName(customerId);
55 }
56 if (customerId !== undefined && customerId.length > 0) {
57 return `${accountOf(parent)}/customers/${customerId}`;
58 }
59 return "";
60 };
61
62 export const toChannelPartnerLinkName = (value: string, account?: string) => {
63 const trimmed = normalizeName(value);
64 if (trimmed.includes("/channelPartnerLinks/")) return trimmed;
65 const acct = account ? toAccountName(account) : accountOf(trimmed);
66 if (acct.length === 0) return trimmed;
67 return `${acct}/channelPartnerLinks/${lastSegment(trimmed)}`;
68 };
69
70 export const toRepricingConfigName = (
71 parent: string,
72 configId: string | undefined,
73 collection: "customerRepricingConfigs" | "channelPartnerRepricingConfigs",
74 ) => {
75 if (configId !== undefined && configId.includes("/")) {
76 return normalizeName(configId);
77 }
78 if (configId !== undefined && configId.length > 0 && parent.length > 0) {
79 return `${normalizeName(parent)}/${collection}/${configId}`;
80 }
81 return "";
82 };
83
84 export const sameText = (left: string | undefined, right: string | undefined) =>
85 (left ?? "") === (right ?? "");
86
87 export const jsonEqual = (left: unknown, right: unknown) =>
88 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
89
90 export const updateMaskOf = (...fields: Array<string | undefined>) =>
91 fields.filter((field): field is string => field !== undefined).join(",");
92
93 export const replaceOnIdentity = (input: {
94 previousId?: string;
95 nextId?: string;
96 previousParent?: string;
97 nextParent?: string;
98 extra?: boolean;
99 }) => {
100 if (input.extra === true) {
101 return { action: "replace" as const, deleteFirst: false };
102 }
103 if (
104 input.previousId !== undefined &&
105 input.nextId !== undefined &&
106 input.previousId !== input.nextId
107 ) {
108 return { action: "replace" as const, deleteFirst: false };
109 }
110 if (
111 input.previousParent !== undefined &&
112 input.nextParent !== undefined &&
113 input.previousParent !== input.nextParent
114 ) {
115 return { action: "replace" as const, deleteFirst: false };
116 }
117 return undefined;
118 };
119
120 export const toOrgDisplayName = (
121 id: string,
122 requested: string | undefined,
123 existing: string | undefined,
124 ) =>
125 Effect.gen(function* () {
126 if (requested !== undefined && requested.length > 0) return requested;
127 if (existing !== undefined && existing.length > 0) return existing;
128 return yield* createPhysicalName({
129 id,
130 maxLength: 40,
131 lowercase: true,
132 });
133 });
134
135 export const toDomain = (id: string, requested: string | undefined, existing: string | undefined) =>
136 Effect.gen(function* () {
137 if (requested !== undefined && requested.length > 0) return requested;
138 if (existing !== undefined && existing.length > 0) return existing;
139 const local = yield* createPhysicalName({
140 id,
141 maxLength: MAX_DOMAIN_LABEL_LENGTH,
142 lowercase: true,
143 });
144 return `${local}.example.com`;
145 });
146
147 export const defaultInvoiceMonth = () =>
148 Effect.sync(() => {
149 const now = new Date();
150 const utcMonthIndex = now.getUTCMonth() + 2;
151 const year = now.getUTCFullYear() + Math.floor(utcMonthIndex / 12);
152 const month = (utcMonthIndex % 12) + 1;
153 return { year, month, day: 0 };
154 });
155
156 export const normalizeDate = (
157 date: cloudchannel.GoogleTypeDate | undefined,
158 ): cloudchannel.GoogleTypeDate | undefined => {
159 if (date === undefined) return undefined;
160 return {
161 year: date.year ?? 0,
162 month: date.month ?? 0,
163 day: date.day ?? 0,
164 };
165 };
166
167 const emptyList = <A>() => Effect.succeed([] as A[]);
168
169 export const collectPages = <A, Page, E, R>(
170 pages: Stream.Stream<Page, E, R>,
171 pick: (page: Page) => readonly A[] | undefined,
172 ) =>
173 pages.pipe(
174 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
175 Stream.runCollect,
176 Effect.map((chunk) => Array.from(chunk)),
177 );
178
179 export const getCustomer = (name: string) =>
180 name.length === 0
181 ? Effect.undefined
182 : cloudchannel
183 .getAccountsCustomers({ name })
184 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
185
186 export const getPartnerCustomer = (name: string) =>
187 name.length === 0
188 ? Effect.undefined
189 : cloudchannel
190 .getAccountsChannelPartnerLinksCustomers({ name })
191 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
192
193 export const listCustomers = (parent: string) =>
194 parent.length === 0
195 ? emptyList<cloudchannel.GoogleCloudChannelV1Customer>()
196 : collectPages(
197 cloudchannel.listAccountsCustomers.pages({
198 parent,
199 pageSize: 50,
200 }),
201 (page) => page.customers,
202 ).pipe(
203 Effect.catchTag("NotFound", () => emptyList<cloudchannel.GoogleCloudChannelV1Customer>()),
204 );
205
206 export const listPartnerCustomers = (parent: string) =>
207 parent.length === 0
208 ? emptyList<cloudchannel.GoogleCloudChannelV1Customer>()
209 : collectPages(
210 cloudchannel.listAccountsChannelPartnerLinksCustomers.pages({
211 parent,
212 pageSize: 50,
213 }),
214 (page) => page.customers,
215 ).pipe(
216 Effect.catchTag("NotFound", () => emptyList<cloudchannel.GoogleCloudChannelV1Customer>()),
217 );
218
219 export const listChannelPartnerLinks = (parent: string) =>
220 parent.length === 0
221 ? emptyList<cloudchannel.GoogleCloudChannelV1ChannelPartnerLink>()
222 : collectPages(
223 cloudchannel.listAccountsChannelPartnerLinks.pages({
224 parent,
225 pageSize: 50,
226 view: "BASIC",
227 }),
228 (page) => page.channelPartnerLinks,
229 ).pipe(
230 Effect.catchTag("NotFound", () =>
231 emptyList<cloudchannel.GoogleCloudChannelV1ChannelPartnerLink>(),
232 ),
233 );
234
235 export const findCustomerByDomain = (
236 parent: string,
237 domain: string,
238 list: typeof listCustomers = listCustomers,
239 ) =>
240 Effect.gen(function* () {
241 if (domain.length === 0) return undefined;
242 const customers = yield* list(parent);
243 return customers.find((customer) => sameText(customer.domain, domain));
244 });
245
246 export const toCustomerAttrs = (
247 customer: cloudchannel.GoogleCloudChannelV1Customer,
248 parent?: string,
249 ) => {
250 const name = customer.name ?? "";
251 const account = accountOf(name || parent || "");
252 const derivedParent =
253 parent !== undefined && parent.includes("/channelPartnerLinks/")
254 ? parent
255 : customer.channelPartnerId
256 ? `${account}/channelPartnerLinks/${customer.channelPartnerId}`
257 : account;
258 return {
259 name,
260 customerId: lastSegment(name),
261 parent: derivedParent,
262 account,
263 orgDisplayName: customer.orgDisplayName,
264 domain: customer.domain,
265 orgPostalAddress: customer.orgPostalAddress,
266 primaryContactInfo: customer.primaryContactInfo,
267 alternateEmail: customer.alternateEmail,
268 languageCode: customer.languageCode,
269 correlationId: customer.correlationId,
270 customerAttestationState: customer.customerAttestationState,
271 channelPartnerId: customer.channelPartnerId,
272 cloudIdentityId: customer.cloudIdentityId,
273 createTime: customer.createTime,
274 updateTime: customer.updateTime,
275 };
276 };
277
278 export const desiredCustomer = (input: {
279 orgDisplayName: string;
280 domain: string;
281 orgPostalAddress?: cloudchannel.GoogleTypePostalAddress;
282 primaryContactInfo?: cloudchannel.GoogleCloudChannelV1ContactInfo;
283 alternateEmail?: string;
284 languageCode?: string;
285 correlationId?: string;
286 customerAttestationState?:
287 | cloudchannel.GoogleCloudChannelV1CustomerCustomerAttestationStateEnum
288 | (string & {});
289 channelPartnerId?: string;
290 }): cloudchannel.GoogleCloudChannelV1Customer => {
291 const address = input.orgPostalAddress ?? DEFAULT_POSTAL_ADDRESS;
292 const email = input.primaryContactInfo?.email ?? `admin@${input.domain}`;
293 return {
294 orgDisplayName: input.orgDisplayName,
295 domain: input.domain,
296 orgPostalAddress: address,
297 primaryContactInfo: {
298 firstName: input.primaryContactInfo?.firstName ?? "Alchemy",
299 lastName: input.primaryContactInfo?.lastName ?? "Test",
300 email,
301 phone: input.primaryContactInfo?.phone,
302 title: input.primaryContactInfo?.title,
303 },
304 alternateEmail: input.alternateEmail,
305 languageCode: input.languageCode ?? DEFAULT_LANGUAGE,
306 correlationId: input.correlationId,
307 customerAttestationState: input.customerAttestationState,
308 channelPartnerId: input.channelPartnerId,
309 };
310 };
311
312 export const getCustomerRepricingConfig = (name: string) =>
313 name.length === 0
314 ? Effect.undefined
315 : cloudchannel
316 .getAccountsCustomersCustomerRepricingConfigs({ name })
317 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
318
319 export const getChannelPartnerRepricingConfig = (name: string) =>
320 name.length === 0
321 ? Effect.undefined
322 : cloudchannel
323 .getAccountsChannelPartnerLinksChannelPartnerRepricingConfigs({
324 name,
325 })
326 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
327
328 export const listCustomerRepricingConfigs = (parent: string) =>
329 parent.length === 0
330 ? emptyList<cloudchannel.GoogleCloudChannelV1CustomerRepricingConfig>()
331 : collectPages(
332 cloudchannel.listAccountsCustomersCustomerRepricingConfigs.pages({
333 parent,
334 pageSize: 100,
335 }),
336 (page) => page.customerRepricingConfigs,
337 ).pipe(
338 Effect.catchTag("NotFound", () =>
339 emptyList<cloudchannel.GoogleCloudChannelV1CustomerRepricingConfig>(),
340 ),
341 );
342
343 export const listChannelPartnerRepricingConfigs = (parent: string) =>
344 parent.length === 0
345 ? emptyList<cloudchannel.GoogleCloudChannelV1ChannelPartnerRepricingConfig>()
346 : collectPages(
347 cloudchannel.listAccountsChannelPartnerLinksChannelPartnerRepricingConfigs.pages({
348 parent,
349 pageSize: 100,
350 }),
351 (page) => page.channelPartnerRepricingConfigs,
352 ).pipe(
353 Effect.catchTag("NotFound", () =>
354 emptyList<cloudchannel.GoogleCloudChannelV1ChannelPartnerRepricingConfig>(),
355 ),
356 );
357
358 export const desiredRepricingConfig = (input: {
359 effectiveInvoiceMonth: cloudchannel.GoogleTypeDate;
360 rebillingBasis?:
361 | cloudchannel.GoogleCloudChannelV1RepricingConfigRebillingBasisEnum
362 | (string & {});
363 adjustmentPercentage?: string;
364 adjustment?: cloudchannel.GoogleCloudChannelV1RepricingAdjustment;
365 entitlementGranularity?: cloudchannel.GoogleCloudChannelV1RepricingConfigEntitlementGranularity;
366 conditionalOverrides?: cloudchannel.GoogleCloudChannelV1ConditionalOverrideList;
367 }): cloudchannel.GoogleCloudChannelV1RepricingConfig => ({
368 effectiveInvoiceMonth: normalizeDate(input.effectiveInvoiceMonth),
369 rebillingBasis: input.rebillingBasis ?? DEFAULT_REBILLING_BASIS,
370 adjustment:
371 input.adjustment ??
372 ({
373 percentageAdjustment: {
374 percentage: { value: input.adjustmentPercentage ?? DEFAULT_ADJUSTMENT },
375 },
376 } satisfies cloudchannel.GoogleCloudChannelV1RepricingAdjustment),
377 entitlementGranularity: input.entitlementGranularity,
378 conditionalOverrides: input.conditionalOverrides,
379 });
380
381 export const toCustomerRepricingAttrs = (
382 config: cloudchannel.GoogleCloudChannelV1CustomerRepricingConfig,
383 ) => {
384 const name = config.name ?? "";
385 return {
386 name,
387 configId: lastSegment(name),
388 parent: parentOf(name),
389 updateTime: config.updateTime,
390 repricingConfig: config.repricingConfig,
391 };
392 };
393
394 export const toChannelPartnerRepricingAttrs = (
395 config: cloudchannel.GoogleCloudChannelV1ChannelPartnerRepricingConfig,
396 ) => {
397 const name = config.name ?? "";
398 return {
399 name,
400 configId: lastSegment(name),
401 parent: parentOf(name),
402 updateTime: config.updateTime,
403 repricingConfig: config.repricingConfig,
404 };
405 };
406
407 export const findCustomerRepricing = (
408 parent: string,
409 name: string | undefined,
410 month: cloudchannel.GoogleTypeDate | undefined,
411 ) =>
412 Effect.gen(function* () {
413 if (name !== undefined && name.length > 0) {
414 const existing = yield* getCustomerRepricingConfig(name);
415 if (existing !== undefined) return existing;
416 }
417 const configs = yield* listCustomerRepricingConfigs(parent);
418 if (month === undefined) return undefined;
419 const wanted = normalizeDate(month);
420 return configs.find((config) =>
421 jsonEqual(normalizeDate(config.repricingConfig?.effectiveInvoiceMonth), wanted),
422 );
423 });
424
425 export const findChannelPartnerRepricing = (
426 parent: string,
427 name: string | undefined,
428 month: cloudchannel.GoogleTypeDate | undefined,
429 ) =>
430 Effect.gen(function* () {
431 if (name !== undefined && name.length > 0) {
432 const existing = yield* getChannelPartnerRepricingConfig(name);
433 if (existing !== undefined) return existing;
434 }
435 const configs = yield* listChannelPartnerRepricingConfigs(parent);
436 if (month === undefined) return undefined;
437 const wanted = normalizeDate(month);
438 return configs.find((config) =>
439 jsonEqual(normalizeDate(config.repricingConfig?.effectiveInvoiceMonth), wanted),
440 );
441 });