Subversion Repositories SmartDukaan

Rev

Rev 26912 | Rev 27395 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
22653 ashik.ali 1
package com.spice.profitmandi.service.scheme;
2
 
26403 amit.gupta 3
import java.text.MessageFormat;
22859 ashik.ali 4
import java.time.LocalDateTime;
23019 ashik.ali 5
import java.util.ArrayList;
26722 amit.gupta 6
import java.util.Arrays;
22653 ashik.ali 7
import java.util.HashMap;
22859 ashik.ali 8
import java.util.HashSet;
22653 ashik.ali 9
import java.util.List;
10
import java.util.Map;
11
import java.util.Set;
23968 amit.gupta 12
import java.util.stream.Collectors;
22653 ashik.ali 13
 
26332 amit.gupta 14
import javax.persistence.criteria.CriteriaBuilder;
15
import javax.persistence.criteria.CriteriaQuery;
16
import javax.persistence.criteria.Predicate;
17
import javax.persistence.criteria.Root;
18
 
23781 ashik.ali 19
import org.apache.logging.log4j.LogManager;
23568 govind 20
import org.apache.logging.log4j.Logger;
26332 amit.gupta 21
import org.hibernate.Session;
22
import org.hibernate.SessionFactory;
23
import org.hibernate.query.Query;
22653 ashik.ali 24
import org.springframework.beans.factory.annotation.Autowired;
23781 ashik.ali 25
import org.springframework.beans.factory.annotation.Qualifier;
26684 amit.gupta 26
import org.springframework.cache.annotation.Cacheable;
22653 ashik.ali 27
import org.springframework.stereotype.Component;
28
 
24307 amit.gupta 29
import com.spice.profitmandi.common.enumuration.ItemType;
22653 ashik.ali 30
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
31
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23019 ashik.ali 32
import com.spice.profitmandi.common.model.SchemeModel;
22859 ashik.ali 33
import com.spice.profitmandi.common.util.StringUtils;
23339 ashik.ali 34
import com.spice.profitmandi.dao.entity.catalog.Item;
22653 ashik.ali 35
import com.spice.profitmandi.dao.entity.catalog.RetailerScheme;
36
import com.spice.profitmandi.dao.entity.catalog.Scheme;
23365 ashik.ali 37
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
22653 ashik.ali 38
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
25503 amit.gupta 39
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
23339 ashik.ali 40
import com.spice.profitmandi.dao.entity.fofo.Purchase;
25043 amit.gupta 41
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
22859 ashik.ali 42
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
43
import com.spice.profitmandi.dao.entity.fofo.SchemeItem;
26498 amit.gupta 44
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
23527 ashik.ali 45
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
22653 ashik.ali 46
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25111 amit.gupta 47
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
27377 amit.gupta 48
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
25503 amit.gupta 49
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
22859 ashik.ali 50
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
22653 ashik.ali 51
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
23995 amit.gupta 52
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
23968 amit.gupta 53
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
23019 ashik.ali 54
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
55
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
23365 ashik.ali 56
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
22653 ashik.ali 57
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
25503 amit.gupta 58
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
23339 ashik.ali 59
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
25043 amit.gupta 60
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
22859 ashik.ali 61
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
62
import com.spice.profitmandi.dao.repository.fofo.SchemeItemRepository;
26498 amit.gupta 63
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
23798 amit.gupta 64
import com.spice.profitmandi.service.authentication.RoleManager;
26722 amit.gupta 65
import com.spice.profitmandi.service.inventory.PurchaseService;
22859 ashik.ali 66
import com.spice.profitmandi.service.wallet.WalletService;
22653 ashik.ali 67
 
22859 ashik.ali 68
import in.shop2020.model.v1.order.WalletReferenceType;
69
 
