// apps/crm/src/api/pipelineSummary.ts
import { z } from 'zod';
import { createEndpoint } from 'zitejs/backend';
import { zite } from 'zitejs/db';
export default createEndpoint({
description: 'Total deal value and count grouped by pipeline stage',
authenticated: true,
inputSchema: z.object({}),
outputSchema: z.object({
byStage: z.array(z.object({ stage: z.string(), total: z.number(), count: z.number() })),
openValue: z.number(),
wonValue: z.number(),
}),
execute: async () => {
const { rows } = await zite.sql({
query: `
SELECT "stage", COALESCE(SUM("value"), 0) AS "total", COUNT(*) AS "count"
FROM "Deals"
GROUP BY "stage"
`,
});
const byStage = rows.map(r => ({
stage: String(r.stage), total: Number(r.total), count: Number(r.count),
}));
const sumOf = (stages: string[]) =>
byStage.filter(s => stages.includes(s.stage)).reduce((n, s) => n + s.total, 0);
return {
byStage,
openValue: sumOf(['Lead', 'Qualified', 'Proposal']),
wonValue: sumOf(['Won']),
};
},
});