This commit is contained in:
2021-06-21 15:14:16 +02:00
parent 1949f1522d
commit b58acdc0c9
9 changed files with 5 additions and 216 deletions

View File

@@ -7,7 +7,6 @@ const routeRestaurant = require("../routes/routeRestaurant.js");
const routeUser = require("../routes/routeUser.js");
const routeSearch = require("../routes/routeSearch.js");
const routeImg = require("../routes/routeImg.js");
const routePayments = require("../routes/routePayments.js");
const routeHealth = require("../routes/routeHealth.js");
const routeAdmin = require("../routes/routeAdmin.js")
@@ -30,7 +29,6 @@ const loadExpress = ({ app, secret }) => {
app.use("/img", routeImg);
app.use("/user", routeUser);
app.use("/search", routeSearch);
app.use("/payments", routePayments);
app.use("/healthcheck", routeHealth);
app.use("/00xc232", routeAdmin)

View File

@@ -1,10 +0,0 @@
const mongoose = require("mongoose");
const paymentSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId,
restaurantId: mongoose.Types.ObjectId,
amount: Number,
months: Number,
});
module.exorts = mongoose.model("Payment", paymentSchema);

View File

@@ -104,9 +104,6 @@ const restaurantSchema = mongoose.Schema({
maxlength: 24
},
hidden: Boolean,
subscriptionActive: Boolean,
subscriptionStarted: Date,
subscriptionDue: Date,
indexed: Date,
categories: [String],
lunchHours: {

View File

@@ -1,14 +0,0 @@
const express = require("express");
const { handleError } = require("../services/services.js");
var router = express.Router();
router.post("/", async (req, res) => {
try {
console.log("test");
} catch (error) {
handleError(error, res);
}
});
module.exports = router;

View File

@@ -9,9 +9,7 @@ const {
changeLunchMenu,
changeLunchMenuSet,
fetchUser,
renewSubscription,
setRestaurantVisibility,
startTrial
} = require("../services/databaseServices.js");
const {
decodeAndSanitize,
@@ -184,36 +182,5 @@ router.post("/visibility", async (req, res) => {
}
})
// ACTIVATE SUBSCRIPTION
router.post("/subscription", async (req, res) => {
try {
const token = req.headers["x-auth-token"];
const user = validateUserToken(token);
await validateRestaurant(req.body.restaurantId);
/* const response = await initializePayment(
req.body.restaurantId,
req.body.userData,
req.body.type
); */
await renewSubscription(req.body.restaurantId, req.body.type);
res.sendStatus(200);
} catch (error) {
handleError(error, res);
}
});
// ACTIVATE TRIAL
router.post("/trial", async (req, res) => {
try {
const token = req.headers["x-auth-token"];
const user = validateUserToken(token);
await startTrial(req.body.restaurantId, user);
res.send("Okres próbny aktywowany.");
} catch (error) {
handleError(error, res);
}
})
module.exports = router;

View File

@@ -14,13 +14,11 @@ router.get("/", async (req, res) => {
const query = sanitizer.sanitize.keepUnicode(decodeURI(req.query.string));
validateSearch(query);
const regex = new RegExp(query, "i");
Restaurant.find(
{
$and: [
{ $or: [{ city: { $regex: regex } }, { name: { $regex: regex } }] },
{ $or: [{ hidden: false }, { hidden: { $exists: false } }] },
{ subscriptionActive: true },
{ $or: [{ hidden: false }, { hidden: { $exists: false } }] }
],
},
"_id name city adress type imgUrl workingHours description tags location"
@@ -76,8 +74,7 @@ router.get("/autocomplete/", (req, res) => {
Restaurant.find(
{ $and: [
{ $or: [{ city: { $regex: regex } }, { name: { $regex: regex } }] },
{ $or: [{ hidden: false }, { hidden: { $exists: false } }] },
{ subscriptionActive: true },
{ $or: [{ hidden: false }, { hidden: { $exists: false } }] }
], },
"name city",
(err, doc) => {

View File

@@ -81,6 +81,7 @@ async function createRestaurant(request, oldRestaurant) {
links: request.links,
phone: request.phone,
hidden: request.hidden,
indexed: new Date()
});
return restaurant;
} else {
@@ -107,9 +108,8 @@ async function createRestaurant(request, oldRestaurant) {
links: request.links,
phone: request.phone,
hidden: request.hidden,
subscriptionActive: oldRestaurant.subscriptionActive,
subscriptionDue: oldRestaurant.subscriptionDue,
subscriptionStarted: oldRestaurant.subscriptionStarted,
indexed: request.indexed,
ratings: request.ratings
});
return restaurant;
}

View File

@@ -1,13 +1,9 @@
const Restaurant = require("../models/restaurant.js");
const Dish = require("../models/dish.js");
const User = require("../models/users.js");
const Payments = require("../models/payments.js");
const Report = require("../models/reports.js")
const { deleteImage } = require("./oceanServices.js");
const { newError } = require("./services.js");
const mongoose = require("mongoose");
const axios = require("axios");
const crypto = require("crypto");
async function changeUserPass(userId, newPass) {
User.findByIdAndUpdate(userId, { $set: { password: newPass } }).catch((e) => {
@@ -67,84 +63,6 @@ async function addRestaurantToUser(user, restaurant) {
});
}
function dueDateBasedOnSubscription(restaurant, monthsToAdd) {
let date;
if (
restaurant.subscriptionActive === false ||
!restaurant.subscriptionActive
) {
date = new Date();
date.setMonth(date.getMonth() + monthsToAdd);
return date;
} else {
date = restaurant.subscriptionDue;
date.setMonth(date.getMonth() + monthsToAdd);
return date;
}
}
function startDate(restaurant) {
let date;
if (
restaurant.subscriptionActive === true &&
restaurant.subscriptionStarted
) {
date = restaurant.subscriptionStarted;
return date;
} else {
date = new Date();
return date;
}
}
async function renewSubscription(restaurantId, monthsToAdd) {
const restaurant = await Restaurant.findById(restaurantId).catch((err) => {
throw newError("Nie udało się pobrać restauracji.", 404);
});
const dueDate = dueDateBasedOnSubscription(restaurant, monthsToAdd);
const start = startDate(restaurant);
await Restaurant.findByIdAndUpdate(restaurantId, {
$set: {
subscriptionActive: true,
subscriptionDue: dueDate,
subscriptionStarted: start,
},
}).catch((e) => {
throw newError(
"Nie udało się przedłużyć subskrypcji, spróbuj ponownie.",
500
);
});
return dueDateBasedOnSubscription(restaurant, monthsToAdd);
}
async function startTrial(restaurantId, userData) {
const restaurant = await Restaurant.findById(restaurantId).catch((err) => {
throw newError("Nie udało się pobrać restauracji.", 404);
});
if (!userData.trialUsed || userData.trialUsed === false) {
const dueDate = dueDateBasedOnSubscription(restaurant, 3);
const start = startDate(restaurant);
await Restaurant.findByIdAndUpdate(restaurantId, {
$set: {
subscriptionActive: true,
subscriptionDue: dueDate,
subscriptionStarted: start,
},
}).catch((e) => {
throw newError(
"Nie udało się aktywować okresu próbnego.",
500
);
});
await User.findByIdAndUpdate(userData.id, { $set: { trialUsed: true } }).catch((e) => {
throw newError("Błąd podczas aktywacji okresu próbnego (user data)")
})
} else {
throw newError("Okres próbny został już wykorzystany.", 500);
}
}
async function checkIfCategoryExists(restaurant, category) {
const categories = restaurant.categories;
if (categories.includes(category)) {
@@ -330,67 +248,6 @@ async function fetchUser(email) {
return user;
}
function amountFromType(type) {
if (type === 1) {
return 6150;
} else if (type === 12) {
return 61500;
} else {
return 0;
}
}
function controlSum(sessionId, merchantId, amount, currency) {
const input = {
sessionId: sessionId,
merchantId: merchantId,
amount: amount,
currency: currency,
crc: "???? wie co tu ma być",
};
let hash = crypto.createHash("sha384");
const checkSum = hash.update(input, "utf8");
return checkSum;
}
async function registerTransaction(paymentInfo, userData) {
const data = {
merchantId: 11111,
posId: paymentInfo.type,
sessionId: paymentInfo._id,
amount: paymentInfo.amount,
currency: "PLN",
description: `Subskrypcja Menui na: ${paymentInfo.months} miesięcy.`,
email: userData.userEmail,
client: `${userData.firstname} ${userData.lastname}`,
country: "PL",
language: "pl",
urlReturn: "http://test.pl",
sign: controlSum(paymentInfo._id, 11111, paymentInfo.amount, "PLN"),
};
const response = await axios({
method: "POST",
url: "https://sandbox.przelewy24.pl/api/v1",
data: data,
}).catch((error) => {
console.log(error);
throw newError("Błąd.", 500);
});
return response;
}
async function initializePayment(restaurantId, userData, type) {
const newPayment = new Payments({
_id: new mongoose.Types.ObjectId(),
restaurantId: restaurantId,
amount: amountFromType(type),
months: type,
});
const payment = await registerTransaction(newPayment, userData);
newPayment.save();
return payment;
}
async function setRestaurantVisibility(restaurantId, visible) {
await Restaurant.findByIdAndUpdate(restaurantId, { $set: { hidden: !visible } }).catch(
(e) => {
@@ -416,7 +273,6 @@ exports.removeDish = removeDish;
exports.removeRestaurant = removeRestaurant;
exports.addDishToRestaurant = addDishToRestaurant;
exports.addRestaurantToUser = addRestaurantToUser;
exports.renewSubscription = renewSubscription;
exports.changeCategory = changeCategory;
exports.setDishVisibility = setDishVisibility;
exports.changeLunchMenuSet = changeLunchMenuSet;
@@ -426,7 +282,5 @@ exports.fetchMultipleRestaurants = fetchMultipleRestaurants;
exports.fetchAllDishesForRestaurant = fetchAllDishesForRestaurant;
exports.fetchDish = fetchDish;
exports.fetchUser = fetchUser;
exports.initializePayment = initializePayment;
exports.setRestaurantVisibility = setRestaurantVisibility;
exports.startTrial = startTrial;
exports.fetchAllAdminData = fetchAllAdminData;