22653 ashik.ali 70
@Component
71
public class SchemeServiceImpl implements SchemeService {
72
 
23568 govind 73
	private static final Logger LOGGER = LogManager.getLogger(SchemeServiceImpl.class);
23444 amit.gupta 74
 
22653 ashik.ali 75
	@Autowired
23781 ashik.ali 76
	@Qualifier("fofoInventoryItemRepository")
22653 ashik.ali 77
	private InventoryItemRepository inventoryItemRepository;
23444 amit.gupta 78
 
22653 ashik.ali 79
	@Autowired
25503 amit.gupta 80
	private PartnerTypeChangeService partnerTypeChangeService;
81
 
82
	@Autowired
26722 amit.gupta 83
	private PurchaseService purchaseService;
84
 
85
	@Autowired
25043 amit.gupta 86
	private ScanRecordRepository scanRecordRepository;
23444 amit.gupta 87
 
22653 ashik.ali 88
	@Autowired
26332 amit.gupta 89
	private SessionFactory sessionFactory;
90
 
26722 amit.gupta 91
	private Set<Integer> tagIds = new HashSet<Integer>(Arrays.asList(4));
92
 
26332 amit.gupta 93
	@Autowired
22653 ashik.ali 94
	private SchemeRepository schemeRepository;
26684 amit.gupta 95
 
26498 amit.gupta 96
	@Autowired
97
	private PriceDropRepository priceDropRepository;
23444 amit.gupta 98
 
22653 ashik.ali 99
	@Autowired
23798 amit.gupta 100
	private RoleManager roleManager;
101
 
102
	@Autowired
22859 ashik.ali 103
	private RetailerRepository retailerRepository;
24562 amit.gupta 104
 
23995 amit.gupta 105
	@Autowired
106
	private TagListingRepository tagListingRepository;
23444 amit.gupta 107
 
22859 ashik.ali 108
	@Autowired
109
	private SchemeInOutRepository schemeInOutRepository;
23444 amit.gupta 110
 
22653 ashik.ali 111
	@Autowired
23781 ashik.ali 112
	@Qualifier("catalogItemRepository")
22859 ashik.ali 113
	private ItemRepository itemRepository;
23444 amit.gupta 114
 
22859 ashik.ali 115
	@Autowired
116
	private SchemeItemRepository schemeItemRepository;
23444 amit.gupta 117
 
22859 ashik.ali 118
	@Autowired
119
	private WalletService walletService;
23444 amit.gupta 120
 
23019 ashik.ali 121
	@Autowired
122
	private FofoOrderItemRepository fofoOrderItemRepository;
23444 amit.gupta 123
 
23019 ashik.ali 124
	@Autowired
125
	private FofoLineItemRepository fofoLineItemRepository;
23444 amit.gupta 126
 
23339 ashik.ali 127
	@Autowired
128
	private PurchaseRepository purchaseRepository;
23444 amit.gupta 129
 
23344 ashik.ali 130
	@Autowired
23365 ashik.ali 131
	private FofoOrderRepository fofoOrderRepository;
23796 amit.gupta 132
 
22653 ashik.ali 133
	@Override
22859 ashik.ali 134
	public void saveScheme(int creatorId, CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
23444 amit.gupta 135
 
23019 ashik.ali 136
		this.validateCreateSchemeRequest(createSchemeRequest);
23444 amit.gupta 137
 
22859 ashik.ali 138
		Scheme scheme = this.toScheme(creatorId, createSchemeRequest);
23444 amit.gupta 139
 
140
		if (scheme.getStartDateTime().isAfter(scheme.getEndDateTime())) {
141
			throw new ProfitMandiBusinessException(
142
					ProfitMandiConstants.START_DATE + ", " + ProfitMandiConstants.END_DATE,
143
					scheme.getStartDateTime() + ", " + scheme.getEndDateTime(), "SCHM_VE_1005");
22653 ashik.ali 144
		}
23444 amit.gupta 145
 
26332 amit.gupta 146
		// this.validateItemIds(createSchemeRequest);
22859 ashik.ali 147
		schemeRepository.persist(scheme);
23444 amit.gupta 148
		for (int itemId : createSchemeRequest.getItemIds()) {
22859 ashik.ali 149
			SchemeItem schemeItem = new SchemeItem();
150
			schemeItem.setSchemeId(scheme.getId());
151
			schemeItem.setItemId(itemId);
152
			schemeItemRepository.persist(schemeItem);
153
		}
23444 amit.gupta 154
 
22653 ashik.ali 155
	}
23444 amit.gupta 156
 
157
	private void validateCreateSchemeRequest(CreateSchemeRequest createSchemeRequest)
158
			throws ProfitMandiBusinessException {
159
		if (createSchemeRequest.getName() == null || createSchemeRequest.getName().isEmpty()) {
160
			throw new ProfitMandiBusinessException(ProfitMandiConstants.NAME, createSchemeRequest.getName(),
161
					"SCHM_VE_1000");
23019 ashik.ali 162
		}
23444 amit.gupta 163
		if (createSchemeRequest.getAmount() <= 0) {
164
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
165
					"SCHM_VE_1001");
23019 ashik.ali 166
		}
23444 amit.gupta 167
 
25503 amit.gupta 168
		if (createSchemeRequest.getAmountType().equals(AmountType.PERCENTAGE)
23444 amit.gupta 169
				&& createSchemeRequest.getAmount() > 100) {
170
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
171
					"SCHM_VE_1002");
23019 ashik.ali 172
		}
23444 amit.gupta 173
 
23886 amit.gupta 174
		if (createSchemeRequest.getStartDate() == null) {
23983 amit.gupta 175
			throw new ProfitMandiBusinessException(ProfitMandiConstants.START_DATE, createSchemeRequest.getStartDate(),
176
					"SCHM_VE_1003");
23019 ashik.ali 177
		}
23886 amit.gupta 178
		if (createSchemeRequest.getEndDate() == null) {
23983 amit.gupta 179
			throw new ProfitMandiBusinessException(ProfitMandiConstants.END_DATE, createSchemeRequest.getEndDate(),
180
					"SCHM_VE_1004");
23019 ashik.ali 181
		}
182
	}
23444 amit.gupta 183
 
184
	private Scheme toScheme(int creatorId, CreateSchemeRequest createSchemeRequest) {
22859 ashik.ali 185
		Scheme scheme = new Scheme();
186
		scheme.setName(createSchemeRequest.getName());
187
		scheme.setDescription(createSchemeRequest.getDescription());
25503 amit.gupta 188
		scheme.setType(createSchemeRequest.getType());
189
		scheme.setAmountType(createSchemeRequest.getAmountType());
22859 ashik.ali 190
		scheme.setAmount(createSchemeRequest.getAmount());
25503 amit.gupta 191
		scheme.setPartnerType(createSchemeRequest.getPartnerType());
25517 amit.gupta 192
		scheme.setStartDateTime(createSchemeRequest.getStartDate());
23886 amit.gupta 193
		scheme.setEndDateTime(createSchemeRequest.getEndDate());
22859 ashik.ali 194
		scheme.setCreatedBy(creatorId);
26686 amit.gupta 195
		scheme.setCashback(createSchemeRequest.isCashBack());
22859 ashik.ali 196
		return scheme;
197
	}
23444 amit.gupta 198
 
199
	private void validateItemIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
200
		if (createSchemeRequest.getItemIds() == null || createSchemeRequest.getItemIds().isEmpty()) {
201
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
202
					"SCHM_1003");
22859 ashik.ali 203
		}
23444 amit.gupta 204
		List<Integer> foundItemIds = itemRepository.selectIdsByIdsAndType(createSchemeRequest.getItemIds(),
205
				ItemType.SERIALIZED);
