Subversion Repositories SmartDukaan

Rev

Rev 37931 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
22551 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
30859 tejbeer 3
import com.spice.profitmandi.common.enumuration.MessageType;
22551 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23936 tejbeer 5
import com.spice.profitmandi.common.model.CustomRetailer;
34527 tejus.loha 6
import com.spice.profitmandi.common.model.HdfcPaymentModel;
22551 ashik.ali 7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
24089 tejbeer 8
import com.spice.profitmandi.common.model.UnsettledPaymentModel;
31238 amit.gupta 9
import com.spice.profitmandi.common.util.*;
29811 tejbeer 10
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
31238 amit.gupta 11
import com.spice.profitmandi.dao.entity.transaction.*;
35971 aman 12
import com.spice.profitmandi.dao.entity.user.FullStockPayment;
32727 shampa 13
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
35971 aman 14
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.FullStockPaymentStatus;
23936 tejbeer 15
import com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus;
24876 tejbeer 16
import com.spice.profitmandi.dao.enumuration.transaction.TransactionType;
33420 amit.gupta 17
import com.spice.profitmandi.dao.model.DateRangeModel;
33861 tejus.loha 18
import com.spice.profitmandi.dao.model.StoreTimelineModel;
23936 tejbeer 19
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
24876 tejbeer 20
import com.spice.profitmandi.dao.repository.catalog.ManualPaymentRequestRepository;
24089 tejbeer 21
import com.spice.profitmandi.dao.repository.catalog.UnsettledPaymentsRepository;
29811 tejbeer 22
import com.spice.profitmandi.dao.repository.dtr.CreditAccountRepository;
24876 tejbeer 23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33861 tejus.loha 24
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
23985 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
32490 jai.hind 26
import com.spice.profitmandi.dao.repository.transaction.*;
35971 aman 27
import com.spice.profitmandi.dao.repository.user.FullStockPaymentRepository;
33861 tejus.loha 28
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
33359 amit.gupta 29
import com.spice.profitmandi.dao.service.SidbiService;
30859 tejbeer 30
import com.spice.profitmandi.service.NotificationService;
24523 amit.gupta 31
import com.spice.profitmandi.service.authentication.RoleManager;
37931 amit 32
import com.spice.profitmandi.service.transaction.SDCreditServiceImpl;
29070 amit.gupta 33
import com.spice.profitmandi.service.transaction.TransactionService;
23936 tejbeer 34
import com.spice.profitmandi.service.user.RetailerService;
33861 tejus.loha 35
import com.spice.profitmandi.service.user.StoreTimelineTatService;
22551 ashik.ali 36
import com.spice.profitmandi.service.wallet.WalletService;
37
import com.spice.profitmandi.web.model.LoginDetails;
38
import com.spice.profitmandi.web.util.CookiesProcessor;
23936 tejbeer 39
import com.spice.profitmandi.web.util.MVCResponseSender;
40
import in.shop2020.model.v1.order.WalletReferenceType;
31238 amit.gupta 41
import org.apache.logging.log4j.LogManager;
42
import org.apache.logging.log4j.Logger;
43
import org.apache.poi.ss.usermodel.Cell;
44
import org.apache.poi.ss.usermodel.CellStyle;
45
import org.apache.poi.ss.usermodel.CreationHelper;
46
import org.apache.poi.ss.usermodel.Sheet;
47
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
48
import org.springframework.beans.factory.annotation.Autowired;
49
import org.springframework.core.io.InputStreamResource;
50
import org.springframework.http.HttpHeaders;
51
import org.springframework.http.HttpStatus;
52
import org.springframework.http.ResponseEntity;
53
import org.springframework.mail.javamail.JavaMailSender;
54
import org.springframework.mail.javamail.MimeMessageHelper;
55
import org.springframework.stereotype.Controller;
35971 aman 56
import org.springframework.transaction.annotation.Transactional;
31238 amit.gupta 57
import org.springframework.ui.Model;
58
import org.springframework.web.bind.annotation.*;
59
import org.springframework.web.multipart.MultipartFile;
23936 tejbeer 60
 
31238 amit.gupta 61
import javax.mail.internet.InternetAddress;
62
import javax.mail.internet.MimeMessage;
63
import javax.servlet.http.HttpServletRequest;
64
import javax.swing.*;
65
import java.io.ByteArrayInputStream;
66
import java.io.ByteArrayOutputStream;
67
import java.io.InputStream;
32490 jai.hind 68
import java.math.BigDecimal;
31238 amit.gupta 69
import java.text.MessageFormat;
33420 amit.gupta 70
import java.time.*;
31238 amit.gupta 71
import java.util.*;
72
import java.util.stream.Collectors;
73
 
34096 aman.kumar 74
import static com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus.approved;
75
 
22551 ashik.ali 76
@Controller
35458 amit 77
@Transactional(rollbackFor = Throwable.class)
22551 ashik.ali 78
public class WalletController {
79
 
32491 jai.hind 80
    private static final int IDX_PERIOD = 1;
81
    private static final int OPENING_BALANCE = 2;
82
    private static final int ACTIVATION_SCHEME = 4;
83
    private static final int ADVANCE_AMOUNT = 5;
84
    private static final int AUTOMATED_ADVANCE = 6;
85
    private static final int BRAND_PAYOUT = 7;
86
    private static final int INVESTMENT_PAYOUT = 8;
87
    private static final int OTHERS = 9;
88
    private static final int PREBOOKING_ORDER = 10;
89
    private static final int PRICE_DROP = 11;
90
    private static final int PURCHASE = 12;
91
    private static final int PURCHASE_BILLED = 13;
92
    private static final int PURCHASE_PENDING_BILLING = 14;
93
    private static final int PURCHASE_CANCELLED = 15;
94
    private static final int RECHARGE = 16;
95
    private static final int REFUND = 17;
96
    private static final int SCHEME_IN = 18;
97
    private static final int SCHEME_OUT = 19;
98
    private static final Map<WalletReferenceType, Integer> walletReferenceMap = new HashMap<>();
32494 amit.gupta 99
    private static final int GRAND_TOTAL = 20;
100
    private static final int CLOSING_BALANCE = 22;
101
    private static final int PENDING_GRN = 23;
102
    private static final int ACTIVATED_IMEIS = 24;
103
    private static final Logger LOGGER = LogManager.getLogger(WalletController.class);
32490 jai.hind 104
 
32491 jai.hind 105
    static {
106
        walletReferenceMap.put(WalletReferenceType.ACTIVATION_SCHEME, ACTIVATION_SCHEME);
107
        walletReferenceMap.put(WalletReferenceType.ADVANCE_AMOUNT, ADVANCE_AMOUNT);
108
        walletReferenceMap.put(WalletReferenceType.AUTOMATED_ADVANCE, AUTOMATED_ADVANCE);
109
        walletReferenceMap.put(WalletReferenceType.BRAND_PAYOUT, BRAND_PAYOUT);
110
        walletReferenceMap.put(WalletReferenceType.INVESTMENT_PAYOUT, INVESTMENT_PAYOUT);
111
        walletReferenceMap.put(WalletReferenceType.OTHERS, OTHERS);
112
        walletReferenceMap.put(WalletReferenceType.PREBOOKING_ORDER, PREBOOKING_ORDER);
113
        walletReferenceMap.put(WalletReferenceType.PRICE_DROP, PRICE_DROP);
114
        walletReferenceMap.put(WalletReferenceType.PURCHASE, PURCHASE);
115
        walletReferenceMap.put(WalletReferenceType.RECHARGE, RECHARGE);
116
        walletReferenceMap.put(WalletReferenceType.REFUND, REFUND);
117
        walletReferenceMap.put(WalletReferenceType.SCHEME_IN, SCHEME_IN);
118
        walletReferenceMap.put(WalletReferenceType.SCHEME_OUT, SCHEME_OUT);
28515 amit.gupta 119
 
32491 jai.hind 120
    }
32490 jai.hind 121
 
32491 jai.hind 122
    @Autowired
36401 amit 123
    JavaMailSender gmailRelaySender;
32494 amit.gupta 124
    @Autowired
35811 amit 125
    com.spice.profitmandi.service.transaction.SDCreditService sdCreditService;
126
    @Autowired
32494 amit.gupta 127
    AddWalletRequestRepository addWalletRequestRepository;
128
    @Autowired
129
    TransactionService transactionService;
130
    @Autowired
32491 jai.hind 131
    private CookiesProcessor cookiesProcessor;
132
    @Autowired
133
    private WalletService walletService;
134
    @Autowired
135
    private UserWalletRepository userWalletRepository;
136
    @Autowired
137
    private UserWalletHistoryRepository userWalletHistoryRepository;
138
    @Autowired
139
    private MVCResponseSender mvcResponseSender;
140
    @Autowired
141
    private UserAccountRepository userAccountRepository;
142
    @Autowired
143
    private OrderRepository orderRepository;
144
    @Autowired
145
    private UnsettledPaymentsRepository unsettledPaymentsRepository;
146
    @Autowired
147
    private RetailerService retailerService;
148
    @Autowired
149
    private RoleManager roleManager;
150
    @Autowired
151
    private FofoStoreRepository fofoStoreRepository;
152
    @Autowired
153
    private ManualPaymentRequestRepository manualPaymentRequestRepository;
154
    @Autowired
155
    private CreditAccountRepository creditAccountRepository;
30859 tejbeer 156
 
32491 jai.hind 157
    @Autowired
158
    private NotificationService notificationService;
159
    @Autowired
160
    LoanRepository loanRepository;
161
    @Autowired
162
    private LoanStatementRepository loanStatementRepository;
163
    @Autowired
36754 amit 164
    private ReturnOrderInfoRepository returnOrderInfoRepository;
165
    @Autowired
32491 jai.hind 166
    SDCreditRequirementRepository sdCreditRequirementRepository;
33861 tejus.loha 167
    @Autowired
168
    LoiFormRepository loiFormRepository;
169
    @Autowired
170
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
171
    @Autowired
172
    StoreTimelineTatService storeTimelineTatService;
28515 amit.gupta 173
 
35971 aman 174
    @Autowired
175
    FullStockPaymentRepository fullStockPaymentRepository;
176
    @Autowired
177
    com.spice.profitmandi.dao.repository.auth.AuthRepository authRepository;
178
    @Autowired
179
    com.spice.profitmandi.dao.repository.cs.PositionRepository positionRepository;
33205 amit.gupta 180
 
35971 aman 181
 
32491 jai.hind 182
    @PostMapping(value = "/wallet/upload")
32495 amit.gupta 183
    public String uploadWalletBulk(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model) throws Exception {
32491 jai.hind 184
        List<WalletHistoryModel> walletHistoryModelList = ExcelUtils.parseWalletBulkCredit(file.getInputStream());
37065 amit 185
        // Scheme/CN-backed reference types (CN_WALLET_REFERENCES) must flow through the scheme/offer code
186
        // paths that also reject the offer_payout / scheme_in_out, so the month-end MARGINS credit note
187
        // reverses with them. Posting one manually from this sheet leaves the payout un-rejected -> the CN
188
        // is over-issued and the account-statement scheme-adjustment line breaks (see the Jul-2026 re-tag
189
        // fix). Reject the whole sheet up-front (this endpoint is not transactional, so validate before any
190
        // row posts); manual scheme recoveries must be posted as OTHERS.
191
        List<WalletHistoryModel> blockedRows = walletHistoryModelList.stream()
192
                .filter(x -> WalletService.CN_WALLET_REFERENCES.contains(x.getWalletReferenceType()))
193
                .collect(Collectors.toList());
194
        if (!blockedRows.isEmpty()) {
195
            String offending = blockedRows.stream()
196
                    .map(x -> "fofoId " + x.getFofoId() + " => " + x.getWalletReferenceType())
197
                    .collect(Collectors.joining(", "));
198
            throw new ProfitMandiBusinessException("Wallet", "Wallet",
199
                    "Scheme/CN-backed reference types cannot be posted from the wallet bulk sheet - they must go "
200
                            + "through the scheme/offer flow so the credit note reverses. Post manual scheme recoveries as OTHERS. "
201
                            + "Offending rows: " + offending);
202
        }
32491 jai.hind 203
        for (WalletHistoryModel walletHistoryModel : walletHistoryModelList) {
204
            if (walletHistoryModel.getReference() == 0) {
32495 amit.gupta 205
                ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(walletHistoryModel.getWalletReferenceType());
32491 jai.hind 206
                if (paymentType == null) {
207
                    paymentType = new ManualPaymentType();
208
                    paymentType.setReferenceType(walletHistoryModel.getWalletReferenceType());
209
                    manualPaymentRequestRepository.persist(paymentType);
210
                }
211
                paymentType.setCounter(paymentType.getCounter() + 1);
212
                int reference = paymentType.getCounter();
32495 amit.gupta 213
                walletService.addAmountToWallet(walletHistoryModel.getFofoId(), reference, walletHistoryModel.getWalletReferenceType(), walletHistoryModel.getDescription(), (float) walletHistoryModel.getAmount(), walletHistoryModel.getBusinessDate());
32491 jai.hind 214
            } else {
32495 amit.gupta 215
                walletService.addAmountToWallet(walletHistoryModel.getFofoId(), walletHistoryModel.getReference(), walletHistoryModel.getWalletReferenceType(), walletHistoryModel.getDescription(), (float) walletHistoryModel.getAmount(), walletHistoryModel.getBusinessDate());
32491 jai.hind 216
            }
217
        }
23993 tejbeer 218
 
32491 jai.hind 219
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
220
        return "response";
221
    }
27067 amit.gupta 222
 
32491 jai.hind 223
    @RequestMapping(value = "/walletDetails", method = RequestMethod.GET)
32495 amit.gupta 224
    public String dashboard(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "100") int limit, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 225
        /*
226
         * boolean underMaintainance = true; if(underMaintainance) { throw new
227
         * ProfitMandiBusinessException("Wallet", "Wallet",
228
         * "Wallet is under Maintenance"); }
229
         */
230
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
231
        int fofoId = fofoDetails.getFofoId();
232
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
233
        UserWallet userWallet = walletService.getUserWallet(fofoId);
23993 tejbeer 234
 
32491 jai.hind 235
        LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
236
        LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
23993 tejbeer 237
 
32491 jai.hind 238
        List<UserWalletHistory> userWalletHistories = new ArrayList<>();
239
        try {
32495 amit.gupta 240
            userWalletHistories = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDateTime, endDateTime, offset, limit);
32491 jai.hind 241
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
37728 amit 242
            LOGGER.warn("UserWallet History not found : ", profitMandiBusinessException);
32491 jai.hind 243
        }
