Subversion Repositories SmartDukaan

Rev

Rev 36720 | Rev 36754 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
22551 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
30859 tejbeer 3
import com.spice.profitmandi.common.enumuration.MessageType;
22551 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23936 tejbeer 5
import com.spice.profitmandi.common.model.CustomRetailer;
34527 tejus.loha 6
import com.spice.profitmandi.common.model.HdfcPaymentModel;
22551 ashik.ali 7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
24089 tejbeer 8
import com.spice.profitmandi.common.model.UnsettledPaymentModel;
31238 amit.gupta 9
import com.spice.profitmandi.common.util.*;
29811 tejbeer 10
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
31238 amit.gupta 11
import com.spice.profitmandi.dao.entity.transaction.*;
35971 aman 12
import com.spice.profitmandi.dao.entity.user.FullStockPayment;
32727 shampa 13
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
35971 aman 14
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.FullStockPaymentStatus;
23936 tejbeer 15
import com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus;
24876 tejbeer 16
import com.spice.profitmandi.dao.enumuration.transaction.TransactionType;
33420 amit.gupta 17
import com.spice.profitmandi.dao.model.DateRangeModel;
33861 tejus.loha 18
import com.spice.profitmandi.dao.model.StoreTimelineModel;
23936 tejbeer 19
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
24876 tejbeer 20
import com.spice.profitmandi.dao.repository.catalog.ManualPaymentRequestRepository;
24089 tejbeer 21
import com.spice.profitmandi.dao.repository.catalog.UnsettledPaymentsRepository;
29811 tejbeer 22
import com.spice.profitmandi.dao.repository.dtr.CreditAccountRepository;
24876 tejbeer 23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33861 tejus.loha 24
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
23985 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
32490 jai.hind 26
import com.spice.profitmandi.dao.repository.transaction.*;
35971 aman 27
import com.spice.profitmandi.dao.repository.user.FullStockPaymentRepository;
33861 tejus.loha 28
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
33359 amit.gupta 29
import com.spice.profitmandi.dao.service.SidbiService;
30859 tejbeer 30
import com.spice.profitmandi.service.NotificationService;
24523 amit.gupta 31
import com.spice.profitmandi.service.authentication.RoleManager;
29070 amit.gupta 32
import com.spice.profitmandi.service.transaction.TransactionService;
23936 tejbeer 33
import com.spice.profitmandi.service.user.RetailerService;
33861 tejus.loha 34
import com.spice.profitmandi.service.user.StoreTimelineTatService;
22551 ashik.ali 35
import com.spice.profitmandi.service.wallet.WalletService;
36
import com.spice.profitmandi.web.model.LoginDetails;
37
import com.spice.profitmandi.web.util.CookiesProcessor;
23936 tejbeer 38
import com.spice.profitmandi.web.util.MVCResponseSender;
39
import in.shop2020.model.v1.order.WalletReferenceType;
31238 amit.gupta 40
import org.apache.logging.log4j.LogManager;
41
import org.apache.logging.log4j.Logger;
42
import org.apache.poi.ss.usermodel.Cell;
43
import org.apache.poi.ss.usermodel.CellStyle;
44
import org.apache.poi.ss.usermodel.CreationHelper;
45
import org.apache.poi.ss.usermodel.Sheet;
46
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
47
import org.springframework.beans.factory.annotation.Autowired;
48
import org.springframework.core.io.InputStreamResource;
49
import org.springframework.http.HttpHeaders;
50
import org.springframework.http.HttpStatus;
51
import org.springframework.http.ResponseEntity;
52
import org.springframework.mail.javamail.JavaMailSender;
53
import org.springframework.mail.javamail.MimeMessageHelper;
54
import org.springframework.stereotype.Controller;
35971 aman 55
import org.springframework.transaction.annotation.Transactional;
31238 amit.gupta 56
import org.springframework.ui.Model;
57
import org.springframework.web.bind.annotation.*;
58
import org.springframework.web.multipart.MultipartFile;
23936 tejbeer 59
 
31238 amit.gupta 60
import javax.mail.internet.InternetAddress;
61
import javax.mail.internet.MimeMessage;
62
import javax.servlet.http.HttpServletRequest;
63
import javax.swing.*;
64
import java.io.ByteArrayInputStream;
65
import java.io.ByteArrayOutputStream;
66
import java.io.InputStream;
32490 jai.hind 67
import java.math.BigDecimal;
31238 amit.gupta 68
import java.text.MessageFormat;
33420 amit.gupta 69
import java.time.*;
31238 amit.gupta 70
import java.util.*;
71
import java.util.stream.Collectors;
72
 
34096 aman.kumar 73
import static com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus.approved;
74
 
22551 ashik.ali 75
@Controller
35458 amit 76
@Transactional(rollbackFor = Throwable.class)
22551 ashik.ali 77
public class WalletController {
78
 
32491 jai.hind 79
    private static final int IDX_PERIOD = 1;
80
    private static final int OPENING_BALANCE = 2;
81
    private static final int ACTIVATION_SCHEME = 4;
82
    private static final int ADVANCE_AMOUNT = 5;
83
    private static final int AUTOMATED_ADVANCE = 6;
84
    private static final int BRAND_PAYOUT = 7;
85
    private static final int INVESTMENT_PAYOUT = 8;
86
    private static final int OTHERS = 9;
87
    private static final int PREBOOKING_ORDER = 10;
88
    private static final int PRICE_DROP = 11;
89
    private static final int PURCHASE = 12;
90
    private static final int PURCHASE_BILLED = 13;
91
    private static final int PURCHASE_PENDING_BILLING = 14;
92
    private static final int PURCHASE_CANCELLED = 15;
93
    private static final int RECHARGE = 16;
94
    private static final int REFUND = 17;
95
    private static final int SCHEME_IN = 18;
96
    private static final int SCHEME_OUT = 19;
97
    private static final Map<WalletReferenceType, Integer> walletReferenceMap = new HashMap<>();
32494 amit.gupta 98
    private static final int GRAND_TOTAL = 20;
99
    private static final int CLOSING_BALANCE = 22;
100
    private static final int PENDING_GRN = 23;
101
    private static final int ACTIVATED_IMEIS = 24;
102
    private static final Logger LOGGER = LogManager.getLogger(WalletController.class);
32490 jai.hind 103
 
32491 jai.hind 104
    static {
105
        walletReferenceMap.put(WalletReferenceType.ACTIVATION_SCHEME, ACTIVATION_SCHEME);
106
        walletReferenceMap.put(WalletReferenceType.ADVANCE_AMOUNT, ADVANCE_AMOUNT);
107
        walletReferenceMap.put(WalletReferenceType.AUTOMATED_ADVANCE, AUTOMATED_ADVANCE);
108
        walletReferenceMap.put(WalletReferenceType.BRAND_PAYOUT, BRAND_PAYOUT);
109
        walletReferenceMap.put(WalletReferenceType.INVESTMENT_PAYOUT, INVESTMENT_PAYOUT);
110
        walletReferenceMap.put(WalletReferenceType.OTHERS, OTHERS);
111
        walletReferenceMap.put(WalletReferenceType.PREBOOKING_ORDER, PREBOOKING_ORDER);
112
        walletReferenceMap.put(WalletReferenceType.PRICE_DROP, PRICE_DROP);
113
        walletReferenceMap.put(WalletReferenceType.PURCHASE, PURCHASE);
114
        walletReferenceMap.put(WalletReferenceType.RECHARGE, RECHARGE);
115
        walletReferenceMap.put(WalletReferenceType.REFUND, REFUND);
116
        walletReferenceMap.put(WalletReferenceType.SCHEME_IN, SCHEME_IN);
117
        walletReferenceMap.put(WalletReferenceType.SCHEME_OUT, SCHEME_OUT);
28515 amit.gupta 118
 
32491 jai.hind 119
    }
32490 jai.hind 120
 
32491 jai.hind 121
    @Autowired
36401 amit 122
    JavaMailSender gmailRelaySender;
32494 amit.gupta 123
    @Autowired
35811 amit 124
    com.spice.profitmandi.service.transaction.SDCreditService sdCreditService;
125
    @Autowired
32494 amit.gupta 126
    AddWalletRequestRepository addWalletRequestRepository;
127
    @Autowired
128
    TransactionService transactionService;
129
    @Autowired
32491 jai.hind 130
    private CookiesProcessor cookiesProcessor;
131
    @Autowired
132
    private WalletService walletService;
133
    @Autowired
134
    private UserWalletRepository userWalletRepository;
135
    @Autowired
136
    private UserWalletHistoryRepository userWalletHistoryRepository;
137
    @Autowired
138
    private MVCResponseSender mvcResponseSender;
139
    @Autowired
140
    private UserAccountRepository userAccountRepository;
141
    @Autowired
142
    private OrderRepository orderRepository;
143
    @Autowired
144
    private UnsettledPaymentsRepository unsettledPaymentsRepository;
145
    @Autowired
146
    private RetailerService retailerService;
147
    @Autowired
148
    private RoleManager roleManager;
149
    @Autowired
150
    private FofoStoreRepository fofoStoreRepository;
151
    @Autowired
152
    private ManualPaymentRequestRepository manualPaymentRequestRepository;
153
    @Autowired
154
    private CreditAccountRepository creditAccountRepository;
30859 tejbeer 155
 
32491 jai.hind 156
    @Autowired
157
    private NotificationService notificationService;
158
    @Autowired
159
    LoanRepository loanRepository;
160
    @Autowired
161
    private LoanStatementRepository loanStatementRepository;
162
    @Autowired
163
    SDCreditRequirementRepository sdCreditRequirementRepository;
33861 tejus.loha 164
    @Autowired
165
    LoiFormRepository loiFormRepository;
166
    @Autowired
167
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
168
    @Autowired
169
    StoreTimelineTatService storeTimelineTatService;
28515 amit.gupta 170
 
35971 aman 171
    @Autowired
172
    FullStockPaymentRepository fullStockPaymentRepository;
173
    @Autowired
174
    com.spice.profitmandi.dao.repository.auth.AuthRepository authRepository;
175
    @Autowired
176
    com.spice.profitmandi.dao.repository.cs.PositionRepository positionRepository;
33205 amit.gupta 177
 
35971 aman 178
 
32491 jai.hind 179
    @PostMapping(value = "/wallet/upload")
32495 amit.gupta 180
    public String uploadWalletBulk(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model) throws Exception {
32491 jai.hind 181
        List<WalletHistoryModel> walletHistoryModelList = ExcelUtils.parseWalletBulkCredit(file.getInputStream());
182
        for (WalletHistoryModel walletHistoryModel : walletHistoryModelList) {
183
            if (walletHistoryModel.getReference() == 0) {
32495 amit.gupta 184
                ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(walletHistoryModel.getWalletReferenceType());
32491 jai.hind 185
                if (paymentType == null) {
186
                    paymentType = new ManualPaymentType();
187
                    paymentType.setReferenceType(walletHistoryModel.getWalletReferenceType());
188
                    manualPaymentRequestRepository.persist(paymentType);
189
                }
190
                paymentType.setCounter(paymentType.getCounter() + 1);
191
                int reference = paymentType.getCounter();
32495 amit.gupta 192
                walletService.addAmountToWallet(walletHistoryModel.getFofoId(), reference, walletHistoryModel.getWalletReferenceType(), walletHistoryModel.getDescription(), (float) walletHistoryModel.getAmount(), walletHistoryModel.getBusinessDate());
32491 jai.hind 193
            } else {
32495 amit.gupta 194
                walletService.addAmountToWallet(walletHistoryModel.getFofoId(), walletHistoryModel.getReference(), walletHistoryModel.getWalletReferenceType(), walletHistoryModel.getDescription(), (float) walletHistoryModel.getAmount(), walletHistoryModel.getBusinessDate());
32491 jai.hind 195
            }
196
        }
23993 tejbeer 197
 
32491 jai.hind 198
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
199
        return "response";
200
    }
27067 amit.gupta 201
 
32491 jai.hind 202
    @RequestMapping(value = "/walletDetails", method = RequestMethod.GET)
32495 amit.gupta 203
    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 204
        /*
205
         * boolean underMaintainance = true; if(underMaintainance) { throw new
206
         * ProfitMandiBusinessException("Wallet", "Wallet",
207
         * "Wallet is under Maintenance"); }
208
         */
209
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
210
        int fofoId = fofoDetails.getFofoId();
211
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
212
        UserWallet userWallet = walletService.getUserWallet(fofoId);
23993 tejbeer 213
 
32491 jai.hind 214
        LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
215
        LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
23993 tejbeer 216
 
32491 jai.hind 217
        List<UserWalletHistory> userWalletHistories = new ArrayList<>();
218
        try {
32495 amit.gupta 219
            userWalletHistories = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDateTime, endDateTime, offset, limit);
32491 jai.hind 220
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
221
            LOGGER.error("UserWallet History not found : ", profitMandiBusinessException);
222
        }
