Subversion Repositories SmartDukaan

Rev

Rev 37194 | 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
36401 amit 101
    JavaMailSender gmailRelaySender;
33507 tejus.loha 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
 
36872 ranu 137
    List<String> agreedBrandFeeChangerEmail = Arrays.asList("sm@smartdukaan.com", "kamini.sharma@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
        }
37243 ranu 150
        // BM (labelled "State Head" on the LOI form) is now the L4/L5 sales head — was
151
        // L2/L3 previously, which no longer matches the org hierarchy.
152
        List<AuthUser> stateHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, Arrays.asList(EscalationType.L4, EscalationType.L5));
34107 tejus.loha 153
        List<AuthUser> bdmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
37243 ranu 154
        List<AuthUser> abmHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_ABM, Arrays.asList(EscalationType.L4, EscalationType.L5));
35038 aman 155
        List<AuthUser> abmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM, EscalationType.L1);
156
        bdmList.addAll(abmList);
157
        stateHeadList.addAll(abmHeadList);
33885 tejus.loha 158
        List<BrandCommit> brandCommits = brandCommitRepository.selectAllActiveBrand();
35971 aman 159
        List<PaymentOption> paperFinanceOptions = paymentOptionRepository.selectAllPaperFinanceOption();
34195 tejus.loha 160
        model.addAttribute("businessTypes", BusinessType.values());
33658 tejus.loha 161
        model.addAttribute("brandCommits", brandCommits);
33507 tejus.loha 162
        model.addAttribute("storeTypeFeePairs", storeTypeFeePairs);
163
        model.addAttribute("authUsersList", authUsersList);
34107 tejus.loha 164
        model.addAttribute("stateHeadList", stateHeadList);
165
        model.addAttribute("bdmList", bdmList);
35971 aman 166
        model.addAttribute("paperFinanceOptions", paperFinanceOptions);
33845 tejus.loha 167
        return "loi-form";
33507 tejus.loha 168
    }
169
 
170
    // use to validate GSTIN
171
    @RequestMapping(value = "/gstValidate", method = RequestMethod.GET)
172
    public ResponseEntity<?> gstValidate(HttpServletRequest request, @RequestParam String gstNo) throws Exception {
173
        LOGGER.info("gstNo -" + gstNo);
174
        GstDetails gstDetails = gstProService.getGstDetails(gstNo);
175
        LOGGER.info("gstDetails -" + gstDetails);
35038 aman 176
        if (gstDetails != null) {
34310 tejus.loha 177
            List<GstDetails.Pradr> adadr = gstDetails.getAdadr();
178
            adadr.add(gstDetails.getPradr());
179
            Collections.reverse(adadr);
180
            LOGGER.info("list_of_adadr-" + adadr);
181
        }
34026 tejus.loha 182
        return ResponseEntity.ok(gstDetails);
33507 tejus.loha 183
    }
184
 
34026 tejus.loha 185
    // Save Loi data in fofo.loi_form table
33577 tejus.loha 186
    @RequestMapping(value = "/submitLoiForm", method = RequestMethod.POST)
33568 tejus.loha 187
    public String submitLoiForm(HttpServletRequest request, @RequestBody LoiFormData loiFormData, Model model) throws Exception {
33507 tejus.loha 188
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
33577 tejus.loha 189
        LOGGER.info("filledBy - " + loginDetails.getEmailId());
190
        boolean isDataCreated = loiFormService.createLoiForm(loiFormData, loginDetails.getEmailId());
33507 tejus.loha 191
        if (isDataCreated) {
192
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
193
            return "response";
194
        } else {
195
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
196
            return "response";
197
        }
198
    }
199
 
34026 tejus.loha 200
    // show all pending loi form to specific auth user who have filled the form(type based)
33710 tejus.loha 201
    @RequestMapping(value = "/pendingLoiForm", method = RequestMethod.GET)
