Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
22550 ashik.ali 1
package com.spice.profitmandi.service.wallet;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
34261 tejus.loha 4
import com.spice.profitmandi.common.model.CustomRetailer;
30740 amit.gupta 5
import com.spice.profitmandi.common.model.ProfitMandiConstants;
34261 tejus.loha 6
import com.spice.profitmandi.common.util.FileUtil;
23269 ashik.ali 7
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
25542 amit.gupta 8
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
34261 tejus.loha 9
import com.spice.profitmandi.dao.entity.transaction.AddWalletRequest;
32494 amit.gupta 10
import com.spice.profitmandi.dao.entity.transaction.ManualPaymentType;
22550 ashik.ali 11
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
12
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
34674 aman.kumar 13
import com.spice.profitmandi.dao.entity.user.User;
22550 ashik.ali 14
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
34261 tejus.loha 15
import com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus;
16
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
32494 amit.gupta 17
import com.spice.profitmandi.dao.repository.catalog.ManualPaymentRequestRepository;
25542 amit.gupta 18
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33845 tejus.loha 19
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
33172 tejus.loha 20
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
22550 ashik.ali 21
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
22
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
23
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
33845 tejus.loha 24
import com.spice.profitmandi.dao.repository.user.StoreTimelinetbRepository;
34674 aman.kumar 25
import com.spice.profitmandi.dao.repository.user.UserRepository;
30025 amit.gupta 26
import com.spice.profitmandi.service.NotificationService;
30740 amit.gupta 27
import com.spice.profitmandi.service.PartnerInvestmentService;
34261 tejus.loha 28
import com.spice.profitmandi.service.order.OrderService;
29
import com.spice.profitmandi.service.user.RetailerService;
33845 tejus.loha 30
import com.spice.profitmandi.service.user.StoreTimelineTatService;
22857 ashik.ali 31
import in.shop2020.model.v1.order.WalletReferenceType;
30025 amit.gupta 32
import org.apache.logging.log4j.LogManager;
33
import org.apache.logging.log4j.Logger;
34
import org.springframework.beans.factory.annotation.Autowired;
34261 tejus.loha 35
import org.springframework.http.ResponseEntity;
30025 amit.gupta 36
import org.springframework.stereotype.Component;
22857 ashik.ali 37
 
30025 amit.gupta 38
import java.time.LocalDateTime;
39
import java.util.*;
40
import java.util.stream.Collectors;
41
 
