Dry run test added

This commit is contained in:
2026-07-29 14:52:16 +02:00
parent 7e2a84681a
commit 22005d464d
2 changed files with 83 additions and 32 deletions
+72 -32
View File
@@ -10,6 +10,7 @@ let excelFile = process.argv[2];
let pdfFile = process.argv[3];
// excel1 => /Users/ddatinguinoo/Downloads/Estratto IPP 5 Sic.xlsx
// excel2 => /Users/ddatinguinoo/Downloads/Estratto Haccp IPP 5 (1).xlsx
// excel3 di prova => /Users/ddatinguinoo/Downloads/File di prova.xlsx
// pdf1 => /Users/ddatinguinoo/Downloads/G-S IPP 5.pdf
// pdf2 => /Users/ddatinguinoo/Downloads/H IPP 5.pdf
@@ -49,7 +50,7 @@ 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, tempFiles) {
async function attachPdfToAccount(sfdc, tempFiles, isDryRun = false) {
let parser;
try {
let contentVersion;
@@ -90,15 +91,44 @@ async function attachPdfToAccount(sfdc, tempFiles) {
// use the soql command to search in the database
// if codice fiscale is not available, I search the user's account based on their name and lastname
const soql = `SELECT Id, Name FROM Account WHERE (${conditions.join(' OR ')}) ORDER BY CreatedDate DESC LIMIT 1`;
const soql = `SELECT Id, Name FROM Account WHERE (${conditions.join(' OR ')}) ORDER BY CreatedDate DESC LIMIT 1`;
const result_soql = await sfdc.query(soql);
//const soql2 = `SELECT Id, Name, ContentType, ParentId FROM Attachment WHERE ParentId='${ result_soql.records[0].Id }'`;
//const result2 = await sfdc.query(soql2);
if (result_soql && result_soql.records && result_soql.records.length > 0) { // if we find something
contentVersion = await sfdc.create('ContentVersion', {
Title: `${ result_soql.records[0].Name }_Document.pdf`,
PathOnClient: `${ result_soql.records[0].Name }_Document.pdf`,
VersionData: base64Pdf, // Must be Base64 string
FirstPublishLocationId: result_soql.records[0].Id// Automatically creates the link to the Account!
});
let matchFound = result_soql.records[0];
console.log('--- Match found! ---');
/*console.log(`|-- Id: ${ matchFound.Id || 'N/D'} --- ${ result_soql.records[0].Id }`);
console.log(`|-- Name: ${ matchFound.Name || 'N/D'}`);
console.log(`|-- Account Salesforce: ${ result_soql.records[0].Name || 'N/D'}: ${ matchFound.Id }`);
console.log(`|-- ContentType: ${ matchFound.ContentType || 'N/D'}`);*/
if (isDryRun) {
console.log('DRY RUN: non creato documento');
}
else {
contentVersion = await sfdc.create('ContentVersion', {
Title: `${ result_soql.records[0].Name }_Document.pdf`,
PathOnClient: `${ result_soql.records[0].Name }_Document.pdf`,
VersionData: base64Pdf, // Must be Base64 string
FirstPublishLocationId: `${ result_soql.records[0].Id }`// Automatically creates the link to the Account!
});
//const accountName = result_soql.records[0].Name;
const nowIsoString = new Date().toISOString(); // current timestamp in UTC
const todayDate = new Date().toISOString().split('T')[0];
const newDocument = await sfdc.create('Documento__c', {
Account__c: `${ result_soql.records[0].Id }`,
//Name: `Attestato - ${ accountName } - ${ todayDate }`,
Name: `Attestato - Sicurezza e Salute sul Lavoro -`,
Data_Caricamento__c: nowIsoString,
Tipo_Documento__c: "Dossier di Tirocinio",
Stato__c: 'Valido'
})
}
}
else {
console.log('Account non trovato su Salesforce!');
}
}
finally {
@@ -108,34 +138,13 @@ async function attachPdfToAccount(sfdc, tempFiles) {
}
}
console.log(`PDFs successfully attached!`);
console.log('Dry run completed!')
} catch (error) {
console.error(`Error uploading PDF: `, error);
}
}
// here we create an Account for each client and upload their pdf file
async function uploadUserAccount(data) {
await initializeSalesforceConnection();
// now for each client we need to create an Account on Salesforce Sandbox
try {
for (let i = 0; i < data.length; i++) {
const firstName = (data[i].NOME || '').toString().trim();
const lastName = (data[i].COGNOME || '').toString().trim();
let userData = {
Name: `${ firstName } ${ lastName }`.trim(),
CF__c: data[i].CODICE_FISCALE || null,
};
const newAccount = await sfdc.create('Account', userData); // it creates the Account
}
console.log('Accounts created successfully!');
}
catch (error) {
console.log('Something went wrong while creating the accounts: ', error);
}
}
// this is where i need to store each page in a temporary pdf file
async function processPage(pdfDoc, pageIndex, tempFiles) {
try {
@@ -273,7 +282,38 @@ function cleanUp(tempFiles) {
}
async function main() {
if (!excelFile || !pdfFile) {
const isMyFlag = process.argv.includes('--myFlag') || process.env.MY_FLAG === 'true';
const isDryRun = process.argv.includes('--dryRun') || process.env.DRY_RUN === 'true';
if (isMyFlag) {
console.log(`--- Test di attachPdfToAccount ${isDryRun ? '(MODALITÀ DRY RUN)' : ''} --- \n`);
const testPdfFile = pdfFile || process.argv[2];
if (!testPdfFile) {
console.error('Errore: Fornisci il percorso di un file PDF per il test.');
process.exit(1);
}
const tempFilePath = [];
try {
let resultExcel = await splitExcelFile(excelFile);
let resultPdf = await splitPDF(resultExcel.numRows, pdfFile, tempFilePath);
await initializeSalesforceConnection();
// Passiamo isDryRun come terzo parametro!
await attachPdfToAccount(sfdc, resultPdf, isDryRun);
} catch (err) {
console.error('An error occurred in test mode: ', err);
} finally {
cleanUp(tempFilePath);
}
return;
}
/*if (!excelFile || !pdfFile) {
console.error('Error: Please provide both Excel and PDF paths.\nUsage: node script.js <path-to-excel> <path-to-pdf>');
process.exit(1);
}
@@ -291,7 +331,7 @@ async function main() {
}
finally {
cleanUp(tempFilePath);
}
}*/
}
main();