-
Notifications
You must be signed in to change notification settings - Fork 3
/
voucher-group-controller.ts
221 lines (205 loc) · 7.97 KB
/
voucher-group-controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of the voucher-group-controller.
*
* @module vouchers
*/
import { Response } from 'express';
import log4js, { Logger } from 'log4js';
import BaseController, { BaseControllerOptions } from './base-controller';
import Policy from './policy';
import { VoucherGroupRequest } from './request/voucher-group-request';
import { RequestWithToken } from '../middleware/token-middleware';
import VoucherGroup from '../entity/user/voucher-group';
import VoucherGroupService from '../service/voucher-group-service';
import { parseRequestPagination } from '../helpers/pagination';
export default class VoucherGroupController extends BaseController {
private logger: Logger = log4js.getLogger('VoucherGroupController');
public constructor(options: BaseControllerOptions) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
}
/**
* @inheritdoc
*/
public getPolicy(): Policy {
return {
'/': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'VoucherGroup', ['*']),
handler: this.getAllVoucherGroups.bind(this),
},
POST: {
body: { modelName: 'VoucherGroupRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'create', 'all', 'VoucherGroup', ['*']),
handler: this.createVoucherGroup.bind(this),
},
},
'/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'VoucherGroup', ['*']),
handler: this.getVoucherGroupById.bind(this),
},
PATCH: {
body: { modelName: 'VoucherGroupRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'update', 'all', 'VoucherGroup', ['*']),
handler: this.updateVoucherGroup.bind(this),
},
},
};
}
/**
* GET /vouchergroups
* @summary Returns all existing voucher groups
* @operationId getAllVouchergroups
* @tags vouchergroups - Operations of voucher group controller
* @security JWT
* @param {integer} take.query - How many voucher groups the endpoint should return
* @param {integer} skip.query - How many voucher groups should be skipped (for pagination)
* @return {PaginatedVoucherGroupResponse} 200 - All existingvoucher
* groups without users
* @return {string} 500 - Internal server error
*/
public async getAllVoucherGroups(req: RequestWithToken, res: Response): Promise<void> {
const { body } = req;
this.logger.trace('Get all voucher groups', body, 'by user', req.token.user);
let take;
let skip;
try {
const pagination = parseRequestPagination(req);
take = pagination.take;
skip = pagination.skip;
} catch (e) {
res.status(400).send(e.message);
return;
}
// handle request
try {
res.json(await VoucherGroupService.getVoucherGroups({}, { take, skip }));
} catch (error) {
this.logger.error('Could not return all voucher groups:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /vouchergroups
* @summary Creates a new voucher group
* @operationId createVouchergroup
* @tags vouchergroups - Operations of voucher group controller
* @param {VoucherGroupRequest} request.body.required -
* The voucher group which should be created
* @security JWT
* @return {VoucherGroupResponse} 200 - The created voucher group entity
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async createVoucherGroup(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as VoucherGroupRequest;
this.logger.trace('Create voucher group', body, 'by user', req.token.user);
const voucherGroupParams = VoucherGroupService.asVoucherGroupParams(body);
// handle request
try {
if (!VoucherGroupService.validateVoucherGroup(voucherGroupParams)) {
res.status(400).json('Invalid voucher group.');
return;
}
res.json(await VoucherGroupService.createVoucherGroup(voucherGroupParams));
} catch (error) {
this.logger.error('Could not create voucher group:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /vouchergroups/{id}
* @summary Returns the requested voucher group
* @operationId getVouchergroupId
* @tags vouchergroups - Operations of voucher group controller
* @param {integer} id.path.required - The id of the voucher group which should be returned
* @security JWT
* @return {VoucherGroupResponse} 200 - The requested voucher group entity
* @return {string} 404 - Not found error
* @return {string} 500 - Internal server error
*/
public async getVoucherGroupById(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const bkgId = Number.parseInt(id, 10);
this.logger.trace('Get single voucher group', id, 'by user', req.token.user);
// handle request
try {
const bkg = await VoucherGroupService.getVoucherGroups({ bkgId });
if (bkg.records[0]) {
res.json(bkg.records[0]);
} else {
res.status(404).json('Voucher group not found.');
}
} catch (error) {
this.logger.error('Could not get voucher group:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PATCH /vouchergroups/{id}
* @summary Updates the requested voucher group
* @operationId updateVoucherGroup
* @tags vouchergroups - Operations of voucher group controller
* @param {integer} id.path.required - The id of the voucher group which should be updated
* @param {VoucherGroupRequest} request.body.required -
* The updated voucher group
* @security JWT
* @return {VoucherGroupResponse} 200 - The requested voucher group entity
* @return {string} 400 - Validation error
* @return {string} 404 - Not found error
* @return {string} 500 - Internal server error
*/
public async updateVoucherGroup(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as VoucherGroupRequest;
const { id } = req.params;
const bkgId = Number.parseInt(id, 10);
this.logger.trace('Update voucher group', id, 'with', body, 'by user', req.token.user);
const voucherGroupParams = VoucherGroupService.asVoucherGroupParams(body);
// handle request
try {
if (!VoucherGroupService.validateVoucherGroup(voucherGroupParams)) {
res.status(400).json('Invalid voucher group.');
return;
}
const bkg = await VoucherGroup.findOne({ where: { id: bkgId } });
if (!bkg) {
res.status(404).json('Voucher group not found.');
return;
}
if (bkg.activeStartDate <= new Date()) {
res.status(403).json('Voucher StartDate has already passed.');
return;
}
if (voucherGroupParams.amount < bkg.amount) {
res.status(400).json('Cannot decrease number of VoucherGroupUsers');
return;
}
res.status(200).json(
await VoucherGroupService.updateVoucherGroup(bkgId, voucherGroupParams),
);
} catch (error) {
this.logger.error('Could not update voucher group:', error);
res.status(500).json('Internal server error.');
}
}
}