23993 tejbeer 244
 
32491 jai.hind 245
        long countItems = 0;
246
        try {
247
            countItems = walletService.getSizeByRetailerId(fofoDetails.getFofoId(), startDateTime, endDateTime);
248
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
37728 amit 249
            LOGGER.warn("UserWallet not found : ", profitMandiBusinessException);
32491 jai.hind 250
        }
36746 amit 251
        com.spice.profitmandi.dao.model.CreditSummary creditSummary = sdCreditService.getCreditSummary(fofoId);
37018 ranu 252
 
253
        // Utilization comes from sd_credit_requirement.utilized_amount — the same source
254
        // the sddirect/summary API uses (GatewayController + SDCreditServiceImpl:732).
255
        // This reflects all credit consumed including limit-block (flagship) loans,
256
        // which the loan-derived CreditSummary.getUtilization() misses because
257
        // selectAllActiveLoan filters out limit_block=true rows.
258
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
259
        java.math.BigDecimal utilizationAmount = (sdCreditRequirement != null && sdCreditRequirement.getUtilizedAmount() != null)
260
                ? sdCreditRequirement.getUtilizedAmount()
261
                : java.math.BigDecimal.ZERO;
37171 amit 262
        java.math.BigDecimal creditLimitAmount = (sdCreditRequirement != null && sdCreditRequirement.getLimit() != null)
263
                ? sdCreditRequirement.getLimit()
264
                : java.math.BigDecimal.ZERO;
37018 ranu 265
 
32491 jai.hind 266
        model.addAttribute("userWallet", userWallet);
267
        model.addAttribute("walletHistories", userWalletHistories);
36242 aman 268
        model.addAttribute("walletAttachmentMap", buildWalletHistoryAttachmentMap(userWalletHistories));
32491 jai.hind 269
        model.addAttribute("start", offset + 1);
270
        model.addAttribute("size", countItems);
271
        model.addAttribute("isAdmin", isAdmin);
36746 amit 272
        model.addAttribute("totalDue", creditSummary.getTotalDue());
37018 ranu 273
        model.addAttribute("utilization", utilizationAmount);
37171 amit 274
        model.addAttribute("creditlimit", creditLimitAmount);
37931 amit 275
        CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fofoId, Gateway.SDDIRECT);
276
        if (creditAccount != null && !creditAccount.isActive()) {
37986 amit 277
            model.addAttribute("creditInactiveMessage", SDCreditServiceImpl.getPartnerInactiveMessage(creditAccount, creditSummary.getDefaultCount()));
37931 amit 278
        }
32491 jai.hind 279
        model.addAttribute(ProfitMandiConstants.START_TIME, startTimeString);
280
        model.addAttribute(ProfitMandiConstants.END_TIME, endTimeString);
23993 tejbeer 281
 
32491 jai.hind 282
        if (userWalletHistories.size() < limit) {
283
            model.addAttribute("end", offset + userWalletHistories.size());
284
        } else {
285
            model.addAttribute("end", offset + limit);
286
        }
287
        return "wallet-details";
288
    }
23993 tejbeer 289
 
32491 jai.hind 290
    @RequestMapping(value = "/getPaginatedWalletHistory")
32495 amit.gupta 291
    public String getSaleHistoryPaginated(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 292
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22551 ashik.ali 293
 
32491 jai.hind 294
        LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
295
        LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
23993 tejbeer 296
 
32491 jai.hind 297
        List<UserWalletHistory> userWalletHistories = new ArrayList<>();
298
        try {
32495 amit.gupta 299
            userWalletHistories = walletService.getPaginatedUserWalletHistoryByRetailerId(loginDetails.getFofoId(), startDateTime, endDateTime, offset, limit);
32491 jai.hind 300
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
37728 amit 301
            LOGGER.warn("UserWallet History not found : ", profitMandiBusinessException);
32491 jai.hind 302
        }
23993 tejbeer 303
 
32491 jai.hind 304
        model.addAttribute("walletHistories", userWalletHistories);
36242 aman 305
        model.addAttribute("walletAttachmentMap", buildWalletHistoryAttachmentMap(userWalletHistories));
32491 jai.hind 306
        return "wallet-history-paginated";
307
    }
23936 tejbeer 308
 
32491 jai.hind 309
    @RequestMapping(value = "/getAddWalletRequest", method = RequestMethod.GET)
36500 ranu 310
    public String getAddwalletRequest(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "100") int limit, Model model) throws Exception {
32491 jai.hind 311
        List<AddWalletRequest> walletRequest = null;
312
        long size = 0;
313
        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.pending);
314
        LOGGER.info("walletRequest" + walletRequest);
315
        size = addWalletRequestRepository.selectCountByStatus(AddWalletRequestStatus.pending);
316
        if (!walletRequest.isEmpty()) {
317
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
30426 tejbeer 318
 
32491 jai.hind 319
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 320
 
32495 amit.gupta 321
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 322
 
32491 jai.hind 323
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
324
            model.addAttribute("walletRequest", walletRequest);
36242 aman 325
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 326
            model.addAttribute("rStatus", "pending");
327
            model.addAttribute("start", offset + 1);
328
            model.addAttribute("size", size);
329
            model.addAttribute("url", "/getPaginatedWalletRequest");
23993 tejbeer 330
 
32491 jai.hind 331
            if (walletRequest.size() < limit) {
332
                model.addAttribute("end", offset + walletRequest.size());
333
            } else {
334
                model.addAttribute("end", offset + limit);
335
            }
23993 tejbeer 336
 
32491 jai.hind 337
        } else {
23993 tejbeer 338
 
32491 jai.hind 339
            model.addAttribute("walletRequest", walletRequest);
340
            model.addAttribute("size", size);
23936 tejbeer 341
 
32491 jai.hind 342
        }
343
        return "add-wallet-request";
344
    }
23936 tejbeer 345
 
32491 jai.hind 346
    @RequestMapping(value = "/getPaginatedWalletRequest", method = RequestMethod.GET)
32495 amit.gupta 347
    public String getPaginatedWalletRequest(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws Exception {
32491 jai.hind 348
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
349
        List<AddWalletRequest> walletRequest = null;
350
        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.pending);
351
        LOGGER.info("walletRequest" + walletRequest);
352
        if (!walletRequest.isEmpty()) {
353
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
354
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 355
 
32495 amit.gupta 356
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 357
 
32491 jai.hind 358
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
359
            model.addAttribute("walletRequest", walletRequest);
36242 aman 360
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 361
            model.addAttribute("rStatus", "pending");
362
            model.addAttribute("url", "/getPaginatedWalletRequest");
23993 tejbeer 363
 
32491 jai.hind 364
        } else {
365
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 366
 
32491 jai.hind 367
        }
23993 tejbeer 368
 
32491 jai.hind 369
        return "add-wallet-request-paginated";
370
    }
23993 tejbeer 371
 
32491 jai.hind 372
    @RequestMapping(value = "/getAddWalletApproved", method = RequestMethod.GET)
34096 aman.kumar 373
    public String walletAddnAccept(HttpServletRequest request, Model model) throws Exception {
374
 
375
        return "add-wallet-req";
376
    }
377
 
378
    @RequestMapping(value = "/getAddWalletApprovedByDate", method = RequestMethod.GET)
379
    public String getAddwalletRequestApproved(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
380
                                              @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
381
        LOGGER.info("requested startDate=[{}], EndDate = [{}]", startDate, endDate);
32491 jai.hind 382
        List<AddWalletRequest> walletRequest = null;
383
        long size = 0;
34096 aman.kumar 384
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.approved);
385
//        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, approved);
386
        size = addWalletRequestRepository.selectCountByStatus(approved);
32491 jai.hind 387
        if (!walletRequest.isEmpty()) {
388
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
389
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 390
 
32495 amit.gupta 391
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 392
 
32491 jai.hind 393
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
394
            model.addAttribute("walletRequest", walletRequest);
36242 aman 395
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 396
            model.addAttribute("start", offset + 1);
397
            model.addAttribute("size", size);
398
            model.addAttribute("url", "/getPaginatedWalletApproved");
23993 tejbeer 399
 
32491 jai.hind 400
            if (walletRequest.size() < limit) {
401
                model.addAttribute("end", offset + walletRequest.size());
402
            } else {
403
                model.addAttribute("end", offset + limit);
404
            }
405
        } else {
23993 tejbeer 406
 
32491 jai.hind 407
            model.addAttribute("walletRequest", walletRequest);
408
            model.addAttribute("size", size);
23936 tejbeer 409
 
32491 jai.hind 410
        }
34096 aman.kumar 411
        return "add-wallet-request-paginated";
32491 jai.hind 412
    }
23936 tejbeer 413
 
32491 jai.hind 414
    @RequestMapping(value = "/getPaginatedWalletApproved", method = RequestMethod.GET)
34096 aman.kumar 415
    public String getPaginatedWalletApproved(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
416
                                             @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 417
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
418
        List<AddWalletRequest> walletRequest = null;
34096 aman.kumar 419
        long size = 0;
420
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.approved);
421
 
422
//        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.approved);
32491 jai.hind 423
        LOGGER.info("walletRequest" + walletRequest);
424
        if (!walletRequest.isEmpty()) {
425
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
426
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 427
 
32495 amit.gupta 428
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 429
 
32491 jai.hind 430
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
431
            model.addAttribute("walletRequest", walletRequest);
36242 aman 432
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 433
            model.addAttribute("url", "/getPaginatedWalletApproved");
434
        } else {
435
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 436
 
32491 jai.hind 437
        }
