Subversion Repositories SmartDukaan

Rev

Rev 31921 | Rev 32871 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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