Subversion Repositories SmartDukaan

Rev

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