Files
ApiCore/ApiCore-Frontend/src/lib/offline/use-capture-mutation.ts
T
Nick SzaunigandClaude Opus 5.5 c01a38835a feat: platform backbone and field capture, first part (checkpoint)
Platform backbone (plan 2026-10-13-plattform-rueckgrat), reviewed tasks:
- run roles api/worker/job/all with shared startup checks (Task 1)
- schema and migration for DomainEvent, deliveries, JobRun, ThrottlerHit (Task 2)
- audit, notifications and domain events written in the same transaction (Task 3)
- dispatcher with SKIP LOCKED claims, retries and stale release (Task 4)
- worker building blocks: tick, LISTEN/NOTIFY wake-up, health (Task 5)
- worker process and entry points (Task 6)
- throttler counters in Postgres (Task 19)
- separate keys per purpose with key ring (Task 20)
- public origin page without exact location (Task 22)
- shop keys split into read and write (Task 23)
- Kustomize base, components, overlay encry, CI validation (Task 26)

Field capture T3 (plan 2026-10-13-t3-erfassung-am-stand), reviewed tasks:
- brood frames, read endpoints, apiary overview and offline pack
- network basics, offline queue v3, navigation sheets, form building blocks
- new inspection with last-time hints and weather, varroa per day,
  treatment prefill, apiary page with round
- inspection photo (Task 10) is implemented, review pending

Not rolled out. Remaining tasks follow in later commits.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-13 17:57:54 +02:00

80 lines
2.9 KiB
TypeScript

"use client";
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ApiError } from "@/lib/auth/api-client";
import { useCurrentUserId } from "@/lib/auth/auth-context";
import { errorMessage } from "@/lib/forms/error-message";
import { CreateOptions, newIdempotencyKey } from "./idempotency";
/** Prefix of every query that reads the offline queue (band, queue sheet). */
export const OFFLINE_QUEUE_QUERY_KEY = ["offline-queue"] as const;
export type CaptureOutcome<R> =
| { via: "online"; result: R }
| { via: "queued"; idempotencyKey: string };
export interface CaptureMutationOptions<I, R> {
create: (input: I, options: CreateOptions) => Promise<R>;
queue: (input: I, idempotencyKey: string, ownerUserId: string) => Promise<void>;
/** Shown when nothing could be saved and the server gave no reason. */
failureMessage: string;
onSaved: (outcome: CaptureOutcome<R>, input: I) => void | Promise<void>;
}
export interface CaptureMutation<I> {
submit: (input: I) => void;
isPending: boolean;
submitError: string | null;
idempotencyKey: string;
}
/**
* Saves a quick-capture form: online first; without a network the entry goes
* into the offline queue under the signed-in user. A server rejection
* (ApiError) is shown at the form and never queued.
*/
export function useCaptureMutation<I, R>({
create,
queue,
failureMessage,
onSaved,
}: CaptureMutationOptions<I, R>): CaptureMutation<I> {
const ownerUserId = useCurrentUserId();
const queryClient = useQueryClient();
// One key per opened form: a double tap or an offline retry of the
// same entry is recognised by the server instead of saved twice.
const [idempotencyKey] = useState(newIdempotencyKey);
const [submitError, setSubmitError] = useState<string | null>(null);
const mutation = useMutation({
// Runs while the browser reports offline too: the request fails fast and
// the entry is queued, instead of the form waiting for a network.
networkMode: "always",
retry: false,
mutationFn: async (input: I): Promise<CaptureOutcome<R>> => {
try {
return { via: "online", result: await create(input, { idempotencyKey }) };
} catch (error) {
// Never queue without an owner: such an entry would be sent under
// whoever signs in next on this device.
if (error instanceof ApiError || !ownerUserId) {
throw error;
}
await queue(input, idempotencyKey, ownerUserId);
void queryClient.invalidateQueries({ queryKey: OFFLINE_QUEUE_QUERY_KEY });
return { via: "queued", idempotencyKey };
}
},
onSuccess: (outcome, input) => onSaved(outcome, input),
onError: (error) => setSubmitError(errorMessage(error, failureMessage)),
});
function submit(input: I): void {
setSubmitError(null);
mutation.mutate(input);
}
return { submit, isPending: mutation.isPending, submitError, idempotencyKey };
}