summaryrefslogtreecommitdiff
path: root/src/app/api/product/import/route.tsx
blob: f96c2d994d3a8585e2cf8e5ca63d9032c82f80ea (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
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import * as XLSX from "xlsx";

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

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

  const body = await request.arrayBuffer();
  const workbook = XLSX.read(body, { type: 'buffer' })
  const worksheetName = workbook.SheetNames[0]
  const worksheet = workbook.Sheets[worksheetName]
  const fileData: any[] = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
  fileData.shift();

  // Fetch all locations for this company for location validation
  const locations = await prisma.location.findMany({
    where: { companyId: intCompanyId }
  })

  // Create a map for quick location lookup by name (case-insensitive) and by id
  const locationByName = new Map(
    locations.map(loc => [loc.name.toLowerCase(), loc.id])
  )
  const locationById = new Map(
    locations.map(loc => [loc.id.toString(), loc.id])
  )

  const newProducts = fileData.map(row => {
    let locationId: number | null = null
    
    // Parse locationId from column 8
    const locationValue = row[8]?.toString().trim()
    
    if (locationValue) {
      // Try to match by ID first, then by name
      const idAsNumber = parseInt(locationValue)
      if (!isNaN(idAsNumber) && locationById.has(idAsNumber.toString())) {
        locationId = idAsNumber
      } else if (locationByName.has(locationValue.toLowerCase())) {
        locationId = locationByName.get(locationValue.toLowerCase()) || null
      }
    }

    return {
      id: undefined,
      isDifferent: false,
      name: row[0]?.toString() || '', // Handle undefined values
      barcode: row[1]?.toString() || '', // Handle undefined values
      itemCode: row[2]?.toString() || '', // Handle undefined values
      onhandQty: row[3] || 0, // Handle undefined values
      differenceQty: row[4] || 0, // Handle undefined values
      companyId: intCompanyId, // Use the parsed company ID
      externalId: row[6] ? row[6].toString() : null, // Handle undefined values
      value: row[7] != null ? Number(row[7]) || 0 : null,
      locationId: locationId, // Set locationId or null if not found/provided
    }
  });

  const whereCompany = { companyId: intCompanyId }

  await prisma.stockOpname.deleteMany({ where: whereCompany })
  await prisma.product.deleteMany({ where: whereCompany })

  await prisma.product.createMany({ data: newProducts })

  return NextResponse.json(true)
}