Subversion Repositories SmartDukaan

Rev

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