Subversion Repositories SmartDukaan

Rev

Rev 33696 | Rev 34096 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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