@pongrass/utils 1.0.1-v20 → 1.0.2-v20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,7 @@ import { AgGridModule } from '@ag-grid-community/angular';
21
21
  import { ClientSideRowModelModule } from '@ag-grid-community/client-side-row-model';
22
22
  import { ModuleRegistry, _EditCoreModule } from '@ag-grid-community/core';
23
23
  import { CsvExportModule } from '@ag-grid-community/csv-export';
24
+ import * as ExcelJS from 'exceljs';
24
25
 
25
26
  class ConfigurationServiceLib {
26
27
  currentTablePreference;
@@ -1246,7 +1247,6 @@ class MultiFormComponent {
1246
1247
  ngOnInit() {
1247
1248
  this.buildFormControls();
1248
1249
  this.saveInitialFormValues();
1249
- console.log('config ->>>', this.configurationService);
1250
1250
  }
1251
1251
  ngOnChanges(changes) {
1252
1252
  if (changes['config'] && !changes['config'].isFirstChange()) {
@@ -2127,6 +2127,327 @@ class ITableGridPagination {
2127
2127
  paginationPageSizeSelector = this.configurationService.allConfigValues()?.tableGridConfig.defaultPageSizeSelector || false;
2128
2128
  }
2129
2129
 
2130
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2131
+ // Output: "2024-10-02 15:43:58"
2132
+ function convertToISOnString(date) {
2133
+ if (!date)
2134
+ return '';
2135
+ const dateString = date instanceof Date ? date.toISOString() : date;
2136
+ if (dateString.includes('T')) {
2137
+ return dateString.replace('T', ' ').split('.')[0];
2138
+ }
2139
+ return dateString;
2140
+ }
2141
+ // defaultDateFormat = 'DD/MM/YYYY';
2142
+ // Output: "02/10/2024"
2143
+ function regionalDateFormat(date) {
2144
+ if (!date)
2145
+ return '';
2146
+ const config = window.config;
2147
+ const month = ('0' + (date.getMonth() + 1)).slice(-2);
2148
+ const day = ('0' + date.getDate()).slice(-2);
2149
+ const year = date.getFullYear();
2150
+ switch (config.defaultDateFormat) {
2151
+ case 'MM/DD/YYYY':
2152
+ return `${month}/${day}/${year}`;
2153
+ case 'DD/MM/YYYY':
2154
+ return `${day}/${month}/${year}`;
2155
+ case 'YYYY/MM/DD':
2156
+ return `${year}/${month}/${day}`;
2157
+ default:
2158
+ return `${month}/${day}/${year}`;
2159
+ }
2160
+ }
2161
+ // convertIsoToFormat(date, 'YYYY/MM/DD');
2162
+ // Output: "2024/10/02"
2163
+ function convertIsoToFormat(date, dateFormat) {
2164
+ if (!date)
2165
+ return '';
2166
+ const config = window.config;
2167
+ let format;
2168
+ if (dateFormat)
2169
+ format = dateFormat;
2170
+ else
2171
+ format = config.defaultDateFormat;
2172
+ const dateObj = new Date(date);
2173
+ const year = dateObj.getFullYear();
2174
+ const month = String(dateObj.getMonth() + 1).padStart(2, '0');
2175
+ const day = String(dateObj.getDate()).padStart(2, '0');
2176
+ return format.replace('YYYY', String(year)).replace('MM', month).replace('DD', day);
2177
+ }
2178
+ // Output: 'Oct 2, 2024, 3:43:58 PM'
2179
+ function convertDateShort(dateString) {
2180
+ if (!dateString) {
2181
+ return '';
2182
+ }
2183
+ const date = new Date(dateString);
2184
+ return date.toLocaleString('en-US', {
2185
+ month: 'short',
2186
+ day: 'numeric',
2187
+ year: 'numeric',
2188
+ hour: 'numeric',
2189
+ minute: 'numeric',
2190
+ second: 'numeric',
2191
+ hour12: true
2192
+ });
2193
+ }
2194
+
2195
+ var ExportToExcelNames;
2196
+ (function (ExportToExcelNames) {
2197
+ ExportToExcelNames["ProdStatusReport"] = "Prod_Status_Report";
2198
+ ExportToExcelNames["NationalROPReport"] = "National ROP Report";
2199
+ ExportToExcelNames["NationalInserts"] = "National Inserts";
2200
+ ExportToExcelNames["ApprovedAdList"] = "Approved Ad List";
2201
+ ExportToExcelNames["PageStatusReport"] = "Page Status Report";
2202
+ })(ExportToExcelNames || (ExportToExcelNames = {}));
2203
+ var ExcelType;
2204
+ (function (ExcelType) {
2205
+ ExcelType["excelBlobType"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
2206
+ ExcelType["xlsxBookType"] = "xlsx";
2207
+ })(ExcelType || (ExcelType = {}));
2208
+
2209
+ class UtilsService {
2210
+ configurationServiceLib = inject(ConfigurationServiceLib);
2211
+ toastrService = inject(ToastrService);
2212
+ allConfigValues = this.configurationServiceLib.allConfigValues() || {};
2213
+ constructor() { }
2214
+ formatToTwoDecimalPlaces(value, decimalPlaces) {
2215
+ if (value !== undefined && value !== null) {
2216
+ const numValue = Number(value);
2217
+ if (!isNaN(numValue)) {
2218
+ return numValue.toFixed(decimalPlaces || 2);
2219
+ }
2220
+ }
2221
+ return value?.toString() || '';
2222
+ }
2223
+ // Truncate values to precision
2224
+ truncateFloat(value, precision) {
2225
+ const num = Number(value);
2226
+ if (isNaN(num))
2227
+ return '';
2228
+ const factor = Math.pow(10, precision);
2229
+ const truncated = Math.trunc(num * factor) / factor;
2230
+ return truncated.toFixed(precision);
2231
+ }
2232
+ /**
2233
+ *
2234
+ * @param excelData Table data to export
2235
+ * @param columns Array of Column keys and label '{ keys: '_key', label: '_label' }'
2236
+ * @param excelFileName Name of the excel file 'Example FileName_export_1740978888354'
2237
+ * @param headers (Optional) Adds Extra headings on top of the columns
2238
+ * @param showTotalValueCols (Optional) Calculates and shows the total of all the values of that column
2239
+ * @param columnAlignment (Optional) Aligns the cell value (currently only to right side)
2240
+ */
2241
+ async exportAsExcelFile(excelData, columns, excelFileName, headers, showTotalValueCols, columnAlignment) {
2242
+ // this.loaderService.show();
2243
+ const workbook = new ExcelJS.Workbook();
2244
+ const worksheet = workbook.addWorksheet(excelFileName);
2245
+ // const currentRow = 1;
2246
+ // if (headers) {
2247
+ // headers.forEach((header: IExcelHeaders) => {
2248
+ // worksheet.mergeCells(`A${currentRow}:K${currentRow}`);
2249
+ // worksheet.getCell(`A${currentRow}`).value = header.heading;
2250
+ // worksheet.getCell(`A${currentRow}`).alignment = { horizontal: header.alignment, wrapText: true };
2251
+ // worksheet.getCell(`A${currentRow}`).font = { bold: header.bold, size: header.fontSize || 14 };
2252
+ // currentRow++;
2253
+ // });
2254
+ // worksheet.addRow({});
2255
+ // }
2256
+ const columnLabels = columns.map(col => col.label);
2257
+ const columnKeys = columns.map(col => col.key);
2258
+ const headerRow = worksheet.addRow(columnLabels);
2259
+ headerRow.eachCell(cell => {
2260
+ cell.font = { bold: true, size: 12 };
2261
+ });
2262
+ // Prepare worksheet data and add it to the worksheet
2263
+ const worksheetData = this.prepareWorksheetData(excelData, columns);
2264
+ worksheetData.forEach(dataRow => {
2265
+ const rowInstance = worksheet.addRow(Object.values(dataRow));
2266
+ // Align specific columns based on columnAlignment parameter
2267
+ if (columnAlignment?.align === 'end' && columnAlignment.headers.length > 0) {
2268
+ rowInstance.eachCell((cell, colNumber) => {
2269
+ const columnKey = columnKeys[colNumber - 1]; // Match index with headers
2270
+ if (columnAlignment.headers.includes(columnKey)) {
2271
+ cell.alignment = { horizontal: 'right' };
2272
+ }
2273
+ });
2274
+ }
2275
+ });
2276
+ // Calculate total for specified columns
2277
+ if (showTotalValueCols && showTotalValueCols.length > 0) {
2278
+ const totalRow = {};
2279
+ columns.forEach(col => {
2280
+ if (showTotalValueCols.includes(col.key)) {
2281
+ totalRow[col.label] = excelData.reduce((sum, row) => sum + (Number(row[col.key]) || 0), 0);
2282
+ }
2283
+ else {
2284
+ totalRow[col.label] = ''; // Empty for non-total columns
2285
+ }
2286
+ });
2287
+ const totalRowInstance = worksheet.addRow(Object.values(totalRow));
2288
+ totalRowInstance.eachCell((cell, colNumber) => {
2289
+ cell.font = { bold: true, color: { argb: '000' }, size: 12 };
2290
+ cell.alignment = { horizontal: 'left' };
2291
+ cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFFF00' } };
2292
+ cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
2293
+ // Apply right alignment for specified total columns
2294
+ const columnKey = columnKeys[colNumber - 1];
2295
+ if (columnAlignment?.headers.includes(columnKey)) {
2296
+ cell.alignment = { horizontal: 'right' };
2297
+ }
2298
+ });
2299
+ }
2300
+ // Set column widths
2301
+ columns.forEach((col, index) => {
2302
+ worksheet.getColumn(index + 1).width = 15;
2303
+ });
2304
+ // Generate Excel file and save
2305
+ const buffer = await workbook.xlsx.writeBuffer();
2306
+ this.saveAsExcelFile(buffer, excelFileName);
2307
+ }
2308
+ /** Prepare Data for Excel Export*/
2309
+ prepareWorksheetData(data, columns) {
2310
+ const rows = data.map(row => {
2311
+ const formattedRow = {};
2312
+ columns.forEach(col => {
2313
+ formattedRow[col.label] = row[col.key];
2314
+ });
2315
+ return formattedRow;
2316
+ });
2317
+ return [...rows];
2318
+ }
2319
+ /** Save Buffer File */
2320
+ saveAsExcelFile(buffer, fileName) {
2321
+ const data = new Blob([buffer], { type: ExcelType.excelBlobType });
2322
+ const url = window.URL.createObjectURL(data);
2323
+ const link = document.createElement('a');
2324
+ link.href = url;
2325
+ const unique = Math.random().toString(36).substring(2, 8).toUpperCase();
2326
+ link.download = `${fileName}_${convertIsoToFormat(new Date())}_${unique}.${ExcelType.xlsxBookType}`;
2327
+ document.body.appendChild(link);
2328
+ link.click();
2329
+ document.body.removeChild(link);
2330
+ window.URL.revokeObjectURL(url);
2331
+ setTimeout(() => {
2332
+ // this.loaderService.hide();
2333
+ this.toastrService.success(`${link.download} file downloaded successfully`, 'Success');
2334
+ }, 500);
2335
+ }
2336
+ /** Print Page Status Report */
2337
+ printHTMLTable(columns, data, headers, showTotalValueCols) {
2338
+ let headersAndHeadings = '';
2339
+ if (headers) {
2340
+ headersAndHeadings = this.generateHeaderHTML(headers);
2341
+ }
2342
+ const headerHTML = `<tr>${columns
2343
+ .map(col => `<th style="border: 1px solid #ddd; padding: 8px; background-color: #f2f2f2;">${col.label}</th>`)
2344
+ .join('')}</tr>`;
2345
+ const bodyHTML = data
2346
+ .map((row, index) => {
2347
+ const rowStyle = index % 2 === 0 ? 'background-color: #f9f9f9;' : 'background-color: #e9ecef;';
2348
+ const rowHTML = columns
2349
+ .map(col => {
2350
+ const cellBackground = col.key === 'page_status_name' ? `background-color: ${row?.html_color || ''};` : '';
2351
+ return `<td style="border: 1px solid #ddd; padding: 8px; ${cellBackground}}">${row[col.key] !== null ? row[col.key] : ''}</td>`;
2352
+ })
2353
+ .join('');
2354
+ return `<tr style="${rowStyle}">${rowHTML}</tr>`;
2355
+ })
2356
+ .join('');
2357
+ // Generate Footer Row with Totals
2358
+ let footerHTML = '';
2359
+ if (showTotalValueCols && showTotalValueCols.length > 0) {
2360
+ const totalRow = columns
2361
+ .map(col => {
2362
+ if (showTotalValueCols.includes(col.key)) {
2363
+ const total = data.reduce((sum, row) => sum + (Number(row[col.key]) || 0), 0);
2364
+ return `<td style="border: 1px solid #ddd; padding: 8px; background-color: yellow; font-weight: bold;">${this.formatToTwoDecimalPlaces(total)}</td>`;
2365
+ }
2366
+ return `<td style="border: 1px solid #ddd; padding: 8px; background-color: yellow;"></td>`; // Empty but styled
2367
+ })
2368
+ .join('');
2369
+ footerHTML = `<tr>${totalRow}</tr>`;
2370
+ }
2371
+ const tableHTML = `
2372
+ <table style="width: 100%; border-collapse: collapse;">
2373
+ <thead>${headerHTML}</thead>
2374
+ <tbody>${bodyHTML}</tbody>
2375
+ <tfoot>${footerHTML}</tfoot>
2376
+ </table>
2377
+ `;
2378
+ // Create a new window for printing
2379
+ const printWindow = window.open('', '', 'width=800, height=600');
2380
+ if (printWindow) {
2381
+ printWindow.document.write(`
2382
+ <html>
2383
+ <head>
2384
+ <style>
2385
+ @media print {
2386
+ @page {
2387
+ size: landscape;
2388
+ }
2389
+ body {
2390
+ -webkit-print-color-adjust: exact;
2391
+ print-color-adjust: exact;
2392
+ }
2393
+ table { width: 100%; border-collapse: collapse; }
2394
+ th, td { border: 1px solid black; padding: 10px; }
2395
+ th { background-color: #f2f2f2; }
2396
+ p { margin: 0; padding: 0; }
2397
+ }
2398
+ </style>
2399
+ </head>
2400
+ <body>
2401
+ <title>Report</title>
2402
+ ${headersAndHeadings}
2403
+ ${tableHTML}
2404
+ <script type="text/javascript">
2405
+ window.onload = function() {
2406
+ window.print();
2407
+ window.onafterprint = window.close();
2408
+ };
2409
+ </script>
2410
+ </body>
2411
+ </html>
2412
+ `);
2413
+ printWindow.document.close();
2414
+ printWindow.focus();
2415
+ }
2416
+ }
2417
+ // Function to generate header HTML from headers array
2418
+ generateHeaderHTML(headers) {
2419
+ return headers
2420
+ .map(header => {
2421
+ let style = '';
2422
+ if (header.alignment) {
2423
+ style += `text-align: ${header.alignment};`;
2424
+ }
2425
+ if (header.bold) {
2426
+ style += 'font-weight: bold;';
2427
+ }
2428
+ if (header.fontSize) {
2429
+ style += `font-size: ${header.fontSize}px;`;
2430
+ }
2431
+ if (header.marginBottom) {
2432
+ style += `margin-bottom: ${header.marginBottom}px;`;
2433
+ }
2434
+ if (header.marginTop) {
2435
+ style += `margin-bottom: ${header.marginTop}px;`;
2436
+ }
2437
+ return `<p style="${style}">${header.heading}</p>`;
2438
+ })
2439
+ .join('');
2440
+ }
2441
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: UtilsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2442
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: UtilsService, providedIn: 'root' });
2443
+ }
2444
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: UtilsService, decorators: [{
2445
+ type: Injectable,
2446
+ args: [{
2447
+ providedIn: 'root'
2448
+ }]
2449
+ }], ctorParameters: () => [] });
2450
+
2130
2451
  /*
2131
2452
  * Public API Surface of utils
2132
2453
  */
@@ -2135,5 +2456,5 @@ class ITableGridPagination {
2135
2456
  * Generated bundle index. Do not edit.
2136
2457
  */
2137
2458
 
2138
- export { CheckboxCellRendererComponent, CircularFocusDirective, ColorCellRendererComponent, CommentsButtonCellRendererComponent, ConfigurationServiceLib, CustomSelectFilterComponent, DecimalInputDirective, EditionListGroupedComponent, FormFieldType, GenericFilterModelComponent, ITableGridConfiguration, ITableGridPagination, IndustryUpdateListboxCellRendererComponent, MultiFormComponent, MultiFormModule, MultiSelectStylerDirective, PageStatusCellRendererComponent, ShowTooltipIfTruncatedDirective, StatusSelectCellRendererComponent, TableGridComponent, TableGridModule };
2459
+ export { CheckboxCellRendererComponent, CircularFocusDirective, ColorCellRendererComponent, CommentsButtonCellRendererComponent, ConfigurationServiceLib, CustomSelectFilterComponent, DecimalInputDirective, EditionListGroupedComponent, ExcelType, ExportToExcelNames, FormFieldType, GenericFilterModelComponent, ITableGridConfiguration, ITableGridPagination, IndustryUpdateListboxCellRendererComponent, MultiFormComponent, MultiFormModule, MultiSelectStylerDirective, PageStatusCellRendererComponent, ShowTooltipIfTruncatedDirective, StatusSelectCellRendererComponent, TableGridComponent, TableGridModule, UtilsService, convertDateShort, convertIsoToFormat, convertToISOnString, regionalDateFormat };
2139
2460
  //# sourceMappingURL=pongrass-utils.mjs.map