import { Prisma } from '../generated/prisma/client'; import type { AnalyticsWindow, AnalyticsVariants } from './analytics.schemas'; function cohort(organizationId: string, input: AnalyticsWindow, now: Date) { const currency = input.currency ? Prisma.sql`AND o.currency = ${input.currency}` : Prisma.empty; return Prisma.sql`SELECT o.id, o.organization_id, o.currency, o.created_at, o.subtotal, o.discount, o.merchandise_total, (o.status = 'PENDING_PAYMENT' AND o.expires_at > ${now}) AS is_open, (o.status = 'PENDING_PAYMENT' AND o.expires_at <= ${now}) AS is_expired, (o.status = 'CANCELLED') AS is_cancelled FROM orders o WHERE o.organization_id = ${organizationId}::uuid AND o.created_at >= ${input.from} AND o.created_at < ${input.to} ${currency}`; } export function dailyQuery( organizationId: string, input: AnalyticsWindow, now: Date, ) { return Prisma.sql`WITH cohort AS (${cohort(organizationId, input, now)}) SELECT to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day, currency, COUNT(*)::int AS "orderCount", COUNT(*) FILTER (WHERE is_open)::int AS "openOrderCount", COUNT(*) FILTER (WHERE is_expired)::int AS "expiredOrderCount", COUNT(*) FILTER (WHERE is_cancelled)::int AS "cancelledOrderCount", SUM(subtotal)::text AS "capturedSubtotal", SUM(discount)::text AS "capturedDiscount", SUM(merchandise_total)::text AS "capturedMerchandiseValue", COALESCE(SUM(merchandise_total) FILTER (WHERE is_open), 0)::text AS "openMerchandiseValue", COALESCE(SUM(merchandise_total) FILTER (WHERE is_expired), 0)::text AS "expiredMerchandiseValue", COALESCE(SUM(merchandise_total) FILTER (WHERE is_cancelled), 0)::text AS "cancelledMerchandiseValue" FROM cohort GROUP BY day, currency ORDER BY day, currency`; } export function variantsQuery( organizationId: string, input: AnalyticsVariants, now: Date, ) { return Prisma.sql`WITH cohort AS (${cohort(organizationId, input, now)}) SELECT c.currency, l.variant_id AS "variantId", l.sku, l.product_name AS "productName", l.variant_name AS "variantName", COUNT(*)::int AS "orderCount", SUM(l.quantity)::text AS "capturedQuantity", COALESCE(SUM(l.quantity) FILTER (WHERE c.is_open), 0)::text AS "openQuantity", COALESCE(SUM(l.quantity) FILTER (WHERE c.is_expired), 0)::text AS "expiredQuantity", COALESCE(SUM(l.quantity) FILTER (WHERE c.is_cancelled), 0)::text AS "cancelledQuantity", SUM(l.line_total)::text AS "capturedLineValue" FROM cohort c JOIN order_lines l ON l.order_id = c.id AND l.organization_id = c.organization_id GROUP BY c.currency, l.variant_id, l.sku, l.product_name, l.variant_name ORDER BY SUM(l.quantity) DESC, l.variant_id ASC, c.currency ASC, l.sku ASC, l.product_name ASC, l.variant_name ASC LIMIT ${input.limit} OFFSET ${input.offset}`; }