Subversion Repositories SmartDukaan

Rev

Rev 36873 | 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;
35971 aman 13
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
33507 tejus.loha 14
import com.spice.profitmandi.dao.entity.onBoarding.*;
34107 tejus.loha 15
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
33507 tejus.loha 16
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
35971 aman 17
import com.spice.profitmandi.dao.enumuration.dtr.StoreTimeline;
33507 tejus.loha 18
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.FeePaymentStatus;
19
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.LoiStatus;
20
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.StoreType;
21
import com.spice.profitmandi.dao.model.LoiFormModel;
22
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
23
import com.spice.profitmandi.dao.repository.brandFee.BrandFeeCollectionRepository;
24
import com.spice.profitmandi.dao.repository.brandFee.BrandFeeRepository;
33658 tejus.loha 25
import com.spice.profitmandi.dao.repository.catalog.BrandCategoryRepository;
26
import com.spice.profitmandi.dao.repository.catalog.BrandsRepository;
33507 tejus.loha 27
import com.spice.profitmandi.dao.repository.cs.CsService;
28
import com.spice.profitmandi.dao.repository.dtr.DistrictMasterRepository;
29
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
30
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
33747 tejus.loha 31
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
35971 aman 32
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
33507 tejus.loha 33
import com.spice.profitmandi.dao.repository.inventory.PartnerOnboardingService;
34
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
35038 aman 35
import com.spice.profitmandi.dao.repository.onboarding.*;
33507 tejus.loha 36
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33658 tejus.loha 37
import com.spice.profitmandi.dao.repository.user.BillingAddressRepository;
33507 tejus.loha 38
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
39
import com.spice.profitmandi.dao.service.LoiDocModel;
40
import com.spice.profitmandi.dao.service.OTPResponse;
41
import com.spice.profitmandi.dao.service.OtpProcessor;
42
import com.spice.profitmandi.dao.service.loiForm.LoiFormService;
43
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
44
import com.spice.profitmandi.service.integrations.gstpro.entity.GstDetails;
45
import com.spice.profitmandi.service.user.StoreTimelineTatService;
46
import com.spice.profitmandi.web.model.LoginDetails;
47
import com.spice.profitmandi.web.util.CookiesProcessor;
48
import com.spice.profitmandi.web.util.MVCResponseSender;
49
import org.apache.commons.lang3.tuple.Pair;
50
import org.apache.logging.log4j.LogManager;
51
import org.apache.logging.log4j.Logger;
52
import org.springframework.beans.factory.annotation.Autowired;
53
import org.springframework.http.ResponseEntity;
54
import org.springframework.mail.javamail.JavaMailSender;
55
import org.springframework.stereotype.Controller;
56
import org.springframework.transaction.annotation.Transactional;
57
import org.springframework.ui.Model;
58
import org.springframework.web.bind.annotation.RequestBody;
59
import org.springframework.web.bind.annotation.RequestMapping;
60
import org.springframework.web.bind.annotation.RequestMethod;
61
import org.springframework.web.bind.annotation.RequestParam;
62
 
63
import javax.servlet.http.HttpServletRequest;
35038 aman 64
import java.nio.charset.StandardCharsets;
33617 tejus.loha 65
import java.time.LocalDate;
33507 tejus.loha 66
import java.time.LocalDateTime;
67
import java.util.*;
68
import java.util.stream.Collectors;
69
 
