Subversion Repositories SmartDukaan

Rev

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