206
		if (foundItemIds.size() != createSchemeRequest.getItemIds().size()) {
22859 ashik.ali 207
			createSchemeRequest.getItemIds().removeAll(foundItemIds);
23444 amit.gupta 208
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
209
					"SCHM_1004");
22859 ashik.ali 210
		}
211
	}
23444 amit.gupta 212
 
22859 ashik.ali 213
	@Override
214
	public Scheme getSchemeById(int schemeId) throws ProfitMandiBusinessException {
215
		Scheme scheme = schemeRepository.selectById(schemeId);
216
		List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(scheme.getId());
23914 govind 217
		if (itemIds.size() > 0) {
218
			List<Item> items = itemRepository.selectByIds(new HashSet<>(itemIds));
219
			scheme.setItemStringMap(this.toItemStringMap(items));
23983 amit.gupta 220
		}
22859 ashik.ali 221
		return scheme;
222
	}
23444 amit.gupta 223
 
224
	public Map<Integer, String> toItemStringMap(List<Item> items) {
23339 ashik.ali 225
		Map<Integer, String> itemMap = new HashMap<>();
23444 amit.gupta 226
		for (Item item : items) {
23339 ashik.ali 227
			itemMap.put(item.getId(), this.getItemString(item));
228
		}
229
		return itemMap;
230
	}
23444 amit.gupta 231
 
232
	public String getItemString(Item item) {
23339 ashik.ali 233
		StringBuilder itemString = new StringBuilder();
23444 amit.gupta 234
		if (item.getBrand() != null && !item.getBrand().isEmpty()) {
23339 ashik.ali 235
			itemString.append(item.getBrand().trim());
236
		}
237
		itemString.append(" ");
23444 amit.gupta 238
		if (item.getModelName() != null && !item.getModelName().isEmpty()) {
23339 ashik.ali 239
			itemString.append(item.getModelName().trim());
240
		}
241
		itemString.append(" ");
23444 amit.gupta 242
		if (item.getModelNumber() != null && !item.getModelNumber().isEmpty()) {
23339 ashik.ali 243
			itemString.append(item.getModelNumber().trim());
244
		}
245
		itemString.append(" ");
23444 amit.gupta 246
		if (item.getColor() != null && !item.getColor().isEmpty()) {
23339 ashik.ali 247
			itemString.append(item.getColor().trim());
248
		}
249
		return itemString.toString();
250
	}
23444 amit.gupta 251
 
252
	private Set<Integer> schemeItemsToItemIds(List<SchemeItem> schemeItems) {
23339 ashik.ali 253
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 254
		for (SchemeItem schemeItem : schemeItems) {
23339 ashik.ali 255
			itemIds.add(schemeItem.getItemId());
256
		}
257
		return itemIds;
258
	}
23444 amit.gupta 259
 
23019 ashik.ali 260
	@Override
261
	public List<SchemeModel> getAllSchemeModels(LocalDateTime startDateTime, LocalDateTime endDateTime) {
262
		List<Scheme> schemes = schemeRepository.selectAllBetweenCreateTimestamp(startDateTime, endDateTime);
263
		Map<Integer, Scheme> schemeIdSchemeMap = this.toSchemeIdSchemeMap(schemes);
264
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
23339 ashik.ali 265
		Set<Integer> itemIds = this.schemeItemsToItemIds(schemeItems);
266
		List<Item> items = itemRepository.selectByIds(itemIds);
267
		Map<Integer, String> itemStringMap = this.toItemStringMap(items);
268
		this.addItemIdsToSchemes(schemeItems, schemeIdSchemeMap, itemStringMap);
23019 ashik.ali 269
		return this.toSchemeModels(schemeIdSchemeMap);
270
	}
23444 amit.gupta 271
 
272
	private void addItemIdsToSchemes(List<SchemeItem> schemeItems, Map<Integer, Scheme> schemeIdSchemeMap,
273
			Map<Integer, String> itemStringMap) {
274
		for (SchemeItem schemeItem : schemeItems) {
275
			schemeIdSchemeMap.get(schemeItem.getSchemeId()).getItemStringMap().put(schemeItem.getItemId(),
276
					itemStringMap.get(schemeItem.getItemId()));
23019 ashik.ali 277
		}
278
	}
23444 amit.gupta 279
 
280
	private void addRetailerIdsToSchemes(List<RetailerScheme> retailerSchemes, Map<Integer, Scheme> schemeIdSchemeMap) {
281
		for (RetailerScheme retailerScheme : retailerSchemes) {
282
			schemeIdSchemeMap.get(retailerScheme.getSchemeId()).getRetailerIds().add(retailerScheme.getRetailerId());
23019 ashik.ali 283
		}
284
	}
23444 amit.gupta 285
 
286
	private List<SchemeModel> toSchemeModels(Map<Integer, Scheme> schemeIdSchemeMap) {
23019 ashik.ali 287
		List<SchemeModel> schemeModels = new ArrayList<>();
23444 amit.gupta 288
		for (Map.Entry<Integer, Scheme> schemeIdSchemeEntry : schemeIdSchemeMap.entrySet()) {
23019 ashik.ali 289
			schemeModels.add(this.toSchemeModel(schemeIdSchemeEntry.getValue()));
290
		}
291
		return schemeModels;
292
	}
23444 amit.gupta 293
 
294
	private SchemeModel toSchemeModel(Scheme scheme) {
23019 ashik.ali 295
		SchemeModel schemeModel = new SchemeModel();
296
		schemeModel.setSchemeId(scheme.getId());
297
		schemeModel.setName(scheme.getName());
298
		schemeModel.setDescription(scheme.getDescription());
299
		schemeModel.setSchemeType(scheme.getType().toString());
300
		schemeModel.setAmountType(scheme.getAmountType().toString());
301
		schemeModel.setAmount(scheme.getAmount());
302
		schemeModel.setStartDateTime(StringUtils.toString(scheme.getStartDateTime()));
303
		schemeModel.setEndDateTime(StringUtils.toString(scheme.getEndDateTime()));
304
		schemeModel.setCreateTimestamp(StringUtils.toString(scheme.getCreateTimestamp()));
305
		schemeModel.setActiveTimestamp(StringUtils.toString(scheme.getActiveTimestamp()));
306
		schemeModel.setExpireTimestamp(StringUtils.toString(scheme.getExpireTimestamp()));
307
		schemeModel.setCreatedBy(scheme.getCreatedBy());
23339 ashik.ali 308
		schemeModel.setItemStringMap(scheme.getItemStringMap());
23019 ashik.ali 309
		schemeModel.setRetailerIds(scheme.getRetailerIds());
310
		return schemeModel;
311
	}
22653 ashik.ali 312
 
313
	@Override
314
	public void activeSchemeById(int schemeId) throws ProfitMandiBusinessException {
315
		Scheme scheme = schemeRepository.selectById(schemeId);
23444 amit.gupta 316
		if (scheme.getActiveTimestamp() != null) {
317
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
318
					"SCHM_1005");
22653 ashik.ali 319
		}
23444 amit.gupta 320
		if (scheme.getExpireTimestamp() != null) {
321
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
322
					"SCHM_1006");
22653 ashik.ali 323
		}
22859 ashik.ali 324
		scheme.setActiveTimestamp(LocalDateTime.now());
325
		schemeRepository.persist(scheme);
25438 amit.gupta 326
		/*
327
		 * if (scheme.getType() == SchemeType.IN) {
328
		 * this.processPreviousPurchases(scheme); } else if (scheme.getType() ==
329
		 * SchemeType.OUT) { this.processPreviousSales(scheme); }
330
		 */
22653 ashik.ali 331
	}
23444 amit.gupta 332
 
22653 ashik.ali 333
	@Override
25069 amit.gupta 334
	public void expireSchemeById(int schemeId, LocalDateTime expiryTime) throws ProfitMandiBusinessException {
22653 ashik.ali 335
		Scheme scheme = schemeRepository.selectById(schemeId);
25111 amit.gupta 336
		if (scheme == null || scheme.getActiveTimestamp() == null) {
23444 amit.gupta 337
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
338
					"SCHM_1007");
22653 ashik.ali 339
		}
23444 amit.gupta 340
		if (scheme.getExpireTimestamp() != null) {
341
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
342
					"SCHM_1008");
22653 ashik.ali 343
		}
22859 ashik.ali 344
		scheme.setExpireTimestamp(LocalDateTime.now());
25069 amit.gupta 345
		scheme.setEndDateTime(expiryTime);
22859 ashik.ali 346
		schemeRepository.persist(scheme);
22653 ashik.ali 347
	}
23444 amit.gupta 348
 
349
	private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
23019 ashik.ali 350
		Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
23444 amit.gupta 351
		for (Scheme scheme : schemes) {
23019 ashik.ali 352
			schemeIdSchemeMap.put(scheme.getId(), scheme);
22859 ashik.ali 353
		}
23019 ashik.ali 354
		return schemeIdSchemeMap;
22859 ashik.ali 355
	}
23444 amit.gupta 356
 
357
	private Set<Integer> inventoryItemsToItemIds(List<InventoryItem> inventoryItems) {
22859 ashik.ali 358
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 359
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 360
			itemIds.add(inventoryItem.getItemId());
361
		}
362
		return itemIds;
363
	}
23444 amit.gupta 364
 
365
	private Map<Integer, Set<Scheme>> toItemIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
23019 ashik.ali 366
		Map<Integer, Scheme> schemeIdSchemesMap = this.toSchemeIdSchemeMap(schemes);
22859 ashik.ali 367
		Map<Integer, Set<Scheme>> itemIdSchemesMap = new HashMap<>();
23444 amit.gupta 368
		for (SchemeItem schemeItem : schemeItems) {
369
			if (!itemIdSchemesMap.containsKey(schemeItem.getItemId())) {
22859 ashik.ali 370
				Set<Scheme> schemesSet = new HashSet<>();
371
				schemesSet.add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
372
				itemIdSchemesMap.put(schemeItem.getItemId(), schemesSet);
23444 amit.gupta 373
			} else {
22859 ashik.ali 374
				itemIdSchemesMap.get(schemeItem.getItemId()).add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
375
			}
376
		}
377
		return itemIdSchemesMap;
378
	}
22653 ashik.ali 379
 
23444 amit.gupta 380
	private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
381
			List<InventoryItem> inventoryItems) {
22859 ashik.ali 382
		Set<Integer> schemeIds = new HashSet<>();
23444 amit.gupta 383
		for (Scheme scheme : schemes) {
22859 ashik.ali 384
			schemeIds.add(scheme.getId());
385
		}
386
		Set<Integer> itemIds = this.inventoryItemsToItemIds(inventoryItems);
387
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndItemIds(schemeIds, itemIds);
23444 amit.gupta 388
 
22859 ashik.ali 389
		Map<Integer, Set<Scheme>> itemIdSchemesMap = this.toItemIdSchemesMap(schemeItems, schemes);
390
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemsMap = new HashMap<>();
23444 amit.gupta 391
		for (InventoryItem inventoryItem : inventoryItems) {
392
			if (itemIdSchemesMap.containsKey(inventoryItem.getItemId())) {
22859 ashik.ali 393
				inventoryItemSchemsMap.put(inventoryItem, itemIdSchemesMap.get(inventoryItem.getItemId()));
394
			}
395
		}
396
		return inventoryItemSchemsMap;
397
	}
23444 amit.gupta 398
 
22859 ashik.ali 399
	@Override
23365 ashik.ali 400
	public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
23369 ashik.ali 401
		LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
23344 ashik.ali 402
		Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
25503 amit.gupta 403
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
404
				purchase.getCreateTimestamp().toLocalDate());
23369 ashik.ali 405
		LOGGER.info("purchase is completed = {}", (purchase.getCompleteTimestamp() != null));
23444 amit.gupta 406
		if (purchase.getCompleteTimestamp() != null) {
25507 amit.gupta 407
			List<Scheme> schemes = schemeRepository.selectActiveAll(SchemeType.IN, partnerType,
26684 amit.gupta 408
					purchase.getCompleteTimestamp(), false);
23365 ashik.ali 409
			float totalCashback = 0;
23444 amit.gupta 410
			if (schemes.isEmpty()) {
23365 ashik.ali 411
				return;
412
			}
413
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
26332 amit.gupta 414
 
26722 amit.gupta 415
			Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
416
			LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
417
			Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
26802 tejbeer 418
					.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
26722 amit.gupta 419
					.collect(Collectors.toSet());
26332 amit.gupta 420
			// Only consider inventory items that were not returned
26722 amit.gupta 421
			inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
422
					.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
423
					.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
25487 amit.gupta 424
			LOGGER.info(inventoryItems);
25438 amit.gupta 425
			if (inventoryItems.size() == 0)
426
				return;
23444 amit.gupta 427
			Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
428
					inventoryItems);
429
 
430
			if (inventoryItemSchemesMap.isEmpty()) {
23365 ashik.ali 431
				return;
432
			}
433
			Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 434
 
435
			for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
23365 ashik.ali 436
				Set<Scheme> allSchemes = new HashSet<>();
23444 amit.gupta 437
				for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
25503 amit.gupta 438
					allSchemes.add(scheme);
22859 ashik.ali 439
				}
23365 ashik.ali 440
				allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
22859 ashik.ali 441
			}
23444 amit.gupta 442
 
26722 amit.gupta 443
			//
444
 
23444 amit.gupta 445
			int itemsCount = 0;
446
			for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
447
					.entrySet()) {
448
				float inventoryItemCashback = 0;
449
				for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
23365 ashik.ali 450
					InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
451
					float cashback = this.createSchemeInOut(scheme, inventoryItem);
23444 amit.gupta 452
					inventoryItemCashback += cashback;
23339 ashik.ali 453
				}
23444 amit.gupta 454
				if (inventoryItemCashback > 0) {
455
					totalCashback += inventoryItemCashback;
456
					itemsCount++;
457
				}
22859 ashik.ali 458
			}
23444 amit.gupta 459
 
23511 amit.gupta 460
			LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
23796 amit.gupta 461
			if (itemsCount > 0) {
26684 amit.gupta 462
				walletService.addAmountToWallet(
463
						retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
464
								+ purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
26498 amit.gupta 465
						totalCashback, purchase.getCreateTimestamp());
23796 amit.gupta 466
				LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
467
						purchase.getPurchaseReference(), itemsCount);
23508 amit.gupta 468
				purchase.setCashback(purchase.getCashback() + totalCashback);
469
				purchaseRepository.persist(purchase);
470
			}
22653 ashik.ali 471
		}
472
	}
23444 amit.gupta 473
 
474
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
24562 amit.gupta 475
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
27377 amit.gupta 476
		float amountToCredit = 0;
24581 amit.gupta 477
		if (schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList())
24562 amit.gupta 478
				.size() == 0) {
479
			SchemeInOut schemeInOut = new SchemeInOut();
27377 amit.gupta 480
			amountToCredit = this.getAmount(inventoryItem, scheme);
23443 amit.gupta 481
			schemeInOut.setSchemeId(scheme.getId());
482
			schemeInOut.setInventoryItemId(inventoryItem.getId());
27377 amit.gupta 483
			schemeInOut.setAmount(amountToCredit);
484
			if(scheme.getType().equals(SchemeType.ACTIVATION)) {
485
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
486
				schemeInOut.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
487
				return 0;
488
			} else {
489
				schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
490
				schemeInOut.setStatusDescription("Credited for sale of IMEI#" + inventoryItem.getSerialNumber());
491
				schemeInOut.setCreditTimestamp(LocalDateTime.now());
492
			}
23443 amit.gupta 493
			schemeInOutRepository.persist(schemeInOut);
494
		}
27377 amit.gupta 495
		return amountToCredit;
22859 ashik.ali 496
	}
23444 amit.gupta 497
 
25049 amit.gupta 498
	// We are maintaining price drop after grn
23444 amit.gupta 499
	private float getAmount(InventoryItem inventoryItem, Scheme scheme) {
22653 ashik.ali 500
		float amount = 0;
25049 amit.gupta 501
		float dpForCalc = 0;
502
		float taxableSellingPrice = 0;
26684 amit.gupta 503
		// float totalTaxRate = inventoryItem.getIgstRate() +
504
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
505
		// Hardcoding it to 18%
26568 amit.gupta 506
		float totalTaxRate = 18f;
26684 amit.gupta 507
		// float totalTaxRate = inventoryItem.getIgstRate() +
508
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
23527 ashik.ali 509
		if (scheme.getAmountType() == AmountType.PERCENTAGE) {
24562 amit.gupta 510
			if (scheme.getType().equals(SchemeType.IN)) {
25049 amit.gupta 511
				dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
23995 amit.gupta 512
			} else {
513
				try {
26684 amit.gupta 514
					dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
26550 amit.gupta 515
							tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
24562 amit.gupta 516
				} catch (Exception e) {
23995 amit.gupta 517
					LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
518
					e.printStackTrace();
519
				}
520
			}
25049 amit.gupta 521
			taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
22859 ashik.ali 522
			amount = taxableSellingPrice * scheme.getAmount() / 100;
25517 amit.gupta 523
			System.out.println(String.format("%d\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%f\t%f\t%f\t%f", inventoryItem.getId(),
25050 amit.gupta 524
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 525
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
526
					scheme.getAmount(), amount));
23444 amit.gupta 527
		} else {
22653 ashik.ali 528
			amount = scheme.getAmount();
25517 amit.gupta 529
			System.out.println(String.format("%d\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%f\t%f\t%d\t%f", inventoryItem.getId(),
25050 amit.gupta 530
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 531
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
532
					0, amount));
22653 ashik.ali 533
		}
25049 amit.gupta 534
 
22859 ashik.ali 535
		return amount;
22653 ashik.ali 536
	}
