Subversion Repositories SmartDukaan

Rev

Rev 35971 | 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);
36064 aman 548
                    try {
549
                        storeTimelineTatService.sendFullStockPaymentPOEmail(storeTimelineModel.getOnboardingId());
550
                    } catch (Exception ex) {
551
                        LOGGER.error("Failed to send FSP PO email after approved FSP >= 7L for onboardingId=" + storeTimelineModel.getOnboardingId(), ex);
552
                    }
35971 aman 553
                }
33861 tejus.loha 554
            }
555
 
32491 jai.hind 556
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
557
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 558
            String subject = "Request Approved for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
559
            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 560
 
32491 jai.hind 561
            //	this.sendMailWithAttachments(subject, messageText);
562
            return "response";
563
        } else {
564
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
565
            return "response";
566
        }
567
    }
23993 tejbeer 568
 
32491 jai.hind 569
    @RequestMapping(value = "/addAmountToWalletRequestRejected", method = RequestMethod.PUT)
32495 amit.gupta 570
    public String addAmountToWalletRequestRejected(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
23993 tejbeer 571
 
32491 jai.hind 572
        AddWalletRequest addWalletRequest = addWalletRequestRepository.selectById(id);
573
        if (addWalletRequest.getStatus().equals(AddWalletRequestStatus.pending)) {
574
            addWalletRequest.setStatus(AddWalletRequestStatus.rejected);
575
            addWalletRequest.setUpdateTimestamp(LocalDateTime.now());
576
            addWalletRequestRepository.persist(addWalletRequest);
35971 aman 577
 
578
            // Mark linked FSP as REJECTED via fspId
579
            if (addWalletRequest.getFspId() > 0) {
580
                try {
581
                    FullStockPayment fsp = fullStockPaymentRepository.selectById(addWalletRequest.getFspId());
582
                    if (fsp != null && fsp.getPaymentStatus() == FullStockPaymentStatus.PENDING) {
583
                        fsp.setPaymentStatus(FullStockPaymentStatus.REJECTED);
584
                        fsp.setDescription("Wallet addon request rejected");
585
                        fsp.setApproveTimestamp(LocalDateTime.now());
586
                        fullStockPaymentRepository.persist(fsp);
587
                        LOGGER.info("Marked FSP id={} as REJECTED via wallet addon rejection", fsp.getId());
588
                    }
589
                } catch (Exception e) {
590
                    LOGGER.error("Error marking FSP as REJECTED on wallet addon rejection", e);
591
                }
592
            }
593
 
32491 jai.hind 594
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
595
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 596
            String subject = "Request Rejected for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
597
            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 598
 
32491 jai.hind 599
            //this.sendMailWithAttachments(subject, messageText);
600
            return "response";
601
        } else {
602
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
603
            return "response";
604
        }
605
    }
23985 tejbeer 606
 
32491 jai.hind 607
    private void sendMailWithAttachments(String subject, String messageText) throws Exception {
608
        MimeMessage message = mailSender.createMimeMessage();
609
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
32495 amit.gupta 610
        String[] email = {"neerajgupta2021@gmail.com", "adeel.yazdani@smartdukaan.com", "kamini.sharma@smartdukaan.com", "care@smartdukaan.com", "mohinder.mutreja@smartdukaan.com"};
32491 jai.hind 611
        helper.setSubject(subject);
612
        helper.setText(messageText);
613
        helper.setTo(email);
614
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
615
        helper.setFrom(senderAddress);
616
        mailSender.send(message);
23993 tejbeer 617
 
32491 jai.hind 618
    }
23936 tejbeer 619
 
32491 jai.hind 620
    private List<Integer> getFofoIdsFromWalletRequest(List<AddWalletRequest> walletRequest) {
621
        return walletRequest.stream().map(x -> x.getRetailerId()).distinct().collect(Collectors.toList());
622
    }
24089 tejbeer 623
 
32491 jai.hind 624
    @RequestMapping(value = "/getcreateUnsettledPayments", method = RequestMethod.GET)
32495 amit.gupta 625
    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 626
        List<UnsettledPayment> up = null;
24089 tejbeer 627
 
32491 jai.hind 628
        long size = 0;
629
        up = unsettledPaymentsRepository.selectAllById(offset, limit);
24089 tejbeer 630
 
32491 jai.hind 631
        size = unsettledPaymentsRepository.selectAllCount();
632
        if (!up.isEmpty()) {
633
            model.addAttribute("unsettledPayment", up);
634
            model.addAttribute("start", offset + 1);
635
            model.addAttribute("size", size);
636
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 637
 
32491 jai.hind 638
            if (up.size() < limit) {
639
                model.addAttribute("end", offset + up.size());
640
            } else {
641
                model.addAttribute("end", offset + limit);
642
            }
643
        } else {
644
            model.addAttribute("unsettledPayment", up);
645
            model.addAttribute("size", size);
646
        }
24089 tejbeer 647
 
32491 jai.hind 648
        LOGGER.info("unsettledPaymentList" + up);
649
        return "unsettled-payments";
650
    }
24089 tejbeer 651
 
32491 jai.hind 652
    @RequestMapping(value = "/getUnsettledPaymentsByAmount", method = RequestMethod.GET)
32495 amit.gupta 653
    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 654
        List<UnsettledPayment> up = null;
24089 tejbeer 655
 
32491 jai.hind 656
        long size = 0;
657
        up = unsettledPaymentsRepository.selectAllByAmount(amount, offset, limit);
24089 tejbeer 658
 
