From 1ec992caf6a37d5195000b2d79c4ce28a078e436 Mon Sep 17 00:00:00 2001 From: Asis Ferrer Date: Tue, 12 May 2026 00:49:23 +0200 Subject: [PATCH] refactor: add proper types, fix zod error handling, and simplify import mapping logic --- src/lib/actions/import.actions.ts | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/lib/actions/import.actions.ts b/src/lib/actions/import.actions.ts index 3c752af..e169893 100644 --- a/src/lib/actions/import.actions.ts +++ b/src/lib/actions/import.actions.ts @@ -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",