33507 tejus.loha 202
    public String pendingLoiForm(HttpServletRequest request, Model model) throws Exception {
203
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
204
        String email = loginDetails.getEmailId();
205
        boolean isDocApprover = false;
206
        String approverEmail = "gaurav.sharma@smartdukaan.com";
207
        if (email.equals(approverEmail)) {
208
            isDocApprover = true;
209
        }
33710 tejus.loha 210
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(email));
36873 ranu 211
        List<String> authEmails = Arrays.asList("sm@smartdukaan.com", "kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
35169 aman 212
        boolean isAuthUser = authEmails.stream().anyMatch(x -> x.equals(email));
33507 tejus.loha 213
        List<LoiFormModel> pendingFormList = loiFormService.pendingFormList(email);
214
        model.addAttribute("isDocApprover", isDocApprover);
33617 tejus.loha 215
        model.addAttribute("isAuthUser", isAuthUser);
33710 tejus.loha 216
        model.addAttribute("isAgreedBrandFeeChanger", isAgreedBrandFeeChanger);
33507 tejus.loha 217
        model.addAttribute("pendingFormList", pendingFormList);
34085 tejus.loha 218
        model.addAttribute("brandType", StoreType.valueList);
33507 tejus.loha 219
        return "pendingForm";
220
    }
221
 
34085 tejus.loha 222
//    @RequestMapping(value = "/pendingLoiFormList", method = RequestMethod.GET)
223
//    public String pendingLoiForm1(HttpServletRequest request, @RequestParam int pageSize, @RequestParam int pageNumber, Model model) throws Exception {
224
//        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
225
//        String email = loginDetails.getEmailId();
226
//        Map<String, Object> pendingFormMap = loiFormService.pendingFormList(email);
227
//        model.addAttribute("pendingFormList", pendingFormMap.get("pendingFormModelList"));
228
//        model.addAttribute("paginationInfo", this.getPaginationInfo(pageNumber,pageSize,(long)pendingFormMap.get("totalCount")));
229
//        return "loiData";
230
//    }
231
//    public String getPaginationInfo(int currentPage, int pageSize, long totalEntries) {
232
//        // Calculate the starting index
233
//        int start = (currentPage - 1) * pageSize + 1; // Start from 1
234
//        // Calculate the ending index
235
//        int end = Math.min(start + pageSize - 1, (int) totalEntries); // Ensure it doesn't exceed totalEntries
236
//
237
//        return "Showing " + start + " to " + end + " of " + totalEntries + " entries";
238
//    }
239
 
33507 tejus.loha 240
    // generate LOI for specific Form data
241
    @RequestMapping(value = "/generateLoi", method = RequestMethod.GET)
33845 tejus.loha 242
    public String generateLoi(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
33507 tejus.loha 243
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33630 tejus.loha 244
        String filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy()).getFullName();
33507 tejus.loha 245
        loiForm.setLoiGeneratedOn(LocalDateTime.now());
35754 amit 246
        BrandFee brandFee = brandFeeRepository.selectById(1L);
33658 tejus.loha 247
        BillingAddress address = billingAddressRepository.selectByLoiFormId(loiId);
248
        List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
249
        double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
33845 tejus.loha 250
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
251
        double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
33658 tejus.loha 252
        BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
253
        model.addAttribute("totalCommitment", totalCommitment);
254
        model.addAttribute("loiBrandCommitments", loiBrandCommitments);
33507 tejus.loha 255
        model.addAttribute("brandFeeAmount", brandFeeAmount);
256
        model.addAttribute("brandFee", brandFee);
257
        model.addAttribute("brandFeeCollection", brandFeeCollection);
258
        model.addAttribute("address", address);
33658 tejus.loha 259
        model.addAttribute("loiForm", loiForm);
33630 tejus.loha 260
        model.addAttribute("filledBy", filledBy);
33507 tejus.loha 261
        return "auto-Loi";
262
 
263
    }
264
 
35038 aman 265
    private String getHash256(String originalString) {
266
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
267
        LOGGER.info("Hash String {}", hashString);
268
        return hashString;
269
    }
33507 tejus.loha 270
 
271
    // send Filled form for update purpose
33658 tejus.loha 272
    @RequestMapping(value = "/updateLoiForm", method = RequestMethod.GET)
