fix conflicts and rework routes

This commit is contained in:
Adrian Thompson
2020-09-07 14:49:24 +02:00
27 changed files with 6208 additions and 4055 deletions

View File

@@ -1,21 +1,13 @@
const express = require('express');
const path = require('path');
const router = express.Router();
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/vinlottis', {
useNewUrlParser: true
})
const mustBeAuthenticated = require(path.join(
__dirname + '/../middleware/mustBeAuthenticated'
));
const config = require(path.join(__dirname + '/../config/defaults/lottery'));
const Highscore = require(path.join(__dirname + '/../schemas/Highscore'));
const Wine = require(path.join(__dirname + '/../schemas/Wine'));
// Utils
const epochToDateString = date => new Date(parseInt(date)).toDateString();
@@ -62,7 +54,7 @@ const resolveWineReferences = listWithWines => {
}
// Routes
router.route('/all').get((req, res) => {
const all = (req, res) => {
return Highscore.find()
.then(highscore => getHighscoreByDates(highscore))
.then(groupedLotteries => groupedHighscoreToSortedList(groupedLotteries))
@@ -70,9 +62,19 @@ router.route('/all').get((req, res) => {
message: "Lotteries by date!",
lotteries
}))
})
}
router.route('/by-date/:date').get((req, res) => {
const latest = (req, res) => {
return Highscore.find()
.then(highscore => getHighscoreByDates(highscore))
.then(groupedLotteries => groupedHighscoreToSortedList(groupedLotteries))
.then(lotteries => res.send({
message: "Latest lottery!",
lottery: lotteries.slice(-1).pop()
}))
}
const byEpochDate = (req, res) => {
const { date } = req.params;
const dateString = epochToDateString(date);
@@ -92,10 +94,10 @@ router.route('/by-date/:date').get((req, res) => {
})
}
})
})
}
router.route("/by-name").get((req, res) => {
const { name } = req.query;
const byName = (req, res) => {
const { name } = req.params;
return Highscore.find({ name })
.then(async (highscore) => {
@@ -113,6 +115,11 @@ router.route("/by-name").get((req, res) => {
})
}
})
})
}
module.exports = router;
module.exports = {
all,
latest,
byEpochDate,
byName
};

View File

