Subversion Repositories SmartDukaan

Rev

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