summaryrefslogtreecommitdiff
path: root/src/app/api/product/route.tsx
blob: 23bb065afde6c8ed86ed8f1dd507cee325f0ee83 (plain)
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
import getServerCredential from "@/common/libs/getServerCredential";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import { Prisma } from "prisma/generated/client";

export async function GET(request: NextRequest) {
  const PAGE_SIZE = 30;

  const searchParams = request.nextUrl.searchParams;
  const search = searchParams.get('search');

  const page = searchParams.get('page');
  const intPage: number = page ? parseInt(page) : 1;

  const paramCompanyId = searchParams.get('companyId')
  const companyId = paramCompanyId ? parseInt(paramCompanyId) : null

  const show = searchParams.get('show')

  const credential = getServerCredential()

  if (!credential) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const where: Prisma.ProductWhereInput = {
    AND: {
      OR: [
        { name: { mode: 'insensitive', contains: search ?? '' } },
        { barcode: { mode: 'insensitive', contains: search ?? '' } },
        { itemCode: { mode: 'insensitive', contains: search ?? '' } },
      ],
      companyId: companyId ?? credential.companyId,
      stockOpnames: { none: show === 'not-count' ? {} : undefined },
      onhandQty: { gt: show === 'not-count' ? 0 : undefined },
    },
  }

  const products = await prisma.product.findMany({
    where,
    include: { company: true, location: true },
    take: PAGE_SIZE,
    skip: (intPage - 1) * PAGE_SIZE,
    orderBy: { name: 'asc' }
  })

  const count = await prisma.product.count({ where })
  const pagination = {
    page: intPage,
    totalPage: Math.ceil(count / PAGE_SIZE),
    count
  }

  return NextResponse.json({ products, ...pagination })
}

// TODO: Search case sensitive
// TODO: Submit harus di done