Subversion Repositories SmartDukaan

Rev

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