438
        return "add-wallet-request-paginated";
439
    }
23993 tejbeer 440
 
32491 jai.hind 441
    @RequestMapping(value = "/getAddWalletRequestRejected", method = RequestMethod.GET)
34096 aman.kumar 442
    public String walletAddnReject(HttpServletRequest request, Model model) throws Exception {
443
 
444
        return "add-wallet-rejected";
445
    }
446
 
447
    @RequestMapping(value = "/getAddWalletRequestRejectedByDate", method = RequestMethod.GET)
448
    public String getAddwalletRequestRejected(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
449
                                              @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 450
        List<AddWalletRequest> walletRequest = null;
23985 tejbeer 451
 
32491 jai.hind 452
        long size = 0;
34096 aman.kumar 453
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.rejected);
32491 jai.hind 454
        size = addWalletRequestRepository.selectCountByStatus(AddWalletRequestStatus.rejected);
455
        LOGGER.info("walletRequest" + walletRequest);
456
        if (!walletRequest.isEmpty()) {
457
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
458
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 459
 
32495 amit.gupta 460
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 461
 
32491 jai.hind 462
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
463
            model.addAttribute("walletRequest", walletRequest);
36242 aman 464
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 465
            model.addAttribute("start", offset + 1);
466
            model.addAttribute("size", size);
467
            model.addAttribute("url", "/getPaginatedWalletRequestRejected");
23985 tejbeer 468
 
32491 jai.hind 469
            if (walletRequest.size() < limit) {
470
                model.addAttribute("end", offset + walletRequest.size());
471
            } else {
472
                model.addAttribute("end", offset + limit);
473
            }
474
        } else {
475
            model.addAttribute("walletRequest", walletRequest);
476
            model.addAttribute("size", size);
477
        }
23993 tejbeer 478
 
34096 aman.kumar 479
        return "add-wallet-request-paginated";
32491 jai.hind 480
    }
23985 tejbeer 481
 
32491 jai.hind 482
    @RequestMapping(value = "/getPaginatedWalletRequestRejected", method = RequestMethod.GET)
34096 aman.kumar 483
    public String getPaginatedWalletRequestRejected(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
484
                                                    @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 485
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
486
        List<AddWalletRequest> walletRequest = null;
34096 aman.kumar 487
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.rejected);
32491 jai.hind 488
        LOGGER.info("walletRequest" + walletRequest);
489
        if (!walletRequest.isEmpty()) {
490
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
491
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
23993 tejbeer 492
 
32495 amit.gupta 493
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
32491 jai.hind 494
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
495
            model.addAttribute("walletRequest", walletRequest);
36242 aman 496
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 497
            model.addAttribute("url", "/getPaginatedWalletRequestRejected");
498
        } else {
499
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 500
 
32491 jai.hind 501
        }
23993 tejbeer 502
 
32491 jai.hind 503
        return "add-wallet-request-paginated";
504
    }
23993 tejbeer 505
 
35197 amit 506
    @Autowired
507
    HdfcPaymentRepository hdfcPaymentRepository;
508
 
32491 jai.hind 509
    @RequestMapping(value = "/addAmountToWallet", method = RequestMethod.PUT)
32495 amit.gupta 510
    public String addAmountToWallet(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, @RequestParam(name = "walletRequestid", defaultValue = "0") int walletRequestid, Model model) throws Exception {
23993 tejbeer 511
 
32491 jai.hind 512
        AddWalletRequest addWalletRequest = addWalletRequestRepository.selectById(walletRequestid);
35197 amit 513
        List<AddWalletRequest> requests = addWalletRequestRepository.selectAllByTransactionReference(addWalletRequest.getTransaction_reference());
36904 aman 514
        // Scope the duplicate-reference check to the SAME retailer. Reference numbers
515
        // (e.g. cheque numbers like "000310") are not globally unique and collide across
516
        // partners; without this filter a legitimate payment is wrongly blocked as
517
        // "Entry already Approved Please reject" because a different store used the same ref.
518
        if (requests.stream().filter(x -> x.getId() != addWalletRequest.getId()).filter(x -> x.getRetailerId() == addWalletRequest.getRetailerId()).filter(x -> x.getStatus().equals(approved)).count() != 1) {
35197 amit 519
            HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(addWalletRequest.getTransaction_reference());
36944 amit 520
            // Block only when the UTR was actually auto-credited to a wallet. Since r36927,
521
            // hdfc_payment also holds merely-captured rows (VA missing/unmatched) that never
522
            // credited — those MUST be approvable here, so guard on the credited flag, not
523
            // mere row existence.
524
            if (hdfcPayment != null && hdfcPayment.isCredited()) {
35197 amit 525
                String rejectReason = "Payment for UTR Already added via Auto Update";
526
                throw new ProfitMandiBusinessException(rejectReason, rejectReason, rejectReason);
527
            }
528
        } else {
529
            String rejectReason = "Entry already Approved Please reject";
530
            throw new ProfitMandiBusinessException(rejectReason, rejectReason, rejectReason);
531
        }
35971 aman 532
        // FSP wallet addons can only be approved by Account team L3
533
        if (addWalletRequest.getFspId() > 0) {
534
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
535
            String approverEmail = loginDetails.getEmailId();
536
            com.spice.profitmandi.dao.entity.auth.AuthUser approverUser = authRepository.selectByEmailOrMobile(approverEmail);
537
            boolean isAccountL3 = false;
538
            if (approverUser != null) {
539
                List<com.spice.profitmandi.dao.entity.cs.Position> positions = positionRepository.selectPositionByAuthId(approverUser.getId());
540
                for (com.spice.profitmandi.dao.entity.cs.Position position : positions) {
541
                    if (position.getEscalationType().equals(com.spice.profitmandi.dao.enumuration.cs.EscalationType.L3)
542
                            && position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS) {
543
                        isAccountL3 = true;
544
                        break;
545
                    }
546
                }
547
            }
548
            if (!isAccountL3) {
549
                throw new ProfitMandiBusinessException(
550
                        "Only Account team L3 can approve Full Stock Payment entries",
551
                        approverEmail,
552
                        "You are not authorized to approve FSP wallet requests");
553
            }
554
        }
555
 
32491 jai.hind 556
        if (addWalletRequest.getStatus().equals(AddWalletRequestStatus.pending)) {
37865 amit 557
            walletService.addAmountToWallet(addWalletRequest.getRetailerId(), walletRequestid, WalletReferenceType.ADVANCE_AMOUNT, "ntfs/rgfs", addWalletRequest.getAmount(), addWalletRequest.getReference_date().atStartOfDay());
32491 jai.hind 558
            addWalletRequest.setStatus(AddWalletRequestStatus.approved);
559
            addWalletRequest.setUpdateTimestamp(LocalDateTime.now());
36965 amit 560
            // If this manual top-up recovers a captured HDFC payment (same UTR), mark that row
561
            // credited so the flag means "credited by any path" — prevents a later duplicate
562
            // approval or re-pushed HDFC credit from topping up the same UTR again. Managed
563
            // entity, so the flag flushes as an UPDATE at commit.
564
            HdfcPayment recoveredHdfcPayment = hdfcPaymentRepository.selectByUtrNo(addWalletRequest.getTransaction_reference());
565
            if (recoveredHdfcPayment != null) {
566
                recoveredHdfcPayment.setCredited(true);
567
            }
32491 jai.hind 568
            unsettledPaymentsRepository.deleteById(id);
33861 tejus.loha 569
 
570
            // check full stock payment if partner comes from Loi process
571
            String code = fofoStoreRepository.selectByRetailerId(addWalletRequest.getRetailerId()).getCode();
572
            StoreTimelineModel storeTimelineModel = partnerOnBoardingPanelRepository.selectStoreTimeLine(code);
573
            if (storeTimelineModel != null && storeTimelineModel.getFullStockTimestamp() == null) {
574
                UserWallet userWallet = userWalletRepository.selectByRetailerId(addWalletRequest.getRetailerId());
575
                List<UserWalletHistory> userWalletHistories = userWalletHistoryRepository.selectByWalletIdAndReferenceType(userWallet.getId(), WalletReferenceType.ADVANCE_AMOUNT);
576
                long totalAdvanceAmount = userWalletHistories.stream().mapToLong(x -> x.getAmount()).sum();
577
                LOGGER.info("totalAdvanceAmount - " + totalAdvanceAmount);
35971 aman 578
                if (totalAdvanceAmount >= ProfitMandiConstants.FSP_DIRECT_WALLET_THRESHOLD) {
33861 tejus.loha 579
                    storeTimelineTatService.onFullPaymentReceived(storeTimelineModel.getOnboardingId());
580
                }
35971 aman 581
 
582
                // Mark linked FullStockPayment record as APPROVED via fspId
583
                if (addWalletRequest.getFspId() > 0) {
584
                    FullStockPayment fsp = fullStockPaymentRepository.selectById(addWalletRequest.getFspId());
585
                    if (fsp != null && fsp.getPaymentStatus() == FullStockPaymentStatus.PENDING) {
586
                        fsp.setPaymentStatus(FullStockPaymentStatus.APPROVED);
587
                        fsp.setApproveTimestamp(LocalDateTime.now());
588
                        fullStockPaymentRepository.persist(fsp);
589
                        LOGGER.info("Marked FSP id={} as APPROVED via wallet addon approval, onboardingId={}", fsp.getId(), storeTimelineModel.getOnboardingId());
590
                    }
591
                }
592
 
593
                // Auto-mark FULL_STOCK_PAYMENT in timeline when total approved FSP amount >= 7 lakh
594
                double totalApprovedFsp = fullStockPaymentRepository.selectByOnboardingId(storeTimelineModel.getOnboardingId())
595
                        .stream()
596
                        .filter(p -> p.getPaymentStatus() == FullStockPaymentStatus.APPROVED)
597
                        .mapToDouble(FullStockPayment::getCollectedAmount)
598
                        .sum();
599
                LOGGER.info("totalApprovedFsp={} for onboardingId={}", totalApprovedFsp, storeTimelineModel.getOnboardingId());
600
                if (totalApprovedFsp >= ProfitMandiConstants.FSP_DIRECT_WALLET_THRESHOLD) {
601
                    storeTimelineTatService.onFullPaymentReceived(storeTimelineModel.getOnboardingId());
602
                    LOGGER.info("Auto-marked FULL_STOCK_PAYMENT done for onboardingId={}, totalApprovedFsp={}", storeTimelineModel.getOnboardingId(), totalApprovedFsp);
36064 aman 603
                    try {
604
                        storeTimelineTatService.sendFullStockPaymentPOEmail(storeTimelineModel.getOnboardingId());
605
                    } catch (Exception ex) {
606
                        LOGGER.error("Failed to send FSP PO email after approved FSP >= 7L for onboardingId=" + storeTimelineModel.getOnboardingId(), ex);
607
                    }
35971 aman 608
                }
33861 tejus.loha 609
            }
610
 
32491 jai.hind 611
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
612
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 613
            String subject = "Request Approved for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
614
            String messageText = MessageFormat.format("User Id - {0}\n Name -{1}\n Email -{2}\n mobile -{3}\n Reference - {4}\n Amount - Rs.{5}", new Integer(addWalletRequest.getRetailerId()), customRetailer.getBusinessName(), customRetailer.getEmail(), customRetailer.getMobileNumber(), addWalletRequest.getTransaction_reference(), new Float(addWalletRequest.getAmount()));
23993 tejbeer 615
 
32491 jai.hind 616
            //	this.sendMailWithAttachments(subject, messageText);
617
            return "response";
618
        } else {
619
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
620
            return "response";
621
        }
622
    }
23993 tejbeer 623
 
32491 jai.hind 624
    @RequestMapping(value = "/addAmountToWalletRequestRejected", method = RequestMethod.PUT)
