Subversion Repositories SmartDukaan

Rev

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