Subversion Repositories SmartDukaan

Rev

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