Subversion Repositories SmartDukaan

Rev

Rev 34947 | Rev 35169 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.hash.Hashing;
import com.spice.profitmandi.common.enumuration.BusinessType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.brandFee.BrandFee;
import com.spice.profitmandi.dao.entity.brandFee.BrandFeeCollection;
import com.spice.profitmandi.dao.entity.dtr.Otp;
import com.spice.profitmandi.dao.entity.onBoarding.*;
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.FeePaymentStatus;
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.LoiStatus;
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.StoreType;
import com.spice.profitmandi.dao.model.LoiFormModel;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.brandFee.BrandFeeCollectionRepository;
import com.spice.profitmandi.dao.repository.brandFee.BrandFeeRepository;
import com.spice.profitmandi.dao.repository.catalog.BrandCategoryRepository;
import com.spice.profitmandi.dao.repository.catalog.BrandsRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.dtr.DistrictMasterRepository;
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
import com.spice.profitmandi.dao.repository.inventory.PartnerOnboardingService;
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
import com.spice.profitmandi.dao.repository.onboarding.*;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.user.BillingAddressRepository;
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
import com.spice.profitmandi.dao.service.LoiDocModel;
import com.spice.profitmandi.dao.service.OTPResponse;
import com.spice.profitmandi.dao.service.OtpProcessor;
import com.spice.profitmandi.dao.service.loiForm.LoiFormService;
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
import com.spice.profitmandi.service.integrations.gstpro.entity.GstDetails;
import com.spice.profitmandi.service.user.StoreTimelineTatService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class LoiFormController {
    private static final Logger LOGGER = LogManager.getLogger(LoiFormController.class);
    @Autowired
    DocumentRepository documentRepository;
    @Autowired
    AuthRepository authRepository;
    @Autowired
    StateRepository stateRepository;
    @Autowired
    DistrictMasterRepository districtMasterRepository;
    @Autowired
    LoiFormRepository loiFormRepository;
    @Autowired
    GstProService gstProService;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    OrderRepository orderRepository;
    @Autowired
    LoiFormService loiFormService;
    @Autowired
    BrandFeeCollectionRepository brandFeeCollectionRepository;
    @Autowired
    BrandFeeRepository brandFeeRepository;
    @Autowired
    OtpProcessor otpProcessor;
    @Autowired
    OtpRepository otpRepository;
    @Autowired
    JavaMailSender mailSender;
    @Autowired
    LoiDocMasterRepository loiDocMasterList;
    @Autowired
    CsService csService;
    @Autowired
    PartnerOnboardingService partnerOnboardingService;
    @Autowired
    StoreTimelineTatService storeTimelineTatService;
    @Autowired
    LoiDocRepository loiDocRepository;
    @Autowired
    MVCResponseSender mvcResponseSender;
    @Autowired
    private CookiesProcessor cookiesProcessor;
    @Autowired
    BrandCommitRepository brandCommitRepository;
    @Autowired
    BrandsRepository brandsRepository;
    @Autowired
    BrandCategoryRepository brandCategoryRepository;
    @Autowired
    BillingAddressRepository billingAddressRepository;
    @Autowired
    LoiBrandCommitmentRepository brandCommitmentRepository;
    @Autowired
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
    @Autowired
    LoiAuditTrailRepository loiAuditTrailRepository;

    @Autowired
    ResponseSender responseSender;

    List<String> agreedBrandFeeChangerEmail = Arrays.asList("sm@smartdukaan.com");

    // Loi Form
    @RequestMapping(value = "/loiForm", method = RequestMethod.GET)
    public String loiForm(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
        List<AuthUser> authUsersList = loiFormService.getReferalAuthList();
        List<BrandFee> brandFee = brandFeeRepository.selectFeeOnDate(LocalDateTime.now());
        Set<Pair<StoreType, BrandFee>> storeTypeFeePairs = new HashSet<>();
        for (BrandFee fee : brandFee) {
            for (StoreType storeType : StoreType.values()) {
                storeTypeFeePairs.add(Pair.of(storeType, fee));
            }
        }
        List<AuthUser> stateHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, Arrays.asList(EscalationType.L2, EscalationType.L3));
        List<AuthUser> bdmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
        List<AuthUser> abmHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_ABM, Arrays.asList(EscalationType.L2, EscalationType.L3));
        List<AuthUser> abmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM, EscalationType.L1);
        bdmList.addAll(abmList);
        stateHeadList.addAll(abmHeadList);
        List<BrandCommit> brandCommits = brandCommitRepository.selectAllActiveBrand();
        model.addAttribute("businessTypes", BusinessType.values());
        model.addAttribute("brandCommits", brandCommits);
        model.addAttribute("storeTypeFeePairs", storeTypeFeePairs);
        model.addAttribute("authUsersList", authUsersList);
        model.addAttribute("stateHeadList", stateHeadList);
        model.addAttribute("bdmList", bdmList);
        return "loi-form";
    }

    // use to validate GSTIN
    @RequestMapping(value = "/gstValidate", method = RequestMethod.GET)
    public ResponseEntity<?> gstValidate(HttpServletRequest request, @RequestParam String gstNo) throws Exception {
        LOGGER.info("gstNo -" + gstNo);
        GstDetails gstDetails = gstProService.getGstDetails(gstNo);
        LOGGER.info("gstDetails -" + gstDetails);
        if (gstDetails != null) {
            List<GstDetails.Pradr> adadr = gstDetails.getAdadr();
            adadr.add(gstDetails.getPradr());
            Collections.reverse(adadr);
            LOGGER.info("list_of_adadr-" + adadr);
        }
        return ResponseEntity.ok(gstDetails);
    }

    // Save Loi data in fofo.loi_form table
    @RequestMapping(value = "/submitLoiForm", method = RequestMethod.POST)
    public String submitLoiForm(HttpServletRequest request, @RequestBody LoiFormData loiFormData, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        LOGGER.info("filledBy - " + loginDetails.getEmailId());
        boolean isDataCreated = loiFormService.createLoiForm(loiFormData, loginDetails.getEmailId());
        if (isDataCreated) {
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
            return "response";
        } else {
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
            return "response";
        }
    }

    // show all pending loi form to specific auth user who have filled the form(type based)
    @RequestMapping(value = "/pendingLoiForm", method = RequestMethod.GET)
    public String pendingLoiForm(HttpServletRequest request, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String email = loginDetails.getEmailId();
        boolean isDocApprover = false;
        String approverEmail = "gaurav.sharma@smartdukaan.com";
        if (email.equals(approverEmail)) {
            isDocApprover = true;
        }
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(email));
        List<String> authEmail = Arrays.asList("sm@smartdukaan.com", "tarun.verma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
        boolean isAuthUser = authEmail.stream().anyMatch(x -> x.equals(email));
        List<LoiFormModel> pendingFormList = loiFormService.pendingFormList(email);
        model.addAttribute("isDocApprover", isDocApprover);
        model.addAttribute("isAuthUser", isAuthUser);
        model.addAttribute("isAgreedBrandFeeChanger", isAgreedBrandFeeChanger);
        model.addAttribute("pendingFormList", pendingFormList);
        model.addAttribute("brandType", StoreType.valueList);
        return "pendingForm";
    }

