Subversion Repositories SmartDukaan

Rev

Rev 33220 | Rev 33226 | 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;
23936 tejbeer 14
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
24876 tejbeer 15
import com.spice.profitmandi.dao.repository.catalog.ManualPaymentRequestRepository;
24089 tejbeer 16
import com.spice.profitmandi.dao.repository.catalog.UnsettledPaymentsRepository;
29811 tejbeer 17
import com.spice.profitmandi.dao.repository.dtr.CreditAccountRepository;
24876 tejbeer 18
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23985 tejbeer 19
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
32490 jai.hind 20
import com.spice.profitmandi.dao.repository.transaction.*;
30859 tejbeer 21
import com.spice.profitmandi.service.NotificationService;
24523 amit.gupta 22
import com.spice.profitmandi.service.authentication.RoleManager;
29070 amit.gupta 23
import com.spice.profitmandi.service.transaction.TransactionService;
23936 tejbeer 24
import com.spice.profitmandi.service.user.RetailerService;
22551 ashik.ali 25
import com.spice.profitmandi.service.wallet.WalletService;
26
import com.spice.profitmandi.web.model.LoginDetails;
27
import com.spice.profitmandi.web.util.CookiesProcessor;
23936 tejbeer 28
import com.spice.profitmandi.web.util.MVCResponseSender;
29
import in.shop2020.model.v1.order.WalletReferenceType;
31238 amit.gupta 30
import org.apache.logging.log4j.LogManager;
31
import org.apache.logging.log4j.Logger;
32
import org.apache.poi.ss.usermodel.Cell;
33
import org.apache.poi.ss.usermodel.CellStyle;
34
import org.apache.poi.ss.usermodel.CreationHelper;
35
import org.apache.poi.ss.usermodel.Sheet;
36
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
37
import org.json.JSONObject;
38
import org.springframework.beans.factory.annotation.Autowired;
39
import org.springframework.core.io.InputStreamResource;
40
import org.springframework.http.HttpHeaders;
41
import org.springframework.http.HttpStatus;
42
import org.springframework.http.ResponseEntity;
43
import org.springframework.mail.javamail.JavaMailSender;
44
import org.springframework.mail.javamail.MimeMessageHelper;
45
import org.springframework.stereotype.Controller;
46
import org.springframework.ui.Model;
47
import org.springframework.web.bind.annotation.*;
48
import org.springframework.web.multipart.MultipartFile;
23936 tejbeer 49
 
31238 amit.gupta 50
import javax.mail.internet.InternetAddress;
51
import javax.mail.internet.MimeMessage;
52
import javax.servlet.http.HttpServletRequest;
53
import javax.swing.*;
54
import javax.transaction.Transactional;
55
import java.io.ByteArrayInputStream;
56
import java.io.ByteArrayOutputStream;
57
import java.io.InputStream;
32490 jai.hind 58
import java.math.BigDecimal;
31238 amit.gupta 59
import java.text.MessageFormat;
60
import java.time.LocalDate;
61
import java.time.LocalDateTime;
33205 amit.gupta 62
import java.time.YearMonth;
31238 amit.gupta 63
import java.time.ZoneId;
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();
742
        CellStyle style2 = workbook.createCellStyle();
33205 amit.gupta 743
        style2.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);
33212 amit.gupta 758
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
759
            List<UserWalletHistory> datewiseWalletHistory = dateWalletMap.get(date);
33220 amit.gupta 760
            LOGGER.info("date - {}, datewiseWalletHistory - {}", date, datewiseWalletHistory);
