Spaces:
Sleeping
Sleeping
Commit ·
ed33547
1
Parent(s): bcb6323
Multi-Image Web Fixed
Browse filesFiles changed (19)
- frontend/src/App.tsx+2
- frontend/src/components/InfoMenu.tsxAdded+46
- frontend/src/components/JobSheetTemplate.tsx+139-18
- frontend/src/components/ReportPageCanvas.tsx+18-21
- frontend/src/components/report-editor.js+309-57
- frontend/src/index.css+4
- frontend/src/lib/sections.tsAdded+165
- frontend/src/pages/EditLayoutsPage.tsx+200-102
- frontend/src/pages/EditReportPage.tsx+20-12
- frontend/src/pages/ExportPage.tsx+39-23
- frontend/src/pages/InputDataPage.tsx+316-135
- frontend/src/pages/RatingsInfoPage.tsxAdded+294
- frontend/src/pages/ReportViewerPage.tsx+24-11
- frontend/src/types/session.ts+13
- server/app/api/routes/sessions.py+38-1
- server/app/api/schemas.py+15
- server/app/services/data_import.py+7-7
- server/app/services/pdf_reportlab.py+7-2
- server/app/services/session_store.py+68-13
7 unmodified lines89101112137 unmodified lines2122232425267 unmodified linesimport EditReportPage from "./pages/EditReportPage";import EditLayoutsPage from "./pages/EditLayoutsPage";import ExportPage from "./pages/ExportPage";export default function App() {return (7 unmodified lines<Route path="/edit-report" element={<EditReportPage />} /><Route path="/edit-layouts" element={<EditLayoutsPage />} /><Route path="/export" element={<ExportPage />} /><Route path="*" element={<Navigate to="/" replace />} /></Routes></BrowserRouter>7 unmodified lines8910111213147 unmodified lines222324252627287 unmodified linesimport EditReportPage from "./pages/EditReportPage";import EditLayoutsPage from "./pages/EditLayoutsPage";import ExportPage from "./pages/ExportPage";import RatingsInfoPage from "./pages/RatingsInfoPage";export default function App() {return (7 unmodified lines<Route path="/edit-report" element={<EditReportPage />} /><Route path="/edit-layouts" element={<EditLayoutsPage />} /><Route path="/export" element={<ExportPage />} /><Route path="/info/ratings" element={<RatingsInfoPage />} /><Route path="*" element={<Navigate to="/" replace />} /></Routes></BrowserRouter>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import { Info } from "react-feather";import { Link } from "react-router-dom";
type InfoMenuProps = { sessionQuery?: string;};
export function InfoMenu({ sessionQuery = "" }: InfoMenuProps) { const ratingsLink = `/info/ratings${sessionQuery}`; return ( <details className="relative no-print"> <summary className="list-none"> <span 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 cursor-pointer"> <Info className="h-4 w-4" /> Info </span> </summary> <div className="absolute right-0 mt-2 w-80 rounded-lg border border-gray-200 bg-white shadow-lg p-3 z-20"> <div className="text-xs font-semibold text-gray-900 mb-2"> RepEx quick guidance </div> <ul className="space-y-2 text-xs text-gray-600"> <li> Workflow: Upload → Review → Input Data → Report Viewer → Edit → Export. </li> <li> Edit Report is for free‑form layout changes; Input Data updates the structured fields. </li> <li> Category and Priority values use the defined rating scales. </li> <li> <Link to={ratingsLink} className="text-blue-600 hover:text-blue-700 underline" > View rating scale tables </Link> </li> </ul> </div> </details> );}10 unmodified lines1112131415168 unmodified lines252627282930101 unmodified lines13213313413513613713813914014114214314414511 unmodified lines15715815916016116220 unmodified lines18318418518618718834 unmodified lines22322422522622722822923023123256 unmodified lines2892902912922932942952961 unmodified line29829930030130230330430524 unmodified lines3303313323333343353363373383393403413423433443453463473483493503513523535 unmodified lines35936036136236336410 unmodified linesphotos?: FileMeta[];orderLocked?: boolean;variant?: "full" | "photos";};type PhotoSlotProps = {8 unmodified linesspan: boolean;};function normalizeKey(value: string) {return value.toLowerCase().replace(/[^a-z0-9]/g, "");}101 unmodified linesreturn (<figureclassName={["rounded-lg border border-gray-200 bg-gray-50 p-2 break-inside-avoid mb-3",className,].join(" ")}><imgsrc={url}alt={label}className={["w-full h-auto object-contain", imageClassName].join(" ")}loading="eager"/><figcaption className="mt-1 text-[10px] text-gray-600 text-center">11 unmodified linesphotos,orderLocked = false,variant = "full",}: JobSheetTemplateProps) {const inspectionDate =template?.inspection_date ?? session?.inspection_date ?? "";20 unmodified linesconst actionText = [actionType, requiredAction].filter((value) => value && value.trim()).join(" - ");const resolvedPhotos =photos && photos.length ? photos : getPhotosForPage(session, pageIndex, 1);34 unmodified linesreturn layout.map((entry) => entry.photo);}, [limitedPhotos, ratios, orderLocked]);const photoColumnsClass = orderedPhotos.length <= 1 ? "columns-1" : "columns-2";return (<div className="w-full h-full p-5 text-[11px] text-gray-700"><header className="mb-3 border-b border-gray-200 pb-2"><div className="grid grid-cols-[auto,1fr,auto] items-center gap-3"><img56 unmodified lines<div className="text-[10px] font-medium text-gray-500">Category</div><span className="template-field inline-flex items-center justify-center rounded-md border border-gray-200 px-4 py-1 text-[11px] font-semibold text-gray-900 min-w-[96px]">{category}</span></div>1 unmodified line<div className="text-[10px] font-medium text-gray-500">Priority</div><span className="template-field inline-flex items-center justify-center rounded-md border border-gray-200 px-4 py-1 text-[11px] font-semibold text-gray-900 min-w-[96px]">{priority}</span></div></div>24 unmodified lines</section>) : null}<section className="mb-3 avoid-break"><div className="text-[11px] font-semibold text-gray-800 border-b border-gray-200 pb-1 mb-2">{variant === "photos" ? "Photo Documentation (continued)" : "Photo Documentation"}</div><divclassName={`${photoColumnsClass}`}style={{ columnGap: "0.75rem" }}>{orderedPhotos.length === 0 ? (<PhotoSlot url={undefined} label="No photo selected" className="break-inside-avoid mb-3" />) : (orderedPhotos.map((photo, index) => (<PhotoSlotkey={photo?.id || `${index}`}url={photo?.url}label={photo?.name || `Figure ${index + 1}`}className="break-inside-avoid mb-3"imageClassName=""/>)))}5 unmodified lines<span>Inspector: {inspector || "-"}</span><span>Doc: {docNumber || "-"}</span><span>Site: {clientSite || "-"}</span></footer></div>);10 unmodified lines111213141516178 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134101 unmodified lines23623723823924024124224324424524624724824911 unmodified lines26126226326426526626720 unmodified lines28828929029129229329429534 unmodified lines33033133233333433533633733833934034134234334434556 unmodified lines4024034044054064074084094104114124134141 unmodified line41641741841942042142242342442542642742824 unmodified lines4534544554564574584594604614624634644654664674684694704714724735 unmodified lines47948048148248348448510 unmodified linesphotos?: FileMeta[];orderLocked?: boolean;variant?: "full" | "photos";sectionLabel?: string;};type PhotoSlotProps = {8 unmodified linesspan: boolean;};type RatingTone = {label: string;bg: string;text: string;border: string;};const CATEGORY_SCALE: Record<string, RatingTone> = {"0": {label: "Excellent",bg: "bg-green-100",text: "text-green-800",border: "border-green-200",},"1": {label: "Good",bg: "bg-green-200",text: "text-green-800",border: "border-green-200",},"2": {label: "Fair",bg: "bg-yellow-100",text: "text-yellow-800",border: "border-yellow-200",},"3": {label: "Poor",bg: "bg-yellow-200",text: "text-yellow-800",border: "border-yellow-200",},"4": {label: "Worse",bg: "bg-orange-200",text: "text-orange-800",border: "border-orange-200",},"5": {label: "Severe",bg: "bg-red-200",text: "text-red-800",border: "border-red-200",},};const PRIORITY_SCALE: Record<string, RatingTone> = {"1": {label: "Immediate",bg: "bg-red-200",text: "text-red-800",border: "border-red-200",},"2": {label: "1 Year",bg: "bg-orange-200",text: "text-orange-800",border: "border-orange-200",},"3": {label: "3 Years",bg: "bg-green-200",text: "text-green-800",border: "border-green-200",},X: {label: "At Use",bg: "bg-purple-200",text: "text-purple-800",border: "border-purple-200",},M: {label: "Monitor",bg: "bg-blue-200",text: "text-blue-800",border: "border-blue-200",},};function ratingKey(value: string) {const raw = (value || "").trim();if (!raw) return "";const match = raw.match(/^([0-9]|[xXmM])/);if (match) return match[1].toUpperCase();return raw.split("-")[0].trim().toUpperCase();}function formatRating(value: string, scale: Record<string, RatingTone>) {const raw = (value || "").trim();const key = ratingKey(raw);const tone = key ? scale[key] : undefined;if (!tone) {return {text: raw || "-",className: "bg-gray-50 text-gray-700 border-gray-200",};}return {text: `${key} - ${tone.label}`,className: `${tone.bg} ${tone.text} ${tone.border}`,};}function normalizeKey(value: string) {return value.toLowerCase().replace(/[^a-z0-9]/g, "");}101 unmodified linesreturn (<figureclassName={["rounded-lg border border-gray-200 bg-gray-50 p-2 break-inside-avoid",className,].join(" ")}><imgsrc={url}alt={label}className={["w-full h-full object-contain", imageClassName].join(" ")}loading="eager"/><figcaption className="mt-1 text-[10px] text-gray-600 text-center">11 unmodified linesphotos,orderLocked = false,variant = "full",sectionLabel,}: JobSheetTemplateProps) {const inspectionDate =template?.inspection_date ?? session?.inspection_date ?? "";20 unmodified linesconst actionText = [actionType, requiredAction].filter((value) => value && value.trim()).join(" - ");const categoryBadge = formatRating(category, CATEGORY_SCALE);const priorityBadge = formatRating(priority, PRIORITY_SCALE);const resolvedPhotos =photos && photos.length ? photos : getPhotosForPage(session, pageIndex, 1);34 unmodified linesreturn layout.map((entry) => entry.photo);}, [limitedPhotos, ratios, orderLocked]);const displayedPhotos =variant === "full" ? orderedPhotos.slice(0, 2) : orderedPhotos;const photoGridClass =displayedPhotos.length <= 1? "grid grid-cols-1 gap-3": "grid grid-cols-2 gap-3";return (<div className="w-full h-full p-5 text-[11px] text-gray-700 flex flex-col"><header className="mb-3 border-b border-gray-200 pb-2"><div className="grid grid-cols-[auto,1fr,auto] items-center gap-3"><img56 unmodified lines<div className="text-[10px] font-medium text-gray-500">Category</div><spanclassName={["template-field inline-flex items-center justify-center rounded-md border px-4 py-1 text-[11px] font-semibold min-w-[120px]",categoryBadge.className,].join(" ")}>{categoryBadge.text}</span></div>1 unmodified line<div className="text-[10px] font-medium text-gray-500">Priority</div><spanclassName={["template-field inline-flex items-center justify-center rounded-md border px-4 py-1 text-[11px] font-semibold min-w-[120px]",priorityBadge.className,].join(" ")}>{priorityBadge.text}</span></div></div>24 unmodified lines</section>) : null}<section className="mb-3 avoid-break flex-1 min-h-0 flex flex-col"><div className="text-[11px] font-semibold text-gray-800 border-b border-gray-200 pb-1 mb-2">{variant === "photos" ? "Photo Documentation (continued)" : "Photo Documentation"}</div><div className={`${photoGridClass} flex-1 items-stretch`}>{displayedPhotos.length === 0 ? (<PhotoSlot url={undefined} label="No photo selected" className="h-full" />) : (displayedPhotos.map((photo, index) => (<PhotoSlotkey={photo?.id || `${index}`}url={photo?.url}label={photo?.name || `Figure ${index + 1}`}className="h-full"imageClassName="h-full"/>)))}5 unmodified lines<span>Inspector: {inspector || "-"}</span><span>Doc: {docNumber || "-"}</span><span>Site: {clientSite || "-"}</span>{sectionLabel ? <span>{sectionLabel}</span> : null}</footer></div>);
11 unmodified lines1213141516175 unmodified lines23242526272829303132333435363774 unmodified lines11211311411511611711811912012112212312412512664 unmodified lines19119219319419519619719819920020120220320420511 unmodified linespageCount: number;scale: number;template?: TemplateFields;className?: string;adaptive?: boolean;};5 unmodified linespageCount,scale,template,className = "",adaptive = false,}: ReportPageCanvasProps) {const items = page?.items ?? [];const safeScale = Number.isFinite(scale) && scale > 0 ? scale : 1;const photos = resolvePagePhotos(session, page, pageIndex);const photosPerSheet = 6;const photoSheets = chunkPhotos(photos, photosPerSheet);const sheets = adaptive && photoSheets.length > 1 ? photoSheets : [photos];const sheetRefs = useRef<Array<HTMLDivElement | null>>([]);const [sheetHeights, setSheetHeights] = useState<number[]>([]);74 unmodified linestransformOrigin: "top left",}}><JobSheetTemplatesession={session}pageIndex={pageIndex}pageCount={pageCount}template={template}photos={sheetPhotos}orderLocked={page?.photo_order_locked ?? false}variant={sheetIndex === 0 ? "full" : "photos"}/></div></div>))}64 unmodified lines);}function chunkPhotos(photos: FileMeta[], perSheet: number) {if (!photos.length) return [[]];const slices: FileMeta[][] = [];for (let i = 0; i < photos.length; i += perSheet) {slices.push(photos.slice(i, i + perSheet));}return slices;}function resolvePagePhotos(session: Session | null,page: Page | null | undefined,11 unmodified lines121314151617185 unmodified lines24252627282930313233343536373874 unmodified lines11311411511611711811912012112212312412512612712812913013113264 unmodified lines19719819920020120211 unmodified linespageCount: number;scale: number;template?: TemplateFields;sectionLabel?: string;className?: string;adaptive?: boolean;};5 unmodified linespageCount,scale,template,sectionLabel,className = "",adaptive = false,}: ReportPageCanvasProps) {const items = page?.items ?? [];const safeScale = Number.isFinite(scale) && scale > 0 ? scale : 1;const pageVariant = page?.variant ?? "full";const photos = resolvePagePhotos(session, page, pageIndex);const sheets = adaptive ? [photos] : [photos];const sheetRefs = useRef<Array<HTMLDivElement | null>>([]);const [sheetHeights, setSheetHeights] = useState<number[]>([]);74 unmodified linestransformOrigin: "top left",}}>{page?.blank ? (<div className="w-full h-full bg-white" />) : (<JobSheetTemplatesession={session}pageIndex={pageIndex}pageCount={pageCount}template={template}photos={sheetPhotos}orderLocked={page?.photo_order_locked ?? false}variant={pageVariant}sectionLabel={sectionLabel}/>)}</div></div>))}64 unmodified lines);}function resolvePagePhotos(session: Session | null,page: Page | null | undefined,
12 unmodified lines131415161718197 unmodified lines27282930313237 unmodified lines70717273747576777879808115 unmodified lines979899100101102103104105106643 unmodified lines75075175275375475515 unmodified lines77177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981021 unmodified lines83283383483583683783883984084184284319 unmodified lines8638648658668678688698708718726 unmodified lines8798808818828838842 unmodified lines8878888898908918928938948957 unmodified lines90390490590690790890911 unmodified lines92192292392492592692792892993093111 unmodified lines94394494594694794894995095195211 unmodified lines9649659669679689699709719729739748 unmodified lines98398498598698798898925 unmodified lines101510161017101810191020102110224 unmodified lines10271028102910301031103210338 unmodified lines1042104310441045104610471048104918 unmodified lines10681069107010711072107310741075107610771078107910801081108210831 unmodified line108510861087108810891090109112 unmodified linesisOpen: false,zoom: 1,activePage: 0,pages: [], // [{ items: [...] }]selectedId: null,tool: "select", // select | text | rectdragging: null, // { id, startX, startY, origX, origY }7 unmodified linesthis.apiBase = null;this._saveTimer = null;this._photoRatios = new Map();}connectedCallback() {37 unmodified linesconst initialCount = Math.max(Number(totalPages) || 1, 1);// Load existing editor pages from storage, else initializeconst stored = this._loadPages();if (stored && Array.isArray(stored.pages) && stored.pages.length) {this.state.pages = stored.pages;} else {this.state.pages = Array.from({ length: initialCount }, () => ({ items: [] }));this._savePages();}this._ensurePageCount(initialCount);15 unmodified linessetTimeout(() => this.updateAll(), 0);if (this.sessionId) {this._loadPagesFromServer().then((pages) => {if (pages && pages.length) {this.state.pages = pages;this._ensurePageCount(Math.max(initialCount, pages.length));this.state.activePage = Math.min(Math.max(0, pageIndex),this.state.pages.length - 1643 unmodified lines_templateMarkup() {const session = this.state.payload || {};const template = this._getTemplate();const inspectionDate =template.inspection_date || session.inspection_date || "";15 unmodified linestemplate.condition_description || session.notes || "";const requiredAction = template.required_action || "";const photos = this._photosForActivePage(session).slice(0, 6);this._ensurePhotoRatios(photos);const orderLocked = !!(this.activePage && this.activePage.photo_order_locked);const orderedPhotos = orderLocked? photos: this._computePhotoLayout(photos).map((entry) => entry.photo);const photoColumnsClass = orderedPhotos.length <= 1 ? "columns-1" : "columns-2";const photoSlots = orderedPhotos.length? orderedPhotos.map((photo, idx) => this._photoSlot(photo, `Figure ${idx + 1}`)).join(""): this._photoSlot(null, "No photo selected");const pageNum = this.state.activePage + 1;const pageCount = this.state.pages.length || 1;return `<div class="w-full h-full p-5 text-[11px] text-gray-700" style="color:#374151; font-size:11px;"><header class="mb-3 border-b border-gray-200 pb-2"><div class="grid grid-cols-[auto,1fr,auto] items-center gap-3"><div class="flex items-center"><img src="/assets/prosento-logo.png" alt="Prosento logo" class="h-10 w-auto object-contain" /></div><div class="text-center leading-tight"><h1 class="text-2xl font-bold text-gray-900 whitespace-nowrap">RepEx Inspection Job Sheet</h1><p class="text-sm text-gray-600 whitespace-nowrap">Report Express - Inspection Management</p></div><div class="flex items-center justify-end"><img src="${this._escape(this._resolveLogoUrl(session, companyLogo))}" alt="Company logo" class="h-10 w-auto object-contain" /></div></div></header><section class="mb-4" aria-labelledby="observations-title"><h2 id="observations-title" class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-1 mb-2">Observations and Findings21 unmodified lines<div class="inline-flex items-center gap-10"><div class="text-center space-y-1"><div class="text-xs font-medium text-gray-500">Category</div>${this._tplField("category", category, "Category", "inline-flex items-center justify-center rounded-md border border-gray-200 px-4 py-1 text-sm font-semibold text-gray-900 min-w-[96px]")}</div><div class="text-center space-y-1"><div class="text-xs font-medium text-gray-500">Priority</div>${this._tplField("priority", priority, "Priority", "inline-flex items-center justify-center rounded-md border border-gray-200 px-4 py-1 text-sm font-semibold text-gray-900 min-w-[96px]")}</div></div></div>19 unmodified lines</div></div></section><section class="mb-4 avoid-break" aria-labelledby="photo-doc-title"><h2 id="photo-doc-title" class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-1 mb-2">Photo Documentation</h2><div class="${photoColumnsClass}" style="column-gap:0.75rem;">6 unmodified lines<span>Inspector: ${this._escape(inspector || "-")}</span><span>Doc: ${this._escape(docNumber || "-")}</span><span>Site: ${this._escape(clientSite || "-")}</span></footer></div>`;2 unmodified lines// ---------- Storage ----------_storageKey() {if (this.sessionId) {return `repex_report_pages_v1_${this.sessionId}`;}return "repex_report_pages_v1";}_loadPages() {7 unmodified lines_savePages(showToast = false) {try {localStorage.setItem(this._storageKey(), JSON.stringify({ pages: this.state.pages }));this._scheduleServerSave();if (showToast) this._toast("Saved");} catch {11 unmodified linesconst base = this._apiRoot();if (!base || !this.sessionId) return null;try {const res = await fetch(`${base}/sessions/${this.sessionId}/pages`);if (!res.ok) return null;const data = await res.json();if (data && Array.isArray(data.pages)) {return data.pages;}} catch {}return null;11 unmodified linesconst base = this._apiRoot();if (!base || !this.sessionId) return;try {const res = await fetch(`${base}/sessions/${this.sessionId}/pages`, {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ pages: this.state.pages }),});if (!res.ok) {throw new Error("Failed");11 unmodified linessetTimeout(() => el.remove(), 1200);}// ---------- Page list ----------renderPageList() {this.$pageList.innerHTML = "";this.state.pages.forEach((_, idx) => {const active = idx === this.state.activePage;const row = document.createElement("div");8 unmodified lines: "border-gray-200 bg-white text-gray-800 hover:bg-gray-50");btn.innerHTML = `<div class="flex items-center justify-between"><div class="text-sm font-semibold">Page ${idx + 1}</div><div class="text-xs ${active ? "text-white/80" : "text-gray-500"}">${this.state.pages[idx].items.length} items</div></div>`;25 unmodified linesaddPage() {this._pushUndoSnapshot();this.state.pages.push({ items: [] });this.state.activePage = this.state.pages.length - 1;this.state.selectedId = null;this._savePages();this.updateAll();4 unmodified linesconst idx = typeof index === "number" ? index : this.state.activePage;if (idx < 0 || idx >= this.state.pages.length) return;this.state.pages.splice(idx, 1);if (this.state.activePage >= this.state.pages.length) {this.state.activePage = this.state.pages.length - 1;} else if (this.state.activePage > idx) {8 unmodified lines_ensurePageCount(count) {const target = Math.max(Number(count) || 1, 1);while (this.state.pages.length < target) {this.state.pages.push({ items: [] });}}18 unmodified linesconst template = document.createElement("div");template.className = "absolute inset-0";let templateHtml = "";try {templateHtml = this._templateMarkup();} catch (err) {console.error("Template render failed", err);templateHtml = `<div class="p-4 text-sm text-red-600">Template failed to render. Check console for details.</div>`;}template.innerHTML = `<div style="width:${this.BASE_W}px; height:${this.BASE_H}px; transform: scale(${scale}); transform-origin: top left;">1 unmodified line</div>`;this.$canvas.appendChild(template);this._bindTemplateFields();const items = this.activePage.items;const selectedId = this.state.selectedId;12 unmodified lines13141516171819207 unmodified lines2829303132333437 unmodified lines7273747576777879808182838485868788899091929315 unmodified lines109110111112113114115116117118643 unmodified lines76276376476576676776815 unmodified lines78478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882921 unmodified lines85185285385485585685785885986086186286386486586686786886987087187219 unmodified lines8928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259266 unmodified lines9339349359369379389392 unmodified lines9429439449459469479489499507 unmodified lines95895996096196296396496596696796811 unmodified lines98098198298398498598698798898999011 unmodified lines1002100310041005100610071008100910101011101211 unmodified lines10241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211838 unmodified lines119211931194119511961197119811991200120125 unmodified lines122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112524 unmodified lines125712581259126012611262126312641265126612671268126912708 unmodified lines127912801281128212831284128512861287128812891290129112921293129418 unmodified lines1313131413151316131713181319132013211322132313241325132613271328132913301331133213331 unmodified line13351336133713381339134013411342134312 unmodified linesisOpen: false,zoom: 1,activePage: 0,pages: [], // flattened pagessections: [], // [{ id, title?, pages: [...] }]selectedId: null,tool: "select", // select | text | rectdragging: null, // { id, startX, startY, origX, origY }7 unmodified linesthis.apiBase = null;this._saveTimer = null;this._photoRatios = new Map();this._indexMap = [];}connectedCallback() {37 unmodified linesconst initialCount = Math.max(Number(totalPages) || 1, 1);// Load existing editor sections from storage, else initializeconst stored = this._loadPages();if (stored && Array.isArray(stored.sections) && stored.sections.length) {this._setSections(stored.sections);} else if (stored && Array.isArray(stored.pages) && stored.pages.length) {this._setSections([{ id: this._sectionId(), title: "Section 1", pages: stored.pages },]);} else {this._setSections([{id: this._sectionId(),title: "Section 1",pages: Array.from({ length: initialCount }, () => ({ items: [] })),},]);this._savePages();}this._ensurePageCount(initialCount);15 unmodified linessetTimeout(() => this.updateAll(), 0);if (this.sessionId) {this._loadPagesFromServer().then((sections) => {if (sections && sections.length) {this._setSections(sections);this._ensurePageCount(Math.max(initialCount, this.state.pages.length));this.state.activePage = Math.min(Math.max(0, pageIndex),this.state.pages.length - 1643 unmodified lines_templateMarkup() {const session = this.state.payload || {};const template = this._getTemplate();const sectionLabel = this._getActiveSectionLabel();const inspectionDate =template.inspection_date || session.inspection_date || "";15 unmodified linestemplate.condition_description || session.notes || "";const requiredAction = template.required_action || "";const categoryScale = {"0": { label: "Excellent", bg: "bg-green-100", text: "text-green-800", border: "border-green-200" },"1": { label: "Good", bg: "bg-green-200", text: "text-green-800", border: "border-green-200" },"2": { label: "Fair", bg: "bg-yellow-100", text: "text-yellow-800", border: "border-yellow-200" },"3": { label: "Poor", bg: "bg-yellow-200", text: "text-yellow-800", border: "border-yellow-200" },"4": { label: "Worse", bg: "bg-orange-200", text: "text-orange-800", border: "border-orange-200" },"5": { label: "Severe", bg: "bg-red-200", text: "text-red-800", border: "border-red-200" },};const priorityScale = {"1": { label: "Immediate", bg: "bg-red-200", text: "text-red-800", border: "border-red-200" },"2": { label: "1 Year", bg: "bg-orange-200", text: "text-orange-800", border: "border-orange-200" },"3": { label: "3 Years", bg: "bg-green-200", text: "text-green-800", border: "border-green-200" },X: { label: "At Use", bg: "bg-purple-200", text: "text-purple-800", border: "border-purple-200" },M: { label: "Monitor", bg: "bg-blue-200", text: "text-blue-800", border: "border-blue-200" },};const categoryBadge = this._ratingBadge(category, categoryScale);const priorityBadge = this._ratingBadge(priority, priorityScale);const variant =(this.activePage && this.activePage.variant) || "full";const photos = this._photosForActivePage(session).slice(0, 6);this._ensurePhotoRatios(photos);const orderLocked = !!(this.activePage && this.activePage.photo_order_locked);const orderedPhotos = orderLocked? photos: this._computePhotoLayout(photos).map((entry) => entry.photo);const displayedPhotos =variant === "full" ? orderedPhotos.slice(0, 2) : orderedPhotos;const photoColumnsClass = displayedPhotos.length <= 1 ? "columns-1" : "columns-2";const photoSlots = displayedPhotos.length? displayedPhotos.map((photo, idx) => this._photoSlot(photo, `Figure ${idx + 1}`)).join(""): this._photoSlot(null, "No photo selected");const pageNum = this.state.activePage + 1;const pageCount = this.state.pages.length || 1;const observationsHtml =variant === "full"? `<section class="mb-4" aria-labelledby="observations-title"><h2 id="observations-title" class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-1 mb-2">Observations and Findings21 unmodified lines<div class="inline-flex items-center gap-10"><div class="text-center space-y-1"><div class="text-xs font-medium text-gray-500">Category</div>${this._tplField("category",categoryBadge.text,"Category",`inline-flex items-center justify-center rounded-md border px-4 py-1 text-sm font-semibold min-w-[120px] ${categoryBadge.className}`,)}</div><div class="text-center space-y-1"><div class="text-xs font-medium text-gray-500">Priority</div>${this._tplField("priority",priorityBadge.text,"Priority",`inline-flex items-center justify-center rounded-md border px-4 py-1 text-sm font-semibold min-w-[120px] ${priorityBadge.className}`,)}</div></div></div>19 unmodified lines</div></div></section>`: "";const photoTitle =variant === "photos" ? "Photo Documentation (continued)" : "Photo Documentation";return `<div class="w-full h-full p-5 text-[11px] text-gray-700" style="color:#374151; font-size:11px;"><header class="mb-3 border-b border-gray-200 pb-2"><div class="grid grid-cols-[auto,1fr,auto] items-center gap-3"><div class="flex items-center"><img src="/assets/prosento-logo.png" alt="Prosento logo" class="h-10 w-auto object-contain" /></div><div class="text-center leading-tight"><h1 class="text-2xl font-bold text-gray-900 whitespace-nowrap">RepEx Inspection Job Sheet</h1><p class="text-sm text-gray-600 whitespace-nowrap">Report Express - Inspection Management</p></div><div class="flex items-center justify-end"><img src="${this._escape(this._resolveLogoUrl(session, companyLogo))}" alt="Company logo" class="h-10 w-auto object-contain" /></div></div></header>${observationsHtml}<section class="mb-4 avoid-break" aria-labelledby="photo-doc-title"><h2 id="photo-doc-title" class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-1 mb-2">${photoTitle}</h2><div class="${photoColumnsClass}" style="column-gap:0.75rem;">6 unmodified lines<span>Inspector: ${this._escape(inspector || "-")}</span><span>Doc: ${this._escape(docNumber || "-")}</span><span>Site: ${this._escape(clientSite || "-")}</span>${sectionLabel ? `<span>${this._escape(sectionLabel)}</span>` : ""}</footer></div>`;2 unmodified lines// ---------- Storage ----------_storageKey() {if (this.sessionId) {return `repex_report_sections_v1_${this.sessionId}`;}return "repex_report_sections_v1";}_loadPages() {7 unmodified lines_savePages(showToast = false) {try {this._syncSectionsFromPages();localStorage.setItem(this._storageKey(),JSON.stringify({ sections: this.state.sections }),);this._scheduleServerSave();if (showToast) this._toast("Saved");} catch {11 unmodified linesconst base = this._apiRoot();if (!base || !this.sessionId) return null;try {const res = await fetch(`${base}/sessions/${this.sessionId}/sections`);if (!res.ok) return null;const data = await res.json();if (data && Array.isArray(data.sections)) {return data.sections;}} catch {}return null;11 unmodified linesconst base = this._apiRoot();if (!base || !this.sessionId) return;try {this._syncSectionsFromPages();const res = await fetch(`${base}/sessions/${this.sessionId}/sections`, {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ sections: this.state.sections }),});if (!res.ok) {throw new Error("Failed");11 unmodified linessetTimeout(() => el.remove(), 1200);}_sectionId() {return `sec_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`;}_ratingBadge(value, scale) {const raw = String(value || "").trim();if (!raw) {return { text: "-", className: "bg-gray-50 text-gray-700 border-gray-200" };}const match = raw.match(/^([0-9]|[xXmM])/);const key = match ? match[1].toUpperCase() : raw.split("-")[0].trim().toUpperCase();const tone = scale[key];if (!tone) {return { text: raw, className: "bg-gray-50 text-gray-700 border-gray-200" };}return {text: `${key} - ${tone.label}`,className: `${tone.bg} ${tone.text} ${tone.border}`,};}_buildPhotoContinuation(source, photoIds) {return {items: [],template: source.template ? { ...source.template } : undefined,photo_ids: photoIds,photo_order_locked: source.photo_order_locked,variant: "photos",};}_splitPagePhotos(page) {const normalized = {...page,items: Array.isArray(page.items) ? page.items : [],};if (normalized.blank) return [normalized];const photoIds = Array.isArray(normalized.photo_ids)? normalized.photo_ids.filter(Boolean): [];if (!photoIds.length) return [normalized];const chunks = [];for (let i = 0; i < photoIds.length; i += 2) {chunks.push(photoIds.slice(i, i + 2));}if (chunks.length <= 1) {return [{ ...normalized, photo_ids: chunks[0] || [], variant: normalized.variant }];}if (normalized.variant === "photos") {return chunks.map((chunk, idx) => {if (idx === 0) {return { ...normalized, photo_ids: chunk, variant: "photos" };}return this._buildPhotoContinuation(normalized, chunk);});}const basePage = {...normalized,photo_ids: chunks[0],variant: normalized.variant || "full",};const extraPages = chunks.slice(1).map((chunk) =>this._buildPhotoContinuation(normalized, chunk),);return [basePage, ...extraPages];}_normalizeSections(sections) {const source = Array.isArray(sections) ? sections : [];if (!source.length) {return [{ id: this._sectionId(), title: "Section 1", pages: [{ items: [] }] }];}return source.map((section) => {const basePages =Array.isArray(section.pages) && section.pages.length? section.pages: [{ items: [] }];const normalizedPages = basePages.flatMap((page) => this._splitPagePhotos(page));return {id: section.id || this._sectionId(),title: section.title ?? "Section",pages: normalizedPages.length ? normalizedPages : [{ items: [] }],};});}_rebuildFlatPages() {this._indexMap = [];this.state.pages = [];const sections = Array.isArray(this.state.sections) ? this.state.sections : [];sections.forEach((section, sectionIndex) => {const pages = Array.isArray(section.pages) && section.pages.length? section.pages: [{ items: [] }];section.pages = pages;pages.forEach((page, pageIndex) => {this.state.pages.push(page);this._indexMap.push({ sectionIndex, pageIndex });});});if (!this.state.pages.length) {this.state.sections = [{ id: this._sectionId(), title: "Section 1", pages: [{ items: [] }] },];this._rebuildFlatPages();}}_setSections(sections) {this.state.sections = this._normalizeSections(sections);this._rebuildFlatPages();}_syncSectionsFromPages() {if (!this._indexMap || this._indexMap.length !== this.state.pages.length) {this._rebuildFlatPages();}const sections = this.state.sections.map((section) => ({...section,pages: Array.isArray(section.pages) ? [...section.pages] : [{ items: [] }],}));this.state.pages.forEach((page, idx) => {const map = this._indexMap[idx];if (!map) return;if (!sections[map.sectionIndex]) return;sections[map.sectionIndex].pages[map.pageIndex] = page;});this.state.sections = sections;}_getActiveSectionLabel() {const map = this._indexMap?.[this.state.activePage];if (!map || !this.state.sections?.[map.sectionIndex]) return "";const section = this.state.sections[map.sectionIndex] || {};const title = section.title || "";if (title) return `Section ${map.sectionIndex + 1} - ${title}`;return `Section ${map.sectionIndex + 1}`;}// ---------- Page list ----------renderPageList() {this.$pageList.innerHTML = "";this.state.pages.forEach((_, idx) => {const map = this._indexMap?.[idx] || { sectionIndex: 0, pageIndex: idx };const section =(this.state.sections && this.state.sections[map.sectionIndex]) || {};const sectionLabel =section.title || `Section ${map.sectionIndex + 1}`;const active = idx === this.state.activePage;const row = document.createElement("div");8 unmodified lines: "border-gray-200 bg-white text-gray-800 hover:bg-gray-50");btn.innerHTML = `<div class="flex items-center justify-between"><div><div class="text-[11px] ${active ? "text-white/80" : "text-gray-500"}">${sectionLabel}</div><div class="text-sm font-semibold">Page ${map.pageIndex + 1}</div></div><div class="text-xs ${active ? "text-white/80" : "text-gray-500"}">${this.state.pages[idx].items.length} items</div></div>`;25 unmodified linesaddPage() {this._pushUndoSnapshot();const map = this._indexMap?.[this.state.activePage] || {sectionIndex: 0,pageIndex: this.state.activePage,};if (!this.state.sections[map.sectionIndex]) {this.state.sections = [{ id: this._sectionId(), title: "Section 1", pages: [{ items: [] }] },];}const section = this.state.sections[map.sectionIndex];section.pages = section.pages || [];section.pages.splice(map.pageIndex + 1, 0, { items: [] });this._setSections(this.state.sections);const newIndex = this._indexMap.findIndex((entry) =>entry.sectionIndex === map.sectionIndex &&entry.pageIndex === map.pageIndex + 1);this.state.activePage =newIndex >= 0 ? newIndex : this.state.pages.length - 1;this.state.selectedId = null;this._savePages();this.updateAll();4 unmodified linesconst idx = typeof index === "number" ? index : this.state.activePage;if (idx < 0 || idx >= this.state.pages.length) return;const map = this._indexMap?.[idx];if (!map || !this.state.sections[map.sectionIndex]) return;const section = this.state.sections[map.sectionIndex];const pages = section.pages || [];if (pages.length <= 1) return;pages.splice(map.pageIndex, 1);section.pages = pages.length ? pages : [{ items: [] }];this._setSections(this.state.sections);if (this.state.activePage >= this.state.pages.length) {this.state.activePage = this.state.pages.length - 1;} else if (this.state.activePage > idx) {8 unmodified lines_ensurePageCount(count) {const target = Math.max(Number(count) || 1, 1);if (!this.state.sections || !this.state.sections.length) {this.state.sections = [{ id: this._sectionId(), title: "Section 1", pages: [{ items: [] }] },];}while (this.state.pages.length < target) {const lastSection = this.state.sections[this.state.sections.length - 1];lastSection.pages = lastSection.pages || [];lastSection.pages.push({ items: [] });this._setSections(this.state.sections);}}18 unmodified linesconst template = document.createElement("div");template.className = "absolute inset-0";const active = this.activePage || {};let templateHtml = "";if (active.blank) {templateHtml = `<div class="w-full h-full bg-white"></div>`;} else {try {templateHtml = this._templateMarkup();} catch (err) {console.error("Template render failed", err);templateHtml = `<div class="p-4 text-sm text-red-600">Template failed to render. Check console for details.</div>`;}}template.innerHTML = `<div style="width:${this.BASE_W}px; height:${this.BASE_H}px; transform: scale(${scale}); transform-origin: top left;">1 unmodified line</div>`;this.$canvas.appendChild(template);if (!active.blank) {this._bindTemplateFields();}const items = this.activePage.items;const selectedId = this.state.selectedId;
66 unmodified lines67686970717266 unmodified linesbox-shadow: none;}@media print {@page {size: A4;66 unmodified lines6768697071727374757666 unmodified linesbox-shadow: none;}summary::-webkit-details-marker {display: none;}@media print {@page {size: A4;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165import type { JobsheetSection, Page } from "../types/session";
export type FlatPage = { sectionId: string; sectionIndex: number; sectionTitle?: string; pageIndex: number; page: Page; flatIndex: number;};
const MAX_PHOTOS_PER_PAGE = 2;
function cloneTemplate(template?: Page["template"]): Page["template"] { if (!template) return undefined; return { ...template };}
function normalizePhotoIds(photoIds?: string[]): string[] { if (!Array.isArray(photoIds)) return []; return photoIds.filter((value) => Boolean(value));}
function buildPhotoContinuation(source: Page, photoIds: string[]): Page { return { items: [], template: cloneTemplate(source.template), photo_ids: photoIds, photo_order_locked: source.photo_order_locked, variant: "photos", };}
function splitPagePhotos(page: Page): Page[] { const items = Array.isArray(page.items) ? page.items : []; const normalized: Page = { ...page, items };
if (normalized.blank) { return [normalized]; }
const photoIds = normalizePhotoIds(normalized.photo_ids); if (!photoIds.length) { return [normalized]; }
const chunks: string[][] = []; for (let i = 0; i < photoIds.length; i += MAX_PHOTOS_PER_PAGE) { chunks.push(photoIds.slice(i, i + MAX_PHOTOS_PER_PAGE)); }
if (chunks.length <= 1) { return [ { ...normalized, photo_ids: chunks[0] ?? [], variant: normalized.variant, }, ]; }
if (normalized.variant === "photos") { return chunks.map((chunk, idx) => { if (idx === 0) { return { ...normalized, photo_ids: chunk, variant: "photos" }; } return buildPhotoContinuation(normalized, chunk); }); }
const basePage: Page = { ...normalized, photo_ids: chunks[0], variant: normalized.variant ?? "full", }; const extraPages = chunks.slice(1).map((chunk) => buildPhotoContinuation(normalized, chunk), ); return [basePage, ...extraPages];}
export function ensureSections(sections?: JobsheetSection[]): JobsheetSection[] { if (sections && sections.length) { return sections.map((section, index) => { const basePages = section.pages?.length ? section.pages : [{ items: [] }]; const normalizedPages = basePages.flatMap((page) => splitPagePhotos(page)); return { id: section.id, title: section.title ?? "Section", pages: normalizedPages.length ? normalizedPages : [{ items: [] }], }; }); } return [ { id: crypto.randomUUID(), title: "Section 1", pages: [{ items: [] }], }, ];}
export function flattenSections(sections: JobsheetSection[]): FlatPage[] { const result: FlatPage[] = []; sections.forEach((section, sectionIndex) => { const pages = section.pages ?? []; pages.forEach((page, pageIndex) => { result.push({ sectionId: section.id, sectionIndex, sectionTitle: section.title ?? `Section ${sectionIndex + 1}`, pageIndex, page, flatIndex: result.length, }); }); }); return result;}
export function replacePage( sections: JobsheetSection[], sectionIndex: number, pageIndex: number, nextPage: Page,): JobsheetSection[] { const next = sections.map((section, sIdx) => { if (sIdx !== sectionIndex) return section; const nextPages = [...(section.pages ?? [])]; nextPages[pageIndex] = nextPage; return { ...section, pages: nextPages }; }); return ensureSections(next);}
export function insertPage( sections: JobsheetSection[], sectionIndex: number, pageIndex: number, page: Page,): JobsheetSection[] { const next = sections.map((section, sIdx) => { if (sIdx !== sectionIndex) return section; const nextPages = [...(section.pages ?? [])]; const safeIndex = Math.max(0, Math.min(pageIndex, nextPages.length)); nextPages.splice(safeIndex, 0, page); return { ...section, pages: nextPages }; }); return ensureSections(next);}
export function removePage( sections: JobsheetSection[], sectionIndex: number, pageIndex: number,): JobsheetSection[] { const next = sections.map((section, sIdx) => { if (sIdx !== sectionIndex) return section; const nextPages = [...(section.pages ?? [])]; if (nextPages.length <= 1) return section; nextPages.splice(pageIndex, 1); return { ...section, pages: nextPages.length ? nextPages : [{ items: [] }] }; }); return ensureSections(next);}14 unmodified lines15161718192021222324252 unmodified lines282930313233348 unmodified lines43444546474849505152533 unmodified lines57585960616263646566676869707172737475767778798081828384858687888990913 unmodified lines95969798991001011021031047 unmodified lines1121131141151161171181191201211221231241254 unmodified lines13013113213313413513613713813914010 unmodified lines15115215315415515615715815916016116216346 unmodified lines21021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728814 unmodified linesimport { putJson, request } from "../lib/api";import { BASE_W } from "../lib/report";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { Page, Session } from "../types/session";import { PageFooter } from "../components/PageFooter";import { PageHeader } from "../components/PageHeader";import { PageShell } from "../components/PageShell";import { ReportPageCanvas } from "../components/ReportPageCanvas";export default function EditLayoutsPage() {2 unmodified linesconst sessionQuery = buildSessionQuery(sessionId);const [session, setSession] = useState<Session | null>(null);const [pages, setPages] = useState<Page[]>([]);const [status, setStatus] = useState("");const [isSaving, setIsSaving] = useState(false);const canModify = Boolean(sessionId) && !isSaving;8 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const pageResp = await request<{ pages: Page[] }>(`/sessions/${sessionId}/pages`,);const loaded = Array.isArray(pageResp.pages) ? pageResp.pages : [];setPages(loaded.length ? loaded : [{ items: [] }]);} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";3 unmodified linesload();}, [sessionId]);const totalPages = useMemo(() => Math.max(1, pages.length), [pages.length]);const previewWidth = 220;const previewScale = previewWidth / BASE_W;function hasExplicitPhotos(source: Page[]) {return source.some((page) => (page.photo_ids ?? []).length > 0);}function flattenPhotoIds(source: Page[]) {const seen = new Set<string>();const result: string[] = [];source.forEach((page) => {(page.photo_ids ?? []).forEach((photoId) => {if (!seen.has(photoId)) {seen.add(photoId);result.push(photoId);}});});return result;}async function saveLayout(next: Page[], nextSelectedIds?: string[]) {if (!sessionId) return;setIsSaving(true);setStatus("Saving layout changes...");try {const requests: Promise<unknown>[] = [putJson<{ pages: Page[] }>(`/sessions/${sessionId}/pages`, { pages: next }),];if (nextSelectedIds !== undefined) {requests.push(3 unmodified lines);}const [pagesResp, sessionResp] = await Promise.all(requests);const updatedPages = (pagesResp as { pages?: Page[] }).pages ?? next;const updatedSession = sessionResp as Session | undefined;const updated = Array.isArray(updatedPages) ? updatedPages : next;setPages(updated.length ? updated : [{ items: [] }]);if (updatedSession) {setSession(updatedSession);}7 unmodified lines}}async function handleAddPage() {const next = [...pages, { items: [] }];await saveLayout(next);}async function handleRemovePage(index: number) {if (pages.length <= 1) return;const next = pages.filter((_, idx) => idx !== index);if (session) {const nextSelected = hasExplicitPhotos(next)? flattenPhotoIds(next)4 unmodified linesawait saveLayout(next);}async function handleMovePage(index: number, direction: number) {const target = index + direction;if (target < 0 || target >= pages.length) return;const next = [...pages];[next[index], next[target]] = [next[target], next[index]];if (session) {const nextSelected = hasExplicitPhotos(next)? flattenPhotoIds(next)10 unmodified linestitle="RepEx - Report Express"subtitle="Edit Page Layouts"right={<Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"><ArrowLeft className="h-4 w-4" />Back</Link>}/>46 unmodified linesAdd, remove, or reorder pages, then return to the report viewer to edit content.</p></div><buttontype="button"onClick={handleAddPage}disabled={!canModify}className="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 transition disabled:opacity-50 disabled:cursor-not-allowed"><Plus className="h-4 w-4" />Add page</button></div>{status ? (<p className="text-sm text-gray-600 mt-3">{status}</p>) : null}</section><section className="grid grid-cols-1 md:grid-cols-2 gap-4">{pages.map((page, index) => (<divkey={`page-${index + 1}`}className="rounded-lg border border-gray-200 bg-white p-3"><div className="flex items-center justify-between mb-2"><div><div className="text-sm font-semibold text-gray-900">Page {index + 1}</div><div className="text-xs text-gray-500">{page.items?.length ?? 0} items</div></div><div className="flex items-center gap-2"><buttontype="button"onClick={() => handleMovePage(index, -1)}disabled={index === 0 || !canModify}className="inline-flex items-center justify-center rounded-lg border border-gray-200 bg-white p-1.5 text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"aria-label="Move page up"><ChevronUp className="h-3.5 w-3.5" /></button><buttontype="button"onClick={() => handleMovePage(index, 1)}disabled={index === pages.length - 1 || !canModify}className="inline-flex items-center justify-center rounded-lg border border-gray-200 bg-white p-1.5 text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"aria-label="Move page down"><ChevronDown className="h-3.5 w-3.5" /></button><buttontype="button"onClick={() => handleRemovePage(index)}disabled={pages.length <= 1 || !canModify}className="inline-flex items-center gap-1 rounded-lg border border-red-200 bg-red-50 px-2.5 py-1.5 text-xs font-semibold text-red-700 hover:bg-red-100 transition disabled:opacity-50 disabled:cursor-not-allowed"><Trash2 className="h-3.5 w-3.5" />Remove</button></div></div><divclassName="mx-auto overflow-hidden rounded-lg border border-gray-200 bg-white"style={{ width: previewWidth, aspectRatio: "210 / 297" }}><ReportPageCanvassession={session}page={page}pageIndex={index}pageCount={totalPages}scale={previewScale}template={page?.template}/></div></div>))}14 unmodified lines151617181920212223242526272 unmodified lines303132333435368 unmodified lines454647484950515253543 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051063 unmodified lines1101111121131141151161171181191207 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701714 unmodified lines17617717817918018118218318418518618718818919010 unmodified lines20120220320420520620720820921021121221321421521646 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538614 unmodified linesimport { putJson, request } from "../lib/api";import { BASE_W } from "../lib/report";import { ensureSections, flattenSections } from "../lib/sections";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { JobsheetSection, Session } from "../types/session";import { PageFooter } from "../components/PageFooter";import { PageHeader } from "../components/PageHeader";import { PageShell } from "../components/PageShell";import { InfoMenu } from "../components/InfoMenu";import { ReportPageCanvas } from "../components/ReportPageCanvas";export default function EditLayoutsPage() {2 unmodified linesconst sessionQuery = buildSessionQuery(sessionId);const [session, setSession] = useState<Session | null>(null);const [sections, setSections] = useState<JobsheetSection[]>([]);const [status, setStatus] = useState("");const [isSaving, setIsSaving] = useState(false);const canModify = Boolean(sessionId) && !isSaving;8 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const sectionResp = await request<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,);setSections(ensureSections(sectionResp.sections));} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";3 unmodified linesload();}, [sessionId]);const flatPages = useMemo(() => flattenSections(ensureSections(sections)),[sections],);const totalPages = useMemo(() => Math.max(1, flatPages.length),[flatPages.length],);const previewWidth = 220;const previewScale = previewWidth / BASE_W;function hasExplicitPhotos(source: JobsheetSection[]) {return source.some((section) =>(section.pages ?? []).some((page) => (page.photo_ids ?? []).length > 0),);}function flattenPhotoIds(source: JobsheetSection[]) {const seen = new Set<string>();const result: string[] = [];source.forEach((section) => {(section.pages ?? []).forEach((page) => {(page.photo_ids ?? []).forEach((photoId) => {if (!seen.has(photoId)) {seen.add(photoId);result.push(photoId);}});});});return result;}async function saveLayout(next: JobsheetSection[], nextSelectedIds?: string[]) {if (!sessionId) return;setIsSaving(true);setStatus("Saving layout changes...");try {const requests: Promise<unknown>[] = [putJson<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,{ sections: next },),];if (nextSelectedIds !== undefined) {requests.push(3 unmodified lines);}const [pagesResp, sessionResp] = await Promise.all(requests);const updatedSections =(pagesResp as { sections?: JobsheetSection[] }).sections ?? next;const updatedSession = sessionResp as Session | undefined;const updated = ensureSections(updatedSections);setSections(updated);if (updatedSession) {setSession(updatedSession);}7 unmodified lines}}async function handleAddSection() {const next = [...sections,{id: crypto.randomUUID(),title: `Section ${sections.length + 1}`,pages: [{ items: [] }],},];await saveLayout(next);}async function handleAddPage(sectionIndex: number) {const next = sections.map((section, idx) => {if (idx !== sectionIndex) return section;return {...section,pages: [...(section.pages ?? []), { items: [], blank: true }],};});if (session) {const nextSelected = hasExplicitPhotos(next)? flattenPhotoIds(next): session.selected_photo_ids ?? [];await saveLayout(next, nextSelected);return;}await saveLayout(next);}async function handleRemovePage(sectionIndex: number, pageIndex: number) {const next = sections.map((section, idx) => {if (idx !== sectionIndex) return section;const pages = [...(section.pages ?? [])];if (pages.length <= 1) return section;pages.splice(pageIndex, 1);return { ...section, pages: pages.length ? pages : [{ items: [] }] };});if (session) {const nextSelected = hasExplicitPhotos(next)? flattenPhotoIds(next)4 unmodified linesawait saveLayout(next);}async function handleMovePage(sectionIndex: number, pageIndex: number, direction: number) {const next = sections.map((section, idx) => {if (idx !== sectionIndex) return section;const pages = [...(section.pages ?? [])];const target = pageIndex + direction;if (target < 0 || target >= pages.length) return section;[pages[pageIndex], pages[target]] = [pages[target], pages[pageIndex]];return { ...section, pages };});if (session) {const nextSelected = hasExplicitPhotos(next)? flattenPhotoIds(next)10 unmodified linestitle="RepEx - Report Express"subtitle="Edit Page Layouts"right={<div className="flex items-center gap-2"><Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"><ArrowLeft className="h-4 w-4" />Back</Link><InfoMenu sessionQuery={sessionQuery} /></div>}/>46 unmodified linesAdd, remove, or reorder pages, then return to the report viewer to edit content.</p></div><div className="flex flex-wrap gap-2"><buttontype="button"onClick={handleAddSection}disabled={!canModify}className="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 transition disabled:opacity-50 disabled:cursor-not-allowed"><Plus className="h-4 w-4" />Add section</button></div></div>{status ? (<p className="text-sm text-gray-600 mt-3">{status}</p>) : null}</section><section className="space-y-6">{sections.map((section, sectionIndex) => (<div key={section.id} className="rounded-lg border border-gray-200 bg-white p-4"><div className="flex flex-wrap items-center justify-between gap-3 mb-4"><div><div className="text-xs font-semibold text-gray-500">Section {sectionIndex + 1}</div><inputtype="text"value={section.title ?? ""}onChange={(event) =>setSections((prev) =>prev.map((item, idx) =>idx === sectionIndex ? { ...item, title: event.target.value } : item,),)}placeholder={`Section ${sectionIndex + 1}`}className="mt-1 w-60 rounded-md border border-gray-200 px-2 py-1 text-sm font-semibold text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-200"/><div className="text-xs text-gray-500">{section.pages?.length ?? 0} pages</div></div><buttontype="button"onClick={() => handleAddPage(sectionIndex)}disabled={!canModify}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 disabled:cursor-not-allowed"><Plus className="h-4 w-4" />Add page</button></div><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{(section.pages ?? []).map((page, pageIndex) => (<divkey={`${section.id}-page-${pageIndex}`}className="rounded-lg border border-gray-200 bg-white p-3"><div className="flex items-center justify-between mb-2"><div><div className="text-sm font-semibold text-gray-900">Page {pageIndex + 1}</div><div className="text-xs text-gray-500">{page.items?.length ?? 0} items</div></div><div className="flex items-center gap-2"><buttontype="button"onClick={() => handleMovePage(sectionIndex, pageIndex, -1)}disabled={pageIndex === 0 || !canModify}className="inline-flex items-center justify-center rounded-lg border border-gray-200 bg-white p-1.5 text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"aria-label="Move page up"><ChevronUp className="h-3.5 w-3.5" /></button><buttontype="button"onClick={() => handleMovePage(sectionIndex, pageIndex, 1)}disabled={pageIndex === (section.pages?.length ?? 1) - 1 || !canModify}className="inline-flex items-center justify-center rounded-lg border border-gray-200 bg-white p-1.5 text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"aria-label="Move page down"><ChevronDown className="h-3.5 w-3.5" /></button><buttontype="button"onClick={() => handleRemovePage(sectionIndex, pageIndex)}disabled={(section.pages?.length ?? 1) <= 1 || !canModify}className="inline-flex items-center gap-1 rounded-lg border border-red-200 bg-red-50 px-2.5 py-1.5 text-xs font-semibold text-red-700 hover:bg-red-100 transition disabled:opacity-50 disabled:cursor-not-allowed"><Trash2 className="h-3.5 w-3.5" />Remove</button></div></div><divclassName="mx-auto rounded-lg border border-gray-200 bg-white"style={{ width: previewWidth }}><ReportPageCanvassession={session}page={page}pageIndex={pageIndex}pageCount={totalPages}scale={previewScale}template={page?.template}sectionLabel={section.title? `Section ${sectionIndex + 1} - ${section.title}`: `Section ${sectionIndex + 1}`}adaptive/></div></div>))}</div></div>))}
2 unmodified lines34567891011121324 unmodified lines3839404142434445464748495036 unmodified lines878889909192939495969798992 unmodified linesimport { ArrowLeft, Download, Edit3, Grid, Layout, Table } from "react-feather";import { API_BASE, request } from "../lib/api";import { buildSessionQuery, 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 EditReportPage() {const [searchParams] = useSearchParams();24 unmodified linessetStoredSessionId(sessionId);async function load() {try {const [data, pageResp] = await Promise.all([request<Session>(`/sessions/${sessionId}`),request<{ pages: { items: unknown[] }[] }>(`/sessions/${sessionId}/pages`),]);setSession(data);const loaded = Array.isArray(pageResp.pages) ? pageResp.pages.length : 0;setPageCount(loaded || null);} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";36 unmodified linestitle="RepEx - Report Express"subtitle="Edit Report"right={<Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"><ArrowLeft className="h-4 w-4" />Back</Link>}/>2 unmodified lines345678910111213141524 unmodified lines4041424344454647484950515253545536 unmodified lines92939495969798991001011021031041051061072 unmodified linesimport { ArrowLeft, Download, Edit3, Grid, Layout, Table } from "react-feather";import { API_BASE, request } from "../lib/api";import { ensureSections, flattenSections } from "../lib/sections";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { JobsheetSection, Session } from "../types/session";import { PageFooter } from "../components/PageFooter";import { PageHeader } from "../components/PageHeader";import { PageShell } from "../components/PageShell";import { InfoMenu } from "../components/InfoMenu";export default function EditReportPage() {const [searchParams] = useSearchParams();24 unmodified linessetStoredSessionId(sessionId);async function load() {try {const [data, sectionResp] = await Promise.all([request<Session>(`/sessions/${sessionId}`),request<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,),]);setSession(data);const loadedSections = ensureSections(sectionResp.sections);const flatPages = flattenSections(loadedSections);setPageCount(flatPages.length || null);} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";36 unmodified linestitle="RepEx - Report Express"subtitle="Edit Report"right={<div className="flex items-center gap-2"><Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"><ArrowLeft className="h-4 w-4" />Back</Link><InfoMenu sessionQuery={sessionQuery} /></div>}/>
3 unmodified lines45678910111213142 unmodified lines1718192021222313 unmodified lines3738394041424344454618 unmodified lines656667686970717273747576777879808182838485863 unmodified lines9091929394959620 unmodified lines1171181191201211221231241251261 unmodified line12812913013113213313413568 unmodified lines20420520620720820921093 unmodified lines30430530630730830931045 unmodified lines3563573583593603613623633643653663673683693703713 unmodified linesimport { API_BASE, request } from "../lib/api";import { BASE_W } from "../lib/report";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { Page, Session } from "../types/session";import { PageFooter } from "../components/PageFooter";import { PageHeader } from "../components/PageHeader";import { PageShell } from "../components/PageShell";import { ReportPageCanvas } from "../components/ReportPageCanvas";export default function ExportPage() {2 unmodified linesconst sessionQuery = buildSessionQuery(sessionId);const [session, setSession] = useState<Session | null>(null);const [pages, setPages] = useState<Page[]>([]);const [error, setError] = useState("");const [incPages, setIncPages] = useState(true);13 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const pageResp = await request<{ pages: Page[] }>(`/sessions/${sessionId}/pages`,);setPages(Array.isArray(pageResp.pages) ? pageResp.pages : []);} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";18 unmodified lines};}, []);const totals = useMemo(() => {const totalItems = pages.reduce((acc, page) => acc + (page?.items?.length ?? 0),0,);return {pages: pages.length,items: totalItems,photos: session?.selected_photo_ids?.length ?? 0,docs: session?.uploads?.documents?.length ?? 0,data: session?.uploads?.data_files?.length ?? 0,};}, [pages, session]);const totalPages =pages.length > 0 ? pages.length : Math.max(1, session?.page_count ?? 0);const serverExportUrl = sessionId? `${API_BASE}/sessions/${sessionId}/export`: "";3 unmodified linesfunction downloadJson() {const pack: Record<string, unknown> = {};if (incPages) pack.pages = pages;if (incLayout) pack.layout = (session as Session | null)?.["layout"] ?? null;if (incPayload) pack.payload = session;if (incTimestamp) pack.exportedAt = new Date().toISOString();20 unmodified linesreturn (<PageShell className="print:ring-0 print:shadow-none print:rounded-none print:p-0 print:my-0 print:max-w-none"><div className="no-print"><PageHeadertitle="RepEx - Report Express"subtitle="Export"right={<Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"1 unmodified line<ArrowLeft className="h-4 w-4" />Back</Link>}/></div><nav className="mb-6 no-print" aria-label="Report workflow navigation">68 unmodified lineschecked={incPages}onChange={(event) => setIncPages(event.target.checked)}/>Include pages</label><label className="inline-flex items-center gap-2 text-sm text-gray-700"><input93 unmodified lines<div className="rounded-lg border border-gray-200 bg-gray-50 p-3"><div className="text-xs font-semibold text-gray-600">Pages</div><div className="text-sm font-semibold text-gray-900">{pages.length? `${totalPages} pages - ${totals.items} total items`: "No saved pages yet"}</div>45 unmodified lines><divref={index === 0 ? previewRef : undefined}className="relative overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm print:border-0 print:rounded-none print:shadow-none"style={{ aspectRatio: "210 / 297" }}><ReportPageCanvassession={session}page={pages[index] ?? { items: [] }}pageIndex={index}pageCount={totalPages}scale={previewScale}template={pages[index]?.template}/></div></div>3 unmodified lines456789101112131415162 unmodified lines1920212223242513 unmodified lines3940414243444546474818 unmodified lines67686970717273747576777879808182838485868788899091923 unmodified lines9697989910010110220 unmodified lines1231241251261271281291301311321331 unmodified line13513613713813914014114214314468 unmodified lines21321421521621721821993 unmodified lines31331431531631731831945 unmodified lines3653663673683693703713723733743753763773783793803813823833843853863873 unmodified linesimport { API_BASE, request } from "../lib/api";import { BASE_W } from "../lib/report";import { ensureSections, flattenSections } from "../lib/sections";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { JobsheetSection, Session } from "../types/session";import { PageFooter } from "../components/PageFooter";import { PageHeader } from "../components/PageHeader";import { PageShell } from "../components/PageShell";import { InfoMenu } from "../components/InfoMenu";import { ReportPageCanvas } from "../components/ReportPageCanvas";export default function ExportPage() {2 unmodified linesconst sessionQuery = buildSessionQuery(sessionId);const [session, setSession] = useState<Session | null>(null);const [sections, setSections] = useState<JobsheetSection[]>([]);const [error, setError] = useState("");const [incPages, setIncPages] = useState(true);13 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const sectionResp = await request<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,);setSections(ensureSections(sectionResp.sections));} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";18 unmodified lines};}, []);const flatPages = useMemo(() => flattenSections(ensureSections(sections)),[sections],);const totals = useMemo(() => {const totalItems = flatPages.reduce((acc, entry) => acc + (entry.page?.items?.length ?? 0),0,);return {pages: flatPages.length,items: totalItems,photos: session?.selected_photo_ids?.length ?? 0,docs: session?.uploads?.documents?.length ?? 0,data: session?.uploads?.data_files?.length ?? 0,};}, [flatPages, session]);const totalPages =flatPages.length > 0 ? flatPages.length : Math.max(1, session?.page_count ?? 0);const serverExportUrl = sessionId? `${API_BASE}/sessions/${sessionId}/export`: "";3 unmodified linesfunction downloadJson() {const pack: Record<string, unknown> = {};if (incPages) pack.sections = sections;if (incLayout) pack.layout = (session as Session | null)?.["layout"] ?? null;if (incPayload) pack.payload = session;if (incTimestamp) pack.exportedAt = new Date().toISOString();20 unmodified linesreturn (<PageShell className="print:ring-0 print:shadow-none print:rounded-none print:p-0 print:my-0 print:max-w-none"><div className="no-print"><PageHeadertitle="RepEx - Report Express"subtitle="Export"right={<div className="flex items-center gap-2"><Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"1 unmodified line<ArrowLeft className="h-4 w-4" />Back</Link><InfoMenu sessionQuery={sessionQuery} /></div>}/></div><nav className="mb-6 no-print" aria-label="Report workflow navigation">68 unmodified lineschecked={incPages}onChange={(event) => setIncPages(event.target.checked)}/>Include job sheet sections</label><label className="inline-flex items-center gap-2 text-sm text-gray-700"><input93 unmodified lines<div className="rounded-lg border border-gray-200 bg-gray-50 p-3"><div className="text-xs font-semibold text-gray-600">Pages</div><div className="text-sm font-semibold text-gray-900">{flatPages.length? `${totalPages} pages - ${totals.items} total items`: "No saved pages yet"}</div>45 unmodified lines><divref={index === 0 ? previewRef : undefined}className="relative rounded-xl border border-gray-200 bg-white shadow-sm print:border-0 print:rounded-none print:shadow-none"><ReportPageCanvassession={session}page={flatPages[index]?.page ?? { items: [] }}pageIndex={index}pageCount={totalPages}scale={previewScale}template={flatPages[index]?.page?.template}sectionLabel={flatPages[index]? flatPages[index].sectionTitle? `Section ${flatPages[index].sectionIndex + 1} - ${flatPages[index].sectionTitle}`: `Section ${flatPages[index].sectionIndex + 1}`: ""}adaptive/></div></div>
3 unmodified lines456789101112131429 unmodified lines44454647484950515253545515 unmodified lines71727374757677787980817 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261272 unmodified lines1301311321331341351361371381391401411421431441451462 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992001 unmodified line20220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725824 unmodified lines28328428528628728828929029129229329429529629729829930030123 unmodified lines32532632732832933033133233333433533683 unmodified lines42042142242342442542642742842943043143248 unmodified lines48148248348448548648748848949049149249325 unmodified lines51952052152252352452513 unmodified lines539540541542543544545181 unmodified lines72772872973073173257 unmodified lines7907917927937947957967977987991 unmodified line801802803804805806807808809164 unmodified lines97497597697797897998010 unmodified lines9919929939949959969973 unmodified linesimport { API_BASE, postForm, putJson, request } from "../lib/api";import { formatDocNumber } from "../lib/report";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { Page, Session, TemplateFields } from "../types/session";import { PageFooter } from "../components/PageFooter";import { PageHeader } from "../components/PageHeader";import { PageShell } from "../components/PageShell";type FieldDef = {key: keyof TemplateFields;29 unmodified linesconst sessionQuery = buildSessionQuery(sessionId);const [session, setSession] = useState<Session | null>(null);const [pages, setPages] = useState<Page[]>([]);const [status, setStatus] = useState("");const [isSaving, setIsSaving] = useState(false);const [isUploading, setIsUploading] = useState(false);const [copySourceIndex, setCopySourceIndex] = useState(0);const [copyTargets, setCopyTargets] = useState("");const [showGeneralColumns, setShowGeneralColumns] = useState(false);const [generalDirty, setGeneralDirty] = useState(false);const [generalTemplate, setGeneralTemplate] = useState<TemplateFields>({});15 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const pageResp = await request<{ pages: Page[] }>(`/sessions/${sessionId}/pages`,);const loaded = Array.isArray(pageResp.pages) ? pageResp.pages : [];setPages(loaded.length ? loaded : [{ items: [] }]);} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";7 unmodified linesif (!sessionId) return;const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const pageResp = await request<{ pages: Page[] }>(`/sessions/${sessionId}/pages`,);const loaded = Array.isArray(pageResp.pages) ? pageResp.pages : [];setPages(loaded.length ? loaded : [{ items: [] }]);}const totalPages = useMemo(() => {if (pages.length > 0) return pages.length;return Math.max(1, session?.page_count ?? 0);}, [pages.length, session?.page_count]);useEffect(() => {if (!sessionId) return;if (pages.length >= totalPages) return;setPages((prev) => {const next = [...prev];while (next.length < totalPages) {next.push({ items: [] });}return next;});}, [pages.length, sessionId, totalPages]);useEffect(() => {if (copySourceIndex >= pages.length) {setCopySourceIndex(Math.max(0, pages.length - 1));}}, [copySourceIndex, pages.length]);useEffect(() => {if (generalDirty) return;const source = pages[0]?.template ?? {};const next: TemplateFields = {};GENERAL_FIELDS.forEach((field) => {const value = source[field.key] ?? getFallbackValue(field.key);2 unmodified lines}});setGeneralTemplate(next);}, [generalDirty, pages, session]);function updateField(pageIndex: number, key: keyof TemplateFields, value: string) {setPages((prev) =>prev.map((page, idx) => {if (idx !== pageIndex) return page;const template = { ...(page.template ?? {}) };template[key] = value;return { ...page, template };}),);}function updateGeneralField(key: keyof TemplateFields, value: string) {2 unmodified lines}function applyRowToAll(pageIndex: number) {const source = pages[pageIndex]?.template ?? {};setPages((prev) =>prev.map((page) => ({...page,template: { ...source },})),);}function applyGeneralToAll() {if (!pages.length) return;setPages((prev) =>prev.map((page) => {const template = { ...(page.template ?? {}) };GENERAL_FIELDS.forEach((field) => {const value = generalTemplate[field.key];if (value !== undefined) {template[field.key] = value;}});return { ...page, template };}),);setGeneralDirty(false);setStatus("Applied general info to all pages.");}function insertPageAt(index: number, templateSource?: TemplateFields) {setPages((prev) => {const next = [...prev];const fallbackTemplate =templateSource ??next[Math.max(0, Math.min(index - 1, next.length - 1))]?.template ??{};next.splice(index, 0, { items: [], template: { ...fallbackTemplate } });return next;});}function removePageAt(index: number) {setPages((prev) => {if (prev.length <= 1) return prev;const next = [...prev];next.splice(index, 1);return next.length ? next : [{ items: [] }];});}function updatePhotoSelection(pageIndex: number, value: string) {1 unmodified line}function updatePagePhotos(pageIndex: number, nextIds: string[]) {setPages((prev) =>prev.map((page, idx) =>idx === pageIndex ? { ...page, photo_ids: nextIds } : page,),);}function setPhotoOrderLocked(pageIndex: number, locked: boolean) {setPages((prev) =>prev.map((page, idx) =>idx === pageIndex ? { ...page, photo_order_locked: locked } : page,),);}function movePhoto(pageIndex: number, from: number, to: number) {setPages((prev) =>prev.map((page, idx) => {if (idx !== pageIndex) return page;const ids = [...(page.photo_ids ?? [])];if (from < 0 || from >= ids.length || to < 0 || to >= ids.length) {return page;}const [moved] = ids.splice(from, 1);ids.splice(to, 0, moved);return { ...page, photo_ids: ids };}),);}function removePhoto(pageIndex: number, index: number) {setPages((prev) =>prev.map((page, idx) => {if (idx !== pageIndex) return page;const ids = [...(page.photo_ids ?? [])];ids.splice(index, 1);return { ...page, photo_ids: ids };}),);}function addPhotoToPage(pageIndex: number, photoId: string) {if (!photoId) return;setPages((prev) =>prev.map((page, idx) => {if (idx !== pageIndex) return page;const ids = [...(page.photo_ids ?? [])];if (!ids.includes(photoId)) ids.push(photoId);return { ...page, photo_ids: ids };}),);}function parseTargetPages(value: string, max: number): number[] {24 unmodified lines}function copyPageToTargets() {if (!pages.length) return;const targets = parseTargetPages(copyTargets, pages.length).filter((idx) => idx !== copySourceIndex,);if (!targets.length) {setStatus("No valid target pages selected for copy.");return;}const sourceTemplate = pages[copySourceIndex]?.template ?? {};setPages((prev) =>prev.map((page, idx) =>targets.includes(idx) ? { ...page, template: { ...sourceTemplate } } : page,),);setStatus(`Copied page ${copySourceIndex + 1} to ${targets23 unmodified linessetIsSaving(true);setStatus("Saving input data...");try {const resp = await putJson<{ pages: Page[] }>(`/sessions/${sessionId}/pages`,{ pages },);const updated = Array.isArray(resp.pages) ? resp.pages : pages;setPages(updated.length ? updated : [{ items: [] }]);setStatus("Input data saved.");} catch (err) {const message =83 unmodified linestitle="RepEx - Report Express"subtitle="Input Data"right={<Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"><ArrowLeft className="h-4 w-4" />Back</Link>}/>48 unmodified lines</p></div><div className="flex flex-wrap gap-2"><buttontype="button"onClick={() => insertPageAt(pages.length, {})}disabled={!sessionId}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed">Add blank page</button><buttontype="button"25 unmodified linesvalue={copySourceIndex}onChange={(event) => setCopySourceIndex(Number(event.target.value))}>{pages.map((_, idx) => (<option key={`copy-source-${idx}`} value={idx}>Page {idx + 1}</option>13 unmodified lines<buttontype="button"onClick={copyPageToTargets}disabled={!pages.length}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 disabled:opacity-50 disabled:cursor-not-allowed">Copy page data181 unmodified lines</div></section><div className="rounded-lg border border-gray-200 bg-white overflow-x-auto"><div className="px-3 py-2 text-xs text-gray-500 bg-gray-50 border-b border-gray-200">General Info (double-click the header below to expand/collapse columns)57 unmodified lines</tr></thead><tbody>{pages.map((page, pageIndex) => {const template = page.template ?? {};const photoIds = page.photo_ids ?? [];const orderLocked = page.photo_order_locked ?? false;const photoLookup = new Map((session?.uploads?.photos ?? []).map((photo) => [photo.id, photo]),);1 unmodified line(photo) => !photoIds.includes(photo.id),);return (<tr key={`row-${pageIndex}`} className="border-b border-gray-100"><td className="px-3 py-2 text-xs font-semibold text-gray-700">Page {pageIndex + 1}</td>{showGeneralColumns ? (GENERAL_FIELDS.map((field) => (164 unmodified lines<buttontype="button"onClick={() => removePageAt(pageIndex)}disabled={pages.length <= 1}className="inline-flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs font-semibold text-red-700 hover:bg-red-100 transition disabled:opacity-50 disabled:cursor-not-allowed">Delete page10 unmodified lines<div className="mt-3 flex justify-end"><buttontype="button"onClick={() => insertPageAt(pages.length, pages[pages.length - 1]?.template)}disabled={!sessionId}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed">3 unmodified lines4567891011121314151617181920212229 unmodified lines525354555657585960616263646515 unmodified lines818283848586878889907 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321332 unmodified lines1361371381391401411421431441451461471481491501511521531541551562 unmodified lines1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582591 unmodified line26126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831924 unmodified lines34434534634734834935035135235335435535635735835936036136236336436536636736836937037123 unmodified lines39539639739839940040140240340440540683 unmodified lines49049149249349449549649749849950050150250350450548 unmodified lines55455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758825 unmodified lines61461561661761861962013 unmodified lines634635636637638639640181 unmodified lines82282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191257 unmodified lines9709719729739749759769779789799801 unmodified line982983984985986987988989990164 unmodified lines115511561157115811591160116110 unmodified lines11721173117411751176117711783 unmodified linesimport { API_BASE, postForm, putJson, request } from "../lib/api";import { formatDocNumber } from "../lib/report";import {ensureSections,flattenSections,insertPage,removePage,replacePage,} from "../lib/sections";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { JobsheetSection, Session, TemplateFields } from "../types/session";import { PageFooter } from "../components/PageFooter";import { PageHeader } from "../components/PageHeader";import { PageShell } from "../components/PageShell";import { InfoMenu } from "../components/InfoMenu";type FieldDef = {key: keyof TemplateFields;29 unmodified linesconst sessionQuery = buildSessionQuery(sessionId);const [session, setSession] = useState<Session | null>(null);const [sections, setSections] = useState<JobsheetSection[]>([]);const [status, setStatus] = useState("");const [isSaving, setIsSaving] = useState(false);const [isUploading, setIsUploading] = useState(false);const [copySourceIndex, setCopySourceIndex] = useState(0);const [copyTargets, setCopyTargets] = useState("");const [addSectionId, setAddSectionId] = useState<string>("");const [sectionsCollapsed, setSectionsCollapsed] = useState(true);const [showGeneralColumns, setShowGeneralColumns] = useState(false);const [generalDirty, setGeneralDirty] = useState(false);const [generalTemplate, setGeneralTemplate] = useState<TemplateFields>({});15 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const sectionResp = await request<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,);setSections(ensureSections(sectionResp.sections));} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";7 unmodified linesif (!sessionId) return;const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const sectionResp = await request<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,);setSections(ensureSections(sectionResp.sections));}const flatPages = useMemo(() => flattenSections(ensureSections(sections)),[sections],);const totalPages = useMemo(() => {if (flatPages.length > 0) return flatPages.length;return Math.max(1, session?.page_count ?? 0);}, [flatPages.length, session?.page_count]);useEffect(() => {if (copySourceIndex >= flatPages.length) {setCopySourceIndex(Math.max(0, flatPages.length - 1));}}, [copySourceIndex, flatPages.length]);useEffect(() => {if (!addSectionId && sections.length > 0) {setAddSectionId(sections[0].id);}}, [addSectionId, sections]);useEffect(() => {if (generalDirty) return;const source = flatPages[0]?.page?.template ?? {};const next: TemplateFields = {};GENERAL_FIELDS.forEach((field) => {const value = source[field.key] ?? getFallbackValue(field.key);2 unmodified lines}});setGeneralTemplate(next);}, [generalDirty, flatPages, session]);function updateField(entryIndex: number,key: keyof TemplateFields,value: string,) {const entry = flatPages[entryIndex];if (!entry) return;setSections((prev) => {const template = { ...(entry.page.template ?? {}) };template[key] = value;const nextPage = { ...entry.page, template };return replacePage(prev, entry.sectionIndex, entry.pageIndex, nextPage);});}function updateGeneralField(key: keyof TemplateFields, value: string) {2 unmodified lines}function applyRowToAll(pageIndex: number) {const entry = flatPages[pageIndex];if (!entry) return;const source = entry.page.template ?? {};setSections((prev) =>prev.map((section) => ({...section,pages: (section.pages ?? []).map((page) => ({...page,template: { ...source },})),})),);}function applyGeneralToAll() {if (!flatPages.length) return;setSections((prev) =>prev.map((section) => ({...section,pages: (section.pages ?? []).map((page) => {const template = { ...(page.template ?? {}) };GENERAL_FIELDS.forEach((field) => {const value = generalTemplate[field.key];if (value !== undefined) {template[field.key] = value;}});return { ...page, template };}),})),);setGeneralDirty(false);setStatus("Applied general info to all pages.");}function insertPageAt(index: number, templateSource?: TemplateFields) {const atEnd = index >= flatPages.length;const entry = flatPages[index] ?? flatPages[flatPages.length - 1];if (!entry) return;setSections((prev) => {const fallbackTemplate =templateSource ??entry.page.template ??{};const pageIndex = atEnd ? entry.pageIndex + 1 : entry.pageIndex;return insertPage(prev, entry.sectionIndex, pageIndex, {items: [],template: { ...fallbackTemplate },});});}function addSection() {const baseTemplate = { ...generalTemplate };setSections((prev) => [...prev,{id: crypto.randomUUID(),title: `Section ${prev.length + 1}`,pages: [{ items: [], template: baseTemplate }],},]);}function updateSectionTitle(sectionId: string, value: string) {setSections((prev) =>prev.map((section) =>section.id === sectionId ? { ...section, title: value } : section,),);}function insertPageIntoSection(sectionId: string, templateSource?: TemplateFields) {const sectionIndex = sections.findIndex((section) => section.id === sectionId);if (sectionIndex === -1) return;const section = sections[sectionIndex];const fallbackTemplate =templateSource ??section.pages?.[section.pages.length - 1]?.template ??generalTemplate ??{};setSections((prev) =>insertPage(prev, sectionIndex, section.pages?.length ?? 0, {items: [],template: { ...fallbackTemplate },}),);}function removePageAt(index: number) {const entry = flatPages[index];if (!entry) return;setSections((prev) =>removePage(prev, entry.sectionIndex, entry.pageIndex),);}function updatePhotoSelection(pageIndex: number, value: string) {1 unmodified line}function updatePagePhotos(pageIndex: number, nextIds: string[]) {const entry = flatPages[pageIndex];if (!entry) return;setSections((prev) => {const nextPage = { ...entry.page, photo_ids: nextIds };return replacePage(prev, entry.sectionIndex, entry.pageIndex, nextPage);});}function setPhotoOrderLocked(pageIndex: number, locked: boolean) {const entry = flatPages[pageIndex];if (!entry) return;setSections((prev) => {const nextPage = { ...entry.page, photo_order_locked: locked };return replacePage(prev, entry.sectionIndex, entry.pageIndex, nextPage);});}function movePhoto(pageIndex: number, from: number, to: number) {const entry = flatPages[pageIndex];if (!entry) return;setSections((prev) => {const ids = [...(entry.page.photo_ids ?? [])];if (from < 0 || from >= ids.length || to < 0 || to >= ids.length) {return prev;}const [moved] = ids.splice(from, 1);ids.splice(to, 0, moved);const nextPage = { ...entry.page, photo_ids: ids };return replacePage(prev, entry.sectionIndex, entry.pageIndex, nextPage);});}function removePhoto(pageIndex: number, index: number) {const entry = flatPages[pageIndex];if (!entry) return;setSections((prev) => {const ids = [...(entry.page.photo_ids ?? [])];ids.splice(index, 1);const nextPage = { ...entry.page, photo_ids: ids };return replacePage(prev, entry.sectionIndex, entry.pageIndex, nextPage);});}function addPhotoToPage(pageIndex: number, photoId: string) {if (!photoId) return;const entry = flatPages[pageIndex];if (!entry) return;setSections((prev) => {const ids = [...(entry.page.photo_ids ?? [])];if (!ids.includes(photoId)) ids.push(photoId);const nextPage = { ...entry.page, photo_ids: ids };return replacePage(prev, entry.sectionIndex, entry.pageIndex, nextPage);});}function parseTargetPages(value: string, max: number): number[] {24 unmodified lines}function copyPageToTargets() {if (!flatPages.length) return;const targets = parseTargetPages(copyTargets, flatPages.length).filter((idx) => idx !== copySourceIndex,);if (!targets.length) {setStatus("No valid target pages selected for copy.");return;}const sourceTemplate = flatPages[copySourceIndex]?.page?.template ?? {};setSections((prev) =>prev.map((section, sIdx) => ({...section,pages: (section.pages ?? []).map((page, pIdx) => {const flatIndex =flattenSections(prev).find((entry) =>entry.sectionIndex === sIdx && entry.pageIndex === pIdx,)?.flatIndex ?? -1;if (!targets.includes(flatIndex)) return page;return { ...page, template: { ...sourceTemplate } };}),})),);setStatus(`Copied page ${copySourceIndex + 1} to ${targets23 unmodified linessetIsSaving(true);setStatus("Saving input data...");try {const resp = await putJson<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,{ sections },);const updated = ensureSections(resp.sections ?? sections);setSections(updated);setStatus("Input data saved.");} catch (err) {const message =83 unmodified linestitle="RepEx - Report Express"subtitle="Input Data"right={<div className="flex items-center gap-2"><Linkto={`/report-viewer${sessionQuery}`}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition"><ArrowLeft className="h-4 w-4" />Back</Link><InfoMenu sessionQuery={sessionQuery} /></div>}/>48 unmodified lines</p></div><div className="flex flex-wrap gap-2"><div className="flex items-center gap-2"><selectclassName="rounded-md border border-gray-200 px-2 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"value={addSectionId}onChange={(event) => setAddSectionId(event.target.value)}disabled={!sections.length}>{sections.map((section, idx) => (<option key={section.id} value={section.id}>{section.title || `Section ${idx + 1}`}</option>))}</select><buttontype="button"onClick={() => insertPageIntoSection(addSectionId, generalTemplate)}disabled={!sessionId || !addSectionId}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed">Add blank page</button></div><buttontype="button"onClick={addSection}disabled={!sessionId}className="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 transition disabled:opacity-50 disabled:cursor-not-allowed">Add section</button><buttontype="button"25 unmodified linesvalue={copySourceIndex}onChange={(event) => setCopySourceIndex(Number(event.target.value))}>{flatPages.map((_, idx) => (<option key={`copy-source-${idx}`} value={idx}>Page {idx + 1}</option>13 unmodified lines<buttontype="button"onClick={copyPageToTargets}disabled={!flatPages.length}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 disabled:opacity-50 disabled:cursor-not-allowed">Copy page data181 unmodified lines</div></section><section className="mb-4 rounded-lg border border-gray-200 bg-white p-3"><div className="flex flex-wrap items-center justify-between gap-2"><div><h3 className="text-sm font-semibold text-gray-900">Job Sheet Sections</h3><p className="text-xs text-gray-600">Rename sections and add pages directly inside a section.</p></div><div className="flex items-center gap-2"><buttontype="button"onClick={() => setSectionsCollapsed((prev) => !prev)}className="inline-flex items-center gap-2 rounded-md border border-gray-200 bg-white px-3 py-1 text-xs font-semibold text-gray-700 hover:bg-gray-50 transition">{sectionsCollapsed ? "Expand" : "Collapse"}</button><buttontype="button"onClick={addSection}className="inline-flex items-center gap-2 rounded-md border border-gray-200 bg-white px-3 py-1 text-xs font-semibold text-gray-700 hover:bg-gray-50 transition">Add section</button></div></div>{sectionsCollapsed ? (<div className="mt-2 text-[11px] text-gray-500">{sections.length} section{sections.length === 1 ? "" : "s"} ·{" "}{sections.reduce((sum, section) => sum + (section.pages?.length ?? 0), 0)}{" "}page{sections.length === 1 ? "" : "s"} total</div>) : (<div className="mt-2 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">{sections.map((section, idx) => (<divkey={section.id}className="rounded-md border border-gray-200 bg-gray-50 p-2"><div className="flex items-center justify-between gap-2"><div className="text-[11px] font-semibold text-gray-700">Section {idx + 1}</div><buttontype="button"onClick={() => insertPageIntoSection(section.id)}className="inline-flex items-center gap-1 rounded-md border border-gray-200 bg-white px-2 py-0.5 text-[11px] font-semibold text-gray-700 hover:bg-gray-50 transition">Add page</button></div><div className="mt-1 text-[11px] text-gray-500">Pages: {section.pages?.length ?? 0}</div><div className="text-[11px] text-gray-500">Page numbers:{" "}{(() => {const start =sections.slice(0, idx).reduce((sum, item) => sum + (item.pages?.length ?? 0), 0) +1;const count = section.pages?.length ?? 0;if (count <= 0) return "-";const end = start + count - 1;return start === end ? `${start}` : `${start}-${end}`;})()}</div><label className="mt-1 block text-[11px] text-gray-600">Title<inputtype="text"className="mt-1 w-full rounded-md border border-gray-200 px-2 py-0.5 text-xs focus:outline-none focus:ring-2 focus:ring-blue-200"value={section.title ?? ""}onChange={(event) =>updateSectionTitle(section.id, event.target.value)}placeholder={`Section ${idx + 1}`}/></label></div>))}</div>)}</section><div className="rounded-lg border border-gray-200 bg-white overflow-x-auto"><div className="px-3 py-2 text-xs text-gray-500 bg-gray-50 border-b border-gray-200">General Info (double-click the header below to expand/collapse columns)57 unmodified lines</tr></thead><tbody>{flatPages.map((entry) => {const pageIndex = entry.flatIndex;const template = entry.page.template ?? {};const photoIds = entry.page.photo_ids ?? [];const orderLocked = entry.page.photo_order_locked ?? false;const photoLookup = new Map((session?.uploads?.photos ?? []).map((photo) => [photo.id, photo]),);1 unmodified line(photo) => !photoIds.includes(photo.id),);return (<tr key={`row-${entry.sectionId}-${entry.pageIndex}`} className="border-b border-gray-100"><td className="px-3 py-2 text-xs font-semibold text-gray-700">Page {entry.flatIndex + 1}</td>{showGeneralColumns ? (GENERAL_FIELDS.map((field) => (164 unmodified lines<buttontype="button"onClick={() => removePageAt(pageIndex)}disabled={flatPages.length <= 1}className="inline-flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs font-semibold text-red-700 hover:bg-red-100 transition disabled:opacity-50 disabled:cursor-not-allowed">Delete page10 unmodified lines<div className="mt-3 flex justify-end"><buttontype="button"onClick={() => insertPageAt(flatPages.length, flatPages[flatPages.length - 1]?.page?.template)}disabled={!sessionId}className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed">
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294import { BarChart2, ArrowLeft } from "react-feather";import { Link, useSearchParams } from "react-router-dom";
import { PageShell } from "../components/PageShell";import { PageHeader } from "../components/PageHeader";import { buildSessionQuery, getSessionId } from "../lib/session";
export default function RatingsInfoPage() { const [searchParams] = useSearchParams(); const sessionId = getSessionId(searchParams.toString()); const sessionQuery = buildSessionQuery(sessionId); return ( <PageShell className="max-w-6xl"> <PageHeader title="Assessment Rating Scales" subtitle="Interactive rating system for condition evaluation" right={ <Link to={`/report-viewer${sessionQuery}`} className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 transition" > <ArrowLeft className="h-4 w-4" /> Back </Link> } />
<section className="mt-4 bg-white rounded-xl shadow-sm p-6"> <h2 className="text-xl font-semibold text-gray-800 border-b border-gray-200 pb-2 mb-4 flex items-center gap-2"> <BarChart2 className="h-5 w-5" /> Rating Scales </h2>
<div className="rounded-lg border border-gray-200 bg-gray-50 p-4 mb-6"> <p className="text-sm text-gray-700"> Use the tables below to interpret{" "} <span className="font-semibold">Category</span> and{" "} <span className="font-semibold">Priority</span> ratings used throughout this report. Ratings determine severity and recommended response time. </p> </div>
<div className="mt-4"> <label className="block text-sm font-medium text-gray-500 mb-2"> Condition Scale </label>
<div className="grid grid-cols-6 gap-1 text-center mb-2"> <div className="text-xs font-bold bg-green-100 text-green-800 p-1 rounded"> 0 </div> <div className="text-xs font-bold bg-green-200 text-green-800 p-1 rounded"> 1 </div> <div className="text-xs font-bold bg-yellow-100 text-yellow-800 p-1 rounded"> 2 </div> <div className="text-xs font-bold bg-yellow-200 text-yellow-800 p-1 rounded"> 3 </div> <div className="text-xs font-bold bg-orange-200 text-orange-800 p-1 rounded"> 4 </div> <div className="text-xs font-bold bg-red-200 text-red-800 p-1 rounded"> 5 </div> </div>
<div className="grid grid-cols-6 gap-1 text-center"> <div className="text-xs font-bold bg-green-100 text-green-800 p-1 rounded" title="Excellent Condition: No Deterioration. Structure is Safe for use. 100% Original Strength of Structure. Remedial Action: None" > Excellent </div> <div className="text-xs font-bold bg-green-200 text-green-800 p-1 rounded" title="Good Condition: Slight Surface Deterioration. Structure is safe for use. 100% Original Strength of Structure. Remedial Action: None" > Good </div> <div className="text-xs font-bold bg-yellow-100 text-yellow-800 p-1 rounded" title="Fair Condition: Some Deterioration deeper than surface level. Structure is safe for use. 95-100% Original Strength of Structure. Remedial Action: Minor Works" > Fair </div> <div className="text-xs font-bold bg-yellow-200 text-yellow-800 p-1 rounded" title="Poor Condition: Discernible Deterioration. Some compromise in safety. 75-95% Original Strength of Structure. Remedial Action: Minor Works" > Poor </div> <div className="text-xs font-bold bg-orange-200 text-orange-800 p-1 rounded" title="Worse Condition: Severe Deterioration. Severe compromise in safety. 50-75% Original Strength of Structure. Remedial Action: Major Works" > Worse </div> <div className="text-xs font-bold bg-red-200 text-red-800 p-1 rounded" title="Severe Condition: Severe Deterioration. Total and complete compromise in safety. <50% Original Strength of Structure. Remedial Action: Major Works Urgently" > Severe </div> </div>
<div className="mt-3 overflow-x-auto rounded-lg border border-gray-200"> <table className="min-w-full divide-y divide-gray-200 text-sm"> <thead className="bg-gray-50"> <tr> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Category </th> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Label </th> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Definition </th> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Strength </th> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Remedial Action </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> <tr> <td className="px-3 py-2 font-semibold text-gray-900">0</td> <td className="px-3 py-2">Excellent</td> <td className="px-3 py-2"> No deterioration. Structure is safe for use. </td> <td className="px-3 py-2">100% Original Strength</td> <td className="px-3 py-2">None</td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">1</td> <td className="px-3 py-2">Good</td> <td className="px-3 py-2"> Slight surface deterioration. Structure is safe for use. </td> <td className="px-3 py-2">100% Original Strength</td> <td className="px-3 py-2">None</td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">2</td> <td className="px-3 py-2">Fair</td> <td className="px-3 py-2"> Some deterioration deeper than surface level. Structure is safe for use. </td> <td className="px-3 py-2">95–100% Original Strength</td> <td className="px-3 py-2">Minor Works</td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">3</td> <td className="px-3 py-2">Poor</td> <td className="px-3 py-2"> Discernible deterioration. Some compromise in safety. </td> <td className="px-3 py-2">75–95% Original Strength</td> <td className="px-3 py-2">Minor Works</td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">4</td> <td className="px-3 py-2">Worse</td> <td className="px-3 py-2"> Severe deterioration. Severe compromise in safety. </td> <td className="px-3 py-2">50–75% Original Strength</td> <td className="px-3 py-2">Major Works</td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">5</td> <td className="px-3 py-2">Severe</td> <td className="px-3 py-2"> Severe deterioration. Total and complete compromise in safety. </td> <td className="px-3 py-2"><50% Original Strength</td> <td className="px-3 py-2">Major Works (Urgently)</td> </tr> </tbody> </table> </div> </div>
<div className="mt-6"> <label className="block text-sm font-medium text-gray-500 mb-2"> Priority Scale </label>
<div className="grid grid-cols-5 gap-1 text-center mb-2"> <div className="text-xs font-bold bg-red-200 text-red-800 p-1 rounded"> 1 </div> <div className="text-xs font-bold bg-orange-200 text-orange-800 p-1 rounded"> 2 </div> <div className="text-xs font-bold bg-green-200 text-green-800 p-1 rounded"> 3 </div> <div className="text-xs font-bold bg-purple-200 text-purple-800 p-1 rounded"> X </div> <div className="text-xs font-bold bg-blue-200 text-blue-800 p-1 rounded"> M </div> </div>
<div className="grid grid-cols-5 gap-1 text-center"> <div className="text-xs font-bold bg-red-200 text-red-800 p-1 rounded"> Immediate </div> <div className="text-xs font-bold bg-orange-200 text-orange-800 p-1 rounded"> 1 Year </div> <div className="text-xs font-bold bg-green-200 text-green-800 p-1 rounded"> 3 Years </div> <div className="text-xs font-bold bg-purple-200 text-purple-800 p-1 rounded"> At Use </div> <div className="text-xs font-bold bg-blue-200 text-blue-800 p-1 rounded"> Monitor </div> </div>
<div className="mt-3 overflow-x-auto rounded-lg border border-gray-200"> <table className="min-w-full divide-y divide-gray-200 text-sm"> <thead className="bg-gray-50"> <tr> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Priority </th> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Label </th> <th className="px-3 py-2 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider"> Definition </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> <tr> <td className="px-3 py-2 font-semibold text-gray-900">1</td> <td className="px-3 py-2">Immediate</td> <td className="px-3 py-2"> Action requires urgent, immediate attention. </td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">2</td> <td className="px-3 py-2">1 Year</td> <td className="px-3 py-2"> Action to be done ASAP, and no later than 1 year from report date. </td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">3</td> <td className="px-3 py-2">3 Years</td> <td className="px-3 py-2"> Action required within the next 3 years from report date. </td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">X</td> <td className="px-3 py-2">At Use</td> <td className="px-3 py-2"> Action must be completed before use of the non-critical service structure. </td> </tr> <tr> <td className="px-3 py-2 font-semibold text-gray-900">M</td> <td className="px-3 py-2">Monitor</td> <td className="px-3 py-2"> Monitoring required to evaluate the extent of damage/deterioration with record keeping. </td> </tr> </tbody> </table> </div> </div> </section> </PageShell> );}12 unmodified lines1314151617181920212223242526272825 unmodified lines54555657585960616263643 unmodified lines6869707172737475767712 unmodified lines909192939495969 unmodified lines10610710810911011111211311411511611723 unmodified lines14114214314414514693 unmodified lines24024124224324424512 unmodified linesimport { request } from "../lib/api";import { BASE_W } from "../lib/report";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { Page, Session } from "../types/session";import { ReportPageCanvas } from "../components/ReportPageCanvas";export default function ReportViewerPage() {const [searchParams] = useSearchParams();const sessionId = getSessionId(searchParams.toString());const [session, setSession] = useState<Session | null>(null);const [pages, setPages] = useState<Page[]>([]);const [pageIndex, setPageIndex] = useState(0);const [scale, setScale] = useState(1);const [error, setError] = useState("");25 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const pageResp = await request<{ pages: Page[] }>(`/sessions/${sessionId}/pages`,);const loaded = Array.isArray(pageResp.pages) ? pageResp.pages : [];setPages(loaded);} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";3 unmodified linesload();}, [sessionId]);const totalPages = useMemo(() => {if (pages.length > 0) return pages.length;return Math.max(1, session?.page_count ?? 0);}, [pages.length, session?.page_count]);useEffect(() => {setPageIndex((idx) => Math.min(Math.max(0, idx), totalPages - 1));12 unmodified linesreturn () => window.removeEventListener("keydown", handler);}, [totalPages]);const page = pages[pageIndex] ?? null;const template = page?.template;const sessionQuery = buildSessionQuery(sessionId || "");const editReportQuery = useMemo(() => {9 unmodified linesconst selected = session.selected_photo_ids?.length ?? 0;const docs = session.uploads?.documents?.length ?? 0;const dataFiles = session.uploads?.data_files?.length ?? 0;const hasEdits = pages.length > 0;return (`Selected example photos: ${selected} - Documents: ${docs} - Data files: ${dataFiles}` +(hasEdits ? " - Edited pages loaded" : " - No saved edits yet"));}, [pages.length, session]);return (<main className="max-w-4xl mx-auto my-8 bg-white shadow-sm ring-1 ring-gray-200 rounded-xl p-6 md:p-8 print:ring-0 print:shadow-none print:rounded-none">23 unmodified lines<ArrowLeft className="h-4 w-4" />Back</Link></div></div></header>93 unmodified linespageCount={totalPages}scale={scale}template={template}adaptive/></div>12 unmodified lines13141516171819202122232425262728293025 unmodified lines56575859606162636465663 unmodified lines707172737475767778798081828312 unmodified lines969798991001011021031041051061079 unmodified lines11711811912012112212312412512612712823 unmodified lines15215315415515615715893 unmodified lines25225325425525625725812 unmodified linesimport { request } from "../lib/api";import { BASE_W } from "../lib/report";import { ensureSections, flattenSections } from "../lib/sections";import { buildSessionQuery, getSessionId, setStoredSessionId } from "../lib/session";import type { JobsheetSection, Session } from "../types/session";import { ReportPageCanvas } from "../components/ReportPageCanvas";import { InfoMenu } from "../components/InfoMenu";export default function ReportViewerPage() {const [searchParams] = useSearchParams();const sessionId = getSessionId(searchParams.toString());const [session, setSession] = useState<Session | null>(null);const [sections, setSections] = useState<JobsheetSection[]>([]);const [pageIndex, setPageIndex] = useState(0);const [scale, setScale] = useState(1);const [error, setError] = useState("");25 unmodified linestry {const data = await request<Session>(`/sessions/${sessionId}`);setSession(data);const sectionResp = await request<{ sections: JobsheetSection[] }>(`/sessions/${sessionId}/sections`,);const loaded = ensureSections(sectionResp.sections);setSections(loaded);} catch (err) {const message =err instanceof Error ? err.message : "Failed to load session.";3 unmodified linesload();}, [sessionId]);const flatPages = useMemo(() => flattenSections(ensureSections(sections)),[sections],);const totalPages = useMemo(() => {if (flatPages.length > 0) return flatPages.length;return Math.max(1, session?.page_count ?? 0);}, [flatPages.length, session?.page_count]);useEffect(() => {setPageIndex((idx) => Math.min(Math.max(0, idx), totalPages - 1));12 unmodified linesreturn () => window.removeEventListener("keydown", handler);}, [totalPages]);const page = flatPages[pageIndex]?.page ?? null;const sectionLabel = flatPages[pageIndex]?.sectionTitle? `Section ${flatPages[pageIndex].sectionIndex + 1} - ${flatPages[pageIndex].sectionTitle}`: flatPages[pageIndex]? `Section ${flatPages[pageIndex].sectionIndex + 1}`: "";const template = page?.template;const sessionQuery = buildSessionQuery(sessionId || "");const editReportQuery = useMemo(() => {9 unmodified linesconst selected = session.selected_photo_ids?.length ?? 0;const docs = session.uploads?.documents?.length ?? 0;const dataFiles = session.uploads?.data_files?.length ?? 0;const hasEdits = flatPages.length > 0;return (`Selected example photos: ${selected} - Documents: ${docs} - Data files: ${dataFiles}` +(hasEdits ? " - Edited pages loaded" : " - No saved edits yet"));}, [flatPages.length, session]);return (<main className="max-w-4xl mx-auto my-8 bg-white shadow-sm ring-1 ring-gray-200 rounded-xl p-6 md:p-8 print:ring-0 print:shadow-none print:rounded-none">23 unmodified lines<ArrowLeft className="h-4 w-4" />Back</Link><InfoMenu sessionQuery={sessionQuery} /></div></div></header>93 unmodified linespageCount={totalPages}scale={scale}template={template}sectionLabel={sectionLabel}adaptive/></div>
28 unmodified lines29303132333454 unmodified lines899091929394959628 unmodified linesuploads: SessionUploads;selected_photo_ids: string[];page_count: number;headings?: Heading[];layout?: Record<string, unknown> | null;};54 unmodified linestemplate?: TemplateFields;photo_ids?: string[];photo_order_locked?: boolean;};export type PagesResponse = {pages: Page[];};28 unmodified lines2930313233343554 unmodified lines9091929394959697989910010110210310410510610710810928 unmodified linesuploads: SessionUploads;selected_photo_ids: string[];page_count: number;jobsheet_sections?: JobsheetSection[];headings?: Heading[];layout?: Record<string, unknown> | null;};54 unmodified linestemplate?: TemplateFields;photo_ids?: string[];photo_order_locked?: boolean;blank?: boolean;variant?: "full" | "photos";};export type JobsheetSection = {id: string;title?: string;pages: Page[];};export type PagesResponse = {pages: Page[];};export type SectionsResponse = {sections: JobsheetSection[];};
11 unmodified lines12131415161777 unmodified lines959697989910048 unmodified lines14915015115215315492 unmodified lines24724824925025125225325421 unmodified lines27627727827928028128228328428511 unmodified linesfrom ..schemas import (PagesRequest,PagesResponse,SelectionRequest,SessionResponse,SessionStatusResponse,77 unmodified linessession = store.get_session(session_id)if not session:raise HTTPException(status_code=404, detail="Session not found.")return _attach_urls(session)48 unmodified linesreturn PagesResponse(pages=session.get("pages") or [])@router.get("/{session_id}/uploads/{file_id}")def get_upload(session_id: str,92 unmodified linesimported_session = payload.get("session") if isinstance(payload, dict) else Nonepages = payload.get("pages") if isinstance(payload, dict) else Noneif not pages and isinstance(imported_session, dict):pages = imported_session.get("pages")if pages:session = store.set_pages(session, pages)21 unmodified linessession = store.get_session(session_id)if not session:raise HTTPException(status_code=404, detail="Session not found.")export_path = Path(store.session_dir(session_id)) / "export.json"payload = {"session": session,"pages": session.get("pages") or [],"exported_at": session.get("updated_at"),}export_path.write_text(11 unmodified lines121314151617181977 unmodified lines97989910010110210348 unmodified lines15215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218392 unmodified lines27627727827928028128228328428528628728821 unmodified lines31031131231331431531631731831932032132211 unmodified linesfrom ..schemas import (PagesRequest,PagesResponse,SectionsRequest,SectionsResponse,SelectionRequest,SessionResponse,SessionStatusResponse,77 unmodified linessession = store.get_session(session_id)if not session:raise HTTPException(status_code=404, detail="Session not found.")store.ensure_sections(session)return _attach_urls(session)48 unmodified linesreturn PagesResponse(pages=session.get("pages") or [])@router.get("/{session_id}/sections", response_model=SectionsResponse)def get_sections(session_id: str, store: SessionStore = Depends(get_session_store)) -> SectionsResponse:session_id = _normalize_session_id(session_id, store)session = store.get_session(session_id)if not session:raise HTTPException(status_code=404, detail="Session not found.")sections = store.ensure_sections(session)return SectionsResponse(sections=sections)@router.put("/{session_id}/sections", response_model=SectionsResponse)def save_sections(session_id: str,payload: SectionsRequest,store: SessionStore = Depends(get_session_store),) -> SectionsResponse:session_id = _normalize_session_id(session_id, store)session = store.get_session(session_id)if not session:raise HTTPException(status_code=404, detail="Session not found.")session = store.set_sections(session, payload.sections)return SectionsResponse(sections=session.get("jobsheet_sections") or [])@router.get("/{session_id}/uploads/{file_id}")def get_upload(session_id: str,92 unmodified linesimported_session = payload.get("session") if isinstance(payload, dict) else Nonepages = payload.get("pages") if isinstance(payload, dict) else Nonesections = payload.get("sections") if isinstance(payload, dict) else Noneif not sections and isinstance(imported_session, dict):sections = imported_session.get("jobsheet_sections")if not pages and isinstance(imported_session, dict):pages = imported_session.get("pages")if sections:session = store.set_sections(session, sections)if pages:session = store.set_pages(session, pages)21 unmodified linessession = store.get_session(session_id)if not session:raise HTTPException(status_code=404, detail="Session not found.")sections = store.ensure_sections(session)pages = store.ensure_pages(session)export_path = Path(store.session_dir(session_id)) / "export.json"payload = {"session": session,"pages": pages,"sections": sections,"exported_at": session.get("updated_at"),}export_path.write_text(
30 unmodified lines31323334353612 unmodified lines49505130 unmodified linesselected_photo_ids: List[str] = Field(default_factory=list)page_count: int = 0headings: List[Heading] = Field(default_factory=list)class SessionStatusResponse(BaseModel):12 unmodified linesclass PagesRequest(BaseModel):pages: List[dict] = Field(default_factory=list)30 unmodified lines3132333435363712 unmodified lines505152535455565758596061626364656630 unmodified linesselected_photo_ids: List[str] = Field(default_factory=list)page_count: int = 0headings: List[Heading] = Field(default_factory=list)jobsheet_sections: List["JobsheetSection"] = Field(default_factory=list)class SessionStatusResponse(BaseModel):12 unmodified linesclass PagesRequest(BaseModel):pages: List[dict] = Field(default_factory=list)class JobsheetSection(BaseModel):id: strtitle: Optional[str] = Nonepages: List[dict] = Field(default_factory=list)class SectionsResponse(BaseModel):sections: List[JobsheetSection] = Field(default_factory=list)class SectionsRequest(BaseModel):sections: List[JobsheetSection] = Field(default_factory=list)
395 unmodified lines39639739839940040140240340423 unmodified lines428429430431432433434435436437438439440395 unmodified linesif headings:session["headings"] = headingspages: List[dict] = []selected_photo_ids: List[str] = []for item in items:company_logo = (general.get("client logo image name")or general.get("client logo")23 unmodified linesfor photo_id in photo_ids:if photo_id not in selected_photo_ids:selected_photo_ids.append(photo_id)pages.append({"items": [], "template": template, "photo_ids": photo_ids})if pages:session["pages"] = pagessession["page_count"] = len(pages)if selected_photo_ids:session["selected_photo_ids"] = selected_photo_idsstore.update_session(session)return session395 unmodified lines39639739839940040140240340423 unmodified lines428429430431432433434435436437438439440395 unmodified linesif headings:session["headings"] = headingssections: List[dict] = []selected_photo_ids: List[str] = []for idx, item in enumerate(items):company_logo = (general.get("client logo image name")or general.get("client logo")23 unmodified linesfor photo_id in photo_ids:if photo_id not in selected_photo_ids:selected_photo_ids.append(photo_id)page = {"items": [], "template": template, "photo_ids": photo_ids}title = item.get("reference") or item.get("area") or f"Section {idx + 1}"sections.append({"id": None, "title": title, "pages": [page]})if sections:if selected_photo_ids:session["selected_photo_ids"] = selected_photo_idsstore.set_sections(session, sections)return session
1 unmodified line234567122 unmodified lines1301311321331341351361371381391 unmodified lineimport mathfrom pathlib import Pathfrom typing import Iterable, List, Optionalfrom reportlab.lib import colors122 unmodified linesdef _badge_style(value: str, scale: dict) -> tuple[str, colors.Color, colors.Color]:key = (value or "").strip().upper()tone = scale.get(key)if not tone:return (value or "-"), colors.HexColor("#f9fafb"), colors.HexColor("#374151")return f"{key} - {tone['label']}", tone["bg"], tone["text"]1 unmodified line2345678122 unmodified lines1311321331341351361371381391401411421431441 unmodified lineimport mathfrom pathlib import Pathimport refrom typing import Iterable, List, Optionalfrom reportlab.lib import colors122 unmodified linesdef _badge_style(value: str, scale: dict) -> tuple[str, colors.Color, colors.Color]:raw = (value or "").strip()key = raw.upper()match = re.match(r"^([0-9]|[XM])", key)if match:key = match.group(1)tone = scale.get(key)if not tone:return (raw or "-"), colors.HexColor("#f9fafb"), colors.HexColor("#374151")return f"{key} - {tone['label']}", tone["bg"], tone["text"]
90 unmodified lines919293949596979843 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516690 unmodified lines"notes": notes,"uploads": {"photos": [], "documents": [], "data_files": []},"selected_photo_ids": [],"page_count": 6,"pages": [],}self._save_session(session)return session43 unmodified linesdef set_pages(self, session: dict, pages: List[dict]) -> dict:if not pages:pages = [{"items": []}]session["pages"] = pagessession["page_count"] = len(pages)self.update_session(session)return sessiondef ensure_pages(self, session: dict) -> List[dict]:pages = session.get("pages") or []if pages:if session.get("page_count") != len(pages):session["page_count"] = len(pages)self.update_session(session)return pagesselected_count = len(session.get("selected_photo_ids") or [])photo_count = len(session.get("uploads", {}).get("photos", []) or [])count = selected_count or photo_count or session.get("page_count", 1) or 1pages = [{"items": []} for _ in range(count)]session["pages"] = pagesself.update_session(session)return pagesdef save_upload(self, session_id: str, upload: UploadFile) -> StoredFile:filename = _safe_name(upload.filename or "upload")90 unmodified lines91929394959697989943 unmodified lines14314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022190 unmodified lines"notes": notes,"uploads": {"photos": [], "documents": [], "data_files": []},"selected_photo_ids": [],"page_count": 0,"pages": [],"jobsheet_sections": [],}self._save_session(session)return session43 unmodified linesdef set_pages(self, session: dict, pages: List[dict]) -> dict:if not pages:pages = [{"items": []}]# Legacy compatibility: store as a single section.session["jobsheet_sections"] = [{"id": uuid4().hex, "title": "Section 1", "pages": pages}]session["pages"] = []session["page_count"] = len(pages)self.update_session(session)return sessiondef ensure_pages(self, session: dict) -> List[dict]:# Legacy compatibility: flatten sections to pages.sections = self.ensure_sections(session)pages: List[dict] = []for section in sections:pages.extend(section.get("pages") or [])session["page_count"] = len(pages)return pagesdef set_sections(self, session: dict, sections: List[dict]) -> dict:normalized: List[dict] = []for section in sections or []:if hasattr(section, "model_dump"):section = section.model_dump()elif hasattr(section, "dict"):section = section.dict()pages = section.get("pages") or []if pages:normalized_pages = []for page in pages:if hasattr(page, "model_dump"):normalized_pages.append(page.model_dump())elif hasattr(page, "dict"):normalized_pages.append(page.dict())else:normalized_pages.append(page)pages = normalized_pagesnormalized.append({"id": section.get("id") or uuid4().hex,"title": section.get("title") or "Section","pages": pages if pages else [{"items": []}],})if not normalized:normalized = [{"id": uuid4().hex, "title": "Section 1", "pages": [{"items": []}]}]session["jobsheet_sections"] = normalizedsession["pages"] = []session["page_count"] = sum(len(section.get("pages") or []) for section in normalized)self.update_session(session)return sessiondef ensure_sections(self, session: dict) -> List[dict]:sections = session.get("jobsheet_sections") or []if sections:session["page_count"] = sum(len(section.get("pages") or []) for section in sections)self.update_session(session)return sectionspages = session.get("pages") or []if not pages:selected_count = len(session.get("selected_photo_ids") or [])photo_count = len(session.get("uploads", {}).get("photos", []) or [])count = selected_count or photo_count or session.get("page_count", 1) or 1pages = [{"items": []} for _ in range(count)]sections = [{"id": uuid4().hex, "title": "Section 1", "pages": pages}]session["jobsheet_sections"] = sectionssession["pages"] = []session["page_count"] = len(pages)self.update_session(session)return sectionsdef save_upload(self, session_id: str, upload: UploadFile) -> StoredFile:filename = _safe_name(upload.filename or "upload")
frontend/src/App.tsx+2
frontend/src/components/InfoMenu.tsxAdded+46
frontend/src/components/JobSheetTemplate.tsx+139-18
frontend/src/components/ReportPageCanvas.tsx+18-21
frontend/src/components/report-editor.js+309-57
frontend/src/index.css+4
frontend/src/lib/sections.tsAdded+165
frontend/src/pages/EditLayoutsPage.tsx+200-102
frontend/src/pages/EditReportPage.tsx+20-12
frontend/src/pages/ExportPage.tsx+39-23
frontend/src/pages/InputDataPage.tsx+316-135
frontend/src/pages/RatingsInfoPage.tsxAdded+294
frontend/src/pages/ReportViewerPage.tsx+24-11
frontend/src/types/session.ts+13
server/app/api/routes/sessions.py+38-1
server/app/api/schemas.py+15
server/app/services/data_import.py+7-7
server/app/services/pdf_reportlab.py+7-2
server/app/services/session_store.py+68-13