Files
inventory/inventory/src/pages/Import.tsx
2025-01-08 20:58:34 -05:00

80 lines
2.3 KiB
TypeScript

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import config from '../config';
export function Import() {
const [file, setFile] = useState<File | null>(null);
const importMutation = useMutation({
mutationFn: async (formData: FormData) => {
const response = await fetch(`${config.apiUrl}/products/import`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('Import failed');
}
return response.json();
},
});
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files?.[0]) {
setFile(e.target.files[0]);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!file) return;
const formData = new FormData();
formData.append('file', file);
importMutation.mutate(formData);
};
return (
<div className="p-8">
<h1 className="text-2xl font-bold mb-6">Import Products</h1>
<div className="max-w-xl">
<form onSubmit={handleSubmit} className="space-y-6">
<div className="space-y-2">
<label className="text-sm font-medium">
Upload CSV File
</label>
<input
type="file"
accept=".csv"
onChange={handleFileChange}
className="w-full border rounded-md p-2"
/>
<p className="text-sm text-muted-foreground">
The CSV file should contain the following columns: sku, name, description (optional), category (optional)
</p>
</div>
<button
type="submit"
disabled={!file || importMutation.isPending}
className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50"
>
{importMutation.isPending ? 'Importing...' : 'Import Products'}
</button>
{importMutation.isSuccess && (
<p className="text-green-600">
Successfully imported {importMutation.data.imported} products
</p>
)}
{importMutation.isError && (
<p className="text-red-500">
Error importing products: {importMutation.error.message}
</p>
)}
</form>
</div>
</div>
);
}