import type { DemoProSeedGraph, ProjectType, SeedProject } from "./types"; import { buildSeedFileObjectMetadata } from "./file-objects"; export const OPERATIONAL_COUNTS = { projectContacts: 1_611, projectMembers: 1_876, tasks: 1_684, taskWatchers: 421, activities: 2_731, scheduleEntries: 1_147, scheduleConflicts: 23, calendarEvents: 613, projectAppointments: 613, bookingPages: 3, bookingProviders: 21, availabilityRules: 35, availabilityExceptions: 7, bookingAppointments: 79, invoices: 347, checklists: 329, checklistItems: 1_693, files: 917, acceptances: 73, acceptanceSignatures: 146, signatureDocuments: 47, signatureSigners: 47, } as const; type ProjectContact = { id: string; projectId: string; contactId: string; role: "auftraggeber" | "bauherr" | "rechnungsempfaenger" | "ansprechpartner"; primary: boolean; }; type ProjectMember = { id: string; projectId: string; userId: string | null; groupId: string | null; role: "monteur" | "projektleiter" | "zustaendig"; }; type SeedTask = { id: string; projectId: string; title: string; description: string; status: "open" | "in_progress" | "blocked" | "done" | "cancelled"; priority: "low" | "normal" | "high" | "urgent"; deadline: string; assignedToUserId: string | null; assignedToGroupId: string | null; completedAt: string | null; createdAt: string; updatedAt: string; }; type SeedActivity = { id: string; projectId: string; actorUserId: string; activityType: string; createdAt: string; summaryText: string; metadata: Record; }; type SeedScheduleEntry = { id: string; projectId: string; assignedUserId: string; title: string; startAt: string; endAt: string; status: "planned" | "confirmed" | "in_progress" | "done" | "cancelled"; calendarEventId: string | null; syncStatus: "pending" | "synced"; }; type SeedCalendarEvent = { id: string; projectId: string; userId: string; title: string; description: string; location: string; startsAt: string; endsAt: string; }; type SeedBookingPage = { id: string; slug: string; title: string; description: string; durationMinutes: number; }; type SeedBookingAppointment = { id: string; bookingPageId: string; providerUserId: string; contactId: string; projectId: string; internalCalendarEventId: string; startsAt: string; endsAt: string; status: "scheduled" | "held" | "cancelled"; customerName: string; customerEmail: string; customerPhone: string; request: string; }; type SeedInvoice = { id: string; projectId: string; invoiceNumber: string; amount: string; status: "entwurf" | "gestellt" | "bezahlt" | "storniert"; date: string; dueAt: string; fileId: string | null; createdAt: string; updatedAt: string; }; type SeedChecklist = { id: string; projectId: string; title: string; type: "generisch" | "maengel" | "abnahme_doku"; }; type SeedChecklistItem = { id: string; checklistId: string; title: string; status: "offen" | "erledigt" | "entfaellt"; defectClass: string | null; assignedToUserId: string; dueAt: string; position: number; photoFileId: null; }; type SeedFile = { id: string; projectId: string; displayName: string; mimeType: string; sizeBytes: number; checksumSha256: string; assignedToUserId: string; tags: string[]; notes: string; linkRole: string; createdAt: string; updatedAt: string; }; type SeedAcceptance = { id: string; projectId: string; checklistId: string | null; creatorUserId: string; date: string; kind: "full" | "with_defects"; attendees: string[]; remarks: string; customerEmail: string; documentFileId: string | null; createdAt: string; updatedAt: string; }; type SeedSignatureDocument = { id: string; projectId: string; sourceFileId: string; creatorUserId: string; status: "sent" | "viewed" | "signed"; title: string; sentAt: string; completedAt: string | null; signerContactId: string; signerEmail: string; signerName: string; createdAt: string; updatedAt: string; }; export type DemoProOperationalGraph = { projectContacts: ProjectContact[]; projectMembers: ProjectMember[]; tasks: SeedTask[]; taskWatchers: Array<{ id: string; taskId: string; userId: string }>; activities: SeedActivity[]; scheduleEntries: SeedScheduleEntry[]; scheduleConflicts: Array<{ id: string; entryId: string; sourceEntryId: string; resolvedAt: string | null }>; calendarEvents: SeedCalendarEvent[]; projectAppointments: Array; bookingPages: SeedBookingPage[]; bookingProviders: Array<{ id: string; bookingPageId: string; providerUserId: string; displayOrder: number }>; availabilityRules: Array<{ id: string; providerUserId: string; dayOfWeek: "monday" | "tuesday" | "wednesday" | "thursday" | "friday"; startTime: string; endTime: string; }>; availabilityExceptions: Array<{ id: string; providerUserId: string; date: string; kind: "unavailable" | "custom_window"; startTime: string | null; endTime: string | null; reason: string; }>; bookingAppointments: SeedBookingAppointment[]; invoices: SeedInvoice[]; checklists: SeedChecklist[]; checklistItems: SeedChecklistItem[]; files: SeedFile[]; acceptances: SeedAcceptance[]; acceptanceSignatures: Array<{ id: string; acceptanceId: string; signerName: string; signerRole: "kunde" | "monteur"; signedAt: string }>; signatureDocuments: SeedSignatureDocument[]; signatureSigners: Array<{ id: string; documentId: string; contactId: string; email: string; name: string; status: "sent" | "viewed" | "signed"; signedAt: string | null; }>; }; const taskTemplates: Readonly> = { reparatur_notdienst: [ "Störungsbild telefonisch aufnehmen", "Ersatzteile und Werkzeug disponieren", "Einsatzbericht mit Messwerten abschließen", "Kunden über Folgemaßnahmen informieren", ], wartung_pruefung: [ "Anlagendaten und Wartungshistorie prüfen", "Wartungsmaterial zusammenstellen", "Mess- und Wartungsprotokoll erfassen", "Nächsten Wartungszyklus vormerken", ], heizungstausch: [ "Heizlast und Bestandssituation prüfen", "Wärmeerzeuger und Speicher disponieren", "Montageablauf mit Kunde abstimmen", "Inbetriebnahme und Einweisung dokumentieren", ], heizungsoptimierung: [ "Bestandswerte und Heizkreise aufnehmen", "Einstellwerte berechnen", "Optimierungsmaßnahmen ausführen", "Verbrauchsempfehlungen dokumentieren", ], badsanierung: [ "Aufmaß und Ausstattungsdetails bestätigen", "Sanitärobjekte und Armaturen disponieren", "Gewerkeablauf koordinieren", "Abnahme und Pflegehinweise vorbereiten", ], sanitaer_rohrarbeiten: [ "Leitungsverlauf und Absperrungen prüfen", "Rohrmaterial disponieren", "Druckprobe dokumentieren", "Bestandsunterlagen aktualisieren", ], objekt_neubau: [ "Ausführungsplanung mit Fachplanung abstimmen", "Bauzeitenplan und Materialabrufe aktualisieren", "Montagefortschritt dokumentieren", "Teilabnahme vorbereiten", ], lueftung_klima: [ "Luftmengen und Aufstellorte prüfen", "Geräte und Kanalmaterial disponieren", "Anlage montieren und einregulieren", "Messprotokoll und Einweisung abschließen", ], }; const activityTemplates = [ ["project.created", "Projekt wurde vollständig angelegt"], ["project.contact_linked", "Kunden- und Ansprechpartner wurden verknüpft"], ["project.assignment_changed", "Projektteam und Zuständigkeiten wurden geplant"], ["project.schedule_planned", "Ausführungstermin wurde in der Plantafel reserviert"], ["project.note_added", "Technische Projektnotiz wurde ergänzt"], ["project.stage_changed", "Pipeline-Status wurde aktualisiert"], ] as const; function id(kind: string, index: number): string { return `rheinmain-shk-v1-${kind}-${String(index + 1).padStart(5, "0")}`; } function addDays(value: string, days: number, hour?: number): string { const date = new Date(value); date.setUTCDate(date.getUTCDate() + days); if (hour !== undefined) date.setUTCHours(hour, 0, 0, 0); return date.toISOString(); } function earlierDate(first: string, second: string): string { return new Date(first) <= new Date(second) ? first : second; } function laterDate(first: string, second: string): string { return new Date(first) >= new Date(second) ? first : second; } function euro(value: string | null, factor: number): string { const amount = Number(value ?? 0); return Math.max(90, Math.round((amount * factor) / 10) * 10).toFixed(2); } function contactDisplayName(graph: DemoProSeedGraph, contactId: string): string { const organization = graph.organizations.find((contact) => contact.id === contactId); if (organization) return organization.orgName; const person = graph.persons.find((contact) => contact.id === contactId); return person ? `${person.firstName} ${person.lastName}` : "Kunde"; } function contactEmail(graph: DemoProSeedGraph, contactId: string): string { return ( graph.organizations.find((contact) => contact.id === contactId)?.email ?? graph.persons.find((contact) => contact.id === contactId)?.email ?? "kunde@unbekannt.example.test" ); } function contactPhone(graph: DemoProSeedGraph, contactId: string): string { return ( graph.organizations.find((contact) => contact.id === contactId)?.phone ?? graph.persons.find((contact) => contact.id === contactId)?.phone ?? "+496990009000" ); } function employeeDisplayName(graph: DemoProSeedGraph, employeeId: string): string { const employee = graph.employees.find(({ id: currentId }) => currentId === employeeId); return employee ? `${employee.firstName} ${employee.lastName}` : "Mitarbeiter"; } export function generateOperationalGraph(graph: DemoProSeedGraph): DemoProOperationalGraph { const crewById = new Map(graph.crews.map((crew) => [crew.id, crew])); const projectContacts: ProjectContact[] = []; const projectMembers: ProjectMember[] = []; const tasks: SeedTask[] = []; const activities: SeedActivity[] = []; const scheduleEntries: SeedScheduleEntry[] = []; const calendarEvents: SeedCalendarEvent[] = []; const projectAppointments: DemoProOperationalGraph["projectAppointments"] = []; for (const [projectIndex, project] of graph.projects.entries()) { for (const contact of project.contacts) { projectContacts.push({ id: id("project-contact", projectContacts.length), projectId: project.id, contactId: contact.contactId, role: contact.role, primary: contact.primary, }); } const crew = crewById.get(project.crewIds[0]!)!; projectMembers.push({ id: id("project-member", projectMembers.length), projectId: project.id, userId: project.projectManagerEmployeeId, groupId: null, role: "projektleiter", }); for (const userId of crew.memberEmployeeIds) { projectMembers.push({ id: id("project-member", projectMembers.length), projectId: project.id, userId, groupId: null, role: "monteur" }); } for (const additionalCrewId of project.crewIds.slice(1)) { const additionalCrew = crewById.get(additionalCrewId)!; for (const userId of additionalCrew.memberEmployeeIds) { projectMembers.push({ id: id("project-member", projectMembers.length), projectId: project.id, userId, groupId: null, role: "monteur" }); } } if (projectIndex < 216) { projectMembers.push({ id: id("project-member", projectMembers.length), projectId: project.id, userId: project.responsibleEmployeeId, groupId: null, role: "zustaendig", }); } const projectTaskCount = projectIndex < 73 ? 4 : 3; for (let slot = 0; slot < projectTaskCount; slot += 1) { const deadline = addDays(project.startDate ?? project.createdAt, 1 + slot * 2); const done = new Date(deadline) < new Date(graph.referenceDate) && (projectIndex + slot) % 4 !== 0; const assignedToCrew = slot === 1 || (slot === 2 && projectIndex % 3 === 0); const createdAt = earlierDate(earlierDate(addDays(project.createdAt, slot), deadline), graph.referenceDate); const completedAt = done ? addDays(deadline, 0, 16) : null; const statusUpdatedAt = done || (projectIndex + slot) % 3 !== 0 ? (completedAt ?? createdAt) : earlierDate(addDays(createdAt, 1 + ((projectIndex + slot) % 5)), graph.referenceDate); tasks.push({ id: id("task", tasks.length), projectId: project.id, title: taskTemplates[project.projectType][slot]!, description: `${project.projectNumber}: ${project.projectName}. Zuständigkeit und Ergebnis nachvollziehbar im Projekt dokumentieren.`, status: done ? "done" : slot === 2 && projectIndex % 17 === 0 ? "blocked" : slot === 0 && projectIndex % 5 === 0 ? "in_progress" : "open", priority: project.priority === "dringend" ? "urgent" : project.priority === "hoch" ? "high" : project.priority === "niedrig" ? "low" : "normal", deadline, assignedToUserId: assignedToCrew ? null : slot === 0 ? project.responsibleEmployeeId : crew.memberEmployeeIds[slot % crew.memberEmployeeIds.length]!, assignedToGroupId: assignedToCrew ? crew.id : null, completedAt, createdAt, updatedAt: laterDate(createdAt, statusUpdatedAt), }); } const activityCount = projectIndex < 46 ? 6 : 5; for (let slot = 0; slot < activityCount; slot += 1) { const [activityType, summaryText] = activityTemplates[slot]!; const candidateCreatedAt = addDays(project.createdAt, slot * 2); activities.push({ id: id("activity", activities.length), projectId: project.id, actorUserId: slot % 2 === 0 ? project.responsibleEmployeeId : project.projectManagerEmployeeId, activityType, createdAt: new Date(candidateCreatedAt) > new Date(graph.referenceDate) ? graph.referenceDate : candidateCreatedAt, summaryText: `${summaryText}: ${project.projectNumber}`, metadata: { projectNumber: project.projectNumber, projectType: project.projectType, seedNamespace: graph.namespace }, }); } const calendarCount = projectIndex < 76 ? 2 : 1; for (let slot = 0; slot < calendarCount; slot += 1) { const userId = slot === 0 ? project.projectManagerEmployeeId : project.responsibleEmployeeId; const calendarWindowStart = project.startDate ?? project.createdAt; const calendarWindowDays = Math.max( 1, Math.floor((new Date(project.deadline ?? graph.referenceDate).getTime() - new Date(calendarWindowStart).getTime()) / 86_400_000) ); const dayOffset = Math.min(calendarWindowDays - 1, (projectIndex * 3 + slot) % calendarWindowDays); const startsAt = addDays(calendarWindowStart, dayOffset, 9 + slot * 4); const endsAt = new Date(new Date(startsAt).getTime() + (slot === 0 ? 90 : 45) * 60 * 1_000).toISOString(); const event = { id: id("calendar", calendarEvents.length), projectId: project.id, userId, title: slot === 0 ? `Baubesprechung · ${project.projectNumber}` : `Kundenabstimmung · ${project.projectNumber}`, description: `${project.projectName}: Termin, nächste Schritte und offene Punkte abstimmen.`, location: `${project.projectAddress.strasse} ${project.projectAddress.hausnummer}, ${project.projectAddress.plz} ${project.projectAddress.ort}`, startsAt, endsAt, }; calendarEvents.push(event); projectAppointments.push({ ...event, id: id("project-appointment", projectAppointments.length), status: new Date(endsAt) < new Date(graph.referenceDate) ? "erledigt" : slot === 0 ? "bestaetigt" : "geplant", }); } } const scheduleConflictPairs: Array<{ entryId: string; sourceEntryId: string }> = []; const scheduledProjects = graph.projects.filter((project): project is SeedProject & { startDate: string } => Boolean(project.startDate)); for (const [scheduledProjectIndex, project] of scheduledProjects.entries()) { const projectStartDate = project.startDate!; const crew = crewById.get(project.crewIds[0]!)!; const scheduleCount = scheduledProjectIndex < 157 ? 4 : 3; const windowDays = Math.max( 1, Math.floor((new Date(project.deadline ?? graph.referenceDate).getTime() - new Date(projectStartDate).getTime()) / 86_400_000) ); const projectEntries: SeedScheduleEntry[] = []; for (let slot = 0; slot < scheduleCount; slot += 1) { const conflictSlot = scheduledProjectIndex < OPERATIONAL_COUNTS.scheduleConflicts && slot === 2; const assignedUserId = conflictSlot ? crew.memberEmployeeIds[0] : crew.memberEmployeeIds[slot % crew.memberEmployeeIds.length]!; const startAt = conflictSlot ? projectEntries[0]!.startAt : addDays(projectStartDate, Math.min(windowDays - 1, Math.floor(slot / 2)), 9 + Math.floor(slot / 2) * 4); const endAt = conflictSlot ? projectEntries[0]!.endAt : new Date(new Date(startAt).getTime() + 3 * 60 * 60 * 1_000).toISOString(); const past = new Date(endAt) < new Date(graph.referenceDate); const entry: SeedScheduleEntry = { id: id("schedule", scheduleEntries.length), projectId: project.id, assignedUserId, title: `${project.projectNumber} · ${project.projectName}`, startAt, endAt, status: past ? "done" : scheduledProjectIndex % 5 === 0 ? "confirmed" : "planned", calendarEventId: null, syncStatus: "pending", }; projectEntries.push(entry); scheduleEntries.push(entry); if (conflictSlot) scheduleConflictPairs.push({ entryId: entry.id, sourceEntryId: projectEntries[0]!.id }); } } const bookingPages: SeedBookingPage[] = [ { id: id("booking-page", 0), slug: "heizung-bad-beratung", title: "Heizungs- und Badberatung", description: "Persönliche Erstberatung für Heizungstausch, Wärmepumpe und Badsanierung im Rhein-Main-Gebiet.", durationMinutes: 45, }, { id: id("booking-page", 1), slug: "wartung-bestandskunden", title: "Wartung für Bestandskunden", description: "Terminabstimmung für die regelmäßige Wartung bestehender Heizungs- und Sanitäranlagen.", durationMinutes: 60, }, { id: id("booking-page", 2), slug: "notdienst-rueckruf", title: "Notdienst-Rückruf", description: "Kurzer technischer Rückruf zur Einschätzung einer akuten Störung und zur Einsatzplanung.", durationMinutes: 30, }, ]; const providers = graph.employees.filter(({ role }) => role === "Projektleiter/Bauleiter"); const bookingProviders = bookingPages.flatMap((page) => providers.map((employee, displayOrder) => ({ id: `${page.id}-provider-${String(displayOrder + 1).padStart(2, "0")}`, bookingPageId: page.id, providerUserId: employee.id, displayOrder, })) ); const weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday"] as const; const availabilityRules = providers.flatMap((provider, providerIndex) => weekdays.map((dayOfWeek, weekdayIndex) => ({ id: id("availability-rule", providerIndex * weekdays.length + weekdayIndex), providerUserId: provider.id, dayOfWeek, startTime: weekdayIndex === 4 ? "08:00" : providerIndex % 2 === 0 ? "08:30" : "09:00", endTime: weekdayIndex === 4 ? "14:00" : providerIndex % 3 === 0 ? "16:30" : "17:00", })) ); const availabilityExceptions = providers.map((provider, index) => { const customWindow = index % 3 === 1; return { id: id("availability-exception", index), providerUserId: provider.id, date: addDays(graph.referenceDate, 11 + index), kind: customWindow ? ("custom_window" as const) : ("unavailable" as const), startTime: customWindow ? "10:00" : null, endTime: customWindow ? "14:00" : null, reason: customWindow ? "Fortbildung am Vormittag" : index % 2 === 0 ? "Urlaub" : "Baustellenbegehung außer Haus", }; }); const projectById = new Map(graph.projects.map((project) => [project.id, project])); const providerIds = new Set(providers.map(({ id: providerId }) => providerId)); const bookingAppointments = calendarEvents .filter(({ userId }) => providerIds.has(userId)) .filter(({ startsAt }) => { const day = new Date(startsAt).getUTCDay(); return day >= 1 && day <= 5; }) .slice(0, OPERATIONAL_COUNTS.bookingAppointments) .map((event, index): SeedBookingAppointment => { const project = projectById.get(event.projectId)!; const primaryContact = project.contacts.find(({ primary }) => primary)?.contactId ?? project.contacts[0]!.contactId; const page = project.projectType === "reparatur_notdienst" ? bookingPages[2]! : project.projectType === "wartung_pruefung" ? bookingPages[1]! : bookingPages[0]!; const cancelled = index % 17 === 0; const endsAt = new Date(new Date(event.startsAt).getTime() + page.durationMinutes * 60_000).toISOString(); event.endsAt = endsAt; const projectAppointment = projectAppointments.find( (appointment) => appointment.projectId === event.projectId && appointment.userId === event.userId && appointment.startsAt === event.startsAt ); if (projectAppointment) projectAppointment.endsAt = endsAt; if (projectAppointment && cancelled) projectAppointment.status = "abgesagt"; return { id: id("booking-appointment", index), bookingPageId: page.id, providerUserId: event.userId, contactId: primaryContact, projectId: project.id, internalCalendarEventId: event.id, startsAt: event.startsAt, endsAt, status: cancelled ? "cancelled" : new Date(endsAt) < new Date(graph.referenceDate) ? "held" : "scheduled", customerName: contactDisplayName(graph, primaryContact), customerEmail: contactEmail(graph, primaryContact), customerPhone: contactPhone(graph, primaryContact), request: `${project.projectName}: Terminwunsch zu ${project.description}`, }; }); const calendarEventsByScheduleWindow = new Map(); for (const event of calendarEvents) { const key = [event.projectId, event.userId, event.startsAt, event.endsAt].join("\u0000"); const matches = calendarEventsByScheduleWindow.get(key) ?? []; matches.push(event); calendarEventsByScheduleWindow.set(key, matches); } for (const entry of scheduleEntries) { const key = [entry.projectId, entry.assignedUserId, entry.startAt, entry.endAt].join("\u0000"); const matches = calendarEventsByScheduleWindow.get(key) ?? []; // A schedule row may only claim sync when one exact calendar counterpart // exists. Similar-looking meetings are intentionally not guessed as links. if (matches.length === 1) { entry.calendarEventId = matches[0]!.id; entry.syncStatus = "synced"; } } const taskWatchers = tasks.slice(0, OPERATIONAL_COUNTS.taskWatchers).map((task, index) => ({ id: id("task-watcher", index), taskId: task.id, userId: graph.employees[(index * 7) % graph.employees.length]!.id, })); const scheduleConflicts = scheduleConflictPairs.map((pair, index) => ({ id: id("schedule-conflict", index), entryId: pair.entryId, sourceEntryId: pair.sourceEntryId, resolvedAt: index % 3 === 0 ? null : addDays(scheduleEntries.find(({ id: entryId }) => entryId === pair.entryId)!.startAt, -2), })); const billableProjects = graph.projects.filter((project) => project.pipeline === "auftrag" || project.stage === "gewonnen"); const invoiceProjects = Array.from({ length: OPERATIONAL_COUNTS.invoices }, (_, index) => billableProjects[index % billableProjects.length]!); const invoices = invoiceProjects.map((project, index): SeedInvoice => { const status: SeedInvoice["status"] = project.stage === "storniert" ? "storniert" : project.stage === "abgeschlossen" ? index % 7 === 0 ? "gestellt" : "bezahlt" : project.stage === "abnahme" && index % 3 === 0 ? "gestellt" : "entwurf"; const date = earlierDate(addDays(project.createdAt, 3 + (index % 21)), graph.referenceDate); const createdAt = earlierDate(addDays(project.createdAt, index % 3), date); const lifecycleOffsetDays = status === "bezahlt" ? 7 + (index % 7) : status === "storniert" ? 2 + (index % 4) : status === "gestellt" ? 1 : 0; return { id: id("invoice", index), projectId: project.id, invoiceNumber: `RE-${new Date(date).getUTCFullYear()}-${String(70419 + index)}`, amount: euro(project.orderVolume ?? project.potentialOrderValue, index % 4 === 0 ? 0.35 : 1), status, date, dueAt: addDays(date, 14), fileId: null, createdAt, updatedAt: laterDate(createdAt, earlierDate(addDays(date, lifecycleOffsetDays), graph.referenceDate)), }; }); const checklistProjects = graph.projects .filter((project) => project.pipeline === "auftrag" || project.stage === "gewonnen") .slice(0, OPERATIONAL_COUNTS.checklists); const checklists = checklistProjects.map( (project, index): SeedChecklist => ({ id: id("checklist", index), projectId: project.id, title: project.stage === "abnahme" || project.stage === "abgeschlossen" ? `Abnahmedokumentation ${project.projectNumber}` : `Ausführungscheckliste ${project.projectNumber}`, type: project.stage === "abnahme" ? "abnahme_doku" : index % 9 === 0 ? "maengel" : "generisch", }) ); const checklistItemTitles = [ "Arbeitsbereich und Absperrungen vorbereitet", "Material und Bauteile vollständig geprüft", "Montage nach Herstellervorgaben ausgeführt", "Messwerte und Druckprobe dokumentiert", "Arbeitsbereich gereinigt und Kunde eingewiesen", "Restpunkt mit Verantwortlichem und Termin erfasst", ] as const; const checklistItems: SeedChecklistItem[] = []; for (const [checklistIndex, checklist] of checklists.entries()) { const project = graph.projects.find(({ id: projectId }) => projectId === checklist.projectId)!; const projectCrew = crewById.get(project.crewIds[0]!)!; const itemCount = checklistIndex < 48 ? 6 : 5; for (let position = 0; position < itemCount; position += 1) { checklistItems.push({ id: id("checklist-item", checklistItems.length), checklistId: checklist.id, title: checklistItemTitles[position]!, status: checklistIndex % 4 === 0 && position > 2 ? "offen" : position === 5 && checklistIndex % 13 === 0 ? "entfaellt" : "erledigt", defectClass: checklist.type === "maengel" && position === 3 ? "B" : null, assignedToUserId: projectCrew.memberEmployeeIds[position % projectCrew.memberEmployeeIds.length]!, dueAt: addDays(project.deadline ?? graph.referenceDate, position - 3), position, photoFileId: null, }); } } const files: SeedFile[] = []; const fileNames = ["Angebot", "Aufmaß", "Montageprotokoll", "Anlagenschema", "Messprotokoll", "Rechnung", "Abnahmeprotokoll"] as const; for (const [projectIndex, project] of graph.projects.entries()) { const fileCount = projectIndex < 380 ? 2 : 1; for (let slot = 0; slot < fileCount; slot += 1) { const ordinal = files.length; const baseName = fileNames[(projectIndex + slot) % fileNames.length]!; const descriptor = { id: id("file", ordinal), displayName: `${baseName}_${project.projectNumber}.pdf`, notes: `Projektunterlage zu ${project.projectName}; dem Projekt ${project.projectNumber} zugeordnet.`, }; files.push({ ...buildSeedFileObjectMetadata(descriptor), projectId: project.id, assignedToUserId: project.projectManagerEmployeeId, tags: [baseName], linkRole: baseName.toLowerCase(), createdAt: earlierDate(addDays(project.createdAt, 2 + slot), graph.referenceDate), updatedAt: earlierDate(addDays(project.createdAt, 2 + slot), graph.referenceDate), }); } } const invoiceFilesByProject = new Map(); for (const file of files.filter(({ displayName }) => displayName.startsWith("Rechnung_"))) { const projectFiles = invoiceFilesByProject.get(file.projectId) ?? []; projectFiles.push(file); invoiceFilesByProject.set(file.projectId, projectFiles); } for (const invoice of invoices) { const projectFiles = invoiceFilesByProject.get(invoice.projectId); invoice.fileId = projectFiles?.shift()?.id ?? null; } const acceptanceEligible = graph.projects.filter((project) => project.pipeline === "auftrag" && ["abnahme", "abgeschlossen"].includes(project.stage)); const defectAcceptanceProjects = acceptanceEligible .filter((project) => checklists.find(({ projectId }) => projectId === project.id)?.type === "maengel") .slice(0, 10); const defectProjectIds = new Set(defectAcceptanceProjects.map(({ id: projectId }) => projectId)); const acceptanceProjects = [ ...defectAcceptanceProjects, ...acceptanceEligible.filter((project) => !defectProjectIds.has(project.id)).slice(0, OPERATIONAL_COUNTS.acceptances - defectAcceptanceProjects.length), ]; const acceptances = acceptanceProjects.map((project, index): SeedAcceptance => { const primaryContact = project.contacts.find(({ primary }) => primary)!.contactId; const checklist = checklists.find(({ projectId }) => projectId === project.id); const kind: SeedAcceptance["kind"] = index < defectAcceptanceProjects.length ? "with_defects" : "full"; const date = earlierDate(addDays(project.deadline ?? graph.referenceDate, index % 3), addDays(graph.referenceDate, -1)); const documentFileId = files.find((file) => file.projectId === project.id && file.displayName.startsWith("Abnahmeprotokoll_"))?.id ?? null; const attendees = [...new Set([contactDisplayName(graph, primaryContact), contactDisplayName(graph, project.contacts.at(-1)!.contactId)])]; if (attendees.length < 2) attendees.push(employeeDisplayName(graph, project.projectManagerEmployeeId)); return { id: id("acceptance", index), projectId: project.id, checklistId: checklist?.id ?? null, creatorUserId: project.projectManagerEmployeeId, date, kind, attendees: attendees.slice(0, 2), remarks: kind === "with_defects" ? "Abnahme mit dokumentierten Restpunkten und verbindlichem Nachtermin." : "Leistung gemeinsam geprüft, Anlage erläutert und ohne Vorbehalt abgenommen.", customerEmail: contactEmail(graph, primaryContact), documentFileId, createdAt: date, updatedAt: addDays(date, 0, 15), }; }); const acceptanceSignatures = acceptances.flatMap((acceptance, index) => { const project = graph.projects.find(({ id: projectId }) => projectId === acceptance.projectId)!; const crew = crewById.get(project.crewIds[0]!)!; return [ { id: id("acceptance-signature", index * 2), acceptanceId: acceptance.id, signerName: acceptance.attendees[0]!, signerRole: "kunde" as const, signedAt: addDays(acceptance.date, 0, 15), }, { id: id("acceptance-signature", index * 2 + 1), acceptanceId: acceptance.id, signerName: employeeDisplayName(graph, crew.memberEmployeeIds[0]!), signerRole: "monteur" as const, signedAt: addDays(acceptance.date, 0, 15), }, ]; }); const signatureProjects = graph.projects .filter( (project) => project.pipeline === "sales" && ["angebot", "gewonnen"].includes(project.stage) && files.some((file) => file.projectId === project.id && file.displayName.startsWith("Angebot_")) ) .slice(0, OPERATIONAL_COUNTS.signatureDocuments); const signatureDocuments = signatureProjects.map((project, index): SeedSignatureDocument => { const primaryContact = project.contacts.find(({ primary }) => primary)!.contactId; const status: SeedSignatureDocument["status"] = index % 4 === 0 ? "sent" : index % 4 === 1 ? "viewed" : "signed"; const sentAt = addDays(project.createdAt, 4 + (index % 8)); const completedAt = status === "signed" ? addDays(sentAt, 2 + (index % 5)) : null; return { id: id("signature-document", index), projectId: project.id, sourceFileId: files.find((file) => file.projectId === project.id && file.displayName.startsWith("Angebot_"))!.id, creatorUserId: project.responsibleEmployeeId, status, title: `Angebot ${project.projectNumber} zur elektronischen Freigabe`, sentAt, completedAt, signerContactId: primaryContact, signerEmail: contactEmail(graph, primaryContact), signerName: contactDisplayName(graph, primaryContact), createdAt: sentAt, updatedAt: completedAt ?? (status === "viewed" ? new Date(new Date(sentAt).getTime() + 3_600_000).toISOString() : sentAt), }; }); const signatureSigners = signatureDocuments.map((document, index) => ({ id: id("signature-signer", index), documentId: document.id, contactId: document.signerContactId, email: document.signerEmail, name: document.signerName, status: document.status, signedAt: document.completedAt, })); const operational: DemoProOperationalGraph = { projectContacts, projectMembers, tasks, taskWatchers, activities, scheduleEntries, scheduleConflicts, calendarEvents, projectAppointments, bookingPages, bookingProviders, availabilityRules, availabilityExceptions, bookingAppointments, invoices, checklists, checklistItems, files, acceptances, acceptanceSignatures, signatureDocuments, signatureSigners, }; validateOperationalGraph(operational, graph.referenceDate); return operational; } export function validateOperationalGraph(graph: DemoProOperationalGraph, referenceDate: string): void { for (const [key, expected] of Object.entries(OPERATIONAL_COUNTS)) { const actual = graph[key as keyof DemoProOperationalGraph].length; if (actual !== expected) throw new Error(`Operational seed ${key}: expected ${expected}, received ${actual}.`); } if (graph.tasks.some((task) => Number(Boolean(task.assignedToUserId)) + Number(Boolean(task.assignedToGroupId)) !== 1)) { throw new Error("Every operational task must have exactly one assignee."); } if (new Set(graph.scheduleEntries.map(({ id: entryId }) => entryId)).size !== graph.scheduleEntries.length) { throw new Error("Operational schedule IDs must be unique."); } const reference = new Date(referenceDate); const invalidTask = graph.tasks.find( (task) => new Date(task.createdAt) > new Date(task.updatedAt) || new Date(task.updatedAt) > reference || (task.completedAt !== null && (new Date(task.completedAt) < new Date(task.createdAt) || new Date(task.completedAt) > reference)) || (task.status === "done") !== (task.completedAt !== null) ); if (invalidTask) throw new Error(`Operational task ${invalidTask.id} timestamps violate the task lifecycle.`); if ( graph.invoices.some( (invoice) => new Date(invoice.createdAt) > new Date(invoice.date) || new Date(invoice.date) > new Date(invoice.updatedAt) || new Date(invoice.updatedAt) > reference || new Date(invoice.date) > new Date(invoice.dueAt) ) ) { throw new Error("Operational invoice timestamps violate the invoice lifecycle."); } if (graph.files.some((file) => new Date(file.createdAt) > new Date(file.updatedAt) || new Date(file.updatedAt) > reference)) { throw new Error("Operational file timestamps violate the file lifecycle."); } if ( graph.acceptances.some( (acceptance) => new Date(acceptance.date) > new Date(acceptance.createdAt) || new Date(acceptance.createdAt) > new Date(acceptance.updatedAt) || new Date(acceptance.updatedAt) > reference ) ) { throw new Error("Operational acceptance timestamps violate the acceptance lifecycle."); } if ( graph.signatureDocuments.some( (document) => document.createdAt !== document.sentAt || new Date(document.createdAt) > new Date(document.updatedAt) || new Date(document.updatedAt) > reference || (document.status === "signed") !== (document.completedAt !== null) || (document.completedAt !== null && document.updatedAt !== document.completedAt) ) ) { throw new Error("Operational signature timestamps violate the signature lifecycle."); } const calendarEventsById = new Map(graph.calendarEvents.map((event) => [event.id, event])); if ( graph.scheduleEntries.some((entry) => { if (entry.calendarEventId === null) return entry.syncStatus !== "pending"; const event = calendarEventsById.get(entry.calendarEventId); return ( entry.syncStatus !== "synced" || !event || event.projectId !== entry.projectId || event.userId !== entry.assignedUserId || event.startsAt !== entry.startAt || event.endsAt !== entry.endAt ); }) ) { throw new Error("Operational schedule entries claim calendar sync without an exact matching event."); } const filesById = new Map(graph.files.map((file) => [file.id, file])); const linkedInvoiceFileIds = graph.invoices.flatMap(({ fileId }) => (fileId ? [fileId] : [])); if ( new Set(linkedInvoiceFileIds).size !== linkedInvoiceFileIds.length || graph.invoices.some((invoice) => { if (invoice.fileId === null) return false; const file = filesById.get(invoice.fileId); return !file || file.projectId !== invoice.projectId || !file.displayName.startsWith("Rechnung_"); }) ) { throw new Error("Operational invoices contain ambiguous or semantically invalid file links."); } if (graph.checklistItems.some(({ photoFileId }) => photoFileId !== null)) { throw new Error("Operational checklist items cannot use generated PDF files as photos."); } if ( graph.acceptances.some((acceptance) => { if (acceptance.documentFileId === null) return false; const file = filesById.get(acceptance.documentFileId); return !file || file.projectId !== acceptance.projectId || !file.displayName.startsWith("Abnahmeprotokoll_"); }) ) { throw new Error("Operational acceptances contain semantically invalid document links."); } }