32491 jai.hind 659
        size = unsettledPaymentsRepository.selectAllCount();
660
        if (!up.isEmpty()) {
661
            model.addAttribute("unsettledPayment", up);
662
            model.addAttribute("start", offset + 1);
663
            model.addAttribute("size", size);
664
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 665
 
32491 jai.hind 666
            if (up.size() < limit) {
667
                model.addAttribute("end", offset + up.size());
668
            } else {
669
                model.addAttribute("end", offset + limit);
670
            }
671
            return "unsettle-payment-modal";
672
        } else {
673
            model.addAttribute("unsettledPayment", up);
674
            model.addAttribute("size", size);
675
        }
24089 tejbeer 676
 
32491 jai.hind 677
        return "unsettle-payment-modal";
678
    }
24089 tejbeer 679
 
32491 jai.hind 680
    @RequestMapping(value = "/createUnsettledPaymentsEntries", method = RequestMethod.POST)
32495 amit.gupta 681
    public String createUnsettledPaymentsEntries(HttpServletRequest request, @RequestBody UnsettledPaymentModel unsettledPaymentModel, Model model) throws Exception {
24089 tejbeer 682
 
32491 jai.hind 683
        UnsettledPayment up = new UnsettledPayment();
684
        up.setTransaction_reference(unsettledPaymentModel.getTransactionReference());
685
        up.setAmount(unsettledPaymentModel.getAmount());
686
        up.setDescription(unsettledPaymentModel.getDescription());
687
        up.setReference_date(unsettledPaymentModel.getReferenceDate());
688
        LOGGER.info("uppaynments" + up);
689
        unsettledPaymentsRepository.persist(up);
690
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
691
        return "response";
692
    }
24089 tejbeer 693
 
32491 jai.hind 694
    @RequestMapping(value = "/removeUnsettledPaymentsEntries", method = RequestMethod.DELETE)
32495 amit.gupta 695
    public String removeUnsettledPaymentsEntries(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
24089 tejbeer 696
 
32491 jai.hind 697
        unsettledPaymentsRepository.deleteById(id);
24089 tejbeer 698
 
32491 jai.hind 699
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
700
        return "response";
701
    }
24509 amit.gupta 702
 
32491 jai.hind 703
    @RequestMapping(value = "/wallet/statement", method = RequestMethod.GET)
32495 amit.gupta 704
    public String getWalletStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
32491 jai.hind 705
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
34441 tejus.loha 706
        if (!isAdmin) {
707
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
708
        }
32491 jai.hind 709
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
710
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32495 amit.gupta 711
        List<UserWalletHistory> uwhList = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDate, endDate, 0, 0);
32491 jai.hind 712
        Collections.reverse(uwhList);
713
        model.addAttribute("opening", openingBalance);
714
        model.addAttribute("closing", closingBalance);
715
        model.addAttribute("history", uwhList);
716
        model.addAttribute("startDate", startDate);
717
        model.addAttribute("endDate", endDate);
718
        return "walletStatement";
719
    }
29811 tejbeer 720
 
32491 jai.hind 721
    @RequestMapping(value = "/account/reco", method = RequestMethod.GET)
32495 amit.gupta 722
    public ResponseEntity<?> accountReco(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 723
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
724
        if (!isAdmin) {
725
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
726
        }
33207 amit.gupta 727
        LocalDateTime closingDateTime = closingDate.plusDays(1).atStartOfDay();
32491 jai.hind 728
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
729
        Set<Integer> retailersSet = customRetailerMap.keySet();
29070 amit.gupta 730
 
32491 jai.hind 731
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 732
 
32491 jai.hind 733
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 734
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 735
 
32491 jai.hind 736
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 737
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
32491 jai.hind 738
        Map<Integer, Float> closingWalletMap = userWalletHistoryRepository.getSumTillDate(closingDateTime, walletSet);
33212 amit.gupta 739
        Map<Integer, Float> peindingIndentMap = transactionService.getPendingIndentValueMap(closingDateTime, Optional.empty());
29811 tejbeer 740
 
32491 jai.hind 741
        List<List<?>> rows = new ArrayList<>();
742
        for (Map.Entry<Integer, Float> closingBalance : closingBalanceMap.entrySet()) {
743
            int walletId = closingBalance.getKey();
744
            int retailerId = walletRetailerMap.get(walletId);
29811 tejbeer 745
 
32491 jai.hind 746
            float accountClosing = 0f;
747
            if (!closingPurchaseMap.containsKey(retailerId)) {
748
                accountClosing = closingBalance.getValue();
749
            } else {
750
                accountClosing = closingBalance.getValue() - closingPurchaseMap.get(retailerId);
751
            }
29070 amit.gupta 752
 
32491 jai.hind 753
            CustomRetailer cr = customRetailerMap.get(retailerId);
29070 amit.gupta 754
 
32495 amit.gupta 755
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), accountClosing, closingWalletMap.get(walletId), peindingIndentMap.get(retailerId)));
32491 jai.hind 756
        }
29070 amit.gupta 757
 
32495 amit.gupta 758
        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 759
        final HttpHeaders headers = new HttpHeaders();
760
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 761
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 762
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
29070 amit.gupta 763
 
32491 jai.hind 764
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
765
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
766
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
767
    }
29811 tejbeer 768
 
32491 jai.hind 769
    @RequestMapping(value = "/account/closing-statements", method = RequestMethod.GET)
32495 amit.gupta 770
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 771
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
772
        if (!isAdmin) {
773
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
774
        }
