All files / lib stats.ts

0% Statements 0/203
0% Branches 0/1
0% Functions 0/1
0% Lines 0/203

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204                                                                                                                                                                                                                                                                                                                                                                                                                       
import { prisma } from './db';
import { cached } from './cache';
import { getSystemConfig } from './system-config';

const TTL_STATS = 30;

export type DashboardStats = {
  productTotal: number;
  pendingQc: number;
  totalTransfers: number;     // all transfers (top "โยกย้ายระหว่างสาขา (Transfer)" card)
  pendingTransfers: number;   // PENDING only (module 4 "รอ Master ยืนยัน")
  openClaims: number;
  defectiveToday: number;
  awaitingCategory: number;
};

export function getDashboardStats() {
  return cached<DashboardStats>(
    'stats:dashboard',
    async () => {
      const startOfDay = new Date();
      startOfDay.setHours(0, 0, 0, 0);

      const [productTotal, pendingQc, totalTransfers, pendingTransfers, openClaims, defectiveToday, awaitingCategory] =
        await Promise.all([
          prisma.product.count(),
          prisma.product.count({ where: { status: 'PENDING_QC' } }),
          prisma.transfer.count(),
          prisma.transfer.count({ where: { status: 'PENDING' } }),
          prisma.claim.count({ where: { status: { in: ['OPEN', 'IN_PROGRESS'] } } }),
          prisma.claim.count({ where: { kind: 'DEFECTIVE', createdAt: { gte: startOfDay } } }),
          prisma.product.count({ where: { status: 'QC_PASS' } }),
        ]);

      return { productTotal, pendingQc, totalTransfers, pendingTransfers, openClaims, defectiveToday, awaitingCategory };
    },
    { ttlSeconds: TTL_STATS },
  );
}

// Pending transfer counts per branch — used by Master dashboard's Module 5
// "รอรับสินค้าเข้า (ADS / DAJA / KEN)" rows.
export function getPendingByBranch() {
  return cached<Array<{ code: string; count: number }>>(
    'stats:pending-by-branch',
    async () => {
      const branches = await prisma.branch.findMany({
        where: { active: true },
        select: { id: true, code: true },
        orderBy: { code: 'asc' },
      });
      const counts = await Promise.all(
        branches.map(async (b) => ({
          code: b.code,
          count: await prisma.transfer.count({
            where: { status: 'PENDING', toBranchId: b.id },
          }),
        })),
      );
      return counts;
    },
    { ttlSeconds: TTL_STATS },
  );
}

export type CategoryCount = {
  categoryCode: string;
  subtypeId: string;
  subtypeCode: string;
  subtypeName: string;
  count: number;
};

export function getSubtypeCounts() {
  return cached<CategoryCount[]>(
    'stats:subtype-counts',
    async () => {
      const subtypes = await prisma.productSubtype.findMany({
        where: { active: true },
        include: {
          category: { select: { code: true } },
          _count: { select: { products: { where: { status: 'CATEGORIZED' } } } },
        },
      });
      return subtypes.map((s) => ({
        categoryCode: s.category.code,
        subtypeId: s.id,
        subtypeCode: s.code,
        subtypeName: s.name,
        count: s._count.products,
      }));
    },
    { ttlSeconds: TTL_STATS },
  );
}

// Data block for the Staff dashboard — counts what's actually tracked and
// returns null/dash for sales fields that have no schema backing yet.
export function getStaffDashboardData() {
  return cached(
    'stats:staff-dashboard',
    async () => {
      const startOfMonth = new Date();
      startOfMonth.setDate(1);
      startOfMonth.setHours(0, 0, 0, 0);
      const startOfDay = new Date();
      startOfDay.setHours(0, 0, 0, 0);

      const [
        monthlyProducts, pendingQc, refundAggToday, config,
        importedToday, qcDoneToday, transferredToday, lastActivity,
      ] = await Promise.all([
        prisma.product.count({ where: { createdAt: { gte: startOfMonth } } }),
        prisma.product.count({ where: { status: 'PENDING_QC' } }),
        prisma.claim.aggregate({
          _sum: { amountTHB: true },
          where: { kind: 'REFUND', status: 'RESOLVED', createdAt: { gte: startOfDay } },
        }),
        getSystemConfig(),
        // Real-data operational metrics for the top of Staff dashboard
        prisma.product.count({ where: { createdAt: { gte: startOfDay } } }),
        prisma.product.count({
          where: { qcAt: { gte: startOfDay }, status: { in: ['QC_PASS', 'CATEGORIZED', 'IN_TRANSFER', 'SOLD'] } },
        }),
        prisma.transfer.count({ where: { status: 'COMPLETED', resolvedAt: { gte: startOfDay } } }),
        prisma.activityLog.findFirst({ orderBy: { createdAt: 'desc' }, select: { createdAt: true } }),
      ]);

      const refundSpent = Number(refundAggToday._sum.amountTHB ?? 0);
      const refundBudget = config.refundDailyBudgetTHB;
      return {
        monthlyProducts,
        pendingQc,
        refundSpent,
        refundBudget,
        refundRemaining: refundBudget - refundSpent,
        importedToday,
        qcDoneToday,
        transferredToday,
        lastActivityAt: lastActivity?.createdAt ?? null,
      };
    },
    { ttlSeconds: 30 },
  );
}

export function getClaimStats() {
  return cached(
    'stats:claims',
    async () => {
      const startOfDay = new Date();
      startOfDay.setHours(0, 0, 0, 0);

      const [claimsToday, defectiveTotal, pendingSupplier] = await Promise.all([
        prisma.claim.count({ where: { kind: 'CLAIM', createdAt: { gte: startOfDay } } }),
        prisma.claim.count({ where: { kind: 'DEFECTIVE' } }),
        // "รอ Supplier รับคืน" = defective items still open / in-progress
        prisma.claim.count({ where: { kind: 'DEFECTIVE', status: { in: ['OPEN', 'IN_PROGRESS'] } } }),
      ]);

      const [refundTotal, config] = await Promise.all([
        prisma.claim.aggregate({
          _sum: { amountTHB: true },
          where: { kind: 'REFUND', status: 'RESOLVED', createdAt: { gte: startOfDay } },
        }),
        getSystemConfig(),
      ]);
      const refundSpent = Number(refundTotal._sum.amountTHB ?? 0);
      const refundBudget = config.refundDailyBudgetTHB;
      return {
        claimsToday,
        defectiveTotal,
        pendingSupplier,
        refundSpent,
        refundBudget,
        refundRemaining: refundBudget - refundSpent,
        refundPerItemCap: config.refundPerItemCapTHB,  // for UI to show "Max ฿X"
      };
    },
    { ttlSeconds: TTL_STATS },
  );
}

export function getRecentActivityLog(limit = 35) {
  return cached(
    `activity:recent:limit=${limit}`,
    async () => {
      const rows = await prisma.activityLog.findMany({
        take: limit,
        include: { user: { select: { username: true } } },
        orderBy: { createdAt: 'desc' },
      });
      return rows.map((l) => ({
        id: l.id,
        createdAt: l.createdAt,
        username: l.user.username,
        action: l.action,
        detail: l.detail,
      }));
    },
    { ttlSeconds: 15 },
  );
}