diff --git a/.gitignore b/.gitignore index 2f0833d..4d86863 100644 --- a/.gitignore +++ b/.gitignore @@ -34,8 +34,12 @@ build/ ### VS Code ### .vscode/ +pom.xml +src/main/resources/application.properties ### logs ### logs/ .nfs* + + diff --git a/README.md b/README.md index 41a497a..46fa222 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,13 @@ https://drive.google.com/file/d/1gyd7sokLba8Ai6vOULL_auioWAXFHsps/view?usp=drive ![UnityLend drawio](https://github.com/VaniThapar/UnityLend/assets/91086564/d81ee720-ae83-4ba6-810b-1676812c2d48) +# Flow diagram for the lender +Draw.io Link: +https://app.diagrams.net/#G1dLFlWWprYTwwtwjXvi5WEJS94RS7x-uo#%7B%22pageId%22%3A%22W7Y_DPB_WjcdcxQGYy3G%22%7D - - - +# Flow diagram for borrowing request +Draw.io Link: +https://drive.google.com/file/d/1pA5A4blyuBDjGBg7mWg6v0XT-DEOwUn8/view?usp=sharing)https://drive.google.com/file/d/1pA5A4blyuBDjGBg7mWg6v0XT-DEOwUn8/view?usp=sharing diff --git a/pom.xml b/pom.xml index b95f6e6..8a566b1 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.springframework.boot @@ -43,7 +43,7 @@ org.springframework.boot spring-boot-starter-tomcat - provided + org.springframework.boot @@ -72,6 +72,11 @@ org.postgresql postgresql + + com.fasterxml.jackson.core + jackson-databind + 2.12.4 + diff --git a/src/main/java/com/educare/unitylend/controller/BorrowRequestCommunityController.java b/src/main/java/com/educare/unitylend/controller/BorrowRequestCommunityController.java new file mode 100644 index 0000000..e14ef8b --- /dev/null +++ b/src/main/java/com/educare/unitylend/controller/BorrowRequestCommunityController.java @@ -0,0 +1,67 @@ +package com.educare.unitylend.controller; + +import com.educare.unitylend.Exception.ControllerException; +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.Community; +import com.educare.unitylend.service.BorrowRequestCommunityService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@Slf4j +@AllArgsConstructor +@RestController +@RequestMapping("/borrowrequestcommunity") +public class BorrowRequestCommunityController { + + BorrowRequestCommunityService borrowRequestCommunityService; + + @GetMapping("/get-communities/{requestId}") + public ResponseEntity> getCommunitiesByRequestId(@PathVariable String requestId) throws ControllerException { + //Getting all communities for a given request + try { + if (requestId == null || requestId.isEmpty()) { + return ResponseEntity.badRequest().body(List.of("Request ID cannot be null or empty")); + } + + List communityList = borrowRequestCommunityService.getCommunitiesByRequestId(requestId); + + if (communityList == null || communityList.isEmpty()) { + return ResponseEntity.notFound().build(); + } + + return ResponseEntity.ok(communityList); + } catch (Exception e) { + log.error("Error encountered in getting the communities with request ID: {}", requestId, e); + throw new ControllerException("Error encountered in getting the communities with request ID", e); + } + } + + @GetMapping("/get-requests/{communityId}") + public ResponseEntity> getRequestsByCommunityId(@PathVariable String communityId) throws ControllerException { + try { + if (communityId == null || communityId.isEmpty()) { + return ResponseEntity.badRequest().body(List.of("Community ID cannot be null or empty")); + } + + List requests = borrowRequestCommunityService.getRequestsByCommunityId(communityId); + + if (requests == null || requests.isEmpty()) { + return ResponseEntity.notFound().build(); + } + + return ResponseEntity.ok(requests); + } catch (Exception e) { + log.error("Error encountered in getting the requests for community with ID: {}", communityId, e); + throw new ControllerException("Error encountered in getting the requests for community with given ID", e); + } + } + +} diff --git a/src/main/java/com/educare/unitylend/controller/BorrowRequestController.java b/src/main/java/com/educare/unitylend/controller/BorrowRequestController.java new file mode 100644 index 0000000..bb720a9 --- /dev/null +++ b/src/main/java/com/educare/unitylend/controller/BorrowRequestController.java @@ -0,0 +1,192 @@ +package com.educare.unitylend.controller; + +import com.educare.unitylend.Exception.ControllerException; +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.Community; +import com.educare.unitylend.service.BorrowRequestCommunityService; +import com.educare.unitylend.service.BorrowRequestService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.annotations.Param; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@Slf4j +@AllArgsConstructor +@RestController +@RequestMapping("/borrow-request") +public class BorrowRequestController extends BaseController{ + BorrowRequestService borrowRequestService; + BorrowRequestCommunityService borrowRequestCommunityService; + + @GetMapping("get-requests-by-user/{userId}") + public ResponseEntity getBorrowRequestsByUserId(@PathVariable String userId) throws ControllerException{ + try { + if(userId==null || userId.isEmpty()){ + return ResponseEntity.badRequest().body(List.of("User ID cannot be null or empty")); + } + List borrowRequestList = borrowRequestService.getBorrowRequestsByUserId(userId); + return ResponseEntity.ok(borrowRequestList); + } catch (ServiceException e) { + log.error("Error encountered in fetching the borrow requests by user id", e); + throw new ControllerException("Error encountered in fetching the borrow requests by user id",e); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error encountered in validating the user"); + } + } + + @GetMapping("/get-communities-for-user/{userId}") + public ResponseEntity getCommunitiesForUser(@PathVariable String userId) throws ControllerException { + try { + if (userId == null || userId.isEmpty()) { + return ResponseEntity.badRequest().body(List.of("User ID cannot be null or empty")); + } + + List communityList = borrowRequestService.getCommunitiesForWhichBorrowRequestRaisedByUser(userId); + + if (communityList == null || communityList.isEmpty()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No communities found where given user has raised a request"); + } + + return ResponseEntity.ok(communityList); + } catch (Exception e) { + log.error("Error encountered in getting the communities for user with ID: {}", userId, e); + throw new ControllerException("Error encountered in getting the communities", e); + } + } + + @PostMapping("/raise-borrow-request") + public ResponseEntity raiseBorrowRequest(@RequestBody BorrowRequest borrowRequest) throws ControllerException { + try { + String userId = borrowRequest.getBorrower().getUserId(); + + if (userId == null || userId.isEmpty()) { + return ResponseEntity.badRequest().body("User ID cannot be null or empty"); + } + + boolean isBorrowRequestValid = borrowRequestService.validateBorrowRequest(borrowRequest); + + if (isBorrowRequestValid) { + borrowRequestService.createBorrowRequest(borrowRequest); + return ResponseEntity.ok("Raised Borrow Request"); + } else { + return ResponseEntity.ok("Cannot make borrow request as your Monthly EMI is greater than half of monthly salary"); + } + } catch (Exception e) { + log.error("Error encountered in raising borrow request for user with ID: {}", borrowRequest.getBorrower(), e); + throw new ControllerException("Error encountered in getting the communities", e); + } + } + + + @GetMapping("/get-requests-by-community/{communityId}") + public ResponseEntity getBorrowRequestsByCommunityId(@PathVariable String communityId) throws ControllerException{ + try { + if (communityId == null || communityId.isEmpty()) { + return ResponseEntity.badRequest().body(List.of("Community ID cannot be null or empty")); + } + + List borrowRequestList = borrowRequestCommunityService.getRequestsByCommunityId(communityId); + + if (borrowRequestList == null || borrowRequestList.isEmpty()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No borrow requests found for given community"); + } + return ResponseEntity.ok(borrowRequestList); + } catch (ServiceException e) { + log.error("Error encountered in fetching borrow requests in a community"); + throw new ControllerException("Error encountered in fetching borrow requests in a community",e); + } + +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error encountered in validating the community"); + + } + + + @GetMapping("/get-requests-by-amount/{communityId}/{amount}") + ResponseEntitygetBorrowRequestsByAmount(@PathVariable String communityId, @PathVariable BigDecimal amount) throws ControllerException{ + try { + if (communityId == null || communityId.isEmpty()) { + return ResponseEntity.badRequest().body(List.of("Community ID cannot be null or empty")); + } + + List borrowRequestList = borrowRequestCommunityService.getRequestsByCommunityId(communityId); + + if (borrowRequestList == null || borrowRequestList.isEmpty()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No borrow requests found for given community and amount"); + } + + List requiredRequestList=new ArrayList<>(); + for(BorrowRequest request:borrowRequestList){ + if (request.getRequestedAmount().compareTo(amount) >= 0) { + requiredRequestList.add(request); + } + } + + log.info("requiredRequestList is "+ requiredRequestList); + return ResponseEntity.ok(requiredRequestList); + } + catch(ServiceException e){ + log.error("Error encountered in fetching borrow requests for the given community and amount"); + throw new ControllerException("Error encountered in fetching borrow requests for the given community and amount",e); + } + } + + @GetMapping("/get-requests-by-interest/{communityId}/{interest}") + ResponseEntitygetBorrowRequestsByInterest(@PathVariable String communityId, @PathVariable BigDecimal interest) throws ControllerException{ + try { + if (communityId == null || communityId.isEmpty()) { + return ResponseEntity.badRequest().body(List.of("Community ID cannot be null or empty")); + } + List borrowRequestList = borrowRequestCommunityService.getRequestsByCommunityId(communityId); + + if (borrowRequestList == null || borrowRequestList.isEmpty()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No borrow requests found for given community and amount"); + } + + List requiredRequestList=new ArrayList<>(); + for(BorrowRequest request:borrowRequestList){ + if(request.getMonthlyInterestRate().compareTo(interest)<=0){ + requiredRequestList.add(request); + } + } + return ResponseEntity.ok(requiredRequestList); + } + catch(ServiceException e){ + log.error("Error encountered in fetching borrow requests for the given community and interest"); + throw new ControllerException("Error encountered in fetching borrow requests for the given community and interest",e); + } + } + + /*For Administration Purpose*/ + @GetMapping("/get-all-borrow-requests") + public ResponseEntity getAllBorrowRequests() throws ControllerException { + try { + ListborrowRequestList=borrowRequestService.getAllBorrowRequests(); + + if (borrowRequestList == null || borrowRequestList.isEmpty()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No borrow requests created yet"); + + } + + return ResponseEntity.ok(borrowRequestList); + } catch (Exception e) { + log.error("Error encountered in getting all borrow requests", e); + throw new ControllerException("Error encountered in getting all borrow requests", e); + } + } + + + + + + + + + +} \ No newline at end of file diff --git a/src/main/java/com/educare/unitylend/controller/CommunityController.java b/src/main/java/com/educare/unitylend/controller/CommunityController.java index e0c40f0..0061980 100644 --- a/src/main/java/com/educare/unitylend/controller/CommunityController.java +++ b/src/main/java/com/educare/unitylend/controller/CommunityController.java @@ -16,15 +16,17 @@ @AllArgsConstructor @RestController @RequestMapping("/community") + public class CommunityController extends BaseController { CommunityService communityService; @GetMapping("all-communities") public ResponseEntity getAllCommunities() throws ControllerException { + //Getting all the existing communities try { List communityList = communityService.getCommunities(); - if (communityList.isEmpty()) { + if (communityList == null || communityList.isEmpty()) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No data found"); } @@ -36,8 +38,13 @@ public ResponseEntity getAllCommunities() throws ControllerException { } @GetMapping("get-community-by-tag") - public ResponseEntity getCommunityWithTag(@RequestParam String commonTag) throws ControllerException { + public ResponseEntity getCommunityWithTag(@RequestParam(required = false) String commonTag) throws ControllerException { + //Getting all communities with the given common tag try { + if (commonTag == null || commonTag.isEmpty()) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("commonTag parameter is missing or empty"); + } + String communityName = communityService.getCommunityName(commonTag); if (communityName == null || communityName.isEmpty()) { @@ -53,7 +60,12 @@ public ResponseEntity getCommunityWithTag(@RequestParam String commonTag) thr @PostMapping("/create-community") public ResponseEntity createNewCommunity(@RequestBody Community community) throws ControllerException { + //Creating a new community with community object try { + if (community == null) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Request body is null"); + } + communityService.createCommunity(community); return ResponseEntity.ok("success!!!"); } catch (ServiceException e) { @@ -61,4 +73,5 @@ public ResponseEntity createNewCommunity(@RequestBody Community communit throw new ControllerException("Error encountered in creating the community", e); } } + } diff --git a/src/main/java/com/educare/unitylend/controller/LendingTransactionController.java b/src/main/java/com/educare/unitylend/controller/LendingTransactionController.java new file mode 100644 index 0000000..df26c91 --- /dev/null +++ b/src/main/java/com/educare/unitylend/controller/LendingTransactionController.java @@ -0,0 +1,22 @@ +package com.educare.unitylend.controller; +import com.educare.unitylend.Exception.ControllerException; +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.service.UserCommunityService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@Slf4j +@AllArgsConstructor +@RestController +@RequestMapping("/lendingtransaction") +public class LendingTransactionController { + + +} diff --git a/src/main/java/com/educare/unitylend/controller/UserCommunityController.java b/src/main/java/com/educare/unitylend/controller/UserCommunityController.java index 8b48b14..35cb392 100644 --- a/src/main/java/com/educare/unitylend/controller/UserCommunityController.java +++ b/src/main/java/com/educare/unitylend/controller/UserCommunityController.java @@ -1,6 +1,7 @@ package com.educare.unitylend.controller; import com.educare.unitylend.Exception.ControllerException; +import com.educare.unitylend.Exception.ServiceException; import com.educare.unitylend.service.UserCommunityService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -18,18 +19,26 @@ @RequestMapping("/usercommunity") public class UserCommunityController { -private UserCommunityService usercommunityService; - @GetMapping("/{userId}") + private UserCommunityService usercommunityService; + + @GetMapping("/get-communities/{userId}") public ResponseEntity> getAllCommunities(@PathVariable String userId) throws ControllerException { + //Getting all communities for a given user try { + if (userId == null || userId.isEmpty()) { + return ResponseEntity.badRequest().body(List.of("User ID cannot be null or empty")); + } + List communityList = usercommunityService.getCommunitiesByUserId(userId); + + if (communityList == null || communityList.isEmpty()) { + return ResponseEntity.notFound().build(); + } + return ResponseEntity.ok(communityList); - } catch (Exception e) { + } catch (ServiceException e) { log.error("Error encountered in getting the communities for user with ID: {}", userId, e); throw new ControllerException("Error encountered in getting the communities", e); } } - - - } diff --git a/src/main/java/com/educare/unitylend/controller/UserController.java b/src/main/java/com/educare/unitylend/controller/UserController.java index 7793631..b1ee250 100644 --- a/src/main/java/com/educare/unitylend/controller/UserController.java +++ b/src/main/java/com/educare/unitylend/controller/UserController.java @@ -12,20 +12,17 @@ import java.util.List; + @Slf4j @AllArgsConstructor @RestController @RequestMapping("/user") -public class UserController extends BaseController { +public class UserController extends BaseController{ UserService userService; - - /** - * @return List of all the available {@link User} - * @throws ControllerException : Exception to be thrown from controller in case of any exception - */ @GetMapping("all-users") public ResponseEntity getAllUsers() throws ControllerException { + //Getting all the users try { List userList = userService.getUsers(); if (userList.isEmpty()) { @@ -37,38 +34,46 @@ public ResponseEntity getAllUsers() throws ControllerException { throw new ControllerException("Error encountered in getting the users", e); } } - - @PostMapping("/create-user") - public ResponseEntity createUser(@RequestBody User user) throws ControllerException{ - // Create the user + public ResponseEntity createUser(@RequestBody User user) throws ControllerException { + //Creating a new user with the user object try { userService.createUser(user); - return ResponseEntity.ok("succcesss!!!"); + return ResponseEntity.ok("success!!!"); } catch (ServiceException e) { - log.error("Error encountered in getting the users"); - throw new ControllerException("Error encountered in getting the users", e); + log.error("Error encountered in creating the user", e); + throw new ControllerException("Error encountered in creating the user", e); } - } - @PutMapping("/{userId}") + @PutMapping("/update-info/{userId}") public ResponseEntity updateUser(@PathVariable String userId, @RequestBody User updatedUser) throws ControllerException { - // Set the userId in the updatedUser object - updatedUser.setUserid(userId); - System.out.println(updatedUser); - // Validate and update the user + + + //Updating the user + + //Updating the user + try { - userService.updateUser(updatedUser); - } catch (ServiceException e) { - log.error("Error encountered in getting the users"); - throw new ControllerException("Error encountered in getting the users", e); + if (userId == null || userId.isEmpty() || updatedUser == null) { + return ResponseEntity.badRequest().body("User ID and updated user cannot be null or empty"); + } + updatedUser.setUserId(userId); + userService.updateUser(updatedUser, userId); + return ResponseEntity.ok("User updated successfully"); + } + catch (ServiceException e) { + log.error("Error encountered in updating the user", e); + throw new ControllerException("Error encountered in updating the user", e); + } catch (Exception e) { + log.error("Error encountered in getting the communities for user with ID: {}", userId, e); + throw new ControllerException("Error encountered in getting the communities", e); } - - return ResponseEntity.ok("User updated successfully"); } - @GetMapping("/{userId}/get-info") - public ResponseEntity getUserByUserId(@PathVariable String userId) throws ControllerException{ + + @GetMapping("/get-info/{userId}") + public ResponseEntity getUserByUserId(@PathVariable String userId) throws ControllerException { + //Getting user information for a given user by its userId try { if (userId == null || userId.isEmpty()) { return ResponseEntity.badRequest().build(); @@ -82,17 +87,19 @@ public ResponseEntity getUserByUserId(@PathVariable String userId) throws return ResponseEntity.notFound().build(); } } catch (ServiceException e) { - // Log the exception or handle it as needed - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + log.error("Error encountered in getting user information by ID: {}", userId, e); + throw new ControllerException("Error encountered in getting user information", e); } } - @PutMapping("/{userId}/inactive") - public ResponseEntity deactivateUser(@PathVariable String userId) { + @PutMapping("/inactive/{userId}") + public ResponseEntity deactivateUser(@PathVariable String userId) throws ControllerException{ + //Deactivating the user try { if (userId == null || userId.isEmpty()) { - return ResponseEntity.badRequest().build(); + return ResponseEntity.badRequest().body("User ID cannot be null or empty"); } + boolean updated = userService.markUserAsInactive(userId); if (updated) { @@ -101,12 +108,9 @@ public ResponseEntity deactivateUser(@PathVariable String userId) { return ResponseEntity.notFound().build(); } } catch (ServiceException e) { - // Log the exception or handle it as needed - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + log.error("Error encountered in deactivating user with ID: {}", userId, e); + throw new ControllerException("Error encountered in deactivating user", e); } } - } - - diff --git a/src/main/java/com/educare/unitylend/controller/WalletController.java b/src/main/java/com/educare/unitylend/controller/WalletController.java new file mode 100644 index 0000000..9256c49 --- /dev/null +++ b/src/main/java/com/educare/unitylend/controller/WalletController.java @@ -0,0 +1,83 @@ +package com.educare.unitylend.controller; + +import com.educare.unitylend.Exception.ControllerException; +import com.educare.unitylend.model.Wallet; +import com.educare.unitylend.service.WalletService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Slf4j +@AllArgsConstructor +@RestController +@RequestMapping("/wallet") +public class WalletController extends BaseController { + + WalletService walletService; + + /** + * @return List of all the available {@link Wallet} + * @throws ControllerException : Exception to be thrown from controller in case of any exception + */ + + @GetMapping("all-wallets") + public List getAllWallets() throws ControllerException { + try { + List walletList = walletService.getWallets(); + return walletList; + } catch (Exception e) { + log.error("Error encountered in getting the users"); + throw new ControllerException("Error encountered in getting the users", e); + } + } + + @GetMapping("/get-user-info/{userId}") + public Wallet getWalletInfo(@PathVariable String userId) throws ControllerException{ + + try { + return walletService.getWalletInfo(userId); + } catch (Exception e) { + log.error("Error encountered in getting the wallet info for the given user"); + throw new ControllerException("Error encountered in getting the wallet info for the given user", e); + } + } + + @GetMapping("get-wallet/{walletId}") + public Wallet getWalletById(@PathVariable String walletId) throws ControllerException { + try { + return walletService.getWalletById(walletId); + } catch (Exception e) { + log.error("Error in fetching desired wallet's details"); + throw new ControllerException("Error encountered in getting the wallet info for the given walletId", e); + } + } + + @PostMapping("/{walletId}/addAmount") + public ResponseEntity addAmountToWallet(@PathVariable String walletId, @RequestParam Float amount) throws ControllerException{ + try { + walletService.addAmountToWallet(walletId, amount); + return ResponseEntity.ok("Amount added successfully to wallet"); + } catch (Exception e) { + log.error("Error adding requested amount to wallet"); + throw new ControllerException("Error encountered while adding requested amount to wallet", e); + } + } + + @PostMapping("/{walletId}/debitAmount") + public ResponseEntity debitFromWallet(@PathVariable String walletId, @RequestParam Float amount) throws ControllerException{ + try { + walletService.debitFromWallet(walletId, amount); + return ResponseEntity.ok("Amount debited successfully from wallet"); + } catch (Exception e) { + log.error("Error debiting requested amount from wallet"); + throw new ControllerException("Error encountered while debiting requested amount from wallet", e); + } + } +} diff --git a/src/main/java/com/educare/unitylend/dao/BorrowRequestCommunityRepository.java b/src/main/java/com/educare/unitylend/dao/BorrowRequestCommunityRepository.java new file mode 100644 index 0000000..eb18cf9 --- /dev/null +++ b/src/main/java/com/educare/unitylend/dao/BorrowRequestCommunityRepository.java @@ -0,0 +1,25 @@ +package com.educare.unitylend.dao; + +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.Community; +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface BorrowRequestCommunityRepository { + + @Select("select communityid as communityId,communityname as communityName,commontag from community where communityid in (select communityid from borrowrequestcommunity where requestid=#{requestId})") + List getCommunitiesByRequestId(@Param("requestId") String requestId); + + @Select("SELECT requestid as requestId,returnperiod as returnPeriod, collectedamount as collectedAmount,requestedamount as requestedAmount, monthlyinterestrate as monthlyInterestRate, timestamp as timestamp from borrowrequest where requestid in (select requestid from borrowrequestcommunity where communityid=#{communityId})") + List getRequestsByCommunityId(@Param("communityId") String communityId); + + @Insert("insert into borrowrequestcommunity(requestid ,communityid) values (#{requestId},#{communityId})") + void createBorrowRequestCommunityMapping(@Param("requestId") String requestId, @Param("communityId") String communityId); +} diff --git a/src/main/java/com/educare/unitylend/dao/BorrowRequestRepository.java b/src/main/java/com/educare/unitylend/dao/BorrowRequestRepository.java new file mode 100644 index 0000000..5380600 --- /dev/null +++ b/src/main/java/com/educare/unitylend/dao/BorrowRequestRepository.java @@ -0,0 +1,22 @@ +package com.educare.unitylend.dao; + +import com.educare.unitylend.model.BorrowRequest; +import org.apache.ibatis.annotations.*; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface BorrowRequestRepository { + + @Insert("INSERT INTO borrowrequest(requestid, returnperiod,timestamp,requestedamount, monthlyinterestrate) VALUES (uuid_generate_v4(),#{returnPeriod},NOW(),#{requestedAmount},#{monthlyInterestRate})") + @Options(useGeneratedKeys = true, keyProperty = "requestId") + void createBorrowRequest(BorrowRequest borrowRequest); + + @Select("SELECT requestid as requestId,returnperiod as returnPeriod, collectedamount as collectedAmount,requestedamount as requestedAmount, monthlyinterestrate as monthlyInterestRate FROM borrowrequest") + List getAllBorrowRequests(); + + @Select("SELECT requestid as requestId,returnperiod as returnPeriod, collectedamount as collectedAmount,requestedamount as requestedAmount, monthlyinterestrate as monthlyInterestRate FROM borrowrequest where borrowerid=#{userId}") + List getBorrowRequestsByUserId(String userId); +} \ No newline at end of file diff --git a/src/main/java/com/educare/unitylend/dao/CommunityRepository.java b/src/main/java/com/educare/unitylend/dao/CommunityRepository.java index c97d27e..22e04fe 100644 --- a/src/main/java/com/educare/unitylend/dao/CommunityRepository.java +++ b/src/main/java/com/educare/unitylend/dao/CommunityRepository.java @@ -1,35 +1,112 @@ package com.educare.unitylend.dao; import com.educare.unitylend.model.Community; -import org.apache.ibatis.annotations.Insert; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import java.util.List; +import java.util.Map; @Mapper @Repository public interface CommunityRepository { - @Select("select * from community") + String SELECT_COMMUNITIES = "select communityid as communityId,communityname as communityName,commontag from community"; + + @Select(SELECT_COMMUNITIES) List getAllCommunities(); - @Select("select communityname from community where commontag = #{commontag}") - String getCommunity(String commontag); + @Select({ + "" + }) + String getCommunity(@Param("commonTag") String commonTag); + + + @Insert({ + "" + }) + void createCommunity(@Param("community") Community community); + + + @Insert({ + "" + }) + void createCommunityUsingStrings(@Param("name") String name, @Param("tag") String tag); - @Insert("INSERT INTO community (communityid, communityname, commontag) VALUES (uuid_generate_v4(), #{communityname}, #{commontag})") - void createCommunity(Community community); - @Insert("INSERT INTO community (communityid, communityname, commontag) VALUES (uuid_generate_v4(), #{name}, #{tag})") - void createCommunityUsingStrings(String name, String tag); + @Select({ + "" + }) + boolean existsByCommontag(@Param("commonTag") String commonTag); - @Select("SELECT COUNT(*) > 0 FROM community WHERE commontag = #{commontag}") - boolean existsByCommontag(String commontag); + @Select({ + "" + }) + @MapKey("commontag") + Map findCommontagsByNames(@Param("names") List names); - @Select("SELECT commontag FROM community WHERE commontag = #{commontag}") - String findByCommontag(String commontag); + @Select({ + "" + }) + String getCommunityIdByName(@Param("name") String name); - @Select("SELECT communityid FROM community WHERE communityname = #{name}") - String getCommunityIdByName(String name); } diff --git a/src/main/java/com/educare/unitylend/dao/LendingTransactionRepository.java b/src/main/java/com/educare/unitylend/dao/LendingTransactionRepository.java new file mode 100644 index 0000000..d029699 --- /dev/null +++ b/src/main/java/com/educare/unitylend/dao/LendingTransactionRepository.java @@ -0,0 +1,4 @@ +package com.educare.unitylend.dao; + +public interface LendingTransactionRepository { +} diff --git a/src/main/java/com/educare/unitylend/dao/UserCommunityRepository.java b/src/main/java/com/educare/unitylend/dao/UserCommunityRepository.java index 33bc46c..626a416 100644 --- a/src/main/java/com/educare/unitylend/dao/UserCommunityRepository.java +++ b/src/main/java/com/educare/unitylend/dao/UserCommunityRepository.java @@ -1,10 +1,7 @@ package com.educare.unitylend.dao; -import org.apache.ibatis.annotations.Insert; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import java.util.List; @@ -12,12 +9,45 @@ @Mapper @Repository public interface UserCommunityRepository { - @Insert("INSERT INTO usercommunity (userid, communityid) VALUES (#{userid}, #{communityid})") - void createUserCommunityMapping(@Param("userid") String userId, @Param("communityid") String communityId); - - - @Select("SELECT c.CommunityName FROM Community c JOIN UserCommunity uc ON c.CommunityId = uc.CommunityId WHERE uc.UserId = #{userId}") + @Select({ + "" + }) List findCommunityNamesByUserId(@Param("userId") String userId); - -} + @Insert({ + "" + }) + void createUserCommunityMapping( + @Param("userId") String userId, + @Param("communityId") String communityId + ); + + + @Delete({ + "" + }) + void deletePrevData(@Param("userId") String userId); + + +} \ No newline at end of file diff --git a/src/main/java/com/educare/unitylend/dao/UserRepository.java b/src/main/java/com/educare/unitylend/dao/UserRepository.java index 713731a..bb9a03d 100644 --- a/src/main/java/com/educare/unitylend/dao/UserRepository.java +++ b/src/main/java/com/educare/unitylend/dao/UserRepository.java @@ -10,39 +10,82 @@ @Repository public interface UserRepository { -// static String getUserForUserIdQuery(String userId){ -// StringBuilder sqlQueryBuilder = new StringBuilder(); -// -// sqlQueryBuilder.append("select userid as userID, password, name,email,dob,income,officename,collegeuniversity,locality,isactive from User where 1=1 "); -// if(userId != null){ -// sqlQueryBuilder.append(" and userId = %s".formatted(userId)); -// } -// -// return sqlQueryBuilder.toString(); -// } - - @Select("select * from tempuser") - List getAllUsers(); + String SELECT_USERS = "select * from tempuser"; -// @SelectProvider(type = UserRepository.class, method = "getUserForUserIdQuery") -// User getUserForUserId(@Param("UserId") String userId); - // static final List SELECT_USERS = "select password from User"; + @Select(SELECT_USERS) + List getAllUsers(); - @Insert("INSERT INTO tempuser (userid, password, name,email,dob,income,officename,collegeuniversity,locality) VALUES (CAST(uuid_generate_v4() AS VARCHAR), #{password}, #{name}, #{email},#{dob},#{income},#{officename},#{collegeuniversity},#{locality})") + @Insert({ + "" + }) void createUser(User user); - @Select("SELECT * FROM tempuser WHERE userid = #{userid}") + @Select({ + "" + }) User getUserForUserId(String userId); - @Select("SELECT userid FROM tempuser WHERE email = #{email}") + + @Select({ + "" + }) String settingID(@Param("email") String email); - @Update("UPDATE tempuser SET name = #{name}, password = #{password}, email = #{email}, locality = #{locality}, officename = #{officename}, collegeuniversity = #{collegeuniversity}, income = #{income}, isActive = #{isActive} WHERE userid = #{userid}") + @Update({ + "" + }) void updateUser(User user); - @Update("UPDATE tempuser SET isActive = #{isActive} WHERE userid = #{userid}") + @Update({ + "" + }) void inactivatingUser(User user); -} + @Select("SELECT CONCAT(officename, ', ', collegeuniversity, ', ', locality) AS community FROM tempuser WHERE userid = #{userId}") + List findCommunitiesByUserId(String userId); + + +} \ No newline at end of file diff --git a/src/main/java/com/educare/unitylend/dao/WalletRepository.java b/src/main/java/com/educare/unitylend/dao/WalletRepository.java new file mode 100644 index 0000000..1a68519 --- /dev/null +++ b/src/main/java/com/educare/unitylend/dao/WalletRepository.java @@ -0,0 +1,44 @@ +package com.educare.unitylend.dao; + + +import com.educare.unitylend.model.User; +import com.educare.unitylend.model.Wallet; +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.springframework.stereotype.Repository; +import org.apache.ibatis.annotations.Update; +import org.springframework.stereotype.Repository; + + +import java.util.List; + + +@Mapper +@Repository +public interface WalletRepository { + + @Select("select * from wallet") + List getAllWallets(); + + + @Select("SELECT w.walletid, w.userid, w.balance FROM wallet w JOIN tempuser u ON w.userid = u.userid WHERE w.userid = #{userId}") + Wallet getWalletInfo(@Param("userId") String userId); + + + @Insert("INSERT INTO wallet (walletid, balance, userid) VALUES (uuid_generate_v4(), 0, #{userId})") + void generateWalletInTable(String userId); + + + @Select("SELECT u.* FROM tempuser u WHERE u.userid = (SELECT userid FROM wallet WHERE walletid = #{ex.walletid})") + User getUserIdWithWallet(@Param("ex") Wallet ex); + + + @Select("SELECT * FROM wallet WHERE walletid = #{walletid}") + Wallet getWalletById(@Param("walletid") String walletid); + + + @Update("UPDATE wallet SET balance = #{balance} WHERE walletid = #{walletid}") + void updateBalance(@Param("walletid") String walletid, @Param("balance") Float balance); +} diff --git a/src/main/java/com/educare/unitylend/model/BorrowRequest.java b/src/main/java/com/educare/unitylend/model/BorrowRequest.java index 3aeabd6..22563b0 100644 --- a/src/main/java/com/educare/unitylend/model/BorrowRequest.java +++ b/src/main/java/com/educare/unitylend/model/BorrowRequest.java @@ -1,23 +1,34 @@ package com.educare.unitylend.model; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.time.LocalDateTime; -import java.util.UUID; +import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor + public class BorrowRequest { private String requestId; private User borrower; - private Community community; - private String returnPeriod; + private List communityIds; + private Integer returnPeriod; private String status; private LocalDateTime timestamp; private BigDecimal collectedAmount; - private BigDecimal targetAmount; + private BigDecimal requestedAmount; + private BigDecimal monthlyInterestRate; + + public String getBorrowerId() { + return (borrower != null) ? borrower.getUserId() : null; + } + + } diff --git a/src/main/java/com/educare/unitylend/model/Community.java b/src/main/java/com/educare/unitylend/model/Community.java index 022b45e..cd0ab53 100644 --- a/src/main/java/com/educare/unitylend/model/Community.java +++ b/src/main/java/com/educare/unitylend/model/Community.java @@ -8,31 +8,7 @@ @NoArgsConstructor @AllArgsConstructor public class Community { - private String communityid; - private String communityname; - private String commontag; - - public String getCommunityid() { - return communityid; - } - - public void setCommunityid(String communityid) { - this.communityid = communityid; - } - - public String getCommunityname() { - return communityname; - } - - public void setCommunityname(String communityname) { - this.communityname = communityname; - } - - public String getCommontag() { - return commontag; - } - - public void setCommontag(String commontag) { - this.commontag = commontag; - } + private String communityId; + private String communityName; + private String commonTag; } diff --git a/src/main/java/com/educare/unitylend/model/LendingHistory.java b/src/main/java/com/educare/unitylend/model/LendingTransaction.java similarity index 100% rename from src/main/java/com/educare/unitylend/model/LendingHistory.java rename to src/main/java/com/educare/unitylend/model/LendingTransaction.java diff --git a/src/main/java/com/educare/unitylend/model/User.java b/src/main/java/com/educare/unitylend/model/User.java index b191a6b..0be287c 100644 --- a/src/main/java/com/educare/unitylend/model/User.java +++ b/src/main/java/com/educare/unitylend/model/User.java @@ -11,107 +11,16 @@ @NoArgsConstructor @AllArgsConstructor public class User { - private String userid; + private String userId; private String password; private String name; private String email; private LocalDate dob; private Integer income; private Integer borrowingLimit; - private String officename; - private String collegeuniversity; + private String officeName; + private String collegeUniversity; private String locality; private boolean isActive; - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean active) { - isActive = active; - } - - public Integer getIncome() { - return income; - } - - public String getOfficename() { - return officename; - } - - public void setOfficename(String officename) { - this.officename = officename; - } - - public String getCollegeuniversity() { - return collegeuniversity; - } - - public String getPassword() { - return password; - } - - public String getName() { - return name; - } - - public String getEmail() { - return email; - } - - public LocalDate getDob() { - return dob; - } - - public void setCollegeuniversity(String collegeuniversity) { - this.collegeuniversity = collegeuniversity; - } - - public String getUserid() { - return userid; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setName(String name) { - this.name = name; - } - - public void setEmail(String email) { - this.email = email; - } - - public void setDob(LocalDate dob) { - this.dob = dob; - } - - public void setUserid(String userid) { - this.userid = userid; - } - - public String getLocality() { - return locality; - } - - public void setLocality(String locality) { - this.locality = locality; - } - - public void setIncome(Integer income) { - // System.out.println(income); - this.income = income; - } - - public Integer getBorrowingLimit() { - return borrowingLimit; - } - - public void setBorrowingLimit(Integer borrowingLimit) { - this.borrowingLimit = borrowingLimit; - // System.out.println(borrowingLimit); - } - - } + diff --git a/src/main/java/com/educare/unitylend/model/Wallet.java b/src/main/java/com/educare/unitylend/model/Wallet.java index 6bfbb8c..a4374d2 100644 --- a/src/main/java/com/educare/unitylend/model/Wallet.java +++ b/src/main/java/com/educare/unitylend/model/Wallet.java @@ -10,7 +10,7 @@ @NoArgsConstructor @AllArgsConstructor public class Wallet { - private String Walletid; - + private String Wallet; + private String userId; private Float Balance; } diff --git a/src/main/java/com/educare/unitylend/service/BorrowRequestCommunityService.java b/src/main/java/com/educare/unitylend/service/BorrowRequestCommunityService.java new file mode 100644 index 0000000..c620691 --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/BorrowRequestCommunityService.java @@ -0,0 +1,14 @@ +package com.educare.unitylend.service; + +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.Community; + +import java.util.List; + +public interface BorrowRequestCommunityService { + + List getCommunitiesByRequestId(String requestId) throws ServiceException; + + List getRequestsByCommunityId(String communityId) throws ServiceException; +} diff --git a/src/main/java/com/educare/unitylend/service/BorrowRequestService.java b/src/main/java/com/educare/unitylend/service/BorrowRequestService.java new file mode 100644 index 0000000..3c5f9cf --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/BorrowRequestService.java @@ -0,0 +1,24 @@ +package com.educare.unitylend.service; + +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.Community; + +import java.util.List; + +public interface BorrowRequestService { + + List getCommunitiesForWhichBorrowRequestRaisedByUser(String userId) throws ServiceException; + + boolean validateBorrowRequest(BorrowRequest borrowRequest) throws ServiceException; + + void createBorrowRequest(BorrowRequest borrowRequest) throws ServiceException; + + void mapBorrowRequestToCommunity(String requestId, ListCommunityIds); + + void mapBorrowRequestToCommunity(String requestId, String communityId); + + List getAllBorrowRequests() throws ServiceException; + + List getBorrowRequestsByUserId(String userId) throws ServiceException; +} \ No newline at end of file diff --git a/src/main/java/com/educare/unitylend/service/CommunityService.java b/src/main/java/com/educare/unitylend/service/CommunityService.java index 291f6c9..8105bb1 100644 --- a/src/main/java/com/educare/unitylend/service/CommunityService.java +++ b/src/main/java/com/educare/unitylend/service/CommunityService.java @@ -2,13 +2,27 @@ import com.educare.unitylend.Exception.ServiceException; import com.educare.unitylend.model.Community; -import com.educare.unitylend.model.User; import java.util.List; public interface CommunityService { + /** + * @return the list of all available {@link Community} + * @throws ServiceException : Throws if any exception occurs + */ List getCommunities() throws ServiceException; + + /** + * @return the Communtiy name of available {@link Community} based on common tag + * @throws ServiceException : Throws if any exception occurs + */ String getCommunityName(String communityTag) throws ServiceException; + + /** + * create the community {@link Community} + * + * @throws ServiceException : Throws if any exception occurs + */ void createCommunity(Community community) throws ServiceException; } diff --git a/src/main/java/com/educare/unitylend/service/LendingTransactionService.java b/src/main/java/com/educare/unitylend/service/LendingTransactionService.java new file mode 100644 index 0000000..54c1c58 --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/LendingTransactionService.java @@ -0,0 +1,4 @@ +package com.educare.unitylend.service; + +public interface LendingTransactionService { +} diff --git a/src/main/java/com/educare/unitylend/service/UserCommunityService.java b/src/main/java/com/educare/unitylend/service/UserCommunityService.java index 67fc9d3..a8d273e 100644 --- a/src/main/java/com/educare/unitylend/service/UserCommunityService.java +++ b/src/main/java/com/educare/unitylend/service/UserCommunityService.java @@ -1,10 +1,13 @@ package com.educare.unitylend.service; import com.educare.unitylend.Exception.ServiceException; -import com.educare.unitylend.model.User; import java.util.List; public interface UserCommunityService { + /** + * @return the list of all available user and community mappings + * @throws ServiceException : Throws if any exception occurs + */ List getCommunitiesByUserId(String userId) throws ServiceException; } diff --git a/src/main/java/com/educare/unitylend/service/UserService.java b/src/main/java/com/educare/unitylend/service/UserService.java index 3034b37..9166f7d 100644 --- a/src/main/java/com/educare/unitylend/service/UserService.java +++ b/src/main/java/com/educare/unitylend/service/UserService.java @@ -13,13 +13,23 @@ public interface UserService { */ List getUsers() throws ServiceException; - void updateUser(User user) throws ServiceException; + /** + * update the user infomation {@link User} + * + * @throws ServiceException : Throws if any exception occurs + */ + void updateUser(User user,String userId) throws ServiceException; boolean markUserAsInactive(String userId) throws ServiceException; + + /** + * create the user {@link User} + * @throws ServiceException : Throws if any exception occurs + */ void createUser(User user) throws ServiceException; + /** - * @param userId : Uniquely identifies a user - * @return Object of {@link User} for the given parameter - * @throws ServiceException :Throws if any exception occurs + * @return the User using userId + * @throws ServiceException : Throws if any exception occurs */ User getUserByUserId(String userId) throws ServiceException; } diff --git a/src/main/java/com/educare/unitylend/service/WalletService.java b/src/main/java/com/educare/unitylend/service/WalletService.java new file mode 100644 index 0000000..37e2419 --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/WalletService.java @@ -0,0 +1,21 @@ +package com.educare.unitylend.service; + +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.model.Wallet; + +import java.util.List; + +public interface WalletService { + + Wallet getWalletInfo(String userId) throws ServiceException; + + void generateWallet(String userId) throws ServiceException; + + List getWallets() throws ServiceException; + + Wallet getWalletById(String walletId) throws ServiceException; + + void addAmountToWallet(String walletId, Float amount) throws ServiceException; + + void debitFromWallet(String walletId, Float amount) throws ServiceException; +} diff --git a/src/main/java/com/educare/unitylend/service/impl/BorrowRequestCommunityServiceImpl.java b/src/main/java/com/educare/unitylend/service/impl/BorrowRequestCommunityServiceImpl.java new file mode 100644 index 0000000..f1e16ce --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/impl/BorrowRequestCommunityServiceImpl.java @@ -0,0 +1,43 @@ +package com.educare.unitylend.service.impl; + +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.dao.BorrowRequestCommunityRepository; +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.Community; +import com.educare.unitylend.service.BorrowRequestCommunityService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.List; +@Slf4j +@AllArgsConstructor +@Service + +public class BorrowRequestCommunityServiceImpl implements BorrowRequestCommunityService { + + BorrowRequestCommunityRepository borrowRequestCommunityRepository; + @Override + public List getCommunitiesByRequestId(String requestId) throws ServiceException { + try{ + Listcommunities = borrowRequestCommunityRepository.getCommunitiesByRequestId(requestId); + return communities; + } + catch(Exception e){ + log.error("Error encountered while fetching communities in which request with given request id is raised"); + throw new ServiceException("Error encountered while fetching communities in which request with given request id is raised",e); + } + } + + @Override + public List getRequestsByCommunityId(String communityId) throws ServiceException { + try{ + Listrequests = borrowRequestCommunityRepository.getRequestsByCommunityId(communityId); + return requests; + } + catch(Exception e){ + log.error("Error encountered while fetching requests by community id"); + throw new ServiceException("Error encountered while fetching requests by community id",e); + } + } +} diff --git a/src/main/java/com/educare/unitylend/service/impl/BorrowRequestServiceImpl.java b/src/main/java/com/educare/unitylend/service/impl/BorrowRequestServiceImpl.java new file mode 100644 index 0000000..a32e919 --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/impl/BorrowRequestServiceImpl.java @@ -0,0 +1,141 @@ +package com.educare.unitylend.service.impl; + +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.dao.BorrowRequestCommunityRepository; +import com.educare.unitylend.dao.BorrowRequestRepository; +import com.educare.unitylend.dao.UserRepository; +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.Community; +import com.educare.unitylend.model.User; +import com.educare.unitylend.service.BorrowRequestService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; + +@Slf4j +@AllArgsConstructor +@Service +public class BorrowRequestServiceImpl implements BorrowRequestService { + private UserRepository userRepository; + private BorrowRequestRepository borrowRequestRepository; + private BorrowRequestCommunityRepository borrowRequestCommunityRepository; + + @Override + public List getCommunitiesForWhichBorrowRequestRaisedByUser(String userId) throws ServiceException { + + try { + ListborrowRequestListByUser=borrowRequestRepository.getBorrowRequestsByUserId(userId); + Listcommunities=new ArrayList<>(); + + for(BorrowRequest request:borrowRequestListByUser){ + ListcommunityList=borrowRequestCommunityRepository.getCommunitiesByRequestId(request.getRequestId()); + for(Community community:communityList){ + if(!communities.contains(community)){ + communities.add(community); + } + } + } + return communities; + } catch (Exception e) { + log.error("Error while getting communities where given user has raised request"); + throw new ServiceException("Error while getting communities where given user has raised request", e); + } + } + + @Override + public void createBorrowRequest(BorrowRequest borrowRequest) throws ServiceException { + + try { + borrowRequestRepository.createBorrowRequest(borrowRequest); + + List communityIds = borrowRequest.getCommunityIds(); + String requestId = borrowRequest.getRequestId(); + + mapBorrowRequestToCommunity(requestId, communityIds); + } catch (Exception e) { + log.error("Error while creating borrow request"); + throw new ServiceException("Error while creating borrow request", e); + } + + } + + @Override + public void mapBorrowRequestToCommunity(String requestId, List CommunityIds) { + for (String communityId : CommunityIds) { + borrowRequestCommunityRepository.createBorrowRequestCommunityMapping(requestId, communityId); + } + } + + @Override + public void mapBorrowRequestToCommunity(String requestId, String communityId) { + borrowRequestCommunityRepository.createBorrowRequestCommunityMapping(requestId, communityId); + } + + @Override + public boolean validateBorrowRequest(BorrowRequest borrowRequest) throws ServiceException { + + try { + String borrowerId=borrowRequest.getBorrower().getUserId(); + User borrower = userRepository.getUserForUserId(borrowerId); + Integer returnPeriod = borrowRequest.getReturnPeriod(); + BigDecimal returnPeriodInMonths = daysToMonths(returnPeriod); + BigDecimal requestedAmount = borrowRequest.getRequestedAmount(); + BigDecimal monthlyInterestRate = borrowRequest.getMonthlyInterestRate(); + + BigDecimal monthlyEMI = calculateMonthlyEMI(requestedAmount, monthlyInterestRate, returnPeriodInMonths); + Integer income = borrower.getIncome(); + + return isMonthlyEMIAffordable(income, monthlyEMI); + } catch (Exception e) { + log.error("Error while validating the borrow request"); + throw new ServiceException("Error while validating the borrow request", e); + } + + } + + @Override + public List getAllBorrowRequests() throws ServiceException{ + try{ + return borrowRequestRepository.getAllBorrowRequests(); + } + catch (Exception e){ + log.error("Error encountered while getting all borrow requests"); + throw new ServiceException("Error encountered while getting all borrow requests",e); + } + } + + @Override + public List getBorrowRequestsByUserId(String userId) throws ServiceException{ + try { + List borrowRequestList = borrowRequestRepository.getBorrowRequestsByUserId(userId); + return borrowRequestList; + } catch (Exception e) { + log.error("Error encountered during getting requests by user id"); + throw new ServiceException("Error encountered during getting requests by user id", e); + } + } + + + public BigDecimal calculateMonthlyEMI(BigDecimal principal, BigDecimal monthlyInterestRate, BigDecimal timeInMonths) { + + BigDecimal numerator = principal.multiply(BigDecimal.ONE.add(monthlyInterestRate.multiply(timeInMonths))); + BigDecimal monthlyEMI = numerator.divide(timeInMonths, 2, BigDecimal.ROUND_HALF_UP); + + return monthlyEMI; + } + + public boolean isMonthlyEMIAffordable(Integer income, BigDecimal monthlyEMI) { + BigDecimal halfIncome = BigDecimal.valueOf(income / 2); + return halfIncome.compareTo(monthlyEMI) >= 0; + } + + public BigDecimal daysToMonths(Integer days) { + return BigDecimal.valueOf(days).divide(BigDecimal.valueOf(30), 2, RoundingMode.HALF_UP); + } + +} \ No newline at end of file diff --git a/src/main/java/com/educare/unitylend/service/impl/CommunityServiceImpl.java b/src/main/java/com/educare/unitylend/service/impl/CommunityServiceImpl.java index 7822985..7ffba19 100644 --- a/src/main/java/com/educare/unitylend/service/impl/CommunityServiceImpl.java +++ b/src/main/java/com/educare/unitylend/service/impl/CommunityServiceImpl.java @@ -42,9 +42,9 @@ public String getCommunityName(String communityTag) throws ServiceException { public void createCommunity(Community newCommunity) throws ServiceException { try { - if (!communityRepository.existsByCommontag(newCommunity.getCommontag())) { - + if (!communityRepository.existsByCommontag(newCommunity.getCommonTag())) { communityRepository.createCommunity(newCommunity); + newCommunity.setCommunityId(communityRepository.getCommunityIdByName(newCommunity.getCommonTag())); } diff --git a/src/main/java/com/educare/unitylend/service/impl/LendingTransactionServiceImpl.java b/src/main/java/com/educare/unitylend/service/impl/LendingTransactionServiceImpl.java new file mode 100644 index 0000000..45a125a --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/impl/LendingTransactionServiceImpl.java @@ -0,0 +1,87 @@ +package com.educare.unitylend.service.impl; + +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.dao.LendingTransactionRepository; +import com.educare.unitylend.dao.UserRepository; +import com.educare.unitylend.model.BorrowRequest; +import com.educare.unitylend.model.LendingTransaction; +import com.educare.unitylend.model.User; +import com.educare.unitylend.service.LendingTransactionService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Slf4j +@AllArgsConstructor +@Service +public class LendingTransactionServiceImpl implements LendingTransactionService { + + UserRepository userRepository; + LendingTransactionRepository lendingTransactionRepository; + + + @Override + public LendingTransaction getTransactionInfo(String transactionId) throws ServiceException { + try { + LendingTransaction transaction = lendingTransactionRepository.getTransactionById(transactionId); + String lenderId = lendingTransactionRepository.getLenderId(transactionId); + String requestId = lendingTransactionRepository.getRequestId(transactionId); + + User lender = userRepository.getUserForUserId(lenderId); +// BorrowRequest request = borrowRequestRepository.getBorrowRequest(transactionId); + transaction.setLender(lender); +// transaction.setBorrowRequest(request); + log.info("Transaction " + transaction); + return transaction; + } catch (Exception e) { + log.error("Error encountered while fetching transaction with given id"); + throw new ServiceException("Error encountered while fetching transaction with given id", e); + } + } + + @Override + public List getTransactionsByUserId(String userId) throws ServiceException { + try { + List transactions = lendingTransactionRepository.getTransactionByUserId(userId); + log.info("Transaction list " + transactions); + for (LendingTransaction transaction : transactions) { + String transactionId = transaction.getLendTransactionId(); + String lenderId = lendingTransactionRepository.getLenderId(transactionId); + String requestId = lendingTransactionRepository.getRequestId(transactionId); + + User lender = userRepository.getUserForUserId(lenderId); +// BorrowRequest request = borrowRequestRepository.getBorrowRequest(transactionId); + transaction.setLender(lender); +// transaction.setBorrowRequest(request); + } + return transactions; + } catch (Exception e) { + log.error("Error encountered during fetching transactions"); + throw new ServiceException("Error encountered during fetching transactions", e); + } + } + + @Override + public List getTransactionsBetweenPayerAndPayee(String payerId, String payeeId) throws ServiceException { + try { + List transactions = lendingTransactionRepository.getTransactionsBetweenPayerAndPayee(payerId, payeeId); + log.info("Transaction list " + transactions); + for (LendingTransaction transaction : transactions) { + String transactionId = transaction.getLendTransactionId(); + String lenderId = lendingTransactionRepository.getLenderId(transactionId); + String requestId = lendingTransactionRepository.getRequestId(transactionId); + + User lender = userRepository.getUserForUserId(lenderId); +// BorrowRequest request = borrowRequestRepository.getBorrowRequest(transactionId); + transaction.setLender(lender); +// transaction.setBorrowRequest(request); + } + return transactions; + } catch (Exception e) { + log.error("Error encountered during fetching transactions between payer and payee"); + throw new ServiceException("Error encountered during fetching transactions between payer and payee", e); + } + } +} diff --git a/src/main/java/com/educare/unitylend/service/impl/UserCommunityServiceImpl.java b/src/main/java/com/educare/unitylend/service/impl/UserCommunityServiceImpl.java index dce7f45..f209f23 100644 --- a/src/main/java/com/educare/unitylend/service/impl/UserCommunityServiceImpl.java +++ b/src/main/java/com/educare/unitylend/service/impl/UserCommunityServiceImpl.java @@ -2,9 +2,7 @@ import com.educare.unitylend.Exception.ServiceException; import com.educare.unitylend.dao.UserCommunityRepository; -import com.educare.unitylend.model.User; import com.educare.unitylend.service.UserCommunityService; -import com.educare.unitylend.service.UserService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/educare/unitylend/service/impl/UserServiceImpl.java b/src/main/java/com/educare/unitylend/service/impl/UserServiceImpl.java index 50a9383..91e87aa 100644 --- a/src/main/java/com/educare/unitylend/service/impl/UserServiceImpl.java +++ b/src/main/java/com/educare/unitylend/service/impl/UserServiceImpl.java @@ -1,7 +1,6 @@ package com.educare.unitylend.service.impl; import com.educare.unitylend.Exception.ServiceException; -import com.educare.unitylend.controller.UserCommunityController; import com.educare.unitylend.dao.CommunityRepository; import com.educare.unitylend.dao.UserCommunityRepository; import com.educare.unitylend.dao.UserRepository; @@ -21,7 +20,6 @@ public class UserServiceImpl implements UserService { private UserRepository userRepository; private CommunityRepository communityRepository; - private UserCommunityController userCommunityController; private UserCommunityRepository userCommunityRepository; @Override @@ -50,75 +48,65 @@ public User getUserByUserId(String userId) throws ServiceException { public void createUser(User newUser) throws ServiceException { - List matchingCommontags = findMatchingCommontags(newUser); + try { // Add any validation logic if needed before saving to the database - for (String tag : matchingCommontags) { - if (!communityRepository.existsByCommontag(tag)) { - communityRepository.createCommunityUsingStrings(tag, tag); - } + List commonTags = new ArrayList<>(); + if (newUser.getOfficeName() != null) commonTags.add(newUser.getOfficeName()); - } + if (newUser.getCollegeUniversity() != null) commonTags.add(newUser.getCollegeUniversity()); - userRepository.createUser(newUser); - newUser.setUserid(userRepository.settingID(newUser.getEmail())); - // log.info("addeddd!!!!", newUser.getIncome()); - newUser.setBorrowingLimit(newUser.getIncome() / 2); + if (newUser.getLocality() != null) commonTags.add(newUser.getLocality()); - // log.info("addeddd!!!!", newUser.getBorrowingLimit()); + for (String commonTag : commonTags) { + if (!communityRepository.existsByCommontag(commonTag)) { - String collegeUni = newUser.getCollegeuniversity(); - String office = newUser.getOfficename(); - String locality = newUser.getLocality(); - if (collegeUni != null) { - userCommunityRepository.createUserCommunityMapping(newUser.getUserid(), communityRepository.getCommunityIdByName(collegeUni)); - } - if (office != null) { - userCommunityRepository.createUserCommunityMapping(newUser.getUserid(), communityRepository.getCommunityIdByName(office)); - } - if (locality != null) { - userCommunityRepository.createUserCommunityMapping(newUser.getUserid(), communityRepository.getCommunityIdByName(locality)); + log.info("Creating community::", commonTag); + communityRepository.createCommunityUsingStrings(commonTag, commonTag); + } } - + userRepository.createUser(newUser); + newUser.setUserId(userRepository.settingID(newUser.getEmail())); + newUser.setBorrowingLimit(newUser.getIncome() / 2); + mapUserToCommunity(newUser.getUserId(), commonTags); } catch (Exception e) { log.error("Error encountered during user creation operation"); throw new ServiceException("Error encountered during user creation operation", e); } } - private List findMatchingCommontags(User user) { - List matchingCommontags = new ArrayList<>(); - String officenameCommontag=null; - String collegeuniversityCommontag=null; - String localityCommontag=null; - - // Check if officename, collegeuniversity, or locality exists in the Community table as commontag - if(user.getOfficename()!=null) - officenameCommontag = communityRepository.findByCommontag(user.getOfficename()); - if(user.getCollegeuniversity()!=null) - collegeuniversityCommontag = communityRepository.findByCommontag(user.getCollegeuniversity()); - if(user.getLocality()!=null) - localityCommontag = communityRepository.findByCommontag(user.getLocality()); - - // Add non-null commontags to the list - if (officenameCommontag == null && user.getOfficename()!=null ) { - matchingCommontags.add(user.getOfficename()); - } - if (collegeuniversityCommontag == null && user.getCollegeuniversity()!=null) { - matchingCommontags.add(user.getCollegeuniversity()); - } - if (localityCommontag == null && user.getLocality()!=null) { - matchingCommontags.add(user.getLocality()); + + private void mapUserToCommunity(String userId, List commonTags) { + + for (String commonTag : commonTags) { + userCommunityRepository.createUserCommunityMapping(userId, communityRepository.getCommunityIdByName(commonTag)); } + } - return matchingCommontags; + private void mapUserToCommunity(String userId, String commonTag) { + userCommunityRepository.createUserCommunityMapping(userId, communityRepository.getCommunityIdByName(commonTag)); } - public void updateUser(User user) throws ServiceException { + + public void updateUser(User user, String userId) throws ServiceException { + List updatedCommunities; + String[] communityName = new String[3]; try { - System.out.println(user); + userCommunityRepository.deletePrevData(userId); userRepository.updateUser(user); + updatedCommunities = userRepository.findCommunitiesByUserId(userId); + for (String community : updatedCommunities) { + communityName = community.split(", "); + } + for (int i = 0; i < 3; i++) { + if (!communityRepository.existsByCommontag(communityName[i])) { + communityRepository.createCommunityUsingStrings(communityName[i], communityName[i]); + mapUserToCommunity(user.getUserId(), communityName[i]); + } + } + user.setBorrowingLimit(user.getIncome() / 2); + } catch (Exception e) { log.error("Error encountered during user fetching operation"); diff --git a/src/main/java/com/educare/unitylend/service/impl/WalletServiceImpl.java b/src/main/java/com/educare/unitylend/service/impl/WalletServiceImpl.java new file mode 100644 index 0000000..bbe3214 --- /dev/null +++ b/src/main/java/com/educare/unitylend/service/impl/WalletServiceImpl.java @@ -0,0 +1,105 @@ +package com.educare.unitylend.service.impl; + +import com.educare.unitylend.Exception.ServiceException; +import com.educare.unitylend.dao.WalletRepository; +import com.educare.unitylend.model.User; +import com.educare.unitylend.model.Wallet; +import com.educare.unitylend.service.WalletService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; + +@Slf4j +@AllArgsConstructor +@Service +public class WalletServiceImpl implements WalletService{ + WalletRepository walletRepository; + + @Override + public List getWallets() throws ServiceException { + try { + List walletList = walletRepository.getAllWallets(); + log.info("walletList ", walletList); + return walletList; + } catch (Exception e) { + log.error("Error encountered during wallet fetching operation"); + throw new ServiceException("Error encountered during wallet fetch operation", e); + } + } + + + @Override + public Wallet getWalletByUserId(String userId) throws ServiceException { + try { + Wallet wallet = walletRepository.getWalletInfo(userId); + User user = walletRepository.getUserIdWithWallet(wallet); + wallet.setUser(user); + return wallet; + } catch (Exception e) { + log.error("Error encountered during wallet fetching operation"); + throw new ServiceException("Error encountered during wallet fetch operation", e); + } + } + + + @Override + public void generateWallet(String userId) throws ServiceException { + try { + walletRepository.generateWalletInTable(userId); + Wallet wallet = walletRepository.getWalletInfo(userId); + User user = walletRepository.getUserIdWithWallet(wallet); + wallet.setUser(user); + } catch (Exception e) { + log.error("Error encountered during generate wallet operation"); + throw new ServiceException("Error encountered during generation of wallet", e); + } + } + + + @Override + public Wallet getWalletByWalletId(String walletId) throws ServiceException{ + try { + Wallet wallet = walletRepository.getWalletById(walletId); + User user = walletRepository.getUserIdWithWallet(wallet); + wallet.setUser(user); + return wallet; + } catch (Exception e) { + log.error("Error encountered during wallet fetching operation"); + throw new ServiceException("Error encountered during wallet fetch operation", e); + } + } + + + @Override + @Transactional + public void addAmountToWallet(String walletId, Float amount) { + Wallet wallet = walletRepository.getWalletById(walletId); + if (wallet != null) { + Float currentBalance = wallet.getBalance(); + Float newBalance = currentBalance + amount; + wallet.setBalance(newBalance); + walletRepository.updateBalance(walletId, newBalance); + } else { + throw new RuntimeException("Wallet not found with id: " + walletId); + } + } + + + @Override + @Transactional + public void debitFromWallet(String walletId, Float amount) { + Wallet wallet = walletRepository.getWalletById(walletId); + if (wallet != null) { + Float currentBalance = wallet.getBalance(); + Float newBalance = currentBalance - amount; + wallet.setBalance(newBalance); + walletRepository.updateBalance(walletId, newBalance); + } else { + throw new RuntimeException("Wallet not found with id: " + walletId); + } + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 371e31f..d597aca 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,8 +1,8 @@ server.port=8085 -spring.datasource.url=jdbc:postgresql://localhost:5432/unitylend +spring.datasource.url=jdbc:postgresql://localhost:5432/unity-lend spring.datasource.username=postgres -spring.datasource.password=prathyu123 +spring.datasource.password=postgres spring.datasource.driver-class-name=org.postgresql.Driver diff --git a/src/main/resources/scratch.sql b/src/main/resources/scratch.sql index e4ce229..ea5e9f2 100644 --- a/src/main/resources/scratch.sql +++ b/src/main/resources/scratch.sql @@ -1355,4 +1355,11 @@ FROM alter table "TempUser" rename to "tempuser"; +ALTER TABLE tempuser + ADD COLUMN isActive BOOLEAN DEFAULT true; + +ALTER TABLE community + ADD COLUMN communitytype VARCHAR(255); + +