All files / lib transfers.ts

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

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

const TTL_LIST = 60;

export type TransferRow = {
  id: string;
  branchFromCode: string | null;
  branchToCode: string;
  productData: string | null;
  productSubtypeName: string | null;
  problem: TransferProblem;
  customerName: string | null;
  initiatedByUsername: string;
  status: TransferStatus;
  createdAt: Date;
};

function mapRow(t: {
  id: string;
  status: TransferStatus;
  problem: TransferProblem;
  customerName: string | null;
  createdAt: Date;
  fromBranch: { code: string } | null;
  toBranch: { code: string };
  product: { loginData: string | null; subtype: { name: string } | null } | null;
  initiatedByUser: { username: string };
}): TransferRow {
  return {
    id: t.id,
    branchFromCode: t.fromBranch?.code ?? null,
    branchToCode: t.toBranch.code,
    productData: t.product?.loginData ?? null,
    productSubtypeName: t.product?.subtype?.name ?? null,
    problem: t.problem,
    customerName: t.customerName,
    initiatedByUsername: t.initiatedByUser.username,
    status: t.status,
    createdAt: t.createdAt,
  };
}

export function listRecentTransfers(limit = 20) {
  return cached(
    `transfer:list:recent:${limit}`,
    async () => {
      const rows = await prisma.transfer.findMany({
        take: limit,
        include: {
          fromBranch: { select: { code: true } },
          toBranch:   { select: { code: true } },
          product:    { select: { loginData: true, subtype: { select: { name: true } } } },
          initiatedByUser: { select: { username: true } },
        },
        orderBy: { createdAt: 'desc' },
      });
      return rows.map(mapRow);
    },
    { ttlSeconds: TTL_LIST },
  );
}

export async function createTransfer(input: {
  productId: string;
  fromBranchId: string | null;
  toBranchId: string;
  problem: TransferProblem;
  customerName?: string | null;
  notes?: string | null;
  initiatedByUserId: string;
  status: TransferStatus;            // computed by caller via transferInitialStatus(role)
}) {
  const t = await prisma.$transaction(async (tx) => {
    const created = await tx.transfer.create({ data: input });
    // If MASTER created the transfer it goes straight to COMPLETED — update product's branch immediately
    if (input.status === 'COMPLETED') {
      await tx.product.update({
        where: { id: input.productId },
        data: { branchId: input.toBranchId, status: 'IN_TRANSFER' },
      });
    }
    return created;
  });
  await cacheInvalidatePattern('transfer:*');
  await cacheInvalidatePattern('product:*');
  await cacheInvalidatePattern('stats:*');
  return t;
}

export async function approveTransfer(input: { transferId: string; approverUserId: string }) {
  const t = await prisma.$transaction(async (tx) => {
    const transfer = await tx.transfer.findUniqueOrThrow({ where: { id: input.transferId } });
    if (transfer.status !== 'PENDING') throw new Error('Transfer is not in PENDING state');
    const updated = await tx.transfer.update({
      where: { id: input.transferId },
      data: {
        status: 'COMPLETED',
        approvedByUserId: input.approverUserId,
        resolvedAt: new Date(),
      },
    });
    await tx.product.update({
      where: { id: transfer.productId },
      data: { branchId: transfer.toBranchId, status: 'IN_TRANSFER' },
    });
    return updated;
  });
  await cacheInvalidatePattern('transfer:*');
  await cacheInvalidatePattern('product:*');
  await cacheInvalidatePattern('stats:*');
  return t;
}

export async function approveAllPendingTransfers(approverUserId: string) {
  const pending = await prisma.transfer.findMany({
    where: { status: 'PENDING' },
    select: { id: true, productId: true, toBranchId: true },
  });
  for (const t of pending) {
    await prisma.$transaction(async (tx) => {
      await tx.transfer.update({
        where: { id: t.id },
        data: { status: 'COMPLETED', approvedByUserId: approverUserId, resolvedAt: new Date() },
      });
      await tx.product.update({
        where: { id: t.productId },
        data: { branchId: t.toBranchId, status: 'IN_TRANSFER' },
      });
    });
  }
  await cacheInvalidatePattern('transfer:*');
  await cacheInvalidatePattern('product:*');
  await cacheInvalidatePattern('stats:*');
  return pending.length;
}