33507 tejus.loha 273
    public String UpdateLoiForm(HttpServletRequest request,
274
                                @RequestParam int loiId,
275
                                Model model) throws ProfitMandiBusinessException {
276
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33658 tejus.loha 277
        model.addAttribute("updateForm", true);
278
        model.addAttribute("loiForm", loiForm);
279
        return "loiForm/update-loiForm";
33507 tejus.loha 280
    }
281
 
33577 tejus.loha 282
    @RequestMapping(value = "/updateLoiFormData", method = RequestMethod.POST)
33507 tejus.loha 283
    public String UpdateLoiFormDetail(HttpServletRequest request,
284
                                      @RequestParam int loiId,
33658 tejus.loha 285
                                      @RequestBody LoiFormData loiFormData,
33507 tejus.loha 286
                                      Model model) throws Exception {
33658 tejus.loha 287
        loiFormService.updateLoiForm(loiFormData, loiId);
33507 tejus.loha 288
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
289
        return "response";
290
    }
291
 
292
    @RequestMapping(value = "/brandfeeCollection", method = RequestMethod.POST)
293
    public String addBrandFee(HttpServletRequest request, @RequestBody BrandFeeCollection brandFeeCollection, @RequestParam int loiId, Model model) throws Exception {
294
        LoiForm loiForm = loiFormRepository.selectById(loiId);
34086 tejus.loha 295
        double totatcollectedfee = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
33507 tejus.loha 296
        double brandFee = loiForm.getAgreedBrandFees();
297
        double differanceAmount = brandFee - totatcollectedfee;
298
        if (totatcollectedfee + brandFeeCollection.getCollectedAmount() <= brandFee) {
299
            brandFeeCollection.setPaymentStatus(FeePaymentStatus.PENDING);
33658 tejus.loha 300
            brandFeeCollection.setLoiFormId(loiId);
301
            brandFeeCollectionRepository.persist(brandFeeCollection);
35971 aman 302
            loiFormService.sentMailToPaymentApprover(brandFeeCollection, loiForm);
33507 tejus.loha 303
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
304
            return "response";
305
        } else {
306
            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");
307
        }
308
    }
309
 
310
 
33617 tejus.loha 311
    @RequestMapping(value = "/paymentsDetail", method = RequestMethod.GET)
33507 tejus.loha 312
    public String paymentsDetails(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
313
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
314
        String email = loginDetails.getEmailId();
315
        boolean isNiraj = false;
316
        if (email.equals("neeraj.gupta@smartdukaan.com")) {
317
            isNiraj = true;
318
        }
33658 tejus.loha 319
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllByLoiFormId(loiId);
33507 tejus.loha 320
        model.addAttribute("brandFeeCollections", brandFeeCollections);
321
        model.addAttribute("confirm", FeePaymentStatus.CONFIRM);
322
        model.addAttribute("isNiraj", isNiraj);
323
        return "payment-collection-details";
324
    }
325
 
326
    // bfcId - Brand Fee Collection Id
33617 tejus.loha 327
    @RequestMapping(value = "/feePaymentApproval", method = RequestMethod.PUT)
33525 tejus.loha 328
    public String feePaymentApproval(HttpServletRequest request, @RequestParam int bfcId, @RequestParam FeePaymentStatus feePaymentStatus, @RequestParam String description,
329
                                     Model model) throws Exception {
33507 tejus.loha 330
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
331
        String authEmail = loginDetails.getEmailId();
332
        BrandFeeCollection brandFeeCollection = brandFeeCollectionRepository.selectById(bfcId);
333
        brandFeeCollection.setApproverEmail(authEmail);
334
        brandFeeCollection.setPaymentStatus(feePaymentStatus);
33525 tejus.loha 335
        brandFeeCollection.setDescription(description);
34195 tejus.loha 336
        brandFeeCollection.setApprovalTimeStamp(LocalDateTime.now());
33848 tejus.loha 337
        if (feePaymentStatus.equals(FeePaymentStatus.CONFIRM)) {
35971 aman 338
            // Payment Approval timeline entry
339
            storeTimelineTatService.createStoreTimeline(brandFeeCollection.getLoiFormId(), StoreTimeline.PAYMENT_APPROVAL);
33848 tejus.loha 340
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(brandFeeCollection.getLoiFormId()));
341
        }