70
@Controller
71
@Transactional(rollbackFor = Throwable.class)
72
public class LoiFormController {
34149 tejus.loha 73
    private static final Logger LOGGER = LogManager.getLogger(LoiFormController.class);
33507 tejus.loha 74
    @Autowired
75
    DocumentRepository documentRepository;
76
    @Autowired
77
    AuthRepository authRepository;
78
    @Autowired
79
    StateRepository stateRepository;
80
    @Autowired
81
    DistrictMasterRepository districtMasterRepository;
82
    @Autowired
83
    LoiFormRepository loiFormRepository;
84
    @Autowired
85
    GstProService gstProService;
86
    @Autowired
87
    ObjectMapper objectMapper;
88
    @Autowired
89
    OrderRepository orderRepository;
90
    @Autowired
91
    LoiFormService loiFormService;
92
    @Autowired
93
    BrandFeeCollectionRepository brandFeeCollectionRepository;
94
    @Autowired
95
    BrandFeeRepository brandFeeRepository;
96
    @Autowired
97
    OtpProcessor otpProcessor;
98
    @Autowired
99
    OtpRepository otpRepository;
100
    @Autowired
36401 amit 101
    JavaMailSender gmailRelaySender;
33507 tejus.loha 102
    @Autowired
103
    LoiDocMasterRepository loiDocMasterList;
104
    @Autowired
105
    CsService csService;
106
    @Autowired
107
    PartnerOnboardingService partnerOnboardingService;
108
    @Autowired
109
    StoreTimelineTatService storeTimelineTatService;
110
    @Autowired
111
    LoiDocRepository loiDocRepository;
112
    @Autowired
113
    MVCResponseSender mvcResponseSender;
114
    @Autowired
115
    private CookiesProcessor cookiesProcessor;
33658 tejus.loha 116
    @Autowired
33879 tejus.loha 117
    BrandCommitRepository brandCommitRepository;
33658 tejus.loha 118
    @Autowired
119
    BrandsRepository brandsRepository;
120
    @Autowired
121
    BrandCategoryRepository brandCategoryRepository;
122
    @Autowired
123
    BillingAddressRepository billingAddressRepository;
124
    @Autowired
125
    LoiBrandCommitmentRepository brandCommitmentRepository;
33747 tejus.loha 126
    @Autowired
127
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
35038 aman 128
    @Autowired
129
    LoiAuditTrailRepository loiAuditTrailRepository;
33747 tejus.loha 130
 
35038 aman 131
    @Autowired
35971 aman 132
    PaymentOptionRepository paymentOptionRepository;
133
 
134
    @Autowired
35038 aman 135
    ResponseSender responseSender;
136
 
36872 ranu 137
    List<String> agreedBrandFeeChangerEmail = Arrays.asList("sm@smartdukaan.com", "kamini.sharma@smartdukaan.com");
33507 tejus.loha 138
 
33845 tejus.loha 139
    // Loi Form
140
    @RequestMapping(value = "/loiForm", method = RequestMethod.GET)
33507 tejus.loha 141
    public String loiForm(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
33579 tejus.loha 142
        List<AuthUser> authUsersList = loiFormService.getReferalAuthList();
33507 tejus.loha 143
        List<BrandFee> brandFee = brandFeeRepository.selectFeeOnDate(LocalDateTime.now());
144
        Set<Pair<StoreType, BrandFee>> storeTypeFeePairs = new HashSet<>();
145
        for (BrandFee fee : brandFee) {
146
            for (StoreType storeType : StoreType.values()) {
147
                storeTypeFeePairs.add(Pair.of(storeType, fee));
148
            }
149
        }
34107 tejus.loha 150
        List<AuthUser> stateHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, Arrays.asList(EscalationType.L2, EscalationType.L3));
151
        List<AuthUser> bdmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
35038 aman 152
        List<AuthUser> abmHeadList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_ABM, Arrays.asList(EscalationType.L2, EscalationType.L3));
153
        List<AuthUser> abmList = csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM, EscalationType.L1);
154
        bdmList.addAll(abmList);
155
        stateHeadList.addAll(abmHeadList);
33885 tejus.loha 156
        List<BrandCommit> brandCommits = brandCommitRepository.selectAllActiveBrand();
35971 aman 157
        List<PaymentOption> paperFinanceOptions = paymentOptionRepository.selectAllPaperFinanceOption();
34195 tejus.loha 158
        model.addAttribute("businessTypes", BusinessType.values());
33658 tejus.loha 159
        model.addAttribute("brandCommits", brandCommits);
33507 tejus.loha 160
        model.addAttribute("storeTypeFeePairs", storeTypeFeePairs);
161
        model.addAttribute("authUsersList", authUsersList);
34107 tejus.loha 162
        model.addAttribute("stateHeadList", stateHeadList);
163
        model.addAttribute("bdmList", bdmList);
35971 aman 164
        model.addAttribute("paperFinanceOptions", paperFinanceOptions);
33845 tejus.loha 165
        return "loi-form";
33507 tejus.loha 166
    }
167
 
168
    // use to validate GSTIN
169
    @RequestMapping(value = "/gstValidate", method = RequestMethod.GET)
170
    public ResponseEntity<?> gstValidate(HttpServletRequest request, @RequestParam String gstNo) throws Exception {
171
        LOGGER.info("gstNo -" + gstNo);
172
        GstDetails gstDetails = gstProService.getGstDetails(gstNo);
173
        LOGGER.info("gstDetails -" + gstDetails);
35038 aman 174
        if (gstDetails != null) {
34310 tejus.loha 175
            List<GstDetails.Pradr> adadr = gstDetails.getAdadr();
176
            adadr.add(gstDetails.getPradr());
177
            Collections.reverse(adadr);
178
            LOGGER.info("list_of_adadr-" + adadr);
179
        }
34026 tejus.loha 180
        return ResponseEntity.ok(gstDetails);
33507 tejus.loha 181
    }