23993 tejbeer 223
 
32491 jai.hind 224
        long countItems = 0;
225
        try {
226
            countItems = walletService.getSizeByRetailerId(fofoDetails.getFofoId(), startDateTime, endDateTime);
227
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
228
            LOGGER.error("UserWallet not found : ", profitMandiBusinessException);
229
        }
36746 amit 230
        com.spice.profitmandi.dao.model.CreditSummary creditSummary = sdCreditService.getCreditSummary(fofoId);
32491 jai.hind 231
        model.addAttribute("userWallet", userWallet);
232
        model.addAttribute("walletHistories", userWalletHistories);
36242 aman 233
        model.addAttribute("walletAttachmentMap", buildWalletHistoryAttachmentMap(userWalletHistories));
32491 jai.hind 234
        model.addAttribute("start", offset + 1);
235
        model.addAttribute("size", countItems);
236
        model.addAttribute("isAdmin", isAdmin);
36746 amit 237
        model.addAttribute("totalDue", creditSummary.getTotalDue());
238
        model.addAttribute("utilization", creditSummary.getUtilization());
32491 jai.hind 239
        model.addAttribute(ProfitMandiConstants.START_TIME, startTimeString);
240
        model.addAttribute(ProfitMandiConstants.END_TIME, endTimeString);
23993 tejbeer 241
 
32491 jai.hind 242
        if (userWalletHistories.size() < limit) {
243
            model.addAttribute("end", offset + userWalletHistories.size());
244
        } else {
245
            model.addAttribute("end", offset + limit);
246
        }
247
        return "wallet-details";
248
    }
23993 tejbeer 249
 
32491 jai.hind 250
    @RequestMapping(value = "/getPaginatedWalletHistory")
32495 amit.gupta 251
    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 252
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22551 ashik.ali 253
 
32491 jai.hind 254
        LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
255
        LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
23993 tejbeer 256
 
32491 jai.hind 257
        List<UserWalletHistory> userWalletHistories = new ArrayList<>();
258
        try {
32495 amit.gupta 259
            userWalletHistories = walletService.getPaginatedUserWalletHistoryByRetailerId(loginDetails.getFofoId(), startDateTime, endDateTime, offset, limit);
32491 jai.hind 260
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
261
            LOGGER.error("UserWallet History not found : ", profitMandiBusinessException);
262
        }
23993 tejbeer 263
 
32491 jai.hind 264
        model.addAttribute("walletHistories", userWalletHistories);
36242 aman 265
        model.addAttribute("walletAttachmentMap", buildWalletHistoryAttachmentMap(userWalletHistories));
32491 jai.hind 266
        return "wallet-history-paginated";
267
    }
23936 tejbeer 268
 
32491 jai.hind 269
    @RequestMapping(value = "/getAddWalletRequest", method = RequestMethod.GET)
36500 ranu 270
    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 271
        List<AddWalletRequest> walletRequest = null;
272
        long size = 0;
273
        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.pending);
274
        LOGGER.info("walletRequest" + walletRequest);
275
        size = addWalletRequestRepository.selectCountByStatus(AddWalletRequestStatus.pending);
276
        if (!walletRequest.isEmpty()) {
277
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
30426 tejbeer 278
 
32491 jai.hind 279
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 280
 
32495 amit.gupta 281
            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 282
 
32491 jai.hind 283
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
284
            model.addAttribute("walletRequest", walletRequest);
36242 aman 285
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 286
            model.addAttribute("rStatus", "pending");
287
            model.addAttribute("start", offset + 1);
288
            model.addAttribute("size", size);
289
            model.addAttribute("url", "/getPaginatedWalletRequest");
23993 tejbeer 290
 
32491 jai.hind 291
            if (walletRequest.size() < limit) {
292
                model.addAttribute("end", offset + walletRequest.size());
293
            } else {
294
                model.addAttribute("end", offset + limit);
295
            }
23993 tejbeer 296
 
32491 jai.hind 297
        } else {
23993 tejbeer 298
 
32491 jai.hind 299
            model.addAttribute("walletRequest", walletRequest);
300
            model.addAttribute("size", size);
23936 tejbeer 301
 
32491 jai.hind 302
        }
303
        return "add-wallet-request";
304
    }
23936 tejbeer 305
 
32491 jai.hind 306
    @RequestMapping(value = "/getPaginatedWalletRequest", method = RequestMethod.GET)
32495 amit.gupta 307
    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 308
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
309
        List<AddWalletRequest> walletRequest = null;
310
        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.pending);
311
        LOGGER.info("walletRequest" + walletRequest);
312
        if (!walletRequest.isEmpty()) {
313
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
314
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 315
 
32495 amit.gupta 316
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 317
 
32491 jai.hind 318
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
319
            model.addAttribute("walletRequest", walletRequest);
36242 aman 320
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 321
            model.addAttribute("rStatus", "pending");
322
            model.addAttribute("url", "/getPaginatedWalletRequest");
23993 tejbeer 323
 
32491 jai.hind 324
        } else {
325
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 326
 
32491 jai.hind 327
        }
23993 tejbeer 328
 
32491 jai.hind 329
        return "add-wallet-request-paginated";
330
    }
23993 tejbeer 331
 
32491 jai.hind 332
    @RequestMapping(value = "/getAddWalletApproved", method = RequestMethod.GET)
34096 aman.kumar 333
    public String walletAddnAccept(HttpServletRequest request, Model model) throws Exception {
334
 
335
        return "add-wallet-req";
336
    }
337
 
338
    @RequestMapping(value = "/getAddWalletApprovedByDate", method = RequestMethod.GET)
339
    public String getAddwalletRequestApproved(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
340
                                              @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
341
        LOGGER.info("requested startDate=[{}], EndDate = [{}]", startDate, endDate);
32491 jai.hind 342
        List<AddWalletRequest> walletRequest = null;
343
        long size = 0;
34096 aman.kumar 344
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.approved);
345
//        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, approved);
346
        size = addWalletRequestRepository.selectCountByStatus(approved);
32491 jai.hind 347
        if (!walletRequest.isEmpty()) {
348
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
349
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 350
 
32495 amit.gupta 351
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 352
 
32491 jai.hind 353
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
354
            model.addAttribute("walletRequest", walletRequest);
36242 aman 355
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 356
            model.addAttribute("start", offset + 1);
357
            model.addAttribute("size", size);
358
            model.addAttribute("url", "/getPaginatedWalletApproved");
23993 tejbeer 359
 
32491 jai.hind 360
            if (walletRequest.size() < limit) {
361
                model.addAttribute("end", offset + walletRequest.size());
362
            } else {
363
                model.addAttribute("end", offset + limit);
364
            }
365
        } else {
23993 tejbeer 366
 
32491 jai.hind 367
            model.addAttribute("walletRequest", walletRequest);
368
            model.addAttribute("size", size);
23936 tejbeer 369
 
32491 jai.hind 370
        }
34096 aman.kumar 371
        return "add-wallet-request-paginated";
32491 jai.hind 372
    }
23936 tejbeer 373
 
32491 jai.hind 374
    @RequestMapping(value = "/getPaginatedWalletApproved", method = RequestMethod.GET)
34096 aman.kumar 375
    public String getPaginatedWalletApproved(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
376
                                             @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 377
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
378
        List<AddWalletRequest> walletRequest = null;
34096 aman.kumar 379
        long size = 0;
380
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.approved);
381
 
382
//        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.approved);
32491 jai.hind 383
        LOGGER.info("walletRequest" + walletRequest);
384
        if (!walletRequest.isEmpty()) {
385
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
386
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 387
 
32495 amit.gupta 388
            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 389
 
32491 jai.hind 390
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
391
            model.addAttribute("walletRequest", walletRequest);
36242 aman 392
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 393
            model.addAttribute("url", "/getPaginatedWalletApproved");
394
        } else {
395
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 396
 
32491 jai.hind 397
        }
398
        return "add-wallet-request-paginated";
399
    }
23993 tejbeer 400
 
32491 jai.hind 401
    @RequestMapping(value = "/getAddWalletRequestRejected", method = RequestMethod.GET)
34096 aman.kumar 402
    public String walletAddnReject(HttpServletRequest request, Model model) throws Exception {
403
 
404
        return "add-wallet-rejected";
405
    }
406
 
407
    @RequestMapping(value = "/getAddWalletRequestRejectedByDate", method = RequestMethod.GET)
408
    public String getAddwalletRequestRejected(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
409
                                              @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 410
        List<AddWalletRequest> walletRequest = null;
23985 tejbeer 411
 
32491 jai.hind 412
        long size = 0;
34096 aman.kumar 413
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.rejected);
32491 jai.hind 414
        size = addWalletRequestRepository.selectCountByStatus(AddWalletRequestStatus.rejected);
415
        LOGGER.info("walletRequest" + walletRequest);
416
        if (!walletRequest.isEmpty()) {
417
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
418
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 419
 
32495 amit.gupta 420
            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 421
 
32491 jai.hind 422
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
423
            model.addAttribute("walletRequest", walletRequest);
36242 aman 424
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 425
            model.addAttribute("start", offset + 1);
426
            model.addAttribute("size", size);
427
            model.addAttribute("url", "/getPaginatedWalletRequestRejected");
23985 tejbeer 428
 
32491 jai.hind 429
            if (walletRequest.size() < limit) {
430
                model.addAttribute("end", offset + walletRequest.size());
431
            } else {
432
                model.addAttribute("end", offset + limit);
433
            }
434
        } else {
435
            model.addAttribute("walletRequest", walletRequest);
436
            model.addAttribute("size", size);
437
        }
23993 tejbeer 438
 
34096 aman.kumar 439
        return "add-wallet-request-paginated";
32491 jai.hind 440
    }
23985 tejbeer 441
 
32491 jai.hind 442
    @RequestMapping(value = "/getPaginatedWalletRequestRejected", method = RequestMethod.GET)
34096 aman.kumar 443
    public String getPaginatedWalletRequestRejected(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
444
                                                    @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 445
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
446
        List<AddWalletRequest> walletRequest = null;
34096 aman.kumar 447
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.rejected);
32491 jai.hind 448
        LOGGER.info("walletRequest" + walletRequest);
449
        if (!walletRequest.isEmpty()) {
450
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
451
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
23993 tejbeer 452
 
32495 amit.gupta 453
            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 454
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
455
            model.addAttribute("walletRequest", walletRequest);
36242 aman 456
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 457
            model.addAttribute("url", "/getPaginatedWalletRequestRejected");
458
        } else {
459
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 460
 
32491 jai.hind 461
        }
23993 tejbeer 462
 
32491 jai.hind 463
        return "add-wallet-request-paginated";
464
    }
23993 tejbeer 465
 
35197 amit 466
    @Autowired
467
    HdfcPaymentRepository hdfcPaymentRepository;
468
 
32491 jai.hind 469
    @RequestMapping(value = "/addAmountToWallet", method = RequestMethod.PUT)
32495 amit.gupta 470
    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 471
 
32491 jai.hind 472
        AddWalletRequest addWalletRequest = addWalletRequestRepository.selectById(walletRequestid);
35197 amit 473
        List<AddWalletRequest> requests = addWalletRequestRepository.selectAllByTransactionReference(addWalletRequest.getTransaction_reference());
474
        if (requests.stream().filter(x -> x.getId() != addWalletRequest.getId()).filter(x -> x.getStatus().equals(approved)).count() != 1) {
475
            HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(addWalletRequest.getTransaction_reference());
476
            if (hdfcPayment != null) {
477
                String rejectReason = "Payment for UTR Already added via Auto Update";
478
                throw new ProfitMandiBusinessException(rejectReason, rejectReason, rejectReason);
479
            }
480
        } else {
481
            String rejectReason = "Entry already Approved Please reject";
482
            throw new ProfitMandiBusinessException(rejectReason, rejectReason, rejectReason);
483
        }
35971 aman 484
        // FSP wallet addons can only be approved by Account team L3
485
        if (addWalletRequest.getFspId() > 0) {
486
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
487
            String approverEmail = loginDetails.getEmailId();
488
            com.spice.profitmandi.dao.entity.auth.AuthUser approverUser = authRepository.selectByEmailOrMobile(approverEmail);
489
            boolean isAccountL3 = false;
490
            if (approverUser != null) {
491
                List<com.spice.profitmandi.dao.entity.cs.Position> positions = positionRepository.selectPositionByAuthId(approverUser.getId());
492
                for (com.spice.profitmandi.dao.entity.cs.Position position : positions) {
493
                    if (position.getEscalationType().equals(com.spice.profitmandi.dao.enumuration.cs.EscalationType.L3)
494
                            && position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS) {
495
                        isAccountL3 = true;
496
                        break;
497
                    }
498
                }
499
            }
500
            if (!isAccountL3) {
501
                throw new ProfitMandiBusinessException(
502
                        "Only Account team L3 can approve Full Stock Payment entries",
503
                        approverEmail,
504
                        "You are not authorized to approve FSP wallet requests");
505
            }
506
        }
507
 
32491 jai.hind 508
        if (addWalletRequest.getStatus().equals(AddWalletRequestStatus.pending)) {
32495 amit.gupta 509
            walletService.addAmountToWallet(addWalletRequest.getRetailerId(), walletRequestid, WalletReferenceType.ADVANCE_AMOUNT, "ntfs/rgfs", addWalletRequest.getAmount(), addWalletRequest.getCreateTimestamp());
32491 jai.hind 510
            addWalletRequest.setStatus(AddWalletRequestStatus.approved);
511
            addWalletRequest.setUpdateTimestamp(LocalDateTime.now());
512
            unsettledPaymentsRepository.deleteById(id);
33861 tejus.loha 513
 
514
            // check full stock payment if partner comes from Loi process
515
            String code = fofoStoreRepository.selectByRetailerId(addWalletRequest.getRetailerId()).getCode();
516
            StoreTimelineModel storeTimelineModel = partnerOnBoardingPanelRepository.selectStoreTimeLine(code);
517
            if (storeTimelineModel != null && storeTimelineModel.getFullStockTimestamp() == null) {
518
                UserWallet userWallet = userWalletRepository.selectByRetailerId(addWalletRequest.getRetailerId());
519
                List<UserWalletHistory> userWalletHistories = userWalletHistoryRepository.selectByWalletIdAndReferenceType(userWallet.getId(), WalletReferenceType.ADVANCE_AMOUNT);
520
                long totalAdvanceAmount = userWalletHistories.stream().mapToLong(x -> x.getAmount()).sum();
521
                LOGGER.info("totalAdvanceAmount - " + totalAdvanceAmount);
35971 aman 522
                if (totalAdvanceAmount >= ProfitMandiConstants.FSP_DIRECT_WALLET_THRESHOLD) {
33861 tejus.loha 523
                    storeTimelineTatService.onFullPaymentReceived(storeTimelineModel.getOnboardingId());
524
                }
35971 aman 525
 
526
                // Mark linked FullStockPayment record as APPROVED via fspId
527
                if (addWalletRequest.getFspId() > 0) {
528
                    FullStockPayment fsp = fullStockPaymentRepository.selectById(addWalletRequest.getFspId());
529
                    if (fsp != null && fsp.getPaymentStatus() == FullStockPaymentStatus.PENDING) {
530
                        fsp.setPaymentStatus(FullStockPaymentStatus.APPROVED);
531
                        fsp.setApproveTimestamp(LocalDateTime.now());
532
                        fullStockPaymentRepository.persist(fsp);
533
                        LOGGER.info("Marked FSP id={} as APPROVED via wallet addon approval, onboardingId={}", fsp.getId(), storeTimelineModel.getOnboardingId());
534
                    }
535
                }
536
 
537
                // Auto-mark FULL_STOCK_PAYMENT in timeline when total approved FSP amount >= 7 lakh
538
                double totalApprovedFsp = fullStockPaymentRepository.selectByOnboardingId(storeTimelineModel.getOnboardingId())
539
                        .stream()
540
                        .filter(p -> p.getPaymentStatus() == FullStockPaymentStatus.APPROVED)
541
                        .mapToDouble(FullStockPayment::getCollectedAmount)
542
                        .sum();
543
                LOGGER.info("totalApprovedFsp={} for onboardingId={}", totalApprovedFsp, storeTimelineModel.getOnboardingId());
544
                if (totalApprovedFsp >= ProfitMandiConstants.FSP_DIRECT_WALLET_THRESHOLD) {
545
                    storeTimelineTatService.onFullPaymentReceived(storeTimelineModel.getOnboardingId());
546
                    LOGGER.info("Auto-marked FULL_STOCK_PAYMENT done for onboardingId={}, totalApprovedFsp={}", storeTimelineModel.getOnboardingId(), totalApprovedFsp);
36064 aman 547
                    try {
548
                        storeTimelineTatService.sendFullStockPaymentPOEmail(storeTimelineModel.getOnboardingId());
549
                    } catch (Exception ex) {
550
                        LOGGER.error("Failed to send FSP PO email after approved FSP >= 7L for onboardingId=" + storeTimelineModel.getOnboardingId(), ex);
551
                    }
35971 aman 552
                }
33861 tejus.loha 553
            }
554
 
32491 jai.hind 555
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
556
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 557
            String subject = "Request Approved for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
558
            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 559
 
32491 jai.hind 560
            //	this.sendMailWithAttachments(subject, messageText);
561
            return "response";
562
        } else {
563
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
564
            return "response";
565
        }
