StudentLoanManagement
LoanController.java
Go to the documentation of this file.
1package com.student_loan.controller;
2
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.http.HttpStatus;
5import org.springframework.http.ResponseEntity;
6import org.springframework.security.core.Authentication;
7import org.springframework.security.core.context.SecurityContextHolder;
8import org.springframework.web.bind.annotation.*;
9
10import java.util.Optional;
11import com.student_loan.dtos.LoanRecord;
12import com.student_loan.model.Loan;
13import com.student_loan.model.User;
14import com.student_loan.service.LoanService;
15import com.student_loan.service.UserService;
16
17import java.sql.Date;
18import java.util.ArrayList;
19import java.util.Objects;
20import java.util.List;
21import org.slf4j.Logger;
22import org.slf4j.LoggerFactory;
23
29@RestController
30@RequestMapping("/loans")
31public class LoanController {
32 @Autowired
33 private LoanService loanService;
34 @Autowired
35 private UserService userService;
36
37 private static final Logger logger = LoggerFactory.getLogger(ItemController.class);
38
44 private User getAuthenticatedUser() {
45 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
46 String email = authentication.getName();
47 return userService.getUserByEmail(email);
48 }
49
56 @GetMapping
57 public ResponseEntity<List<Loan>> getAllLoans(@RequestParam("token") String token) {
58 User user = userService.getUserByToken(token);
59 if (user == null || user.getAdmin()==false) {
60 return new ResponseEntity<>(new ArrayList<>(),HttpStatus.UNAUTHORIZED);
61 }
62 return new ResponseEntity<>(loanService.getAllLoans(),HttpStatus.OK);
63 }
72 @GetMapping("/{id}")
73 public ResponseEntity<Loan> getLoanById(@PathVariable Long id, @RequestParam("token") String token) {
74 User user = userService.getUserByToken(token);
75 if (user == null ||
76 (!user.getAdmin() &&
77 user.getId() != loanService.getLoanById(id).get().getLender() &&
78 user.getId() != loanService.getLoanById(id).get().getBorrower())) {
79 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
80 }
81
82 Optional<Loan> loanOpt = loanService.getLoanById(id);
83 if (loanOpt.isEmpty()) {
84 return new ResponseEntity<>(HttpStatus.NOT_FOUND);
85 }
86 Loan loan = loanOpt.get();
87 return new ResponseEntity<>(loan, HttpStatus.OK);
88 }
89
97 @GetMapping("/lender")
98 public ResponseEntity<List<Loan>> getLoansByLender() {
99 User user = getAuthenticatedUser();
100 if (user == null) {
101 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
102 }
103 try {
104 List<Loan> loans = loanService.getLoansByLender(user.getId());
105 return new ResponseEntity<>(loans, HttpStatus.OK);
106
107 } catch (RuntimeException e) {
108 return new ResponseEntity<>(HttpStatus.NOT_FOUND);
109 }
110 }
111
119 @GetMapping("/borrower")
120 public ResponseEntity<List<Loan>> getLoansByBorrower() {
121
122 User user = getAuthenticatedUser();
123 if (user == null) {
124 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
125 }
126
127 List<Loan> loans = loanService.getLoansByBorrower(user.getId());
128 return new ResponseEntity<>(loans, HttpStatus.OK);
129 }
130
137 @PostMapping("/create")
138 public ResponseEntity<String> createLoan(@RequestBody LoanRecord loanRecord) {
139 User user = getAuthenticatedUser();
140 if (user == null) {
141 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
142 }
143
144 Loan loanEntity = convertToLoan(loanRecord);
145 loanEntity.setBorrower(user.getId());
146 try {
147 loanService.createLoan(loanEntity);
148 } catch (RuntimeException e) {
149 return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
150 }
151 // If the loan is created successfully, return a 201 Created response
152 return new ResponseEntity<>(HttpStatus.CREATED);
153 }
154
164 @PutMapping("/{id}")
165 public ResponseEntity<String> updateLoan(@PathVariable Long id, @RequestBody LoanRecord loan, @RequestHeader("Authorization") String authHeader) {
166 if (authHeader == null || !authHeader.startsWith("Bearer ")) {
167 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
168 }
169
170 String token = authHeader.substring(7);
171
172 User user = userService.getUserByToken(token);
173 Loan existingLoan = loanService.getLoanById(id).get();
174 if (user == null || user.getId()!=existingLoan.getLender() && user.getId()!=existingLoan.getBorrower() && user.getAdmin()==false) {
175 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
176 }
177
178 try {
179 existingLoan.setLender(loan.lender()==null ? existingLoan.getLender() : loan.lender());
180 existingLoan.setBorrower(loan.borrower()==null ? existingLoan.getBorrower() : loan.borrower());
181 existingLoan.setItem(loan.item()==null ? existingLoan.getItem() : loan.item());
182 existingLoan.setLoanDate(loan.loanDate()==null ? existingLoan.getLoanDate() : Date.valueOf(loan.loanDate()));
183 existingLoan.setEstimatedReturnDate(loan.estimatedReturnDate()==null ? existingLoan.getEstimatedReturnDate() : Date.valueOf(loan.estimatedReturnDate()));
184 existingLoan.setRealReturnDate(loan.realReturnDate()==null ? existingLoan.getRealReturnDate() : Date.valueOf(loan.realReturnDate()));
185 existingLoan.setLoanStatus(loan.loanStatus()==null ? existingLoan.getLoanStatus() : Loan.Status.valueOf(loan.loanStatus()));
186 existingLoan.setRating(loan.rating()==null ? existingLoan.getRating() : Double.valueOf(loan.rating()));
187 existingLoan.setObservations(loan.observations()==null ? existingLoan.getObservations() : loan.observations());
188 loanService.saveLoan(existingLoan);
189 return new ResponseEntity<>(HttpStatus.OK);
190 } catch (RuntimeException e) {
191 return new ResponseEntity<>(e.getMessage(),HttpStatus.NOT_FOUND);
192 }
193 }
194
201 @PutMapping("/{itemId}/return")
202 public ResponseEntity<Void> returnLoan(@PathVariable Long itemId) {
203 User user = getAuthenticatedUser();
204 if (user == null) {
205 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
206 }
207 try {
208 boolean updated = loanService.returnLoan(itemId, user.getId());
209 if (updated) {
210 return new ResponseEntity<>(HttpStatus.OK);
211 } else {
212 return new ResponseEntity<>(HttpStatus.NOT_FOUND);
213 }
214 } catch (Exception e) {
215 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
216 }
217 }
218
219
227 @DeleteMapping("/{id}")
228 public ResponseEntity<String> deleteLoan(@PathVariable Long id, @RequestParam("token") String token) {
229 User user = userService.getUserByToken(token);
230 if (user == null || user.getId()!=loanService.getLoanById(id).get().getLender() && user.getId()!=loanService.getLoanById(id).get().getBorrower() && user.getAdmin()==false) {
231 return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
232 }
233 try {
234 loanService.deleteLoan(id);
235 return new ResponseEntity<>(HttpStatus.OK);
236 } catch (RuntimeException e) {
237 return new ResponseEntity<>(HttpStatus.NOT_FOUND);
238 }
239
240 }
241
248 private Loan convertToLoan(LoanRecord loanRecord) {
249 return new Loan(
250 null,
251 loanRecord.lender(),
252 null, // It is setted in createLoan function
253 loanRecord.item(),
254 Date.valueOf(loanRecord.loanDate()),
255 Date.valueOf(loanRecord.estimatedReturnDate()),
256 null,
257 Loan.Status.IN_USE,
258 null,
259 loanRecord.observations()
260 );
261 }
262
263}
ResponseEntity< List< Loan > > getAllLoans(@RequestParam("token") String token)