Subversion Repositories SmartDukaan

Rev

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