@startsimpli/integrations 0.2.49 → 0.2.51

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.
@@ -0,0 +1,358 @@
1
+ /**
2
+ * Recipient-local-time sends in the comms UI (bd startsim-ofio9.4, epic
3
+ * startsim-ofio9): the schedule picker's "exact time" vs "each recipient's own
4
+ * time zone" choice with the no-known-zone count and the fallback that applies,
5
+ * the default_timezone setting, and per-zone progress in the scheduled list.
6
+ * A mocked Django (msw) behind the REAL createCommsApi client.
7
+ */
8
+ import * as React from 'react';
9
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
10
+ import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
11
+ import userEvent from '@testing-library/user-event';
12
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
13
+ import { http, HttpResponse } from 'msw';
14
+ import { setupServer } from 'msw/node';
15
+
16
+ import { DefaultTimeZoneSetting } from '../components/DefaultTimeZoneSetting';
17
+ import { DraftReview } from '../components/DraftReview';
18
+ import { SendLog } from '../components/SendLog';
19
+ import { createCommsApi, setApiBase } from '../api/index';
20
+ import type { CommsSettings, Draft, DraftGroup, ScheduledSend } from '../types/index';
21
+ import { BASE, P, SLUG, draft, settings } from './fixtures';
22
+
23
+ interface Hit { method: string; path: string; body: any }
24
+ let hits: Hit[] = [];
25
+ let drafts: Draft[] = [];
26
+ let scheduledReport: ScheduledSend[] = [];
27
+ let commsSettings: CommsSettings = settings();
28
+ let noTimezone: number | undefined = 3;
29
+
30
+ const rel = (p: string) => p.replace(new URL(P).pathname, '');
31
+
32
+ const server = setupServer(
33
+ http.all(`${P}/*`, async ({ request }) => {
34
+ const url = new URL(request.url);
35
+ const text = request.method === 'GET' ? '' : await request.text();
36
+ const hit: Hit = { method: request.method, path: rel(url.pathname), body: text ? JSON.parse(text) : undefined };
37
+ hits.push(hit);
38
+ const { method, path, body } = hit;
39
+ let m: RegExpMatchArray | null;
40
+ if (path === '/settings/') {
41
+ if (method === 'PATCH') commsSettings = { ...commsSettings, ...body };
42
+ return HttpResponse.json(commsSettings);
43
+ }
44
+ if (path === '/drafts/' && method === 'GET') {
45
+ const wanted = url.searchParams.get('status');
46
+ const results = drafts.filter((d) => !wanted || d.approval === wanted);
47
+ return HttpResponse.json({ count: results.length, next: null, previous: null, results });
48
+ }
49
+ if ((m = path.match(/^\/drafts\/([\w-]+)\/(approve|reschedule|cancel)\/$/)) && method === 'POST') {
50
+ const d = drafts.find((x) => x.id === m![1])!;
51
+ if (m[2] === 'approve' && body?.send_mode === 'recipient_local') {
52
+ Object.assign(d, { approval: 'scheduled', state: 'scheduled', send_mode: 'recipient_local', local_time: `${body.send_at}:00`, send_at: '2026-11-19T19:00:00+00:00', groups: [] });
53
+ } else if (m[2] === 'approve') {
54
+ d.approval = 'approved';
55
+ } else if (m[2] === 'reschedule') {
56
+ Object.assign(d, { local_time: `${body.send_at}:00` });
57
+ } else {
58
+ Object.assign(d, { approval: 'sent', state: 'sent', notice: { code: 'cancelled_partial', reason: 'Cancelled. 6 recipients in 5 time zones had not been sent and will not be. 1 recipient in 1 time zone was already sent or started and cannot be recalled.' } });
59
+ }
60
+ return HttpResponse.json(d);
61
+ }
62
+ if ((m = path.match(/^\/drafts\/([\w-]+)\/audience\/$/)) && method === 'GET') {
63
+ const preview: any = { count: 7, eligible: 7, excluded: {}, excluded_total: 0, sample: [], excluded_sample: [] };
64
+ if (noTimezone !== undefined) preview.no_timezone = noTimezone;
65
+ return HttpResponse.json({ audience: { base: 'all' }, is_default: true, preview });
66
+ }
67
+ if (path === '/sends/' && method === 'GET') {
68
+ return HttpResponse.json({ count: 0, next: null, previous: null, results: [], scheduled: scheduledReport });
69
+ }
70
+ return HttpResponse.json({ detail: `unhandled ${method} ${path}` }, { status: 599 });
71
+ }),
72
+ );
73
+
74
+ beforeAll(() => {
75
+ server.listen({ onUnhandledRequest: 'error' });
76
+ setApiBase(`${BASE}/api/v1`);
77
+ });
78
+ afterEach(() => server.resetHandlers());
79
+ afterAll(() => server.close());
80
+ beforeEach(() => {
81
+ hits = [];
82
+ drafts = [draft()];
83
+ scheduledReport = [];
84
+ commsSettings = settings();
85
+ noTimezone = 3;
86
+ });
87
+
88
+ function renderWith(node: (api: ReturnType<typeof createCommsApi>) => React.ReactElement) {
89
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
90
+ return render(<QueryClientProvider client={qc}>{node(createCommsApi(SLUG))}</QueryClientProvider>);
91
+ }
92
+
93
+ const writes = () => hits.filter((h) => h.method !== 'GET');
94
+ const LOCAL = 'In each recipient.s own time zone';
95
+ const EXACT = 'At this exact time';
96
+
97
+ async function openPicker() {
98
+ await userEvent.click(await screen.findByRole('button', { name: /schedule/i }));
99
+ }
100
+
101
+ const group = (over: Partial<DraftGroup>): DraftGroup => ({
102
+ zone: 'Asia/Tokyo', at: '2026-11-20T00:00:00+00:00', state: 'waiting', late: false, note: null,
103
+ sources: { browser: 1, foundry_default: 0, utc: 0 }, count: 1, pending: 1, sent: 0, failed: 0, suppressed: 0,
104
+ started_at: null, completed_at: null, failure: null, reason: null, ...over,
105
+ });
106
+
107
+ const rolling = (over: Partial<Draft> = {}): Draft => draft({
108
+ approval: 'rolling', state: 'rolling', next_actions: ['reschedule', 'send_now', 'cancel'],
109
+ send_mode: 'recipient_local', local_time: '2026-11-20T09:00:00', send_at: '2026-11-20T00:00:00+00:00',
110
+ recipient_count: 3,
111
+ groups: [
112
+ group({ zone: 'Pacific/Kiritimati', at: '2026-11-19T19:00:00+00:00', state: 'sent', pending: 0, sent: 1 }),
113
+ group({ zone: 'Asia/Tokyo', state: 'sending', count: 2, pending: 1, sent: 1 }),
114
+ group({ zone: 'America/New_York', at: '2026-11-20T14:00:00+00:00' }),
115
+ ],
116
+ group_summary: { total: 3, waiting: 1, sending: 1, sent: 1, failed: 0, expired: 0, cancelled: 0 },
117
+ ...over,
118
+ });
119
+
120
+ describe('the schedule picker offers two ways to time a send', () => {
121
+ it('defaults to the exact time and shows the choice', async () => {
122
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
123
+ await openPicker();
124
+ expect(screen.getByRole('radio', { name: EXACT })).toBeChecked();
125
+ expect(screen.getByRole('radio', { name: new RegExp(LOCAL, 'i') })).not.toBeChecked();
126
+ expect(screen.getByLabelText('Time zone')).toBeInTheDocument();
127
+ });
128
+
129
+ it('exact mode still posts the instant with its zone and no send_mode', async () => {
130
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
131
+ await openPicker();
132
+ fireEvent.change(screen.getByLabelText('Send at'), { target: { value: '2026-11-03T10:00' } });
133
+ await userEvent.selectOptions(screen.getByLabelText('Time zone'), 'Asia/Tokyo');
134
+ await userEvent.click(screen.getByRole('button', { name: /approve and schedule/i }));
135
+ await waitFor(() => expect(writes()[0].body).toEqual({ send_at: '2026-11-03T10:00', timezone: 'Asia/Tokyo' }));
136
+ });
137
+
138
+ it('local mode posts the wall-clock time with send_mode and no time zone', async () => {
139
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
140
+ await openPicker();
141
+ await userEvent.click(screen.getByRole('radio', { name: new RegExp(LOCAL, 'i') }));
142
+ expect(screen.queryByLabelText('Time zone')).toBeNull();
143
+ fireEvent.change(screen.getByLabelText('Send at'), { target: { value: '2026-11-20T09:00' } });
144
+ await userEvent.click(screen.getByRole('button', { name: /approve and schedule/i }));
145
+ await waitFor(() =>
146
+ expect(writes()[0]).toMatchObject({
147
+ method: 'POST', path: '/drafts/d-1/approve/', body: { send_at: '2026-11-20T09:00', send_mode: 'recipient_local' },
148
+ }),
149
+ );
150
+ expect(writes()[0].body.timezone).toBeUndefined();
151
+ });
152
+
153
+ it('says how many recipients have no known zone and that UTC applies when no default is set', async () => {
154
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
155
+ await openPicker();
156
+ await userEvent.click(screen.getByRole('radio', { name: new RegExp(LOCAL, 'i') }));
157
+ expect(await screen.findByText(/3 recipients have no known time zone/i)).toBeInTheDocument();
158
+ expect(await screen.findByText(/no default time zone is set.*UTC/i)).toBeInTheDocument();
159
+ });
160
+
161
+ it('names the default time zone as the fallback when one is set', async () => {
162
+ commsSettings = settings({ default_timezone: 'Europe/Paris' });
163
+ noTimezone = 1;
164
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
165
+ await openPicker();
166
+ await userEvent.click(screen.getByRole('radio', { name: new RegExp(LOCAL, 'i') }));
167
+ expect(await screen.findByText(/1 recipient has no known time zone/i)).toBeInTheDocument();
168
+ expect(await screen.findByText(/they get Europe\/Paris, your default time zone/i)).toBeInTheDocument();
169
+ });
170
+
171
+ it('says so when every recipient has a known zone', async () => {
172
+ noTimezone = 0;
173
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
174
+ await openPicker();
175
+ await userEvent.click(screen.getByRole('radio', { name: new RegExp(LOCAL, 'i') }));
176
+ expect(await screen.findByText(/every recipient has a known time zone/i)).toBeInTheDocument();
177
+ });
178
+
179
+ it('explains the span and the late-zone rule in plain words', async () => {
180
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
181
+ await openPicker();
182
+ await userEvent.click(screen.getByRole('radio', { name: new RegExp(LOCAL, 'i') }));
183
+ expect(screen.getByText(/up to 26 hours/i)).toBeInTheDocument();
184
+ expect(screen.getByText(/zones where that time has passed send immediately/i)).toBeInTheDocument();
185
+ });
186
+
187
+ it('asks the audience only once local mode is chosen', async () => {
188
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
189
+ await openPicker();
190
+ expect(hits.filter((h) => h.path.endsWith('/audience/') && h.path.includes('d-1'))).toHaveLength(0);
191
+ });
192
+ });
193
+
194
+ describe('a scheduled recipient-local draft', () => {
195
+ beforeEach(() => {
196
+ drafts = [draft({
197
+ approval: 'scheduled', state: 'scheduled', send_mode: 'recipient_local', local_time: '2026-11-20T09:00:00',
198
+ send_at: '2026-11-19T19:00:00+00:00', send_timezone: null, recipient_count: 7, groups: [],
199
+ })];
200
+ });
201
+
202
+ it('is listed as 9:00 in each recipient\'s own time zone', async () => {
203
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
204
+ const heading = await screen.findByRole('heading', { name: /scheduled to send/i });
205
+ const list = within(heading.parentElement as HTMLElement);
206
+ expect(await list.findByText(/in each recipient.s own time zone/i)).toBeInTheDocument();
207
+ expect(list.getByText(/9:00/)).toBeInTheDocument();
208
+ expect(list.getByText(/people who join after the first zone starts are not included/i)).toBeInTheDocument();
209
+ });
210
+
211
+ it('reschedules with the local picker preselected', async () => {
212
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
213
+ await userEvent.click(await screen.findByRole('button', { name: /^reschedule$/i }));
214
+ expect(screen.getByRole('radio', { name: new RegExp(LOCAL, 'i') })).toBeChecked();
215
+ fireEvent.change(screen.getByLabelText('Send at'), { target: { value: '2026-11-22T08:30' } });
216
+ await userEvent.click(screen.getByRole('button', { name: /move send/i }));
217
+ await waitFor(() =>
218
+ expect(writes()[0]).toMatchObject({
219
+ path: '/drafts/d-1/reschedule/', body: { send_at: '2026-11-22T08:30', send_mode: 'recipient_local' },
220
+ }),
221
+ );
222
+ });
223
+ });
224
+
225
+ describe('a rolling recipient-local draft', () => {
226
+ beforeEach(() => {
227
+ drafts = [rolling()];
228
+ });
229
+
230
+ it('shows per-zone progress, soonest first', async () => {
231
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
232
+ const table = await screen.findByRole('table', { name: /progress by time zone/i });
233
+ const rows = within(table).getAllByRole('row').slice(1);
234
+ expect(rows).toHaveLength(3);
235
+ expect(rows[0]).toHaveTextContent('Pacific/Kiritimati');
236
+ expect(rows[0]).toHaveTextContent(/sent/i);
237
+ expect(rows[0]).toHaveTextContent('1 of 1');
238
+ expect(rows[1]).toHaveTextContent('Asia/Tokyo');
239
+ expect(rows[1]).toHaveTextContent(/sending/i);
240
+ expect(rows[1]).toHaveTextContent('1 of 2');
241
+ expect(rows[2]).toHaveTextContent('America/New_York');
242
+ expect(rows[2]).toHaveTextContent(/waiting/i);
243
+ });
244
+
245
+ it('summarises how many zones have gone out', async () => {
246
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
247
+ expect(await screen.findByText(/2 of 3 time zones started/i)).toBeInTheDocument();
248
+ });
249
+
250
+ it('says what cancel does to zones already sent', async () => {
251
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
252
+ expect(await screen.findByText(/zones already sent cannot be recalled/i)).toBeInTheDocument();
253
+ });
254
+
255
+ it('cancel posts cancel and shows what the server says was and was not sent', async () => {
256
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
257
+ await userEvent.click(await screen.findByRole('button', { name: /cancel remaining zones/i }));
258
+ await waitFor(() => expect(writes()[0]).toMatchObject({ method: 'POST', path: '/drafts/d-1/cancel/' }));
259
+ });
260
+
261
+ it('shows a failed zone with its reason', async () => {
262
+ drafts = [rolling({
263
+ groups: [group({ zone: 'Asia/Tokyo', state: 'failed', pending: 2, count: 2,
264
+ failure: { stage: 'send', code: 'recipients_not_sent', reason: '2 recipients still unsent after 3 retries' } })],
265
+ })];
266
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
267
+ const table = await screen.findByRole('table', { name: /progress by time zone/i });
268
+ expect(within(table).getByText(/2 recipients still unsent after 3 retries/i)).toBeInTheDocument();
269
+ });
270
+
271
+ it('marks a zone that went out late and one with a clock-change note', async () => {
272
+ drafts = [rolling({
273
+ groups: [
274
+ group({ zone: 'Asia/Tokyo', state: 'sending', late: true }),
275
+ group({ zone: 'America/New_York', state: 'waiting', note: 'gap' }),
276
+ ],
277
+ })];
278
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
279
+ const table = await screen.findByRole('table', { name: /progress by time zone/i });
280
+ expect(within(table).getByText(/sent late/i)).toBeInTheDocument();
281
+ expect(within(table).getByText(/clock change skips this time/i)).toBeInTheDocument();
282
+ expect(within(table).getByText(/first moment after the change/i)).toBeInTheDocument();
283
+ expect(within(table).queryByText(/elapsed/i)).toBeNull();
284
+ });
285
+
286
+ it('says the plan is frozen at the first zone, before and after it starts', async () => {
287
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
288
+ expect(await screen.findByText(/people who join after the first zone starts are not included/i)).toBeInTheDocument();
289
+ });
290
+
291
+ it('Send now asks first, says what it does, and posts only on confirm', async () => {
292
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
293
+ await userEvent.click(await screen.findByRole('button', { name: /^send now$/i }));
294
+ expect(writes()).toEqual([]);
295
+ expect(screen.getByText(/send now starts every waiting time zone immediately/i)).toBeInTheDocument();
296
+ await userEvent.click(screen.getByRole('button', { name: /yes, start every waiting zone/i }));
297
+ await waitFor(() => expect(writes()[0]).toMatchObject({ method: 'POST', path: '/drafts/d-1/approve/' }));
298
+ expect(writes()[0].body).toBeUndefined();
299
+ });
300
+
301
+ it('Send now can be backed out of with no write', async () => {
302
+ renderWith((api) => <DraftReview api={api} pollIntervalMs={10} />);
303
+ await userEvent.click(await screen.findByRole('button', { name: /^send now$/i }));
304
+ await userEvent.click(screen.getByRole('button', { name: /keep waiting/i }));
305
+ expect(screen.queryByText(/send now starts every waiting time zone/i)).toBeNull();
306
+ expect(writes()).toEqual([]);
307
+ });
308
+ });
309
+
310
+ describe('send log', () => {
311
+ it('lists a rolling draft with its progress reason', async () => {
312
+ scheduledReport = [{
313
+ id: 'r-1', program_key: 'announcement', subject: 'Global news', status: 'rolling',
314
+ reason: '2 of 3 time zones started; next: America/New_York at 2026-11-20T14:00:00+00:00',
315
+ send_at: '2026-11-20T14:00:00+00:00', send_timezone: null, cancelled_at: null,
316
+ send_mode: 'recipient_local', local_time: '2026-11-20T09:00:00', groups: [], group_summary: null,
317
+ }];
318
+ renderWith((api) => <SendLog api={api} />);
319
+ expect(await screen.findByText('Global news')).toBeInTheDocument();
320
+ expect(screen.getByText('rolling')).toBeInTheDocument();
321
+ expect(screen.getByText(/2 of 3 time zones started/i)).toBeInTheDocument();
322
+ expect(screen.getByText(/in each recipient.s own time zone/i)).toBeInTheDocument();
323
+ });
324
+ });
325
+
326
+ describe('default time zone setting', () => {
327
+ it('shows the current value and saves a new one', async () => {
328
+ commsSettings = settings({ default_timezone: 'Europe/Paris' });
329
+ renderWith((api) => <DefaultTimeZoneSetting api={api} />);
330
+ const select = await screen.findByLabelText(/default time zone/i);
331
+ expect(select).toHaveValue('Europe/Paris');
332
+ await userEvent.selectOptions(select, 'America/Denver');
333
+ await userEvent.click(screen.getByRole('button', { name: /save/i }));
334
+ await waitFor(() =>
335
+ expect(writes()[0]).toMatchObject({ method: 'PATCH', path: '/settings/', body: { default_timezone: 'America/Denver' } }),
336
+ );
337
+ expect(await screen.findByText(/saved/i)).toBeInTheDocument();
338
+ });
339
+
340
+ it('can be cleared back to UTC', async () => {
341
+ commsSettings = settings({ default_timezone: 'Europe/Paris' });
342
+ renderWith((api) => <DefaultTimeZoneSetting api={api} />);
343
+ await userEvent.selectOptions(await screen.findByLabelText(/default time zone/i), '');
344
+ await userEvent.click(screen.getByRole('button', { name: /save/i }));
345
+ await waitFor(() => expect(writes()[0].body).toEqual({ default_timezone: '' }));
346
+ });
347
+
348
+ it('explains what it is for', async () => {
349
+ renderWith((api) => <DefaultTimeZoneSetting api={api} />);
350
+ expect(await screen.findByText(/used for recipients whose own time zone is not known/i)).toBeInTheDocument();
351
+ });
352
+
353
+ it('makes no write until Save', async () => {
354
+ renderWith((api) => <DefaultTimeZoneSetting api={api} />);
355
+ await screen.findByLabelText(/default time zone/i);
356
+ expect(writes()).toEqual([]);
357
+ });
358
+ });
@@ -13,6 +13,8 @@ import { Button, Input, Label, Textarea } from '@startsimpli/ui';
13
13
  import type { CommsApi } from '../api/comms';
14
14
  import { DEFAULT_POLL_MS, useCreateDraft, useDraft } from '../hooks/index';
15
15
  import type { CommsAsset } from '../types/index';
16
+
17
+ type EmailContentInput = { subject: string; html: string; preheader?: string; text?: string };
16
18
  import { DraftReview } from './DraftReview';
17
19
  import { ImageLibrary } from './ImageLibrary';
18
20
  import { ErrorNotice, Note, humanize, useFieldId } from './_shared';
@@ -24,6 +26,24 @@ export interface AnnouncementComposerProps {
24
26
 
25
27
  type Mode = 'write' | 'notes';
26
28
 
29
+ /** An email file in the composer's own JSON format: {subject, preheader?, html, text?}. */
30
+ function parseEmailFile(raw: string): { input?: EmailContentInput; error?: string } {
31
+ let data: unknown;
32
+ try {
33
+ data = JSON.parse(raw);
34
+ } catch {
35
+ return { error: 'That file is not valid JSON.' };
36
+ }
37
+ const o = (data && typeof data === 'object' ? data : {}) as Record<string, unknown>;
38
+ const str = (k: string) => (typeof o[k] === 'string' ? (o[k] as string) : undefined);
39
+ const subject = str('subject');
40
+ const html = str('html');
41
+ if (!subject?.trim() || !html?.trim()) return { error: 'That file needs a subject and html to be an email.' };
42
+ const preheader = str('preheader');
43
+ const text = str('text');
44
+ return { input: { subject, html, ...(preheader !== undefined ? { preheader } : {}), ...(text !== undefined ? { text } : {}) } };
45
+ }
46
+
27
47
  const escapeHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
28
48
 
29
49
  const IMAGE = /!\[([^\]]*)\]\((https?:\/\/[^\s)]+)\)/g;