23444 amit.gupta 537
 
22653 ashik.ali 538
	@Override
23365 ashik.ali 539
	public void processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
540
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
23444 amit.gupta 541
 
25507 amit.gupta 542
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
543
				fofoOrder.getCreateTimestamp().toLocalDate());
544
 
25043 amit.gupta 545
		List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
546
		Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
547
				.collect(Collectors.toSet());
548
		Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
549
				.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
550
				.collect(Collectors.toSet());
26726 amit.gupta 551
		if (inventoryItems.size() == 0) {
552
			return;
553
		}
26722 amit.gupta 554
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
23444 amit.gupta 555
 
26722 amit.gupta 556
		Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
26802 tejbeer 557
				.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(fofoOrder.getCreateTimestamp()))
558
				.map(x -> x.getItemId()).collect(Collectors.toSet());
26722 amit.gupta 559
		// Only consider inventory items that were not returned
560
		inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
561
				.collect(Collectors.toSet());
562
 
25043 amit.gupta 563
		if (inventoryItems.size() == 0) {
23365 ashik.ali 564
			return;
22859 ashik.ali 565
		}
23444 amit.gupta 566
 
25043 amit.gupta 567
		float totalCashback = 0;
568
		int count = 0;
23444 amit.gupta 569
 
27377 amit.gupta 570
		List<Scheme> allActiveSchemes = schemeRepository
571
				.selectActiveAll(SchemeType.OUT, partnerType, fofoOrder.getCreateTimestamp(), false);
572
		allActiveSchemes.addAll(schemeRepository.selectActiveAll(SchemeType.ACTIVATION, partnerType, fofoOrder.getCreateTimestamp(), false));
573
 
25043 amit.gupta 574
		for (InventoryItem inventoryItem : inventoryItems) {
25710 amit.gupta 575
			float itemCashback = 0;
25043 amit.gupta 576
			Purchase purchase = purchaseRepository.selectByIdAndFofoId(inventoryItem.getPurchaseId(), retailerId);
577
			Set<Integer> schemeIds = new HashSet<>(
578
					schemeItemRepository.selectSchemeIdByItemId(inventoryItem.getItemId()));
26332 amit.gupta 579
			if (purchase.getCompleteTimestamp() == null) {
25579 amit.gupta 580
				continue;
581
			}
27377 amit.gupta 582
			allActiveSchemes = allActiveSchemes.stream().filter(x -> schemeIds.contains(x.getId())).collect(Collectors.toList());
583
			for (Scheme scheme : allActiveSchemes) {
25043 amit.gupta 584
				itemCashback += this.createSchemeInOut(scheme, inventoryItem);
22653 ashik.ali 585
			}
25043 amit.gupta 586
			if (itemCashback > 0) {
587
				count++;
588
				totalCashback += itemCashback;
22859 ashik.ali 589
			}
22653 ashik.ali 590
		}
25043 amit.gupta 591
		if (count > 0) {
23444 amit.gupta 592
			walletService.addAmountToWallet(retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT,
23796 amit.gupta 593
					"Sales margin for invoice number " + fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
26498 amit.gupta 594
					totalCashback, fofoOrder.getCreateTimestamp());
23365 ashik.ali 595
			fofoOrder.setCashback(totalCashback);
596
			fofoOrderRepository.persist(fofoOrder);
22859 ashik.ali 597
		}
22653 ashik.ali 598
	}
23444 amit.gupta 599
 
23508 amit.gupta 600
	@Override
23796 amit.gupta 601
	public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
602
			throws Exception {
23638 amit.gupta 603
		Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
23508 amit.gupta 604
		float amountToRollback = 0;
605
		List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
23796 amit.gupta 606
		for (SchemeInOut schemeInOut : schemes) {
23983 amit.gupta 607
			if (schemeInOut.getRolledBackTimestamp() == null) {
608
				schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
27377 amit.gupta 609
				if(schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
610
					amountToRollback += schemeInOut.getAmount();
611
				}
612
				schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
613
				schemeInOut.setStatusDescription(rollbackReason);
23983 amit.gupta 614
			}
23508 amit.gupta 615
		}
23983 amit.gupta 616
		if (amountToRollback > 0) {
23638 amit.gupta 617
			int inventoryItemId = inventoryItemIds.get(0);
26498 amit.gupta 618
			InventoryItem ii = inventoryItemRepository.selectById(inventoryItemId);
619
			Integer fofoId = ii.getFofoId();
27377 amit.gupta 620
			//Purchase p = purchaseRepository.selectById(ii.getPurchaseId());
26684 amit.gupta 621
			// TODO//
26693 amit.gupta 622
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, ii.getPurchaseId(),
26498 amit.gupta 623
					WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
23638 amit.gupta 624
		}
23508 amit.gupta 625
	}
23884 amit.gupta 626
 
23781 ashik.ali 627
	@Override
23796 amit.gupta 628
	public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
629
			throws ProfitMandiBusinessException {
23781 ashik.ali 630
		Map<String, Object> map = new HashMap<>();
631
		List<Scheme> schemes = null;
632
		long size = 0;
23798 amit.gupta 633
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 634
			schemes = schemeRepository.selectAll(offset, limit);
635
			size = schemeRepository.selectAllCount();
23796 amit.gupta 636
		} else {
23781 ashik.ali 637
			schemes = schemeRepository.selectActiveAll(offset, limit);
638
			size = schemeRepository.selectAllActiveCount();
639
		}
640
		map.put("schemes", schemes);
641
		map.put("start", offset + 1);
642
		map.put("size", size);
23796 amit.gupta 643
		if (schemes.size() < limit) {
23781 ashik.ali 644
			map.put("end", offset + schemes.size());
23796 amit.gupta 645
		} else {
23781 ashik.ali 646
			map.put("end", offset + limit);
647
		}
648
		return map;
649
	}
23796 amit.gupta 650
 
23781 ashik.ali 651
	@Override
23796 amit.gupta 652
	public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
653
			throws ProfitMandiBusinessException {
23781 ashik.ali 654
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
655
		List<Scheme> schemes = null;
23798 amit.gupta 656
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 657
			schemes = schemeRepository.selectAll(offset, limit);
23796 amit.gupta 658
		} else {
23781 ashik.ali 659
			schemes = schemeRepository.selectActiveAll(offset, limit);
660
		}
661
		return schemes;
662
	}
23508 amit.gupta 663
 
23968 amit.gupta 664
	@Override
24976 amit.gupta 665
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
26332 amit.gupta 666
			throws ProfitMandiBusinessException {
26498 amit.gupta 667
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
24976 amit.gupta 668
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
669
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
670
 
671
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
672
			float amountToCredit = 0;
673
			float amountToDebit = 0;
674
			int purchaseId = purchaseEntry.getKey();
675
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
676
 
677
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
678
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
679
 
680
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
681
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
682
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
683
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
684
			for (SchemeInOut schemeInOut : schemeInOuts) {
685
				InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
686
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
687
				if (scheme.getType().equals(SchemeType.OUT))
688
					continue;
689
				if (scheme.getAmountType().equals(AmountType.FIXED)) {
690
					continue;
23995 amit.gupta 691
				}
24976 amit.gupta 692
				if (schemeInOut.getRolledBackTimestamp() == null) {
693
					float newAmount = getAmount(ii, scheme);
694
					if (schemeInOut.getAmount() - newAmount >= 0.01f) {
695
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
696
						schemeInOutRepository.persist(schemeInOut);
697
						SchemeInOut sioNew = new SchemeInOut();
698
						sioNew.setAmount(newAmount);
699
						sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
700
						sioNew.setSchemeId(schemeInOut.getSchemeId());
701
						schemeInOutRepository.persist(sioNew);
702
						amountToCredit += sioNew.getAmount();
703
						amountToDebit += schemeInOut.getAmount();
704
					}
24562 amit.gupta 705
 
24976 amit.gupta 706
				}
23986 amit.gupta 707
			}
24976 amit.gupta 708
			int fofoId = inventoryItems.get(0).getFofoId();
709
			if (amountToDebit > 0) {
26684 amit.gupta 710
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
711
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
712
						priceDrop.getAffectedOn());
24976 amit.gupta 713
			}
714
			if (amountToCredit > 0) {
26403 amit.gupta 715
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
26684 amit.gupta 716
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), amountToCredit,
717
						priceDrop.getAffectedOn());
24976 amit.gupta 718
			}
23968 amit.gupta 719
		}
720
	}
24562 amit.gupta 721
 
24264 amit.gupta 722
	@Override
24562 amit.gupta 723
	public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
724
			SchemeType schemeType) throws ProfitMandiBusinessException {
24264 amit.gupta 725
		Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
726
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
727
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
728
		List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
27377 amit.gupta 729
		float amountToRollback = 0;
24264 amit.gupta 730
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size()).stream()
731
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
732
		for (SchemeInOut schemeInOut : schemeInOuts) {
733
			Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
24562 amit.gupta 734
			if (scheme.getType().equals(schemeType)) {
735
				if (schemeInOut.getRolledBackTimestamp() == null) {
24264 amit.gupta 736
					schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
27377 amit.gupta 737
					if(schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
738
						amountToRollback += schemeInOut.getAmount();
739
					}
740
					schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
741
					schemeInOut.setStatusDescription(reversalReason);
24264 amit.gupta 742
				}
743
			}
744
		}
745
		int fofoId = inventoryItems.get(0).getFofoId();
24562 amit.gupta 746
		WalletReferenceType walletReferenceType = schemeType.equals(SchemeType.OUT) ? WalletReferenceType.SCHEME_OUT
27377 amit.gupta 747
				: schemeType.equals(SchemeType.IN) ? WalletReferenceType.SCHEME_IN : WalletReferenceType.ACTIVATION_SCHEME;
748
		if (amountToRollback > 0) {
26684 amit.gupta 749
			// TODO//
27377 amit.gupta 750
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, reversalReference, walletReferenceType,
26498 amit.gupta 751
					reversalReason, LocalDateTime.now());
24268 amit.gupta 752
		}
24264 amit.gupta 753
	}
23968 amit.gupta 754
 
26332 amit.gupta 755
	@Override
