Subversion Repositories SmartDukaan

Rev

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