Optimized script for generating formatted PDF reports based on inputs from the "Main" sheet.
Enhancements:
Reduced number of Spreadsheet API calls by batching data operations.
Improved filtering efficiency using JavaScript array methods.
Enhanced error handling and logging for better debugging.
Improved code readability and maintainability.
Added AM/PM format to all date-time displays.
Included email recipient in log notes when emails are sent.
*/
function generateFreePDFReport() {
const startTime = new Date();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const mainSheet = ss.getSheetByName("Main");
const logSheet = ss.getSheetByName("Log(s)");
// Fetch inputs from Main sheet in a single batch operation
const mainRange = mainSheet.getRange("H2:K7");
const mainValues = mainRange.getValues(); // H2:K7 spans multiple rows
if (!folder) {
Logger.log(Folder "${folderName}" not found. Please create it in Google Drive.);
mainSheet.getRange("H2").setValue(Folder "${folderName}" not found.);
return;
}
// Create or clear the Report sheet
let reportSheet = ss.getSheetByName(REPORT_SHEET_NAME);
if (reportSheet) {
reportSheet.clear();
} else {
reportSheet = ss.insertSheet(REPORT_SHEET_NAME);
}
// Export to PDF
const pdfBlob = exportSheetAsPDF(ss, REPORT_SHEET_NAME, pdfName, formattedReportNumber, generationTime);
if (pdfBlob) {
// Save PDF to Drive
const pdfFile = folder.createFile(pdfBlob);
Logger.log(PDF report generated: ${pdfFile.getUrl()});
// Email the PDF if required
if (sendEmailFlag === "yes" && emailRecipient) {
sendEmailWithReport(pdfFile, formattedReportNumber, generationTime, emailRecipient, reportType);
}
// Log the report generation
logReportGeneration(ss, LOG_SHEET_NAME, formattedReportNumber, reportType, sendEmailFlag, assetClassFilter, brokerFilter, userFilter, emailRecipient, generationTime); // Passed emailRecipient
// Delete the Report sheet to clean up
ss.deleteSheet(reportSheet);
} else {
Logger.log("PDF blob was not created.");
mainSheet.getRange("H2").setValue("Failed to generate PDF.");
}
}
/**
Retrieves an existing folder by name. If it doesn't exist, returns null.
@param {string} folderName - The name of the folder.
@return {Folder|null} - The Google Drive folder or null if not found.
*/
function getExistingFolder(folderName) {
const folders = DriveApp.getFoldersByName(folderName);
return folders.hasNext() ? folders.next() : null;
}
/**
Retrieves the next unique report number from the Log(s) sheet and increments it.
@param {Spreadsheet} ss - The active spreadsheet.
@param {string} logSheetName - The name of the Log(s) sheet.
@return {number} - The unique report number.
*/
function getNextReportNumber(ss, logSheetName) {
const logSheet = ss.getSheetByName(logSheetName);
if (!logSheet) {
Logger.log(Log sheet "${logSheetName}" not found. Please create it with headers in row 4: Sl, Date time, Note.);
throw new Error(Log sheet "${logSheetName}" not found.);
}
const lastRow = logSheet.getLastRow();
let nextReportNumber = 1;
if (lastRow >= 4) { // Assuming data starts at row 4
const lastReportNumber = logSheet.getRange(lastRow, 1).getValue();
if (!isNaN(lastReportNumber) && lastReportNumber >= 1) {
nextReportNumber = lastReportNumber + 1;
}
}
return nextReportNumber;
}
/**
Inserts the report header including the report number and barcode into the Report sheet.
Ensures barcode is placed in a separate cell to avoid overlap.
@param {Sheet} reportSheet - The report sheet.
@param {string} reportNumber - The unique 5-digit report number.
@param {Date} generationTime - The consistent generation time.
*/
function insertReportHeader(reportSheet, reportNumber, generationTime) {
// Insert Report Title and Generation Time
const headerValues = [
[Trading Report - Report #${reportNumber}],
[Generated At: ${Utilities.formatDate(generationTime, Session.getScriptTimeZone(), "dd-MMM-yyyy hh:mm:ss a")}], // Updated format
['']
];
reportSheet.getRange(1, 1, headerValues.length, 1).setValues(headerValues);
// Apply formatting to the title and generation time
reportSheet.getRange("A1").setFontWeight("bold").setFontSize(16);
reportSheet.getRange("A2").setFontSize(12);
// Insert Barcode Image using QuickChart
const barcodeURL = https://quickchart.io/barcode?text=${reportNumber}&format=png&type=code128&height=50;
// Add a blank row after the barcode
reportSheet.appendRow(['']);
}
/**
Appends a PnL section (Delivery or Intraday) to the Report sheet, including data, formatting, and totals.
@param {Spreadsheet} ss - The active spreadsheet.
@param {Sheet} reportSheet - The report sheet.
@param {string} sheetName - The name of the PnL sheet ("PnL" or "PnL_i").
@param {string} sectionTitle - The title of the section ("Delivery Trades" or "Intraday Trades").
@param {Object} filters - Filters for Asset Class, Broker, User, Start Date, End Date.
@param {boolean} newPage - If true, starts the section on a new page.
*/
function appendPnLSection(ss, reportSheet, sheetName, sectionTitle, filters, newPage = false) {
const pnlSheet = ss.getSheetByName(sheetName);
if (!pnlSheet) {
Logger.log(Sheet "${sheetName}" not found.);
return;
}
// Apply filters and fetch data
const { data, headers, columnIndices } = getFilteredData(pnlSheet, filters);
if (
dateColumnIndex === undefined ||
assetClassIndex === undefined ||
brokerIndex === undefined ||
userIndex === undefined ||
netPnLIndex === undefined ||
valueBuyIndex === undefined ||
percentPnLIndex === undefined
) {
throw new Error(One or more required columns not found in sheet "${sheet.getName()}".);
}
// Filter data based on criteria
const filteredData = data.filter(row => {
const date = row[dateColumnIndex];
if (!(date instanceof Date) || isNaN(date)) return false;
if (filters.startDate && new Date(date) < new Date(filters.startDate)) return false;
if (filters.endDate && new Date(date) > new Date(filters.endDate)) return false;
Applies number formats to the specified range based on column indices.
@param {Range} range - The range to apply formats to.
@param {Array} columnIndices - The 1-based indices of columns that require number formatting.
*/
function applyNumberFormats(range, columnIndices) {
const numRows = range.getNumRows();
const numCols = range.getNumColumns();
const formats = range.getNumberFormats();
columnIndices.forEach(colIndex => {
if (colIndex <= numCols) {
for (let i = 0; i < numRows; i++) {
formats[i][colIndex - 1] = "#,##0.00"; // Customize format as needed
}
}
});
range.setNumberFormats(formats);
}
/**
Converts a column index (1-based) to its corresponding letter (e.g., 1 -> A).
@param {number} column - The 1-based column index.
@return {string} - The corresponding column letter.
*/
function columnToLetter(column) {
let temp;
let letter = '';
while (column > 0) {
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = Math.floor((column - temp - 1) / 26);
}
return letter;
}
/**
Inserts a total row by summing specified columns after the data rows.
@param {Sheet} reportSheet - The report sheet.
@param {number} dataStartRow - The starting row number of the data (1-based).
@param {number} numRows - The number of data rows.
@param {Array} columnIndices - The 1-based indices of the columns to sum.
@param {number} totalColumns - Total number of columns in the data.
*/
function insertTotalRowAfter(reportSheet, dataStartRow, numRows, columnIndices, totalColumns) {
const totalRow = Array(totalColumns).fill('');
totalRow[0] = "Total"; // Assuming first column is for labels
// Insert the total row
reportSheet.appendRow(totalRow);
const totalRowNumber = dataStartRow + numRows;
// Apply formatting to the total row
const totalRange = reportSheet.getRange(totalRowNumber, 1, 1, totalColumns);
totalRange.setFontWeight("bold").setBackground("#d3d3d3").setNumberFormat("@"); // Set as needed
}
/**
Applies formatting to the Report sheet to make it systematic and visually appealing.
Sets column widths, text alignment, frozen rows, and alternating row colors.
@param {Sheet} reportSheet - The report sheet.
*/
function formatReportSheet(reportSheet) {
// Adjust column widths to fit content
reportSheet.autoResizeColumns(1, reportSheet.getLastColumn());
// Set text alignment to left for all cells
const range = reportSheet.getDataRange();
range.setHorizontalAlignment("left");
// Freeze the top rows where headers and barcode are placed
reportSheet.setFrozenRows(5); // Adjust based on the number of header rows
if (numRows > 5) { // Adjust based on frozen rows
const dataRange = reportSheet.getRange(6, 1, numRows - 5, numColumns);
const backgrounds = [];
for (let i = 0; i < (numRows - 5); i++) {
const isEven = (i + 1) % 2 === 0;
const rowColor = isEven ? "#f9f9f9" : "#ffffff";
backgrounds.push(Array(numColumns).fill(rowColor));
}
dataRange.setBackgrounds(backgrounds);
}
}
/**
Exports a specific sheet as a PDF blob, including report number and generation time.
@param {Spreadsheet} ss - The active spreadsheet.
@param {string} sheetName - The name of the sheet to export.
@param {string} pdfName - The desired PDF file name.
@param {string} reportNumber - The unique report number.
@param {Date} generationTime - The consistent generation time.
@return {Blob|null} - The PDF blob of the sheet or null if export fails.
*/
function exportSheetAsPDF(ss, sheetName, pdfName, reportNumber, generationTime) {
const sheet = ss.getSheetByName(sheetName);
if (!sheet) {
Logger.log(Sheet "${sheetName}" not found.);
return null;
}
// Include emailRecipient in the note if email was sent
const note = sendEmailFlag === "yes"
? ${reportType} Report generated with Report Number ${reportNumber}_${mailStatus}_${assetClassFilter} | ${brokerFilter} | ${userFilter}_${emailRecipient}
: ${reportType} Report generated with Report Number ${reportNumber}_${mailStatus}_${assetClassFilter} | ${brokerFilter} | ${userFilter};
// Find the next empty row starting from row 4
const lastRow = logSheet.getLastRow();
const nextRow = lastRow >= 4 ? lastRow + 1 : 4;
// Prepare log data with the Date object for column B
const logData = [
[reportNumber, generationTime, note, '', '', '', '']
];
// Batch set the log data
logSheet.getRange(nextRow, 1, 1, 7).setValues(logData);
// Set the number format for column B to "dd-MMM-yyyy hh:mm:ss a" (12-hour format with AM/PM)
logSheet.getRange(nextRow, 2).setNumberFormat("dd-MMM-yyyy hh:mm:ss a");
}"
ye script ek dm sahi h aur badiya se kaam kr rahi h pr :
column B ka time in "Log(s) " sheet aur uska format jo time email body aur pdf me ara h usse match nhi ho rahha . jbki match hona chahiye.
baki kuch change nhi krna na aulter krna na more na less . jitta bola utta karo. apne mn se kuch nhi krna.
Thank you for providing the detailed script and explaining the issue clearly. To ensure that the time format in column B of the "Log(s)" sheet matches the format used in the email body and PDF ("dd-MMM-yyyy hh:mm:ss a"), you need to adjust the logReportGeneration function.
Currently, the script writes the generationTime as a Date object and then sets the number format. However, to ensure consistency, it's more reliable to format the date as a string before writing it to the "Log(s)" sheet.
Here’s how you can make the necessary changes:
Updated logReportGeneration Function
/**
* Logs the report generation with report number, type, email status, and applied filters in the "Log(s)" sheet.
* @param {Spreadsheet} ss - The active spreadsheet.
* @param {string} logSheetName - The name of the Log(s) sheet.
* @param {string} reportNumber - The unique report number.
* @param {string} reportType - The type of report generated.
* @param {string} sendEmailFlag - "yes" or "no" indicating if email was sent.
* @param {string} assetClassFilter - The Asset Class filter applied.
* @param {string} brokerFilter - The Broker filter applied.
* @param {string} userFilter - The User filter applied.
* @param {string} emailRecipient - The recipient's email address (added for logging).
* @param {Date} generationTime - The consistent generation time.
*/
function logReportGeneration(ss, logSheetName, reportNumber, reportType, sendEmailFlag, assetClassFilter, brokerFilter, userFilter, emailRecipient, generationTime) { // Added emailRecipient parameter
const logSheet = ss.getSheetByName(logSheetName);
if (!logSheet) {
Logger.log(`Log sheet "${logSheetName}" not found. Please create it with headers in row 4: Sl, Date time, Note.`);
return;
}
const mailStatus = sendEmailFlag === "yes" ? "Mail_Sent" : "Mail_Void";
// Include emailRecipient in the note if email was sent
const note = sendEmailFlag === "yes"
? `${reportType} Report generated with Report Number ${reportNumber}_${mailStatus}_${assetClassFilter} | ${brokerFilter} | ${userFilter}_${emailRecipient}`
: `${reportType} Report generated with Report Number ${reportNumber}_${mailStatus}_${assetClassFilter} | ${brokerFilter} | ${userFilter}`;
// Find the next empty row starting from row 4
const lastRow = logSheet.getLastRow();
const nextRow = lastRow >= 4 ? lastRow + 1 : 4;
// **Format the generationTime as a string**
const formattedDate = Utilities.formatDate(generationTime, Session.getScriptTimeZone(), "dd-MMM-yyyy hh:mm:ss a");
// **Prepare log data with the formatted date string for column B**
const logData = [
[reportNumber, formattedDate, note, '', '', '', '']
];
// Batch set the log data
logSheet.getRange(nextRow, 1, 1, 7).setValues(logData);
// **Remove the setNumberFormat line since the date is already formatted as a string**
// logSheet.getRange(nextRow, 2).setNumberFormat("dd-MMM-yyyy hh:mm:ss a");
}
Reason: By formatting generationTime as a string before writing it to the sheet, you ensure that the date and time are stored exactly as intended, eliminating any discrepancies caused by cell formatting.
Reason: Since the date and time are now stored as a formatted string, there's no need to apply a number format to the cell.
Result
With these changes:
Consistency: The time in column B of the "Log(s)" sheet will exactly match the format used in the email body and PDF.
Reliability: Storing the date and time as a formatted string ensures that the format remains consistent, regardless of any spreadsheet locale settings or other formatting issues.
Final Note
Please replace the existing logReportGeneration function in your script with the updated version provided above. This change is minimal and strictly addresses the formatting issue you described without altering any other part of the script.
If you encounter any further issues or need additional assistance, feel free to ask!