From be0f537dc4fe384eef09436833c6407e6482c16d Mon Sep 17 00:00:00 2001
From: Rafi Zadanly <zadanlyr@gmail.com>
Date: Thu, 9 Nov 2023 15:40:16 +0700
Subject: Initial commit

---
 src/app/api/stock-opname/location/route.tsx | 57 +++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
 create mode 100644 src/app/api/stock-opname/location/route.tsx

(limited to 'src/app/api/stock-opname/location/route.tsx')

diff --git a/src/app/api/stock-opname/location/route.tsx b/src/app/api/stock-opname/location/route.tsx
new file mode 100644
index 0000000..1009486
--- /dev/null
+++ b/src/app/api/stock-opname/location/route.tsx
@@ -0,0 +1,57 @@
+import { DetailTeam, StockOpnameLocationRes } from "@/common/types/stockOpname";
+import { Location, Team } from "@prisma/client";
+import { NextRequest, NextResponse } from "next/server";
+import { prisma } from "prisma/client";
+
+
+
+const getOpnameQuantity = async (where: { locationId: number, productId: number }) => {
+  const detailTeam: DetailTeam = {
+    COUNT1: { quantity: undefined, user: undefined },
+    COUNT2: { quantity: undefined, user: undefined },
+    VERIFICATION: { quantity: undefined, user: undefined },
+  }
+  for (const team of Object.keys(Team)) {
+    const opname = await prisma.stockOpname.findFirst({
+      where: { ...where, team: team as Team },
+      select: { quantity: true, user: true },
+    })
+    if (!opname) continue
+    detailTeam[team as Team]['quantity'] = opname?.quantity
+    detailTeam[team as Team]['user'] = opname?.user
+  }
+  return detailTeam
+}
+
+export async function GET(request: NextRequest) {
+  const searchParams = request.nextUrl.searchParams;
+  const productId = searchParams.get('productId') ?? '';
+  const companyId = searchParams.get('companyId');
+  const intProductId = parseInt(productId);
+
+  if (!companyId) {
+    return NextResponse.json({ error: 'Bad Request. Missing companyId' }, { status: 400 })
+  }
+
+  const intCompanyId = parseInt(companyId);
+
+  const opnameLocByProduct = await prisma.stockOpname.groupBy({
+    by: ['locationId'],
+    where: { productId: intProductId, companyId: intCompanyId },
+  })
+
+  const locationIds = opnameLocByProduct.map((opname) => opname.locationId)
+
+  const result: StockOpnameLocationRes[] = []
+
+  for (const locationId of locationIds) {
+    const detail = await getOpnameQuantity({ locationId, productId: intProductId })
+    const location = await prisma.location.findFirst({
+      where: { id: locationId, companyId: intCompanyId }
+    })
+    if (!location) continue
+    result.push({ ...location, ...detail })
+  }
+
+  return NextResponse.json(result)
+}
\ No newline at end of file
-- 
cgit v1.2.3

