Subversion Repositories SmartDukaan

Rev

Rev 31921 | Rev 32871 | 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
 
30066 amit.gupta 3
import com.spice.profitmandi.common.enumuration.MessageType;
22550 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30740 amit.gupta 5
import com.spice.profitmandi.common.model.ProfitMandiConstants;
30025 amit.gupta 6
import com.spice.profitmandi.common.util.FormattingUtils;
23269 ashik.ali 7
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
25542 amit.gupta 8
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
32494 amit.gupta 9
import com.spice.profitmandi.dao.entity.transaction.ManualPaymentType;
22550 ashik.ali 10
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
11
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
12
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
32494 amit.gupta 13
import com.spice.profitmandi.dao.repository.catalog.ManualPaymentRequestRepository;
25542 amit.gupta 14
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22550 ashik.ali 15
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
16
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
17
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
30025 amit.gupta 18
import com.spice.profitmandi.service.NotificationService;
30740 amit.gupta 19
import com.spice.profitmandi.service.PartnerInvestmentService;
22857 ashik.ali 20
import in.shop2020.model.v1.order.WalletReferenceType;
30025 amit.gupta 21
import org.apache.logging.log4j.LogManager;
22
import org.apache.logging.log4j.Logger;
23
import org.springframework.beans.factory.annotation.Autowired;
24
import org.springframework.stereotype.Component;
22857 ashik.ali 25
 
30025 amit.gupta 26
import java.time.LocalDateTime;
27
import java.util.*;
28
import java.util.stream.Collectors;
29
 