182
 
34026 tejus.loha 183
    // Save Loi data in fofo.loi_form table
33577 tejus.loha 184
    @RequestMapping(value = "/submitLoiForm", method = RequestMethod.POST)
33568 tejus.loha 185
    public String submitLoiForm(HttpServletRequest request, @RequestBody LoiFormData loiFormData, Model model) throws Exception {
33507 tejus.loha 186
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
33577 tejus.loha 187
        LOGGER.info("filledBy - " + loginDetails.getEmailId());
188
        boolean isDataCreated = loiFormService.createLoiForm(loiFormData, loginDetails.getEmailId());
33507 tejus.loha 189
        if (isDataCreated) {
190
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
191
            return "response";
192
        } else {
193
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
194
            return "response";
195
        }
196
    }
197
 
34026 tejus.loha 198
    // show all pending loi form to specific auth user who have filled the form(type based)
33710 tejus.loha 199
    @RequestMapping(value = "/pendingLoiForm", method = RequestMethod.GET)
33507 tejus.loha 200
    public String pendingLoiForm(HttpServletRequest request, Model model) throws Exception {
201
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
202
        String email = loginDetails.getEmailId();
203
        boolean isDocApprover = false;
204
        String approverEmail = "gaurav.sharma@smartdukaan.com";
205
        if (email.equals(approverEmail)) {
206
            isDocApprover = true;
207
        }
33710 tejus.loha 208
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(email));
36873 ranu 209
        List<String> authEmails = Arrays.asList("sm@smartdukaan.com", "kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
35169 aman 210
        boolean isAuthUser = authEmails.stream().anyMatch(x -> x.equals(email));
33507 tejus.loha 211
        List<LoiFormModel> pendingFormList = loiFormService.pendingFormList(email);
212
        model.addAttribute("isDocApprover", isDocApprover);
33617 tejus.loha 213
        model.addAttribute("isAuthUser", isAuthUser);
33710 tejus.loha 214
        model.addAttribute("isAgreedBrandFeeChanger", isAgreedBrandFeeChanger);
33507 tejus.loha 215
        model.addAttribute("pendingFormList", pendingFormList);
34085 tejus.loha 216
        model.addAttribute("brandType", StoreType.valueList);
33507 tejus.loha 217
        return "pendingForm";
218
    }
219
 
34085 tejus.loha 220
//    @RequestMapping(value = "/pendingLoiFormList", method = RequestMethod.GET)
221
//    public String pendingLoiForm1(HttpServletRequest request, @RequestParam int pageSize, @RequestParam int pageNumber, Model model) throws Exception {
222
//        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
223
//        String email = loginDetails.getEmailId();
224
//        Map<String, Object> pendingFormMap = loiFormService.pendingFormList(email);
225
//        model.addAttribute("pendingFormList", pendingFormMap.get("pendingFormModelList"));
226
//        model.addAttribute("paginationInfo", this.getPaginationInfo(pageNumber,pageSize,(long)pendingFormMap.get("totalCount")));
227
//        return "loiData";
228
//    }
229
//    public String getPaginationInfo(int currentPage, int pageSize, long totalEntries) {
230
//        // Calculate the starting index
231
//        int start = (currentPage - 1) * pageSize + 1; // Start from 1
232
//        // Calculate the ending index
233
//        int end = Math.min(start + pageSize - 1, (int) totalEntries); // Ensure it doesn't exceed totalEntries
234
//
235
//        return "Showing " + start + " to " + end + " of " + totalEntries + " entries";
236
//    }
237
 
33507 tejus.loha 238
    // generate LOI for specific Form data
239
    @RequestMapping(value = "/generateLoi", method = RequestMethod.GET)
33845 tejus.loha 240
    public String generateLoi(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
33507 tejus.loha 241
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33630 tejus.loha 242
        String filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy()).getFullName();
33507 tejus.loha 243
        loiForm.setLoiGeneratedOn(LocalDateTime.now());
35754 amit 244
        BrandFee brandFee = brandFeeRepository.selectById(1L);
33658 tejus.loha 245
        BillingAddress address = billingAddressRepository.selectByLoiFormId(loiId);
246
        List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
247
        double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
