From 29c80a0e7359b1af3b63f8b2bb3f4414976d62d1 Mon Sep 17 00:00:00 2001 From: Martin Date: Mon, 14 Sep 2026 18:48:57 +0200 Subject: [PATCH] L11 Kundenversand: Bericht-PDF an Kunden senden (Service, Action, API, Berichtsseite) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sendReportToCustomer: report:approve, Scope, nur approved mit PDF, Empfänger Ansprechpartner -> Kunde, Dedupe je Adresse+Version, Audit export - Server Action + POST /api/v1/reports/{id}/send inkl. OpenAPI-Eintrag - /reports/[id]: Abschnitt „An Kunden senden" mit bisherigen Versänden, Texte de/en Co-Authored-By: Claude Opus 5 --- messages/de/reports.json | 31 ++++ messages/en/reports.json | 31 ++++ src/app/(app)/reports/[id]/page.tsx | 15 ++ src/app/api/v1/reports/[id]/send/route.ts | 15 ++ .../reports/send-to-customer-state.ts | 9 ++ src/components/reports/send-to-customer.tsx | 125 ++++++++++++++++ src/lib/api/openapi.ts | 27 ++++ .../actions/reports/send-to-customer.ts | 25 ++++ .../services/reports/send-to-customer.ts | 135 ++++++++++++++++++ 9 files changed, 413 insertions(+) create mode 100644 src/app/api/v1/reports/[id]/send/route.ts create mode 100644 src/components/reports/send-to-customer-state.ts create mode 100644 src/components/reports/send-to-customer.tsx create mode 100644 src/server/actions/reports/send-to-customer.ts create mode 100644 src/server/services/reports/send-to-customer.ts diff --git a/messages/de/reports.json b/messages/de/reports.json index c97594c..1a7da9f 100644 --- a/messages/de/reports.json +++ b/messages/de/reports.json @@ -226,6 +226,37 @@ "alreadySigned": "Unterschrift liegt vor.", "noReport": "Zuerst den Abschlussbericht erstellen." }, + "customerMail": { + "title": "An Kunden senden", + "sub": "Das freigegebene PDF geht als Anhang an den Kunden. Antworten gehen an die Antwortadresse Ihres Betriebs.", + "to": "Empfänger", + "toHint": "Vorbelegt mit dem Ansprechpartner des Auftrags bzw. dem Kunden.", + "noDefault": "Beim Auftrag ist keine E-Mail-Adresse hinterlegt. Bitte Empfänger eingeben.", + "message": "Nachricht (optional)", + "messagePlaceholder": "Kurze Nachricht an den Kunden", + "submit": "Bericht senden", + "sending": "Wird gesendet …", + "history": "Bisherige Versände", + "historyEmpty": "Noch nicht an den Kunden gesendet.", + "result": { + "sent": "Bericht an {to} versendet.", + "queued": "Bericht an {to} wird versendet.", + "duplicate": "Diese Version wurde bereits an {to} gesendet.", + "failed": "Versand an {to} fehlgeschlagen. Bitte später erneut versuchen." + }, + "delivery": { + "sent": "Versendet", + "pending": "In Zustellung", + "failed": "Fehlgeschlagen", + "other": "Nicht zugestellt" + }, + "errors": { + "recipient_missing": "Bitte eine E-Mail-Adresse angeben.", + "invalid_to": "Bitte eine gültige E-Mail-Adresse angeben.", + "report_not_approved": "Nur freigegebene Berichte können versendet werden.", + "pdf_missing": "Das PDF ist noch nicht erzeugt." + } + }, "pdf": { "page": "Seite {page} von {pages}", "reportId": "Bericht-ID", diff --git a/messages/en/reports.json b/messages/en/reports.json index 4dbc881..fef17bf 100644 --- a/messages/en/reports.json +++ b/messages/en/reports.json @@ -226,6 +226,37 @@ "alreadySigned": "Signature captured.", "noReport": "Create the completion report first." }, + "customerMail": { + "title": "Send to customer", + "sub": "The approved PDF is sent to the customer as an attachment. Replies go to your company's reply address.", + "to": "Recipient", + "toHint": "Prefilled with the work order contact or the customer.", + "noDefault": "No e-mail address is stored for this work order. Please enter a recipient.", + "message": "Message (optional)", + "messagePlaceholder": "Short message to the customer", + "submit": "Send report", + "sending": "Sending …", + "history": "Previous sends", + "historyEmpty": "Not sent to the customer yet.", + "result": { + "sent": "Report sent to {to}.", + "queued": "Report to {to} is being sent.", + "duplicate": "This version has already been sent to {to}.", + "failed": "Sending to {to} failed. Please try again later." + }, + "delivery": { + "sent": "Sent", + "pending": "Being delivered", + "failed": "Failed", + "other": "Not delivered" + }, + "errors": { + "recipient_missing": "Please enter an e-mail address.", + "invalid_to": "Please enter a valid e-mail address.", + "report_not_approved": "Only approved reports can be sent.", + "pdf_missing": "The PDF has not been generated yet." + } + }, "pdf": { "page": "Page {page} of {pages}", "reportId": "Report ID", diff --git a/src/app/(app)/reports/[id]/page.tsx b/src/app/(app)/reports/[id]/page.tsx index 53268ce..afc4488 100644 --- a/src/app/(app)/reports/[id]/page.tsx +++ b/src/app/(app)/reports/[id]/page.tsx @@ -14,6 +14,8 @@ import { ServiceError } from "@/server/services/context"; import { tenantTimeZone } from "@/server/services/reports/build-content"; import { getReportDetail } from "@/server/services/reports/queries"; import { readCtx } from "@/server/services/reports/read-ctx"; +import { SendToCustomer } from "@/components/reports/send-to-customer"; +import { defaultReportRecipient, listCustomerMailings } from "@/server/services/reports/send-to-customer"; /** /reports/[id] — structured view, PDF, versions, approve/reject/new version (reject as popup ?reject=1). */ export default async function ReportDetailPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ reject?: string }> }) { @@ -29,6 +31,14 @@ export default async function ReportDetailPage({ params, searchParams }: { param const { report, content, versions, workOrder, permissions } = detail; const dt = (d: Date | null) => (d ? format.dateTime(d, { dateStyle: "medium", timeStyle: "short", timeZone }) : null); const base = `/reports/${id}`; + // L11: customer mail section — approved report with PDF, backoffice right (the action re-checks against the DB) + const customerMail = + report.status === "approved" && report.pdfDocumentId && ctx.permissions.has("report:approve") + ? await Promise.all([defaultReportRecipient(ctx, report), listCustomerMailings(ctx, id)]).then(([defaultTo, rows]) => ({ + defaultTo, + mailings: rows.map((m) => ({ id: m.id, to: m.to, status: m.status, version: m.version, when: dt(m.sentAt ?? m.createdAt) ?? "" })), + })) + : null; const meta: Array<[string, string | null]> = [ [t("field.workOrder"), `${workOrder.number}`], @@ -87,6 +97,11 @@ export default async function ReportDetailPage({ params, searchParams }: { param
+ {customerMail && ( +
+ +
+ )}
diff --git a/src/app/api/v1/reports/[id]/send/route.ts b/src/app/api/v1/reports/[id]/send/route.ts new file mode 100644 index 0000000..73a36d0 --- /dev/null +++ b/src/app/api/v1/reports/[id]/send/route.ts @@ -0,0 +1,15 @@ +import { requireApiContext } from "@/server/api/context"; +import { json, readJsonObject, withApi } from "@/server/api/respond"; +import { sendReportToCustomer } from "@/server/services/reports/send-to-customer"; + +/** + * POST /api/v1/reports/:id/send — e-mail the approved report PDF to the customer (L11). + * Body (optional): { to?: string, message?: string }. 202 queued, 200 sent/duplicate/failed. + */ +export const POST = withApi(async (req: Request, { params }: { params: Promise<{ id: string }> }) => { + const ctx = await requireApiContext("reports", "report:approve"); + const { id } = await params; + const body = await readJsonObject(req, { allowEmpty: true }); + const res = await sendReportToCustomer(ctx, { reportId: id, to: body.to, message: body.message }); + return json(res, { status: res.status === "queued" ? 202 : 200 }); +}); diff --git a/src/components/reports/send-to-customer-state.ts b/src/components/reports/send-to-customer-state.ts new file mode 100644 index 0000000..271def1 --- /dev/null +++ b/src/components/reports/send-to-customer-state.ts @@ -0,0 +1,9 @@ +import type { ReportActionErrorCode } from "@/lib/reports/action-state"; + +/** Result of the "send report to customer" action (client-safe; kept out of the "use server" file). */ +export type SendToCustomerState = + | { status: "idle" } + | { status: "ok"; result: "sent" | "queued" | "duplicate" | "failed"; to: string; at: number } + | { status: "error"; code: ReportActionErrorCode; field?: string; reason?: string; at: number }; + +export const SEND_TO_CUSTOMER_IDLE: SendToCustomerState = { status: "idle" }; diff --git a/src/components/reports/send-to-customer.tsx b/src/components/reports/send-to-customer.tsx new file mode 100644 index 0000000..9223bd8 --- /dev/null +++ b/src/components/reports/send-to-customer.tsx @@ -0,0 +1,125 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useActionState, useEffect } from "react"; +import { useTranslations } from "next-intl"; +import { CheckCircle2, Clock, Info, Mail, XCircle } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { sendReportToCustomerAction } from "@/server/actions/reports/send-to-customer"; +import { SEND_TO_CUSTOMER_IDLE } from "./send-to-customer-state"; + +export type CustomerMailingRow = { id: string; to: string; status: string; version: number | null; when: string }; + +const KNOWN_REASONS = new Set(["recipient_missing", "report_not_approved", "pdf_missing"]); + +/** /reports/[id] section „An Kunden senden" (approved + report:approve). The service enforces rights and status. */ +export function SendToCustomer({ reportId, defaultTo, mailings }: { reportId: string; defaultTo: string | null; mailings: CustomerMailingRow[] }) { + const t = useTranslations("reports.customerMail"); + const tr = useTranslations("reports"); + const router = useRouter(); + const [state, action, pending] = useActionState(sendReportToCustomerAction, SEND_TO_CUSTOMER_IDLE); + + useEffect(() => { + if (state.status === "ok") router.refresh(); + }, [state, router]); + + let feedback: React.ReactNode = null; + if (state.status === "ok") { + const bad = state.result === "failed"; + const hint = state.result === "duplicate"; + feedback = ( +

+ {bad ? : hint ? : } + {t(`result.${state.result}`, { to: state.to })} +

+ ); + } else if (state.status === "error") { + const key = + state.reason && KNOWN_REASONS.has(state.reason) + ? `errors.${state.reason}` + : state.field === "to" + ? "errors.invalid_to" + : null; + feedback = ( +

+ + {key ? t(key) : tr(`errors.${state.code}`)} +

+ ); + } + + return ( +
+

+ {t("title")} +

+

{t("sub")}

+ +
+ +
+ + +

+ {defaultTo ? t("toHint") : t("noDefault")} +

+
+
+ +