Cambio a registro de grupos
This commit is contained in:
parent
8f3ce95914
commit
11b00e9a16
@ -126,6 +126,33 @@ function sendTicket(header, values) {
|
||||
],*/
|
||||
};
|
||||
|
||||
console.log('sendTicket >>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<', header, body)
|
||||
|
||||
return send(header, body);
|
||||
}
|
||||
|
||||
function sendTicketOnline(header, values) {
|
||||
//console.log('>>>>>>>>>>>>>>>>>>><<VALUES ONLINE>>>', values);
|
||||
const body = {
|
||||
TemplateID: 3717629,
|
||||
TemplateLanguage: true,
|
||||
TemplateErrorDeliver: true,
|
||||
TemplateErrorReporting: {
|
||||
Email: "info@rodax-software.com",
|
||||
Name: "Air traffic control",
|
||||
},
|
||||
Variables: {
|
||||
tipoEntrada: values.tipoEntrada,
|
||||
descriptionEntrada: values.descriptionEntrada,
|
||||
eventName: values.eventName,
|
||||
dateEvent: values.dateEvent,
|
||||
dateInscription: values.dateInscription,
|
||||
color: values.color ? values.color : "gray",
|
||||
nameInscription: header.name,
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
console.log(body.Variables);
|
||||
|
||||
return send(header, body);
|
||||
@ -170,7 +197,7 @@ function sendReservationCode(header, values) {
|
||||
reservationDescription: values.reservationDescription ? values.reservationDescription : "-",
|
||||
},
|
||||
};
|
||||
|
||||
console.log('sendReservationCode >>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<', header, body)
|
||||
return send(header, body);
|
||||
}
|
||||
|
||||
@ -223,4 +250,5 @@ module.exports = {
|
||||
sendListaEspera,
|
||||
sendCancelacion,
|
||||
sendReservationCode,
|
||||
sendTicketOnline,
|
||||
};
|
||||
|
||||
@ -408,12 +408,11 @@ function verify(req, res, next) {
|
||||
}
|
||||
|
||||
async function getOrCreateUser(req, res, next) {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> getOrCreateUser");
|
||||
const params = controllerHelper.extractParamsFromRequest(req, res, {});
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription)
|
||||
return controllerHelper.handleResultResponse(
|
||||
"Error getOrCreateUser, prepareInscription, recuperateEvent, recuperateReservationByCode requerida",
|
||||
"Error getOrCreateUser, prepareDataInscription, recuperateReservationByCode requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
@ -460,16 +459,15 @@ async function getOrCreateUser(req, res, next) {
|
||||
} catch (error) {
|
||||
return controllerHelper.handleErrorResponse(
|
||||
MODULE_NAME,
|
||||
"createInscription",
|
||||
"getOrCreateUser",
|
||||
error,
|
||||
res
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",
|
||||
dataUser.userResult.user.Entity
|
||||
);
|
||||
dataUser.id = dataUser.userResult.user.id; //phone y demas también deberían refrescarse
|
||||
|
||||
//console.log(">>>>>>>>>>>>>>>>>>>> getOrCreateUser", dataUser.userResult.user.Entity);
|
||||
//Refrescamos datos que nos interesan
|
||||
dataUser.id = dataUser.userResult.user.id;
|
||||
dataUser.entityId = dataUser.userResult.user.Entity
|
||||
? dataUser.userResult.user.Entity.id
|
||||
: null;
|
||||
@ -479,6 +477,13 @@ async function getOrCreateUser(req, res, next) {
|
||||
dataUser.entityLevel = dataUser.userResult.user.Entity
|
||||
? dataUser.userResult.user.Entity.level
|
||||
: null;
|
||||
|
||||
dataUser.email = dataUser.userResult.user ? dataUser.userResult.user.email : null;
|
||||
dataUser.phone = dataUser.userResult.user ? dataUser.userResult.user.phone : null; //((req.body.phone != '+34') ? req.body.phone : null), lo quitamos de momento por la de movistar
|
||||
dataUser.name = dataUser.userResult.user ? dataUser.userResult.user.name : null;
|
||||
dataUser.surname = dataUser.userResult.user ? dataUser.userResult.user.surname : null;
|
||||
;
|
||||
//Reasignamos a variable de entorno
|
||||
res.locals.dataUser = dataUser;
|
||||
next();
|
||||
}
|
||||
|
||||
@ -11,6 +11,8 @@ const eventService = require("./event.service");
|
||||
const eventReservationService = require("./events_reservations.service");
|
||||
const eventInscriptionService = require("./events_inscriptions.service");
|
||||
const notificationService = require("../notification/notification.service");
|
||||
const marketingListService = require("./marketing_list.service");
|
||||
const mailService = require("./mail.service");
|
||||
|
||||
const {
|
||||
extractParamsFromRequest,
|
||||
@ -55,37 +57,7 @@ function generateMemberInscription(user, inscription, reservation) {
|
||||
return memberInscription;
|
||||
}
|
||||
|
||||
function generateHeaderMail(member) {
|
||||
let headerMail = null;
|
||||
if (member) {
|
||||
headerMail = {
|
||||
to: member.email,
|
||||
name: member.name + " " + member.surname,
|
||||
subject:
|
||||
(member.validated ? "Entrada" : "Lista de espera") + " para el congreso " + member.event_name + " confirmada",
|
||||
};
|
||||
}
|
||||
|
||||
return headerMail;
|
||||
}
|
||||
|
||||
function generateBodyMail(member) {
|
||||
let bodyMail = null;
|
||||
if (member) {
|
||||
bodyMail = {
|
||||
tipoEntrada: member.validated ? "Entrada" : "Lista de espera",
|
||||
descriptionEntrada: member.description,
|
||||
qrCode: member.qrCode,
|
||||
qrCodeUrl: member.qrCodeUrl,
|
||||
color: member.qrConfig.color,
|
||||
codeTicket: member.code_ticket,
|
||||
eventName: member.event_name,
|
||||
dateEvent: moment(member.event_date).format("D [de] MMMM [de] YYYY"),
|
||||
dateInscription: moment(member.date_inscription).format("DD/MM/YY HH:mm "),
|
||||
};
|
||||
}
|
||||
return bodyMail;
|
||||
}
|
||||
|
||||
const extraControllers = {
|
||||
checkCapacity: async (req, res, next) => {
|
||||
@ -96,6 +68,7 @@ const extraControllers = {
|
||||
allow: false,
|
||||
error: undefined,
|
||||
};
|
||||
console.log('>>>>>>>>>>>>>>>>>>>>>>>checkCapacity', result);
|
||||
|
||||
if (!result.eventId) {
|
||||
return handleResultResponse(null, null, params, res, httpStatus.BAD_REQUEST);
|
||||
@ -166,6 +139,33 @@ const extraControllers = {
|
||||
}
|
||||
},
|
||||
|
||||
//Funcion que devuelve:
|
||||
//1. Todas las inscripciones online de un evento, cuando el usuario es administrador
|
||||
getInscriptionsOnline: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
const eventId = params.params.id;
|
||||
const userId = req.user.id;
|
||||
var result = null;
|
||||
|
||||
//console.log(params, req.user.level);
|
||||
if (!eventId)
|
||||
return handleResultResponse("Es necesario el ID del evento", null, params, res, httpStatus.NOT_FOUND);
|
||||
|
||||
|
||||
try {
|
||||
if (req.user.level === 8) result = await eventInscriptionService._getInscriptionByEvent(eventId);
|
||||
else result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, userId);
|
||||
|
||||
return handleResultResponse(result, null, params, res, result === null ? httpStatus.NOT_FOUND : httpStatus.OK);
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "getInscriptions", error, res);
|
||||
}
|
||||
|
||||
|
||||
|
||||
},
|
||||
|
||||
|
||||
getInscriptionsOfNextEventsCount: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
const userId = req.user.id;
|
||||
@ -180,29 +180,7 @@ const extraControllers = {
|
||||
}
|
||||
},
|
||||
|
||||
getInscription: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
const inscriptionId = params.params.id;
|
||||
const userId = req.user.id;
|
||||
|
||||
try {
|
||||
let inscription = await eventInscriptionService._getInscriptionById(inscriptionId);
|
||||
if (!inscription) {
|
||||
return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
||||
} else if (inscription.userId !== userId) {
|
||||
return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription);
|
||||
inscription = await inscription.toJSON();
|
||||
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
||||
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||
inscription.code_ticket_qr = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||
console.log(">>>>>>>voy a dar inscription");
|
||||
return handleResultResponse(inscription, null, params, res, httpStatus.OK);
|
||||
} catch (error) {
|
||||
return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
findPartners: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
@ -290,9 +268,11 @@ const extraControllers = {
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
try {
|
||||
//Eliminamos miembro de la lista de mailchimp a la que está asociado
|
||||
await eventInscriptionService._deleteMember(marketingListIdOverflow, inscription.user.email); // inscription.marketing_memberId);
|
||||
|
||||
await marketingListService._deleteMember(marketingListIdOverflow, inscription.user.email); // inscription.marketing_memberId);
|
||||
} catch (error) {
|
||||
console.log("validate incription", error);
|
||||
}
|
||||
@ -309,7 +289,7 @@ const extraControllers = {
|
||||
"mandar correo>>>>>>>>>>>>>await QRHelper.getInscriptionQRCode(member.qrConfig); >>>>>>>> ",
|
||||
member
|
||||
);
|
||||
emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member));
|
||||
emailHelper.sendTicket(mailService.generateHeaderMail(member), mailService.generateBodyMail(member));
|
||||
} catch (error) {
|
||||
console.log("No se ha podido mandar email con entrada");
|
||||
}
|
||||
@ -333,586 +313,17 @@ const extraControllers = {
|
||||
}
|
||||
},
|
||||
|
||||
deleteInscription: async (req, res, next) => {
|
||||
syncronizeMarketingList: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
const user = req.user;
|
||||
const inscriptionId = params.params.id;
|
||||
const eventId = params.params.id;
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><syncronizeMarketingList");
|
||||
|
||||
try {
|
||||
const inscription = await eventInscriptionService._getInscriptionById(inscriptionId);
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion a borrar:");
|
||||
console.log(inscription);
|
||||
if (!inscription || inscription.userId !== user.id)
|
||||
return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
||||
if (marketingListService.syncronizeEventWithMarketingList(eventId))
|
||||
return handleResultResponse("La sincronización se ha realizado correctamente", null, params, res, httpStatus.DELETEOK);
|
||||
|
||||
//Borramos inscripcion y descontamos asistentes
|
||||
if ((await eventInscriptionService._deleteInscription(inscription.id)) > 0) {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada");
|
||||
//En caso de inscripciones online no hacemos nada mas ya que no se controlan aforos
|
||||
if (inscription.type !== "online" && inscription.type !== "online group") {
|
||||
const EventOrReservationChangeId = inscription.reservationId
|
||||
? inscription.reservationId
|
||||
: inscription.overflowEventId
|
||||
? inscription.overflowEventId
|
||||
: inscription.eventId;
|
||||
let NewConfirmed = 0;
|
||||
let marketingListId = null;
|
||||
|
||||
if (inscription.reservationId != null) {
|
||||
console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId);
|
||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||
EventOrReservationChangeId
|
||||
);
|
||||
marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId))
|
||||
.marketing_list;
|
||||
} else if (inscription.overflowEventId != null) {
|
||||
console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId);
|
||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
||||
EventOrReservationChangeId
|
||||
);
|
||||
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
|
||||
} else if (inscription.eventId != null) {
|
||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(
|
||||
EventOrReservationChangeId
|
||||
);
|
||||
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
|
||||
}
|
||||
|
||||
//Actualizamos aforo del evento o de la reserva
|
||||
if (inscription.reservationId != null) {
|
||||
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo reserva", EventOrReservationChangeId);
|
||||
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
|
||||
if (!(await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed)))
|
||||
return handleResultResponse(
|
||||
"Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
} else {
|
||||
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo evento", EventOrReservationChangeId);
|
||||
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
|
||||
if (!(await eventService._updateConfirmedEvent(EventOrReservationChangeId, NewConfirmed)))
|
||||
return handleResultResponse(
|
||||
"Error al eliminar inscripción, no puedo cambiar confirmados a la inscripcion",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
//Desinscribimos de mailchimp y mandamos correo de confirmacion de desinscripcion
|
||||
await eventInscriptionService._deleteMember(marketingListId, inscription.user.email); //inscription.marketing_memberId);
|
||||
} catch (error) {
|
||||
console.log("error mailchimp>><", error);
|
||||
}
|
||||
|
||||
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
||||
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
||||
let headerMail = generateHeaderMail(member);
|
||||
headerMail.subject = "Cancelación de " + headerMail.subject;
|
||||
|
||||
try {
|
||||
emailHelper.sendCancelacion(headerMail, generateBodyMail(member));
|
||||
} catch (error) {
|
||||
console.log("No se ha podido mandar email con entrada");
|
||||
}
|
||||
|
||||
console.log(">>>>>>>>>>>>>>Inscripcion eliminada con todos los pasos");
|
||||
return handleResultResponse("Inscripción eliminada", null, params, res, httpStatus.DELETEOK);
|
||||
} else return handleResultResponse("No se pudo eliminar inscripción", null, params, res, httpStatus.NOT_FOUND);
|
||||
} catch (error) {
|
||||
console.log("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeerrrrrrrrrrrrrrrrrrorrrr", error);
|
||||
return handleResultResponse("Error al eliminar inscripción", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
},
|
||||
|
||||
recuperateEvent: async (req, res, next) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> recuperateEvent");
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription)
|
||||
return handleResultResponse(
|
||||
"Error al recuperar evento, prepareInscription requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
try {
|
||||
dataInscription.event = await eventService._getEvent(dataInscription.eventId);
|
||||
if (dataInscription.event) {
|
||||
dataInscription.event = await dataInscription.event.toJSON();
|
||||
} else {
|
||||
// No se ha encontrado
|
||||
return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "recuperateEvent", error, res);
|
||||
}
|
||||
// console.log('>>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse');
|
||||
// console.log(req.dataInscription.event);
|
||||
// return handleResultResponse(req.dataInscription, null, req.params, res, httpStatus.OK);
|
||||
res.locals.dataInscription = dataInscription;
|
||||
next();
|
||||
},
|
||||
|
||||
//Esta función se puede llamar desde APP y desde WEB
|
||||
createInscription: async (req, res, next) => {
|
||||
console.log("CREATE INSCRIPTION********************************************>>>< ", req.body.type);
|
||||
//Si la inscripcion en online o grupal saltamos la incripcion antigua y lo hacemos del nuevo modo
|
||||
if (req.body.group_size && req.body.group_size > 1) {
|
||||
console.log(">>>voy por la otra rama group_size: ", req.body.group_size);
|
||||
next();
|
||||
return;
|
||||
}
|
||||
if (req.body.type && req.body.type === "online") {
|
||||
console.log(">>>voy por la otra rama: ", req.body.type);
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ANTIGUA ");
|
||||
//Iniciamos entidades relacionadas con la inscripción.
|
||||
let dataUser = {
|
||||
id: req.user ? req.user.id : null,
|
||||
phone: req.user ? req.user.phone : null, //((req.body.phone != '+34') ? req.body.phone : null), lo quitamos de momento por la de movistar
|
||||
name: req.user ? req.user.name : req.body.name,
|
||||
surname: req.user ? req.user.surname : req.body.surname,
|
||||
email: req.user ? req.user.email : req.body.email,
|
||||
entityId: null,
|
||||
userResult: req.user ? req.user : null,
|
||||
};
|
||||
|
||||
let dataInscription = {
|
||||
eventId: params.params.id,
|
||||
reservationCode: req.user ? req.body.code : Buffer.from(req.body.code, "base64").toString("ascii"),
|
||||
type: req.body.code ? "reservation" : "regular",
|
||||
source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web
|
||||
validated: null, //si no esta validado la inscripción es a la lista de espera
|
||||
inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada
|
||||
inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada
|
||||
event: null,
|
||||
reservation: null,
|
||||
inscription: null,
|
||||
};
|
||||
|
||||
console.log("DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>");
|
||||
console.log(dataUser);
|
||||
console.log("DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>");
|
||||
console.log(dataInscription);
|
||||
|
||||
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
|
||||
if (dataInscription.reservationCode) {
|
||||
try {
|
||||
dataInscription.reservation = await eventReservationService._getReservaByCode(
|
||||
dataInscription.eventId,
|
||||
dataInscription.reservationCode
|
||||
);
|
||||
if (dataInscription.reservation) {
|
||||
dataInscription.reservation = await dataInscription.reservation.toJSON();
|
||||
dataInscription.event = dataInscription.reservation.Event;
|
||||
} else {
|
||||
// No se ha encontrado
|
||||
return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "createInscription", error, res);
|
||||
}
|
||||
}
|
||||
//SOLO RECUPERAMOS EL EVENTO
|
||||
else {
|
||||
try {
|
||||
dataInscription.event = await eventService._getEvent(dataInscription.eventId);
|
||||
if (dataInscription.event) {
|
||||
dataInscription.event = await dataInscription.event.toJSON();
|
||||
} else {
|
||||
// No se ha encontrado
|
||||
return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "createInscription", error, res);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse");
|
||||
console.log(dataInscription.reservation);
|
||||
console.log(dataInscription.event);
|
||||
//Asignamos a los datos del usuario a crear, el id de la entidad a la que pertenece, este caso solo es necesario cuando viene la inscripción por web ya que hay que crear un usuario nuevo
|
||||
if (dataInscription.reservation) dataUser.entityId = dataInscription.reservation.entityId;
|
||||
|
||||
//creamos o recuperamos el usuario teniendo en cuenta que pude venir por APP o WEB
|
||||
//si viene por web se tendra en cuenta el email y si viene por APP el phone para buscar
|
||||
try {
|
||||
//CHAPUZA PARA PODER DAR DE ALTA USUARIOS CON EL MISMO CORREO ELECTRONICO, PERO DISTINTO NOMBRE Y APELLIDO.
|
||||
if (req.user)
|
||||
//? 'app' : 'web', //En el caso de tener ya usuario viene por APP sino viene por web
|
||||
dataUser.userResult = await userService._getOrCreateUser(dataUser);
|
||||
else dataUser.userResult = await userService._getOrCreateUserWEB(dataUser);
|
||||
|
||||
if (!dataUser.userResult) {
|
||||
// No se ha encontrado
|
||||
return handleResultResponse(
|
||||
"No se ha podido crear o encontrar el usuario dado",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "createInscription", error, res);
|
||||
}
|
||||
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>este es el usuario que quiere inscribirse");
|
||||
console.log(dataUser.userResult);
|
||||
|
||||
try {
|
||||
//Comprobamos que el usuario no tenga ya inscripcion para ese evento
|
||||
dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id
|
||||
);
|
||||
if (dataInscription.inscription) {
|
||||
console.log("esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><");
|
||||
console.log(dataInscription.inscription);
|
||||
//Devuelvo la reserva que ya tiene hecha el usuario
|
||||
if (
|
||||
!dataInscription.inscription.reservationId ||
|
||||
dataInscription.inscription.reservationId == dataInscription.reservation.id
|
||||
)
|
||||
return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
|
||||
|
||||
//ACTUALIZAMOS LA RESERVA DE LA INSCRIPCION CON LA NUEVA Y CAMBIAMOS COMFIRMADOS DEVOLVIENDO LA INSCRIPCIÓN CON LA NUEVA RESERVA
|
||||
let CountConfirmedOldReservation = await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||
dataInscription.inscription.reservationId
|
||||
);
|
||||
--CountConfirmedOldReservation;
|
||||
console.log("actualizo confirmados de la reserva anterior");
|
||||
await eventReservationService._updateConfirmedReservation(
|
||||
dataInscription.inscription.reservationId,
|
||||
CountConfirmedOldReservation
|
||||
);
|
||||
|
||||
let CountConfirmedNewReservation = await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||
dataInscription.reservation.id
|
||||
);
|
||||
++CountConfirmedNewReservation;
|
||||
console.log("actualizo confirmados de la nueva reserva");
|
||||
await eventReservationService._updateConfirmedReservation(
|
||||
dataInscription.reservation.id,
|
||||
CountConfirmedNewReservation
|
||||
);
|
||||
await eventInscriptionService._updateReservationOfInscription(
|
||||
dataInscription.inscription.id,
|
||||
dataInscription.reservation.id
|
||||
);
|
||||
|
||||
dataInscription.inscription = await eventInscriptionService._getInscriptionById(dataInscription.inscription.id);
|
||||
return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
|
||||
}
|
||||
//TENEMOS QUE CREAR INSCRIPCIÓN
|
||||
else {
|
||||
//CON CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DE LA RESERVA, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
|
||||
if (dataInscription.reservation) {
|
||||
dataInscription.inscriptionsWithReservationCount =
|
||||
await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id);
|
||||
++dataInscription.inscriptionsWithReservationCount;
|
||||
|
||||
console.log(
|
||||
"me inscribo por reserva>>>>>>>>>>>>>>>>>>>>>>>>>>><< con asistentes: ",
|
||||
dataInscription.reservation.assistants
|
||||
);
|
||||
console.log(dataInscription.reservation.sold_out);
|
||||
console.log(dataInscription.inscriptionsWithReservationCount);
|
||||
|
||||
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA
|
||||
if (
|
||||
dataInscription.reservation.sold_out == 0 &&
|
||||
dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount
|
||||
) {
|
||||
dataInscription.validated = true;
|
||||
|
||||
//Actualizamos aforo de la lista de espera de la reserva y creamos inscripcion en la lista de espera de la reserva
|
||||
if (
|
||||
await eventReservationService._updateConfirmedReservation(
|
||||
dataInscription.reservation.id,
|
||||
dataInscription.inscriptionsWithReservationCount
|
||||
)
|
||||
)
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id,
|
||||
dataInscription.type,
|
||||
dataInscription.validated,
|
||||
dataInscription.source,
|
||||
dataInscription.reservation.id,
|
||||
null
|
||||
);
|
||||
else
|
||||
return handleResultResponse(
|
||||
"No se ha podido actualizar el aforo de la reserva",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
//Ponemos la reserva en SOLD_OUT para que no se pueda apuntar nadie más
|
||||
if (dataInscription.reservation.assistants == dataInscription.inscriptionsWithReservationCount)
|
||||
await eventReservationService._updateSoldOutReservation(dataInscription.reservation.id, true);
|
||||
}
|
||||
// APUNTARSE A LISTA DE ESPERA SI SE PUEDE
|
||||
else {
|
||||
if (dataInscription.reservation.allow_overflow === true) {
|
||||
dataInscription.validated = false;
|
||||
dataInscription.inscriptionsWithReservationCount =
|
||||
await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||
dataInscription.reservation.overflow_reservationId
|
||||
);
|
||||
++dataInscription.inscriptionsWithReservationCount;
|
||||
|
||||
// if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) {
|
||||
//Actualizamos aforo de la reserva y creamos inscripcion
|
||||
if (
|
||||
await eventReservationService._updateConfirmedReservation(
|
||||
dataInscription.reservation.overflow_reservationId,
|
||||
dataInscription.inscriptionsWithReservationCount
|
||||
)
|
||||
)
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id,
|
||||
dataInscription.type,
|
||||
dataInscription.validated,
|
||||
dataInscription.source,
|
||||
dataInscription.reservation.overflow_reservationId,
|
||||
null
|
||||
);
|
||||
else
|
||||
return handleResultResponse(
|
||||
"No se ha podido actualizar el aforo de la reserva",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
} else
|
||||
return handleResultResponse(
|
||||
"Aforo completo de la reserva y no hay lista de espera",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
}
|
||||
}
|
||||
//SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
|
||||
else {
|
||||
dataInscription.inscriptionsWithoutReservationAndOverflowCount =
|
||||
await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(dataInscription.event.id);
|
||||
++dataInscription.inscriptionsWithoutReservationAndOverflowCount;
|
||||
|
||||
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO
|
||||
if (
|
||||
dataInscription.event.sold_out == 0 &&
|
||||
dataInscription.event.assistants >= dataInscription.inscriptionsWithoutReservationAndOverflowCount
|
||||
) {
|
||||
dataInscription.validated = true;
|
||||
//Actualizamos aforo del evento y creamos inscripcion
|
||||
if (
|
||||
await eventService._updateConfirmedEvent(
|
||||
dataInscription.event.id,
|
||||
dataInscription.inscriptionsWithoutReservationAndOverflowCount
|
||||
)
|
||||
)
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id,
|
||||
dataInscription.type,
|
||||
dataInscription.validated,
|
||||
dataInscription.source,
|
||||
null,
|
||||
null
|
||||
);
|
||||
else
|
||||
return handleResultResponse(
|
||||
"No se ha podido actualizar el aforo del evento",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
//Ponemos el evento en SOLD_OUT
|
||||
if (dataInscription.event.assistants == dataInscription.inscriptionsWithoutReservationAndOverflowCount)
|
||||
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
|
||||
}
|
||||
// APUNTARSE A la lista de espera si se puede
|
||||
else {
|
||||
if (dataInscription.event.allow_overflow === true) {
|
||||
dataInscription.validated = false;
|
||||
|
||||
//Actualizamos aforo de la lista de espera del evento y creamos inscripcion
|
||||
console.log(
|
||||
"evento de lista de espera que debo actulizar sus confirmados>>>>>>>>>>>>>>>>>>>>>",
|
||||
dataInscription.event.overflow_eventId
|
||||
);
|
||||
//recuperamos la cantidad de apuntados al evento overflow a lista de espera
|
||||
let ConfirmedWaitList = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
||||
dataInscription.event.overflow_eventId
|
||||
);
|
||||
console.log(
|
||||
"cantidad apuntados al evento padre>>>>>>>>>>>>>>>>>>>>>",
|
||||
dataInscription.inscriptionsWithoutReservationAndOverflowCount
|
||||
);
|
||||
console.log(
|
||||
"cantidad apuntados al evento de lista de espera asociado>>>>>>>>>>>>>>>>>>>>>",
|
||||
ConfirmedWaitList
|
||||
);
|
||||
|
||||
if (
|
||||
await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, ++ConfirmedWaitList)
|
||||
) {
|
||||
//console.log('voy a crearrrrrr la inscripcion');
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id,
|
||||
dataInscription.type,
|
||||
dataInscription.validated,
|
||||
dataInscription.source,
|
||||
null,
|
||||
dataInscription.event.overflow_eventId
|
||||
);
|
||||
} else {
|
||||
console.log("No se ha podido actualizar el aforo del evento");
|
||||
return handleResultResponse(
|
||||
"No se ha podido actualizar el aforo del evento",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
}
|
||||
} else
|
||||
return handleResultResponse(
|
||||
"Aforo completo y no hay lista de espera",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "createInscription", error, res);
|
||||
}
|
||||
|
||||
const marketingListOfInscription = dataInscription.event.marketing_list;
|
||||
/*AHORA SE ALMACENA TODO EN UNA ÚNICA LISTA DE MAILCHIMP, QUE ES LA DEL EVENTO
|
||||
(si en un futuro se quiere tener listas independientes, bastaría con tratarlo aqui los campos de marketinglist de la reserva ...)
|
||||
if (dataInscription.inscription.reservationId)
|
||||
marketingListOfInscription = dataInscription.reservation.marketingList
|
||||
else if (dataInscription.inscription.overflowEventId)
|
||||
marketingListOfInscription = (await _getEvent(dataInscription.inscription.overflowEventId)).marketingList;
|
||||
else
|
||||
marketingListOfInscription = dataInscription.event.marketingList;
|
||||
*/
|
||||
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
||||
var member = generateMemberInscription(
|
||||
dataUser.userResult.user,
|
||||
dataInscription.inscription,
|
||||
dataInscription.reservation
|
||||
);
|
||||
//En este caso al ser una inscripcion recien creada hay que asignar los datos del evento desde el evento
|
||||
member.event_name = dataInscription.event.name;
|
||||
member.event_date = dataInscription.event.init_date;
|
||||
|
||||
try {
|
||||
member.marketing_memberId = await eventInscriptionService._addMember(marketingListOfInscription, member);
|
||||
eventInscriptionService._updateMarketingMemberOfInscription(
|
||||
dataInscription.inscription.id,
|
||||
member.marketing_memberId
|
||||
);
|
||||
} catch (error) {
|
||||
console.log("No se ha podido añadir email a mailchimp");
|
||||
}
|
||||
|
||||
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
|
||||
|
||||
console.log("Mandamos mail con entrada>>>>>>>>>>>>>>>>>>>>>>>>>>>");
|
||||
//console.log(headerMail, bodyMail);
|
||||
|
||||
try {
|
||||
if (member.validated) emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member));
|
||||
else emailHelper.sendListaEspera(generateHeaderMail(member), generateBodyMail(member));
|
||||
} catch (error) {
|
||||
console.log("No se ha podido mandar email con entrada");
|
||||
}
|
||||
|
||||
return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED);
|
||||
},
|
||||
|
||||
addConfirmedfromReservation: async (req, res, next) => {
|
||||
//_updateConfirmedEvent
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> addConfirmedfromReservation");
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
|
||||
//En caso de ser online no descontamos ningun aforo ya que no se controla de momento
|
||||
if (dataInscription.type === "online" || dataInscription.type === "online group") {
|
||||
console.log(">> No se aplica descuento");
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!dataInscription || !dataInscription.reservation || !dataInscription.event)
|
||||
return handleResultResponse(
|
||||
"Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
if (res.locals.dataUser.entityLevel === "aliado") {
|
||||
const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants;
|
||||
if (dataInscription.event.assistants < newConfirmed)
|
||||
return handleResultResponse(
|
||||
{ message: "El aforo solicitado es superior a las plazas disponibles" },
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.OK
|
||||
);
|
||||
|
||||
//SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
|
||||
if (!(await eventService._updateConfirmedEvent(dataInscription.event.id, newConfirmed)))
|
||||
return handleResultResponse(
|
||||
"No se ha podido actualizar el aforo del evento",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
//Si se ha llenado ponemos el evento en SOLD_OUT
|
||||
if (dataInscription.event.assistants == newConfirmed)
|
||||
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
|
||||
}
|
||||
next();
|
||||
},
|
||||
|
||||
getQRCodeInscription: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
@ -939,24 +350,6 @@ const extraControllers = {
|
||||
}
|
||||
},
|
||||
|
||||
checkInscription: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
var eventId = params.params.id;
|
||||
var email = params.params.email;
|
||||
|
||||
try {
|
||||
const user = await userService._getUserByEmail(email);
|
||||
if (user) {
|
||||
const result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, user.id);
|
||||
if (result) return handleResultResponse(result.stateText, null, params, res, httpStatus.OK);
|
||||
}
|
||||
|
||||
return handleResultResponse("No hay inscripción con ese email", null, params, res, httpStatus.NOT_FOUND);
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "checkInscription", error, res);
|
||||
}
|
||||
},
|
||||
|
||||
sendMailTicket: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
const inscriptionId = params.params.id;
|
||||
@ -982,8 +375,8 @@ const extraControllers = {
|
||||
//console.log(headerMail, bodyMail);
|
||||
|
||||
try {
|
||||
if (member.validated) emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member));
|
||||
else emailHelper.sendListaEspera(generateHeaderMail(member), generateBodyMail(member));
|
||||
if (member.validated) emailHelper.sendTicket(mailService.generateHeaderMail(member), mailService.generateBodyMail(member));
|
||||
else emailHelper.sendListaEspera(mailService.generateHeaderMail(member), mailService.generateBodyMail(member));
|
||||
} catch (error) {
|
||||
console.log("No se ha podido mandar email con entrada");
|
||||
}
|
||||
|
||||
@ -271,30 +271,26 @@ routes.get(
|
||||
next();
|
||||
},
|
||||
cacheSuccesses('1 hour'),*/
|
||||
eventController.getInscription
|
||||
eventInscriptionController.getInscription
|
||||
);
|
||||
|
||||
// Hacer una inscripción ANTIGUA NO TOCAR
|
||||
// Hacer una inscripción
|
||||
routes.post(
|
||||
"/events/:id/inscriptions",
|
||||
isLoggedUser,
|
||||
SchemaValidator(eventValidation.InscriptionInputType, true),
|
||||
eventController.createInscription,
|
||||
|
||||
//Si la inscripcion en online o grupal la hacemos con el nuevo método
|
||||
//Prepara los datos de la inscripción tipo ....
|
||||
eventInscriptionController.prepareInscription,
|
||||
//Recupera el evento
|
||||
eventController.recuperateEvent,
|
||||
eventInscriptionController.prepareDataInscription,
|
||||
//Recupera la reservation si viene
|
||||
eventReservationController.recuperateReservationByCode,
|
||||
//Recupera a registra el usuario que se va a inscribir
|
||||
authController.getOrCreateUser,
|
||||
//Comprobamos que no tenga ya hecha una incripción, en tal caso la devolvemos
|
||||
eventInscriptionController.checkInscription,
|
||||
//Comprobamos si tiene ya una incripción, en tal caso, comprobamos el código de reserva sea el de la inscripcion hecha,
|
||||
//si no es así es el caso de un usuario que se reinscribe con otro código de reserva
|
||||
eventInscriptionController.checkInscriptionByUser,
|
||||
//Si es un usuario tutor y solicita un group_size se crea la reserva
|
||||
eventReservationController.createReservationToEntity,
|
||||
eventController.addConfirmedfromReservation,
|
||||
eventReservationController.activeReservationToEntity,
|
||||
|
||||
(req, res, next) => {
|
||||
@ -323,7 +319,7 @@ routes.delete(
|
||||
"/inscriptions/:id",
|
||||
isLoggedUser,
|
||||
//SchemaValidator(eventValidation.InscriptionInputType, true),
|
||||
eventController.deleteInscription
|
||||
eventInscriptionController.deleteInscription
|
||||
);
|
||||
|
||||
// Imagen del código QR de una inscripción
|
||||
@ -356,11 +352,11 @@ routes.get(
|
||||
routes.post(
|
||||
"/web/events/:id/inscriptions",
|
||||
SchemaValidator(eventValidation.webInscriptionInputType, true),
|
||||
eventController.createInscription
|
||||
eventInscriptionController.createInscription
|
||||
);
|
||||
|
||||
// Comprobar si estoy inscrito al congreso por la web
|
||||
routes.get("/web/events/:id/inscriptions/:email", eventController.checkInscription);
|
||||
routes.get("/web/events/:id/inscriptions/:email", eventInscriptionController.checkInscriptionByMail);
|
||||
|
||||
/*
|
||||
routes.get('/tickets/:id/',
|
||||
@ -382,6 +378,7 @@ routes.get('/tickets/:id/',
|
||||
*/
|
||||
// Inscripciones
|
||||
// Esto da las inscripciones de un evento
|
||||
routes.get("/admin/events/:id/inscriptions/online", isAdministratorUser, eventController.getInscriptionsOnline);
|
||||
routes.get("/admin/events/:id/inscriptions", isAdministratorUser, eventController.getInscriptions);
|
||||
|
||||
// Todos los ponentes
|
||||
@ -454,6 +451,13 @@ routes.get(
|
||||
eventReservationController.getReservationsExcel
|
||||
);
|
||||
|
||||
routes.get(
|
||||
"/admin/events/:id/syncMarketingList",
|
||||
//isAdministratorUser,
|
||||
eventController.syncronizeMarketingList
|
||||
);
|
||||
|
||||
|
||||
routes.get(
|
||||
"/admin/events/:id/reservations/:type/excel",
|
||||
isAdministratorUser,
|
||||
|
||||
@ -60,6 +60,28 @@ const extraMethods = {
|
||||
});
|
||||
},
|
||||
|
||||
_updateAssistantsEvent: (eventId, assistants) => {
|
||||
console.log('>> _updateAssistantsEvent: Actualizamos aforo', assistants);
|
||||
return new Promise(function (resolve, reject) {
|
||||
models.Event.update(
|
||||
{
|
||||
assistants: assistants,
|
||||
},
|
||||
{
|
||||
where: { id: eventId, typeId: { [Sequelize.Op.ne]: null } },
|
||||
}
|
||||
)
|
||||
.then(function (result) {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateAssistantsEvent", result);
|
||||
if (result) resolve(result[0] === 1);
|
||||
else resolve(false);
|
||||
})
|
||||
.catch(function (error) {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
_updateSoldOutEvent: (eventId, sold_out) => {
|
||||
return new Promise(function (resolve, reject) {
|
||||
models.Event.update(
|
||||
|
||||
@ -3,67 +3,157 @@
|
||||
const httpStatus = require("http-status");
|
||||
const generateControllers = require("../../core/controllers");
|
||||
const eventInscriptionService = require("./events_inscriptions.service");
|
||||
const eventReservationService = require("./events_reservations.service");
|
||||
const eventService = require("./event.service");
|
||||
const mailService = require("./mail.service");
|
||||
const marketingListService = require("./marketing_list.service");
|
||||
|
||||
const QRHelper = require("../../helpers/qr.helper");
|
||||
const { extractParamsFromRequest, handleResultResponse } = require("../../helpers/controller.helper");
|
||||
const { data } = require("../../core/logger");
|
||||
const lodash = require("lodash");
|
||||
|
||||
// Module Name
|
||||
const MODULE_NAME = "[eventInscription.controller]";
|
||||
const controllerOptions = { MODULE_NAME };
|
||||
|
||||
|
||||
async function refreshConfirmed (inscription){
|
||||
|
||||
if (!inscription){
|
||||
return handleResultResponse(
|
||||
"Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
};
|
||||
|
||||
if (inscription.type === "online")
|
||||
return true;
|
||||
|
||||
//En caso de inscripciones
|
||||
const EventOrReservationChangeId = inscription.reservationId
|
||||
? inscription.reservationId
|
||||
: inscription.overflowEventId
|
||||
? inscription.overflowEventId
|
||||
: inscription.eventId;
|
||||
|
||||
let NewConfirmed = 0;
|
||||
|
||||
//Si la inscripción viene por una reserva modificamos los confirmados de la reserva
|
||||
if (inscription.reservationId != null) {
|
||||
console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId);
|
||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||
EventOrReservationChangeId
|
||||
);
|
||||
//No se tienen en cuenta los marketinglist de las otras estructuras si lo tuviera seria esto
|
||||
// marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId))
|
||||
// .marketing_list;
|
||||
|
||||
//Inscripcion de lista de espera bien de reserva o de evento de lista de espera
|
||||
} else if (inscription.overflowEventId != null) {
|
||||
console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId);
|
||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
||||
EventOrReservationChangeId
|
||||
);
|
||||
//No se tienen en cuenta los marketinglist de las otras estructuras si lo tuviera seria esto
|
||||
/// marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
|
||||
|
||||
//Inscripción al evento (ni reserva ni lista de espera)
|
||||
} else if (inscription.eventId != null) {
|
||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(
|
||||
EventOrReservationChangeId
|
||||
);
|
||||
|
||||
//No se tienen en cuenta los marketinglist de las otras estructuras si lo tuviera seria esto
|
||||
//marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
|
||||
};
|
||||
|
||||
//Actualizamos aforo del evento o de la reserva
|
||||
if (inscription.reservationId != null) {
|
||||
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo reserva", EventOrReservationChangeId);
|
||||
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
|
||||
if (!(await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed)))
|
||||
return handleResultResponse(
|
||||
"Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
} else {
|
||||
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo evento", EventOrReservationChangeId);
|
||||
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
|
||||
if (!(await eventService._updateConfirmedEvent(EventOrReservationChangeId, NewConfirmed)))
|
||||
return handleResultResponse(
|
||||
"Error al eliminar inscripción, no puedo cambiar confirmados a la inscripcion",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const extraControllers = {
|
||||
///////////////////////////////////////////////////////////////////
|
||||
//Prepara la estructura de datos para el registro de inscripciones
|
||||
///////////////////////////////////////////////////////////////////
|
||||
prepareInscription: async (req, res, next) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> prepareInscription");
|
||||
prepareDataInscription: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
|
||||
let typeInscription = "onsite";
|
||||
//online
|
||||
if (req.body.type === "online") {
|
||||
// reservation online
|
||||
if (req.body.code) typeInscription = "online group";
|
||||
//reservation online
|
||||
else if (req.body.group_size > 1) typeInscription = "online group";
|
||||
else typeInscription = "online";
|
||||
}
|
||||
//onsite
|
||||
else {
|
||||
// reservation presencial
|
||||
if (req.body.code) typeInscription = "onsite group";
|
||||
// reservation presencial
|
||||
else if (req.body.group_size > 1) typeInscription = "onsite group";
|
||||
}
|
||||
|
||||
//Si no viene type es porque es una inscripción con la app antigua y el valor por defecto es onsite
|
||||
let typeInscription = "onsite";
|
||||
if ((req.body.type) && (req.body.type === "online"))
|
||||
typeInscription = "online";
|
||||
|
||||
//Si viene code es la appa antigua o la nueva
|
||||
if (((req.body.code) && (req.body.code !==""))
|
||||
|| ((req.body.group_size) && (req.body.group_size > 1)))
|
||||
typeInscription = typeInscription + " group";
|
||||
|
||||
let dataInscription = {
|
||||
eventId: params.params.id,
|
||||
reservationCode: req.user ? req.body.code : Buffer.from(req.body.code, "base64").toString("ascii"),
|
||||
type: typeInscription,
|
||||
groupSize: req.body.group_size ? req.body.group_size : 1,
|
||||
groupSize: req.body.group_size ? req.body.group_size : 1, //Si no viene group_size será uno porque es una inscripcion de la APP antigua
|
||||
source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web
|
||||
validated: null, //si no esta validado la inscripción es a la lista de espera
|
||||
validated: false, //si no esta validado la inscripción es a la lista de espera
|
||||
inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada
|
||||
inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada
|
||||
event: null,
|
||||
reservation: null,
|
||||
inscription: null,
|
||||
};
|
||||
|
||||
try {
|
||||
dataInscription.event = await eventService._getEvent(dataInscription.eventId);
|
||||
if (dataInscription.event) {
|
||||
dataInscription.event = await dataInscription.event.toJSON();
|
||||
} else {
|
||||
// No se ha encontrado
|
||||
return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "encontrado", error, res);
|
||||
}
|
||||
|
||||
res.locals.dataInscription = dataInscription;
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> prepareDataInscription", dataInscription.type);
|
||||
next();
|
||||
},
|
||||
|
||||
///////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//Esta función comprueba si el usuario ya tiene una inscripción para el evento
|
||||
///////////////////////////////////////////////////////////////////
|
||||
checkInscription: async (req, res, next) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> checkInscription (event_inscriptions.controller)");
|
||||
//si es así se comprueba que no quiera cambiar de codigo de reserva y se actualiza
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
checkInscriptionByUser: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription || !dataInscription.event)
|
||||
return handleResultResponse(
|
||||
"Error createReservationToEntity, prepareInscription, recuperateEvent requerida",
|
||||
"Error checkInscriptionByUser, prepareDataInscription requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
@ -72,33 +162,117 @@ const extraControllers = {
|
||||
let dataUser = res.locals.dataUser;
|
||||
if (!dataUser)
|
||||
return handleResultResponse(
|
||||
"Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida",
|
||||
"Error checkInscriptionByUser, prepareDataInscription, getOrCreateUser requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
//Comprobamos que el usuario no tenga ya inscripcion para ese evento
|
||||
dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id
|
||||
);
|
||||
if (dataInscription.inscription) {
|
||||
console.log(
|
||||
"esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><",
|
||||
dataInscription.inscription.reservationId
|
||||
try {
|
||||
//Comprobamos que el usuario no tenga ya inscripcion para ese evento
|
||||
dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id
|
||||
);
|
||||
console.log(dataInscription.inscription);
|
||||
//Devuelvo la reserva que ya tiene hecha el usuario
|
||||
// if (
|
||||
// !dataInscription.inscription.reservationId ||
|
||||
// dataInscription.inscription.reservationId == dataInscription.reservation.id
|
||||
// )
|
||||
return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
|
||||
}
|
||||
|
||||
if (dataInscription.inscription) {
|
||||
console.log("esta es la inscripcion que ya tengo>>>>",
|
||||
dataInscription.inscription
|
||||
);
|
||||
|
||||
//Si la inscripcion no tiene reserva o la tiene y es la misma de la insripcion devuelvo la inscripcion
|
||||
if ((!dataInscription.inscription.reservationId)
|
||||
|| ((dataInscription.reservation) && (dataInscription.inscription.reservationId == dataInscription.reservation.id)))
|
||||
return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
|
||||
|
||||
|
||||
//En caso contrario devuelvo la plaza a la reserva que tenia la inscripción anterior y apunto la inscripción a la nueva reserva
|
||||
//ACTUALIZAMOS LA RESERVA DE LA INSCRIPCION CON LA NUEVA Y CAMBIAMOS COMFIRMADOS DEVOLVIENDO LA INSCRIPCIÓN CON LA NUEVA RESERVA
|
||||
let CountConfirmedOldReservation = await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||
dataInscription.inscription.reservationId
|
||||
);
|
||||
console.log("actualizo confirmados de la reserva anterior");
|
||||
await eventReservationService._updateConfirmedReservation(
|
||||
dataInscription.inscription.reservationId,
|
||||
--CountConfirmedOldReservation
|
||||
);
|
||||
|
||||
let CountConfirmedNewReservation = await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||
dataInscription.reservation.id
|
||||
);
|
||||
console.log("actualizo confirmados de la nueva reserva");
|
||||
await eventReservationService._updateConfirmedReservation(
|
||||
dataInscription.reservation.id,
|
||||
++CountConfirmedNewReservation
|
||||
);
|
||||
await eventInscriptionService._updateReservationOfInscription(
|
||||
dataInscription.inscription.id,
|
||||
dataInscription.reservation.id
|
||||
);
|
||||
|
||||
dataInscription.inscription = await eventInscriptionService._getInscriptionById(dataInscription.inscription.id);
|
||||
return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
|
||||
};
|
||||
|
||||
} catch(error){
|
||||
return handleResultResponse("Error checkInscriptionByUser", error, params, res, httpStatus.NOT_FOUND);
|
||||
};
|
||||
next();
|
||||
},
|
||||
|
||||
getInscription: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
const inscriptionId = params.params.id;
|
||||
const userId = req.user.id;
|
||||
|
||||
try {
|
||||
let inscription = await eventInscriptionService._getInscriptionById(inscriptionId);
|
||||
if (!inscription) {
|
||||
return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
||||
} else if (inscription.userId !== userId) {
|
||||
return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
//console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription);
|
||||
inscription = await inscription.toJSON();
|
||||
// console.log(">>>>>>>voy a dar inscription>>><", inscription.user);
|
||||
var member = marketingListService._generateMarketingDTO(inscription);
|
||||
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||
inscription.code_ticket_qr = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||
|
||||
//Si el usuario de la inscripción no es tutor limpiamos la información de la reserva
|
||||
if (inscription.user.profile !== 'tutor')
|
||||
if (inscription.reservation) inscription.reservation.assistants = null;
|
||||
|
||||
console.log(">>>>>>>voy a dar inscription", inscription);
|
||||
return handleResultResponse(inscription, null, params, res, httpStatus.OK);
|
||||
} catch (error) {
|
||||
return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
},
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//Esta función comprueba si el email ya tiene una inscripción para el evento
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
checkInscriptionByMail: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
var eventId = params.params.id;
|
||||
var email = params.params.email;
|
||||
|
||||
try {
|
||||
const user = await userService._getUserByEmail(email);
|
||||
if (user) {
|
||||
const result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, user.id);
|
||||
if (result) return handleResultResponse(result.stateText, null, params, res, httpStatus.OK);
|
||||
}
|
||||
|
||||
return handleResultResponse("No hay inscripción con ese email", null, params, res, httpStatus.NOT_FOUND);
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "checkInscription", error, res);
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////
|
||||
//Esta función se llama solo desde APP
|
||||
//Inscripción sin CODIGO DE RESERVA, SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
|
||||
@ -107,15 +281,17 @@ const extraControllers = {
|
||||
createInscription: async (req, res, next) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> createInscription (event_inscriptions.controller)");
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription || !dataInscription.event)
|
||||
return handleResultResponse(
|
||||
"Error prepareInscription, recuperateEvent requerida",
|
||||
"Error prepareDataInscription requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
let dataUser = res.locals.dataUser;
|
||||
if (!dataUser)
|
||||
return handleResultResponse("Error getOrCreateUser requerida", null, params, res, httpStatus.NOT_FOUND);
|
||||
@ -129,36 +305,222 @@ const extraControllers = {
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
//Si es una inscripcion online no se validan aforos se crea inscripción y ya esta
|
||||
if (dataInscription.type === "online" || dataInscription.type === "online group") {
|
||||
try {
|
||||
try {
|
||||
|
||||
//ONLINE
|
||||
//Si es una inscripcion online no se validan aforos se crea inscripción y ya esta
|
||||
if (dataInscription.type === "online" || dataInscription.type === "online group") {
|
||||
//creamos inscripcion
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id,
|
||||
dataInscription.type,
|
||||
true, //validated,
|
||||
false, //validated,
|
||||
dataInscription.source,
|
||||
null,
|
||||
null
|
||||
);
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ENTRADA ONLINE", dataInscription.inscription);
|
||||
};
|
||||
|
||||
//ONSITE INDIVIDUAL
|
||||
if (!dataInscription.inscription) {
|
||||
|
||||
let member = marketingListService.addMarketingList(dataUser, dataInscription);
|
||||
let inscriptionsWithoutReservationAndOverflowCount =
|
||||
await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(dataInscription.event.id);
|
||||
++inscriptionsWithoutReservationAndOverflowCount;
|
||||
|
||||
console.log("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", member);
|
||||
// member = mailService._sendInscriptionEmail(dataInscription, member);
|
||||
console.log('Vamos a ver si hay aforo>>>>', inscriptionsWithoutReservationAndOverflowCount)
|
||||
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO
|
||||
if (
|
||||
dataInscription.event.sold_out == 0 &&
|
||||
dataInscription.event.assistants >= inscriptionsWithoutReservationAndOverflowCount
|
||||
) {
|
||||
dataInscription.validated = true;
|
||||
console.log('actualizamos afoorooo>>>');
|
||||
//Actualizamos aforo del evento y creamos inscripcion
|
||||
if (
|
||||
await eventService._updateConfirmedEvent(
|
||||
dataInscription.event.id,
|
||||
inscriptionsWithoutReservationAndOverflowCount
|
||||
)
|
||||
){
|
||||
try{
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.id,
|
||||
dataInscription.type,
|
||||
dataInscription.validated,
|
||||
dataInscription.source,
|
||||
null,
|
||||
null
|
||||
)
|
||||
}catch(error){console.log('SSSSSSSSSSSSSSSSSSSSSSSSS',error)}
|
||||
}
|
||||
else
|
||||
return handleResultResponse(
|
||||
"No se ha podido actualizar el aforo del evento",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
console.log('Inscripcion hecha>>>', dataInscription.inscription);
|
||||
|
||||
//************************************************************************************************************************************************
|
||||
//EN UN FUTURO SE METERÄ AQUI LAS INSCRIPCIONES NORMALES************************************
|
||||
//************************************************************************************************************************************************
|
||||
//Ponemos el evento en SOLD_OUT
|
||||
if (dataInscription.event.assistants == inscriptionsWithoutReservationAndOverflowCount)
|
||||
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
|
||||
}
|
||||
|
||||
// APUNTARSE A la lista de espera si se puede
|
||||
else {
|
||||
dataInscription.validated = false;
|
||||
|
||||
return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED);
|
||||
} catch (Error) {
|
||||
return handleResultResponse("Error al crear la incripción online", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
if (dataInscription.event.allow_overflow === false) {
|
||||
console.log("Aforo completo y no hay lista de espera");
|
||||
return handleResultResponse(
|
||||
"Aforo completo y no hay lista de espera",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
};
|
||||
|
||||
//recuperamos la cantidad de apuntados al evento overflow (lista de espera)
|
||||
let ConfirmedWaitList = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
||||
dataInscription.event.overflow_eventId
|
||||
);
|
||||
//recuperamos aforo de la lista de espera
|
||||
dataInscription.overflow_event = await eventService._getEvent(dataInscription.event.overflow_eventId);
|
||||
console.log("cantidad apuntados a lista de espera asociado, aforo >>>>>>>>>>>>>>>>>>>>>",
|
||||
ConfirmedWaitList, dataInscription.overflow_event.assistants
|
||||
);
|
||||
|
||||
//Si no hay espacio a lista de espera damos el mismo error que no hay lista de espera
|
||||
if (dataInscription.overflow_event.assistants < ++ConfirmedWaitList) {
|
||||
console.log("Aforo completo de lista de espera");
|
||||
return handleResultResponse(
|
||||
"Aforo completo y no hay lista de espera",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
};
|
||||
|
||||
//Creamos inscripción a lista de espera
|
||||
if (
|
||||
await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, ConfirmedWaitList)
|
||||
) {
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id,
|
||||
dataInscription.type,
|
||||
dataInscription.validated,
|
||||
dataInscription.source,
|
||||
null,
|
||||
dataInscription.event.overflow_eventId
|
||||
);
|
||||
} else {
|
||||
console.log("No se ha podido actualizar el aforo de la lista de espera del evento");
|
||||
return handleResultResponse(
|
||||
"o se ha podido actualizar el aforo de la lista de espera del evento",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
}
|
||||
} //FIN APUNTARSE A la lista de espera si se puede
|
||||
};
|
||||
|
||||
dataInscription.inscription = await dataInscription.inscription.toJSON();
|
||||
//Incluimos correo en sendinblue
|
||||
try {
|
||||
marketingListService.addMarketingList(dataUser, dataInscription);
|
||||
} catch(error){ console.log('Se ha producido un error al añadir a SenINBlue>>>>>>>>>>>>>>>>><<', error);}
|
||||
|
||||
//Mandamos correo con entrada o lista de espera
|
||||
try {
|
||||
mailService.sendEmailConfirm(dataUser, dataInscription);
|
||||
} catch(error){ console.log('Se ha producido un error al enviar mail>>>>>>>>>>>>>>>>><<', error);}
|
||||
|
||||
|
||||
return handleResultResponse(await dataInscription.inscription, null, params, res, httpStatus.CREATED);
|
||||
|
||||
} catch (Error) {
|
||||
return handleResultResponse("Error al crear la incripción createInscription", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
deleteInscription: async (req, res, next) => {
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
const user = req.user;
|
||||
const inscriptionId = params.params.id;
|
||||
let marketingListId = null;
|
||||
|
||||
try {
|
||||
const inscription = await eventInscriptionService._getInscriptionById(inscriptionId);
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion a borrar:");
|
||||
console.log(inscription);
|
||||
|
||||
//Solo se tiene en cuenta el marketinglist del evento
|
||||
marketingListId = inscription.event.marketing_list;
|
||||
|
||||
//Esto no seria posible si es asi damos error
|
||||
if (!inscription || inscription.userId !== user.id)
|
||||
return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
||||
|
||||
//En el caso de ser una inscripción grupal y el tutor se quiere quitar, se podrá hacer solo en el caso de que en la reserva no haya ya confirmados
|
||||
if (inscription.user.profile === "tutor" && inscription.reservation && inscription.reservation.confirmed > 1)
|
||||
return handleResultResponse("No se pudo eliminar inscripción por ser tutor de grupo y tener alumnos apuntados, pongase en contacto con nosotros", null, params, res, httpStatus.NOT_FOUND)
|
||||
|
||||
//Borramos inscripción
|
||||
if ((await eventInscriptionService._deleteInscription(inscription.id)) > 0) {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada");
|
||||
|
||||
//Actualizamos confirmados asistentes
|
||||
refreshConfirmed (inscription);
|
||||
|
||||
if (inscription.user.profile === "tutor" && inscription.reservation && inscription.reservation.confirmed === 1) {
|
||||
//Eliminamos la reserva hecha del centro aliado
|
||||
if (!((await eventReservationService._deleteReservation(inscription.reservation.id)) > 0))
|
||||
return handleResultResponse("No se pudo eliminar inscripción por ser tutor de grupo online y tener alumnos apuntados, pongase en contacto con nosotros", null, params, res, httpStatus.NOT_FOUND);
|
||||
|
||||
if (lodash.words(inscription.type).includes("onsite")) {
|
||||
const eventOfReservation = await eventService._getEvent(inscription.reservation.eventId);
|
||||
//Modificamos los asistentes de evento (AFORO) para añadir las plazas de la reserva eliminada
|
||||
const newAforo = eventOfReservation.assistants + inscription.reservation.assistants;
|
||||
if (!(await eventService._updateAssistantsEvent(eventOfReservation.id, newAforo)))
|
||||
return handleResultResponse("No se ha podido actualizar el aforo del evento, para reservar las plazas solicitadas", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
};
|
||||
}
|
||||
else
|
||||
return handleResultResponse("No se pudo eliminar inscripción", null, params, res, httpStatus.NOT_FOUND);
|
||||
|
||||
|
||||
//Quitamos correo en sendinblue
|
||||
try {
|
||||
marketingListService._deleteMember(marketingListId, inscription.user.email);
|
||||
} catch(error){ console.log('Se ha producido un error al eliminar de SenINBlue>>>>>>>>>>>>>>>>><<', error);}
|
||||
|
||||
//Mandamos correo de confirmación de eliminación
|
||||
try {
|
||||
mailService.sendEmailCancelate(inscription);
|
||||
} catch(error){ console.log('Se ha producido un error al enviar mail>>>>>>>>>>>>>>>>><<', error);}
|
||||
|
||||
console.log(">>>>>>>>>>>>>>Inscripcion eliminada con todos los pasos");
|
||||
return handleResultResponse("Inscripción eliminada", null, params, res, httpStatus.DELETEOK);
|
||||
|
||||
} catch (error) {
|
||||
console.log("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeerrrrrrrrrrrrrrrrrrorrrr", error);
|
||||
return handleResultResponse("Error al eliminar inscripción", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
module.exports = generateControllers(eventInscriptionService, extraControllers, controllerOptions);
|
||||
|
||||
@ -107,6 +107,8 @@ module.exports = function (sequelize, DataTypes) {
|
||||
"end_available_date",
|
||||
"stateCode",
|
||||
"stateText",
|
||||
"marketing_list",
|
||||
"assistants",
|
||||
],
|
||||
include: [
|
||||
{
|
||||
|
||||
@ -213,42 +213,14 @@ const extraMethods = {
|
||||
);
|
||||
},
|
||||
|
||||
_addMember: (marketingListId, member) => {
|
||||
// console.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasddddddmemberrrrr1');
|
||||
// console.debug(member);
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (!marketingListId) {
|
||||
// || !member.validated) {
|
||||
resolve(member);
|
||||
} else {
|
||||
marketing
|
||||
.addMember(marketingListId, member)
|
||||
.then(function (result) {
|
||||
resolve(result.ID);
|
||||
})
|
||||
.catch(function (error) {
|
||||
reject(error);
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
_deleteMember: (marketingListId, marketingMemberId) => {
|
||||
console.debug(
|
||||
"Elimino miembro de la lista de mailchimp>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<",
|
||||
marketingListId,
|
||||
marketingMemberId
|
||||
);
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (!marketingListId || !marketingMemberId) {
|
||||
resolve();
|
||||
} else {
|
||||
resolve(marketing.deleteMember(marketingListId, marketingMemberId));
|
||||
}
|
||||
});
|
||||
},
|
||||
_getInscriptionsWithoutMemberId: (eventId) => {
|
||||
return models.EventInscription.scope(["includeEventAndVenue", "includeReservation", "defaultScope"]).findAll({
|
||||
where: {
|
||||
eventId: eventId,
|
||||
marketing_memberId: null
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
_getInscriptionsExcel: (user, eventId, callback) => {
|
||||
models.EventInscription.findAll({
|
||||
@ -351,6 +323,7 @@ const extraMethods = {
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
module.exports = generateService(models.EventInscription, extraMethods);
|
||||
|
||||
@ -5,6 +5,9 @@ const generateControllers = require("../../core/controllers");
|
||||
const eventService = require("./event.service");
|
||||
const eventReservationService = require("./events_reservations.service");
|
||||
const eventInscriptionService = require("./events_inscriptions.service");
|
||||
const mailService = require("./mail.service");
|
||||
const marketingListService = require("./marketing_list.service");
|
||||
|
||||
const {
|
||||
extractParamsFromRequest,
|
||||
handleErrorResponse,
|
||||
@ -20,33 +23,6 @@ const MODULE_NAME = "[eventReservation.controller]";
|
||||
|
||||
const controllerOptions = { MODULE_NAME };
|
||||
|
||||
function generateHeaderMail(reservation) {
|
||||
let headerMail = null;
|
||||
if (reservation) {
|
||||
headerMail = {
|
||||
to: reservation.Entity.contact_email,
|
||||
name: reservation.Entity.name,
|
||||
bcc: "cbarrantes@loquedeverdadimporta.org",
|
||||
bccName: "Carolina Barrantes",
|
||||
subject: "Códigos de invitación para congreso LQDVI",
|
||||
};
|
||||
}
|
||||
return headerMail;
|
||||
}
|
||||
|
||||
function generateBodyMail(reservation) {
|
||||
let bodyMail = null;
|
||||
if (reservation) {
|
||||
bodyMail = {
|
||||
entityName: reservation.Entity.name,
|
||||
eventName: reservation.Event.name,
|
||||
dateEvent: moment(reservation.Event.init_date).format("D [de] MMMM [de] YYYY"),
|
||||
reservationCode: reservation.reservation_code,
|
||||
reservationDescription: reservation.description,
|
||||
};
|
||||
}
|
||||
return bodyMail;
|
||||
}
|
||||
|
||||
async function _addConfirmedToEvent(confirmed, event) {
|
||||
const newConfirmed = event.confirmed + confirmed;
|
||||
@ -136,7 +112,7 @@ const extraControllers = {
|
||||
|
||||
try {
|
||||
if (reservation.Entity.contact_email)
|
||||
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
|
||||
emailHelper.sendReservationCode(mailService.generateHeaderMailReservation(reservation), mailService.generateBodyMailReservation(reservation));
|
||||
} catch (error) {
|
||||
// console.log(error);
|
||||
console.log("No se ha podido mandar email con los códigos de invitación");
|
||||
@ -169,7 +145,7 @@ const extraControllers = {
|
||||
console.log("mando correo: ", reservation.Entity.name);
|
||||
if (reservation.Entity.contact_email && reservation.Entity.contact_email.length !== 0) {
|
||||
console.log("correo: ", reservation.Entity.contact_email);
|
||||
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
|
||||
emailHelper.sendReservationCode(mailService.generateHeaderMailReservation(reservation), mailService.generateBodyMailReservation(reservation));
|
||||
result =
|
||||
result +
|
||||
"Invitación con código " +
|
||||
@ -193,18 +169,19 @@ const extraControllers = {
|
||||
},
|
||||
|
||||
recuperateReservationByCode: async (req, res, next) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> recuperateReservationByCode");
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription)
|
||||
return handleResultResponse(
|
||||
"Error recuperateReservationByCode, prepareInscription, recuperateEvent requerida",
|
||||
"Error recuperateReservationByCode, prepareDataInscription requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> recuperateReservationByCode", dataInscription.type);
|
||||
|
||||
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
|
||||
if (dataInscription.reservationCode) {
|
||||
try {
|
||||
@ -221,7 +198,7 @@ const extraControllers = {
|
||||
}
|
||||
res.locals.dataInscription = dataInscription;
|
||||
} catch (error) {
|
||||
return handleErrorResponse(MODULE_NAME, "recuperateEventAndReservation", error, res);
|
||||
return handleErrorResponse(MODULE_NAME, "recuperateReservationByCode", error, res);
|
||||
}
|
||||
}
|
||||
next();
|
||||
@ -233,7 +210,7 @@ const extraControllers = {
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription || !dataInscription.event)
|
||||
return handleResultResponse(
|
||||
"Error createReservationToEntity, prepareInscription, recuperateEvent requerida",
|
||||
"Error createReservationToEntity, prepareDataInscription, requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
@ -242,20 +219,31 @@ const extraControllers = {
|
||||
let dataUser = res.locals.dataUser;
|
||||
if (!dataUser)
|
||||
return handleResultResponse(
|
||||
"Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida",
|
||||
"Error createReservationToEntity, prepareDataInscription, getOrCreateUser requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> createReservationToEntity>>>>>>", dataInscription.type);
|
||||
//Si viene group_size crearemos un código de reserva
|
||||
if (dataInscription.groupSize > 1) {
|
||||
|
||||
if (!dataUser.entityId) {
|
||||
return handleResultResponse(
|
||||
"Error No es posible crear reserva grupal si no pertences a una entidad educativa",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
)};
|
||||
|
||||
const reservationData = {
|
||||
reservation_code: eventReservationService._generateReservatioCode(dataInscription.event, dataUser.entityName),
|
||||
state: "draft", //sin confirmar, publish es cuando se descuenta del aforo del evento
|
||||
color: "gray",
|
||||
description: dataInscription.type,
|
||||
description: (dataInscription.type === 'online group')? 'Incripción online en grupo' : 'Reserva',
|
||||
init_available_date: dataInscription.event.init_available_date,
|
||||
end_available_date: dataInscription.event.end_available_date,
|
||||
entityId: dataUser.entityId,
|
||||
@ -267,43 +255,109 @@ const extraControllers = {
|
||||
allow_overflow: false,
|
||||
};
|
||||
|
||||
//Comprobamos aforo si no es online, si no es posible apuntarse iria a lista de espera
|
||||
if (dataInscription.type !== "online" && dataInscription.type !== "online group"){
|
||||
const plazasDisponibles = dataInscription.event.assistants - dataInscription.event.confirmed;
|
||||
if (plazasDisponibles < reservationData.assistants)
|
||||
if (dataInscription.event.allow_overflow){
|
||||
reservationData.overflowEventId = dataInscription.event.overflow_eventId;
|
||||
reservationData.description = reservationData.description + ' en lista de espera'
|
||||
console.log('Asigno lista de espera>>>>>>>>>>>>>>>>>>>>>>>',reservationData.eventId);
|
||||
}
|
||||
else return handleResultResponse("Aforo lleno no es posible efectuar la reserva", null, params, res, httpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1.
|
||||
dataInscription.reservation = await eventReservationService.create(
|
||||
reservationData,
|
||||
generateControllers.buildContext(req, {})
|
||||
);
|
||||
|
||||
dataInscription.reservation = dataInscription.reservation.toJSON();
|
||||
res.locals.dataInscription = dataInscription;
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>RESERVATION CREADA", dataInscription.reservation);
|
||||
} else console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>no hago nada");
|
||||
}
|
||||
else console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>no hago nada");
|
||||
next();
|
||||
},
|
||||
|
||||
activeReservationToEntity: async (req, res, next) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity");
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription)
|
||||
let dataUser = res.locals.dataUser;
|
||||
if (!dataUser || !dataInscription || !dataInscription.event)
|
||||
return handleResultResponse(
|
||||
"Error activeReservationToEntity, prepareInscription, recuperateEvent requerida",
|
||||
"Error createReservationToEntity, prepareDataInscription, ActiveReservationToEntity requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
if (dataInscription.reservation) {
|
||||
if (res.locals.dataUser.entityLevel === "aliado") {
|
||||
///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1.
|
||||
//En caso de ser online no descontamos ningun aforo ya que no se controla de momento
|
||||
if (dataInscription.type === "online" || dataInscription.type === "online group") {
|
||||
console.log(">> No se aplica descuento de aforo");
|
||||
next();
|
||||
return;
|
||||
};
|
||||
|
||||
//En caso de ser una inscripción normal o una reserva ya publicada no descontamos ningun aforo al evento
|
||||
if (!dataInscription.reservation || (dataInscription.reservation.state === 'publish')){ // || (!dataInscription.reservationCode) || (dataInscription.reservationCode === "")) {
|
||||
console.log(">> No se aplica descuento de aforo ya que es una reserva publicada");
|
||||
next();
|
||||
return;
|
||||
};
|
||||
|
||||
|
||||
//Si es centro aliado
|
||||
if (dataUser.entityLevel === "aliado") {
|
||||
//La reserva puede estar asociada a la lista de espera es de donde se quitará aforo, si no al evento
|
||||
const eventToDiscountAssistants = dataInscription.reservation.overflowEventId
|
||||
? await eventService._getEvent(dataInscription.reservation.overflowEventId)
|
||||
: dataInscription.event;
|
||||
|
||||
const plazasDisponibles = eventToDiscountAssistants.assistants - eventToDiscountAssistants.confirmed;
|
||||
if (plazasDisponibles < dataInscription.reservation.assistants)
|
||||
return handleResultResponse("Aforo lleno no es posible efectuar la reserva", null, params, res, httpStatus.NOT_FOUND)
|
||||
|
||||
const newAforo = eventToDiscountAssistants.assistants - dataInscription.reservation.assistants;
|
||||
//Modificamos los asistentes de evento (AFORO) para quitar los de la reserva
|
||||
if (!(await eventService._updateAssistantsEvent(eventToDiscountAssistants.id, newAforo)))
|
||||
return handleResultResponse(
|
||||
"No se ha podido actualizar el aforo del evento, para reservar las plazas solicitadas",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
//Si se ha llenado ponemos el evento en SOLD_OUT
|
||||
if (eventToDiscountAssistants.confirmed == newAforo)
|
||||
await eventService._updateSoldOutEvent(eventToDiscountAssistants.id, true);
|
||||
|
||||
//Finalmente publicamos la reserva solo si no está asociada a la lista de espera
|
||||
if (!dataInscription.reservation.overflowEventId) {
|
||||
if (!(await eventReservationService._updatePublishReservation(dataInscription.reservation.id)))
|
||||
return handleResultResponse(
|
||||
"No se ha podido publicar la reserva del evento",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
dataInscription.reservation.state = "publish";
|
||||
return handleResultResponse(
|
||||
"No se ha podido publicar la reserva del evento",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
dataInscription.reservation.state = "publish";
|
||||
|
||||
//Mandamos el código de reserva para que registra a sus alumnos
|
||||
dataInscription.reservation.contact_email = dataUser.email;
|
||||
dataInscription.reservation.contact_name = dataUser.name;
|
||||
dataInscription.reservation.event = dataInscription.event;
|
||||
console.log('MANDAMOS CODIO RESERVA>>>>>>',dataInscription.reservation);
|
||||
|
||||
try{
|
||||
mailService.sendReservationEmail(dataInscription.reservation);
|
||||
}catch(error){
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
next();
|
||||
@ -331,15 +385,17 @@ const extraControllers = {
|
||||
createInscriptionReservation: async (req, res, next) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>> createInscriptionReservation (event_reservations.controller)");
|
||||
const params = extractParamsFromRequest(req, res, {});
|
||||
|
||||
let dataInscription = res.locals.dataInscription;
|
||||
if (!dataInscription || !dataInscription.event || !dataInscription.reservation)
|
||||
return handleResultResponse(
|
||||
"Error prepareInscription, recuperateEvent, recuperateReservationByCode o createReservationToEntity requerida",
|
||||
"Error prepareDataInscription, recuperateReservationByCode o createReservationToEntity requerida",
|
||||
null,
|
||||
params,
|
||||
res,
|
||||
httpStatus.NOT_FOUND
|
||||
);
|
||||
|
||||
let dataUser = res.locals.dataUser;
|
||||
if (!dataUser)
|
||||
return handleResultResponse("Error getOrCreateUser requerida", null, params, res, httpStatus.NOT_FOUND);
|
||||
@ -350,19 +406,24 @@ const extraControllers = {
|
||||
await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id);
|
||||
++dataInscription.inscriptionsWithReservationCount;
|
||||
|
||||
console.log(
|
||||
/*console.log(
|
||||
"me inscribo por reserva>>>>>>>>>>>>>>>>>>>>>>>>>>><< con asistentes: ",
|
||||
dataInscription.reservation.assistants
|
||||
dataInscription
|
||||
);
|
||||
console.log(dataInscription.reservation.sold_out);
|
||||
console.log(dataInscription.inscriptionsWithReservationCount);
|
||||
|
||||
*/
|
||||
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA
|
||||
if (
|
||||
dataInscription.reservation.sold_out == 0 &&
|
||||
dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount
|
||||
) {
|
||||
dataInscription.validated = true;
|
||||
|
||||
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>ESTA ES LA RESERVA>>>>>>>>>>>>>>>')
|
||||
//Es la inscripción automática del tutor o alguien que tiene el código y eso no puede ser
|
||||
if (dataInscription.reservation.state === 'publish')
|
||||
dataInscription.validated = true;
|
||||
|
||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", dataInscription.type);
|
||||
//Actualizamos aforo de la lista de espera de la reserva y creamos inscripcion en la lista de espera de la reserva
|
||||
if (
|
||||
@ -373,7 +434,7 @@ const extraControllers = {
|
||||
)
|
||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||
dataInscription.event.id,
|
||||
dataUser.userResult.user.id,
|
||||
dataUser.id,
|
||||
dataInscription.type,
|
||||
dataInscription.validated,
|
||||
dataInscription.source,
|
||||
@ -443,6 +504,17 @@ const extraControllers = {
|
||||
...Result,
|
||||
};
|
||||
|
||||
|
||||
// Incluimos correo en sendinblue
|
||||
try {
|
||||
// marketingListService.addMarketingList(dataUser, dataInscription);
|
||||
} catch(error){ console.log('Se ha producido un error al añadir a SenINBlue>>>>>>>>>>>>>>>>><<', error);}
|
||||
|
||||
//Mandamos correo con entrada o lista de espera
|
||||
try {
|
||||
mailService.sendEmailConfirm(dataUser, dataInscription);
|
||||
} catch(error){ console.log('Se ha producido un error al enviar mail>>>>>>>>>>>>>>>>><<', error);}
|
||||
|
||||
return handleResultResponse(Result, null, params, res, httpStatus.CREATED);
|
||||
} catch (error) {
|
||||
return handleResultResponse("Error al crear la incripción online", null, params, res, httpStatus.NOT_FOUND);
|
||||
|
||||
@ -168,6 +168,16 @@ const extraMethods = {
|
||||
return result.toUpperCase();
|
||||
},
|
||||
|
||||
_deleteReservation: (id) => {
|
||||
//habria que poner el idusuario para asegurar que otro usuario no borra una inscripcion de otro
|
||||
|
||||
return models.EventReservation.destroy({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
_getReservationsExcel: (user, eventId, partnerId, type, callback) => {
|
||||
console.log(">>>>>>>>>>>>>>>>>>>><consulta con type:", type);
|
||||
|
||||
|
||||
@ -1,28 +1,119 @@
|
||||
"use strict";
|
||||
|
||||
const lodash = require("lodash");
|
||||
const moment = require("moment");
|
||||
const QRHelper = require("../../helpers/qr.helper");
|
||||
const emailHelper = require("../../helpers/mail.helper");
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// dataInscription {incription:{...}, {..., event:{...}, reservation:{...}, user:{...}}
|
||||
////////////////////////////////////////////////////////////////////
|
||||
/*AHORA SE ALMACENA TODO EN UNA ÚNICA LISTA DE MAILCHIMP, QUE ES LA DEL EVENTO
|
||||
(si en un futuro se quiere tener listas independientes, bastaría con tratarlo aqui los campos de marketinglist de la reserva ...)
|
||||
if (dataInscription.inscription.reservationId)
|
||||
marketingListOfInscription = dataInscription.reservation.marketingList
|
||||
else if (dataInscription.inscription.overflowEventId)
|
||||
marketingListOfInscription = (await _getEvent(dataInscription.inscription.overflowEventId)).marketingList;
|
||||
else
|
||||
marketingListOfInscription = dataInscription.event.marketingList;
|
||||
*/
|
||||
function _generateMailDTO(dataInscription) {
|
||||
let inscriptionDTO = {};
|
||||
//console.log('*******ENTRO****', dataInscription);
|
||||
const inscription = dataInscription.inscription ? dataInscription.inscription : dataInscription;
|
||||
const event = dataInscription.event ? dataInscription.event : dataInscription.inscription.event;
|
||||
const reservation = dataInscription.reservation ? dataInscription.reservation : null;
|
||||
const user = dataInscription.user ? dataInscription.user : dataInscription.inscription.user;
|
||||
|
||||
if (inscription) {
|
||||
inscriptionDTO.id = inscription.id;
|
||||
inscriptionDTO.source = inscription.source;
|
||||
inscriptionDTO.event_name = event ? event.name : "N/A";
|
||||
inscriptionDTO.event_date = event ? event.init_date : "N/A";
|
||||
inscriptionDTO.event_marketing_list = event ? event.marketing_list : null;
|
||||
inscriptionDTO.date_inscription = inscription.date;
|
||||
inscriptionDTO.code_ticket = inscription.code_ticket;
|
||||
inscriptionDTO.validated = inscription.validated;
|
||||
inscriptionDTO.type = inscription.type; // inscription.tipoEntrada ? inscription.tipoEntrada : inscription.type;
|
||||
|
||||
inscriptionDTO.reservation_code = reservation ? reservation.reservation_code : null;
|
||||
inscriptionDTO.color = reservation ? reservation.color : null;
|
||||
inscriptionDTO.description = ((reservation ? reservation.description : "Entrada").toUpperCase() + (lodash.words(inscription.type).includes("online")? " online" : ""));
|
||||
inscriptionDTO.qrConfig= null;
|
||||
inscriptionDTO.qrCode= null;
|
||||
|
||||
if (user) {
|
||||
//Era para mailchimp
|
||||
/// inscriptionDTO.marketing_memberId = inscription.marketing_memberId ? inscription.marketing_memberId : null;
|
||||
inscriptionDTO.email = user.email;
|
||||
inscriptionDTO.name = user.name;
|
||||
inscriptionDTO.surname = user.surname;
|
||||
inscriptionDTO.userId = user.id;
|
||||
inscriptionDTO.entity = reservation && reservation.Entity ? reservation.Entity.name : (user.Entity ? user.Entity.name : user.entityId);
|
||||
};
|
||||
|
||||
}
|
||||
console.log('*******SALGO****', inscriptionDTO);
|
||||
return inscriptionDTO;
|
||||
}
|
||||
|
||||
function generateHeaderMail(member) {
|
||||
let headerMail = null;
|
||||
let AsuntoOnline = lodash.words(member.type).includes("online") ? "Inscripción online" : "";
|
||||
let AsuntoOnsite = member.validated ? "Entrada" : "Lista de espera";
|
||||
|
||||
if (member) {
|
||||
headerMail = {
|
||||
to: member.email,
|
||||
name: member.name + " " + member.surname,
|
||||
subject:
|
||||
(member.validated ? "Entrada" : "Lista de espera") + " para el congreso " + member.event_name + " confirmada",
|
||||
((AsuntoOnline === "") ? AsuntoOnsite : AsuntoOnline) + " para el congreso " + member.event_name + " confirmada",
|
||||
};
|
||||
}
|
||||
|
||||
return headerMail;
|
||||
}
|
||||
|
||||
function generateBodyMail(member) {
|
||||
function generateHeaderMailReservation(reservation) {
|
||||
let headerMail = null;
|
||||
if (reservation) {
|
||||
headerMail = {
|
||||
to: reservation.Entity ? reservation.Entity.contact_email : reservation.contact_email,
|
||||
name: reservation.Entity ? reservation.Entity.name : reservation.contact_name,
|
||||
bcc: "cbarrantes@loquedeverdadimporta.org",
|
||||
bccName: "Carolina Barrantes",
|
||||
subject: "Códigos de invitación para congreso LQDVI",
|
||||
};
|
||||
}
|
||||
console.log('generateHeaderMailReservation>>>>>>>', headerMail);
|
||||
return headerMail;
|
||||
}
|
||||
|
||||
function generateBodyMailReservation(reservation) {
|
||||
console.log('generateBodyMailReservation>>>>>>>', reservation);
|
||||
const event = reservation.Event ? reservation.Event : reservation.event;
|
||||
let bodyMail = null;
|
||||
if (reservation) {
|
||||
bodyMail = {
|
||||
entityName: reservation.Entity? reservation.Entity.name : reservation.contact_name,
|
||||
eventName: event.name,
|
||||
dateEvent: moment(event.init_date).format("D [de] MMMM [de] YYYY"),
|
||||
reservationCode: reservation.reservation_code,
|
||||
reservationDescription: reservation.description,
|
||||
};
|
||||
}
|
||||
console.log('generateBodyMailReservation>>>>>>>', bodyMail);
|
||||
return bodyMail;
|
||||
}
|
||||
|
||||
function generateBodyMail(member) {
|
||||
//console.log('>>>generateBodyMail>>>>> ', member);
|
||||
let bodyMail = null;
|
||||
let tipoEntrada = lodash.words(member.type).includes("online") ? "Inscripción online confirmada" : (member.validated ? "Entrada" : "Lista de espera");
|
||||
|
||||
if (member) {
|
||||
bodyMail = {
|
||||
tipoEntrada: member.validated ? "Entrada" : "Lista de espera",
|
||||
tipoEntrada: tipoEntrada,
|
||||
descriptionEntrada: member.description,
|
||||
qrCode: member.qrCode,
|
||||
qrCodeUrl: member.qrCodeUrl,
|
||||
@ -33,10 +124,58 @@ function generateBodyMail(member) {
|
||||
dateInscription: moment(member.date_inscription).format("DD/MM/YY HH:mm "),
|
||||
};
|
||||
}
|
||||
//console.log('>>>retunr>>>>> ', bodyMail);
|
||||
return bodyMail;
|
||||
}
|
||||
|
||||
|
||||
async function sendEmailConfirm(dataUser, dataInscription) {
|
||||
dataInscription.user = dataUser.userResult.user;
|
||||
const isOnline = lodash.words(dataInscription.type).includes("online");
|
||||
let mailDTO = _generateMailDTO(dataInscription);
|
||||
|
||||
mailDTO.qrConfig = QRHelper.generateQRConfig(mailDTO);
|
||||
mailDTO.qrCode = await QRHelper.getInscriptionQRCode(mailDTO.qrConfig);
|
||||
mailDTO.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
|
||||
|
||||
console.log("Mandamos mail con entrada>>>>>>>>>>>>>>>>>>>>>>>>>>>");
|
||||
//console.log(headerMail, bodyMail);
|
||||
|
||||
try {
|
||||
if (isOnline)
|
||||
emailHelper.sendTicketOnline(generateHeaderMail(mailDTO), generateBodyMail(mailDTO))
|
||||
else
|
||||
if (dataInscription.inscription.validated)
|
||||
emailHelper.sendTicket(generateHeaderMail(mailDTO), generateBodyMail(mailDTO));
|
||||
else
|
||||
emailHelper.sendListaEspera(generateHeaderMail(mailDTO), generateBodyMail(mailDTO));
|
||||
} catch (error) {
|
||||
console.log("No se ha podido mandar email con entrada");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function sendEmailCancelate(inscription) {
|
||||
let mailDTO = _generateMailDTO(inscription);
|
||||
|
||||
mailDTO.qrConfig = QRHelper.generateQRConfig(mailDTO);
|
||||
mailDTO.qrCode = await QRHelper.getInscriptionQRCode(mailDTO.qrConfig);
|
||||
mailDTO.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
||||
let headerMail = generateHeaderMail(mailDTO);
|
||||
headerMail.subject = "Cancelación de " + headerMail.subject;
|
||||
|
||||
console.log("Mandamos mail con la cancelacion>>>>>>>>>>>>>>>>>>>>>>>>>>>");
|
||||
try {
|
||||
emailHelper.sendCancelacion(headerMail, generateBodyMail(mailDTO));
|
||||
} catch (error) {console.log("No se ha podido mandar email con cancelación")};
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
async function _sendInscriptionEmail(dataInscription, member) {
|
||||
let mailDTO = _generateMailDTO(inscription);
|
||||
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
|
||||
@ -51,3 +190,23 @@ async function _sendInscriptionEmail(dataInscription, member) {
|
||||
console.log("No se ha podido mandar email con entrada");
|
||||
}
|
||||
}
|
||||
|
||||
async function sendReservationEmail(reservation) {
|
||||
try {
|
||||
emailHelper.sendReservationCode(generateHeaderMailReservation(reservation), generateBodyMailReservation(reservation));
|
||||
} catch (error) {
|
||||
console.log("No se ha podido mandar email _sendReservationEmail", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
module.exports = {
|
||||
sendEmailConfirm,
|
||||
sendEmailCancelate,
|
||||
sendReservationEmail,
|
||||
generateHeaderMail,
|
||||
generateHeaderMailReservation,
|
||||
generateBodyMail,
|
||||
generateBodyMailReservation,
|
||||
};
|
||||
|
||||
|
||||
@ -1,34 +1,11 @@
|
||||
"use strict";
|
||||
|
||||
const eventInscriptionService = require("./events_inscriptions.service");
|
||||
const marketing = require("../../helpers/sendinblue.helper");
|
||||
|
||||
function generateMemberInscription2(user, datainscription) {
|
||||
let memberInscription = null;
|
||||
if (user && datainscription.inscription) {
|
||||
memberInscription = {
|
||||
marketing_memberId: null,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
surname: user.surname,
|
||||
source: datainscription.inscription.source,
|
||||
event_name: datainscription.inscription.event ? datainscription.inscription.event.name : "N/A",
|
||||
event_date: datainscription.inscription.event ? datainscription.inscription.event.init_date : "N/A",
|
||||
reservation_code: datainscription.reservation ? datainscription.reservation.reservation_code : null,
|
||||
date_inscription: datainscription.inscription.date,
|
||||
code_ticket: datainscription.inscription.code_ticket,
|
||||
validated: datainscription.inscription.validated,
|
||||
color: datainscription.reservation ? datainscription.reservation.color : null,
|
||||
description: (datainscription.reservation ? datainscription.reservation.description : "Entrada").toUpperCase(),
|
||||
entity: datainscription.reservation ? datainscription.reservation.Entity.name : user.entityId,
|
||||
userId: user.id,
|
||||
qrConfig: null,
|
||||
qrCode: null,
|
||||
};
|
||||
}
|
||||
return memberInscription;
|
||||
}
|
||||
|
||||
async function _addMarketingList(dataUser, dataInscription) {
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// dataInscription {incription:{...}, {..., event:{...}, reservation:{...}, user:{...}}
|
||||
////////////////////////////////////////////////////////////////////
|
||||
/*AHORA SE ALMACENA TODO EN UNA ÚNICA LISTA DE MAILCHIMP, QUE ES LA DEL EVENTO
|
||||
(si en un futuro se quiere tener listas independientes, bastaría con tratarlo aqui los campos de marketinglist de la reserva ...)
|
||||
if (dataInscription.inscription.reservationId)
|
||||
@ -38,25 +15,130 @@ async function _addMarketingList(dataUser, dataInscription) {
|
||||
else
|
||||
marketingListOfInscription = dataInscription.event.marketingList;
|
||||
*/
|
||||
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
||||
let member = generateMemberInscription2(dataUser.userResult.user, dataInscription);
|
||||
//Meter esto en el servicio
|
||||
//En este caso al ser una inscripcion recien creada hay que asignar los datos del evento desde el evento
|
||||
//member.event_name = dataInscription.event.name;
|
||||
//member.event_date = dataInscription.event.init_date;
|
||||
function _generateMarketingDTO(dataInscription) {
|
||||
let inscriptionDTO = {};
|
||||
|
||||
try {
|
||||
member.marketing_memberId = await eventInscriptionService._addMember(dataInscription.event.marketing_list, member);
|
||||
eventInscriptionService._updateMarketingMemberOfInscription(
|
||||
dataInscription.inscription.id,
|
||||
member.marketing_memberId
|
||||
let inscription = dataInscription.inscription ? dataInscription.inscription : dataInscription;
|
||||
|
||||
console.log('entro>>>', inscription);
|
||||
if (inscription) {
|
||||
inscriptionDTO.id = inscription.id;
|
||||
inscriptionDTO.source = inscription.source;
|
||||
inscriptionDTO.event_name = inscription.event ? inscription.event.name : "N/A";
|
||||
inscriptionDTO.event_date = inscription.event ? inscription.event.init_date : "N/A";
|
||||
inscriptionDTO.event_marketing_list = inscription.event ? inscription.event.marketing_list : null;
|
||||
inscriptionDTO.date_inscription = inscription.date;
|
||||
inscriptionDTO.code_ticket = inscription.code_ticket;
|
||||
inscriptionDTO.validated = inscription.validated;
|
||||
|
||||
inscriptionDTO.reservation_code = inscription.reservation ? inscription.reservation.reservation_code : null;
|
||||
inscriptionDTO.color = inscription.reservation ? inscription.reservation.color : null;
|
||||
inscriptionDTO.description = (inscription.reservation ? inscription.reservation.description : "Entrada").toUpperCase();
|
||||
inscriptionDTO.qrConfig= null;
|
||||
inscriptionDTO.qrCode= null;
|
||||
|
||||
if (inscription.user) {
|
||||
//Era para mailchimp
|
||||
/// inscriptionDTO.marketing_memberId = inscription.marketing_memberId ? inscription.marketing_memberId : null;
|
||||
inscriptionDTO.email = inscription.user.email;
|
||||
inscriptionDTO.name = inscription.user.name;
|
||||
inscriptionDTO.surname = inscription.user.surname;
|
||||
inscriptionDTO.userId = inscription.user.id;
|
||||
inscriptionDTO.entity = inscription.reservation && inscription.reservation.Entity ? inscription.reservation.Entity.name : (inscription.user.Entity ? inscription.user.Entity.name : inscription.user.entityId);
|
||||
};
|
||||
|
||||
}
|
||||
console.log('salgo>>>', inscriptionDTO);
|
||||
return inscriptionDTO;
|
||||
}
|
||||
|
||||
function sleep(time) {
|
||||
return new Promise((resolve) => setTimeout(resolve, time));
|
||||
}
|
||||
|
||||
|
||||
async function _addMember (inscriptionDTO) {
|
||||
console.debug('>>>> _addMember', inscriptionDTO.email);
|
||||
console.debug('>>>> event_marketing_list', inscriptionDTO.event_marketing_list);
|
||||
// console.debug(member);
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (!inscriptionDTO.event_marketing_list) {
|
||||
// || !member.validated) {
|
||||
resolve(inscriptionDTO);
|
||||
} else {
|
||||
marketing
|
||||
.addMember(inscriptionDTO.event_marketing_list, inscriptionDTO)
|
||||
.then(function (result) {
|
||||
resolve(result.ID);
|
||||
})
|
||||
.catch(function (error) {
|
||||
reject(error);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function _deleteMember (idLista, email) {
|
||||
console.debug(
|
||||
"Elimino miembro de la lista de marketing>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<",
|
||||
email,
|
||||
idLista,
|
||||
);
|
||||
return member;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (!idLista || !email) {
|
||||
resolve();
|
||||
} else {
|
||||
resolve(marketing.deleteMember(idLista, email));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function addMarketingList(dataUser, dataInscription) {
|
||||
dataInscription.user = dataUser.userResult.user;
|
||||
return _addMember(_generateMarketingDTO(dataInscription));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
async function syncronizeEventWithMarketingList (eventId) {
|
||||
let result = false;
|
||||
try {
|
||||
let inscriptionsToSync = await eventInscriptionService._getInscriptionsWithoutMemberId(eventId);
|
||||
|
||||
|
||||
for (var i = 0; i < inscriptionsToSync.length; i++) {
|
||||
const item = inscriptionsToSync[i].get({
|
||||
plain: true
|
||||
});
|
||||
|
||||
sleep(1000 * i).then(function () {
|
||||
let inscriptionDTO = _addMember(_generateMarketingDTO(item));
|
||||
// let marketingDTO = _generateMarketingDTO(item);
|
||||
// console.log(marketingDTO)
|
||||
// _deleteMember(marketingDTO.event_marketing_list, marketingDTO.email)
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
result = true;
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.log("No se ha podido añadir email a mailchimp");
|
||||
console.log("No se ha podido _syncronizeEventWithMarketingList", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
module.exports = {
|
||||
addMarketingList: _addMarketingList,
|
||||
syncronizeEventWithMarketingList,
|
||||
addMarketingList,
|
||||
_deleteMember,
|
||||
_generateMarketingDTO,
|
||||
|
||||
};
|
||||
|
||||
@ -245,17 +245,19 @@ const extraControllers = {
|
||||
|
||||
try {
|
||||
const context = buildContext(req, config);
|
||||
var data = {
|
||||
const userId = context.user && context.user.id ? context.user.id : null;
|
||||
|
||||
let data = {
|
||||
token: req.body.token,
|
||||
valid: 1,
|
||||
userId: context.user.id
|
||||
userId
|
||||
};
|
||||
|
||||
let params = extractParamsFromRequest(req, res, {
|
||||
includeAll: false,
|
||||
paginate: { limit: 1, page: 1 },
|
||||
params: {
|
||||
userId: context.user.id,
|
||||
//userId,
|
||||
token: data.token,
|
||||
}
|
||||
});
|
||||
|
||||
@ -56,7 +56,7 @@ routes.post('/admin/notifications',
|
||||
);*/
|
||||
|
||||
routes.post('/notifications/devices',
|
||||
isLoggedUser,
|
||||
//isLoggedUser,
|
||||
SchemaValidator(deviceTokenInputType, true),
|
||||
notificationController.registerDevice()
|
||||
);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user