Subversion Repositories SmartDukaan

Rev

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