Subversion Repositories SmartDukaan

Rev

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