File size: 2,570 Bytes
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { TARGET_MODULE_AUTOMATION, TARGET_MODULE_DATABASE } from "../alerts/alertsModel";
import type { NotificationTarget } from "../alerts/alertsModel";

declare module "../alerts/alertsModel" {
  interface NotificationTarget {
    application?: string;
  }
}

const str = (v: unknown): string => (typeof v === "string" ? v : "");

export type TargetRoute =
  | { surface: "database"; key: string; viewId?: string }
  | { surface: "intelligence"; key: string; viewId?: never }
  | { surface: "automation"; autoId: string; tab: string }
  | { surface: "map"; routeId: string };

export const OPEN_RETRY_MS = [0, 250, 700, 1500, 2600] as const;

/** Retry while the destination loads, stopping after success or cancellation. */
export function retryEmit(
  emit: () => boolean | void,
  schedule: (fn: () => void, ms: number) => number = setTimeout as never,
  ladder: readonly number[] = OPEN_RETRY_MS
): () => void {
  const timers: number[] = [];
  let done = false;
  for (const ms of ladder) {
    timers.push(
      schedule(() => {
        if (done) return;
        if (emit() === true) done = true;
      }, ms)
    );
  }
  return () => {
    done = true;
    for (const t of timers) clearTimeout(t as never);
  };
}

export function routeForTarget(t: NotificationTarget | null): TargetRoute | null {
  if (!t || !str(t.module).trim() || !str(t.id).trim()) return null;
  if (t.module === "intelligence") {
    const query = new URLSearchParams({ path: t.id });
    if (str(t.tab).trim()) query.set("proposal", t.tab!.trim());
    return { surface: "intelligence", key: `intelligence?${query}` };
  }
  if (t.module === TARGET_MODULE_AUTOMATION)
    return { surface: "automation", autoId: t.id, tab: str(t.tab).trim() || "runs" };
  if (t.module === TARGET_MODULE_DATABASE) {
    const viewId = str(t.tab).trim();
    return { surface: "database", key: t.id, ...(viewId ? { viewId } : {}) };
  }
  const application = str(t.application).trim();
  // A Routing App address takes precedence over the legacy map destination.
  if (t.module === "customer_data" && t.tab === "map" && application) {
    const query = new URLSearchParams({ database: "customer_data", application, route: t.id });
    return { surface: "database", key: `app?${query}` };
  }
  if (t.module.startsWith("ut_") && str(t.id).trim()) {
    const query = new URLSearchParams({ database: t.module, record: t.id });
    return { surface: "database", key: `data?${query}` };
  }
  if (t.module === "customer_data" && t.tab === "map") return { surface: "map", routeId: t.id };
  return null;
}