@@ -87,6 +107,7 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
87
107
  const [following, setFollowing] = useState<string | null>(null);
88
108
  const [status, setStatus] = useState<string | null>(null);
89
109
  const [failure, setFailure] = useState<string | null>(null);
110
+ const [loadedId, setLoadedId] = useState<string | null>(null);
90
111
 
91
112
  const onFinished = useCallback((error: string | null) => {
92
113
  setFollowing(null);
@@ -97,6 +118,20 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
97
118
  const insertImage = (a: CommsAsset) =>
98
119
  setMessage((m) => `${m.trimEnd()}${m.trim() ? '\n\n' : ''}![${a.alt}](${a.url})`);
99
120
 
121
+ const loadFile = async (file: File | undefined) => {
122
+ if (!file) return;
123
+ setStatus(null);
124
+ setFailure(null);
125
+ const { input, error } = parseEmailFile(await file.text());
126
+ if (!input) return setFailure(error ?? 'That file could not be read.');
127
+ create.mutate(input, {
128
+ onSuccess: (d) => {
129
+ setLoadedId(d.id);
130
+ setStatus(`Loaded "${file.name}" as a draft. It opens in the email viewer; nothing is sent until you approve it.`);
131
+ },
132
+ });
133
+ };
134
+
100
135
  const canSave = mode === 'write' ? !!subject.trim() && !!message.trim() : !!notes.trim();
101
136
 
102
137
  const submit = () => {
@@ -180,6 +215,21 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
180
215
  </div>
181
216
  )}
182
217
 
218
+ <div className="space-y-1">
219
+ <Label htmlFor={`${ids}-file`}>Load an email from a file (.json)</Label>
220
+ <input
221
+ id={`${ids}-file`}
222
+ type="file"
223
+ accept=".json,application/json"
224
+ className="block text-sm"
225
+ onChange={(e) => {
226
+ void loadFile(e.target.files?.[0]);
227
+ e.target.value = '';
228
+ }}
229
+ />
230
+ <Note>{'A file with {"subject", "preheader", "html", "text"}. The file becomes a draft and opens in the email viewer.'}</Note>
231
+ </div>
232
+
183
233
  <Button type="submit" disabled={!canSave || create.isPending || !!following}>
184
234
  {mode === 'write' ? 'Save as draft' : 'Write a draft from my notes'}
185
235
  </Button>
@@ -190,7 +240,7 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
190
240
  ) : null}
