All files / lib claims.ts

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

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                                                                                                                                                         
import { prisma } from './db';
import { cached, cacheInvalidatePattern } from './cache';
import { Prisma } from '@prisma/client';
import type { ClaimKind, ClaimStatus } from '@prisma/client';

const TTL_LIST = 60;

export type ClaimRow = {
  id: string;
  kind: ClaimKind;
  status: ClaimStatus;
  productCode: string | null;
  productLoginData: string | null;
  issueTypeName: string | null;
  customerName: string | null;
  amountTHB: number | null;
  description: string | null;
  filedByUsername: string;
  createdAt: Date;
};

export function listRecentClaims(limit = 30) {
  return cached(
    `claim:list:recent:${limit}`,
    async () => {
      const rows = await prisma.claim.findMany({
        take: limit,
        include: {
          product:     { select: { loginData: true } },
          issueType:   { select: { name: true } },
          filedByUser: { select: { username: true } },
        },
        orderBy: { createdAt: 'desc' },
      });
      return rows.map<ClaimRow>((c) => ({
        id: c.id,
        kind: c.kind,
        status: c.status,
        productCode: c.productCode,
        productLoginData: c.product?.loginData ?? null,
        issueTypeName: c.issueType?.name ?? null,
        customerName: c.customerName,
        amountTHB: c.amountTHB ? Number(c.amountTHB) : null,
        description: c.description,
        filedByUsername: c.filedByUser.username,
        createdAt: c.createdAt,
      }));
    },
    { ttlSeconds: TTL_LIST },
  );
}

export async function createClaim(input: {
  kind: ClaimKind;
  productCode?: string | null;
  issueTypeId?: string | null;
  customerName?: string | null;
  amountTHB?: number | null;
  description?: string | null;
  filedByUserId: string;
}) {
  const c = await prisma.claim.create({
    data: {
      kind: input.kind,
      productCode: input.productCode ?? null,
      issueTypeId: input.issueTypeId ?? null,
      customerName: input.customerName ?? null,
      amountTHB: input.amountTHB != null ? new Prisma.Decimal(input.amountTHB) : null,
      description: input.description ?? null,
      filedByUserId: input.filedByUserId,
    },
  });
  await cacheInvalidatePattern('claim:*');
  await cacheInvalidatePattern('stats:*');
  return c;
}