566
    }
23993 tejbeer 567
 
32491 jai.hind 568
    @RequestMapping(value = "/addAmountToWalletRequestRejected", method = RequestMethod.PUT)
32495 amit.gupta 569
    public String addAmountToWalletRequestRejected(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
23993 tejbeer 570
 
32491 jai.hind 571
        AddWalletRequest addWalletRequest = addWalletRequestRepository.selectById(id);
572
        if (addWalletRequest.getStatus().equals(AddWalletRequestStatus.pending)) {
573
            addWalletRequest.setStatus(AddWalletRequestStatus.rejected);
574
            addWalletRequest.setUpdateTimestamp(LocalDateTime.now());
575
            addWalletRequestRepository.persist(addWalletRequest);
35971 aman 576
 
577
            // Mark linked FSP as REJECTED via fspId
578
            if (addWalletRequest.getFspId() > 0) {
579
                try {
580
                    FullStockPayment fsp = fullStockPaymentRepository.selectById(addWalletRequest.getFspId());
581
                    if (fsp != null && fsp.getPaymentStatus() == FullStockPaymentStatus.PENDING) {
582
                        fsp.setPaymentStatus(FullStockPaymentStatus.REJECTED);
583
                        fsp.setDescription("Wallet addon request rejected");
584
                        fsp.setApproveTimestamp(LocalDateTime.now());
585
                        fullStockPaymentRepository.persist(fsp);
586
                        LOGGER.info("Marked FSP id={} as REJECTED via wallet addon rejection", fsp.getId());
587
                    }
588
                } catch (Exception e) {
589
                    LOGGER.error("Error marking FSP as REJECTED on wallet addon rejection", e);
590
                }
591
            }
592
 
32491 jai.hind 593
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
594
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 595
            String subject = "Request Rejected for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
596
            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 597
 
32491 jai.hind 598
            //this.sendMailWithAttachments(subject, messageText);
599
            return "response";
600
        } else {
601
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
602
            return "response";
603
        }
604
    }
23985 tejbeer 605
 
32491 jai.hind 606
    private void sendMailWithAttachments(String subject, String messageText) throws Exception {
36401 amit 607
        MimeMessage message = gmailRelaySender.createMimeMessage();
32491 jai.hind 608
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
32495 amit.gupta 609
        String[] email = {"neerajgupta2021@gmail.com", "adeel.yazdani@smartdukaan.com", "kamini.sharma@smartdukaan.com", "care@smartdukaan.com", "mohinder.mutreja@smartdukaan.com"};
32491 jai.hind 610
        helper.setSubject(subject);
611
        helper.setText(messageText);
612
        helper.setTo(email);
613
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
614
        helper.setFrom(senderAddress);
36401 amit 615
        gmailRelaySender.send(message);
23993 tejbeer 616
 
32491 jai.hind 617
    }
23936 tejbeer 618
 
32491 jai.hind 619
    private List<Integer> getFofoIdsFromWalletRequest(List<AddWalletRequest> walletRequest) {
620
        return walletRequest.stream().map(x -> x.getRetailerId()).distinct().collect(Collectors.toList());
621
    }
24089 tejbeer 622
 
36242 aman 623
    /**
624
     * Builds a map of AddWalletRequest.id -> FullStockPayment.attachment for requests linked to FSP.
625
     */
626
    private Map<Integer, Integer> buildFspAttachmentMap(List<AddWalletRequest> walletRequests) {
627
        Map<Integer, Integer> attachmentMap = new HashMap<>();
628
        List<Integer> fspIds = walletRequests.stream()
629
                .filter(r -> r.getFspId() > 0)
630
                .map(AddWalletRequest::getFspId)
631
                .distinct()
632
                .collect(Collectors.toList());
633
        if (fspIds.isEmpty()) {
634
            return attachmentMap;
635
        }
636
        List<FullStockPayment> fspList = fullStockPaymentRepository.selectByIds(fspIds);
637
        Map<Integer, Integer> fspIdToAttachment = fspList.stream()
638
                .filter(f -> f.getAttachment() > 0)
639
                .collect(Collectors.toMap(FullStockPayment::getId, FullStockPayment::getAttachment));
640
        for (AddWalletRequest r : walletRequests) {
641
            if (r.getFspId() > 0 && fspIdToAttachment.containsKey(r.getFspId())) {
642
                attachmentMap.put(r.getId(), fspIdToAttachment.get(r.getFspId()));
643
            }
644
        }
645
        return attachmentMap;
646
    }
647
 
648
    /**
649
     * Builds a map of UserWalletHistory.id -> FullStockPayment.attachment for ADVANCE_AMOUNT entries linked to FSP.
650
     */
651
    private Map<Integer, Integer> buildWalletHistoryAttachmentMap(List<UserWalletHistory> histories) {
652
        Map<Integer, Integer> attachmentMap = new HashMap<>();
653
        List<Integer> awrIds = histories.stream()
654
                .filter(h -> h.getReferenceType() == WalletReferenceType.ADVANCE_AMOUNT && h.getReference() > 0)
655
                .map(UserWalletHistory::getReference)
656
                .distinct()
657
                .collect(Collectors.toList());
658
        if (awrIds.isEmpty()) {
659
            return attachmentMap;
660
        }
661
        List<AddWalletRequest> awrList = addWalletRequestRepository.selectByIds(awrIds);
662
        Map<Integer, Integer> awrIdToFspId = awrList.stream()
663
                .filter(r -> r.getFspId() > 0)
664
                .collect(Collectors.toMap(AddWalletRequest::getId, AddWalletRequest::getFspId));
665
        List<Integer> fspIds = awrIdToFspId.values().stream().distinct().collect(Collectors.toList());
666
        if (fspIds.isEmpty()) {
667
            return attachmentMap;
668
        }
669
        List<FullStockPayment> fspList = fullStockPaymentRepository.selectByIds(fspIds);
670
        Map<Integer, Integer> fspIdToAttachment = fspList.stream()
671
                .filter(f -> f.getAttachment() > 0)
672
                .collect(Collectors.toMap(FullStockPayment::getId, FullStockPayment::getAttachment));
673
        for (UserWalletHistory h : histories) {
674
            if (h.getReferenceType() == WalletReferenceType.ADVANCE_AMOUNT && h.getReference() > 0) {
675
                Integer fspId = awrIdToFspId.get(h.getReference());
676
                if (fspId != null && fspIdToAttachment.containsKey(fspId)) {
677
                    attachmentMap.put(h.getId(), fspIdToAttachment.get(fspId));
678
                }
679
            }
680
        }
681
        return attachmentMap;
682
    }
683
 
32491 jai.hind 684
    @RequestMapping(value = "/getcreateUnsettledPayments", method = RequestMethod.GET)
32495 amit.gupta 685
    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 686
        List<UnsettledPayment> up = null;
24089 tejbeer 687
 
32491 jai.hind 688
        long size = 0;
689
        up = unsettledPaymentsRepository.selectAllById(offset, limit);
24089 tejbeer 690
 
32491 jai.hind 691
        size = unsettledPaymentsRepository.selectAllCount();
692
        if (!up.isEmpty()) {
693
            model.addAttribute("unsettledPayment", up);
694
            model.addAttribute("start", offset + 1);
695
            model.addAttribute("size", size);
696
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 697
 
32491 jai.hind 698
            if (up.size() < limit) {
699
                model.addAttribute("end", offset + up.size());
700
            } else {
701
                model.addAttribute("end", offset + limit);
702
            }
703
        } else {
704
            model.addAttribute("unsettledPayment", up);
705
            model.addAttribute("size", size);
706
        }
24089 tejbeer 707
 
32491 jai.hind 708
        LOGGER.info("unsettledPaymentList" + up);
709
        return "unsettled-payments";
710
    }
24089 tejbeer 711
 
32491 jai.hind 712
    @RequestMapping(value = "/getUnsettledPaymentsByAmount", method = RequestMethod.GET)
32495 amit.gupta 713
    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 714
        List<UnsettledPayment> up = null;
24089 tejbeer 715
 