775
        LocalDateTime closingDateTime = closingDate.atStartOfDay().plusDays(1);
28597 amit.gupta 776
 
32491 jai.hind 777
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
778
        Set<Integer> retailersSet = customRetailerMap.keySet();
28597 amit.gupta 779
 
32491 jai.hind 780
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 781
 
32491 jai.hind 782
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 783
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 784
 
32491 jai.hind 785
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 786
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
28597 amit.gupta 787
 
32491 jai.hind 788
        List<List<?>> rows = new ArrayList<>();
789
        for (Map.Entry<Integer, Float> closingWalletBalance : closingBalanceMap.entrySet()) {
790
            int walletId = closingWalletBalance.getKey();
791
            int retailerId = walletRetailerMap.get(walletId);
792
            if (!closingPurchaseMap.containsKey(retailerId)) {
793
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue());
794
            } else {
32495 amit.gupta 795
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue() - closingPurchaseMap.get(retailerId));
32491 jai.hind 796
            }
797
            float closingValue = closingPurchaseMap.get(retailerId);
798
            CustomRetailer cr = customRetailerMap.get(retailerId);
28597 amit.gupta 799
 
32495 amit.gupta 800
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), closingValue));
32491 jai.hind 801
        }
28597 amit.gupta 802
 
32495 amit.gupta 803
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance"), rows);
32491 jai.hind 804
        final HttpHeaders headers = new HttpHeaders();
805
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 806
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 807
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28597 amit.gupta 808
 
32491 jai.hind 809
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
810
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28597 amit.gupta 811
 
32491 jai.hind 812
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28597 amit.gupta 813
 
32491 jai.hind 814
    }
28515 amit.gupta 815
 
32491 jai.hind 816
    @RequestMapping(value = "/account/statement", method = RequestMethod.GET)
32495 amit.gupta 817
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
34440 amit.gupta 818
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
819
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
820
        if (!isAdmin) {
821
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
822
        }
33212 amit.gupta 823
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
824
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32491 jai.hind 825
        UserWallet uw = walletService.getUserWallet(fofoId);
33220 amit.gupta 826
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
32495 amit.gupta 827
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
33220 amit.gupta 828
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
33205 amit.gupta 829
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
830
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType())).sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
33220 amit.gupta 831
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
33205 amit.gupta 832
 
32491 jai.hind 833
        InputStream is = getClass().getClassLoader().getResourceAsStream("account-statement.xlsx");
33205 amit.gupta 834
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
33225 amit.gupta 835
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
33212 amit.gupta 836
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
837
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
28515 amit.gupta 838
 
33212 amit.gupta 839
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
840
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
841
        LOGGER.info("Opening - {}, Closing - {}", openingPendingAmount, closingPendingAmount);
842
        ByteArrayOutputStream byteArrayOutputStream = this.populateData(is, openingBalance + openingPendingAmount, closingBalance + closingPendingAmount,
33225 amit.gupta 843
                customRetailer, history, startDate, endDate, billedStatementDetails);
33212 amit.gupta 844
 
32491 jai.hind 845
        final HttpHeaders headers = new HttpHeaders();
846
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
32495 amit.gupta 847
        headers.set("Content-disposition", "inline; filename=account-statement." + StringUtils.toHyphenatedString(startDate.toLocalDate()) + "-" + StringUtils.toHyphenatedString(endDate.toLocalDate()) + ".xlsx");
32491 jai.hind 848
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28515 amit.gupta 849
 
32491 jai.hind 850
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
851
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28515 amit.gupta 852
 
32491 jai.hind 853
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28515 amit.gupta 854
 
32491 jai.hind 855
    }
28597 amit.gupta 856
 
33205 amit.gupta 857
    @Autowired
858
    CreditNoteRepository creditNoteRepository;
859
    @Autowired
860
    CreditNoteLineRepository creditNoteLineRepository;
861
 
862
    private ByteArrayOutputStream populateData(InputStream is, float openingBalance, float closingBalance, CustomRetailer customRetailer, List<UserWalletHistory> history,
863
                                               LocalDateTime startLocalDateTime, LocalDateTime endLocalDateTime, List<StatementDetailModel> invoiceDetails) throws Exception {
864
        Map<LocalDate, List<StatementDetailModel>> dateInvoiceMap = invoiceDetails.stream().collect(Collectors.groupingBy(x -> x.getOnDate().toLocalDate()));
33220 amit.gupta 865
        //LOGGER.info("dateInvoiceMap - {}", dateInvoiceMap);
866
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
32491 jai.hind 867
        XSSFWorkbook workbook = new XSSFWorkbook(is);
868
        CreationHelper creationHelper = workbook.getCreationHelper();
33226 amit.gupta 869
        CellStyle dateStyle = workbook.createCellStyle();
870
        dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dd/mm/yyyy"));
28597 amit.gupta 871
 
32491 jai.hind 872
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
873
        Sheet sheet = workbook.getSheetAt(0);
33205 amit.gupta 874
        sheet.getRow(0).getCell(0).setCellValue(customRetailer.getBusinessName());
875
        sheet.getRow(1).getCell(1).setCellValue(new Date(startLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
876
        sheet.getRow(1).getCell(2).setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
32491 jai.hind 877
        sheet.getRow(2).getCell(2).setCellValue(openingBalance);
878
        long grandTotalDebit = 0l;
879
        long grandTotalCredit = 0l;
880
        int row = 4;
33212 amit.gupta 881
        LocalDate startDate = startLocalDateTime.toLocalDate();
33205 amit.gupta 882
        LocalDate endDate = endLocalDateTime.toLocalDate();
33220 amit.gupta 883
        LOGGER.info(" startDate - {}", startDate);
884
        LOGGER.info(" endDate - {}", endDate);
33226 amit.gupta 885
        double currentOpening = openingBalance;
33212 amit.gupta 886
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
887
            List<UserWalletHistory> datewiseWalletHistory = dateWalletMap.get(date);
33220 amit.gupta 888
            LOGGER.info("date - {}, datewiseWalletHistory - {}", date, datewiseWalletHistory);
33212 amit.gupta 889
            if (datewiseWalletHistory != null) {
890
                for (UserWalletHistory walletEntry : datewiseWalletHistory) {
891
                    Cell dateCell = sheet.createRow(row).createCell(0);
33226 amit.gupta 892
                    //Date
33212 amit.gupta 893
                    dateCell.setCellValue(new Date(walletEntry.getTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 894
                    dateCell.setCellStyle(dateStyle);
895
                    //TransactType
33212 amit.gupta 896
                    sheet.getRow(row).createCell(1).setCellValue(walletEntry.getReferenceType().toString());
33226 amit.gupta 897
                    //Reference Id
33227 amit.gupta 898
                    sheet.getRow(row).createCell(2).setCellValue(walletEntry.getReference());
33212 amit.gupta 899
                    if (walletEntry.getAmount() > 0) {
33226 amit.gupta 900
                        //Debit
33227 amit.gupta 901
                        sheet.getRow(row).createCell(3).setCellValue(0);
33226 amit.gupta 902
                        //Credit
33227 amit.gupta 903
                        sheet.getRow(row).createCell(4).setCellValue(walletEntry.getAmount());
33212 amit.gupta 904
                        grandTotalCredit += walletEntry.getAmount();
905
                    } else {
33227 amit.gupta 906
                        sheet.getRow(row).createCell(3).setCellValue(-walletEntry.getAmount());
907
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 908
                        grandTotalDebit -= walletEntry.getAmount();
909
                    }
33226 amit.gupta 910
                    //Running balance
911
                    currentOpening += walletEntry.getAmount();
33227 amit.gupta 912
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33226 amit.gupta 913
                    //Description
33227 amit.gupta 914
                    sheet.getRow(row).createCell(6).setCellValue(walletEntry.getDescription());
33212 amit.gupta 915
                    row++;
916
                }
917
            }
918
            List<StatementDetailModel> statementDetailModels = dateInvoiceMap.get(date);
919
            LOGGER.info("statementDetailModels - {}", statementDetailModels);
920
            if (statementDetailModels != null) {
921
                for (StatementDetailModel statementDetailModel : statementDetailModels) {
922
                    Cell dateCell = sheet.createRow(row).createCell(0);
923
                    dateCell.setCellValue(statementDetailModel.getOnDate());
33226 amit.gupta 924
                    dateCell.setCellStyle(dateStyle);
925
                    //Transact Type
33212 amit.gupta 926
                    sheet.getRow(row).createCell(1).setCellValue("BILLING");
33226 amit.gupta 927
                    //Transact Reference
33227 amit.gupta 928
                    sheet.getRow(row).createCell(2).setCellValue(statementDetailModel.getInvoiceNumber());
33212 amit.gupta 929
                    if (statementDetailModel.getAmount() > 0) {
33227 amit.gupta 930
                        sheet.getRow(row).createCell(3).setCellValue(statementDetailModel.getAmount());
931
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 932
                        grandTotalDebit += statementDetailModel.getAmount();
933
                    } else {
33227 amit.gupta 934
                        sheet.getRow(row).createCell(3).setCellValue(0);
935
                        sheet.getRow(row).createCell(4).setCellValue(-statementDetailModel.getAmount());
33212 amit.gupta 936
                        grandTotalCredit += -statementDetailModel.getAmount();
937
                    }
33226 amit.gupta 938
                    //Running Balance
33229 amit.gupta 939
                    currentOpening -= statementDetailModel.getAmount();
33228 amit.gupta 940
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33212 amit.gupta 941
 
33226 amit.gupta 942
 
943
                    //Narration
33227 amit.gupta 944
                    sheet.getRow(row).createCell(6).setCellValue(statementDetailModel.getReferenceType());
33212 amit.gupta 945
 
946
                    row += 1;
947
                }
948
            }
949
            if (YearMonth.from(date).atEndOfMonth().equals(date)) {
950
                List<CreditNote> creditNotes = creditNoteRepository.selectAll(customRetailer.getPartnerId(), YearMonth.from(date));
951
                if (creditNotes != null) {
952
                    for (CreditNote creditNote : creditNotes) {
953
                        double cnAmount = creditNoteLineRepository.selectAllByCreditNote(creditNote.getId()).stream().collect(Collectors.summingDouble(x -> x.getAmount()));
33205 amit.gupta 954
                        Cell dateCell = sheet.createRow(row).createCell(0);
33212 amit.gupta 955
                        dateCell.setCellValue(new Date(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 956
                        dateCell.setCellStyle(dateStyle);
33212 amit.gupta 957
                        sheet.getRow(row).createCell(1).setCellValue("CREDIT NOTE");
33227 amit.gupta 958
                        sheet.getRow(row).createCell(2).setCellValue(creditNote.getCreditNoteNumber());
33212 amit.gupta 959
                        if (cnAmount > 0) {
33227 amit.gupta 960
                            sheet.getRow(row).createCell(3).setCellValue(0);
961
                            sheet.getRow(row).createCell(4).setCellValue(cnAmount);
33212 amit.gupta 962
                            grandTotalCredit += cnAmount;
963
                        } else {
33227 amit.gupta 964
                            sheet.getRow(row).createCell(3).setCellValue(-cnAmount);
965
                            sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 966
                            grandTotalDebit += -cnAmount;
33205 amit.gupta 967
                        }
33226 amit.gupta 968
                        //Running balance
969
                        currentOpening += cnAmount;
33227 amit.gupta 970
                        sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33226 amit.gupta 971
                        //Narration
33227 amit.gupta 972
                        sheet.getRow(row).createCell(6).setCellValue("Credit Note Issued");
33205 amit.gupta 973
 
974
                        row += 1;
975
                    }
976
                }
977
            }
32491 jai.hind 978
        }
33205 amit.gupta 979
 
33238 amit.gupta 980
        sheet.createRow(row).createCell(2).setCellValue("Grand Total");
981
        sheet.getRow(row).createCell(3).setCellValue(grandTotalDebit);
982
        sheet.getRow(row).createCell(4).setCellValue(grandTotalCredit);
983
        /*row += 2;
32491 jai.hind 984
        sheet.createRow(row).createCell(0).setCellValue("Closing Balance");
33238 amit.gupta 985
        sheet.getRow(row).createCell(3).setCellValue(closingBalance);*/
32491 jai.hind 986
        row++;
987
        /*
988
         * sheet.createRow(row).createCell(0).setCellValue("Pending Grns");
989
         * sheet.getRow(row).createCell(2).setCellValue(closingBalance); row++;
990
         */
991
        try {
992
            workbook.write(bos);
993
        } finally {
994
            workbook.close();
995
            bos.close();
996
        }
28515 amit.gupta 997
 
32491 jai.hind 998
        return bos;
999
    }
24876 tejbeer 1000
 
32491 jai.hind 1001
    @RequestMapping(value = "/manualPayment", method = RequestMethod.GET)
1002
    public String ManualPayment(HttpServletRequest request, Model model) throws Exception {
1003
        model.addAttribute("referenceTypes", WalletReferenceType.referenceType);
1004
        model.addAttribute("transactionTypes", TransactionType.values());
1005
        return "wallet-edit";
24876 tejbeer 1006
 
32491 jai.hind 1007
    }
24876 tejbeer 1008
 
32491 jai.hind 1009
    @RequestMapping(value = "/getWalletHistory", method = RequestMethod.GET)
32495 amit.gupta 1010
    public String getWalletHistory(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
25018 tejbeer 1011
 
32491 jai.hind 1012
        LOGGER.info("type" + referenceType);
32495 amit.gupta 1013
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
25018 tejbeer 1014
 
32491 jai.hind 1015
        if (userWalletHistory.isEmpty()) {
1016
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1017
        }
25018 tejbeer 1018
 
32491 jai.hind 1019
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
25018 tejbeer 1020
 
32491 jai.hind 1021
        LOGGER.info("userWallet" + userWallet);
1022
        CustomRetailer customretailer = retailerService.getFofoRetailer(userWallet.getUserId());
25018 tejbeer 1023
 
32491 jai.hind 1024
        model.addAttribute("userWallet", userWallet);
1025
        model.addAttribute("customretailer", customretailer);
24876 tejbeer 1026
 
32491 jai.hind 1027
        model.addAttribute("wallethistory", userWalletHistory);
1028
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1029
        return "wallet-history";
25018 tejbeer 1030
 
32491 jai.hind 1031
    }
25018 tejbeer 1032
 
32491 jai.hind 1033
    @RequestMapping(value = "/getWalletHistoryByPartner", method = RequestMethod.GET)
32512 amit.gupta 1034
    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 1035
 
32491 jai.hind 1036
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
32495 amit.gupta 1037
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectPaginatedByWalletIdReferenceType(userWallet.getId(), referenceType, SortOrder.DESCENDING, offset, limit);
25018 tejbeer 1038
 
32491 jai.hind 1039
        CustomRetailer customretailer = retailerService.getFofoRetailer(fofoId);
25018 tejbeer 1040
 
32491 jai.hind 1041
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
32597 amit.gupta 1042
 
1043
        List<Loan> loans = null;
1044
        BigDecimal totalDue = BigDecimal.ZERO;
1045
        BigDecimal availableLimit = BigDecimal.ZERO;
1046
        BigDecimal creditlimit = BigDecimal.ZERO;
32598 amit.gupta 1047
        if (sdCreditRequirement != null) {
32597 amit.gupta 1048
            loans = loanRepository.selectActiveLoan(fofoId);
1049
            availableLimit = sdCreditRequirement.getAvailableLimit();
1050
            creditlimit = sdCreditRequirement.getLimit();
1051
            for (Loan loan : loans) {
1052
                BigDecimal pendingAmount = loan.getPendingAmount();
1053
                BigDecimal interestAccrued = loan.getInterestAccrued();
1054
                BigDecimal interestPaid = loan.getInterestPaid();
1055
                totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));
1056
                availableLimit = creditlimit.subtract(totalDue);
1057
            }
32491 jai.hind 1058
        }
1059
        model.addAttribute("userWallet", userWallet);
1060
        model.addAttribute("customretailer", customretailer);
1061
        model.addAttribute("wallethistory", userWalletHistory);
1062
        model.addAttribute("loans", loans);
1063
        model.addAttribute("totalDue", totalDue);
1064
        model.addAttribute("availableLimit", availableLimit);
1065
        model.addAttribute("creditlimit", creditlimit);
1066
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1067
        return "wallet-history";
1068
    }
30426 tejbeer 1069
 
24876 tejbeer 1070
 
32491 jai.hind 1071
    @RequestMapping(value = "/getPartnerName", method = RequestMethod.GET)
32495 amit.gupta 1072
    public String getPartnerName(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
24905 amit.gupta 1073
 
32495 amit.gupta 1074
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1075
        if (userWalletHistory.isEmpty()) {
1076
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1077
        }
1078
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
24905 amit.gupta 1079
 
32491 jai.hind 1080
        CustomRetailer retailer = retailerService.getFofoRetailer(userWallet.getUserId());
24905 amit.gupta 1081
 
32491 jai.hind 1082
        model.addAttribute("response1", mvcResponseSender.createResponseString(retailer));
24876 tejbeer 1083
 
32491 jai.hind 1084
        return "response";
24876 tejbeer 1085
 
32491 jai.hind 1086
    }
30677 amit.gupta 1087
 
32491 jai.hind 1088
    @RequestMapping(value = "/reset-wallet/9990381", method = RequestMethod.GET)
1089
    public String walletUpdate(Model model) throws Exception {
1090
        walletService.resetWallet();
1091
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1092
        return "response";
1093
    }
24876 tejbeer 1094
 
32491 jai.hind 1095
    @RequestMapping(value = "/walletUpdate", method = RequestMethod.POST)
32495 amit.gupta 1096
    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 1097
        WalletReferenceType referenceType = WalletReferenceType.findByValue(referenceTypeValue);
1098
        if (reference == 0 && referenceType.getValue() >= WalletReferenceType.INCENTIVES.getValue()) {
1099
            LOGGER.error("referenceType: " + referenceType);
1100
            ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(referenceType);
28515 amit.gupta 1101
 
32491 jai.hind 1102
            if (paymentType == null) {
1103
                paymentType = new ManualPaymentType();
1104
                paymentType.setReferenceType(referenceType);
1105
            }
1106
            paymentType.setCounter(paymentType.getCounter() + 1);
1107
            manualPaymentRequestRepository.persist(paymentType);
1108
            reference = paymentType.getCounter();
28515 amit.gupta 1109
 
32491 jai.hind 1110
        } else if (reference == 0) {
32495 amit.gupta 1111
            throw new ProfitMandiBusinessException("RefrenceId", reference, "System specific reference type cant be used manually");
32491 jai.hind 1112
        }
24876 tejbeer 1113
 
32495 amit.gupta 1114
        List<UserWalletHistory> userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1115
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
1116
        int walletId = userWallet.getId();
1117
        int walletAmount = walletService.getWalletAmount(retailerId);
24876 tejbeer 1118
 
32491 jai.hind 1119
        int returnReference = 0;
1120
        UserWalletHistory newUserWalletHistory = new UserWalletHistory();
28515 amit.gupta 1121
 
32491 jai.hind 1122
        if (!userWalletHistoryList.isEmpty()) {
1123
            long validRetailerEntries = userWalletHistoryList.stream().filter(x -> x.getWalletId() == walletId).count();
1124
            if (validRetailerEntries == 0) {
32495 amit.gupta 1125
                throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id assign to Other  partner");
32491 jai.hind 1126
            }
1127
        }
28515 amit.gupta 1128
 
32491 jai.hind 1129
        if (TransactionType.DEBIT.equals(transactiontype)) {
1130
            amount = -amount;
1131
        }
26485 amit.gupta 1132
 
32491 jai.hind 1133
        userWallet.setAmount(walletAmount + amount);
1134
        newUserWalletHistory.setAmount(amount);
1135
        newUserWalletHistory.setBusinessTimestamp(businessTimestamp);
1136
        newUserWalletHistory.setDescription(description);
1137
        newUserWalletHistory.setReference(reference);
1138
        newUserWalletHistory.setWalletId(userWallet.getId());
1139
        newUserWalletHistory.setReferenceType(referenceType);
1140
        newUserWalletHistory.setTimestamp(LocalDateTime.now());
1141
        userWalletHistoryRepository.persist(newUserWalletHistory);
24876 tejbeer 1142
 
32491 jai.hind 1143
        model.addAttribute("response1", mvcResponseSender.createResponseString(reference));
1144
        return "response";
25018 tejbeer 1145
 
32491 jai.hind 1146
    }
25018 tejbeer 1147
 
32491 jai.hind 1148
    @RequestMapping(value = "/addMoney", method = RequestMethod.POST)
32495 amit.gupta 1149
    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 1150
        transactionReference = transactionReference.toUpperCase().trim();
1151
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectByReference(transactionReference);
34096 aman.kumar 1152
        addWalletRequests = addWalletRequests.stream().filter(x -> Arrays.asList(approved, AddWalletRequestStatus.pending).contains(x.getStatus())).collect(Collectors.toList());
33175 amit.gupta 1153
        if (addWalletRequests.size() > 0) {
1154
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1155
        }
1156
        HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(transactionReference);
33205 amit.gupta 1157
        if (hdfcPayment != null) {
33175 amit.gupta 1158
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1159
        }
32491 jai.hind 1160
        AddWalletRequest addWalletRequest = new AddWalletRequest();
1161
        addWalletRequest.setRetailerId(fofoId);
1162
        addWalletRequest.setAmount(amount);
33175 amit.gupta 1163
        addWalletRequest.setTransaction_reference(transactionReference.toUpperCase());
32491 jai.hind 1164
        addWalletRequest.setCreateTimestamp(LocalDateTime.now());
1165
        addWalletRequest.setBank_name(bankName);
1166
        addWalletRequest.setReference_date(referenceTime.toLocalDate());
1167
        addWalletRequest.setStatus(AddWalletRequestStatus.pending);
25018 tejbeer 1168
 
32491 jai.hind 1169
        LOGGER.info("info" + addWalletRequest);
29811 tejbeer 1170
 
32491 jai.hind 1171
        addWalletRequestRepository.persist(addWalletRequest);
1172
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1173
        return "response";
1174
    }
