import { Command } from 'commander'; import { searchReport } from '../../../../helpers/profileGeneratorHelper'; import fs from 'fs'; import path from 'path'; import { parse, stringify } from 'yaml'; import { setEntityColumnsSourceId, setEntityColumnsKeys, setEntityColumnsTrackForChanges, setEntityColumnsVisibility, findEntityById, } from '../../../../helpers/entityHelper'; import { composeProfile } from '../../../compose/composeCommand'; function extractSqlSelectFields(sql: string) { // todo: make it smarter, currently it only accept some kinds of sql that has alias return sql .match(/[\t\s\r\n]+as[\t\s\r\n]([^,\r\n\s\t]+)/g) ?.map((e: string) => e .replace(/[\t\s\r\n]+as[\t\s\r\n]([^,\r\n\s\t]+)/g, '$1') .replace(/[^a-zA-Z0-9_]/g, ''), ); } export function GenerateReportTableCommand(): Command { const cmd = new Command('generate-table') .alias('gt') .description('Regenerate a HexaSync Report Table contents') .option( '-n, --report-name ', "Search for related report, e.g.: 'negative product stock', 'skus exist in shopify only'", ) .action(async ({ reportName }) => { const reportYml = (await searchReport(reportName)) as any; if (!reportYml) { console.error(`There is no such report ${reportName}`); return; } const tableFileName = reportYml.tableId .replaceAll('**', '') .replace(/_Id$/g, ''); // const componentPath = getProjectComponentPath(); const tableFilePath = path.join( path.dirname(reportYml.__file_path), `${tableFileName}.yaml`, ); const tableYml = parse(fs.readFileSync(tableFilePath, 'utf-8')); if (!tableYml) { console.error( `There is no such table associated to report ${reportName}. Did you use hexasync-cli tool correctly?`, ); return; } const fields = extractSqlSelectFields(reportYml.reportSql) || []; let cols = tableYml.tables[0].columns || {}; for (var i = 0; i < fields.length; i++) { cols[fields[i]] = { indexGroups: [] }; } tableYml.tables[0].columns = { ...cols }; fs.writeFileSync( tableFilePath, stringify(tableYml, { keepSourceTokens: true, lineWidth: 0 }), ); await setEntityColumnsSourceId(reportYml.tableId, '', 'table'); await setEntityColumnsKeys(reportYml.tableId, '', 'table'); await setEntityColumnsTrackForChanges(reportYml.tableId, '', 'table'); await setEntityColumnsVisibility(reportYml.tableId, '', 'table'); await composeProfile(); }); return cmd; }