Subversion Repositories SmartDukaan

Rev

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