All files / lib products.ts

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

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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { prisma } from './db';
import { cached, cacheInvalidatePattern } from './cache';
import { decrypt, encrypt } from './crypto';
import { Prisma, type ProductStatus } from '@prisma/client';

const TTL_LIST = 60;

export type ProductRow = {
  id: string;
  loginData: string | null;       // decrypted in transit
  rawType: string | null;
  branchCode: string | null;
  branchId: string | null;
  subtypeName: string | null;
  status: ProductStatus;
  createdAt: Date;
};

type Raw = {
  id: string;
  loginData: string | null;
  rawType: string | null;
  branch: { code: string; id: string } | null;
  subtype: { name: string } | null;
  status: ProductStatus;
  createdAt: Date;
};

function mapRow(p: Raw): ProductRow {
  return {
    id: p.id,
    loginData: decrypt(p.loginData),
    rawType: p.rawType,
    branchCode: p.branch?.code ?? null,
    branchId: p.branch?.id ?? null,
    subtypeName: p.subtype?.name ?? null,
    status: p.status,
    createdAt: p.createdAt,
  };
}

export function listPendingQc() {
  return cached(
    'product:list:pending-qc',
    async () => {
      const rows = await prisma.product.findMany({
        where: { status: 'PENDING_QC' },
        include: { branch: { select: { id: true, code: true } }, subtype: { select: { name: true } } },
        orderBy: { createdAt: 'desc' },
      });
      return rows.map(mapRow);
    },
    { ttlSeconds: TTL_LIST },
  );
}

export function listAwaitingCategory() {
  return cached(
    'product:list:awaiting-category',
    async () => {
      const rows = await prisma.product.findMany({
        where: { status: 'QC_PASS' },
        include: { branch: { select: { id: true, code: true } }, subtype: { select: { name: true } } },
        orderBy: { createdAt: 'desc' },
      });
      return rows.map(mapRow);
    },
    { ttlSeconds: TTL_LIST },
  );
}

export function listCategorizedAtBranch(branchCode?: string, limit?: number) {
  const key = `product:list:categorized${branchCode ? `:branch=${branchCode}` : ''}${limit ? `:lim=${limit}` : ''}`;
  return cached(
    key,
    async () => {
      const rows = await prisma.product.findMany({
        where: {
          status: 'CATEGORIZED',
          ...(branchCode ? { branch: { code: branchCode } } : {}),
        },
        include: { branch: { select: { id: true, code: true } }, subtype: { select: { name: true } } },
        orderBy: { createdAt: 'desc' },
        ...(limit ? { take: limit } : {}),
      });
      return rows.map(mapRow);
    },
    { ttlSeconds: TTL_LIST },
  );
}

/**
 * Server-side search across ALL categorized products (no cache — query is
 * unique per user input).  Used by Transfer's product picker when the user
 * needs a row beyond the initial 100 shown.  Searches branch.code +
 * subtype.name + rawType.  Cannot search by login text — loginData is
 * encrypted at rest.
 */
export async function searchCategorizedProducts(query: string, limit = 50): Promise<ProductRow[]> {
  const q = query.trim();
  if (q.length < 2) return [];
  const rows = await prisma.product.findMany({
    where: {
      status: 'CATEGORIZED',
      OR: [
        { rawType: { contains: q, mode: 'insensitive' } },
        { subtype: { name: { contains: q, mode: 'insensitive' } } },
        { branch:  { code: { contains: q.toUpperCase() } } },
      ],
    },
    take: limit,
    include: { branch: { select: { id: true, code: true } }, subtype: { select: { name: true } } },
    orderBy: { createdAt: 'desc' },
  });
  return rows.map(mapRow);
}

/** Full row for the "All Products" page — includes who created it, QC timestamp, etc. */
export type ProductAllRow = ProductRow & {
  qcAt: Date | null;
  createdByUsername: string;
};

