Skip to content

Commit

Permalink
Merge pull request #60 from innovationacademy-kr/yoyoo
Browse files Browse the repository at this point in the history
Yoyoo
  • Loading branch information
yubinquitous authored Jun 17, 2022
2 parents a7af928 + 1cc2da9 commit 3f861cc
Show file tree
Hide file tree
Showing 20 changed files with 337 additions and 182 deletions.
1 change: 0 additions & 1 deletion backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ app.use(morgan('dev'));
const { apiRouter } = require('./routes/apiRoute');
const { authMiddleware } = require('./middleware/authmiddleware');

// test for git
app.use(express.static(path.join(__dirname, '../frontend/build/')));
app.use('/api', authMiddleware, apiRouter);

Expand Down
49 changes: 49 additions & 0 deletions backend/controller/activationController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const pool = require('../config/database');
const { sendResponse, isNumeric } = require('../utils/util');
const query = require('../db/query');

// 고장 사물함 리스트 조회
const getInactivatedCabinet = async (_req, res) => {
const connection = await pool.getConnection();
try {
const cabinetList = await query.getInactivatedCabinetList(connection);
return sendResponse(res, cabinetList, 200);
} finally {
connection.release();
}
};

const patchActivation = async (req, res) => {
const { cabinetIdx, activation, reason } = req.body;
if (
!cabinetIdx &&
!activation &&
!isNumeric(activation) &&
!isNumeric(cabinetIdx)
) {
return sendResponse(res, {}, 400);
}

const connection = await pool.getConnection();
try {
connection.beginTransaction();

await query.modifyCabinetActivation(connection, cabinetIdx, activation);
if (activation === 0)
await query.addDisablelog(connection, cabinetIdx, reason);
else await query.modifyDisablelog(connection, cabinetIdx);
connection.commit();
return sendResponse(res, 'ok', 200);
} catch (err) {
connection.rollback();
console.log(err);
return sendResponse(res, err, 500);
} finally {
connection.release();
}
};

module.exports = {
getInactivatedCabinet,
patchActivation,
};
22 changes: 22 additions & 0 deletions backend/controller/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require('dotenv').config({ path: '../.env' });
const jwt = require('jsonwebtoken');
const { sendResponse } = require('../utils/util');
const { getJwtSecret } = require('../config/config');

const postLogin = (req, res) => {
const { id, password } = req.body;
if (!id || !password) {
return sendResponse(res, {}, 400, 'Input error');
}
if (id !== process.env.ADMIN_ID || password !== process.env.ADMIN_PASSWORD) {
return sendResponse(res, {}, 403, 'Authentication fail');
}
const payload = {};
const accessToken = jwt.sign(payload, getJwtSecret(), { expiresIn: '24h' });

return sendResponse(res, { accessToken }, 200, 'Authentication success');
};

module.exports = {
postLogin,
};
18 changes: 18 additions & 0 deletions backend/controller/cabinetController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { sendResponse } = require('../utils/util');
const { getCabinetInfoByFloor } = require('../db/query');
const pool = require('../config/database');

// 층별 사물함 현황(sum)
const getCabinetCountFloor = async (_req, res) => {
const connection = await pool.getConnection();
try {
const cabientInfoByFloor = await getCabinetInfoByFloor(connection);
return sendResponse(res, cabientInfoByFloor, 200);
} finally {
connection.release();
}
};

module.exports = {
getCabinetCountFloor,
};
28 changes: 28 additions & 0 deletions backend/controller/lentController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { getLentUserInfo, getLentOverdue } = require('../db/query');
const { sendResponse } = require('../utils/util');
const pool = require('../config/database');

const getLentInfo = async (_req, res) => {
const connection = await pool.getConnection();
try {
const lentInfo = await getLentUserInfo(connection);
return sendResponse(res, lentInfo, 200);
} finally {
connection.release();
}
};

const getLentOverdueInfo = async (_req, res) => {
const connection = await pool.getConnection();
try {
const overdueInfo = await getLentOverdue(connection);
return sendResponse(res, overdueInfo, 200);
} finally {
connection.release();
}
};

module.exports = {
getLentInfo,
getLentOverdueInfo,
};
60 changes: 60 additions & 0 deletions backend/controller/returnController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const query = require('../db/query');
const { sendResponse, isNumeric } = require('../utils/util');
const pool = require('../config/database');

// 특정 사물함의 정보 ( 대여중이라면: + 유저 + 렌트 정보) 가져옴
const getReturn = async (req, res) => {
const { cabinetIdx } = req.query;

if (!cabinetIdx && !isNumeric(cabinetIdx)) {
return sendResponse(res, {}, 400);
}

const connection = await pool.getConnection();
try {
const cabinetInfo = await query.getCabinet(connection, cabinetIdx);
if (!cabinetInfo) {
return sendResponse(res, {}, 400);
}
return sendResponse(res, cabinetInfo, 200);
} finally {
connection.release();
}
};

// 특정 사물함 반납 처리
const patchReturn = async (req, res) => {
const { cabinetIdx } = req.query;
if (!cabinetIdx && !isNumeric(cabinetIdx)) {
return sendResponse(res, {}, 400);
}

const connection = await pool.getConnection();
try {
await connection.beginTransaction();

// 해당 사물함의 user, lent 정보 가져옴
const userLentInfo = await query.getUserLent(connection, cabinetIdx);
if (!userLentInfo) {
return sendResponse(res, {}, 400);
}

await Promise.all([
query.deleteLent(connection, userLentInfo), // lent 테이블에서 해당 사물함의 대여 정보 삭제
query.addLentLog(connection, userLentInfo), // lent_log에 반납되는 사물함 정보 추가
]);

await connection.commit();
return sendResponse(res, 'ok', 200);
} catch (err) {
await connection.rollback();
return undefined;
} finally {
connection.release();
}
};