33212 amit.gupta 761
            if (datewiseWalletHistory != null) {
762
                for (UserWalletHistory walletEntry : datewiseWalletHistory) {
763
                    Cell dateCell = sheet.createRow(row).createCell(0);
764
                    dateCell.setCellValue(new Date(walletEntry.getTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
765
                    dateCell.setCellStyle(style2);
766
                    sheet.getRow(row).createCell(1).setCellValue(walletEntry.getReferenceType().toString());
767
                    if (walletEntry.getAmount() > 0) {
768
                        sheet.getRow(row).createCell(2).setCellValue(0);
769
                        sheet.getRow(row).createCell(3).setCellValue(walletEntry.getAmount());
770
                        grandTotalCredit += walletEntry.getAmount();
771
                    } else {
772
                        sheet.getRow(row).createCell(2).setCellValue(-walletEntry.getAmount());
773
                        sheet.getRow(row).createCell(3).setCellValue(0);
774
                        grandTotalDebit -= walletEntry.getAmount();
775
                    }
776
                    sheet.getRow(row).createCell(4).setCellValue(walletEntry.getDescription());
777
                    sheet.getRow(row).createCell(5).setCellValue(walletEntry.getReference());
778
                    row++;
779
                }
780
            }
781
            List<StatementDetailModel> statementDetailModels = dateInvoiceMap.get(date);
782
            LOGGER.info("statementDetailModels - {}", statementDetailModels);
783
            if (statementDetailModels != null) {
784
                for (StatementDetailModel statementDetailModel : statementDetailModels) {
785
                    Cell dateCell = sheet.createRow(row).createCell(0);
786
                    dateCell.setCellValue(statementDetailModel.getOnDate());
787
                    dateCell.setCellStyle(style2);
788
                    sheet.getRow(row).createCell(1).setCellValue("BILLING");
789
                    if (statementDetailModel.getAmount() > 0) {
790
                        sheet.getRow(row).createCell(2).setCellValue(statementDetailModel.getAmount());
791
                        sheet.getRow(row).createCell(3).setCellValue(0);
792
                        grandTotalDebit += statementDetailModel.getAmount();
793
                    } else {
794
                        sheet.getRow(row).createCell(2).setCellValue(0);
795
                        sheet.getRow(row).createCell(3).setCellValue(-statementDetailModel.getAmount());
796
                        grandTotalCredit += -statementDetailModel.getAmount();
797
                    }
798
 
799
                    sheet.getRow(row).createCell(4).setCellValue(statementDetailModel.getReferenceType());
800
                    sheet.getRow(row).createCell(5).setCellValue(statementDetailModel.getInvoiceNumber());
801
 
802
                    row += 1;
803
                }
804
            }
805
            if (YearMonth.from(date).atEndOfMonth().equals(date)) {
806
                List<CreditNote> creditNotes = creditNoteRepository.selectAll(customRetailer.getPartnerId(), YearMonth.from(date));
807
                if (creditNotes != null) {
808
                    for (CreditNote creditNote : creditNotes) {
809
                        double cnAmount = creditNoteLineRepository.selectAllByCreditNote(creditNote.getId()).stream().collect(Collectors.summingDouble(x -> x.getAmount()));
33205 amit.gupta 810
                        Cell dateCell = sheet.createRow(row).createCell(0);
33212 amit.gupta 811
                        dateCell.setCellValue(new Date(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33205 amit.gupta 812
                        dateCell.setCellStyle(style2);
33212 amit.gupta 813
                        sheet.getRow(row).createCell(1).setCellValue("CREDIT NOTE");
814
                        if (cnAmount > 0) {
815
                            sheet.getRow(row).createCell(2).setCellValue(0);
816
                            sheet.getRow(row).createCell(3).setCellValue(cnAmount);
817
                            grandTotalCredit += cnAmount;
818
                        } else {
819
                            sheet.getRow(row).createCell(2).setCellValue(-cnAmount);
33205 amit.gupta 820
                            sheet.getRow(row).createCell(3).setCellValue(0);
33212 amit.gupta 821
                            grandTotalDebit += -cnAmount;
33205 amit.gupta 822
                        }
823
 
33212 amit.gupta 824
                        sheet.getRow(row).createCell(4).setCellValue("Credit Note Issued");
825
                        sheet.getRow(row).createCell(5).setCellValue(creditNote.getCreditNoteNumber());
33205 amit.gupta 826
 
827
                        row += 1;
828
                    }
829
                }
830
            }
32491 jai.hind 831
        }
33205 amit.gupta 832
 
32491 jai.hind 833
        sheet.createRow(row).createCell(0).setCellValue("Grand Total");
834
        sheet.getRow(row).createCell(2).setCellValue(grandTotalDebit);
835
        sheet.getRow(row).createCell(3).setCellValue(grandTotalCredit);
836
        row += 2;
837
        sheet.createRow(row).createCell(0).setCellValue("Closing Balance");
838
        sheet.getRow(row).createCell(3).setCellValue(closingBalance);
839
        row++;
840
        /*
841
         * sheet.createRow(row).createCell(0).setCellValue("Pending Grns");
842
         * sheet.getRow(row).createCell(2).setCellValue(closingBalance); row++;
843
         */
844
        try {
845
            workbook.write(bos);
846
        } finally {
847
            workbook.close();
848
            bos.close();
849
        }
28515 amit.gupta 850
 
32491 jai.hind 851
        return bos;
852
    }
24876 tejbeer 853
 
32491 jai.hind 854
    @RequestMapping(value = "/manualPayment", method = RequestMethod.GET)
855
    public String ManualPayment(HttpServletRequest request, Model model) throws Exception {
30426 tejbeer 856
 
32495 amit.gupta 857
        List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());
32491 jai.hind 858
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
24876 tejbeer 859
 
32495 amit.gupta 860
        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 861
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
862
        model.addAttribute("customRetailers", customRetailers);
24876 tejbeer 863
 
32491 jai.hind 864
        model.addAttribute("referenceTypes", WalletReferenceType.referenceType);
865
        model.addAttribute("transactionTypes", TransactionType.values());
866
        return "wallet-edit";
24876 tejbeer 867
 
32491 jai.hind 868
    }
24876 tejbeer 869
 
32491 jai.hind 870
    @RequestMapping(value = "/getWalletHistory", method = RequestMethod.GET)
32495 amit.gupta 871
    public String getWalletHistory(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
25018 tejbeer 872
 
32491 jai.hind 873
        LOGGER.info("type" + referenceType);
32495 amit.gupta 874
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
25018 tejbeer 875
 
32491 jai.hind 876
        if (userWalletHistory.isEmpty()) {
877
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
878
        }
25018 tejbeer 879
 
32491 jai.hind 880
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
25018 tejbeer 881
 
32491 jai.hind 882
        LOGGER.info("userWallet" + userWallet);
883
        CustomRetailer customretailer = retailerService.getFofoRetailer(userWallet.getUserId());
25018 tejbeer 884
 
32491 jai.hind 885
        model.addAttribute("userWallet", userWallet);
886
        model.addAttribute("customretailer", customretailer);
24876 tejbeer 887
 
32491 jai.hind 888
        model.addAttribute("wallethistory", userWalletHistory);
889
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
890
        return "wallet-history";
25018 tejbeer 891
 
32491 jai.hind 892
    }
25018 tejbeer 893
 
32491 jai.hind 894
    @RequestMapping(value = "/getWalletHistoryByPartner", method = RequestMethod.GET)
32512 amit.gupta 895
    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 896
 
32491 jai.hind 897
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
32495 amit.gupta 898
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectPaginatedByWalletIdReferenceType(userWallet.getId(), referenceType, SortOrder.DESCENDING, offset, limit);
25018 tejbeer 899
 
32491 jai.hind 900
        CustomRetailer customretailer = retailerService.getFofoRetailer(fofoId);
25018 tejbeer 901
 
32491 jai.hind 902
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
32597 amit.gupta 903
 
904
        List<Loan> loans = null;
905
        BigDecimal totalDue = BigDecimal.ZERO;
906
        BigDecimal availableLimit = BigDecimal.ZERO;
907
        BigDecimal creditlimit = BigDecimal.ZERO;
32598 amit.gupta 908
        if (sdCreditRequirement != null) {
32597 amit.gupta 909
            loans = loanRepository.selectActiveLoan(fofoId);
910
            availableLimit = sdCreditRequirement.getAvailableLimit();
911
            creditlimit = sdCreditRequirement.getLimit();
912
            for (Loan loan : loans) {
913
                BigDecimal pendingAmount = loan.getPendingAmount();
914
                BigDecimal interestAccrued = loan.getInterestAccrued();
915
                BigDecimal interestPaid = loan.getInterestPaid();
916
                totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));
917
                availableLimit = creditlimit.subtract(totalDue);
918
            }