191
241
  {status ? <Note>{status}</Note> : null}
192
242
  <ErrorNotice error={create.error ?? (failure ? new Error(failure) : null)} />
193
- <DraftReview api={api} pollIntervalMs={pollIntervalMs} />
243
+ <DraftReview api={api} pollIntervalMs={pollIntervalMs} openId={loadedId} />
194
244
  </div>
195
245
  );
196
246
  }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The foundry's default time zone (bd startsim-ofio9.4): the zone used for
3
+ * recipients whose own zone is not known when a send is timed per recipient.
4
+ * Blank means UTC. PATCH settings.default_timezone.
5
+ */
6
+ import { useState, type ReactElement } from 'react';
7
+ import { Button, Label } from '@startsimpli/ui';
8
+
9
+ import type { CommsApi } from '../api/comms';
10
+ import { useCommsSettings, useUpdateCommsSettings } from '../hooks/index';
11
+ import { ErrorNotice, NativeSelect, Note, timeZoneOptions, useFieldId } from './_shared';
12
+
13
+ export interface DefaultTimeZoneSettingProps {
14
+ api: CommsApi;
15
+ }
16
+
17
+ function Form({ api, current }: { api: CommsApi; current: string }) {
18
+ const update = useUpdateCommsSettings(api);
19
+ const id = useFieldId('comms-default-zone');
20
+ const [zone, setZone] = useState(current);
21
+ const [saved, setSaved] = useState(false);
22
+ const options = Array.from(new Set([...(current ? [current] : []), ...timeZoneOptions()]));
23
+ return (
24
+ <form
25
+ className="space-y-3"
26
+ onSubmit={(e) => {
27
+ e.preventDefault();
28
+ setSaved(false);
29
+ update.mutate({ default_timezone: zone }, { onSuccess: () => setSaved(true) });
30
+ }}
31
+ >
32
+ <div className="space-y-1">
33
+ <Label htmlFor={id}>Default time zone</Label>
34
+ <div>
35
+ <NativeSelect
36
+ id={id}
37
+ value={zone}
38
+ onChange={(e) => {
39
+ setSaved(false);
40
+ setZone(e.target.value);
41
+ }}
42
+ >
43
+ <option value="">Not set (UTC)</option>
44
+ {options.map((z) => (
45
+ <option key={z} value={z}>{z}</option>
46
+ ))}
47
+ </NativeSelect>
48
+ </div>
49
+ <p className="text-sm text-muted-foreground">
50
+ Used for recipients whose own time zone is not known, when an email goes out at the same local time for
51
+ everyone. Without one, those recipients get UTC.
52
+ </p>
53
+ </div>
54
+ <div className="flex items-center gap-3">
55
+ <Button type="submit" disabled={update.isPending}>Save time zone</Button>
56
+ {saved ? <Note>Saved.</Note> : null}
57
+ </div>
58
+ <ErrorNotice error={update.error} />
59
+ </form>
60
+ );
61
+ }
62
+
63
+ export function DefaultTimeZoneSetting({ api }: DefaultTimeZoneSettingProps): ReactElement | null {
64
+ const { data: settings } = useCommsSettings(api);
65
+ if (!settings) return null;
66
+ return <Form api={api} current={settings.default_timezone ?? ''} />;
67
+ }
@@ -15,14 +15,13 @@ import {
15
15
  useApproveDraft,
16
16
  useDiscardDraft,
17
17
  useRetryDraft,
18
- useDraftPreview,
19
18
  useDrafts,
20
19
  useSendTest,
21
20
  useUpdateDraft,
22
21
  } from '../hooks/index';
