refactor: add proper types, fix zod error handling, and simplify import mapping logic

This commit is contained in:
2026-05-12 00:49:23 +02:00
parent bb0948f590
commit 1ec992caf6
+19 -10
View File
@@ -2,9 +2,18 @@
import { revalidatePath } from "next/cache"
import Papa from "papaparse"
import { flattenError } from "zod"
import { type ImportFormType, importSchema } from "@/lib/schemas/import.schemas"
import type { ImportItem } from "@/lib/types"
import type { CreateMovementFormType } from "@/lib/schemas/movement.schemas"
import type {
Asset,
Assignment,
Category,
ImportItem,
Item,
Recipient,
} from "@/lib/types"
import { AssetService } from "@/services/asset.service"
import { AssignmentService } from "@/services/assignment.service"
import { CategoryService } from "@/services/category.service"
@@ -17,7 +26,7 @@ export async function importItems(formData: ImportFormType) {
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
errors: flattenError(validatedFields.error).fieldErrors,
}
}
@@ -155,7 +164,7 @@ export async function importItems(formData: ImportFormType) {
importErrors.push(`Row ${index + 2}: Category or categoryId is required`)
}
if (stock && isNaN(Number(stock))) {
if (stock && Number.isNaN(stock)) {
importErrors.push(`Row ${index + 2}: Stock must be a number`)
}
@@ -202,7 +211,7 @@ export async function importItems(formData: ImportFormType) {
categoryId: categoryId ? categoryId : row.categoryId?.trim() || "",
category: row.category?.trim() || "",
deliveryNote: row.deliveryNote?.trim() || "",
assigned: row.assigned?.trim() === "true" ? true : false,
assigned: row.assigned?.trim() === "true",
username: row.username?.trim() || "",
firstName: row.firstName?.trim() || "",
lastName: row.lastName?.trim() || "",
@@ -224,11 +233,11 @@ export async function importItems(formData: ImportFormType) {
} = item
// Reset variables at the beginning of each iteration
let newItem
let newAsset
let newCategory
let newRecipient
let newAssignment
let newItem: Item | null = null
let newAsset: Asset | null = null
let newCategory: Category | null = null
let newRecipient: Recipient | null = null
let newAssignment: Assignment | null = null
const existingCategory = categoryId
? await CategoryService.findById(categoryId)
@@ -307,7 +316,7 @@ export async function importItems(formData: ImportFormType) {
})
}
const movementData: any = {
const movementData: CreateMovementFormType = {
assetId: newAsset?.id || undefined,
quantity: stock || 1,
type: assigned ? "ASSIGNMENT" : "IN",