Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
22551 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
30859 tejbeer 3
import com.spice.profitmandi.common.enumuration.MessageType;
22551 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23936 tejbeer 5
import com.spice.profitmandi.common.model.CustomRetailer;
22551 ashik.ali 6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
24089 tejbeer 7
import com.spice.profitmandi.common.model.UnsettledPaymentModel;
31238 amit.gupta 8
import com.spice.profitmandi.common.util.*;
29811 tejbeer 9
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
31238 amit.gupta 10
import com.spice.profitmandi.dao.entity.transaction.*;
32727 shampa 11
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
23936 tejbeer 12
import com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus;
24876 tejbeer 13
import com.spice.profitmandi.dao.enumuration.transaction.TransactionType;
33420 amit.gupta 14
import com.spice.profitmandi.dao.model.DateRangeModel;
33861 tejus.loha 15
import com.spice.profitmandi.dao.model.StoreTimelineModel;
23936 tejbeer 16
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
24876 tejbeer 17
import com.spice.profitmandi.dao.repository.catalog.ManualPaymentRequestRepository;
24089 tejbeer 18
import com.spice.profitmandi.dao.repository.catalog.UnsettledPaymentsRepository;
29811 tejbeer 19
import com.spice.profitmandi.dao.repository.dtr.CreditAccountRepository;
24876 tejbeer 20
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33861 tejus.loha 21
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
23985 tejbeer 22
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
32490 jai.hind 23
import com.spice.profitmandi.dao.repository.transaction.*;
33861 tejus.loha 24
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
33359 amit.gupta 25
import com.spice.profitmandi.dao.service.SidbiService;
30859 tejbeer 26
import com.spice.profitmandi.service.NotificationService;
24523 amit.gupta 27
import com.spice.profitmandi.service.authentication.RoleManager;
29070 amit.gupta 28
import com.spice.profitmandi.service.transaction.TransactionService;
23936 tejbeer 29
import com.spice.profitmandi.service.user.RetailerService;
33861 tejus.loha 30
import com.spice.profitmandi.service.user.StoreTimelineTatService;
22551 ashik.ali 31
import com.spice.profitmandi.service.wallet.WalletService;
32
import com.spice.profitmandi.web.model.LoginDetails;
33
import com.spice.profitmandi.web.util.CookiesProcessor;
23936 tejbeer 34
import com.spice.profitmandi.web.util.MVCResponseSender;
35
import in.shop2020.model.v1.order.WalletReferenceType;
31238 amit.gupta 36
import org.apache.logging.log4j.LogManager;
37
import org.apache.logging.log4j.Logger;
38
import org.apache.poi.ss.usermodel.Cell;
39
import org.apache.poi.ss.usermodel.CellStyle;
40
import org.apache.poi.ss.usermodel.CreationHelper;
41
import org.apache.poi.ss.usermodel.Sheet;
42
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
43
import org.json.JSONObject;
44
import org.springframework.beans.factory.annotation.Autowired;
45
import org.springframework.core.io.InputStreamResource;
46
import org.springframework.http.HttpHeaders;
47
import org.springframework.http.HttpStatus;
48
import org.springframework.http.ResponseEntity;
49
import org.springframework.mail.javamail.JavaMailSender;
50
import org.springframework.mail.javamail.MimeMessageHelper;
51
import org.springframework.stereotype.Controller;
52
import org.springframework.ui.Model;
53
import org.springframework.web.bind.annotation.*;
54
import org.springframework.web.multipart.MultipartFile;
23936 tejbeer 55
 
31238 amit.gupta 56
import javax.mail.internet.InternetAddress;
57
import javax.mail.internet.MimeMessage;
58
import javax.servlet.http.HttpServletRequest;
59
import javax.swing.*;
60
import javax.transaction.Transactional;
61
import java.io.ByteArrayInputStream;
62
import java.io.ByteArrayOutputStream;
63
import java.io.InputStream;
32490 jai.hind 64
import java.math.BigDecimal;
31238 amit.gupta 65
import java.text.MessageFormat;
33420 amit.gupta 66
import java.time.*;
31238 amit.gupta 67
import java.util.*;
68
import java.util.stream.Collectors;
69
 
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
 
33861 tejus.loha 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());
619
        if (fofoId > 0) {
620
            if (!isAdmin) {
621
                throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
622
            }
623
        } else {
624
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
625
        }
626
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
627
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32495 amit.gupta 628
        List<UserWalletHistory> uwhList = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDate, endDate, 0, 0);
32491 jai.hind 629
        Collections.reverse(uwhList);
630
        model.addAttribute("opening", openingBalance);
631
        model.addAttribute("closing", closingBalance);
632
        model.addAttribute("history", uwhList);
