summaryrefslogtreecommitdiff
path: root/src/app/api/stock-opname/route.tsx
blob: 406981bc095e2395e5580571d55a1b3c9adf02ad (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
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
import { StockOpnameLocationRes, StockOpnameRequest } from "@/common/types/stockOpname";
import { Team } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import _ from "lodash"
import getServerCredential from "@/common/libs/getServerCredential";

type Quantity = {
  [key in keyof typeof Team]: number | null
}

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

  const params = request.nextUrl.searchParams
  const companyId = params.get('companyId')
  const search = params.get('search')
  const page = params.get('page') ?? null
  const show = params.get('show')
  const intPage = page ? parseInt(page) : 1

  if (!companyId) {
    return NextResponse.json({ error: 'Bad Request. Missing companyId' }, { status: 400 })
  }

  const where = {
    AND: {
      stockOpnames: { some: {} },
      companyId: parseInt(companyId),
      isDifferent: show ? (show == 'diff' ? true : false) : undefined,
      OR: [
        { name: { contains: search ?? '' } },
        { itemCode: { contains: search ?? '' } },
        { barcode: { contains: search ?? '' } },
      ]
    }
  }

  const products = await prisma.product.findMany({
    skip: (intPage - 1) * PAGE_SIZE,
    take: PAGE_SIZE,
    where,
    select: {
      id: true,
      name: true,
      itemCode: true,
      barcode: true,
      onhandQty: true,
      differenceQty: true,
      isDifferent: true
    }
  })

  const productCount = await prisma.product.count({ where })

  const pagination = {
    page: intPage,
    totalPage: Math.ceil(productCount / PAGE_SIZE),
  }

  type ProductWithSum = typeof products[0] & { quantity: Quantity }

  const productsWithSum: ProductWithSum[] = []

  for (const product of products) {
    const quantity = await calculateOpnameQuantity({
      productId: product.id,
      companyId: parseInt(companyId)
    })
    productsWithSum.push({ ...product, quantity })
  }

  return NextResponse.json({
    result: productsWithSum,
    ...pagination
  })
}

const calculateOpnameQuantity = async (
  where: {
    productId: number,
    companyId: number
  }
): Promise<Quantity> => {
  const quantity: Quantity = { COUNT1: null, COUNT2: null, COUNT3: null, VERIFICATION: null }

  for (const team of Object.values(Team)) {
    const opnameQty = await prisma.stockOpname.groupBy({
      by: ['productId', 'team'],
      _sum: { quantity: true },
      where: { team, ...where }
    })
    if (opnameQty.length === 0) continue
    quantity[team] = opnameQty[0]._sum.quantity
  }
  return quantity
}

export async function POST(request: NextRequest) {
  const credential = getServerCredential()

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

  const body: StockOpnameRequest = await request.json()

  const { companyId, team } = credential

  const query = {
    locationId: body.location,
    productId: body.product,
    companyId,
    team
  }

  const stockOpname = await prisma.stockOpname.findFirst({
    where: query
  })

  const data = {
    ...query,
    userId: credential.id,
    quantity: body.quantity,
    isDifferent: false
  }

  let newStockOpname = null

  if (!stockOpname) {
    newStockOpname = await prisma.stockOpname.create({ data })
  } else {
    newStockOpname = await prisma.stockOpname.update({
      where: { id: stockOpname.id },
      data
    })
  }

  await computeIsDifferent({ productId: body.product, companyId: companyId })

  return NextResponse.json(newStockOpname)
}

const SELF_HOST = process.env.SELF_HOST as string

const computeIsDifferent = async ({
  companyId,
  productId
}: {
  companyId: number,
  productId: number
}) => {
  const totalQty: { [key in keyof typeof Team]: number | null } = {
    COUNT1: null,
    COUNT2: null,
    COUNT3: null,
    VERIFICATION: null
  }

  const searchParams = new URLSearchParams({
    companyId: companyId.toString(),
    productId: productId.toString()
  })

  const stockOpnamesFetch = await fetch(`${SELF_HOST}/api/stock-opname/location?${searchParams}`)
  const stockOpnames: StockOpnameLocationRes[] = await stockOpnamesFetch.json()

  const count2Count = await prisma.stockOpname.count({
    where: { companyId, productId, team: 'COUNT2' }
  })

  const isCount2Counted: boolean = count2Count > 0

  let isDifferent: boolean = false

  for (const opname of stockOpnames) {
    let { COUNT1, COUNT2, COUNT3, VERIFICATION } = opname

    if (totalQty['COUNT1'] === null && _.isNumber(COUNT1.quantity)) totalQty['COUNT1'] = 0
    if (totalQty['COUNT2'] === null && _.isNumber(COUNT2.quantity)) totalQty['COUNT2'] = 0
    if (totalQty['COUNT3'] === null && _.isNumber(COUNT3.quantity)) totalQty['COUNT3'] = 0
    if (totalQty['VERIFICATION'] === null && _.isNumber(VERIFICATION.quantity)) totalQty['VERIFICATION'] = 0

    if (_.isNumber(totalQty['COUNT1']) && _.isNumber(COUNT1.quantity)) totalQty['COUNT1'] += COUNT1.quantity
    if (_.isNumber(totalQty['COUNT2']) && _.isNumber(COUNT2.quantity)) totalQty['COUNT2'] += COUNT2.quantity
    if (_.isNumber(totalQty['COUNT3']) && _.isNumber(COUNT3.quantity)) totalQty['COUNT3'] += COUNT3.quantity
    if (_.isNumber(totalQty['VERIFICATION']) && _.isNumber(VERIFICATION.quantity)) totalQty['VERIFICATION'] += VERIFICATION.quantity
  }

  const product = await prisma.product.findFirst({ where: { id: productId } })
  if (!product) return

  const onhandQty = product?.onhandQty || 0

  if (!isDifferent) {
    const conditional = {
      wasVerified: typeof totalQty['VERIFICATION'] === 'number' && totalQty['VERIFICATION'] > 0,
      anyCountEqWithOnhand: [totalQty['COUNT1'], totalQty['COUNT2'], totalQty['COUNT3']].includes(onhandQty),
      count1EqWithCount2: totalQty['COUNT1'] !== null && totalQty['COUNT2'] !== null && totalQty['COUNT1'] === totalQty['COUNT2'],
      count1EqWithCount3: totalQty['COUNT1'] !== null && totalQty['COUNT3'] !== null && totalQty['COUNT1'] === totalQty['COUNT3'],
      count2EqWithCount3: totalQty['COUNT2'] !== null && totalQty['COUNT3'] !== null && totalQty['COUNT2'] === totalQty['COUNT3']
    }

    isDifferent = !(
      conditional.wasVerified ||
      conditional.anyCountEqWithOnhand ||
      conditional.count1EqWithCount2 ||
      conditional.count1EqWithCount3 ||
      conditional.count2EqWithCount3
    )

    // if (isCount2Counted && totalQty['COUNT1'] != onhandQty) {
    //   isDifferent = true
    // }
  }

  await prisma.product.update({
    where: { id: product.id },
    data: { isDifferent }
  })
}