Subversion Repositories SmartDukaan

Rev

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