UNPKG

@ldss95/helpers

Version:

Multiples funciones para problemas comunes como validacion de cedula dominicana, formatear strings telefonicos o moneda, generar pdf a partid de html. Etc...

308 lines (307 loc) 13.4 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.handlebars = exports.pdf = exports.format = exports.duiIsValid = void 0; var fs_1 = __importDefault(require("fs")); var puppeteer_1 = __importDefault(require("puppeteer")); var handlebars_1 = __importDefault(require("handlebars")); exports.handlebars = handlebars_1["default"]; /** * Verifica la validez de cedulda de identidad y electoral doninicana * {@link https://www.youtube.com/watch?v=__Ko7VxoCuU&t=179s Video} * @param dui Numero de cedula *Sin guiones* */ function duiIsValid(dui) { //La cedula es invalida hasta que se demuestre lo conrario var isValid = false; //Si no tiene una longitud de 11 caracteres no es valida if (!dui || dui.length != 11) { return isValid; } //Si tiene algun caracter no numerico no es valida if (dui.replace(/[0-9]/g, '') != '') { return false; } //Suma los digitos individuales de un numero (16 = 1 + 6 = 7) var separateAndSum = function (number) { var numbers = number.toString().split(''); var leftDigit = Number(numbers[0]); var rightDigit = Number(numbers[1]); return leftDigit + rightDigit; }; var digits = dui.split(''); //Quitamos el ultimo digito del array y lo guardamos para validar al final var lastDigit = Number(digits.pop()); var sum = digits.map(function (digit, index) { digit = Number(digit); var multiplier = (index % 2) ? 2 : 1; var result = digit * multiplier; return (result > 9) ? separateAndSum(result) : result; }).reduce(function (total, n) { return total + n; }, 0); var topTen = (Math.floor(sum / 10) + 1) * 10; var validator = topTen - sum; if (lastDigit == validator || (lastDigit === 0 && validator === 10)) { isValid = true; } return isValid; } exports.duiIsValid = duiIsValid; /** * Funcciones para transformar entradas agregando formatos. */ var format = { /** * RNC, Registro Nacional de Contribuyente * @param rnc `string` *sin guiones* * * @example * format.rnc('130800035'); * * @returns `string` RNC con formato `130-80003-5` */ rnc: function (rnc) { return this.custom(rnc, '000-00000-0'); }, /** * Cedula de identidad y electoral dominicana * @param dui numero de cedula *sin guiones* * * @example * format.dui('10225088357'); * * @returns `string` Cedula con formato `102-2508835-7` */ dui: function (dui) { return this.custom(dui, '000-0000000-0'); }, /** * Numero de telefono dominicano * @param phone numero telefonico *sin guiones ni espacios ni parentesis* * * @example * format.phone('8093458812'); * * @returns `string` Numero Telefonico con formato `(809) 345-8812` */ phone: function (phone) { return this.custom(phone, '(000) 000-0000'); }, /** * Formato Moneda * @param cash Monto * @param decimals `0 | 1 | 2` Cantidad de decimales, Por defecto 0 * * @example * format.cash(4623, 2); -> '4,623.00' * format.cash(4623, 1); -> '4,623.0' * format.cash(4623); -> '4,623' * * @returns Monto con format de moneda `9,000.00` */ cash: function (amount, decimals) { if (decimals === void 0) { decimals = 0; } return Intl.NumberFormat('es-DO', { minimumFractionDigits: decimals }).format(amount); }, /** * Formatea cadenas de texto segun ejemplo introducido * @param input texto sin formato * @param example ejemplo de texto formateado * * @example * format.custom('99511469110', '0000-0000-00-0'); */ custom: function (input, example) { /** * Validamos que la longitud del ejemplo (tras remover los caracaters especiales) * sea la misma que la del input */ if (input.length != example.replace(/[^0-0A-Za-z]/g, '').length) { return 'Entrada Invalida'; } var inputArr = input.split(''); //Expresion regular para encontrar caracteres eseciales var isSpecial = new RegExp(/[^0-9A-Za-z]/); //Obtenemos los caracteres especiales y sus posiciones example.split('').forEach(function (char, index) { if (isSpecial.test(char)) inputArr.splice(index, 0, char); }); return inputArr.join(''); } }; exports.format = format; /** * Generador de pdf asincrono, tomando como entrada una plantilla handlebars y los paramstros para la misma */ var pdf = { /** * Genera pdf y lo devuelve en formato stream * @return `fs.ReadStream` * @param templatePath ruta de la platilla handlebars * @param context parametros para la plantilla handlebars * @param options opciones de configuracion para el documento pdf {@link https://www.npmjs.com/package/html-pdf#options Ver Documentacion}. */ toStream: function (templatePath, context, options) { return __awaiter(void 0, void 0, void 0, function () { var template, html, browser, page, pdfBuffer, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 6, , 7]); template = fs_1["default"].readFileSync(templatePath, 'utf8'); html = handlebars_1["default"].compile(template)(context); return [4 /*yield*/, puppeteer_1["default"].launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox'] })]; case 1: browser = _a.sent(); return [4 /*yield*/, browser.newPage()]; case 2: page = _a.sent(); return [4 /*yield*/, page.setContent(html)]; case 3: _a.sent(); return [4 /*yield*/, page.pdf(__assign({ format: 'A4', printBackground: true }, options))]; case 4: pdfBuffer = _a.sent(); return [4 /*yield*/, browser.close()]; case 5: _a.sent(); return [2 /*return*/, fs_1["default"].createReadStream('', { start: 0, end: pdfBuffer.length - 1 })]; case 6: error_1 = _a.sent(); throw error_1; case 7: return [2 /*return*/]; } }); }); }, /** * Genera pdf y lo devuelve en formato buffer * @return `fs.ReadStream` * @param templatePath ruta de la platilla handlebars * @param context parametros para la plantilla handlebars * @param options opciones de configuracion para el documento pdf {@link https://www.npmjs.com/package/html-pdf#options Ver Documentacion}. */ toBuffer: function (templatePath, context, options) { return __awaiter(void 0, void 0, void 0, function () { var template, html, browser, page, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 5, , 6]); template = fs_1["default"].readFileSync(templatePath, 'utf8'); html = handlebars_1["default"].compile(template)(context); return [4 /*yield*/, puppeteer_1["default"].launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox'] })]; case 1: browser = _a.sent(); return [4 /*yield*/, browser.newPage()]; case 2: page = _a.sent(); return [4 /*yield*/, page.setContent(html)]; case 3: _a.sent(); return [4 /*yield*/, page.pdf(__assign({ format: 'A4', printBackground: true }, options))]; case 4: return [2 /*return*/, _a.sent()]; case 5: error_2 = _a.sent(); throw error_2; case 6: return [2 /*return*/]; } }); }); }, /** * Genera pdf y lo guarda en la ruta especificada, devuelve la informacion del archivo generado * @return `FileInfo` * @param {PdfToFileParams} params objeto con los parametros para generar el pdf * @param options opciones de configuracion para el documento pdf {@link https://www.npmjs.com/package/html-pdf#options Ver Documentacion}. */ toFile: function (params) { return __awaiter(void 0, void 0, void 0, function () { var template, html, browser, page, buffer, error_3; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 6, , 7]); template = fs_1["default"].readFileSync(params.templatePath, 'utf8'); html = handlebars_1["default"].compile(template)(params.context); return [4 /*yield*/, puppeteer_1["default"].launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox'] })]; case 1: browser = _a.sent(); return [4 /*yield*/, browser.newPage()]; case 2: page = _a.sent(); return [4 /*yield*/, page.setContent(html)]; case 3: _a.sent(); return [4 /*yield*/, page.pdf(__assign({ format: 'A4', printBackground: true }, params.options))]; case 4: buffer = _a.sent(); return [4 /*yield*/, browser.close()]; case 5: _a.sent(); fs_1["default"].writeFileSync(params.outDir + params.filename, buffer); return [3 /*break*/, 7]; case 6: error_3 = _a.sent(); throw error_3; case 7: return [2 /*return*/]; } }); }); } }; exports.pdf = pdf;