do what we can

This commit is contained in:
2025-12-07 22:41:33 -06:00
parent ca95d296b5
commit 0d6abeb287
3 changed files with 75 additions and 26 deletions
+12 -3
View File
@@ -507,7 +507,7 @@ async function createShareLink(accessToken, driveId, itemId) {
return json; return json;
} }
async function run() { async function run(incomingRecords) {
console.log('minimal-uploader starting', dryRun ? '(dry-run)' : ''); console.log('minimal-uploader starting', dryRun ? '(dry-run)' : '');
const token = await getAppToken(); const token = await getAppToken();
console.log('acquired app token (truncated):', token ? token.substring(0, 30) + '...' : '(none)'); console.log('acquired app token (truncated):', token ? token.substring(0, 30) + '...' : '(none)');
@@ -522,8 +522,16 @@ async function run() {
} }
const safeMainFolderName = sanitizeName(mainFolderName); const safeMainFolderName = sanitizeName(mainFolderName);
const subFolderName = 'Managers Info'; const subFolderName = 'Managers Info';
// Prefer generating from an Excel workbook if EXCEL_DRIVE_ID and EXCEL_ITEM_ID are present
let csvBase64 = await pdfFromCsvToBase64(pathToCsv); // Priority: use incoming records from add-in, else try CSV, else try workbook from Graph
let csvBase64 = null;
if (incomingRecords && incomingRecords.length > 0) {
console.log('Using records from Excel add-in:', incomingRecords.length, 'rows');
csvBase64 = await pdfFromRecordsToBase64(incomingRecords, 'Managers Info');
} else {
// fallback to CSV file or Graph workbook
csvBase64 = await pdfFromCsvToBase64(pathToCsv);
if (process.env.EXCEL_DRIVE_ID && process.env.EXCEL_ITEM_ID) { if (process.env.EXCEL_DRIVE_ID && process.env.EXCEL_ITEM_ID) {
console.log('EXCEL_DRIVE_ID/EXCEL_ITEM_ID present, downloading workbook from Graph to build PDF'); console.log('EXCEL_DRIVE_ID/EXCEL_ITEM_ID present, downloading workbook from Graph to build PDF');
try { try {
@@ -543,6 +551,7 @@ async function run() {
console.error('Failed to build PDF from workbook', e && e.message ? e.message : e); console.error('Failed to build PDF from workbook', e && e.message ? e.message : e);
} }
} }
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const fileName = sanitizeName(`Managers Info - ${timestamp}.pdf`); const fileName = sanitizeName(`Managers Info - ${timestamp}.pdf`);
+3 -1
View File
@@ -19,7 +19,9 @@ app.get('/api/health', (req, res) => res.json({ ok: true, ts: new Date().toISOSt
// main endpoint — run the uploader flow (download workbook if env vars exist, create folders and upload PDF) // main endpoint — run the uploader flow (download workbook if env vars exist, create folders and upload PDF)
app.post('/api/upload-managers', async (req, res) => { app.post('/api/upload-managers', async (req, res) => {
try { try {
const result = await run(); // Accept records from request body (sent from Excel add-in)
const records = req.body && req.body.records ? req.body.records : null;
const result = await run(records);
res.json({ ok: true, result }); res.json({ ok: true, result });
} catch (err) { } catch (err) {
console.error('Error in /api/upload-managers', err); console.error('Error in /api/upload-managers', err);
@@ -1,7 +1,5 @@
// Minimal add-in taskpane script — one button that calls the playground server // Minimal add-in taskpane script — reads Excel data and uploads to playground server
// Wait for Office to be ready before attaching event handlers
Office.onReady(function(info) { Office.onReady(function(info) {
// info.host will be 'Excel' when running in Excel
console.log('Office.onReady fired, host:', info.host); console.log('Office.onReady fired, host:', info.host);
const uploadBtn = document.getElementById('uploadBtn'); const uploadBtn = document.getElementById('uploadBtn');
@@ -11,15 +9,55 @@ Office.onReady(function(info) {
status.innerHTML = '<div class="' + (ok ? 'ok' : 'err') + '">' + text + '</div>'; status.innerHTML = '<div class="' + (ok ? 'ok' : 'err') + '">' + text + '</div>';
} }
// Read data from worksheet "Managers Info" and convert A1:E49 into array of objects
// Only rows with any non-empty cell are included; first row is header
async function getExcelData() {
return Excel.run(async (context) => {
// Use the specific worksheet by name and the fixed range A1:E49
const sheet = context.workbook.worksheets.getItem('Managers Info');
const range = sheet.getRange('a2:E49');
range.load('values');
await context.sync();
const values = range.values;
if (!values || values.length < 2) {
throw new Error('No data found in Managers Info A1:E49 (need header row + at least one data row)');
}
const headers = values[0].map(h => String(h || '').trim());
const records = [];
for (let i = 1; i < values.length; i++) {
const row = values[i];
// skip fully-empty rows
const isEmpty = row.every(c => c === null || c === undefined || String(c).trim() === '');
if (isEmpty) continue;
const obj = {};
headers.forEach((h, idx) => {
obj[h] = row[idx];
});
records.push(obj);
}
if (records.length === 0) throw new Error('No data rows found in Managers Info A1:E49');
return records;
});
}
uploadBtn.addEventListener('click', async function() { uploadBtn.addEventListener('click', async function() {
uploadBtn.disabled = true; uploadBtn.disabled = true;
setStatus('Starting upload...'); setStatus('Reading Excel data...');
try { try {
const res = await fetch('http://localhost:3002/api/upload-managers', { method: 'POST' }); const records = await getExcelData();
setStatus('Uploading ' + records.length + ' rows...');
const res = await fetch('http://localhost:3002/api/upload-managers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ records: records })
});
const json = await res.json(); const json = await res.json();
if (!res.ok) throw new Error(json && json.error ? json.error : 'Unknown response'); if (!res.ok) throw new Error(json && json.error ? json.error : 'Unknown response');
var link = (json.result && json.result.share && json.result.share.link) ? json.result.share.link.webUrl : 'unknown'; var link = (json.result && json.result.share && json.result.share.link) ? json.result.share.link.webUrl : 'unknown';
setStatus('Upload finished. Share link: ' + link, true); setStatus('Upload finished. Share link: <a href="' + link + '" target="_blank">' + link + '</a>', true);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
setStatus('Upload failed: ' + (err.message || err), false); setStatus('Upload failed: ' + (err.message || err), false);