Commit 52c6cc60 authored by Geovanny's avatar Geovanny

Refactored house routing

parent 3045fac3
...@@ -16,7 +16,7 @@ class MembershipManager(commands.Cog): ...@@ -16,7 +16,7 @@ class MembershipManager(commands.Cog):
"""Send member request to house id""" """Send member request to house id"""
try: try:
session = await self.bot.getUserSession(ctx.message.author) session = await self.bot.getUserSession(ctx.message.author)
await Api.postSession('/house/request', {"house_id": house_id}, session) await Api.postSession('/house/membership/request', {"house_id": house_id}, session)
await ctx.send('Request sent'); await ctx.send('Request sent');
except ApiError as error: except ApiError as error:
await ctx.send(error.message) await ctx.send(error.message)
...@@ -26,7 +26,7 @@ class MembershipManager(commands.Cog): ...@@ -26,7 +26,7 @@ class MembershipManager(commands.Cog):
"""Cancel member request""" """Cancel member request"""
try: try:
session = await self.bot.getUserSession(ctx.message.author) session = await self.bot.getUserSession(ctx.message.author)
await Api.deleteSession('/house/request', session) await Api.deleteSession('/house/membership/request', session)
await ctx.send('Request cancelled'); await ctx.send('Request cancelled');
except ApiError as error: except ApiError as error:
await ctx.send(error.message) await ctx.send(error.message)
...@@ -36,7 +36,7 @@ class MembershipManager(commands.Cog): ...@@ -36,7 +36,7 @@ class MembershipManager(commands.Cog):
"""All requests to house""" """All requests to house"""
try: try:
session = await self.bot.getUserSession(ctx.message.author) session = await self.bot.getUserSession(ctx.message.author)
data = await Api.getSession('/house/requests', session) data = await Api.getSession('/house/membership/request/all', session)
if(len(data) == 0): if(len(data) == 0):
await ctx.send('No requests') await ctx.send('No requests')
else: else:
...@@ -63,7 +63,7 @@ class MembershipManager(commands.Cog): ...@@ -63,7 +63,7 @@ class MembershipManager(commands.Cog):
"""Accept membership request""" """Accept membership request"""
try: try:
session = await self.bot.getUserSession(ctx.message.author) session = await self.bot.getUserSession(ctx.message.author)
data = await Api.postSession('/house/accept-request',{"user_id": user_id} , session) data = await Api.postSession('/house/membership',{"user_id": user_id} , session)
await ctx.send('Membership accepted') await ctx.send('Membership accepted')
except ApiError as error: except ApiError as error:
...@@ -74,7 +74,7 @@ class MembershipManager(commands.Cog): ...@@ -74,7 +74,7 @@ class MembershipManager(commands.Cog):
"""Refuse membership request""" """Refuse membership request"""
try: try:
session = await self.bot.getUserSession(ctx.message.author) session = await self.bot.getUserSession(ctx.message.author)
data = await Api.deleteSession('/house/reject-request/{0}'.format(user_id), session) data = await Api.deleteSession('/house/membership/request/{0}'.format(user_id), session)
await ctx.send('Membership rejected') await ctx.send('Membership rejected')
except ApiError as error: except ApiError as error:
......
...@@ -18,7 +18,7 @@ class WarManager(commands.Cog): ...@@ -18,7 +18,7 @@ class WarManager(commands.Cog):
async def currentWar(self, ctx): async def currentWar(self, ctx):
"""Get current war information""" """Get current war information"""
try: try:
data = await Api.get('/house/current-war'); data = await Api.get('/house/war');
date = parser.parse(data.get('day')) date = parser.parse(data.get('day'))
await ctx.send('Current War Date: {0}/{1}/{2}'.format(date.year, date.month, date.day)) await ctx.send('Current War Date: {0}/{1}/{2}'.format(date.year, date.month, date.day))
except ApiError as error: except ApiError as error:
...@@ -27,7 +27,7 @@ class WarManager(commands.Cog): ...@@ -27,7 +27,7 @@ class WarManager(commands.Cog):
async def warParticipation(self, ctx, decision): async def warParticipation(self, ctx, decision):
try: try:
session = await self.bot.getUserSession(ctx.message.author) session = await self.bot.getUserSession(ctx.message.author)
await Api.postSession('/house/participation', {"decision": decision}, session) await Api.postSession('/house/war/participation', {"decision": decision}, session)
await ctx.send('Participation updated') await ctx.send('Participation updated')
except ApiError as error: except ApiError as error:
await ctx.send(error.message) await ctx.send(error.message)
......
const db = require('../../database/database');
const model = {};
model.getMembers = async(house_id) => {
const sql_text = `SELECT u.id, u.username, u.leadership, hr.lk_name as house_role, hr.lk_key
FROM users as u
LEFT JOIN house_role_lk as hr ON hr.lk_key = u.lk_house_role
WHERE u.house_id = ?;`;
const data = await db.pool.query(sql_text, [house_id]);
return data;
}
model.getMemberUnits = async(member_id) => {
const sql_text = `SELECT u.*, uu.unit_level, uu.elite_flg
FROM users as us
LEFT JOIN users_units as uu ON us.id = uu.user_id
LEFT JOIN units as u ON uu.unit_id = u.id
WHERE us.id = ? ORDER BY u.name ASC;`
const data = await db.pool.query(sql_text, [member_id]);
return data;
}
module.exports = model;
\ No newline at end of file
const Router = require('@koa/router');
const router = new Router();
const memberModel = require('./model');
// DELETE
const HOUSE_ROLES = {
lg: 0,
sen: 1,
mar: 2,
nob: 3,
tre: 4,
kng: 5
}
function hasHouseNoThrow(context){
return context.user.house_id;
}
function checkPermissions(context, ROLE){
if(!hasHouseNoThrow(context) || ROLE < context.user.lk_permission_level){
context.throw(403, "No Permissions")
}
}
function hasHouse(context){
if(!context.user.house_id){
context.throw(400, 'No house');
}
}
// END DELETE
router.get('/all', async (context, next) => {
hasHouse(context);
try{
const data = await memberModel.getMembers(context.user.house_id);
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw(400, "Failed to get members")
}
});
router.get('/:member_id/units', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
try{
const data = await memberModel.getMemberUnits(context.params.member_id);
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw('Failed to get Member Units');
}
});
module.exports = router;
\ No newline at end of file
const db = require('../../database/database');
const model = {};
async function checkHouseRequest(house_id, user_id){
const sql_exists = 'SELECT EXISTS(SELECT * FROM house_requests WHERE house_id = ? AND user_id = ?) as result;'
const exists = await db.pool.query(sql_exists, [house_id , user_id]);
if(exists[0] && exists[0].result===0){
throw Error("Membership request not send for user's house")
}
}
model.acceptRequest = async(user_id, house_id) => {
checkHouseRequest(house_id, user_id);
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?;';
const sql_text2 = 'UPDATE users SET house_id = ?, lk_house_role = \'kng\' WHERE id = ?;';
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;');
await con.query(sql_text, [user_id]);
await con.query(sql_text2, [house_id, user_id]);
await con.query('COMMIT;');
await con.release();
}
model.changeHouseLiege = async(liege_id, member_id) => {
const sql_text = `UPDATE users SET lk_house_role = 'kng' WHERE id = ?;`;
const sql_text2 = `UPDATE users SET lk_house_role = 'lg' WHERE id = ?;`;
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;')
await con.query(sql_text, [liege_id]);
await con.query(sql_text2, [member_id]);
await con.query('COMMIT;');
await con.release();
}
model.modifyMemberRole = async(member_id, role) => {
const sql_text = 'UPDATE users SET lk_house_role = ? WHERE id = ?;';
await db.pool.query(sql_text, [role, member_id]);
}
// DELETE AFTER CHANGING MODEL
model.deleteHouse = async(house_id) => {
const sql_text = 'UPDATE users SET lk_house_role = NULL where house_id = ?';
const sql_text2 = 'DELETE FROM houses WHERE id = ?;';
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;');
await con.query(sql_text, [house_id]);
await con.query(sql_text2, [house_id]);
await con.query('COMMIT;');
await con.release();
}
model.leaveHouse = async(user_id) => {
const sql_text = 'UPDATE users SET house_id = NULL, lk_house_role = NULL WHERE id = ?;';
await db.pool.query(sql_text, [user_id]);
}
model.deleteMember = async(user_id) => {
const sql_text = 'UPDATE users SET house_id = NULL, lk_house_role = NULL WHERE id = ? AND lk_house_role != \'lg\';';
await db.pool.query(sql_text, [user_id]);
}
module.exports = model;
\ No newline at end of file
const db = require('../../../database/database');
const model = {};
async function checkHouseRequest(house_id, user_id){
const sql_exists = 'SELECT EXISTS(SELECT * FROM house_requests WHERE house_id = ? AND user_id = ?) as result;'
const exists = await db.pool.query(sql_exists, [house_id , user_id]);
if(exists[0] && exists[0].result===0){
throw Error("Membership request not send for user's house")
}
}
model.getHouseRequests = async(house_id) => {
const sql_text = `SELECT u.id, u.username
FROM house_requests as hr
LEFT JOIN users as u ON u.id = hr.user_id
WHERE hr.house_id = ?;`
const data = await db.pool.query(sql_text, [house_id]);
return data;
}
model.sendRequest = async(house_id, user_id) => {
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?';
const sql_text2 = 'INSERT INTO house_requests (house_id, user_id) VALUES (?, ?)';
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;');
await con.query(sql_text, [user_id]);
await con.query(sql_text2, [house_id, user_id]);
await con.query('COMMIT;');
await con.release();
};
model.cancelRequests = async(user_id) => {
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?';
await db.pool.query(sql_text, [user_id]);
}
model.rejectRequest = async(user_id, house_id) => {
checkHouseRequest(house_id, user_id);
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?;';
await db.pool.query(sql_text, [user_id]);
}
module.exports = model;
\ No newline at end of file
const Router = require('@koa/router');
const router = new Router();
const requestModel = require('./model');
// DELETE START
const HOUSE_ROLES = {
lg: 0,
sen: 1,
mar: 2,
nob: 3,
tre: 4,
kng: 5
}
function checkPermissions(context, ROLE){
if(!hasHouseNoThrow(context) || ROLE < context.user.lk_permission_level){
context.throw(403, "No Permissions")
}
}
function hasHouseNoThrow(context){
return context.user.house_id;
}
// DELETE END
router.get('/all', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
try{
const data = await requestModel.getHouseRequests(context.user.house_id);
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw(400, 'Unable to get requests');
}
});
router.post('/', async (context, next) => {
if(context.user.house_id){
context.throw(400, 'Already in a house')
}
try{
const body = context.request.body;
if(!body || !body.house_id){
throw Error('No house ID');
}
await requestModel.sendRequest(body.house_id, context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to send request');
}
});
router.delete('/', async (context, next) =>{
if(context.user.house_id){
context.throw(400, 'Already in a house')
}
try{
await requestModel.cancelRequests(context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to send request');
}
});
router.delete('/:user_id', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
try{
const body = context.request.body;
if(!context.params.user_id){
throw Error("No user to refuse");
}
await requestModel.rejectRequest(context.params.user_id, context.user.house_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to reject Request')
}
});
module.exports = router;
\ No newline at end of file
const Router = require('@koa/router');
const router = new Router();
const membershipModel = require('./model');
const userModel = require('../../user/model');
const requestRouter = require('./request/route');
router.use('/request', requestRouter.routes(), requestRouter.allowedMethods());
// DELETE START
const HOUSE_ROLES = {
lg: 0,
sen: 1,
mar: 2,
nob: 3,
tre: 4,
kng: 5
}
function checkPermissions(context, ROLE){
if(!hasHouseNoThrow(context) || ROLE < context.user.lk_permission_level){
context.throw(403, "No Permissions")
}
}
function hasHouseNoThrow(context){
return context.user.house_id;
}
function hasHouse(context){
if(!context.user.house_id){
context.throw(400, 'No house');
}
}
function checkPermissionsNoThrow(context, ROLE){
return ROLE >= context.user.lk_permission_level;
}
// DELETE END
router.get('/permissions', async (context, next) => {
if(!context.user.house_id || context.user.lk_permission_level === undefined){
context.throw(400, 'No house');
}
try{
context.response.status = 200;
context.response.body = context.user.lk_permission_level;
}catch(error){
console.log(error);
context.throw(400, 'ERROR');
}
});
router.post('/', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
try{
const body = context.request.body;
if(!body || !body.user_id){
throw Error('No user to accept');
}
await membershipModel.acceptRequest(body.user_id, context.user.house_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Accept Request')
}
});
router.put('/:member_id', async(context, next) => {
hasHouse(context);
const body = context.request.body;
if(!body || !body.role){
context.throw(400, 'Missing parameters')
}
try{
const member = await userModel.getUserFullFromId(context.params.member_id);
if(!member){
throw Error('Member does not exists');
}
if(member.house_id !== context.user.house_id){
throw Error('Not on the same house');
}
if(member.lk_permission_level <= context.user.lk_permission_level){
throw Error('Member permission level is high')
}
if(checkPermissionsNoThrow(context, HOUSE_ROLES.lg)){
if(body.role === 'lg'){
await membershipModel.changeHouseLiege(context.user.id, member.id);
}else{
await membershipModel.modifyMemberRole(member.id, body.role);
}
}else{
if(context.user.lk_house_role < HOUSE_ROLES[body.role]){
await membershipModel.modifyMemberRole(member.id, body.role);
}else{
throw Error('Cannot modify to the same level');
}
}
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to modify role')
}
});
router.delete('/', async (context, next) => {
if(context.user.lk_house_role==='lg'){
try{
await membershipModel.deleteHouse(context.user.house_id, context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Delete House');
}
}else{
try{
await membershipModel.leaveHouse(context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Leave');
}
}
});
router.delete('/:user_id', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
if(context.params.user_id===context.session.user_id){
context.throw(400, "Can't delete yourself");
}
try{
const member = await userModel.getUserFullFromId(context.params.user_id);
if(!member){
throw Error('Member does not exists');
}
if(member.house_id !== context.user.house_id){
throw Error('Not on the same house');
}
if(member.lk_permission_level <= context.user.lk_permission_level){
throw Error("Member permission level is high")
}
await membershipModel.deleteMember(context.params.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Delete Member')
}
});
module.exports = router;
\ No newline at end of file
...@@ -4,14 +4,6 @@ const model = {}; ...@@ -4,14 +4,6 @@ const model = {};
const h_columns = ['house_name', 'house_level', 'camp_location']; const h_columns = ['house_name', 'house_level', 'camp_location'];
async function checkHouseRequest(house_id, user_id){
const sql_exists = 'SELECT EXISTS(SELECT * FROM house_requests WHERE house_id = ? AND user_id = ?) as result;'
const exists = await db.pool.query(sql_exists, [house_id , user_id]);
if(exists[0] && exists[0].result===0){
throw Error("Membership request not send for user's house")
}
}
model.getAll = async () => { model.getAll = async () => {
const sql_text = `SELECT h.*, u.username as liege_username const sql_text = `SELECT h.*, u.username as liege_username
FROM houses as h FROM houses as h
...@@ -103,166 +95,4 @@ model.deleteHouse = async(house_id) => { ...@@ -103,166 +95,4 @@ model.deleteHouse = async(house_id) => {
await con.release(); await con.release();
} }
model.sendRequest = async(house_id, user_id) => {
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?';
const sql_text2 = 'INSERT INTO house_requests (house_id, user_id) VALUES (?, ?)';
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;');
await con.query(sql_text, [user_id]);
await con.query(sql_text2, [house_id, user_id]);
await con.query('COMMIT;');
await con.release();
};
model.cancelRequests = async(user_id) => {
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?';
await db.pool.query(sql_text, [user_id]);
}
model.getHouseRequests = async(house_id) => {
const sql_text = `SELECT u.id, u.username
FROM house_requests as hr
LEFT JOIN users as u ON u.id = hr.user_id
WHERE hr.house_id = ?;`
const data = await db.pool.query(sql_text, [house_id]);
return data;
}
model.acceptRequest = async(user_id, house_id) => {
checkHouseRequest(house_id, user_id);
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?;';
const sql_text2 = 'UPDATE users SET house_id = ?, lk_house_role = \'kng\' WHERE id = ?;';
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;');
await con.query(sql_text, [user_id]);
await con.query(sql_text2, [house_id, user_id]);
await con.query('COMMIT;');
await con.release();
}
model.rejectRequest = async(user_id, house_id) => {
checkHouseRequest(house_id, user_id);
const sql_text = 'DELETE FROM house_requests WHERE user_id = ?;';
await db.pool.query(sql_text, [user_id]);
}
model.deleteMember = async(user_id) => {
const sql_text = 'UPDATE users SET house_id = NULL, lk_house_role = NULL WHERE id = ? AND lk_house_role != \'lg\';';
await db.pool.query(sql_text, [user_id]);
}
model.leaveHouse = async(user_id) => {
const sql_text = 'UPDATE users SET house_id = NULL, lk_house_role = NULL WHERE id = ?;';
await db.pool.query(sql_text, [user_id]);
}
model.getMembers = async(house_id) => {
const sql_text = `SELECT u.id, u.username, u.leadership, hr.lk_name as house_role, hr.lk_key
FROM users as u
LEFT JOIN house_role_lk as hr ON hr.lk_key = u.lk_house_role
WHERE u.house_id = ?;`;
const data = await db.pool.query(sql_text, [house_id]);
return data;
}
model.modifyMemberRole = async(member_id, role) => {
const sql_text = 'UPDATE users SET lk_house_role = ? WHERE id = ?;';
await db.pool.query(sql_text, [role, member_id]);
}
model.changeHouseLiege = async(liege_id, member_id) => {
const sql_text = `UPDATE users SET lk_house_role = 'kng' WHERE id = ?;`;
const sql_text2 = `UPDATE users SET lk_house_role = 'lg' WHERE id = ?;`;
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;')
await con.query(sql_text, [liege_id]);
await con.query(sql_text2, [member_id]);
await con.query('COMMIT;');
await con.release();
}
model.getMemberUnits = async(member_id) => {
const sql_text = `SELECT u.*, uu.unit_level, uu.elite_flg
FROM users as us
LEFT JOIN users_units as uu ON us.id = uu.user_id
LEFT JOIN units as u ON uu.unit_id = u.id
WHERE us.id = ? ORDER BY u.name ASC;`
const data = await db.pool.query(sql_text, [member_id]);
return data;
}
model.getCurrentWar = async() => {
const sql_text = 'SELECT * FROM war_days WHERE completed = 0 LIMIT 1;'
const data = await db.pool.query(sql_text);
return data[0];
}
model.insertNewWar = async() => {
const sql_text = 'UPDATE war_days SET completed = 1;';
const sql_text2 = 'INSERT INTO war_days (day) VALUES (CURDATE());'
let con = await db.pool.getConnection()
await con.query('START TRANSACTION;');
await con.query(sql_text);
await con.query(sql_text2);
await con.query('COMMIT;');
await con.release();
}
model.warParticipation = async (user_id, house_id, decision) => {
const sql_text = 'SELECT @current_war_id:=id FROM war_days WHERE completed = 0 LIMIT 1;';
const sql_text2 = `INSERT INTO users_war (user_id, war_id, house_id, decision) VALUES (?, @current_war_id, ?, ?)
ON DUPLICATE KEY UPDATE decision = ?`;
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;');
await con.query(sql_text);
await con.query(sql_text2, [user_id, house_id, decision, decision]);
await con.query('COMMIT;');
await con.release();
}
model.getParticipation = async (house_id) => {
const sql_text = `SELECT u.username, uw.decision
FROM users as u
LEFT JOIN users_war as uw ON uw.user_id = u.id
LEFT JOIN war_days as w ON w.id = uw.war_id
WHERE uw.house_id = ? AND w.completed = 0;`;
const data = await db.pool.query(sql_text, [house_id]);
return data;
}
module.exports = model; module.exports = model;
\ No newline at end of file
const Koa = require('koa');
const Router = require('@koa/router'); const Router = require('@koa/router');
const CronJob = require('cron').CronJob;
const router = new Router(); const router = new Router();
const authRouter = new Router(); const authRouter = new Router();
...@@ -8,6 +6,16 @@ const houseModel = require('./model'); ...@@ -8,6 +6,16 @@ const houseModel = require('./model');
const userModel = require('../user/model'); const userModel = require('../user/model');
const membershipRouter = require('./membership/route');
authRouter.use('/membership', membershipRouter.routes(), membershipRouter.allowedMethods());
const memberRouter = require('./member/route');
authRouter.use('/member', memberRouter.routes(), memberRouter.allowedMethods());
const [warRouter, warAuthRouter] = require('./war/route');
router.use('/war', warRouter.routes(), warRouter.allowedMethods());
authRouter.use('/war', warAuthRouter.routes(), warAuthRouter.allowedMethods());
const HOUSE_ROLES = { const HOUSE_ROLES = {
lg: 0, lg: 0,
sen: 1, sen: 1,
...@@ -53,80 +61,6 @@ router.get('/all', async (context, next) => { ...@@ -53,80 +61,6 @@ router.get('/all', async (context, next) => {
} }
}); });
authRouter.get('/members', async(context, next) => {
hasHouse(context);
try{
const data = await houseModel.getMembers(context.user.house_id);
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw(400, "Failed to get members")
}
});
authRouter.get('/member-units/:member_id', async(context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
try{
const data = await houseModel.getMemberUnits(context.params.member_id);
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw('Failed to get Member Units');
}
});
authRouter.post('/modify-role', async(context, next) => {
hasHouse(context);
const body = context.request.body;
if(!body || !body.member_id || !body.role){
context.throw(400, 'Missing parameters')
}
try{
const member = await userModel.getUserFullFromId(body.member_id);
if(!member){
throw Error('Member does not exists');
}
if(member.house_id !== context.user.house_id){
throw Error('Not on the same house');
}
if(member.lk_permission_level <= context.user.lk_permission_level){
throw Error("Member permission level is high")
}
if(checkPermissionsNoThrow(context, HOUSE_ROLES.lg)){
if(body.role === 'lg'){
await houseModel.changeHouseLiege(context.user.id, member.id);
}else{
await houseModel.modifyMemberRole(member.id, body.role);
}
}else{
if(context.user.lk_house_role < HOUSE_ROLES[body.role]){
await houseModel.modifyHouse(member.id, body.role);
}else{
throw Error("Can't modify to the same level");
}
}
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to modify role')
}
})
authRouter.get('/my-permission', async(context, next) => {
if(!context.user.house_id || context.user.lk_permission_level === undefined){
context.throw(400, 'No house');
}
try{
context.response.status = 200;
context.response.body = context.user.lk_permission_level;
}catch(error){
console.log(error);
context.throw(400, 'ERROR');
}
});
authRouter.get('/has-house', async (context, next) => { authRouter.get('/has-house', async (context, next) => {
try{ try{
if(context.user.house_id){ if(context.user.house_id){
...@@ -141,123 +75,6 @@ authRouter.get('/has-house', async (context, next) => { ...@@ -141,123 +75,6 @@ authRouter.get('/has-house', async (context, next) => {
} }
}) })
authRouter.post('/request', async (context, next) => {
if(context.user.house_id){
context.throw(400, 'Already in a house')
}
try{
const body = context.request.body;
if(!body || !body.house_id){
throw Error('No house ID');
}
await houseModel.sendRequest(body.house_id, context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to send request');
}
});
authRouter.delete('/request', async (context, next) => {
if(context.user.house_id){
context.throw(400, 'Already in a house')
}
try{
await houseModel.cancelRequests(context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to send request');
}
});
authRouter.get('/requests', async (context, next) => {
// checkHouse(context);
checkPermissions(context, HOUSE_ROLES.sen);
try{
const data = await houseModel.getHouseRequests(context.user.house_id);
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw(400, 'Unable to get requests');
}
});
authRouter.post('/accept-request', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
try{
const body = context.request.body;
if(!body || !body.user_id){
throw Error("No user to accept");
}
await houseModel.acceptRequest(body.user_id, context.user.house_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Accept Request')
}
});
authRouter.delete('/reject-request/:user_id', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
try{
const body = context.request.body;
if(!context.params.user_id){
throw Error("No user to refuse");
}
await houseModel.rejectRequest(context.params.user_id, context.user.house_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to reject Request')
}
});
authRouter.delete('/delete-member/:user_id', async (context, next) => {
checkPermissions(context, HOUSE_ROLES.sen);
if(context.params.user_id===context.session.user_id){
context.throw(400, "Can't delete yourself");
}
try{
const member = await userModel.getUserFullFromId(context.params.user_id);
if(!member){
throw Error('Member does not exists');
}
if(member.house_id !== context.user.house_id){
throw Error('Not on the same house');
}
if(member.lk_permission_level <= context.user.lk_permission_level){
throw Error("Member permission level is high")
}
await houseModel.deleteMember(context.params.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Delete Member')
}
});
authRouter.delete('/leave-house', async (context, next) => {
if(context.user.lk_house_role==='lg'){
try{
await houseModel.deleteHouse(context.user.house_id, context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Delete House');
}
}else{
try{
await houseModel.leaveHouse(context.session.user_id);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Unable to Leave');
}
}
});
authRouter.get('/', async (context, next) => { authRouter.get('/', async (context, next) => {
hasHouse(context); hasHouse(context);
try{ try{
...@@ -316,64 +133,4 @@ authRouter.delete('/', async (context, next) => { ...@@ -316,64 +133,4 @@ authRouter.delete('/', async (context, next) => {
} }
}); });
authRouter.get('/participation', async (context, next) => {
hasHouse(context);
try{
const war = await houseModel.getCurrentWar();
if(!war){
throw Error('Failed to get Current War');
}
const participation = await houseModel.getParticipation(context.user.house_id);
context.response.status = 200;
context.response.body = {war: war, participation: participation};
}catch(error){
console.log(error);
context.throw('Failed to get Participation');
}
});
authRouter.post('/participation', async (context, next) => {
hasHouse(context);
const body = context.request.body;
if(!body || !body.decision){
context.throw(400, 'No decision found');
}
try{
await houseModel.warParticipation(context.user.id, context.user.house_id, body.decision);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to Update Participation');
}
});
router.get('/current-war', async (context, next) => {
try{
const data = await houseModel.getCurrentWar();
if(!data){
throw Error('Failed to get Current War');
}
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw(400, 'Failed to get Current War');
}
});
async function insertNewWar(){
try{
await houseModel.insertNewWar();
console.log('Inserted new War')
}catch(error){
console.log(error);
}
}
const war_job = new CronJob('30 22 * * Tue,Sat', ()=> {
insertNewWar();
});
war_job.start();
module.exports = [router, authRouter]; module.exports = [router, authRouter];
\ No newline at end of file
const db = require('../../database/database');
const model = {};
model.getCurrentWar = async() => {
const sql_text = 'SELECT * FROM war_days WHERE completed = 0 LIMIT 1;'
const data = await db.pool.query(sql_text);
return data[0];
}
model.insertNewWar = async() => {
const sql_text = 'UPDATE war_days SET completed = 1;';
const sql_text2 = 'INSERT INTO war_days (day) VALUES (CURDATE());'
let con = await db.pool.getConnection()
await con.query('START TRANSACTION;');
await con.query(sql_text);
await con.query(sql_text2);
await con.query('COMMIT;');
await con.release();
}
module.exports = model;
\ No newline at end of file
const db = require('../../../database/database');
const model = {};
// TO DELETE
model.getCurrentWar = async() => {
const sql_text = 'SELECT * FROM war_days WHERE completed = 0 LIMIT 1;'
const data = await db.pool.query(sql_text);
return data[0];
}
model.warParticipation = async (user_id, house_id, decision) => {
const sql_text = 'SELECT @current_war_id:=id FROM war_days WHERE completed = 0 LIMIT 1;';
const sql_text2 = `INSERT INTO users_war (user_id, war_id, house_id, decision) VALUES (?, @current_war_id, ?, ?)
ON DUPLICATE KEY UPDATE decision = ?`;
let con = await db.pool.getConnection();
await con.query('START TRANSACTION;');
await con.query(sql_text);
await con.query(sql_text2, [user_id, house_id, decision, decision]);
await con.query('COMMIT;');
await con.release();
}
model.getParticipation = async (house_id) => {
const sql_text = `SELECT u.username, uw.decision
FROM users as u
LEFT JOIN users_war as uw ON uw.user_id = u.id
LEFT JOIN war_days as w ON w.id = uw.war_id
WHERE uw.house_id = ? AND w.completed = 0;`;
const data = await db.pool.query(sql_text, [house_id]);
return data;
}
module.exports = model;
\ No newline at end of file
const Router = require('@koa/router');
const router = new Router();
const participationModel = require('./model');
// DELETE WHEN CHANGING MODEL
function hasHouse(context){
if(!context.user.house_id){
context.throw(400, 'No house');
}
}
router.get('/', async (context, next) => {
hasHouse(context);
try{
const war = await participationModel.getCurrentWar();
if(!war){
throw Error('Failed to get Current War');
}
const participation = await participationModel.getParticipation(context.user.house_id);
context.response.status = 200;
context.response.body = {war: war, participation: participation};
}catch(error){
console.log(error);
context.throw('Failed to get Participation');
}
});
router.post('/', async (context, next) => {
hasHouse(context);
const body = context.request.body;
if(!body || !body.decision){
context.throw(400, 'No decision found');
}
try{
await participationModel.warParticipation(context.user.id, context.user.house_id, body.decision);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to Update Participation');
}
});
module.exports = router;
\ No newline at end of file
const Router = require('@koa/router');
const CronJob = require('cron').CronJob;
const router = new Router();
const authRouter = new Router();
const warModel = require('./model');
const participationRouter = require('./participation/route');
authRouter.use('/participation', participationRouter.routes(), participationRouter.allowedMethods());
router.get('/', async (context, next) => {
try{
const data = await warModel.getCurrentWar();
if(!data){
throw Error('Failed to get Current War');
}
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw(400, 'Failed to get Current War');
}
});
async function insertNewWar(){
try{
await warModel.insertNewWar();
console.log('Inserted new War')
}catch(error){
console.log(error);
}
}
const war_job = new CronJob('30 22 * * Tue,Sat', ()=> {
insertNewWar();
});
// war_job.start();
module.exports = [router, authRouter];
\ No newline at end of file
...@@ -26,7 +26,7 @@ class Sync{ ...@@ -26,7 +26,7 @@ class Sync{
} }
async requestHouse(house_id){ async requestHouse(house_id){
const response = await fetch('/api/house/request', { const response = await fetch('/api/house/membership/request', {
method: "POST", method: "POST",
body: JSON.stringify({house_id: house_id}), body: JSON.stringify({house_id: house_id}),
headers: { headers: {
......
class Sync{ class Sync{
async getHouse(){ async getHouse(){
const response = await fetch("/api/house/"); const response = await fetch("/api/house");
if(!response.ok){ if(!response.ok){
throw Error('Failed to get requests'); throw Error('Failed to get requests');
...@@ -25,7 +25,7 @@ class Sync{ ...@@ -25,7 +25,7 @@ class Sync{
} }
async modifyHouse(house){ async modifyHouse(house){
const response = await fetch(`/api/house`, { const response = await fetch("/api/house", {
method: "PUT", method: "PUT",
body: JSON.stringify(house), body: JSON.stringify(house),
headers: { headers: {
...@@ -38,7 +38,7 @@ class Sync{ ...@@ -38,7 +38,7 @@ class Sync{
} }
async getRequests(){ async getRequests(){
const response = await fetch("/api/house/requests"); const response = await fetch("/api/house/membership/request/all");
if(!response.ok){ if(!response.ok){
throw Error('Failed to get requests'); throw Error('Failed to get requests');
...@@ -49,7 +49,7 @@ class Sync{ ...@@ -49,7 +49,7 @@ class Sync{
} }
async getMembers(){ async getMembers(){
const response = await fetch("/api/house/members"); const response = await fetch("/api/house/member/all");
if(!response.ok){ if(!response.ok){
throw Error('Failed to get Members'); throw Error('Failed to get Members');
...@@ -60,7 +60,7 @@ class Sync{ ...@@ -60,7 +60,7 @@ class Sync{
} }
async getPermissionLevel(){ async getPermissionLevel(){
const response = await fetch("/api/house/my-permission"); const response = await fetch("/api/house/membership/permissions");
if(!response.ok){ if(!response.ok){
throw Error('Failed to get Permissions'); throw Error('Failed to get Permissions');
...@@ -71,9 +71,9 @@ class Sync{ ...@@ -71,9 +71,9 @@ class Sync{
} }
async modifyMemberRole(member_id, role){ async modifyMemberRole(member_id, role){
const response = await fetch("/api/house/modify-role", { const response = await fetch(`/api/house/membership/${member_id}`, {
method: "POST", method: "PUT",
body: JSON.stringify({member_id: member_id, role: role}), body: JSON.stringify({role: role}),
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
...@@ -84,7 +84,7 @@ class Sync{ ...@@ -84,7 +84,7 @@ class Sync{
} }
async kickMember(member_id){ async kickMember(member_id){
const response = await fetch(`/api/house/delete-member/${member_id}`,{ const response = await fetch(`/api/house/membership/${member_id}`,{
method: "DELETE" method: "DELETE"
}); });
if(!response.ok){ if(!response.ok){
...@@ -93,7 +93,7 @@ class Sync{ ...@@ -93,7 +93,7 @@ class Sync{
} }
async acceptRequest(user_id){ async acceptRequest(user_id){
const response = await fetch("/api/house/accept-request", { const response = await fetch("/api/house/membership", {
method: "POST", method: "POST",
body: JSON.stringify({user_id: user_id}), body: JSON.stringify({user_id: user_id}),
headers: { headers: {
...@@ -106,7 +106,7 @@ class Sync{ ...@@ -106,7 +106,7 @@ class Sync{
} }
async rejectRequest(user_id){ async rejectRequest(user_id){
const response = await fetch(`/api/house/reject-request/${user_id}`, { const response = await fetch(`/api/house/membership/request/${user_id}`, {
method: "DELETE", method: "DELETE",
}); });
if(!response.ok){ if(!response.ok){
...@@ -115,7 +115,7 @@ class Sync{ ...@@ -115,7 +115,7 @@ class Sync{
} }
async getMemberUnits(member_id){ async getMemberUnits(member_id){
const response = await fetch(`/api/house/member-units/${member_id}`); const response = await fetch(`/api/house/member/${member_id}/units`);
if(!response.ok){ if(!response.ok){
throw Error('Failed to get member units'); throw Error('Failed to get member units');
...@@ -126,7 +126,7 @@ class Sync{ ...@@ -126,7 +126,7 @@ class Sync{
} }
async getParticipation(){ async getParticipation(){
const response = await fetch('/api/house/participation'); const response = await fetch('/api/house/war/participation');
if(!response.ok){ if(!response.ok){
throw Error('Failed to get participations'); throw Error('Failed to get participations');
} }
...@@ -136,7 +136,7 @@ class Sync{ ...@@ -136,7 +136,7 @@ class Sync{
} }
async updateParticipation(decision){ async updateParticipation(decision){
const response = await fetch('/api/house/participation',{ const response = await fetch('/api/house/war/participation',{
method: "POST", method: "POST",
body: JSON.stringify({decision: decision}), body: JSON.stringify({decision: decision}),
headers: { headers: {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment