Subversion Repositories SmartDukaan

Rev

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