ndc-suez
Version:
Generate standard ndc UI
826 lines • 38.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ndcModule = void 0;
const schematics_1 = require("@angular-devkit/schematics");
const core_1 = require("@angular-devkit/core");
const XLSX = require("xlsx");
const utils_1 = require("../utils/utils");
function ndcModule(options) {
let page;
let updateDate;
let toolTips = [];
let blocking = [];
let nonBlocking = [];
let labels = [];
let units = [];
let listbox = [];
const listBoxes = [];
const listBoxesWithMatrix = {}; // for things like ##machin_truc_lbl[0]##
const listBoxesWithPlaceHolder = {}; // for things like ##machin_truc_lbl##
const listBoxVars = {};
const casesValues = [];
const casesRules = [];
const precisions = [];
const updatable = [];
const resultTags = {};
let blockingRules = {};
let nonBlockingRules = {};
const screenHtml = {};
const functionName = {};
let blockingFields = [];
let nonBlockingFields = [];
let blockingEffectiveFields = [];
let nonBlockingEffectiveFields = [];
let visibleImpact = [];
let updateImpact = [];
let group = [];
let noteStruct = undefined;
let apiRoute = '';
let nextPages = [];
let order = 1;
let graph = undefined;
return ( /*tree: Tree*/ /*, _context: SchematicContext*/) => {
const workbook = XLSX.readFile(options.filename);
group = options.group;
if (group.length > 0) {
group.forEach((screen) => {
const screenWorkbook = workbook.Sheets[screen];
const screenData = XLSX.utils.sheet_to_json(screenWorkbook, { header: 2 });
const cRules = {};
screenData.forEach((row) => {
var _a, _b;
if (['H1', 'H2', 'H3', 'H4'].includes(row.Tool)) {
cRules[row.Label] = row.Line;
}
if (['TextBox', 'ListBox', 'ListBox2', 'Result', 'Report'].includes(row.Tool)) {
cRules[row.Variable] = row.Line;
}
if (row.BlockingRule) {
blockingFields.push(((_a = row.Variable) === null || _a === void 0 ? void 0 : _a.length) > 0 ? row.Variable : row.Label);
}
if (['ListBox', 'ListBox2'].includes(row.Tool) && row.Mandatory == '1' && !row.DefaultValue) {
blockingFields.push(row.Variable);
}
if (row.NonBlockingRule) {
nonBlockingFields.push(((_b = row.Variable) === null || _b === void 0 ? void 0 : _b.length) > 0 ? row.Variable : row.Label);
}
});
casesRules.push({
[screen]: cRules
});
});
// Generate group config file
const groupTemplateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files/group'), [
(0, schematics_1.applyTemplates)({
classify: core_1.strings.classify,
dasherize: core_1.strings.dasherize,
name: options.name,
groupName: options.groupName,
casesRules: casesRules,
blockingFields: Array.from(new Set(blockingFields)).filter(item => item !== ""),
nonBlockingFields: Array.from(new Set(nonBlockingFields)).filter(item => item !== "")
}),
(0, schematics_1.move)((0, core_1.normalize)(`/src/app/modules/${core_1.strings.dasherize(options.name)}`))
]);
return (0, schematics_1.mergeWith)(groupTemplateSource, schematics_1.MergeStrategy.Overwrite);
}
else {
page = options.page;
group = options.group || [];
if (!options.update) {
updateDate = new Date().toISOString().slice(0, 10);
}
else {
updateDate = options.update;
}
//------------------------------Conf--------------------------------------
const confSheet = workbook.Sheets['conf'];
const conf = XLSX.utils.sheet_to_json(confSheet, { header: 2 });
//-----------------------------Tooltips------------------------------------
const toolTipWorkbook = workbook.Sheets['tooltip'];
//------------------------------BlokingMessage------------------------------
const blockingMessageWorkbook = workbook.Sheets['blocking'];
//------------------------------NonBlockingMessage--------------------------
const nonBlockingMessageWorkbook = workbook.Sheets['nonblocking'];
//------------------------------Labels--------------------------------------
const labelsWorkbook = workbook.Sheets['label'];
//------------------------------Unit--------------------------------------
const unitWorkbook = workbook.Sheets['unit'];
//------------------------------Listbox--------------------------------------
const listboxWorkbook = workbook.Sheets['listbox'];
//-----------------------------graph----------------------------------------
if (workbook.SheetNames.includes('graph')) {
graph = (0, utils_1.transformGraphSheetToJson)(workbook.Sheets['graph']);
}
//------------------------------Langs----------------------------------------
let langs = [];
if (page) {
toolTips = (0, utils_1.filterByScreenWithHeader2)(toolTipWorkbook, page);
blocking = (0, utils_1.filterByScreenWithHeader2)(blockingMessageWorkbook, page);
nonBlocking = (0, utils_1.filterByScreenWithHeader2)(nonBlockingMessageWorkbook, page);
labels = processPlaceHolders((0, utils_1.filterByScreenWithHeader2)(labelsWorkbook, page, true));
units = (0, utils_1.filterByScreenWithHeader2)(unitWorkbook, page);
listbox = (0, utils_1.filterByScreenWithHeader2)(listboxWorkbook, page);
//------------------------------Langs----------------------------------------
const processedLabels = processPlaceHolders((0, utils_1.filterByScreenWithHeader2)(labelsWorkbook, page, true));
langs = [...(0, utils_1.filterByScreenWithHeader2)(toolTipWorkbook, page, true),
...(0, utils_1.filterByScreenWithHeader2)(blockingMessageWorkbook, page, true),
...(0, utils_1.filterByScreenWithHeader2)(nonBlockingMessageWorkbook, page, true),
...processedLabels,
...(0, utils_1.filterByScreenWithHeader2)(unitWorkbook, page, true),
...processPlaceHolders(processedLabels, (0, utils_1.filterByScreenWithHeader2)(listboxWorkbook, page, true))
];
const structureWorkbook = workbook.Sheets['structure'];
if (structureWorkbook) {
const noteStructAndGroupRoute = transformWorksheetToNoteStruct(structureWorkbook, page);
noteStruct = noteStructAndGroupRoute === null || noteStructAndGroupRoute === void 0 ? void 0 : noteStructAndGroupRoute.noteStruct;
apiRoute = noteStructAndGroupRoute === null || noteStructAndGroupRoute === void 0 ? void 0 : noteStructAndGroupRoute.apiRoute;
order = noteStructAndGroupRoute === null || noteStructAndGroupRoute === void 0 ? void 0 : noteStructAndGroupRoute.startOrder;
if (noteStruct === null || noteStruct === void 0 ? void 0 : noteStruct.pages) {
nextPages = getNextPages(page, noteStruct.pages);
}
}
}
else {
toolTips = XLSX.utils.sheet_to_json(toolTipWorkbook, { header: 2 });
blocking = XLSX.utils.sheet_to_json(blockingMessageWorkbook, { header: 2 });
nonBlocking = XLSX.utils.sheet_to_json(nonBlockingMessageWorkbook, { header: 2 });
labels = XLSX.utils.sheet_to_json(labelsWorkbook, { header: 2 });
units = XLSX.utils.sheet_to_json(unitWorkbook, { header: 2 });
listbox = XLSX.utils.sheet_to_json(listboxWorkbook, { header: 2 });
langs = [...toolTips, ...blocking, ...nonBlocking, ...labels, ...units, ...listbox];
}
listbox.forEach((row) => {
var _a, _b;
if (isMatrix(row.Fr)) {
listBoxesWithMatrix[row.Name] = (_a = row.Fr) === null || _a === void 0 ? void 0 : _a.replace(/##/g, '');
}
else if (typeof row.Fr === 'string' && row.Fr.includes('##')) {
listBoxesWithPlaceHolder[row.Name] = (_b = row.Fr) === null || _b === void 0 ? void 0 : _b.replace(/##/g, '');
}
});
//------------------------------Variable--------------------------------------
//for multiple page note, the config must come from api, so we won't need that
const worksheet = workbook.Sheets['variable'];
const variables = XLSX.utils.sheet_to_json(worksheet, { header: 3 });
variables.forEach((row) => {
if (row.Type != 'Input') {
resultTags[row.Variable] = row.Type;
}
});
//--------------------------- Screens----------------------------------------
//ts-ignore
let screens = getScreensByPrefix(workbook.SheetNames, conf[0].ScreenPattern);
if (page) {
screens = [page];
}
screens.forEach((screen) => {
const screenWorkbook = workbook.Sheets[screen];
const screenData = XLSX.utils.sheet_to_json(screenWorkbook, { header: 2 });
if (screenData) {
const funcName = screenData.find((row) => row.Tool == 'Fonction');
if (funcName) {
functionName[screen] = funcName.Variable;
}
}
screenHtml[screen] = screenData;
// read Variable column
const variableColumn = screenData.map((row) => row.Variable).filter(value => value !== undefined);
const blockingString = screenData.map((row) => row.BlockingRule + ' ' + row.Visibility).join(' ');
blockingFields = extractFields(blockingString, variableColumn);
const nonBlockingString = screenData.map((row) => row.NonBlockingRule).join(' ');
nonBlockingFields = extractFields(nonBlockingString, variableColumn);
const visibilityString = screenData.map((row) => row.Visibility).join(' ');
visibleImpact = extractFields(visibilityString, variableColumn);
const updatableString = screenData.map((row) => row.Updatable).join(' ');
updateImpact = extractFields(updatableString, variableColumn);
screenData.forEach((row) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
if (row.hasOwnProperty('Tool')) {
if (row.NonBlockingRule) {
if (['H1', 'H2', 'H3', 'H4'].includes(row.Tool)) {
nonBlockingRules[row.Label] = row.NonBlockingRule;
}
else {
nonBlockingRules[row.Variable] = row.NonBlockingRule;
}
nonBlockingEffectiveFields.push(((_a = row.Variable) === null || _a === void 0 ? void 0 : _a.length) > 0 ? row.Variable : row.Label);
}
if (row.BlockingRule) {
if (['H1', 'H2', 'H3', 'H4'].includes(row.Tool)) {
blockingRules[row.Label] = row.BlockingRule;
}
else {
if (row.Mandatory == '1') {
blockingRules[row.Variable] = row.BlockingRule;
}
else {
blockingRules[row.Variable] = updateNonMandatoryRules(row.Variable, row.BlockingRule);
}
}
blockingEffectiveFields.push(((_b = row.Variable) === null || _b === void 0 ? void 0 : _b.length) > 0 ? row.Variable : row.Label);
}
if (row.Updatable) {
updatable.push({
name: row.Variable,
rule: row.Updatable == 1 ? true : row.hasOwnProperty('Updatable') ? `"${(_c = new String(row.Updatable)) === null || _c === void 0 ? void 0 : _c.replace(/\\r\\n/g, " ")}"` : false,
});
}
switch (row.Tool) {
case 'ListBox':
case 'ListBox2':
listBoxVars[row.Variable] = extractCommonPrefix(row.Listbox);
let listValues = transformStringToArray(row.Listbox);
if (row.Tool == 'ListBox2') {
listValues = transformRuledStringToArray(row.Listbox);
}
listBoxes.push({
name: core_1.strings.camelize(row.Variable) + 'Box',
lists: listValues
});
casesValues.push({
name: row.Variable,
defaultValue: ((_d = row.DefaultValue) === null || _d === void 0 ? void 0 : _d.length) > 0 ? (_e = row.DefaultValue) === null || _e === void 0 ? void 0 : _e.replace(/\r\n/g, " ") : ((_f = listValues[0]) === null || _f === void 0 ? void 0 : _f.split(':').length) > 1 ? (_g = listValues[0]) === null || _g === void 0 ? void 0 : _g.split(':')[0] : listValues[0]
});
casesRules.push({
name: row.Variable,
isVisible: !isNaN(Number(row.Visibility)) ? row.Visibility == 1 : row.hasOwnProperty('Visibility') ? (_h = row.Visibility) === null || _h === void 0 ? void 0 : _h.replace(/\r\n/g, " ") : false,
lineNumber: row.Line
});
if (row.Mandatory == '1' && !row.DefaultValue) {
blockingFields.push(row.Variable);
}
break;
// @ts-ignore
case 'Result':
precisions.push({
name: row.Variable,
precision: row.Precision
});
// FALLS THROUGH to TextBox
case 'TextBox':
case 'Calcul':
casesValues.push({
name: row.Variable,
defaultValue: stringOrNull(row.DefaultValue)
});
casesRules.push({
name: row.Variable,
isVisible: !isNaN(Number(row.Visibility)) ? row.Visibility == 1 : (_j = row.Visibility) === null || _j === void 0 ? void 0 : _j.replace(/\r\n/g, " "),
lineNumber: row.Line
});
break;
case 'H1':
case 'H2':
case 'H3':
case 'H4':
casesRules.push({
name: row.Label,
isVisible: !isNaN(Number(row.Visibility)) ? row.Visibility == 1 : (_k = row.Visibility) === null || _k === void 0 ? void 0 : _k.replace(/\r\n/g, " "),
lineNumber: row.Line
});
break;
case 'Report':
casesRules.push({
name: row.Variable,
isVisible: false,
lineNumber: row.Line
});
break;
}
}
});
});
//--------------------------------------------------------------------------
// Generate module file
const moduleTemplateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files/module'), [
(0, schematics_1.applyTemplates)({
classify: core_1.strings.classify,
dasherize: core_1.strings.dasherize,
name: options.name
}),
(0, schematics_1.move)((0, core_1.normalize)(`/src/app/modules/${core_1.strings.dasherize(options.name)}`))
]);
// Generate component file
const componentTemplateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files/component'), [
(0, schematics_1.applyTemplates)({
classify: core_1.strings.classify,
dasherize: core_1.strings.dasherize,
camelize: core_1.strings.camelize,
stringify: JSON.stringify,
name: options.name,
units: units,
listBoxes: listBoxes,
listBoxVars: listBoxVars,
matrixList: listBoxesWithMatrix,
placeHolderBox: listBoxesWithPlaceHolder,
checkMatrixList: checkIsMatrixList,
casesValues: casesValues,
casesRules: casesRules,
precisions: precisions,
updatable: updatable,
fixDup: trackOccurrences,
blockingRules: explodeObject(blockingRules, resultTags),
nonBlockingRules: explodeObject(nonBlockingRules, resultTags),
blockingEffectiveFields: blockingEffectiveFields,
nonBlockingEffectiveFields: nonBlockingEffectiveFields,
screens: screens,
isApiConfig: options.apiConfig,
isPartial: options.partial,
page: options.page,
noteStruct: noteStruct,
nextPages: nextPages,
apiRoute: apiRoute,
groupName: options.groupName,
customFormat: customFormat,
updateDate: updateDate,
noteVersion: options.version,
exportPrefix: options.exportPrefix,
functionName: functionName,
slave: options.slave,
graph: graph
}),
(0, schematics_1.move)((0, core_1.normalize)(`/src/app/modules/${core_1.strings.dasherize(options.name)}`))
]);
// Generate html file
const htmlTemplateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files/html'), [
(0, schematics_1.applyTemplates)({
classify: core_1.strings.classify,
dasherize: core_1.strings.dasherize,
camelize: core_1.strings.camelize,
findStrings: findStrings2,
isExpertOnly: isExpertModeOnly,
extractMatName: extractMatrixName,
extractMainPart: extractMainPart,
outputArray: [],
name: options.name,
page: page,
order: order,
toolTips: toolTips,
blockingMessage: blocking,
nonBlockingMessage: nonBlocking,
screens: screenHtml,
hasBlockingImpact: blockingFields,
hasNonBlockingImpact: nonBlockingFields,
hasVisibleImpact: visibleImpact,
hasUpdateImpact: updateImpact,
slave: options.slave
}),
(0, schematics_1.move)((0, core_1.normalize)(`/src/app/modules/${core_1.strings.dasherize(options.name)}`))
]);
// Generate service file
/*const serviceTemplateSource = apply(
url('./files/service'), [
applyTemplates({
classify: strings.classify,
dasherize: strings.dasherize,
name: options.name,
conf: conf[0]
}),
move(normalize(`/src/app/services`))
]
);*/
const enTemplateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files/en'), [
(0, schematics_1.applyTemplates)({
langs: langs,
listBoxWithVars: listBoxesWithMatrix,
transformString: transformString,
labels: labels,
stringify: JSON.stringify,
name: options.name,
extractMainPart: extractMainPart
}),
(0, schematics_1.move)((0, core_1.normalize)(`/src/assets/i18n/${core_1.strings.dasherize(options.name)}`))
]);
const frTemplateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files/fr'), [
(0, schematics_1.applyTemplates)({
langs: langs,
listBoxWithVars: listBoxesWithMatrix,
transformString: transformString,
labels: labels,
stringify: JSON.stringify,
name: options.name,
extractMainPart: extractMainPart
}),
(0, schematics_1.move)((0, core_1.normalize)(`/src/assets/i18n/${core_1.strings.dasherize(options.name)}`))
]);
return (0, schematics_1.chain)([
(0, schematics_1.externalSchematic)('@schematics/angular', 'module', {
name: core_1.strings.dasherize(options.name),
route: core_1.strings.dasherize(options.name),
path: 'src/app/modules',
module: 'app.module'
}),
/*externalSchematic('@schematics/angular', 'service', {
name: strings.dasherize(options.name),
path: 'src/app/services',
}),*/
(0, schematics_1.mergeWith)(moduleTemplateSource, schematics_1.MergeStrategy.Overwrite),
(0, schematics_1.mergeWith)(componentTemplateSource, schematics_1.MergeStrategy.Overwrite),
(0, schematics_1.mergeWith)(htmlTemplateSource, schematics_1.MergeStrategy.Overwrite),
// mergeWith(serviceTemplateSource, MergeStrategy.Overwrite),
(0, schematics_1.mergeWith)(enTemplateSource, schematics_1.MergeStrategy.Overwrite),
(0, schematics_1.mergeWith)(frTemplateSource, schematics_1.MergeStrategy.Overwrite)
]);
}
};
}
exports.ndcModule = ndcModule;
// replaces the ##...## patterns with {{...}}, and then replaces the bracketed numbers with underscores
function transformString(inputString, labels, lang) {
if (!inputString) {
return '';
}
if (typeof inputString !== 'string') {
return inputString;
}
let transformedString = inputString
.replace(/##(.*?)##/g, '{{$1}}');
//.replace(/\[(\d+)\]/g, '_$1');
if (labels && lang) {
transformedString = replaceLabelPlaceholdersFromArray(transformedString, labels, lang);
}
return transformedString;
}
function replaceLabelPlaceholdersFromArray(str, labels, lang) {
return str.replace(/{{([a-zA-Z0-9_]+_lbl)}}/g, (_, label) => {
const found = labels.find(item => item.Name === label);
return found ? found[lang] : `{{${label}}}`;
});
}
// return array of strings from ##string##
/*function findStrings(inputString: string) {
const regex = /##(.*?)##/g;
const matches = inputString.match(regex);
const result = matches ? matches.map(match => match.slice(2, -2)) : [];
return result;
}*/
// transform {s1;s2} to ["s1","s2"]
function transformStringToArray(input) {
// Remove the curly braces at the beginning and end of the string
const strippedString = input.slice(1, -1);
// Split the string by semicolon and trim any whitespace
const stringArray = strippedString.split(';').map(item => item === null || item === void 0 ? void 0 : item.trim());
return stringArray;
}
function transformRuledStringToArray(input) {
// Remove the curly braces at the beginning and end of the string
const strippedString = input.slice(1, -1);
// Split the string by semicolon and trim any whitespace
const stringArray = strippedString.split(';').map(item => {
item = item.trim();
if (!item.includes(':')) {
item += ':true';
}
return item;
});
return stringArray;
}
function extractCommonPrefix(input) {
// Remove the leading "{" and trailing "}", then split the input into individual strings
const strings = input.slice(1, -1).split(/; ?/);
if (strings.length === 0) {
return '';
}
// Find the common prefix among the strings
const commonPrefix = strings.reduce((prefix, str) => {
let i = 0;
// Find the index where the current string differs from the prefix
while (i < prefix.length && prefix[i] === str[i]) {
i++;
}
// Return the common prefix up to the differing index
return prefix.slice(0, i);
});
return commonPrefix;
}
function isExpertModeOnly(str) {
if (str == '1') {
return false;
}
if (str == '2') {
return true;
}
return /^mode\s*=\s*expert(?:\s+ET|$)/.test(str === null || str === void 0 ? void 0 : str.trim());
}
function getScreensByPrefix(arr, prefix) {
const subArray = [];
for (const item of arr) {
if (item.startsWith(prefix)) {
subArray.push(item);
}
}
return subArray;
}
function findStrings2(inputString, outputArray) {
if (!inputString) {
return 0;
}
const regex = /##(.*?)##/g;
const matches = inputString.match(regex);
const uniqueStrings = matches ? [...new Set(matches.map(match => match.slice(2, -2)))] : [];
outputArray.length = 0;
outputArray.push(...uniqueStrings);
return uniqueStrings.length;
}
function processPlaceHolders(labels, customLabels) {
const processing = (labs) => {
for (const label of labs) {
if (/^##.*##$/.test(label.Fr)) {
const match = label.Fr.match(/^##(.*)##$/)[1];
//find it
const lab = labels.find(l => l.Name == match);
if (lab) {
label['Fr'] = lab.Fr;
label['En'] = lab.En;
}
}
}
};
if (customLabels) {
processing(customLabels);
return customLabels;
}
else {
/*for (const label of labels) {
if (/^##.*##$/.test(label.Fr)) {
const match = label.Fr.match(/^##(.*)##$/)[1];
//find it
const lab = labels.find(l => l.Name == match);
if (lab) {
label['Fr'] = lab.Fr;
label['En'] = lab.En;
}
}
}*/
processing(labels);
return labels;
}
}
function stringOrNull(value) {
const isNull = value === null || value === undefined || value === '';
if (isNull) {
return null;
}
if (typeof value == 'number') {
return String(value);
}
return value.replace(/\r\n/g, " ");
}
/*function extractFields(inputString: string, fieldNames: any[]): string[] {
// Constructing a regular expression dynamically to match any of the field names
const regex = new RegExp(`(?:${fieldNames.join('|')})\\b`, 'g');
const matches = inputString.match(regex);
if (matches) {
// Convert matches to a Set to remove duplicates
const uniqueMatches = new Set(matches);
// Convert the Set back to an array
return Array.from(uniqueMatches);
} else {
return [];
}
}*/
function extractFields(inputString, fieldNames) {
const words = inputString === null || inputString === void 0 ? void 0 : inputString.split(/\W+/);
// Create a Set to store matched field names (to remove duplicates)
const matchedFields = new Set();
// Iterate over the words in the input string
words === null || words === void 0 ? void 0 : words.forEach(word => {
const normalizedWord = word.toLowerCase();
// Check if the current word matches any of the field names
fieldNames.forEach(field => {
if (normalizedWord === field.toLowerCase()) {
matchedFields.add(field); // Add the original field name to maintain case
}
});
});
return Array.from(matchedFields);
}
function updateNonMandatoryRules(key, conditions) {
const conditionArray = conditions === null || conditions === void 0 ? void 0 : conditions.split(';');
// Prepend "key != VIDE ET" after the field name in each condition
const transformedConditions = conditionArray === null || conditionArray === void 0 ? void 0 : conditionArray.map(condition => {
// Split on the first occurrence of ':' to separate field from condition
const [field, ...rest] = condition.split(':');
const conditionBody = rest.join(':');
return `${field}:${key} != VIDE ET ${conditionBody}`;
});
return transformedConditions.join('; ');
}
/**
* input : {
key1: "Aer_mess_err_nobloq_21:Aer_Type_Aeration = Aer_t_Aeration_lbox_0;Aer_mess_err_nobloq_23:Aer_Alt < Aer_Bdd_Altmin;Aer_mess_nobloq_2:toto=tata OU bonjour=bonsoir",
key2: "Aer_mess_err_nobloq_21:Aer_Type_Aeration = Aer_t_Aeration_lbox_0;Aer_mess_err_nobloq_23:Aer_Alt < Aer_Bdd_Altmin;Aer_mess_nobloq_5:toto=tata OU bonjour=bonsoir"
}
* output :
*
{
key1: {
Aer_mess_err_nobloq_21: 'Aer_Type_Aeration = Aer_t_Aeration_lbox_0',
Aer_mess_err_nobloq_23: 'Aer_Alt < Aer_Bdd_Altmin',
Aer_mess_nobloq_2: 'toto=tata OU bonjour=bonsoir'
},
key2: {
Aer_mess_err_nobloq_21: 'Aer_Type_Aeration = Aer_t_Aeration_lbox_0',
Aer_mess_err_nobloq_23: 'Aer_Alt < Aer_Bdd_Altmin',
Aer_mess_nobloq_5: 'toto=tata OU bonjour=bonsoir'
}
}
* */
function explodeObject(original, result = {}) {
const message = {};
for (const key in original) {
const value = original[key];
const parts = value === null || value === void 0 ? void 0 : value.split(';');
//ts-ignore
message[key] = {};
if (!Array.isArray(parts)) {
continue;
}
parts.forEach((part) => {
const [messageKey, messageValue] = part.split(':');
if (messageValue) {
let rule = messageValue.trim().replace(/\r\n/g, " ");
if (result.hasOwnProperty(key)) {
rule = 'isResult = true ET ' + rule;
}
message[key][messageKey.trim()] = rule;
}
});
}
return message;
}
/*function extractNumber(str: any) {
const match = str.match(/-?\d+(\.\d+)?$/);
return match ? parseFloat(match[0]) : null;
}*/
function extractFirstPart(str) {
const match = str.match(/^(.*?)(-?\d+(\.\d+)?)$/);
return match ? match[1] : null;
}
/**
* transform toto[0] to toto_0; toto[1][2] to toto_1_2
* @param str
*/
function extractMainPart(str) {
// return str?.replace(/\[(\d+)\]/g, '_$1'); //Todo: remove => no more need for that
return str;
}
/**
*
* @param name
* @param listboxWithMatrix
* @param isTranslateString
*
* checkIsMatrixList('toto_machin_lbox_1', listboxWithMatrix) => toto_machin_lbox_1 or
* this.translate.instant('toto_machin_lbox_1', {Bdd_var: oneShotGetMatrix(Bdd_var)}) or 'toto_machin_lbox_' + oneShotGetMatrix(Bdd_var)
*/
function checkIsMatrixList(name, listboxWithMatrix, isTranslateString = false, listboxWithPlaceHolders = {}) {
if (Object.keys(listboxWithMatrix).includes(name)) {
if (isTranslateString) {
// return `this.translate.instant('${name}', {${extractMainPart(listboxWithMatrix[name])}: this.oneShotGetMatrixValue('${listboxWithMatrix[name]}')})`;
return `this.translate.instant('${name}', {'${listboxWithMatrix[name]}': this.oneShotGetMatrixValue('${listboxWithMatrix[name]}')})`;
}
else {
return `\'${extractFirstPart(name)}\' + this.oneShotGetMatrixValue('${listboxWithMatrix[name]}')`;
}
}
else {
if (isTranslateString) {
if (Object.keys(listboxWithPlaceHolders).includes(name)) {
return `this.translate.instant('${listboxWithPlaceHolders[name]}')`;
}
return `this.translate.instant('${name}')`;
}
return `\'${name}\'`;
}
}
function extractMatrixName(input) {
const regex = /^([A-Za-z_]\w*)\[\d+.*$/;
const match = input.match(regex);
return match ? match[1] : null; // return the captured array name, or null if not found
}
function isMatrix(input) {
const matrixPattern = /^(##)?[A-Za-z0-9_]+(\[\d+\])+(##)?$/;
return matrixPattern.test(input);
}
/**
* Track occurences and prepend _2_ to the second item and _3_ for third and so on
*/
function trackOccurrences() {
const occurrences = {};
return function (value) {
if (occurrences[value]) {
occurrences[value] += 1;
return `_${occurrences[value]}_${value}`;
}
else {
occurrences[value] = 1;
return value;
}
};
}
function getNextPages(name, pages) {
// Find the current item by name
const currentItem = pages.find(page => page.name === name);
if (!currentItem) {
return []; // If the item is not found, return an empty array
}
const currentIndex = pages.findIndex(page => page.name === name);
let nextItems = new Set();
for (let i = currentIndex + 1; i < pages.length; i++) {
const nextPage = pages[i];
//console.log(nextPage.group, name);
if (nextPage.group) {
if (!nextPage.group.includes(name)) {
nextItems.add(nextPage.group[0]);
}
}
else {
nextItems.add(nextPage.name);
}
}
return [...nextItems];
}
function transformWorksheetToNoteStruct(worksheet, pageName) {
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
const result = { tabs: [], pages: [] };
const groupMap = {};
let order = 1;
jsonData.forEach((row, index) => {
if (index === 0)
return; // Skip header row
const [name, type, parent, group, startOrder] = row;
if (type === 'Tab') {
const tab = { name: name };
tab['activable'] = index === 1;
tab['checked'] = index === 1;
result.tabs.push(tab);
}
else if (type === 'Page') {
if (pageName == name) {
order = startOrder;
}
const page = { name: name };
if (parent) {
page['tab'] = parent;
}
page['activable'] = pageName == name;
page['checked'] = pageName == name;
page['hasResults'] = false;
page['route'] = '/' + name.toLowerCase();
if (group) {
page['group'] = null;
if (!groupMap[group]) {
groupMap[group] = [];
}
groupMap[group].push(name);
}
result.pages.push(page);
}
});
let apiRoute = pageName;
// Assign groups to pages
result.pages.forEach((page) => {
for (const group in groupMap) {
if (groupMap[group].includes(page.name)) {
page.group = groupMap[group];
if (page.name == pageName) {
apiRoute = page.group[0];
}
}
}
});
return { noteStruct: result, apiRoute: apiRoute, startOrder: order };
}
function customFormat(obj, indent = 0) {
const indentSpaces = ' '.repeat(indent);
if (Array.isArray(obj)) {
// Inline formatting for simple arrays
const isSimpleArray = obj.every(item => typeof item !== 'object' && !Array.isArray(item));
if (isSimpleArray) {
return `[${obj.map(item => JSON.stringify(item)).join(', ')}]`;
}
// Multiline formatting for complex arrays
return `[\n${obj
.map(item => `${indentSpaces} ${customFormat(item, indent + 2)}`)
.join(',\n')}\n${indentSpaces}]`;
}
else if (typeof obj === 'object' && obj !== null) {
// Inline formatting for objects
const entries = Object.entries(obj).map(([key, value]) => {
const formattedValue = Array.isArray(value) || typeof value === 'object'
? customFormat(value, indent + 2)
: typeof value === 'string'
? `'${value}'` // Quote strings
: value; // Primitive values
return `${key}: ${formattedValue}`;
});
return `{ ${entries.join(', ')} }`;
}
else if (typeof obj === 'string') {
return `'${obj}'`; // Wrap strings in single quotes
}
return String(obj); // Handle numbers, booleans,
}
//# sourceMappingURL=index.js.map