×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Added: Sep 11, 2017 11:58 AM
Views: 3
Tags: no tags
make user static to use discount coupon
  1. package com.ichalet.booking.service.impl;
  2.  
  3. import java.security.Principal;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.Calendar;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.Set;
  12.  
  13. import org.joda.time.DateTime;
  14. import org.joda.time.Days;
  15. import org.joda.time.LocalDate;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.context.annotation.PropertySource;
  18. import org.springframework.core.env.Environment;
  19. import org.springframework.http.HttpEntity;
  20. import org.springframework.http.HttpHeaders;
  21. import org.springframework.http.HttpMethod;
  22. import org.springframework.http.MediaType;
  23. import org.springframework.http.ResponseEntity;
  24. import org.springframework.security.oauth2.client.OAuth2RestTemplate;
  25. import org.springframework.stereotype.Service;
  26. import org.springframework.transaction.annotation.Transactional;
  27. import org.springframework.web.client.RestTemplate;
  28.  
  29. import com.ichalet.booking.common.utils.CodeGenerator;
  30. import com.ichalet.booking.common.utils.CodeOperations;
  31. import com.ichalet.booking.common.view.ErrorMessages;
  32. import com.ichalet.booking.common.view.ItemOrderRequestTemplate;
  33. import com.ichalet.booking.common.view.OrderCancellationExecutionResponseTemplate;
  34. import com.ichalet.booking.common.view.StartBookingChaletResponse;
  35. import com.ichalet.booking.domain.entity.Booking;
  36. import com.ichalet.booking.domain.entity.ChaletAvailabilityDates;
  37. import com.ichalet.booking.domain.entity.ChaletAvailabilityDatesPK;
  38. import com.ichalet.booking.domain.entity.ChaletDetails;
  39. import com.ichalet.booking.domain.entity.ChaletRestrictions;
  40. import com.ichalet.booking.domain.entity.DiscountCoupons;
  41. import com.ichalet.booking.domain.entity.IndividualUser;
  42. import com.ichalet.booking.domain.entity.LookupAvailabilityStatus;
  43. import com.ichalet.booking.domain.entity.LookupBookingStatus;
  44. import com.ichalet.booking.domain.entity.OrderCancellationExpirationExecution;
  45. import com.ichalet.booking.domain.entity.PaymentDetails;
  46.  
  47. import com.ichalet.booking.domain.entity.ResortDetails;
  48. import com.ichalet.booking.domain.entity.UserAccount;
  49. import com.ichalet.booking.domain.model.ChaletRestrictionsModel;
  50. import com.ichalet.booking.domain.model.LookupBookingStatusTemplate;
  51. import com.ichalet.booking.domain.model.UserOwnerTemplete;
  52. import com.ichalet.booking.domain.model.bookingDetailsTemplete;
  53. import com.ichalet.booking.domain.model.chaletDetailTemplete;
  54. import com.ichalet.booking.domain.model.discountCouponTemplete;
  55. import com.ichalet.booking.domain.model.paymentDetailTemplete;
  56. import com.ichalet.booking.domain.model.resortDetailTemplete;
  57. import com.ichalet.booking.repository.BookRepository;
  58. import com.ichalet.booking.repository.ChaletAvailabilityDateRepository;
  59. import com.ichalet.booking.repository.ChaletDetailRepositroy;
  60. import com.ichalet.booking.repository.ChaletRestrictionRepository;
  61. import com.ichalet.booking.repository.DiscountCouponsRepository;
  62. import com.ichalet.booking.repository.IndividualUserRepository;
  63. import com.ichalet.booking.repository.LookupAvailabilityStatusRepository;
  64. import com.ichalet.booking.repository.LookupBookingStatusRepository;
  65. import com.ichalet.booking.repository.PaymentNeedsConfirmationRepository;
  66.  
  67. import com.ichalet.booking.repository.ResortRepository;
  68. import com.ichalet.booking.repository.ResortSettingsRepository;
  69. import com.ichalet.booking.repository.UserRepository;
  70. import com.ichalet.booking.view.CustomResponseDataIsList;
  71. import com.ichalet.booking.view.JsonResponseBuilder;
  72. import com.ichalet.booking.view.JsonResponseBuilderGenerics;
  73. import lombok.Getter;
  74.  
  75. @Service
  76. @Transactional
  77. @PropertySource(value = "classpath:RestURL.properties")
  78. public class BookingServiceImpl {
  79.  
  80.     @Autowired
  81.     private UserRepository userRepository;
  82.     @Autowired
  83.     private BookRepository bookRepository;
  84.     @Autowired
  85.     private OAuth2RestTemplate oauthRestTemplate;
  86.     @Autowired
  87.     private ChaletRestrictionRepository restriction;
  88.     @Autowired
  89.     private ResortRepository resortRepository;
  90.     @Autowired
  91.     private ChaletDetailRepositroy chaletDetailRepositroy;
  92.     @Autowired
  93.     private LookupBookingStatusRepository lookupBookingStatusRepository;
  94.     private List<ChaletRestrictions> StartBookingChaletResponse;
  95.     @Autowired
  96.     private ChaletAvailabilityDateRepository chaletAvaliabilityDateRepository;
  97.     @Autowired
  98.     private ResortSettingsRepository resortSettingsRepository;
  99.     @Autowired
  100.     private IndividualUserRepository individualUserRepository;
  101.     @Autowired
  102.     private DiscountCouponsRepository discountCouponsRepository;
  103.     @Autowired
  104.     private PaymentNeedsConfirmationRepository paymentNeedsConfirmationRepository;
  105.     @Autowired
  106.     private LookupAvailabilityStatusRepository lookupAvailabilityStatusRepository;
  107.     @Autowired
  108.     private Environment env;
  109.  
  110.     public JsonResponseBuilder startBookingChalet(long chalet_Id, Date bookingDate, Date bookingStartDate,
  111.             long userId) {
  112.  
  113.         ChaletDetails chaletDetails = chaletDetailRepositroy.findOne(chalet_Id);
  114.         ChaletAvailabilityDatesPK avalibalitiyDate = new ChaletAvailabilityDatesPK(chalet_Id, bookingStartDate);
  115.         ChaletAvailabilityDates chaletAvailabilityDate = chaletAvaliabilityDateRepository
  116.                 .findByChaletAvailabilityDatesPK(avalibalitiyDate);
  117.         HttpHeaders headers = new HttpHeaders();
  118.         headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
  119.         // MultiValueMap<String, String> body = new LinkedMultiValueMap<String,
  120.         // String>();
  121.         ItemOrderRequestTemplate request = new ItemOrderRequestTemplate(1L, (byte) 1, bookingDate.getTime(), bookingStartDate.getTime(),
  122.                 chaletAvailabilityDate.getPrice(), userId);
  123.         HttpEntity<?> httpEntity = new HttpEntity<Object>(request, headers);
  124.         // ResponseEntity<OrderCancellationExecutionResponseTemplate>
  125.         // cancellationDeductions =
  126.         // oauthRestTemplate.exchange("http://192.168.5.65:8086/generateExpirationExecuationTemplate",
  127.         // HttpMethod.POST, httpEntity,
  128.         // OrderCancellationExecutionResponseTemplate.class);
  129.         RestTemplate rest = new RestTemplate();
  130.         ResponseEntity<OrderCancellationExecutionResponseTemplate> cancellationDeductions = rest.exchange(
  131.                 "http://192.168.5.19:8086/generateExpirationExecuationTemplate", HttpMethod.POST, httpEntity,
  132.                 OrderCancellationExecutionResponseTemplate.class);
  133.         List<ChaletRestrictions> restrictions = restriction.findByChaletDetails(chaletDetails);
  134.         StartBookingChaletResponse disclaimerdata = new StartBookingChaletResponse();
  135.  
  136.         disclaimerdata.setCancellationDeduction(cancellationDeductions.getBody());
  137.  
  138.         if (restrictions != null) {
  139.             List<ChaletRestrictionsModel> restrictionList = new ArrayList<>();
  140.             for (ChaletRestrictions restrict : restrictions) {
  141.                 ChaletRestrictionsModel restriction = new ChaletRestrictionsModel(Long.valueOf(restrict.getChaletRestrictionsPK().getChaletRestrictionId() + ""),
  142.                         restrict.getChaletDetails().getChaletId(),
  143.                         restrict.getLookupChaletRestrictions().getChaletRestrictionId(),
  144.                         restrict.getLookupChaletSubrestrictions().getChaletSubrestrictionId(),
  145.                         restrict.getLookupChaletRestrictions().getChaletrestrictionEn(),
  146.                         restrict.getLookupChaletSubrestrictions().getChaletsubrestrictionEn()
  147.                 );
  148.                 restrictionList.add(restriction);
  149.             }
  150.             disclaimerdata.setChaletRestrictions(restrictionList);
  151.         }
  152.  
  153.         disclaimerdata.setResortNeedsApproval(resortSettingsRepository
  154.                 .findOne(chaletDetails.getResortDetails().getResortId()).
  155.                 getIsApprovalRequired());
  156.  
  157.         if (chaletDetails.getCustomRestrictions() != null) {
  158.             disclaimerdata.setRestrictionText(chaletDetails.getCustomRestrictions());
  159.         }
  160.  
  161.         disclaimerdata.setResortRules(resortSettingsRepository
  162.                 .findOne(chaletDetails.getResortDetails().getResortId()).getPolicyUrl());
  163.         JsonResponseBuilder response = new JsonResponseBuilder();
  164.         response.setStatus(ErrorMessages.statusSuccess);
  165.         response.setErrorCode("booking.start-bookikng.success");
  166.         response.setMessage(ErrorMessages.successMessage);
  167.         response.add("disclaimerdata", disclaimerdata);
  168.         return response;
  169.     }
  170.  
  171.     public JsonResponseBuilder bookChalet(int resortId, long chaletId, long userIdTenant,
  172.             Date bookingFromDate, Date bookingToDate, int numberOfNights, double totalPriceBeforeDiscount,
  173.             List<OrderCancellationExpirationExecution> orderCancellationExpirationExecution) {
  174.  
  175.         JsonResponseBuilder response = new JsonResponseBuilder();
  176.  
  177.         int LocalNumberofNights = Days.daysBetween(new LocalDate(bookingFromDate), new LocalDate(bookingToDate))
  178.                 .getDays();
  179.  
  180.         double totalPrice = 0.00;
  181.         for (int i = 0; i < LocalNumberofNights; i++) {
  182.             DateTime dateTime = new DateTime(bookingFromDate);
  183.             dateTime = dateTime.plusDays(i);
  184.             ChaletAvailabilityDatesPK avalibalitiyDate = new ChaletAvailabilityDatesPK(chaletId, dateTime.toDate());
  185.             ChaletAvailabilityDates chaletAvailabilityDate = chaletAvaliabilityDateRepository
  186.                     .findByChaletAvailabilityDatesPK(avalibalitiyDate);
  187.  
  188.             if (chaletAvailabilityDate.getLookupAvailabilityStatus().getAvailabilityStatusId() != 2) {
  189.                 response.setStatus(ErrorMessages.statusErrorMessage);
  190.                 response.setErrorCode("booking.error.not-availabile");
  191.                 response.setMessage(ErrorMessages.chaletAvalilabiltyErrorMessage);
  192.                 return response;
  193.  
  194.             } else {
  195.                 totalPrice = totalPrice + chaletAvailabilityDate.getPrice();
  196.             }
  197.         }
  198.  
  199.         if (totalPrice != totalPriceBeforeDiscount || LocalNumberofNights != numberOfNights) {
  200.  
  201.             response.setStatus(ErrorMessages.statusErrorMessage);
  202.             response.setErrorCode("booking.error.TotalPrice-or-Nights");
  203.             response.setMessage(ErrorMessages.chaletPriceErrorMessage);
  204.             return response;
  205.         }
  206.  
  207.         for (int i = 0; i < LocalNumberofNights; i++) {
  208.             DateTime dateTime = new DateTime(bookingFromDate);
  209.             dateTime = dateTime.plusDays(i);
  210.             ChaletAvailabilityDatesPK avalibalitiyDate = new ChaletAvailabilityDatesPK(chaletId, dateTime.toDate());
  211.  
  212.             ChaletAvailabilityDates chaletAvailabilityDate = chaletAvaliabilityDateRepository
  213.                     .findByChaletAvailabilityDatesPK(avalibalitiyDate);
  214.             LookupAvailabilityStatus stauts = lookupAvailabilityStatusRepository.findOne((short) 4);
  215.             chaletAvailabilityDate.setLookupAvailabilityStatus(stauts);
  216.             chaletAvaliabilityDateRepository.save(chaletAvailabilityDate);
  217.         }
  218.  
  219.         Booking booking = new Booking();
  220.         // ResortDetails resort= resortRepository.findOne(resortId);
  221.         if (resortSettingsRepository.findOne(resortId).getIsApprovalRequired() == true) {
  222.  
  223.             booking.setLookupBookingStatus(lookupBookingStatusRepository.findOne((short) 1));
  224.             Calendar cal = Calendar.getInstance(); // creates calendar
  225.             cal.setTime(new Date()); // sets calendar time/date
  226.             cal.add(Calendar.HOUR_OF_DAY, lookupBookingStatusRepository.findOne((short) 1).getPendingHours());
  227.             booking.setExpiryDateTimeBeforeConfirmation(cal.getTime());
  228.         } else {
  229.             booking.setLookupBookingStatus(lookupBookingStatusRepository.findOne((short) 4));
  230.             Calendar cal = Calendar.getInstance(); // creates calendar
  231.             cal.setTime(new Date()); // sets calendar time/date
  232.             cal.add(Calendar.HOUR_OF_DAY, lookupBookingStatusRepository.findOne((short) 4).getPendingHours()); // adds
  233.             // //
  234.             // hour
  235.  
  236.             booking.setExpiryDateTimeBeforeConfirmation(cal.getTime());
  237.         }
  238.         booking.setStatusDateTime(new Date());
  239.         booking.setResortId(resortId);
  240.         booking.setChaletDetails(chaletDetailRepositroy.findOne(chaletId));
  241.         booking.setBookingDateTime(new Date());
  242.         booking.setBookingCode("waitingid");
  243.         booking.setBookingFromDate(bookingFromDate);
  244.         booking.setBookingToDate(bookingToDate);
  245.         IndividualUser iuser = individualUserRepository.findOne(userIdTenant);
  246.         booking.setIndividualUser(iuser);
  247.  
  248.         bookRepository.save(booking);
  249.         booking.setBookingCode(CodeGenerator.encrypt(booking.getBookingId().toString(), CodeOperations.Booking_Chalet));
  250.         bookRepository.saveAndFlush(booking);
  251.  
  252.         for (OrderCancellationExpirationExecution o : orderCancellationExpirationExecution) {
  253.             o.setBookingId(booking.getBookingId());
  254.         }
  255.  
  256.         HttpHeaders headers = new HttpHeaders();
  257.         headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
  258.         HttpEntity<?> httpEntity = new HttpEntity<Object>(orderCancellationExpirationExecution, headers);
  259.         RestTemplate rest = new RestTemplate();
  260.         ResponseEntity<List> cancellationDeductions = rest.exchange("http://192.168.5.19:8086/saveExpirationExecuation",
  261.                 HttpMethod.POST, httpEntity, List.class);
  262.         response.setErrorCode("success");
  263.         response.setMessage(ErrorMessages.successMessage);
  264.         response.setStatus(ErrorMessages.statusSuccess);
  265.         response.setNotificationsCount(0);
  266.         response.setPointsAmount(0);
  267.         response.setPointsCount(0);
  268.         short statuss = booking.getLookupBookingStatus().getBookingStatusId();
  269.         LookupBookingStatus bookingStatus = lookupBookingStatusRepository.findOne(statuss);
  270.         LookupBookingStatusTemplate statusTemp = new LookupBookingStatusTemplate(bookingStatus);
  271.         long bookingID = booking.getBookingId();
  272.         String bookingCode = booking.getBookingCode();
  273.         response.add("bookingStatus", statusTemp);
  274.         response.add("bookingID", bookingID);
  275.         response.add("bookingCode", bookingCode);
  276.         return response;
  277.  
  278.     }
  279.  
  280.     //2.4
  281.     public JsonResponseBuilder RejectChaletBooking(long bookingID, Principal principal) {
  282.         JsonResponseBuilder responseBuilder = new JsonResponseBuilder();
  283.         UserAccount user = userRepository.findByEmailAddress(principal.getName());
  284.         //3=it mean user is resort only has privilage
  285.         if (user.getLookupUserTypes().getUserTypeId() == 3) {
  286.             Booking booking = bookRepository.findOne(bookingID);
  287.             if (booking == null) {//if booking not found in DB
  288.                 responseBuilder.setStatus(ErrorMessages.statusError + "");
  289.                 responseBuilder.setMessage(ErrorMessages.chaletNotRegisterdMessage);
  290.                 return responseBuilder;
  291.             }
  292.             //3 = mean 'Resort Approval Request Rejectes'
  293.             booking.setLookupBookingStatus(lookupBookingStatusRepository.findOne((short) 3));
  294.             booking.setExpiryDateTimeBeforeConfirmation(null);
  295.             booking.setBookingToDate(null);
  296.             bookRepository.saveAndFlush(booking);
  297.             responseBuilder.setStatus(ErrorMessages.statusSuccess);
  298.         } else {
  299.             responseBuilder.setStatus(ErrorMessages.statusError + "");
  300.             responseBuilder.setMessage("Invalid User Privilage Not Resort Admin");
  301.         }
  302.         return responseBuilder;
  303.     }
  304.  
  305.     //2.5
  306.     public JsonResponseBuilder AssignDiscountCoupon(long bookID, String bookCode, long discountCouponID, String couponCode, Principal principal) {
  307.         Double TotalPriceAfterDiscount = null;
  308.         Booking booking = null;
  309.         DiscountCoupons discountCoupon = null;
  310.  
  311.         if (bookID != -1) {
  312.             booking = bookRepository.findOne(bookID);
  313.         } else {
  314.             booking = bookRepository.findByBookingCode(bookCode);
  315.         }
  316.  
  317.         if (discountCouponID != -1) {
  318.             discountCoupon = discountCouponsRepository.findOne(discountCouponID);
  319.         } else {
  320.             discountCoupon = discountCouponsRepository.findByCouponCode(couponCode);
  321.         }
  322.  
  323.         //validate discount coupon
  324.         HttpHeaders headers = new HttpHeaders();
  325.         headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
  326.  
  327.         Map requestBody = new HashMap();//request Body Data
  328.         requestBody.put("discountCode", discountCoupon.getCouponCode());
  329.         requestBody.put("targetUserID", 1/*discountCoupon.getUser().getUserId()*/);
  330.         requestBody.put("targetEntityID", discountCoupon.getTargetEntityId());
  331.         requestBody.put("bookingId", booking.getBookingId());
  332.  
  333.         HttpEntity<?> httpEntity = new HttpEntity<>(requestBody, headers);
  334.  
  335.         //call Kero to check if this discount coupon is valid or not
  336.         ResponseEntity<?> responseEntity = oauthRestTemplate.exchange(env.getProperty("useDiscountCoupon.url"), HttpMethod.POST, httpEntity, Map.class);
  337.         Map body = (Map) responseEntity.getBody();
  338.         JsonResponseBuilder jrb = new JsonResponseBuilder();//prepare to response
  339.         if (!body.get("status").equals("0")) {// status 0 is this discount coupon INVALID
  340.             if (discountCoupon.getDiscountValue() != null) {
  341.                 if (discountCoupon.getDiscountValue() > 0.0) { //do process
  342.                     TotalPriceAfterDiscount = booking.getTotalPayment() - discountCoupon.getDiscountValue();
  343.                 }
  344.             }
  345.             if (discountCoupon.getDicountPercentage() != null) {
  346.                 if (discountCoupon.getDicountPercentage() > 0.0) { //do process
  347.                     double discountval = (booking.getTotalPayment() * discountCoupon.getDicountPercentage()) / 100;
  348.                     TotalPriceAfterDiscount = booking.getTotalPayment() - discountval;
  349.                 }
  350.             }
  351.             booking.setTotalPriceAfterDiscount(TotalPriceAfterDiscount);
  352.             booking.setDiscountCoupons(discountCoupon);
  353.             discountCoupon.setBooking(booking);
  354.            
  355.             discountCouponsRepository.saveAndFlush(discountCoupon);
  356.             bookRepository.saveAndFlush(booking);
  357.  
  358.             jrb.setStatus(ErrorMessages.statusSuccess);
  359.             jrb.setMessage(ErrorMessages.successMessage);
  360.             jrb.add("totalPriceAfterDiscount", booking.getTotalPriceAfterDiscount());
  361.         }//end if discount Coupon Is Valid or Not
  362.         else {
  363.             jrb.setMessage(body.get("message").toString());
  364.             jrb.setStatus(body.get("status").toString());
  365.         }
  366.         return jrb;
  367.     }
  368.  
  369.     public JsonResponseBuilder UnassignDiscountCoupon(Principal principal, long bookID, String bookCode) {
  370.  
  371.         Double TotalPriceBeforeDiscount = null;
  372.         Booking booking = null;
  373.  
  374.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  375.         UserAccount userLogin = userRepository.findByEmailAddress(principal.getName());
  376.  
  377.         if (bookID != -1) {
  378.             booking = bookRepository.findOne(bookID);
  379.         } else {
  380.             booking = bookRepository.findByBookingCode(bookCode);
  381.         }
  382.         //call Release Discount Coupon First before relase discount from booking vise verse
  383.         //configure header
  384.         HttpHeaders httpHeaders = new HttpHeaders();
  385.         httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
  386.  
  387.         //configure body Request
  388.         Map<String, Object> bodyRequest = new HashMap<>();
  389.         bodyRequest.put("discountId", booking.getDiscountCoupons().getCouponId());
  390.  
  391.         //merger header and body
  392.         HttpEntity<?> httpEntity = new HttpEntity<>(bodyRequest, httpHeaders);
  393.  
  394.         Object STATUS = oauthRestTemplate.exchange(env.getProperty("releaseDiscountCoupon.url"), HttpMethod.POST, httpEntity, Map.class).getBody().get("status");
  395.         if (STATUS.equals("1")) //sucess ONLY //it may confused by calling API from relase first as discount coupon has no booking id value so
  396.         {
  397.             if (userLogin.getUserId() == booking.getIndividualUser().getUserId()) {
  398.                 if (booking.getDiscountCoupons().getDiscountValue() != null) {
  399.                     if (booking.getDiscountCoupons().getDiscountValue() > 0.0) { //do process
  400.                         TotalPriceBeforeDiscount = booking.getTotalPriceAfterDiscount() + booking.getDiscountCoupons().getDiscountValue();
  401.                         jrb.setStatus(ErrorMessages.statusSuccess);
  402.                     }
  403.                 }
  404.                 if (booking.getDiscountCoupons().getDicountPercentage() != null) {
  405.                     if (booking.getDiscountCoupons().getDicountPercentage() > 0.0) {
  406.                         TotalPriceBeforeDiscount = booking.getTotalPriceAfterDiscount() + ((booking.getTotalPriceBeforeDiscount() * booking.getDiscountCoupons().getDicountPercentage()) / 100);
  407.                         jrb.setStatus(ErrorMessages.statusSuccess);
  408.                     }
  409.                 }
  410.                 booking.setTotalPriceBeforeDiscount(TotalPriceBeforeDiscount);
  411.                 booking.setTotalPriceAfterDiscount(null);
  412.                 booking.setDiscountCoupons(null);
  413.                 bookRepository.saveAndFlush(booking);
  414.             }//condition if user has booking
  415.         }
  416.         return jrb;
  417.     }
  418.  
  419.     //2.21
  420.     public JsonResponseBuilderGenerics<?> GetMyChaletBookingDetails(long bookingID, String bookCode, Principal principal) {
  421.         Booking bookingDB = null;
  422.         if (bookingID != -1) {
  423.             bookingDB = bookRepository.findOne(bookingID);
  424.         } else {
  425.             bookingDB = bookRepository.findByBookingCode(bookCode);
  426.         }
  427.         //class generated to merge all templete in one json
  428.         @Getter
  429.         class ListMyChaletBookingWrapper {
  430.  
  431.             bookingDetailsTemplete bookDetailsTemplete;
  432.             chaletDetailTemplete ChaletdetailTemplete;
  433.             discountCouponTemplete couponTemplete;
  434.             List paymentDetailTemplete;
  435.             resortDetailTemplete resortDetailTemplete;
  436.             List userBeneficiaries;
  437.             UserOwnerTemplete UserOwnerTemplete;
  438.             UserOwnerTemplete bookingUser;
  439.  
  440.             private ListMyChaletBookingWrapper(Booking Book, ChaletDetails chaletDetails, DiscountCoupons discountCoupons, ResortDetails resortDetail, List userBeneficiaries, UserAccount chaletOwner, UserAccount bookingUser, Set<PaymentDetails> paymentDetailTempletE) {
  441.                 bookDetailsTemplete = new bookingDetailsTemplete(Book);//booking item info detail
  442.                 ChaletdetailTemplete = new chaletDetailTemplete(chaletDetails);//chalet detail
  443.                 couponTemplete = new discountCouponTemplete(discountCoupons); //discount Coupon Item
  444.                 resortDetailTemplete = new resortDetailTemplete(resortDetail);
  445.                 this.userBeneficiaries = userBeneficiaries;
  446.                 UserOwnerTemplete = new UserOwnerTemplete(chaletOwner);
  447.                 this.bookingUser = new UserOwnerTemplete(bookingUser);
  448.                 paymentDetailTemplete = new ArrayList<>();
  449.                 for (PaymentDetails dt : paymentDetailTempletE) {
  450.                     paymentDetailTemplete dt1 = new paymentDetailTemplete(dt);
  451.                     paymentDetailTemplete.add(dt1);
  452.                 }
  453.             }
  454.         }
  455.  
  456.         ListMyChaletBookingWrapper bookingWrapper = null;
  457.         //list to add benefi users per chalet id
  458.         List benefi = new ArrayList<>();
  459.         bookingDB.getChaletDetails().getIndividualUserSet().forEach((iu) -> {
  460.             UserOwnerTemplete ownerTemplete = new UserOwnerTemplete(userRepository.findOne(iu.getUserId()));
  461.             benefi.add(ownerTemplete);
  462.         });
  463.         //UserAccount userLogin = userRepository.findByEmailAddress(principal.getName());
  464.         // if (userLogin.getUserId() == bookingDB.getIndividualUser().getUserId()) {
  465.         bookingWrapper = new ListMyChaletBookingWrapper(bookingDB, bookingDB.getChaletDetails(), bookingDB.getDiscountCoupons(), bookingDB.getChaletDetails().getResortDetails(), benefi, userRepository.findOne(bookingDB.getChaletDetails().getIndividualUser().getUserId()), userRepository.findOne(bookingDB.getIndividualUser().getUserId()), bookingDB.getLookupPaymentMethods().getPaymentDetailsSet());
  466.         // }//END if for users
  467.         //prepare to response
  468.         JsonResponseBuilderGenerics<ListMyChaletBookingWrapper> builderGenerics = new JsonResponseBuilderGenerics();
  469.         builderGenerics.setData(bookingWrapper);
  470.         builderGenerics.setStatus(ErrorMessages.statusSuccess);
  471.         return builderGenerics;
  472.     }
  473.  
  474.     //2.20
  475.     public JsonResponseBuilderGenerics<?> GetChaletBookingMiniDetails(long bookingID, String bookCode, Principal principal) {
  476.         @Getter
  477.         class ListMyChaletBookingWrapper {
  478.  
  479.             bookingDetailsTemplete bookDetailsTemplete;
  480.             chaletDetailTemplete ChaletdetailTemplete;
  481.  
  482.             private ListMyChaletBookingWrapper(Booking Book, ChaletDetails chaletDetails) {
  483.                 bookDetailsTemplete = new bookingDetailsTemplete(Book);//booking item info detail
  484.                 ChaletdetailTemplete = new chaletDetailTemplete(chaletDetails);//chalet detail
  485.             }
  486.         }
  487.  
  488.         Booking bookingDB = null;
  489.         if (bookingID != -1) {
  490.             bookingDB = bookRepository.findOne(bookingID);
  491.         } else {
  492.             bookingDB = bookRepository.findByBookingCode(bookCode);
  493.         }
  494.         ListMyChaletBookingWrapper detailsTemplete = new ListMyChaletBookingWrapper(bookingDB, bookingDB.getChaletDetails());
  495.         JsonResponseBuilderGenerics<ListMyChaletBookingWrapper> builderGenerics = new JsonResponseBuilderGenerics();
  496.         builderGenerics.setData(detailsTemplete);
  497.         builderGenerics.setStatus(ErrorMessages.statusSuccess);
  498.         return builderGenerics;
  499.     }
  500.  
  501.     //2.19
  502.     public CustomResponseDataIsList ListMyChaletBooking(String emailAddress) {
  503.         @Getter
  504.         class ListMyChaletBookingWrapper {
  505.  
  506.             bookingDetailsTemplete bookDetailsTemplete;
  507.             chaletDetailTemplete ChaletdetailTemplete;
  508.             discountCouponTemplete couponTemplete;
  509.  
  510.             private ListMyChaletBookingWrapper(Booking Book, ChaletDetails chaletDetails, DiscountCoupons discountCoupons) {
  511.                 bookDetailsTemplete = new bookingDetailsTemplete(Book);//booking item info detail
  512.                 ChaletdetailTemplete = new chaletDetailTemplete(chaletDetails);//chalet detail
  513.                 couponTemplete = new discountCouponTemplete(discountCoupons); //discount Coupon Item
  514.             }
  515.  
  516.         }
  517.  
  518.         CustomResponseDataIsList<ListMyChaletBookingWrapper> responseBuilder = new CustomResponseDataIsList();
  519.         IndividualUser iu = new IndividualUser(userRepository.findByEmailAddress(emailAddress).getUserId());
  520.         bookRepository.findByIndividualUserOrderByBookingFromDateAsc(iu).forEach((Book) -> {
  521.             ListMyChaletBookingWrapper listMyChaletBookingClass = new ListMyChaletBookingWrapper(Book, Book.getChaletDetails(), Book.getDiscountCoupons());
  522.             responseBuilder.getData().add(listMyChaletBookingClass);
  523.         });
  524.         responseBuilder.setStatus(ErrorMessages.statusSuccess);
  525.         return responseBuilder;
  526.     }
  527.  
  528.     //2.15      Check-in At Resort Gate
  529.     public JsonResponseBuilder CheckInAtResortGate(Principal principal, long BookingID, String bookCode) {
  530.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  531.  
  532.         Booking bookingDB = null;
  533.  
  534.         if (BookingID != -1) {
  535.             bookingDB = bookRepository.findOne(BookingID);
  536.         } else {
  537.             bookingDB = bookRepository.findByBookingCode(bookCode);
  538.         }
  539.         UserAccount userLogin = userRepository.findByEmailAddress(principal.getName());
  540.         //3=it mean user is resort only has privilage
  541.         if (userLogin.getLookupUserTypes().getUserTypeId() == 3
  542.                 && (bookingDB.getLookupBookingStatus().getBookingStatusId() == 11// Booking Confirmed
  543.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 12//Booking Confirmed & Protected
  544.                 )) {
  545.             //Booking Status should updated to “Checked-in at Gate”
  546.             bookingDB.setLookupBookingStatus(lookupBookingStatusRepository.findOne((short) 15));
  547.             bookingDB.setStatusDateTime(new Date());
  548.             bookingDB.setCheckinDateTime(new Date());
  549.             bookRepository.saveAndFlush(bookingDB);
  550.             jrb.setStatus(ErrorMessages.statusSuccess);
  551.         } else {
  552.             jrb.setStatus(ErrorMessages.statusError + "");
  553.             jrb.setMessage("NO Check-In At Resort Gate");
  554.         }
  555.         return jrb;
  556.     }
  557.  
  558.     //2.13      Delete My Booking
  559.     public JsonResponseBuilder DeleteMyBooking(long bookID, String bookCode, Principal pricipal) {
  560.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  561.  
  562.         Booking bookingDB = null;
  563.         if (bookID != -1) {
  564.             bookingDB = bookRepository.findOne(bookID);
  565.         } else {
  566.             bookingDB = bookRepository.findByBookingCode(bookCode);
  567.         }
  568.  
  569.         UserAccount userLogin = userRepository.findByEmailAddress(pricipal.getName());
  570.         // Users who have Bookings
  571.         if (userLogin.getUserId() == bookingDB.getIndividualUser().getUserId()
  572.                 && (bookingDB.getLookupBookingStatus().getBookingStatusId() == 2//No Approval Response from Resort
  573.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 3//Resort Approval Request Rejected
  574.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 5//Booking Cancelled by Property Owner
  575.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 9//Booking Ignored by Tenant
  576.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 10//Booking Expired
  577.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 14//Booking Cancelled by Tenant
  578.                 )) {
  579.             bookingDB.setIsDeleted(true);
  580.             bookRepository.saveAndFlush(bookingDB);
  581.             jrb.setStatus(ErrorMessages.statusSuccess);
  582.         } else {
  583.             jrb.setStatus(ErrorMessages.statusError + "");
  584.             jrb.setMessage("Chalet Booking Not Deleted");
  585.         }
  586.         return jrb;
  587.     }
  588.  
  589.     // 2.10     Protect Chalet Booking
  590.     public JsonResponseBuilder ProtectChaletBooking(long bookID, String bookCode, Principal pricipal) {
  591.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  592.  
  593.         Booking bookingDB = null;
  594.         if (bookID != -1) {
  595.             bookingDB = bookRepository.findOne(bookID);
  596.         } else {
  597.             bookingDB = bookRepository.findByBookingCode(bookCode);
  598.         }
  599.         if (bookingDB == null) {//if no booking available in DB
  600.             jrb.setStatus(ErrorMessages.statusError + "");
  601.             jrb.setMessage("booking Not Exist");
  602.             return jrb;
  603.         }
  604.  
  605.         UserAccount userLogin = userRepository.findByEmailAddress(pricipal.getName());
  606.         // Users who have Bookings And Payment Statisfied AND IDENTIFIED  
  607.         if (userLogin.getUserId() == bookingDB.getIndividualUser().getUserId() && userLogin.getIndividualUser().getIsIdentified()) {
  608. //            TO proteced it must Total Payment = Total Price After Discount Value if has discount Id OR vise verse
  609.             if ((bookingDB.getDiscountCoupons() != null && bookingDB.getTotalPayment() == bookingDB.getTotalPriceAfterDiscount()) || (bookingDB.getDiscountCoupons() == null && bookingDB.getTotalPayment() == bookingDB.getTotalPriceBeforeDiscount())) {
  610.                 bookingDB.setLookupBookingStatus(lookupBookingStatusRepository.findOne((short) 12));//Booking Confirmed & Protected
  611.                 bookingDB.setStatusDateTime(new Date());
  612.                 bookRepository.saveAndFlush(bookingDB);
  613.                 jrb.setStatus(ErrorMessages.statusSuccess);
  614.             } else {//else for calculation payment error
  615.                 jrb.setStatus(ErrorMessages.statusError + "");
  616.                 jrb.setMessage("Payment Calculation (total != before or after discount price)");
  617.             }
  618.         } else {//else for user not resort or not identified
  619.             jrb.setStatus(ErrorMessages.statusError + "");
  620.             jrb.setMessage("Chalet Booking Not Protected");
  621.         }
  622.         return jrb;
  623.     }
  624.  
  625.     //2.11      Unprotect Chalet Booking
  626.     public JsonResponseBuilder UnProtectChaletBooking(long bookID, String bookCode, Principal pricipal) {
  627.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  628.  
  629.         Booking bookingDB = null;
  630.         if (bookID != -1) {
  631.             bookingDB = bookRepository.findOne(bookID);
  632.         } else {
  633.             bookingDB = bookRepository.findByBookingCode(bookCode);
  634.         }
  635.  
  636.         if (bookingDB == null) {//if no booking available in DB
  637.             jrb.setStatus(ErrorMessages.statusError + "");
  638.             jrb.setMessage("booking Not Exist");
  639.             return jrb;
  640.         }
  641.  
  642.         UserAccount userLogin = userRepository.findByEmailAddress(pricipal.getName());
  643.         // Users who have Bookings And Payment Statisfied
  644.         if (userLogin.getUserId() == bookingDB.getIndividualUser().getUserId()
  645.                 && bookingDB.getLookupBookingStatus().getBookingStatusId() == 12//Booking Confirmed & Protected
  646.                 ) {
  647.             bookingDB.setLookupBookingStatus(lookupBookingStatusRepository.findOne((short) 11));//Booking Confirmed
  648.             bookingDB.setStatusDateTime(new Date());
  649.             bookRepository.saveAndFlush(bookingDB);
  650.             jrb.setStatus(ErrorMessages.statusSuccess);
  651.         } else {
  652.             jrb.setStatus(ErrorMessages.statusError + "");
  653.         }
  654.  
  655.         return jrb;
  656.     }
  657.  
  658.     //2.12      Cancel Chalet Booking
  659.     public void CancelChaletBooking(long BookID) {
  660.  
  661.     }
  662.  
  663.     //2.14      Check Chalet Booking Expiration PAYMENT INTEGRATION
  664.     public void CheckChaletBookingExpiration(Principal principal) {
  665.  
  666.         bookRepository.findAll().forEach((bookRecord) -> {
  667.             //I.Call the Function “Unassign Discount Coupon” if there’s an assigned Discount Coupon
  668.             UnassignDiscountCoupon(principal, bookRecord.getBookingId(), "-1");
  669.  
  670. //            II.       Checking whether if there an “Order ID” for that Booking or not
  671.             if (bookRecord.getOrders() != null) {//has Order ID
  672. //            III.      Calling Function “List Order Payments” if the Booking has an “Order ID
  673.             }
  674. //            calling the Function “Refund Payment” for each Payment
  675.  
  676.             LookupBookingStatus BookStatus = null;
  677.             if (bookRecord.getLookupBookingStatus().getBookingStatusId() == 1) {
  678.                 BookStatus = lookupBookingStatusRepository.findOne((short) 10);//No Approval Response from Resort
  679.             }
  680.             if (bookRecord.getLookupBookingStatus().getBookingStatusId() == 4 || bookRecord.getLookupBookingStatus().getBookingStatusId() == 6 || bookRecord.getLookupBookingStatus().getBookingStatusId() == 7) {
  681.                 BookStatus = lookupBookingStatusRepository.findOne((short) 10);//booking Expired
  682.             }
  683.  
  684.             bookRecord.setLookupBookingStatus(BookStatus);
  685.             bookRecord.setStatusDateTime(new Date());
  686.             bookRecord.setExpiryDateTimeBeforeConfirmation(null);
  687.             bookRecord.setBookingToDate(null);
  688.             bookRecord.setTotalPayment(0);
  689.  
  690.         });
  691.  
  692.     }
  693.  
  694.     //2.16      Request Chalet Check-in
  695.     public JsonResponseBuilder RequestChaletCheckIn(long bookID, String bookCode) {
  696.         Booking bookingDB = null;
  697.         if (bookID != -1) {
  698.             bookingDB = bookRepository.findOne(bookID);
  699.         } else {
  700.             bookingDB = bookRepository.findByBookingCode(bookCode);
  701.         }
  702.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  703.         Calendar checkinTime = Calendar.getInstance();
  704.         checkinTime.setTime(bookingDB.getCheckinDateTime());
  705.  
  706.         Calendar timeNow = Calendar.getInstance();
  707.         timeNow.add(Calendar.HOUR, -1);
  708.         //  check in before 1 houre And Maximum by end of day in the first Booking day
  709.         if (Calendar.getInstance().get(Calendar.HOUR) - checkinTime.get(Calendar.HOUR) <= 1
  710.                 && new Date().before(bookingDB.getBookingFromDate())
  711.                 && (bookingDB.getLookupBookingStatus().getBookingStatusId() == 11 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 12)) {
  712.             bookingDB.setCheckinRequestDateTime(new Date());
  713.             bookRepository.saveAndFlush(bookingDB);
  714.             jrb.setStatus(ErrorMessages.statusSuccess);
  715.         } else {
  716.             jrb.setStatus(ErrorMessages.statusError + "");
  717.         }
  718.         return jrb;
  719.     }
  720.  
  721.     //2.17      Check Initial-No-Show Booking
  722.     public void CheckInitialNoShowBooking(long bookID, Principal principal) {
  723.  
  724.         Booking bookingDB = bookRepository.findOne(bookID);
  725.         UserAccount userLogin = userRepository.findByEmailAddress(principal.getName());
  726.  
  727.         // Users who have Bookings And or User IS RESORT Privilage AND booking Available
  728.         if ((userLogin.getUserId() == bookingDB.getIndividualUser().getUserId()
  729.                 || userLogin.getLookupUserTypes().getUserTypeId() == 5)
  730.                 && bookingDB.getLookupBookingStatus().getBookingStatusId() == 21) { //Initial No Show
  731.             //return last avilable Day in that booking
  732.             ChaletAvailabilityDates lastAvilableDay = chaletAvaliabilityDateRepository.findTopByChaletDetailsAndLookupAvailabilityStatus_availabilityStatusIdOrderByChaletAvailabilityDatesPK_availabilityDateDesc(
  733.                     chaletDetailRepositroy.findOne(bookRepository.findOne(bookID).getChaletDetails().getChaletId()),
  734.                     (short) 2);
  735.  
  736.             if (lastAvilableDay != null) {
  737.                 return;
  738.             } else {
  739.                 return;
  740.             }
  741.  
  742.         }
  743.     }
  744.  
  745.     public JsonResponseBuilder ChangeChaletBookingStatus(long bookId, String bookCode, short statusId) {
  746.  
  747.         Booking bookingDB = null;
  748.         if (bookId != -1) {
  749.             bookingDB = bookRepository.findOne(bookId);
  750.         } else {
  751.             bookingDB = bookRepository.findByBookingCode(bookCode);
  752.         }
  753.  
  754.         bookingDB.setLookupBookingStatus(lookupBookingStatusRepository.findOne(statusId));
  755.         bookRepository.saveAndFlush(bookingDB);
  756.         //prepare to response
  757.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  758.         jrb.setStatus(ErrorMessages.statusSuccess);
  759.         return jrb;
  760.     }
  761.  
  762.     //2.23      Validate Booking Code
  763.     public JsonResponseBuilder ValidateBookingCode(long resortId, String bookingCode) {
  764.  
  765.         Booking bookingDB = null;
  766.         String prefix = bookingCode.substring(0, 2);
  767. //        Chalet Booking
  768.         if (prefix.equals("CB")) {
  769.             bookingDB = bookRepository.findByBookingCode(bookingCode);
  770.         }
  771.         //Direct Booking
  772.         if (prefix.equals("DB")) {
  773.         }
  774.         //Hotel Booking
  775.         if (prefix.equals("HB")) {
  776.         }
  777.         JsonResponseBuilder jrb = new JsonResponseBuilder();
  778.  
  779.         if (bookingDB == null) {
  780.             // Incorrect Booking Code (if Booking Code is not exist)
  781.             jrb.setStatus(ErrorMessages.statusError + "");
  782.             jrb.setMessage("Booking Code doesn't exist");
  783.         } // Irrelevant Booking Code (if Booking Code is not relevant to that Resort)
  784.         else if (bookingDB.getResortId() != resortId) {
  785.             jrb.setStatus(ErrorMessages.statusError + "");
  786.             jrb.setMessage("Booking Code doesn'tS relevant to that Resort");
  787.         }//  Invalid Booking Duration (if Booking Start Date or Finish Date are not in range)
  788.         else if (bookingDB.getBookingFromDate().before(new Date()) && bookingDB.getBookingToDate().before(new Date())) {
  789.             jrb.setStatus(ErrorMessages.statusError + "");
  790.             jrb.setMessage("Invalid Booking Duration");
  791.             //Inactive Booking Code (if Booking Status is not one of the mentioned Status below)
  792.         } else if (bookingDB.getLookupBookingStatus().getBookingStatusId() == 11
  793.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 12
  794.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 13
  795.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 15
  796.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 20
  797.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 21
  798.                 || bookingDB.getLookupBookingStatus().getBookingStatusId() == 24) {
  799.             jrb.setStatus(ErrorMessages.statusError + "");
  800.             jrb.setMessage("Inactive Booking Code");
  801.         } else {
  802.             jrb.setStatus(ErrorMessages.statusSuccess);
  803.             jrb.setMessage(ErrorMessages.successMessage.trim());
  804.         }
  805.         return jrb;
  806.     }
  807.  
  808. }
  809.