@cognitiv-traits/traitos-ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/browser.js ADDED
@@ -0,0 +1,8 @@
1
+ // Entry for the <script>-tag bundle: window.TraitOSUI (elements, controllers) and window.TraitOS (the SDK).
2
+ import * as UI from './index.js';
3
+ import * as SDK from '../../sdk/src/index.js';
4
+
5
+ if (typeof window !== 'undefined') {
6
+ window.TraitOSUI = UI;
7
+ window.TraitOS = { ...(window.TraitOS ?? {}), ...SDK };
8
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Dialer endpoints the SDK 0.7 has no wrapper for (GET /telephony/numbers, GET|PUT /telephony/outbound-call-settings, GET /calls).
3
+ * SDK 0.8 adds them as methods and those are used when present; older SDKs fall back to the same routes.
4
+ */
5
+ const json = (method, body) => ({ method, body: JSON.stringify(body ?? {}) });
6
+ const raw = (client) => client._request?.bind(client);
7
+
8
+ export async function listLines(client) {
9
+ if (typeof client.phoneNumbers?.list === 'function') return (await client.phoneNumbers.list())?.numbers ?? [];
10
+ return (await raw(client)('/telephony/numbers'))?.numbers ?? [];
11
+ }
12
+ export async function getOutboundMode(client) {
13
+ if (typeof client.calls?.outboundSettings?.get === 'function') return (await client.calls.outboundSettings.get())?.mode ?? 'direct';
14
+ return (await raw(client)('/telephony/outbound-call-settings'))?.mode ?? 'direct';
15
+ }
16
+ export async function setOutboundMode(client, mode) {
17
+ if (typeof client.calls?.outboundSettings?.update === 'function') return client.calls.outboundSettings.update({ mode });
18
+ return raw(client)('/telephony/outbound-call-settings', json('PUT', { mode }));
19
+ }
20
+
21
+ export async function listCalls(client, limit = 10) {
22
+ if (typeof client.calls?.list === 'function') return (await client.calls.list({ limit }))?.calls ?? [];
23
+ return (await raw(client)(`/calls?limit=${limit}`))?.calls ?? [];
24
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Calls this browser handled, newest first. The API has no call-history endpoint that can be read newest-first (the event log is
3
+ * oldest-first), so the softphone keeps its own short list: it feeds the "recent calls" list, one-click redial and the missed badge.
4
+ * Kept in `storage` (localStorage) when given, so it survives a reload; only on this device.
5
+ */
6
+ const KEY = 'traitos.calllog';
7
+ export class CallLog {
8
+ constructor({ storage, max = 10, now = Date.now } = {}) {
9
+ this.storage = storage; this.max = max; this.now = now; this.listeners = new Set();
10
+ this.entries = this._read();
11
+ this.seenAt = this._seen();
12
+ }
13
+ _read() { try { const v = JSON.parse(this.storage?.getItem(KEY) || '[]'); return Array.isArray(v) ? v.slice(0, this.max) : []; } catch { return []; } }
14
+ _seen() { try { return Number(this.storage?.getItem(`${KEY}.seen`)) || 0; } catch { return 0; } }
15
+ _save() { try { this.storage?.setItem(KEY, JSON.stringify(this.entries)); this.storage?.setItem(`${KEY}.seen`, String(this.seenAt)); } catch { /* storage full or blocked */ } }
16
+ subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
17
+ /** @param {{who: string, number?: string|null, direction: 'in'|'out', outcome: 'answered'|'missed', durationMs?: number}} e */
18
+ add(e) {
19
+ this.entries = [{ ...e, at: this.now() }, ...this.entries].slice(0, this.max);
20
+ this._save(); this.listeners.forEach((fn) => fn());
21
+ }
22
+ list() { return this.entries.map((e) => ({ ...e })); }
23
+ /** Missed inbound calls since the log was last marked seen (the widget's badge). */
24
+ missedCount() { return this.entries.filter((e) => e.outcome === 'missed' && e.at > this.seenAt).length; }
25
+ markSeen() { this.seenAt = this.now(); this._save(); this.listeners.forEach((fn) => fn()); }
26
+ clear() { this.entries = []; this._save(); this.listeners.forEach((fn) => fn()); }
27
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Dialer settings the server does not store: how long this browser rings, and which channels ring it. They live in this
3
+ * browser (localStorage) and feed `softphone.register({ ringTimeoutSeconds, numbers })`.
4
+ */
5
+ export const MAX_RING_SECONDS = 60; // the server clamps to 0–60
6
+ const KEY = 'traitos.dialer.prefs';
7
+ export const DEFAULT_PREFS = Object.freeze({ ringTimeoutSeconds: 20, ringChannels: { whatsapp: true, phone: true }, callerId: null });
8
+
9
+ export function normalizePrefs(p = {}) {
10
+ const n = Math.round(Number(p?.ringTimeoutSeconds));
11
+ return {
12
+ ringTimeoutSeconds: p?.ringTimeoutSeconds === '' || p?.ringTimeoutSeconds == null || !Number.isFinite(n) ? DEFAULT_PREFS.ringTimeoutSeconds : Math.min(MAX_RING_SECONDS, Math.max(0, n)),
13
+ ringChannels: { whatsapp: p?.ringChannels?.whatsapp !== false, phone: p?.ringChannels?.phone !== false },
14
+ callerId: typeof p?.callerId === 'string' && p.callerId ? p.callerId : null,
15
+ };
16
+ }
17
+ export function loadPrefs(storage) { try { return normalizePrefs(JSON.parse(storage?.getItem(KEY) || '{}')); } catch { return normalizePrefs(); } }
18
+ export function savePrefs(storage, prefs) { try { storage?.setItem(KEY, JSON.stringify(normalizePrefs(prefs))); } catch { /* blocked */ } }
19
+
20
+ /** `{ringTimeoutSeconds, numbers}` for `softphone.register`: lines whose channel is ticked ring here. `numbers` is omitted when no line info. */
21
+ export function registrationFor(prefs, lines) {
22
+ const p = normalizePrefs(prefs);
23
+ if (!lines?.length) return { ringTimeoutSeconds: p.ringTimeoutSeconds };
24
+ const numbers = lines.filter((l) => {
25
+ const ch = Array.isArray(l.channels) ? l.channels : [];
26
+ return (ch.includes('whatsapp_calling') && p.ringChannels.whatsapp) || (ch.includes('voice') && p.ringChannels.phone);
27
+ }).map((l) => l.number).filter(Boolean);
28
+ return { ringTimeoutSeconds: p.ringTimeoutSeconds, numbers };
29
+ }
30
+
31
+ /** The saved prefs, or null when nobody has chosen any (so the server defaults stay in force until an admin changes them). */
32
+ export function storedPrefs(storage) { try { const v = storage?.getItem(KEY); return v ? normalizePrefs(JSON.parse(v)) : null; } catch { return null; } }
33
+ export const PREFS_EVENT = 'traitos-dialer-prefs';
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Keypad logic with no DOM. A call needs a country code, so a number must hold MIN_DIGITS digits before a call button works.
3
+ * `onCall({ number, channel })` receives digits only (no "+").
4
+ */
5
+ export const MIN_DIGITS = 7;
6
+ export const MAX_LENGTH = 24;
7
+
8
+ export const KEYS = Object.freeze([
9
+ { d: '1', l: '' }, { d: '2', l: 'ABC' }, { d: '3', l: 'DEF' },
10
+ { d: '4', l: 'GHI' }, { d: '5', l: 'JKL' }, { d: '6', l: 'MNO' },
11
+ { d: '7', l: 'PQRS' }, { d: '8', l: 'TUV' }, { d: '9', l: 'WXYZ' },
12
+ { d: '*', l: '' }, { d: '0', l: '+' }, { d: '#', l: '' },
13
+ ]);
14
+ export const CHANNELS = Object.freeze([
15
+ { id: 'whatsapp', labelKey: 'whatsapp', capKey: 'whatsappCallingEnabled' },
16
+ { id: 'phone', labelKey: 'phoneChannel', capKey: 'phoneCallingEnabled' },
17
+ ]);
18
+
19
+ /** Only characters a phone number can hold, capped in length. */
20
+ export const sanitizeNumber = (v) => String(v ?? '').replace(/[^0-9+*#\s-]/g, '').slice(0, MAX_LENGTH);
21
+ export const digitsOf = (v) => String(v ?? '').replace(/\D/g, '');
22
+ export const canCall = (v) => digitsOf(v).length >= MIN_DIGITS;
23
+ export const enabledChannels = (caps) => CHANNELS.filter((c) => caps && caps[c.capKey]).map((c) => c.id);
24
+
25
+ /** What Enter does: the preferred channel if enabled, else WhatsApp when on, else phone; null when nothing is enabled. */
26
+ export function defaultChannel(caps, preferred) {
27
+ const on = enabledChannels(caps);
28
+ if (preferred && on.includes(preferred)) return preferred;
29
+ return on.includes('whatsapp') ? 'whatsapp' : on[0] ?? null;
30
+ }
31
+
32
+ /** Channels a list of lines (GET /telephony/numbers) can call on: `voice` is phone, `whatsapp_calling` is WhatsApp. */
33
+ export function capsFromLines(lines) {
34
+ const has = (c) => (lines || []).some((l) => Array.isArray(l?.channels) && l.channels.includes(c));
35
+ return { whatsappCallingEnabled: has('whatsapp_calling'), phoneCallingEnabled: has('voice') };
36
+ }
37
+
38
+ /** @param {{caps?: object, onCall?: Function, defaultChannel?: string, clearOnCall?: boolean}} [opts] */
39
+ export function createDialpad(opts = {}) {
40
+ let number = '';
41
+ let caps = opts.caps || {};
42
+ let onCall = opts.onCall;
43
+ const listeners = new Set();
44
+ const set = (v) => { number = sanitizeNumber(v); listeners.forEach((fn) => fn()); };
45
+ const api = {
46
+ get number() { return number; },
47
+ get caps() { return caps; },
48
+ get digits() { return digitsOf(number); },
49
+ get canCall() { return canCall(number); },
50
+ get channels() { return enabledChannels(caps); },
51
+ get nothingEnabled() { return enabledChannels(caps).length === 0; },
52
+ setNumber: set,
53
+ press: (d) => set(number + d),
54
+ /** Long-press on 0: a "+" when the box is empty, otherwise an ordinary 0. */
55
+ pressZeroLong: () => set(number ? number + '0' : '+'),
56
+ backspace: () => set(number.slice(0, -1)),
57
+ clear: () => set(''),
58
+ setCaps(next) { caps = next || {}; listeners.forEach((fn) => fn()); },
59
+ setOnCall(fn) { onCall = fn; },
60
+ /** Returns true when `onCall` was invoked. A disabled channel or a short number never calls. */
61
+ call(channel) {
62
+ if (!canCall(number) || !enabledChannels(caps).includes(channel) || typeof onCall !== 'function') return false;
63
+ const payload = { number: digitsOf(number), channel };
64
+ if (opts.clearOnCall !== false) number = '';
65
+ listeners.forEach((fn) => fn());
66
+ onCall(payload);
67
+ return true;
68
+ },
69
+ /** Enter key. */
70
+ submit() { const ch = defaultChannel(caps, opts.defaultChannel); return ch ? api.call(ch) : false; },
71
+ subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
72
+ };
73
+ return api;
74
+ }
@@ -0,0 +1,115 @@
1
+ import { normalizeFlow, validateFlow, emptyFlow } from './flowModel.js';
2
+
3
+ /**
4
+ * State for the visual call-flow builder: load a number's flow, edit it, check it with the server, try a call, save.
5
+ * Needs a browser token with the `settings` scope (or an admin's own token).
6
+ */
7
+ export class FlowBuilderController {
8
+ constructor({ client, phoneNumberId, agents = [], team = [] }) {
9
+ this.client = client;
10
+ this.phoneNumberId = phoneNumberId;
11
+ this.lookup = { agents, team };
12
+ this._listeners = new Set();
13
+ this._history = [];
14
+ this._future = [];
15
+ this.state = { status: 'idle', flow: emptyFlow(), saved: null, enabled: true, localErrors: {}, serverCheck: null, simulation: null, message: null, dirty: false, busy: false };
16
+ }
17
+
18
+ snapshot() { return { ...this.state, canUndo: this._history.length > 0, canRedo: this._future.length > 0 }; }
19
+ subscribe(fn) { this._listeners.add(fn); return () => this._listeners.delete(fn); }
20
+ _set(patch) {
21
+ this.state = { ...this.state, ...patch };
22
+ for (const fn of [...this._listeners]) { try { fn(this.snapshot()); } catch { /* ignore */ } }
23
+ }
24
+
25
+ async load() {
26
+ this._set({ status: 'loading', message: null });
27
+ try {
28
+ const res = await this.client.phoneNumbers.flow.get(this.phoneNumberId);
29
+ const flow = normalizeFlow(res.flow);
30
+ this._history = []; this._future = [];
31
+ this._set({ status: 'ready', flow, saved: res.flow ? flow : null, enabled: res.enabled !== false, localErrors: validateFlow(flow), dirty: false, serverCheck: null, simulation: null });
32
+ } catch (error) {
33
+ this._set({ status: 'error', message: error?.message || 'Could not load this flow.' });
34
+ }
35
+ }
36
+
37
+ /** Apply an edit function from flowModel (e.g. `(f) => addRoute(f)`). Keeps undo history. */
38
+ apply(fn) {
39
+ const next = fn(this.state.flow);
40
+ if (!next || next === this.state.flow) return;
41
+ this._history.push(this.state.flow);
42
+ if (this._history.length > 100) this._history.shift();
43
+ this._future = [];
44
+ this._commit(next);
45
+ }
46
+
47
+ undo() { if (this._history.length) { this._future.push(this.state.flow); this._commit(this._history.pop()); } }
48
+ redo() { if (this._future.length) { this._history.push(this.state.flow); this._commit(this._future.pop()); } }
49
+
50
+ _commit(flow) {
51
+ this._set({ flow, localErrors: validateFlow(flow), dirty: JSON.stringify(flow) !== JSON.stringify(this.state.saved), serverCheck: null, message: null });
52
+ }
53
+
54
+ setEnabled(enabled) { this._set({ enabled, dirty: true }); }
55
+
56
+ /** Ask the server to check the flow. Resolves `{ valid, error? }`; never saves. */
57
+ async check() {
58
+ this._set({ busy: true });
59
+ try {
60
+ const r = await this.client.flows.validate(this.state.flow);
61
+ this._set({ serverCheck: r, busy: false });
62
+ return r;
63
+ } catch (error) {
64
+ this._set({ busy: false, message: error?.message || 'Could not check the flow.' });
65
+ return { valid: false, error: error?.message };
66
+ }
67
+ }
68
+
69
+ /** Dry-run a call through the flow at no phone cost. @param {{digits?: string, callerNumber?: string, scenario?: string}} options */
70
+ async simulate(options = {}) {
71
+ this._set({ busy: true, simulation: null });
72
+ try {
73
+ const simulation = await this.client.flows.simulate(this.state.flow, { ...options, phoneNumber: this.phoneNumberId });
74
+ this._set({ simulation, busy: false });
75
+ return simulation;
76
+ } catch (error) {
77
+ this._set({ busy: false, message: error?.message || 'Could not run the simulation.' });
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /** Describe the flow in plain English. The draft replaces the current flow (undoable); nothing is saved. */
83
+ async generate(prompt) {
84
+ if (!String(prompt ?? '').trim()) return false;
85
+ this._set({ busy: true, message: null });
86
+ try {
87
+ const res = await this.client.flows.generate(prompt, { currentFlow: this.state.flow, agents: this.lookup.agents.map(({ id, name }) => ({ id, name })) });
88
+ const draft = res.flow ?? res.draft;
89
+ if (!draft) { this._set({ busy: false, message: 'No draft came back. Try describing it differently.' }); return false; }
90
+ this._set({ busy: false });
91
+ this.apply(() => normalizeFlow(draft));
92
+ return true;
93
+ } catch (error) {
94
+ this._set({ busy: false, message: error?.message || 'Could not draft a flow.' });
95
+ return false;
96
+ }
97
+ }
98
+
99
+ /** Check locally, then save. Saving changes live call handling. Resolves true when saved. */
100
+ async save() {
101
+ const errors = validateFlow(this.state.flow);
102
+ if (Object.keys(errors).length) { this._set({ localErrors: errors, message: 'Fix the highlighted fields first.' }); return false; }
103
+ this._set({ busy: true, message: null });
104
+ try {
105
+ const res = await this.client.phoneNumbers.flow.save(this.phoneNumberId, this.state.flow, { enabled: this.state.enabled });
106
+ const flow = normalizeFlow(res?.flow ?? this.state.flow);
107
+ this._history = []; this._future = [];
108
+ this._set({ busy: false, flow, saved: flow, dirty: false, message: 'Saved. New calls use this flow.', serverCheck: null });
109
+ return true;
110
+ } catch (error) {
111
+ this._set({ busy: false, message: error?.message || 'Could not save the flow.' });
112
+ return false;
113
+ }
114
+ }
115
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The call-flow (TraitFlow) as plain data with immutable edit functions, so the builder can undo, diff and validate without a DOM.
3
+ * The server validates and normalises on save; `validateFlow` catches the mistakes a person can fix before asking it.
4
+ */
5
+ import { isE164 } from './softphoneState.js';
6
+
7
+ export const TARGET_TYPES = ['agent', 'team_member', 'department', 'external'];
8
+ export const TARGET_LABEL = { agent: 'AI agent', team_member: 'Team member', department: 'Department', external: 'Phone number' };
9
+ export const DIGITS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
10
+ export const DAYS = [{ n: 0, label: 'Sun' }, { n: 1, label: 'Mon' }, { n: 2, label: 'Tue' }, { n: 3, label: 'Wed' }, { n: 4, label: 'Thu' }, { n: 5, label: 'Fri' }, { n: 6, label: 'Sat' }];
11
+
12
+ export const emptyFlow = () => ({
13
+ greeting: 'Thanks for calling.',
14
+ menu: { prompt: 'For sales press 1. For support press 2.', timeoutSec: 6, maxDigits: 1, routes: {}, fallbackAgentId: null },
15
+ spam: { rateLimitPer10Min: 5, press1ScreenUnverified: false },
16
+ hours: { enabled: false, timezone: 'UTC', openHour: 9, closeHour: 17, days: [1, 2, 3, 4, 5], afterHoursAction: 'voicemail', afterHoursAgentId: null, voicemailPrompt: '' },
17
+ });
18
+
19
+ const copy = (f) => JSON.parse(JSON.stringify(f));
20
+ const edit = (flow, fn) => { const f = copy(flow); fn(f); return f; };
21
+
22
+ /** Fill the parts a saved flow may omit, so forms always have something to bind to. */
23
+ export function normalizeFlow(flow) {
24
+ const base = emptyFlow();
25
+ const f = flow ?? {};
26
+ return { ...base, ...f, menu: { ...base.menu, ...(f.menu ?? {}), routes: { ...(f.menu?.routes ?? {}) } }, spam: { ...base.spam, ...(f.spam ?? {}) }, hours: { ...base.hours, ...(f.hours ?? {}) } };
27
+ }
28
+
29
+ export const setGreeting = (flow, greeting) => edit(flow, (f) => { f.greeting = greeting; });
30
+ export const setMenu = (flow, patch) => edit(flow, (f) => { Object.assign(f.menu, patch); });
31
+ export const setSpam = (flow, patch) => edit(flow, (f) => { Object.assign(f.spam, patch); });
32
+ export const setHours = (flow, patch) => edit(flow, (f) => { Object.assign(f.hours, patch); });
33
+
34
+ export const nextFreeDigit = (flow) => DIGITS.find((d) => !(d in flow.menu.routes)) ?? null;
35
+
36
+ /** Add a route on the next free digit (or `digit`). Returns the same flow when every digit is taken. */
37
+ export function addRoute(flow, digit) {
38
+ const d = digit ?? nextFreeDigit(flow);
39
+ if (!d || d in flow.menu.routes) return flow;
40
+ return edit(flow, (f) => { f.menu.routes[d] = { extension: d, label: '', targetType: 'agent', targetAgentId: null, ringTimeoutSec: 20, enabled: true }; });
41
+ }
42
+
43
+ export const removeRoute = (flow, digit) => edit(flow, (f) => { delete f.menu.routes[digit]; });
44
+
45
+ export function setRoute(flow, digit, patch) {
46
+ if (!(digit in flow.menu.routes)) return flow;
47
+ return edit(flow, (f) => {
48
+ const r = Object.assign(f.menu.routes[digit], patch);
49
+ // Switching the kind of target drops the fields of the old kind, so a stale agent id cannot linger behind a phone number.
50
+ if (patch.targetType) {
51
+ if (r.targetType !== 'agent') r.targetAgentId = null;
52
+ if (r.targetType !== 'team_member') r.teamMemberId = null;
53
+ if (r.targetType !== 'department') r.departmentTargets = null;
54
+ if (r.targetType !== 'external') r.externalNumber = null;
55
+ }
56
+ });
57
+ }
58
+
59
+ /** Move a route to another digit. Refuses (returns the same flow) if that digit is taken. */
60
+ export function moveRoute(flow, from, to) {
61
+ if (from === to || !(from in flow.menu.routes) || to in flow.menu.routes) return flow;
62
+ return edit(flow, (f) => { const r = f.menu.routes[from]; delete f.menu.routes[from]; r.extension = to; f.menu.routes[to] = r; });
63
+ }
64
+
65
+ export const toggleDay = (flow, n) => edit(flow, (f) => { const s = new Set(f.hours.days); s.has(n) ? s.delete(n) : s.add(n); f.hours.days = [...s].sort(); });
66
+
67
+ /** Mistakes a person can fix. Keys are paths: `greeting`, `menu.prompt`, `routes.2.target`, `hours.closeHour`. */
68
+ export function validateFlow(flow) {
69
+ const e = {};
70
+ if (!String(flow.greeting ?? '').trim()) e.greeting = 'Say something when the call connects.';
71
+ if (!String(flow.menu?.prompt ?? '').trim()) e['menu.prompt'] = 'Tell callers what each number does.';
72
+ const t = Number(flow.menu?.timeoutSec);
73
+ if (!(t >= 1 && t <= 30)) e['menu.timeoutSec'] = 'Wait between 1 and 30 seconds.';
74
+ for (const [d, r] of Object.entries(flow.menu?.routes ?? {})) {
75
+ if (!String(r.label ?? '').trim()) e[`routes.${d}.label`] = 'Give this choice a name.';
76
+ if (r.targetType === 'agent' && !r.targetAgentId) e[`routes.${d}.target`] = 'Choose an AI agent.';
77
+ else if (r.targetType === 'team_member' && !r.teamMemberId) e[`routes.${d}.target`] = 'Choose a team member.';
78
+ else if (r.targetType === 'department' && !(r.departmentTargets?.length)) e[`routes.${d}.target`] = 'Choose at least one person in the department.';
79
+ else if (r.targetType === 'external' && !isE164(r.externalNumber)) e[`routes.${d}.target`] = 'Use + then country code and number.';
80
+ else if (!TARGET_TYPES.includes(r.targetType)) e[`routes.${d}.target`] = 'Choose who answers.';
81
+ }
82
+ const h = flow.hours;
83
+ if (h?.enabled) {
84
+ if (!(Number.isInteger(+h.openHour) && +h.openHour >= 0 && +h.openHour <= 23)) e['hours.openHour'] = 'Opening hour is 0 to 23.';
85
+ if (!(Number.isInteger(+h.closeHour) && +h.closeHour >= 1 && +h.closeHour <= 24)) e['hours.closeHour'] = 'Closing hour is 1 to 24.';
86
+ else if (+h.closeHour <= +h.openHour) e['hours.closeHour'] = 'Closing time must be after opening time.';
87
+ if (!h.days?.length) e['hours.days'] = 'Pick at least one open day.';
88
+ if (h.afterHoursAction === 'agent' && !h.afterHoursAgentId) e['hours.afterHoursAgentId'] = 'Choose who answers after hours.';
89
+ }
90
+ return e;
91
+ }
92
+
93
+ /**
94
+ * The flow as a picture: caller → greeting → menu → one lane per route (+ hours). Pure data, the element draws it.
95
+ * @param {object} flow
96
+ * @param {{agents?: {id: string, name: string}[], team?: {id: string, name: string}[]}} [lookup]
97
+ */
98
+ export function describeFlow(flow, lookup = {}) {
99
+ const name = (list, id) => (list ?? []).find((x) => x.id === id)?.name ?? id ?? '?';
100
+ const routes = Object.entries(flow.menu.routes).sort(([a], [b]) => DIGITS.indexOf(a) - DIGITS.indexOf(b)).map(([digit, r]) => ({
101
+ digit, label: r.label || '(unnamed)', kind: r.targetType,
102
+ target: r.targetType === 'agent' ? name(lookup.agents, r.targetAgentId)
103
+ : r.targetType === 'team_member' ? name(lookup.team, r.teamMemberId)
104
+ : r.targetType === 'department' ? `${r.departmentTargets?.length ?? 0} people`
105
+ : r.externalNumber || '?',
106
+ }));
107
+ return {
108
+ steps: [{ kind: 'caller', text: 'Caller dials' }, ...(flow.hours?.enabled ? [{ kind: 'hours', text: `Open ${flow.hours.openHour}:00 to ${flow.hours.closeHour}:00; after hours: ${flow.hours.afterHoursAction === 'agent' ? name(lookup.agents, flow.hours.afterHoursAgentId) : 'voicemail'}` }] : []), { kind: 'greeting', text: flow.greeting }, { kind: 'menu', text: flow.menu.prompt }],
109
+ routes,
110
+ fallback: flow.menu.fallbackAgentId ? name(lookup.agents, flow.menu.fallbackAgentId) : null,
111
+ };
112
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Recent calls for the dialer: the server's list (GET /calls, newest first) merged with this browser's own log, so a call
3
+ * shows once and a missed call the browser saw still shows if the server row is not there yet.
4
+ */
5
+ export const SAME_CALL_MS = 120_000;
6
+ const digits = (v) => String(v ?? '').replace(/\D/g, '');
7
+
8
+ /** A server call record → the dialer's entry. The "other party" is the caller for inbound calls, the callee for outbound. */
9
+ export function fromRecord(r) {
10
+ const inbound = r.direction === 'inbound';
11
+ const number = (inbound ? r.from : r.to) || null;
12
+ const at = r.startedAt ? Date.parse(r.startedAt) : 0;
13
+ const dur = Number(r.durationSeconds) > 0 ? Number(r.durationSeconds) * 1000 : 0;
14
+ return { who: number ?? 'Unknown', number, direction: inbound ? 'in' : 'out', outcome: dur ? 'answered' : 'missed', durationMs: dur, at, id: r.id };
15
+ }
16
+
17
+ export function mergeCalls(local = [], server = [], max = 10) {
18
+ const out = [...local];
19
+ for (const r of server.map(fromRecord)) {
20
+ const dup = out.some((e) => digits(e.number) === digits(r.number) && Math.abs((e.at || 0) - r.at) <= SAME_CALL_MS);
21
+ if (!dup) out.push(r);
22
+ }
23
+ return out.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, max);
24
+ }
@@ -0,0 +1,95 @@
1
+ import { SECTIONS, clone } from './settingsSections.js';
2
+
3
+ /**
4
+ * State for the settings forms: load, edit a draft, validate, save only what changed. Elements render `snapshot()`.
5
+ * Needs a browser token with the `settings` scope (or an admin's own token).
6
+ */
7
+ export class SettingsController {
8
+ /**
9
+ * @param {{client: object, agentId?: string, sections?: string[], storage?: Storage}} options `storage` holds the dialer's browser-only settings
10
+ */
11
+ constructor({ client, agentId, sections = ['handoff', 'approvals', 'usage'], storage }) {
12
+ this.client = client;
13
+ this.storage = storage;
14
+ this.agentId = agentId;
15
+ this.ids = sections.filter((id) => SECTIONS[id]);
16
+ this._listeners = new Set();
17
+ this._seq = {};
18
+ this.state = Object.fromEntries(this.ids.map((id) => [id, this._blank(id)]));
19
+ }
20
+
21
+ _blank(id) {
22
+ const needsAgent = SECTIONS[id].needsAgent && !this.agentId;
23
+ return { id, status: needsAgent ? 'needs-agent' : 'idle', original: null, draft: null, errors: {}, message: null, dirty: false };
24
+ }
25
+
26
+ snapshot() { return Object.fromEntries(this.ids.map((id) => [id, { ...this.state[id] }])); }
27
+ subscribe(fn) { this._listeners.add(fn); return () => this._listeners.delete(fn); }
28
+
29
+ _patch(id, patch) {
30
+ this.state[id] = { ...this.state[id], ...patch };
31
+ for (const fn of [...this._listeners]) { try { fn(this.snapshot()); } catch { /* ignore */ } }
32
+ }
33
+
34
+ setAgent(agentId) {
35
+ this.agentId = agentId;
36
+ for (const id of this.ids) this.state[id] = this._blank(id);
37
+ return this.loadAll();
38
+ }
39
+
40
+ loadAll() { return Promise.all(this.ids.map((id) => this.load(id))); }
41
+
42
+ async load(id) {
43
+ const def = SECTIONS[id];
44
+ if (def.needsAgent && !this.agentId) return this._patch(id, { status: 'needs-agent' });
45
+ const n = this._seq[id] = (this._seq[id] ?? 0) + 1; // a slow answer for an old agent must not overwrite a newer one
46
+ this._patch(id, { status: 'loading', message: null });
47
+ try {
48
+ const model = await def.load(this.client, { agentId: this.agentId, storage: this.storage });
49
+ if (n !== this._seq[id]) return;
50
+ this._patch(id, { status: 'ready', original: model, draft: clone(model), errors: {}, dirty: false });
51
+ } catch (error) {
52
+ if (n !== this._seq[id]) return;
53
+ this._patch(id, { status: 'error', message: error?.message || 'Could not load this section.' });
54
+ }
55
+ }
56
+
57
+ /** Change the draft with a function that mutates it (one of the section's edit helpers, or your own). */
58
+ edit(id, mutate) {
59
+ const s = this.state[id];
60
+ if (!s.draft || s.status === 'saving') return;
61
+ const draft = clone(s.draft);
62
+ mutate(draft, SECTIONS[id]);
63
+ const errors = SECTIONS[id].validate(draft);
64
+ this._patch(id, { draft, errors, dirty: SECTIONS[id].toPatch(s.original, draft) !== null, message: null, status: s.status === 'saved' ? 'ready' : s.status });
65
+ }
66
+
67
+ /** Set a top-level field, e.g. `set('handoff', 'transferNumber', '+1876…')`. */
68
+ set(id, field, value) { this.edit(id, (d) => { d[field] = value; }); }
69
+
70
+ reset(id) {
71
+ const s = this.state[id];
72
+ if (s.original) this._patch(id, { draft: clone(s.original), errors: {}, dirty: false, message: null, status: 'ready' });
73
+ }
74
+
75
+ /** Save the section. Resolves true when saved. Validation errors stay on the form; nothing is sent. */
76
+ async save(id) {
77
+ const def = SECTIONS[id];
78
+ const s = this.state[id];
79
+ if (!s.draft || s.status === 'saving') return false; // a double click must not save twice
80
+ const errors = def.validate(s.draft);
81
+ if (Object.keys(errors).length) { this._patch(id, { errors, message: 'Fix the highlighted fields first.' }); return false; }
82
+ const patch = def.toPatch(s.original, s.draft);
83
+ if (!patch) { this._patch(id, { message: 'Nothing to save.' }); return false; }
84
+ this._patch(id, { status: 'saving', message: null });
85
+ try {
86
+ await def.save(this.client, { agentId: this.agentId, storage: this.storage }, patch);
87
+ await this.load(id);
88
+ this._patch(id, { status: 'saved', message: 'Saved.' });
89
+ return true;
90
+ } catch (error) {
91
+ this._patch(id, { status: 'ready', message: error?.message || 'Could not save.' });
92
+ return false;
93
+ }
94
+ }
95
+ }