Subversion Repositories SmartDukaan

Rev

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