Subversion Repositories SmartDukaan

Rev

Rev 35169 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33507 tejus.loha 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.fasterxml.jackson.databind.ObjectMapper;
35038 aman 4
import com.google.common.hash.Hashing;
33507 tejus.loha 5
import com.spice.profitmandi.common.enumuration.BusinessType;
6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
34107 tejus.loha 7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
35038 aman 8
import com.spice.profitmandi.common.web.util.ResponseSender;
33507 tejus.loha 9
import com.spice.profitmandi.dao.entity.auth.AuthUser;
10
import com.spice.profitmandi.dao.entity.brandFee.BrandFee;
11
import com.spice.profitmandi.dao.entity.brandFee.BrandFeeCollection;
12
import com.spice.profitmandi.dao.entity.dtr.Otp;
13
import com.spice.profitmandi.dao.entity.onBoarding.*;
34107 tejus.loha 14
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
33507 tejus.loha 15
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
16
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.FeePaymentStatus;
17
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.LoiStatus;
18
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.StoreType;
19
import com.spice.profitmandi.dao.model.LoiFormModel;
20
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
21
import com.spice.profitmandi.dao.repository.brandFee.BrandFeeCollectionRepository;
22
import com.spice.profitmandi.dao.repository.brandFee.BrandFeeRepository;
33658 tejus.loha 23
import com.spice.profitmandi.dao.repository.catalog.BrandCategoryRepository;
24
import com.spice.profitmandi.dao.repository.catalog.BrandsRepository;
33507 tejus.loha 25
import com.spice.profitmandi.dao.repository.cs.CsService;
26
import com.spice.profitmandi.dao.repository.dtr.DistrictMasterRepository;
27
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
28
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
33747 tejus.loha 29
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
33507 tejus.loha 30
import com.spice.profitmandi.dao.repository.inventory.PartnerOnboardingService;
31
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
35038 aman 32
import com.spice.profitmandi.dao.repository.onboarding.*;
33507 tejus.loha 33
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33658 tejus.loha 34
import com.spice.profitmandi.dao.repository.user.BillingAddressRepository;
33507 tejus.loha 35
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
36
import com.spice.profitmandi.dao.service.LoiDocModel;
37
import com.spice.profitmandi.dao.service.OTPResponse;
38
import com.spice.profitmandi.dao.service.OtpProcessor;
39
import com.spice.profitmandi.dao.service.loiForm.LoiFormService;
40
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
41
import com.spice.profitmandi.service.integrations.gstpro.entity.GstDetails;
42
import com.spice.profitmandi.service.user.StoreTimelineTatService;
43
import com.spice.profitmandi.web.model.LoginDetails;
44
import com.spice.profitmandi.web.util.CookiesProcessor;
45
import com.spice.profitmandi.web.util.MVCResponseSender;
46
import org.apache.commons.lang3.tuple.Pair;
47
import org.apache.logging.log4j.LogManager;
48
import org.apache.logging.log4j.Logger;
49
import org.springframework.beans.factory.annotation.Autowired;
50
import org.springframework.http.ResponseEntity;
51
import org.springframework.mail.javamail.JavaMailSender;
52
import org.springframework.stereotype.Controller;
53
import org.springframework.transaction.annotation.Transactional;
54
import org.springframework.ui.Model;
55
import org.springframework.web.bind.annotation.RequestBody;
56
import org.springframework.web.bind.annotation.RequestMapping;
57
import org.springframework.web.bind.annotation.RequestMethod;
58
import org.springframework.web.bind.annotation.RequestParam;
59
 
60
import javax.servlet.http.HttpServletRequest;
35038 aman 61
import java.nio.charset.StandardCharsets;
33617 tejus.loha 62
import java.time.LocalDate;
33507 tejus.loha 63
import java.time.LocalDateTime;
64
import java.util.*;
65
import java.util.stream.Collectors;
66
 
67
@Controller
68
@Transactional(rollbackFor = Throwable.class)
69
public class LoiFormController {
34149 tejus.loha 70
    private static final Logger LOGGER = LogManager.getLogger(LoiFormController.class);
33507 tejus.loha 71
    @Autowired
72
    DocumentRepository documentRepository;
73
    @Autowired
74
    AuthRepository authRepository;
75
    @Autowired
76
    StateRepository stateRepository;
77
    @Autowired
78
    DistrictMasterRepository districtMasterRepository;
79
    @Autowired
80
    LoiFormRepository loiFormRepository;
81
    @Autowired
82
    GstProService gstProService;
83
    @Autowired
84
    ObjectMapper objectMapper;
85
    @Autowired
86
    OrderRepository orderRepository;
87
    @Autowired
88
    LoiFormService loiFormService;
89
    @Autowired
90
    BrandFeeCollectionRepository brandFeeCollectionRepository;
91
    @Autowired
92
    BrandFeeRepository brandFeeRepository;
93
    @Autowired
94
    OtpProcessor otpProcessor;
95
    @Autowired
96
    OtpRepository otpRepository;
97
    @Autowired
98
    JavaMailSender mailSender;
99
    @Autowired
100
    LoiDocMasterRepository loiDocMasterList;
101
    @Autowired
102
    CsService csService;
103
    @Autowired
104
    PartnerOnboardingService partnerOnboardingService;
105
    @Autowired
106
    StoreTimelineTatService storeTimelineTatService;
107
    @Autowired
108
    LoiDocRepository loiDocRepository;
109
    @Autowired
110
    MVCResponseSender mvcResponseSender;
111
    @Autowired
112
    private CookiesProcessor cookiesProcessor;
33658 tejus.loha 113
    @Autowired
33879 tejus.loha 114
    BrandCommitRepository brandCommitRepository;
33658 tejus.loha 115
    @Autowired
116
    BrandsRepository brandsRepository;
117
    @Autowired
118
    BrandCategoryRepository brandCategoryRepository;
119
    @Autowired
120
    BillingAddressRepository billingAddressRepository;
121
    @Autowired
122
    LoiBrandCommitmentRepository brandCommitmentRepository;
33747 tejus.loha 123
    @Autowired
124
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
35038 aman 125
    @Autowired
126
    LoiAuditTrailRepository loiAuditTrailRepository;
33747 tejus.loha 127
 
35038 aman 128
    @Autowired
129
    ResponseSender responseSender;
130
 
33710 tejus.loha 131
    List<String> agreedBrandFeeChangerEmail = Arrays.asList("sm@smartdukaan.com");
33507 tejus.loha 132
 
33845 tejus.loha 133
    // Loi Form
134
    @RequestMapping(value = "/loiForm", method = RequestMethod.GET)
33507 tejus.loha 135
    public String loiForm(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
33579 tejus.loha 136
        List<AuthUser> authUsersList = loiFormService.getReferalAuthList();
33507 tejus.loha 137
        List<BrandFee> brandFee = brandFeeRepository.selectFeeOnDate(LocalDateTime.now());
138
        Set<Pair<StoreType, BrandFee>> storeTypeFeePairs = new HashSet<>();
139
        for (BrandFee fee : brandFee) {
140
            for (StoreType storeType : StoreType.values()) {
141
                storeTypeFeePairs.add(Pair.of(storeType, fee));
142
            }
143
        }
34107 tejus.loha 144
        List<AuthUser> stateHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, Arrays.asList(EscalationType.L2, EscalationType.L3));
145
        List<AuthUser> bdmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
35038 aman 146
        List<AuthUser> abmHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_ABM, Arrays.asList(EscalationType.L2, EscalationType.L3));
147
        List<AuthUser> abmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM, EscalationType.L1);
148
        bdmList.addAll(abmList);
149
        stateHeadList.addAll(abmHeadList);
33885 tejus.loha 150
        List<BrandCommit> brandCommits = brandCommitRepository.selectAllActiveBrand();
34195 tejus.loha 151
        model.addAttribute("businessTypes", BusinessType.values());
33658 tejus.loha 152
        model.addAttribute("brandCommits", brandCommits);
33507 tejus.loha 153
        model.addAttribute("storeTypeFeePairs", storeTypeFeePairs);
154
        model.addAttribute("authUsersList", authUsersList);
34107 tejus.loha 155
        model.addAttribute("stateHeadList", stateHeadList);
156
        model.addAttribute("bdmList", bdmList);
33845 tejus.loha 157
        return "loi-form";
33507 tejus.loha 158
    }
159
 
160
    // use to validate GSTIN
161
    @RequestMapping(value = "/gstValidate", method = RequestMethod.GET)
162
    public ResponseEntity<?> gstValidate(HttpServletRequest request, @RequestParam String gstNo) throws Exception {
163
        LOGGER.info("gstNo -" + gstNo);
164
        GstDetails gstDetails = gstProService.getGstDetails(gstNo);
165
        LOGGER.info("gstDetails -" + gstDetails);
35038 aman 166
        if (gstDetails != null) {
34310 tejus.loha 167
            List<GstDetails.Pradr> adadr = gstDetails.getAdadr();
168
            adadr.add(gstDetails.getPradr());
169
            Collections.reverse(adadr);
170
            LOGGER.info("list_of_adadr-" + adadr);
171
        }
34026 tejus.loha 172
        return ResponseEntity.ok(gstDetails);
33507 tejus.loha 173
    }
174
 
34026 tejus.loha 175
    // Save Loi data in fofo.loi_form table
33577 tejus.loha 176
    @RequestMapping(value = "/submitLoiForm", method = RequestMethod.POST)
33568 tejus.loha 177
    public String submitLoiForm(HttpServletRequest request, @RequestBody LoiFormData loiFormData, Model model) throws Exception {
33507 tejus.loha 178
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
33577 tejus.loha 179
        LOGGER.info("filledBy - " + loginDetails.getEmailId());
180
        boolean isDataCreated = loiFormService.createLoiForm(loiFormData, loginDetails.getEmailId());
33507 tejus.loha 181
        if (isDataCreated) {
182
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
183
            return "response";
184
        } else {
185
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
186
            return "response";
187
        }
188
    }
189
 
34026 tejus.loha 190
    // show all pending loi form to specific auth user who have filled the form(type based)
33710 tejus.loha 191
    @RequestMapping(value = "/pendingLoiForm", method = RequestMethod.GET)
33507 tejus.loha 192
    public String pendingLoiForm(HttpServletRequest request, Model model) throws Exception {
193
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
194
        String email = loginDetails.getEmailId();
195
        boolean isDocApprover = false;
196
        String approverEmail = "gaurav.sharma@smartdukaan.com";
197
        if (email.equals(approverEmail)) {
198
            isDocApprover = true;
199
        }
33710 tejus.loha 200
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(email));
35169 aman 201
        List<String> authEmails = Arrays.asList("sm@smartdukaan.com", "tarun.verma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
202
        boolean isAuthUser = authEmails.stream().anyMatch(x -> x.equals(email));
33507 tejus.loha 203
        List<LoiFormModel> pendingFormList = loiFormService.pendingFormList(email);
204
        model.addAttribute("isDocApprover", isDocApprover);
33617 tejus.loha 205
        model.addAttribute("isAuthUser", isAuthUser);
33710 tejus.loha 206
        model.addAttribute("isAgreedBrandFeeChanger", isAgreedBrandFeeChanger);
33507 tejus.loha 207
        model.addAttribute("pendingFormList", pendingFormList);
34085 tejus.loha 208
        model.addAttribute("brandType", StoreType.valueList);
33507 tejus.loha 209
        return "pendingForm";
210
    }
211
 
34085 tejus.loha 212
//    @RequestMapping(value = "/pendingLoiFormList", method = RequestMethod.GET)
213
//    public String pendingLoiForm1(HttpServletRequest request, @RequestParam int pageSize, @RequestParam int pageNumber, Model model) throws Exception {
214
//        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
215
//        String email = loginDetails.getEmailId();
216
//        Map<String, Object> pendingFormMap = loiFormService.pendingFormList(email);
217
//        model.addAttribute("pendingFormList", pendingFormMap.get("pendingFormModelList"));
218
//        model.addAttribute("paginationInfo", this.getPaginationInfo(pageNumber,pageSize,(long)pendingFormMap.get("totalCount")));
219
//        return "loiData";
220
//    }
221
//    public String getPaginationInfo(int currentPage, int pageSize, long totalEntries) {
222
//        // Calculate the starting index
223
//        int start = (currentPage - 1) * pageSize + 1; // Start from 1
224
//        // Calculate the ending index
225
//        int end = Math.min(start + pageSize - 1, (int) totalEntries); // Ensure it doesn't exceed totalEntries
226
//
227
//        return "Showing " + start + " to " + end + " of " + totalEntries + " entries";
228
//    }
229
 
33507 tejus.loha 230
    // generate LOI for specific Form data
231
    @RequestMapping(value = "/generateLoi", method = RequestMethod.GET)
33845 tejus.loha 232
    public String generateLoi(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
33507 tejus.loha 233
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33630 tejus.loha 234
        String filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy()).getFullName();
33507 tejus.loha 235
        loiForm.setLoiGeneratedOn(LocalDateTime.now());
35754 amit 236
        BrandFee brandFee = brandFeeRepository.selectById(1L);
33658 tejus.loha 237
        BillingAddress address = billingAddressRepository.selectByLoiFormId(loiId);
238
        List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
239
        double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
33845 tejus.loha 240
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
241
        double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
33658 tejus.loha 242
        BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
243
        model.addAttribute("totalCommitment", totalCommitment);
244
        model.addAttribute("loiBrandCommitments", loiBrandCommitments);
33507 tejus.loha 245
        model.addAttribute("brandFeeAmount", brandFeeAmount);
246
        model.addAttribute("brandFee", brandFee);
247
        model.addAttribute("brandFeeCollection", brandFeeCollection);
248
        model.addAttribute("address", address);
33658 tejus.loha 249
        model.addAttribute("loiForm", loiForm);
33630 tejus.loha 250
        model.addAttribute("filledBy", filledBy);
33507 tejus.loha 251
        return "auto-Loi";
252
 
253
    }
254
 
35038 aman 255
    private String getHash256(String originalString) {
256
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
257
        LOGGER.info("Hash String {}", hashString);
258
        return hashString;
259
    }
33507 tejus.loha 260
 
261
    // send Filled form for update purpose
33658 tejus.loha 262
    @RequestMapping(value = "/updateLoiForm", method = RequestMethod.GET)
33507 tejus.loha 263
    public String UpdateLoiForm(HttpServletRequest request,
264
                                @RequestParam int loiId,
265
                                Model model) throws ProfitMandiBusinessException {
266
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33658 tejus.loha 267
        model.addAttribute("updateForm", true);
268
        model.addAttribute("loiForm", loiForm);
269
        return "loiForm/update-loiForm";
33507 tejus.loha 270
    }
271
 
33577 tejus.loha 272
    @RequestMapping(value = "/updateLoiFormData", method = RequestMethod.POST)
33507 tejus.loha 273
    public String UpdateLoiFormDetail(HttpServletRequest request,
274
                                      @RequestParam int loiId,
33658 tejus.loha 275
                                      @RequestBody LoiFormData loiFormData,
33507 tejus.loha 276
                                      Model model) throws Exception {
33658 tejus.loha 277
        loiFormService.updateLoiForm(loiFormData, loiId);
33507 tejus.loha 278
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
279
        return "response";
280
    }
281
 
282
    @RequestMapping(value = "/brandfeeCollection", method = RequestMethod.POST)
283
    public String addBrandFee(HttpServletRequest request, @RequestBody BrandFeeCollection brandFeeCollection, @RequestParam int loiId, Model model) throws Exception {
284
        LoiForm loiForm = loiFormRepository.selectById(loiId);
34086 tejus.loha 285
        double totatcollectedfee = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
33507 tejus.loha 286
        double brandFee = loiForm.getAgreedBrandFees();
287
        double differanceAmount = brandFee - totatcollectedfee;
288
        if (totatcollectedfee + brandFeeCollection.getCollectedAmount() <= brandFee) {
289
            brandFeeCollection.setPaymentStatus(FeePaymentStatus.PENDING);
33658 tejus.loha 290
            brandFeeCollection.setLoiFormId(loiId);
291
            brandFeeCollectionRepository.persist(brandFeeCollection);
33885 tejus.loha 292
//            loiFormService.sentMailToPaymentApprover(brandFeeCollection, loiForm);
33507 tejus.loha 293
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
294
            return "response";
295
        } else {
296
            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");
297
        }
298
    }
299
 
300
 
33617 tejus.loha 301
    @RequestMapping(value = "/paymentsDetail", method = RequestMethod.GET)
33507 tejus.loha 302
    public String paymentsDetails(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
303
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
304
        String email = loginDetails.getEmailId();
305
        boolean isNiraj = false;
306
        if (email.equals("neeraj.gupta@smartdukaan.com")) {
307
            isNiraj = true;
308
        }
33658 tejus.loha 309
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllByLoiFormId(loiId);
33507 tejus.loha 310
        model.addAttribute("brandFeeCollections", brandFeeCollections);
311
        model.addAttribute("confirm", FeePaymentStatus.CONFIRM);
312
        model.addAttribute("isNiraj", isNiraj);
313
        return "payment-collection-details";
314
    }
315
 
316
    // bfcId - Brand Fee Collection Id
33617 tejus.loha 317
    @RequestMapping(value = "/feePaymentApproval", method = RequestMethod.PUT)
33525 tejus.loha 318
    public String feePaymentApproval(HttpServletRequest request, @RequestParam int bfcId, @RequestParam FeePaymentStatus feePaymentStatus, @RequestParam String description,
319
                                     Model model) throws Exception {
33507 tejus.loha 320
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
321
        String authEmail = loginDetails.getEmailId();
322
        BrandFeeCollection brandFeeCollection = brandFeeCollectionRepository.selectById(bfcId);
323
        brandFeeCollection.setApproverEmail(authEmail);
324
        brandFeeCollection.setPaymentStatus(feePaymentStatus);
33525 tejus.loha 325
        brandFeeCollection.setDescription(description);
34195 tejus.loha 326
        brandFeeCollection.setApprovalTimeStamp(LocalDateTime.now());
33848 tejus.loha 327
        if (feePaymentStatus.equals(FeePaymentStatus.CONFIRM)) {
328
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(brandFeeCollection.getLoiFormId()));
329
        }
33845 tejus.loha 330
        loiFormService.sendPaymentStatusMailToLoiFormFilledBy(brandFeeCollection);
331
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
33507 tejus.loha 332
        return "response";
333
 
334
    }
335
 
34739 aman.kumar 336
    @RequestMapping(value = "/feePaymentDeletion", method = RequestMethod.PUT)
337
    public String feePaymentDeletion(HttpServletRequest request, @RequestParam int bfcId,
338
                                     Model model) throws Exception {
339
        brandFeeCollectionRepository.deleteById(bfcId);
340
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
341
        return "response";
33658 tejus.loha 342
 
34739 aman.kumar 343
    }
344
 
345
 
33617 tejus.loha 346
    @RequestMapping(value = "/uploadDocumentForm", method = RequestMethod.GET)
33507 tejus.loha 347
    public String uploadDocumentForm(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
348
        List<LoiDocMaster> activeDocMasterList = loiDocMasterList.getAllActiveDoc();
349
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
350
        String authEmail = authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getEmailId();
351
        String approverEmail = "gaurav.sharma@smartdukaan.com";
352
        boolean isApprover = false;
353
        if (authEmail.equals(approverEmail)) {
354
            isApprover = true;
355
        }
33845 tejus.loha 356
        Map<Integer, LoiDoc> masterDocIdLoiDocMap = loiDocRepository.selectByLoiFormId(loiId).stream().collect(Collectors.toMap(x -> x.getMasterDocId(), x -> x));
33507 tejus.loha 357
        model.addAttribute("isApprover", isApprover);
358
        model.addAttribute("loiId", loiId);
359
        model.addAttribute("activeDocMasterList", activeDocMasterList);
360
        model.addAttribute("masterDocIdLoiDocMap", masterDocIdLoiDocMap);
361
        return "loiForm/document-upload";
362
    }
363
 
364
    @RequestMapping(value = "/uploadOnboardingDocument", method = RequestMethod.POST)
365
    public String uploadDocument(HttpServletRequest request, @RequestParam int loiId, @RequestBody List<LoiDocModel> loiDocModels, Model model) throws Exception {
366
        LoiForm loiForm = loiFormRepository.selectById(loiId);
367
        loiFormService.setDocs(loiForm, loiDocModels);
368
        model.addAttribute("response1", mvcResponseSender.createResponseString("Document uploaded successfully"));
369
        return "response";
370
 
371
    }
372
 
373
 
33617 tejus.loha 374
    @RequestMapping(value = "/documentVerify", method = RequestMethod.PUT)
33507 tejus.loha 375
    public String docApproval(HttpServletRequest request, @RequestParam int loiId, @RequestParam int docMasterId, @RequestParam boolean flag, Model model) throws Exception {
376
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
377
        AuthUser auth = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
378
        LoiDoc loiDoc = loiDocRepository.selectByLoiIdAndMasterDocId(loiId, docMasterId);
379
        if (flag) {
380
            loiDoc.setOk(true);
381
            loiDoc.setVerifyBy(auth.getId());
382
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Accepted "));
383
            return "response";
384
        } else {
385
            loiDoc.setOk(false);
386
            loiDoc.setVerifyBy(auth.getId());
33658 tejus.loha 387
            loiFormService.sendDocRejectionMail(loiDoc);
33507 tejus.loha 388
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Rejected"));
389
            return "response";
390
        }
391
    }
392
 
393
    @RequestMapping(value = "/loiAcceptanceOtp", method = RequestMethod.POST)
394
    public String sentLoiAcceptanceOtp(@RequestParam int loiId, Model model) throws Exception {
33658 tejus.loha 395
        LoiForm loiForm = loiFormRepository.selectById(loiId);
396
        String mobile = String.valueOf(loiForm.getMobile());
33525 tejus.loha 397
        OTPResponse otpResponse = otpProcessor.generateOtp(mobile, OtpType.LOI_ACCEPTANCE);
33658 tejus.loha 398
        String message = "OTP send on your register mobile and EmailId - ";
33568 tejus.loha 399
        LOGGER.info("OTPResponse Message - " + otpResponse.getMessage());
400
        if (otpResponse.isResult()) {
33658 tejus.loha 401
            model.addAttribute("response1", mvcResponseSender.createResponseString(message + mobile + " and " + loiForm.getEmail()));
33568 tejus.loha 402
            return "response";
33525 tejus.loha 403
        } else {
404
            model.addAttribute("response1", mvcResponseSender.createResponseString("Something went wrong.."));
33568 tejus.loha 405
            return "response";
33525 tejus.loha 406
        }
33507 tejus.loha 407
    }
408
 
409
    @RequestMapping(value = "/validateLoiOtp", method = RequestMethod.PUT)
35038 aman 410
    public ResponseEntity<?> validateLoiAcceptanceOtp(HttpServletRequest request, @RequestParam int loiId, @RequestParam String provideOtp, Model model) throws Exception {
33658 tejus.loha 411
        LoiForm loiForm = loiFormRepository.selectById(loiId);
412
        String mobile = String.valueOf(loiForm.getMobile());
33507 tejus.loha 413
        Otp otp = otpRepository.selectAllByMobileWithTime(mobile).get(0);
414
        OTPResponse otpResponse = otpProcessor.validateOtp(otp.getId(), mobile, provideOtp);
35038 aman 415
        Map<String, Object> response = new HashMap<>();
33507 tejus.loha 416
        if (otpResponse.isResult()) {
33658 tejus.loha 417
            loiForm.setLoiSignOtp(provideOtp);
418
            loiForm.setLoiSignedOn(LocalDateTime.now());
35038 aman 419
 
420
            List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
421
            double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
422
            List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
423
            double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
424
            BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
425
            String prevHash = loiAuditTrailRepository.findDocumentHashByLoiId(loiId);
426
            String rawData = loiId + "|"
427
                    + loiForm.getCompanyName() + "|"
428
                    + loiForm.getBrandType() + "|"
429
                    + brandFeeAmount + "|"
430
                    + brandFeeCollection.getPaymentMode() + "|"
431
                    + totalCommitment;
432
            String hash = getHash256(rawData);
433
 
434
            LoiAuditTrail audit = new LoiAuditTrail();
435
            audit.setLoiId(loiId);
436
            audit.setCompanyName(loiForm.getCompanyName());
437
            audit.setReferBy(loiForm.getReferBy());
438
            audit.setReferId(loiForm.getReferId());
439
            audit.setFilledBy(loiForm.getFilledBy());
440
            audit.setFranchiseeName(loiForm.getFullName());
441
            audit.setBrandType(loiForm.getBrandType());
442
            audit.setBrandFeeAmount(brandFeeAmount);
443
            audit.setPaymentMode(brandFeeCollection.getPaymentMode());
444
            audit.setTotalCommitment(totalCommitment);
445
            audit.setLoiSignedOn(LocalDateTime.now());
446
            audit.setLoiGeneratedOn(loiForm.getLoiGeneratedOn());
447
            audit.setLoiOtp(provideOtp);
448
            if (prevHash != null) {
449
                audit.setPrevHash(prevHash);
450
            }
451
            audit.setIpAddress(request.getRemoteAddr());
452
            audit.setDocumentHash(hash);
453
 
454
            response.put("success", true);
455
            response.put("documentHash", audit.getDocumentHash());
456
            response.put("ipAddress", audit.getIpAddress());
457
            response.put("generatedAt", audit.getCreatedAt());
458
            response.put("loiId", loiId);
459
            loiAuditTrailRepository.persist(audit);
460
 
33845 tejus.loha 461
        } else {
462
            throw new ProfitMandiBusinessException("Wrong OTP", "", "Your given Otp ->" + provideOtp + " is wrong , please check OTP and try again");
33507 tejus.loha 463
        }
35038 aman 464
        return responseSender.ok(response);
33507 tejus.loha 465
    }
466
 
33845 tejus.loha 467
    @RequestMapping(value = "/saveLoiDoc", method = RequestMethod.POST)
468
    public String saveLoiDoc(@RequestParam int loiId, @RequestParam int loiDocId, Model model) throws Exception {
469
        LOGGER.info("loi_docId-" + loiDocId);
470
        LoiForm loiForm = loiFormRepository.selectById(loiId);
471
        if (loiDocId > 0) {
472
            loiForm.setLoiDoc(loiDocId);
473
            loiFormService.sendSignedLoiPdfToPartner(loiForm);
33848 tejus.loha 474
            loiFormService.checkLoiDetailsCompletion(loiForm);
33845 tejus.loha 475
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
476
        } else {
34947 aman 477
            loiForm.setLoiSignOtp(null);
33845 tejus.loha 478
            loiForm.setLoiGeneratedOn(null);
479
            loiForm.setLoiSignedOn(null);
480
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
481
        }
482
        return "response";
483
 
484
    }
485
 
33617 tejus.loha 486
    @RequestMapping(value = "/downloadLoiFromReport", method = RequestMethod.GET)
487
    public ResponseEntity<?> downloadAllLoiForm(@RequestParam LocalDate from, @RequestParam LocalDate to) throws Exception {
488
        ResponseEntity<?> responseEntity = loiFormService.createLoiFormReport(from, to);
489
        return responseEntity;
490
    }
491
 
33658 tejus.loha 492
    @RequestMapping(value = "/updatePayment", method = RequestMethod.POST)
