1
1
const Router = require ( "koa-router" ) ;
2
2
const { AdminRequest, Request, User } = require ( "../models" ) ;
3
3
const router = new Router ( ) ;
4
- const { User } = require ( '../models' ) ; // Asegúrate de importar el modelo User
5
4
6
5
const getUserById = async ( userId ) => {
7
6
return await User . findOne ( {
8
7
where : { id : userId } ,
9
- attributes : [ 'id' , 'isAdmin' ] , // Obtener solo los campos necesarios
8
+ attributes : [ 'id' , 'isAdmin' ] ,
10
9
} ) ;
11
10
} ;
12
11
@@ -186,7 +185,13 @@ router.post('/bonds/:bondId/buy', async (ctx) => {
186
185
187
186
router . patch ( '/bonds/:bondId/discount' , async ( ctx ) => {
188
187
const { bondId } = ctx . params ;
189
- const { discount } = ctx . request . body ;
188
+ const { userId, discount } = ctx . request . body ;
189
+
190
+ if ( ! userId ) {
191
+ ctx . status = 400 ;
192
+ ctx . body = { error : 'userId is required.' } ;
193
+ return ;
194
+ }
190
195
191
196
if ( ! [ 10 , 20 , 30 ] . includes ( discount ) ) {
192
197
ctx . status = 400 ;
@@ -195,19 +200,26 @@ router.patch('/bonds/:bondId/discount', async (ctx) => {
195
200
}
196
201
197
202
try {
198
- const bond = await AdminRequest . findByPk ( bondId ) ;
199
-
200
- if ( ! bond ) {
201
- ctx . status = 404 ;
202
- ctx . body = { error : 'Bond not found' } ;
203
- return ;
204
- }
205
-
206
- bond . discount = discount ;
207
- await bond . save ( ) ;
203
+ const user = await User . findOne ( { where : { id : userId } } ) ;
204
+ if ( ! user || ! user . isAdmin ) {
205
+ ctx . status = 403 ;
206
+ ctx . body = { error : 'Access denied. Admins only.' } ;
207
+ return ;
208
+ }
209
+
210
+ const bond = await AdminRequest . findByPk ( bondId ) ;
208
211
209
- ctx . status = 200 ;
210
- ctx . body = { message : 'Discount applied successfully.' , bond } ;
212
+ if ( ! bond ) {
213
+ ctx . status = 404 ;
214
+ ctx . body = { error : 'Bond not found' } ;
215
+ return ;
216
+ }
217
+
218
+ bond . discount = discount ;
219
+ await bond . save ( ) ;
220
+
221
+ ctx . status = 200 ;
222
+ ctx . body = { message : 'Discount applied successfully.' , bond } ;
211
223
} catch ( error ) {
212
224
console . error ( 'Error applying discount:' , error ) ;
213
225
ctx . status = 500 ;
0 commit comments