From 6062b54cf06ce7f189ed96a3ac519ab4cf23706c Mon Sep 17 00:00:00 2001 From: Anoushk <186037197+Current-cmd@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:50:31 +0100 Subject: [PATCH] mobile: fixes from 5-agent review - queue: 15 min XHR timeout, auto-retry on reconnect/app start/every 30 s, ask the server before resending a recovered job, keep all unfinished jobs, no storage writes per progress tick, steps never move backwards on event replay, no removal while uploading, per-job token - api: websocket reconnect timer cleared on close, spi/forecast may be null - Today: no crash when SPI is null, reached states not tappable, spelled-out KPI labels, safe-area bottom padding, accessibility labels - Capture: works offline with cached zones (alert links to settings), try/catch around camera/mic/send, 'Senden an ', not-yet-sent banner, audio/mp4, duration read before stop - Report: removed the fake Freigeben button, PDF is the main action; Scan: encoded ids in URLs - Settings: QR scan handled once and confirmed before switching server - App: report/overview failures no longer mark the app offline, Android back button, toast live region - UI: 44 pt default and icon buttons, darker success/info badge text --- mobile/App.tsx | 36 +++++++--- mobile/components/ui/badge.tsx | 4 +- mobile/components/ui/button.tsx | 4 +- mobile/src/api.ts | 26 +++++--- mobile/src/queue.ts | 115 ++++++++++++++++++++++++-------- mobile/src/screens/Capture.tsx | 78 ++++++++++++++-------- mobile/src/screens/Report.tsx | 13 ++-- mobile/src/screens/Scan.tsx | 2 +- mobile/src/screens/Settings.tsx | 15 ++++- mobile/src/screens/Today.tsx | 22 +++--- 10 files changed, 219 insertions(+), 96 deletions(-) diff --git a/mobile/App.tsx b/mobile/App.tsx index 5aeff30..6dae0ec 100644 --- a/mobile/App.tsx +++ b/mobile/App.tsx @@ -8,7 +8,8 @@ import { PortalHost } from "@rn-primitives/portal"; import { StatusBar } from "expo-status-bar"; import { CircleDot, FileText, PlusCircle, ScanLine, Settings as Gear, X } from "lucide-react-native"; import React, { useCallback, useEffect, useRef, useState } from "react"; -import { Animated, Pressable, View } from "react-native"; +import AsyncStorage from "@react-native-async-storage/async-storage"; +import { Animated, BackHandler, Pressable, View } from "react-native"; import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; import { Health, Overview, Report as ReportData, Zone, getJson, listen, loadSettings } from "./src/api"; import { Job, initQueue, setStep, subscribe } from "./src/queue"; @@ -19,6 +20,7 @@ import { Settings } from "./src/screens/Settings"; import { Today } from "./src/screens/Today"; type Tab = "today" | "capture" | "scan" | "report"; +const ZONES_KEY = "tw.zones"; const TABS: [Tab, any, string][] = [["today", CircleDot, "Heute"], ["capture", PlusCircle, "Erfassen"], ["scan", ScanLine, "Scan"], ["report", FileText, "Bericht"]]; export default function App() { @@ -46,10 +48,13 @@ export default function App() { const load = useCallback(async () => { setRefreshing(true); try { - const [h, z, o, r] = await Promise.all([ - getJson("/health"), getJson("/zones"), getJson("/api/overview"), getJson("/api/v2/report"), - ]); - setHealth(h); setZones(z); setOverview(o); setReport(r); setError(null); + // health and zones decide "connected"; a failing report or overview must not take the rest down + const [h, z] = await Promise.all([getJson("/health"), getJson("/zones")]); + setHealth(h); setZones(z); setError(null); + AsyncStorage.setItem(ZONES_KEY, JSON.stringify(z)); // so recording works offline later + const [o, r] = await Promise.allSettled([getJson("/api/overview"), getJson("/api/v2/report")]); + if (o.status === "fulfilled") setOverview(o.value); + if (r.status === "fulfilled") setReport(r.value); } catch (e: any) { setError(e.message); setHealth(null); } finally { @@ -58,7 +63,12 @@ export default function App() { }, []); useEffect(() => { - (async () => { await loadSettings(); setReady(true); await initQueue(); load(); })(); + (async () => { + await loadSettings(); + const cached = await AsyncStorage.getItem(ZONES_KEY); + if (cached) setZones(JSON.parse(cached)); + setReady(true); await initQueue(); load(); + })(); return subscribe(setJobs); }, [load]); @@ -73,6 +83,16 @@ export default function App() { return () => { stop(); if (t) clearTimeout(t); }; }, [ready, health?.project, load]); + // Android back: close settings, else go to the capture tab, else leave the app + useEffect(() => { + const sub = BackHandler.addEventListener("hardwareBackPress", () => { + if (showSettings) { setShowSettings(false); return true; } + if (tab !== "capture") { setTab("capture"); return true; } + return false; + }); + return () => sub.remove(); + }, [showSettings, tab]); + const names: Record = {}; (overview?.zones ?? []).forEach((z) => z.elements.forEach((e) => (names[e.id] = e.name))); const pending = jobs.filter((j) => j.status !== "done" && j.status !== "error").length; @@ -100,12 +120,12 @@ export default function App() { {!ready ? null : showSettings ? setShowSettings(false)} onSaved={load} /> : tab === "today" ? - : tab === "capture" ? + : tab === "capture" ? setShowSettings(true)} /> : tab === "scan" ? : } - + {msg && ( {msg.text} diff --git a/mobile/components/ui/badge.tsx b/mobile/components/ui/badge.tsx index 1afdd1a..bb5b8ae 100644 --- a/mobile/components/ui/badge.tsx +++ b/mobile/components/ui/badge.tsx @@ -46,9 +46,9 @@ const badgeTextVariants = cva('text-xs font-medium', { secondary: 'text-secondary-foreground', destructive: 'text-white', outline: 'text-foreground', - success: 'text-success', + success: 'text-green-800', warning: 'text-warning-foreground', - info: 'text-info', + info: 'text-blue-800', }, }, defaultVariants: { diff --git a/mobile/components/ui/button.tsx b/mobile/components/ui/button.tsx index 646bf4b..05ae4c3 100644 --- a/mobile/components/ui/button.tsx +++ b/mobile/components/ui/button.tsx @@ -40,10 +40,10 @@ const buttonVariants = cva( link: '', }, size: { - default: cn('h-10 px-4 py-2 sm:h-9', Platform.select({ web: 'has-[>svg]:px-3' })), + default: cn('h-11 px-4 py-2', Platform.select({ web: 'has-[>svg]:px-3' })), // Tagwerk: 44 pt minimum sm: cn('h-9 gap-1.5 rounded-md px-3 sm:h-8', Platform.select({ web: 'has-[>svg]:px-2.5' })), lg: cn('h-11 rounded-md px-6 sm:h-10', Platform.select({ web: 'has-[>svg]:px-4' })), - icon: 'h-10 w-10 sm:h-9 sm:w-9', + icon: 'h-11 w-11', // Tagwerk: glove-friendly targets on site xl: 'h-14 rounded-lg px-6', hero: 'h-20 rounded-xl px-6', diff --git a/mobile/src/api.ts b/mobile/src/api.ts index 28a58ab..c7af29e 100644 --- a/mobile/src/api.ts +++ b/mobile/src/api.ts @@ -31,7 +31,7 @@ export function parseConnect(text: string): Settings | null { return /^https?:\/\//.test(t) ? { server: t, token: "" } : null; } -const headers = (): Record => (current.token ? { Authorization: `Bearer ${current.token}` } : {}); +const headers = (token = current.token): Record => (token ? { Authorization: `Bearer ${token}` } : {}); /** A page URL to open in the browser (pages read the token from `?token=`). */ export function pageUrl(path: string): string { @@ -39,16 +39,16 @@ export function pageUrl(path: string): string { return current.token ? `${u}${u.includes("?") ? "&" : "?"}token=${encodeURIComponent(current.token)}` : u; } -export async function getJson(path: string, timeoutMs = 10000, server = current.server): Promise { +export async function getJson(path: string, timeoutMs = 10000, server = current.server, token = current.token): Promise { const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), timeoutMs); try { - const r = await fetch(`${server}${path}`, { headers: headers(), signal: ctl.signal }); + const r = await fetch(`${server}${path}`, { headers: headers(token), signal: ctl.signal }); const body = await r.json().catch(() => ({})); - if (!r.ok) throw new Error(body.detail || `HTTP ${r.status}`); + if (!r.ok) throw Object.assign(new Error(body.detail || `HTTP ${r.status}`), { status: r.status }); return body as T; } catch (e: any) { - if (e?.name === "AbortError") throw new Error("Server antwortet nicht (Tailscale an?)"); + if (e?.name === "AbortError") throw new Error("Keine Verbindung: Server antwortet nicht (Tailscale an?)"); throw e; } finally { clearTimeout(timer); @@ -70,7 +70,8 @@ export type MediaFile = { uri: string; name: string; type: string }; * server starts processing; the promise resolves with the server's answer. */ export async function postForm( path: string, fields: Record, files: MediaFile[], - onProgress?: (fraction: number) => void, onUploaded?: () => void, server = current.server, + onProgress?: (fraction: number) => void, onUploaded?: () => void, server = current.server, token = current.token, + timeoutMs = 15 * 60 * 1000, // upload + GPU processing of a long video; a dead connection must not hang the queue ): Promise { const form = new FormData(); for (const [k, v] of Object.entries(fields)) if (v !== undefined && v !== "") form.append(k, v); @@ -81,7 +82,8 @@ export async function postForm( return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("POST", `${server}${path}`); - for (const [k, v] of Object.entries(headers())) xhr.setRequestHeader(k, v); + for (const [k, v] of Object.entries(headers(token))) xhr.setRequestHeader(k, v); + xhr.timeout = timeoutMs; xhr.upload.onprogress = (e) => e.lengthComputable && onProgress?.(e.loaded / e.total); xhr.upload.onload = () => { onProgress?.(1); onUploaded?.(); }; xhr.onload = () => { @@ -91,6 +93,8 @@ export async function postForm( else reject(new Error(body.detail || `HTTP ${xhr.status}`)); }; xhr.onerror = () => reject(new Error("Keine Verbindung zum Server")); + xhr.ontimeout = () => reject(new Error("Keine Verbindung: Zeitüberschreitung")); + xhr.onabort = () => reject(new Error("Keine Verbindung: abgebrochen")); xhr.send(form); }); } @@ -98,15 +102,17 @@ export async function postForm( /** Live pipeline steps from the API's websocket (`/events`). Returns a function that closes it. */ export function listen(onMessage: (m: any) => void): () => void { let ws: WebSocket | null = null, closed = false, backoff = 1000; + let timer: ReturnType | null = null; const open = () => { + if (closed) return; const base = current.server.replace(/^http/, "ws"); ws = new WebSocket(`${base}/events${current.token ? `?token=${encodeURIComponent(current.token)}` : ""}`); ws.onmessage = (ev) => { try { onMessage(JSON.parse(String(ev.data))); } catch { /* ignore */ } }; ws.onopen = () => { backoff = 1000; }; - ws.onclose = () => { if (!closed) setTimeout(open, backoff); backoff = Math.min(backoff * 2, 15000); }; + ws.onclose = () => { if (!closed) timer = setTimeout(open, backoff); backoff = Math.min(backoff * 2, 15000); }; }; open(); - return () => { closed = true; ws?.close(); }; + return () => { closed = true; if (timer) clearTimeout(timer); ws?.close(); }; } // ---------- response shapes (only the fields the app reads) ---------- @@ -120,7 +126,7 @@ export type Activity = { export type Change = { element_id: string; action: string; state: string; pct?: number; quote?: string; evidence?: string; activity_id?: string }; export type Overview = { date: string; - kpi: { pct_actual: number; pct_planned: number; spi: number; delay_d: number; forecast_finish: string; open_defects?: number }; + kpi: { pct_actual: number; pct_planned: number; spi: number | null; delay_d: number; forecast_finish: string | null; open_defects?: number }; activities: Activity[]; zones: { zone_id: string; name: string; elements: Element[] }[]; proposals: { element_id: string; state: string; name?: string; quote?: string; capture_id?: string }[]; diff --git a/mobile/src/queue.ts b/mobile/src/queue.ts index e7da17c..15c74e3 100644 --- a/mobile/src/queue.ts +++ b/mobile/src/queue.ts @@ -2,23 +2,37 @@ // a job is resent with the same capture_id, and the server answers "exists" for one it already has. import AsyncStorage from "@react-native-async-storage/async-storage"; import { Directory, File, Paths } from "expo-file-system"; -import { Platform } from "react-native"; +import { AppState, Platform } from "react-native"; import { CaptureResult, MediaFile, getJson, postForm, settings } from "./api"; export type JobStatus = "waiting" | "uploading" | "processing" | "done" | "error"; export type Job = { - id: string; server: string; zone_id: string; zone_name: string; note?: string; kind: string; files: MediaFile[]; + id: string; server: string; token?: string; zone_id: string; zone_name: string; note?: string; kind: string; files: MediaFile[]; created: string; status: JobStatus; progress: number; step?: string; error?: string; result?: CaptureResult; + attempts?: number; recovered?: boolean; }; const KEY = "tw.jobs"; +const KEEP_DONE = 30; // finished jobs kept for the list; unfinished ones are never dropped +const STEPS = ["Hochgeladen", "normalized", "transcribed", "vision", "structured", "done", "sfm"]; let jobs: Job[] = []; let running = false; +let retryTimer: ReturnType | null = null; const subs = new Set<(j: Job[]) => void>(); +const isNetwork = (msg: string) => /Verbindung|Network|Tailscale/i.test(msg); const emit = () => { const copy = jobs.map((j) => ({ ...j })); subs.forEach((f) => f(copy)); }; -const persist = () => AsyncStorage.setItem(KEY, JSON.stringify(jobs.slice(0, 50))); -const patch = (id: string, p: Partial) => { jobs = jobs.map((j) => (j.id === id ? { ...j, ...p } : j)); emit(); persist(); }; +const persist = () => { + let done = 0; + const keep = jobs.filter((j) => j.status !== "done" || ++done <= KEEP_DONE); + jobs.filter((j) => !keep.includes(j)).forEach((j) => cleanup(j.id)); + jobs = keep; + return AsyncStorage.setItem(KEY, JSON.stringify(jobs)); +}; +/** `save: false` for progress ticks: re-render, but do not rewrite storage hundreds of times per upload. */ +const patch = (id: string, p: Partial, save = true) => { + jobs = jobs.map((j) => (j.id === id ? { ...j, ...p } : j)); emit(); if (save) persist(); +}; export function subscribe(f: (j: Job[]) => void): () => void { subs.add(f); f(jobs.map((j) => ({ ...j }))); @@ -27,69 +41,112 @@ export function subscribe(f: (j: Job[]) => void): () => void { export async function initQueue(): Promise { const raw = await AsyncStorage.getItem(KEY); - // a job cut off mid-upload or mid-processing goes back to waiting and is resent (idempotent) - jobs = raw ? (JSON.parse(raw) as Job[]).map((j) => (j.status === "uploading" || j.status === "processing" ? { ...j, status: "waiting" } : j)) : []; + // a job cut off mid-upload or mid-processing goes back to waiting; before resending, the queue asks the server + // whether it already has it (re-uploading while the first run is still processing would overwrite its files) + jobs = raw ? (JSON.parse(raw) as Job[]).map((j) => (j.status === "uploading" || j.status === "processing" + ? { ...j, status: "waiting", recovered: true } : j)) : []; emit(); - run(); + // back from the background (signal may be back too): try again + AppState.addEventListener("change", (s) => { if (s === "active") kick(); }); + kick(); // also resends jobs that failed for lack of connection last time } export const newId = () => `cap-m-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; /** Copy the picked files out of the picker's cache (Android may clear it) and queue the job. */ -export async function enqueue(j: Omit): Promise { +export async function enqueue(j: Omit): Promise { let files = j.files; if (Platform.OS !== "web") { const dir = new Directory(Paths.document, "captures", j.id); - if (!dir.exists) dir.create({ intermediates: true }); - files = await Promise.all(j.files.map(async (f) => { - const dest = new File(dir, f.name); - if (!dest.exists) await new File(f.uri).copy(dest); - return { ...f, uri: dest.uri }; - })); + try { + if (!dir.exists) dir.create({ intermediates: true }); + files = await Promise.all(j.files.map(async (f) => { + const dest = new File(dir, f.name); + if (!dest.exists) await new File(f.uri).copy(dest); + return { ...f, uri: dest.uri }; + })); + } catch (e) { + cleanup(j.id); + throw e; + } } - jobs = [{ ...j, server: settings().server, files, status: "waiting", progress: 0, created: new Date().toISOString() }, ...jobs]; + const { server, token } = settings(); + jobs = [{ ...j, server, token, files, status: "waiting", progress: 0, created: new Date().toISOString() }, ...jobs]; emit(); await persist(); run(); } -export function retry(id: string) { patch(id, { status: "waiting", error: undefined }); run(); } -export function remove(id: string) { jobs = jobs.filter((j) => j.id !== id); emit(); persist(); cleanup(id); } -export function setStep(id: string, step: string) { if (jobs.some((j) => j.id === id && j.status === "processing")) patch(id, { step }); } +export function retry(id: string) { patch(id, { status: "waiting", error: undefined, attempts: 0 }); run(); } +/** Only waiting or failed jobs can be removed: an upload in flight still reads the files. */ +export function remove(id: string) { + const j = jobs.find((x) => x.id === id); + if (!j || j.status === "uploading" || j.status === "processing") return; + jobs = jobs.filter((x) => x.id !== id); emit(); persist(); cleanup(id); +} +/** Live step from the websocket. The server replays old events on reconnect, so a step never moves backwards. */ +export function setStep(id: string, step: string) { + const j = jobs.find((x) => x.id === id && x.status === "processing"); + if (j && STEPS.indexOf(step) > STEPS.indexOf(j.step ?? "")) patch(id, { step }, false); +} +/** Resend jobs that failed for lack of connection (app back in front, or the timer). */ +export function kick() { + jobs.forEach((j) => { if (j.status === "error" && isNetwork(j.error ?? "")) patch(j.id, { status: "waiting" }); }); + run(); +} function cleanup(id: string) { if (Platform.OS === "web") return; try { const d = new Directory(Paths.document, "captures", id); if (d.exists) d.delete(); } catch { /* best effort */ } } +async function fetchExisting(job: Job): Promise { + try { + return summarize(await getJson(`/captures/${job.id}`, 10000, job.server, job.token ?? settings().token), job.id); + } catch (e: any) { + if (e?.status === 404) return null; + throw e; + } +} + async function run(): Promise { if (running) return; running = true; + let offline = false; try { for (;;) { const job = [...jobs].reverse().find((j) => j.status === "waiting"); // oldest first if (!job) break; patch(job.id, { status: "uploading", progress: 0, step: undefined }); try { - let res = await postForm( - "/captures", { zone_id: job.zone_id, capture_id: job.id, note: job.note, lang: "auto" }, job.files, - (p) => patch(job.id, { progress: p }), () => patch(job.id, { status: "processing", step: "Hochgeladen" }), - job.server, // the project it was recorded for, even if the app has switched server since - ); - if (res.status === "exists") res = summarize(await getJson(`/captures/${job.id}`, 10000, job.server), job.id); - patch(job.id, { status: "done", result: res, step: undefined }); + const token = job.token ?? settings().token; + let res = job.recovered ? await fetchExisting(job) : null; + if (!res) { + res = await postForm( + "/captures", { zone_id: job.zone_id, capture_id: job.id, note: job.note, lang: "auto" }, job.files, + (p) => patch(job.id, { progress: p }, false), () => patch(job.id, { status: "processing", step: "Hochgeladen" }), + job.server ?? settings().server, token, // the project it was recorded for, even if the app switched server since + ); + if (res.status === "exists") res = (await fetchExisting(job)) ?? res; + } + patch(job.id, { status: "done", result: res, step: undefined, recovered: false, error: undefined }); cleanup(job.id); } catch (e: any) { - patch(job.id, { status: "error", error: String(e?.message ?? e) }); - // no connection: stop here and let the user (or the next app start) retry - if (/Verbindung|Network/i.test(String(e?.message))) break; + const msg = String(e?.message ?? e); + // after a failed attempt the server may hold the capture already: ask first next time + patch(job.id, { status: "error", error: msg, recovered: true, attempts: (job.attempts ?? 0) + 1 }); + if (isNetwork(msg)) { offline = true; break; } // the other jobs would fail the same way } } } finally { running = false; } + if (offline) { + if (retryTimer) clearTimeout(retryTimer); + retryTimer = setTimeout(kick, 30000); // keep trying while the app is open + } } -/** GET /captures/{id} returns the raw pipeline result; bring it into the POST /captures shape. */ +/** GET /captures/{id}: the in-memory pipeline result, or after an API restart only the stored capture. */ function summarize(r: any, id: string): CaptureResult { if (r?.status === "processed") return r; const s = r?.structured ?? {}; diff --git a/mobile/src/screens/Capture.tsx b/mobile/src/screens/Capture.tsx index c4f07c3..fdc95ae 100644 --- a/mobile/src/screens/Capture.tsx +++ b/mobile/src/screens/Capture.tsx @@ -1,4 +1,5 @@ // "Erfassen": zone, then video with commentary / photo / voice note / typed note. Everything goes through the queue. +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Icon } from "@/components/ui/icon"; @@ -7,7 +8,7 @@ import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/utils"; import { RecordingPresets, requestRecordingPermissionsAsync, setAudioModeAsync, useAudioRecorder, useAudioRecorderState } from "expo-audio"; import * as ImagePicker from "expo-image-picker"; -import { Camera, Images, Mic, Send, Square, Video, X } from "lucide-react-native"; +import { Camera, Images, Mic, Send, Square, Video, WifiOff, X } from "lucide-react-native"; import React, { useState } from "react"; import { Pressable, ScrollView, View } from "react-native"; import { MediaFile, Zone } from "../api"; @@ -17,8 +18,9 @@ import { SectionLabel } from "../ui"; type Draft = MediaFile & { label: string; icon: any }; -export function Capture({ zones, jobs, names, toast }: { +export function Capture({ zones, jobs, names, toast, online, openSettings }: { zones: Zone[]; jobs: Job[]; names: Record; toast: (m: string, err?: boolean) => void; + online: boolean; openSettings: () => void; }) { const [zone, setZone] = useState(null); const [note, setNote] = useState(""); @@ -26,6 +28,7 @@ export function Capture({ zones, jobs, names, toast }: { const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY); const rec = useAudioRecorderState(recorder, 250); const zoneId = zone && zones.some((z) => z.id === zone) ? zone : zones[0]?.id ?? null; + const zoneName = zones.find((z) => z.id === zoneId)?.name.split(" / ")[0] ?? zoneId ?? ""; const add = (assets: ImagePicker.ImagePickerAsset[]) => setDraft((d) => [...d, ...assets.map((a, i) => { const video = a.type === "video"; @@ -34,28 +37,37 @@ export function Capture({ zones, jobs, names, toast }: { label: video ? `Video${a.duration ? ` · ${Math.round(a.duration / 1000)} s` : ""}` : "Foto", icon: video ? Video : Camera }; })]); + const fail = (what: string, e: any) => toast(`${what}: ${e?.message ?? e}`, true); const shoot = async (kind: "videos" | "images") => { - const perm = await ImagePicker.requestCameraPermissionsAsync(); - if (!perm.granted) return toast("Kamera nicht erlaubt (Einstellungen)", true); - const r = await ImagePicker.launchCameraAsync({ mediaTypes: [kind], videoMaxDuration: 180, quality: 0.7 }); - if (!r.canceled) add(r.assets); + try { + const perm = await ImagePicker.requestCameraPermissionsAsync(); + if (!perm.granted) return toast("Kamera nicht erlaubt (Einstellungen)", true); + const r = await ImagePicker.launchCameraAsync({ mediaTypes: [kind], videoMaxDuration: 180, quality: 0.7 }); + if (!r.canceled) add(r.assets); + } catch (e) { fail("Kamera", e); } }; const gallery = async () => { - const r = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ["videos", "images"], allowsMultipleSelection: true, quality: 0.7 }); - if (!r.canceled) add(r.assets); + try { + const r = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ["videos", "images"], allowsMultipleSelection: true, quality: 0.7 }); + if (!r.canceled) add(r.assets); + } catch (e) { fail("Galerie", e); } }; const voice = async () => { - if (rec.isRecording) { - await recorder.stop(); - const uri = recorder.uri; - if (uri) setDraft((d) => [...d, { uri, type: "audio/m4a", name: `sprache_${Date.now()}.m4a`, label: `Sprachnotiz · ${Math.round(rec.durationMillis / 1000)} s`, icon: Mic }]); - return; - } - const perm = await requestRecordingPermissionsAsync(); - if (!perm.granted) return toast("Mikrofon nicht erlaubt (Einstellungen)", true); - await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true }); - await recorder.prepareToRecordAsync(); - recorder.record(); + try { + if (rec.isRecording) { + const secs = Math.round(rec.durationMillis / 1000); // read before stop resets it + await recorder.stop(); + await setAudioModeAsync({ allowsRecording: false, playsInSilentMode: true }); + const uri = recorder.uri; + if (uri) setDraft((d) => [...d, { uri, type: "audio/mp4", name: `sprache_${Date.now()}.m4a`, label: `Sprachnotiz · ${secs} s`, icon: Mic }]); + return; + } + const perm = await requestRecordingPermissionsAsync(); + if (!perm.granted) return toast("Mikrofon nicht erlaubt (Einstellungen)", true); + await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true }); + await recorder.prepareToRecordAsync(); + recorder.record(); + } catch (e) { fail("Mikrofon", e); } }; const send = async () => { @@ -63,20 +75,30 @@ export function Capture({ zones, jobs, names, toast }: { if (!draft.length && !note.trim()) return toast("Erst aufnehmen oder Notiz schreiben", true); const kind = draft.some((d) => d.type.startsWith("video")) ? "Video" : draft.some((d) => d.type.startsWith("image")) ? "Foto" : draft.length ? "Sprachnotiz" : "Notiz"; - await enqueue({ id: newId(), zone_id: zoneId, zone_name: zones.find((z) => z.id === zoneId)?.name.split(" / ")[0] ?? zoneId, - note: note.trim() || undefined, kind, files: draft.map(({ label, icon, ...f }) => f) }); + try { + await enqueue({ id: newId(), zone_id: zoneId, zone_name: zoneName, note: note.trim() || undefined, kind, + files: draft.map(({ label, icon, ...f }) => f) }); + } catch (e) { return fail("Speichern fehlgeschlagen", e); } setDraft([]); setNote(""); - toast("In der Warteschlange · wird gesendet"); + toast(online ? `Wird gesendet · ${zoneName}` : `Gespeichert · wird gesendet, sobald Netz da ist`); }; return ( - Zone + {!online && ( + + Kein Server erreichbar + {zones.length ? "Aufnehmen geht trotzdem: Aufnahmen warten und werden später gesendet." : "Einmal verbinden, damit die Zonen geladen sind."} + + + )} + Zone · gilt für diese Aufnahme {zones.map((z) => { const on = z.id === zoneId; return ( - setZone(z.id)} className={cn( + setZone(z.id)} accessibilityRole="radio" accessibilityState={{ selected: on }} + accessibilityLabel={`Zone ${z.name}`} className={cn( "h-11 justify-center rounded-full border px-4", on ? "border-primary bg-primary" : "border-border bg-background active:bg-accent")}> {z.name.split(" / ")[0]} @@ -107,13 +129,15 @@ export function Capture({ zones, jobs, names, toast }: { placeholder="Notiz (optional), z. B. „Estrich Saal fertig, 2 Mann krank“" /> {draft.length > 0 && ( - + + Noch nicht gesendet: unten auf „Senden“ tippen. {draft.map((d, i) => ( {d.label} - @@ -122,7 +146,7 @@ export function Capture({ zones, jobs, names, toast }: { )} {jobs.length > 0 && Gesendet} diff --git a/mobile/src/screens/Report.tsx b/mobile/src/screens/Report.tsx index 3ec72fc..9aa45ae 100644 --- a/mobile/src/screens/Report.tsx +++ b/mobile/src/screens/Report.tsx @@ -5,7 +5,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com import { Icon } from "@/components/ui/icon"; import { Text } from "@/components/ui/text"; import * as WebBrowser from "expo-web-browser"; -import { AlertTriangle, CheckCheck, FileText, LayoutDashboard, Thermometer, Users } from "lucide-react-native"; +import { AlertTriangle, FileText, LayoutDashboard, Thermometer, Users } from "lucide-react-native"; import React from "react"; import { RefreshControl, ScrollView, View } from "react-native"; import { Report as R, pageUrl } from "../api"; @@ -29,13 +29,14 @@ export function Report({ data, reload, refreshing, toast }: { {data.project.name} · aus {data.recordings.length} Aufnahme(n) geschrieben - - + + Prüfen und bei Fehlern per Sprachnotiz korrigieren. Freigabe durch die Bauleitung im Dashboard. +
diff --git a/mobile/src/screens/Scan.tsx b/mobile/src/screens/Scan.tsx index d4dadc2..f3ba214 100644 --- a/mobile/src/screens/Scan.tsx +++ b/mobile/src/screens/Scan.tsx @@ -45,7 +45,7 @@ export function Scan({ toast }: { toast: (m: string, err?: boolean) => void }) { const open3d = () => { const { server, token } = settings(); - WebBrowser.openBrowserAsync(`${server}/app/${token ? `?token=${encodeURIComponent(token)}` : ""}#/scan/${result!.scan_id}`); + WebBrowser.openBrowserAsync(`${server}/app/${token ? `?token=${encodeURIComponent(token)}` : ""}#/scan/${encodeURIComponent(result!.scan_id)}`); }; const groups: Record = {}; (result?.items ?? []).forEach((i) => (groups[i.category_de] ??= []).push(i)); diff --git a/mobile/src/screens/Settings.tsx b/mobile/src/screens/Settings.tsx index 3f06e7f..7cccf6d 100644 --- a/mobile/src/screens/Settings.tsx +++ b/mobile/src/screens/Settings.tsx @@ -8,8 +8,8 @@ import { Text } from "@/components/ui/text"; import { cn } from "@/lib/utils"; import { CameraView, useCameraPermissions } from "expo-camera"; import { CheckCircle2, Plug, QrCode, XCircle } from "lucide-react-native"; -import React, { useState } from "react"; -import { Modal, ScrollView, View } from "react-native"; +import React, { useRef, useState } from "react"; +import { Alert, Modal, ScrollView, View } from "react-native"; import { DEFAULT_SERVER, Health, getJson, parseConnect, saveSettings, settings } from "../api"; export function Settings({ onClose, onSaved }: { onClose: () => void; onSaved: () => void }) { @@ -19,6 +19,7 @@ export function Settings({ onClose, onSaved }: { onClose: () => void; onSaved: ( const [busy, setBusy] = useState(false); const [scanning, setScanning] = useState(false); const [perm, requestPerm] = useCameraPermissions(); + const handled = useRef(false); // onBarcodeScanned fires on every frame until the modal closes const test = async (srv = server, tok = token) => { setBusy(true); setStatus(null); @@ -39,6 +40,7 @@ export function Settings({ onClose, onSaved }: { onClose: () => void; onSaved: ( const scan = async () => { if (!perm?.granted && !(await requestPerm()).granted) return; + handled.current = false; setScanning(true); }; @@ -84,9 +86,16 @@ export function Settings({ onClose, onSaved }: { onClose: () => void; onSaved: ( { + if (handled.current) return; const c = parseConnect(data); if (!c) return; - setScanning(false); setServer(c.server); setToken(c.token); test(c.server, c.token); + handled.current = true; + setScanning(false); + // a QR code can point anywhere: recordings would go there, so the user confirms the address + Alert.alert("Mit diesem Server verbinden?", `${c.server}${c.token ? "\n(mit Token)" : ""}`, [ + { text: "Abbrechen", style: "cancel" }, + { text: "Verbinden", onPress: () => { setServer(c.server); setToken(c.token); test(c.server, c.token); } }, + ]); }} /> QR-Code vom Laptop scannen diff --git a/mobile/src/screens/Today.tsx b/mobile/src/screens/Today.tsx index 9638d8d..6331763 100644 --- a/mobile/src/screens/Today.tsx +++ b/mobile/src/screens/Today.tsx @@ -9,6 +9,7 @@ import { cn } from "@/lib/utils"; import { Check, Eye, WifiOff } from "lucide-react-native"; import React, { useState } from "react"; import { Modal, Pressable, RefreshControl, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { Element, Overview, postJson } from "../api"; import { Kpi, PlanBar, SectionLabel, de, pct } from "../ui"; @@ -20,6 +21,7 @@ export function Today({ data, error, reload, refreshing, toast }: { const [sheet, setSheet] = useState(null); const [busy, setBusy] = useState(false); const [allProps, setAllProps] = useState(false); + const insets = useSafeAreaInsets(); const els: Record = {}; (data?.zones ?? []).forEach((z) => z.elements.forEach((e) => (els[e.id] = { ...e, zone: z.name }))); @@ -54,8 +56,9 @@ export function Today({ data, error, reload, refreshing, toast }: { {k && ( - - 0 ? "destructive" : "success"} /> + + 0 ? "destructive" : "success"} /> )} @@ -98,7 +101,7 @@ export function Today({ data, error, reload, refreshing, toast }: { {!!a.cause && (a.delay_d ?? 0) > 0 && {a.cause}} {a.elements.map((id) => els[id]).filter(Boolean).map((e) => ( - setSheet(e)} className={cn( + setSheet(e)} accessibilityRole="button" accessibilityLabel={`${e.name}, ${de(e.state)}, ${pct(e.pct)}`} className={cn( "bg-background border-border active:bg-accent min-h-[52px] min-w-[47%] flex-grow justify-center rounded-lg border border-l-4 px-3 py-2", !e.pct ? "border-l-border" : e.pct >= 100 ? "border-l-success" : "border-l-warning")}> {e.name} @@ -113,21 +116,24 @@ export function Today({ data, error, reload, refreshing, toast }: { setSheet(null)}> setSheet(null)} /> {sheet && ( - + {sheet.name} {sheet.zone} · jetzt: {de(sheet.state)} ({pct(sheet.pct)}) {sheet.states.map((st, i) => { const cur = sheet.states.indexOf(sheet.state); return ( - confirm(sheet.id, st)} className={cn( - "active:bg-accent mb-2 min-h-14 flex-row items-center justify-between rounded-lg border px-4", - i === cur ? "border-success bg-success/10" : "border-border")}> + // states only go up: reached states are shown, not tappable + confirm(sheet.id, st)} + accessibilityRole="button" accessibilityState={{ disabled: i <= cur, selected: i === cur }} + accessibilityLabel={`${sheet.name}: ${de(st)}${i <= cur ? " (erreicht)" : ""}`} className={cn( + "mb-2 min-h-14 flex-row items-center justify-between rounded-lg border px-4", + i === cur ? "border-success bg-success/10" : i < cur ? "border-border bg-muted opacity-60" : "border-border active:bg-accent")}> {de(st)} {i <= cur && } ); })} - Zustände gehen nur nach oben. Ein Tipp zählt wie eine Sprachnotiz. + Erreichte Zustände lassen sich nicht zurücksetzen. Ein Tipp zählt wie eine Sprachnotiz. )}