Skip to content
Snippets Groups Projects
Commit 06630386 authored by Agustin's avatar Agustin
Browse files

Merge branch 'feature/Calculos' into origin/develop

parents 35ce97e6 170861a7
No related branches found
No related tags found
No related merge requests found
Pipeline #15597 passed
Showing
with 865 additions and 234 deletions
import {
Handler, Request, Response, Router,
} from 'express';
import AgeGroupJSON from '../DTOs/AgeGroupJSON';
import CalculatorService from '../Services/CalculatorService';
import CalculatorResponse from '../DTOs/CalculatorResponseDTO';
import logger from '../Logger/logger';
const router = Router();
const getREP: Handler = async (req: Request, res: Response) => {
const groups: AgeGroupJSON[] = req.body;
try {
const EnergyReq: CalculatorResponse = CalculatorService.calculateEnergeticRequirement(groups);
return res.status(200).send(EnergyReq);
} catch (error) {
const e = error as Error;
logger.info(e.message);
return res.status(400).json({ error: e.message });
}
};
router.post('/', getREP);
export default router;
import {
Handler, Request, Response, Router,
} from 'express';
import ParameterType from '../Enum/ParameterType';
const router = Router();
const getParametersOfType: Handler = async (req: Request, res: Response) => {
res.send();
};
router.post('/', getParametersOfType);
export default router;
import { import {
Handler, Request, Response, Router, Handler, Request, Response, Router,
} from 'express'; } from 'express';
import { SheetParserResponse } from '../Models/SheetParserResponse'; import { SheetParserResponse } from '../Models/SheetParserResponse';
import SheetService from '../Services/SheetService'; import SheetService from '../Services/SheetService';
import logger from '../Logger/logger'; import logger from '../Logger/logger';
const router = Router(); const router = Router();
const parseSheet: Handler = async (req: Request, res: Response) => { const parseSheet: Handler = async (req: Request, res: Response) => {
const sheet: Buffer = req.body; const sheet: Buffer = req.body;
try { try {
const parsedSheet: SheetParserResponse = SheetService.parseSheetService(sheet); const parsedSheet: SheetParserResponse = SheetService.parseSheetService(sheet);
return res.status(200).send(parsedSheet); return res.status(200).send(parsedSheet);
} catch (error) { } catch (error) {
const e = error as Error; const e = error as Error;
logger.info(e.message); logger.info(e.message);
return res.status(400).json({ error: e.message }); return res.status(400).json({ error: e.message });
} }
}; };
router.post('/', parseSheet); router.post('/', parseSheet);
export default router; export default router;
import AgeBracket from '../Enum/AgeBracket';
import Sex from '../Enum/Sex';
type AgeGroup = {
edad: AgeBracket;
sexo: Sex;
pesoMediano: number;
cantidad: number;
};
export default AgeGroup;
type AgeGroupJSON = {
edad: string;
sexo: string;
pesoMediano: string;
cantidad: string;
};
export default AgeGroupJSON;
import EnergeticRequirement from './EnergeticRequirementDTO';
import GroupEnergeticRequirement from './GroupEnergeticRequirementDTO';
type CalculatorResponse = {
requerimientosPorGrupo: GroupEnergeticRequirement[];
requerimientoTotal: EnergeticRequirement;
};
export default CalculatorResponse;
type EnergeticRequirement = {
requerimientoEnergeticoPerCapita: number;
requerimientoEnergeticoTotal: number;
poblacionTotal: number;
};
export default EnergeticRequirement;
import AgeGroupJSON from './AgeGroupJSON';
type GroupEnergeticRequirement = {
grupoEtario: AgeGroupJSON;
requerimientoEnergeticoPerCapita: number;
requerimientoEnergeticoTotal: number;
};
export default GroupEnergeticRequirement;
enum AgeBracket {
m0 = '0 meses',
m1 = '1 mes',
m2 = '2 meses',
m3 = '3 meses',
m4 = '4 meses',
m5 = '5 meses',
m6 = '6 meses',
m7 = '7 meses',
m8 = '8 meses',
m9 = '9 meses',
m10 = '10 meses',
m11 = '11 meses',
a1 = '1 año',
a2 = '2 años',
a3 = '3 años',
a4 = '4 años',
a5 = '5 años',
a6 = '6 años',
a7 = '7 años',
a8 = '8 años',
a9 = '9 años',
a10 = '10 años',
a11 = '11 años',
a12 = '12 años',
a13 = '13 años',
a14 = '14 años',
a15 = '15 años',
a16 = '16 años',
a17 = '17 años',
a18_29 = '18-29 años',
a30_59 = '30-59 años',
a60 = '60+ años',
}
export default AgeBracket;
enum ParameterType {
NAF = 'NAF',
PesoPorDefecto = 'Peso por defecto',
EmbarazoYLactancia = 'Embarazo y lactancia',
ConstanteDeEcuacion = 'Constante de ecuacion'
}
export default ParameterType;
enum Sex {
Masculino = 'Masculino',
Femenino = 'Femenino',
}
export default Sex;
import { import {
createLogger, format, transports, Logger, createLogger, format, transports, Logger,
} from 'winston'; } from 'winston';
const { const {
combine, timestamp, combine, timestamp,
} = format; } = format;
const logger: Logger = createLogger({ const logger: Logger = createLogger({
level: 'info', level: 'info',
format: combine( format: combine(
timestamp(), timestamp(),
format.errors({ stack: true }), format.errors({ stack: true }),
format.json(), format.json(),
), ),
transports: [ transports: [
new transports.File({ new transports.File({
level: 'error', level: 'error',
filename: 'logs/error-logs', filename: 'logs/error-logs',
maxsize: 104857600, // 100Mb maxsize: 104857600, // 100Mb
maxFiles: 3, maxFiles: 3,
}), }),
new transports.File({ new transports.File({
level: 'info', level: 'info',
filename: 'logs/info-logs', filename: 'logs/info-logs',
maxsize: 104857600, // 100Mb maxsize: 104857600, // 100Mb
maxFiles: 3, maxFiles: 3,
}), }),
], ],
}); });
export default logger; export default logger;
class Parameter {
name: string;
value: number;
constructor(name: string, value: number) {
this.name = name;
this.value = value;
}
}
export default Parameter;
type SheetParserResponse = { type SheetParserResponse = {
hombresMenores: Menores[] | null; hombresMenores: Menores[] | null;
mujeresMenores: Menores[] | null; mujeresMenores: Menores[] | null;
hombres: Mayores[] | null; hombres: Mayores[] | null;
mujeres: Mayores[] | null; mujeres: Mayores[] | null;
} | null; } | null;
type Menores = { type Menores = {
edad: number; edad: number;
peso: number; peso: number;
} | null; } | null;
type Mayores = { type Mayores = {
edad: number; edad: number;
peso?: number; peso?: number;
talla?: number; talla?: number;
} | null; } | null;
type MenoresSheet = { type MenoresSheet = {
'Edad (meses)': number; 'Edad (meses)': number;
'Peso (Kg)': number; 'Peso (Kg)': number;
}; };
type MayoresSheet = { type MayoresSheet = {
'Edad (años)': number; 'Edad (años)': number;
'Peso (Kg)': number; 'Peso (Kg)': number;
'Talla (cm)': number; 'Talla (cm)': number;
}; };
export type { export type {
SheetParserResponse, Menores, Mayores, MenoresSheet, MayoresSheet, SheetParserResponse, Menores, Mayores, MenoresSheet, MayoresSheet,
}; };
import ERCalculator from './ERCalculator';
import ParameterService from './ParameterService';
import ParserService from './ParserService';
import AgeGroup from '../DTOs/AgeGroupDTO';
import CalculatorResponse from '../DTOs/CalculatorResponseDTO';
import AgeGroupJSON from '../DTOs/AgeGroupJSON';
const calculateEnergeticRequirement = (data: AgeGroupJSON[]): CalculatorResponse => {
const parametros = new Map<number[], AgeGroup>();
const ageGroups = ParserService.parseGroups(data);
ageGroups.forEach((group: AgeGroup) => {
parametros.set(ParameterService.getEquationValues(group.edad, group.sexo), group);
});
const res: CalculatorResponse = ERCalculator.calculateER(parametros);
return res;
};
export default { calculateEnergeticRequirement };
import AgeGroup from '../DTOs/AgeGroupDTO';
import EnergeticRequirement from '../DTOs/EnergeticRequirementDTO';
import CalculatorResponse from '../DTOs/CalculatorResponseDTO';
import GroupEnergeticRequirement from '../DTOs/GroupEnergeticRequirementDTO';
import ParserService from './ParserService';
import AgeBracket from '../Enum/AgeBracket';
const calculateLessThanAYear = (group: AgeGroup, params: number[]): GroupEnergeticRequirement => {
const requirement = params[0] + (params[1] * group.pesoMediano) + params[2];
const groupRequirement: GroupEnergeticRequirement = {
grupoEtario: ParserService.unparseGroup(group),
requerimientoEnergeticoPerCapita: requirement,
requerimientoEnergeticoTotal: requirement * group.cantidad,
};
return groupRequirement;
};
const calculateOneToFiveYears = (group: AgeGroup, params: number[]): GroupEnergeticRequirement => {
const requirement = params[0]
+ (params[1] * group.pesoMediano)
+ (params[2] * (group.pesoMediano ** 2))
+ params[3];
const groupRequirement: GroupEnergeticRequirement = {
grupoEtario: ParserService.unparseGroup(group),
requerimientoEnergeticoPerCapita: requirement,
requerimientoEnergeticoTotal: requirement * group.cantidad,
};
return groupRequirement;
};
const calculateER = (groupParameters: Map<number[], AgeGroup>): CalculatorResponse => {
let totalOfPeople = 0;
let totalRequirement = 0;
const requirements: GroupEnergeticRequirement[] = [];
groupParameters.forEach((group: AgeGroup, params: number[]) => {
totalOfPeople += group.cantidad;
let groupRequirement: GroupEnergeticRequirement;
switch (group.edad) {
case AgeBracket.m0:
case AgeBracket.m1:
case AgeBracket.m2:
case AgeBracket.m3:
case AgeBracket.m4:
case AgeBracket.m5:
case AgeBracket.m6:
case AgeBracket.m7:
case AgeBracket.m8:
case AgeBracket.m9:
case AgeBracket.m10:
case AgeBracket.m11: {
groupRequirement = calculateLessThanAYear(group, params);
break;
}
case AgeBracket.a1:
case AgeBracket.a2:
case AgeBracket.a3:
case AgeBracket.a4:
case AgeBracket.a5: {
groupRequirement = calculateOneToFiveYears(group, params);
break;
}
default: {
throw new Error('Parsing error, attribute edad does not respect format');
}
}
totalRequirement += groupRequirement.requerimientoEnergeticoTotal;
requirements.push(groupRequirement);
});
const totalER: EnergeticRequirement = {
requerimientoEnergeticoPerCapita: totalRequirement / totalOfPeople,
requerimientoEnergeticoTotal: totalRequirement,
poblacionTotal: totalOfPeople,
};
const result: CalculatorResponse = {
requerimientosPorGrupo: requirements,
requerimientoTotal: totalER,
};
return result;
};
export default { calculateER };
import AgeBracket from '../Enum/AgeBracket';
import ParameterType from '../Enum/ParameterType';
import Sex from '../Enum/Sex';
// import Parameter from '../Models/Parameter';
const getEquationValues = (ageBracket: AgeBracket, sex: Sex): number[] => {
let res: number[] = [];
switch (ageBracket) {
case (AgeBracket.m0): {
if (sex === Sex.Masculino) {
// -152 + (92.8*MP) + 211
res = [-152, 92.8, 211];
} else if (sex === Sex.Femenino) {
// -152 + (92.8*MP) + 178
res = [-152, 92.8, 178];
}
break;
}
case (AgeBracket.m1): {
if (sex === Sex.Masculino) {
// -152 + (92.8*MP) + 183
res = [-152, 92.8, 183];
} else if (sex === Sex.Femenino) {
// -152 + (92.8*MP) + 161
res = [-152, 92.8, 161];
}
break;
}
case (AgeBracket.m2): {
if (sex === Sex.Masculino) {
// -152 + (92.8*MP) + 139
res = [-152, 92.8, 139];
} else if (sex === Sex.Femenino) {
// -152 + (92.8*MP) + 134
res = [-152, 92.8, 134];
}
break;
}
case (AgeBracket.m3): {
if (sex === Sex.Masculino) {
// -152 + (92.8*MP) + 53
res = [-152, 92.8, 53];
} else if (sex === Sex.Femenino) {
// -152 + (92.8*MP) + 68
res = [-152, 92.8, 68];
}
break;
}
case (AgeBracket.m4): {
if (sex === Sex.Masculino) {
// -152 + (92.8*MP) + 46
res = [-152, 92.8, 46];
} else if (sex === Sex.Femenino) {
// -152 + (92.8*MP) + 57
res = [-152, 92.8, 57];
}
break;
}
case (AgeBracket.m5): {
if (sex === Sex.Masculino) {
// -152 + (92.8*MP) + 36
res = [-152, 92.8, 36];
} else if (sex === Sex.Femenino) {
// -152 + (92.8*MP) + 47
res = [-152, 92.8, 47];
}
break;
}
case (AgeBracket.m6): {
if (sex === Sex.Masculino) {
// -99.4 + (88.6*MP) + 17
res = [-99.4, 88.6, 17];
} else if (sex === Sex.Femenino) {
// -99.4 + (88.6*MP) + 20
res = [-99.4, 88.6, 20];
}
break;
}
case (AgeBracket.m7): {
if (sex === Sex.Masculino) {
// -99.4 + (88.6*MP) + 16
res = [-99.4, 88.6, 16];
} else if (sex === Sex.Femenino) {
// -99.4 + (88.6*MP) + 17
res = [-99.4, 88.6, 17];
}
break;
}
case (AgeBracket.m8): {
if (sex === Sex.Masculino) {
// -99.4 + (88.6*MP) + 14
res = [-99.4, 88.6, 14];
} else if (sex === Sex.Femenino) {
// -99.4 + (88.6*MP) + 15
res = [-99.4, 88.6, 15];
}
break;
}
case (AgeBracket.m9): {
if (sex === Sex.Masculino) {
// -99.4 + (88.6*MP) + 21
res = [-99.4, 88.6, 21];
} else if (sex === Sex.Femenino) {
// -99.4 + (88.6*MP) + 18
res = [-99.4, 88.6, 18];
}
break;
}
case (AgeBracket.m10): {
if (sex === Sex.Masculino) {
// -99.4 + (88.6*MP) + 21
res = [-99.4, 88.6, 21];
} else if (sex === Sex.Femenino) {
// -99.4 + (88.6*MP) + 15
res = [-99.4, 88.6, 15];
}
break;
}
case (AgeBracket.m11): {
if (sex === Sex.Masculino) {
// -99.4 + (88.6*MP) + 22
res = [-99.4, 88.6, 22];
} else if (sex === Sex.Femenino) {
// -99.4 + (88.6*MP) + 14
res = [-99.4, 88.6, 14];
}
break;
}
case (AgeBracket.a1): {
if (sex === Sex.Masculino) {
// 310.2 + (63.3*MP) - 0.263*MP^2 + 13
res = [310.2, 63.3, -0.263, 13];
} else if (sex === Sex.Femenino) {
// 263.4 + (65.3*MP) - 0.454*MP^2 + 13
res = [263.4, 65.3, -0.454, 13];
}
break;
}
case (AgeBracket.a2): {
if (sex === Sex.Masculino) {
// 310.2 + (63.3*MP) - 0.263*MP^2 + 12
res = [310.2, 63.3, -0.263, 12];
} else if (sex === Sex.Femenino) {
// 263.4 + (65.3*MP) - 0.454*MP^2 + 13
res = [263.4, 65.3, -0.454, 13];
}
break;
}
case (AgeBracket.a3): {
if (sex === Sex.Masculino) {
// 310.2 + (63.3*MP) - 0.263*MP^2 + 12
res = [310.2, 63.3, -0.263, 12];
} else if (sex === Sex.Femenino) {
// 263.4 + (65.3*MP) - 0.454*MP^2 + 11
res = [263.4, 65.3, -0.454, 11];
}
break;
}
case (AgeBracket.a4): {
if (sex === Sex.Masculino) {
// 310.2 + (63.3*MP) - 0.263*MP^2 + 11
res = [310.2, 63.3, -0.263, 11];
} else if (sex === Sex.Femenino) {
// 263.4 + (65.3*MP) - 0.454*MP^2 + 10
res = [263.4, 65.3, -0.454, 10];
}
break;
}
case (AgeBracket.a5): {
if (sex === Sex.Masculino) {
// 310.2 + (63.3*MP) - 0.263*MP^2 + 11
res = [310.2, 63.3, -0.263, 11];
} else if (sex === Sex.Femenino) {
// 263.4 + (65.3*MP) - 0.454*MP^2 + 10
res = [263.4, 65.3, -0.454, 10];
}
break;
}
default: {
throw new Error('Parsing error, attribute edad does not respect format');
}
}
return res;
};
export default { getEquationValues };
import AgeGroup from '../DTOs/AgeGroupDTO';
import AgeGroupJSON from '../DTOs/AgeGroupJSON';
import AgeBracket from '../Enum/AgeBracket';
import Sex from '../Enum/Sex';
// const parseSex = (sexo: string): Sex => {
// let sex: Sex = sexo;
// switch (sexo) {
// case 'Masculino': {
// sex = Sex.Masculino;
// break;
// }
// case 'Femenino': {
// sex = Sex.Femenino;
// break;
// }
// default: {
// throw new Error('Parsing error, attribute sexo does not respect format');
// }
// }
// return sex;
// };
//
// const parseAge = (edad: string): AgeBracket => {
// let age: AgeBracket;
// switch (edad) {
// case '0 meses': {
// age = AgeBracket.m0;
// break;
// }
// case '1 mes': {
// age = AgeBracket.m1;
// break;
// }
// case '2 meses': {
// age = AgeBracket.m2;
// break;
// }
// case '3 meses': {
// age = AgeBracket.m3;
// break;
// }
// case '4 meses': {
// age = AgeBracket.m4;
// break;
// }
// case '5 meses': {
// age = AgeBracket.m5;
// break;
// }
// case '6 meses': {
// age = AgeBracket.m6;
// break;
// }
// case '7 meses': {
// age = AgeBracket.m7;
// break;
// }
// case '8 meses': {
// age = AgeBracket.m8;
// break;
// }
// case '9 meses': {
// age = AgeBracket.m9;
// break;
// }
// case '10 meses': {
// age = AgeBracket.m10;
// break;
// }
// case '11 meses': {
// age = AgeBracket.m11;
// break;
// }
// case '1 año': {
// age = AgeBracket.a1;
// break;
// }
// case '2 años': {
// age = AgeBracket.a2;
// break;
// }
// case '3 años': {
// age = AgeBracket.a3;
// break;
// }
// case '4 años': {
// age = AgeBracket.a4;
// break;
// }
// case '5 años': {
// age = AgeBracket.a5;
// break;
// }
// case '6 años': {
// age = AgeBracket.a6;
// break;
// }
// case '7 años': {
// age = AgeBracket.a7;
// break;
// }
// case '8 años': {
// age = AgeBracket.a8;
// break;
// }
// case '9 años': {
// age = AgeBracket.a9;
// break;
// }
// case '10 años': {
// age = AgeBracket.a10;
// break;
// }
// case '11 años': {
// age = AgeBracket.a11;
// break;
// }
// case '12 años': {
// age = AgeBracket.a12;
// break;
// }
// case '13 años': {
// age = AgeBracket.a13;
// break;
// }
// case '14 años': {
// age = AgeBracket.a14;
// break;
// }
// case '15 años': {
// age = AgeBracket.a15;
// break;
// }
// case '16 años': {
// age = AgeBracket.a16;
// break;
// }
// case '17 años': {
// age = AgeBracket.a17;
// break;
// }
// case '18-29 años': {
// age = AgeBracket.a18_29;
// break;
// }
// case '30-59 años': {
// age = AgeBracket.a30_59;
// break;
// }
// case '60+ años': {
// age = AgeBracket.a60;
// break;
// }
// default: {
// throw new Error('Parsing error, attribute edad does not respect format');
// }
// }
// return age;
// };
const parseGroups = (groups: AgeGroupJSON[]): AgeGroup[] => {
const retGroups: AgeGroup[] = [];
groups.forEach((obj: AgeGroupJSON) => {
// if (typeof (obj.pesoMediano) !== 'number' || typeof (obj.cantidad) !== 'number') {
// console.log('Estas haciendo cualquiera flaco');
// throw new Error('Parsing error, attributes do not respect format');
// }
const group: AgeGroup = {
edad: obj.edad as AgeBracket,
sexo: obj.sexo as Sex,
pesoMediano: parseFloat(obj.pesoMediano),
cantidad: parseFloat(obj.cantidad),
};
retGroups.push(group);
});
return retGroups;
};
const unparseGroup = (group: AgeGroup): AgeGroupJSON => {
const retGroup: AgeGroupJSON = {
edad: group.edad as string,
sexo: group.sexo as string,
pesoMediano: String(group.pesoMediano),
cantidad: String(group.cantidad),
};
return retGroup;
};
export default { parseGroups, unparseGroup };
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import { SheetNames } from '../Config/Constants'; import { SheetNames } from '../Config/Constants';
import { import {
SheetParserResponse, Menores, Mayores, MenoresSheet, MayoresSheet, SheetParserResponse, Menores, Mayores, MenoresSheet, MayoresSheet,
} from '../Models/SheetParserResponse'; } from '../Models/SheetParserResponse';
/* PRIVATE FUNCTIONS */ /* PRIVATE FUNCTIONS */
// const ec = (r: number, c: number): string => XLSX.utils.encode_cell({ r, c }); // const ec = (r: number, c: number): string => XLSX.utils.encode_cell({ r, c });
// const deleteRow = (ws: XLSX.WorkSheet, rowIndex: number): XLSX.WorkSheet => { // const deleteRow = (ws: XLSX.WorkSheet, rowIndex: number): XLSX.WorkSheet => {
// const work = ws; // const work = ws;
// if (work['!ref'] === undefined) throw new Error('An error has ocurred in deleteRow'); // if (work['!ref'] === undefined) throw new Error('An error has ocurred in deleteRow');
// const variable = XLSX.utils.decode_range(work['!ref']); // const variable = XLSX.utils.decode_range(work['!ref']);
// for (let R = rowIndex; R < variable.e.r; R += 1) { // for (let R = rowIndex; R < variable.e.r; R += 1) {
// for (let C = variable.s.c; C <= variable.e.c; C += 1) { // for (let C = variable.s.c; C <= variable.e.c; C += 1) {
// work[ec(R, C)] = work[ec(R + 1, C)]; // work[ec(R, C)] = work[ec(R + 1, C)];
// } // }
// } // }
// variable.e.r -= 1; // variable.e.r -= 1;
// work['!ref'] = XLSX.utils.encode_range(variable.s, variable.e); // work['!ref'] = XLSX.utils.encode_range(variable.s, variable.e);
// return work; // return work;
// }; // };
const parseAdults = (worksheet: XLSX.WorkSheet): Mayores[] => { const parseAdults = (worksheet: XLSX.WorkSheet): Mayores[] => {
const res: Mayores[] = []; const res: Mayores[] = [];
const ref = worksheet['!ref']; const ref = worksheet['!ref'];
if (ref === undefined) throw new Error('An error ocurred'); if (ref === undefined) throw new Error('An error ocurred');
const range = XLSX.utils.decode_range(ref); const range = XLSX.utils.decode_range(ref);
range.s.c = 0; range.s.c = 0;
range.e.c = 2; range.e.c = 2;
const newRange = XLSX.utils.encode_range(range); const newRange = XLSX.utils.encode_range(range);
const aux = XLSX.utils.sheet_to_json(worksheet, { range: newRange }) as unknown as MayoresSheet[]; const aux = XLSX.utils.sheet_to_json(worksheet, { range: newRange }) as unknown as MayoresSheet[];
aux.forEach((element: MayoresSheet) => { aux.forEach((element: MayoresSheet) => {
res.push( res.push(
{ {
edad: element['Edad (años)'], edad: element['Edad (años)'],
peso: element['Peso (Kg)'], peso: element['Peso (Kg)'],
talla: element['Talla (cm)'], talla: element['Talla (cm)'],
}, },
); );
}); });
return res; return res;
}; };
const parseBabies = (worksheet: XLSX.WorkSheet): Menores[] => { const parseBabies = (worksheet: XLSX.WorkSheet): Menores[] => {
const res: Menores[] = []; const res: Menores[] = [];
const aux = XLSX.utils.sheet_to_json(worksheet) as unknown as MenoresSheet[]; const aux = XLSX.utils.sheet_to_json(worksheet) as unknown as MenoresSheet[];
aux.forEach((element: MenoresSheet) => { aux.forEach((element: MenoresSheet) => {
res.push( res.push(
{ {
edad: element['Edad (meses)'], edad: element['Edad (meses)'],
peso: element['Peso (Kg)'], peso: element['Peso (Kg)'],
}, },
); );
}); });
return res; return res;
}; };
/* EXPORT FUNCTIONS */ /* EXPORT FUNCTIONS */
const parseSheetService = (data: Buffer): SheetParserResponse => { const parseSheetService = (data: Buffer): SheetParserResponse => {
const workbook: XLSX.WorkBook = XLSX.read(data); const workbook: XLSX.WorkBook = XLSX.read(data);
let parsed: SheetParserResponse = null; let parsed: SheetParserResponse = null;
let hombresMenores: Menores[] = []; let hombresMenores: Menores[] = [];
let hombres: Mayores[] = []; let hombres: Mayores[] = [];
let mujeresMenores: Menores[] = []; let mujeresMenores: Menores[] = [];
let mujeres: Mayores[] = []; let mujeres: Mayores[] = [];
const sheetNames: string[] = workbook.SheetNames; const sheetNames: string[] = workbook.SheetNames;
// Check there are 4 sheets, no more, no less // Check there are 4 sheets, no more, no less
if (sheetNames.length !== 4) { if (sheetNames.length !== 4) {
throw new Error('File does not respect scheme, there are more or less than 4 sheets'); throw new Error('File does not respect scheme, there are more or less than 4 sheets');
} }
sheetNames.forEach((name) => { sheetNames.forEach((name) => {
const worksheet: XLSX.WorkSheet = workbook.Sheets[name]; const worksheet: XLSX.WorkSheet = workbook.Sheets[name];
switch (name) { switch (name) {
case SheetNames.HOMBRES_MENORES: case SheetNames.HOMBRES_MENORES:
hombresMenores = parseBabies(worksheet); hombresMenores = parseBabies(worksheet);
break; break;
case SheetNames.HOMBRES: case SheetNames.HOMBRES:
hombres = parseAdults(worksheet); hombres = parseAdults(worksheet);
break; break;
case SheetNames.MUJERES_MENORES: case SheetNames.MUJERES_MENORES:
mujeresMenores = parseBabies(worksheet); mujeresMenores = parseBabies(worksheet);
break; break;
case SheetNames.MUJERES: case SheetNames.MUJERES:
mujeres = parseAdults(worksheet); mujeres = parseAdults(worksheet);
break; break;
default: default:
throw new Error(`Sheet name ${name} is not part of the scheme `); throw new Error(`Sheet name ${name} is not part of the scheme `);
} }
}); });
parsed = { parsed = {
hombresMenores, hombresMenores,
hombres, hombres,
mujeresMenores, mujeresMenores,
mujeres, mujeres,
}; };
return parsed; return parsed;
// TODO: depends on sheet layout what to do // TODO: depends on sheet layout what to do
}; };
export default { export default {
parseSheetService, parseSheetService,
}; };
/* eslint-disable no-console */ /* eslint-disable no-console */
import express, { Application } from 'express'; import express, { Application } from 'express';
import 'dotenv/config'; import 'dotenv/config';
import cors from 'cors'; import cors from 'cors';
import swaggerUi from 'swagger-ui-express'; import swaggerUi from 'swagger-ui-express';
import helmet from 'helmet'; import helmet from 'helmet';
import YAML from 'yamljs'; import YAML from 'yamljs';
import Routes from './routes'; import Routes from './routes';
import logger from './Logger/logger'; import logger from './Logger/logger';
const app: Application = express(); const app: Application = express();
const PORT = process.env.PORT || 8000; const PORT = process.env.PORT || 8000;
app.use(helmet.hidePoweredBy()); app.use(helmet.hidePoweredBy());
// swagger init // swagger init
const swaggerDocument = YAML.load('./swagger.yaml'); const swaggerDocument = YAML.load('./swagger.yaml');
// middlewares // middlewares
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use(express.json({ app.use(express.json({
limit: '50mb', limit: '50mb',
})); }));
app.use(express.urlencoded({ extended: false })); app.use(express.urlencoded({ extended: false }));
app.use(cors({ app.use(cors({
origin: '*', origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false, preflightContinue: false,
optionsSuccessStatus: 204, optionsSuccessStatus: 204,
})); }));
app.use(express.raw({ app.use(express.raw({
limit: '50mb', limit: '50mb',
})); }));
app.use(Routes); app.use(Routes);
app.listen(PORT, (): void => { app.listen(PORT, (): void => {
console.log(`REPP Backend running here 👉 https://localhost:${PORT}`); console.log(`REPP Backend running here 👉 https://localhost:${PORT}`);
logger.info('Server initiated'); logger.info('Server initiated');
}); });
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment