Subversion Repositories SmartDukaan

Rev

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