StudentLoanManagement
ItemController.java
Go to the documentation of this file.
1package com.student_loan.controller;
2
3import org.slf4j.Logger;
4import org.slf4j.LoggerFactory;
5import org.springframework.beans.factory.annotation.Autowired;
6import org.springframework.http.HttpStatus;
7import org.springframework.http.ResponseEntity;
8import org.springframework.security.core.Authentication;
9import org.springframework.security.core.context.SecurityContextHolder;
10import org.springframework.web.bind.annotation.*;
11import java.io.IOException;
12
13import com.student_loan.dtos.ItemRecord;
14import com.student_loan.model.Item;
15import com.student_loan.model.User;
16import com.student_loan.service.ItemService;
17import com.student_loan.service.LoanService;
18import com.student_loan.service.UserService;
19import com.student_loan.utils.ImageUtil;
20
21import java.util.ArrayList;
22import java.util.List;
23import java.util.Optional;
24
30@RestController
31@RequestMapping("/items")
32public class ItemController {
33
34 private static final Logger logger = LoggerFactory.getLogger(ItemController.class);
35
36 @Autowired
37 private ItemService itemService;
38 @Autowired
39 private UserService userService;
40 @Autowired
41 private LoanService loanService;
42
50 @Autowired
51 public ItemController(ItemService itemService, UserService userService, LoanService loanService) {
52 this.itemService = itemService;
53 this.userService = userService;
54 this.loanService = loanService;
55 }
56
62 private User getAuthenticatedUser() {
63 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
64 String email = authentication.getName();
65 return userService.getUserByEmail(email);
66 }
67
73 @GetMapping
74 public ResponseEntity<List<Item>> getAllItems() {
75 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
76 String email = authentication.getName();
77
78 User user = userService.getUserByEmail(email);
79 if (user == null) { // || user.getAdmin()==false) { Temporal
80 return new ResponseEntity<>(new ArrayList<>(),HttpStatus.UNAUTHORIZED);
81 }
82
83 return new ResponseEntity<>(itemService.getAllItems(),HttpStatus.OK);
84 }
85
95 @GetMapping("/available")
96 public ResponseEntity<List<Item>> getAvailableItems() {
97 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
98 String email = authentication.getName();
99
100 User user = userService.getUserByEmail(email);
101 if (user == null) {
102 return new ResponseEntity<>(new ArrayList<>(),HttpStatus.UNAUTHORIZED);
103 }
104
105 return new ResponseEntity<>(itemService.getAvailableItems(),HttpStatus.OK);
106 }
107
108
115 @GetMapping("/user/{id}")
116 public ResponseEntity<List<Item>> getItemsByUser(@PathVariable Long id) {
117 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
118 String email = authentication.getName();
119
120 User user = userService.getUserByEmail(email);
121
122 if (user == null) { // || (user.getAdmin()==false && user.getId()!=id)) { TODO Uncomment to enable a user only to see its own items
123 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
124 }else {
125 try {
126 List<Item> items = itemService.getItemsByUser(id);
127 return new ResponseEntity<>(items, HttpStatus.OK);
128 } catch (RuntimeException e) {
129 return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
130 }
131 }
132 }
133
158 @GetMapping("/{id}")
159 public ResponseEntity<Item> getItemById(@PathVariable Long id) {
160 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
161 String email = authentication.getName();
162
163 User user = userService.getUserByEmail(email);
164 Optional<Item> optionalItem = itemService.getItemById(id);
165
166 if (user == null || optionalItem.isEmpty()) {
167 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); // o 404 si prefieres
168 }
169
170 Item item = optionalItem.get();
171
172 if (!item.getOwner().equals(user.getId())) { // TODO && !user.getAdmin()) {
173 return new ResponseEntity<>(HttpStatus.FORBIDDEN);
174 }
175
176 return new ResponseEntity<>(item, HttpStatus.OK);
177 }
178
184 @GetMapping("/lent")
185 public ResponseEntity<List<Item>> getLentItemsByUser() {
186 // Obtener el usuario autenticado desde el SecurityContext
187 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
188 String email = authentication.getName(); // Usamos el email como identificador
189
190 // Buscar al usuario por el email
191 User user = userService.getUserByEmail(email);
192 if (user == null) {
193 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
194 }
195
196 try {
197 // Obtener los items que el usuario ha prestado
198 List<Long> lentItemsId = loanService.getLentItemsIdByUser(user.getId());
199 List<Item> lentItems = itemService.getItemsById(lentItemsId);
200
201 return new ResponseEntity<>(lentItems, HttpStatus.OK);
202 } catch (RuntimeException e) {
203 // Si ocurre un error, devolvemos un error 500
204 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
205 }
206 }
207
213 @GetMapping("/borrowed")
214 public ResponseEntity<List<Item>> getBorrowedItemsByUser() {
215 // Obtener el usuario autenticado desde el SecurityContext
216 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
217 String email = authentication.getName(); // Usamos el email como identificador
218
219 // Buscar al usuario por el email
220 User user = userService.getUserByEmail(email);
221 if (user == null) {
222 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
223 }
224
225 try {
226 // Obtener los items que el usuario ha prestado
227 List<Long> lentItemsId = loanService.getBorrowedItemsIdByUser(user.getId());
228 List<Item> lentItems = itemService.getItemsById(lentItemsId);
229
230 return new ResponseEntity<>(lentItems, HttpStatus.OK);
231 } catch (RuntimeException e) {
232 // Si ocurre un error, devolvemos un error 500
233 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
234 }
235 }
236
243 @PostMapping("/create")
244 public ResponseEntity<String> createItem(@RequestBody ItemRecord itemRecord) {
245 User user = getAuthenticatedUser();
246 if (user == null) {
247 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
248 }
249
250 Item item = convertToItem(itemRecord);
251 item.setOwner(user.getId());
252 try {
253 if (itemRecord.imageBase64() != null && !itemRecord.imageBase64().isEmpty()) {
254 String imageUrl = ImageUtil.saveBase64Image(itemRecord.imageBase64(), "uploads");
255 item.setImage(imageUrl); // Esto será "/images/xxxx.png"
256 }
257 itemService.saveItem(item);
258 } catch (IOException e) {
259 // Captura la excepción y responde con error 500
260 return new ResponseEntity<>("Error al guardar la imagen: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
261 } catch (RuntimeException e) {
262 return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
263 }
264 // If the item is created successfully, return a 201 Created response
265 return new ResponseEntity<>(HttpStatus.CREATED);
266 }
267
268
269
277 @PostMapping(params = "token")
278 public ResponseEntity<String> createItem(@RequestBody ItemRecord itemRecord, @RequestParam("token") String token) {
279 User user = userService.getUserByToken(token);
280 if (user == null) {
281 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
282 }
283 Item item = convertToItem(itemRecord);
284 item.setOwner(user.getId());
285 try {
286 itemService.saveItem(item);
287 } catch (RuntimeException e) {
288 return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
289 }
290 return new ResponseEntity<>(HttpStatus.CREATED);
291 }
292
293
302 @DeleteMapping("/{id}")
303 public ResponseEntity<String> deleteItem(@PathVariable Long id, @RequestParam("token") String token) {
304 User user = userService.getUserByToken(token);
305 if (user == null || user.getAdmin()==false && user.getId()!=itemService.getItemById(id).get().getOwner()) {
306 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
307
308 }
309
310 itemService.deleteItem(id);
311 return new ResponseEntity<>(HttpStatus.OK);
312 }
313
322 @PutMapping("/{id}")
323 public ResponseEntity<String> updateItem(@PathVariable Long id, @RequestBody ItemRecord item, @RequestParam("token") String token) {
324 User user = userService.getUserByToken(token);
325 if (user == null || user.getId()!=Long.valueOf(itemService.getItemById(id).get().getOwner()) && user.getAdmin()!=true) {
326 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
327 }
328
329 try {
330 Item itemToModify = itemService.getItemById(id).get();
331 itemToModify.setName(item.name() == null ? itemToModify.getName() : item.name() );
332 itemToModify.setDescription(item.description() == null ? itemToModify.getDescription() : item.description() );
333 itemToModify.setCategory(item.category() == null ? itemToModify.getCategory() : item.category());
334 itemToModify.setImage(item.imageBase64() == null ? itemToModify.getImage() : item.imageBase64());
335 itemToModify.setStatus(Item.ItemStatus.valueOf(item.status()==null ? itemToModify.getStatus().toString() : item.status()));
336 itemToModify.setCondition(Item.ItemCondition.valueOf(item.condition()==null ? itemToModify.getCondition().toString() : item.condition()));
337 itemService.saveItem(itemToModify);
338 return new ResponseEntity<>(HttpStatus.OK);
339 } catch (RuntimeException e) {
340 return new ResponseEntity<>(e.getMessage(),HttpStatus.NOT_FOUND);
341 }
342 }
343
350 private Item convertToItem(ItemRecord itemRecord) {
351 Item item = new Item();
352 item.setName(itemRecord.name());
353 item.setDescription(itemRecord.description());
354 item.setCategory(itemRecord.category());
355 item.setImage(itemRecord.imageBase64());
356 item.setStatus(Item.ItemStatus.valueOf(itemRecord.status().toUpperCase()));
357 item.setPurchaseDate(new java.util.Date());
358 item.setPurchasePrice(Double.valueOf(itemRecord.purchasePrice()));
359 item.setCondition(Item.ItemCondition.valueOf(itemRecord.condition().toUpperCase()));
360 return item;
361 }
362}
ItemController(ItemService itemService, UserService userService, LoanService loanService)
ResponseEntity< List< Item > > getAllItems()