Subversion Repositories SmartDukaan

Rev

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