Subversion Repositories SmartDukaan

Rev

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