ZoeApi/helpers/serialBook.js

116 lines
2.7 KiB
JavaScript

const { v4: uuidv4 } = require("uuid");
const fs = require("fs");
const { stringify } = require("csv-stringify");
let columns = {
fisrt: "FIRSTLINE",
second: "SECONDLINE",
};
var serialList = [];
function genSerialList(quantity, results) {
let oldValues = [];
Object.values(results).forEach((element) => {
oldValues.push(element.serial);
});
serialList = [];
return new Promise((resolve, reject) => {
while (serialList.length < quantity) {
let uui = uuidv4();
uui = uui.replace(/-/gm, "");
uui = uui.toUpperCase();
let milliseconds = Date.now().toString();
milliseconds = milliseconds.match(/[0-9]{4}/gm);
let partition = uui.match(/[0-9A-Z]{4}/gm);
let head = partition[0].concat(
" ",
milliseconds[1],
" ",
partition[1],
" ",
milliseconds[2]
);
let body = partition[2].concat(
" ",
milliseconds[1],
" ",
partition[3],
" ",
milliseconds[2]
);
let legs = partition[4].concat(
" ",
milliseconds[1],
" ",
partition[5],
" ",
milliseconds[2]
);
let tail = partition[6].concat(
" ",
milliseconds[1],
" ",
partition[7],
" ",
milliseconds[2]
);
let now = new Date();
oldValues.includes(head)
? ""
: serialList.push({ serial: head, createdAt: now, updatedAt: now });
oldValues.includes(body)
? ""
: serialList.push({ serial: body, createdAt: now, updatedAt: now });
oldValues.includes(legs)
? ""
: serialList.push({ serial: legs, createdAt: now, updatedAt: now });
oldValues.includes(tail)
? ""
: serialList.push({ serial: tail, createdAt: now, updatedAt: now });
}
serialList = serialList.slice(0, quantity);
resolve(serialList);
});
}
function generateCSV(list) {
return new Promise((resolve, reject) => {
let filename = `${__dirname}\\mycsv.csv`;
let data = [];
Object.values(list).forEach((element) => {
let partSerial = element.serial.match(/[0-9A-Z]{4}/gm);
data.push([
partSerial[0].concat(" ", partSerial[1]),
partSerial[2].concat(" ", partSerial[3]),
]);
});
stringify(
data,
{
header: true,
columns: columns,
delimiter: ";",
},
(err, output) => {
if (err) {
reject(err);
}
fs.writeFile(filename, output, (err) => {
if (err) {
reject(err);
}
resolve(filename);
});
}
);
});
}
module.exports = {
genSerialList,
generateCSV,
};