This repository has been archived on 2026-11-18. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
everythingbutwork/apps/api/src/routers/deal.ts
T
dejanandClaude Opus 4.8 22f79460b2
ci / quality (push) Failing after 38s
ci / build (push) Has been skipped
deploy / deploy (push) Successful in 53s
fix: Bug-Review-Fixes + README aktualisiert
Backend:
- Vortags-Feed (dashboard.overview + dayEntry.feed) sortierte aufsteigend
  mit limit(50) → zeigte die ÄLTESTEN statt neuesten Einträge. Jetzt desc.
- deal.updateStage: wonValueEur wurde beim Gewinnen mit der Wahrscheinlichkeit
  gewichtet → zu niedriger Won-Umsatz. Jetzt voller Auftragswert.
- Pflicht-Minimum „Status aktuell" wurde global (letzte Reflexion irgendwo)
  statt pro Projekt berechnet. Jetzt je Projekt aus dem jüngsten Statusbericht.
- time.listToday/teamToday nutzten fixen +02:00-Offset → im Winter (CET) um
  1h verschobene Tagesgrenze. Jetzt DST-sicher via AT TIME ZONE 'Europe/Berlin'.

Frontend:
- lead.tsx + projekt.tsx: Datumsanzeigen nutzten UTC (toISOString) → abends
  Off-by-one. Jetzt Berlin-lokal formatiert.
- reflexion.tsx: Submit mappte nur den initialen ToDo-Snapshot → mitten am Tag
  ergänzte ToDos verloren ihren Status. Jetzt über die aktuelle Liste.
- leads.tsx: CSV-Zeilenzähler konnte „-1" zeigen (Math.max).
- TimerPill: Label ohne Control (a11y-Lint-Error, war repo-weit rot) + unused
  clsx-Import behoben → pnpm lint jetzt 0 Errors.

DB: seed.ts unbedingten updatedAt-Bump aller User entfernt (Debug-Rest).

README: vollständig auf aktuellen Stand gebracht (Leads/CRM, CSV-Import,
PM-Tiefe, Phasen/Status/Risiken/Stakeholder/Änderungen, Tabellen bis 0011,
tRPC-Router, staleTime 0, Auto-Deploy-Runner + Startup-Migrationen).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 17:00:03 +02:00

136 lines
4.3 KiB
TypeScript

import { z } from 'zod';
import { TRPCError } from '@trpc/server';
import { desc, eq, sql, sum } from 'drizzle-orm';
import { deal, gtmStep, area } from '@cockpit/db';
import { DealSchemas } from '@cockpit/shared';
import { router, protectedProcedure } from '../trpc.js';
const SALES_AREA_SLUG = 'vertrieb';
async function getSalesAreaId(db: import('@cockpit/db').Db): Promise<string> {
const a = (await db.select().from(area).where(eq(area.slug, SALES_AREA_SLUG)).limit(1))[0];
if (!a) throw new Error('Sales-Area fehlt — bitte seed laufen lassen.');
return a.id;
}
export const dealRouter = router({
list: protectedProcedure.query(async ({ ctx }) => {
return ctx.db.select().from(deal).orderBy(desc(deal.enteredStageAt));
}),
kpis: protectedProcedure.query(async ({ ctx }) => {
const allDeals = await ctx.db.select().from(deal);
const open = allDeals.filter((d) => !d.wonAt);
const won = allDeals.filter((d) => d.wonAt);
const weightedPipeline = open.reduce((acc, d) => acc + (d.valueEur * d.probability) / 100, 0);
// „Laufendes Quartal" = aktuelles Kalenderquartal (Server-Zeit).
const now = new Date();
const qStart = new Date(now.getFullYear(), Math.floor(now.getMonth() / 3) * 3, 1);
const wonThisQuarter = won.filter((d) => d.wonAt && d.wonAt >= qStart);
const wonValueQuarter = wonThisQuarter.reduce((acc, d) => acc + (d.wonValueEur ?? 0), 0);
return {
weightedPipelineEur: Math.round(weightedPipeline),
openDealCount: open.length,
wonCountQuarter: wonThisQuarter.length,
wonValueQuarterEur: wonValueQuarter,
};
}),
create: protectedProcedure.input(DealSchemas.createDealInput).mutation(async ({ ctx, input }) => {
const areaId = await getSalesAreaId(ctx.db);
const [created] = await ctx.db
.insert(deal)
.values({
areaId,
name: input.name,
ownerUserId: input.ownerUserId ?? null,
valueEur: input.valueEur,
probability: input.probability,
stage: input.stage,
})
.returning();
return created;
}),
updateStage: protectedProcedure
.input(DealSchemas.updateDealStageInput)
.mutation(async ({ ctx, input }) => {
const [updated] = await ctx.db
.update(deal)
.set({
stage: input.stage,
enteredStageAt: new Date(),
wonAt: input.stage === 'abschluss' ? new Date() : null,
// Gewonnener Deal = voller Auftragswert (nicht mit Wahrscheinlichkeit gewichtet).
wonValueEur:
input.stage === 'abschluss' ? sql`COALESCE(${deal.valueEur}, 0)` : null,
})
.where(eq(deal.id, input.dealId))
.returning();
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Deal nicht gefunden.' });
return updated;
}),
});
export const gtmRouter = router({
list: protectedProcedure
.input(z.object({ product: z.string().optional() }))
.query(async ({ ctx, input }) => {
if (input.product) {
return ctx.db
.select()
.from(gtmStep)
.where(eq(gtmStep.product, input.product))
.orderBy(gtmStep.order);
}
return ctx.db.select().from(gtmStep).orderBy(gtmStep.product, gtmStep.order);
}),
create: protectedProcedure
.input(
z.object({
product: z.string().min(1).max(100),
title: z.string().min(1).max(200),
ownerUserId: z.string().uuid().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
const existing = await ctx.db
.select()
.from(gtmStep)
.where(eq(gtmStep.product, input.product));
const [created] = await ctx.db
.insert(gtmStep)
.values({
product: input.product,
title: input.title,
ownerUserId: input.ownerUserId ?? null,
order: existing.length,
})
.returning();
return created;
}),
setStatus: protectedProcedure
.input(
z.object({
id: z.string().uuid(),
status: z.enum(['open', 'in_progress', 'done']),
}),
)
.mutation(async ({ ctx, input }) => {
const [updated] = await ctx.db
.update(gtmStep)
.set({ status: input.status })
.where(eq(gtmStep.id, input.id))
.returning();
return updated;
}),
});
// linter
void sum;