29811 tejbeer 1175
 
33045 amit.gupta 1176
    List<Gateway> directGateways = Arrays.asList(Gateway.SDDIRECT, Gateway.SIDBI);
1177
 
1178
    @Autowired
1179
    FofoSidbiSanctionRepository fofoSidbiSanctionRepository;
33175 amit.gupta 1180
 
32491 jai.hind 1181
    @RequestMapping(value = "/getCreditDetail", method = RequestMethod.GET)
1182
    public String getCreditDetail(HttpServletRequest request, Model model) throws Exception {
33175 amit.gupta 1183
        List<CreditAccount> creditAccounts = creditAccountRepository.selectAll().stream().filter(x -> directGateways.contains(x.getGateway())).collect(Collectors.toList());
32491 jai.hind 1184
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29962 tejbeer 1185
 
33420 amit.gupta 1186
        List<Integer> fofoIds = creditAccounts.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
33045 amit.gupta 1187
        //Need to maintain valid upto
33175 amit.gupta 1188
        Map<Integer, FofoSidbiSanction> fofoSidbiPendingSanctionsMap = fofoSidbiSanctionRepository.selectAll(Optional.of(false)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
29811 tejbeer 1189
 
33420 amit.gupta 1190
        Map<Integer, Integer> partnerAverageCreditDaysMap = new HashMap<>();
33045 amit.gupta 1191
 
33420 amit.gupta 1192
        List<Loan> loans = loanRepository.selectAllLoans(fofoIds, DateRangeModel.withStartDate(LocalDate.now().atStartOfDay().minusYears(2)));
1193
        Map<Integer, List<Loan>> partnerClosedLoansMap = loans.stream().filter(x -> x.getPendingAmount().compareTo(BigDecimal.ZERO) == 0)
1194
                .collect(Collectors.groupingBy(x -> x.getFofoId()));
1195
        for (Integer fofoId : fofoIds) {
1196
            List<Loan> closedLoans = partnerClosedLoansMap.get(fofoId);
1197
 
1198
            if (closedLoans != null) {
1199
                long averageCreditDays = Math.round(closedLoans.stream().mapToLong(x -> Duration.between(x.getCreatedOn(),
1200
                        x.getSettledOn() == null ? x.getCreatedOn().plusDays(10) : x.getSettledOn()).toDays() + 1).average().orElse(0.0));
1201
                partnerAverageCreditDaysMap.put(fofoId, (int) averageCreditDays);
1202
            }
1203
        }
1204
 
1205
 
32491 jai.hind 1206
        model.addAttribute("creditAccounts", creditAccounts);
33045 amit.gupta 1207
        model.addAttribute("fofoSidbiPendingSanctionsMap", fofoSidbiPendingSanctionsMap);
1208
        model.addAttribute("directGateways", directGateways);
32491 jai.hind 1209
        model.addAttribute("customRetailers", customRetailers);
33420 amit.gupta 1210
        model.addAttribute("partnerAverageCreditDaysMap", partnerAverageCreditDaysMap);
32491 jai.hind 1211
        return "partner-credit-detail";
1212
    }
29811 tejbeer 1213
 
33045 amit.gupta 1214
 
33359 amit.gupta 1215
    @Autowired
1216
    SidbiService sidbiService;
33363 amit.gupta 1217
 
32491 jai.hind 1218
    @RequestMapping(value = "/activateKred", method = RequestMethod.POST)
33045 amit.gupta 1219
    public String activateKred(HttpServletRequest request, @RequestParam int id, Model model, @RequestParam Gateway gateway) throws Exception {
32491 jai.hind 1220
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
33359 amit.gupta 1221
        if (creditAccount.getGateway().equals(gateway)) {
1222
            creditAccount.setActive(true);
1223
        } else {
33363 amit.gupta 1224
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(creditAccount.getFofoId());
33360 amit.gupta 1225
 
33363 amit.gupta 1226
            if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) != 0) {
33360 amit.gupta 1227
                LOGGER.info("sdCreditRequirement - {}", sdCreditRequirement);
33363 amit.gupta 1228
                throw new ProfitMandiBusinessException("Could not change to " + gateway + " unless previous loans are settled", "", "");
33205 amit.gupta 1229
            }
33359 amit.gupta 1230
            if (gateway.equals(Gateway.SIDBI)) {
1231
                //TODO - Issuance pending
1232
                FofoSidbiSanction fofoSidbiSanction = fofoSidbiSanctionRepository.selectByFofoId(creditAccount.getFofoId());
1233
                sidbiService.issueLimit(fofoSidbiSanction);
33363 amit.gupta 1234
                sdCreditRequirement.setLimit(BigDecimal.valueOf(fofoSidbiSanction.getLoanAmount()));
1235
                sdCreditRequirement.setSuggestedLimit(sdCreditRequirement.getLimit());
33359 amit.gupta 1236
                if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) > 0) {
1237
                    throw new ProfitMandiBusinessException("Loans are not closed", "Loans are not closed", "Loans are not closed");
1238
                }
