Skip to content

Commit

Permalink
Merge pull request #40 from Gosrock/dev
Browse files Browse the repository at this point in the history
#38 공연장 인원 제한으로 인한 기능 업데이트
  • Loading branch information
ImNM authored Feb 9, 2022
2 parents 26822e3 + 470be59 commit 62359b6
Show file tree
Hide file tree
Showing 7 changed files with 241 additions and 69 deletions.
17 changes: 15 additions & 2 deletions src/model/Ticket.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,29 @@ const TicketSchema = new Schema(
enum: ['confirm-deposit', 'pending-deposit', 'enter', 'non-deposit']
},

// 전화번호
phoneNumber: { type: String },
// 전화번호 --> 코로나 대응 버젼으로 1인 1매 원칙 유니크 검
phoneNumber: { type: String, unique: true },

// 티켓 연번
ticketNumber: { type: Number, required: true },

// 어드민 (공짜티켓관련)
adminTicket: { type: Boolean, default: false },

// 입금자명
accountName: { type: String },

// 학번
studentID: {
type: String
},

// 소모임 신청 여부
smallGroup: {
type: Boolean,
default: false
},

// 마지막으로 관리한 사람이 누군지. populate 활용하세요.
manager: { type: Schema.Types.ObjectId, ref: 'admin' }
},
Expand Down
11 changes: 8 additions & 3 deletions src/routes/RouteAdminTicketsInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ RouteAdminTicketsInfo.get(
pendingDeposit,
nonDeposit,
entered,
notEntered
notEntered,
// 소모임 신청 관련 인원수
smallGroupSubscription
] = await Promise.all([
Ticket.countDocuments(),
Ticket.countDocuments({
Expand All @@ -44,6 +46,9 @@ RouteAdminTicketsInfo.get(
}),
Ticket.countDocuments({
status: { $in: ['confirm-deposit', 'pending-deposit', 'non-deposit'] }
}),
Ticket.countDocuments({
smallGroup: true
})
]);
resultObject = {
Expand All @@ -53,10 +58,10 @@ RouteAdminTicketsInfo.get(
pendingDeposit: pendingDeposit,
nonDeposit: nonDeposit,
entered: entered,
notEntered: notEntered
notEntered: notEntered,
smallGroupSubscription
};
return res.custom200SuccessData(resultObject);
// return res.json({ success: true, data: { user: '찬진' } });
} catch (err) {
if (err instanceof CustomError) {
return next(err);
Expand Down
6 changes: 3 additions & 3 deletions src/routes/RouteAdminTicketsStatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ RouteAdminTicketsStatus.patch(
validationCatch,
async (req, res, next) => {
try {
const ticketStatus = req.body.status;
const { status: ticketStatus, adminUser } = req.body;
const id = req.params._id;
console.log(id);
// 요청 받은 아이디를 찾아서 그의 status를 요청받은 status로 변경해줘야 함

console.log('어드민 유ㅜ저', adminUser._id);
const statusUpdate = await Ticket.findOneAndUpdate(
{ _id: id },
{ status: ticketStatus },
{ status: ticketStatus, manager: adminUser._id },
{ new: true }
);
console.log(statusUpdate);
Expand Down
74 changes: 74 additions & 0 deletions src/routes/RouteAdminTicketsinfo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const express = require('express');
const RouteAdminTicketsInfo = express.Router();
const { validationCatch } = require('../middleware/validationCatch');
const { query, body } = require('express-validator');
const { ServerCommonError, CustomError } = require('../errors');
const { Ticket, Admin } = require('../model');
const { AdminAuthentication } = require('../middleware');

RouteAdminTicketsInfo.get(
'/admin/tickets/info',
AdminAuthentication,
[],
validationCatch,
async (req, res, next) => {
try {
//티켓관련
let resultObject = {};
const [
issuedTickets,
salesProceeds,
confirmedDeposit,
pendingDeposit,
nonDeposit,
entered,
notEntered,
// 소모임 신청 관련 인원수
smallGroupSubscription
] = await Promise.all([
Ticket.countDocuments(),
Ticket.countDocuments({
status: {
$in: ['confirm-deposit', 'enter']
}
}),
Ticket.countDocuments({
status: { $in: ['confirm-deposit', 'enter'] }
}),
Ticket.countDocuments({
status: { $in: ['pending-deposit'] }
}),
Ticket.countDocuments({
status: { $in: ['non-deposit'] }
}),
Ticket.countDocuments({
status: { $in: ['enter'] }
}),
Ticket.countDocuments({
status: { $in: ['confirm-deposit', 'pending-deposit', 'non-deposit'] }
}),
Ticket.countDocuments({
smallGroup: true
})
]);
resultObject = {
issuedTickets: issuedTickets,
salesProceeds: salesProceeds * 3000,
confirmedDeposit: confirmedDeposit,
pendingDeposit: pendingDeposit,
nonDeposit: nonDeposit,
entered: entered,
notEntered: notEntered,
smallGroupSubscription
};
return res.custom200SuccessData(resultObject);
} catch (err) {
if (err instanceof CustomError) {
return next(err);
}
return next(new ServerCommonError(err));
}
}
);

module.exports = { RouteAdminTicketsInfo };
26 changes: 12 additions & 14 deletions src/routes/RoutePostAdminTickets.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,34 @@ RoutePostAdminTickets.post(
'/admin/tickets',
AdminAuthentication,
[
body('ticketCount')
.exists()
.withMessage('티켓 개수를 입력해주세요')
.isInt()
.withMessage('ticketCount 0이상 10이하의 정수로 필요합니다.')
body('accountNameList').isArray().withMessage('배열을 필요로 합니다'),
body('accountNameList.*.accountName')
.isString()
.withMessage('accountName을 가진 도큐멘트를 필요로 합니다')
.isLength({ min: 1 })
.withMessage('accountName의 길이가 1이상이어야합니다.')
],
validationCatch,
async (req, res, next) => {
try {
// 추후 phoneNumber 는 accessToken 미들웨어에서 가져올 예정입니다./
const { ticketCount, adminUser } = req.body;

if (ticketCount <= 0 || ticketCount > 10) {
return res.custom400FailMessage('티켓수량오류');
}
const { accountNameList, adminUser } = req.body;

let listOfTickets = [];
let step = 0;
// 티켓 전체 수량 세기
const allTicketCount = await Ticket.find().countDocuments();
for (step = 0; step < ticketCount; step++) {
// 티켓 서버에서 발급
accountNameList.map(element => {
const ticket = new Ticket({
ticketNumber: allTicketCount + 1 + step,
accountName: adminUser.name,
accountName: element.accountName,
adminTicket: true,
manager: adminUser._id,
status: 'confirm-deposit'
});
step++;
listOfTickets.push(ticket);
}
});

// 병렬로 티켓 저장
await Promise.all(
Expand Down
83 changes: 42 additions & 41 deletions src/routes/RoutePostTickets.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,68 +13,69 @@ RoutePostTickets.post(
'/tickets',
userAuthentication,
[
body('ticketCount')
.isInt()
.withMessage('ticketCount 0이상 10이하의 정수로 필요합니다.'),
body('accountName')
.isString()
.withMessage('accountName 숫자로 필요합니다.')
.isLength({ min: 2, max: 4 })
.withMessage('name 길이는 3자이어야 합니다.')
.withMessage('name 길이는 3자이어야 합니다.'),
body('studentID')
.isString()
.withMessage('studentID 필요합니다.')
.isLength({ min: 7, max: 7 })
.withMessage('studentID 길이는 7자이어야 합니다.')
.matches(/^C235[0-5][0-9][0-9]|C211[0-2][0-9][0-9]/)
.withMessage('신입생 학번이 맞지 않습니다.'),
body('smallGroup').isBoolean().withMessage('Boolean 형식이어야 합니다.')
],
validationCatch,
async (req, res, next) => {
try {
// 추후 phoneNumber 는 accessToken 미들웨어에서 가져올 예정입니다./
const { phoneNumber, ticketCount, accountName } = req.body;
console.log(phoneNumber, ticketCount, accountName);
const { phoneNumber, accountName, smallGroup, studentID } = req.body;
console.log(phoneNumber, accountName);
const caller = process.env.NAVER_CALLER;

if (ticketCount <= 0 || ticketCount > 10) {
return res.custom400FailMessage('티켓수량오류');
// 티켓 전체 수량 세기
const [allTicketCount, phoneNumberFindTicket] = await Promise.all([
Ticket.find().countDocuments(),
Ticket.findOne({ phoneNumber: phoneNumber })
]);
if (phoneNumberFindTicket) {
// 해당 티켓이 이미 발급된 티켓이면 에러
return res.custom400FailMessage('1인 1매 제한입니다.');
}

let listOfTickets = [];
// 티켓 전체 수량 세기
const allTicketCount = await Ticket.find().countDocuments();
const ticket = new Ticket({
ticketNumber: allTicketCount + 1,
accountName,
phoneNumber,
smallGroup,
studentID
});
// listOfTickets.push(ticket);

for (step = 0; step < ticketCount; step++) {
// 티켓 서버에서 발급
const ticket = new Ticket({
ticketNumber: allTicketCount + 1 + step,
accountName,
phoneNumber
});
listOfTickets.push(ticket);
}
let content = '고스락 티켓 ';
let count = 0;

const multiContent = listOfTickets.map(ticket => {
count++;
return {
// 리스트 형식이어야 함
const messageSendContent = [
{
to: phoneNumber,
content:
content +
ticketCount +
`매\n(${count}/${ticketCount})\n` +
url +
`${ticket._id}`
};
});
// console.log(caller, content, getBytes(multiContent[0].content));
content: content + url + `${ticket._id}`
}
];

await naverMessage(caller, phoneNumber, content, multiContent);
await naverMessage(caller, phoneNumber, content, messageSendContent);

// 병렬로 티켓 저장
//
await Promise.all(
listOfTickets.map(async ticket => {
await ticket.save();
})
);
// 기획안 변경으로 티켓 단매로 바뀌었지만 리스트 구조는 그대로 유지
// await Promise.all(
// listOfTickets.map(async ticket => {
// await ticket.save();
// })
// );
await ticket.save();

return res.custom200SuccessData(listOfTickets);
return res.custom200SuccessData([ticket]);
// return res.json({ success: true, data: { user: '찬진' } });
} catch (err) {
if (err instanceof CustomError) {
Expand Down
Loading

0 comments on commit 62359b6

Please sign in to comment.