Subversion Repositories SmartDukaan

Rev

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