32491 jai.hind 919
        }
920
        model.addAttribute("userWallet", userWallet);
921
        model.addAttribute("customretailer", customretailer);
922
        model.addAttribute("wallethistory", userWalletHistory);
923
        model.addAttribute("loans", loans);
924
        model.addAttribute("totalDue", totalDue);
925
        model.addAttribute("availableLimit", availableLimit);
926
        model.addAttribute("creditlimit", creditlimit);
927
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
928
        return "wallet-history";
929
    }
30426 tejbeer 930
 
24876 tejbeer 931
 
32491 jai.hind 932
    @RequestMapping(value = "/getPartnerName", method = RequestMethod.GET)
32495 amit.gupta 933
    public String getPartnerName(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
24905 amit.gupta 934
 
32495 amit.gupta 935
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 936
        if (userWalletHistory.isEmpty()) {
937
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
938
        }
939
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
24905 amit.gupta 940
 
32491 jai.hind 941
        CustomRetailer retailer = retailerService.getFofoRetailer(userWallet.getUserId());
24905 amit.gupta 942
 
32491 jai.hind 943
        model.addAttribute("response1", mvcResponseSender.createResponseString(retailer));
24876 tejbeer 944
 
32491 jai.hind 945
        return "response";
24876 tejbeer 946
 
32491 jai.hind 947
    }
