L9 Lotse – KI-Assistent: Transkription, Berichtsentwurf, Vollständigkeitsprüfung, Freigabeprinzip (Services)

- OpenAI-kompatible Transkription + Processor transcription (done/failed/disabled, AiGeneration, Notiz aus Sprachnotiz)
- Claude-Lotse (strukturierte Ausgabe, Refusal/Fallback), Datenminimierung, Vorschläge in content.lotse
- Vollständigkeitsprüfung (Regeln + KI-Hinweise mit Deep-Link), Einstellungen, KI-Protokoll
- Freigabeprinzip: Submit eines Lotse-Entwurfs nur mit Prüfbestätigung (serverseitig)
- Migration lotse_address_form (TenantSettings)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-14 17:19:38 +02:00
co-authored by Claude Opus 5
parent d5c1221ab5
commit ff5c57f276
39 changed files with 1815 additions and 7 deletions
+67
View File
@@ -0,0 +1,67 @@
import type { CompletenessItem } from "@/lib/lotse/completeness";
import { parseReportContent } from "@/lib/reports/content";
import { assertCan, type ServiceCtx } from "@/server/services/context";
import { requireVisibleWorkOrder } from "@/server/services/work-orders/visibility";
import { assertLotseEnabled } from "./settings";
/**
* „3 Angaben fehlen – Lotse prüfen lassen“ (Brandbook §12.4, lane L9).
* Deterministic rules first (no AI call, always the same answer for the same data), then — if a
* Lotse draft exists for an open report — the model's `missingInformation` hints.
* Every item carries a deep link into the mobile sub page where it can be fixed.
*/
export async function checkCompleteness(ctx: ServiceCtx, workOrderId: string): Promise<CompletenessItem[]> {
assertCan(ctx, "lotse:use");
const wo = await requireVisibleWorkOrder(ctx, workOrderId, { id: true, signatureRequired: true });
await assertLotseEnabled(ctx);
const base = `/m/orders/${wo.id}`;
const [requirements, checklist, plans, usages, workEntries, descriptionNotes, reports] = await Promise.all([
ctx.db.photoRequirement.findMany({ where: { workOrderId: wo.id }, orderBy: { sortOrder: "asc" }, select: { label: true, _count: { select: { photos: true } } } }),
ctx.db.checklistItem.findMany({ where: { workOrderId: wo.id, required: true, checked: false }, orderBy: { sortOrder: "asc" }, select: { label: true } }),
ctx.db.materialPlan.findMany({ where: { workOrderId: wo.id }, orderBy: { sortOrder: "asc" }, select: { id: true, name: true, plannedQuantity: true } }),
ctx.db.materialUsage.findMany({ where: { workOrderId: wo.id }, select: { name: true, materialPlanId: true, usageStatus: true, actualQuantity: true, deviationReason: true } }),
ctx.db.timeEntry.findMany({ where: { type: "work", workSession: { workOrderId: wo.id } }, select: { startedAt: true, endedAt: true }, take: 50 }),
ctx.db.activityNote.count({ where: { workOrderId: wo.id, deletedAt: null, kind: { in: ["work_done", "general"] } } }),
ctx.db.report.findMany({
where: { workOrderId: wo.id, status: { not: "superseded" } },
orderBy: { updatedAt: "desc" },
select: { type: true, status: true, content: true, signature: { select: { id: true } } },
}),
]);
const items: CompletenessItem[] = [];
for (const r of requirements) if (r._count.photos === 0) items.push({ code: "photo_requirement", label: r.label, href: `${base}/photos`, source: "rule" });
for (const c of checklist) items.push({ code: "checklist_item", label: c.label, href: `${base}/checklist`, source: "rule" });
const planById = new Map(plans.map((p) => [p.id, p]));
for (const u of usages) {
const plan = u.materialPlanId ? planById.get(u.materialPlanId) : undefined;
const deviates = u.usageStatus !== "fully_used" || !u.materialPlanId || (plan ? !plan.plannedQuantity.equals(u.actualQuantity) : false);
if (deviates && !u.deviationReason?.trim()) items.push({ code: "material_reason", label: u.name, href: `${base}/materials`, source: "rule" });
}
const usedPlanIds = new Set(usages.map((u) => u.materialPlanId).filter(Boolean));
for (const p of plans) if (!usedPlanIds.has(p.id)) items.push({ code: "material_unconfirmed", label: p.name, href: `${base}/materials`, source: "rule" });
const now = Date.now();
if (!workEntries.some((e) => (e.endedAt?.getTime() ?? now) > e.startedAt.getTime())) items.push({ code: "no_work_time", href: `${base}/time`, source: "rule" });
const parsed = reports.map((r) => {
try {
return { ...r, parsed: parseReportContent(r.content) };
} catch {
return { ...r, parsed: null };
}
});
const reportText = parsed.some((r) => r.parsed?.texts.workPerformed.trim());
if (descriptionNotes === 0 && !reportText) items.push({ code: "no_description", href: `${base}/notes`, source: "rule" });
const completion = reports.filter((r) => r.type === "completion");
if (wo.signatureRequired && !completion.some((r) => r.signature)) items.push({ code: "signature_missing", href: `${base}/sign`, source: "rule" });
const openDraft = parsed.find((r) => (r.status === "draft" || r.status === "rejected") && r.parsed?.lotse);
for (const text of openDraft?.parsed?.lotse?.missingInformation ?? []) {
items.push({ code: "lotse_hint", text, href: `${base}/report?type=${openDraft!.type}`, source: "lotse" });
}
return items;
}
+110
View File
@@ -0,0 +1,110 @@
import type { Prisma, Report } from "@prisma/client";
import { LOTSE_TEXT_FIELDS, type LotseBlock } from "@/lib/lotse/content";
import { REPORT_EDITABLE, type ReportContent, type ReportStatus } from "@/lib/reports/content";
import type { ReportDraftInput } from "@/server/ai/providers";
import { getLotseProvider } from "@/server/ai/lotse/anthropic";
import type { LotseAssistant } from "@/server/ai/lotse/types";
import { writeAuditLog } from "@/server/audit";
import { assertCan, inTransaction, ServiceError, type ServiceCtx } from "@/server/services/context";
import { contentOf, requireVisibleReport } from "@/server/services/reports/common";
import { buildReportDraftInput } from "./minimize";
import { assertLotseEnabled, lotseVoice } from "./settings";
import { loadDraftNotes, loadMinimizationContext } from "./sources";
export type LotseDeps = { provider: LotseAssistant | null; now?: () => Date };
export const defaultLotseDeps = (): LotseDeps => ({ provider: getLotseProvider() });
/** Report visible + Lotse usable + status draft/rejected; shared by draft and suggestion decisions. */
export async function requireDraftableReport(ctx: ServiceCtx, reportId: string): Promise<Report> {
assertCan(ctx, "lotse:use");
assertCan(ctx, "report:write");
const report = await requireVisibleReport(ctx, reportId);
if (!REPORT_EDITABLE.includes(report.status as ReportStatus)) {
throw new ServiceError("blocked", `report is ${report.status}`, { reason: "not_editable" });
}
await assertLotseEnabled(ctx);
return report;
}
/** The exact (minimised) input the provider would receive — used by the service and the snapshot test. */
export async function prepareDraftInput(ctx: ServiceCtx, report: Report, content: ReportContent): Promise<ReportDraftInput> {
const [notes, minimization, voice] = await Promise.all([
loadDraftNotes(ctx, report),
loadMinimizationContext(ctx, report.workOrderId),
lotseVoice(ctx),
]);
return buildReportDraftInput({ content, notes, minimization, ...voice });
}
/**
* „Bericht mit Lotse vorbereiten“ (Spec §15.2–15.4): builds the minimised input from the report
* snapshot, notes and transcripts, asks the provider and stores the result as SUGGESTIONS in
* `content.lotse` (texts, activity notes and transcripts stay untouched). Sets `aiDrafted` and
* `aiGenerationId`, records the call as `AiGeneration`, writes an audit entry.
*/
export async function draftReportWithLotse(ctx: ServiceCtx, reportId: string, deps: LotseDeps = defaultLotseDeps()) {
const report = await requireDraftableReport(ctx, reportId);
if (!deps.provider) throw new ServiceError("invalid", "lotse provider not configured", { reason: "not_configured" });
const content = contentOf(report);
const input = await prepareDraftInput(ctx, report, content);
let output;
try {
output = await deps.provider.draftReport(input);
} catch (err) {
console.error("[lotse] draft failed:", (err as Error).message);
throw new ServiceError("conflict", "lotse provider failed", { reason: "provider_failed" });
}
const now = (deps.now ?? (() => new Date()))();
const { meta, missingInformation, ...texts } = output;
const suggestions = LOTSE_TEXT_FIELDS.filter((f) => texts[f]?.trim()).map((field) => ({
field,
text: texts[field].trim(),
state: "pending" as const,
decidedAt: null,
}));
return inTransaction(ctx, async (tx) => {
const generation = await tx.db.aiGeneration.create({
data: {
tenantId: tx.tenantId,
kind: "report_draft",
provider: meta.provider,
model: meta.model,
entityType: "report",
entityId: report.id,
input: input as unknown as Prisma.InputJsonValue,
output: { ...texts, missingInformation } as unknown as Prisma.InputJsonValue,
inputTokens: meta.inputTokens ?? null,
outputTokens: meta.outputTokens ?? null,
createdById: tx.userId,
},
});
const lotse: LotseBlock = {
generationId: generation.id,
model: meta.model,
draftedAt: now.toISOString(),
draftedById: tx.userId,
suggestions,
missingInformation,
reviewedAt: null,
reviewedById: null,
};
const res = await tx.db.report.updateMany({
where: { id: report.id, status: { in: ["draft", "rejected"] } },
data: { content: { ...content, lotse } as unknown as Prisma.InputJsonValue, aiDrafted: true, aiGenerationId: generation.id },
});
if (res.count !== 1) throw new ServiceError("conflict", "report changed concurrently");
await writeAuditLog({
tenantId: tx.tenantId,
actorId: tx.userId,
action: "update",
entity: "report",
entityId: report.id,
before: { aiDrafted: report.aiDrafted, aiGenerationId: report.aiGenerationId },
after: { aiDrafted: true, aiGenerationId: generation.id, suggestionFields: suggestions.map((s) => s.field), missingInformation: missingInformation.length },
});
return { reportId: report.id, generationId: generation.id, suggestions: suggestions.length, missingInformation };
});
}
+126
View File
@@ -0,0 +1,126 @@
import type { ReportContent } from "@/lib/reports/content";
import type { ReportDraftInput } from "@/server/ai/providers";
/**
* Data minimisation for everything sent to an AI provider (Spec §27, lane L9). Pure functions.
*
* - No phone numbers, e-mail addresses or postal addresses: known values of the order (customer,
* site, contact, tenant) are replaced literally, anything else that looks like one by pattern.
* - Employees → initials ("Max Monteur" → "M. M."), contact persons → "Ansprechpartner",
* private customers → "Kunde". The customer's company name is not sent at all.
* Placeholders: [Telefon], [E-Mail], [Adresse].
*/
export type MinimizationContext = {
/** employee names (all tenant users) → initials */
employees: string[];
/** contact persons / on-site contacts → "Ansprechpartner" */
contacts: string[];
/** private customer names → "Kunde" */
customerPersons: string[];
/** known phone numbers of the order */
phones: string[];
/** known e-mail addresses of the order */
emails: string[];
/** known address parts ("Hafenstraße 1", "20457", "Hamburg", …) */
addressParts: string[];
};
export const PLACEHOLDER = { phone: "[Telefon]", email: "[E-Mail]", address: "[Adresse]", contact: "Ansprechpartner", customer: "Kunde" } as const;
const NOT_WORD_BEFORE = "(?<![\\p{L}\\p{N}])";
const NOT_WORD_AFTER = "(?![\\p{L}\\p{N}])";
const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const EMAIL_RE = /[\p{L}\p{N}._%+-]+@[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*\.\p{L}{2,}/gu;
// German/international numbers start with + or 0; at least 7 digits (quantities, dates, order numbers stay).
const PHONE_RE = /(?<![\p{L}\p{N}])(?:\+|0)[\d \t/().-]{5,}\d(?![\p{L}\p{N}])/gu;
const STREET_RE =
/(?<![\p{L}])\p{Lu}[\p{L}ß-]*(?:straße|strasse|str\.|weg|allee|platz|gasse|ring|damm|chaussee|ufer|kai|pfad|steig)\s*\d+\s?[a-zA-Z]?(?![\p{L}\p{N}])/gu;
const POSTCODE_CITY_RE = /(?<![\p{N}])\d{5}\s+\p{Lu}[\p{L}-]+(?:\s(?:an der|am|im|in der)\s\p{Lu}[\p{L}-]+)?/gu;
/** "Max Monteur" → "M. M."; "Anna-Lena Bauer" → "A. B." */
export function initials(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (!parts.length) return "—";
return parts.map((p) => `${p[0].toUpperCase()}.`).join(" ");
}
function replaceLiteral(text: string, value: string, replacement: string): string {
const v = value.trim();
if (v.length < 3) return text;
return text.replace(new RegExp(`${NOT_WORD_BEFORE}${escape(v)}${NOT_WORD_AFTER}`, "giu"), replacement);
}
/** Name replacements: full names first, then single name parts (≥ 3 characters). */
function nameRules(ctx: MinimizationContext): Array<[string, string]> {
const rules: Array<[string, string]> = [];
const add = (names: string[], replacement: (full: string, part?: string) => string) => {
for (const full of names) {
const n = full.trim();
if (!n) continue;
rules.push([n, replacement(n)]);
const parts = n.split(/\s+/);
if (parts.length > 1) for (const p of parts) if (p.length >= 3) rules.push([p, replacement(n, p)]);
}
};
add(ctx.employees, (full, part) => (part ? `${part[0].toUpperCase()}.` : initials(full)));
add(ctx.contacts, () => PLACEHOLDER.contact);
add(ctx.customerPersons, () => PLACEHOLDER.customer);
return rules.sort((a, b) => b[0].length - a[0].length);
}
export function scrubText(text: string | null | undefined, ctx: MinimizationContext): string {
if (!text) return "";
let out = text;
for (const e of ctx.emails) out = replaceLiteral(out, e, PLACEHOLDER.email);
out = out.replace(EMAIL_RE, PLACEHOLDER.email);
for (const p of ctx.phones) out = replaceLiteral(out, p, PLACEHOLDER.phone);
out = out.replace(PHONE_RE, (m) => (m.replace(/\D/g, "").length >= 7 ? PLACEHOLDER.phone : m));
out = out.replace(STREET_RE, PLACEHOLDER.address).replace(POSTCODE_CITY_RE, PLACEHOLDER.address);
for (const a of [...ctx.addressParts].sort((x, y) => y.length - x.length)) out = replaceLiteral(out, a, PLACEHOLDER.address);
for (const [name, replacement] of nameRules(ctx)) out = replaceLiteral(out, name, replacement);
return out.replace(/\[Adresse\](?:[,\s]+\[Adresse\])+/g, PLACEHOLDER.address).trim();
}
export type DraftNote = { kind: string; text: string; at: Date; fromVoice: boolean };
/**
* Build the provider input from the report snapshot and the raw notes/transcripts. Only fields of
* `ReportDraftInput` leave the server; every free text passes `scrubText`.
*/
export function buildReportDraftInput(args: {
content: ReportContent;
notes: DraftNote[];
addressForm: ReportDraftInput["addressForm"];
locale: ReportDraftInput["locale"];
minimization: MinimizationContext;
}): ReportDraftInput {
const { content: c, minimization: m } = args;
const s = (t: string | null | undefined) => scrubText(t, m);
const materials = [...c.materials.used, ...c.materials.notUsed, ...c.materials.additional];
return {
locale: args.locale,
addressForm: args.addressForm,
workOrder: {
title: s(c.workOrder.title),
description: c.workOrder.description ? s(c.workOrder.description) : null,
scope: c.workOrder.scope ? s(c.workOrder.scope) : null,
orderType: c.workOrder.orderType,
},
notes: args.notes
.filter((n) => n.text.trim())
.map((n) => ({ kind: n.fromVoice ? `${n.kind} (Sprachnotiz)` : n.kind, text: s(n.text), at: n.at.toISOString() })),
checklist: c.checklist.map((i) => ({ label: s(i.label), checked: i.checked, comment: i.comment ? s(i.comment) : null })),
materials: materials.map((l) => ({
name: l.name,
...(l.plannedQuantity !== null ? { planned: l.plannedQuantity } : {}),
actual: l.actualQuantity ?? "",
unit: l.unit,
status: l.status ?? "undocumented",
reason: l.deviationReason ? s(l.deviationReason) : null,
})),
photos: c.photos.map((p) => ({ phase: p.phase, comment: p.comment ? s(p.comment) : null, requirement: p.requirement })),
time: c.time.entries.map((e) => ({ type: e.type, minutes: e.minutes, user: initials(e.name) })),
};
}
+46
View File
@@ -0,0 +1,46 @@
import { can, ServiceError, type ServiceCtx } from "@/server/services/context";
/**
* AiGeneration protocol (Spec §15.4 Transparenz, lane L9): time, kind, model, tokens, user.
* Readable with `tenant:manage` or `audit:read`; inputs/outputs (the data sent to / returned by the
* provider) only with `tenant:manage`.
*/
export const PROTOCOL_PAGE_SIZE = 50;
export function canReadProtocol(ctx: ServiceCtx): boolean {
return can(ctx, "tenant:manage") || can(ctx, "audit:read");
}
export async function listAiGenerations(ctx: ServiceCtx, opts: { page?: number; kind?: string } = {}) {
if (!canReadProtocol(ctx)) throw new ServiceError("forbidden", "missing permission audit:read");
const page = Math.max(1, Math.floor(opts.page ?? 1));
const where = opts.kind ? { kind: opts.kind } : {};
const [rows, total] = await Promise.all([
ctx.db.aiGeneration.findMany({
where,
orderBy: { createdAt: "desc" },
skip: (page - 1) * PROTOCOL_PAGE_SIZE,
take: PROTOCOL_PAGE_SIZE,
select: { id: true, createdAt: true, kind: true, provider: true, model: true, entityType: true, entityId: true, inputTokens: true, outputTokens: true, createdById: true },
}),
ctx.db.aiGeneration.count({ where }),
]);
const userIds = [...new Set(rows.map((r) => r.createdById).filter((x): x is string => Boolean(x)))];
const users = userIds.length ? await ctx.db.user.findMany({ where: { id: { in: userIds } }, select: { id: true, name: true } }) : [];
const nameOf = new Map(users.map((u) => [u.id, u.name]));
return {
items: rows.map((r) => ({ ...r, userName: r.createdById ? (nameOf.get(r.createdById) ?? null) : null })),
total,
page,
pageSize: PROTOCOL_PAGE_SIZE,
canSeeContent: can(ctx, "tenant:manage"),
};
}
export async function getAiGenerationContent(ctx: ServiceCtx, id: string) {
if (!can(ctx, "tenant:manage")) throw new ServiceError("forbidden", "missing permission tenant:manage");
const row = await ctx.db.aiGeneration.findFirst({ where: { id }, select: { id: true, kind: true, model: true, createdAt: true, input: true, output: true } });
if (!row) throw new ServiceError("not_found", "ai generation not found");
return row;
}
+24
View File
@@ -0,0 +1,24 @@
import type { Report } from "@prisma/client";
import type { ReportContent } from "@/lib/reports/content";
import { ServiceError, type ServiceCtx } from "@/server/services/context";
/**
* Freigabeprinzip (Spec §15.3, lane L9): a report the Lotse has drafted (`aiDrafted`) must never be
* submitted without an explicit human confirmation. Called by `submitReport` BEFORE anything is written.
*
* Throws `invalid` with `details.field = "aiReviewed"` when the confirmation is missing; otherwise
* returns the content with the review proof (`lotse.reviewedAt/reviewedById`) that is persisted with
* the submission and frozen with the approval. Reports without Lotse involvement pass unchanged.
*/
export function applyLotseReview(
ctx: ServiceCtx,
report: Pick<Report, "aiDrafted">,
content: ReportContent,
aiReviewed: boolean | undefined,
now: Date = new Date(),
): ReportContent {
if (!report.aiDrafted) return content;
if (aiReviewed !== true) throw new ServiceError("invalid", "lotse draft must be reviewed before submit", { field: "aiReviewed" });
if (!content.lotse) return content;
return { ...content, lotse: { ...content.lotse, reviewedAt: now.toISOString(), reviewedById: ctx.userId } };
}
+83
View File
@@ -0,0 +1,83 @@
import { z } from "zod";
import { LOTSE_ADDRESS_FORMS, type LotseAddressForm } from "@/lib/lotse/content";
import type { ReportDraftInput } from "@/server/ai/providers";
import { AI_MODEL, isAiConfigured } from "@/server/ai/client";
import { transcriptionConfig } from "@/server/ai/transcription/openai-compatible";
import { writeAuditLog } from "@/server/audit";
import { assertCan, inTransaction, ServiceError, type ServiceCtx } from "@/server/services/context";
/**
* Lotse settings per tenant (lane L9): on/off = module toggle `lotse` (TenantModule, missing row = on),
* address form = `TenantSettings.lotseAddressForm` ("sie" | "du" | null = neutral).
*/
export const LOTSE_MODULE_KEY = "lotse";
export async function isLotseEnabled(ctx: Pick<ServiceCtx, "db" | "tenantId">): Promise<boolean> {
const row = await ctx.db.tenantModule.findUnique({
where: { tenantId_moduleKey: { tenantId: ctx.tenantId, moduleKey: LOTSE_MODULE_KEY } },
select: { enabled: true },
});
return !row || row.enabled;
}
/** Throws `forbidden` (details.reason = "disabled") when the tenant switched the Lotse off. */
export async function assertLotseEnabled(ctx: ServiceCtx): Promise<void> {
if (!(await isLotseEnabled(ctx))) throw new ServiceError("forbidden", "lotse disabled for tenant", { reason: "disabled" });
}
function toAddressForm(v: string | null | undefined): LotseAddressForm | null {
return (LOTSE_ADDRESS_FORMS as readonly string[]).includes(v ?? "") ? (v as LotseAddressForm) : null;
}
/** Address form and language for prompts. */
export async function lotseVoice(ctx: Pick<ServiceCtx, "db">): Promise<{ addressForm: ReportDraftInput["addressForm"]; locale: ReportDraftInput["locale"] }> {
const s = await ctx.db.tenantSettings.findFirst({ select: { lotseAddressForm: true, locale: true } });
return { addressForm: toAddressForm(s?.lotseAddressForm) ?? "neutral", locale: s?.locale === "en" ? "en" : "de" };
}
export async function getLotseSettings(ctx: ServiceCtx) {
assertCan(ctx, "tenant:manage");
const [enabled, s] = await Promise.all([isLotseEnabled(ctx), ctx.db.tenantSettings.findFirst({ select: { lotseAddressForm: true } })]);
const transcription = transcriptionConfig();
return {
enabled,
addressForm: toAddressForm(s?.lotseAddressForm),
draft: { configured: isAiConfigured(), provider: "Anthropic (Claude)", model: AI_MODEL },
transcription,
};
}
export const lotseSettingsSchema = z.object({
enabled: z.boolean(),
addressForm: z.enum(["sie", "du", "neutral"]),
});
export type LotseSettingsInput = z.input<typeof lotseSettingsSchema>;
export async function updateLotseSettings(ctx: ServiceCtx, raw: LotseSettingsInput) {
assertCan(ctx, "tenant:manage");
const input = lotseSettingsSchema.parse(raw);
const addressForm = input.addressForm === "neutral" ? null : input.addressForm;
const before = {
enabled: await isLotseEnabled(ctx),
addressForm: (await ctx.db.tenantSettings.findFirst({ select: { lotseAddressForm: true } }))?.lotseAddressForm ?? null,
};
await inTransaction(ctx, async (tx) => {
await tx.db.tenantModule.upsert({
where: { tenantId_moduleKey: { tenantId: tx.tenantId, moduleKey: LOTSE_MODULE_KEY } },
update: { enabled: input.enabled },
create: { tenantId: tx.tenantId, moduleKey: LOTSE_MODULE_KEY, enabled: input.enabled },
});
const existing = await tx.db.tenantSettings.findFirst({ select: { id: true } });
if (existing) {
await tx.db.tenantSettings.update({ where: { id: existing.id }, data: { lotseAddressForm: addressForm } });
} else {
const tenant = await tx.db.tenant.findUnique({ where: { id: tx.tenantId }, select: { name: true } });
await tx.db.tenantSettings.create({ data: { tenantId: tx.tenantId, orgName: tenant?.name ?? "—", lotseAddressForm: addressForm } });
}
});
const after = { enabled: input.enabled, addressForm };
await writeAuditLog({ tenantId: ctx.tenantId, actorId: ctx.userId, action: "update", entity: "lotse_settings", entityId: ctx.tenantId, before, after });
return after;
}
+70
View File
@@ -0,0 +1,70 @@
import type { Report } from "@prisma/client";
import { dayWindow, dbDateToKey } from "@/lib/reports/dates";
import type { ServiceCtx } from "@/server/services/context";
import { tenantTimeZone } from "@/server/services/reports/build-content";
import type { DraftNote, MinimizationContext } from "./minimize";
const nonEmpty = (xs: Array<string | null | undefined>) => [...new Set(xs.map((x) => x?.trim() ?? "").filter(Boolean))];
/** Everything that must never reach the model for this work order (literal values for scrubText). */
export async function loadMinimizationContext(ctx: ServiceCtx, workOrderId: string): Promise<MinimizationContext> {
const [wo, users, settings] = await Promise.all([
ctx.db.workOrder.findFirstOrThrow({
where: { id: workOrderId },
select: {
customer: { select: { companyName: true, firstName: true, lastName: true, phone: true, mobile: true, email: true, street: true, houseNumber: true, postalCode: true, city: true, contacts: { select: { name: true, phone: true, mobile: true, email: true } } } },
site: { select: { street: true, houseNumber: true, postalCode: true, city: true, phone: true, onSiteContact: true } },
contact: { select: { name: true, phone: true, mobile: true, email: true } },
},
}),
ctx.db.user.findMany({ select: { name: true }, take: 1000 }),
ctx.db.tenantSettings.findFirst({ select: { phone: true, email: true, address: true } }),
]);
const c = wo.customer;
const contacts = [...c.contacts, ...(wo.contact ? [wo.contact] : [])];
const street = (s?: string | null, n?: string | null) => [s, n].filter(Boolean).join(" ");
return {
employees: nonEmpty(users.map((u) => u.name)),
contacts: nonEmpty([...contacts.map((x) => x.name), wo.site?.onSiteContact]),
customerPersons: c.companyName ? [] : nonEmpty([[c.firstName, c.lastName].filter(Boolean).join(" ")]),
phones: nonEmpty([c.phone, c.mobile, wo.site?.phone, settings?.phone, ...contacts.flatMap((x) => [x.phone, x.mobile])]),
emails: nonEmpty([c.email, settings?.email, ...contacts.map((x) => x.email)]),
addressParts: nonEmpty([
street(c.street, c.houseNumber),
c.postalCode,
c.city,
street(wo.site?.street, wo.site?.houseNumber),
wo.site?.postalCode,
wo.site?.city,
settings?.address,
]),
};
}
/**
* Raw documentation of the report period: activity notes (incl. notes created from voice notes)
* plus transcripts not linked to a note. Daily report = tenant-local day only.
*/
export async function loadDraftNotes(ctx: ServiceCtx, report: Pick<Report, "workOrderId" | "type" | "reportDate">): Promise<DraftNote[]> {
let range: { gte: Date; lt: Date } | undefined;
if (report.type === "daily") {
const win = dayWindow(dbDateToKey(report.reportDate), await tenantTimeZone(ctx));
range = { gte: win.start, lt: win.end };
}
const [notes, voices] = await Promise.all([
ctx.db.activityNote.findMany({
where: { workOrderId: report.workOrderId, deletedAt: null, ...(range ? { createdAt: range } : {}) },
orderBy: { createdAt: "asc" },
select: { kind: true, text: true, createdAt: true, voiceNoteId: true },
}),
ctx.db.voiceNote.findMany({
where: { workOrderId: report.workOrderId, transcript: { not: null }, activityNote: null, ...(range ? { recordedAt: range } : {}) },
orderBy: { recordedAt: "asc" },
select: { transcript: true, recordedAt: true },
}),
]);
return [
...notes.map((n) => ({ kind: n.kind, text: n.text, at: n.createdAt, fromVoice: Boolean(n.voiceNoteId) })),
...voices.map((v) => ({ kind: "general", text: v.transcript ?? "", at: v.recordedAt, fromVoice: true })),
].sort((a, b) => a.at.getTime() - b.at.getTime());
}
+31
View File
@@ -0,0 +1,31 @@
import { REPORT_EDITABLE, type ReportStatus } from "@/lib/reports/content";
import type { LotseBlock } from "@/lib/lotse/content";
import { isAiConfigured } from "@/server/ai/client";
import { can, type ServiceCtx } from "@/server/services/context";
import { contentOf, requireVisibleReport } from "@/server/services/reports/common";
import { isLotseEnabled } from "./settings";
/** Read model for the Lotse panel in the report editors (mobile + backoffice). `null` = render nothing. */
export async function getLotseReportState(ctx: ServiceCtx, reportId: string): Promise<{
reportId: string;
editable: boolean;
canDraft: boolean;
configured: boolean;
lotse: LotseBlock | null;
texts: Record<string, string>;
} | null> {
if (!can(ctx, "lotse:use") && !can(ctx, "report:read")) return null;
const report = await requireVisibleReport(ctx, reportId);
const content = contentOf(report);
const enabled = await isLotseEnabled(ctx);
if (!enabled && !content.lotse) return null;
const editable = REPORT_EDITABLE.includes(report.status as ReportStatus);
return {
reportId: report.id,
editable,
canDraft: enabled && editable && can(ctx, "lotse:use") && can(ctx, "report:write"),
configured: isAiConfigured(),
lotse: content.lotse ?? null,
texts: content.texts,
};
}
+60
View File
@@ -0,0 +1,60 @@
import type { Prisma } from "@prisma/client";
import { z } from "zod";
import { LOTSE_TEXT_FIELDS, LOTSE_TEXT_MAX } from "@/lib/lotse/content";
import { REPORT_EDITABLE, type ReportStatus } from "@/lib/reports/content";
import { writeAuditLog } from "@/server/audit";
import { assertCan, ServiceError, type ServiceCtx } from "@/server/services/context";
import { contentOf, requireVisibleReport } from "@/server/services/reports/common";
export const decideSuggestionSchema = z.object({
reportId: z.string().min(1).max(64),
field: z.enum(LOTSE_TEXT_FIELDS),
decision: z.enum(["accept", "discard"]),
/** edited suggestion text ("bearbeiten, dann übernehmen"); defaults to the suggestion */
text: z.string().max(LOTSE_TEXT_MAX).optional(),
});
export type DecideSuggestionInput = z.input<typeof decideSuggestionSchema>;
/**
* Person decides on one Lotse suggestion: accept (optionally edited) → replaces the report text field;
* discard → text stays. The model output itself is never written to the texts without this step.
* Needs only `report:write` (a draft can still be finished if the Lotse was switched off meanwhile).
*/
export async function decideLotseSuggestion(ctx: ServiceCtx, raw: DecideSuggestionInput) {
assertCan(ctx, "report:write");
const input = decideSuggestionSchema.parse(raw);
const report = await requireVisibleReport(ctx, input.reportId);
if (!REPORT_EDITABLE.includes(report.status as ReportStatus)) throw new ServiceError("blocked", `report is ${report.status}`, { reason: "not_editable" });
const content = contentOf(report);
const suggestion = content.lotse?.suggestions.find((s) => s.field === input.field);
if (!content.lotse || !suggestion || suggestion.state !== "pending") throw new ServiceError("conflict", "no pending suggestion", { reason: "no_suggestion" });
const decidedAt = new Date().toISOString();
const textBefore = content.texts[input.field];
const textAfter = input.decision === "accept" ? (input.text ?? suggestion.text).trim() : textBefore;
const next = {
...content,
texts: { ...content.texts, [input.field]: textAfter },
lotse: {
...content.lotse,
suggestions: content.lotse.suggestions.map((s) =>
s.field === input.field ? { ...s, state: input.decision === "accept" ? ("accepted" as const) : ("discarded" as const), decidedAt } : s,
),
},
};
const res = await ctx.db.report.updateMany({
where: { id: report.id, status: { in: ["draft", "rejected"] }, updatedAt: report.updatedAt },
data: { content: next as unknown as Prisma.InputJsonValue },
});
if (res.count !== 1) throw new ServiceError("conflict", "report changed concurrently");
await writeAuditLog({
tenantId: ctx.tenantId,
actorId: ctx.userId,
action: "update",
entity: "report",
entityId: report.id,
before: { field: input.field, suggestion: "pending", text: textBefore },
after: { field: input.field, suggestion: input.decision === "accept" ? "accepted" : "discarded", text: textAfter, edited: input.decision === "accept" && input.text !== undefined && input.text.trim() !== suggestion.text },
});
return { reportId: report.id, workOrderId: report.workOrderId };
}
+110
View File
@@ -0,0 +1,110 @@
import type { TranscriptionStatus } from "@prisma/client";
import type { TranscriptionProvider } from "@/server/ai/providers";
import { getTranscriptionProvider } from "@/server/ai/transcription/openai-compatible";
import { writeAuditLog } from "@/server/audit";
import { inTransaction, type ServiceCtx } from "@/server/services/context";
import { readDocumentBytes } from "@/server/services/documents/read";
import { isLotseEnabled } from "./settings";
export type TranscriptionDeps = {
provider: TranscriptionProvider | null;
loadBytes: (ctx: ServiceCtx, documentId: string) => Promise<{ bytes: Buffer; mimeType: string }>;
};
export const defaultTranscriptionDeps = (): TranscriptionDeps => ({
provider: getTranscriptionProvider(),
loadBytes: (ctx, documentId) => readDocumentBytes(ctx, documentId),
});
/** Separator when a transcript is appended to an existing activity note. */
export const TRANSCRIPT_SEPARATOR = "\n\n";
/**
* Transcribe one VoiceNote (job `transcription`, ARCHITEKTUR §4.4). System context: tenant from the
* job payload, no permission checks (the note was created by an authorised user).
*
* pending → done (transcript, transcriptionModel, AiGeneration; transcript appended to the linked
* ActivityNote or a new note kind `general` linked via voiceNoteId = „aus Sprachnotiz“)
* pending → disabled (no provider configured or Lotse switched off for the tenant)
* pending → failed (provider/storage error; no content in logs).
* Idempotent: notes that are no longer pending are left untouched.
*/
export async function processTranscription(ctx: ServiceCtx, voiceNoteId: string, deps: TranscriptionDeps = defaultTranscriptionDeps()): Promise<TranscriptionStatus | null> {
const voice = await ctx.db.voiceNote.findFirst({
where: { id: voiceNoteId },
select: { id: true, workOrderId: true, documentId: true, durationSeconds: true, recordedById: true, recordedAt: true, transcriptionStatus: true, activityNote: { select: { id: true, text: true } } },
});
if (!voice) return null;
if (voice.transcriptionStatus !== "pending") return voice.transcriptionStatus;
const actorId = ctx.userId || voice.recordedById || undefined;
const setStatus = async (status: TranscriptionStatus, reason: string) => {
await ctx.db.voiceNote.updateMany({ where: { id: voice.id, transcriptionStatus: "pending" }, data: { transcriptionStatus: status } });
await writeAuditLog({ tenantId: ctx.tenantId, actorId, action: "update", entity: "voice_note", entityId: voice.id, before: { transcriptionStatus: "pending" }, after: { transcriptionStatus: status, reason } });
return status;
};
if (!(await isLotseEnabled(ctx))) return setStatus("disabled", "lotse_disabled");
if (!deps.provider) return setStatus("disabled", "not_configured");
let text: string;
let meta;
let size = 0;
let mimeType = "";
try {
const file = await deps.loadBytes(ctx, voice.documentId);
size = file.bytes.byteLength;
mimeType = file.mimeType;
const res = await deps.provider.transcribe({ bytes: file.bytes, mimeType: file.mimeType, language: "de" });
text = res.text.trim();
meta = res.meta;
} catch (err) {
console.error(`[lotse] transcription of voice note ${voice.id} failed:`, (err as Error).message);
return setStatus("failed", "provider_failed");
}
return inTransaction(ctx, async (tx) => {
const res = await tx.db.voiceNote.updateMany({
where: { id: voice.id, transcriptionStatus: "pending" },
data: { transcript: text, transcriptionStatus: "done", transcriptionModel: meta.model },
});
if (res.count !== 1) return "done" as const; // processed concurrently
await tx.db.aiGeneration.create({
data: {
tenantId: tx.tenantId,
kind: "transcription",
provider: meta.provider,
model: meta.model,
entityType: "voice_note",
entityId: voice.id,
input: { documentId: voice.documentId, mimeType, size, durationSeconds: voice.durationSeconds },
output: { characters: text.length },
inputTokens: meta.inputTokens ?? null,
outputTokens: meta.outputTokens ?? null,
createdById: actorId ?? null,
},
});
let noteId: string | null = null;
if (text) {
if (voice.activityNote) {
await tx.db.activityNote.update({ where: { id: voice.activityNote.id }, data: { text: `${voice.activityNote.text}${TRANSCRIPT_SEPARATOR}${text}` } });
noteId = voice.activityNote.id;
} else {
const note = await tx.db.activityNote.create({
data: { tenantId: tx.tenantId, workOrderId: voice.workOrderId, authorId: voice.recordedById, kind: "general", text, voiceNoteId: voice.id, createdAt: voice.recordedAt },
});
noteId = note.id;
}
}
await writeAuditLog({
tenantId: tx.tenantId,
actorId,
action: "update",
entity: "voice_note",
entityId: voice.id,
before: { transcriptionStatus: "pending" },
after: { transcriptionStatus: "done", transcriptionModel: meta.model, activityNoteId: noteId },
});
return "done" as const;
});
}
+125
View File
@@ -0,0 +1,125 @@
import { z } from "zod";
import { LOTSE_TEXT_MAX } from "@/lib/lotse/content";
import { writeAuditLog } from "@/server/audit";
import { assertCan, inTransaction, ServiceError, type ServiceCtx } from "@/server/services/context";
import { requireFieldOrder } from "@/server/services/field/common";
import { createNote } from "@/server/services/field/notes";
import { workOrderScope } from "@/server/services/work-orders/visibility";
import { defaultLotseDeps, type LotseDeps } from "./draft-report";
import { scrubText } from "./minimize";
import { assertLotseEnabled, lotseVoice } from "./settings";
import { loadMinimizationContext } from "./sources";
import { TRANSCRIPT_SEPARATOR } from "./transcription";
/** Voice note in the caller's work order scope, or not_found (existence is never revealed). */
async function requireVisibleVoiceNote(ctx: ServiceCtx, voiceNoteId: string) {
const voice = await ctx.db.voiceNote.findFirst({
where: { id: voiceNoteId, workOrder: await workOrderScope(ctx) },
select: { id: true, workOrderId: true, transcript: true, transcriptionStatus: true, activityNote: { select: { id: true, text: true } } },
});
if (!voice) throw new ServiceError("not_found", "voice note not found");
return voice;
}
export const updateTranscriptSchema = z.object({
voiceNoteId: z.string().min(1).max(64),
transcript: z.string().max(LOTSE_TEXT_MAX),
});
/**
* Correct a transcript (or type it in when transcription is disabled/failed). Keeps the linked
* activity note in sync: a note created from the voice note gets the new text; an appended
* transcript is replaced in place; otherwise a note „aus Sprachnotiz“ is created.
*/
export async function updateTranscript(ctx: ServiceCtx, raw: z.input<typeof updateTranscriptSchema>) {
assertCan(ctx, "field:execute");
const input = updateTranscriptSchema.parse(raw);
const voice = await requireVisibleVoiceNote(ctx, input.voiceNoteId);
await requireFieldOrder(ctx, voice.workOrderId, { editable: true });
if (voice.transcriptionStatus === "pending") throw new ServiceError("conflict", "transcription still running", { reason: "pending" });
const next = input.transcript.trim();
const previous = voice.transcript ?? "";
await inTransaction(ctx, async (tx) => {
await tx.db.voiceNote.update({ where: { id: voice.id }, data: { transcript: next || null } });
const note = voice.activityNote;
if (note) {
let text = note.text;
if (text === previous) text = next;
else if (previous && text.endsWith(`${TRANSCRIPT_SEPARATOR}${previous}`)) text = `${text.slice(0, -previous.length)}${next}`;
else if (previous && text.includes(previous)) text = text.replace(previous, next);
if (text.trim() && text !== note.text) await tx.db.activityNote.update({ where: { id: note.id }, data: { text } });
} else if (next) {
const current = await tx.db.voiceNote.findFirstOrThrow({ where: { id: voice.id }, select: { recordedAt: true, recordedById: true } });
await tx.db.activityNote.create({
data: { tenantId: tx.tenantId, workOrderId: voice.workOrderId, authorId: current.recordedById ?? tx.userId, kind: "general", text: next, voiceNoteId: voice.id, createdAt: current.recordedAt },
});
}
});
await writeAuditLog({ tenantId: ctx.tenantId, actorId: ctx.userId, action: "update", entity: "voice_note", entityId: voice.id, before: { transcript: previous }, after: { transcript: next } });
return { voiceNoteId: voice.id, workOrderId: voice.workOrderId };
}
/** „Sprachnotiz zusammenfassen“: minimised transcript → Lotse → AiGeneration (voice_summary). */
export async function summarizeVoiceNote(ctx: ServiceCtx, voiceNoteId: string, deps: LotseDeps = defaultLotseDeps()) {
assertCan(ctx, "lotse:use");
const voice = await requireVisibleVoiceNote(ctx, voiceNoteId);
await assertLotseEnabled(ctx);
if (!voice.transcript?.trim()) throw new ServiceError("invalid", "voice note has no transcript", { reason: "no_transcript" });
if (!deps.provider) throw new ServiceError("invalid", "lotse provider not configured", { reason: "not_configured" });
const [minimization, lang] = await Promise.all([loadMinimizationContext(ctx, voice.workOrderId), lotseVoice(ctx)]);
const transcript = scrubText(voice.transcript, minimization);
let result;
try {
result = await deps.provider.summarizeTranscript({ transcript, ...lang });
} catch (err) {
console.error("[lotse] voice summary failed:", (err as Error).message);
throw new ServiceError("conflict", "lotse provider failed", { reason: "provider_failed" });
}
const generation = await ctx.db.aiGeneration.create({
data: {
tenantId: ctx.tenantId,
kind: "voice_summary",
provider: result.meta.provider,
model: result.meta.model,
entityType: "voice_note",
entityId: voice.id,
input: { transcript, ...lang },
output: { summary: result.summary },
inputTokens: result.meta.inputTokens ?? null,
outputTokens: result.meta.outputTokens ?? null,
createdById: ctx.userId,
},
});
await writeAuditLog({ tenantId: ctx.tenantId, actorId: ctx.userId, action: "create", entity: "ai_generation", entityId: generation.id, after: { kind: "voice_summary", voiceNoteId: voice.id, model: generation.model } });
return { generationId: generation.id, summary: result.summary, workOrderId: voice.workOrderId };
}
/** Take a summary over as a new activity note (idempotent per summary). The transcript stays unchanged. */
export async function adoptVoiceSummary(ctx: ServiceCtx, generationId: string) {
assertCan(ctx, "field:execute");
const gen = await ctx.db.aiGeneration.findFirst({ where: { id: generationId, kind: "voice_summary", entityType: "voice_note" }, select: { id: true, entityId: true, output: true } });
if (!gen?.entityId) throw new ServiceError("not_found", "summary not found");
const voice = await requireVisibleVoiceNote(ctx, gen.entityId);
const summary = (gen.output as { summary?: unknown } | null)?.summary;
if (typeof summary !== "string" || !summary.trim()) throw new ServiceError("invalid", "summary is empty");
const res = await createNote(ctx, { workOrderId: voice.workOrderId, kind: "work_done", text: summary.trim(), clientId: `lotse-summary-${gen.id}` });
return { noteId: res.noteId, workOrderId: voice.workOrderId };
}
/** Latest summary per voice note (for the notes page). */
export async function latestVoiceSummaries(ctx: ServiceCtx, voiceNoteIds: string[]): Promise<Map<string, { generationId: string; summary: string }>> {
if (!voiceNoteIds.length) return new Map();
const rows = await ctx.db.aiGeneration.findMany({
where: { kind: "voice_summary", entityType: "voice_note", entityId: { in: voiceNoteIds } },
orderBy: { createdAt: "desc" },
select: { id: true, entityId: true, output: true },
});
const map = new Map<string, { generationId: string; summary: string }>();
for (const r of rows) {
const summary = (r.output as { summary?: unknown } | null)?.summary;
if (r.entityId && !map.has(r.entityId) && typeof summary === "string") map.set(r.entityId, { generationId: r.id, summary });
}
return map;
}
+2 -1
View File
@@ -27,7 +27,7 @@ export function contentOf(report: Pick<Report, "content">): ReportContent {
/** Rebuild DB-derived parts of a report snapshot while keeping number, version and edited texts. */
export async function refreshContent(ctx: ServiceCtx, report: Report): Promise<ReportContent> {
const current = contentOf(report);
return buildReportContent(ctx, {
const built = await buildReportContent(ctx, {
workOrderId: report.workOrderId,
type: report.type,
reportDate: dbDateToKey(report.reportDate),
@@ -38,6 +38,7 @@ export async function refreshContent(ctx: ServiceCtx, report: Report): Promise<R
previousSignature: current.signature,
technicianUserId: report.createdById,
});
return current.lotse ? { ...built, lotse: current.lotse } : built; // L9: keep Lotse suggestions/review proof
}
/** Compact, PII-light audit projection of a report. */
+4 -1
View File
@@ -7,12 +7,15 @@ import { assertCan, ServiceError, type ServiceCtx } from "@/server/services/cont
// TODO(merge L2): import from "@/server/services/work-orders/transition" and ".../guards"
import { getCompletionBlockers } from "@/server/services/work-orders/completion";
import { transitionWorkOrder } from "@/server/services/work-orders/transition";
import { applyLotseReview } from "@/server/services/lotse/review";
import { auditReport, assertEditable, orderNumberOf, refreshContent, reportAuditView, requireVisibleReport } from "./common";
export const submitReportSchema = z.object({
reportId: z.string().min(1).max(64),
/** WorkOrder.version seen by the device (offline sync conflict detection) */
expectedWorkOrderVersion: z.number().int().positive().optional(),
/** L9: submitter confirmed "Ich habe den Vorschlag geprüft" — mandatory for Lotse-drafted reports */
aiReviewed: z.boolean().optional(),
});
export type SubmitReportInput = z.input<typeof submitReportSchema>;
@@ -71,7 +74,7 @@ export async function submitReport(ctx: ServiceCtx, raw: SubmitReportInput): Pro
throw new ServiceError("conflict", "work order version changed");
}
const content = await refreshContent(ctx, report);
const content = applyLotseReview(ctx, report, await refreshContent(ctx, report), input.aiReviewed); // L9 Freigabeprinzip
const blockers: CompletionBlocker[] = missingRequiredTexts(content).map((field) => ({ kind: "missing_field", field }));
if (report.type === "completion" && report.version === 1) blockers.push(...(await getCompletionBlockers(ctx, wo.id)));
if (blockers.length) throw new ServiceError("blocked", "report incomplete", blockers);