prg-class
Version:
Clases genéricas utilizadas por microservicios Programamos SPA.
337 lines (336 loc) • 12.7 kB
JavaScript
;
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseClass = void 0;
const obj_xls_1 = require("../obj-xls/obj-xls");
const C = require('prg-constant');
const F = require('prg-function'); // Funciones genéricas.
// const expressPino = require('express-pino-logger')({});
// const pino = require('pino')('./logs/info.log');
// const expressPinoFile = require('express-pino-logger')({
// logger: pino,
// });
class BaseClass {
constructor() {
this.useExcelWidth = false; // Usar medidas de Excel para exportar.
this.unitToXls = 1.42857142857143; // Unidades a Excel.
this.xlsToUnit = 0.7; // Excel a Unidades.
this.msPermiso = '';
this.moIdApp = [];
this.moColSql = []; // Arreglo para auditar.
this.moUPRM = { IP: '', P_EMP: '', P_SUC: '', P_SYS: '', P_TKN: '', P_USR: '', UA: '' };
this.msTable = '';
this.msPk = '';
this.msView = '';
this.mbLogme = false;
this.msModuleName = this.constructor.name;
}
fnInitClass(aoReq) {
this.setIpUa(aoReq);
}
fnVoid() {
return new Promise((resolve) => {
return resolve(F.fnReturn(null, null, C.HttpCode.Ok.OK));
});
}
allRight() {
return new Promise((resolve) => {
return resolve(F.fnReturn(null, null, C.HttpCode.Ok.OK));
});
}
getUsr() {
let lsUsr = this.getUPRMValue('P_USR');
if (F.trim(lsUsr) === '') {
lsUsr = '-1';
}
return lsUsr;
}
auditMe(abAudit, asTitle, aoValue) {
if (abAudit) {
this.developerMsg(asTitle, aoValue);
}
}
developerMsg(asTitle, aoValue) {
console.log(asTitle, aoValue);
}
getSys() {
let lsValue = this.getUPRMValue('P_SYS');
if (F.trim(lsValue) === '') {
lsValue = '-1';
}
return F.intval(lsValue);
}
getCompany() {
let lsValue = this.getUPRMValue('P_EMP');
if (F.trim(lsValue) === '') {
lsValue = '-1';
}
return F.intval(lsValue);
}
getCampus() {
let lsValue = this.getUPRMValue('P_SUC');
if (F.trim(lsValue) === '') {
lsValue = '-1';
}
return F.intval(lsValue);
}
getMaq() {
return this.getUPRMValue('IP');
}
init(aoUPRM, aoIdApp, asTable, asPk, asView) {
this.moUPRM = aoUPRM;
this.moIdApp = aoIdApp;
this.msTable = asTable;
this.msPk = asPk;
this.msView = asView;
}
logme(asFunction, aoErr, asSql) {
if (this.mbLogme) {
return;
}
}
readFileSync(asFile_1, aoFs_1) {
return __awaiter(this, arguments, void 0, function* (asFile, aoFs, asEncoding = 'utf8') {
try {
const loData = aoFs.readFileSync(asFile, asEncoding);
return F.fnRetOk(loData);
}
catch (err) {
return F.fnRetErrInt(err);
}
});
}
deleteFileSync(asFile, aoFs) {
return __awaiter(this, void 0, void 0, function* () {
try {
aoFs.unlinkSync(asFile);
return F.fnRetOk('');
}
catch (err) {
return F.fnRetErrInt(err);
}
});
}
// protected async deleteFileSyncDelay(asFile: string, aoFs: any): Promise<IParamRet> {
// try {
// aoFs.unlinkSync(asFile);
// return F.fnRetOk('');
// } catch (err) {
// return F.fnRetErrInt(err);
// }
// }
writeFileSync(asFile, aoFs, aoContent) {
return __awaiter(this, void 0, void 0, function* () {
try {
aoFs.writeFileSync(asFile, aoContent);
return F.fnRetOk('');
}
catch (err) {
return F.fnRetErrInt(err);
}
});
}
getCHF(asField, asCaption, asType = C.tipoCampo.String, asFieldAlt = '') {
const lsFldAlt = asFieldAlt === '' ? asField : asFieldAlt;
return { n: asField, c: asCaption, t: asType, fa: lsFldAlt };
}
checkMod(aoNewData, aoOldData, aoCheck) {
const loMod = [];
const llDec = 2;
aoCheck.forEach((check) => {
let lsOld = '';
let lsNew = '';
if (check.t === C.tipoCampo.String) { // String.
lsOld = F.trim(aoOldData[check.n]);
lsNew = F.trim(aoNewData[check.fa]);
}
if (check.t === C.tipoCampo.Numero) { // Número.
lsOld = F.floatval(aoOldData[check.n]);
lsNew = F.floatval(aoNewData[check.fa]);
lsOld = F.floatval(Number.parseFloat(lsOld).toFixed(llDec));
lsNew = F.floatval(Number.parseFloat(lsNew).toFixed(llDec));
}
if (check.t === C.tipoCampo.Moneda) { // Moneda.
lsOld = F.floatval(aoOldData[check.n]);
lsNew = F.floatval(aoNewData[check.fa]);
lsOld = F.floatval(Number.parseFloat(lsOld).toFixed(llDec));
lsNew = F.floatval(Number.parseFloat(lsNew).toFixed(llDec));
lsOld = F.numberFormat(lsOld, '$ ', llDec);
lsNew = F.numberFormat(lsNew, '$ ', llDec);
}
if (check.t === C.tipoCampo.Porcentaje) { // Porcentaje.
lsOld = F.floatval(aoOldData[check.n]);
lsNew = F.floatval(aoNewData[check.fa]);
lsOld = F.floatval(Number.parseFloat(lsOld).toFixed(llDec));
lsNew = F.floatval(Number.parseFloat(lsNew).toFixed(llDec));
lsOld = F.numberFormat(lsOld, '', llDec, ' %');
lsNew = F.numberFormat(lsNew, '', llDec, ' %');
}
if (check.t === C.tipoCampo.Boolean) { // Boolean.
lsOld = F.intval(aoOldData[check.n]) === 1 ? 'SI' : 'NO';
lsNew = F.intval(aoNewData[check.fa]) === 1 ? 'SI' : 'NO';
}
if (check.t === C.tipoCampo.Fecha) { // Fecha.
lsOld = F.fechaChile(aoOldData[check.n]);
lsNew = F.fechaChile(aoNewData[`_${check.fa}`]);
}
if (lsOld === null || lsOld === undefined) {
lsOld = '';
}
if (lsNew === null || lsNew === undefined) {
lsNew = '';
}
if (lsOld !== lsNew) {
loMod.push({ n: check.n, c: check.c, a: lsOld, d: lsNew });
}
});
return JSON.stringify(loMod);
}
getUPRMValue(asField) {
let lsRet = '';
if (this.moUPRM) {
const loObj = this.moUPRM;
lsRet = loObj[asField];
if (lsRet === undefined || lsRet === null) {
lsRet = '';
}
}
return lsRet;
}
// protected fnFec(asField: string): string {
// const lsTz: string = U.Params.App.Timezone.Database;
// return `(${asField} at time zone '${lsTz}') AT TIME ZONE 'UTC' `;
// }
/**
* Define una columna para exportar datos a Excel y/o mostrar lista de datos a Cliente.
*
* @protected
* @param {string} asFieldName Nombre de campo en base de datos.
* @param {string} asCaption Nombre de encabezado de columna.
* @param {number} [alWidth=100] Ancho de columna,
* @param {string} [asFormat=""] Formato para exportar a Excel.
* @param {string} [asAlign="left"] Alineación de campo al exportar a Excel.
* @param {number} [alType=101] Tipo del campo. Por defecto será texto.
* @param {string} [asFormatCli=""] Formato para cliente.
* @param {string} [asTootip=""] Tooltip de encabezado de columna.
* @param {number} [alMaxWidth=0] Ancho máximo ancho para lista de datos.
* @returns {*}
* @memberof jaxClass
*/
fnRowXls(asFieldName, asCaption, alWidth = 100, asFormat = '', asAlign = 'left', alType = 101, alListOrder = 0) {
if (this.useExcelWidth) { // Convierte ancho de Excel a unidades.
alWidth *= this.unitToXls;
}
const loRet = {
t: alType,
a: F.trim(asAlign),
n: F.trim(asFieldName),
f: F.trim(asFormat),
c: F.trim(asCaption),
w: alWidth,
lo: alListOrder,
};
return loRet;
}
fnMakeXlsParams(aoParams, asTitle, asTag, asSubject) {
// Factor de conversión para unidades de ancho de excel.
// Unidades a Excel: 1,42857142857143.
// Excel a Unidades: 0,7.
const loW = { title: asTitle, tag: asTag, subject: asSubject };
aoParams.wb = loW;
}
fnExportDataToExcel(aoParams) {
return new Promise((resolve, reject) => {
return this.fnExportDatasetXls(aoParams).then((d) => {
if (d.error) {
return reject(F.fnReturn(d.error, null, C.HttpCode.Error.ServerError));
}
else {
return resolve(F.fnReturn(null, d.json, C.HttpCode.Ok.OK));
}
});
});
}
/**
* Exporta lista de datos a Excel.
*/
fnExportDatasetXls(aoParams) {
return new Promise((resolve, reject) => {
const loUt = new obj_xls_1.ObjExcel();
aoParams.u = this.getUPRMValue('P_USR');
return loUt.fnExportDataset(aoParams).then((d) => {
return resolve(F.fnReturn(null, d.json, C.HttpCode.Ok.OK));
});
});
}
genericReturn(aoRet) {
return __awaiter(this, void 0, void 0, function* () {
if (aoRet.error) {
return aoRet;
}
if (aoRet.json.r !== 1) {
return F.fnRetErrInt(aoRet.json.rs[0]);
}
return F.fnRetOk(aoRet.json.rs[0]);
});
}
waitMe(alSec) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((rs, rj) => {
setTimeout(() => {
return rs(this.allRight());
}, alSec * 1000);
});
});
}
setIpUa(aoReq) {
let lsIp = '';
let lsUserAgent = aoReq ? aoReq.headers['user-agent'] : '';
const lsUAO = lsUserAgent; // Guarda copia de useragent.
if (aoReq && aoReq.headers.via) {
lsIp = aoReq.headers['x-forwarded-for']; // Recupera ip de cliente (con proxy).
}
else {
lsIp = aoReq.connection.remoteAddress;
}
if (lsIp === undefined) {
lsIp = aoReq.connection.remoteAddress;
} // Recupera id de cliente (sin proxy).
const lsRIP = aoReq ? aoReq.headers['x-real-ip'] : ''; // IP para el caso de NGINX.
if (lsRIP) {
lsIp = lsRIP;
}
aoReq.IP = lsIp;
if (lsUserAgent !== '' && lsUserAgent !== undefined && lsUserAgent != null) {
let llAux = 0;
for (let i = 0; i < lsUserAgent.length; i++) {
// const lsLet: string = lsUserAgent.substring(i, 1);
const lsLet = lsUserAgent.slice(i, i + 1);
// const lsLet: string = lsUserAgent.substring(i, 1);
// const llAsc: number = lsLet.charCodeAt(0) * i;
const llAsc = lsLet.charCodeAt(0);
const llAscCalc = llAsc * (i + 1);
// llAux += llAsc;
llAux += llAscCalc;
}
// eslint-disable-next-line prefer-template
lsUserAgent = llAux + '';
}
else {
lsUserAgent = '';
}
const loUPRM = { UA: lsUserAgent, UAO: lsUAO, IP: lsIp };
aoReq.UA = lsUserAgent;
aoReq.UAO = lsUAO;
aoReq.UPRM = loUPRM;
}
}
exports.BaseClass = BaseClass;