Subversion Repositories SmartDukaan

Rev

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