Spaces:
Sleeping
Sleeping
Merge branch 'dev'
Browse filesFiles changed (7)
- frontend/src/components/JobSheetTemplate.tsx+14-14
- frontend/src/components/PdfPreviewPanel.tsxAdded+1
- frontend/src/components/report-editor.js+29-29
- frontend/src/pages/EditReportPage.tsx+3-1
- server/app/services/pdf_export.py+17-34
- server/app/services/pdf_reportlab.py+15-15
- server/app/services/session_store.py+26
35 unmodified lines363738394041424344454647484950515253545556575859606162636465666768697071722 unmodified lines757677787980818283848586878889909192939495969798991001011021031041055 unmodified lines1111121131141151161172 unmodified lines12012112212312412512612712812913013135 unmodified linesconst CATEGORY_SCALE: Record<string, RatingTone> = {"0": {label: "100% Original Strength",bg: "bg-green-100",text: "text-green-800",border: "border-green-200",},"1": {label: "100% Original Strength",bg: "bg-green-200",text: "text-green-800",border: "border-green-200",},"2": {label: "95-100% Original Strength",bg: "bg-yellow-100",text: "text-yellow-800",border: "border-yellow-200",},"3": {label: "75-95% Original Strength",bg: "bg-yellow-200",text: "text-yellow-800",border: "border-yellow-200",},"4": {label: "50-75% Original Strength",bg: "bg-orange-200",text: "text-orange-800",border: "border-orange-200",},"5": {label: "<50% Original Strength",bg: "bg-red-200",text: "text-red-800",border: "border-red-200",2 unmodified linesconst 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",5 unmodified linesif (!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>) {2 unmodified linesconst 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}`,};}35 unmodified lines363738394041424344454647484950515253545556575859606162636465666768697071722 unmodified lines757677787980818283848586878889909192939495969798991001011021031041055 unmodified lines1111121131141151161172 unmodified lines12012112212312412512612712812913013135 unmodified linesconst CATEGORY_SCALE: Record<string, RatingTone> = {"0": {label: "(100% Original Strength)",bg: "bg-green-100",text: "text-green-800",border: "border-green-200",},"1": {label: "(100% Original Strength)",bg: "bg-green-200",text: "text-green-800",border: "border-green-200",},"2": {label: "(95-100% Original Strength)",bg: "bg-yellow-100",text: "text-yellow-800",border: "border-yellow-200",},"3": {label: "(75-95% Original Strength)",bg: "bg-yellow-200",text: "text-yellow-800",border: "border-yellow-200",},"4": {label: "(50-75% Original Strength)",bg: "bg-orange-200",text: "text-orange-800",border: "border-orange-200",},"5": {label: "(<50% Original Strength)",bg: "bg-red-200",text: "text-red-800",border: "border-red-200",2 unmodified linesconst 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",5 unmodified linesif (!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>) {2 unmodified linesconst 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}`,};}
1
1 unmodified line234567891011121314151617181920217 unmodified lines2930313233343536373839404142991 unmodified lines10341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062309 unmodified lines13721373137413751376137713781379138013811382138313841385138613871 unmodified lineimport * as feather from "feather-icons";const CATEGORY_SCALE = {"0": { label: "100% Original Strength", className: "bg-green-100 text-green-800 border-green-200" },"1": { label: "100% Original Strength", className: "bg-green-200 text-green-800 border-green-200" },"2": { label: "95-100% Original Strength", className: "bg-yellow-100 text-yellow-800 border-yellow-200" },"3": { label: "75-95% Original Strength", className: "bg-yellow-200 text-yellow-800 border-yellow-200" },"4": { label: "50-75% Original Strength", className: "bg-orange-200 text-orange-800 border-orange-200" },"5": { label: "<50% Original Strength", className: "bg-red-200 text-red-800 border-red-200" },};const PRIORITY_SCALE = {"1": { label: "Immediate", className: "bg-red-200 text-red-800 border-red-200" },"2": { label: "1 Year", className: "bg-orange-200 text-orange-800 border-orange-200" },"3": { label: "3 Years", className: "bg-green-200 text-green-800 border-green-200" },X: { label: "At Use", className: "bg-purple-200 text-purple-800 border-purple-200" },M: { label: "Monitor", className: "bg-blue-200 text-blue-800 border-blue-200" },};const MAX_PHOTOS_PRIMARY_PAGE = 2;7 unmodified linesfunction buildScaleBadge(value, scale) {const raw = String(value || "").trim();if (!raw) {return { text: "-", className: "bg-gray-50 text-gray-700 border-gray-200" };}const code = parseScaleCode(raw);const tone = scale[code];if (!tone) {return { text: raw, className: "bg-gray-50 text-gray-700 border-gray-200" };}return { text: `${code} - ${tone.label}`, className: tone.className };}class ReportEditor extends HTMLElement {constructor() {991 unmodified linesconst requiredAction = template.required_action || "";const categoryScale = {"0": { label: "Excellent (100%)", bg: "bg-green-100", text: "text-green-800", border: "border-green-200" },"1": { label: "Good (100%)", bg: "bg-green-200", text: "text-green-800", border: "border-green-200" },"2": { label: "Fair (95-100%)", bg: "bg-yellow-100", text: "text-yellow-800", border: "border-yellow-200" },"3": { label: "Unsatisfactory (75-95%)", bg: "bg-yellow-200", text: "text-yellow-800", border: "border-yellow-200" },"4": { label: "Poor (50-75%)", bg: "bg-orange-200", text: "text-orange-800", border: "border-orange-200" },"5": { label: "Severe (<50%)", 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 categoryOptions = ["0", "1", "2", "3", "4", "5"].map((key) => ({value: key,label: `${key} - ${categoryScale[key].label}`,}));const priorityOptions = ["1", "2", "3", "X", "M"].map((key) => ({value: key,label: `${key} - ${priorityScale[key].label}`,}));const variant =309 unmodified lines_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}`,};}1 unmodified line234567891011121314151617181920217 unmodified lines2930313233343536373839404142991 unmodified lines10341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062309 unmodified lines13721373137413751376137713781379138013811382138313841385138613871 unmodified lineimport * as feather from "feather-icons";const CATEGORY_SCALE = {"0": { label: "(100% Original Strength)", className: "bg-green-100 text-green-800 border-green-200" },"1": { label: "(100% Original Strength)", className: "bg-green-200 text-green-800 border-green-200" },"2": { label: "(95-100% Original Strength)", className: "bg-yellow-100 text-yellow-800 border-yellow-200" },"3": { label: "(75-95% Original Strength)", className: "bg-yellow-200 text-yellow-800 border-yellow-200" },"4": { label: "(50-75% Original Strength)", className: "bg-orange-200 text-orange-800 border-orange-200" },"5": { label: "(<50% Original Strength)", className: "bg-red-200 text-red-800 border-red-200" },};const PRIORITY_SCALE = {"1": { label: "(Immediate)", className: "bg-red-200 text-red-800 border-red-200" },"2": { label: "(1 Year)", className: "bg-orange-200 text-orange-800 border-orange-200" },"3": { label: "(3 Years)", className: "bg-green-200 text-green-800 border-green-200" },X: { label: "(At Use)", className: "bg-purple-200 text-purple-800 border-purple-200" },M: { label: "(Monitor)", className: "bg-blue-200 text-blue-800 border-blue-200" },};const MAX_PHOTOS_PRIMARY_PAGE = 2;7 unmodified linesfunction buildScaleBadge(value, scale) {const raw = String(value || "").trim();if (!raw) {return { text: "", className: "bg-gray-50 text-gray-700 border-gray-200" };}const code = parseScaleCode(raw);const tone = scale[code];if (!tone) {return { text: raw, className: "bg-gray-50 text-gray-700 border-gray-200" };}return { text: `${code} ${tone.label}`, className: tone.className };}class ReportEditor extends HTMLElement {constructor() {991 unmodified linesconst requiredAction = template.required_action || "";const categoryScale = {"0": { label: "(100% Original Strength)", bg: "bg-green-100", text: "text-green-800", border: "border-green-200" },"1": { label: "(100% Original Strength)", bg: "bg-green-200", text: "text-green-800", border: "border-green-200" },"2": { label: "(95-100% Original Strength)", bg: "bg-yellow-100", text: "text-yellow-800", border: "border-yellow-200" },"3": { label: "(75-95% Original Strength)", bg: "bg-yellow-200", text: "text-yellow-800", border: "border-yellow-200" },"4": { label: "(50-75% Original Strength)", bg: "bg-orange-200", text: "text-orange-800", border: "border-orange-200" },"5": { label: "(<50% Original Strength)", 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 categoryOptions = ["0", "1", "2", "3", "4", "5"].map((key) => ({value: key,label: `${key} ${categoryScale[key].label}`,}));const priorityOptions = ["1", "2", "3", "X", "M"].map((key) => ({value: key,label: `${key} ${priorityScale[key].label}`,}));const variant =309 unmodified lines_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}`,};}
95 unmodified lines9697989910010110295 unmodified linesvoid saveAndNavigate(`/report-viewer${sessionQuery}`);};editorEl.addEventListener("editor-closed", handleClose);return () => editorEl.removeEventListener("editor-closed", handleClose);}, [editorEl, saveAndNavigate, sessionQuery]);useEffect(() => {95 unmodified lines9697989910010110210310495 unmodified linesvoid saveAndNavigate(`/report-viewer${sessionQuery}`);};editorEl.addEventListener("editor-closed", handleClose);return () => {editorEl.removeEventListener("editor-closed", handleClose);};}, [editorEl, saveAndNavigate, sessionQuery]);useEffect(() => {
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859from __future__ import annotationsimport asyncioimport sysfrom pathlib import Pathfrom playwright.async_api import async_playwrightfrom ..core.config import get_settingsasync def _render_pdf_async(session_id: str, output_path: Path) -> Path:settings = get_settings()base_url = settings.frontend_base_url.rstrip("/")url = f"{base_url}/print/report?session={session_id}"output_path.parent.mkdir(parents=True, exist_ok=True)async with async_playwright() as playwright:browser = await playwright.chromium.launch(headless=True, args=["--no-sandbox"])context = await browser.new_context()page = await context.new_page()await page.goto(url, wait_until="networkidle", timeout=settings.pdf_timeout_ms)await page.wait_for_selector('[data-print-ready="true"]', timeout=settings.pdf_timeout_ms)await page.wait_for_function("document.fonts && document.fonts.ready")await page.wait_for_function("Array.from(document.images || []).every(img => img.complete)")await page.pdf(path=str(output_path),format="A4",print_background=True,prefer_css_page_size=True,margin={"top": "0mm", "right": "0mm", "bottom": "0mm", "left": "0mm"},)await context.close()await browser.close()return output_pathdef _run_with_proactor(coro: asyncio.Future) -> Path:if sys.platform.startswith("win"):loop = asyncio.ProactorEventLoop()try:asyncio.set_event_loop(loop)return loop.run_until_complete(coro)finally:loop.close()asyncio.set_event_loop(None)return asyncio.run(coro)def render_pdf_sync(session_id: str, output_path: Path) -> Path:return _run_with_proactor(_render_pdf_async(session_id, output_path))123456789101112131415161718192021222324252627282930313233343536373839404142from __future__ import annotationsfrom pathlib import Pathfrom playwright.sync_api import sync_playwrightfrom ..core.config import get_settingsdef render_pdf(session_id: str, output_path: Path) -> Path:settings = get_settings()base_url = settings.frontend_base_url.rstrip("/")url = f"{base_url}/print/report?session={session_id}"output_path.parent.mkdir(parents=True, exist_ok=True)with sync_playwright() as playwright:browser = playwright.chromium.launch(headless=True, args=["--no-sandbox"])context = browser.new_context()page = context.new_page()page.goto(url, wait_until="networkidle", timeout=settings.pdf_timeout_ms)page.wait_for_selector('[data-print-ready="true"]',timeout=settings.pdf_timeout_ms,)page.wait_for_function("document.fonts && document.fonts.ready")page.wait_for_function("Array.from(document.images || []).every(img => img.complete)")page.pdf(path=str(output_path),format="A4",print_background=True,prefer_css_page_size=True,margin={"top": "10mm", "right": "10mm", "bottom": "10mm", "left": "10mm"},)context.close()browser.close()return output_path
184 unmodified lines185186187188189190191192386 unmodified lines57958058158258358458558658758858959059159259359459559659764 unmodified lines66266366466566666766829 unmodified lines698699700701702703704184 unmodified lineskey = 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"]def _resolve_logo_path(store: SessionStore, session: dict, raw: str) -> Optional[Path]:386 unmodified linescategory = _safe_text(template.get("category"))priority = _safe_text(template.get("priority"))cat_scale = {"0": {"label": "100% Original Strength", "bg": green_100, "text": colors.HexColor("#166534")},"1": {"label": "100% Original Strength", "bg": green_200, "text": colors.HexColor("#166534")},"2": {"label": "95-100% Original Strength", "bg": yellow_100, "text": colors.HexColor("#854d0e")},"3": {"label": "75-95% Original Strength", "bg": yellow_200, "text": colors.HexColor("#854d0e")},"4": {"label": "50-75% Original Strength", "bg": orange_200, "text": colors.HexColor("#9a3412")},"5": {"label": "<50% Original Strength", "bg": red_200, "text": colors.HexColor("#991b1b")},}pr_scale = {"1": {"label": "Immediate", "bg": red_200, "text": colors.HexColor("#991b1b")},"2": {"label": "1 Year", "bg": orange_200, "text": colors.HexColor("#9a3412")},"3": {"label": "3 Years", "bg": green_200, "text": colors.HexColor("#166534")},"X": {"label": "At Use", "bg": purple_200, "text": purple_800},"M": {"label": "Monitor", "bg": blue_200, "text": blue_900},}cat_text, cat_bg, cat_text_color = _badge_style(category, cat_scale)pr_text, pr_bg, pr_text_color = _badge_style(priority, pr_scale)64 unmodified linespdf.setStrokeColor(gray_200)cond_lines = _wrap_lines(pdf,condition or "-",width - 2 * margin - 4 * mm,4,"Helvetica",29 unmodified linespdf.setStrokeColor(gray_200)action_lines = _wrap_lines(pdf,action or "-",width - 2 * margin - 4 * mm,4,"Helvetica",184 unmodified lines185186187188189190191192386 unmodified lines57958058158258358458558658758858959059159259359459559659764 unmodified lines66266366466566666766829 unmodified lines698699700701702703704184 unmodified lineskey = 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"]def _resolve_logo_path(store: SessionStore, session: dict, raw: str) -> Optional[Path]:386 unmodified linescategory = _safe_text(template.get("category"))priority = _safe_text(template.get("priority"))cat_scale = {"0": {"label": "(100% Original Strength)", "bg": green_100, "text": colors.HexColor("#166534")},"1": {"label": "(100% Original Strength)", "bg": green_200, "text": colors.HexColor("#166534")},"2": {"label": "(95-100% Original Strength)", "bg": yellow_100, "text": colors.HexColor("#854d0e")},"3": {"label": "(75-95% Original Strength)", "bg": yellow_200, "text": colors.HexColor("#854d0e")},"4": {"label": "(50-75% Original Strength)", "bg": orange_200, "text": colors.HexColor("#9a3412")},"5": {"label": "(<50% Original Strength)", "bg": red_200, "text": colors.HexColor("#991b1b")},}pr_scale = {"1": {"label": "(Immediate)", "bg": red_200, "text": colors.HexColor("#991b1b")},"2": {"label": "(1 Year)", "bg": orange_200, "text": colors.HexColor("#9a3412")},"3": {"label": "(3 Years)", "bg": green_200, "text": colors.HexColor("#166534")},"X": {"label": "(At Use)", "bg": purple_200, "text": purple_800},"M": {"label": "(Monitor)", "bg": blue_200, "text": blue_900},}cat_text, cat_bg, cat_text_color = _badge_style(category, cat_scale)pr_text, pr_bg, pr_text_color = _badge_style(priority, pr_scale)64 unmodified linespdf.setStrokeColor(gray_200)cond_lines = _wrap_lines(pdf,condition or "",width - 2 * margin - 4 * mm,4,"Helvetica",29 unmodified linespdf.setStrokeColor(gray_200)action_lines = _wrap_lines(pdf,action or "",width - 2 * margin - 4 * mm,4,"Helvetica",
10 unmodified lines1112131415161 unmodified line18192021222358 unmodified lines828384858687497 unmodified lines58558658758858959010 unmodified linesfrom uuid import uuid4from fastapi import UploadFilefrom ..core.config import get_settings1 unmodified lineIMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}DOC_EXTS = {".pdf", ".doc", ".docx"}DATA_EXTS = {".csv", ".xls", ".xlsx"}SESSION_ID_RE = re.compile(r"^[0-9a-f]{32}$")BUILTIN_PAGE_TEMPLATES = [{58 unmodified linesreturn "documents"def _validate_session_id(session_id: str) -> str:if not session_id:raise ValueError("Invalid session id.")497 unmodified lineshandle.write(chunk)category = _category_for(filename)return StoredFile(id=file_id,name=filename,10 unmodified lines111213141516171 unmodified line1920212223242558 unmodified lines84858687888990919293949596979899100101102103104105106107108109110497 unmodified lines60860961061161261361461561610 unmodified linesfrom uuid import uuid4from fastapi import UploadFilefrom PIL import Image, ImageOps, UnidentifiedImageErrorfrom ..core.config import get_settings1 unmodified lineIMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}DOC_EXTS = {".pdf", ".doc", ".docx"}DATA_EXTS = {".csv", ".xls", ".xlsx"}EXIF_NORMALIZE_EXTS = {".jpg", ".jpeg", ".png", ".webp"}SESSION_ID_RE = re.compile(r"^[0-9a-f]{32}$")BUILTIN_PAGE_TEMPLATES = [{58 unmodified linesreturn "documents"def _normalize_uploaded_photo(path: Path) -> None:ext = path.suffix.lower()if ext not in EXIF_NORMALIZE_EXTS:returntry:with Image.open(path) as image:normalized = ImageOps.exif_transpose(image)format_name = image.formatif normalized.mode in ("RGBA", "LA", "P") and format_name in {"JPEG", "JPG"}:normalized = normalized.convert("RGB")save_kwargs = {"exif": b""}if format_name in {"JPEG", "JPG"}:save_kwargs["quality"] = 95save_kwargs["optimize"] = Truenormalized.save(path, format=format_name, **save_kwargs)except (UnidentifiedImageError, OSError, ValueError, TypeError):# Keep original bytes if the file cannot be decoded by Pillow.returndef _validate_session_id(session_id: str) -> str:if not session_id:raise ValueError("Invalid session id.")497 unmodified lineshandle.write(chunk)category = _category_for(filename)if category == "photos":_normalize_uploaded_photo(dest)size = dest.stat().st_sizereturn StoredFile(id=file_id,name=filename,
frontend/src/components/JobSheetTemplate.tsx+14-14
frontend/src/components/PdfPreviewPanel.tsxAdded+1
frontend/src/components/report-editor.js+29-29
frontend/src/pages/EditReportPage.tsx+3-1
server/app/services/pdf_export.py+17-34
server/app/services/pdf_reportlab.py+15-15
server/app/services/session_store.py+26