33363 amit.gupta 1239
                creditAccount.setSanctionedAmount((float) fofoSidbiSanction.getLoanAmount());
33359 amit.gupta 1240
            }
33363 amit.gupta 1241
            creditAccount.setAvailableAmount(creditAccount.getSanctionedAmount());
1242
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
1243
            creditAccount.setActive(true);
1244
            creditAccount.setGateway(gateway);
33045 amit.gupta 1245
        }
29811 tejbeer 1246
 
32491 jai.hind 1247
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
30859 tejbeer 1248
 
34712 amit.gupta 1249
        String title = "Credit Limit Approved";
32491 jai.hind 1250
        String url = "http://app.smartdukaan.com/pages/home/credit";
32495 amit.gupta 1251
        String message = "Congratulations! Your Credit Limit is approved for Rs." + FormattingUtils.formatDecimal(creditAccount.getSanctionedAmount());
1252
        notificationService.sendNotification(creditAccount.getFofoId(), "Loan", MessageType.notification, title, message, url);
29811 tejbeer 1253
 
32491 jai.hind 1254
        model.addAttribute("creditAccount", creditAccount);
1255
        model.addAttribute("customRetailers", customRetailers);
1256
        return "partner-credit-detail-row";
1257
    }
29811 tejbeer 1258
 
