Subversion Repositories SmartDukaan

Rev

Rev 32490 | Rev 32494 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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