30677 amit.gupta 948
 
32491 jai.hind 949
    @RequestMapping(value = "/reset-wallet/9990381", method = RequestMethod.GET)
950
    public String walletUpdate(Model model) throws Exception {
951
        walletService.resetWallet();
952
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
953
        return "response";
954
    }
24876 tejbeer 955
 
32491 jai.hind 956
    @RequestMapping(value = "/walletUpdate", method = RequestMethod.POST)
32495 amit.gupta 957
    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 958
        WalletReferenceType referenceType = WalletReferenceType.findByValue(referenceTypeValue);
959
        if (reference == 0 && referenceType.getValue() >= WalletReferenceType.INCENTIVES.getValue()) {
960
            LOGGER.error("referenceType: " + referenceType);
961
            ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(referenceType);
28515 amit.gupta 962
 
32491 jai.hind 963
            if (paymentType == null) {
964
                paymentType = new ManualPaymentType();
965
                paymentType.setReferenceType(referenceType);
966
            }
967
            paymentType.setCounter(paymentType.getCounter() + 1);
968
            manualPaymentRequestRepository.persist(paymentType);
969
            reference = paymentType.getCounter();
28515 amit.gupta 970
 
32491 jai.hind 971
        } else if (reference == 0) {
32495 amit.gupta 972
            throw new ProfitMandiBusinessException("RefrenceId", reference, "System specific reference type cant be used manually");
32491 jai.hind 973
        }
24876 tejbeer 974
 
32495 amit.gupta 975
        List<UserWalletHistory> userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 976
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
977
        int walletId = userWallet.getId();
978
        int walletAmount = walletService.getWalletAmount(retailerId);
24876 tejbeer 979
 
32491 jai.hind 980
        int returnReference = 0;
981
        UserWalletHistory newUserWalletHistory = new UserWalletHistory();
28515 amit.gupta 982
 
32491 jai.hind 983
        if (!userWalletHistoryList.isEmpty()) {
984
            long validRetailerEntries = userWalletHistoryList.stream().filter(x -> x.getWalletId() == walletId).count();
985
            if (validRetailerEntries == 0) {
32495 amit.gupta 986
                throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id assign to Other  partner");
32491 jai.hind 987
            }
988
        }
28515 amit.gupta 989
 
32491 jai.hind 990
        if (TransactionType.DEBIT.equals(transactiontype)) {
991
            amount = -amount;
992
        }
26485 amit.gupta 993
 
32491 jai.hind 994
        userWallet.setAmount(walletAmount + amount);
995
        newUserWalletHistory.setAmount(amount);
996
        newUserWalletHistory.setBusinessTimestamp(businessTimestamp);
997
        newUserWalletHistory.setDescription(description);
998
        newUserWalletHistory.setReference(reference);
999
        newUserWalletHistory.setWalletId(userWallet.getId());
1000
        newUserWalletHistory.setReferenceType(referenceType);
1001
        newUserWalletHistory.setTimestamp(LocalDateTime.now());
1002
        userWalletHistoryRepository.persist(newUserWalletHistory);
24876 tejbeer 1003
 
32491 jai.hind 1004
        model.addAttribute("response1", mvcResponseSender.createResponseString(reference));
1005
        return "response";
25018 tejbeer 1006
 
32491 jai.hind 1007
    }
25018 tejbeer 1008
 
33175 amit.gupta 1009
    @Autowired
1010
    HdfcPaymentRepository hdfcPaymentRepository;
1011
 
32491 jai.hind 1012
    @RequestMapping(value = "/addMoney", method = RequestMethod.POST)
32495 amit.gupta 1013
    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 1014
        transactionReference = transactionReference.toUpperCase().trim();
1015
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectByReference(transactionReference);
1016
        addWalletRequests = addWalletRequests.stream().filter(x -> Arrays.asList(AddWalletRequestStatus.approved, AddWalletRequestStatus.pending).contains(x.getStatus())).collect(Collectors.toList());
1017
        if (addWalletRequests.size() > 0) {
1018
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1019
        }
1020
        HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(transactionReference);
33205 amit.gupta 1021
        if (hdfcPayment != null) {
33175 amit.gupta 1022
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1023
        }
32491 jai.hind 1024
        AddWalletRequest addWalletRequest = new AddWalletRequest();
1025
        addWalletRequest.setRetailerId(fofoId);
1026
        addWalletRequest.setAmount(amount);
33175 amit.gupta 1027
        addWalletRequest.setTransaction_reference(transactionReference.toUpperCase());
32491 jai.hind 1028
        addWalletRequest.setCreateTimestamp(LocalDateTime.now());
1029
        addWalletRequest.setBank_name(bankName);
1030
        addWalletRequest.setReference_date(referenceTime.toLocalDate());
1031
        addWalletRequest.setStatus(AddWalletRequestStatus.pending);
25018 tejbeer 1032
 
32491 jai.hind 1033
        LOGGER.info("info" + addWalletRequest);
29811 tejbeer 1034
 
32491 jai.hind 1035
        addWalletRequestRepository.persist(addWalletRequest);
1036
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1037
        return "response";
1038
    }
29811 tejbeer 1039
 
33045 amit.gupta 1040
    List<Gateway> directGateways = Arrays.asList(Gateway.SDDIRECT, Gateway.SIDBI);
1041
 
1042
    @Autowired
1043
    FofoSidbiSanctionRepository fofoSidbiSanctionRepository;
33175 amit.gupta 1044
 
32491 jai.hind 1045
    @RequestMapping(value = "/getCreditDetail", method = RequestMethod.GET)
