File size: 11,496 Bytes
21bb60f
 
 
 
 
 
 
 
 
 
b9cd14b
21bb60f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9cd14b
 
 
 
 
 
 
21bb60f
 
 
 
b9cd14b
21bb60f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9cd14b
21bb60f
b9cd14b
 
 
 
 
21bb60f
 
b9cd14b
21bb60f
 
 
b9cd14b
21bb60f
 
 
 
 
 
 
 
 
b9cd14b
 
 
 
 
 
21bb60f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import React, {
    createContext,
    useCallback,
    useContext,
    useEffect,
    useMemo,
    useRef,
    useState,
} from 'react';
import { apiFetch } from '@/lib/api';
import { mergeSequenceIntoContacts } from '@/lib/mergeSequenceIntoContacts';

const GeneratorWorkflowContext = createContext(null);

export function GeneratorWorkflowProvider({ children }) {
    const [step, setStep] = useState(1);
    const [uploadedFile, setUploadedFile] = useState(null);
    const [selectedProducts, setSelectedProducts] = useState([]);
    const [prompts, setPrompts] = useState({});
    const [linkedinPrompts, setLinkedinPrompts] = useState({});
    const [includeLinkedin, setIncludeLinkedin] = useState(false);
    const [isGenerating, setIsGenerating] = useState(false);
    const [generationComplete, setGenerationComplete] = useState(false);
    const [generationRunId, setGenerationRunId] = useState(0);
    const [genPhase, setGenPhase] = useState('email');
    const [contacts, setContacts] = useState([]);
    const [sequences, setSequences] = useState([]);
    const [progress, setProgress] = useState(0);
    const [streamComplete, setStreamComplete] = useState(false);
    const [reconnectKey, setReconnectKey] = useState(0);

    const prevRunIdRef = useRef(null);
    const eventSourceRef = useRef(null);

    const resetWorkflow = useCallback(() => {
        if (eventSourceRef.current) {
            eventSourceRef.current.close();
            eventSourceRef.current = null;
        }
        setStep(1);
        setUploadedFile(null);
        setSelectedProducts([]);
        setPrompts({});
        setLinkedinPrompts({});
        setIncludeLinkedin(false);
        setIsGenerating(false);
        setGenerationComplete(false);
        setGenerationRunId(0);
        setGenPhase('email');
        setContacts([]);
        setSequences([]);
        setProgress(0);
        setStreamComplete(false);
        prevRunIdRef.current = null;
    }, []);

    const beginGeneration = useCallback((runIdIncrement = true) => {
        setStreamComplete(false);
        setGenerationComplete(false);
        setContacts([]);
        setSequences([]);
        setProgress(0);
        setGenPhase('email');
        setIsGenerating(true);
        if (runIdIncrement) {
            setGenerationRunId((r) => r + 1);
        }
    }, []);

    const contactCount = uploadedFile?.contactCount || 0;

    useEffect(() => {
        if (!isGenerating || !uploadedFile?.fileId) return;

        const isNewRun = prevRunIdRef.current !== generationRunId;
        if (isNewRun) {
            prevRunIdRef.current = generationRunId;
            setContacts([]);
            setSequences([]);
            setProgress(0);
            setStreamComplete(false);
        }

        const reset = isNewRun ? 1 : 0;
        const url = `/api/generate-sequences?file_id=${encodeURIComponent(uploadedFile.fileId)}&reset=${reset}`;
        const eventSource = new EventSource(url);
        eventSourceRef.current = eventSource;

        eventSource.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.type === 'sequence') {
                    const seq = data.sequence;
                    setSequences((prev) => {
                        const sig = `${seq.id}-${seq.emailNumber}-${seq.channel || 'email'}-${seq.stepOrder ?? ''}`;
                        if (
                            prev.some(
                                (s) =>
                                    `${s.id}-${s.emailNumber}-${s.channel || 'email'}-${s.stepOrder ?? ''}` === sig
                            )
                        ) {
                            return prev;
                        }
                        return [...prev, seq];
                    });
                    setContacts((prev) => mergeSequenceIntoContacts(prev, seq));
                } else if (data.type === 'progress') {
                    if (typeof data.progress === 'number') setProgress(data.progress);
                } else if (data.type === 'phase') {
                    if (data.phase === 'linkedin') setGenPhase('linkedin');
                } else if (data.type === 'complete') {
                    setStreamComplete(true);
                    setIsGenerating(false);
                    setGenerationComplete(true);
                    eventSource.close();
                    eventSourceRef.current = null;
                } else if (data.type === 'error') {
                    console.error('Generation error:', data.error);
                    alert('Error generating sequences: ' + data.error);
                    eventSource.close();
                    eventSourceRef.current = null;
                    setIsGenerating(false);
                }
            } catch (err) {
                console.error('Error parsing SSE data:', err);
            }
        };

        eventSource.onerror = () => {
            eventSource.close();
            eventSourceRef.current = null;
            if (!streamComplete) setReconnectKey((k) => k + 1);
        };

        return () => {
            eventSource.close();
            if (eventSourceRef.current === eventSource) eventSourceRef.current = null;
        };
    }, [isGenerating, uploadedFile?.fileId, generationRunId]);

    useEffect(() => {
        if (!isGenerating || !uploadedFile?.fileId || reconnectKey === 0) return;
        let cancelled = false;
        (async () => {
            try {
                const [statusRes, seqRes] = await Promise.all([
                    apiFetch(`/api/generation-status?file_id=${encodeURIComponent(uploadedFile.fileId)}`),
                    apiFetch(`/api/sequences?file_id=${encodeURIComponent(uploadedFile.fileId)}`),
                ]);
                if (cancelled) return;
                if (statusRes.ok && seqRes.ok) {
                    const status = await statusRes.json();
                    const { sequences: list } = await seqRes.json();
                    if (status.is_complete) {
                        setStreamComplete(true);
                        setIsGenerating(false);
                        setGenerationComplete(true);
                    }
                    if (list?.length > 0) {
                        const byContact = new Map();
                        list.forEach((seq) => {
                            const key = seq.email;
                            const ch = seq.channel || 'email';
                            if (!byContact.has(key)) {
                                byContact.set(key, {
                                    id: seq.id,
                                    firstName: seq.firstName,
                                    lastName: seq.lastName,
                                    email: seq.email,
                                    company: seq.company,
                                    title: seq.title,
                                    product: seq.product,
                                    emails: [],
                                    linkedin: [],
                                });
                            }
                            const row = {
                                emailNumber: seq.emailNumber,
                                subject: seq.subject,
                                emailContent: seq.emailContent,
                                channel: ch,
                                stepOrder: seq.stepOrder,
                            };
                            const dedupe = (e) =>
                                e.stepOrder != null
                                    ? `ord-${e.stepOrder}-${ch}`
                                    : `${ch}-${e.emailNumber}`;
                            const rowKey = dedupe(row);
                            const c = byContact.get(key);
                            if (ch === 'linkedin') {
                                if (!c.linkedin.some((e) => dedupe(e) === rowKey)) {
                                    c.linkedin.push(row);
                                }
                            } else {
                                if (!c.emails.some((e) => dedupe(e) === rowKey)) {
                                    c.emails.push(row);
                                }
                            }
                        });
                        const arr = [...byContact.values()];
                        arr.sort((a, b) => (a.id || 0) - (b.id || 0));
                        setSequences(list);
                        setContacts(arr);
                        if (status.total_contacts > 0) {
                            const exp =
                                status.campaign_sequence_actions && status.total_contacts > 0
                                    ? status.total_contacts * status.campaign_sequence_actions
                                    : status.has_linkedin_prompts
                                      ? status.total_contacts * 2
                                      : status.total_contacts;
                            setProgress(
                                Math.min(100, ((status.completed_count || 0) / exp) * 100)
                            );
                        }
                    }
                }
            } catch (e) {
                if (!cancelled) console.error('Reconnect fetch error:', e);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [reconnectKey, isGenerating, uploadedFile?.fileId, contactCount]);

    useEffect(() => {
        if (!isGenerating || !uploadedFile?.fileId) return;
        const onVisible = () => {
            if (document.visibilityState === 'visible') setReconnectKey((k) => k + 1);
        };
        document.addEventListener('visibilitychange', onVisible);
        return () => document.removeEventListener('visibilitychange', onVisible);
    }, [isGenerating, uploadedFile?.fileId]);

    const value = useMemo(
        () => ({
            step,
            setStep,
            uploadedFile,
            setUploadedFile,
            selectedProducts,
            setSelectedProducts,
            prompts,
            setPrompts,
            linkedinPrompts,
            setLinkedinPrompts,
            includeLinkedin,
            setIncludeLinkedin,
            isGenerating,
            generationComplete,
            generationRunId,
            beginGeneration,
            setIsGenerating,
            setGenerationComplete,
            resetWorkflow,
            contacts,
            sequences,
            progress,
            genPhase,
            streamComplete,
            contactCount,
        }),
        [
            step,
            uploadedFile,
            selectedProducts,
            prompts,
            linkedinPrompts,
            includeLinkedin,
            isGenerating,
            generationComplete,
            generationRunId,
            beginGeneration,
            resetWorkflow,
            contacts,
            sequences,
            progress,
            genPhase,
            streamComplete,
            contactCount,
        ]
    );

    return (
        <GeneratorWorkflowContext.Provider value={value}>{children}</GeneratorWorkflowContext.Provider>
    );
}

export function useGeneratorWorkflow() {
    const ctx = useContext(GeneratorWorkflowContext);
    if (!ctx) {
        throw new Error('useGeneratorWorkflow must be used within GeneratorWorkflowProvider');
    }
    return ctx;
}