633
        model.addAttribute("startDate", startDate);
634
        model.addAttribute("endDate", endDate);
635
        return "walletStatement";
636
    }
29811 tejbeer 637
 
32491 jai.hind 638
    @RequestMapping(value = "/account/reco", method = RequestMethod.GET)
32495 amit.gupta 639
    public ResponseEntity<?> accountReco(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 640
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
641
        if (!isAdmin) {
642
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
643
        }
33207 amit.gupta 644
        LocalDateTime closingDateTime = closingDate.plusDays(1).atStartOfDay();
32491 jai.hind 645
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
646
        Set<Integer> retailersSet = customRetailerMap.keySet();
29070 amit.gupta 647
 
32491 jai.hind 648
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 649
 
32491 jai.hind 650
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 651
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 652
 
32491 jai.hind 653
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 654
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
32491 jai.hind 655
        Map<Integer, Float> closingWalletMap = userWalletHistoryRepository.getSumTillDate(closingDateTime, walletSet);
33212 amit.gupta 656
        Map<Integer, Float> peindingIndentMap = transactionService.getPendingIndentValueMap(closingDateTime, Optional.empty());
29811 tejbeer 657
 
32491 jai.hind 658
        List<List<?>> rows = new ArrayList<>();
659
        for (Map.Entry<Integer, Float> closingBalance : closingBalanceMap.entrySet()) {
660
            int walletId = closingBalance.getKey();
661
            int retailerId = walletRetailerMap.get(walletId);
29811 tejbeer 662
 
32491 jai.hind 663
            float accountClosing = 0f;
664
            if (!closingPurchaseMap.containsKey(retailerId)) {
665
                accountClosing = closingBalance.getValue();
666
            } else {
667
                accountClosing = closingBalance.getValue() - closingPurchaseMap.get(retailerId);
668
            }
29070 amit.gupta 669
 
32491 jai.hind 670
            CustomRetailer cr = customRetailerMap.get(retailerId);
29070 amit.gupta 671
 
32495 amit.gupta 672
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), accountClosing, closingWalletMap.get(walletId), peindingIndentMap.get(retailerId)));
32491 jai.hind 673
        }
29070 amit.gupta 674
 
32495 amit.gupta 675
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance", "Closing Wallet", "In Transit"), rows);
32491 jai.hind 676
        final HttpHeaders headers = new HttpHeaders();
677
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 678
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 679
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
29070 amit.gupta 680
 
32491 jai.hind 681
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
682
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
683
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
684
    }
29811 tejbeer 685
 
32491 jai.hind 686
    @RequestMapping(value = "/account/closing-statements", method = RequestMethod.GET)
32495 amit.gupta 687
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 688
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
689
        if (!isAdmin) {
690
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
691
        }
692
        LocalDateTime closingDateTime = closingDate.atStartOfDay().plusDays(1);
28597 amit.gupta 693
 
32491 jai.hind 694
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
695
        Set<Integer> retailersSet = customRetailerMap.keySet();
28597 amit.gupta 696
 
32491 jai.hind 697
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 698
 
32491 jai.hind 699
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 700
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 701
 
32491 jai.hind 702
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 703
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
28597 amit.gupta 704
 
32491 jai.hind 705
        List<List<?>> rows = new ArrayList<>();
706
        for (Map.Entry<Integer, Float> closingWalletBalance : closingBalanceMap.entrySet()) {
707
            int walletId = closingWalletBalance.getKey();
708
            int retailerId = walletRetailerMap.get(walletId);
709
            if (!closingPurchaseMap.containsKey(retailerId)) {
710
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue());
711
            } else {
32495 amit.gupta 712
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue() - closingPurchaseMap.get(retailerId));
32491 jai.hind 713
            }
714
            float closingValue = closingPurchaseMap.get(retailerId);
715
            CustomRetailer cr = customRetailerMap.get(retailerId);
28597 amit.gupta 716
 
32495 amit.gupta 717
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), closingValue));
32491 jai.hind 718
        }
28597 amit.gupta 719
 
32495 amit.gupta 720
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance"), rows);
32491 jai.hind 721
        final HttpHeaders headers = new HttpHeaders();
722
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 723
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 724
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28597 amit.gupta 725
 
32491 jai.hind 726
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
727
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28597 amit.gupta 728
 
32491 jai.hind 729
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28597 amit.gupta 730
 
32491 jai.hind 731
    }
28515 amit.gupta 732
 
32491 jai.hind 733
    @RequestMapping(value = "/account/statement", method = RequestMethod.GET)
32495 amit.gupta 734
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
32491 jai.hind 735
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
736
        if (fofoId > 0) {
737
            if (!isAdmin) {
738
                throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
739
            }
740
        } else {
741
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
742
        }
