Merge remote-tracking branch 'origin/master'
All checks were successful
Jenkins Production Deployment
All checks were successful
Jenkins Production Deployment
# Conflicts: # src/models/rapla-middleware/icalgenerator/icalgenerator.service.ts
This commit is contained in:
commit
488f502b2d
6
.gitignore
vendored
6
.gitignore
vendored
|
@ -2,3 +2,9 @@
|
|||
.idea
|
||||
**/*.iml
|
||||
.env
|
||||
|
||||
# Build output
|
||||
dist/
|
||||
logs/
|
||||
node_modules/
|
||||
public/
|
||||
|
|
39
app.ts
39
app.ts
|
@ -1,6 +1,8 @@
|
|||
import express from 'express';
|
||||
import * as http from 'http';
|
||||
import * as dotenv from 'dotenv';
|
||||
import swaggerUi from 'swagger-ui-express';
|
||||
import swaggerJSDoc from 'swagger-jsdoc';
|
||||
// Router imports
|
||||
import {partyPlanerRouter} from './src/models/partyplaner/PartyPlaner.router';
|
||||
import {highlightMarkerRouter} from './src/models/twitch-highlight-marker/HighlightMarker.router';
|
||||
|
@ -8,6 +10,8 @@ import {dhbwServiceRouter} from './src/models/dhbw-service/DHBWService.router';
|
|||
import logger from './src/middleware/logger';
|
||||
import {dhbwRaPlaChangesRouter} from './src/models/dhbw-rapla-changes/DHBWRaPlaChanges.router';
|
||||
import {raPlaMiddlewareRouter} from './src/models/rapla-middleware/RaPlaMiddleware.router';
|
||||
import {betterzonRouter} from './src/models/betterzon/Betterzon.router';
|
||||
import {crrRouter} from './src/models/climbing-route-rating/ClimbingRouteRating.router';
|
||||
|
||||
let cors = require('cors');
|
||||
|
||||
|
@ -29,12 +33,47 @@ app.use(express.json());
|
|||
// Use CORS
|
||||
app.use(cors());
|
||||
|
||||
// Swagger documentation
|
||||
const swaggerDefinition = {
|
||||
openapi: '3.0.0',
|
||||
info: {
|
||||
title: 'Pluto Development REST API',
|
||||
version: '2.0.0',
|
||||
license: {
|
||||
name: 'Licensed Under MIT',
|
||||
url: 'https://spdx.org/licenses/MIT.html'
|
||||
},
|
||||
contact: {
|
||||
name: 'Pluto Development',
|
||||
url: 'https://www.pluto-development.de'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const options = {
|
||||
swaggerDefinition,
|
||||
// Paths to files containing OpenAPI definitions
|
||||
apis: [
|
||||
'./src/models/**/*.router.ts'
|
||||
]
|
||||
};
|
||||
|
||||
const swaggerSpec = swaggerJSDoc(options);
|
||||
|
||||
app.use(
|
||||
'/docs',
|
||||
swaggerUi.serve,
|
||||
swaggerUi.setup(swaggerSpec)
|
||||
);
|
||||
|
||||
// Add routers
|
||||
app.use('/dhbw-service', dhbwServiceRouter);
|
||||
app.use('/twitch-highlight-marker', highlightMarkerRouter);
|
||||
app.use('/partyplaner', partyPlanerRouter);
|
||||
app.use('/raplachanges', dhbwRaPlaChangesRouter);
|
||||
app.use('/rapla-middleware', raPlaMiddlewareRouter);
|
||||
app.use('/betterzon', betterzonRouter);
|
||||
app.use('/crr', crrRouter);
|
||||
|
||||
// this is a simple route to make sure everything is working properly
|
||||
app.get('/', (req: express.Request, res: express.Response) => {
|
||||
|
|
5345
package-lock.json
generated
5345
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
75
package.json
75
package.json
|
@ -1,36 +1,43 @@
|
|||
{
|
||||
"name": "PlutoDevExpressAPI",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "tsc && node ./dist/app.js",
|
||||
"build": "tsc",
|
||||
"debug": "export DEBUG=* && npm run start",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"app-root-path": "^3.0.0",
|
||||
"bcrypt": "^5.0.1",
|
||||
"cors": "^2.8.5",
|
||||
"debug": "^4.3.1",
|
||||
"dotenv": "^8.2.0",
|
||||
"express": "^4.17.1",
|
||||
"guid-typescript": "^1.0.9",
|
||||
"mariadb": "^2.5.3",
|
||||
"winston": "^3.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/app-root-path": "^1.2.4",
|
||||
"@types/bcrypt": "^3.0.1",
|
||||
"@types/debug": "^4.1.5",
|
||||
"@types/express": "^4.17.11",
|
||||
"@types/winston": "^2.4.4",
|
||||
"source-map-support": "^0.5.19",
|
||||
"tslint": "^6.1.3",
|
||||
"typescript": "^4.1.5"
|
||||
}
|
||||
"name": "plutodev_express_api",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "tsc && node ./dist/app.js",
|
||||
"build": "tsc",
|
||||
"debug": "export DEBUG=* && npm run start",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"app-root-path": "^3.0.0",
|
||||
"axios": "^0.24.0",
|
||||
"bcrypt": "^5.0.1",
|
||||
"cors": "^2.8.5",
|
||||
"debug": "^4.3.1",
|
||||
"dotenv": "^8.2.0",
|
||||
"express": "^4.17.1",
|
||||
"guid-typescript": "^1.0.9",
|
||||
"mariadb": "^2.5.3",
|
||||
"random-words": "^1.1.1",
|
||||
"swagger-jsdoc": "^6.1.0",
|
||||
"swagger-ui-express": "^4.3.0",
|
||||
"winston": "^3.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/app-root-path": "^1.2.4",
|
||||
"@types/bcrypt": "^3.0.1",
|
||||
"@types/debug": "^4.1.5",
|
||||
"@types/express": "^4.17.11",
|
||||
"@types/random-words": "^1.1.2",
|
||||
"@types/swagger-jsdoc": "^6.0.1",
|
||||
"@types/swagger-ui-express": "^4.1.3",
|
||||
"@types/winston": "^2.4.4",
|
||||
"source-map-support": "^0.5.19",
|
||||
"tslint": "^6.1.3",
|
||||
"typescript": "^4.1.5"
|
||||
}
|
||||
}
|
||||
|
|
19
src/models/betterzon/Betterzon.db.ts
Normal file
19
src/models/betterzon/Betterzon.db.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export namespace BetterzonDB {
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.BETTERZON_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
export function getConnection() {
|
||||
return pool;
|
||||
}
|
||||
}
|
47
src/models/betterzon/Betterzon.router.ts
Normal file
47
src/models/betterzon/Betterzon.router.ts
Normal file
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
import express, {Request, Response} from 'express';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import logger from '../../middleware/logger';
|
||||
import {productsRouter} from './products/products.router';
|
||||
import {contactpersonsRouter} from './contact_persons/contact_persons.router';
|
||||
import {pricealarmsRouter} from './pricealarms/pricealarms.router';
|
||||
import {usersRouter} from './users/users.router';
|
||||
import {pricesRouter} from './prices/prices.router';
|
||||
import {vendorsRouter} from './vendors/vendors.router';
|
||||
import {categoriesRouter} from './categories/categories.router';
|
||||
import {manufacturersRouter} from './manufacturers/manufacturers.router';
|
||||
import {favoriteshopsRouter} from './favorite_shops/favoriteshops.router';
|
||||
import {crawlingstatusRouter} from './crawling_status/crawling_status.router';
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
export const betterzonRouter = express.Router();
|
||||
|
||||
betterzonRouter.use('/products', productsRouter);
|
||||
betterzonRouter.use('/categories', categoriesRouter);
|
||||
betterzonRouter.use('/manufacturers', manufacturersRouter);
|
||||
betterzonRouter.use('/prices', pricesRouter);
|
||||
betterzonRouter.use('/users', usersRouter);
|
||||
betterzonRouter.use('/vendors', vendorsRouter);
|
||||
betterzonRouter.use('/pricealarms', pricealarmsRouter);
|
||||
betterzonRouter.use('/contactpersons', contactpersonsRouter);
|
||||
betterzonRouter.use('/favoriteshops', favoriteshopsRouter);
|
||||
betterzonRouter.use('/crawlingstatus', crawlingstatusRouter);
|
||||
|
||||
|
||||
betterzonRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
res.status(200).send('Pluto Development Betterzon API Endpoint');
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
5
src/models/betterzon/categories/categories.interface.ts
Normal file
5
src/models/betterzon/categories/categories.interface.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
import {Category} from './category.interface';
|
||||
|
||||
export interface Categories {
|
||||
[key: number]: Category;
|
||||
}
|
70
src/models/betterzon/categories/categories.router.ts
Normal file
70
src/models/betterzon/categories/categories.router.ts
Normal file
|
@ -0,0 +1,70 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as CategoryService from './categories.service';
|
||||
import {Category} from './category.interface';
|
||||
import {Categories} from './categories.interface';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const categoriesRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// GET categories/
|
||||
categoriesRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const categories: Categories = await CategoryService.findAll();
|
||||
|
||||
res.status(200).send(categories);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET categories/:id
|
||||
categoriesRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const category: Category = await CategoryService.find(id);
|
||||
|
||||
res.status(200).send(category);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET categories/search/:term
|
||||
categoriesRouter.get('/search/:term', async (req: Request, res: Response) => {
|
||||
const term: string = req.params.term;
|
||||
|
||||
if (!term) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const categories: Categories = await CategoryService.findBySearchTerm(term);
|
||||
|
||||
res.status(200).send(categories);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
89
src/models/betterzon/categories/categories.service.ts
Normal file
89
src/models/betterzon/categories/categories.service.ts
Normal file
|
@ -0,0 +1,89 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Category} from './category.interface';
|
||||
import {Categories} from './categories.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches and returns all known categories
|
||||
*/
|
||||
export const findAll = async (): Promise<Categories> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let categRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT category_id, name FROM categories');
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
let categ: Category = {
|
||||
category_id: 0,
|
||||
name: ''
|
||||
};
|
||||
const sqlCateg = rows[row];
|
||||
|
||||
categ.category_id = sqlCateg.category_id;
|
||||
categ.name = sqlCateg.name;
|
||||
categRows.push(categ);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return categRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the category with the specified id
|
||||
* @param id The id of the category to fetch
|
||||
*/
|
||||
export const find = async (id: number): Promise<Category> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let categ: any;
|
||||
try {
|
||||
const rows = await conn.query('SELECT category_id, name FROM categories WHERE category_id = ?', id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
categ = rows[row];
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return categ;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns all categories that match the search term
|
||||
* @param term the term to match
|
||||
*/
|
||||
export const findBySearchTerm = async (term: string): Promise<Categories> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let categRows = [];
|
||||
try {
|
||||
term = '%' + term + '%';
|
||||
const rows = await conn.query('SELECT category_id, name FROM categories WHERE name LIKE ?', term);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
categRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return categRows;
|
||||
};
|
4
src/models/betterzon/categories/category.interface.ts
Normal file
4
src/models/betterzon/categories/category.interface.ts
Normal file
|
@ -0,0 +1,4 @@
|
|||
export interface Category {
|
||||
category_id: number;
|
||||
name: string;
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
export interface Contact_Person {
|
||||
contact_person_id: number;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
gender: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
vendor_id: number;
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
import {Contact_Person} from './contact_person.interface';
|
||||
|
||||
export interface Contact_Persons {
|
||||
[key: number]: Contact_Person;
|
||||
}
|
133
src/models/betterzon/contact_persons/contact_persons.router.ts
Normal file
133
src/models/betterzon/contact_persons/contact_persons.router.ts
Normal file
|
@ -0,0 +1,133 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as ContactPersonService from './contact_persons.service';
|
||||
import {Contact_Person} from './contact_person.interface';
|
||||
import {Contact_Persons} from './contact_persons.interface';
|
||||
import * as UserService from '../users/users.service';
|
||||
import * as PriceService from '../prices/prices.service';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const contactpersonsRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// GET contactpersons/
|
||||
contactpersonsRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const contacts: Contact_Persons = await ContactPersonService.findAll();
|
||||
|
||||
res.status(200).send(contacts);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET contactpersons/:id
|
||||
contactpersonsRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const contact: Contact_Person = await ContactPersonService.find(id);
|
||||
|
||||
res.status(200).send(contact);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET contactpersons/byvendor/:id
|
||||
contactpersonsRouter.get('/byvendor/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const contacts: Contact_Persons = await ContactPersonService.findByVendor(id);
|
||||
|
||||
res.status(200).send(contacts);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// POST contactpersons/
|
||||
contactpersonsRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get required parameters
|
||||
const vendor_id = req.body.vendor_id;
|
||||
const first_name = req.body.first_name;
|
||||
const last_name = req.body.last_name;
|
||||
const gender = req.body.gender;
|
||||
const email = req.body.email;
|
||||
const phone = req.body.phone;
|
||||
|
||||
const success = await ContactPersonService.createContactEntry(user.user_id, vendor_id, first_name, last_name, gender, email, phone);
|
||||
|
||||
if (success) {
|
||||
res.status(201).send({});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// PUT contactpersons/:id
|
||||
contactpersonsRouter.put('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get required parameters
|
||||
const contact_person_id = parseInt(req.params.id, 10);
|
||||
const vendor_id = req.body.vendor_id;
|
||||
const first_name = req.body.first_name;
|
||||
const last_name = req.body.last_name;
|
||||
const gender = req.body.gender;
|
||||
const email = req.body.email;
|
||||
const phone = req.body.phone;
|
||||
|
||||
const success = await ContactPersonService.updateContactEntry(user.user_id, contact_person_id, vendor_id, first_name, last_name, gender, email, phone);
|
||||
|
||||
if (success) {
|
||||
res.status(200).send({});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
139
src/models/betterzon/contact_persons/contact_persons.service.ts
Normal file
139
src/models/betterzon/contact_persons/contact_persons.service.ts
Normal file
|
@ -0,0 +1,139 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Contact_Person} from './contact_person.interface';
|
||||
import {Contact_Persons} from './contact_persons.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches and returns all known contact persons
|
||||
*/
|
||||
export const findAll = async (): Promise<Contact_Persons> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let contRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT contact_person_id, first_name, last_name, gender, email, phone, vendor_id FROM contact_persons');
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
contRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return contRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the contact person with the specified id
|
||||
* @param id The id of the contact person to fetch
|
||||
*/
|
||||
export const find = async (id: number): Promise<Contact_Person> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let cont: any;
|
||||
try {
|
||||
const rows = await conn.query('SELECT contact_person_id, first_name, last_name, gender, email, phone, vendor_id FROM contact_persons WHERE contact_person_id = ?', id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
cont = rows[row];
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return cont;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the contact persons for the specified vendor
|
||||
* @param id The id of the vendor to fetch contact persons for
|
||||
*/
|
||||
export const findByVendor = async (id: number): Promise<Contact_Persons> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let contRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT contact_person_id, first_name, last_name, gender, email, phone, vendor_id FROM contact_persons WHERE vendor_id = ?', id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
contRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return contRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a contact entry record
|
||||
* @param user_id The user id of the issuing user
|
||||
* @param vendor_id The vendor id of the vendor to create the record for
|
||||
* @param first_name The first name of the contact person
|
||||
* @param last_name The last name of the contact person
|
||||
* @param gender The gender of the contact person
|
||||
* @param email The email of the contact person
|
||||
* @param phone The phone number of the contact person
|
||||
*/
|
||||
export const createContactEntry = async (user_id: number, vendor_id: number, first_name: string, last_name: string, gender: string, email: string, phone: string): Promise<Boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Check if the user is authorized to manage the requested vendor
|
||||
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
||||
if (user_vendor_rows.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create contact person entry
|
||||
const res = await conn.query('INSERT INTO contact_persons (first_name, last_name, gender, email, phone, vendor_id) VALUES (?, ?, ?, ?, ?, ?)', [first_name, last_name, gender, email, phone, vendor_id]);
|
||||
|
||||
// If there are more / less than 1 affected rows, return false
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a contact entry record
|
||||
* @param user_id The user id of the issuing user
|
||||
* @param contact_person_id The id of the record to update
|
||||
* @param vendor_id The vendor id of the vendor to create the record for
|
||||
* @param first_name The first name of the contact person
|
||||
* @param last_name The last name of the contact person
|
||||
* @param gender The gender of the contact person
|
||||
* @param email The email of the contact person
|
||||
* @param phone The phone number of the contact person
|
||||
*/
|
||||
export const updateContactEntry = async (user_id: number, contact_person_id: number, vendor_id: number, first_name: string, last_name: string, gender: string, email: string, phone: string): Promise<Boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Check if the user is authorized to manage the requested vendor
|
||||
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
||||
if (user_vendor_rows.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create contact person entry
|
||||
const res = await conn.query('UPDATE contact_persons SET first_name = ?, last_name = ?, gender = ?, email = ?, phone = ? WHERE contact_person_id = ? AND vendor_id = ?', [first_name, last_name, gender, email, phone, contact_person_id, vendor_id]);
|
||||
|
||||
// If there are more / less than 1 affected rows, return false
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
|
@ -0,0 +1,7 @@
|
|||
export interface Crawling_Status {
|
||||
process_id: number;
|
||||
started_timestamp: Date;
|
||||
combinations_to_crawl: number;
|
||||
successful_crawls: number;
|
||||
failed_crawls: number;
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as CrawlingStatusService from './crawling_status.service';
|
||||
import {Crawling_Status} from './crawling_status.interface';
|
||||
import {Crawling_Statuses} from './crawling_statuses.interface';
|
||||
import * as UserService from '../users/users.service';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const crawlingstatusRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// GET crawlingstatus/
|
||||
crawlingstatusRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = (req.query.session_id ?? '').toString();
|
||||
const session_key = (req.query.session_key ?? '').toString();
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
if (!user.is_admin) {
|
||||
res.status(403).send({});
|
||||
return;
|
||||
}
|
||||
|
||||
const status: Crawling_Status = await CrawlingStatusService.getCurrent();
|
||||
|
||||
res.status(200).send(status);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
|
@ -0,0 +1,59 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Crawling_Status} from './crawling_status.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches and returns the current crawling status if the issuing user is an admin
|
||||
*/
|
||||
export const getCurrent = async (): Promise<Crawling_Status> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Get the current crawling process
|
||||
let process_info = {
|
||||
process_id: -1,
|
||||
started_timestamp: new Date(),
|
||||
combinations_to_crawl: -1
|
||||
};
|
||||
const process = await conn.query('SELECT process_id, started_timestamp, combinations_to_crawl FROM crawling_processes ORDER BY started_timestamp DESC LIMIT 1');
|
||||
for (let row in process) {
|
||||
if (row !== 'meta') {
|
||||
process_info = process[row];
|
||||
}
|
||||
}
|
||||
|
||||
// Get the current status
|
||||
let total_crawls = 0;
|
||||
let successful_crawls = 0;
|
||||
const rows = await conn.query('SELECT COUNT(status_id) as total, SUM(success) as successful FROM crawling_status WHERE process_id = ?', process_info.process_id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
total_crawls = rows[row].total;
|
||||
successful_crawls = rows[row].successful;
|
||||
}
|
||||
}
|
||||
|
||||
const failed_crawls = total_crawls - successful_crawls;
|
||||
|
||||
return {
|
||||
process_id: process_info.process_id,
|
||||
started_timestamp: process_info.started_timestamp,
|
||||
combinations_to_crawl: process_info.combinations_to_crawl,
|
||||
successful_crawls: successful_crawls,
|
||||
failed_crawls: failed_crawls
|
||||
};
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
|
@ -0,0 +1,5 @@
|
|||
import {Crawling_Status} from './crawling_status.interface';
|
||||
|
||||
export interface Crawling_Statuses {
|
||||
[key: number]: Crawling_Status;
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
export interface FavoriteShop {
|
||||
favorite_id: number;
|
||||
vendor_id: number;
|
||||
user_id: number;
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
import {FavoriteShop} from './favoriteshop.interface';
|
||||
|
||||
export interface FavoriteShops {
|
||||
[key: number]: FavoriteShop;
|
||||
}
|
106
src/models/betterzon/favorite_shops/favoriteshops.router.ts
Normal file
106
src/models/betterzon/favorite_shops/favoriteshops.router.ts
Normal file
|
@ -0,0 +1,106 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as FavoriteShopsService from './favoriteshops.service';
|
||||
import {FavoriteShop} from './favoriteshop.interface';
|
||||
import {FavoriteShops} from './favoriteshops.interface';
|
||||
import * as UserService from '../users/users.service';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
export const favoriteshopsRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
//GET favoriteshops/
|
||||
favoriteshopsRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = (req.query.session_id ?? '').toString();
|
||||
const session_key = (req.query.session_key ?? '').toString();
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
const priceAlarms = await FavoriteShopsService.getFavoriteShops(user.user_id);
|
||||
|
||||
res.status(200).send(priceAlarms);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// POST favoriteshops/
|
||||
favoriteshopsRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get info for price alarm creation
|
||||
const vendor_id = req.body.vendor_id;
|
||||
|
||||
if (!vendor_id) {
|
||||
// Missing
|
||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Create price alarm
|
||||
const success = await FavoriteShopsService.createFavoriteShop(user.user_id, vendor_id);
|
||||
|
||||
if (success) {
|
||||
res.status(201).send(JSON.stringify({success: true}));
|
||||
return;
|
||||
} else {
|
||||
res.status(500).send(JSON.stringify({success: false}));
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE favoriteshops/
|
||||
favoriteshopsRouter.delete('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = (req.query.session_id ?? '').toString();
|
||||
const session_key = (req.query.session_key ?? '').toString();
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get info for price alarm creation
|
||||
const favorite_id = parseInt(req.params.id, 10);
|
||||
|
||||
if (!favorite_id) {
|
||||
// Missing
|
||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Create price alarm
|
||||
const success = await FavoriteShopsService.deleteFavoriteShop(user.user_id, favorite_id);
|
||||
|
||||
if (success) {
|
||||
res.status(201).send(JSON.stringify({success: true}));
|
||||
return;
|
||||
} else {
|
||||
res.status(500).send(JSON.stringify({success: false}));
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
67
src/models/betterzon/favorite_shops/favoriteshops.service.ts
Normal file
67
src/models/betterzon/favorite_shops/favoriteshops.service.ts
Normal file
|
@ -0,0 +1,67 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {FavoriteShops} from './favoriteshops.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a favorite shop entry for the given user for the given shop
|
||||
* @param user_id The id of the user to create the favorite shop entry for
|
||||
* @param vendor_id The id of the vendor to set as favorite
|
||||
*/
|
||||
export const createFavoriteShop = async (user_id: number, vendor_id: number): Promise<boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
const res = await conn.query('INSERT INTO favorite_shops (vendor_id, user_id) VALUES (?, ?)', [vendor_id, user_id]);
|
||||
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns all favorite shops for the given user
|
||||
* @param user_id
|
||||
*/
|
||||
export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let shops = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT favorite_id, vendor_id, user_id FROM favorite_shops WHERE user_id = ?', user_id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
shops.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
return shops;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes the given favorite shop entry
|
||||
* @param user_id The id of the user that wants to delete the favorite shop entry
|
||||
* @param favorite_id The favorite shop to delete
|
||||
*/
|
||||
export const deleteFavoriteShop = async (user_id: number, favorite_id: number): Promise<boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
const res = await conn.query('DELETE FROM favorite_shops WHERE favorite_id = ? AND user_id = ?', [favorite_id, user_id]);
|
||||
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
|
@ -0,0 +1,4 @@
|
|||
export interface Manufacturer {
|
||||
manufacturer_id: number;
|
||||
name: string;
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
import {Manufacturer} from './manufacturer.interface';
|
||||
|
||||
export interface Manufacturers {
|
||||
[key: number]: Manufacturer;
|
||||
}
|
70
src/models/betterzon/manufacturers/manufacturers.router.ts
Normal file
70
src/models/betterzon/manufacturers/manufacturers.router.ts
Normal file
|
@ -0,0 +1,70 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as ManufacturerService from './manufacturers.service';
|
||||
import {Manufacturer} from './manufacturer.interface';
|
||||
import {Manufacturers} from './manufacturers.interface';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const manufacturersRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// GET manufacturers/
|
||||
manufacturersRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const manufacturers: Manufacturers = await ManufacturerService.findAll();
|
||||
|
||||
res.status(200).send(manufacturers);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET manufacturers/:id
|
||||
manufacturersRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const manufacturer: Manufacturer = await ManufacturerService.find(id);
|
||||
|
||||
res.status(200).send(manufacturer);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET manufacturers/:term
|
||||
manufacturersRouter.get('/search/:term', async (req: Request, res: Response) => {
|
||||
const term: string = req.params.term;
|
||||
|
||||
if (!term) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const manufacturer: Manufacturers = await ManufacturerService.findBySearchTerm(term);
|
||||
|
||||
res.status(200).send(manufacturer);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
89
src/models/betterzon/manufacturers/manufacturers.service.ts
Normal file
89
src/models/betterzon/manufacturers/manufacturers.service.ts
Normal file
|
@ -0,0 +1,89 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Manufacturer} from './manufacturer.interface';
|
||||
import {Manufacturers} from './manufacturers.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches and returns all known manufacturers
|
||||
*/
|
||||
export const findAll = async (): Promise<Manufacturers> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let manRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers');
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
let man: Manufacturer = {
|
||||
manufacturer_id: 0,
|
||||
name: ''
|
||||
};
|
||||
const sqlMan = rows[row];
|
||||
|
||||
man.manufacturer_id = sqlMan.manufacturer_id;
|
||||
man.name = sqlMan.name;
|
||||
manRows.push(man);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return manRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the manufacturer with the specified id
|
||||
* @param id The id of the manufacturer to fetch
|
||||
*/
|
||||
export const find = async (id: number): Promise<Manufacturer> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let man: any;
|
||||
try {
|
||||
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE manufacturer_id = ?', id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
man = rows[row];
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return man;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns all manufacturers that match the search term
|
||||
* @param term the term to match
|
||||
*/
|
||||
export const findBySearchTerm = async (term: string): Promise<Manufacturers> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let manRows = [];
|
||||
try {
|
||||
term = '%' + term + '%';
|
||||
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE name LIKE ?', term);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
manRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return manRows;
|
||||
};
|
6
src/models/betterzon/pricealarms/pricealarm.interface.ts
Normal file
6
src/models/betterzon/pricealarms/pricealarm.interface.ts
Normal file
|
@ -0,0 +1,6 @@
|
|||
export interface PriceAlarm {
|
||||
alarm_id: number;
|
||||
user_id: number;
|
||||
product_id: number;
|
||||
defined_price: number;
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
import {PriceAlarm} from './pricealarm.interface';
|
||||
|
||||
export interface PriceAlarms {
|
||||
[key: number]: PriceAlarm;
|
||||
}
|
134
src/models/betterzon/pricealarms/pricealarms.router.ts
Normal file
134
src/models/betterzon/pricealarms/pricealarms.router.ts
Normal file
|
@ -0,0 +1,134 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as PriceAlarmsService from './pricealarms.service';
|
||||
import {PriceAlarm} from './pricealarm.interface';
|
||||
import {PriceAlarms} from './pricealarms.interface';
|
||||
import * as UserService from '../users/users.service';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
export const pricealarmsRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
//GET pricealarms/
|
||||
pricealarmsRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = (req.query.session_id ?? '').toString();
|
||||
const session_key = (req.query.session_key ?? '').toString();
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
const priceAlarms = await PriceAlarmsService.getPriceAlarms(user.user_id);
|
||||
|
||||
res.status(200).send(priceAlarms);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// POST pricealarms/
|
||||
pricealarmsRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get info for price alarm creation
|
||||
const product_id = req.body.product_id;
|
||||
const defined_price = req.body.defined_price;
|
||||
|
||||
if (!product_id || !defined_price) {
|
||||
// Missing
|
||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Create price alarm
|
||||
const success = await PriceAlarmsService.createPriceAlarm(user.user_id, product_id, defined_price);
|
||||
|
||||
if (success) {
|
||||
res.status(201).send(JSON.stringify({success: true}));
|
||||
return;
|
||||
} else {
|
||||
res.status(500).send(JSON.stringify({success: false}));
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// PUT pricealarms/
|
||||
pricealarmsRouter.put('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get info for price alarm creation
|
||||
const alarm_id = req.body.alarm_id;
|
||||
const defined_price = req.body.defined_price;
|
||||
|
||||
if (!alarm_id || !defined_price) {
|
||||
// Missing
|
||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Update price alarm
|
||||
const success = await PriceAlarmsService.updatePriceAlarm(alarm_id, user.user_id, defined_price);
|
||||
|
||||
if (success) {
|
||||
res.status(200).send(JSON.stringify({success: true}));
|
||||
return;
|
||||
} else {
|
||||
res.status(500).send(JSON.stringify({success: false}));
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE pricealarms/:id
|
||||
pricealarmsRouter.delete('/:id', async (req, res) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = (req.query.session_id ?? '').toString();
|
||||
const session_key = (req.query.session_key ?? '').toString();
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
const success = await PriceAlarmsService.deletePriceAlarm(id, user.user_id);
|
||||
|
||||
if (success) {
|
||||
res.status(200).send(JSON.stringify({success: true}));
|
||||
return;
|
||||
} else {
|
||||
res.status(500).send(JSON.stringify({success: false}));
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
85
src/models/betterzon/pricealarms/pricealarms.service.ts
Normal file
85
src/models/betterzon/pricealarms/pricealarms.service.ts
Normal file
|
@ -0,0 +1,85 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {PriceAlarms} from './pricealarms.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a price alarm for the given user for the product with the defined price
|
||||
* @param user_id The id of the user to create the price alarm for
|
||||
* @param product_id The id of the product to create the price alarm for
|
||||
* @param defined_price The defined price for the price alarm
|
||||
*/
|
||||
export const createPriceAlarm = async (user_id: number, product_id: number, defined_price: number): Promise<boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
const res = await conn.query('INSERT INTO price_alarms (user_id, product_id, defined_price) VALUES (?, ?, ?)', [user_id, product_id, defined_price]);
|
||||
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns all price alarms for the given user
|
||||
* @param user_id
|
||||
*/
|
||||
export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let priceAlarms = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT alarm_id, user_id, product_id, defined_price FROM price_alarms WHERE user_id = ?', user_id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
priceAlarms.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
return priceAlarms;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the given price alarm with the given fields
|
||||
* @param alarm_id The id of the price alarm to update
|
||||
* @param user_id The id of the user that wants to update the price alarm
|
||||
* @param defined_price The defined price for the price alarm
|
||||
*/
|
||||
export const updatePriceAlarm = async (alarm_id: number, user_id: number, defined_price: number): Promise<boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
const res = await conn.query('UPDATE price_alarms SET defined_price = ? WHERE alarm_id = ? AND user_id = ?', [defined_price, alarm_id, user_id]);
|
||||
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes the given price alarm
|
||||
* @param alarm_id The id of the price alarm to update
|
||||
* @param user_id The id of the user that wants to update the price alarm
|
||||
*/
|
||||
export const deletePriceAlarm = async (alarm_id: number, user_id: number): Promise<boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
const res = await conn.query('DELETE FROM price_alarms WHERE alarm_id = ? AND user_id = ?', [alarm_id, user_id]);
|
||||
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
27
src/models/betterzon/prices/price.interface.ts
Normal file
27
src/models/betterzon/prices/price.interface.ts
Normal file
|
@ -0,0 +1,27 @@
|
|||
export interface Price {
|
||||
price_id: number;
|
||||
product_id: number;
|
||||
vendor_id: number;
|
||||
price_in_cents: number;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export class Deal implements Price {
|
||||
price_id: number;
|
||||
product_id: number;
|
||||
vendor_id: number;
|
||||
price_in_cents: number;
|
||||
timestamp: Date;
|
||||
amazonDifference: number;
|
||||
amazonDifferencePercent: number;
|
||||
|
||||
constructor(price_id: number, product_id: number, vendor_id: number, price_in_cents: number, timestamp: Date, amazonDifference: number, amazonDifferencePercent: number) {
|
||||
this.price_id = price_id;
|
||||
this.product_id = product_id;
|
||||
this.vendor_id = vendor_id;
|
||||
this.price_in_cents = price_in_cents;
|
||||
this.timestamp = timestamp;
|
||||
this.amazonDifference = amazonDifference;
|
||||
this.amazonDifferencePercent = amazonDifferencePercent;
|
||||
}
|
||||
}
|
5
src/models/betterzon/prices/prices.interface.ts
Normal file
5
src/models/betterzon/prices/prices.interface.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
import {Price} from './price.interface';
|
||||
|
||||
export interface Prices {
|
||||
[key: number]: Price;
|
||||
}
|
130
src/models/betterzon/prices/prices.router.ts
Normal file
130
src/models/betterzon/prices/prices.router.ts
Normal file
|
@ -0,0 +1,130 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as PriceService from './prices.service';
|
||||
import {Price} from './price.interface';
|
||||
import {Prices} from './prices.interface';
|
||||
import * as UserService from '../users/users.service';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const pricesRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// GET prices/
|
||||
pricesRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let prices: Prices = [];
|
||||
const product = req.query.product;
|
||||
const vendor = req.query.vendor;
|
||||
const type = req.query.type;
|
||||
|
||||
if (product) {
|
||||
if (vendor) {
|
||||
prices = await PriceService.findByVendor(<string> product, <string> vendor, <string> type);
|
||||
} else {
|
||||
prices = await PriceService.findByType(<string> product, <string> type);
|
||||
}
|
||||
} else {
|
||||
prices = await PriceService.findAll();
|
||||
}
|
||||
|
||||
res.status(200).send(prices);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET prices/:id
|
||||
pricesRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const price: Price = await PriceService.find(id);
|
||||
|
||||
res.status(200).send(price);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET prices/bestDeals
|
||||
pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => {
|
||||
const amount: number = parseInt(req.params.amount, 10);
|
||||
|
||||
if (!amount) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const prices: Prices = await PriceService.getBestDeals(amount);
|
||||
|
||||
res.status(200).send(prices);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET prices/byProduct/list/[]
|
||||
pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) => {
|
||||
const productIds: [number] = JSON.parse(req.params.ids);
|
||||
|
||||
if (!productIds) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const prices: Prices = await PriceService.findListByProducts(productIds);
|
||||
|
||||
res.status(200).send(prices);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// POST prices/
|
||||
pricesRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get required parameters
|
||||
const vendor_id = req.body.vendor_id;
|
||||
const product_id = req.body.product_id;
|
||||
const price_in_cents = req.body.price_in_cents;
|
||||
|
||||
const success = await PriceService.createPriceEntry(user.user_id, vendor_id, product_id, price_in_cents);
|
||||
|
||||
if (success) {
|
||||
res.status(201).send({});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
350
src/models/betterzon/prices/prices.service.ts
Normal file
350
src/models/betterzon/prices/prices.service.ts
Normal file
|
@ -0,0 +1,350 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Deal, Price} from './price.interface';
|
||||
import {Prices} from './prices.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches and returns all known prices
|
||||
*/
|
||||
export const findAll = async (): Promise<Prices> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let priceRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT price_id, product_id, v.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE active_listing = true AND v.isActive = true');
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
let price: Price = {
|
||||
price_id: 0,
|
||||
price_in_cents: 0,
|
||||
product_id: 0,
|
||||
timestamp: new Date(),
|
||||
vendor_id: 0
|
||||
};
|
||||
const sqlPrice = rows[row];
|
||||
|
||||
price.price_id = sqlPrice.price_id;
|
||||
price.product_id = sqlPrice.product_id;
|
||||
price.vendor_id = sqlPrice.vendor_id;
|
||||
price.price_in_cents = sqlPrice.price_in_cents;
|
||||
price.timestamp = sqlPrice.timestamp;
|
||||
priceRows.push(price);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return priceRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the price with the specified id
|
||||
* @param id The id of the price to fetch
|
||||
*/
|
||||
export const find = async (id: number): Promise<Price> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let price: any;
|
||||
try {
|
||||
const rows = await conn.query('SELECT price_id, product_id, p.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE price_id = ? AND active_listing = true AND v.isActive = true', id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
price = rows[row];
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return price;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns all prices that belong to the specified product
|
||||
* @param product the product to fetch the prices for
|
||||
*/
|
||||
export const findByProduct = async (product: number): Promise<Prices> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let priceRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT price_id, product_id, p.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND active_listing = true AND v.isActive = true', product);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
priceRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return priceRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns prices that belong to the specified product.
|
||||
* If type is newest, only the newest prices for each vendor will be returned.
|
||||
* If type is lowest, the lowest daily price for the product is returned.
|
||||
* Otherwise, all prices for this product are returned.
|
||||
* @param product The product to fetch the prices for
|
||||
* @param type The type of prices, e.g. newest / lowest
|
||||
*/
|
||||
export const findByType = async (product: string, type: string): Promise<Prices> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let priceRows = [];
|
||||
try {
|
||||
let rows = [];
|
||||
if (type === 'newest') {
|
||||
// Used to get the newest price for this product per vendor
|
||||
rows = await conn.query(('WITH summary AS ( ' +
|
||||
'SELECT p.product_id, ' +
|
||||
'p.vendor_id, ' +
|
||||
'p.price_in_cents, ' +
|
||||
'p.timestamp, ' +
|
||||
'ROW_NUMBER() OVER( ' +
|
||||
'PARTITION BY p.vendor_id ' +
|
||||
'ORDER BY p.timestamp DESC) AS rk ' +
|
||||
'FROM prices p ' +
|
||||
'LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id ' +
|
||||
'WHERE product_id = ? AND p.vendor_id != 1 AND active_listing = true AND v.isActive = true) ' +
|
||||
'SELECT s.* ' +
|
||||
'FROM summary s ' +
|
||||
'WHERE s.rk = 1 '), product);
|
||||
} else if (type === 'lowest') {
|
||||
// Used to get the lowest prices for this product over a period of time
|
||||
rows = await conn.query('SELECT price_id, product_id, p.vendor_id, MIN(price_in_cents) as price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND v.vendor_id != 1 AND active_listing = true AND v.isActive = true GROUP BY DAY(timestamp) ORDER BY timestamp', product);
|
||||
} else {
|
||||
// If no type is given, return all prices for this product
|
||||
rows = await conn.query('SELECT price_id, product_id, p.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND p.vendor_id != 1 AND active_listing = true AND v.isActive = true', product);
|
||||
}
|
||||
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
priceRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return priceRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns prices that belong to the specified product and vendor.
|
||||
* If type is newest, only the newest known price for the product at the vendor is returned.
|
||||
* If type is lowest, only the lowest ever known price for the product at the vendor is returned.
|
||||
* Otherwise, all prices for this product are returned.
|
||||
* @param product The product to fetch the prices for
|
||||
* @param vendor The vendor to fetch the prices for
|
||||
* @param type The type of prices, e.g. newest / lowest
|
||||
*/
|
||||
export const findByVendor = async (product: string, vendor: string, type: string): Promise<Prices> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let priceRows = [];
|
||||
try {
|
||||
let rows = [];
|
||||
if (type === 'newest') {
|
||||
// Used to get the newest price for this product and vendor
|
||||
rows = await conn.query('SELECT price_id, product_id, p.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND p.vendor_id = ? AND active_listing = true AND v.isActive = true ORDER BY timestamp DESC LIMIT 1', [product, vendor]);
|
||||
} else if (type === 'lowest') {
|
||||
// Used to get the lowest prices for this product and vendor in all time
|
||||
rows = await conn.query('SELECT price_id, product_id, p.vendor_id, MIN(price_in_cents) as price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND p.vendor_id = ? AND active_listing = true AND v.isActive = true LIMIT 1', [product, vendor]);
|
||||
} else {
|
||||
// If no type is given, return all prices for this product and vendor
|
||||
rows = await conn.query('SELECT price_id, product_id, p.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND p.vendor_id = ? AND active_listing = true AND v.isActive = true', [product, vendor]);
|
||||
}
|
||||
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
priceRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return priceRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the best current deals, i.e. the non-amazon prices that have the biggest difference to amazon prices.
|
||||
* Only the latest known prices for every vendor are taken into consideration so we only get up-to-date-deals.
|
||||
* @param amount The amount of deals to return
|
||||
*/
|
||||
export const getBestDeals = async (amount: number): Promise<Prices> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let priceRows = [];
|
||||
try {
|
||||
let allPrices: Record<number, Price[]> = {};
|
||||
|
||||
// Get newest prices for every product at every vendor
|
||||
const rows = await conn.query(
|
||||
'WITH summary AS (\n' +
|
||||
' SELECT p.product_id,\n' +
|
||||
' p.vendor_id,\n' +
|
||||
' p.price_in_cents,\n' +
|
||||
' p.timestamp,\n' +
|
||||
' ROW_NUMBER() OVER(\n' +
|
||||
' PARTITION BY p.product_id, p.vendor_id\n' +
|
||||
' ORDER BY p.timestamp DESC) AS rk\n' +
|
||||
' FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE active_listing = true AND v.isActive = true)\n' +
|
||||
'SELECT s.*\n' +
|
||||
'FROM summary s\n' +
|
||||
'WHERE s.rk = 1');
|
||||
|
||||
// Write returned values to allPrices map with product id as key and a list of prices as value
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
if (!allPrices[parseInt(rows[row].product_id)]) {
|
||||
allPrices[parseInt(rows[row].product_id)] = [];
|
||||
}
|
||||
|
||||
allPrices[parseInt(rows[row].product_id)].push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate over all prices to find the products with the biggest difference between amazon and other vendor
|
||||
let deals: Deal[] = [];
|
||||
|
||||
Object.keys(allPrices).forEach(productId => {
|
||||
if (allPrices[parseInt(productId)]) {
|
||||
let pricesForProd = allPrices[parseInt(productId)];
|
||||
|
||||
// Get amazon price and lowest price from other vendor
|
||||
let amazonPrice = {} as Price;
|
||||
let lowestPrice = {} as Price;
|
||||
pricesForProd.forEach(function (price, priceIndex) {
|
||||
if (price.vendor_id === 1) {
|
||||
amazonPrice = price;
|
||||
} else {
|
||||
// If there is no lowest price yet or the price of the current iteration is lower, set / replace it
|
||||
if (!lowestPrice.price_in_cents || lowestPrice.price_in_cents > price.price_in_cents) {
|
||||
lowestPrice = price;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Create deal object and add it to list
|
||||
let deal = {
|
||||
'product_id': lowestPrice.product_id,
|
||||
'vendor_id': lowestPrice.vendor_id,
|
||||
'price_in_cents': lowestPrice.price_in_cents,
|
||||
'timestamp': lowestPrice.timestamp,
|
||||
'amazonDifference': (amazonPrice.price_in_cents - lowestPrice.price_in_cents),
|
||||
'amazonDifferencePercent': ((amazonPrice.price_in_cents / lowestPrice.price_in_cents) * 100)
|
||||
};
|
||||
|
||||
// Push only deals were the amazon price is actually higher
|
||||
if (deal.amazonDifferencePercent > 0 && deal.amazonDifference > 0) {
|
||||
deals.push(deal as Deal);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Sort to have the best deals on the top
|
||||
deals.sort((a, b) => a.amazonDifferencePercent! < b.amazonDifferencePercent! ? 1 : -1);
|
||||
|
||||
// Return only as many records as requested or the maximum amount of found deals, whatever is less
|
||||
let maxAmt = Math.min(amount, deals.length);
|
||||
|
||||
for (let dealIndex = 0; dealIndex < maxAmt; dealIndex++) {
|
||||
priceRows.push(deals[dealIndex] as Price);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
throw err;
|
||||
}
|
||||
|
||||
return priceRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the lowest, latest, non-amazon price for each given product
|
||||
* @param productIds the ids of the products
|
||||
*/
|
||||
export const findListByProducts = async (productIds: [number]): Promise<Prices> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let priceRows: Price[] = [];
|
||||
try {
|
||||
let allPrices: Record<number, Price[]> = {};
|
||||
|
||||
// Get newest prices for every given product at every vendor
|
||||
const rows = await conn.query(
|
||||
'WITH summary AS (\n' +
|
||||
' SELECT p.product_id,\n' +
|
||||
' p.vendor_id,\n' +
|
||||
' p.price_in_cents,\n' +
|
||||
' p.timestamp,\n' +
|
||||
' ROW_NUMBER() OVER(\n' +
|
||||
' PARTITION BY p.product_id, p.vendor_id\n' +
|
||||
' ORDER BY p.timestamp DESC) AS rk\n' +
|
||||
' FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id ' +
|
||||
' WHERE p.product_id IN (?) AND v.isActive = true' +
|
||||
' AND p.vendor_id != 1 AND active_listing = true)\n' +
|
||||
'SELECT s.*\n' +
|
||||
'FROM summary s\n' +
|
||||
'WHERE s.rk = 1', [productIds]);
|
||||
|
||||
// Write returned values to allPrices map with product id as key and a list of prices as value
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
if (!allPrices[parseInt(rows[row].product_id)]) {
|
||||
allPrices[parseInt(rows[row].product_id)] = [];
|
||||
}
|
||||
|
||||
allPrices[parseInt(rows[row].product_id)].push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate over all products to find lowest price
|
||||
Object.keys(allPrices).forEach(productId => {
|
||||
if (allPrices[parseInt(productId)]) {
|
||||
let pricesForProd = allPrices[parseInt(productId)];
|
||||
|
||||
// Sort ascending by price so index 0 has the lowest price
|
||||
pricesForProd.sort((a, b) => a.price_in_cents > b.price_in_cents ? 1 : -1);
|
||||
|
||||
// Push the lowest price to the return list
|
||||
priceRows.push(pricesForProd[0]);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return priceRows;
|
||||
};
|
||||
|
||||
export const createPriceEntry = async (user_id: number, vendor_id: number, product_id: number, price_in_cents: number): Promise<Boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Check if the user is authorized to manage the requested vendor
|
||||
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
||||
if (user_vendor_rows.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create price entry
|
||||
const res = await conn.query('INSERT INTO prices (product_id, vendor_id, price_in_cents) VALUES (?,?,?)', [product_id, vendor_id, price_in_cents]);
|
||||
|
||||
// If there are more / less than 1 affected rows, return false
|
||||
return res.affectedRows === 1;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
14
src/models/betterzon/products/product.interface.ts
Normal file
14
src/models/betterzon/products/product.interface.ts
Normal file
|
@ -0,0 +1,14 @@
|
|||
export interface Product {
|
||||
product_id: number;
|
||||
asin: string;
|
||||
is_active: boolean;
|
||||
name: string;
|
||||
short_description: string;
|
||||
long_description: string;
|
||||
image_guid: string;
|
||||
date_added: Date;
|
||||
last_modified: Date;
|
||||
manufacturer_id: number;
|
||||
selling_rank: string;
|
||||
category_id: number;
|
||||
}
|
5
src/models/betterzon/products/products.interface.ts
Normal file
5
src/models/betterzon/products/products.interface.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
import {Product} from './product.interface';
|
||||
|
||||
export interface Products {
|
||||
[key: number]: Product;
|
||||
}
|
131
src/models/betterzon/products/products.router.ts
Normal file
131
src/models/betterzon/products/products.router.ts
Normal file
|
@ -0,0 +1,131 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as ProductService from './products.service';
|
||||
import {Product} from './product.interface';
|
||||
import {Products} from './products.interface';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const productsRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// GET products/
|
||||
productsRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const products: Products = await ProductService.findAll();
|
||||
|
||||
res.status(200).send(products);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET products/:id
|
||||
productsRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const product: Product = await ProductService.find(id);
|
||||
|
||||
res.status(200).send(product);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET products/search/:term
|
||||
productsRouter.get('/search/:term', async (req: Request, res: Response) => {
|
||||
const term: string = req.params.term;
|
||||
|
||||
if (!term) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const products: Products = await ProductService.findBySearchTerm(term);
|
||||
|
||||
res.status(200).send(products);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET products/list/[1,2,3]
|
||||
productsRouter.get('/list/:ids', async (req: Request, res: Response) => {
|
||||
const ids: [number] = JSON.parse(req.params.ids);
|
||||
|
||||
if (!ids) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const products: Products = await ProductService.findList(ids);
|
||||
|
||||
res.status(200).send(products);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET products/vendor/:id
|
||||
productsRouter.get('/vendor/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const products: Products = await ProductService.findByVendor(id);
|
||||
|
||||
res.status(200).send(products);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// POST products/
|
||||
productsRouter.post('/', async (req: Request, res: Response) => {
|
||||
const asin: string = req.body.asin;
|
||||
|
||||
if (!asin) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result: boolean = await ProductService.addNewProduct(asin);
|
||||
|
||||
if (result) {
|
||||
res.status(201).send({});
|
||||
} else {
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
194
src/models/betterzon/products/products.service.ts
Normal file
194
src/models/betterzon/products/products.service.ts
Normal file
|
@ -0,0 +1,194 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Product} from './product.interface';
|
||||
import {Products} from './products.interface';
|
||||
import * as http from 'http';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches and returns all known products
|
||||
*/
|
||||
export const findAll = async (): Promise<Products> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let prodRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products');
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
let prod: Product = {
|
||||
asin: '',
|
||||
category_id: 0,
|
||||
date_added: new Date(),
|
||||
image_guid: '',
|
||||
is_active: false,
|
||||
last_modified: new Date(),
|
||||
long_description: '',
|
||||
manufacturer_id: 0,
|
||||
name: '',
|
||||
product_id: 0,
|
||||
selling_rank: '',
|
||||
short_description: ''
|
||||
};
|
||||
const sqlProd = rows[row];
|
||||
|
||||
prod.product_id = sqlProd.product_id;
|
||||
prod.name = sqlProd.name;
|
||||
prod.asin = sqlProd.asin;
|
||||
prod.is_active = sqlProd.is_active;
|
||||
prod.short_description = sqlProd.short_description;
|
||||
prod.long_description = sqlProd.long_description;
|
||||
prod.image_guid = sqlProd.image_guid;
|
||||
prod.date_added = sqlProd.date_added;
|
||||
prod.last_modified = sqlProd.last_modified;
|
||||
prod.manufacturer_id = sqlProd.manufacturer_id;
|
||||
prod.selling_rank = sqlProd.selling_rank;
|
||||
prod.category_id = sqlProd.category_id;
|
||||
prodRows.push(prod);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return prodRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the product with the specified id
|
||||
* @param id The id of the product to fetch
|
||||
*/
|
||||
export const find = async (id: number): Promise<Product> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let prod: any;
|
||||
try {
|
||||
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE product_id = ?', id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
prod = rows[row];
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return prod;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns all products that match the search term
|
||||
* @param term the term to match
|
||||
*/
|
||||
export const findBySearchTerm = async (term: string): Promise<Products> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let prodRows = [];
|
||||
try {
|
||||
term = '%' + term + '%';
|
||||
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE name LIKE ?', term);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
prodRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
throw err;
|
||||
}
|
||||
|
||||
return prodRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the product details for the given list of product ids
|
||||
* @param ids The list of product ids to fetch the details for
|
||||
*/
|
||||
export const findList = async (ids: [number]): Promise<Products> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let prodRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE product_id IN (?)', [ids]);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
prodRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return prodRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the products that the given vendor has price entries for
|
||||
* @param id The id of the vendor to fetch the products for
|
||||
*/
|
||||
export const findByVendor = async (id: number): Promise<Products> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let prodRows = [];
|
||||
try {
|
||||
// Get the relevant product ids
|
||||
let relevant_prod_ids = [];
|
||||
const relevantProds = await conn.query('SELECT product_id FROM prices WHERE vendor_id = ? GROUP BY product_id', id);
|
||||
for (let row in relevantProds) {
|
||||
if (row !== 'meta') {
|
||||
relevant_prod_ids.push(relevantProds[row].product_id);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch products
|
||||
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE product_id IN (?)', [relevant_prod_ids]);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
prodRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return prodRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes a callout to a crawler instance to search for the requested product
|
||||
* @param asin The amazon asin of the product to look for
|
||||
*/
|
||||
export const addNewProduct = async (asin: string): Promise<boolean> => {
|
||||
try {
|
||||
let options = {
|
||||
host: 'crawl.p4ddy.com',
|
||||
path: '/searchNew',
|
||||
port: '443',
|
||||
method: 'POST'
|
||||
};
|
||||
|
||||
let req = http.request(options, res => {
|
||||
return res.statusCode === 202;
|
||||
});
|
||||
req.write(JSON.stringify({
|
||||
asin: asin,
|
||||
key: process.env.CRAWLER_ACCESS_KEY
|
||||
}));
|
||||
req.end();
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
throw(err);
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
10
src/models/betterzon/users/session.interface.ts
Normal file
10
src/models/betterzon/users/session.interface.ts
Normal file
|
@ -0,0 +1,10 @@
|
|||
export interface Session {
|
||||
session_id: number;
|
||||
session_key: string;
|
||||
session_key_hash: string;
|
||||
createdDate?: Date;
|
||||
lastLogin?: Date;
|
||||
validUntil?: Date;
|
||||
validDays?: number;
|
||||
last_IP: string;
|
||||
}
|
9
src/models/betterzon/users/user.interface.ts
Normal file
9
src/models/betterzon/users/user.interface.ts
Normal file
|
@ -0,0 +1,9 @@
|
|||
export interface User {
|
||||
user_id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
password_hash: string;
|
||||
registration_date: Date;
|
||||
last_login_date: Date;
|
||||
is_admin: boolean;
|
||||
}
|
5
src/models/betterzon/users/users.interface.ts
Normal file
5
src/models/betterzon/users/users.interface.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
import {User} from './user.interface';
|
||||
|
||||
export interface Users {
|
||||
[key: number]: User;
|
||||
}
|
121
src/models/betterzon/users/users.router.ts
Normal file
121
src/models/betterzon/users/users.router.ts
Normal file
|
@ -0,0 +1,121 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as UserService from './users.service';
|
||||
import {User} from './user.interface';
|
||||
import {Users} from './users.interface';
|
||||
import {Session} from './session.interface';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const usersRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// POST users/register
|
||||
usersRouter.post('/register', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const username: string = req.body.username;
|
||||
const password: string = req.body.password;
|
||||
const email: string = req.body.email;
|
||||
const ip: string = req.connection.remoteAddress ?? '';
|
||||
|
||||
if (!username || !password || !email) {
|
||||
// Missing
|
||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if username and / or email are already used
|
||||
const status = await UserService.checkUsernameAndEmail(username, email);
|
||||
|
||||
if (status.hasProblems) {
|
||||
// Username and/or email are duplicates, return error
|
||||
res.status(400).send(JSON.stringify({messages: status.messages, codes: status.codes}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the user and a session
|
||||
const session: Session = await UserService.createUser(username, password, email, ip);
|
||||
|
||||
// Send the session details back to the user
|
||||
res.status(201).send({
|
||||
session_id: session.session_id,
|
||||
session_key: session.session_key
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// POST users/login
|
||||
usersRouter.post('/login', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const username: string = req.body.username;
|
||||
const password: string = req.body.password;
|
||||
const ip: string = req.connection.remoteAddress ?? '';
|
||||
|
||||
if (!username || !password) {
|
||||
// Missing
|
||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the user entry and create a session
|
||||
const session: Session = await UserService.login(username, password, ip);
|
||||
|
||||
if (!session.session_id) {
|
||||
// Error logging in, probably wrong username / password
|
||||
res.status(401).send(JSON.stringify({messages: ['Wrong username and / or password'], codes: [1, 4]}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Send the session details back to the user
|
||||
res.status(200).send({
|
||||
session_id: session.session_id,
|
||||
session_key: session.session_key
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// POST users/checkSessionValid
|
||||
usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const ip: string = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
|
||||
if(!session_id || !session_key) {
|
||||
// Error logging in, probably wrong username / password
|
||||
res.status(401).send(JSON.stringify({messages: ['No session detected'], codes: [5]}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the user entry and create a session
|
||||
const user: User = await UserService.checkSession(session_id, session_key, ip);
|
||||
|
||||
if (!user.user_id) {
|
||||
// Error logging in, probably wrong username / password
|
||||
res.status(401).send(JSON.stringify({messages: ['Invalid session'], codes: [5]}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Send the session details back to the user
|
||||
res.status(200).send(user);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
286
src/models/betterzon/users/users.service.ts
Normal file
286
src/models/betterzon/users/users.service.ts
Normal file
|
@ -0,0 +1,286 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import {User} from './user.interface';
|
||||
import {Session} from './session.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a user record in the database, also creates a session. Returns the session if successful.
|
||||
*/
|
||||
export const createUser = async (username: string, password: string, email: string, ip: string): Promise<Session> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Hash password and generate + hash session key
|
||||
const pwHash = bcrypt.hashSync(password, 10);
|
||||
const sessionKey = Guid.create().toString();
|
||||
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
||||
|
||||
// Create user entry in SQL
|
||||
const userQuery = 'INSERT INTO users (username, email, bcrypt_password_hash) VALUES (?, ?, ?) RETURNING user_id';
|
||||
const userIdRes = await conn.query(userQuery, [username, email, pwHash]);
|
||||
await conn.commit();
|
||||
|
||||
// Get user id of the created user
|
||||
let userId: number = -1;
|
||||
for (const row in userIdRes) {
|
||||
if (row !== 'meta' && userIdRes[row].user_id != null) {
|
||||
userId = userIdRes[row].user_id;
|
||||
}
|
||||
}
|
||||
|
||||
// Create session
|
||||
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, createdDate, lastLogin, validUntil, validDays, last_IP) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),30,?) RETURNING session_id';
|
||||
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
|
||||
await conn.commit();
|
||||
|
||||
// Get session id of the created session
|
||||
let sessionId: number = -1;
|
||||
for (const row in sessionIdRes) {
|
||||
if (row !== 'meta' && sessionIdRes[row].session_id != null) {
|
||||
sessionId = sessionIdRes[row].session_id;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
session_id: sessionId,
|
||||
session_key: sessionKey,
|
||||
session_key_hash: 'HIDDEN',
|
||||
last_IP: ip
|
||||
};
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return {} as Session;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the given credentials are valid and creates a new session if they are.
|
||||
* Returns the session information in case of a successful login
|
||||
*/
|
||||
export const login = async (username: string, password: string, ip: string): Promise<Session> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Get saved password hash
|
||||
const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?';
|
||||
const userRows = await conn.query(query, username);
|
||||
let savedHash = '';
|
||||
let userId = -1;
|
||||
for (const row in userRows) {
|
||||
if (row !== 'meta' && userRows[row].user_id != null) {
|
||||
savedHash = userRows[row].bcrypt_password_hash;
|
||||
userId = userRows[row].user_id;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for correct password
|
||||
if (!bcrypt.compareSync(password, savedHash)) {
|
||||
// Wrong password, return invalid
|
||||
return {} as Session;
|
||||
}
|
||||
// Password is valid, continue
|
||||
|
||||
// Generate + hash session key
|
||||
const sessionKey = Guid.create().toString();
|
||||
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
||||
|
||||
// Update user entry in SQL
|
||||
const userQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
|
||||
const userIdRes = await conn.query(userQuery, userId);
|
||||
await conn.commit();
|
||||
|
||||
// Create session
|
||||
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, createdDate, lastLogin, validUntil, validDays, last_IP) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),30,?) RETURNING session_id';
|
||||
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
|
||||
await conn.commit();
|
||||
|
||||
// Get session id of the created session
|
||||
let sessionId: number = -1;
|
||||
for (const row in sessionIdRes) {
|
||||
if (row !== 'meta' && sessionIdRes[row].session_id != null) {
|
||||
sessionId = sessionIdRes[row].session_id;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
session_id: sessionId,
|
||||
session_key: sessionKey,
|
||||
session_key_hash: 'HIDDEN',
|
||||
last_IP: ip
|
||||
};
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return {} as Session;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the given session information are valid and returns the user information if they are
|
||||
*/
|
||||
export const checkSession = async (sessionId: string, sessionKey: string, ip: string): Promise<User> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Get saved session key hash
|
||||
const query = 'SELECT user_id, session_key_hash, validUntil FROM sessions WHERE session_id = ?';
|
||||
const sessionRows = await conn.query(query, sessionId);
|
||||
let savedHash = '';
|
||||
let userId = -1;
|
||||
let validUntil = new Date();
|
||||
for (const row in sessionRows) {
|
||||
if (row !== 'meta' && sessionRows[row].user_id != null) {
|
||||
savedHash = sessionRows[row].session_key_hash;
|
||||
userId = sessionRows[row].user_id;
|
||||
validUntil = sessionRows[row].validUntil;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for correct key
|
||||
if (!bcrypt.compareSync(sessionKey, savedHash)) {
|
||||
// Wrong key, return invalid
|
||||
return {} as User;
|
||||
}
|
||||
// Key is valid, continue
|
||||
|
||||
// Check if the session is still valid
|
||||
if (validUntil <= new Date()) {
|
||||
// Session expired, return invalid
|
||||
return {} as User;
|
||||
}
|
||||
// Session still valid, continue
|
||||
|
||||
// Update session entry in SQL
|
||||
const updateSessionsQuery = 'UPDATE sessions SET lastLogin = NOW(), last_IP = ? WHERE session_id = ?';
|
||||
const updateUsersQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
|
||||
const userIdRes = await conn.query(updateSessionsQuery, [ip, sessionId]);
|
||||
await conn.query(updateUsersQuery, userId);
|
||||
await conn.commit();
|
||||
|
||||
// Get the other required user information and update the user
|
||||
const userQuery = 'SELECT user_id, username, email, registration_date, last_login_date, is_admin FROM users WHERE user_id = ?';
|
||||
const userRows = await conn.query(userQuery, userId);
|
||||
let username = '';
|
||||
let email = '';
|
||||
let registrationDate = new Date();
|
||||
let lastLoginDate = new Date();
|
||||
let is_admin = false;
|
||||
for (const row in userRows) {
|
||||
if (row !== 'meta' && userRows[row].user_id != null) {
|
||||
username = userRows[row].username;
|
||||
email = userRows[row].email;
|
||||
registrationDate = userRows[row].registration_date;
|
||||
lastLoginDate = userRows[row].last_login_date;
|
||||
is_admin = userRows[row].is_admin;
|
||||
}
|
||||
}
|
||||
|
||||
// Everything is fine, return user information
|
||||
return {
|
||||
user_id: userId,
|
||||
username: username,
|
||||
email: email,
|
||||
password_hash: 'HIDDEN',
|
||||
registration_date: registrationDate,
|
||||
last_login_date: lastLoginDate,
|
||||
is_admin: is_admin
|
||||
};
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Calls the checkSession method after extracting the required information from the authentication cookie
|
||||
* @param cookie The betterauth cookie
|
||||
* @param ip The users IP address
|
||||
*/
|
||||
export const checkSessionWithCookie = async (cookie: any, ip: string): Promise<User> => {
|
||||
const parsedCookie = JSON.parse(cookie);
|
||||
const session_id = parsedCookie.id;
|
||||
const session_key = parsedCookie.key;
|
||||
|
||||
|
||||
return checkSession(session_id, session_key, '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Used in the checkUsernameAndEmail method as return value
|
||||
*/
|
||||
export interface Status {
|
||||
hasProblems: boolean;
|
||||
messages: string[];
|
||||
codes: number[]; // 0 = all good, 1 = wrong username, 2 = wrong email, 3 = server error, 4 = wrong password, 5 = wrong session
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given username and email are not used yet by another user
|
||||
* @param username The username to check
|
||||
* @param email The email to check
|
||||
*/
|
||||
export const checkUsernameAndEmail = async (username: string, email: string): Promise<Status> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Create user entry in SQL
|
||||
const usernameQuery = 'SELECT username FROM users WHERE username = ?';
|
||||
const emailQuery = 'SELECT email FROM users WHERE email = ?';
|
||||
const usernameRes = await conn.query(usernameQuery, username);
|
||||
const emailRes = await conn.query(emailQuery, email);
|
||||
|
||||
let res: Status = {
|
||||
hasProblems: false,
|
||||
messages: [],
|
||||
codes: []
|
||||
};
|
||||
|
||||
const usernameRegex = RegExp('^[a-zA-Z0-9\\-\\_]{4,20}$'); // Can contain a-z, A-Z, 0-9, -, _ and has to be 4-20 chars long
|
||||
if (!usernameRegex.test(username)) {
|
||||
// Username doesn't match requirements
|
||||
res.hasProblems = true;
|
||||
res.messages.push('Invalid username');
|
||||
res.codes.push(1);
|
||||
}
|
||||
|
||||
const emailRegex = RegExp('^[a-zA-Z0-9\\-\\_.]{1,30}\\@[a-zA-Z0-9\\-.]{1,20}\\.[a-z]{1,20}$'); // Normal email regex, user@betterzon.xyz
|
||||
if (!emailRegex.test(email)) {
|
||||
// Username doesn't match requirements
|
||||
res.hasProblems = true;
|
||||
res.messages.push('Invalid email');
|
||||
res.codes.push(2);
|
||||
}
|
||||
|
||||
if (usernameRes.length > 0) {
|
||||
// Username is a duplicate
|
||||
res.hasProblems = true;
|
||||
res.messages.push('Duplicate username');
|
||||
res.codes.push(1);
|
||||
}
|
||||
|
||||
if (emailRes.length > 0) {
|
||||
// Email is a duplicate
|
||||
res.hasProblems = true;
|
||||
res.messages.push('Duplicate email');
|
||||
res.codes.push(2);
|
||||
}
|
||||
|
||||
return res;
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
10
src/models/betterzon/vendors/vendor.interface.ts
vendored
Normal file
10
src/models/betterzon/vendors/vendor.interface.ts
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
export interface Vendor {
|
||||
vendor_id: number;
|
||||
name: string;
|
||||
streetname: string;
|
||||
zip_code: string;
|
||||
city: string;
|
||||
country_code: string;
|
||||
phone: string;
|
||||
website: string;
|
||||
}
|
5
src/models/betterzon/vendors/vendors.interface.ts
vendored
Normal file
5
src/models/betterzon/vendors/vendors.interface.ts
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
import {Vendor} from './vendor.interface';
|
||||
|
||||
export interface Vendors {
|
||||
[key: number]: Vendor;
|
||||
}
|
165
src/models/betterzon/vendors/vendors.router.ts
vendored
Normal file
165
src/models/betterzon/vendors/vendors.router.ts
vendored
Normal file
|
@ -0,0 +1,165 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
|
||||
import express, {Request, Response} from 'express';
|
||||
import * as VendorService from './vendors.service';
|
||||
import {Vendor} from './vendor.interface';
|
||||
import {Vendors} from './vendors.interface';
|
||||
import * as UserService from '../users/users.service';
|
||||
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
|
||||
export const vendorsRouter = express.Router();
|
||||
|
||||
|
||||
/**
|
||||
* Controller Definitions
|
||||
*/
|
||||
|
||||
// GET vendors/
|
||||
vendorsRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const vendors: Vendors = await VendorService.findAll();
|
||||
|
||||
res.status(200).send(vendors);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET vendors/managed
|
||||
vendorsRouter.get('/managed', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = (req.query.session_id ?? '').toString();
|
||||
const session_key = (req.query.session_key ?? '').toString();
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
const vendors = await VendorService.getManagedShops(user.user_id);
|
||||
|
||||
res.status(200).send(vendors);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET vendors/:id
|
||||
vendorsRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
const id: number = parseInt(req.params.id, 10);
|
||||
|
||||
if (!id) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const vendor: Vendor = await VendorService.find(id);
|
||||
|
||||
res.status(200).send(vendor);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// GET vendors/search/:term
|
||||
vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
|
||||
const term: string = req.params.term;
|
||||
|
||||
if (!term) {
|
||||
res.status(400).send('Missing parameters.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const vendors: Vendors = await VendorService.findBySearchTerm(term);
|
||||
|
||||
res.status(200).send(vendors);
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// PUT vendors/manage/deactivatelisting
|
||||
vendorsRouter.put('/manage/deactivatelisting', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get required parameters
|
||||
const vendor_id = req.body.vendor_id;
|
||||
const product_id = req.body.product_id;
|
||||
|
||||
const success = await VendorService.deactivateListing(user.user_id, vendor_id, product_id);
|
||||
|
||||
if (success) {
|
||||
res.status(200).send({});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// PUT vendors/manage/shop/deactivate/:id
|
||||
vendorsRouter.put('/manage/shop/deactivate/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get required parameters
|
||||
const vendor_id = parseInt(req.params.id, 10);
|
||||
|
||||
const success = await VendorService.setShopStatus(user.user_id, vendor_id, false);
|
||||
|
||||
if (success) {
|
||||
res.status(200).send({});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
||||
|
||||
// PUT vendors/manage/shop/activate/:id
|
||||
vendorsRouter.put('/manage/shop/activate/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user_ip = req.connection.remoteAddress ?? '';
|
||||
const session_id = req.body.session_id;
|
||||
const session_key = req.body.session_key;
|
||||
const user = await UserService.checkSession(session_id, session_key, user_ip);
|
||||
|
||||
// Get required parameters
|
||||
const vendor_id = parseInt(req.params.id, 10);
|
||||
|
||||
const success = await VendorService.setShopStatus(user.user_id, vendor_id, true);
|
||||
|
||||
if (success) {
|
||||
res.status(200).send({});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error handling a request: ' + e.message);
|
||||
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
|
||||
}
|
||||
});
|
174
src/models/betterzon/vendors/vendors.service.ts
vendored
Normal file
174
src/models/betterzon/vendors/vendors.service.ts
vendored
Normal file
|
@ -0,0 +1,174 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Vendor} from './vendor.interface';
|
||||
import {Vendors} from './vendors.interface';
|
||||
import {BetterzonDB} from '../Betterzon.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Data Model Interfaces
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Service Methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches and returns all known vendors
|
||||
*/
|
||||
export const findAll = async (): Promise<Vendors> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let vendorRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE isActive = true');
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
let vendor: Vendor = {
|
||||
city: '',
|
||||
country_code: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
streetname: '',
|
||||
vendor_id: 0,
|
||||
website: '',
|
||||
zip_code: ''
|
||||
};
|
||||
const sqlVendor = rows[row];
|
||||
|
||||
vendor.vendor_id = sqlVendor.vendor_id;
|
||||
vendor.name = sqlVendor.name;
|
||||
vendor.streetname = sqlVendor.streetname;
|
||||
vendor.zip_code = sqlVendor.zip_code;
|
||||
vendor.city = sqlVendor.city;
|
||||
vendor.country_code = sqlVendor.country_code;
|
||||
vendor.phone = sqlVendor.phone;
|
||||
vendor.website = sqlVendor.website;
|
||||
vendorRows.push(vendor);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return vendorRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns the vendor with the specified id
|
||||
* @param id The id of the vendor to fetch
|
||||
*/
|
||||
export const find = async (id: number): Promise<Vendor> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let vendor: any;
|
||||
try {
|
||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE vendor_id = ? AND isActive = true', id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
vendor = rows[row];
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return vendor;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns all vendors that match the search term
|
||||
* @param term the term to match
|
||||
*/
|
||||
export const findBySearchTerm = async (term: string): Promise<Vendors> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let vendorRows = [];
|
||||
try {
|
||||
term = '%' + term + '%';
|
||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE name LIKE ? AND isActive = true', term);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
vendorRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return vendorRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all vendors that have the given user as admin
|
||||
* @param user The user to return the managed shops for
|
||||
*/
|
||||
export const getManagedShops = async (user_id: number): Promise<Vendors> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
let vendorRows = [];
|
||||
try {
|
||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE admin_id LIKE ?', user_id);
|
||||
for (let row in rows) {
|
||||
if (row !== 'meta') {
|
||||
vendorRows.push(rows[row]);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return vendorRows;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deactivates a product listing for a specific vendor
|
||||
* @param user_id The user id of the issuing user
|
||||
* @param vendor_id The vendor id of the vendor to deactivate the listing for
|
||||
* @param product_id The product id of the product to deactivate the listing for
|
||||
*/
|
||||
export const deactivateListing = async (user_id: number, vendor_id: number, product_id: number): Promise<Boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Check if the user is authorized to manage the requested vendor
|
||||
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
||||
if (user_vendor_rows.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const status = await conn.query('UPDATE prices SET active_listing = false WHERE vendor_id = ? and product_id = ?', [vendor_id, product_id]);
|
||||
|
||||
return status.affectedRows > 0;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the specified shop to either active or not active
|
||||
* @param user_id The user id of the issuing user
|
||||
* @param vendor_id The vendor id of the shop to update
|
||||
* @param isActive The new active state
|
||||
*/
|
||||
export const setShopStatus = async (user_id: number, vendor_id: number, isActive: boolean): Promise<Boolean> => {
|
||||
let conn = BetterzonDB.getConnection();
|
||||
try {
|
||||
// Check if the user is authorized to manage the requested vendor
|
||||
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
||||
if (user_vendor_rows.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update the vendor state
|
||||
const status = await conn.query('UPDATE vendors SET isActive = ? WHERE vendor_id = ?', [isActive, vendor_id]);
|
||||
|
||||
return status.affectedRows > 0;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
19
src/models/climbing-route-rating/ClimbingRouteRating.db.ts
Normal file
19
src/models/climbing-route-rating/ClimbingRouteRating.db.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export namespace ClimbingRouteRatingDB {
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.CRR_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
export function getConnection() {
|
||||
return pool;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
import express, {Request, Response} from 'express';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import logger from '../../middleware/logger';
|
||||
import {climbingGymRouter} from './climbing_gyms/climbingGyms.router';
|
||||
import {climbingRoutesRouter} from './climbing_routes/climbingRoutes.router';
|
||||
import {routeCommentsRouter} from './route_comments/routeComments.router';
|
||||
import {routeRatingsRouter} from './route_ratings/routeRatings.router';
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
export const crrRouter = express.Router();
|
||||
|
||||
// Sub-Endpoints
|
||||
crrRouter.use('/gyms', climbingGymRouter);
|
||||
crrRouter.use('/routes', climbingRoutesRouter);
|
||||
crrRouter.use('/comments', routeCommentsRouter);
|
||||
crrRouter.use('/ratings', routeRatingsRouter);
|
||||
|
||||
crrRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
res.status(200).send('Pluto Development Climbing Route Rating API Endpoint');
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
|
@ -0,0 +1,6 @@
|
|||
export interface ClimbingGym {
|
||||
gym_id: number;
|
||||
name: string;
|
||||
city: string;
|
||||
verified: boolean;
|
||||
}
|
|
@ -0,0 +1,152 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
import express, {Request, Response} from 'express';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import logger from '../../../middleware/logger';
|
||||
import {ClimbingGym} from './ClimbingGym.interface';
|
||||
import * as GymService from './climbingGyms.service';
|
||||
import {verifyCaptcha} from '../common/VerifyCaptcha';
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
export const climbingGymRouter = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/gyms:
|
||||
* get:
|
||||
* summary: Retrieve all known climbing gyms
|
||||
* description: Returns all climbing gyms in a JSON list
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Success
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* gym_id:
|
||||
* type: integer
|
||||
* description: The gym id
|
||||
* example: 1
|
||||
* name:
|
||||
* type: string
|
||||
* description: The gym name
|
||||
* example: DAV Kletterhalle
|
||||
* city:
|
||||
* type: string
|
||||
* description: The city where the gym is in
|
||||
* example: Karlsruhe
|
||||
* verified:
|
||||
* type: boolean
|
||||
* description: If the gym is verified
|
||||
* example: 1
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
*/
|
||||
climbingGymRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const gyms: ClimbingGym[] = await GymService.findAll();
|
||||
|
||||
res.status(200).send(gyms);
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/gyms:
|
||||
* post:
|
||||
* summary: Create a new climbing gym
|
||||
* description: Creates a new climbing gym and returns the id of the created gym
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Created
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* gym_id:
|
||||
* type: integer
|
||||
* description: The gym id
|
||||
* example: 1
|
||||
* 400:
|
||||
* description: Wrong parameters, see response body for detailed information
|
||||
* 403:
|
||||
* description: Invalid captcha, please try again.
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: name
|
||||
* required: true
|
||||
* description: The name of the gym
|
||||
* schema:
|
||||
* type: string
|
||||
* example: DAV Kletterhalle
|
||||
* - in: query
|
||||
* name: city
|
||||
* required: true
|
||||
* description: The city where the gym is in
|
||||
* schema:
|
||||
* type: string
|
||||
* example: Karlsruhe
|
||||
* - in: query
|
||||
* name: hcaptcha_response
|
||||
* required: true
|
||||
* description: The hCaptcha response key
|
||||
* schema:
|
||||
* type: string
|
||||
* example: P0_ey[...]bVu
|
||||
*/
|
||||
climbingGymRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let name = req.query.name as string;
|
||||
let city = req.query.city as string;
|
||||
let captcha_token = req.query['hcaptcha_response'] as string;
|
||||
|
||||
if (!name || !city || !captcha_token) {
|
||||
res.status(400).send({'message': 'Missing parameters'});
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
let success = await verifyCaptcha(captcha_token);
|
||||
if (!success) {
|
||||
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
|
||||
return;
|
||||
}
|
||||
|
||||
let result = await GymService.createGym(name, city);
|
||||
|
||||
if (result) {
|
||||
res.status(201).send({'gym_id': result});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
|
@ -0,0 +1,33 @@
|
|||
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
|
||||
import {ClimbingGym} from './ClimbingGym.interface';
|
||||
|
||||
/**
|
||||
* Fetches and returns all known climbing gyms
|
||||
* @return Promise<ClimbingHall[]> The climbing halls
|
||||
*/
|
||||
export const findAll = async (): Promise<ClimbingGym[]> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
try {
|
||||
return await conn.query('SELECT gym_id, name, city, verified FROM climbing_gyms');
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a climbing gym and returns the id of the created gym
|
||||
* @param name The name of the climbing hall
|
||||
* @param city The city of the climbing hall
|
||||
* @return number The id of the climbing hall
|
||||
*/
|
||||
export const createGym = async (name: string, city: string): Promise<number> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
|
||||
try {
|
||||
let res = await conn.query('INSERT INTO climbing_gyms (name, city) VALUES (?, ?) RETURNING gym_id', [name, city]);
|
||||
|
||||
return res[0].gym_id;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
|
@ -0,0 +1,7 @@
|
|||
export interface ClimbingRoute {
|
||||
route_id: string;
|
||||
gym_id: number;
|
||||
name: string;
|
||||
difficulty: string;
|
||||
route_setting_date: Date;
|
||||
}
|
|
@ -0,0 +1,226 @@
|
|||
/**
|
||||
* Required External Modules and Interfaces
|
||||
*/
|
||||
import express, {Request, Response} from 'express';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import logger from '../../../middleware/logger';
|
||||
import {ClimbingRoute} from './ClimbingRoute.interface';
|
||||
import * as RouteService from './climbingRoutes.service';
|
||||
import {verifyCaptcha} from '../common/VerifyCaptcha';
|
||||
|
||||
/**
|
||||
* Router Definition
|
||||
*/
|
||||
export const climbingRoutesRouter = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/routes:
|
||||
* get:
|
||||
* summary: Retrieve all known climbing routes
|
||||
* description: Returns all climbing routes in a JSON list
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Success
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* route_id:
|
||||
* type: string
|
||||
* description: The route id
|
||||
* example: duck-score-guide
|
||||
* gym_id:
|
||||
* type: integer
|
||||
* description: The id of the gym that the route belongs to
|
||||
* example: 1
|
||||
* name:
|
||||
* type: string
|
||||
* description: The route name
|
||||
* example: Mary Poppins
|
||||
* difficulty:
|
||||
* type: string
|
||||
* description: The difficulty of the route
|
||||
* example: 'DE: 5, FR: 5c'
|
||||
* route_setting_date:
|
||||
* type: datetime
|
||||
* description: The route setting date
|
||||
* example: 2022-01-07T23:00:00.000Z
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
*/
|
||||
climbingRoutesRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const routes: ClimbingRoute[] = await RouteService.findAll();
|
||||
|
||||
res.status(200).send(routes);
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/routes/{id}:
|
||||
* get:
|
||||
* summary: Retrieve the route with the given id
|
||||
* description: Returns the climbing route with the given id if it exists
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Success
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* route_id:
|
||||
* type: string
|
||||
* description: The route id
|
||||
* example: duck-score-guide
|
||||
* gym_id:
|
||||
* type: integer
|
||||
* description: The id of the gym that the route belongs to
|
||||
* example: 1
|
||||
* name:
|
||||
* type: string
|
||||
* description: The route name
|
||||
* example: Mary Poppins
|
||||
* difficulty:
|
||||
* type: string
|
||||
* description: The difficulty of the route
|
||||
* example: 'DE: 5, FR: 5c'
|
||||
* route_setting_date:
|
||||
* type: datetime
|
||||
* description: The route setting date
|
||||
* example: 2022-01-07T23:00:00.000Z
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* description: The id of the route
|
||||
* schema:
|
||||
* type: string
|
||||
* example: duck-score-guide
|
||||
*/
|
||||
climbingRoutesRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let route_id = req.params.id;
|
||||
|
||||
const route: ClimbingRoute = await RouteService.findById(route_id);
|
||||
|
||||
res.status(200).send(route);
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/routes:
|
||||
* post:
|
||||
* summary: Create a new climbing route
|
||||
* description: Creates a new climbing route and returns the id of the created route
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Created
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* route_id:
|
||||
* type: string
|
||||
* description: The route id
|
||||
* example: duck-score-guide
|
||||
* 400:
|
||||
* description: Wrong parameters, see response body for detailed information
|
||||
* 403:
|
||||
* description: Invalid captcha, please try again.
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: gym_id
|
||||
* required: true
|
||||
* description: The gym id of the gym that the route belongs to
|
||||
* schema:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* - in: query
|
||||
* name: name
|
||||
* required: true
|
||||
* description: The name of the route
|
||||
* schema:
|
||||
* type: string
|
||||
* example: Mary Poppins
|
||||
* - in: query
|
||||
* name: difficulty
|
||||
* required: true
|
||||
* description: The difficulty of the route
|
||||
* schema:
|
||||
* type: string
|
||||
* example: 'DE: 5, FR: 5c'
|
||||
* - in: query
|
||||
* name: hcaptcha_response
|
||||
* required: true
|
||||
* description: The hCaptcha response key
|
||||
* schema:
|
||||
* type: string
|
||||
* example: P0_ey[...]bVu
|
||||
*/
|
||||
climbingRoutesRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let gym_id = Number(req.query.gym_id);
|
||||
let name = req.query.name as string;
|
||||
let difficulty = req.query.difficulty as string;
|
||||
let captcha_token = req.query['hcaptcha_response'] as string;
|
||||
|
||||
if (isNaN(gym_id) || !name || !difficulty || !captcha_token) {
|
||||
res.status(400).send({'message': 'Missing parameters'});
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
if (!await verifyCaptcha(captcha_token)) {
|
||||
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
|
||||
return;
|
||||
}
|
||||
|
||||
let route_id = await RouteService.createRoute(gym_id, name, difficulty);
|
||||
|
||||
res.status(201).send({'route_id': route_id});
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
|
@ -0,0 +1,59 @@
|
|||
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
|
||||
import {ClimbingRoute} from './ClimbingRoute.interface';
|
||||
import random from 'random-words';
|
||||
|
||||
/**
|
||||
* Fetches and returns all known climbing routes
|
||||
* @return Promise<ClimbingRoute[]> The climbing routes
|
||||
*/
|
||||
export const findAll = async (): Promise<ClimbingRoute[]> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
try {
|
||||
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes');
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches and returns information about the given route
|
||||
* @param route_id The id of the route
|
||||
* @return Promise<ClimbingRoute> The climbing route
|
||||
*/
|
||||
export const findById = async (route_id: string): Promise<ClimbingRoute> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
try {
|
||||
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes WHERE route_id = ?', route_id);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new route and returns the id of the created route
|
||||
* @param gym_id The id of the climbing gym that the route belongs to
|
||||
* @param name The name of the climbing route
|
||||
* @param difficulty The difficulty of the climbing route
|
||||
* @return string The id of the created route
|
||||
*/
|
||||
export const createRoute = async (gym_id: number, name: string, difficulty: string): Promise<string> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
|
||||
// Generate route id
|
||||
let route_id = '';
|
||||
let randWords = random(3);
|
||||
for (let i = 0; i <= 2; i++) {
|
||||
route_id += randWords[i];
|
||||
if (i < 2) {
|
||||
route_id += '-';
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await conn.query('INSERT INTO climbing_routes (route_id, gym_id, name, difficulty) VALUES (?, ?, ?, ?)', [route_id, gym_id, name, difficulty]);
|
||||
|
||||
return route_id;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
15
src/models/climbing-route-rating/common/VerifyCaptcha.ts
Normal file
15
src/models/climbing-route-rating/common/VerifyCaptcha.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import * as querystring from 'qs';
|
||||
import axios from 'axios';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export const verifyCaptcha = async (captcha_token: string): Promise<boolean> => {
|
||||
let postData = querystring.stringify({
|
||||
response: captcha_token,
|
||||
secret: process.env.HCAPTCHA_SECRET
|
||||
});
|
||||
|
||||
let res = await axios.post('https://hcaptcha.com/siteverify', postData);
|
||||
return res.data.success;
|
||||
};
|
|
@ -0,0 +1,6 @@
|
|||
export interface RouteComment {
|
||||
comment_id: number;
|
||||
route_id: string;
|
||||
comment: string;
|
||||
timestamp: Date;
|
||||
}
|
|
@ -0,0 +1,155 @@
|
|||
import express, {Request, Response} from 'express';
|
||||
import * as CommentService from './routeComments.service';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import logger from '../../../middleware/logger';
|
||||
import {RouteComment} from './RouteComment.interface';
|
||||
import {verifyCaptcha} from '../common/VerifyCaptcha';
|
||||
|
||||
export const routeCommentsRouter = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/comments/by/route/{id}:
|
||||
* get:
|
||||
* summary: Retrieve the comments for the given route
|
||||
* description: Returns all comments for the route with the specified id
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Success
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* comment_id:
|
||||
* type: integer
|
||||
* description: The comment id
|
||||
* example: 2
|
||||
* route_id:
|
||||
* type: string
|
||||
* description: The id of the route that the comment belongs to
|
||||
* example: duck-score-guide
|
||||
* comment:
|
||||
* type: string
|
||||
* description: The comment text
|
||||
* example: Nice route! Was a lot of fun!
|
||||
* timestamp:
|
||||
* type: datetime
|
||||
* description: The time when the comment was sent
|
||||
* example: 2022-01-08T21:43:31.000Z
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* description: The id of the route
|
||||
* schema:
|
||||
* type: string
|
||||
* example: duck-score-guide
|
||||
*/
|
||||
routeCommentsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let route_id = req.params.id;
|
||||
|
||||
const comments: RouteComment[] = await CommentService.findByRoute(route_id);
|
||||
|
||||
res.status(200).send(comments);
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/comments:
|
||||
* post:
|
||||
* summary: Create a new comment
|
||||
* description: Creates a new comment and returns the id of the created comment
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Created
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* comment_id:
|
||||
* type: integer
|
||||
* description: The comment id
|
||||
* example: 1
|
||||
* 400:
|
||||
* description: Wrong parameters, see response body for detailed information
|
||||
* 403:
|
||||
* description: Invalid captcha, please try again.
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: route_id
|
||||
* required: true
|
||||
* description: The id of the route to create the comment for
|
||||
* schema:
|
||||
* type: string
|
||||
* example: duck-score-guide
|
||||
* - in: query
|
||||
* name: comment
|
||||
* required: true
|
||||
* description: The comment text
|
||||
* schema:
|
||||
* type: string
|
||||
* example: Nice route! Was a lot of fun!
|
||||
* - in: query
|
||||
* name: hcaptcha_response
|
||||
* required: true
|
||||
* description: The hCaptcha response key
|
||||
* schema:
|
||||
* type: string
|
||||
* example: P0_ey[...]bVu
|
||||
*/
|
||||
routeCommentsRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let route_id = req.query.route_id as string;
|
||||
let comment = req.query.comment as string;
|
||||
let captcha_token = req.query['hcaptcha_response'] as string;
|
||||
|
||||
if (!route_id || !comment || !captcha_token) {
|
||||
res.status(400).send({'message': 'Missing parameters'});
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
if (!await verifyCaptcha(captcha_token)) {
|
||||
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
|
||||
return;
|
||||
}
|
||||
|
||||
let result = await CommentService.createComment(route_id, comment);
|
||||
|
||||
if (result) {
|
||||
res.status(201).send({'comment_id': result});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
|
@ -0,0 +1,32 @@
|
|||
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
|
||||
import {RouteComment} from './RouteComment.interface';
|
||||
|
||||
/**
|
||||
* Fetches and returns all comments that belong to the given route
|
||||
* @return Promise<RouteComment[]> The comments
|
||||
*/
|
||||
export const findByRoute = async (route_id: string): Promise<RouteComment[]> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
try {
|
||||
return await conn.query('SELECT comment_id, route_id, comment, timestamp FROM route_comments WHERE route_id = ?', route_id);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new comment and returns the id of the created comment
|
||||
* @param route_id The id of the route to create the comment for
|
||||
* @param comment The comment
|
||||
* @return number The id of the comment
|
||||
*/
|
||||
export const createComment = async (route_id: string, comment: string): Promise<number> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
try {
|
||||
let res = await conn.query('INSERT INTO route_comments (route_id, comment) VALUES (?, ?) RETURNING comment_id', [route_id, comment]);
|
||||
|
||||
return res[0].comment_id;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
|
@ -0,0 +1,6 @@
|
|||
export interface RouteRating {
|
||||
rating_id: number;
|
||||
route_id: string;
|
||||
stars: number;
|
||||
timestamp: Date;
|
||||
}
|
|
@ -0,0 +1,140 @@
|
|||
import express, {Request, Response} from 'express';
|
||||
import * as RatingService from './routeRatings.service';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import logger from '../../../middleware/logger';
|
||||
import {verifyCaptcha} from '../common/VerifyCaptcha';
|
||||
|
||||
export const routeRatingsRouter = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/ratings/by/route/{id}:
|
||||
* get:
|
||||
* summary: Retrieve the rating for the given route
|
||||
* description: Returns the medium amount of stars that the route got
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Success
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* rating:
|
||||
* type: float
|
||||
* description: The median amount of stars
|
||||
* example: 4.5
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* description: The id of the route
|
||||
* schema:
|
||||
* type: string
|
||||
* example: duck-score-guide
|
||||
*/
|
||||
routeRatingsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let route_id = req.params.id;
|
||||
|
||||
let rating = await RatingService.getStarsForRoute(route_id);
|
||||
|
||||
res.status(200).send({'rating': rating});
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /crr/ratings:
|
||||
* post:
|
||||
* summary: Create a new rating
|
||||
* description: Creates a new rating and returns the id of the created rating
|
||||
* tags:
|
||||
* - climbing-route-rating
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Created
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* rating_id:
|
||||
* type: integer
|
||||
* description: The rating id
|
||||
* example: 1
|
||||
* 400:
|
||||
* description: Wrong parameters, see response body for detailed information
|
||||
* 403:
|
||||
* description: Invalid captcha, please try again.
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: route_id
|
||||
* required: true
|
||||
* description: The id of the route to create the rating for
|
||||
* schema:
|
||||
* type: string
|
||||
* example: duck-score-guide
|
||||
* - in: query
|
||||
* name: stars
|
||||
* required: true
|
||||
* description: The amount of stars to give
|
||||
* schema:
|
||||
* type: integer
|
||||
* example: 4
|
||||
* - in: query
|
||||
* name: hcaptcha_response
|
||||
* required: true
|
||||
* description: The hCaptcha response key
|
||||
* schema:
|
||||
* type: string
|
||||
* example: P0_ey[...]bVu
|
||||
*/
|
||||
routeRatingsRouter.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let route_id = req.query.route_id as string;
|
||||
let stars = Number(req.query.stars);
|
||||
let captcha_token = req.query['hcaptcha_response'] as string;
|
||||
|
||||
if (!route_id || isNaN(stars) || !captcha_token) {
|
||||
res.status(400).send({'message': 'Missing parameters'});
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
if (!await verifyCaptcha(captcha_token)) {
|
||||
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
|
||||
return;
|
||||
}
|
||||
|
||||
let result = await RatingService.createRating(route_id, stars);
|
||||
|
||||
if (result) {
|
||||
res.status(201).send({'rating_id': result});
|
||||
} else {
|
||||
res.status(500).send({});
|
||||
}
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
res.status(500).send({
|
||||
'status': 'PROCESSING_ERROR',
|
||||
'message': 'Internal Server Error. Try again later.',
|
||||
'reference': errorGuid
|
||||
});
|
||||
}
|
||||
});
|
|
@ -0,0 +1,52 @@
|
|||
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
|
||||
import {RouteRating} from './RouteRating.interface';
|
||||
|
||||
/**
|
||||
* Fetches and returns all ratings for the given route
|
||||
* @param route_id The id of the route to get the ratings for
|
||||
* @return Promise<RouteRating[]> The ratings
|
||||
*/
|
||||
export const findByRoute = async (route_id: string): Promise<RouteRating[]> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
try {
|
||||
return await conn.query('SELECT rating_id, route_id, stars, timestamp FROM route_ratings WHERE route_id = ?', route_id);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the median amount of stars the given route got from climbers
|
||||
* @param route_id The id of the route to get the rating for
|
||||
* @return number The median amount of stars with 1 fraction digit.
|
||||
*/
|
||||
export const getStarsForRoute = async (route_id: string): Promise<number> => {
|
||||
let ratings = await findByRoute(route_id);
|
||||
|
||||
let starsSum = 0;
|
||||
let starsAmount = 0;
|
||||
|
||||
for (let rating of ratings) {
|
||||
starsSum += rating.stars;
|
||||
starsAmount++;
|
||||
}
|
||||
|
||||
return Number((starsSum / starsAmount).toFixed(1));
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new rating and returns the id
|
||||
* @param route_id The id of the route to be rated
|
||||
* @param stars The amount of stars to be given
|
||||
* @return number The id of the created rating
|
||||
*/
|
||||
export const createRating = async (route_id: string, stars: number): Promise<number> => {
|
||||
let conn = ClimbingRouteRatingDB.getConnection();
|
||||
try {
|
||||
let res = await conn.query('INSERT INTO route_ratings (route_id, stars) VALUES (?, ?) RETURNING rating_id', [route_id, stars]);
|
||||
|
||||
return res[0].comment_id;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
};
|
19
src/models/dhbw-rapla-changes/DHBWRaPlaChanges.db.ts
Normal file
19
src/models/dhbw-rapla-changes/DHBWRaPlaChanges.db.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export namespace RaPlaChangesDB {
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.RAPLACHANGES_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
export function getConnection() {
|
||||
return pool;
|
||||
}
|
||||
}
|
|
@ -1,23 +1,13 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Event} from './Event.interface';
|
||||
import {Change} from './Change.interface';
|
||||
import {RaPlaChangesDB} from '../DHBWRaPlaChanges.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.RAPLACHANGES_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
export const getChanges = async (course: string, week: string): Promise<Event[]> => {
|
||||
let conn;
|
||||
let conn = RaPlaChangesDB.getConnection();
|
||||
try {
|
||||
conn = await pool.getConnection();
|
||||
|
||||
let relevantEventsRows = await conn.query('SELECT DISTINCT(entry_id) FROM rapla_changes WHERE new_start > ? AND new_start < DATE_ADD(?, INTERVAL 7 DAY)', [week, week]);
|
||||
|
||||
let relevantEventIds: string[] = [];
|
||||
|
@ -78,18 +68,12 @@ export const getChanges = async (course: string, week: string): Promise<Event[]>
|
|||
return Array.from(eventsMap.values()) as Event[];
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const getEventById = async (course: string, id: string): Promise<Event> => {
|
||||
let conn;
|
||||
let conn = RaPlaChangesDB.getConnection();
|
||||
try {
|
||||
conn = await pool.getConnection();
|
||||
|
||||
let rows = await conn.query('SELECT c.change_id, c.entry_id, c.change_timestamp, c.isDeleted, c.new_summary, c.new_description, c.new_start, c.new_last_modified, c.new_end, c.new_created, c.new_location, c.new_organizer, c.new_categories, e.uid FROM rapla_changes c LEFT OUTER JOIN rapla_entries e ON c.entry_id = e.entry_id WHERE e.uid = ? ORDER BY c.change_id', id);
|
||||
|
||||
let eventsMap = new Map();
|
||||
|
@ -139,9 +123,5 @@ export const getEventById = async (course: string, id: string): Promise<Event> =
|
|||
return Array.from(eventsMap.values())[0];
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
29
src/models/partyplaner/PartyPlaner.db.ts
Normal file
29
src/models/partyplaner/PartyPlaner.db.ts
Normal file
|
@ -0,0 +1,29 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export namespace PartyPlanerDB {
|
||||
const prod_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_PROD_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
const dev_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_DEV_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
export function getConnection(useDev: boolean = false) {
|
||||
if (useDev) {
|
||||
return dev_pool;
|
||||
}
|
||||
return prod_pool;
|
||||
}
|
||||
}
|
|
@ -1,24 +1,9 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Event} from './Event.interface';
|
||||
import {PartyPlanerDB} from '../PartyPlaner.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
const prod_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_PROD_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
const dev_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_DEV_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns all events of the given user
|
||||
* @param useDev If the dev or prod database should be used
|
||||
|
@ -26,14 +11,8 @@ const dev_pool = mariadb.createPool({
|
|||
* @return Event[] A list of events
|
||||
*/
|
||||
export const getEventData = async (useDev: boolean, userId: string): Promise<Event[]> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
let eventRows = await conn.query('SELECT event_id, name, description, takes_place_date, registration_until_date, max_participants FROM events WHERE creator_id = ?', userId);
|
||||
|
||||
let eventsMap = new Map<string, Event>();
|
||||
|
@ -90,9 +69,5 @@ export const getEventData = async (useDev: boolean, userId: string): Promise<Eve
|
|||
return eventsList;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
@ -1,24 +1,9 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {Friendship} from './Friendship.interface';
|
||||
import {PartyPlanerDB} from '../PartyPlaner.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
const prod_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_PROD_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
const dev_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_DEV_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns all friends of the given user
|
||||
* @param useDev If the dev or prod database should be used
|
||||
|
@ -26,14 +11,8 @@ const dev_pool = mariadb.createPool({
|
|||
* @return Friendship[] A list of friends
|
||||
*/
|
||||
export const getFriendshipData = async (useDev: boolean, userId: string): Promise<Friendship[]> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
let rows = await conn.query('SELECT f.friendship_id, f.friend_id, u.first_name as friend_first_name, u.last_name as friend_last_name, u.username as friend_username FROM friendships f LEFT OUTER JOIN users u ON f.friend_id = u.user_id WHERE f.user_id = ?', userId);
|
||||
|
||||
let friends: Friendship[] = [];
|
||||
|
@ -51,9 +30,5 @@ export const getFriendshipData = async (useDev: boolean, userId: string): Promis
|
|||
return friends;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
@ -1,24 +1,9 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {ReceivedInvite} from './ReceivedInvite.interface';
|
||||
import {PartyPlanerDB} from '../PartyPlaner.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
const prod_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_PROD_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
const dev_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_DEV_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns all events the user is invited to
|
||||
* @param useDev If the dev or prod database should be used
|
||||
|
@ -26,14 +11,8 @@ const dev_pool = mariadb.createPool({
|
|||
* @return ReceivedInvite[] A list of invites
|
||||
*/
|
||||
export const getInvitesData = async (useDev: boolean, userId: string): Promise<ReceivedInvite[]> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
let rows = await conn.query('SELECT i.invite_id, i.valid_until, i.already_used, i.invite_key, e.name as event_name, e.description as event_description, e.takes_place_date, e.registration_until_date, e.max_participants, e.creator_id, u.first_name, u.last_name FROM invitations i LEFT OUTER JOIN events e ON e.event_id = i.event_id LEFT OUTER JOIN users u ON u.user_id = e.creator_id WHERE i.user_id = ?', userId);
|
||||
|
||||
let invites: ReceivedInvite[] = [];
|
||||
|
@ -58,9 +37,5 @@ export const getInvitesData = async (useDev: boolean, userId: string): Promise<R
|
|||
return invites;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
@ -1,24 +1,9 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {SessionData} from './SessionData.interface';
|
||||
import {PartyPlanerDB} from '../PartyPlaner.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
const prod_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_PROD_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
const dev_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_DEV_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns all active sessions of the given user
|
||||
* @param useDev If the dev or prod database should be used
|
||||
|
@ -26,14 +11,8 @@ const dev_pool = mariadb.createPool({
|
|||
* @return SessionData[] A list containing objects with the session data
|
||||
*/
|
||||
export const getSessionData = async (useDev: boolean, userId: string): Promise<SessionData[]> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
let rows = await conn.query('SELECT session_id, type, last_login, last_ip FROM sessions WHERE user_id = ? AND valid_until > NOW()', userId);
|
||||
|
||||
let sessions: SessionData[] = [];
|
||||
|
@ -50,9 +29,5 @@ export const getSessionData = async (useDev: boolean, userId: string): Promise<S
|
|||
return sessions;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
@ -4,25 +4,10 @@ import {Guid} from 'guid-typescript';
|
|||
import {UserData} from './UserData.interface';
|
||||
import {Session} from './Session.interface';
|
||||
import {Status} from './Status.interface';
|
||||
import {PartyPlanerDB} from '../PartyPlaner.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
const prod_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_PROD_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
const dev_pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.PARTYPLANER_DEV_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns all data about the given user
|
||||
* @param useDev If the dev or prod database should be used
|
||||
|
@ -30,14 +15,8 @@ const dev_pool = mariadb.createPool({
|
|||
* @return UserData An object containing the user data
|
||||
*/
|
||||
export const getUserData = async (useDev: boolean, userId: string): Promise<UserData> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
let rows = await conn.query('SELECT username, email, first_name, last_Name, last_login, email_is_verified, is_premium_user FROM users WHERE user_id = ?', userId);
|
||||
|
||||
let user: UserData = {} as UserData;
|
||||
|
@ -57,10 +36,6 @@ export const getUserData = async (useDev: boolean, userId: string): Promise<User
|
|||
return user;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -70,14 +45,8 @@ export const getUserData = async (useDev: boolean, userId: string): Promise<User
|
|||
* @return any An object with a list of usernames and emails
|
||||
*/
|
||||
export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<any> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
const rows = await conn.query('SELECT username, email FROM users');
|
||||
|
||||
let usernames: string[] = [];
|
||||
|
@ -94,10 +63,6 @@ export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<an
|
|||
};
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -113,14 +78,8 @@ export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<an
|
|||
* @param deviceInfo The user agent of the new user
|
||||
*/
|
||||
export const registerUser = async (useDev: boolean, username: string, email: string, firstName: string, lastName: string, password: string, ip: string, deviceInfo: string): Promise<Session> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
const pwHash = bcrypt.hashSync(password, 10);
|
||||
const sessionKey = Guid.create().toString();
|
||||
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
||||
|
@ -166,10 +125,6 @@ export const registerUser = async (useDev: boolean, username: string, email: str
|
|||
};
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -183,14 +138,8 @@ export const registerUser = async (useDev: boolean, username: string, email: str
|
|||
* @param deviceInfo The user agent of the new user
|
||||
*/
|
||||
export const loginUser = async (useDev: boolean, username: string, email: string, password: string, ip: string, deviceInfo: string): Promise<Session> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
let query_result;
|
||||
|
||||
// Get the saved hash
|
||||
|
@ -248,10 +197,6 @@ export const loginUser = async (useDev: boolean, username: string, email: string
|
|||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -262,13 +207,8 @@ export const loginUser = async (useDev: boolean, username: string, email: string
|
|||
* @param email The email to check
|
||||
*/
|
||||
export const checkUsernameAndEmail = async (useDev: boolean, username: string, email: string): Promise<Status> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
const usernameQuery = 'SELECT username FROM users WHERE username = ?';
|
||||
const emailQuery = 'SELECT email FROM users WHERE email = ?';
|
||||
const usernameRes = await conn.query(usernameQuery, username);
|
||||
|
@ -314,22 +254,12 @@ export const checkUsernameAndEmail = async (useDev: boolean, username: string, e
|
|||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const checkSession = async (useDev: boolean, userId: string, sessionId: string, sessionKey: string): Promise<boolean> => {
|
||||
let conn;
|
||||
let conn = PartyPlanerDB.getConnection(useDev);
|
||||
try {
|
||||
if (useDev) {
|
||||
conn = await dev_pool.getConnection();
|
||||
} else {
|
||||
conn = await prod_pool.getConnection();
|
||||
}
|
||||
|
||||
let rows = await conn.query('SELECT session_key_hash FROM sessions WHERE user_id = ? AND session_id = ?', [userId, sessionId]);
|
||||
|
||||
let savedHash = '';
|
||||
|
@ -340,9 +270,5 @@ export const checkSession = async (useDev: boolean, userId: string, sessionId: s
|
|||
return bcrypt.compareSync(sessionKey, savedHash);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
@ -11,10 +11,61 @@ import * as icalgenerator from './icalgenerator/icalgenerator.service';
|
|||
*/
|
||||
export const raPlaMiddlewareRouter = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /rapla-middleware:
|
||||
* get:
|
||||
* summary: Retrieve the adjusted RaPla .ics file
|
||||
* description: Downloads the current .ics file from DHBW servers, removes unwanted events and returns the file.
|
||||
* Required urls can be generated on https://rapla-middleware.p4ddy.com
|
||||
* tags:
|
||||
* - rapla-middleware
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The .ics file
|
||||
* 400:
|
||||
* description: Wrong parameters, see response body for detailed information
|
||||
* 500:
|
||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: user
|
||||
* required: true
|
||||
* description: The user from RaPla, can be taken directly from the RaPla link
|
||||
* schema:
|
||||
* type: string
|
||||
* example: mueller
|
||||
* - in: query
|
||||
* name: file
|
||||
* required: true
|
||||
* description: The file from RaPla, can be taken directly from the RaPla link
|
||||
* schema:
|
||||
* type: string
|
||||
* example: TINF19B4
|
||||
* - in: query
|
||||
* name: blockers
|
||||
* required: false
|
||||
* description: Whether to remove blockers from the .ics file
|
||||
* schema:
|
||||
* type: boolean
|
||||
* example: 1
|
||||
* - in: query
|
||||
* name: wahl
|
||||
* required: false
|
||||
* description: The chosen elective module which is not to be filtered out
|
||||
* schema:
|
||||
* type: integer
|
||||
* example: 0
|
||||
* - in: query
|
||||
* name: pflicht
|
||||
* required: false
|
||||
* description: The chosen profile module which is not to be filtered out
|
||||
* schema:
|
||||
* type: integer
|
||||
* example: 2
|
||||
*/
|
||||
raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
logger.info('Starting transaction');
|
||||
|
||||
let user = (req.query.user ?? '').toString();
|
||||
let file = (req.query.file ?? '').toString();
|
||||
let blockers = (req.query.blockers ?? '').toString() === '1';
|
||||
|
@ -35,8 +86,6 @@ raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
|
|||
|
||||
res.set({'Content-Disposition': 'attachment; filename=' + file + '.ics'});
|
||||
res.status(200).send(resultingFile);
|
||||
|
||||
logger.info('Stopping transaction');
|
||||
} catch (e) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||
|
@ -47,21 +96,3 @@ raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
|
|||
});
|
||||
}
|
||||
});
|
||||
|
||||
let electiveModules = {
|
||||
1: {name: ''},
|
||||
2: {name: ''},
|
||||
3: {name: ''},
|
||||
4: {name: ''},
|
||||
5: {name: ''},
|
||||
6: {name: ''},
|
||||
7: {name: ''}
|
||||
};
|
||||
|
||||
let profileModules = {
|
||||
1: {name: ''},
|
||||
2: {name: ''},
|
||||
3: {name: ''},
|
||||
4: {name: ''},
|
||||
5: {name: ''}
|
||||
};
|
||||
|
|
|
@ -48,7 +48,7 @@ export const parseIcal = function (icalContents: string): iCalFile {
|
|||
header = headerMatch[0];
|
||||
}
|
||||
|
||||
header = header.substr(0, header.lastIndexOf('\n'));
|
||||
header = header.substr(0, header.lastIndexOf('\n') + 1);
|
||||
|
||||
let events: iCalEvent[] = [];
|
||||
let match: any;
|
||||
|
@ -67,11 +67,9 @@ export const parseIcal = function (icalContents: string): iCalFile {
|
|||
};
|
||||
};
|
||||
|
||||
export const getDuration = function(event: string): number {
|
||||
let startRegex: RegExp = /DTSTART.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm; // Fix this, doesnt match \n but matching Z doesnt work all the time
|
||||
let endRegex: RegExp = /DTEND.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm; // s.o.
|
||||
|
||||
// localhost:3000/rapla-middleware?user=eisenbiegler&file=TINF19B4&blockers=0&wahl=4&pflicht=2
|
||||
export const getDuration = function (event: string): number {
|
||||
let startRegex: RegExp = /DTSTART.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm;
|
||||
let endRegex: RegExp = /DTEND.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm;
|
||||
|
||||
let startMatch = startRegex.exec(event);
|
||||
|
||||
|
@ -80,7 +78,7 @@ export const getDuration = function(event: string): number {
|
|||
let startDtDay = 0;
|
||||
let startDtHour = 0;
|
||||
let startDtMinute = 0;
|
||||
if(startMatch) {
|
||||
if (startMatch) {
|
||||
startDtYear = parseInt(startMatch[1]);
|
||||
startDtMonth = parseInt(startMatch[2]);
|
||||
startDtDay = parseInt(startMatch[3]);
|
||||
|
@ -94,7 +92,7 @@ export const getDuration = function(event: string): number {
|
|||
let endDtDay = 0;
|
||||
let endDtHour = 0;
|
||||
let endDtMinute = 0;
|
||||
if(endMatch) {
|
||||
if (endMatch) {
|
||||
endDtYear = parseInt(endMatch[1]);
|
||||
endDtMonth = parseInt(endMatch[2]);
|
||||
endDtDay = parseInt(endMatch[3]);
|
||||
|
@ -105,15 +103,22 @@ export const getDuration = function(event: string): number {
|
|||
let startDt = new Date(startDtYear, startDtMonth - 1, startDtDay, startDtHour, startDtMinute);
|
||||
let endDt = new Date(endDtYear, endDtMonth - 1, endDtDay, endDtHour, endDtMinute);
|
||||
|
||||
return endDt.getHours() - startDt.getHours();
|
||||
}
|
||||
let hourDifference = endDt.getHours() - startDt.getHours();
|
||||
let minuteDifference = 0;
|
||||
|
||||
if (hourDifference === 0) {
|
||||
minuteDifference = endDt.getMinutes() - startDt.getMinutes();
|
||||
}
|
||||
|
||||
return hourDifference + (minuteDifference / 60);
|
||||
};
|
||||
|
||||
export const serializeIcal = function (ical: iCalFile): string {
|
||||
let resString = ical.head;
|
||||
ical.body.forEach((event) => {
|
||||
resString += event.content + '\n';
|
||||
});
|
||||
resString += 'END:VCALENDAR';
|
||||
resString += 'END:VCALENDAR\n';
|
||||
|
||||
return resString;
|
||||
};
|
||||
|
@ -126,6 +131,7 @@ export const removeBlockers = function (ical: iCalFile): iCalFile {
|
|||
!event.content.includes('SUMMARY:Beginn Theorie')
|
||||
&& !event.content.includes('SUMMARY:Präsenz')
|
||||
&& event.duration < 10
|
||||
&& event.duration > 0.25
|
||||
) {
|
||||
remainingEvents.push(event);
|
||||
}
|
||||
|
|
19
src/models/twitch-highlight-marker/HighlightMarker.db.ts
Normal file
19
src/models/twitch-highlight-marker/HighlightMarker.db.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export namespace HighlightMarkerDB {
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.BETTERZON_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
export function getConnection() {
|
||||
return pool;
|
||||
}
|
||||
}
|
|
@ -1,25 +1,15 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
import {HighlightMarkerDB} from '../HighlightMarker.db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mariadb = require('mariadb');
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.TWITCH_HIGHLIGHTS_DATABASE,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
/**
|
||||
* Creates a new highlight entry in SQL
|
||||
* @param req_body The request body
|
||||
*/
|
||||
export const createHighlightEntry = async (req_body: any) => {
|
||||
let conn;
|
||||
let conn = HighlightMarkerDB.getConnection();
|
||||
try {
|
||||
conn = await pool.getConnection();
|
||||
|
||||
const streamers = await conn.query('SELECT streamer_id FROM streamers WHERE username = ?', req_body.streamer);
|
||||
let streamer_id: number = -1;
|
||||
|
||||
|
@ -34,9 +24,5 @@ export const createHighlightEntry = async (req_body: any) => {
|
|||
const rows = await conn.query('INSERT INTO highlights (streamer_id, stream_id, description, stream_timestamp, issuing_user, game) VALUES (?, ?, ?, ?, ?, ?)', params);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
if (conn) {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2016",
|
||||
"module": "commonjs",
|
||||
"outDir": "./dist",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"inlineSourceMap": true
|
||||
}
|
||||
"compilerOptions": {
|
||||
"target": "es2016",
|
||||
"module": "commonjs",
|
||||
"outDir": "./dist",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"inlineSourceMap": true
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user