32495 amit.gupta 625
    public String addAmountToWalletRequestRejected(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
23993 tejbeer 626
 
32491 jai.hind 627
        AddWalletRequest addWalletRequest = addWalletRequestRepository.selectById(id);
628
        if (addWalletRequest.getStatus().equals(AddWalletRequestStatus.pending)) {
629
            addWalletRequest.setStatus(AddWalletRequestStatus.rejected);
630
            addWalletRequest.setUpdateTimestamp(LocalDateTime.now());
631
            addWalletRequestRepository.persist(addWalletRequest);
35971 aman 632
 
633
            // Mark linked FSP as REJECTED via fspId
634
            if (addWalletRequest.getFspId() > 0) {
635
                try {
636
                    FullStockPayment fsp = fullStockPaymentRepository.selectById(addWalletRequest.getFspId());
637
                    if (fsp != null && fsp.getPaymentStatus() == FullStockPaymentStatus.PENDING) {
638
                        fsp.setPaymentStatus(FullStockPaymentStatus.REJECTED);
639
                        fsp.setDescription("Wallet addon request rejected");
640
                        fsp.setApproveTimestamp(LocalDateTime.now());
641
                        fullStockPaymentRepository.persist(fsp);
642
                        LOGGER.info("Marked FSP id={} as REJECTED via wallet addon rejection", fsp.getId());
643
                    }
644
                } catch (Exception e) {
645
                    LOGGER.error("Error marking FSP as REJECTED on wallet addon rejection", e);
646
                }
647
            }
648
 
32491 jai.hind 649
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
650
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 651
            String subject = "Request Rejected for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
652
            String messageText = MessageFormat.format("User Id - {0}\n Name -{1}\n Email -{2}\n mobile -{3}\n Reference - {4}\n Amount - Rs.{5}", new Integer(addWalletRequest.getRetailerId()), customRetailer.getBusinessName(), customRetailer.getEmail(), customRetailer.getMobileNumber(), addWalletRequest.getTransaction_reference(), new Float(addWalletRequest.getAmount()));
23993 tejbeer 653
 
32491 jai.hind 654
            //this.sendMailWithAttachments(subject, messageText);
655
            return "response";
656
        } else {
657
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
658
            return "response";
659
        }
660
    }
23985 tejbeer 661
 
32491 jai.hind 662
    private void sendMailWithAttachments(String subject, String messageText) throws Exception {
36401 amit 663
        MimeMessage message = gmailRelaySender.createMimeMessage();
32491 jai.hind 664
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
37630 amit 665
        String[] email = {"neerajgupta2021@gmail.com", "kamini.sharma@smartdukaan.com", "care@smartdukaan.com", "mohinder.mutreja@smartdukaan.com"};
32491 jai.hind 666
        helper.setSubject(subject);
667
        helper.setText(messageText);
668
        helper.setTo(email);
669
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
670
        helper.setFrom(senderAddress);
36401 amit 671
        gmailRelaySender.send(message);
23993 tejbeer 672
 
32491 jai.hind 673
    }
23936 tejbeer 674
 
32491 jai.hind 675
    private List<Integer> getFofoIdsFromWalletRequest(List<AddWalletRequest> walletRequest) {
676
        return walletRequest.stream().map(x -> x.getRetailerId()).distinct().collect(Collectors.toList());
677
    }
24089 tejbeer 678
 
36242 aman 679
    /**
680
     * Builds a map of AddWalletRequest.id -> FullStockPayment.attachment for requests linked to FSP.
681
     */
682
    private Map<Integer, Integer> buildFspAttachmentMap(List<AddWalletRequest> walletRequests) {
683
        Map<Integer, Integer> attachmentMap = new HashMap<>();
684
        List<Integer> fspIds = walletRequests.stream()
685
                .filter(r -> r.getFspId() > 0)
686
                .map(AddWalletRequest::getFspId)
687
                .distinct()
688
                .collect(Collectors.toList());
689
        if (fspIds.isEmpty()) {
690
            return attachmentMap;
691
        }
692
        List<FullStockPayment> fspList = fullStockPaymentRepository.selectByIds(fspIds);
693
        Map<Integer, Integer> fspIdToAttachment = fspList.stream()
694
                .filter(f -> f.getAttachment() > 0)
695
                .collect(Collectors.toMap(FullStockPayment::getId, FullStockPayment::getAttachment));
696
        for (AddWalletRequest r : walletRequests) {
697
            if (r.getFspId() > 0 && fspIdToAttachment.containsKey(r.getFspId())) {
698
                attachmentMap.put(r.getId(), fspIdToAttachment.get(r.getFspId()));
699
            }
700
        }
701
        return attachmentMap;
702
    }
703
 
704
    /**
705
     * Builds a map of UserWalletHistory.id -> FullStockPayment.attachment for ADVANCE_AMOUNT entries linked to FSP.
706
     */
707
    private Map<Integer, Integer> buildWalletHistoryAttachmentMap(List<UserWalletHistory> histories) {
708
        Map<Integer, Integer> attachmentMap = new HashMap<>();
709
        List<Integer> awrIds = histories.stream()
710
                .filter(h -> h.getReferenceType() == WalletReferenceType.ADVANCE_AMOUNT && h.getReference() > 0)
711
                .map(UserWalletHistory::getReference)
712
                .distinct()
713
                .collect(Collectors.toList());
714
        if (awrIds.isEmpty()) {
715
            return attachmentMap;
716
        }
717
        List<AddWalletRequest> awrList = addWalletRequestRepository.selectByIds(awrIds);
718
        Map<Integer, Integer> awrIdToFspId = awrList.stream()
719
                .filter(r -> r.getFspId() > 0)
720
                .collect(Collectors.toMap(AddWalletRequest::getId, AddWalletRequest::getFspId));
721
        List<Integer> fspIds = awrIdToFspId.values().stream().distinct().collect(Collectors.toList());
722
        if (fspIds.isEmpty()) {
723
            return attachmentMap;
724
        }
725
        List<FullStockPayment> fspList = fullStockPaymentRepository.selectByIds(fspIds);
726
        Map<Integer, Integer> fspIdToAttachment = fspList.stream()
727
                .filter(f -> f.getAttachment() > 0)
728
                .collect(Collectors.toMap(FullStockPayment::getId, FullStockPayment::getAttachment));
729
        for (UserWalletHistory h : histories) {
730
            if (h.getReferenceType() == WalletReferenceType.ADVANCE_AMOUNT && h.getReference() > 0) {
731
                Integer fspId = awrIdToFspId.get(h.getReference());
732
                if (fspId != null && fspIdToAttachment.containsKey(fspId)) {
733
                    attachmentMap.put(h.getId(), fspIdToAttachment.get(fspId));
734
                }
735
            }
736
        }
737
        return attachmentMap;
738
    }
739
 
32491 jai.hind 740
    @RequestMapping(value = "/getcreateUnsettledPayments", method = RequestMethod.GET)
32495 amit.gupta 741
    public String getcreateUnsettledPayment(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "15") int limit, Model model) throws Exception {
32491 jai.hind 742
        List<UnsettledPayment> up = null;
24089 tejbeer 743
 
32491 jai.hind 744
        long size = 0;
745
        up = unsettledPaymentsRepository.selectAllById(offset, limit);
24089 tejbeer 746
 
32491 jai.hind 747
        size = unsettledPaymentsRepository.selectAllCount();
748
        if (!up.isEmpty()) {
749
            model.addAttribute("unsettledPayment", up);
750
            model.addAttribute("start", offset + 1);
751
            model.addAttribute("size", size);
752
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 753
 
32491 jai.hind 754
            if (up.size() < limit) {
755
                model.addAttribute("end", offset + up.size());
756
            } else {
757
                model.addAttribute("end", offset + limit);
758
            }
759
        } else {
760
            model.addAttribute("unsettledPayment", up);
761
            model.addAttribute("size", size);
762
        }
24089 tejbeer 763
 
32491 jai.hind 764
        LOGGER.info("unsettledPaymentList" + up);
765
        return "unsettled-payments";
766
    }
24089 tejbeer 767
 
32491 jai.hind 768
    @RequestMapping(value = "/getUnsettledPaymentsByAmount", method = RequestMethod.GET)
32495 amit.gupta 769
    public String getUnsettledPaymentByAmount(HttpServletRequest request, @RequestParam(name = "amount", defaultValue = "0") float amount, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws Exception {
32491 jai.hind 770
        List<UnsettledPayment> up = null;
24089 tejbeer 771
 
32491 jai.hind 772
        long size = 0;
773
        up = unsettledPaymentsRepository.selectAllByAmount(amount, offset, limit);
24089 tejbeer 774
 
32491 jai.hind 775
        size = unsettledPaymentsRepository.selectAllCount();
776
        if (!up.isEmpty()) {
777
            model.addAttribute("unsettledPayment", up);
778
            model.addAttribute("start", offset + 1);
779
            model.addAttribute("size", size);
780
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 781
 
32491 jai.hind 782
            if (up.size() < limit) {
783
                model.addAttribute("end", offset + up.size());
784
            } else {
785
                model.addAttribute("end", offset + limit);
786
            }
787
            return "unsettle-payment-modal";
788
        } else {
789
            model.addAttribute("unsettledPayment", up);
790
            model.addAttribute("size", size);
791
        }
24089 tejbeer 792
 
32491 jai.hind 793
        return "unsettle-payment-modal";
794
    }
24089 tejbeer 795
 
32491 jai.hind 796
    @RequestMapping(value = "/createUnsettledPaymentsEntries", method = RequestMethod.POST)
32495 amit.gupta 797
    public String createUnsettledPaymentsEntries(HttpServletRequest request, @RequestBody UnsettledPaymentModel unsettledPaymentModel, Model model) throws Exception {
24089 tejbeer 798
 
32491 jai.hind 799
        UnsettledPayment up = new UnsettledPayment();
800
        up.setTransaction_reference(unsettledPaymentModel.getTransactionReference());
801
        up.setAmount(unsettledPaymentModel.getAmount());
802
        up.setDescription(unsettledPaymentModel.getDescription());
803
        up.setReference_date(unsettledPaymentModel.getReferenceDate());
804
        LOGGER.info("uppaynments" + up);
805
        unsettledPaymentsRepository.persist(up);
806
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
807
        return "response";
808
    }
24089 tejbeer 809
 
32491 jai.hind 810
    @RequestMapping(value = "/removeUnsettledPaymentsEntries", method = RequestMethod.DELETE)
32495 amit.gupta 811
    public String removeUnsettledPaymentsEntries(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
24089 tejbeer 812
 
32491 jai.hind 813
        unsettledPaymentsRepository.deleteById(id);
24089 tejbeer 814
 
32491 jai.hind 815
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
816
        return "response";
817
    }
24509 amit.gupta 818
 
32491 jai.hind 819
    @RequestMapping(value = "/wallet/statement", method = RequestMethod.GET)
32495 amit.gupta 820
    public String getWalletStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
32491 jai.hind 821
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
34441 tejus.loha 822
        if (!isAdmin) {
823
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
824
        }
32491 jai.hind 825
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
826
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32495 amit.gupta 827
        List<UserWalletHistory> uwhList = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDate, endDate, 0, 0);
32491 jai.hind 828
        Collections.reverse(uwhList);
829
        model.addAttribute("opening", openingBalance);
830
        model.addAttribute("closing", closingBalance);
831
        model.addAttribute("history", uwhList);
832
        model.addAttribute("startDate", startDate);
833
        model.addAttribute("endDate", endDate);
834
        return "walletStatement";
835
    }
29811 tejbeer 836
 
32491 jai.hind 837
    @RequestMapping(value = "/account/reco", method = RequestMethod.GET)
32495 amit.gupta 838
    public ResponseEntity<?> accountReco(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 839
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
840
        if (!isAdmin) {
841
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
842
        }
33207 amit.gupta 843
        LocalDateTime closingDateTime = closingDate.plusDays(1).atStartOfDay();
32491 jai.hind 844
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
845
        Set<Integer> retailersSet = customRetailerMap.keySet();
29070 amit.gupta 846
 
32491 jai.hind 847
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 848
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
36775 amit 849
        Set<Integer> walletSet = walletRetailerMap.keySet();
29811 tejbeer 850
 
36775 amit 851
        // Closing uses the SAME model as the individual account statement (/account/statement):
852
        //   Closing Balance = wallet balance + pending indent (in-transit orders) − loan outstanding (principal + interest)
32491 jai.hind 853
        Map<Integer, Float> closingWalletMap = userWalletHistoryRepository.getSumTillDate(closingDateTime, walletSet);
33212 amit.gupta 854
        Map<Integer, Float> peindingIndentMap = transactionService.getPendingIndentValueMap(closingDateTime, Optional.empty());
36775 amit 855
        Map<Integer, Float> loanOutstandingMap = loanStatementRepository.getLoanOutstandingAtDate(retailersSet, closingDateTime);
29811 tejbeer 856
 
32491 jai.hind 857
        List<List<?>> rows = new ArrayList<>();
36775 amit 858
        for (Map.Entry<Integer, Float> closingWalletEntry : closingWalletMap.entrySet()) {
859
            int walletId = closingWalletEntry.getKey();
32491 jai.hind 860
            int retailerId = walletRetailerMap.get(walletId);
29811 tejbeer 861
 
36775 amit 862
            float wallet = closingWalletEntry.getValue() == null ? 0f : closingWalletEntry.getValue();
863
            float pendingIndent = peindingIndentMap.getOrDefault(retailerId, 0f);
37590 amit 864
        float loanOutstanding = loanOutstandingMap.getOrDefault(retailerId, 0f);
37539 amit 865
            float accountClosing = wallet + pendingIndent;
29070 amit.gupta 866
 
32491 jai.hind 867
            CustomRetailer cr = customRetailerMap.get(retailerId);
29070 amit.gupta 868
 
36775 amit 869
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), accountClosing, wallet, pendingIndent, loanOutstanding));
32491 jai.hind 870
        }
29070 amit.gupta 871
 
36780 amit 872
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance", "Closing Wallet", "Unbilled PO", "Loan Outstanding"), rows);
32491 jai.hind 873
        final HttpHeaders headers = new HttpHeaders();
874
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 875
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 876
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
29070 amit.gupta 877
 
32491 jai.hind 878
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
879
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
880
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
881
    }
29811 tejbeer 882
 
32491 jai.hind 883
    @RequestMapping(value = "/account/statement", method = RequestMethod.GET)
32495 amit.gupta 884
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
34440 amit.gupta 885
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
886
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
887
        if (!isAdmin) {
888
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
889
        }
33212 amit.gupta 890
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
891
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32491 jai.hind 892
        UserWallet uw = walletService.getUserWallet(fofoId);
33220 amit.gupta 893
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
32495 amit.gupta 894
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
33220 amit.gupta 895
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
36772 amit 896
        // Raw scheme entries (CN_WALLET_REFERENCES) are normally shown as the month-end MARGINS credit-note line; but for a
897
        // statement that does NOT end on a month-end the trailing month's CN isn't issued yet, so we fall back to these
898
        // raw entries for that partial month (see populateData).
899
        List<UserWalletHistory> schemeEntries = history.stream()
900
                .filter(x -> WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType()))
901
                .sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
36831 amit 902
        // Body shows wallet movements. Exclude only: PURCHASE (rebuilt via billing) and the scheme set
903
        // CN_WALLET_REFERENCES (shown instead as the month-end MARGINS credit-note line / partial fallback).
904
        // Loan/credit legs (CREDIT_LIMIT/CREDIT_UTILIZED/LOAN/LOAN_REPAYMENT) are kept so the body reconciles to
905
        // the loan-free closing (wallet + pending indent); loan is not represented separately in this statement.
33205 amit.gupta 906
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
36754 amit 907
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType()))
908
                .sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
33205 amit.gupta 909
 
32491 jai.hind 910
        InputStream is = getClass().getClassLoader().getResourceAsStream("account-statement.xlsx");
33205 amit.gupta 911
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
33225 amit.gupta 912
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
36754 amit 913
        List<StatementDetailModel> returnDetails = returnOrderInfoRepository.selectReturnsBetween(fofoId, startDate, endDate);
33212 amit.gupta 914
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
915
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
28515 amit.gupta 916
 
33212 amit.gupta 917
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
918
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
36831 amit 919
        LOGGER.info("OpeningPI - {}, ClosingPI - {}", openingPendingAmount, closingPendingAmount);
920
        ByteArrayOutputStream byteArrayOutputStream = this.populateData(is, openingBalance + openingPendingAmount, closingBalance + closingPendingAmount,
921
                customRetailer, history, startDate, endDate, billedStatementDetails, returnDetails, schemeEntries);
33212 amit.gupta 922
 
32491 jai.hind 923
        final HttpHeaders headers = new HttpHeaders();
924
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
32495 amit.gupta 925
        headers.set("Content-disposition", "inline; filename=account-statement." + StringUtils.toHyphenatedString(startDate.toLocalDate()) + "-" + StringUtils.toHyphenatedString(endDate.toLocalDate()) + ".xlsx");
32491 jai.hind 926
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28515 amit.gupta 927
 
32491 jai.hind 928
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
929
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28515 amit.gupta 930
 
32491 jai.hind 931
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28515 amit.gupta 932
 
32491 jai.hind 933
    }
28597 amit.gupta 934
 
33205 amit.gupta 935
    @Autowired
936
    CreditNoteRepository creditNoteRepository;
937
    @Autowired
938
    CreditNoteLineRepository creditNoteLineRepository;
939
 
36754 amit 940
    // Friendly category for a statement line, keyed on the wallet reference-type or billing sub-type string.
941
    private String statementCategory(String type) {
942
        if (type == null) return "Other";
943
        switch (type) {
944
            case "ADVANCE_AMOUNT": case "AUTOMATED_ADVANCE": return "Advance / Payment";
945
            case "PAYMENT_GATEWAY": case "RECHARGE": return "Payment";
946
            case "SCHEME_IN": case "SCHEME_OUT": case "ADDITIONAL_SCHEME": case "ACTIVATION_SCHEME": return "Scheme / Margin";
947
            case "CREDIT_LIMIT": case "CREDIT_UTILIZED": return "SD Credit (Loan)";
948
            case "PURCHASE": return "Purchase / Order Refund";
949
            case "REFUND": return "Refund";
950
            case "PRICE_DROP": return "Price Drop";
951
            case "BRAND_PAYOUT": case "INVESTMENT_PAYOUT": return "Payout";
952
            case "SPECIAL_SUPPORT": return "Special Support";
953
            case "DAMAGE_PROTECTION": return "Damage Protection";
954
            case "PREBOOKING_ORDER": return "Prebooking Order";
955
            // billing sub-types from selectDetailsBetween
956
            case "BILLED": return "Billing / Invoice";
957
            case "RTO": return "Cancellation (RTO)";
958
            case "RETURNED": return "Return";
959
            case "INVOICE_CANCELLED": return "Invoice Cancelled";
960
            case "RETURNS_CN": return "Return (Credit Note)";
961
            default: return "Other";
962
        }
963
    }
964
 