33212 amit.gupta 743
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
744
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32491 jai.hind 745
        UserWallet uw = walletService.getUserWallet(fofoId);
33220 amit.gupta 746
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
32495 amit.gupta 747
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
33220 amit.gupta 748
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
33205 amit.gupta 749
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
750
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType())).sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
33220 amit.gupta 751
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
33205 amit.gupta 752
 
32491 jai.hind 753
        InputStream is = getClass().getClassLoader().getResourceAsStream("account-statement.xlsx");
33205 amit.gupta 754
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
33225 amit.gupta 755
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
33212 amit.gupta 756
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
757
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
28515 amit.gupta 758
 
33212 amit.gupta 759
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
760
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
761
        LOGGER.info("Opening - {}, Closing - {}", openingPendingAmount, closingPendingAmount);
762
        ByteArrayOutputStream byteArrayOutputStream = this.populateData(is, openingBalance + openingPendingAmount, closingBalance + closingPendingAmount,
33225 amit.gupta 763
                customRetailer, history, startDate, endDate, billedStatementDetails);
33212 amit.gupta 764
 
32491 jai.hind 765
        final HttpHeaders headers = new HttpHeaders();
766
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
32495 amit.gupta 767
        headers.set("Content-disposition", "inline; filename=account-statement." + StringUtils.toHyphenatedString(startDate.toLocalDate()) + "-" + StringUtils.toHyphenatedString(endDate.toLocalDate()) + ".xlsx");
32491 jai.hind 768
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28515 amit.gupta 769
 
32491 jai.hind 770
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
771
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28515 amit.gupta 772
 
32491 jai.hind 773
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28515 amit.gupta 774
 
32491 jai.hind 775
    }
28597 amit.gupta 776
 
33205 amit.gupta 777
    @Autowired
778
    CreditNoteRepository creditNoteRepository;
779
    @Autowired
780
    CreditNoteLineRepository creditNoteLineRepository;
781
 