1046
    public String getCreditDetail(HttpServletRequest request, Model model) throws Exception {
33175 amit.gupta 1047
        List<CreditAccount> creditAccounts = creditAccountRepository.selectAll().stream().filter(x -> directGateways.contains(x.getGateway())).collect(Collectors.toList());
32491 jai.hind 1048
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29962 tejbeer 1049
 
33045 amit.gupta 1050
        //Need to maintain valid upto
33175 amit.gupta 1051
        Map<Integer, FofoSidbiSanction> fofoSidbiPendingSanctionsMap = fofoSidbiSanctionRepository.selectAll(Optional.of(false)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
29811 tejbeer 1052
 
33045 amit.gupta 1053
 
32491 jai.hind 1054
        model.addAttribute("creditAccounts", creditAccounts);
33045 amit.gupta 1055
        model.addAttribute("fofoSidbiPendingSanctionsMap", fofoSidbiPendingSanctionsMap);
1056
        model.addAttribute("directGateways", directGateways);
1057
 
32491 jai.hind 1058
        model.addAttribute("customRetailers", customRetailers);
1059
        return "partner-credit-detail";
1060
    }
29811 tejbeer 1061
 
33045 amit.gupta 1062
 
32491 jai.hind 1063
    @RequestMapping(value = "/activateKred", method = RequestMethod.POST)
33045 amit.gupta 1064
    public String activateKred(HttpServletRequest request, @RequestParam int id, Model model, @RequestParam Gateway gateway) throws Exception {
32491 jai.hind 1065
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
1066
        creditAccount.setActive(true);
33045 amit.gupta 1067
        creditAccount.setGateway(gateway);
33175 amit.gupta 1068
        if (gateway.equals(Gateway.SIDBI)) {
33045 amit.gupta 1069
            FofoSidbiSanction fofoSidbiSanction = fofoSidbiSanctionRepository.selectByFofoId(creditAccount.getFofoId());
1070
            creditAccount.setAvailableAmount((float) fofoSidbiSanction.getSanctionAmount());
1071
            creditAccount.setSanctionedAmount((float) fofoSidbiSanction.getSanctionAmount());
33205 amit.gupta 1072
 
1073
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(creditAccount.getFofoId());
1074
            sdCreditRequirement.setLimit(BigDecimal.valueOf(fofoSidbiSanction.getSanctionAmount()));
1075
            if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) > 0) {
1076
                throw new ProfitMandiBusinessException("Loans are not closed", "Loans are not closed", "Loans are not closed");
1077
            }
1078
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
33045 amit.gupta 1079
        }
29811 tejbeer 1080
 
32491 jai.hind 1081
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
30859 tejbeer 1082
 
32491 jai.hind 1083
        String title = "Loan Approved";
1084
        String url = "http://app.smartdukaan.com/pages/home/credit";
32495 amit.gupta 1085
        String message = "Congratulations! Your Credit Limit is approved for Rs." + FormattingUtils.formatDecimal(creditAccount.getSanctionedAmount());
1086
        notificationService.sendNotification(creditAccount.getFofoId(), "Loan", MessageType.notification, title, message, url);
29811 tejbeer 1087
 
32491 jai.hind 1088
        model.addAttribute("creditAccount", creditAccount);
1089
        model.addAttribute("customRetailers", customRetailers);
1090
        return "partner-credit-detail-row";
1091
    }
29811 tejbeer 1092
 
32491 jai.hind 1093
    @RequestMapping(value = "/deactivateKred", method = RequestMethod.POST)
1094
    public String deactivateKred(HttpServletRequest request, @RequestParam int id, Model model) throws Exception {
1095
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
29811 tejbeer 1096
 
32491 jai.hind 1097
        creditAccount.setActive(false);
29811 tejbeer 1098
 
32491 jai.hind 1099
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29811 tejbeer 1100
 
32491 jai.hind 1101
        model.addAttribute("creditAccount", creditAccount);
1102
        model.addAttribute("customRetailers", customRetailers);
1103
        return "partner-credit-detail-row";
1104
    }
1105
 
22551 ashik.ali 1106
}