32491 jai.hind 1259
    @RequestMapping(value = "/deactivateKred", method = RequestMethod.POST)
1260
    public String deactivateKred(HttpServletRequest request, @RequestParam int id, Model model) throws Exception {
1261
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
29811 tejbeer 1262
 
32491 jai.hind 1263
        creditAccount.setActive(false);
29811 tejbeer 1264
 
32491 jai.hind 1265
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29811 tejbeer 1266
 
32491 jai.hind 1267
        model.addAttribute("creditAccount", creditAccount);
1268
        model.addAttribute("customRetailers", customRetailers);
1269
        return "partner-credit-detail-row";
1270
    }
1271
 
34261 tejus.loha 1272
    @RequestMapping(value = "/downloadAddWalletRequestReport", method = RequestMethod.GET)
34527 tejus.loha 1273
    public ResponseEntity<?> addWalletRequestPendingReport(@RequestParam LocalDate startDate, @RequestParam LocalDate endDate, @RequestParam AddWalletRequestStatus status, Model model) throws Exception {
1274
        if (endDate == null) {
1275
            endDate = LocalDate.now();
34261 tejus.loha 1276
        }
1277
        LocalDateTime form = startDate.atStartOfDay();
1278
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1279
        return walletService.createAddWalletRequestReport(form, to, status);
1280
    }
