osr-mono/packages/osr-tasks/tasks/laser2.js
2025-10-29 13:43:08 +01:00

260 lines
10 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.register = exports.createLaserFiles = exports.laserDetails = exports.regexLaserFile = void 0;
const path = require("path");
const pMap = require("p-map");
const osr_commons_1 = require("@plastichub/osr-commons");
const primitives_1 = require("@plastichub/core/primitives");
const read_1 = require("@plastichub/fs/read");
const exists_1 = require("@plastichub/fs/exists");
const osr_sync_1 = require("@plastichub/osr-sync");
const library_1 = require("../library");
const src_1 = require("../src");
exports.regexLaserFile = /^(\d+)_([a-zA-Z0-9]+(?:[_-][a-zA-Z0-9]+)*)_x(\d+)_(\d+)mm_(\w+)$/;
const laserDetails = (input) => {
if (!input) {
return false;
}
const fileName = (path.parse(input).name);
const match = fileName.match(exports.regexLaserFile);
if (!match) {
const idMatch = input.match(/^(\d+)_/);
const nameMatch = input.match(/_(\w+)_/);
const quantityMatch = input.match(/_x\d+_/);
const thicknessMatch = input.match(/_\d+mm_/);
const materialMatch = input.match(/_\w+$/);
let errorMessage = 'Invalid input format:';
if (!idMatch) {
errorMessage += `\n- Leading ID (digits) is missing or invalid : ${fileName}`;
}
if (!nameMatch) {
errorMessage += `\n- Name (letters) is missing or invalid ${fileName}`;
}
if (!quantityMatch) {
errorMessage += `\n- Quantity (x followed by digits) is missing or invalid ${fileName}`;
}
if (!thicknessMatch) {
errorMessage += `\n- Thickness (digits followed by "mm") is missing or invalid ${fileName}`;
}
if (!materialMatch) {
errorMessage += `\n- Material (alphanumeric characters) is missing or invalid ${fileName}`;
}
src_1.logger.error(errorMessage);
return;
}
const [_, id, name, quantity, thickness, material] = match;
return {
id: parseInt(id),
name,
quantity: parseInt(quantity),
thickness: parseInt(thickness),
material
};
};
exports.laserDetails = laserDetails;
const parts_with_laser = (model) => {
if (!model) {
return [];
}
let parts = [...model.filter((f) => f.IsLaser === "1"), ...model];
return parts.filter((f) => {
const _path = path.resolve((0, osr_commons_1.resolve)(f['File Path']));
if (_path && (0, exists_1.sync)(_path)) {
const dir = path.parse(_path).dir;
const laser = path.resolve(path.join(dir, 'laser'));
if ((0, exists_1.sync)(laser)) {
return f;
}
}
});
};
const createLaserFiles = async (root, product, options, grunt) => {
if (!(0, exists_1.sync)(root)) {
options.debug && src_1.logger.info("Create Laser Files : Root doesnt exists" + root);
}
const PRODUCT_ROOT = path.resolve(path.join(root, product));
if (!(0, exists_1.sync)(PRODUCT_ROOT)) {
src_1.logger.warn(`Invalid product root : ${PRODUCT_ROOT}`);
return false;
}
const main = (0, library_1.MainAssembly)(PRODUCT_ROOT, options.filePattern);
if (!main) {
src_1.logger.warn("Have no main assembly at " + PRODUCT_ROOT);
return false;
}
const modelFilePath = (0, library_1.file_path_with_ext_ex)(main, 'json');
if (!modelFilePath || !(0, exists_1.sync)(modelFilePath)) {
src_1.logger.warn("Have no model at " + modelFilePath);
return false;
}
const model = (0, read_1.sync)(modelFilePath, 'json');
let tree = null;
const treeFilePath = (0, library_1.file_path_with_ext_ex)(main, 'tree.json');
if (!treeFilePath || !(0, exists_1.sync)(treeFilePath)) {
src_1.logger.warn("Have no tree at " + treeFilePath);
}
else {
tree = (0, read_1.sync)(treeFilePath, 'json');
}
const laserParts = parts_with_laser(model);
let laserDirectories = [
...new Set(laserParts.map((f) => {
const _path = path.resolve((0, osr_commons_1.resolve)(f['File Path']));
const dir = path.parse(_path).dir;
const ret = {
target: (0, library_1.forward_slash)(path.relative(PRODUCT_ROOT, dir)).
replace('../components/', '').
replace('components', '').
replace('cad', '').
replace('../', ''),
path: path.resolve(dir + '/laser')
};
return ret;
}))
];
const config = (0, read_1.sync)(path.join(PRODUCT_ROOT, 'config.json'), 'json');
if (!config) {
src_1.logger.warn("Have no config at " + PRODUCT_ROOT);
return [];
}
laserDirectories = (0, library_1.unique_by)(laserDirectories, 'path');
src_1.logger.debug('Create laser files for ', laserDirectories);
const qtyTotal = (qty, filePath) => {
if (tree) {
const { Components } = tree.assembly;
if (!Components) {
return qty;
}
const c = Components.filter((c) => {
const partPath = path.parse(c.Path).name.toLowerCase();
const laserFilePath = path.parse(filePath).name.toLowerCase();
return partPath === laserFilePath && !c.IsSuppressed;
}).length;
if (c) {
return c;
}
else {
debugger;
src_1.logger.warn(`Cant find instances of file : ${path.parse(filePath).name} : \n\t${filePath} in tree : \n\t${treeFilePath}`);
}
}
return qty;
};
const qtyTotal2 = (qty, filePath) => {
if (tree) {
const { Components } = tree.assembly;
if (!Components) {
return qty;
}
let count = 1;
const chlidren = tree.root.Children;
if (chlidren) {
const items = chlidren.filter((c) => {
const partPath = path.parse(c.Path).name.toLowerCase();
const laserFilePath = path.parse(filePath).name.toLowerCase();
return partPath === laserFilePath && !c.IsSuppressed;
});
count = items.length;
}
if (count) {
return count;
}
else {
src_1.logger.warn(`Cant find instances of file : ${path.parse(filePath).name} : \n\t${filePath} in tree : \n\t${treeFilePath}`);
}
}
return qty;
};
return pMap(laserDirectories, async (item) => {
return pMap(['en', 'es'], async (lCode) => {
const renamer = (from, to) => {
if ((0, osr_commons_1.isFolder)(from)) {
return;
}
const lParts = (0, exports.laserDetails)(from) || {};
if (!lParts) {
src_1.logger.warn(`Invalid laser file in ${PRODUCT_ROOT} : ${from}`);
}
const fromParts = path.parse('' + from);
const toParts = path.parse('' + to);
const pCode = config.code || '';
const toFileParts = ('' + toParts.name).split('_');
const fromFileParts = ('' + fromParts.name).split('_');
let qty = qtyTotal2(lParts.quantity, from);
let material = fromFileParts[4];
if (!material) {
src_1.logger.error('logger.error : invalid material ', from + ' : ' + ' to : ' + to, toFileParts);
return to;
}
if (lCode === 'en') {
material = material.toLowerCase().replace("ferro", "Steel").replace("inox", "Stainless");
}
const newName = path.resolve(toParts.dir + '/' +
material + '/' +
`${lParts.thickness}mm` + '/' +
pCode + '-' +
toFileParts[0] + '_' +
toFileParts[1] + '_' +
`x${qty}` +
toParts.ext.toLowerCase());
return newName;
};
const target = `${PRODUCT_ROOT}/laser/${lCode}/${item.target}`;
src_1.logger.debug(`Create laser files for ${item.path} ${lCode} : to ${target}`);
return (0, osr_sync_1.sync)({
renamer: renamer,
clear: options.clear,
source: path.resolve(item.path),
target,
debug: options.debug,
verbose: options.verbose,
profile: options.profile,
logLevel: options.logLevel || 'warn'
});
}, { concurrency: 1 });
}, { concurrency: 1 });
};
exports.createLaserFiles = createLaserFiles;
const create = async (item, options, grunt) => {
try {
return (0, exports.createLaserFiles)(options.cwd || '.', item, options, grunt);
}
catch (e) {
src_1.logger.error(e);
return [];
}
};
const register = (grunt) => {
grunt.registerMultiTask('laser2', 'Create laser files', function () {
const done = this.async();
const task_options = this.data.options || {};
let src = (0, primitives_1.isArray)(this.data.src) ? this.data.src : [this.data.src];
src_1.logger.setSettings({ minLevel: (0, library_1.option)('logLevel', task_options, grunt, 'warn') });
let p;
src.forEach((item) => {
try {
p = create(item, {
verbose: (0, library_1.option)('verbose', task_options, grunt, false),
clear: (0, library_1.option)('clear', task_options, grunt, true),
debug: (0, library_1.option)('debug', task_options, grunt, true),
filePattern: (0, library_1.option)('filePattern', task_options, grunt, library_1.CAD_MAIN_PATTERN),
profile: (0, library_1.option)('profile', task_options, grunt, {
"matching": ["*"]
}),
module: (0, library_1.option)('module', task_options, grunt, 'osr-tasks'),
cwd: (0, library_1.option)('cwd', task_options, grunt, process.cwd())
}, grunt);
}
catch (e) {
src_1.logger.error(e);
}
});
if (p) {
p.then((result) => {
done(true);
});
}
});
};
exports.register = register;
//# sourceMappingURL=laser2.js.map