Subversion Repositories SmartDukaan

Rev

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