782
    private ByteArrayOutputStream populateData(InputStream is, float openingBalance, float closingBalance, CustomRetailer customRetailer, List<UserWalletHistory> history,
783
                                               LocalDateTime startLocalDateTime, LocalDateTime endLocalDateTime, List<StatementDetailModel> invoiceDetails) throws Exception {
784
        Map<LocalDate, List<StatementDetailModel>> dateInvoiceMap = invoiceDetails.stream().collect(Collectors.groupingBy(x -> x.getOnDate().toLocalDate()));
33220 amit.gupta 785
        //LOGGER.info("dateInvoiceMap - {}", dateInvoiceMap);
786
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
32491 jai.hind 787
        XSSFWorkbook workbook = new XSSFWorkbook(is);
788
        CreationHelper creationHelper = workbook.getCreationHelper();
33226 amit.gupta 789
        CellStyle dateStyle = workbook.createCellStyle();
790
        dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dd/mm/yyyy"));
28597 amit.gupta 791
 
32491 jai.hind 792
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
793
        Sheet sheet = workbook.getSheetAt(0);
33205 amit.gupta 794
        sheet.getRow(0).getCell(0).setCellValue(customRetailer.getBusinessName());
795
        sheet.getRow(1).getCell(1).setCellValue(new Date(startLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
796
        sheet.getRow(1).getCell(2).setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
32491 jai.hind 797
        sheet.getRow(2).getCell(2).setCellValue(openingBalance);
798
        long grandTotalDebit = 0l;
799
        long grandTotalCredit = 0l;
800
        int row = 4;
33212 amit.gupta 801
        LocalDate startDate = startLocalDateTime.toLocalDate();
33205 amit.gupta 802
        LocalDate endDate = endLocalDateTime.toLocalDate();
33220 amit.gupta 803
        LOGGER.info(" startDate - {}", startDate);
804
        LOGGER.info(" endDate - {}", endDate);
33226 amit.gupta 805
        double currentOpening = openingBalance;
33212 amit.gupta 806
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
807
            List<UserWalletHistory> datewiseWalletHistory = dateWalletMap.get(date);
33220 amit.gupta 808
            LOGGER.info("date - {}, datewiseWalletHistory - {}", date, datewiseWalletHistory);
33212 amit.gupta 809
            if (datewiseWalletHistory != null) {
810
                for (UserWalletHistory walletEntry : datewiseWalletHistory) {
811
                    Cell dateCell = sheet.createRow(row).createCell(0);
33226 amit.gupta 812
                    //Date
33212 amit.gupta 813
                    dateCell.setCellValue(new Date(walletEntry.getTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 814
                    dateCell.setCellStyle(dateStyle);
815
                    //TransactType
33212 amit.gupta 816
                    sheet.getRow(row).createCell(1).setCellValue(walletEntry.getReferenceType().toString());
33226 amit.gupta 817
                    //Reference Id
33227 amit.gupta 818
                    sheet.getRow(row).createCell(2).setCellValue(walletEntry.getReference());
33212 amit.gupta 819
                    if (walletEntry.getAmount() > 0) {
33226 amit.gupta 820
                        //Debit
33227 amit.gupta 821
                        sheet.getRow(row).createCell(3).setCellValue(0);
33226 amit.gupta 822
                        //Credit
33227 amit.gupta 823
                        sheet.getRow(row).createCell(4).setCellValue(walletEntry.getAmount());
33212 amit.gupta 824
                        grandTotalCredit += walletEntry.getAmount();
825
                    } else {
33227 amit.gupta 826
                        sheet.getRow(row).createCell(3).setCellValue(-walletEntry.getAmount());
827
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 828
                        grandTotalDebit -= walletEntry.getAmount();
829
                    }
33226 amit.gupta 830
                    //Running balance
831
                    currentOpening += walletEntry.getAmount();
33227 amit.gupta 832
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33226 amit.gupta 833
                    //Description
33227 amit.gupta 834
                    sheet.getRow(row).createCell(6).setCellValue(walletEntry.getDescription());
33212 amit.gupta 835
                    row++;
836
                }
837
            }
838
            List<StatementDetailModel> statementDetailModels = dateInvoiceMap.get(date);
839
            LOGGER.info("statementDetailModels - {}", statementDetailModels);
840
            if (statementDetailModels != null) {
841
                for (StatementDetailModel statementDetailModel : statementDetailModels) {
842
                    Cell dateCell = sheet.createRow(row).createCell(0);
843
                    dateCell.setCellValue(statementDetailModel.getOnDate());
33226 amit.gupta 844
                    dateCell.setCellStyle(dateStyle);
845
                    //Transact Type
33212 amit.gupta 846
                    sheet.getRow(row).createCell(1).setCellValue("BILLING");
33226 amit.gupta 847
                    //Transact Reference
33227 amit.gupta 848
                    sheet.getRow(row).createCell(2).setCellValue(statementDetailModel.getInvoiceNumber());
33212 amit.gupta 849
                    if (statementDetailModel.getAmount() > 0) {
33227 amit.gupta 850
                        sheet.getRow(row).createCell(3).setCellValue(statementDetailModel.getAmount());
851
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 852
                        grandTotalDebit += statementDetailModel.getAmount();
853
                    } else {
33227 amit.gupta 854
                        sheet.getRow(row).createCell(3).setCellValue(0);
855
                        sheet.getRow(row).createCell(4).setCellValue(-statementDetailModel.getAmount());
33212 amit.gupta 856
                        grandTotalCredit += -statementDetailModel.getAmount();
857
                    }
33226 amit.gupta 858
                    //Running Balance
33229 amit.gupta 859
                    currentOpening -= statementDetailModel.getAmount();
33228 amit.gupta 860
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33212 amit.gupta 861
 
33226 amit.gupta 862
 
863
                    //Narration
33227 amit.gupta 864
                    sheet.getRow(row).createCell(6).setCellValue(statementDetailModel.getReferenceType());
33212 amit.gupta 865
 
866
                    row += 1;
867
                }
868
            }
869
            if (YearMonth.from(date).atEndOfMonth().equals(date)) {
870
                List<CreditNote> creditNotes = creditNoteRepository.selectAll(customRetailer.getPartnerId(), YearMonth.from(date));
871
                if (creditNotes != null) {
872
                    for (CreditNote creditNote : creditNotes) {
873
                        double cnAmount = creditNoteLineRepository.selectAllByCreditNote(creditNote.getId()).stream().collect(Collectors.summingDouble(x -> x.getAmount()));
33205 amit.gupta 874
                        Cell dateCell = sheet.createRow(row).createCell(0);
33212 amit.gupta 875
                        dateCell.setCellValue(new Date(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 876
                        dateCell.setCellStyle(dateStyle);
33212 amit.gupta 877
                        sheet.getRow(row).createCell(1).setCellValue("CREDIT NOTE");
33227 amit.gupta 878
                        sheet.getRow(row).createCell(2).setCellValue(creditNote.getCreditNoteNumber());
33212 amit.gupta 879
                        if (cnAmount > 0) {
33227 amit.gupta 880
                            sheet.getRow(row).createCell(3).setCellValue(0);
881
                            sheet.getRow(row).createCell(4).setCellValue(cnAmount);
33212 amit.gupta 882
                            grandTotalCredit += cnAmount;
883
                        } else {
33227 amit.gupta 884
                            sheet.getRow(row).createCell(3).setCellValue(-cnAmount);
885
                            sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 886
                            grandTotalDebit += -cnAmount;
33205 amit.gupta 887
                        }
33226 amit.gupta 888
                        //Running balance
889
                        currentOpening += cnAmount;
33227 amit.gupta 890
                        sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33226 amit.gupta 891
                        //Narration
33227 amit.gupta 892
                        sheet.getRow(row).createCell(6).setCellValue("Credit Note Issued");
33205 amit.gupta 893
 
894
                        row += 1;
895
                    }
896
                }
897
            }
32491 jai.hind 898
        }
33205 amit.gupta 899
 
33238 amit.gupta 900
        sheet.createRow(row).createCell(2).setCellValue("Grand Total");
901
        sheet.getRow(row).createCell(3).setCellValue(grandTotalDebit);
902
        sheet.getRow(row).createCell(4).setCellValue(grandTotalCredit);
903
        /*row += 2;
32491 jai.hind 904
        sheet.createRow(row).createCell(0).setCellValue("Closing Balance");
33238 amit.gupta 905
        sheet.getRow(row).createCell(3).setCellValue(closingBalance);*/
32491 jai.hind 906
        row++;
907
        /*
908
         * sheet.createRow(row).createCell(0).setCellValue("Pending Grns");
909
         * sheet.getRow(row).createCell(2).setCellValue(closingBalance); row++;
910
         */
911
        try {
912
            workbook.write(bos);
913
        } finally {
914
            workbook.close();
915
            bos.close();
916
        }
28515 amit.gupta 917
 
32491 jai.hind 918
        return bos;
919
    }
24876 tejbeer 920
 
32491 jai.hind 921
    @RequestMapping(value = "/manualPayment", method = RequestMethod.GET)
922
    public String ManualPayment(HttpServletRequest request, Model model) throws Exception {
30426 tejbeer 923
 
32495 amit.gupta 924
        List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());
32491 jai.hind 925
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
24876 tejbeer 926
 
32495 amit.gupta 927
        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 928
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
929
        model.addAttribute("customRetailers", customRetailers);
24876 tejbeer 930
 
32491 jai.hind 931
        model.addAttribute("referenceTypes", WalletReferenceType.referenceType);
932
        model.addAttribute("transactionTypes", TransactionType.values());
933
        return "wallet-edit";
24876 tejbeer 934
 
32491 jai.hind 935
    }
24876 tejbeer 936
 
32491 jai.hind 937
    @RequestMapping(value = "/getWalletHistory", method = RequestMethod.GET)
32495 amit.gupta 938
    public String getWalletHistory(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
25018 tejbeer 939
 
32491 jai.hind 940
        LOGGER.info("type" + referenceType);
32495 amit.gupta 941
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
25018 tejbeer 942
 
32491 jai.hind 943
        if (userWalletHistory.isEmpty()) {
944
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
945
        }
25018 tejbeer 946
 
32491 jai.hind 947
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
25018 tejbeer 948
 
32491 jai.hind 949
        LOGGER.info("userWallet" + userWallet);
950
        CustomRetailer customretailer = retailerService.getFofoRetailer(userWallet.getUserId());
25018 tejbeer 951
 
32491 jai.hind 952
        model.addAttribute("userWallet", userWallet);
953
        model.addAttribute("customretailer", customretailer);
24876 tejbeer 954
 
32491 jai.hind 955
        model.addAttribute("wallethistory", userWalletHistory);
956
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
957
        return "wallet-history";
25018 tejbeer 958
 
32491 jai.hind 959
    }
25018 tejbeer 960
 
32491 jai.hind 961
    @RequestMapping(value = "/getWalletHistoryByPartner", method = RequestMethod.GET)
32512 amit.gupta 962
    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 963
 
32491 jai.hind 964
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
32495 amit.gupta 965
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectPaginatedByWalletIdReferenceType(userWallet.getId(), referenceType, SortOrder.DESCENDING, offset, limit);
25018 tejbeer 966
 
32491 jai.hind 967
        CustomRetailer customretailer = retailerService.getFofoRetailer(fofoId);
25018 tejbeer 968
 
32491 jai.hind 969
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
32597 amit.gupta 970
 
971
        List<Loan> loans = null;
972
        BigDecimal totalDue = BigDecimal.ZERO;
973
        BigDecimal availableLimit = BigDecimal.ZERO;
974
        BigDecimal creditlimit = BigDecimal.ZERO;
32598 amit.gupta 975
        if (sdCreditRequirement != null) {
32597 amit.gupta 976
            loans = loanRepository.selectActiveLoan(fofoId);
977
            availableLimit = sdCreditRequirement.getAvailableLimit();
978
            creditlimit = sdCreditRequirement.getLimit();
979
            for (Loan loan : loans) {
980
                BigDecimal pendingAmount = loan.getPendingAmount();
981
                BigDecimal interestAccrued = loan.getInterestAccrued();
982
                BigDecimal interestPaid = loan.getInterestPaid();
983
                totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));
984
                availableLimit = creditlimit.subtract(totalDue);
985
            }
32491 jai.hind 986
        }
987
        model.addAttribute("userWallet", userWallet);
988
        model.addAttribute("customretailer", customretailer);
989
        model.addAttribute("wallethistory", userWalletHistory);
990
        model.addAttribute("loans", loans);
991
        model.addAttribute("totalDue", totalDue);
992
        model.addAttribute("availableLimit", availableLimit);
993
        model.addAttribute("creditlimit", creditlimit);
994
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
995
        return "wallet-history";
996
    }
30426 tejbeer 997
 
24876 tejbeer 998
 
32491 jai.hind 999
    @RequestMapping(value = "/getPartnerName", method = RequestMethod.GET)
32495 amit.gupta 1000
    public String getPartnerName(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
24905 amit.gupta 1001
 
32495 amit.gupta 1002
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1003
        if (userWalletHistory.isEmpty()) {
1004
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1005
        }
1006
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
24905 amit.gupta 1007
 
32491 jai.hind 1008
        CustomRetailer retailer = retailerService.getFofoRetailer(userWallet.getUserId());
24905 amit.gupta 1009
 
32491 jai.hind 1010
        model.addAttribute("response1", mvcResponseSender.createResponseString(retailer));
24876 tejbeer 1011
 
32491 jai.hind 1012
        return "response";
24876 tejbeer 1013
 
32491 jai.hind 1014
    }
30677 amit.gupta 1015
 
32491 jai.hind 1016
    @RequestMapping(value = "/reset-wallet/9990381", method = RequestMethod.GET)
1017
    public String walletUpdate(Model model) throws Exception {
1018
        walletService.resetWallet();
1019
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1020
        return "response";
1021
    }
24876 tejbeer 1022
 
32491 jai.hind 1023
    @RequestMapping(value = "/walletUpdate", method = RequestMethod.POST)
32495 amit.gupta 1024
    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 1025
        WalletReferenceType referenceType = WalletReferenceType.findByValue(referenceTypeValue);
1026
        if (reference == 0 && referenceType.getValue() >= WalletReferenceType.INCENTIVES.getValue()) {
1027
            LOGGER.error("referenceType: " + referenceType);
1028
            ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(referenceType);
28515 amit.gupta 1029
 
32491 jai.hind 1030
            if (paymentType == null) {
1031
                paymentType = new ManualPaymentType();
1032
                paymentType.setReferenceType(referenceType);
1033
            }
1034
            paymentType.setCounter(paymentType.getCounter() + 1);
1035
            manualPaymentRequestRepository.persist(paymentType);
1036
            reference = paymentType.getCounter();
28515 amit.gupta 1037
 
32491 jai.hind 1038
        } else if (reference == 0) {
32495 amit.gupta 1039
            throw new ProfitMandiBusinessException("RefrenceId", reference, "System specific reference type cant be used manually");
32491 jai.hind 1040
        }
24876 tejbeer 1041
 
32495 amit.gupta 1042
        List<UserWalletHistory> userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1043
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
1044
        int walletId = userWallet.getId();
1045
        int walletAmount = walletService.getWalletAmount(retailerId);
24876 tejbeer 1046
 
32491 jai.hind 1047
        int returnReference = 0;
1048
        UserWalletHistory newUserWalletHistory = new UserWalletHistory();
28515 amit.gupta 1049
 
32491 jai.hind 1050
        if (!userWalletHistoryList.isEmpty()) {
1051
            long validRetailerEntries = userWalletHistoryList.stream().filter(x -> x.getWalletId() == walletId).count();
1052
            if (validRetailerEntries == 0) {
32495 amit.gupta 1053
                throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id assign to Other  partner");
32491 jai.hind 1054
            }
1055
        }
28515 amit.gupta 1056
 
32491 jai.hind 1057
        if (TransactionType.DEBIT.equals(transactiontype)) {
1058
            amount = -amount;
1059
        }
26485 amit.gupta 1060
 
32491 jai.hind 1061
        userWallet.setAmount(walletAmount + amount);
1062
        newUserWalletHistory.setAmount(amount);
1063
        newUserWalletHistory.setBusinessTimestamp(businessTimestamp);
1064
        newUserWalletHistory.setDescription(description);
1065
        newUserWalletHistory.setReference(reference);
1066
        newUserWalletHistory.setWalletId(userWallet.getId());
1067
        newUserWalletHistory.setReferenceType(referenceType);
1068
        newUserWalletHistory.setTimestamp(LocalDateTime.now());
1069
        userWalletHistoryRepository.persist(newUserWalletHistory);
24876 tejbeer 1070
 
32491 jai.hind 1071
        model.addAttribute("response1", mvcResponseSender.createResponseString(reference));
1072
        return "response";
25018 tejbeer 1073
 
32491 jai.hind 1074
    }