22550 ashik.ali 30
@Component
31
public class WalletServiceImpl implements WalletService {
32
 
32494 amit.gupta 33
    private static final Logger LOGGER = LogManager.getLogger(WalletServiceImpl.class);
25395 tejbeer 34
 
32494 amit.gupta 35
    @Autowired
36
    ManualPaymentRequestRepository manualPaymentRequestRepository;
37
    ProfitMandiBusinessException pbse = new ProfitMandiBusinessException("Wallet", "Wallet",
38
            "Wallet is under maintainance, please try after some time");
39
    ProfitMandiBusinessException inactivepbse = new ProfitMandiBusinessException("Wallet", "Wallet",
40
            "Investment is incomplete, please add amount to wallet to complete the investment");
41
    @Autowired
42
    PartnerInvestmentService partnerInvestmentService;
43
    private boolean underMaintainance = false;
44
    @Autowired
45
    private UserAccountRepository userAccountRepository;
46
    @Autowired
47
    private WalletService walletService;
48
    @Autowired
49
    private UserWalletRepository userWalletRepository;
50
    @Autowired
51
    private FofoStoreRepository fofoStoreRepository;
52
    @Autowired
53
    private UserWalletHistoryRepository userWalletHistoryRepository;
54
    @Autowired
55
    private NotificationService notificationService;
24739 tejbeer 56
 
32494 amit.gupta 57
    @Override
58
    public void addAmountToWallet(int retailerId, int referenceId, WalletReferenceType referenceType,
59
                                  String description, float amount, LocalDateTime businessTime) throws ProfitMandiBusinessException {
60
        if (Math.round(amount) == 0)
61
            return;
62
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
63
        int walletAmount = walletService.getWalletAmount(retailerId);
64
        // userWallet = userWalletRepository.selectByIdForUpdate(userWallet.getId());
65
        userWallet.setAmount(walletAmount + Math.round(amount));
66
        if (amount > 0) {
67
            notificationService.sendNotification(retailerId, "walletcredit", MessageType.wallet, "Rs." + FormattingUtils.formatDecimal(amount) + " credited in SD Wallet", description);
68
        }
69
        this.createUserWalletHistory(Math.round(amount), userWallet.getId(), referenceId, referenceType, description, businessTime);
70
    }
25609 amit.gupta 71
 
32494 amit.gupta 72
    @Override
73
    public void consumeAmountFromWallet(int retailerId, int referenceId, WalletReferenceType referenceType,
74
                                        String description, float amount, LocalDateTime businessTime) throws ProfitMandiBusinessException {
75
        if (underMaintainance) {
76
            throw pbse;
77
        } else if (WalletReferenceType.RECHARGE.equals(referenceType) && !isActive(retailerId)) {
78
            throw inactivepbse;
79
        }
80
        if (amount == 0)
81
            return;
82
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
83
        int walletAmount = walletService.getWalletAmount(retailerId);
84
        // userWallet = userWalletRepository.selectByIdForUpdate(userWallet.getId());
85
        if (!WalletReferenceType.DAMAGE_PROTECTION.equals(referenceType) && amount > 2 && Math.floor(amount) > walletAmount) {
86
            LOGGER.error("Wallet Balance is insufficient!");
87
            throw new ProfitMandiBusinessException("balance", walletAmount, "WLT_1000");
88
        }
89
        userWallet.setAmount(walletAmount - Math.round(amount));
90
        userWalletRepository.persist(userWallet);
91
        this.createUserWalletHistory(-Math.round(amount), userWallet.getId(), referenceId, referenceType, description, businessTime);
92
    }
24739 tejbeer 93
 
32494 amit.gupta 94
    @Override
95
    public void consumeAmountFromWallet(int retailerId, int referenceId, WalletReferenceType referenceType,
96
                                        String description, float amount, LocalDateTime businessTime, boolean forced) throws ProfitMandiBusinessException {
97
        if (underMaintainance) {
98
            throw pbse;
99
        } else if (WalletReferenceType.RECHARGE.equals(referenceType) && !isActive(retailerId)) {
100
            throw inactivepbse;
101
        }
102
        if (amount == 0)
103
            return;
104
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
105
        int walletAmount = walletService.getWalletAmount(retailerId);
106
        // userWallet = userWalletRepository.selectByIdForUpdate(userWallet.getId());
107
        if (!forced && amount > 2 && amount > walletAmount) {
108
            LOGGER.error("Wallet Balance is insufficient!");
109
            throw new ProfitMandiBusinessException("balance", walletAmount, "WLT_1000");
110
        }
111
        userWallet.setAmount(walletAmount - Math.round(amount));
112
        this.createUserWalletHistory(-Math.round(amount), userWallet.getId(), referenceId, referenceType, description, businessTime);
113
    }
24739 tejbeer 114
 
32494 amit.gupta 115
    @Override
116
    public void rollbackAmountFromWallet(int retailerId, float amountToRollback, int rollbackReference,
117
                                         WalletReferenceType walletReferenceType, String rollbackReason, LocalDateTime businessTime) throws ProfitMandiBusinessException {
25542 amit.gupta 118
 
32494 amit.gupta 119
        if (amountToRollback == 0)
120
            return;
121
        int walletAmount = walletService.getWalletAmount(retailerId);
122
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
123
        List<UserWalletHistory> uwh = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(rollbackReference, walletReferenceType)
124
                .stream().filter(x -> x.getWalletId() == userWallet.getId()).collect(Collectors.toList());
125
        if (uwh.size() == 0) {
126
            LOGGER.info("Retailer with id {} dont have valid reference {} and reference type {}",
127
                    retailerId, rollbackReference, walletReferenceType);
128
            throw new ProfitMandiBusinessException("Retailer specific wallet entries doesn't exist", retailerId, "Nothing to rollback");
129
        }
130
        // userWallet = userWalletRepository.selectByIdForUpdate(userWallet.getId());
131
        userWallet.setAmount(walletAmount - Math.round(amountToRollback));
132
        this.createUserWalletHistory(-Math.round(amountToRollback), userWallet.getId(), rollbackReference,
133
                walletReferenceType, rollbackReason, businessTime);
134
        userWalletRepository.persist(userWallet);
24739 tejbeer 135
 
32494 amit.gupta 136
    }
30025 amit.gupta 137
 
32494 amit.gupta 138
    private void createUserWalletHistory(float amount, int walletId, int referenceId, WalletReferenceType referenceType,
139
                                         String description, LocalDateTime businessTimestamp) {
140
        if (amount == 0)
141
            return;
142
        UserWalletHistory userWalletHistory = new UserWalletHistory();
143
        userWalletHistory.setWalletId(walletId);
144
        userWalletHistory.setAmount(Math.round(amount));
145
        userWalletHistory.setReference(referenceId);
146
        userWalletHistory.setReferenceType(referenceType);
147
        userWalletHistory.setTimestamp(LocalDateTime.now());
148
        userWalletHistory.setDescription(description);
149
        userWalletHistory.setBusinessTimestamp(businessTimestamp);
150
        userWalletHistoryRepository.persist(userWalletHistory);
151
    }
24739 tejbeer 152
 
32494 amit.gupta 153
    @Override
154
    public UserWallet getUserWalletByUserId(int userId) throws ProfitMandiBusinessException {
155
        UserAccount userAccount = userAccountRepository.selectByUserIdType(userId, AccountType.saholic);
23509 amit.gupta 156
 
32494 amit.gupta 157
        if (underMaintainance) {
158
            throw pbse;
159
        }
160
        return userWalletRepository.selectByRetailerId(Integer.valueOf(userAccount.getAccountKey()));
161
    }
30889 amit.gupta 162
 
32494 amit.gupta 163
    @Override
164
    public List<UserWalletHistory> getUserWalletHistoryByUserId(int userId) throws ProfitMandiBusinessException {
165
        if (underMaintainance || !isActive(userId)) {
166
            throw pbse;
167
        }
168
        UserWallet userWallet = this.getUserWalletByUserId(userId);
169
        List<UserWalletHistory> userWalletHistories = userWalletHistoryRepository.selectByWalletId(userWallet.getId());
170
        return userWalletHistories;
171
    }
25395 tejbeer 172
 
32494 amit.gupta 173
    //Definition is now changed, active also means valid investment should be ok
174
    private boolean isActive(int userId) {
175
        boolean active = true;
176
        try {
177
            FofoStore fs = fofoStoreRepository.selectByRetailerId(userId);
178
            active = fs.isActive() && partnerInvestmentService.isInvestmentOk(userId, ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT);
179
        } catch (Exception e) {
24739 tejbeer 180
 
32494 amit.gupta 181
        }
182
        return active;
183
    }
24739 tejbeer 184
 
32494 amit.gupta 185
    @Override
186
    public List<UserWalletHistory> getUserWalletHistoryByRetailerId(int retailerId)
187
            throws ProfitMandiBusinessException {
188
        if (underMaintainance) {
189
            throw pbse;
190
        }
191
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
192
        return userWalletHistoryRepository.selectByWalletId(userWallet.getId());
193
    }
24739 tejbeer 194
 
32494 amit.gupta 195
    @Override
196
    public long getSizeByRetailerId(int retailerId, LocalDateTime startDateTime, LocalDateTime endDateTime)
197
            throws ProfitMandiBusinessException {
198
        if (underMaintainance) {
199
            throw pbse;
200
        }
201
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
202
        return userWalletHistoryRepository.selectCountByWalletId(userWallet.getId(), startDateTime, endDateTime);
203
    }
25542 amit.gupta 204
 
32494 amit.gupta 205
    @Override
206
    public List<UserWalletHistory> getPaginatedUserWalletHistoryByRetailerId(int retailerId,
207
                                                                             LocalDateTime startDateTime, LocalDateTime endDateTime, int offset, int limit)
208
            throws ProfitMandiBusinessException {
209
        if (underMaintainance) {
210
            throw pbse;
211
        }
212
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
213
        return userWalletHistoryRepository.selectPaginatedByWalletId(userWallet.getId(), startDateTime, endDateTime,
214
                offset, limit);
215
    }
22550 ashik.ali 216
 
32494 amit.gupta 217
    @Override
218
    public Map<Integer, UserWallet> getRetailerIdUserWalletMap(Set<Integer> retailerIds) {
219
        List<UserWallet> userWallets = userWalletRepository.selectByRetailerIds(retailerIds);
220
        Map<Integer, UserWallet> retailerIdUserWalletMap = new HashMap<>();
221
        for (UserWallet userWallet : userWallets) {
222
            retailerIdUserWalletMap.put(userWallet.getUserId(), userWallet);
223
        }
224
        return retailerIdUserWalletMap;
225
    }
24739 tejbeer 226
 
32494 amit.gupta 227
    @Override
228
    public Map<Integer, Integer> getWaleltRetailerMap(Set<Integer> walletIds) {
229
        List<UserWallet> userWallets = userWalletRepository.selectAllById(walletIds);
230
        Map<Integer, Integer> walletRetailerMap = new HashMap<>();
231
        for (UserWallet userWallet : userWallets) {
232
            walletRetailerMap.put(userWallet.getId(), userWallet.getUserId());
233
        }
234
        return walletRetailerMap;
235
    }
30740 amit.gupta 236
 
32494 amit.gupta 237
    @Override
238
    public boolean isExistWalletHistory(int retailerId, int referenceId, WalletReferenceType referenceType)
239
            throws ProfitMandiBusinessException {
240
        if (underMaintainance) {
241
            throw pbse;
242
        }
243
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
244
        return userWalletHistoryRepository.isExist(userWallet.getId(), referenceType, referenceId);
245
    }
25542 amit.gupta 246
 
32494 amit.gupta 247
    @Override
248
    public UserWallet getUserWallet(int retailerId) throws ProfitMandiBusinessException {
249
        if (underMaintainance) {
250
            throw pbse;
251
        }
252
        try {
253
            return userWalletRepository.selectByRetailerId(retailerId);
254
        } catch (Exception e) {
255
            UserWallet uw = new UserWallet();
256
            uw.setAmount(0);
257
            uw.setRefundableAmount(0);
258
            uw.setUserId(retailerId);
259
            userWalletRepository.persist(uw);
260
            return uw;
261
        }
262
    }
25542 amit.gupta 263
 
32494 amit.gupta 264
    @Override
265
    public float getOpeningTill(int fofoId, LocalDateTime date) throws ProfitMandiBusinessException {
266
        UserWallet wallet = userWalletRepository.selectByRetailerId(fofoId);
267
        return userWalletHistoryRepository.getSumTillDate(wallet.getId(), date);
268
    }
24739 tejbeer 269
 
32494 amit.gupta 270
    @Override
271
    public float getOpeningTillExcludingPurchase(int fofoId, LocalDateTime date) throws ProfitMandiBusinessException {
272
        UserWallet wallet = userWalletRepository.selectByRetailerId(fofoId);
273
        return userWalletHistoryRepository.getSumTillDate(wallet.getId(), date) - userWalletHistoryRepository.getSumTillDate(wallet.getId(), date, WalletReferenceType.PURCHASE);
274
    }
24739 tejbeer 275
 
32494 amit.gupta 276
    @Override
277
    public boolean refundToWallet(int retailerId, float amountToRefund, int transactionId,
278
                                  WalletReferenceType walletReferenceType, String description) throws ProfitMandiBusinessException {
24739 tejbeer 279
 
32494 amit.gupta 280
        List<UserWalletHistory> all_entries = userWalletHistoryRepository
281
                .selectAllByreferenceIdandreferenceType(transactionId, walletReferenceType);
30449 amit.gupta 282
 
32494 amit.gupta 283
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
284
        int walletAmount = walletService.getWalletAmount(retailerId);
285
        LOGGER.info("userWallet" + userWallet);
286
        int max_eligible_credit_amount = 0;
24739 tejbeer 287
 
32494 amit.gupta 288
        LOGGER.info("all_entries {}", all_entries);
289
        for (UserWalletHistory history : all_entries) {
290
            max_eligible_credit_amount -= history.getAmount();
291
        }
292
        if (max_eligible_credit_amount < amountToRefund) {
293
            LOGGER.info("Cant be credited back to wallet as most of it has been already credited");
294
            return false;
295
        }
22550 ashik.ali 296
 
32494 amit.gupta 297
        userWallet.setAmount(walletAmount + Math.round(amountToRefund));
23509 amit.gupta 298
 
32494 amit.gupta 299
        LOGGER.info("userWallet" + userWallet);
30449 amit.gupta 300
 
32494 amit.gupta 301
        UserWalletHistory userWalletHistory = new UserWalletHistory();
302
        userWalletHistory.setAmount(Math.round(amountToRefund));
303
        userWalletHistory.setReference(transactionId);
304
        userWalletHistory.setReferenceType(walletReferenceType);
305
        userWalletHistory.setWalletId(userWallet.getId());
306
        userWalletHistory.setTimestamp(LocalDateTime.now());
307
        userWalletHistory.setDescription(description);
308
        userWalletHistory.setBusinessTimestamp(all_entries.get(0).getBusinessTimestamp());
30449 amit.gupta 309
 
32494 amit.gupta 310
        userWalletHistoryRepository.persist(userWalletHistory);
311
        return true;
24739 tejbeer 312
 
32494 amit.gupta 313
    }
26254 amit.gupta 314
 
32494 amit.gupta 315
    @Override
316
    public int getWalletAmount(int retailerId) throws ProfitMandiBusinessException {
317
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
318
        if (userWallet == null) {
319
            return 0;
320
        }
321
        return (int) userWalletHistoryRepository.selectSumByWallet(userWallet.getId());
322
    }
24739 tejbeer 323
 
32494 amit.gupta 324
    @Override
325
    public List<UserWalletHistory> getAllByReference(int fofoId, int reference, WalletReferenceType walletReferenceType)
326
            throws ProfitMandiBusinessException {
327
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
328
        if (userWallet == null) {
329
            return new ArrayList<UserWalletHistory>();
330
        }
331
        return userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(userWallet.getId(), reference,
332
                walletReferenceType);
333
    }
30449 amit.gupta 334
 
32494 amit.gupta 335
    @Override
336
    public void resetWallet() throws ProfitMandiBusinessException {
337
        List<UserWallet> userWallets = userWalletRepository.selectAll();
338
        for (UserWallet userWallet : userWallets) {
339
            userWallet.setAmount(this.getWalletAmount(userWallet.getUserId()));
24739 tejbeer 340
 
32494 amit.gupta 341
        }
342
    }
25395 tejbeer 343
 
32494 amit.gupta 344
    @Override
345
    public int getManualReference(WalletReferenceType referenceType) {
346
        ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(referenceType);
24739 tejbeer 347
 
32494 amit.gupta 348
        if (paymentType == null) {
349
            paymentType = new ManualPaymentType();
350
            paymentType.setReferenceType(referenceType);
351
            manualPaymentRequestRepository.persist(paymentType);
352
        }
353
        paymentType.setCounter(paymentType.getCounter() + 1);
354
        return paymentType.getCounter();
24739 tejbeer 355
 
32494 amit.gupta 356
    }
357
}
24739 tejbeer 358