@@ -1,92 +1,109 @@
const request = require("request");
const https = require("https");
const path = require("path");
const config = require(path.join(__dirname + "/../config/defaults/lottery"));
async function sendMessage(winnerObject) {
async function sendWineSelectMessage(winnerObject) {
winnerObject.timestamp_sent = new Date().getTime();
winnerObject.timestamp_limit = new Date().getTime() * 600000;
await winnerObject.save();
let url = new URL(`/#/winner/${winnerObject.id}`, "https://lottis.vin");
await sendMessageToUser(
return sendMessageToUser(
winnerObject.phoneNumber,
`Gratulerer som heldig vinner av vinlotteriet ${winnerObject.name}! Her er linken for å velge hva slags vin du vil ha, du har 10 minutter på å velge ut noe før du blir lagt bakerst i køen. ${url.href}. (Hvis den siden kommer opp som tom må du prøve å refreshe siden noen ganger.)`
);
return true;
)
}
async function sendWonWineMessage(winnerObject, wineObject) {
console.log(
`User ${winnerObject.id} is only one left, chosing wine for him/her.`
);
async function sendLastWinnerMessage(winnerObject, wineObject) {
console.log(`User ${winnerObject.id} is only one left, chosing wine for him/her.`);
winnerObject.timestamp_sent = new Date().getTime();
winnerObject.timestamp_limit = new Date().getTime();
await winnerObject.save();
await sendMessageToUser(
return sendMessageToUser(
winnerObject.phoneNumber,
`Gratulerer som heldig vinner av vinlotteriet ${winnerObject.name}! Du har vunnet vinen ${wineObject.name}, og vil få nærmere info om hvordan/hvor du kan hente vinen snarest. Ha en ellers fin helg!`
);
return true;
}
async function sendMessageTooLate(winnerObject) {
await sendMessageToUser(
async function sendWineSelectMessageTooLate(winnerObject) {
return sendMessageToUser(
winnerObject.phoneNumber,
`Hei ${winnerObject.name}, du har dessverre brukt mer enn 10 minutter på å velge premie og blir derfor puttet bakerst i køen. Du vil få en ny SMS når det er din tur igjen.`
);
}
async function sendMessageToUser(phoneNumber, message) {
try {
request.post(
{
url: `https://gatewayapi.com/rest/mtsms?token=${config.gatewayToken}`,
json: true,
body: {
sender: "Vinlottis",
message: message,
recipients: [{ msisdn: `47${phoneNumber}` }]
}
},
function(err, r, body) {
console.log(err ? err : body);
if(err) {
console.log(phoneNumber, message);
}
}
);
} catch(e) {
console.log(phoneNumber, message);
}
console.log(`Attempting to send message to ${ phoneNumber }.`)
const body = {
sender: "Vinlottis",
message: message,
recipients: [{ msisdn: `47${ phoneNumber }`}]
};
return gatewayRequest(body);
}
async function sendUpdate(winners) {
async function sendInitialMessageToWinners(winners) {
let numbers = [];
for (let i = 0; i < winners.length; i++) {
numbers.push({ msisdn: `47${winners[i].phoneNumber}` });
}
request.post(
{
url: `https://gatewayapi.com/rest/mtsms?token=${config.gatewayToken}`,
json: true,
body: {
sender: "Vinlottis",
message:
"Gratulerer som vinner av vinlottisen! Du vil snart få en SMS med oppdatering om hvordan gangen går!",
recipients: numbers
}
},
function(err, r, body) {
console.log(err ? err : body);
}
);
const body = {
sender: "Vinlottis",
message:
"Gratulerer som vinner av vinlottisen! Du vil snart få en SMS med oppdatering om hvordan gangen går!",
recipients: numbers
}
return gatewayRequest(body);
}
module.exports.sendUpdate = sendUpdate;
module.exports.sendMessage = sendMessage;
module.exports.sendMessageTooLate = sendMessageTooLate;
module.exports.sendWonWineMessage = sendWonWineMessage;
async function gatewayRequest(body) {
return new Promise((resolve, reject) => {
const options = {
hostname: "gatewayapi.com",
post: 443,
path: `/rest/mtsms?token=${ config.gatewayToken }`,
method: "POST",
headers: {
"Content-Type": "application/json"
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${ res.statusCode }`);
console.log(`statusMessage: ${ res.statusMessage }`);
res.setEncoding('utf8');
if (res.statusCode == 200) {
res.on("data", (d) => resolve(JSON.parse(d)));
} else {
res.on("data", (data) => {
data = JSON.parse(data);
return reject('Gateway error: ' + data['message'] || data)
});
}
})
req.on("error", (error) => {
console.error(`Error from sms service: ${ error }`);
reject(`Error from sms service: ${ error }`);
})
req.write(JSON.stringify(body));
req.end();
});
}
module.exports = {
sendWineSelectMessage,
sendLastWinnerMessage,
sendWineSelectMessageTooLate,
sendInitialMessageToWinners
}

View File

@@ -1,43 +1,41 @@
const express = require("express");
const path = require("path");
const router = express.Router();
const fetch = require('node-fetch');
const { send } = require("process");
const RequestedWine = require(path.join(
__dirname + "/../schemas/RequestedWine"
));
const Wine = require(path.join(
__dirname + "/../schemas/Wine"
));
const mustBeAuthenticated = require(path.join(
__dirname + "/../middleware/mustBeAuthenticated"
));
router.use((req, res, next) => {
next();
});
const deleteRequestedWineById = async (req, res) => {
const { id } = req.params;
if(id == null){
return res.json({
message: "Id er ikke definert",
success: false
})
}
router.route("/request/").delete(mustBeAuthenticated, async (req, res) => {
await RequestedWine.deleteOne({wineId: req.body.id})
res.json(true);
})
await RequestedWine.deleteOne({wineId: id})
return res.json({
message: `Slettet vin med id: ${id}`,
success: true
});
}
router.route("/request").get(async (req, res) => {
const rWines = await RequestedWine.find({}).populate("wine")
return res.send(rWines)
})
router.route("/request/all").get(async (req, res) => {
const getAllRequestedWines = async (req, res) => {
const allWines = await RequestedWine.find({}).populate("wine");
return res.json(allWines);
}
res.json(allWines);
});
router.route("/request").post(async (req, res) => {
const requestNewWine = async (req, res) => {
const {wine} = req.body
console.log(req.body)
let thisWineIsLOKO = await Wine.findOne({id: wine.id})
if(thisWineIsLOKO == undefined){
thisWineIsLOKO = new Wine({
name: wine.name,
@@ -49,7 +47,7 @@ router.route("/request").post(async (req, res) => {
});
await thisWineIsLOKO.save()
}
let requestedWine = await RequestedWine.findOne({ "wineId": wine.id})
if(requestedWine == undefined){
@@ -62,9 +60,12 @@ router.route("/request").post(async (req, res) => {
requestedWine.count += 1;
}
await requestedWine.save()
return res.send(requestedWine);
}
res.send(requestedWine);
});
module.exports = router;
module.exports = {
requestNewWine,
getAllRequestedWines,
deleteRequestedWineById
};

View File

@@ -1,6 +1,6 @@
const express = require("express");
const path = require("path");
const router = express.Router();
// const router = express.Router();
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/vinlottis", {
useNewUrlParser: true
@@ -13,23 +13,19 @@ const PreLotteryWine = require(path.join(
__dirname + "/../schemas/PreLotteryWine"
));
router.use((req, res, next) => {
next();
});
router.route("/wines/prelottery").get(async (req, res) => {
const prelotteryWines = async (req, res) => {
let wines = await PreLotteryWine.find();
res.json(wines);
});
return res.json(wines);
};
router.route("/purchase/statistics").get(async (req, res) => {
const allPurchase = async (req, res) => {
let purchases = await Purchase.find()
.populate("wines")
.sort({ date: 1 });
res.json(purchases);
});
return res.json(purchases);
};
router.route("/purchase/statistics/color").get(async (req, res) => {
const purchaseByColor = async (req, res) => {
const countColor = await Purchase.find();
let red = 0;
let blue = 0;
@@ -75,7 +71,7 @@ router.route("/purchase/statistics/color").get(async (req, res) => {
const total = red + yellow + blue + green;
res.json({
return res.json({
red: {
total: red,
win: redWin
@@ -95,22 +91,21 @@ router.route("/purchase/statistics/color").get(async (req, res) => {
stolen: stolen,
total: total
});
});
};
router.route("/highscore/statistics").get(async (req, res) => {
const highscore = async (req, res) => {
const highscore = await Highscore.find().populate("wins.wine");
res.json(highscore);
});
return res.json(highscore);
};
router.route("/wines/statistics").get(async (req, res) => {
const allWines = async (req, res) => {
const wines = await Wine.find();
res.json(wines);
});
return res.json(wines);
};
router.route("/wines/statistics/overall").get(async (req, res) => {
const allWinesSummary = async (req, res) => {
const highscore = await Highscore.find().populate("wins.wine");
let wines = {};
@@ -150,7 +145,14 @@ router.route("/wines/statistics/overall").get(async (req, res) => {
}
}
res.json(Object.values(wines));
});
return res.json(Object.values(wines));
};
module.exports = router;
module.exports = {
prelotteryWines,
allPurchase,
purchaseByColor,
highscore,
allWines,
allWinesSummary
};

69
api/router.js Normal file
View File

@@ -0,0 +1,69 @@
const express = require("express");
const path = require("path");
// Middleware
const mustBeAuthenticated = require(__dirname + "/../middleware/mustBeAuthenticated");
const update = require(path.join(__dirname + "/update"));
const retrieve = require(path.join(__dirname + "/retrieve"));
const request = require(path.join(__dirname + "/request"));
const subscriptionApi = require(path.join(__dirname + "/subscriptions"));
const loginApi = require(path.join(__dirname + "/login"));
const wineinfo = require(path.join(__dirname + "/wineinfo"));
const virtualApi = require(path.join(__dirname + "/virtualLottery"));
const virtualRegistrationApi = require(path.join(
__dirname + "/virtualRegistration"
));
const lottery = require(path.join(__dirname + "/lottery"));
const router = express.Router();
router.get("/wineinfo/search", wineinfo.wineSearch);
router.get("/request/all", request.getAllRequestedWines);
router.post("/request/new-wine", request.requestNewWine);
router.delete("/request/:id", request.deleteRequestedWineById);
router.get("/wineinfo/schema", mustBeAuthenticated, update.schema);
router.get("/wineinfo/:ean", wineinfo.byEAN);
router.post("/log/wines", mustBeAuthenticated, update.submitWines);
router.post("/lottery", update.submitLottery);
router.post("/lottery/wines", update.submitWinesToLottery);
// router.delete("/lottery/wine/:id", update.deleteWineFromLottery);
router.post("/lottery/winners", update.submitWinnersToLottery);
router.get("/wines/prelottery", retrieve.prelotteryWines);
router.get("/purchase/statistics", retrieve.allPurchase);
router.get("/purchase/statistics/color", retrieve.purchaseByColor);
router.get("/highscore/statistics", retrieve.highscore)
router.get("/wines/statistics", retrieve.allWines);
router.get("/wines/statistics/overall", retrieve.allWinesSummary);
router.get("/lottery/all", lottery.all);
router.get("/lottery/latest", lottery.latest);
router.get("/lottery/by-date/:date", lottery.byEpochDate);
router.get("/lottery/by-name/:name", lottery.byName);
router.delete('/virtual/winner/all', mustBeAuthenticated, virtualApi.deleteWinners);
router.delete('/virtual/attendee/all', mustBeAuthenticated, virtualApi.deleteAttendees);
router.get('/virtual/winner/draw', virtualApi.drawWinner);
router.get('/virtual/winner/all', virtualApi.winners);
router.get('/virtual/winner/all/secure', mustBeAuthenticated, virtualApi.winnersSecure);
router.post('/virtual/finish', mustBeAuthenticated, virtualApi.finish);
router.get('/virtual/attendee/all', virtualApi.attendees);
router.get('/virtual/attendee/all/secure', mustBeAuthenticated, virtualApi.attendeesSecure);
router.post('/virtual/attendee/add', mustBeAuthenticated, virtualApi.addAttendee);
router.post('/winner/notify/:id', virtualRegistrationApi.sendNotificationToWinnerById);
router.get('/winner/:id', virtualRegistrationApi.getWinesToWinnerById);
router.post('/winner/:id', virtualRegistrationApi.registerWinnerSelection);
// router.use("/api/", updateApi);
// router.use("/api/", retrieveApi);
// router.use("/api/", wineinfoApi);
// router.use("/api/lottery", lottery);
// router.use("/virtual-registration/", virtualRegistrationApi);
module.exports = router;

View File

@@ -1,29 +1,21 @@
const express = require("express");
const path = require("path");
const router = express.Router();
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/vinlottis", {
useNewUrlParser: true
});
const sub = require(path.join(__dirname + "/../api/subscriptions"));
const mustBeAuthenticated = require(path.join(
__dirname + "/../middleware/mustBeAuthenticated"
));
const _wineFunctions = require(path.join(__dirname + "/../api/wine"));
const _personFunctions = require(path.join(__dirname + "/../api/person"));
const Subscription = require(path.join(__dirname + "/../schemas/Subscription"));
const Purchase = require(path.join(__dirname + "/../schemas/Purchase"));
const Lottery = require(path.join(__dirname + "/../schemas/Purchase"));
const PreLotteryWine = require(path.join(
__dirname + "/../schemas/PreLotteryWine"
));
router.use((req, res, next) => {
next();
});
router.route("/log/wines").post(mustBeAuthenticated, async (req, res) => {
const submitWines = async (req, res) => {
const wines = req.body;
for (let i = 0; i < wines.length; i++) {
let wine = wines[i];
@@ -40,69 +32,115 @@ router.route("/log/wines").post(mustBeAuthenticated, async (req, res) => {
}
let subs = await Subscription.find();
console.log("Sending new wines w/ push notification to all subscribers.")
for (let i = 0; i < subs.length; i++) {
let subscription = subs[i]; //get subscription from your databse here.
const message = JSON.stringify({
message: "Dagens vin er lagt til, se den på lottis.vin/dagens!",
title: "Ny vin!",
link: "/#/dagens"
});
sub.sendNotification(subscription, message);
try {
sub.sendNotification(subscription, message);
} catch (error) {
console.error("Error when trying to send push notification to subscriber.");
console.error(error);
}
}
res.send(true);
});
return res.send({
message: "Submitted and notified push subscribers of new wines!",
success: true
});
};
router.route("/log/schema").get(mustBeAuthenticated, async (req, res) => {
const schema = async (req, res) => {
let schema = { ...PreLotteryWine.schema.obj };
let nulledSchema = Object.keys(schema).reduce((accumulator, current) => {
accumulator[current] = "";
return accumulator;
return accumulator
}, {});
res.send(nulledSchema);
});
return res.send(nulledSchema);
}
router.route("/log").post(mustBeAuthenticated, async (req, res) => {
await PreLotteryWine.deleteMany();
// TODO IMPLEMENT WITH FRONTEND (unused)
const submitWinesToLottery = async (req, res) => {
const { lottery } = req.body;
const { date, wines } = lottery;
const wineObjects = await Promise.all(wines.map(async (wine) => await _wineFunctions.findSaveWine(wine)))
const purchaseBody = req.body.purchase;
const winnersBody = req.body.winners;
return Lottery.findOneAndUpdate({ date: date }, {
date: date,
wines: wineObjects
}, {
upsert: true
}).then(_ => res.send(true))
.catch(err => res.status(500).send({ message: 'Unexpected error while updating/saving wine to lottery.',
success: false,
exception: err.message }));
}
const date = purchaseBody.date;
const blue = purchaseBody.blue;
const red = purchaseBody.red;
const yellow = purchaseBody.yellow;
const green = purchaseBody.green;
/**
* @apiParam (Request body) {Array} winners List of winners
*/
const submitWinnersToLottery = async (req, res) => {
const { lottery } = req.body;
const { winners, date } = lottery;
const bought = purchaseBody.bought;
const stolen = purchaseBody.stolen;
const winesThisDate = [];
for (let i = 0; i < winnersBody.length; i++) {
let currentWinner = winnersBody[i];
let wonWine = await _wineFunctions.findSaveWine(currentWinner);
winesThisDate.push(wonWine);
await _personFunctions.findSavePerson(currentWinner, wonWine, date);
for (let i = 0; i < winners.length; i++) {
let currentWinner = winners[i];
let wonWine = await _wineFunctions.findSaveWine(currentWinner.wine); // TODO rename to findAndSaveWineToLottery
await _personFunctions.findSavePerson(currentWinner, wonWine, date); // TODO rename to findAndSaveWineToPerson
}
let purchase = new Purchase({
date: date,
blue: blue,
yellow: yellow,
red: red,
green: green,
wines: winesThisDate,
bought: bought,
stolen: stolen
});
return res.json(true);
}
await purchase.save();
/**
* @apiParam (Request body) {Date} date Date of lottery
* @apiParam (Request body) {Number} blue Number of blue tickets
* @apiParam (Request body) {Number} red Number of red tickets
* @apiParam (Request body) {Number} green Number of green tickets
* @apiParam (Request body) {Number} yellow Number of yellow tickets
* @apiParam (Request body) {Number} bought Number of tickets bought
* @apiParam (Request body) {Number} stolen Number of tickets stolen
*/
const submitLottery = async (req, res) => {
const { lottery } = req.body
res.send(true);
});
const { date,
blue,
red,
yellow,
green,
bought,
stolen } = lottery;
module.exports = router;
return Lottery.findOneAndUpdate({ date: date }, {
date: date,
blue: blue,
yellow: yellow,
red: red,
green: green,
bought: bought,
stolen: stolen
}, {
upsert: true
}).then(_ => res.send(true))
.catch(err => res.status(500).send({ message: 'Unexpected error while updating/saving lottery.',
success: false,
exception: err.message }));
return res.send(true);
};
module.exports = {
submitWines,
schema,
submitLottery,
submitWinnersToLottery,
submitWinesToLottery
};

View File

@@ -1,44 +1,16 @@
const express = require("express");
const path = require("path");
const router = express.Router();
const crypto = require("crypto");
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/vinlottis", {
useNewUrlParser: true
});
let io;
const mustBeAuthenticated = require(path.join(
__dirname + "/../middleware/mustBeAuthenticated"
));
const config = require(path.join(__dirname + "/../config/defaults/lottery"));
const Message = require(path.join(__dirname + "/message"));
const { findAndNotifyNextWinner } = require(path.join(__dirname + "/virtualRegistration"));
const Attendee = require(path.join(__dirname + "/../schemas/Attendee"));
const VirtualWinner = require(path.join(
__dirname + "/../schemas/VirtualWinner"
));
const PreLotteryWine = require(path.join(
__dirname + "/../schemas/PreLotteryWine"
));
const VirtualWinner = require(path.join(__dirname + "/../schemas/VirtualWinner"));
const PreLotteryWine = require(path.join(__dirname + "/../schemas/PreLotteryWine"));
const Message = require(path.join(__dirname + "/../api/message"));
router.use((req, res, next) => {
next();
});
router.route("/winners").delete(mustBeAuthenticated, async (req, res) => {
await VirtualWinner.deleteMany();
io.emit("refresh_data", {});
res.json(true);
});
router.route("/attendees").delete(mustBeAuthenticated, async (req, res) => {
await Attendee.deleteMany();
io.emit("refresh_data", {});
res.json(true);
});
router.route("/winners").get(async (req, res) => {
const winners = async (req, res) => {
let winners = await VirtualWinner.find();
let winnersRedacted = [];
let winner;
@@ -50,19 +22,82 @@ router.route("/winners").get(async (req, res) => {
});
}
res.json(winnersRedacted);
});
};
router.route("/winners/secure").get(mustBeAuthenticated, async (req, res) => {
const winnersSecure = async (req, res) => {
let winners = await VirtualWinner.find();
res.json(winners);
});
return res.json(winners);
};
router.route("/winner").get(mustBeAuthenticated, async (req, res) => {
const deleteWinners = async (req, res) => {
await VirtualWinner.deleteMany();
var io = req.app.get('socketio');
io.emit("refresh_data", {});
return res.json(true);
};
const attendees = async (req, res) => {
let attendees = await Attendee.find();
let attendeesRedacted = [];
let attendee;
for (let i = 0; i < attendees.length; i++) {
attendee = attendees[i];
attendeesRedacted.push({
name: attendee.name,
ballots: attendee.red + attendee.blue + attendee.yellow + attendee.green,
red: attendee.red,
blue: attendee.blue,
green: attendee.green,
yellow: attendee.yellow
});
}
return res.json(attendeesRedacted);
};
const attendeesSecure = async (req, res) => {
let attendees = await Attendee.find();
return res.json(attendees);
};
const addAttendee = async (req, res) => {
const attendee = req.body;
const { red, blue, yellow, green } = attendee;
let newAttendee = new Attendee({
name: attendee.name,
red,
blue,
green,
yellow,
phoneNumber: attendee.phoneNumber,
winner: false
});
await newAttendee.save();
var io = req.app.get('socketio');
io.emit("new_attendee", {});
return res.send(true);
};
const deleteAttendees = async (req, res) => {
await Attendee.deleteMany();
var io = req.app.get('socketio');
io.emit("refresh_data", {});
return res.json(true);
};
const drawWinner = async (req, res) => {
let allContestants = await Attendee.find({ winner: false });
if (allContestants.length == 0) {
res.json(false);
return;
return res.json({
success: false,
message: "No attendees left that have not won."
});
}
let ballotColors = [];
for (let i = 0; i < allContestants.length; i++) {
@@ -131,6 +166,7 @@ router.route("/winner").get(mustBeAuthenticated, async (req, res) => {
Math.floor(Math.random() * attendeeListDemocratic.length)
];
var io = req.app.get('socketio');
io.emit("winner", { color: colorToChooseFrom, name: winner.name });
let newWinnerElement = new VirtualWinner({
@@ -151,8 +187,40 @@ router.route("/winner").get(mustBeAuthenticated, async (req, res) => {
);
await newWinnerElement.save();
res.json(winner);
});
return res.json(winner);
};
const finish = async (req, res) => {
if (!config.gatewayToken) {
return res.json({
message: "Missing api token for sms gateway.",
success: false
});
}
let winners = await VirtualWinner.find({ timestamp_sent: undefined }).sort({
timestamp_drawn: 1
});
if (winners.length == 0) {
return res.json({
message: "No winners to draw from.",
success: false
});
}
Message.sendInitialMessageToWinners(winners.slice(1));
return findAndNotifyNextWinner()
.then(() => res.json({
success: true,
message: "Sent wine select message to first winner and update message to rest of winners."
}))
.catch(error => res.json({
message: error["message"] || "Unable to send message to first winner.",
success: false
}))
};
const genRandomString = function(length) {
return crypto
@@ -168,87 +236,6 @@ const sha512 = function(password, salt) {
return value;
};
router.route("/finish").get(mustBeAuthenticated, async (req, res) => {
if (!config.gatewayToken) {
res.json(false);
return;
}
let winners = await VirtualWinner.find({ timestamp_sent: undefined }).sort({
timestamp_drawn: 1
});
if (winners.length == 0) {
res.json(false);
return;
}
let firstWinner = winners[0];
messageSent = false;
try {
let messageSent = await Message.sendMessage(firstWinner);
Message.sendUpdate(winners.slice(1));
if (!messageSent) {
res.json(false);
return;
}
} catch (e) {
res.json(false);
return;
}
firstWinner.timestamp_sent = new Date().getTime();
firstWinner.timestamp_limit = new Date().getTime() + 600000;
await firstWinner.save();
startTimeout(firstWinner.id);
res.json(true);
return;
});
router.route("/attendees").get(async (req, res) => {
let attendees = await Attendee.find();
let attendeesRedacted = [];
let attendee;
for (let i = 0; i < attendees.length; i++) {
attendee = attendees[i];
attendeesRedacted.push({
name: attendee.name,
ballots: attendee.red + attendee.blue + attendee.yellow + attendee.green,
red: attendee.red,
blue: attendee.blue,
green: attendee.green,
yellow: attendee.yellow
});
}
res.json(attendeesRedacted);
});
router.route("/attendees/secure").get(mustBeAuthenticated, async (req, res) => {
let attendees = await Attendee.find();
res.json(attendees);
});
router.route("/attendee").post(mustBeAuthenticated, async (req, res) => {
const attendee = req.body;
const { red, blue, yellow, green } = attendee;
let newAttendee = new Attendee({
name: attendee.name,
red,
blue,
green,
yellow,
phoneNumber: attendee.phoneNumber,
winner: false
});
await newAttendee.save();
io.emit("new_attendee", {});
res.send(true);
});
function shuffle(array) {
let currentIndex = array.length,
temporaryValue,
@@ -269,43 +256,15 @@ function shuffle(array) {
return array;
}
function startTimeout(id) {
console.log(`Starting timeout for user ${id}.`);
setTimeout(async () => {
let virtualWinner = await VirtualWinner.findOne({ id: id });
if (!virtualWinner) {
console.log(
`Timeout done for user ${id}, but user has already sent data.`
);
return;
}
console.log(`Timeout done for user ${id}, sending update to user.`);
Message.sendMessageTooLate(virtualWinner);
virtualWinner.timestamp_drawn = new Date().getTime();
virtualWinner.timestamp_limit = null;
virtualWinner.timestamp_sent = null;
await virtualWinner.save();
let prelotteryWine = await PreLotteryWine.find();
let nextWinner = await VirtualWinner.find().sort({ timestamp_drawn: 1 });
if (nextWinner.length == 1 && prelotteryWine.length == 1) {
chooseForUser(nextWinner[0], prelotteryWine[0]);
} else {
nextWinner[0].timestamp_sent = new Date().getTime();
nextWinner[0].timestamp_limit = new Date().getTime() + 600000;
await nextWinner[0].save();
Message.sendMessage(nextWinner[0]);
startTimeout(nextWinner[0].id);
}
}, 600000);
module.exports = {
deleteWinners,
deleteAttendees,
winners,
winnersSecure,
drawWinner,
finish,
attendees,
attendeesSecure,
addAttendee
}
module.exports = function(_io) {
io = _io;
return router;
};

View File

@@ -1,11 +1,4 @@
const express = require("express");
const path = require("path");
const router = express.Router();
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/vinlottis", {
useNewUrlParser: true
});
const _wineFunctions = require(path.join(__dirname + "/../api/wine"));
const _personFunctions = require(path.join(__dirname + "/../api/person"));
@@ -17,72 +10,70 @@ const PreLotteryWine = require(path.join(
__dirname + "/../schemas/PreLotteryWine"
));
router.use((req, res, next) => {
next();
});
router.route("/winner/:id").get((req, res) => {
res.redirect(`/#/winner/${req.params.id}`);
});
router.route("/:id").get(async (req, res) => {
const getWinesToWinnerById = async (req, res) => {
let id = req.params.id;
let foundWinner = await VirtualWinner.findOne({ id: id });
if (!foundWinner) {
res.json({
return res.json({
success: false,
message: "No winner with this id.",
existing: false,
turn: false
});
return;
}
let allWinners = await VirtualWinner.find().sort({ timestamp_drawn: 1 });
if (
allWinners[0].id != foundWinner.id ||
foundWinner.timestamp_limit == undefined ||
foundWinner.timestamp_sent == undefined
) {
res.json({ existing: true, turn: false });
return;
return res.json({
success: false,
message: "Not the winner next in line!",
existing: true,
turn: false
});
}
res.json({
return res.json({
success: true,
existing: true,
turn: true,
name: foundWinner.name,
color: foundWinner.color
});
return;
});
};
router.route("/:id").post(async (req, res) => {
const registerWinnerSelection = async (req, res) => {
let id = req.params.id;
let wineName = req.body.wineName;
let foundWinner = await VirtualWinner.findOne({ id: id });
if (!foundWinner) {
res.json(false);
return;
return res.json({
success: false,
message: "No winner with this id."
})
} else if (foundWinner.timestamp_limit < new Date().getTime()) {
return res.json({
success: false,
message: "Timelimit expired, you will receive a wine after other users have chosen.",
limit: true
})
}
if (foundWinner.timestamp_limit < new Date().getTime()) {
res.json({
success: false,
limit: true
});
return;
}
let date = new Date();
date.setHours(5, 0, 0, 0);
let prelotteryWine = await PreLotteryWine.findOne({ name: wineName });
if (!prelotteryWine) {
res.json({
return res.json({
success: false,
wine: true
message: "No wine with this name.",
wine: false
});
}
@@ -91,31 +82,78 @@ router.route("/:id").post(async (req, res) => {
await _personFunctions.findSavePerson(foundWinner, wonWine, date);
await foundWinner.delete();
console.info("Saved winners choice.");
let nextWineBottle = await PreLotteryWine.find();
let nextWinner = await VirtualWinner.find().sort({ timestamp_drawn: 1 });
if (nextWinner.length > 1 && nextWineBottle.length > 1) {
Message.sendMessage(nextWinner[0]);
startTimeout(id);
} else if (nextWinner.length == 1 && nextWineBottle.length == 1) {
chooseForUser(nextWinner[0], nextWineBottle[0]);
}
return findAndNotifyNextWinner()
.then(() => res.json({
message: "Choice saved and next in line notified.",
success: true
}))
.catch(error => res.json({
message: error["message"] || "Error when notifing next winner.",
success: false
}))
};
res.json({
success: true
});
return;
});
async function chooseForUser(winner, prelotteryWine) {
const chooseLastWineForUser = (winner, prelotteryWine) => {
let date = new Date();
date.setHours(5, 0, 0, 0);
let wonWine = await _wineFunctions.findSaveWine(prelotteryWine);
await _personFunctions.findSavePerson(winner, wonWine, date);
await prelotteryWine.delete();
await Message.sendWonWineMessage(winner, prelotteryWine);
await winner.delete();
return _wineFunctions.findSaveWine(preLotteryWine)
.then(wonWine => _personFunctions.findSavePerson(winner, wonWine, date))
.then(() => prelotteryWine.delete())
.then(() => Message.sendLastWinnerMessage(winner, preLotteryWine))
.then(() => winner.delete());
}
const findAndNotifyNextWinner = async () => {
let nextWinner = undefined;
let winnersLeft = await VirtualWinner.find().sort({ timestamp_drawn: 1 });
let winesLeft = await PreLotteryWine.find();
if (winnersLeft.length > 1) {
nextWinner = winnersLeft[0]; // multiple winners left, choose next in line
} else if (winnersLeft.length == 1 && winesLeft.length > 1) {
nextWinner = winnersLeft[0] // one winner left, but multiple wines
} else if (winnersLeft.length == 1 && winesLeft.length == 1) {
nextWinner = winnersLeft[0] // one winner and one wine left, choose for user
wine = winesLeft[0]
return chooseLastWineForUser(nextWinner, wine);
}
if (nextWinner) {
return Message.sendWineSelectMessage(nextWinner)
.then(messageResponse => startTimeout(nextWinner.id))
} else {
console.info("All winners notified. Could start cleanup here.");
return Promise.resolve({
message: "All winners notified."
})
}
};
const sendNotificationToWinnerById = async (req, res) => {
const { id } = req.params;
let winner = await VirtualWinner.findOne({ id: id });
if (!winner) {
return res.json({
message: "No winner with this id.",
success: false
})
}
return Message.sendWineSelectMessage(winner)
.then(success => res.json({
success: success,
message: `Message sent to winner ${id} successfully!`
}))
.catch(err => res.json({
success: false,
message: "Error while trying to send sms.",
error: err
}))
}
function startTimeout(id) {
@@ -123,27 +161,28 @@ function startTimeout(id) {
setTimeout(async () => {
let virtualWinner = await VirtualWinner.findOne({ id: id });
if (!virtualWinner) {
console.log(
`Timeout done for user ${id}, but user has already sent data.`
);
console.log(`Timeout done for user ${id}, but user has already sent data.`);
return;
}
console.log(`Timeout done for user ${id}, sending update to user.`);
Message.sendMessageTooLate(virtualWinner);
Message.sendWineSelectMessageTooLate(virtualWinner);
virtualWinner.timestamp_drawn = new Date().getTime();
virtualWinner.timestamp_limit = null;
virtualWinner.timestamp_sent = null;
await virtualWinner.save();
let prelotteryWine = await PreLotteryWine.find();
let nextWinner = await VirtualWinner.find().sort({ timestamp_drawn: 1 });
if (nextWinner.length == 1 && prelotteryWine.length == 1) {
chooseForUser(nextWinner[0], prelotteryWine[0]);
}
}, 600000);
findAndNotifyNextWinner();
}, 60000);
return Promise.resolve()
}
module.exports = router;
module.exports = {
getWinesToWinnerById,
registerWinnerSelection,
findAndNotifyNextWinner,
sendNotificationToWinnerById
};

View File

@@ -1,15 +1,8 @@
const express = require("express");
const path = require("path");
const router = express.Router();
const fetch = require('node-fetch')
const path = require('path')
const config = require(path.join(__dirname + "/../config/env/lottery.config"));
const mustBeAuthenticated = require(path.join(__dirname + "/../middleware/mustBeAuthenticated"))
router.use((req, res, next) => {
next();
});
const convertToOurWineObject = wine => {
if(wine.basic.ageLimit === "18"){
return {
@@ -25,11 +18,11 @@ const convertToOurWineObject = wine => {
}
}
router.route("/wineinfo/search").get(async (req, res) => {
const wineSearch = async (req, res) => {
const {query} = req.query
let url = new URL(`https://apis.vinmonopolet.no/products/v0/details-normal?productShortNameContains=test&maxResults=15`)
url.searchParams.set('productShortNameContains', query)
const vinmonopoletResponse = await fetch(url, {
headers: {
"Ocp-Apim-Subscription-Key": config.vinmonopoletToken
@@ -37,8 +30,8 @@ router.route("/wineinfo/search").get(async (req, res) => {
})
.then(resp => resp.json())
.catch(err => console.error(err))
if (vinmonopoletResponse.errors != null) {
return vinmonopoletResponse.errors.map(error => {
if (error.type == "UnknownProductError") {
@@ -51,12 +44,11 @@ router.route("/wineinfo/search").get(async (req, res) => {
})
}
const winesConverted = vinmonopoletResponse.map(convertToOurWineObject).filter(Boolean)
res.send(winesConverted);
});
return res.send(winesConverted);
}
router.route("/wineinfo/:ean").get(async (req, res) => {
const byEAN = async (req, res) => {
const vinmonopoletResponse = await fetch("https://app.vinmonopolet.no/vmpws/v2/vmp/products/barCodeSearch/" + req.params.ean)
.then(resp => resp.json())
@@ -72,7 +64,10 @@ router.route("/wineinfo/:ean").get(async (req, res) => {
})
}
res.send(vinmonopoletResponse);
});
return res.send(vinmonopoletResponse);
};
module.exports = router;
module.exports = {
byEAN,
wineSearch
};