33845 tejus.loha 248
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
249
        double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
33658 tejus.loha 250
        BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
251
        model.addAttribute("totalCommitment", totalCommitment);
252
        model.addAttribute("loiBrandCommitments", loiBrandCommitments);
33507 tejus.loha 253
        model.addAttribute("brandFeeAmount", brandFeeAmount);
254
        model.addAttribute("brandFee", brandFee);
255
        model.addAttribute("brandFeeCollection", brandFeeCollection);
256
        model.addAttribute("address", address);
33658 tejus.loha 257
        model.addAttribute("loiForm", loiForm);
33630 tejus.loha 258
        model.addAttribute("filledBy", filledBy);
33507 tejus.loha 259
        return "auto-Loi";
260
 
261
    }
262
 
35038 aman 263
    private String getHash256(String originalString) {
264
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
265
        LOGGER.info("Hash String {}", hashString);
266
        return hashString;
267
    }
33507 tejus.loha 268
 
269
    // send Filled form for update purpose
33658 tejus.loha 270
    @RequestMapping(value = "/updateLoiForm", method = RequestMethod.GET)
33507 tejus.loha 271
    public String UpdateLoiForm(HttpServletRequest request,
272
                                @RequestParam int loiId,
273
                                Model model) throws ProfitMandiBusinessException {
274
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33658 tejus.loha 275
        model.addAttribute("updateForm", true);
276
        model.addAttribute("loiForm", loiForm);
277
        return "loiForm/update-loiForm";
33507 tejus.loha 278
    }
279
 
33577 tejus.loha 280
    @RequestMapping(value = "/updateLoiFormData", method = RequestMethod.POST)
33507 tejus.loha 281
    public String UpdateLoiFormDetail(HttpServletRequest request,
282
                                      @RequestParam int loiId,
33658 tejus.loha 283
                                      @RequestBody LoiFormData loiFormData,
33507 tejus.loha 284
                                      Model model) throws Exception {
33658 tejus.loha 285
        loiFormService.updateLoiForm(loiFormData, loiId);
33507 tejus.loha 286
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
287
        return "response";
288
    }
289
 
290
    @RequestMapping(value = "/brandfeeCollection", method = RequestMethod.POST)
291
    public String addBrandFee(HttpServletRequest request, @RequestBody BrandFeeCollection brandFeeCollection, @RequestParam int loiId, Model model) throws Exception {
292
        LoiForm loiForm = loiFormRepository.selectById(loiId);
34086 tejus.loha 293
        double totatcollectedfee = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
33507 tejus.loha 294
        double brandFee = loiForm.getAgreedBrandFees();
295
        double differanceAmount = brandFee - totatcollectedfee;
296
        if (totatcollectedfee + brandFeeCollection.getCollectedAmount() <= brandFee) {
297
            brandFeeCollection.setPaymentStatus(FeePaymentStatus.PENDING);
33658 tejus.loha 298
            brandFeeCollection.setLoiFormId(loiId);
299
            brandFeeCollectionRepository.persist(brandFeeCollection);
35971 aman 300
            loiFormService.sentMailToPaymentApprover(brandFeeCollection, loiForm);
33507 tejus.loha 301
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
302
            return "response";
303
        } else {
304
            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");
305
        }
306
    }
307
 
308
 
33617 tejus.loha 309
    @RequestMapping(value = "/paymentsDetail", method = RequestMethod.GET)
33507 tejus.loha 310
    public String paymentsDetails(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
311
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
312
        String email = loginDetails.getEmailId();
313
        boolean isNiraj = false;
314
        if (email.equals("neeraj.gupta@smartdukaan.com")) {
315
            isNiraj = true;
316
        }
33658 tejus.loha 317
        List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllByLoiFormId(loiId);
33507 tejus.loha 318
        model.addAttribute("brandFeeCollections", brandFeeCollections);
319
        model.addAttribute("confirm", FeePaymentStatus.CONFIRM);
320
        model.addAttribute("isNiraj", isNiraj);
321
        return "payment-collection-details";
322
    }
323
 
324
    // bfcId - Brand Fee Collection Id
33617 tejus.loha 325
    @RequestMapping(value = "/feePaymentApproval", method = RequestMethod.PUT)
