106 lines
2.7 KiB
TypeScript
106 lines
2.7 KiB
TypeScript
import express, { Request, Response } from 'express';
|
|
import { prisma, __path, log } from '../../../../index.js';
|
|
import { UploadedFile } from 'express-fileupload';
|
|
import { parse } from 'csv';
|
|
import { itemStatus, itemCategory, PrismaPromise } from '@prisma/client';
|
|
|
|
function post(req: Request, res: Response) {
|
|
// 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);
|
|
});
|
|
log.db.debug(categories);
|
|
// Remove categories that already exists in the database
|
|
prisma.itemCategory
|
|
.findMany({
|
|
where: {
|
|
name: {
|
|
in: Array.from(categories)
|
|
}
|
|
}
|
|
})
|
|
.then((values) => {
|
|
values.forEach((value) => {
|
|
categories.delete(value.name);
|
|
});
|
|
log.db.debug(categories);
|
|
const categoryPromises: PrismaPromise<itemCategory>[] = [];
|
|
categories.forEach((category: string) => {
|
|
const promise = prisma.itemCategory.create({
|
|
data: {
|
|
name: category,
|
|
description: ''
|
|
}
|
|
});
|
|
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: itemStatus.normal,
|
|
createdBy: '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;
|
|
});
|
|
});
|
|
}
|
|
|
|
function get(req: Request, res: Response) {
|
|
// Render page
|
|
res.render(__path + '/src/frontend/manage/imports/csvImport.eta.html');
|
|
}
|
|
|
|
export default { get, post };
|