import { Command } from 'commander'; import path from 'path'; import fs from 'fs'; import { normalizeName } from '../../../../helpers/profileGeneratorHelper'; import { v4 } from 'uuid'; import { getProjectPath } from '../../../../helpers/cluserHelper'; import { reportYaml } from '../../../../components/reportTemplate'; import { tableYaml } from '../../../../components/tableTemplate'; import { mergeVariables } from '../../../../helpers/variablesHelper'; export function GenerateReportCommand(): Command { const cmd = new Command('generate') .alias('g') .description('Generates a HexaSync Report') .option( '-n, --report-name ', "Search for related report, e.g.: 'negative product stock', 'skus exist in shopify only'", ) .option( '-c, --category ', 'Classify the report folder, e.g.: product', ) .action(async ({ reportName, category }) => { const componentPath = getProjectPath(); if (!fs.existsSync(path.join(componentPath, 'reports'))) { fs.mkdirSync(path.join(componentPath, 'reports'), { recursive: true, }); } const reportPath = path.join( componentPath, 'reports', category.toLowerCase().replace(/[^a-zA-Z0-9]+/g, '-'), ); if (!fs.existsSync(reportPath)) { fs.mkdirSync(reportPath, { recursive: true }); } const normalizedReportName = normalizeName(reportName); const reportVariableKey = `${normalizedReportName.camelCaseName}_Report`; let reportYml = reportYaml(); const reportId = v4(); const tableId = v4(); const reportVariables = [ { field: 'id', key: `**${reportVariableKey}_Id**`, value: reportId, }, { field: 'name', key: `**${reportVariableKey}_Name**`, value: normalizedReportName.displayName, }, { field: 'tableName', key: `**${reportVariableKey}_Table_Name**`, value: `__hsr_${normalizedReportName.underscoreSlug}`, }, { field: 'tableId', key: `**${reportVariableKey}_Table_Id**`, value: tableId, }, ]; for (var i = 0; i < reportVariables.length; i++) { var variable = reportVariables[i]; reportYml = reportYml.replaceAll( `||VARIABLE_KEY_${variable.field}||`, variable.key, ); } // generating a report does not care about table content. Just create an empty table let tableYml = tableYaml(); const tableVariables = [ { field: 'id', key: `**${reportVariableKey}_Table_Id**`, value: tableId, }, ]; for (var i = 0; i < tableVariables.length; i++) { var variable = tableVariables[i]; tableYml = tableYml.replaceAll( `||VARIABLE_KEY_${variable.field}||`, variable.key, ); } mergeVariables(reportVariables); const reportFilePath = path.join(reportPath, `${reportVariableKey}.yaml`); const reportTableFilePath = path.join( reportPath, `${reportVariableKey}_Table.yaml`, ); if (fs.existsSync(reportFilePath)) { console.error(`There is a file exists in ${reportFilePath}`); return; } if (fs.existsSync(reportTableFilePath)) { console.error(`There is a file exists in ${reportTableFilePath}`); return; } fs.writeFileSync(reportFilePath, reportYml); fs.writeFileSync(reportTableFilePath, tableYml); }); return cmd; }