import { createLogger, format, transports } from "winston"; import moment from "moment-timezone"; import nodemailer from "nodemailer"; import { Types } from "./typing"; export namespace Utils { /** * @param dni * Dado un RUN sin el DV, obtiene el dígito verificador */ export const getDV = (dni: number) => { const adni = dni; let M=0,S=1; for(;dni;dni=Math.floor(dni/10)) { S = (S+dni%10*(9-M++%6))%11; } const dv = S ? `${S-1}` : 'K'; return `${adni.toString().trim()}-${dv.toString().trim()}` } export const logger = createLogger({ level: 'info', format: format.combine( format(info => { info.level = info.level.toUpperCase(); return info; })(), format.colorize(), format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), format.printf(info => { return `${info.timestamp} - ${info.level}: ${info.message}`; }) ), transports: [new transports.Console()] }); export const logError = (err: any, place: string) => { return logger.error(`at ${place}`), console.log(err) } export const isJSONString = (cadena: string) => { cadena = typeof cadena !== "string" ? JSON.stringify(cadena) : cadena; try { cadena = JSON.parse(cadena); } catch (e) { return false; } if (typeof cadena === "object" && cadena !== null) { return true; } return false; } export const stringToAccesgroup = (str: string) => { if (!str) return undefined; return str.toUpperCase() .replace(/[.,\/#!$%\^&\*;:{}=\-_`~() ]/g, '') .normalize("NFD") .replace(/[\u0300-\u036f]/g, ""); } export const momento = () => { return moment().tz("America/Santiago") } export const sendMailTo = async (data: Types.DataMail, auth: Types.AuthMail) => { try { const host = `${auth.host}`; const email = `${auth.user}`; const pass = `${auth.passwd}`; const port = Number(auth.port); const mailTransport = nodemailer.createTransport({ host, port, auth: { user: email, pass }, tls: { rejectUnauthorized: false } }); await mailTransport.sendMail({ from: email, to: data.mail, replyTo: email, subject: `${data.subject}`, html: data.body }); } catch (error) { logger.error(JSON.stringify(error)); } } export const getMonthsDST = (timezone: string) => { switch (timezone) { case 'America/Santiago': return { monthIniDST: 9, monthFinDST: 4 }; default: return { monthIniDST: 0, monthFinDST: 0 }; } } /** * * @param begFin * @returns * Determina una fecha según un numeral. Por ej, el primer sabado de abril: begFin: 1-6-4 */ export const getNumeralDayOfMonth = (begFin: { numeral: number, day: number, month: number, year: number}) => { const { month, year, day, numeral } = begFin; if ( month > 12 || month < 1 ) return 'input error'; if ( day > 7 || day < 1 ) return 'input error'; if ( numeral > 5 || numeral < 1) return 'input error'; let dateFounded = []; let dateInit = new Date(`${year}-${month}-01`) while (month === dateInit.getMonth()+1) { if (dateInit.getDay() === day) { dateFounded.push(dateInit); } dateInit = new Date(new Date(dateInit).setDate(dateInit.getDate() + 1)); } return dateFounded[numeral-1]; } export const toCapitalCase = (str: string) => { return str.toLowerCase().replace(/\b[a-z]/g, (x) => x.toUpperCase()) } }