1281
 
34527 tejus.loha 1282
    @GetMapping(value = "/getHdfcPaymentsReport")
1283
    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 1284
 
34527 tejus.loha 1285
        if (startDate == null) {
1286
            startDate = LocalDate.now().minusDays(7);
1287
        }
1288
        if (endDate == null) {
1289
            endDate = LocalDate.now();
1290
        }
1291
        LocalDateTime form = startDate.atStartOfDay();
1292
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1293
        List<HdfcPayment> hdfcPayments = hdfcPaymentRepository.selectAllByTransferModeAndDataRange(transferMode, form, to);
1294
        Map<Integer, CustomRetailer> allFofoRetailers = retailerService.getAllFofoRetailers();
1295
        List<HdfcPaymentModel> hdfcPaymentModelList = new ArrayList<>();
1296
        if (hdfcPayments != null && hdfcPayments.size() > 0) {
1297
            for (HdfcPayment upiPayment : hdfcPayments) {
1298
                HdfcPaymentModel hdfcPaymentModel = new HdfcPaymentModel();
1299
                // remove prifix to get fofoId = "nwspic" from virtual account "nwspicFOFOID" eg "nwspic175140063" to "175140063"
1300
                String partnerIdString = upiPayment.getVirtualAccount().substring(6);
1301
                CustomRetailer customRetailer = allFofoRetailers.get(Integer.parseInt(partnerIdString));
1302
                hdfcPaymentModel.setAmount(upiPayment.getAmount());
1303
                hdfcPaymentModel.setName(customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")");
1304
                hdfcPaymentModel.setUtr(upiPayment.getUtr());
1305
                hdfcPaymentModel.setCreateTimestamp(upiPayment.getCreateTimestamp());
1306
                hdfcPaymentModel.setCreditTimestamp(upiPayment.getCreditTimestamp());
1307
                hdfcPaymentModel.setTransactionId(upiPayment.getTransactionId());
1308
                hdfcPaymentModel.setTransferMode(upiPayment.getTransferMode());
1309
                hdfcPaymentModelList.add(hdfcPaymentModel);
1310
            }
1311
        }
1312
 
1313
        List<String> transferModeList = Arrays.asList("OTH","FUND TRANS","IMPS","NEFT","RTGS");
1314
        model.addAttribute("hdfcPaymentModels", hdfcPaymentModelList);
1315
        model.addAttribute("startDate", startDate);
1316
        model.addAttribute("endDate", endDate);
1317
        model.addAttribute("mode", transferMode);
1318
        model.addAttribute("transferModeList", transferModeList);
1319
        return "upi-payments-report-panel";
1320
    }
1321
 
1322
 
22551 ashik.ali 1323
}