32491 jai.hind 716
        long size = 0;
717
        up = unsettledPaymentsRepository.selectAllByAmount(amount, offset, limit);
24089 tejbeer 718
 
32491 jai.hind 719
        size = unsettledPaymentsRepository.selectAllCount();
720
        if (!up.isEmpty()) {
721
            model.addAttribute("unsettledPayment", up);
722
            model.addAttribute("start", offset + 1);
723
            model.addAttribute("size", size);
724
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 725
 
32491 jai.hind 726
            if (up.size() < limit) {
727
                model.addAttribute("end", offset + up.size());
728
            } else {
729
                model.addAttribute("end", offset + limit);
730
            }
731
            return "unsettle-payment-modal";
732
        } else {
733
            model.addAttribute("unsettledPayment", up);
734
            model.addAttribute("size", size);
735
        }
24089 tejbeer 736
 
32491 jai.hind 737
        return "unsettle-payment-modal";
738
    }
24089 tejbeer 739
 
32491 jai.hind 740
    @RequestMapping(value = "/createUnsettledPaymentsEntries", method = RequestMethod.POST)
32495 amit.gupta 741
    public String createUnsettledPaymentsEntries(HttpServletRequest request, @RequestBody UnsettledPaymentModel unsettledPaymentModel, Model model) throws Exception {
24089 tejbeer 742
 
32491 jai.hind 743
        UnsettledPayment up = new UnsettledPayment();
744
        up.setTransaction_reference(unsettledPaymentModel.getTransactionReference());
745
        up.setAmount(unsettledPaymentModel.getAmount());
746
        up.setDescription(unsettledPaymentModel.getDescription());
747
        up.setReference_date(unsettledPaymentModel.getReferenceDate());
748
        LOGGER.info("uppaynments" + up);
749
        unsettledPaymentsRepository.persist(up);
750
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
751
        return "response";
752
    }
24089 tejbeer 753
 
32491 jai.hind 754
    @RequestMapping(value = "/removeUnsettledPaymentsEntries", method = RequestMethod.DELETE)
32495 amit.gupta 755
    public String removeUnsettledPaymentsEntries(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
24089 tejbeer 756
 
32491 jai.hind 757
        unsettledPaymentsRepository.deleteById(id);
24089 tejbeer 758
 
32491 jai.hind 759
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
760
        return "response";
761
    }
24509 amit.gupta 762
 
32491 jai.hind 763
    @RequestMapping(value = "/wallet/statement", method = RequestMethod.GET)
32495 amit.gupta 764
    public String getWalletStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
32491 jai.hind 765
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
34441 tejus.loha 766
        if (!isAdmin) {
767
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
768
        }
32491 jai.hind 769
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
770
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32495 amit.gupta 771
        List<UserWalletHistory> uwhList = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDate, endDate, 0, 0);
32491 jai.hind 772
        Collections.reverse(uwhList);
773
        model.addAttribute("opening", openingBalance);
774
        model.addAttribute("closing", closingBalance);
775
        model.addAttribute("history", uwhList);
776
        model.addAttribute("startDate", startDate);
777
        model.addAttribute("endDate", endDate);
778
        return "walletStatement";
779
    }
29811 tejbeer 780
 
32491 jai.hind 781
    @RequestMapping(value = "/account/reco", method = RequestMethod.GET)
32495 amit.gupta 782
    public ResponseEntity<?> accountReco(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 783
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
784
        if (!isAdmin) {
785
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
786
        }
33207 amit.gupta 787
        LocalDateTime closingDateTime = closingDate.plusDays(1).atStartOfDay();
32491 jai.hind 788
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
789
        Set<Integer> retailersSet = customRetailerMap.keySet();
29070 amit.gupta 790
 
32491 jai.hind 791
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 792
 
32491 jai.hind 793
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 794
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 795
 
32491 jai.hind 796
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 797
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
32491 jai.hind 798
        Map<Integer, Float> closingWalletMap = userWalletHistoryRepository.getSumTillDate(closingDateTime, walletSet);
33212 amit.gupta 799
        Map<Integer, Float> peindingIndentMap = transactionService.getPendingIndentValueMap(closingDateTime, Optional.empty());
29811 tejbeer 800
 
32491 jai.hind 801
        List<List<?>> rows = new ArrayList<>();
802
        for (Map.Entry<Integer, Float> closingBalance : closingBalanceMap.entrySet()) {
803
            int walletId = closingBalance.getKey();
804
            int retailerId = walletRetailerMap.get(walletId);
29811 tejbeer 805
 
32491 jai.hind 806
            float accountClosing = 0f;
807
            if (!closingPurchaseMap.containsKey(retailerId)) {
808
                accountClosing = closingBalance.getValue();
809
            } else {
810
                accountClosing = closingBalance.getValue() - closingPurchaseMap.get(retailerId);
811
            }
29070 amit.gupta 812
 
32491 jai.hind 813
            CustomRetailer cr = customRetailerMap.get(retailerId);
29070 amit.gupta 814
 
32495 amit.gupta 815
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), accountClosing, closingWalletMap.get(walletId), peindingIndentMap.get(retailerId)));
32491 jai.hind 816
        }
29070 amit.gupta 817
 
32495 amit.gupta 818
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance", "Closing Wallet", "In Transit"), rows);
32491 jai.hind 819
        final HttpHeaders headers = new HttpHeaders();
820
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 821
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 822
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
29070 amit.gupta 823
 
32491 jai.hind 824
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
825
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
826
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
827
    }
29811 tejbeer 828
 
32491 jai.hind 829
    @RequestMapping(value = "/account/closing-statements", method = RequestMethod.GET)
32495 amit.gupta 830
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 831
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
832
        if (!isAdmin) {
833
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
834
        }
835
        LocalDateTime closingDateTime = closingDate.atStartOfDay().plusDays(1);
28597 amit.gupta 836
 
32491 jai.hind 837
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
838
        Set<Integer> retailersSet = customRetailerMap.keySet();
28597 amit.gupta 839
 
32491 jai.hind 840
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 841
 
32491 jai.hind 842
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 843
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 844
 
32491 jai.hind 845
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 846
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
28597 amit.gupta 847
 
32491 jai.hind 848
        List<List<?>> rows = new ArrayList<>();
849
        for (Map.Entry<Integer, Float> closingWalletBalance : closingBalanceMap.entrySet()) {
850
            int walletId = closingWalletBalance.getKey();
851
            int retailerId = walletRetailerMap.get(walletId);
852
            if (!closingPurchaseMap.containsKey(retailerId)) {
853
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue());
854
            } else {
32495 amit.gupta 855
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue() - closingPurchaseMap.get(retailerId));
32491 jai.hind 856
            }
857
            float closingValue = closingPurchaseMap.get(retailerId);
858
            CustomRetailer cr = customRetailerMap.get(retailerId);
28597 amit.gupta 859
 
32495 amit.gupta 860
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), closingValue));
32491 jai.hind 861
        }
28597 amit.gupta 862
 
32495 amit.gupta 863
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance"), rows);
32491 jai.hind 864
        final HttpHeaders headers = new HttpHeaders();
865
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 866
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 867
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28597 amit.gupta 868
 
32491 jai.hind 869
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
870
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28597 amit.gupta 871
 
32491 jai.hind 872
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28597 amit.gupta 873
 
32491 jai.hind 874
    }
28515 amit.gupta 875
 
32491 jai.hind 876
    @RequestMapping(value = "/account/statement", method = RequestMethod.GET)
32495 amit.gupta 877
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
34440 amit.gupta 878
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
879
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
880
        if (!isAdmin) {
881
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
882
        }
33212 amit.gupta 883
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
884
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32491 jai.hind 885
        UserWallet uw = walletService.getUserWallet(fofoId);
33220 amit.gupta 886
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
32495 amit.gupta 887
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
33220 amit.gupta 888
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
33205 amit.gupta 889
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
890
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType())).sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
33220 amit.gupta 891
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
33205 amit.gupta 892
 
32491 jai.hind 893
        InputStream is = getClass().getClassLoader().getResourceAsStream("account-statement.xlsx");
33205 amit.gupta 894
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
33225 amit.gupta 895
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
33212 amit.gupta 896
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
897
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
28515 amit.gupta 898
 
33212 amit.gupta 899
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
900
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
901
        LOGGER.info("Opening - {}, Closing - {}", openingPendingAmount, closingPendingAmount);
902
        ByteArrayOutputStream byteArrayOutputStream = this.populateData(is, openingBalance + openingPendingAmount, closingBalance + closingPendingAmount,
33225 amit.gupta 903
                customRetailer, history, startDate, endDate, billedStatementDetails);
33212 amit.gupta 904
 
32491 jai.hind 905
        final HttpHeaders headers = new HttpHeaders();
906
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
32495 amit.gupta 907
        headers.set("Content-disposition", "inline; filename=account-statement." + StringUtils.toHyphenatedString(startDate.toLocalDate()) + "-" + StringUtils.toHyphenatedString(endDate.toLocalDate()) + ".xlsx");
32491 jai.hind 908
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28515 amit.gupta 909
 
32491 jai.hind 910
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
911
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28515 amit.gupta 912
 
32491 jai.hind 913
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28515 amit.gupta 914
 
32491 jai.hind 915
    }
28597 amit.gupta 916
 
33205 amit.gupta 917
    @Autowired
918
    CreditNoteRepository creditNoteRepository;
919
    @Autowired
920
    CreditNoteLineRepository creditNoteLineRepository;
921
 
