Archived
1
0
Fork 0
This repository has been archived on 2024-02-17. You can view files and clone it, but cannot push or open issues or pull requests.
SOD/routes/command.js

59 lines
2 KiB
JavaScript
Raw Normal View History

let express = require("express");
let router = express.Router();
let models = require("../models");
router.post("/", async (req, res) => {
if (!req.body.department || !req.body.firstName || !req.body.lastName || !req.body.sandwich1 || !req.body.date1) {
res.render("error", {message: "Invalid command !", "error": {status: "Missing arguments"}});
return;
}
let department = await models.Department.findByPk(req.body.department);
if (!department) {
res.render("error", {message: "Invalid command !", error: {status: "Invalid department"}});
return;
}
2020-08-16 12:48:43 +02:00
let sandwiches = [];
let price = 0;
for (let i = 1; req.body["sandwich" + i] !== undefined; i++) {
if (req.body["date" + i] === undefined) {
res.render("error", {message: "Invalid command !", error: {status: "Sandwich without date"}});
return;
}
let sandwich = await models.Sandwich.findByPk(req.body["sandwich" + i]);
if (!sandwich) {
res.render("error", {
message: "Invalid command !",
error: {status: "Invalid sandwich: "+req.body["sandwich" + i]}
});
return;
}
2020-08-16 12:48:43 +02:00
sandwiches.push([sandwich.name, req.body["date" + i]]);
price += sandwich.price;
}
let command = await models.Command.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
price: price
});
let user = await models.User.findOne({where: {firstName: req.body.firstName, lastName: req.body.lastName}});
if (user)
await command.setUser(user);
await command.setDepartment(department);
2020-08-16 12:48:43 +02:00
for (let data of sandwiches)
try {
await models.SandwichCommand.create({CommandId: command.id, SandwichName: data[0], date: data[1]});
} catch (e) {
await command.destroy();
res.render("error", {message: "Invalid command !", error: {status: "Invalid date"}});
throw e;
}
res.send("Ok");
});
module.exports = router;