23
22
  import type { Draft, DraftAction, DraftPatch } from '../types/index';
24
23
  import { AudiencePanel } from './AudiencePanel';
25
- import { EmailPreview } from './EmailPreview';
24
+ import { PreviewAsInbox } from './EmailPreviewPage';
26
25
  import { SchedulePicker } from './SchedulePicker';
27
26
  import { ScheduledSends } from './ScheduledSends';
28
27
  import { ErrorNotice, Note, formatDate, formatDateTime, humanize, useFieldId } from './_shared';
@@ -32,6 +31,8 @@ export interface DraftReviewProps {
32
31
  pollIntervalMs?: number;
33
32
  /** Drafts per server page. Default 10. */
34
33
  pageSize?: number;
34
+ /** A draft whose inbox viewer opens by itself (the one just loaded from a file). */
35
+ openId?: string | null;
35
36
  }
36
37
 
37
38
  function DraftEditor({ api, draft, onDone }: { api: CommsApi; draft: Draft; onDone: () => void }) {
@@ -92,17 +93,18 @@ export function DraftItem({
92
93
  api,
93
94
  draft,
94
95
  onSentImmediately,
96
+ startPreviewing = false,
95
97
  }: {
96
98
  api: CommsApi;
97
99
  draft: Draft;
98
100
  onSentImmediately?: (draft: Draft) => void;
101
+ /** Open the inbox viewer straight away (a draft just loaded from a file). */
102
+ startPreviewing?: boolean;
99
103
  }) {
100
104
  const [editing, setEditing] = useState(false);
101
- const [previewing, setPreviewing] = useState(false);
102
105
  const [auditing, setAuditing] = useState(false);
103
106
  const [scheduling, setScheduling] = useState(false);
104
107
  const ready = !draft.generating && !draft.error;
105
- const preview = useDraftPreview(api, draft.id, previewing && ready);
106
108
  const sendTest = useSendTest(api);
107
109
  const approve = useApproveDraft(api);
108
110
  const discard = useDiscardDraft(api);
@@ -123,7 +125,7 @@ export function DraftItem({
123
125
  <div className="flex flex-wrap gap-2">
124
126
  {ready ? (
125
127
  <>
126
- <Button type="button" size="sm" variant="outline" onClick={() => setPreviewing((v) => !v)}>Preview</Button>
128
+ <PreviewAsInbox api={api} source={{ kind: 'draft', id: draft.id }} label="Preview as inbox" autoOpen={startPreviewing} />
127
129
  {allowed(draft, 'edit') ? (
128
130
  <>
129
131
  <Button type="button" size="sm" variant="outline" onClick={() => setEditing((v) => !v)}>Edit</Button>
@@ -184,12 +186,13 @@ export function DraftItem({
184
186
  : draft.notice.reason}
185
187
  </Note>
186
188
  ) : null}
187
- <ErrorNotice error={sendTest.error ?? approve.error ?? discard.error ?? retry.error ?? preview.error} />
189
+ <ErrorNotice error={sendTest.error ?? approve.error ?? discard.error ?? retry.error} />
188
190
  {editing && ready ? <DraftEditor api={api} draft={draft} onDone={() => setEditing(false)} /> : null}
189
191
  {auditing && ready ? <AudiencePanel api={api} draftId={draft.id} /> : null}
190
- {previewing && preview.data ? <EmailPreview email={preview.data} /> : null}
191
192
  {scheduling && ready ? (
192
193
  <SchedulePicker
194
+ api={api}
195
+ draftId={draft.id}
193
196
  submitLabel="Approve and schedule"
194
197
  pending={approve.isPending}
195
198
  onCancel={() => setScheduling(false)}
@@ -223,7 +226,7 @@ function NeedsAttention({ api, pollIntervalMs, onSentImmediately }: {
223
226
  );
224
227
  }
225
228
 
226
- export function DraftReview({ api, pollIntervalMs = DEFAULT_POLL_MS, pageSize = 10 }: DraftReviewProps): ReactElement | null {
229
+ export function DraftReview({ api, pollIntervalMs = DEFAULT_POLL_MS, pageSize = 10, openId = null }: DraftReviewProps): ReactElement | null {
227
230
  const [page, setPage] = useState(1);
228
231
  const [justSent, setJustSent] = useState<Draft | null>(null);
229
232
  const drafts = useDrafts(api, { status: 'pending', page, page_size: pageSize }, pollIntervalMs);
@@ -255,7 +258,7 @@ export function DraftReview({ api, pollIntervalMs = DEFAULT_POLL_MS, pageSize =
255
258
  <h3 className="text-sm font-medium">Waiting for approval</h3>
256
259
  <ul className="divide-y">
257
260
  {results.map((d) => (
258
- <DraftItem key={d.id} api={api} draft={d} onSentImmediately={setJustSent} />
261
+ <DraftItem key={d.id} api={api} draft={d} onSentImmediately={setJustSent} startPreviewing={d.id === openId} />
259
262
  ))}
260
263
  </ul>
261
264
  {count > pageSize ? (