22550 ashik.ali 42
@Component
43
public class WalletServiceImpl implements WalletService {
44
 
32494 amit.gupta 45
    private static final Logger LOGGER = LogManager.getLogger(WalletServiceImpl.class);
25395 tejbeer 46
 
32494 amit.gupta 47
    @Autowired
48
    ManualPaymentRequestRepository manualPaymentRequestRepository;
34261 tejus.loha 49
    @Autowired
50
    AddWalletRequestRepository addWalletRequestRepository;
51
    @Autowired
52
    OrderService orderService;
53
    @Autowired
54
    RetailerService retailerService;
33194 amit.gupta 55
    ProfitMandiBusinessException pbse = new ProfitMandiBusinessException("Wallet", "Wallet", "Wallet is under maintainance, please try after some time");
56
    ProfitMandiBusinessException inactivepbse = new ProfitMandiBusinessException("Wallet", "Wallet", "Investment is incomplete, please add amount to wallet to complete the investment");
57
 
32494 amit.gupta 58
    @Autowired
59
    PartnerInvestmentService partnerInvestmentService;
60
    private boolean underMaintainance = false;
61
    @Autowired
62
    private UserAccountRepository userAccountRepository;
33172 tejus.loha 63
 
32494 amit.gupta 64
    @Autowired
65
    private UserWalletRepository userWalletRepository;
66
    @Autowired
67
    private FofoStoreRepository fofoStoreRepository;
68
    @Autowired
69
    private UserWalletHistoryRepository userWalletHistoryRepository;
70
    @Autowired
71
    private NotificationService notificationService;
24739 tejbeer 72
 
33172 tejus.loha 73
    @Autowired
74
    RetailerRepository retailerRepository;
33845 tejus.loha 75
    @Autowired
76
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
77
    @Autowired
78
    StoreTimelineTatService storeTimelineTatService;
79
    @Autowired
80
    StoreTimelinetbRepository storeTimelinetbRepository;
33172 tejus.loha 81
 
34674 aman.kumar 82
    @Autowired
83
    UserRepository userRepository;
84
 
32494 amit.gupta 85
    @Override
86
    public void addAmountToWallet(int retailerId, int referenceId, WalletReferenceType referenceType,
87
                                  String description, float amount, LocalDateTime businessTime) throws ProfitMandiBusinessException {
88
        if (Math.round(amount) == 0)
89
            return;
90
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
35828 amit 91
        userWallet.setAmount(userWallet.getAmount() + Math.round(amount));
32494 amit.gupta 92
        this.createUserWalletHistory(Math.round(amount), userWallet.getId(), referenceId, referenceType, description, businessTime);
93
    }
25609 amit.gupta 94
 
32494 amit.gupta 95
    @Override
96
    public void consumeAmountFromWallet(int retailerId, int referenceId, WalletReferenceType referenceType,
97
                                        String description, float amount, LocalDateTime businessTime) throws ProfitMandiBusinessException {
98
        if (underMaintainance) {
99
            throw pbse;
100
        } else if (WalletReferenceType.RECHARGE.equals(referenceType) && !isActive(retailerId)) {
101
            throw inactivepbse;
102
        }
103
        if (amount == 0)
104
            return;
105
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
35828 amit 106
        int walletAmount = userWallet.getAmount();
33547 tejus.loha 107
        if (!WalletReferenceType.DAMAGE_PROTECTION.equals(referenceType) && amount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && Math.floor(amount) > walletAmount) {
34575 vikas.jang 108
            LOGGER.error("Wallet Balance is insufficient!, needed - {}, wallet has - {}, for retailer - {}", Math.floor(amount), walletAmount, retailerId);
34674 aman.kumar 109
            User user = userRepository.selectById(retailerId);
110
            throw new ProfitMandiBusinessException(user.getName(), walletAmount, "WLT_1000");
32494 amit.gupta 111
        }
112
        userWallet.setAmount(walletAmount - Math.round(amount));
113
        this.createUserWalletHistory(-Math.round(amount), userWallet.getId(), referenceId, referenceType, description, businessTime);
114
    }
24739 tejbeer 115
 
32494 amit.gupta 116
    @Override
117
    public void consumeAmountFromWallet(int retailerId, int referenceId, WalletReferenceType referenceType,
118
                                        String description, float amount, LocalDateTime businessTime, boolean forced) throws ProfitMandiBusinessException {
119
        if (underMaintainance) {
120
            throw pbse;
121
        } else if (WalletReferenceType.RECHARGE.equals(referenceType) && !isActive(retailerId)) {
122
            throw inactivepbse;
123
        }
124
        if (amount == 0)
125
            return;
126
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
35828 amit 127
        int walletAmount = userWallet.getAmount();
32494 amit.gupta 128
        if (!forced && amount > 2 && amount > walletAmount) {
129
            LOGGER.error("Wallet Balance is insufficient!");
130
            throw new ProfitMandiBusinessException("balance", walletAmount, "WLT_1000");
131
        }
132
        userWallet.setAmount(walletAmount - Math.round(amount));
133
        this.createUserWalletHistory(-Math.round(amount), userWallet.getId(), referenceId, referenceType, description, businessTime);
134
    }
24739 tejbeer 135
 
32494 amit.gupta 136
    @Override
137
    public void rollbackAmountFromWallet(int retailerId, float amountToRollback, int rollbackReference,
138
                                         WalletReferenceType walletReferenceType, String rollbackReason, LocalDateTime businessTime) throws ProfitMandiBusinessException {
25542 amit.gupta 139
 
32494 amit.gupta 140
        if (amountToRollback == 0)
141
            return;
142
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
35828 amit 143
        int walletAmount = userWallet.getAmount();
32494 amit.gupta 144
        List<UserWalletHistory> uwh = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(rollbackReference, walletReferenceType)
145
                .stream().filter(x -> x.getWalletId() == userWallet.getId()).collect(Collectors.toList());
146
        if (uwh.size() == 0) {
147
            LOGGER.info("Retailer with id {} dont have valid reference {} and reference type {}",
148
                    retailerId, rollbackReference, walletReferenceType);
149
            throw new ProfitMandiBusinessException("Retailer specific wallet entries doesn't exist", retailerId, "Nothing to rollback");
150
        }
151
        // userWallet = userWalletRepository.selectByIdForUpdate(userWallet.getId());
152
        userWallet.setAmount(walletAmount - Math.round(amountToRollback));
153
        this.createUserWalletHistory(-Math.round(amountToRollback), userWallet.getId(), rollbackReference,
154
                walletReferenceType, rollbackReason, businessTime);
155
        userWalletRepository.persist(userWallet);
24739 tejbeer 156
 
32494 amit.gupta 157
    }
30025 amit.gupta 158
 
32494 amit.gupta 159
    private void createUserWalletHistory(float amount, int walletId, int referenceId, WalletReferenceType referenceType,
160
                                         String description, LocalDateTime businessTimestamp) {
161
        if (amount == 0)
162
            return;
163
        UserWalletHistory userWalletHistory = new UserWalletHistory();
164
        userWalletHistory.setWalletId(walletId);
165
        userWalletHistory.setAmount(Math.round(amount));
166
        userWalletHistory.setReference(referenceId);
167
        userWalletHistory.setReferenceType(referenceType);
168
        userWalletHistory.setTimestamp(LocalDateTime.now());
169
        userWalletHistory.setDescription(description);
170
        userWalletHistory.setBusinessTimestamp(businessTimestamp);
171
        userWalletHistoryRepository.persist(userWalletHistory);
172
    }
24739 tejbeer 173
 
32494 amit.gupta 174
    @Override
175
    public UserWallet getUserWalletByUserId(int userId) throws ProfitMandiBusinessException {
176
        UserAccount userAccount = userAccountRepository.selectByUserIdType(userId, AccountType.saholic);
23509 amit.gupta 177
 
32494 amit.gupta 178
        if (underMaintainance) {
179
            throw pbse;
180
        }
181
        return userWalletRepository.selectByRetailerId(Integer.valueOf(userAccount.getAccountKey()));
182
    }
30889 amit.gupta 183
 
32494 amit.gupta 184
    @Override
185
    public List<UserWalletHistory> getUserWalletHistoryByUserId(int userId) throws ProfitMandiBusinessException {
186
        if (underMaintainance || !isActive(userId)) {
187
            throw pbse;
188
        }
189
        UserWallet userWallet = this.getUserWalletByUserId(userId);
190
        List<UserWalletHistory> userWalletHistories = userWalletHistoryRepository.selectByWalletId(userWallet.getId());
191
        return userWalletHistories;
192
    }
25395 tejbeer 193
 
32494 amit.gupta 194
    //Definition is now changed, active also means valid investment should be ok
195
    private boolean isActive(int userId) {
196
        boolean active = true;
197
        try {
198
            FofoStore fs = fofoStoreRepository.selectByRetailerId(userId);
199
            active = fs.isActive() && partnerInvestmentService.isInvestmentOk(userId, ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT);
200
        } catch (Exception e) {
24739 tejbeer 201
 
32494 amit.gupta 202
        }
203
        return active;
204
    }
24739 tejbeer 205
 
32494 amit.gupta 206
    @Override
207
    public List<UserWalletHistory> getUserWalletHistoryByRetailerId(int retailerId)
208
            throws ProfitMandiBusinessException {
209
        if (underMaintainance) {
210
            throw pbse;
211
        }
212
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
213
        return userWalletHistoryRepository.selectByWalletId(userWallet.getId());
214
    }
24739 tejbeer 215
 
32494 amit.gupta 216
    @Override
217
    public long getSizeByRetailerId(int retailerId, LocalDateTime startDateTime, LocalDateTime endDateTime)
218
            throws ProfitMandiBusinessException {
219
        if (underMaintainance) {
220
            throw pbse;
221
        }
222
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
223
        return userWalletHistoryRepository.selectCountByWalletId(userWallet.getId(), startDateTime, endDateTime);
224
    }
25542 amit.gupta 225
 
32494 amit.gupta 226
    @Override
227
    public List<UserWalletHistory> getPaginatedUserWalletHistoryByRetailerId(int retailerId,
228
                                                                             LocalDateTime startDateTime, LocalDateTime endDateTime, int offset, int limit)
229
            throws ProfitMandiBusinessException {
230
        if (underMaintainance) {
231
            throw pbse;
232
        }
233
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
234
        return userWalletHistoryRepository.selectPaginatedByWalletId(userWallet.getId(), startDateTime, endDateTime,
235
                offset, limit);
236
    }
22550 ashik.ali 237
 
32494 amit.gupta 238
    @Override
33247 ranu 239
    public Map<Integer, UserWallet> getRetailerIdUserWalletMap(Set<Integer> retailerIds) throws ProfitMandiBusinessException {
32494 amit.gupta 240
        List<UserWallet> userWallets = userWalletRepository.selectByRetailerIds(retailerIds);
241
        Map<Integer, UserWallet> retailerIdUserWalletMap = new HashMap<>();
242
        for (UserWallet userWallet : userWallets) {
243
            retailerIdUserWalletMap.put(userWallet.getUserId(), userWallet);
244
        }
245
        return retailerIdUserWalletMap;
246
    }
24739 tejbeer 247
 
32494 amit.gupta 248
    @Override
33247 ranu 249
    public Map<Integer, Integer> getWaleltRetailerMap(Set<Integer> walletIds) throws ProfitMandiBusinessException {
32494 amit.gupta 250
        List<UserWallet> userWallets = userWalletRepository.selectAllById(walletIds);
251
        Map<Integer, Integer> walletRetailerMap = new HashMap<>();
252
        for (UserWallet userWallet : userWallets) {
253
            walletRetailerMap.put(userWallet.getId(), userWallet.getUserId());
254
        }
255
        return walletRetailerMap;
256
    }
30740 amit.gupta 257
 
32494 amit.gupta 258
    @Override
259
    public boolean isExistWalletHistory(int retailerId, int referenceId, WalletReferenceType referenceType)
260
            throws ProfitMandiBusinessException {
261
        if (underMaintainance) {
262
            throw pbse;
263
        }
264
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
265
        return userWalletHistoryRepository.isExist(userWallet.getId(), referenceType, referenceId);
266
    }
25542 amit.gupta 267
 
32494 amit.gupta 268
    @Override
269
    public UserWallet getUserWallet(int retailerId) throws ProfitMandiBusinessException {
270
        if (underMaintainance) {
271
            throw pbse;
272
        }
273
        try {
274
            return userWalletRepository.selectByRetailerId(retailerId);
275
        } catch (Exception e) {
276
            UserWallet uw = new UserWallet();
277
            uw.setAmount(0);
278
            uw.setRefundableAmount(0);
279
            uw.setUserId(retailerId);
280
            userWalletRepository.persist(uw);
281
            return uw;
282
        }
283
    }
25542 amit.gupta 284
 
32494 amit.gupta 285
    @Override
286
    public float getOpeningTill(int fofoId, LocalDateTime date) throws ProfitMandiBusinessException {
287
        UserWallet wallet = userWalletRepository.selectByRetailerId(fofoId);
288
        return userWalletHistoryRepository.getSumTillDate(wallet.getId(), date);
289
    }
24739 tejbeer 290
 
32494 amit.gupta 291
    @Override
292
    public float getOpeningTillExcludingPurchase(int fofoId, LocalDateTime date) throws ProfitMandiBusinessException {
293
        UserWallet wallet = userWalletRepository.selectByRetailerId(fofoId);
294
        return userWalletHistoryRepository.getSumTillDate(wallet.getId(), date) - userWalletHistoryRepository.getSumTillDate(wallet.getId(), date, WalletReferenceType.PURCHASE);
295
    }
24739 tejbeer 296
 
32494 amit.gupta 297
    @Override
298
    public boolean refundToWallet(int retailerId, float amountToRefund, int transactionId,
299
                                  WalletReferenceType walletReferenceType, String description) throws ProfitMandiBusinessException {
24739 tejbeer 300
 
32494 amit.gupta 301
        List<UserWalletHistory> all_entries = userWalletHistoryRepository
302
                .selectAllByreferenceIdandreferenceType(transactionId, walletReferenceType);
30449 amit.gupta 303
 
32494 amit.gupta 304
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
35828 amit 305
        int walletAmount = userWallet.getAmount();
32494 amit.gupta 306
        LOGGER.info("userWallet" + userWallet);
307
        int max_eligible_credit_amount = 0;
24739 tejbeer 308
 
32494 amit.gupta 309
        LOGGER.info("all_entries {}", all_entries);
310
        for (UserWalletHistory history : all_entries) {
311
            max_eligible_credit_amount -= history.getAmount();
312
        }
313
        if (max_eligible_credit_amount < amountToRefund) {
314
            LOGGER.info("Cant be credited back to wallet as most of it has been already credited");
315
            return false;
316
        }
22550 ashik.ali 317
 
32494 amit.gupta 318
        userWallet.setAmount(walletAmount + Math.round(amountToRefund));
23509 amit.gupta 319
 
32494 amit.gupta 320
        LOGGER.info("userWallet" + userWallet);
30449 amit.gupta 321
 
32494 amit.gupta 322
        UserWalletHistory userWalletHistory = new UserWalletHistory();
323
        userWalletHistory.setAmount(Math.round(amountToRefund));
324
        userWalletHistory.setReference(transactionId);
325
        userWalletHistory.setReferenceType(walletReferenceType);
326
        userWalletHistory.setWalletId(userWallet.getId());
327
        userWalletHistory.setTimestamp(LocalDateTime.now());
328
        userWalletHistory.setDescription(description);
329
        userWalletHistory.setBusinessTimestamp(all_entries.get(0).getBusinessTimestamp());
30449 amit.gupta 330
 
32494 amit.gupta 331
        userWalletHistoryRepository.persist(userWalletHistory);
332
        return true;
24739 tejbeer 333
 
32494 amit.gupta 334
    }
26254 amit.gupta 335
 
32494 amit.gupta 336
    @Override
337
    public int getWalletAmount(int retailerId) throws ProfitMandiBusinessException {
338
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
339
        if (userWallet == null) {
33421 amit.gupta 340
            userWallet = new UserWallet();
341
            userWallet.setUserId(retailerId);
342
            userWalletRepository.persist(userWallet);
32494 amit.gupta 343
        }
35828 amit 344
        int sum = (int) userWalletHistoryRepository.selectSumByWallet(userWallet.getId());
345
        userWallet.setAmount(sum);
346
        return sum;
32494 amit.gupta 347
    }
24739 tejbeer 348
 
32494 amit.gupta 349
    @Override
350
    public List<UserWalletHistory> getAllByReference(int fofoId, int reference, WalletReferenceType walletReferenceType)
351
            throws ProfitMandiBusinessException {
352
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
353
        if (userWallet == null) {
354
            return new ArrayList<UserWalletHistory>();
355
        }
356
        return userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(userWallet.getId(), reference,
357
                walletReferenceType);
358
    }
30449 amit.gupta 359
 
32494 amit.gupta 360
    @Override
361
    public void resetWallet() throws ProfitMandiBusinessException {
362
        List<UserWallet> userWallets = userWalletRepository.selectAll();
363
        for (UserWallet userWallet : userWallets) {
364
            userWallet.setAmount(this.getWalletAmount(userWallet.getUserId()));
24739 tejbeer 365
 
32494 amit.gupta 366
        }
367
    }
25395 tejbeer 368
 
32494 amit.gupta 369
    @Override
370
    public int getManualReference(WalletReferenceType referenceType) {
371
        ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(referenceType);
24739 tejbeer 372
 
32494 amit.gupta 373
        if (paymentType == null) {
374
            paymentType = new ManualPaymentType();
375
            paymentType.setReferenceType(referenceType);
376
            manualPaymentRequestRepository.persist(paymentType);
377
        }
378
        paymentType.setCounter(paymentType.getCounter() + 1);
379
        return paymentType.getCounter();
24739 tejbeer 380
 
32494 amit.gupta 381
    }
34261 tejus.loha 382
 
383
    @Override
384
    public ResponseEntity<?> createAddWalletRequestReport(LocalDateTime startDate, LocalDateTime endDate, AddWalletRequestStatus status) throws Exception {
385
        List<List<?>> rows = new ArrayList<>();
386
        List<String> header = Arrays.asList(
387
                "Retailer Id",
388
                "Retailer Name",
389
                "Email",
390
                "City",
391
                "State",
392
                "Transaction Reference",
393
                "Bank Name",
394
                "Reference Date",
395
                "Amount",
396
                "status",
397
                "Created On",
398
                "Updated On"
399
        );
400
 
401
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, status);
402
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
403
        for (AddWalletRequest addWalletRequest : addWalletRequests) {
404
            CustomRetailer customRetailer = customRetailerMap.get(addWalletRequest.getRetailerId());
405
            rows.add(Arrays
406
                    .asList(
407
                            addWalletRequest.getRetailerId(),
408
                            customRetailer.getBusinessName(),
409
                            customRetailer.getEmail(),
410
                            customRetailer.getAddress().getCity(),
411
                            customRetailer.getAddress().getState(),
412
                            addWalletRequest.getTransaction_reference(),
413
                            addWalletRequest.getBank_name(),
414
                            addWalletRequest.getReference_date(),
415
                            addWalletRequest.getAmount(),
416
                            addWalletRequest.getStatus(),
417
                            addWalletRequest.getCreateTimestamp(),
418
                            addWalletRequest.getUpdateTimestamp()
419
                    )
420
            );
421
        }
422
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(header, rows);
423
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Add-wallet-request-"+status+"-Reort-" + startDate.toLocalDate() + "-To-" + endDate.toLocalDate());
424
        return responseEntity;
425
    }
32494 amit.gupta 426
}
24739 tejbeer 427