493
    public String updateForm(@RequestBody BrandFeeCollection brandFeeCollection, Model model) throws Exception {
494
        BrandFeeCollection brandFeeCollection1 = brandFeeCollectionRepository.selectById(brandFeeCollection.getId());
33845 tejus.loha 495
        LoiForm loiForm = loiFormRepository.selectById(brandFeeCollection1.getLoiFormId());
33850 tejus.loha 496
        brandFeeCollection1.setFeeCollectingTimeStamp(brandFeeCollection.getFeeCollectingTimeStamp());
497
        brandFeeCollection1.setCollectedAmount(brandFeeCollection.getCollectedAmount());
33885 tejus.loha 498
        brandFeeCollection1.setPaymentAttachment(brandFeeCollection.getPaymentAttachment());
33850 tejus.loha 499
        brandFeeCollection1.setPaymentReferenceNo(brandFeeCollection.getPaymentReferenceNo());
500
        brandFeeCollection1.setPaymentMode(brandFeeCollection.getPaymentMode());
501
        double totalCollectedFee = brandFeeCollectionRepository.selectAllByLoiFormId(loiForm.getId()).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
502
        if (totalCollectedFee <= loiForm.getAgreedBrandFees()) {
33845 tejus.loha 503
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
504
        } else {
33850 tejus.loha 505
            double differanceAmount = totalCollectedFee - loiForm.getAgreedBrandFees();
33845 tejus.loha 506
            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");
507
        }
33658 tejus.loha 508
        return "response";
509
    }
33617 tejus.loha 510
 
33710 tejus.loha 511
    @RequestMapping(value = "/updateAgreedBrandFee", method = RequestMethod.PUT)
34085 tejus.loha 512
    public String updateAgreedBrandFee(HttpServletRequest request, @RequestParam int loiId, @RequestParam double brandFee, @RequestParam StoreType storeType, Model model) throws Exception {
33710 tejus.loha 513
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
514
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(loginDetails.getEmailId()));
515
        if (isAgreedBrandFeeChanger) {
516
            LoiForm loiForm = loiFormRepository.selectById(loiId);
517
            loiForm.setAgreedBrandFees(brandFee);
34085 tejus.loha 518
            loiForm.setBrandType(storeType);
34086 tejus.loha 519
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(loiId));
33710 tejus.loha 520
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
521
            return "response";
522
        } else {
523
            throw new ProfitMandiBusinessException("failed in Authority check ", null, "Sorry " + authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getName() + " you have no authority to change agreed brand fee");
524
        }
525
    }
526
 
33845 tejus.loha 527
    @RequestMapping(value = "/approve-reject-Loi", method = RequestMethod.PUT)
528
    public String approveDetails(HttpServletRequest request, @RequestParam int loiId, @RequestParam boolean flag, Model model) throws Exception {
529
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
530
        String email = loginDetails.getEmailId();
33711 tejus.loha 531
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33845 tejus.loha 532
        AuthUser filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy());
533
        AuthUser manager = authRepository.selectById(filledBy.getManagerId());
534
        AuthUser upperManager = null;
535
        List<String> approverMail = new ArrayList<>();
536
        approverMail.add(manager.getEmailId());
537
        upperManager = authRepository.selectById(manager.getManagerId());
538
        approverMail.add(upperManager.getEmailId());
539
 
540
        LOGGER.info("approverMail-" + approverMail);
541
        // Approver - Manager or Upper manager of loi filledBy(BM)
542
        boolean isApprover = approverMail.contains(email);
543
        LOGGER.info("isApprover-" + isApprover);
544
        List<String> authEmail = Arrays.asList("sm@smartdukaan.com", "tarun.verma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
545
        boolean isAuthUser = authEmail.stream().anyMatch(x -> x.equals(email));
546
        if (flag) {
547
            if (isApprover || isAuthUser) {
548
                loiForm.setLoiApprover(email);
549
                loiForm.setLoiApproved(flag);
550
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
551
            } else {
552
                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");
553
            }
554
        } else {
555
            if (isApprover || isAuthUser) {
556
                loiForm.setLoiApprover(email);
557
                loiForm.setLoiApproved(flag);
558
                loiForm.setStatus(LoiStatus.LOI_REJECT);
559
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
560
            } else {
561
                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");
562
            }
563
        }
33711 tejus.loha 564
        return "response";
565
    }
566
 
33845 tejus.loha 567
 
33507 tejus.loha 568
}