Subversion Repositories SmartDukaan

Rev

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