922
    private ByteArrayOutputStream populateData(InputStream is, float openingBalance, float closingBalance, CustomRetailer customRetailer, List<UserWalletHistory> history,
923
                                               LocalDateTime startLocalDateTime, LocalDateTime endLocalDateTime, List<StatementDetailModel> invoiceDetails) throws Exception {
924
        Map<LocalDate, List<StatementDetailModel>> dateInvoiceMap = invoiceDetails.stream().collect(Collectors.groupingBy(x -> x.getOnDate().toLocalDate()));
33220 amit.gupta 925
        //LOGGER.info("dateInvoiceMap - {}", dateInvoiceMap);
926
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
32491 jai.hind 927
        XSSFWorkbook workbook = new XSSFWorkbook(is);
928
        CreationHelper creationHelper = workbook.getCreationHelper();
33226 amit.gupta 929
        CellStyle dateStyle = workbook.createCellStyle();
930
        dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dd/mm/yyyy"));
28597 amit.gupta 931
 
32491 jai.hind 932
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
933
        Sheet sheet = workbook.getSheetAt(0);
33205 amit.gupta 934
        sheet.getRow(0).getCell(0).setCellValue(customRetailer.getBusinessName());
935
        sheet.getRow(1).getCell(1).setCellValue(new Date(startLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
936
        sheet.getRow(1).getCell(2).setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
32491 jai.hind 937
        sheet.getRow(2).getCell(2).setCellValue(openingBalance);
938
        long grandTotalDebit = 0l;
939
        long grandTotalCredit = 0l;
940
        int row = 4;
33212 amit.gupta 941
        LocalDate startDate = startLocalDateTime.toLocalDate();
33205 amit.gupta 942
        LocalDate endDate = endLocalDateTime.toLocalDate();
33220 amit.gupta 943
        LOGGER.info(" startDate - {}", startDate);
944
        LOGGER.info(" endDate - {}", endDate);
33226 amit.gupta 945
        double currentOpening = openingBalance;
33212 amit.gupta 946
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
947
            List<UserWalletHistory> datewiseWalletHistory = dateWalletMap.get(date);
33220 amit.gupta 948
            LOGGER.info("date - {}, datewiseWalletHistory - {}", date, datewiseWalletHistory);
33212 amit.gupta 949
            if (datewiseWalletHistory != null) {
950
                for (UserWalletHistory walletEntry : datewiseWalletHistory) {
951
                    Cell dateCell = sheet.createRow(row).createCell(0);
33226 amit.gupta 952
                    //Date
33212 amit.gupta 953
                    dateCell.setCellValue(new Date(walletEntry.getTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 954
                    dateCell.setCellStyle(dateStyle);
955
                    //TransactType
33212 amit.gupta 956
                    sheet.getRow(row).createCell(1).setCellValue(walletEntry.getReferenceType().toString());
33226 amit.gupta 957
                    //Reference Id
33227 amit.gupta 958
                    sheet.getRow(row).createCell(2).setCellValue(walletEntry.getReference());
33212 amit.gupta 959
                    if (walletEntry.getAmount() > 0) {
33226 amit.gupta 960
                        //Debit
33227 amit.gupta 961
                        sheet.getRow(row).createCell(3).setCellValue(0);
33226 amit.gupta 962
                        //Credit
33227 amit.gupta 963
                        sheet.getRow(row).createCell(4).setCellValue(walletEntry.getAmount());
33212 amit.gupta 964
                        grandTotalCredit += walletEntry.getAmount();
965
                    } else {
33227 amit.gupta 966
                        sheet.getRow(row).createCell(3).setCellValue(-walletEntry.getAmount());
967
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 968
                        grandTotalDebit -= walletEntry.getAmount();
969
                    }
33226 amit.gupta 970
                    //Running balance
971
                    currentOpening += walletEntry.getAmount();
33227 amit.gupta 972
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33226 amit.gupta 973
                    //Description
33227 amit.gupta 974
                    sheet.getRow(row).createCell(6).setCellValue(walletEntry.getDescription());
33212 amit.gupta 975
                    row++;
976
                }
977
            }
978
            List<StatementDetailModel> statementDetailModels = dateInvoiceMap.get(date);
979
            LOGGER.info("statementDetailModels - {}", statementDetailModels);
980
            if (statementDetailModels != null) {
981
                for (StatementDetailModel statementDetailModel : statementDetailModels) {
982
                    Cell dateCell = sheet.createRow(row).createCell(0);
983
                    dateCell.setCellValue(statementDetailModel.getOnDate());
33226 amit.gupta 984
                    dateCell.setCellStyle(dateStyle);
985
                    //Transact Type
33212 amit.gupta 986
                    sheet.getRow(row).createCell(1).setCellValue("BILLING");
33226 amit.gupta 987
                    //Transact Reference
33227 amit.gupta 988
                    sheet.getRow(row).createCell(2).setCellValue(statementDetailModel.getInvoiceNumber());
33212 amit.gupta 989
                    if (statementDetailModel.getAmount() > 0) {
33227 amit.gupta 990
                        sheet.getRow(row).createCell(3).setCellValue(statementDetailModel.getAmount());
991
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 992
                        grandTotalDebit += statementDetailModel.getAmount();
993
                    } else {
33227 amit.gupta 994
                        sheet.getRow(row).createCell(3).setCellValue(0);
995
                        sheet.getRow(row).createCell(4).setCellValue(-statementDetailModel.getAmount());
33212 amit.gupta 996
                        grandTotalCredit += -statementDetailModel.getAmount();
997
                    }
33226 amit.gupta 998
                    //Running Balance
33229 amit.gupta 999
                    currentOpening -= statementDetailModel.getAmount();
33228 amit.gupta 1000
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33212 amit.gupta 1001
 
33226 amit.gupta 1002
 
1003
                    //Narration
33227 amit.gupta 1004
                    sheet.getRow(row).createCell(6).setCellValue(statementDetailModel.getReferenceType());
33212 amit.gupta 1005
 
1006
                    row += 1;
1007
                }
1008
            }
1009
            if (YearMonth.from(date).atEndOfMonth().equals(date)) {
1010
                List<CreditNote> creditNotes = creditNoteRepository.selectAll(customRetailer.getPartnerId(), YearMonth.from(date));
1011
                if (creditNotes != null) {
1012
                    for (CreditNote creditNote : creditNotes) {
1013
                        double cnAmount = creditNoteLineRepository.selectAllByCreditNote(creditNote.getId()).stream().collect(Collectors.summingDouble(x -> x.getAmount()));
33205 amit.gupta 1014
                        Cell dateCell = sheet.createRow(row).createCell(0);
33212 amit.gupta 1015
                        dateCell.setCellValue(new Date(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 1016
                        dateCell.setCellStyle(dateStyle);
33212 amit.gupta 1017
                        sheet.getRow(row).createCell(1).setCellValue("CREDIT NOTE");
33227 amit.gupta 1018
                        sheet.getRow(row).createCell(2).setCellValue(creditNote.getCreditNoteNumber());
33212 amit.gupta 1019
                        if (cnAmount > 0) {
33227 amit.gupta 1020
                            sheet.getRow(row).createCell(3).setCellValue(0);
1021
                            sheet.getRow(row).createCell(4).setCellValue(cnAmount);
33212 amit.gupta 1022
                            grandTotalCredit += cnAmount;
1023
                        } else {
33227 amit.gupta 1024
                            sheet.getRow(row).createCell(3).setCellValue(-cnAmount);
1025
                            sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 1026
                            grandTotalDebit += -cnAmount;
33205 amit.gupta 1027
                        }
33226 amit.gupta 1028
                        //Running balance
1029
                        currentOpening += cnAmount;
33227 amit.gupta 1030
                        sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33226 amit.gupta 1031
                        //Narration
33227 amit.gupta 1032
                        sheet.getRow(row).createCell(6).setCellValue("Credit Note Issued");
33205 amit.gupta 1033
 
1034
                        row += 1;
1035
                    }
1036
                }
1037
            }
32491 jai.hind 1038
        }
33205 amit.gupta 1039
 
33238 amit.gupta 1040
        sheet.createRow(row).createCell(2).setCellValue("Grand Total");
1041
        sheet.getRow(row).createCell(3).setCellValue(grandTotalDebit);
1042
        sheet.getRow(row).createCell(4).setCellValue(grandTotalCredit);
1043
        /*row += 2;
32491 jai.hind 1044
        sheet.createRow(row).createCell(0).setCellValue("Closing Balance");
33238 amit.gupta 1045
        sheet.getRow(row).createCell(3).setCellValue(closingBalance);*/
32491 jai.hind 1046
        row++;
1047
        /*
1048
         * sheet.createRow(row).createCell(0).setCellValue("Pending Grns");
1049
         * sheet.getRow(row).createCell(2).setCellValue(closingBalance); row++;
1050
         */
1051
        try {
1052
            workbook.write(bos);
1053
        } finally {
1054
            workbook.close();
1055
            bos.close();
1056
        }
28515 amit.gupta 1057
 
32491 jai.hind 1058
        return bos;
1059
    }
24876 tejbeer 1060
 
32491 jai.hind 1061
    @RequestMapping(value = "/manualPayment", method = RequestMethod.GET)
1062
    public String ManualPayment(HttpServletRequest request, Model model) throws Exception {
1063
        model.addAttribute("referenceTypes", WalletReferenceType.referenceType);
1064
        model.addAttribute("transactionTypes", TransactionType.values());
1065
        return "wallet-edit";
24876 tejbeer 1066
 
32491 jai.hind 1067
    }
24876 tejbeer 1068
 
32491 jai.hind 1069
    @RequestMapping(value = "/getWalletHistory", method = RequestMethod.GET)
32495 amit.gupta 1070
    public String getWalletHistory(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
25018 tejbeer 1071
 
32491 jai.hind 1072
        LOGGER.info("type" + referenceType);
32495 amit.gupta 1073
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
25018 tejbeer 1074
 
32491 jai.hind 1075
        if (userWalletHistory.isEmpty()) {
1076
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1077
        }
25018 tejbeer 1078
 
32491 jai.hind 1079
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
25018 tejbeer 1080
 
32491 jai.hind 1081
        LOGGER.info("userWallet" + userWallet);
1082
        CustomRetailer customretailer = retailerService.getFofoRetailer(userWallet.getUserId());
25018 tejbeer 1083
 
32491 jai.hind 1084
        model.addAttribute("userWallet", userWallet);
1085
        model.addAttribute("customretailer", customretailer);
24876 tejbeer 1086
 
32491 jai.hind 1087
        model.addAttribute("wallethistory", userWalletHistory);
1088
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1089
        return "wallet-history";
25018 tejbeer 1090
 
32491 jai.hind 1091
    }
25018 tejbeer 1092
 
32491 jai.hind 1093
    @RequestMapping(value = "/getWalletHistoryByPartner", method = RequestMethod.GET)
32512 amit.gupta 1094
    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 1095
 
32491 jai.hind 1096
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
32495 amit.gupta 1097
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectPaginatedByWalletIdReferenceType(userWallet.getId(), referenceType, SortOrder.DESCENDING, offset, limit);
25018 tejbeer 1098
 
32491 jai.hind 1099
        CustomRetailer customretailer = retailerService.getFofoRetailer(fofoId);
25018 tejbeer 1100
 
32491 jai.hind 1101
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
32597 amit.gupta 1102
 
1103
        List<Loan> loans = null;
1104
        BigDecimal totalDue = BigDecimal.ZERO;
1105
        BigDecimal availableLimit = BigDecimal.ZERO;
1106
        BigDecimal creditlimit = BigDecimal.ZERO;
32598 amit.gupta 1107
        if (sdCreditRequirement != null) {
32597 amit.gupta 1108
            loans = loanRepository.selectActiveLoan(fofoId);
1109
            availableLimit = sdCreditRequirement.getAvailableLimit();
1110
            creditlimit = sdCreditRequirement.getLimit();
1111
            for (Loan loan : loans) {
1112
                BigDecimal pendingAmount = loan.getPendingAmount();
1113
                BigDecimal interestAccrued = loan.getInterestAccrued();
1114
                BigDecimal interestPaid = loan.getInterestPaid();
1115
                totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));
1116
                availableLimit = creditlimit.subtract(totalDue);
1117
            }
32491 jai.hind 1118
        }
1119
        model.addAttribute("userWallet", userWallet);
1120
        model.addAttribute("customretailer", customretailer);
1121
        model.addAttribute("wallethistory", userWalletHistory);
1122
        model.addAttribute("loans", loans);
1123
        model.addAttribute("totalDue", totalDue);
1124
        model.addAttribute("availableLimit", availableLimit);
1125
        model.addAttribute("creditlimit", creditlimit);
1126
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1127
        return "wallet-history";
1128
    }
30426 tejbeer 1129
 
24876 tejbeer 1130
 
32491 jai.hind 1131
    @RequestMapping(value = "/getPartnerName", method = RequestMethod.GET)
32495 amit.gupta 1132
    public String getPartnerName(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
24905 amit.gupta 1133
 
32495 amit.gupta 1134
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1135
        if (userWalletHistory.isEmpty()) {
1136
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1137
        }
1138
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
24905 amit.gupta 1139
 
32491 jai.hind 1140
        CustomRetailer retailer = retailerService.getFofoRetailer(userWallet.getUserId());
24905 amit.gupta 1141
 
32491 jai.hind 1142
        model.addAttribute("response1", mvcResponseSender.createResponseString(retailer));
24876 tejbeer 1143
 
32491 jai.hind 1144
        return "response";
24876 tejbeer 1145
 
32491 jai.hind 1146
    }
30677 amit.gupta 1147
 
32491 jai.hind 1148
    @RequestMapping(value = "/reset-wallet/9990381", method = RequestMethod.GET)
1149
    public String walletUpdate(Model model) throws Exception {
1150
        walletService.resetWallet();
1151
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1152
        return "response";
1153
    }
24876 tejbeer 1154
 
32491 jai.hind 1155
    @RequestMapping(value = "/walletUpdate", method = RequestMethod.POST)
32495 amit.gupta 1156
    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 1157
        WalletReferenceType referenceType = WalletReferenceType.findByValue(referenceTypeValue);
1158
        if (reference == 0 && referenceType.getValue() >= WalletReferenceType.INCENTIVES.getValue()) {
1159
            LOGGER.error("referenceType: " + referenceType);
1160
            ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(referenceType);
28515 amit.gupta 1161
 
32491 jai.hind 1162
            if (paymentType == null) {
1163
                paymentType = new ManualPaymentType();
1164
                paymentType.setReferenceType(referenceType);
1165
            }
1166
            paymentType.setCounter(paymentType.getCounter() + 1);
1167
            manualPaymentRequestRepository.persist(paymentType);
1168
            reference = paymentType.getCounter();
28515 amit.gupta 1169
 
32491 jai.hind 1170
        } else if (reference == 0) {
32495 amit.gupta 1171
            throw new ProfitMandiBusinessException("RefrenceId", reference, "System specific reference type cant be used manually");
32491 jai.hind 1172
        }
24876 tejbeer 1173
 
32495 amit.gupta 1174
        List<UserWalletHistory> userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1175
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
1176
        int walletId = userWallet.getId();
1177
        int walletAmount = walletService.getWalletAmount(retailerId);
24876 tejbeer 1178
 
32491 jai.hind 1179
        int returnReference = 0;
1180
        UserWalletHistory newUserWalletHistory = new UserWalletHistory();
28515 amit.gupta 1181
 
32491 jai.hind 1182
        if (!userWalletHistoryList.isEmpty()) {
1183
            long validRetailerEntries = userWalletHistoryList.stream().filter(x -> x.getWalletId() == walletId).count();
1184
            if (validRetailerEntries == 0) {
32495 amit.gupta 1185
                throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id assign to Other  partner");
32491 jai.hind 1186
            }
1187
        }
28515 amit.gupta 1188
 
32491 jai.hind 1189
        if (TransactionType.DEBIT.equals(transactiontype)) {
1190
            amount = -amount;
1191
        }
26485 amit.gupta 1192
 
32491 jai.hind 1193
        userWallet.setAmount(walletAmount + amount);
1194
        newUserWalletHistory.setAmount(amount);
1195
        newUserWalletHistory.setBusinessTimestamp(businessTimestamp);
1196
        newUserWalletHistory.setDescription(description);
1197
        newUserWalletHistory.setReference(reference);
1198
        newUserWalletHistory.setWalletId(userWallet.getId());
1199
        newUserWalletHistory.setReferenceType(referenceType);
1200
        newUserWalletHistory.setTimestamp(LocalDateTime.now());
36513 amit 1201
        newUserWalletHistory.setRunningBalance(userWallet.getAmount());
32491 jai.hind 1202
        userWalletHistoryRepository.persist(newUserWalletHistory);
24876 tejbeer 1203
 
32491 jai.hind 1204
        model.addAttribute("response1", mvcResponseSender.createResponseString(reference));
1205
        return "response";
25018 tejbeer 1206
 
32491 jai.hind 1207
    }
25018 tejbeer 1208
 
32491 jai.hind 1209
    @RequestMapping(value = "/addMoney", method = RequestMethod.POST)
32495 amit.gupta 1210
    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 1211
        transactionReference = transactionReference.toUpperCase().trim();
1212
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectByReference(transactionReference);
34096 aman.kumar 1213
        addWalletRequests = addWalletRequests.stream().filter(x -> Arrays.asList(approved, AddWalletRequestStatus.pending).contains(x.getStatus())).collect(Collectors.toList());
33175 amit.gupta 1214
        if (addWalletRequests.size() > 0) {
1215
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1216
        }
1217
        HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(transactionReference);
33205 amit.gupta 1218
        if (hdfcPayment != null) {
33175 amit.gupta 1219
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1220
        }
32491 jai.hind 1221
        AddWalletRequest addWalletRequest = new AddWalletRequest();
1222
        addWalletRequest.setRetailerId(fofoId);
1223
        addWalletRequest.setAmount(amount);
33175 amit.gupta 1224
        addWalletRequest.setTransaction_reference(transactionReference.toUpperCase());
32491 jai.hind 1225
        addWalletRequest.setCreateTimestamp(LocalDateTime.now());
1226
        addWalletRequest.setBank_name(bankName);
1227
        addWalletRequest.setReference_date(referenceTime.toLocalDate());
1228
        addWalletRequest.setStatus(AddWalletRequestStatus.pending);
25018 tejbeer 1229
 
32491 jai.hind 1230
        LOGGER.info("info" + addWalletRequest);
29811 tejbeer 1231
 
32491 jai.hind 1232
        addWalletRequestRepository.persist(addWalletRequest);
1233
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1234
        return "response";
1235
    }