25018 tejbeer 1075
 
33175 amit.gupta 1076
    @Autowired
1077
    HdfcPaymentRepository hdfcPaymentRepository;
1078
 
32491 jai.hind 1079
    @RequestMapping(value = "/addMoney", method = RequestMethod.POST)
32495 amit.gupta 1080
    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 1081
        transactionReference = transactionReference.toUpperCase().trim();
1082
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectByReference(transactionReference);
34096 aman.kumar 1083
        addWalletRequests = addWalletRequests.stream().filter(x -> Arrays.asList(approved, AddWalletRequestStatus.pending).contains(x.getStatus())).collect(Collectors.toList());
33175 amit.gupta 1084
        if (addWalletRequests.size() > 0) {
1085
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1086
        }
1087
        HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(transactionReference);
33205 amit.gupta 1088
        if (hdfcPayment != null) {
33175 amit.gupta 1089
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1090
        }
32491 jai.hind 1091
        AddWalletRequest addWalletRequest = new AddWalletRequest();
1092
        addWalletRequest.setRetailerId(fofoId);
1093
        addWalletRequest.setAmount(amount);
33175 amit.gupta 1094
        addWalletRequest.setTransaction_reference(transactionReference.toUpperCase());
32491 jai.hind 1095
        addWalletRequest.setCreateTimestamp(LocalDateTime.now());
