sm-utility 2.1.0 → 2.1.2

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.
@@ -0,0 +1 @@
1
+ export declare const ITEM_DEFAULT = "-";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ITEM_DEFAULT = void 0;
4
+ exports.ITEM_DEFAULT = '-';
@@ -0,0 +1,10 @@
1
+ export declare const enum ExcelFormat {
2
+ DATE = "mmm - yy",
3
+ PERCENTAGE = "0%",
4
+ MONEY = "R$ 0.00",
5
+ ZERO_DEFAULT = "0",
6
+ NUMBER = "123"
7
+ }
8
+ export declare const enum ExcelType {
9
+ OPTIONS = "options"
10
+ }
package/excel/enums.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,6 @@
1
+ /// <reference types="node" />
2
+ import { ISpreadSheet } from "../interfaces";
3
+ export declare class ExcelCreator {
4
+ createSync<T extends Record<string, string>>(sheets: ISpreadSheet<T>[]): Buffer;
5
+ createAsync<T extends Record<string, string>>(sheets: ISpreadSheet<T>[]): Promise<Buffer>;
6
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ExcelCreator = void 0;
7
+ const node_xlsx_1 = __importDefault(require("node-xlsx"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const sheetExcelCreator_1 = require("./sheetExcelCreator");
10
+ const thread_1 = require("../../thread");
11
+ const logger_1 = require("../../logger");
12
+ const RELATIVE_PATH = "./excelCreatorWorker/worker.ts";
13
+ const EXCEL_CREATOR_WORKER_PATH = path_1.default.resolve(__dirname, RELATIVE_PATH);
14
+ class ExcelCreator {
15
+ createSync(sheets) {
16
+ const builderSheets = sheets.map((sheet) => new sheetExcelCreator_1.SheetExcelCreator().create(sheet));
17
+ const buffer = node_xlsx_1.default.build(builderSheets);
18
+ return buffer;
19
+ }
20
+ async createAsync(sheets) {
21
+ const builderSheets = sheets.map((sheet) => new sheetExcelCreator_1.SheetExcelCreator().create(sheet));
22
+ const result = await thread_1.workerfy({
23
+ data: builderSheets,
24
+ path: EXCEL_CREATOR_WORKER_PATH,
25
+ });
26
+ if (result.error) {
27
+ logger_1.logger.info("Excel creation failed", {
28
+ context: sheets.map((s) => s.name),
29
+ err: result.error,
30
+ });
31
+ }
32
+ return result.file;
33
+ }
34
+ }
35
+ exports.ExcelCreator = ExcelCreator;
@@ -0,0 +1,6 @@
1
+ import { IFormatStructure } from "../interfaces";
2
+ export declare class ExcelCreatorCustomizer {
3
+ custom(element: string, structure: IFormatStructure | undefined): string;
4
+ private validOptionsValue;
5
+ private formatValue;
6
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExcelCreatorCustomizer = void 0;
4
+ class ExcelCreatorCustomizer {
5
+ custom(element, structure) {
6
+ if (!structure)
7
+ return element;
8
+ let formattedValue = element;
9
+ if (structure.type === "options" /* OPTIONS */ && structure.options)
10
+ this.validOptionsValue(element, structure.options);
11
+ if (structure.customFormat)
12
+ formattedValue = this.formatValue(element, structure.customFormat);
13
+ if (structure.customFormatCallback)
14
+ formattedValue = structure.customFormatCallback(formattedValue);
15
+ return formattedValue;
16
+ }
17
+ validOptionsValue(value, customOptions) {
18
+ const isValid = customOptions.includes(value);
19
+ if (!isValid)
20
+ throw new Error("The element row is not in options custom items");
21
+ }
22
+ formatValue(value, customFormat) {
23
+ var _a;
24
+ switch (customFormat) {
25
+ case "123" /* NUMBER */:
26
+ return value.toString();
27
+ case "mmm - yy" /* DATE */: {
28
+ const date = new Date(value);
29
+ const month = date.getMonth();
30
+ const year = date.getFullYear();
31
+ return `${month} - ${year}`;
32
+ }
33
+ case "R$ 0.00" /* MONEY */:
34
+ return parseFloat(value).toLocaleString("pt-BR", {
35
+ style: "currency",
36
+ currency: "BRL",
37
+ });
38
+ case "0%" /* PERCENTAGE */:
39
+ return `${value}%`;
40
+ case "0" /* ZERO_DEFAULT */:
41
+ return (_a = value.toString()) !== null && _a !== void 0 ? _a : "0";
42
+ }
43
+ }
44
+ }
45
+ exports.ExcelCreatorCustomizer = ExcelCreatorCustomizer;
@@ -0,0 +1,3 @@
1
+ import { WorkSheet } from "node-xlsx";
2
+ import { IWorkerResult } from "../../interfaces";
3
+ export declare function createExcelTable(builderSheets: WorkSheet<string>[]): IWorkerResult;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createExcelTable = void 0;
7
+ const node_xlsx_1 = __importDefault(require("node-xlsx"));
8
+ function createExcelTable(builderSheets) {
9
+ try {
10
+ const file = node_xlsx_1.default.build(builderSheets);
11
+ return { file };
12
+ }
13
+ catch (err) {
14
+ const error = err;
15
+ return { error };
16
+ }
17
+ }
18
+ exports.createExcelTable = createExcelTable;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const worker_threads_1 = require("worker_threads");
4
+ const createExcelTable_1 = require("./createExcelTable");
5
+ function main() {
6
+ if (worker_threads_1.parentPort) {
7
+ const workerResult = createExcelTable_1.createExcelTable(worker_threads_1.workerData.data);
8
+ worker_threads_1.parentPort.postMessage(workerResult);
9
+ }
10
+ else {
11
+ throw Error("The 'parentPort' is not available. This code should run within a worker context.");
12
+ }
13
+ }
14
+ main();
@@ -0,0 +1,10 @@
1
+ import { WorkSheet } from "node-xlsx";
2
+ import { ISpreadSheet } from "../interfaces";
3
+ export declare class SheetExcelCreator {
4
+ create<T extends Record<string, string>>({ name, items, structures, }: ISpreadSheet<T>): WorkSheet<string>;
5
+ private buildSheetBuilder;
6
+ private buildSheetData;
7
+ private customItem;
8
+ private buildOptions;
9
+ private checkValidItem;
10
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SheetExcelCreator = void 0;
4
+ const excelCreatorCustomizer_1 = require("./excelCreatorCustomizer");
5
+ const constants_1 = require("../constants");
6
+ class SheetExcelCreator {
7
+ create({ name, items, structures, }) {
8
+ const buildedSheetData = this.buildSheetData(items, structures);
9
+ const buildedOptions = this.buildOptions(structures);
10
+ const sheetBuilder = this.buildSheetBuilder(name, buildedSheetData, buildedOptions);
11
+ return sheetBuilder;
12
+ }
13
+ buildSheetBuilder(name, data, options) {
14
+ const sheetBuilder = { name, data, options };
15
+ return sheetBuilder;
16
+ }
17
+ buildSheetData(items, structures) {
18
+ const buildedItems = [];
19
+ const buildedTitleSheet = [
20
+ structures.map((struct) => struct.header.displayName),
21
+ ];
22
+ const buildedItemSheet = items.map((item) => structures.map((struct) => this.customItem(struct, item)));
23
+ const buildedSheet = buildedItems.concat(buildedTitleSheet, buildedItemSheet);
24
+ return buildedSheet;
25
+ }
26
+ customItem(struct, item) {
27
+ const { id, custom: itemCustom } = struct;
28
+ const itemField = item[id];
29
+ if (!this.checkValidItem(itemField))
30
+ return constants_1.ITEM_DEFAULT;
31
+ const customElement = new excelCreatorCustomizer_1.ExcelCreatorCustomizer().custom(itemField, itemCustom);
32
+ return customElement;
33
+ }
34
+ buildOptions(structures) {
35
+ const buildedColumnStyle = structures.map((struct) => ({
36
+ width: struct.width,
37
+ }));
38
+ const options = { ["!cols"]: buildedColumnStyle };
39
+ return options;
40
+ }
41
+ checkValidItem(item) {
42
+ return ![null, undefined, ""].includes(item);
43
+ }
44
+ }
45
+ exports.SheetExcelCreator = SheetExcelCreator;
@@ -0,0 +1,5 @@
1
+ import { IExcelParserData } from "../interfaces";
2
+ export declare class ExcelParser {
3
+ parse<T = any>(data: IExcelParserData): Promise<T[][]>;
4
+ private deleteFile;
5
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ExcelParser = void 0;
7
+ const node_xlsx_1 = __importDefault(require("node-xlsx"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const dirname_1 = require("../../dirname");
11
+ const sheetExcelParser_1 = require("./sheetExcelParser");
12
+ class ExcelParser {
13
+ async parse(data) {
14
+ const filePath = path_1.default.resolve(dirname_1.DIRNAME, "uploads", `${data.filename}`);
15
+ const sheets = node_xlsx_1.default.parse(filePath);
16
+ const parsedResult = sheets.map((sheet) => new sheetExcelParser_1.SheetExcelParser().parse(sheet));
17
+ await this.deleteFile(filePath);
18
+ return parsedResult;
19
+ }
20
+ async deleteFile(path) {
21
+ await fs_1.default.promises.stat(path);
22
+ await fs_1.default.promises.unlink(path);
23
+ }
24
+ }
25
+ exports.ExcelParser = ExcelParser;
@@ -0,0 +1,8 @@
1
+ import { IExcelSheet } from "../interfaces";
2
+ export declare class SheetExcelParser {
3
+ parse<T>(sheet: IExcelSheet): T[];
4
+ private removingEmptyRows;
5
+ private extractHeadersFromExcelSheet;
6
+ private typeSheetCells;
7
+ private buildExcelResultRow;
8
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SheetExcelParser = void 0;
4
+ class SheetExcelParser {
5
+ parse(sheet) {
6
+ const headers = this.extractHeadersFromExcelSheet(sheet);
7
+ this.removingEmptyRows(sheet);
8
+ const sheetData = this.typeSheetCells(sheet, headers);
9
+ return sheetData;
10
+ }
11
+ removingEmptyRows(sheet) {
12
+ sheet.data = sheet.data.filter((row) => !row.every((item) => !item));
13
+ }
14
+ extractHeadersFromExcelSheet(sheet) {
15
+ const headers = sheet.data[0];
16
+ sheet.data.shift();
17
+ return headers;
18
+ }
19
+ typeSheetCells(sheet, headers) {
20
+ const sheetData = sheet.data.map((row) => {
21
+ const sheetRow = this.buildExcelResultRow(row, headers);
22
+ return sheetRow;
23
+ });
24
+ return sheetData;
25
+ }
26
+ buildExcelResultRow(row, headers) {
27
+ const buildedRow = {};
28
+ for (const [index, item] of row.entries()) {
29
+ const header = headers[index];
30
+ if (typeof item === "number") {
31
+ const value = parseFloat(item.toString());
32
+ buildedRow[header] = value;
33
+ }
34
+ else {
35
+ buildedRow[header] = item.toString();
36
+ }
37
+ }
38
+ return buildedRow;
39
+ }
40
+ }
41
+ exports.SheetExcelParser = SheetExcelParser;
@@ -0,0 +1,4 @@
1
+ export { ExcelCreator } from './excel-creator/excelCreator';
2
+ export { ExcelParser } from './excel-parser/excelParser';
3
+ export { ExcelFormat, ExcelType } from './enums';
4
+ export { ISpreadSheet, ISheetStructure, IFormatStructure, IExcelParserData, IExcelSheet, } from './interfaces';
package/excel/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExcelParser = exports.ExcelCreator = void 0;
4
+ var excelCreator_1 = require("./excel-creator/excelCreator");
5
+ Object.defineProperty(exports, "ExcelCreator", { enumerable: true, get: function () { return excelCreator_1.ExcelCreator; } });
6
+ var excelParser_1 = require("./excel-parser/excelParser");
7
+ Object.defineProperty(exports, "ExcelParser", { enumerable: true, get: function () { return excelParser_1.ExcelParser; } });
@@ -0,0 +1,35 @@
1
+ /// <reference types="node" />
2
+ import { ExcelFormat, ExcelType } from "./enums";
3
+ export interface ISpreadSheet<T> {
4
+ name: string;
5
+ items: T[];
6
+ structures: ISheetStructure[];
7
+ }
8
+ export interface ISheetStructure {
9
+ header: {
10
+ displayName: string;
11
+ };
12
+ id: string;
13
+ width: number;
14
+ custom?: IFormatStructure;
15
+ }
16
+ export interface IFormatStructure {
17
+ customFormat?: ExcelFormat;
18
+ type?: ExcelType;
19
+ options?: string[];
20
+ customFormatCallback?: (value: any) => string;
21
+ }
22
+ export interface IExcelParserData {
23
+ filename: string;
24
+ }
25
+ export interface IExcelSheet {
26
+ name: string;
27
+ data: string[][];
28
+ }
29
+ export declare type IWorkerResult = IWorkerSuccessResult | IWorkerFailedResult;
30
+ export declare type IWorkerSuccessResult = {
31
+ file: Buffer;
32
+ };
33
+ export declare type IWorkerFailedResult = {
34
+ error: Error;
35
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "sm-utility",
3
- "version": "2.1.0",
3
+ "version": "2.1.2",
4
4
  "description": "reusable utility codes for sm projects",
5
5
  "main": "index.js",
6
6
  "types": "./index.d.ts",
7
7
  "typings": "./index.d.ts",
8
8
  "scripts": {
9
9
  "clean": "rm -rf dist",
10
- "prebuild":"npm run clean",
10
+ "prebuild": "npm run clean",
11
11
  "build": "tsc",
12
12
  "postbuild": "npm run copy-files",
13
13
  "copy-files": "copyfiles package.json README.md ./dist",
@@ -30,6 +30,7 @@
30
30
  "aws-sdk": "^2.1134.0",
31
31
  "axios": "^0.23.0",
32
32
  "express-winston": "^4.1.0",
33
+ "node-xlsx": "^0.23.0",
33
34
  "redis": "^4.1.0",
34
35
  "uuid": "^8.3.2",
35
36
  "winston": "^3.3.3"
@@ -0,0 +1,4 @@
1
+ export declare function workerfy<T, K = unknown>(workerData: unknown & {
2
+ data: K;
3
+ path: string;
4
+ }): Promise<T>;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.workerfy = void 0;
4
+ const worker_threads_1 = require("worker_threads");
5
+ function workerfy(workerData) {
6
+ return new Promise((resolve, reject) => {
7
+ const worker = new worker_threads_1.Worker(workerData.path, {
8
+ workerData,
9
+ execArgv: ['-r', 'ts-node/register'],
10
+ });
11
+ worker.on('message', (msg) => {
12
+ resolve(msg);
13
+ });
14
+ worker.on('error', (error) => {
15
+ reject(error);
16
+ });
17
+ worker.on('exit', (code) => {
18
+ if (code !== 0)
19
+ reject(new Error(`Worker stopped with exit code ${code}`));
20
+ });
21
+ });
22
+ }
23
+ exports.workerfy = workerfy;