Subversion Repositories SmartDukaan

Rev

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