Subversion Repositories SmartDukaan

Rev

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