29811 tejbeer 1236
 
33045 amit.gupta 1237
    List<Gateway> directGateways = Arrays.asList(Gateway.SDDIRECT, Gateway.SIDBI);
1238
 
1239
    @Autowired
1240
    FofoSidbiSanctionRepository fofoSidbiSanctionRepository;
33175 amit.gupta 1241
 
32491 jai.hind 1242
    @RequestMapping(value = "/getCreditDetail", method = RequestMethod.GET)
1243
    public String getCreditDetail(HttpServletRequest request, Model model) throws Exception {
33175 amit.gupta 1244
        List<CreditAccount> creditAccounts = creditAccountRepository.selectAll().stream().filter(x -> directGateways.contains(x.getGateway())).collect(Collectors.toList());
32491 jai.hind 1245
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29962 tejbeer 1246
 
33420 amit.gupta 1247
        List<Integer> fofoIds = creditAccounts.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
33045 amit.gupta 1248
        //Need to maintain valid upto
33175 amit.gupta 1249
        Map<Integer, FofoSidbiSanction> fofoSidbiPendingSanctionsMap = fofoSidbiSanctionRepository.selectAll(Optional.of(false)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
29811 tejbeer 1250
 
33420 amit.gupta 1251
        Map<Integer, Integer> partnerAverageCreditDaysMap = new HashMap<>();
33045 amit.gupta 1252
 
33420 amit.gupta 1253
        List<Loan> loans = loanRepository.selectAllLoans(fofoIds, DateRangeModel.withStartDate(LocalDate.now().atStartOfDay().minusYears(2)));
1254
        Map<Integer, List<Loan>> partnerClosedLoansMap = loans.stream().filter(x -> x.getPendingAmount().compareTo(BigDecimal.ZERO) == 0)
1255
                .collect(Collectors.groupingBy(x -> x.getFofoId()));
1256
        for (Integer fofoId : fofoIds) {
1257
            List<Loan> closedLoans = partnerClosedLoansMap.get(fofoId);
1258
 
1259
            if (closedLoans != null) {
1260
                long averageCreditDays = Math.round(closedLoans.stream().mapToLong(x -> Duration.between(x.getCreatedOn(),
1261
                        x.getSettledOn() == null ? x.getCreatedOn().plusDays(10) : x.getSettledOn()).toDays() + 1).average().orElse(0.0));
1262
                partnerAverageCreditDaysMap.put(fofoId, (int) averageCreditDays);
1263
            }
1264
        }
1265
 
1266
 
32491 jai.hind 1267
        model.addAttribute("creditAccounts", creditAccounts);
33045 amit.gupta 1268
        model.addAttribute("fofoSidbiPendingSanctionsMap", fofoSidbiPendingSanctionsMap);
1269
        model.addAttribute("directGateways", directGateways);
32491 jai.hind 1270
        model.addAttribute("customRetailers", customRetailers);
33420 amit.gupta 1271
        model.addAttribute("partnerAverageCreditDaysMap", partnerAverageCreditDaysMap);
32491 jai.hind 1272
        return "partner-credit-detail";
1273
    }
29811 tejbeer 1274
 
33045 amit.gupta 1275
 
33359 amit.gupta 1276
    @Autowired
1277
    SidbiService sidbiService;
33363 amit.gupta 1278
 
32491 jai.hind 1279
    @RequestMapping(value = "/activateKred", method = RequestMethod.POST)
33045 amit.gupta 1280
    public String activateKred(HttpServletRequest request, @RequestParam int id, Model model, @RequestParam Gateway gateway) throws Exception {
32491 jai.hind 1281
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
33359 amit.gupta 1282
        if (creditAccount.getGateway().equals(gateway)) {
1283
            creditAccount.setActive(true);
1284
        } else {
33363 amit.gupta 1285
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(creditAccount.getFofoId());
33360 amit.gupta 1286
 
33363 amit.gupta 1287
            if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) != 0) {
33360 amit.gupta 1288
                LOGGER.info("sdCreditRequirement - {}", sdCreditRequirement);
33363 amit.gupta 1289
                throw new ProfitMandiBusinessException("Could not change to " + gateway + " unless previous loans are settled", "", "");
33205 amit.gupta 1290
            }
33359 amit.gupta 1291
            if (gateway.equals(Gateway.SIDBI)) {
1292
                //TODO - Issuance pending
1293
                FofoSidbiSanction fofoSidbiSanction = fofoSidbiSanctionRepository.selectByFofoId(creditAccount.getFofoId());
1294
                sidbiService.issueLimit(fofoSidbiSanction);
33363 amit.gupta 1295
                sdCreditRequirement.setLimit(BigDecimal.valueOf(fofoSidbiSanction.getLoanAmount()));
1296
                sdCreditRequirement.setSuggestedLimit(sdCreditRequirement.getLimit());
33359 amit.gupta 1297
                if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) > 0) {
1298
                    throw new ProfitMandiBusinessException("Loans are not closed", "Loans are not closed", "Loans are not closed");
1299
                }
