pmtool / src /hooks /asset-management /useBulkImportSystemDetails.ts
devarshia5's picture
Upload 487 files
d97b8f9 verified
Raw
History Blame Contribute Delete
6.72 kB
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { SystemDetailsCreateRequest, AssetCreateRequest } from '@/types/asset-management';
import { systemDetailsApi } from '@/services/systemDetailsApi';
import { assetApi } from '@/services/assetApi';
import { toast } from '@/lib/custom-toast';
interface SystemDetailsImportData extends Omit<SystemDetailsCreateRequest, 'assetID'> {
assetID?: number;
// Asset creation fields if asset doesn't exist
assetType?: string;
brandModel?: string;
serialNumber?: string;
assetCondition?: string;
purchaseDate?: string;
warrantyExpiry?: string;
purchaseCost?: number;
currentValue?: number;
location?: string;
notes?: string;
}
interface SystemDetailsBulkImportResponse {
success: boolean;
message: string;
results: {
successful: number;
failed: number;
details: Array<{
row: number;
success: boolean;
message: string;
data?: any;
}>;
};
}
export const useBulkImportSystemDetails = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (systemDetailsData: SystemDetailsImportData[]): Promise<SystemDetailsBulkImportResponse> => {
const results: SystemDetailsBulkImportResponse = {
success: true,
message: '',
results: {
successful: 0,
failed: 0,
details: []
}
};
for (let i = 0; i < systemDetailsData.length; i++) {
const data = systemDetailsData[i];
const rowNum = i + 1;
try {
let assetID = data.assetID;
let assetExists = false;
// Check if asset ID exists
if (assetID) {
try {
const existingAsset = await assetApi.getById(assetID);
assetExists = !!existingAsset;
} catch (error) {
// Asset doesn't exist, we'll create a new one
assetExists = false;
}
}
// If no asset ID provided or asset doesn't exist, create a new asset
if (!assetID || !assetExists) {
if (!data.assetType || !data.brandModel || !data.serialNumber || !data.assetCondition) {
results.results.failed++;
results.results.details.push({
row: rowNum,
success: false,
message: assetID ?
`Asset ID ${assetID} not found and missing required fields to create new asset (Asset Type, Brand/Model, Serial Number, Asset Condition)` :
`Missing required fields to create new asset (Asset Type, Brand/Model, Serial Number, Asset Condition)`
});
continue;
}
const assetData: AssetCreateRequest = {
assetType: data.assetType!,
brandModel: data.brandModel!,
serialNumber: data.serialNumber!,
assetCondition: data.assetCondition!,
purchaseDate: data.purchaseDate,
warrantyExpiry: data.warrantyExpiry,
purchaseCost: data.purchaseCost,
currentValue: data.currentValue,
location: data.location,
notes: data.notes
};
try {
const newAsset = await assetApi.create(assetData);
assetID = newAsset.assetID;
} catch (error: any) {
results.results.failed++;
results.results.details.push({
row: rowNum,
success: false,
message: assetID ?
`Asset ID ${assetID} not found and failed to create new asset: ${error.message || 'Unknown error'}` :
`Failed to create new asset: ${error.message || 'Unknown error'}`
});
continue;
}
}
// Create system details with the asset ID
const systemDetailsRequest: SystemDetailsCreateRequest = {
assetID: assetID!,
systemModel: data.systemModel,
processor: data.processor,
installedRAM: data.installedRAM,
graphics: data.graphics,
screenResolution: data.screenResolution,
diskModel: data.diskModel,
diskSize: data.diskSize,
manufacturer: data.manufacturer
};
const systemDetails = await systemDetailsApi.create(systemDetailsRequest);
results.results.successful++;
results.results.details.push({
row: rowNum,
success: true,
message: data.assetID && assetExists ?
`System details created for existing asset ${assetID}` :
`New asset ${assetID} created with system details`,
data: systemDetails
});
} catch (error: any) {
results.results.failed++;
results.results.details.push({
row: rowNum,
success: false,
message: `Failed to create system details: ${error.message || 'Unknown error'}`
});
}
}
// Set overall success status
results.success = results.results.failed === 0;
results.message = results.success ?
`Successfully imported ${results.results.successful} system details` :
`Import completed with ${results.results.failed} failures`;
return results;
},
onSuccess: (result: SystemDetailsBulkImportResponse) => {
// Invalidate and refetch both system details and assets data
queryClient.invalidateQueries({ queryKey: ['systemDetails'] });
queryClient.invalidateQueries({ queryKey: ['assets'] });
if (result.success) {
if (result.results.failed === 0) {
toast.success(`Successfully imported all ${result.results.successful} system details`);
} else {
toast.success(
`Import completed: ${result.results.successful} successful, ${result.results.failed} failed`,
{
description: 'Check the import results for details on failed items.'
}
);
}
} else {
toast.error(`Import failed: ${result.results.failed} system details could not be imported`, {
description: result.message
});
}
},
onError: (error: any) => {
const errorMessage = error?.message || 'Failed to import system details';
toast.error('Bulk import failed', {
description: errorMessage
});
}
});
};