Subversion Repositories SmartDukaan

Rev

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