33525 tejus.loha 326
    public String feePaymentApproval(HttpServletRequest request, @RequestParam int bfcId, @RequestParam FeePaymentStatus feePaymentStatus, @RequestParam String description,
327
                                     Model model) throws Exception {
33507 tejus.loha 328
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
329
        String authEmail = loginDetails.getEmailId();
330
        BrandFeeCollection brandFeeCollection = brandFeeCollectionRepository.selectById(bfcId);
331
        brandFeeCollection.setApproverEmail(authEmail);
332
        brandFeeCollection.setPaymentStatus(feePaymentStatus);
33525 tejus.loha 333
        brandFeeCollection.setDescription(description);
34195 tejus.loha 334
        brandFeeCollection.setApprovalTimeStamp(LocalDateTime.now());
33848 tejus.loha 335
        if (feePaymentStatus.equals(FeePaymentStatus.CONFIRM)) {
35971 aman 336
            // Payment Approval timeline entry
337
            storeTimelineTatService.createStoreTimeline(brandFeeCollection.getLoiFormId(), StoreTimeline.PAYMENT_APPROVAL);
33848 tejus.loha 338
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(brandFeeCollection.getLoiFormId()));
339
        }
33845 tejus.loha 340
        loiFormService.sendPaymentStatusMailToLoiFormFilledBy(brandFeeCollection);
341
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
33507 tejus.loha 342
        return "response";
343
 
344
    }
345
 
34739 aman.kumar 346
    @RequestMapping(value = "/feePaymentDeletion", method = RequestMethod.PUT)
347
    public String feePaymentDeletion(HttpServletRequest request, @RequestParam int bfcId,
348
                                     Model model) throws Exception {
349
        brandFeeCollectionRepository.deleteById(bfcId);
350
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
351
        return "response";
33658 tejus.loha 352
 
34739 aman.kumar 353
    }
354
 
355
 
33617 tejus.loha 356
    @RequestMapping(value = "/uploadDocumentForm", method = RequestMethod.GET)
33507 tejus.loha 357
    public String uploadDocumentForm(HttpServletRequest request, @RequestParam int loiId, Model model) throws ProfitMandiBusinessException {
358
        List<LoiDocMaster> activeDocMasterList = loiDocMasterList.getAllActiveDoc();
359
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
360
        String authEmail = authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getEmailId();
361
        String approverEmail = "gaurav.sharma@smartdukaan.com";
362
        boolean isApprover = false;
363
        if (authEmail.equals(approverEmail)) {
364
            isApprover = true;
365
        }
33845 tejus.loha 366
        Map<Integer, LoiDoc> masterDocIdLoiDocMap = loiDocRepository.selectByLoiFormId(loiId).stream().collect(Collectors.toMap(x -> x.getMasterDocId(), x -> x));
33507 tejus.loha 367
        model.addAttribute("isApprover", isApprover);
368
        model.addAttribute("loiId", loiId);
369
        model.addAttribute("activeDocMasterList", activeDocMasterList);
370
        model.addAttribute("masterDocIdLoiDocMap", masterDocIdLoiDocMap);
371
        return "loiForm/document-upload";
372
    }
373
 
374
    @RequestMapping(value = "/uploadOnboardingDocument", method = RequestMethod.POST)
375
    public String uploadDocument(HttpServletRequest request, @RequestParam int loiId, @RequestBody List<LoiDocModel> loiDocModels, Model model) throws Exception {
376
        LoiForm loiForm = loiFormRepository.selectById(loiId);
377
        loiFormService.setDocs(loiForm, loiDocModels);
378
        model.addAttribute("response1", mvcResponseSender.createResponseString("Document uploaded successfully"));
379
        return "response";
380
 
381
    }
382
 
383
 
33617 tejus.loha 384
    @RequestMapping(value = "/documentVerify", method = RequestMethod.PUT)
33507 tejus.loha 385
    public String docApproval(HttpServletRequest request, @RequestParam int loiId, @RequestParam int docMasterId, @RequestParam boolean flag, Model model) throws Exception {
386
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
387
        AuthUser auth = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
388
        LoiDoc loiDoc = loiDocRepository.selectByLoiIdAndMasterDocId(loiId, docMasterId);
389
        if (flag) {
390
            loiDoc.setOk(true);
391
            loiDoc.setVerifyBy(auth.getId());
35971 aman 392
            // Document Approval timeline entry
393
            storeTimelineTatService.createStoreTimeline(loiId, StoreTimeline.LOI_DOCUMENT_APPROVAL);
33507 tejus.loha 394
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Accepted "));
395
            return "response";
396
        } else {
397
            loiDoc.setOk(false);
398
            loiDoc.setVerifyBy(auth.getId());
35971 aman 399
            LoiForm loiForm = loiFormRepository.selectById(loiId);
400
            if (loiForm.isLoiApproved()) {
401
                loiForm.setLoiApproved(false);
402
            }
33658 tejus.loha 403
            loiFormService.sendDocRejectionMail(loiDoc);
33507 tejus.loha 404
            model.addAttribute("response1", mvcResponseSender.createResponseString(loiDoc.getDocType() + " is Rejected"));
405
            return "response";
406
        }
407
    }