33845 tejus.loha 342
        loiFormService.sendPaymentStatusMailToLoiFormFilledBy(brandFeeCollection);
343
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
33507 tejus.loha 344
        return "response";
345
 
346
    }
347
 
34739 aman.kumar 348
    @RequestMapping(value = "/feePaymentDeletion", method = RequestMethod.PUT)
349
    public String feePaymentDeletion(HttpServletRequest request, @RequestParam int bfcId,
350
                                     Model model) throws Exception {
351
        brandFeeCollectionRepository.deleteById(bfcId);
352
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
353
        return "response";
33658 tejus.loha 354
 
34739 aman.kumar 355
    }
356
 
357
 
33617 tejus.loha 358
    @RequestMapping(value = "/uploadDocumentForm", method = RequestMethod.GET)
33507 tejus.loha 359
    public String uploadDocumentForm(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
360
        List<LoiDocMaster> activeDocMasterList = loiDocMasterList.getAllActiveDoc();
361
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
362
        String authEmail = authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getEmailId();
363
        String approverEmail = "gaurav.sharma@smartdukaan.com";
364
        boolean isApprover = false;
365
        if (authEmail.equals(approverEmail)) {
366
            isApprover = true;
367
        }
33845 tejus.loha 368
        Map<Integer, LoiDoc> masterDocIdLoiDocMap = loiDocRepository.selectByLoiFormId(loiId).stream().collect(Collectors.toMap(x -> x.getMasterDocId(), x -> x));
33507 tejus.loha 369
        model.addAttribute("isApprover", isApprover);
370
        model.addAttribute("loiId", loiId);
371
        model.addAttribute("activeDocMasterList", activeDocMasterList);
372
        model.addAttribute("masterDocIdLoiDocMap", masterDocIdLoiDocMap);
373
        return "loiForm/document-upload";
374
    }
375
 
376
    @RequestMapping(value = "/uploadOnboardingDocument", method = RequestMethod.POST)
377
    public String uploadDocument(HttpServletRequest request, @RequestParam int loiId, @RequestBody List<LoiDocModel> loiDocModels, Model model) throws Exception {
378
        LoiForm loiForm = loiFormRepository.selectById(loiId);
379
        loiFormService.setDocs(loiForm, loiDocModels);
380
        model.addAttribute("response1", mvcResponseSender.createResponseString("Document uploaded successfully"));
381
        return "response";
382
 
383
    }
384
 
385
 
33617 tejus.loha 386
    @RequestMapping(value = "/documentVerify", method = RequestMethod.PUT)
33507 tejus.loha 387
    public String docApproval(HttpServletRequest request, @RequestParam int loiId, @RequestParam int docMasterId, @RequestParam boolean flag, Model model) throws Exception {
388
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
389
        AuthUser auth = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
390
        LoiDoc loiDoc = loiDocRepository.selectByLoiIdAndMasterDocId(loiId, docMasterId);
391
        if (flag) {
392
            loiDoc.setOk(true);
393
            loiDoc.setVerifyBy(auth.getId());
35971 aman 394
            // Document Approval timeline entry
395
            storeTimelineTatService.createStoreTimeline(loiId, StoreTimeline.LOI_DOCUMENT_APPROVAL);
33507 tejus.loha 396
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Accepted "));
397
            return "response";
398
        } else {
399
            loiDoc.setOk(false);
400
            loiDoc.setVerifyBy(auth.getId());
35971 aman 401
            LoiForm loiForm = loiFormRepository.selectById(loiId);
402
            if (loiForm.isLoiApproved()) {
403
                loiForm.setLoiApproved(false);
404
            }
33658 tejus.loha 405
            loiFormService.sendDocRejectionMail(loiDoc);
33507 tejus.loha 406
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Rejected"));
407
            return "response";
408
        }
409
    }
