diff --git a/almadevprod.json b/almadevprod.json new file mode 100644 index 0000000..7b61e01 --- /dev/null +++ b/almadevprod.json @@ -0,0 +1,11 @@ +{ + "access_token":"00D1t000000ss9x!AQEAQE1CnJO6.Pj0Dp.sNM8GJiLqg78JObdGkoMe_8bSvKiAghEx96_U4UerGqmWNjC0HhRqT3WxS9SAJ2mV.Sx_zZEB9cKb", + "refresh_token":"5Aep8610F.RUa2F48BnJfSHjt4eCIOSyaqJl8Ge64SjsPyNpED5mcb5jPDcu_LKFFtZxiGH9VxtfA==", + "signature":"BKDhT/jYJpboLOxPNz5Wc4jOH6WA1zoPesOYzQbpLyg=", + "scope":"refresh_token chatter_api api full", + "id_token":"eyJraWQiOiIyNjAiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiNEs2VUplRmxJeXFaVVVURzE0dXRYUSIsInN1YiI6Imh0dHBzOi8vbG9naW4uc2FsZXNmb3JjZS5jb20vaWQvMDBEMXQwMDAwMDBzczl4RUFBLzAwNTF0MDAwMDAxcGRWckFBSSIsImF1ZCI6IjNNVkc5UmQzcUM2b01hbFVJQWhPMXlyYUpCU3NkT181WDB0VGgwTTNaVzJ3aWFfZEhaYXc0d2lrYlU5STVYVVpDakQ4RmI0dnZTMmd0djBranlLUjEiLCJhbXIiOlsiVG90cCIsIm1mYSIsIm90cCIsInB3ZCJdLCJpc3MiOiJodHRwczovL2xvZ2luLnNhbGVzZm9yY2UuY29tIiwiZXhwIjoxNzczNzMyMTY0LCJpYXQiOjE3NzM3MzIwNDR9.hNM0BuXYa40Bu8WAHfPJtA6AzgSRRaKgejUTu6XwD7-tdAUe8f_mSdU4OnSRrreW13ixGzqk8r0CEWGMvPPTNHYueePMoNYSRWZeERJlclbygijwLu-w6U2HVp6KTl7kl2-VSwT2xUZ2lOu-Cu0hAY1EoqVrq-oRHUWfSjKgjCanPeD4MIJ2yxo6NrOJ6EV6wQanInkMQeycVtMIJUGTlNqeQMuBJkk9HY_kjaMI_M4acIGnupUcl4i-h9-Kzxh4BCVCQBTdh45PQ69VbdfyJbhX1W3czaXxx0W0Tyr6J1EtX5ttlOB9Hyp16dkbE_ajpSilUSPil2-2_a_g1sLgWX3OkVO0OR8CLi1F4ZDLR8Li9NYVnZNABluM912siTHUJfhAJj1p5EsKN0TMpU4f-k7EL3h90C7oiwlFW1OmHs6r3XK9N3sVAqWz9ByRggyNw_l_hhyIxKNZNJisBSURRTr85thkhwqH9Gq8b8w0jnCxLN0pnz8rmDK6oxwbjcLLaOCGp-oqV8IamMGkJu45aCAqZVxSvr5oEz3zqb2PoeEyZDVEzzrRlw-CcTxH5tF14zxq4WJXqKV1kbRgIOGdgGAQzgP0fnm5HGO4cIDIHFDH2TYX9Km-AD3JkkHIKRvqcYOCVmW8ir5RJ10yNzNmn6C1IwjB8JnP4KNFmFQLQBc", + "instance_url":"https://almascuola.my.salesforce.com", + "id":"https://login.salesforce.com/id/00D1t000000ss9xEAA/0051t000001pdVrAAI", + "token_type":"Bearer", + "issued_at":"1773732044735" +} \ No newline at end of file diff --git a/file.js b/file.js index 1dde7fc..3a46952 100644 --- a/file.js +++ b/file.js @@ -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 '); process.exit(1); } @@ -291,7 +331,7 @@ async function main() { } finally { cleanUp(tempFilePath); - } + }*/ } main(); \ No newline at end of file