File size: 2,113 Bytes
6f07329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 type { MessageAgentQueueUpdate } from "$lib/types/MessageUpdate";
import type {
	AgentQueueMutation,
	AgentQueueReplacement,
	AgentQueueSnapshot,
} from "./activityTypes";

export interface AgentQueueMutationTarget {
	queue: AgentQueueMutation["queue"];
	index: number;
	value: string;
	expected: AgentQueueSnapshot;
}

function cloneSnapshot(snapshot: AgentQueueSnapshot): AgentQueueSnapshot {
	return {
		steering: [...snapshot.steering],
		followUp: [...snapshot.followUp],
	};
}

export function snapshotAgentQueue(
	update: Pick<MessageAgentQueueUpdate, "steering" | "followUp">
): AgentQueueSnapshot {
	return {
		steering: [...update.steering],
		followUp: [...update.followUp],
	};
}

export function captureAgentQueueMutationTarget(
	update: Pick<MessageAgentQueueUpdate, "steering" | "followUp">,
	queue: AgentQueueMutation["queue"],
	index: number
): AgentQueueMutationTarget | undefined {
	const expected = snapshotAgentQueue(update);
	const value = expected[queue][index];
	if (typeof value !== "string") return;
	return { queue, index, value, expected };
}

export function agentQueueMatchesSnapshot(
	update: Pick<MessageAgentQueueUpdate, "steering" | "followUp">,
	expected: AgentQueueSnapshot
): boolean {
	return (
		update.steering.length === expected.steering.length &&
		update.followUp.length === expected.followUp.length &&
		update.steering.every((value, index) => value === expected.steering[index]) &&
		update.followUp.every((value, index) => value === expected.followUp[index])
	);
}

export function createAgentQueueReplacement(
	target: AgentQueueMutationTarget,
	action: AgentQueueMutation["action"],
	value?: string
): AgentQueueReplacement | undefined {
	if (target.expected[target.queue][target.index] !== target.value) return;
	if (action === "edit" && typeof value !== "string") return;

	const expected = cloneSnapshot(target.expected);
	const replacement = cloneSnapshot(target.expected);
	if (action === "remove") replacement[target.queue].splice(target.index, 1);
	else replacement[target.queue][target.index] = value as string;
	return { expected, replacement };
}