1096
        addWalletRequest.setBank_name(bankName);
1097
        addWalletRequest.setReference_date(referenceTime.toLocalDate());
1098
        addWalletRequest.setStatus(AddWalletRequestStatus.pending);
25018 tejbeer 1099
 
32491 jai.hind 1100
        LOGGER.info("info" + addWalletRequest);
29811 tejbeer 1101
 
32491 jai.hind 1102
        addWalletRequestRepository.persist(addWalletRequest);
1103
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1104
        return "response";
1105
    }
29811 tejbeer 1106
 
33045 amit.gupta 1107
    List<Gateway> directGateways = Arrays.asList(Gateway.SDDIRECT, Gateway.SIDBI);
1108
 
1109
    @Autowired
1110
    FofoSidbiSanctionRepository fofoSidbiSanctionRepository;
33175 amit.gupta 1111
 
32491 jai.hind 1112
    @RequestMapping(value = "/getCreditDetail", method = RequestMethod.GET)
1113
    public String getCreditDetail(HttpServletRequest request, Model model) throws Exception {
33175 amit.gupta 1114
        List<CreditAccount> creditAccounts = creditAccountRepository.selectAll().stream().filter(x -> directGateways.contains(x.getGateway())).collect(Collectors.toList());
32491 jai.hind 1115
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29962 tejbeer 1116
 
33420 amit.gupta 1117
        List<Integer> fofoIds = creditAccounts.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
33045 amit.gupta 1118
        //Need to maintain valid upto
33175 amit.gupta 1119
        Map<Integer, FofoSidbiSanction> fofoSidbiPendingSanctionsMap = fofoSidbiSanctionRepository.selectAll(Optional.of(false)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
29811 tejbeer 1120
 
33420 amit.gupta 1121
        Map<Integer, Integer> partnerAverageCreditDaysMap = new HashMap<>();
33045 amit.gupta 1122
 
33420 amit.gupta 1123
        List<Loan> loans = loanRepository.selectAllLoans(fofoIds, DateRangeModel.withStartDate(LocalDate.now().atStartOfDay().minusYears(2)));
1124
        Map<Integer, List<Loan>> partnerClosedLoansMap = loans.stream().filter(x -> x.getPendingAmount().compareTo(BigDecimal.ZERO) == 0)
1125
                .collect(Collectors.groupingBy(x -> x.getFofoId()));
1126
        for (Integer fofoId : fofoIds) {
1127
            List<Loan> closedLoans = partnerClosedLoansMap.get(fofoId);
1128
 
1129
            if (closedLoans != null) {
1130
                long averageCreditDays = Math.round(closedLoans.stream().mapToLong(x -> Duration.between(x.getCreatedOn(),
1131
                        x.getSettledOn() == null ? x.getCreatedOn().plusDays(10) : x.getSettledOn()).toDays() + 1).average().orElse(0.0));
1132
                partnerAverageCreditDaysMap.put(fofoId, (int) averageCreditDays);
1133
            }
1134
        }
1135
 
1136
 
32491 jai.hind 1137
        model.addAttribute("creditAccounts", creditAccounts);
33045 amit.gupta 1138
        model.addAttribute("fofoSidbiPendingSanctionsMap", fofoSidbiPendingSanctionsMap);
1139
        model.addAttribute("directGateways", directGateways);
32491 jai.hind 1140
        model.addAttribute("customRetailers", customRetailers);
33420 amit.gupta 1141
        model.addAttribute("partnerAverageCreditDaysMap", partnerAverageCreditDaysMap);
32491 jai.hind 1142
        return "partner-credit-detail";
1143
    }
29811 tejbeer 1144
 
33045 amit.gupta 1145
 
33359 amit.gupta 1146
    @Autowired
1147
    SidbiService sidbiService;
33363 amit.gupta 1148
 
32491 jai.hind 1149
    @RequestMapping(value = "/activateKred", method = RequestMethod.POST)
33045 amit.gupta 1150
    public String activateKred(HttpServletRequest request, @RequestParam int id, Model model, @RequestParam Gateway gateway) throws Exception {
32491 jai.hind 1151
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
33359 amit.gupta 1152
        if (creditAccount.getGateway().equals(gateway)) {
1153
            creditAccount.setActive(true);
1154
        } else {
33363 amit.gupta 1155
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(creditAccount.getFofoId());
33360 amit.gupta 1156
 
33363 amit.gupta 1157
            if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) != 0) {
33360 amit.gupta 1158
                LOGGER.info("sdCreditRequirement - {}", sdCreditRequirement);
33363 amit.gupta 1159
                throw new ProfitMandiBusinessException("Could not change to " + gateway + " unless previous loans are settled", "", "");
33205 amit.gupta 1160
            }
33359 amit.gupta 1161
            if (gateway.equals(Gateway.SIDBI)) {
1162
                //TODO - Issuance pending
1163
                FofoSidbiSanction fofoSidbiSanction = fofoSidbiSanctionRepository.selectByFofoId(creditAccount.getFofoId());
1164
                sidbiService.issueLimit(fofoSidbiSanction);
33363 amit.gupta 1165
                sdCreditRequirement.setLimit(BigDecimal.valueOf(fofoSidbiSanction.getLoanAmount()));
1166
                sdCreditRequirement.setSuggestedLimit(sdCreditRequirement.getLimit());
33359 amit.gupta 1167
                if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) > 0) {
1168
                    throw new ProfitMandiBusinessException("Loans are not closed", "Loans are not closed", "Loans are not closed");
1169
                }
