diff --git a/backend/app/api/correspondence.py b/backend/app/api/correspondence.py index 1ee8bfa..d962e6c 100644 --- a/backend/app/api/correspondence.py +++ b/backend/app/api/correspondence.py @@ -146,6 +146,7 @@ def post_dispatch( body.attachment_element_ids, [item.model_dump() for item in body.evidence], body.historical_gap, + body.capture_editions, request.app.state.settings.media_root, request.state.cleanup_files, ) diff --git a/backend/app/api/schemas.py b/backend/app/api/schemas.py index 7fa123d..628d65e 100644 --- a/backend/app/api/schemas.py +++ b/backend/app/api/schemas.py @@ -413,6 +413,7 @@ class DispatchIn(APIModel): attachment_element_ids: list[UUID] = Field(default_factory=list, max_length=100) evidence: list[EvidenceIn] = Field(default_factory=list, max_length=20) historical_gap: bool = False + capture_editions: bool = True class DispatchEvidenceIn(APIModel): diff --git a/backend/app/correspondence.py b/backend/app/correspondence.py index 25274e5..cd06033 100644 --- a/backend/app/correspondence.py +++ b/backend/app/correspondence.py @@ -196,11 +196,16 @@ def record_dispatch( attachment_ids: list[UUID], evidence: list[dict], historical_gap: bool, + capture_editions: bool, media_root: str, cleanup: list[Path], ) -> dict: if channel not in CHANNELS: raise unprocessable("Der Versandweg ist nicht vorgesehen.") + if not capture_editions and attachment_ids: + raise unprocessable("Ein Beleg sichert das Schreiben nicht als Versandfassung.") + if not capture_editions and not evidence: + raise unprocessable("Ein Beleg braucht mindestens einen Nachweis.") if len(attachment_ids) != len(set(attachment_ids)): raise unprocessable("Dieselbe Anlage ist mehrfach im Versand genannt.") container_row, page, scope = open_container(conn, actor, context, placement, "edit") @@ -231,17 +236,19 @@ def record_dispatch( actor, ), ).fetchone() - states = [_capture_item(conn, actor, dispatch, host, "host", 0, page, historical_gap, media_root, cleanup)] - ordered = [row for row in _uses(conn, scope, host_id) if row["attachment_element_id"] in set(attachment_ids)] - position_of = {item: index for index, item in enumerate(attachment_ids)} - ordered.sort(key=lambda row: position_of[row["attachment_element_id"]]) - for index, row in enumerate(ordered, start=1): - element = _readable(conn, actor, row["attachment_element_id"], page) - if element is None: - raise not_found() - states.append( - _capture_item(conn, actor, dispatch, element, "attachment", index, page, historical_gap, media_root, cleanup) - ) + states = [] + if capture_editions: + states.append(_capture_item(conn, actor, dispatch, host, "host", 0, page, historical_gap, media_root, cleanup)) + ordered = [row for row in _uses(conn, scope, host_id) if row["attachment_element_id"] in set(attachment_ids)] + position_of = {item: index for index, item in enumerate(attachment_ids)} + ordered.sort(key=lambda row: position_of[row["attachment_element_id"]]) + for index, row in enumerate(ordered, start=1): + element = _readable(conn, actor, row["attachment_element_id"], page) + if element is None: + raise not_found() + states.append( + _capture_item(conn, actor, dispatch, element, "attachment", index, page, historical_gap, media_root, cleanup) + ) evidence_rows = [] for item in evidence: evidence_rows.append( @@ -260,7 +267,7 @@ def record_dispatch( log=False, ) ) - completeness = _completeness(states) + completeness = _completeness(states) if capture_editions else "secured" conn.execute( "UPDATE dispatches SET completeness = %s, updated_at = now() WHERE id = %s", (completeness, dispatch["id"]), @@ -314,7 +321,16 @@ def detach_dispatch_evidence( if deleted is None: raise not_found() _clear_evidence_fold(conn, scope, element_id) - _log(conn, dispatch_id, actor, "Nachweis aus diesem Versand gelöst") + leftover_evidence = conn.execute( + "SELECT id FROM dispatch_evidence WHERE dispatch_id = %s", (dispatch_id,) + ).fetchone() + leftover_items = conn.execute( + "SELECT id FROM dispatch_items WHERE dispatch_id = %s", (dispatch_id,) + ).fetchone() + if leftover_evidence is None and leftover_items is None: + conn.execute("DELETE FROM dispatches WHERE id = %s", (dispatch_id,)) + else: + _log(conn, dispatch_id, actor, "Nachweis aus diesem Versand gelöst") audit(conn, actor, container_row["home_scope_id"], "dispatch_evidence_detached", "element", dispatch["host_element_id"], page) @@ -1020,6 +1036,7 @@ def _public_evidence(conn, proof, element, page: Ctx) -> dict: "id": str(proof["id"]), "element_id": str(element["id"]), "title": element["title"], + "kind": element["kind"], "role": proof["role"], "role_label": EVIDENCE_ROLES[proof["role"]], "source_state": proof["source_state"], diff --git a/frontend/src/pages/content.jsx b/frontend/src/pages/content.jsx index c48999a..be85ad9 100644 --- a/frontend/src/pages/content.jsx +++ b/frontend/src/pages/content.jsx @@ -26,7 +26,6 @@ import { scopeBody, StructureAssignDialog, UnitDetail, - writeAssign, } from "./correspondence.jsx"; export function formatDate(value) { @@ -890,12 +889,10 @@ function EntryMark({ element, context, assignable = false, dropId = "", onAssign {url ? : ( <> @@ -1532,36 +1529,74 @@ export function ContentBoard({ }, 0); } - function beginCarry(payload) { - carryRef.current = payload; - } - - function endCarry(event) { - const carried = carryRef.current; - if (!carried) { + function beginCarryPointer(event, payload) { + if (pending || (event.button != null && event.button !== 0)) return; + if (event.target.closest("button, a, input, textarea, select")) return; + event.stopPropagation(); + const carried = { + ...payload, + pointerId: event.pointerId, + anchorX: event.clientX, + anchorY: event.clientY, + moved: false, + useBindingId: "", + sourceNode: event.target.closest?.("[data-carry], .entry-mark") || event.target, + }; + function pointOf(pointer) { + return document.elementFromPoint(pointer.clientX, pointer.clientY); + } + function track(pointer) { + if (carryRef.current !== carried || pointer.pointerId !== carried.pointerId) return; + if (Math.hypot(pointer.clientX - carried.anchorX, pointer.clientY - carried.anchorY) > 4) { + carried.moved = true; + if (carried.sourceNode) carried.sourceNode.dataset.dragged = "1"; + } + if (!carried.moved) return; + const hit = pointOf(pointer); + const useId = useDropId(hit); + const ownChip = hit?.closest?.(`[data-carry="${carried.source}:${carried.elementId}"]`); + if (useId && useId !== carried.bindingId) { + carried.useBindingId = useId; + setIndicator({ kind: "use", bindingId: useId }); + return; + } + carried.useBindingId = ""; + const inside = Boolean(hit && rootRef.current?.contains(hit)); + if (inside && !ownChip && (carried.source === "attachment" || carried.source === "evidence")) { + setIndicator({ kind: "release" }); + return; + } setIndicator(null); - return; } - carryRef.current = null; - setIndicator(null); - if (carried.settled) return; - carried.settled = true; - const x = event?.clientX || 0; - const y = event?.clientY || 0; - const pointOk = x > 0 || y > 0; - const moved = Math.hypot(x - (carried.anchorX || 0), y - (carried.anchorY || 0)); - if (pointOk && moved < 8 && !carried.useBindingId) return; - const hit = pointOk ? document.elementFromPoint(x, y) : null; - if (hit && rootRef.current && !rootRef.current.contains(hit)) return; - if (!hit && !carried.useBindingId) return; - const useId = hit ? useDropId(hit) : (carried.useBindingId || ""); - if (useId && useId !== carried.bindingId) { - placeUseRef.current?.(useId, carried); - return; + function finish(pointer) { + if (pointer && pointer.pointerId !== carried.pointerId) return; + window.removeEventListener("pointermove", track); + window.removeEventListener("pointerup", finish); + window.removeEventListener("pointercancel", finish); + if (carryRef.current !== carried) return; + carryRef.current = null; + setIndicator(null); + if (!carried.moved) return; + const hit = pointer ? pointOf(pointer) : null; + const useId = useDropId(hit) || carried.useBindingId; + if (useId && useId !== carried.bindingId) { + placeUseRef.current?.(useId, carried); + return; + } + const inside = Boolean(hit && rootRef.current?.contains(hit)); + if (!inside) return; + if (hit.closest?.(`[data-carry="${carried.source}:${carried.elementId}"]`)) return; + if (carried.source === "attachment" || carried.source === "evidence") releaseRef.current?.(carried); + } + carryRef.current = carried; + window.addEventListener("pointermove", track); + window.addEventListener("pointerup", finish); + window.addEventListener("pointercancel", finish); + try { + carried.sourceNode.setPointerCapture?.(event.pointerId); + } catch { + // Window listeners still follow the pointer. } - if (!hit || useId) return; - if (hit.closest?.(`[data-carry="${carried.source}:${carried.elementId}"]`)) return; - if (carried.source === "attachment" || carried.source === "evidence") releaseRef.current?.(carried); } function bindingByElement(elementId) { @@ -1657,6 +1692,73 @@ export function ContentBoard({ } } + async function placeReceipt(hostBinding, payload, element) { + if (!payload || payload.elementId === hostBinding.element.id) return; + const role = element?.external?.source === "imap" ? "email" : "other"; + setPending(true); + setError(""); + try { + const scope = correspondenceScope(); + if (payload.source === "attachment") { + const from = bindingByElement(payload.hostElementId); + if (!from) return; + await api(`/api/v1/elements/${from.element.id}/attachments/${payload.elementId}/detach`, { + method: "POST", + body: { expected_version: from.element.version, ...scope }, + }); + } + if (payload.source === "evidence") { + const found = dispatchOf(payload.dispatchId); + if (!found) return; + await api(`/api/v1/dispatches/${found.dispatch.id}/evidence/${payload.elementId}/detach`, { + method: "POST", + body: { expected_version: found.dispatch.version, ...scope }, + }); + } + let expected = hostBinding.element.version; + if (payload.source === "attachment") { + const from = bindingByElement(payload.hostElementId); + if (from?.element.id === hostBinding.element.id) expected += 1; + } + const holder = (hostBinding.correspondence?.dispatches || []).find((item) => ( + item.channel === "other" + && !(item.items || []).some((part) => part.role === "host" || part.role === "attachment") + )); + if (!holder) { + await api(`/api/v1/elements/${hostBinding.element.id}/dispatches`, { + method: "POST", + body: { + expected_version: expected, + channel: "other", + sent_on: null, + counterpart: null, + attachment_element_ids: [], + evidence: [{ element_id: payload.elementId, role, fold: "evidence" }], + historical_gap: false, + capture_editions: false, + ...scope, + }, + }); + } else { + await api(`/api/v1/dispatches/${holder.id}/evidence`, { + method: "POST", + body: { + expected_version: holder.version, + element_id: payload.elementId, + role, + fold: "evidence", + ...scope, + }, + }); + } + onChange(); + } catch (err) { + setError(err.message); + } finally { + setPending(false); + } + } + function openPlace(hostBindingId, payload) { const host = source.find((item) => item.id === hostBindingId); if (!host || !payload || host.element.id === payload.elementId) return; @@ -1692,7 +1794,8 @@ export function ContentBoard({ } return ( -
+
+ {indicator?.kind === "release" ?
In den Vorgang legen
: null}

{viewMode === "chronology" ? "Chronologie" : (activePath || listTitle || "Inhalte")} {shownCount}

@@ -1812,33 +1915,8 @@ export function ContentBoard({ setDialog(null); }}>Als Anlage
@@ -2033,32 +2111,19 @@ export function ContentBoard({ context={context} dropId={canEdit ? binding.id : ""} assignable={canEdit && !pending && !picking} - onAssignStart={(event) => { - event.stopPropagation(); - beginCarry({ - source: "list", - elementId: element.id, - bindingId: binding.id, - title: element.title, - anchorX: event.clientX, - anchorY: event.clientY, - }); - writeAssign(event, { - source: "list", - elementId: element.id, - bindingId: binding.id, - title: element.title, - }); - }} - onAssignEnd={endCarry} + onAssignStart={(event) => beginCarryPointer(event, { + source: "list", + elementId: element.id, + bindingId: binding.id, + title: element.title, + })} /> { const found = source.find((item) => item.element?.id === elementId); if (found) onOpen?.(found); diff --git a/frontend/src/pages/correspondence.jsx b/frontend/src/pages/correspondence.jsx index da297a3..e528ecc 100644 --- a/frontend/src/pages/correspondence.jsx +++ b/frontend/src/pages/correspondence.jsx @@ -45,18 +45,6 @@ export function hostMark(binding) { return `Dieselbe Unterlage · Anlage zu ${hosts.map((item) => item.title).join(", ")}`; } -function snapshotHref(dispatchId, itemId, scope) { - const search = new URLSearchParams({ - context_kind: scope.context.kind, - context_id: scope.context.id, - }); - if (scope.placement) { - search.set("placement_kind", scope.placement.kind); - search.set("placement_id", scope.placement.id); - } - return `/api/v1/dispatches/${dispatchId}/items/${itemId}/content?${search}`; -} - function fieldBody(scope, extra) { const body = { ...extra, context: scope.context }; if (scope.placement) body.placement = scope.placement; @@ -76,6 +64,25 @@ export function receiptRoleLabel(role, fallback = "") { return RECEIPT_ROLES.find((item) => item[0] === role)?.[1] || fallback || role; } +function receiptCaption(proof) { + if (proof.role === "email" && proof.kind === "file") return "Beleg"; + return receiptRoleLabel(proof.role, proof.role_label); +} + +function isShipment(item) { + const proofs = item.evidence || []; + if (item.channel === "other") return false; + if (proofs.length > 0 && proofs.every((proof) => proof.kind === "file")) return false; + return (item.items || []).length > 0; +} + +function receiptHeading(item) { + const who = item.counterpart ? ` · ${item.counterpart}` : ""; + if (!isShipment(item)) return `${item.sent_on ? formatDate(item.sent_on) : "Beleg"}${who}`; + const when = item.undated ? "undatiert" : formatDate(item.sent_on); + return `Versand ${when} · ${item.channel_label}${who}`; +} + export function writeAssign(event, payload) { event.dataTransfer.effectAllowed = "copyMove"; event.dataTransfer.setData(ASSIGN_MIME, JSON.stringify(payload)); @@ -145,10 +152,10 @@ export function StructureAssignDialog({ host, bindings, chapters, scope, pending const [query, setQuery] = useState(""); const [selected, setSelected] = useState(() => new Set()); const [step, setStep] = useState("pick"); - const [role, setRole] = useState("email"); + const [role, setRole] = useState("other"); const [fold, setFold] = useState("evidence"); const [dispatchId, setDispatchId] = useState(host.correspondence?.dispatches?.[0]?.id || ""); - const [channel, setChannel] = useState("email"); + const [channel, setChannel] = useState("other"); const [sentOn, setSentOn] = useState(""); const [counterpart, setCounterpart] = useState(""); const [error, setError] = useState(""); @@ -241,9 +248,10 @@ export function StructureAssignDialog({ host, bindings, chapters, scope, pending channel, sent_on: sentOn || null, counterpart: counterpart.trim() || null, - attachment_element_ids: (host.correspondence?.attachments || []).map((item) => item.element_id), + attachment_element_ids: [], evidence: ids.map((id) => ({ element_id: id, role, fold })), historical_gap: false, + capture_editions: false, }), }); } else { @@ -565,9 +573,9 @@ export function EvidenceDialog({ element, hosts, scope, pending, presetDispatchI const [dispatchId, setDispatchId] = useState( presetDispatchId !== undefined ? presetDispatchId : (host?.correspondence?.dispatches?.[0]?.id || ""), ); - const [role, setRole] = useState("email"); + const [role, setRole] = useState("other"); const [fold, setFold] = useState("evidence"); - const [channel, setChannel] = useState("email"); + const [channel, setChannel] = useState("other"); const [sentOn, setSentOn] = useState(""); const [counterpart, setCounterpart] = useState(""); const [result, setResult] = useState(null); @@ -593,9 +601,10 @@ export function EvidenceDialog({ element, hosts, scope, pending, presetDispatchI channel, sent_on: sentOn || null, counterpart: counterpart.trim() || null, - attachment_element_ids: (host.correspondence?.attachments || []).map((item) => item.element_id), + attachment_element_ids: [], evidence: [{ element_id: element.id, role, fold }], historical_gap: false, + capture_editions: false, }), }); const proof = (created.evidence || []).find((item) => item.element_id === element.id); @@ -698,23 +707,11 @@ export function ComparisonList({ comparisons = [], state, reason }) { ); } -function chipDrag(enabled, payload, onCarryStart, onCarryEnd) { +function chipPointer(enabled, payload, onCarryStart) { + if (!enabled) return {}; return { - draggable: enabled, - onDragStart(event) { - if (event.target.closest("button, a")) { - event.preventDefault(); - return; - } - event.stopPropagation(); - payload.anchorX = event.clientX; - payload.anchorY = event.clientY; - event.currentTarget.dataset.dragged = "1"; - writeAssign(event, payload); - onCarryStart?.(payload); - }, - onDragEnd(event) { - onCarryEnd?.(event); + onPointerDown(event) { + onCarryStart?.(event, payload); }, }; } @@ -743,13 +740,11 @@ export function UnitDetail({ binding, canEdit, pending, - scope, onOpen, onDetach, onDetachEvidence, onUnfold, onCarryStart, - onCarryEnd, children, }) { const pack = binding.correspondence || {}; @@ -761,12 +756,14 @@ export function UnitDetail({ return typeof children === "function" ? children(null, null) : null; } const evidenceCount = dispatches.reduce((sum, item) => sum + (item.evidence || []).length, 0); + const shipmentCount = dispatches.filter(isShipment).length; const attachmentLabel = attachments.length === 1 ? "1 Anlage" : `${attachments.length} Anlagen`; const receiptParts = []; - if (dispatches.length === 1) receiptParts.push("1 Versand"); - else if (dispatches.length > 1) receiptParts.push(`${dispatches.length} Versände`); + if (shipmentCount === 1) receiptParts.push("1 Versand"); + else if (shipmentCount > 1) receiptParts.push(`${shipmentCount} Versände`); if (evidenceCount === 1) receiptParts.push("1 Beleg"); else if (evidenceCount > 1) receiptParts.push(`${evidenceCount} Belege`); + const receiptLabel = receiptParts.join(" · "); const switches = ( {attachments.length ? ( @@ -776,7 +773,7 @@ export function UnitDetail({ ) : null} {dispatches.length ? ( ) : null} @@ -792,13 +789,13 @@ export function UnitDetail({ key={item.id} className="use-chip" data-carry={`attachment:${item.element_id}`} - {...(canEdit ? chipDrag(!pending, { + {...chipPointer(canEdit && !pending, { source: "attachment", elementId: item.element_id, hostElementId: binding.element.id, bindingId: item.binding_id || "", title: item.title, - }, onCarryStart, onCarryEnd) : {})} + }, onCarryStart)} > {canEdit ?
@@ -899,7 +879,7 @@ export function Chronology({ bindings, direction, itemHref, selectedId, onOpen } events.push({ key: `send-${dispatch.id}`, date: dispatch.sent_on || "", - label: "Versand", + label: isShipment(dispatch) ? "Versand" : "Beleg", title: binding.element?.title || "", detail: [ dispatch.undated ? "Versand undatiert" : `Versanddatum ${formatDate(dispatch.sent_on)}`, diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 5744b35..8b118e6 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -1359,12 +1359,31 @@ button.unit-switch[aria-expanded="true"] { color: var(--brand); } .use-chip { cursor: grab; } .use-chip__grip { width: 10px; height: 14px; border: 0; padding: 0; border-left: 2px dotted var(--text3); border-right: 2px dotted var(--text3); background: transparent; flex: none; } .use-chip__title { cursor: pointer; font-weight: 600; text-align: left; } -.entry-mark[draggable="true"] { cursor: grab; } +.entry-mark[role="button"] { cursor: grab; touch-action: none; } +.contents.is-release-target { box-shadow: inset 0 0 0 2px var(--accent); } +.release-mark { + position: sticky; + top: 36px; + z-index: 3; + margin: 0 0 4px; + padding: 2px 8px; + border-radius: 4px; + background: var(--accent-light); + color: var(--brand); + font-size: 12px; + font-weight: 650; + line-height: 22px; + text-align: left; +} .use-editions summary { cursor: pointer; color: var(--text2); font-size: 13px; text-align: left; } +.preview-row.is-use-target { + background: var(--accent-light); + box-shadow: inset 3px 0 0 var(--accent); +} .preview-row.is-use-target .direction-trigger, .preview-row.is-use-target .entry-mark { box-shadow: inset 0 0 0 2px var(--accent); - background: var(--accent-light); + background: #fff; } .pick-tree-dialog { justify-items: start; text-align: left; gap: 8px; } .pick-tree__lead { margin: 0; text-align: left; font-size: 13px; font-weight: 400; color: var(--text2); }