410
 
411
    @RequestMapping(value = "/loiAcceptanceOtp", method = RequestMethod.POST)
412
    public String sentLoiAcceptanceOtp(@RequestParam int loiId, Model model) throws Exception {
33658 tejus.loha 413
        LoiForm loiForm = loiFormRepository.selectById(loiId);
414
        String mobile = String.valueOf(loiForm.getMobile());
37194 aman 415
        Map<String, Object> response = new HashMap<>();
416
 
417
        OTPResponse otpResponse;
418
        try {
419
            otpResponse = otpProcessor.generateOtp(mobile, OtpType.LOI_ACCEPTANCE);
420
        } catch (Exception e) {
421
            // The dispatch itself blew up (gateway error, duplicate loi_form on this mobile, ...). Never
422
            // report this as a send - the panel used to show "OTP Sent Successfully!" for exactly this case.
423
            LOGGER.error("LOI acceptance OTP dispatch failed for loiId " + loiId + ", mobile " + mobile, e);
424
            response.put("status", false);
425
            response.put("sent", false);
426
            response.put("message", "OTP could not be sent due to a system error. Please report to tech support.");
427
            model.addAttribute("response1", mvcResponseSender.createResponseString(response));
33568 tejus.loha 428
            return "response";
37194 aman 429
        }
430
 
431
        LOGGER.info("OTPResponse for loiId " + loiId + " - result=" + otpResponse.isResult()
432
                + ", sent=" + otpResponse.isSent() + ", message=" + otpResponse.getMessage());
433
 
434
        response.put("status", otpResponse.isResult());
435
        response.put("sent", otpResponse.isSent());
436
        if (otpResponse.isResult() && otpResponse.isSent()) {
437
            response.put("message", "OTP sent on registered mobile and EmailId - " + mobile + " and " + loiForm.getEmail());
33525 tejus.loha 438
        } else {
37194 aman 439
            // Accepted-but-not-dispatched (resend throttle) and outright rejections (daily cap) both land
440
            // here. Pass the processor's own reason through instead of a generic "Something went wrong..".
441
            response.put("message", otpResponse.getMessage());
33525 tejus.loha 442
        }
37194 aman 443
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
444
        return "response";
33507 tejus.loha 445
    }
446
 
447
    @RequestMapping(value = "/validateLoiOtp", method = RequestMethod.PUT)
35038 aman 448
    public ResponseEntity<?> validateLoiAcceptanceOtp(HttpServletRequest request, @RequestParam int loiId, @RequestParam String provideOtp, Model model) throws Exception {
33658 tejus.loha 449
        LoiForm loiForm = loiFormRepository.selectById(loiId);
450
        String mobile = String.valueOf(loiForm.getMobile());
33507 tejus.loha 451
        Otp otp = otpRepository.selectAllByMobileWithTime(mobile).get(0);
452
        OTPResponse otpResponse = otpProcessor.validateOtp(otp.getId(), mobile, provideOtp);
35038 aman 453
        Map<String, Object> response = new HashMap<>();
33507 tejus.loha 454
        if (otpResponse.isResult()) {
33658 tejus.loha 455
            loiForm.setLoiSignOtp(provideOtp);
456
            loiForm.setLoiSignedOn(LocalDateTime.now());
35038 aman 457
 
458
            List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
459
            double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
460
            List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
461
            double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
462
            BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
463
            String prevHash = loiAuditTrailRepository.findDocumentHashByLoiId(loiId);
464
            String rawData = loiId + "|"
465
                    + loiForm.getCompanyName() + "|"
466
                    + loiForm.getBrandType() + "|"
467
                    + brandFeeAmount + "|"
468
                    + brandFeeCollection.getPaymentMode() + "|"
469
                    + totalCommitment;
470
            String hash = getHash256(rawData);
471
 
472
            LoiAuditTrail audit = new LoiAuditTrail();
473
            audit.setLoiId(loiId);
474
            audit.setCompanyName(loiForm.getCompanyName());
475
            audit.setReferBy(loiForm.getReferBy());
476
            audit.setReferId(loiForm.getReferId());
477
            audit.setFilledBy(loiForm.getFilledBy());
478
            audit.setFranchiseeName(loiForm.getFullName());
479
            audit.setBrandType(loiForm.getBrandType());
480
            audit.setBrandFeeAmount(brandFeeAmount);
481
            audit.setPaymentMode(brandFeeCollection.getPaymentMode());
482
            audit.setTotalCommitment(totalCommitment);
483
            audit.setLoiSignedOn(LocalDateTime.now());
484
            audit.setLoiGeneratedOn(loiForm.getLoiGeneratedOn());
485
            audit.setLoiOtp(provideOtp);
486
            if (prevHash != null) {
487
                audit.setPrevHash(prevHash);
488
            }
489
            audit.setIpAddress(request.getRemoteAddr());
490
            audit.setDocumentHash(hash);
491
 
492
            response.put("success", true);
493
            response.put("documentHash", audit.getDocumentHash());
494
            response.put("ipAddress", audit.getIpAddress());
495
            response.put("generatedAt", audit.getCreatedAt());
496
            response.put("loiId", loiId);
497
            loiAuditTrailRepository.persist(audit);
498
 
33845 tejus.loha 499
        } else {
500
            throw new ProfitMandiBusinessException("Wrong OTP", "", "Your given Otp ->" + provideOtp + " is wrong , please check OTP and try again");
33507 tejus.loha 501
        }
35038 aman 502
        return responseSender.ok(response);
33507 tejus.loha 503
    }