756
	public double getTotalMargin(int itemId, PartnerType partnerType, LocalDateTime dateTime) {
757
		Session session = sessionFactory.getCurrentSession();
758
		CriteriaBuilder cb = session.getCriteriaBuilder();
759
		CriteriaQuery<Double> criteriaQuery = cb.createQuery(Double.class);
760
		Root<SchemeItem> schemeItem = criteriaQuery.from(SchemeItem.class);
761
		Root<Scheme> scheme = criteriaQuery.from(Scheme.class);
762
		Predicate schemePredicate = cb.equal(scheme.get(ProfitMandiConstants.AMOUNT_TYPE), AmountType.PERCENTAGE);
763
		Predicate lessThanPredicate = cb.lessThanOrEqualTo(scheme.get(ProfitMandiConstants.END_DATE_TIME), dateTime);
764
		Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(scheme.get(ProfitMandiConstants.START_DATE_TIME),
765
				dateTime);
766
		Predicate joinPredicate = cb.equal(scheme.get("id"), schemeItem.get("schemeId"));
767
		Predicate schemeItemPredicate = cb.equal(schemeItem.get(ProfitMandiConstants.ITEM_ID), itemId);
768
		criteriaQuery.select(cb.sum(scheme.get(ProfitMandiConstants.AMOUNT))).where(schemePredicate, lessThanPredicate,
769
				greaterThanPredicate, schemeItemPredicate, joinPredicate);
770
 
771
		Query<Double> query = session.createQuery(criteriaQuery);
772
		return query.getSingleResult() + ProfitMandiConstants.SCHEME_INVESTMENT_MARGIN;
773
 
774
	}
775
 
26684 amit.gupta 776
	@Override
777
	@Cacheable(value = "itemSchemeCashback", cacheManager = "timeoutCacheManager")
778
	public Map<Integer, Float> getItemSchemeCashBack() {
779
		Map<Integer, Float> itemCashbackMap = new HashMap<>();
780
		Map<Integer, Scheme> cashbackSchemesMap = schemeRepository
781
				.selectActiveAll(SchemeType.OUT, PartnerType.ALL, LocalDateTime.now(), true).stream()
782
				.filter(x -> x.getAmountType().equals(AmountType.FIXED))
783
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
26722 amit.gupta 784
		if (cashbackSchemesMap.size() > 0) {
26713 amit.gupta 785
			List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(cashbackSchemesMap.keySet());
786
			schemeItems.stream().forEach(x -> {
787
				itemCashbackMap.put(x.getItemId(), cashbackSchemesMap.get(x.getSchemeId()).getAmount());
788
			});
789
		}
26722 amit.gupta 790
		// A107FD Model needs to removed
26703 amit.gupta 791
		itemCashbackMap.remove(30211);
792
		itemCashbackMap.remove(30212);
793
		itemCashbackMap.remove(30213);
794
		itemCashbackMap.remove(30756);
26684 amit.gupta 795
		return itemCashbackMap;
796
	}
797
 
24976 amit.gupta 798
	/*
799
	 * @Override public void updateSchmesForModel(int catalogId) throws
800
	 * ProfitMandiBusinessException { List<Item> items =
801
	 * itemRepository.selectAllByCatalogItemId(catalogId); Map<Integer, Scheme>
802
	 * schemes = schemeRepository .selectAllByItemIds(items.stream().map(x ->
803
	 * x.getId()).collect(Collectors.toList()));
804
	 * 
805
	 * }
806
	 */
24562 amit.gupta 807
 
26802 tejbeer 808
	@Override
809
	public List<Scheme> selectSchemeByPartnerType(PartnerType partnerType, int itemId, boolean isAdmin, int offset,
810
			int limit) {
811
		Session session = sessionFactory.getCurrentSession();
812
		CriteriaBuilder cb = session.getCriteriaBuilder();
813
		CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
814
		Root<Scheme> scheme = query.from(Scheme.class);
815
		List<PartnerType> pt = new ArrayList<>();
816
		pt.add(PartnerType.ALL);
817
		pt.add(partnerType);
818
		Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
819
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
820
		cb.desc(cb.isNull(scheme.get("expireTimestamp")));
821
 
822
		Predicate p3 = null;
823
		Predicate finalPredicate = null;
824
		if (itemId != 0) {
825
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
826
			p3 = cb.in(scheme.get("id")).value(schemeIds);
827
			if (!isAdmin) {
828
 
829
				finalPredicate = cb.and(p1, p2, p3);
830
				query.where(finalPredicate);
831
			} else {
832
				finalPredicate = cb.and(p1, p3);
833
				query.where(finalPredicate);
834
			}
835
		} else {
836
 
837
			if (!isAdmin) {
838
 
839
				finalPredicate = cb.and(p1, p2);
26912 tejbeer 840
				query.where(finalPredicate);
26802 tejbeer 841
			} else {
842
				query.where(p1);
843
			}
844
		}
845
		query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
846
 
847
		return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
848
 
849
	}
850
 
851
	@Override
852
	public long selectSchemeCount(PartnerType partnerType, int itemId, boolean isAdmin) {
853
		Session session = sessionFactory.getCurrentSession();
854
		CriteriaBuilder cb = session.getCriteriaBuilder();
855
		CriteriaQuery<Long> query = cb.createQuery(Long.class);
856
		Root<Scheme> scheme = query.from(Scheme.class);
857
		List<PartnerType> pt = new ArrayList<>();
858
		pt.add(PartnerType.ALL);
859
		pt.add(partnerType);
860
		Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
861
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
862
		Predicate finalPredicate = null;
863
		if (itemId != 0) {
864
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
865
			Predicate p3 = cb.in(scheme.get("id")).value(schemeIds);
866
			if (!isAdmin) {
867
 
868
				finalPredicate = cb.and(p1, p2, p3);
869
				query.select(cb.count(scheme)).where(finalPredicate);
870
			} else {
871
				finalPredicate = cb.and(p1, p3);
872
				query.select(cb.count(scheme)).where(finalPredicate);
873
			}
874
		} else {
875
			if (!isAdmin) {
876
				finalPredicate = cb.and(p1, p2);
877
				query.select(cb.count(scheme)).where(finalPredicate);
878
 
879
			} else {
880
				query.select(cb.count(scheme)).where(p1);
881
 
882
			}
883
		}
884
 
885
		return session.createQuery(query).getSingleResult();
886
 
887
	}
888
 
22653 ashik.ali 889
}