summaryrefslogtreecommitdiff
path: root/src/app/api/stock-opname/export/route.tsx
blob: 25370704abb866cfcf749574650f8220db883553 (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
import { StockOpnameLocationRes } from "@/common/types/stockOpname";
import { Product } from "prisma/generated/client";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import * as XLSX from "xlsx"

const SELF_HOST = process.env.SELF_HOST as string

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const paramCompanyId = searchParams.get('companyId')

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

  const companyId = parseInt(paramCompanyId)

  let page = 1;
  let totalPage = 1;
  const stockOpnames = []
  do {
    const requestParams = new URLSearchParams({
      page: page.toString(),
      companyId: companyId.toString()
    })
    const stockOpnamesFetch = await fetch(`${SELF_HOST}/api/stock-opname?${requestParams}`)
    const stockOpnamesJson = await stockOpnamesFetch.json()
    stockOpnames.push(...stockOpnamesJson.result)

    page++
    totalPage = stockOpnamesJson.totalPage
  } while (page <= totalPage);

  for (const opname of stockOpnames) {
    const requestParams = new URLSearchParams({
      productId: opname.id.toString(),
      companyId: companyId.toString()
    })
    const detailsFetch = await fetch(`${SELF_HOST}/api/stock-opname/location?${requestParams}`)
    const details: StockOpnameLocationRes[] = await detailsFetch.json()

    opname['details'] = details
  }


  const dataSheet = []

  for (const opname of stockOpnames) {
    const defaultItems = {
      externalId: opname?.externalId,
      itemCode: opname?.itemCode,
      barcode: opname?.barcode,
      name: opname.name,
    }

    dataSheet.push({
      ...defaultItems,
      location: '',
      count1: opname.quantity.COUNT1,
      count2: opname.quantity.COUNT2,
      count3: opname.quantity.COUNT3,
      verification: opname.quantity.VERIFICATION,
      onhandQty: opname.onhandQty,
      differenceQty: opname.differenceQty,
      isDifferent: opname.isDifferent
    })

    for (const detail of opname['details']) {
      dataSheet.push({
        ...defaultItems,
        location: detail.name,
        count1: detail.COUNT1.quantity,
        count2: detail.COUNT2.quantity,
        count3: detail.COUNT3.quantity,
        verification: detail.VERIFICATION.quantity,
        onhandQty: '',
        differenceQty: '',
        isDifferent: ''
      })
    }
  }

  const worksheet = XLSX.utils.json_to_sheet(dataSheet)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1")
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', 'type': 'buffer' })

  return new NextResponse(excelBuffer, {
    headers: {
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': 'attachment; filename=export.xlsx'
    }
  })
}