408
 
409
    @RequestMapping(value = "/loiAcceptanceOtp", method = RequestMethod.POST)
410
    public String sentLoiAcceptanceOtp(@RequestParam int loiId, Model model) throws Exception {
33658 tejus.loha 411
        LoiForm loiForm = loiFormRepository.selectById(loiId);
412
        String mobile = String.valueOf(loiForm.getMobile());
37194 aman 413
        Map<String, Object> response = new HashMap<>();
414
 
415
        OTPResponse otpResponse;
416
        try {
417
            otpResponse = otpProcessor.generateOtp(mobile, OtpType.LOI_ACCEPTANCE);
418
        } catch (Exception e) {
419
            // The dispatch itself blew up (gateway error, duplicate loi_form on this mobile, ...). Never
420
            // report this as a send - the panel used to show "OTP Sent Successfully!" for exactly this case.
421
            LOGGER.error("LOI acceptance OTP dispatch failed for loiId " + loiId + ", mobile " + mobile, e);
422
            response.put("status", false);
423
            response.put("sent", false);
424
            response.put("message", "OTP could not be sent due to a system error. Please report to tech support.");
425
            model.addAttribute("response1", mvcResponseSender.createResponseString(response));
33568 tejus.loha 426
            return "response";
37194 aman 427
        }
428
 
429
        LOGGER.info("OTPResponse for loiId " + loiId + " - result=" + otpResponse.isResult()
430
                + ", sent=" + otpResponse.isSent() + ", message=" + otpResponse.getMessage());
431
 
432
        response.put("status", otpResponse.isResult());
433
        response.put("sent", otpResponse.isSent());
434
        if (otpResponse.isResult() && otpResponse.isSent()) {
435
            response.put("message", "OTP sent on registered mobile and EmailId - " + mobile + " and " + loiForm.getEmail());
33525 tejus.loha 436
        } else {
37194 aman 437
            // Accepted-but-not-dispatched (resend throttle) and outright rejections (daily cap) both land
438
            // here. Pass the processor's own reason through instead of a generic "Something went wrong..".
439
            response.put("message", otpResponse.getMessage());
33525 tejus.loha 440
        }
37194 aman 441
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
442
        return "response";
33507 tejus.loha 443
    }
444
 
445
    @RequestMapping(value = "/validateLoiOtp", method = RequestMethod.PUT)