33363 amit.gupta 1300
                creditAccount.setSanctionedAmount((float) fofoSidbiSanction.getLoanAmount());
33359 amit.gupta 1301
            }
33363 amit.gupta 1302
            creditAccount.setAvailableAmount(creditAccount.getSanctionedAmount());
1303
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
1304
            creditAccount.setActive(true);
1305
            creditAccount.setGateway(gateway);
33045 amit.gupta 1306
        }
29811 tejbeer 1307
 
32491 jai.hind 1308
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
30859 tejbeer 1309
 
34712 amit.gupta 1310
        String title = "Credit Limit Approved";
32491 jai.hind 1311
        String url = "http://app.smartdukaan.com/pages/home/credit";
32495 amit.gupta 1312
        String message = "Congratulations! Your Credit Limit is approved for Rs." + FormattingUtils.formatDecimal(creditAccount.getSanctionedAmount());
1313
        notificationService.sendNotification(creditAccount.getFofoId(), "Loan", MessageType.notification, title, message, url);
29811 tejbeer 1314
 
32491 jai.hind 1315
        model.addAttribute("creditAccount", creditAccount);
1316
        model.addAttribute("customRetailers", customRetailers);
1317
        return "partner-credit-detail-row";
1318
    }
29811 tejbeer 1319
 
32491 jai.hind 1320
    @RequestMapping(value = "/deactivateKred", method = RequestMethod.POST)
1321
    public String deactivateKred(HttpServletRequest request, @RequestParam int id, Model model) throws Exception {
1322
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
29811 tejbeer 1323
 
32491 jai.hind 1324
        creditAccount.setActive(false);
29811 tejbeer 1325
 
32491 jai.hind 1326
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29811 tejbeer 1327
 
32491 jai.hind 1328
        model.addAttribute("creditAccount", creditAccount);
1329
        model.addAttribute("customRetailers", customRetailers);
1330
        return "partner-credit-detail-row";
1331
    }
1332
 
34261 tejus.loha 1333
    @RequestMapping(value = "/downloadAddWalletRequestReport", method = RequestMethod.GET)
34527 tejus.loha 1334
    public ResponseEntity<?> addWalletRequestPendingReport(@RequestParam LocalDate startDate, @RequestParam LocalDate endDate, @RequestParam AddWalletRequestStatus status, Model model) throws Exception {
1335
        if (endDate == null) {
1336
            endDate = LocalDate.now();
34261 tejus.loha 1337
        }
1338
        LocalDateTime form = startDate.atStartOfDay();
1339
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1340
        return walletService.createAddWalletRequestReport(form, to, status);
1341
    }
1342
 
34527 tejus.loha 1343
    @GetMapping(value = "/getHdfcPaymentsReport")
1344
    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 1345
 
34527 tejus.loha 1346
        if (startDate == null) {
1347
            startDate = LocalDate.now().minusDays(7);
1348
        }
1349
        if (endDate == null) {
1350
            endDate = LocalDate.now();
1351
        }
1352
        LocalDateTime form = startDate.atStartOfDay();
1353
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1354
        List<HdfcPayment> hdfcPayments = hdfcPaymentRepository.selectAllByTransferModeAndDataRange(transferMode, form, to);
1355
        Map<Integer, CustomRetailer> allFofoRetailers = retailerService.getAllFofoRetailers();
1356
        List<HdfcPaymentModel> hdfcPaymentModelList = new ArrayList<>();
1357
        if (hdfcPayments != null && hdfcPayments.size() > 0) {
1358
            for (HdfcPayment upiPayment : hdfcPayments) {
1359
                HdfcPaymentModel hdfcPaymentModel = new HdfcPaymentModel();
1360
                // remove prifix to get fofoId = "nwspic" from virtual account "nwspicFOFOID" eg "nwspic175140063" to "175140063"
1361
                String partnerIdString = upiPayment.getVirtualAccount().substring(6);
1362
                CustomRetailer customRetailer = allFofoRetailers.get(Integer.parseInt(partnerIdString));
1363
                hdfcPaymentModel.setAmount(upiPayment.getAmount());
1364
                hdfcPaymentModel.setName(customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")");
1365
                hdfcPaymentModel.setUtr(upiPayment.getUtr());
1366
                hdfcPaymentModel.setCreateTimestamp(upiPayment.getCreateTimestamp());
1367
                hdfcPaymentModel.setCreditTimestamp(upiPayment.getCreditTimestamp());
1368
                hdfcPaymentModel.setTransactionId(upiPayment.getTransactionId());
1369
                hdfcPaymentModel.setTransferMode(upiPayment.getTransferMode());
1370
                hdfcPaymentModelList.add(hdfcPaymentModel);
1371
            }
1372
        }
1373
 
1374
        List<String> transferModeList = Arrays.asList("OTH","FUND TRANS","IMPS","NEFT","RTGS");
1375
        model.addAttribute("hdfcPaymentModels", hdfcPaymentModelList);
1376
        model.addAttribute("startDate", startDate);
1377
        model.addAttribute("endDate", endDate);
1378
        model.addAttribute("mode", transferMode);
1379
        model.addAttribute("transferModeList", transferModeList);
1380
        return "upi-payments-report-panel";
1381
    }
1382
 
1383
 
22551 ashik.ali 1384
}