/** All products, optionally filtered by status / category / branch. */
export function listAllProducts(filters: {
  status?: string;       // ProductStatus enum value, or 'ALL'/undefined
  categoryCode?: string; // 'FB' | 'PAGE' | 'LINE_OA' | 'ALL' | undefined
  branchCode?: string;   // 'ADS' | 'DAJA' | 'KEN' | 'ALL' | undefined
}) {
  const key = `product:list:all:status=${filters.status ?? 'ALL'}:cat=${filters.categoryCode ?? 'ALL'}:branch=${filters.branchCode ?? 'ALL'}`;
  return cached<ProductAllRow[]>(
    key,
    async () => {
      const where: Prisma.ProductWhereInput = {};
      if (filters.status && filters.status !== 'ALL') {
        where.status = filters.status as ProductStatus;
      }
      if (filters.categoryCode && filters.categoryCode !== 'ALL') {
        where.subtype = { category: { code: filters.categoryCode } };
      }
      if (filters.branchCode && filters.branchCode !== 'ALL') {
        where.branch = { code: filters.branchCode };
      }
      const rows = await prisma.product.findMany({
        where,
        include: {
          branch:    { select: { id: true, code: true } },
          subtype:   { select: { name: true } },
          createdBy: { select: { username: true } },
        },
        orderBy: { createdAt: 'desc' },
      });
      return rows.map((p) => ({
        ...mapRow(p),
        qcAt: p.qcAt,
        createdByUsername: p.createdBy.username,
      }));
    },
    { ttlSeconds: TTL_LIST },
  );
}

/** All CATEGORIZED products, optionally filtered by ProductCategory.code (FB / PAGE / LINE_OA). */
export function listCategorizedByCategory(categoryCode?: string) {
  const key = `product:list:categorized:cat=${categoryCode ?? 'all'}`;
  return cached(
    key,
    async () => {
      const rows = await prisma.product.findMany({
        where: {
          status: 'CATEGORIZED',
          ...(categoryCode ? { subtype: { category: { code: categoryCode } } } : {}),
        },
        include: { branch: { select: { id: true, code: true } }, subtype: { select: { name: true } } },
        orderBy: { createdAt: 'desc' },
      });
      return rows.map(mapRow);
    },
    { ttlSeconds: TTL_LIST },
  );
}

export async function createProduct(input: {
  branchId: string;
  loginData: string;
  subtypeId?: string | null;       // optional: if importer already knows the subtype
  rawType?: string | null;         // fallback for "อื่น ๆ" path
  email?: string | null;
  bankInfo?: string | null;
  createdById: string;
}) {
  const p = await prisma.product.create({
    data: {
      branchId: input.branchId,
      loginData: encrypt(input.loginData),
      subtypeId: input.subtypeId ?? null,
      rawType: input.rawType ?? null,
      email: encrypt(input.email ?? null),
      bankInfo: encrypt(input.bankInfo ?? null),
      status: 'PENDING_QC',
      createdById: input.createdById,
    },
  });
  await cacheInvalidatePattern('product:list:*');
  await cacheInvalidatePattern('stats:*');
  return p;
}

export async function setQcResult(input: {
  productId: string;
  pass: boolean;
  failReason?: string | null;
  qcByUserId: string;
}) {
  if (input.pass) {
    // Auto-bump to CATEGORIZED if the product was pre-categorized at import time.
    const cur = await prisma.product.findUnique({
      where: { id: input.productId },
      select: { subtypeId: true },
    });
    const status = cur?.subtypeId ? 'CATEGORIZED' : 'QC_PASS';
    const p = await prisma.product.update({
      where: { id: input.productId },
      data: { status, qcFailReason: null, qcByUserId: input.qcByUserId, qcAt: new Date() },
    });
    await cacheInvalidatePattern('product:list:*');
    await cacheInvalidatePattern('stats:*');
    return p;
  }

  const p = await prisma.product.update({
    where: { id: input.productId },
    data: {
      status: 'QC_FAIL',
      qcFailReason: input.failReason ?? null,
      qcByUserId: input.qcByUserId,
      qcAt: new Date(),
    },
  });
  await cacheInvalidatePattern('product:list:*');
  await cacheInvalidatePattern('stats:*');
  return p;
}

export async function assignSubtype(input: { productId: string; subtypeId: string }) {
  const p = await prisma.product.update({
    where: { id: input.productId },
    data: { subtypeId: input.subtypeId, status: 'CATEGORIZED' },
  });
  await cacheInvalidatePattern('product:list:*');
  await cacheInvalidatePattern('stats:*');
  return p;
}