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

main
ts 365 lines 11.8 KB
Raw
1 import * as cci from "@distilled.cloud/gcp/contactcenterinsights_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { DateRangeConfig } from "./Dashboard.ts";
13 import {
14 encodeOwnership,
15 hasOwnershipMarker,
16 lastSegment,
17 locationOf,
18 locationParent,
19 ownedByAlchemy,
20 parentOf,
21 parseOwnership,
22 sameJson,
23 toResourceId,
24 } from "./ownership.ts";
25
26 export type DashboardsChartProps = {
27 /**
28 * Parent Dashboard resource name
29 * (`projects/{project}/locations/{location}/dashboards/{dashboard}`).
30 * Immutable — changing it replaces the chart.
31 */
32 parent: string;
33 /**
34 * Chart id (the `{chart}` segment). If omitted, a unique id is generated.
35 * Immutable — changing it replaces the chart. 4-64 characters matching
36 * `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$`.
37 */
38 chartId?: string;
39 /**
40 * User-facing display name.
41 */
42 displayName?: string;
43 /**
44 * Chart description. Charts have no labels field, so Alchemy ownership
45 * is stored in a `[alchemy …]` prefix and stripped from attributes.
46 */
47 description?: string;
48 /**
49 * Filter applied to the chart.
50 */
51 filter?: string;
52 /**
53 * Width in grid units.
54 */
55 width?: number;
56 /**
57 * Height in grid units.
58 */
59 height?: number;
60 /**
61 * Visualization (`BAR`, `LINE`, `AREA`, `PIE`, `TABLE`, …).
62 */
63 chartVisualizationType?:
64 | "CHART_VISUALIZATION_TYPE_UNSPECIFIED"
65 | "BAR"
66 | "LINE"
67 | "AREA"
68 | "PIE"
69 | "SCATTER"
70 | "TABLE"
71 | "SCORE_CARD"
72 | "SUNBURST"
73 | "GAUGE"
74 | "SANKEY";
75 /**
76 * Date range applied to the chart.
77 */
78 dateRangeConfig?: DateRangeConfig;
79 /**
80 * Query or generative-insights data source.
81 */
82 dataSource?: cci.GoogleCloudContactcenterinsightsV1ChartDataSource;
83 /**
84 * Click action (redirect or conversation filter).
85 */
86 action?: cci.GoogleCloudContactcenterinsightsV1ChartAction;
87 };
88
89 export type DashboardsChart = Resource<
90 "GCP.ContactCenterInsights.DashboardsChart",
91 DashboardsChartProps,
92 {
93 /** Full resource name. */
94 name: string;
95 /** Chart id (last path segment). */
96 chartId: string;
97 /** Parent dashboard resource name. */
98 parent: string;
99 /** Region id. */
100 location: string;
101 /** Project id. */
102 project: string;
103 /** User-facing display name. */
104 displayName: string | undefined;
105 /** User description with the Alchemy ownership prefix stripped. */
106 description: string | undefined;
107 /** Chart filter. */
108 filter: string | undefined;
109 /** Width in grid units. */
110 width: number | undefined;
111 /** Height in grid units. */
112 height: number | undefined;
113 /** Server-assigned chart type. */
114 chartType: string | undefined;
115 /** Visualization type. */
116 chartVisualizationType: string | undefined;
117 /** Date range config. */
118 dateRangeConfig: DateRangeConfig | undefined;
119 /** Data source. */
120 dataSource: cci.GoogleCloudContactcenterinsightsV1ChartDataSource | undefined;
121 /** Click action. */
122 action: cci.GoogleCloudContactcenterinsightsV1ChartAction | undefined;
123 /** RFC3339 creation timestamp. */
124 createTime: string | undefined;
125 /** RFC3339 last-update timestamp. */
126 updateTime: string | undefined;
127 },
128 never,
129 Providers
130 >;
131
132 /**
133 * A chart widget on a Contact Center Insights dashboard.
134 *
135 * Parent dashboard and chart id are immutable. Charts have no labels
136 * field — Alchemy stamps ownership into the description. Display name,
137 * description, filter, size, visualization, and data source update in
138 * place.
139 *
140 * ### Creating a Chart
141 * **Example:** Bar chart on a dashboard
142 * ```typescript
143 * const chart = yield* GCP.ContactCenterInsights.DashboardsChart("Volume", {
144 * parent: dashboard.name,
145 * displayName: "volume",
146 * chartVisualizationType: "BAR",
147 * });
148 * ```
149 *
150 * @resource
151 * @category ContactCenterInsights
152 */
153 export const DashboardsChart = Resource<DashboardsChart>(
154 "GCP.ContactCenterInsights.DashboardsChart",
155 );
156
157 export class DashboardsChartNotResolved extends Data.TaggedError(
158 "GCP.ContactCenterInsights.DashboardsChartNotResolved",
159 )<{
160 resourceName: string;
161 }> {}
162
163 const resourceName = (parent: string, chartId: string) => `${parent}/charts/${chartId}`;
164
165 const optionalString = (value: string | undefined): string | undefined => value;
166
167 const toDateRangeConfig = (
168 config: cci.GoogleCloudContactcenterinsightsV1DateRangeConfig | undefined,
169 ): DateRangeConfig | undefined => {
170 if (config === undefined) return undefined;
171 return {
172 relativeDateRange:
173 config.relativeDateRange === undefined
174 ? undefined
175 : {
176 quantity: config.relativeDateRange.quantity,
177 unit: config.relativeDateRange.unit,
178 },
179 absoluteDateRange:
180 config.absoluteDateRange === undefined
181 ? undefined
182 : {
183 startTime: config.absoluteDateRange.startTime,
184 endTime: config.absoluteDateRange.endTime,
185 },
186 };
187 };
188
189 const toAttrs = (chart: cci.GoogleCloudContactcenterinsightsV1Chart, project: string) => {
190 const name = chart.name ?? "";
191 const parsed = parseOwnership(chart.description);
192 return {
193 name,
194 chartId: lastSegment(name),
195 parent: parentOf(name),
196 location: locationOf(name),
197 project,
198 displayName: chart.displayName,
199 description: parsed.text,
200 filter: chart.filter,
201 width: chart.width,
202 height: chart.height,
203 chartType: optionalString(chart.chartType),
204 chartVisualizationType: optionalString(chart.chartVisualizationType),
205 dateRangeConfig: toDateRangeConfig(chart.dateRangeConfig),
206 dataSource: chart.dataSource,
207 action: chart.action,
208 createTime: chart.createTime,
209 updateTime: chart.updateTime,
210 };
211 };
212
213 const getByName = (name: string) =>
214 name.length === 0
215 ? Effect.undefined
216 : cci
217 .getProjectsLocationsDashboardsCharts({ name })
218 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
219
220 const listDashboards = (parent: string) =>
221 cci.listProjectsLocationsDashboards.pages({ parent, pageSize: 100 }).pipe(
222 Stream.flatMap((page) => Stream.fromIterable(page.dashboards ?? [])),
223 Stream.map((dashboard) => dashboard.name ?? ""),
224 Stream.filter((name) => name.length > 0),
225 Stream.runCollect,
226 Effect.map((chunk) => Array.from(chunk)),
227 Effect.catchTag("NotFound", () => Effect.succeed([] as string[])),
228 );
229
230 const listAtParent = (parent: string, project: string) =>
231 cci.listProjectsLocationsDashboardsCharts({ parent }).pipe(
232 Effect.map((page) =>
233 (page.charts ?? [])
234 .filter((chart) => hasOwnershipMarker(chart.description))
235 .map((chart) => toAttrs(chart, project)),
236 ),
237 Effect.catchTag("NotFound", () => Effect.succeed([])),
238 );
239
240 export const DashboardsChartProvider = () =>
241 Provider.succeed(DashboardsChart, {
242 stables: ["name", "chartId", "parent", "location", "project", "createTime"],
243
244 diff: Effect.fn(function* ({ news, olds, output }) {
245 if (!isResolved(news)) return undefined;
246 const previousParent = olds?.parent ?? output?.parent;
247 if (previousParent !== undefined && news.parent !== previousParent) {
248 return { action: "replace" as const, deleteFirst: false };
249 }
250 const previousId = olds?.chartId ?? output?.chartId;
251 if (previousId !== undefined && news.chartId !== undefined && news.chartId !== previousId) {
252 return { action: "replace" as const, deleteFirst: true };
253 }
254 return undefined;
255 }),
256
257 read: Effect.fn(function* ({ id, olds, output, previous }) {
258 const env = yield* GcpEnvironment.current;
259 const chartId = yield* toResourceId(id, olds?.chartId, output?.chartId);
260 const name =
261 output?.name ?? (olds?.parent !== undefined ? resourceName(olds.parent, chartId) : "");
262 const existing = yield* getByName(name);
263 if (existing === undefined) return undefined;
264 const attrs = toAttrs(existing, env.project);
265 return (yield* ownedByAlchemy(id, existing.description))
266 ? attrs
267 : unownedUnlessPrevious(attrs, previous, "name");
268 }),
269
270 list: () =>
271 Effect.gen(function* () {
272 const env = yield* GcpEnvironment.current;
273 const dashboards = yield* listDashboards(locationParent(env.project, env.region));
274 const pages = yield* Effect.forEach(
275 dashboards,
276 (parent) => listAtParent(parent, env.project),
277 { concurrency: 4 },
278 );
279 return pages.flat();
280 }),
281
282 reconcile: Effect.fn(function* ({ id, news, output }) {
283 const env = yield* GcpEnvironment.current;
284 const chartId = yield* toResourceId(id, news.chartId, output?.chartId);
285 const name = resourceName(news.parent, chartId);
286 const ownership = yield* createInternalLabels(id);
287 const description = encodeOwnership(ownership, news.description);
288 const displayName = news.displayName ?? chartId;
289
290 let current = yield* getByName(output?.name ?? name);
291
292 if (current === undefined) {
293 const created = yield* cci
294 .createProjectsLocationsDashboardsCharts({
295 parent: news.parent,
296 chartId,
297 body: {
298 displayName,
299 description,
300 filter: news.filter,
301 width: news.width,
302 height: news.height,
303 chartVisualizationType: news.chartVisualizationType,
304 dateRangeConfig: news.dateRangeConfig,
305 dataSource: news.dataSource,
306 action: news.action,
307 },
308 })
309 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
310 current = created ?? undefined;
311 }
312
313 if (current === undefined) {
314 return yield* new DashboardsChartNotResolved({ resourceName: name });
315 }
316
317 const displayChanged = (current.displayName ?? "") !== displayName;
318 const descriptionChanged = (current.description ?? "") !== description;
319 const filterChanged = (current.filter ?? "") !== (news.filter ?? "");
320 const widthChanged = (current.width ?? 0) !== (news.width ?? 0);
321 const heightChanged = (current.height ?? 0) !== (news.height ?? 0);
322 const vizChanged =
323 (current.chartVisualizationType ?? "") !== (news.chartVisualizationType ?? "");
324 const dateRangeChanged = !sameJson(current.dateRangeConfig, news.dateRangeConfig);
325 const dataSourceChanged = !sameJson(current.dataSource, news.dataSource);
326 const actionChanged = !sameJson(current.action, news.action);
327
328 if (
329 displayChanged ||
330 descriptionChanged ||
331 filterChanged ||
332 widthChanged ||
333 heightChanged ||
334 vizChanged ||
335 dateRangeChanged ||
336 dataSourceChanged ||
337 actionChanged
338 ) {
339 current = yield* cci.patchProjectsLocationsDashboardsCharts({
340 name: current.name ?? name,
341 updateMask: "*",
342 body: {
343 name: current.name ?? name,
344 displayName,
345 description,
346 filter: news.filter,
347 width: news.width,
348 height: news.height,
349 chartVisualizationType: news.chartVisualizationType,
350 dateRangeConfig: news.dateRangeConfig,
351 dataSource: news.dataSource,
352 action: news.action,
353 },
354 });
355 }
356
357 return toAttrs(current, env.project);
358 }),
359
360 delete: Effect.fn(function* ({ output }) {
361 yield* cci
362 .deleteProjectsLocationsDashboardsCharts({ name: output.name })
363 .pipe(Effect.catchTag("NotFound", () => Effect.void));
364 }),
365 });