module.exports = {
getReturn,
patchReturn,
};
40 changes: 40 additions & 0 deletions backend/controller/searchController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const query = require('../db/query');
const { isNumeric, sendResponse } = require('../utils/util');
const pool = require('../config/database');
// intra_id, cabinetNum 검색 기능
const getSearch = async (req, res) => {
const { intraId, cabinetNum, floor } = req.query;

const connection = await pool.getConnection();
try {
let resultFromLent;
let resultFromLentLog;

if (intraId) {
[resultFromLent, resultFromLentLog] = await Promise.all([
query.getLentByIntraId(connection, intraId),
query.getLentLogByIntraId(connection, intraId),
]);
} else if (
cabinetNum &&
floor &&
isNumeric(cabinetNum) &&
isNumeric(floor)
) {
[resultFromLent, resultFromLentLog] = await Promise.all([
query.getLentByCabinetNum(connection, cabinetNum, floor),
query.getLentLogByCabinetNum(connection, cabinetNum, floor),
]);
} else {
return sendResponse(res, {}, 400);
}

const result = { resultFromLent, resultFromLentLog };
return sendResponse(res, result, 200);
} finally {
connection.release();
}
};
module.exports = {
getSearch,
};
21 changes: 21 additions & 0 deletions backend/db/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,25 @@ const modifyCabinetActivation = async (connection, cabinetIdx, activation) => {
await connection.query(content);
};

// 고장 사물함 log 추가
const addDisablelog = async (connection, cabinetIdx, note) => {
const content = `
INSERT INTO disable (disable_cabinet_id, note)
VALUES (${cabinetIdx}, "${note}");
`;
await connection.query(content);
}

// 고장 사물함 status 0 처리
const modifyDisablelog = async (connection, cabinetIdx) => {
const content = `
UPDATE disable d
SET status=0, fix_time=now()
WHERE disable_cabinet_id=${cabinetIdx} AND status=1;
`;
await connection.query(content);
}

// 반납할 사물함의 lent 정보 가져옴
const getUserLent = async (connection, cabinetIdx) => {
const getUserLentQuery = `
Expand Down Expand Up @@ -186,6 +205,8 @@ module.exports = {
getLentByCabinetNum,
getLentLogByCabinetNum,
modifyCabinetActivation,
addDisablelog,
modifyDisablelog,
getInactivatedCabinetList,
getUserLent,
getCabinet,
Expand Down
9 changes: 9 additions & 0 deletions backend/initial-setting/cabinet.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS `cabinet` (
`cabinet_id` int(11) NOT NULL AUTO_INCREMENT,
`cabinet_num` int(11) NOT NULL,
`location` varchar(30) COLLATE utf8_bin NOT NULL,
`floor` int(11) NOT NULL,
`section` varchar(30) NOT NULL,
`activation` tinyint(4) NOT NULL,
PRIMARY KEY (`cabinet_id`)
) ENGINE=InnoDB AUTO_INCREMENT=345 DEFAULT CHARSET=latin1;
55 changes: 55 additions & 0 deletions backend/initial-setting/createDisabledLogTable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

const pool = require('../config/database');

const disabledLogQuery = fs
.readFileSync('./disabled-log.sql')
.toString('utf-8');
const userQuery = fs.readFileSync('./user.sql').toString('utf-8');
const cabinetQuery = fs.readFileSync('./cabinet.sql').toString('utf-8');

const init = async () => {
try {
await Promise.all([
pool.query(disabledLogQuery),
pool.query(userQuery),
pool.query(cabinetQuery),
]);
console.log(' ✅ User Table');
console.log(' ✅ Cabinet Table');
console.log(' ✅ Disable Log Table');
} catch (error) {
console.log(`❌ ${error}`);
} finally {
pool.end();
}
};

console.log(
'\n 해당 명령어는 한 번만 사용하시면 됩니다.\n\n\x1b[35m `user` `cabinet` `disable`\x1b[0m 테이블을 만듭니다.\n 테이블이 존재하는 경우엔 만들지 않습니다.\n\n 만드시겠습니까? [y/n] (EOF는 yes 처리됩니다.)'
);

rl.on('line', (line) => {
if (line === 'n') {
process.exit();
} else if (line === 'y') {
rl.close();
} else {
console.log('[y/n]으로 입력해주세요');
}
});
rl.on('SIGINT', () => {
process.exit();
});
rl.on('SIGQUIT', () => {
process.exit();
});
rl.on('close', () => {
init();
});
8 changes: 8 additions & 0 deletions backend/initial-setting/disabled-log.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `disable` (
`disable_id` INT AUTO_INCREMENT PRIMARY KEY,
`disable_cabinet_id` INT NOT NULL,
`disable_time` TIMESTAMP DEFAULT current_timestamp,
`fix_time` TIMESTAMP,
`status` TINYINT DEFAULT 1,
`note` TEXT
) ENGINE=innoDB DEFAULT CHARSET=utf8mb4;
8 changes: 8 additions & 0 deletions backend/initial-setting/user.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(11) NOT NULL,
`intra_id` varchar(30) NOT NULL,
`auth` tinyint(4) NOT NULL,
`email` varchar(128) DEFAULT NULL,
`phone` varchar(128) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4 changes: 4 additions & 0 deletions backend/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"compilerOptions": {},
"exclude": ["dist"]
}
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
},
"scripts": {
"start": "npm run build --prefix ../frontend && nodemon app.js",
"dev": "nodemon app.js"
"dev": "nodemon app.js",
"table": "cd initial-setting && node createDisabledLogTable.js"
},
"devDependencies": {
"@types/express": "^4.17.13",
Expand Down
Loading

0 comments on commit 3f861cc

Please sign in to comment.