//    @RequestMapping(value = "/pendingLoiFormList", method = RequestMethod.GET)
//    public String pendingLoiForm1(HttpServletRequest request, @RequestParam int pageSize, @RequestParam int pageNumber, Model model) throws Exception {
//        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
//        String email = loginDetails.getEmailId();
//        Map<String, Object> pendingFormMap = loiFormService.pendingFormList(email);
//        model.addAttribute("pendingFormList", pendingFormMap.get("pendingFormModelList"));
//        model.addAttribute("paginationInfo", this.getPaginationInfo(pageNumber,pageSize,(long)pendingFormMap.get("totalCount")));
//        return "loiData";
//    }
//    public String getPaginationInfo(int currentPage, int pageSize, long totalEntries) {
//        // Calculate the starting index
//        int start = (currentPage - 1) * pageSize + 1; // Start from 1
//        // Calculate the ending index
//        int end = Math.min(start + pageSize - 1, (int) totalEntries); // Ensure it doesn't exceed totalEntries
//
//        return "Showing " + start + " to " + end + " of " + totalEntries + " entries";
//    }

    // generate LOI for specific Form data
    @RequestMapping(value = "/generateLoi", method = RequestMethod.GET)
    public String generateLoi(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        String filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy()).getFullName();
        loiForm.setLoiGeneratedOn(LocalDateTime.now());
        BrandFee brandFee = brandFeeRepository.selectById(1);
        BillingAddress address = billingAddressRepository.selectByLoiFormId(loiId);
        List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
        double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
        double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
        BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
        model.addAttribute("totalCommitment", totalCommitment);
        model.addAttribute("loiBrandCommitments", loiBrandCommitments);
        model.addAttribute("brandFeeAmount", brandFeeAmount);
        model.addAttribute("brandFee", brandFee);
        model.addAttribute("brandFeeCollection", brandFeeCollection);
        model.addAttribute("address", address);
        model.addAttribute("loiForm", loiForm);
        model.addAttribute("filledBy", filledBy);
        return "auto-Loi";

    }

    private String getHash256(String originalString) {
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
        LOGGER.info("Hash String {}", hashString);
        return hashString;
    }

    // send Filled form for update purpose
    @RequestMapping(value = "/updateLoiForm", method = RequestMethod.GET)
    public String UpdateLoiForm(HttpServletRequest request,
                                @RequestParam int loiId,
                                Model model) throws ProfitMandiBusinessException {
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        model.addAttribute("updateForm", true);
        model.addAttribute("loiForm", loiForm);
        return "loiForm/update-loiForm";
    }

    @RequestMapping(value = "/updateLoiFormData", method = RequestMethod.POST)
    public String UpdateLoiFormDetail(HttpServletRequest request,
                                      @RequestParam int loiId,
                                      @RequestBody LoiFormData loiFormData,
                                      Model model) throws Exception {
        loiFormService.updateLoiForm(loiFormData, loiId);
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        return "response";
    }

    @RequestMapping(value = "/brandfeeCollection", method = RequestMethod.POST)
    public String addBrandFee(HttpServletRequest request, @RequestBody BrandFeeCollection brandFeeCollection, @RequestParam int loiId, Model model) throws Exception {
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        double totatcollectedfee = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
        double brandFee = loiForm.getAgreedBrandFees();
        double differanceAmount = brandFee - totatcollectedfee;
        if (totatcollectedfee + brandFeeCollection.getCollectedAmount() <= brandFee) {
            brandFeeCollection.setPaymentStatus(FeePaymentStatus.PENDING);
            brandFeeCollection.setLoiFormId(loiId);
            brandFeeCollectionRepository.persist(brandFeeCollection);
//            loiFormService.sentMailToPaymentApprover(brandFeeCollection, loiForm);
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
            return "response";
        } else {
            throw new ProfitMandiBusinessException("You need to add only due brand fee that is Only, " + differanceAmount + " INR", null, "Pay differance amount or less then differance amount");
        }
    }


    @RequestMapping(value = "/paymentsDetail", method = RequestMethod.GET)
    public String paymentsDetails(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String email = loginDetails.getEmailId();
        boolean isNiraj = false;
        if (email.equals("neeraj.gupta@smartdukaan.com")) {
            isNiraj = true;
        }
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllByLoiFormId(loiId);
        model.addAttribute("brandFeeCollections", brandFeeCollections);
        model.addAttribute("confirm", FeePaymentStatus.CONFIRM);
        model.addAttribute("isNiraj", isNiraj);
        return "payment-collection-details";
    }

    // bfcId - Brand Fee Collection Id
    @RequestMapping(value = "/feePaymentApproval", method = RequestMethod.PUT)
    public String feePaymentApproval(HttpServletRequest request, @RequestParam int bfcId, @RequestParam FeePaymentStatus feePaymentStatus, @RequestParam String description,
                                     Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String authEmail = loginDetails.getEmailId();
        BrandFeeCollection brandFeeCollection = brandFeeCollectionRepository.selectById(bfcId);
        brandFeeCollection.setApproverEmail(authEmail);
        brandFeeCollection.setPaymentStatus(feePaymentStatus);
        brandFeeCollection.setDescription(description);
        brandFeeCollection.setApprovalTimeStamp(LocalDateTime.now());
        if (feePaymentStatus.equals(FeePaymentStatus.CONFIRM)) {
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(brandFeeCollection.getLoiFormId()));
        }
        loiFormService.sendPaymentStatusMailToLoiFormFilledBy(brandFeeCollection);
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        return "response";

    }

    @RequestMapping(value = "/feePaymentDeletion", method = RequestMethod.PUT)
    public String feePaymentDeletion(HttpServletRequest request, @RequestParam int bfcId,
                                     Model model) throws Exception {
        brandFeeCollectionRepository.deleteById(bfcId);
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        return "response";

    }


    @RequestMapping(value = "/uploadDocumentForm", method = RequestMethod.GET)
    public String uploadDocumentForm(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
        List<LoiDocMaster> activeDocMasterList = loiDocMasterList.getAllActiveDoc();
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String authEmail = authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getEmailId();
        String approverEmail = "gaurav.sharma@smartdukaan.com";
        boolean isApprover = false;
        if (authEmail.equals(approverEmail)) {
            isApprover = true;
        }
        Map<Integer, LoiDoc> masterDocIdLoiDocMap = loiDocRepository.selectByLoiFormId(loiId).stream().collect(Collectors.toMap(x -> x.getMasterDocId(), x -> x));
        model.addAttribute("isApprover", isApprover);
        model.addAttribute("loiId", loiId);
        model.addAttribute("activeDocMasterList", activeDocMasterList);
        model.addAttribute("masterDocIdLoiDocMap", masterDocIdLoiDocMap);
        return "loiForm/document-upload";
    }

    @RequestMapping(value = "/uploadOnboardingDocument", method = RequestMethod.POST)
    public String uploadDocument(HttpServletRequest request, @RequestParam int loiId, @RequestBody List<LoiDocModel> loiDocModels, Model model) throws Exception {
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        loiFormService.setDocs(loiForm, loiDocModels);
        model.addAttribute("response1", mvcResponseSender.createResponseString("Document uploaded successfully"));
        return "response";

    }


    @RequestMapping(value = "/documentVerify", method = RequestMethod.PUT)
    public String docApproval(HttpServletRequest request, @RequestParam int loiId, @RequestParam int docMasterId, @RequestParam boolean flag, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        AuthUser auth = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
        LoiDoc loiDoc = loiDocRepository.selectByLoiIdAndMasterDocId(loiId, docMasterId);
        if (flag) {
            loiDoc.setOk(true);
            loiDoc.setVerifyBy(auth.getId());
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Accepted "));
            return "response";
        } else {
            loiDoc.setOk(false);
            loiDoc.setVerifyBy(auth.getId());
            loiFormService.sendDocRejectionMail(loiDoc);
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Rejected"));
            return "response";
        }
    }

    @RequestMapping(value = "/loiAcceptanceOtp", method = RequestMethod.POST)
    public String sentLoiAcceptanceOtp(@RequestParam int loiId, Model model) throws Exception {
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        String mobile = String.valueOf(loiForm.getMobile());
        OTPResponse otpResponse = otpProcessor.generateOtp(mobile, OtpType.LOI_ACCEPTANCE);
        String message = "OTP send on your register mobile and EmailId - ";
        LOGGER.info("OTPResponse Message - " + otpResponse.getMessage());
        if (otpResponse.isResult()) {
            model.addAttribute("response1", mvcResponseSender.createResponseString(message + mobile + " and " + loiForm.getEmail()));
            return "response";
        } else {
            model.addAttribute("response1", mvcResponseSender.createResponseString("Something went wrong.."));
            return "response";
        }
    }

    @RequestMapping(value = "/validateLoiOtp", method = RequestMethod.PUT)
    public ResponseEntity<?> validateLoiAcceptanceOtp(HttpServletRequest request, @RequestParam int loiId, @RequestParam String provideOtp, Model model) throws Exception {
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        String mobile = String.valueOf(loiForm.getMobile());
        Otp otp = otpRepository.selectAllByMobileWithTime(mobile).get(0);
        OTPResponse otpResponse = otpProcessor.validateOtp(otp.getId(), mobile, provideOtp);
        Map<String, Object> response = new HashMap<>();
        if (otpResponse.isResult()) {
            loiForm.setLoiSignOtp(provideOtp);
            loiForm.setLoiSignedOn(LocalDateTime.now());

            List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
            double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
            List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
            double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
            BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
            String prevHash = loiAuditTrailRepository.findDocumentHashByLoiId(loiId);
            String rawData = loiId + "|"
                    + loiForm.getCompanyName() + "|"
                    + loiForm.getBrandType() + "|"
                    + brandFeeAmount + "|"
                    + brandFeeCollection.getPaymentMode() + "|"
                    + totalCommitment;
            String hash = getHash256(rawData);

            LoiAuditTrail audit = new LoiAuditTrail();
            audit.setLoiId(loiId);
            audit.setCompanyName(loiForm.getCompanyName());
            audit.setReferBy(loiForm.getReferBy());
            audit.setReferId(loiForm.getReferId());
            audit.setFilledBy(loiForm.getFilledBy());
            audit.setFranchiseeName(loiForm.getFullName());
            audit.setBrandType(loiForm.getBrandType());
            audit.setBrandFeeAmount(brandFeeAmount);
            audit.setPaymentMode(brandFeeCollection.getPaymentMode());
            audit.setTotalCommitment(totalCommitment);
            audit.setLoiSignedOn(LocalDateTime.now());
            audit.setLoiGeneratedOn(loiForm.getLoiGeneratedOn());
            audit.setLoiOtp(provideOtp);
            if (prevHash != null) {
                audit.setPrevHash(prevHash);
            }
            audit.setIpAddress(request.getRemoteAddr());
            audit.setDocumentHash(hash);

            response.put("success", true);
            response.put("documentHash", audit.getDocumentHash());
            response.put("ipAddress", audit.getIpAddress());
            response.put("generatedAt", audit.getCreatedAt());
            response.put("loiId", loiId);
            loiAuditTrailRepository.persist(audit);

        } else {
            throw new ProfitMandiBusinessException("Wrong OTP", "", "Your given Otp ->" + provideOtp + " is wrong , please check OTP and try again");
        }
        return responseSender.ok(response);
    }

    @RequestMapping(value = "/saveLoiDoc", method = RequestMethod.POST)
    public String saveLoiDoc(@RequestParam int loiId, @RequestParam int loiDocId, Model model) throws Exception {
        LOGGER.info("loi_docId-" + loiDocId);
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        if (loiDocId > 0) {
            loiForm.setLoiDoc(loiDocId);
            loiFormService.sendSignedLoiPdfToPartner(loiForm);
            loiFormService.checkLoiDetailsCompletion(loiForm);
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } else {
            loiForm.setLoiSignOtp(null);
            loiForm.setLoiGeneratedOn(null);
            loiForm.setLoiSignedOn(null);
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
        }
        return "response";

    }

    @RequestMapping(value = "/downloadLoiFromReport", method = RequestMethod.GET)
    public ResponseEntity<?> downloadAllLoiForm(@RequestParam LocalDate from, @RequestParam LocalDate to) throws Exception {
        ResponseEntity<?> responseEntity = loiFormService.createLoiFormReport(from, to);
        return responseEntity;
    }

    @RequestMapping(value = "/updatePayment", method = RequestMethod.POST)
    public String updateForm(@RequestBody BrandFeeCollection brandFeeCollection, Model model) throws Exception {
        BrandFeeCollection brandFeeCollection1 = brandFeeCollectionRepository.selectById(brandFeeCollection.getId());
        LoiForm loiForm = loiFormRepository.selectById(brandFeeCollection1.getLoiFormId());
        brandFeeCollection1.setFeeCollectingTimeStamp(brandFeeCollection.getFeeCollectingTimeStamp());
        brandFeeCollection1.setCollectedAmount(brandFeeCollection.getCollectedAmount());
        brandFeeCollection1.setPaymentAttachment(brandFeeCollection.getPaymentAttachment());
        brandFeeCollection1.setPaymentReferenceNo(brandFeeCollection.getPaymentReferenceNo());
        brandFeeCollection1.setPaymentMode(brandFeeCollection.getPaymentMode());
        double totalCollectedFee = brandFeeCollectionRepository.selectAllByLoiFormId(loiForm.getId()).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
        if (totalCollectedFee <= loiForm.getAgreedBrandFees()) {
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } else {
            double differanceAmount = totalCollectedFee - loiForm.getAgreedBrandFees();
            throw new ProfitMandiBusinessException("You need to add only due brand fee that is Only, " + differanceAmount + " INR", null, "Pay differance amount or less then differance amount");
        }
        return "response";
    }

    @RequestMapping(value = "/updateAgreedBrandFee", method = RequestMethod.PUT)
    public String updateAgreedBrandFee(HttpServletRequest request, @RequestParam int loiId, @RequestParam double brandFee, @RequestParam StoreType storeType, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(loginDetails.getEmailId()));
        if (isAgreedBrandFeeChanger) {
            LoiForm loiForm = loiFormRepository.selectById(loiId);
            loiForm.setAgreedBrandFees(brandFee);
            loiForm.setBrandType(storeType);
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(loiId));
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
            return "response";
        } else {
            throw new ProfitMandiBusinessException("failed in Authority check ", null, "Sorry " + authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getName() + " you have no authority to change agreed brand fee");
        }
    }

    @RequestMapping(value = "/approve-reject-Loi", method = RequestMethod.PUT)
    public String approveDetails(HttpServletRequest request, @RequestParam int loiId, @RequestParam boolean flag, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String email = loginDetails.getEmailId();
        LoiForm loiForm = loiFormRepository.selectById(loiId);
        AuthUser filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy());
        AuthUser manager = authRepository.selectById(filledBy.getManagerId());
        AuthUser upperManager = null;
        List<String> approverMail = new ArrayList<>();
        approverMail.add(manager.getEmailId());
        upperManager = authRepository.selectById(manager.getManagerId());
        approverMail.add(upperManager.getEmailId());

        LOGGER.info("approverMail-" + approverMail);
        // Approver - Manager or Upper manager of loi filledBy(BM)
        boolean isApprover = approverMail.contains(email);
        LOGGER.info("isApprover-" + isApprover);
        List<String> authEmail = Arrays.asList("sm@smartdukaan.com", "tarun.verma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
        boolean isAuthUser = authEmail.stream().anyMatch(x -> x.equals(email));
        if (flag) {
            if (isApprover || isAuthUser) {
                loiForm.setLoiApprover(email);
                loiForm.setLoiApproved(flag);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
            } else {
                throw new ProfitMandiBusinessException("Failed in Authority check ", "Read", "Sorry " + authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getName() + " you have no authority to Approve this Loi Form ,Only reporting manager and upper can Approve");
            }
        } else {
            if (isApprover || isAuthUser) {
                loiForm.setLoiApprover(email);
                loiForm.setLoiApproved(flag);
                loiForm.setStatus(LoiStatus.LOI_REJECT);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
            } else {
                throw new ProfitMandiBusinessException("Failed in Authority check ", "Read", "Sorry " + authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getName() + " you have no authority to Approve this Loi Form ,Only reporting manager and upper can Approve");
            }
        }
        return "response";
    }


}