35038 aman 446
    public ResponseEntity<?> validateLoiAcceptanceOtp(HttpServletRequest request, @RequestParam int loiId, @RequestParam String provideOtp, Model model) throws Exception {
33658 tejus.loha 447
        LoiForm loiForm = loiFormRepository.selectById(loiId);
448
        String mobile = String.valueOf(loiForm.getMobile());
33507 tejus.loha 449
        Otp otp = otpRepository.selectAllByMobileWithTime(mobile).get(0);
450
        OTPResponse otpResponse = otpProcessor.validateOtp(otp.getId(), mobile, provideOtp);
35038 aman 451
        Map<String, Object> response = new HashMap<>();
33507 tejus.loha 452
        if (otpResponse.isResult()) {
33658 tejus.loha 453
            loiForm.setLoiSignOtp(provideOtp);
454
            loiForm.setLoiSignedOn(LocalDateTime.now());
35038 aman 455
 
456
            List<LoiBrandCommitment> loiBrandCommitments = brandCommitmentRepository.selectByLoiId(loiId).stream().filter(x -> x.getAmount() > 0).collect(Collectors.toList());
457
            double totalCommitment = loiBrandCommitments.stream().mapToDouble(x -> x.getAmount()).sum();
458
            List<BrandFeeCollection> brandFeeCollections = brandFeeCollectionRepository.selectAllConfirmPaymetByLoiId(loiId);
459
            double brandFeeAmount = brandFeeCollections.stream().mapToDouble(x -> x.getCollectedAmount()).sum();
460
            BrandFeeCollection brandFeeCollection = brandFeeCollections.get(0);
461
            String prevHash = loiAuditTrailRepository.findDocumentHashByLoiId(loiId);
462
            String rawData = loiId + "|"
463
                    + loiForm.getCompanyName() + "|"
464
                    + loiForm.getBrandType() + "|"
465
                    + brandFeeAmount + "|"
466
                    + brandFeeCollection.getPaymentMode() + "|"
467
                    + totalCommitment;
468
            String hash = getHash256(rawData);
469
 
470
            LoiAuditTrail audit = new LoiAuditTrail();
471
            audit.setLoiId(loiId);
472
            audit.setCompanyName(loiForm.getCompanyName());
473
            audit.setReferBy(loiForm.getReferBy());
474
            audit.setReferId(loiForm.getReferId());
475
            audit.setFilledBy(loiForm.getFilledBy());
476
            audit.setFranchiseeName(loiForm.getFullName());
477
            audit.setBrandType(loiForm.getBrandType());
478
            audit.setBrandFeeAmount(brandFeeAmount);
479
            audit.setPaymentMode(brandFeeCollection.getPaymentMode());
480
            audit.setTotalCommitment(totalCommitment);
481
            audit.setLoiSignedOn(LocalDateTime.now());
482
            audit.setLoiGeneratedOn(loiForm.getLoiGeneratedOn());
483
            audit.setLoiOtp(provideOtp);
484
            if (prevHash != null) {
485
                audit.setPrevHash(prevHash);
486
            }
487
            audit.setIpAddress(request.getRemoteAddr());
488
            audit.setDocumentHash(hash);
489
 
490
            response.put("success", true);
491
            response.put("documentHash", audit.getDocumentHash());
492
            response.put("ipAddress", audit.getIpAddress());
493
            response.put("generatedAt", audit.getCreatedAt());
494
            response.put("loiId", loiId);
495
            loiAuditTrailRepository.persist(audit);
496
 
33845 tejus.loha 497
        } else {
498
            throw new ProfitMandiBusinessException("Wrong OTP", "", "Your given Otp ->" + provideOtp + " is wrong , please check OTP and try again");
33507 tejus.loha 499
        }
35038 aman 500
        return responseSender.ok(response);
33507 tejus.loha 501
    }
502
 
33845 tejus.loha 503
    @RequestMapping(value = "/saveLoiDoc", method = RequestMethod.POST)
504
    public String saveLoiDoc(@RequestParam int loiId, @RequestParam int loiDocId, Model model) throws Exception {
505
        LOGGER.info("loi_docId-" + loiDocId);
506
        LoiForm loiForm = loiFormRepository.selectById(loiId);
507
        if (loiDocId > 0) {
508
            loiForm.setLoiDoc(loiDocId);
509
            loiFormService.sendSignedLoiPdfToPartner(loiForm);
33848 tejus.loha 510
            loiFormService.checkLoiDetailsCompletion(loiForm);
33845 tejus.loha 511
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
512
        } else {
34947 aman 513
            loiForm.setLoiSignOtp(null);
33845 tejus.loha 514
            loiForm.setLoiGeneratedOn(null);
515
            loiForm.setLoiSignedOn(null);
516
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
517
        }
518
        return "response";
519
 
520
    }
521
 
33617 tejus.loha 522
    @RequestMapping(value = "/downloadLoiFromReport", method = RequestMethod.GET)
523
    public ResponseEntity<?> downloadAllLoiForm(@RequestParam LocalDate from, @RequestParam LocalDate to) throws Exception {
524
        ResponseEntity<?> responseEntity = loiFormService.createLoiFormReport(from, to);
525
        return responseEntity;
526
    }
527
 
33658 tejus.loha 528
    @RequestMapping(value = "/updatePayment", method = RequestMethod.POST)
529
    public String updateForm(@RequestBody BrandFeeCollection brandFeeCollection, Model model) throws Exception {
530
        BrandFeeCollection brandFeeCollection1 = brandFeeCollectionRepository.selectById(brandFeeCollection.getId());
33845 tejus.loha 531
        LoiForm loiForm = loiFormRepository.selectById(brandFeeCollection1.getLoiFormId());
33850 tejus.loha 532
        brandFeeCollection1.setFeeCollectingTimeStamp(brandFeeCollection.getFeeCollectingTimeStamp());
533
        brandFeeCollection1.setCollectedAmount(brandFeeCollection.getCollectedAmount());
33885 tejus.loha 534
        brandFeeCollection1.setPaymentAttachment(brandFeeCollection.getPaymentAttachment());
33850 tejus.loha 535
        brandFeeCollection1.setPaymentReferenceNo(brandFeeCollection.getPaymentReferenceNo());
536
        brandFeeCollection1.setPaymentMode(brandFeeCollection.getPaymentMode());
537
        double totalCollectedFee = brandFeeCollectionRepository.selectAllByLoiFormId(loiForm.getId()).stream().mapToDouble(x -> x.getCollectedAmount()).sum();
538
        if (totalCollectedFee <= loiForm.getAgreedBrandFees()) {
33845 tejus.loha 539
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
540
        } else {
33850 tejus.loha 541
            double differanceAmount = totalCollectedFee - loiForm.getAgreedBrandFees();
33845 tejus.loha 542
            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");
543
        }
33658 tejus.loha 544
        return "response";
545
    }
