102 lines
2.6 KiB
TypeScript

import express, { Request, Response } from 'express';
import { prisma, __path, log } from '../../../../index.js';
import { UploadedFile } from 'express-fileupload';
import { parse, transform } from 'csv';
import { Status, Category, PrismaPromise } from '@prisma/client';
export default (req: Request, res: Response) => {
// Decide wether its post or get
if (req.method === 'POST') {
// Handle file upload and import
console.log(req.files)
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
const file: UploadedFile = req.files.formFile as UploadedFile;
const csv = file.data.toString();
parse(csv, { columns: true }, function (err, records) {
if (err) {
res.send(err);
return;
}
// Find all categories and save them into a set
const categories = new Set<string>();
records.forEach((record: any) => {
categories.add(record.category);
});
// Remove categories that already exists in the database
prisma.category.findMany({
where: {
name: {
in: Array.from(categories)
}
}
}).then((values) => {
values.forEach((value) => {
categories.delete(value.name);
});
const categoryPromises: PrismaPromise<Category>[] = [];
categories.forEach((category: string) => {
const promise = prisma.category.create({
data: {
name: category
}
})
categoryPromises.push(promise);
});
Promise.all(categoryPromises).then((values) => {
// Create items
const listOfPromises = [];
for (let i = 0; i < records.length; i++) {
const record = records[i];
const promise = prisma.item.create({
data: {
name: record.name,
Amount: parseInt(record.amount),
Comment: record.comment,
category: {
connect: {
name: record.category
}
},
SKU: record.sku,
manufacturer: record.manufacturer,
status: Status.normal,
importedBy: "CSV Import"
}
});
listOfPromises.push(promise);
}
Promise.all(listOfPromises).then((values) => {
console.log(values);
res.send('ok');
}).catch((err) => {
res.send('failed to create items');
log.db.error(err);
return;
});
}).catch((err) => {
// res.send('failed to create categories');
log.db.error(err);
});
}).catch((err) => {
res.send('failed to find categories');
log.db.error(err);
return;
});
});
} else {
// Render page
res.render(__path + '/src/frontend/manage/imports/csvImport.eta.html');
}
};