504
 
33845 tejus.loha 505
    @RequestMapping(value = "/saveLoiDoc", method = RequestMethod.POST)
506
    public String saveLoiDoc(@RequestParam int loiId, @RequestParam int loiDocId, Model model) throws Exception {
507
        LOGGER.info("loi_docId-" + loiDocId);
508
        LoiForm loiForm = loiFormRepository.selectById(loiId);
509
        if (loiDocId > 0) {
510
            loiForm.setLoiDoc(loiDocId);
511
            loiFormService.sendSignedLoiPdfToPartner(loiForm);
33848 tejus.loha 512
            loiFormService.checkLoiDetailsCompletion(loiForm);
33845 tejus.loha 513
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
514
        } else {
34947 aman 515
            loiForm.setLoiSignOtp(null);
33845 tejus.loha 516
            loiForm.setLoiGeneratedOn(null);
517
            loiForm.setLoiSignedOn(null);
518
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
519
        }
520
        return "response";
521
 
522
    }
523
 
33617 tejus.loha 524
    @RequestMapping(value = "/downloadLoiFromReport", method = RequestMethod.GET)
525
    public ResponseEntity<?> downloadAllLoiForm(@RequestParam LocalDate from, @RequestParam LocalDate to) throws Exception {
526
        ResponseEntity<?> responseEntity = loiFormService.createLoiFormReport(from, to);
527
        return responseEntity;
528
    }
529
 
33658 tejus.loha 530
    @RequestMapping(value = "/updatePayment", method = RequestMethod.POST)
531
    public String updateForm(@RequestBody BrandFeeCollection brandFeeCollection, Model model) throws Exception {
532
        BrandFeeCollection brandFeeCollection1 = brandFeeCollectionRepository.selectById(brandFeeCollection.getId());
33845 tejus.loha 533
        LoiForm loiForm = loiFormRepository.selectById(brandFeeCollection1.getLoiFormId());
33850 tejus.loha 534
        brandFeeCollection1.setFeeCollectingTimeStamp(brandFeeCollection.getFeeCollectingTimeStamp());
535
        brandFeeCollection1.setCollectedAmount(brandFeeCollection.getCollectedAmount());
33885 tejus.loha 536
        brandFeeCollection1.setPaymentAttachment(brandFeeCollection.getPaymentAttachment());
33850 tejus.loha 537
        brandFeeCollection1.setPaymentReferenceNo(brandFeeCollection.getPaymentReferenceNo());
538
        brandFeeCollection1.setPaymentMode(brandFeeCollection.getPaymentMode());
539
        double totalCollectedFee = brandFeeCollectionRepository.selectAllByLoiFormId(loiForm.getId()).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
540
        if (totalCollectedFee <= loiForm.getAgreedBrandFees()) {
33845 tejus.loha 541
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
542
        } else {
33850 tejus.loha 543
            double differanceAmount = totalCollectedFee - loiForm.getAgreedBrandFees();
33845 tejus.loha 544
            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");
545
        }
33658 tejus.loha 546
        return "response";
547
    }