33363 amit.gupta 1170
                creditAccount.setSanctionedAmount((float) fofoSidbiSanction.getLoanAmount());
33359 amit.gupta 1171
            }
33363 amit.gupta 1172
            creditAccount.setAvailableAmount(creditAccount.getSanctionedAmount());
1173
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
1174
            creditAccount.setActive(true);
1175
            creditAccount.setGateway(gateway);
33045 amit.gupta 1176
        }
29811 tejbeer 1177
 
32491 jai.hind 1178
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
30859 tejbeer 1179
 
32491 jai.hind 1180
        String title = "Loan Approved";
1181
        String url = "http://app.smartdukaan.com/pages/home/credit";
32495 amit.gupta 1182
        String message = "Congratulations! Your Credit Limit is approved for Rs." + FormattingUtils.formatDecimal(creditAccount.getSanctionedAmount());
1183
        notificationService.sendNotification(creditAccount.getFofoId(), "Loan", MessageType.notification, title, message, url);
29811 tejbeer 1184
 
32491 jai.hind 1185
        model.addAttribute("creditAccount", creditAccount);
1186
        model.addAttribute("customRetailers", customRetailers);
1187
        return "partner-credit-detail-row";
1188
    }
29811 tejbeer 1189
 
32491 jai.hind 1190
    @RequestMapping(value = "/deactivateKred", method = RequestMethod.POST)
1191
    public String deactivateKred(HttpServletRequest request, @RequestParam int id, Model model) throws Exception {
1192
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
29811 tejbeer 1193
 
32491 jai.hind 1194
        creditAccount.setActive(false);
29811 tejbeer 1195
 
32491 jai.hind 1196
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29811 tejbeer 1197
 
32491 jai.hind 1198
        model.addAttribute("creditAccount", creditAccount);
1199
        model.addAttribute("customRetailers", customRetailers);
1200
        return "partner-credit-detail-row";
1201
    }
1202
 
22551 ashik.ali 1203
}