Subversion Repositories SmartDukaan

Rev

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