Subversion Repositories SmartDukaan

Rev

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