File size: 21,869 Bytes
15a4294
1643ce8
 
 
 
 
 
 
 
 
15a4294
1643ce8
 
15a4294
1643ce8
 
 
 
 
 
 
 
 
 
 
15a4294
 
1643ce8
 
 
 
41178f4
1643ce8
15a4294
 
1643ce8
 
 
 
 
 
 
 
 
 
 
 
15a4294
74b1b27
15a4294
 
1643ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
41178f4
 
 
 
1643ce8
 
 
 
41178f4
 
 
1643ce8
41178f4
1643ce8
15a4294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74b1b27
 
 
 
15a4294
74b1b27
15a4294
 
 
 
 
 
 
 
 
 
1643ce8
41178f4
 
1643ce8
41178f4
 
 
 
 
1643ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15a4294
1643ce8
15a4294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1643ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41178f4
1643ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41178f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1643ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15a4294
1643ce8
15a4294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1643ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import { useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import {
  CheckCircle,
  Image as ImageIcon,
  FileText,
  Table,
  CheckSquare,
  Square,
  ArrowRight,
  UploadCloud,
} from "react-feather";

import { postForm, putJson, request } from "../lib/api";
import { getSessionId, setStoredSessionId } from "../lib/session";
import type { Session } from "../types/session";
import { PageFooter } from "../components/PageFooter";
import { PageHeader } from "../components/PageHeader";
import { PageShell } from "../components/PageShell";

export default function ReviewSetupPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const sessionId = getSessionId(searchParams.toString());

  const photoUploadRef = useRef<HTMLInputElement | null>(null);
  const dataUploadRef = useRef<HTMLInputElement | null>(null);
  const [session, setSession] = useState<Session | null>(null);
  const [selectedPhotoIds, setSelectedPhotoIds] = useState<Set<string>>(
    new Set(),
  );
  const [showAllPhotos, setShowAllPhotos] = useState(false);
  const [statusMessage, setStatusMessage] = useState("");
  const [isUploadingPhotos, setIsUploadingPhotos] = useState(false);
  const [isUploadingData, setIsUploadingData] = useState(false);

  useEffect(() => {
    if (!sessionId) {
      setStatusMessage("No active session found. Return to upload to continue.");
      return;
    }
    setStoredSessionId(sessionId);
    async function loadSession() {
      try {
        const data = await request<Session>(`/sessions/${sessionId}`);
        setSession(data);
        const initial = new Set(data.selected_photo_ids || []);
        const photoIds = (data.uploads?.photos ?? []).map((photo) => photo.id);
        if (photoIds.length > 0 && initial.size < photoIds.length) {
          photoIds.forEach((photoId) => initial.add(photoId));
        }
        setSelectedPhotoIds(initial);
      } catch (err) {
        const message =
          err instanceof Error ? err.message : "Failed to load session.";
        setStatusMessage(message);
      }
    }
    loadSession();
  }, [sessionId]);

  const photos = session?.uploads?.photos ?? [];
  const documents = session?.uploads?.documents ?? [];
  const dataFiles = session?.uploads?.data_files ?? [];

  const canContinue =
    selectedPhotoIds.size > 0 || (session?.uploads?.data_files?.length ?? 0) > 0;
  const previewCount = 9;
  const visiblePhotos = showAllPhotos ? photos : photos.slice(0, previewCount);

  const readyStatus = useMemo(() => {
    if (!sessionId) return "No active session found. Return to upload to continue.";
    if (!canContinue) return "Choose report example images to continue...";
    if (selectedPhotoIds.size === 0 && (session?.uploads?.data_files?.length ?? 0) > 0) {
      return "Data file detected. Continue to build the report.";
    }
    return "Ready. Continue to report viewer.";
  }, [canContinue, selectedPhotoIds.size, session?.uploads?.data_files?.length, sessionId]);

  async function handleUploadPhotos(files: FileList | null) {
    if (!sessionId || !files || files.length === 0) return;
    setIsUploadingPhotos(true);
    setStatusMessage("");
    const priorPhotoIds = new Set(
      (session?.uploads?.photos ?? []).map((photo) => photo.id),
    );
    try {
      let updatedSession: Session | null = session;
      for (const file of Array.from(files)) {
        const formData = new FormData();
        formData.append("file", file);
        updatedSession = await postForm<Session>(
          `/sessions/${sessionId}/uploads`,
          formData,
        );
      }
      if (updatedSession) {
        setSession(updatedSession);
        const next = new Set(selectedPhotoIds);
        for (const photo of updatedSession.uploads?.photos ?? []) {
          if (!priorPhotoIds.has(photo.id)) {
            next.add(photo.id);
          }
        }
        setSelectedPhotoIds(next);
      }
    } catch (err) {
      const message =
        err instanceof Error ? err.message : "Failed to upload photos.";
      setStatusMessage(message);
    } finally {
      setIsUploadingPhotos(false);
      if (photoUploadRef.current) photoUploadRef.current.value = "";
    }
  }

  async function handleUploadDataFile(files: FileList | null) {
    if (!sessionId || !files || files.length === 0) return;
    setIsUploadingData(true);
    setStatusMessage("");
    try {
      const file = files[0];
      const formData = new FormData();
      formData.append("file", file);
      const updated = await postForm<Session>(
        `/sessions/${sessionId}/data-files`,
        formData,
      );
      setSession(updated);
      const nextSelected = new Set(updated.selected_photo_ids || []);
      const allPhotoIds = (updated.uploads?.photos ?? []).map((photo) => photo.id);
      if (nextSelected.size < allPhotoIds.length) {
        allPhotoIds.forEach((photoId) => nextSelected.add(photoId));
      }
      setSelectedPhotoIds(nextSelected);
    } catch (err) {
      const message =
        err instanceof Error ? err.message : "Failed to upload data file.";
      setStatusMessage(message);
    } finally {
      setIsUploadingData(false);
      if (dataUploadRef.current) dataUploadRef.current.value = "";
    }
  }

  async function handleContinue() {
    if (!sessionId) return;
    if (selectedPhotoIds.size === 0 && dataFiles.length === 0) return;
    try {
      if (selectedPhotoIds.size > 0) {
        await putJson(`/sessions/${sessionId}/selection`, {
          selected_photo_ids: Array.from(selectedPhotoIds),
        });
      }
      navigate(`/report-viewer?session=${encodeURIComponent(sessionId)}`);
    } catch (err) {
      const message =
        err instanceof Error ? err.message : "Failed to save selection.";
      setStatusMessage(message);
    }
  }

  return (
    <PageShell>
      <PageHeader
        title="RepEx - Report Express"
        subtitle="Review uploads -> pick examples -> continue to report viewer"
        right={
          <span className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-xs font-semibold text-gray-700">
            <CheckCircle className="h-4 w-4" />
            Uploads processed
          </span>
        }
      />

      <section className="mb-8" aria-labelledby="what-next">
        <h2
          id="what-next"
          className="text-xl font-semibold text-gray-800 border-b border-gray-200 pb-2 mb-4"
        >
          What happens on this page
        </h2>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
            <div className="inline-flex h-10 w-10 items-center justify-center rounded-full bg-blue-50 border border-blue-100 mb-3">
              <ImageIcon className="h-5 w-5 text-blue-700" />
            </div>
            <h3 className="font-semibold text-gray-900 mb-1">
              Select example photos
            </h3>
            <p className="text-sm text-gray-600">
              Choose which uploaded images should appear as example figures in the report.
            </p>
          </div>

          <div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
            <div className="inline-flex h-10 w-10 items-center justify-center rounded-full bg-emerald-50 border border-emerald-100 mb-3">
              <FileText className="h-5 w-5 text-emerald-700" />
            </div>
            <h3 className="font-semibold text-gray-900 mb-1">Confirm documents</h3>
            <p className="text-sm text-gray-600">
              Ensure supporting PDFs/DOCX are correct (and later attach to export if needed).
            </p>
          </div>

          <div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
            <div className="inline-flex h-10 w-10 items-center justify-center rounded-full bg-amber-50 border border-amber-100 mb-3">
              <Table className="h-5 w-5 text-amber-700" />
            </div>
            <h3 className="font-semibold text-gray-900 mb-1">Use Excel/CSV data</h3>
            <p className="text-sm text-gray-600">
              If Excel/CSV exists, it will populate report data areas automatically in later steps.
            </p>
          </div>
        </div>
      </section>

      <section className="mb-8" aria-labelledby="review-uploads">
        <h2
          id="review-uploads"
          className="text-xl font-semibold text-gray-800 border-b border-gray-200 pb-2 mb-6"
        >
          Review uploaded files
        </h2>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2">
            <div className="flex flex-wrap items-center justify-between gap-3 mb-3">
              <h3 className="text-lg font-semibold text-gray-900">Photos</h3>
              <div className="flex flex-wrap items-center gap-2">
                <span className="text-sm font-semibold text-gray-600">
                  {photos.length} file{photos.length === 1 ? "" : "s"}
                </span>
                <button
                  type="button"
                  onClick={() => photoUploadRef.current?.click()}
                  disabled={!sessionId || isUploadingPhotos}
                  className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-xs font-semibold text-gray-800 hover:bg-gray-50 transition disabled:opacity-50"
                >
                  <UploadCloud className="h-4 w-4" />
                  {isUploadingPhotos ? "Uploading..." : "Add photos"}
                </button>
                <input
                  ref={photoUploadRef}
                  type="file"
                  className="hidden"
                  multiple
                  accept=".jpg,.jpeg,.png,.webp"
                  onChange={(event) => handleUploadPhotos(event.target.files)}
                />
              </div>
            </div>

            <div className="rounded-lg border border-gray-200 bg-white p-4">
              <p className="text-sm text-gray-600 mb-3">
                Select images to use as example figures in the report.{" "}
                <span className="font-semibold text-gray-800">Recommended:</span>{" "}
                2-6 images.
              </p>

              <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                {photos.length === 0 ? (
                  <div className="col-span-full text-sm text-gray-500">
                    No photos were uploaded.
                  </div>
                ) : (
                  visiblePhotos.map((photo) => {
                    const isChecked = selectedPhotoIds.has(photo.id);
                    return (
                      <label key={photo.id} className="cursor-pointer">
                        <input
                          type="checkbox"
                          className="sr-only"
                          checked={isChecked}
                          onChange={(event) => {
                            const next = new Set(selectedPhotoIds);
                            if (event.target.checked) {
                              next.add(photo.id);
                            } else {
                              next.delete(photo.id);
                            }
                            setSelectedPhotoIds(next);
                          }}
                        />
                        <div
                          className={[
                            "rounded-lg border bg-gray-50 overflow-hidden transition",
                            isChecked
                              ? "ring-2 ring-emerald-200 border-emerald-300"
                              : "border-gray-200",
                          ].join(" ")}
                        >
                          <div className="relative">
                            <img
                              src={photo.url}
                              alt={photo.name}
                              className="h-28 w-full object-cover"
                              loading="eager"
                            />
                            <div
                              className={[
                                "absolute top-2 right-2 inline-flex items-center justify-center rounded-full border p-1.5",
                                isChecked
                                  ? "bg-emerald-50 border-emerald-200 text-emerald-700"
                                  : "bg-white/90 border-gray-200 text-gray-700",
                              ].join(" ")}
                            >
                              <CheckCircle className="h-4 w-4" />
                            </div>
                          </div>
                          <div className="p-2">
                            <div className="text-xs font-semibold text-gray-900 truncate">
                              {photo.name}
                            </div>
                            <div className="text-xs text-gray-500">
                              Click to select for report
                            </div>
                          </div>
                        </div>
                      </label>
                    );
                  })
                )}
              </div>

              {photos.length > previewCount ? (
                <div className="mt-3 flex items-center justify-between gap-3 text-sm text-gray-600">
                  <span>
                    Showing {visiblePhotos.length} of {photos.length} photos
                  </span>
                  <button
                    type="button"
                    onClick={() => setShowAllPhotos((prev) => !prev)}
                    className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"
                  >
                    {showAllPhotos ? "Show fewer" : `Show all (${photos.length})`}
                  </button>
                </div>
              ) : null}

              <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
                <div className="text-sm text-gray-600">
                  Selected for report:{" "}
                  <span className="font-semibold text-gray-900">
                    {selectedPhotoIds.size}
                  </span>
                </div>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => {
                      setSelectedPhotoIds(new Set(photos.map((p) => p.id)));
                    }}
                    className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"
                  >
                    <CheckSquare className="h-4 w-4" />
                    Select all
                  </button>
                  <button
                    type="button"
                    onClick={() => setSelectedPhotoIds(new Set())}
                    className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"
                  >
                    <Square className="h-4 w-4" />
                    Clear
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div className="space-y-6">
            <div>
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-lg font-semibold text-gray-900">Documents</h3>
                <span className="text-sm font-semibold text-gray-600">
                  {documents.length} file{documents.length === 1 ? "" : "s"}
                </span>
              </div>

              <div className="rounded-lg border border-gray-200 bg-white p-4">
                <ul className="space-y-2 text-sm text-gray-700">
                  {documents.length === 0 ? (
                    <li className="text-sm text-gray-500">
                      No supporting documents detected.
                    </li>
                  ) : (
                    documents.map((doc) => (
                      <li
                        key={doc.id}
                        className="flex items-center justify-between gap-3 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2"
                      >
                        <div className="flex items-center gap-2 min-w-0">
                          <FileText className="h-4 w-4 text-gray-600" />
                          <span className="truncate text-gray-800">{doc.name}</span>
                        </div>
                        <span className="text-xs font-semibold text-gray-600">
                          {doc.content_type || "File"}
                        </span>
                      </li>
                    ))
                  )}
                </ul>
                {documents.length === 0 ? (
                  <p className="text-xs text-gray-500 mt-3">
                    PDFs/DOCX appear here after processing.
                  </p>
                ) : null}
              </div>
            </div>

            <div>
              <div className="flex flex-wrap items-center justify-between gap-3 mb-3">
                <h3 className="text-lg font-semibold text-gray-900">Data files</h3>
                <div className="flex flex-wrap items-center gap-2">
                  <span className="text-sm font-semibold text-gray-600">
                    {dataFiles.length} file{dataFiles.length === 1 ? "" : "s"}
                  </span>
                  <button
                    type="button"
                    onClick={() => dataUploadRef.current?.click()}
                    disabled={!sessionId || isUploadingData}
                    className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-xs font-semibold text-gray-800 hover:bg-gray-50 transition disabled:opacity-50"
                  >
                    <UploadCloud className="h-4 w-4" />
                    {isUploadingData ? "Uploading..." : "Upload data file"}
                  </button>
                  <input
                    ref={dataUploadRef}
                    type="file"
                    className="hidden"
                    accept=".csv,.xls,.xlsx"
                    onChange={(event) => handleUploadDataFile(event.target.files)}
                  />
                </div>
              </div>

              <div className="rounded-lg border border-gray-200 bg-white p-4">
                {dataFiles.length === 0 ? (
                  <div className="rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm text-gray-600">
                    <div className="font-semibold text-gray-800 mb-1">
                      No Excel/CSV detected
                    </div>
                    If you upload a CSV or Excel file, RepEx can auto-populate report data fields.
                  </div>
                ) : (
                  dataFiles.map((file) => (
                    <div
                      key={file.id}
                      className="rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm text-gray-700 mb-2 last:mb-0"
                    >
                      <div className="flex items-center justify-between gap-3">
                        <div className="flex items-center gap-2 min-w-0">
                          <Table className="h-4 w-4 text-amber-700" />
                          <span className="truncate font-semibold text-gray-900">
                            {file.name}
                          </span>
                        </div>
                        <span className="text-xs font-semibold text-gray-600">
                          {file.content_type || "Data"}
                        </span>
                      </div>
                      <div className="text-xs text-gray-600 mt-1">
                        Will populate report data areas (tables/fields).
                      </div>
                    </div>
                  ))
                )}
                <p className="text-xs text-gray-500 mt-3">
                  If present, these files will populate report tables/fields automatically.
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="mb-4" aria-label="Continue to report viewer">
        <div className="rounded-lg border border-gray-200 bg-gray-50 p-4 flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between">
          <div
            className={[
              "text-sm",
              canContinue ? "text-emerald-700 font-semibold" : "text-amber-700 font-semibold",
            ].join(" ")}
          >
            {readyStatus}
          </div>

          <button
            type="button"
            onClick={handleContinue}
            disabled={!canContinue}
            className="inline-flex items-center justify-center gap-2 rounded-lg bg-emerald-600 px-5 py-2.5 text-white font-semibold hover:bg-emerald-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <ArrowRight className="h-5 w-5" />
            Continue to Report Viewer
          </button>
        </div>

        <p className="text-xs text-gray-500 mt-3">
          Note: This page assumes uploads were completed on a previous processing step.
        </p>
      </section>

      {statusMessage ? (
        <p className="text-sm text-red-600">{statusMessage}</p>
      ) : null}

      <PageFooter note="Workflow: Processing -> Review uploads -> Report viewer -> Edit -> Export" />
    </PageShell>
  );
}