Subversion Repositories SmartDukaan

Rev

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