Removed the global variables 'data' and 'tempFilePath'

This commit is contained in:
2026-07-27 17:45:50 +02:00
parent aaacec71f4
commit 181cc4876b
+42 -33
View File
@@ -14,8 +14,6 @@ let pdfFile = process.argv[3];
// excel2 => /Users/ddatinguinoo/Downloads/Estratto Haccp IPP 5 (1).xlsx
// pdf1 => /Users/ddatinguinoo/Downloads/G-S IPP 5.pdf
// pdf2 => /Users/ddatinguinoo/Downloads/H IPP 5.pdf
const data = []; // contains the info of all the clients
const tempFilePath = []; // contains the temp files
const authConfig = {
sfdcTokenFile: process.env.SFDC_TOKEN_FILE, // Path to store/retrieve OAuth tokens
@@ -53,13 +51,13 @@ function escapeSoql(str) {
// the pdf files contain the identifying ids of the users such as 'Codice Fiscale' (CF) and we use them to attach
// the page/pages to the specific account that has that id. If CFs are not available we search based on the
// name an lastname of the user
async function attachPdfToAccount(sfdc) {
async function attachPdfToAccount(sfdc, temFiles) {
let parser;
try {
let contentVersion;
for (let i = 0; i < tempFilePath.length; i++) {
for (let i = 0; i < temFiles.length; i++) {
// 1. Read the local PDF file and convert it to Base64
const pdfBuffer = fs.readFileSync(tempFilePath[i]);
const pdfBuffer = fs.readFileSync(temFiles[i]);
const base64Pdf = pdfBuffer.toString('base64');
parser = new PDFParse({ data: pdfBuffer });
try {
@@ -119,7 +117,7 @@ async function attachPdfToAccount(sfdc) {
}
// here we create an Account for each client and upload their pdf file
async function uploadUserAccount() {
async function uploadUserAccount(data) {
await initializeSalesforceConnection();
// now for each client we need to create an Account on Salesforce Sandbox
@@ -141,7 +139,7 @@ async function uploadUserAccount() {
}
}
// this is where i need to store each page in a temporary pdf file
async function processPage(pdfDoc, pageIndex) {
async function processPage(pdfDoc, pageIndex, tempFiles) {
try {
const newDoc = await PDFDocument.create();
const [ copiedPage ] = await newDoc.copyPages(pdfDoc, [pageIndex]);
@@ -150,7 +148,7 @@ async function processPage(pdfDoc, pageIndex) {
const filepath = path.join(os.tmpdir(), `fileTemp_page_${pageIndex}.pdf`);
fs.writeFileSync(filepath, pdfBytes);
tempFilePath.push(filepath);
tempFiles.push(filepath);
}
catch (error) {
console.error('Error in processPage:', error);
@@ -160,6 +158,7 @@ async function processPage(pdfDoc, pageIndex) {
async function splitExcelFile(inputFile) {
let numRows; // this parameter is needed when we need to analyze the pdf file in case it has duplicate pages
const columnNames = []; // contains the names of the columns (header names)
const data = []; // contains the info of all the clients
try {
console.log(`Loading excel file: ${ inputFile }\n`);
@@ -221,14 +220,14 @@ async function splitExcelFile(inputFile) {
})
data.push(dataUser);
}
return numRows;
return { numRows, data };
}
catch (error) {
console.error('Error processing the excel file: ', error);
}
}
async function splitPDF(numRows, inputFile) {
async function splitPDF(numRows, inputFile, tempFiles) {
console.log(`Loading pdf file: ${ inputFile }...\n`);
let parser;
@@ -256,7 +255,7 @@ async function splitPDF(numRows, inputFile) {
console.log(result.pages[i].text);
console.log("\n");*/
await processPage(srcPdf, i);
await processPage(srcPdf, i, tempFiles);
displayNumPage++;
}
}
@@ -265,7 +264,7 @@ async function splitPDF(numRows, inputFile) {
/*console.log(`--- PAGE ${i + 1} ---`);
console.log(result.pages[i].text);
console.log("\n");*/
await processPage(srcPdf, i); // Pass 0-based index i
await processPage(srcPdf, i, tempFiles); // Pass 0-based index i
}
}
}
@@ -280,15 +279,15 @@ async function splitPDF(numRows, inputFile) {
}
// cleans up temporary files from OS temp directory
function cleanUp() {
tempFilePath.forEach((file) => {
function cleanUp(tempFiles) {
tempFiles.forEach((file) => {
try {
if (fs.existsSync(file)) {
fs.unlinkSync(file);
}
}
catch (err) {
console.log(`Failed in deleting the temporary file ${ file }: `, err);
console.error(`Failed in deleting the temporary file ${ file }: `, err);
}
})
}
@@ -298,32 +297,42 @@ async function main() {
console.error('Error: Please provide both Excel and PDF paths.\nUsage: node script.js <path-to-excel> <path-to-pdf>');
process.exit(1);
}
const result = await splitExcelFile(excelFile);
await splitPDF(result, pdfFile);
const rl = readline.createInterface({ input, output });
let reply = '';
const tempFilePath = []; // contains the temp files
let resultExcel;
try {
while(!reply) {
const response = await rl.question('Do you want to create accounts or upload pages (accounts/pages)? ');
reply = response.trim();
resultExcel = await splitExcelFile(excelFile);
await splitPDF(resultExcel.numRows, pdfFile, tempFilePath);
const rl = readline.createInterface({ input, output });
let reply = '';
if (!reply) {
console.log('Please try again!');
try {
while(!reply) {
const response = await rl.question('Do you want to create accounts or upload pages (accounts/pages)? ');
reply = response.trim();
if (!reply) {
console.log('Please try again!');
}
}
if (reply === 'accounts') {
await uploadUserAccount(resultExcel.data);
}
else if (reply === 'pages') {
await initializeSalesforceConnection();
await attachPdfToAccount(sfdc, tempFilePath);
}
}
if (reply === 'accounts') {
await uploadUserAccount();
}
else if (reply === 'pages') {
await initializeSalesforceConnection();
await attachPdfToAccount(sfdc);
finally {
rl.close();
}
}
catch (err) {
console.error('An error occurred in main: ', err);
}
finally {
rl.close();
cleanUp();
cleanUp(tempFilePath);
}
}