33617 tejus.loha 548
 
33710 tejus.loha 549
    @RequestMapping(value = "/updateAgreedBrandFee", method = RequestMethod.PUT)
34085 tejus.loha 550
    public String updateAgreedBrandFee(HttpServletRequest request, @RequestParam int loiId, @RequestParam double brandFee, @RequestParam StoreType storeType, Model model) throws Exception {
33710 tejus.loha 551
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
552
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(loginDetails.getEmailId()));
553
        if (isAgreedBrandFeeChanger) {
554
            LoiForm loiForm = loiFormRepository.selectById(loiId);
555
            loiForm.setAgreedBrandFees(brandFee);
34085 tejus.loha 556
            loiForm.setBrandType(storeType);
34086 tejus.loha 557
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(loiId));
33710 tejus.loha 558
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
559
            return "response";
560
        } else {
561
            throw new ProfitMandiBusinessException("failed in Authority check ", null, "Sorry " + authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getName() + " you have no authority to change agreed brand fee");
562
        }
563
    }
564
 
33845 tejus.loha 565
    @RequestMapping(value = "/approve-reject-Loi", method = RequestMethod.PUT)
566
    public String approveDetails(HttpServletRequest request, @RequestParam int loiId, @RequestParam boolean flag, Model model) throws Exception {
567
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
568
        String email = loginDetails.getEmailId();
33711 tejus.loha 569
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33845 tejus.loha 570
        AuthUser filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy());
571
        AuthUser manager = authRepository.selectById(filledBy.getManagerId());
572
        AuthUser upperManager = null;
573
        List<String> approverMail = new ArrayList<>();
574
        approverMail.add(manager.getEmailId());
575
        upperManager = authRepository.selectById(manager.getManagerId());
576
        approverMail.add(upperManager.getEmailId());
577
 
578
        LOGGER.info("approverMail-" + approverMail);
579
        // Approver - Manager or Upper manager of loi filledBy(BM)
580
        boolean isApprover = approverMail.contains(email);
581
        LOGGER.info("isApprover-" + isApprover);
36872 ranu 582
        List<String> authEmail = Arrays.asList("sm@smartdukaan.com", "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
33845 tejus.loha 583
        boolean isAuthUser = authEmail.stream().anyMatch(x -> x.equals(email));
584
        if (flag) {
585
            if (isApprover || isAuthUser) {
586
                loiForm.setLoiApprover(email);
587
                loiForm.setLoiApproved(flag);
35971 aman 588
                if (loiForm.getStatus() == LoiStatus.LOI_REJECT) {
589
                    loiForm.setStatus(LoiStatus.PENDING);
590
                }
591
                // BM Approval timeline entry
592
                storeTimelineTatService.createStoreTimeline(loiId, StoreTimeline.BM_APPROVAL);
593
                // Check if all LOI conditions are now met (BM approval could be the last step)
594
                loiFormService.checkLoiDetailsCompletion(loiForm);
33845 tejus.loha 595
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
596
            } else {
597
                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");
598
            }
599
        } else {
600
            if (isApprover || isAuthUser) {
601
                loiForm.setLoiApprover(email);
602
                loiForm.setLoiApproved(flag);
603
                loiForm.setStatus(LoiStatus.LOI_REJECT);
604
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
605
            } else {
606
                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");
607
            }
608
        }
33711 tejus.loha 609
        return "response";
610
    }
611
 
33845 tejus.loha 612
 
33507 tejus.loha 613
}