33617 tejus.loha 546
 
33710 tejus.loha 547
    @RequestMapping(value = "/updateAgreedBrandFee", method = RequestMethod.PUT)
34085 tejus.loha 548
    public String updateAgreedBrandFee(HttpServletRequest request, @RequestParam int loiId, @RequestParam double brandFee, @RequestParam StoreType storeType, Model model) throws Exception {
33710 tejus.loha 549
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
550
        boolean isAgreedBrandFeeChanger = agreedBrandFeeChangerEmail.stream().anyMatch(x -> x.equals(loginDetails.getEmailId()));
551
        if (isAgreedBrandFeeChanger) {
552
            LoiForm loiForm = loiFormRepository.selectById(loiId);
553
            loiForm.setAgreedBrandFees(brandFee);
34085 tejus.loha 554
            loiForm.setBrandType(storeType);
34086 tejus.loha 555
            loiFormService.checkLoiDetailsCompletion(loiFormRepository.selectById(loiId));
33710 tejus.loha 556
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
557
            return "response";
558
        } else {
559
            throw new ProfitMandiBusinessException("failed in Authority check ", null, "Sorry " + authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getName() + " you have no authority to change agreed brand fee");
560
        }
561
    }
562
 
33845 tejus.loha 563
    @RequestMapping(value = "/approve-reject-Loi", method = RequestMethod.PUT)
564
    public String approveDetails(HttpServletRequest request, @RequestParam int loiId, @RequestParam boolean flag, Model model) throws Exception {
565
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
566
        String email = loginDetails.getEmailId();
33711 tejus.loha 567
        LoiForm loiForm = loiFormRepository.selectById(loiId);
33845 tejus.loha 568
        AuthUser filledBy = authRepository.selectByEmailOrMobile(loiForm.getFilledBy());
569
        AuthUser manager = authRepository.selectById(filledBy.getManagerId());
570
        AuthUser upperManager = null;
571
        List<String> approverMail = new ArrayList<>();
572
        approverMail.add(manager.getEmailId());
573
        upperManager = authRepository.selectById(manager.getManagerId());
574
        approverMail.add(upperManager.getEmailId());
575
 
576
        LOGGER.info("approverMail-" + approverMail);
577
        // Approver - Manager or Upper manager of loi filledBy(BM)
578
        boolean isApprover = approverMail.contains(email);
579
        LOGGER.info("isApprover-" + isApprover);
36872 ranu 580
        List<String> authEmail = Arrays.asList("sm@smartdukaan.com", "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "ashutosh.verma@smartdukaan.com");
33845 tejus.loha 581
        boolean isAuthUser = authEmail.stream().anyMatch(x -> x.equals(email));
582
        if (flag) {
583
            if (isApprover || isAuthUser) {
584
                loiForm.setLoiApprover(email);
585
                loiForm.setLoiApproved(flag);
35971 aman 586
                if (loiForm.getStatus() == LoiStatus.LOI_REJECT) {
587
                    loiForm.setStatus(LoiStatus.PENDING);
588
                }
589
                // BM Approval timeline entry
590
                storeTimelineTatService.createStoreTimeline(loiId, StoreTimeline.BM_APPROVAL);
591
                // Check if all LOI conditions are now met (BM approval could be the last step)
592
                loiFormService.checkLoiDetailsCompletion(loiForm);
33845 tejus.loha 593
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
594
            } else {
595
                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");
596
            }
597
        } else {
598
            if (isApprover || isAuthUser) {
599
                loiForm.setLoiApprover(email);
600
                loiForm.setLoiApproved(flag);
601
                loiForm.setStatus(LoiStatus.LOI_REJECT);
602
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
603
            } else {
604
                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");
605
            }
606
        }
33711 tejus.loha 607
        return "response";
608
    }
609
 
33845 tejus.loha 610
 
33507 tejus.loha 611
}