33205 amit.gupta 965
    private ByteArrayOutputStream populateData(InputStream is, float openingBalance, float closingBalance, CustomRetailer customRetailer, List<UserWalletHistory> history,
36754 amit 966
                                               LocalDateTime startLocalDateTime, LocalDateTime endLocalDateTime, List<StatementDetailModel> invoiceDetails,
36831 amit 967
                                               List<StatementDetailModel> returnDetails, List<UserWalletHistory> schemeEntries) throws Exception {
33205 amit.gupta 968
        Map<LocalDate, List<StatementDetailModel>> dateInvoiceMap = invoiceDetails.stream().collect(Collectors.groupingBy(x -> x.getOnDate().toLocalDate()));
36754 amit 969
        Map<LocalDate, List<StatementDetailModel>> dateReturnMap = returnDetails == null ? new HashMap<>()
970
                : returnDetails.stream().collect(Collectors.groupingBy(x -> x.getOnDate().toLocalDate()));
33220 amit.gupta 971
        //LOGGER.info("dateInvoiceMap - {}", dateInvoiceMap);
972
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
32491 jai.hind 973
        XSSFWorkbook workbook = new XSSFWorkbook(is);
974
        CreationHelper creationHelper = workbook.getCreationHelper();
33226 amit.gupta 975
        CellStyle dateStyle = workbook.createCellStyle();
976
        dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dd/mm/yyyy"));
28597 amit.gupta 977
 
32491 jai.hind 978
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
979
        Sheet sheet = workbook.getSheetAt(0);
33205 amit.gupta 980
        sheet.getRow(0).getCell(0).setCellValue(customRetailer.getBusinessName());
981
        sheet.getRow(1).getCell(1).setCellValue(new Date(startLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
982
        sheet.getRow(1).getCell(2).setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
32491 jai.hind 983
        sheet.getRow(2).getCell(2).setCellValue(openingBalance);
984
        long grandTotalDebit = 0l;
985
        long grandTotalCredit = 0l;
986
        int row = 4;
33212 amit.gupta 987
        LocalDate startDate = startLocalDateTime.toLocalDate();
33205 amit.gupta 988
        LocalDate endDate = endLocalDateTime.toLocalDate();
33220 amit.gupta 989
        LOGGER.info(" startDate - {}", startDate);
990
        LOGGER.info(" endDate - {}", endDate);
33226 amit.gupta 991
        double currentOpening = openingBalance;
33212 amit.gupta 992
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
993
            List<UserWalletHistory> datewiseWalletHistory = dateWalletMap.get(date);
33220 amit.gupta 994
            LOGGER.info("date - {}, datewiseWalletHistory - {}", date, datewiseWalletHistory);
33212 amit.gupta 995
            if (datewiseWalletHistory != null) {
996
                for (UserWalletHistory walletEntry : datewiseWalletHistory) {
997
                    Cell dateCell = sheet.createRow(row).createCell(0);
33226 amit.gupta 998
                    //Date
33212 amit.gupta 999
                    dateCell.setCellValue(new Date(walletEntry.getTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 1000
                    dateCell.setCellStyle(dateStyle);
1001
                    //TransactType
33212 amit.gupta 1002
                    sheet.getRow(row).createCell(1).setCellValue(walletEntry.getReferenceType().toString());
33226 amit.gupta 1003
                    //Reference Id
33227 amit.gupta 1004
                    sheet.getRow(row).createCell(2).setCellValue(walletEntry.getReference());
33212 amit.gupta 1005
                    if (walletEntry.getAmount() > 0) {
33226 amit.gupta 1006
                        //Debit
33227 amit.gupta 1007
                        sheet.getRow(row).createCell(3).setCellValue(0);
33226 amit.gupta 1008
                        //Credit
33227 amit.gupta 1009
                        sheet.getRow(row).createCell(4).setCellValue(walletEntry.getAmount());
33212 amit.gupta 1010
                        grandTotalCredit += walletEntry.getAmount();
1011
                    } else {
33227 amit.gupta 1012
                        sheet.getRow(row).createCell(3).setCellValue(-walletEntry.getAmount());
1013
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 1014
                        grandTotalDebit -= walletEntry.getAmount();
1015
                    }
33226 amit.gupta 1016
                    //Running balance
1017
                    currentOpening += walletEntry.getAmount();
33227 amit.gupta 1018
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
36754 amit 1019
                    //Category + Description
1020
                    String wCategory = statementCategory(walletEntry.getReferenceType().toString());
1021
                    String wDesc = walletEntry.getDescription();
1022
                    sheet.getRow(row).createCell(6).setCellValue(wDesc == null || wDesc.isEmpty() ? wCategory : wCategory + " — " + wDesc);
33212 amit.gupta 1023
                    row++;
1024
                }
1025
            }
1026
            List<StatementDetailModel> statementDetailModels = dateInvoiceMap.get(date);
1027
            LOGGER.info("statementDetailModels - {}", statementDetailModels);
1028
            if (statementDetailModels != null) {
1029
                for (StatementDetailModel statementDetailModel : statementDetailModels) {
36754 amit 1030
                    // Returns are shown individually from returnorderinfo below; skip the billing query's aggregated
1031
                    // RETURNED and the RETURNS_CN (returns are not taken from credit notes).
1032
                    if ("RETURNED".equals(statementDetailModel.getReferenceType())
1033
                            || "RETURNS_CN".equals(statementDetailModel.getReferenceType())) {
1034
                        continue;
1035
                    }
33212 amit.gupta 1036
                    Cell dateCell = sheet.createRow(row).createCell(0);
1037
                    dateCell.setCellValue(statementDetailModel.getOnDate());
33226 amit.gupta 1038
                    dateCell.setCellStyle(dateStyle);
1039
                    //Transact Type
33212 amit.gupta 1040
                    sheet.getRow(row).createCell(1).setCellValue("BILLING");
33226 amit.gupta 1041
                    //Transact Reference
33227 amit.gupta 1042
                    sheet.getRow(row).createCell(2).setCellValue(statementDetailModel.getInvoiceNumber());
33212 amit.gupta 1043
                    if (statementDetailModel.getAmount() > 0) {
33227 amit.gupta 1044
                        sheet.getRow(row).createCell(3).setCellValue(statementDetailModel.getAmount());
1045
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 1046
                        grandTotalDebit += statementDetailModel.getAmount();
1047
                    } else {
33227 amit.gupta 1048
                        sheet.getRow(row).createCell(3).setCellValue(0);
1049
                        sheet.getRow(row).createCell(4).setCellValue(-statementDetailModel.getAmount());
33212 amit.gupta 1050
                        grandTotalCredit += -statementDetailModel.getAmount();
1051
                    }
33226 amit.gupta 1052
                    //Running Balance
33229 amit.gupta 1053
                    currentOpening -= statementDetailModel.getAmount();
33228 amit.gupta 1054
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33212 amit.gupta 1055
 
33226 amit.gupta 1056
 
36754 amit 1057
                    //Category (Narration)
1058
                    sheet.getRow(row).createCell(6).setCellValue(statementCategory(statementDetailModel.getReferenceType()) + " (" + statementDetailModel.getReferenceType() + ")");
33212 amit.gupta 1059
 
1060
                    row += 1;
1061
                }
1062
            }
36754 amit 1063
            // Individual returns (returnorderinfo): one credit line per return, against its invoice, on refundedAt.
1064
            List<StatementDetailModel> dateReturns = dateReturnMap.get(date);
1065
            if (dateReturns != null) {
1066
                for (StatementDetailModel ret : dateReturns) {
1067
                    Cell dateCell = sheet.createRow(row).createCell(0);
1068
                    dateCell.setCellValue(ret.getOnDate());
1069
                    dateCell.setCellStyle(dateStyle);
1070
                    sheet.getRow(row).createCell(1).setCellValue("RETURN");
1071
                    sheet.getRow(row).createCell(2).setCellValue(ret.getInvoiceNumber());
1072
                    sheet.getRow(row).createCell(3).setCellValue(0);
1073
                    sheet.getRow(row).createCell(4).setCellValue(ret.getAmount());
1074
                    grandTotalCredit += ret.getAmount();
1075
                    currentOpening += ret.getAmount();
1076
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
1077
                    sheet.getRow(row).createCell(6).setCellValue("Return (Against Invoice " + ret.getInvoiceNumber() + ")");
1078
                    row += 1;
1079
                }
1080
            }
36772 amit 1081
            // Month-end scheme/margin: one "Margin / Scheme Payout" line PER credit note (MARGINS credit; CN_CANCELLATION
1082
            // debit, reverses a MARGINS CN), keyed by margin_month. RETURNS are sourced from returnorderinfo and skipped.
1083
            // Per CN: net >=0 => credit (CN); net <0 => debit (DN), reducing the balance.
33212 amit.gupta 1084
            if (YearMonth.from(date).atEndOfMonth().equals(date)) {
36831 amit 1085
                YearMonth marginMonth = YearMonth.from(date);
1086
                double cnTotalForMonth = 0d;
1087
                List<CreditNote> creditNotes = creditNoteRepository.selectByMarginMonth(customRetailer.getPartnerId(), marginMonth);
33212 amit.gupta 1088
                if (creditNotes != null) {
1089
                    for (CreditNote creditNote : creditNotes) {
36754 amit 1090
                        if (creditNote.getType() == CreditNoteType.RETURNS) {
1091
                            continue;
1092
                        }
33212 amit.gupta 1093
                        double cnAmount = creditNoteLineRepository.selectAllByCreditNote(creditNote.getId()).stream().collect(Collectors.summingDouble(x -> x.getAmount()));
36754 amit 1094
                        if (creditNote.getType() == CreditNoteType.CN_CANCELLATION) {
1095
                            cnAmount = -cnAmount;
1096
                        }
36772 amit 1097
                        if (Math.abs(cnAmount) <= 0.01) {
1098
                            continue;
1099
                        }
1100
                        boolean isCredit = cnAmount >= 0;
33205 amit.gupta 1101
                        Cell dateCell = sheet.createRow(row).createCell(0);
33212 amit.gupta 1102
                        dateCell.setCellValue(new Date(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 1103
                        dateCell.setCellStyle(dateStyle);
36772 amit 1104
                        sheet.getRow(row).createCell(1).setCellValue("Margin / Scheme Payout");
33227 amit.gupta 1105
                        sheet.getRow(row).createCell(2).setCellValue(creditNote.getCreditNoteNumber());
36772 amit 1106
                        if (isCredit) {
33227 amit.gupta 1107
                            sheet.getRow(row).createCell(3).setCellValue(0);
1108
                            sheet.getRow(row).createCell(4).setCellValue(cnAmount);
36772 amit 1109
                            grandTotalCredit += (long) cnAmount;
33212 amit.gupta 1110
                        } else {
33227 amit.gupta 1111
                            sheet.getRow(row).createCell(3).setCellValue(-cnAmount);
1112
                            sheet.getRow(row).createCell(4).setCellValue(0);
36772 amit 1113
                            grandTotalDebit += (long) -cnAmount;
33205 amit.gupta 1114
                        }
33226 amit.gupta 1115
                        currentOpening += cnAmount;
36831 amit 1116
                        cnTotalForMonth += cnAmount;
33227 amit.gupta 1117
                        sheet.getRow(row).createCell(5).setCellValue(currentOpening);
36772 amit 1118
                        sheet.getRow(row).createCell(6).setCellValue(isCredit ? "Credit Note (CN)" : "Debit Note (DN)");
33205 amit.gupta 1119
                        row += 1;
1120
                    }
1121
                }
36831 amit 1122
                // Reconcile the margin CNs to the actual wallet scheme net for this month. MARGINS CNs are built from
1123
                // GROSS scheme credits and miss same-month scheme REVERSALS (e.g. a "Live Demo ... Converted" -X), but
1124
                // the wallet (and the formula closing) reflect the NET. Post the delta so the running balance lands on
1125
                // the wallet net rather than the CN gross; otherwise it leaks into the FLOAT DIFF line mislabeled as rounding.
1126
                if (schemeEntries != null) {
1127
                    double walletSchemeNet = 0d;
1128
                    for (UserWalletHistory s : schemeEntries) {
1129
                        if (YearMonth.from(s.getTimestamp()).equals(marginMonth)) {
1130
                            walletSchemeNet += s.getAmount();
1131
                        }
1132
                    }
1133
                    double schemeRecon = walletSchemeNet - cnTotalForMonth;
1134
                    if (Math.abs(schemeRecon) > 0.01) {
1135
                        boolean isReconCredit = schemeRecon >= 0;
1136
                        Cell reconDateCell = sheet.createRow(row).createCell(0);
1137
                        reconDateCell.setCellValue(new Date(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
1138
                        reconDateCell.setCellStyle(dateStyle);
1139
                        sheet.getRow(row).createCell(1).setCellValue("Scheme adjustment (per wallet)");
1140
                        sheet.getRow(row).createCell(2).setCellValue("");
1141
                        if (isReconCredit) {
1142
                            sheet.getRow(row).createCell(3).setCellValue(0);
1143
                            sheet.getRow(row).createCell(4).setCellValue(schemeRecon);
1144
                            grandTotalCredit += (long) schemeRecon;
1145
                        } else {
1146
                            sheet.getRow(row).createCell(3).setCellValue(-schemeRecon);
1147
                            sheet.getRow(row).createCell(4).setCellValue(0);
1148
                            grandTotalDebit += (long) -schemeRecon;
1149
                        }
1150
                        currentOpening += schemeRecon;
1151
                        sheet.getRow(row).createCell(5).setCellValue(currentOpening);
1152
                        sheet.getRow(row).createCell(6).setCellValue("Scheme reversals not captured in margin CN (reconciled to wallet)");
1153
                        row += 1;
1154
                    }
1155
                }
33205 amit.gupta 1156
            }
32491 jai.hind 1157
        }
33205 amit.gupta 1158
 
36772 amit 1159
        // Partial-month fallback (net computed here, rendered as ONE line just before the FLOAT DIFF below): if the
1160
        // statement does NOT end on a month-end, the trailing month's MARGINS CN isn't issued yet, so consolidate that
1161
        // month's raw scheme entries into a single line. Full months already used their month-end CN above; only the
1162
        // trailing month's entries are summed here.
1163
        double schemeFallbackNet = 0d;
1164
        if (!YearMonth.from(endDate).atEndOfMonth().equals(endDate) && schemeEntries != null) {
1165
            LocalDate partialStart = YearMonth.from(endDate).atDay(1);
1166
            for (UserWalletHistory s : schemeEntries) {
1167
                if (!s.getTimestamp().toLocalDate().isBefore(partialStart)) {
1168
                    schemeFallbackNet += s.getAmount();
1169
                }
1170
            }
1171
        }
1172
 
36754 amit 1173
        // --- Reconciling lines at period end ---
36831 amit 1174
        // Loan and interest are excluded from the account statement entirely (closing = wallet + pending indent);
1175
        // the loan ledger is tracked separately, not in this statement.
36772 amit 1176
        // Single consolidated scheme/margin line for a partial (non-month-end) trailing month (computed above). Placed
1177
        // here, at the end of the statement just before the float adjustment. Net >=0 => credit (CN); net <0 => debit (DN).
1178
        if (Math.abs(schemeFallbackNet) > 0.01) {
1179
            boolean isCredit = schemeFallbackNet >= 0;
1180
            Cell dateCell = sheet.createRow(row).createCell(0);
1181
            dateCell.setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
1182
            dateCell.setCellStyle(dateStyle);
1183
            sheet.getRow(row).createCell(1).setCellValue("Margin / Scheme Payout");
1184
            sheet.getRow(row).createCell(2).setCellValue("");
1185
            if (isCredit) {
1186
                sheet.getRow(row).createCell(3).setCellValue(0);
1187
                sheet.getRow(row).createCell(4).setCellValue(schemeFallbackNet);
1188
                grandTotalCredit += (long) schemeFallbackNet;
1189
            } else {
1190
                sheet.getRow(row).createCell(3).setCellValue(-schemeFallbackNet);
1191
                sheet.getRow(row).createCell(4).setCellValue(0);
1192
                grandTotalDebit += (long) -schemeFallbackNet;
1193
            }
1194
            currentOpening += schemeFallbackNet;
1195
            sheet.getRow(row).createCell(5).setCellValue(currentOpening);
1196
            sheet.getRow(row).createCell(6).setCellValue(isCredit ? "Credit Note (CN)" : "Debit Note (DN)");
1197
            row++;
1198
        }
36755 amit 1199
        // Float-difference line: lands the running balance exactly on the formula closing. With clean data this is only
1200
        // a few rupees of rounding/float; a large value signals a data issue (e.g. MARGINS CN not yet rolled out) and is
1201
        // surfaced by the reconciliation warning below rather than being a real ledger movement.
1202
        double floatDiff = closingBalance - currentOpening;
1203
        if (Math.abs(floatDiff) > 0.01) {
36754 amit 1204
            Cell dateCell = sheet.createRow(row).createCell(0);
1205
            dateCell.setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
1206
            dateCell.setCellStyle(dateStyle);
36755 amit 1207
            sheet.getRow(row).createCell(1).setCellValue("FLOAT DIFF");
36754 amit 1208
            sheet.getRow(row).createCell(2).setCellValue("");
36755 amit 1209
            if (floatDiff > 0) {
36754 amit 1210
                sheet.getRow(row).createCell(3).setCellValue(0);
36755 amit 1211
                sheet.getRow(row).createCell(4).setCellValue(floatDiff);
1212
                grandTotalCredit += (long) floatDiff;
36754 amit 1213
            } else {
36755 amit 1214
                sheet.getRow(row).createCell(3).setCellValue(-floatDiff);
36754 amit 1215
                sheet.getRow(row).createCell(4).setCellValue(0);
36755 amit 1216
                grandTotalDebit += (long) -floatDiff;
36754 amit 1217
            }
36755 amit 1218
            currentOpening += floatDiff;
36754 amit 1219
            sheet.getRow(row).createCell(5).setCellValue(currentOpening);
36755 amit 1220
            sheet.getRow(row).createCell(6).setCellValue("Rounding / float difference");
36754 amit 1221
            row++;
1222
        }
1223
 
33238 amit.gupta 1224
        sheet.createRow(row).createCell(2).setCellValue("Grand Total");
1225
        sheet.getRow(row).createCell(3).setCellValue(grandTotalDebit);
1226
        sheet.getRow(row).createCell(4).setCellValue(grandTotalCredit);
36754 amit 1227
        row += 2;
32491 jai.hind 1228
        sheet.createRow(row).createCell(0).setCellValue("Closing Balance");
36754 amit 1229
        sheet.getRow(row).createCell(5).setCellValue(closingBalance);
32491 jai.hind 1230
        row++;
36754 amit 1231
        double diff = Math.abs(currentOpening - closingBalance);
1232
        if (diff > 1) {
1233
            LOGGER.warn("Account statement reconciliation mismatch for {}: computed={}, expected={}, diff={}",
1234
                    customRetailer.getPartnerId(), currentOpening, closingBalance, diff);
1235
        }
32491 jai.hind 1236
        try {
1237
            workbook.write(bos);
1238
        } finally {
1239
            workbook.close();
1240
            bos.close();
1241
        }
28515 amit.gupta 1242
 
32491 jai.hind 1243
        return bos;
1244
    }
24876 tejbeer 1245
 
32491 jai.hind 1246
    @RequestMapping(value = "/manualPayment", method = RequestMethod.GET)
1247
    public String ManualPayment(HttpServletRequest request, Model model) throws Exception {
1248
        model.addAttribute("referenceTypes", WalletReferenceType.referenceType);
1249
        model.addAttribute("transactionTypes", TransactionType.values());
1250
        return "wallet-edit";
24876 tejbeer 1251
 
32491 jai.hind 1252
    }
24876 tejbeer 1253
 
32491 jai.hind 1254
    @RequestMapping(value = "/getWalletHistory", method = RequestMethod.GET)
32495 amit.gupta 1255
    public String getWalletHistory(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
25018 tejbeer 1256
 
32491 jai.hind 1257
        LOGGER.info("type" + referenceType);
32495 amit.gupta 1258
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
25018 tejbeer 1259
 
32491 jai.hind 1260
        if (userWalletHistory.isEmpty()) {
1261
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1262
        }
25018 tejbeer 1263
 
32491 jai.hind 1264
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
25018 tejbeer 1265
 
32491 jai.hind 1266
        LOGGER.info("userWallet" + userWallet);
1267
        CustomRetailer customretailer = retailerService.getFofoRetailer(userWallet.getUserId());
25018 tejbeer 1268
 
36928 amit 1269
        com.spice.profitmandi.dao.model.CreditSummary creditSummary = sdCreditService.getCreditSummary(userWallet.getUserId());
1270
 
32491 jai.hind 1271
        model.addAttribute("userWallet", userWallet);
1272
        model.addAttribute("customretailer", customretailer);
24876 tejbeer 1273
 
32491 jai.hind 1274
        model.addAttribute("wallethistory", userWalletHistory);
36928 amit 1275
        model.addAttribute("totalDue", creditSummary.getTotalDue());
1276
        model.addAttribute("creditlimit", creditSummary.getCreditLimit());
1277
        model.addAttribute("availableLimit", creditSummary.getAvailableLimit());
32491 jai.hind 1278
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1279
        return "wallet-history";
25018 tejbeer 1280
 
32491 jai.hind 1281
    }
25018 tejbeer 1282
 
32491 jai.hind 1283
    @RequestMapping(value = "/getWalletHistoryByPartner", method = RequestMethod.GET)
32512 amit.gupta 1284
    public String getWalletHistoryByPartner(HttpServletRequest request, int fofoId, @RequestParam(name = "referenceType", required = false) WalletReferenceType referenceType, @RequestParam(name = "offset", required = false, defaultValue = "0") int offset, @RequestParam(name = "limit", required = false, defaultValue = "100") int limit, Model model) throws Exception {
25018 tejbeer 1285
 
32491 jai.hind 1286
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
32495 amit.gupta 1287
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectPaginatedByWalletIdReferenceType(userWallet.getId(), referenceType, SortOrder.DESCENDING, offset, limit);
25018 tejbeer 1288
 
32491 jai.hind 1289
        CustomRetailer customretailer = retailerService.getFofoRetailer(fofoId);
25018 tejbeer 1290
 
32491 jai.hind 1291
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
32597 amit.gupta 1292
 
1293
        List<Loan> loans = null;
1294
        BigDecimal totalDue = BigDecimal.ZERO;
1295
        BigDecimal availableLimit = BigDecimal.ZERO;
1296
        BigDecimal creditlimit = BigDecimal.ZERO;
32598 amit.gupta 1297
        if (sdCreditRequirement != null) {
32597 amit.gupta 1298
            loans = loanRepository.selectActiveLoan(fofoId);
1299
            availableLimit = sdCreditRequirement.getAvailableLimit();
1300
            creditlimit = sdCreditRequirement.getLimit();
1301
            for (Loan loan : loans) {
1302
                BigDecimal pendingAmount = loan.getPendingAmount();
1303
                BigDecimal interestAccrued = loan.getInterestAccrued();
1304
                BigDecimal interestPaid = loan.getInterestPaid();
1305
                totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));
1306
                availableLimit = creditlimit.subtract(totalDue);
1307
            }
32491 jai.hind 1308
        }
1309
        model.addAttribute("userWallet", userWallet);
1310
        model.addAttribute("customretailer", customretailer);
1311
        model.addAttribute("wallethistory", userWalletHistory);
1312
        model.addAttribute("loans", loans);
1313
        model.addAttribute("totalDue", totalDue);
1314
        model.addAttribute("availableLimit", availableLimit);
1315
        model.addAttribute("creditlimit", creditlimit);
1316
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1317
        return "wallet-history";
1318
    }
30426 tejbeer 1319
 
24876 tejbeer 1320
 
32491 jai.hind 1321
    @RequestMapping(value = "/getPartnerName", method = RequestMethod.GET)
32495 amit.gupta 1322
    public String getPartnerName(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
24905 amit.gupta 1323
 
32495 amit.gupta 1324
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1325
        if (userWalletHistory.isEmpty()) {
1326
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1327
        }
1328
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
24905 amit.gupta 1329
 
32491 jai.hind 1330
        CustomRetailer retailer = retailerService.getFofoRetailer(userWallet.getUserId());
24905 amit.gupta 1331
 
32491 jai.hind 1332
        model.addAttribute("response1", mvcResponseSender.createResponseString(retailer));
24876 tejbeer 1333
 
32491 jai.hind 1334
        return "response";
24876 tejbeer 1335
 
32491 jai.hind 1336
    }
30677 amit.gupta 1337
 
32491 jai.hind 1338
    @RequestMapping(value = "/reset-wallet/9990381", method = RequestMethod.GET)
1339
    public String walletUpdate(Model model) throws Exception {
1340
        walletService.resetWallet();
1341
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1342
        return "response";
1343
    }
24876 tejbeer 1344
 
32491 jai.hind 1345
    @RequestMapping(value = "/walletUpdate", method = RequestMethod.POST)
32495 amit.gupta 1346
    public String walletUpdate(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam int referenceTypeValue, @RequestParam TransactionType transactiontype, @RequestParam int amount, @RequestParam String description, @RequestParam int retailerId, Model model, @RequestParam LocalDateTime businessTimestamp) throws Exception {
32491 jai.hind 1347
        WalletReferenceType referenceType = WalletReferenceType.findByValue(referenceTypeValue);
37590 amit 1348
        int usedReference = walletService.applyManualAdjustment(retailerId, reference, referenceType,
1349
                transactiontype, amount, description, businessTimestamp);
28515 amit.gupta 1350
 
37590 amit 1351
        model.addAttribute("response1", mvcResponseSender.createResponseString(usedReference));
32491 jai.hind 1352
        return "response";
25018 tejbeer 1353
 
32491 jai.hind 1354
    }
25018 tejbeer 1355
 
32491 jai.hind 1356
    @RequestMapping(value = "/addMoney", method = RequestMethod.POST)
32495 amit.gupta 1357
    public String addMoney(HttpServletRequest request, @RequestParam float amount, @RequestParam String transactionReference, @RequestParam LocalDateTime referenceTime, @RequestParam String bankName, @RequestParam int fofoId, Model model) throws Exception {
33175 amit.gupta 1358
        transactionReference = transactionReference.toUpperCase().trim();
1359
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectByReference(transactionReference);
34096 aman.kumar 1360
        addWalletRequests = addWalletRequests.stream().filter(x -> Arrays.asList(approved, AddWalletRequestStatus.pending).contains(x.getStatus())).collect(Collectors.toList());
33175 amit.gupta 1361
        if (addWalletRequests.size() > 0) {
1362
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1363
        }
1364
        HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(transactionReference);
33205 amit.gupta 1365
        if (hdfcPayment != null) {
33175 amit.gupta 1366
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1367
        }
32491 jai.hind 1368
        AddWalletRequest addWalletRequest = new AddWalletRequest();
1369
        addWalletRequest.setRetailerId(fofoId);
1370
        addWalletRequest.setAmount(amount);
33175 amit.gupta 1371
        addWalletRequest.setTransaction_reference(transactionReference.toUpperCase());
32491 jai.hind 1372
        addWalletRequest.setCreateTimestamp(LocalDateTime.now());
1373
        addWalletRequest.setBank_name(bankName);
1374
        addWalletRequest.setReference_date(referenceTime.toLocalDate());
1375
        addWalletRequest.setStatus(AddWalletRequestStatus.pending);
25018 tejbeer 1376
 
32491 jai.hind 1377
        LOGGER.info("info" + addWalletRequest);
29811 tejbeer 1378
 
32491 jai.hind 1379
        addWalletRequestRepository.persist(addWalletRequest);
1380
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1381
        return "response";
1382
    }
29811 tejbeer 1383
 
33045 amit.gupta 1384
    List<Gateway> directGateways = Arrays.asList(Gateway.SDDIRECT, Gateway.SIDBI);
1385
 
1386
    @Autowired
1387
    FofoSidbiSanctionRepository fofoSidbiSanctionRepository;
33175 amit.gupta 1388
 
32491 jai.hind 1389
    @RequestMapping(value = "/getCreditDetail", method = RequestMethod.GET)
1390
    public String getCreditDetail(HttpServletRequest request, Model model) throws Exception {
33175 amit.gupta 1391
        List<CreditAccount> creditAccounts = creditAccountRepository.selectAll().stream().filter(x -> directGateways.contains(x.getGateway())).collect(Collectors.toList());
32491 jai.hind 1392
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29962 tejbeer 1393
 
33420 amit.gupta 1394
        List<Integer> fofoIds = creditAccounts.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
33045 amit.gupta 1395
        //Need to maintain valid upto
33175 amit.gupta 1396
        Map<Integer, FofoSidbiSanction> fofoSidbiPendingSanctionsMap = fofoSidbiSanctionRepository.selectAll(Optional.of(false)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
29811 tejbeer 1397
 
33420 amit.gupta 1398
        Map<Integer, Integer> partnerAverageCreditDaysMap = new HashMap<>();
33045 amit.gupta 1399
 
33420 amit.gupta 1400
        List<Loan> loans = loanRepository.selectAllLoans(fofoIds, DateRangeModel.withStartDate(LocalDate.now().atStartOfDay().minusYears(2)));
1401
        Map<Integer, List<Loan>> partnerClosedLoansMap = loans.stream().filter(x -> x.getPendingAmount().compareTo(BigDecimal.ZERO) == 0)
1402
                .collect(Collectors.groupingBy(x -> x.getFofoId()));
1403
        for (Integer fofoId : fofoIds) {
1404
            List<Loan> closedLoans = partnerClosedLoansMap.get(fofoId);
1405
 
1406
            if (closedLoans != null) {
1407
                long averageCreditDays = Math.round(closedLoans.stream().mapToLong(x -> Duration.between(x.getCreatedOn(),
1408
                        x.getSettledOn() == null ? x.getCreatedOn().plusDays(10) : x.getSettledOn()).toDays() + 1).average().orElse(0.0));
1409
                partnerAverageCreditDaysMap.put(fofoId, (int) averageCreditDays);
1410
            }
1411
        }
1412
 
1413
 
32491 jai.hind 1414
        model.addAttribute("creditAccounts", creditAccounts);
33045 amit.gupta 1415
        model.addAttribute("fofoSidbiPendingSanctionsMap", fofoSidbiPendingSanctionsMap);
1416
        model.addAttribute("directGateways", directGateways);
32491 jai.hind 1417
        model.addAttribute("customRetailers", customRetailers);
33420 amit.gupta 1418
        model.addAttribute("partnerAverageCreditDaysMap", partnerAverageCreditDaysMap);
32491 jai.hind 1419
        return "partner-credit-detail";
1420
    }
29811 tejbeer 1421
 
33045 amit.gupta 1422
 
33359 amit.gupta 1423
    @Autowired
1424
    SidbiService sidbiService;
33363 amit.gupta 1425
 
37031 amit 1426
    // Only these admins may block/unblock a partner's credit.
1427
    private void assertCreditBlockAdmin(HttpServletRequest request) throws ProfitMandiBusinessException {
1428
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1429
        String email = loginDetails.getEmailId();
37124 amit 1430
        boolean isAdmin = "tarun.verma@smartdukaan.com".equals(email) || "kamini.sharma@smartdukaan.com".equals(email) || "siddharth.chaturvedi@smartdukaan.com".equals(email);
37031 amit 1431
        if (!isAdmin) {
1432
            throw new ProfitMandiBusinessException("You are not authorized to block/unblock credit", "", "");
1433
        }
1434
    }
1435
 
1436
    /** Block (deactivate) a partner's credit. Reason is mandatory and recorded in the block log. */
1437
    @RequestMapping(value = "/blockCredit", method = RequestMethod.POST)
1438
    public String blockCredit(HttpServletRequest request, @RequestParam int id, @RequestParam String reason, Model model) throws Exception {
1439
        assertCreditBlockAdmin(request);
1440
        String performedBy = cookiesProcessor.getCookiesObject(request).getEmailId();
1441
        sdCreditService.blockCredit(id, reason, performedBy);
1442
 
32491 jai.hind 1443
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
37031 amit 1444
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
1445
        model.addAttribute("creditAccount", creditAccount);
1446
        model.addAttribute("customRetailers", customRetailers);
1447
        return "partner-credit-detail-row";
1448
    }
1449
 
1450
    /** Unblock (reactivate) a previously blocked credit account (same gateway). Reason is optional. */
1451
    @RequestMapping(value = "/unblockCredit", method = RequestMethod.POST)
1452
    public String unblockCredit(HttpServletRequest request, @RequestParam int id, @RequestParam(required = false) String reason, Model model) throws Exception {
1453
        assertCreditBlockAdmin(request);
1454
        String performedBy = cookiesProcessor.getCookiesObject(request).getEmailId();
1455
        sdCreditService.unblockCredit(id, reason, performedBy);
1456
 
1457
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
1458
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
1459
        model.addAttribute("creditAccount", creditAccount);
1460
        model.addAttribute("customRetailers", customRetailers);
1461
        return "partner-credit-detail-row";
1462
    }
1463
 
1464
    /** Full block/unblock history for a partner, rendered into the unblock modal. */
1465
    @RequestMapping(value = "/creditBlockLogs", method = RequestMethod.GET)
1466
    public String creditBlockLogs(HttpServletRequest request, @RequestParam int fofoId, Model model) throws Exception {
1467
        model.addAttribute("creditBlockLogs", sdCreditService.getCreditBlockLogs(fofoId));
1468
        return "credit-block-logs";
1469
    }
1470
 
1471
    /** Switch a partner to a different credit gateway (e.g. SIDBI) and activate it. */
1472
    @RequestMapping(value = "/switchCreditGateway", method = RequestMethod.POST)
37927 amit 1473
    public String switchCreditGateway(HttpServletRequest request, @RequestParam int id, Model model, @RequestParam Gateway gateway, @RequestParam String reason) throws Exception {
37031 amit 1474
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
37927 amit 1475
        if (!creditAccount.isActive()) {
1476
            // Checks reason + loan-default rule before any gateway side effect; the transaction rolls back on later failures.
1477
            String activationReason = reason.trim().isEmpty() ? reason : reason.trim() + " (gateway " + gateway + ")";
1478
            sdCreditService.activateCredit(creditAccount, activationReason, cookiesProcessor.getCookiesObject(request).getEmailId());
1479
        }
1480
        if (!creditAccount.getGateway().equals(gateway)) {
33363 amit.gupta 1481
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(creditAccount.getFofoId());
33360 amit.gupta 1482
 
33363 amit.gupta 1483
            if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) != 0) {
33360 amit.gupta 1484
                LOGGER.info("sdCreditRequirement - {}", sdCreditRequirement);
33363 amit.gupta 1485
                throw new ProfitMandiBusinessException("Could not change to " + gateway + " unless previous loans are settled", "", "");
33205 amit.gupta 1486
            }
33359 amit.gupta 1487
            if (gateway.equals(Gateway.SIDBI)) {
1488
                //TODO - Issuance pending
1489
                FofoSidbiSanction fofoSidbiSanction = fofoSidbiSanctionRepository.selectByFofoId(creditAccount.getFofoId());
1490
                sidbiService.issueLimit(fofoSidbiSanction);
33363 amit.gupta 1491
                sdCreditRequirement.setLimit(BigDecimal.valueOf(fofoSidbiSanction.getLoanAmount()));
1492
                sdCreditRequirement.setSuggestedLimit(sdCreditRequirement.getLimit());
33359 amit.gupta 1493
                if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) > 0) {
1494
                    throw new ProfitMandiBusinessException("Loans are not closed", "Loans are not closed", "Loans are not closed");
1495
                }
33363 amit.gupta 1496
                creditAccount.setSanctionedAmount((float) fofoSidbiSanction.getLoanAmount());
33359 amit.gupta 1497
            }
33363 amit.gupta 1498
            creditAccount.setAvailableAmount(creditAccount.getSanctionedAmount());
1499
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
1500
            creditAccount.setActive(true);
37927 amit 1501
            creditAccount.setInactiveReason(null);
33363 amit.gupta 1502
            creditAccount.setGateway(gateway);
33045 amit.gupta 1503
        }
29811 tejbeer 1504
 
32491 jai.hind 1505
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
30859 tejbeer 1506
 
34712 amit.gupta 1507
        String title = "Credit Limit Approved";
32491 jai.hind 1508
        String url = "http://app.smartdukaan.com/pages/home/credit";
32495 amit.gupta 1509
        String message = "Congratulations! Your Credit Limit is approved for Rs." + FormattingUtils.formatDecimal(creditAccount.getSanctionedAmount());
1510
        notificationService.sendNotification(creditAccount.getFofoId(), "Loan", MessageType.notification, title, message, url);
29811 tejbeer 1511
 
32491 jai.hind 1512
        model.addAttribute("creditAccount", creditAccount);
1513
        model.addAttribute("customRetailers", customRetailers);
1514
        return "partner-credit-detail-row";
1515
    }
29811 tejbeer 1516
 
34261 tejus.loha 1517
    @RequestMapping(value = "/downloadAddWalletRequestReport", method = RequestMethod.GET)
34527 tejus.loha 1518
    public ResponseEntity<?> addWalletRequestPendingReport(@RequestParam LocalDate startDate, @RequestParam LocalDate endDate, @RequestParam AddWalletRequestStatus status, Model model) throws Exception {
1519
        if (endDate == null) {
1520
            endDate = LocalDate.now();
34261 tejus.loha 1521
        }
1522
        LocalDateTime form = startDate.atStartOfDay();
1523
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1524
        return walletService.createAddWalletRequestReport(form, to, status);
1525
    }
1526
 
34527 tejus.loha 1527
    @GetMapping(value = "/getHdfcPaymentsReport")
1528
    public String upiPaymentReport(HttpServletRequest request, @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate,@RequestParam(defaultValue = "OTH") String transferMode, Model model) throws Exception {
34261 tejus.loha 1529
 
34527 tejus.loha 1530
        if (startDate == null) {
1531
            startDate = LocalDate.now().minusDays(7);
1532
        }
1533
        if (endDate == null) {
1534
            endDate = LocalDate.now();
1535
        }
1536
        LocalDateTime form = startDate.atStartOfDay();
1537
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1538
        List<HdfcPayment> hdfcPayments = hdfcPaymentRepository.selectAllByTransferModeAndDataRange(transferMode, form, to);
1539
        Map<Integer, CustomRetailer> allFofoRetailers = retailerService.getAllFofoRetailers();
1540
        List<HdfcPaymentModel> hdfcPaymentModelList = new ArrayList<>();
1541
        if (hdfcPayments != null && hdfcPayments.size() > 0) {
1542
            for (HdfcPayment upiPayment : hdfcPayments) {
1543
                HdfcPaymentModel hdfcPaymentModel = new HdfcPaymentModel();
1544
                // remove prifix to get fofoId = "nwspic" from virtual account "nwspicFOFOID" eg "nwspic175140063" to "175140063"
1545
                String partnerIdString = upiPayment.getVirtualAccount().substring(6);
1546
                CustomRetailer customRetailer = allFofoRetailers.get(Integer.parseInt(partnerIdString));
1547
                hdfcPaymentModel.setAmount(upiPayment.getAmount());
1548
                hdfcPaymentModel.setName(customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")");
1549
                hdfcPaymentModel.setUtr(upiPayment.getUtr());
1550
                hdfcPaymentModel.setCreateTimestamp(upiPayment.getCreateTimestamp());
1551
                hdfcPaymentModel.setCreditTimestamp(upiPayment.getCreditTimestamp());
1552
                hdfcPaymentModel.setTransactionId(upiPayment.getTransactionId());
1553
                hdfcPaymentModel.setTransferMode(upiPayment.getTransferMode());
1554
                hdfcPaymentModelList.add(hdfcPaymentModel);
1555
            }
1556
        }
1557
 
1558
        List<String> transferModeList = Arrays.asList("OTH","FUND TRANS","IMPS","NEFT","RTGS");
1559
        model.addAttribute("hdfcPaymentModels", hdfcPaymentModelList);
1560
        model.addAttribute("startDate", startDate);
1561
        model.addAttribute("endDate", endDate);
1562
        model.addAttribute("mode", transferMode);
1563
        model.addAttribute("transferModeList", transferModeList);
1564
        return "upi-payments-report-panel";
1565
    }
1566
 
1567
 
22551 ashik.ali 1568
}