Subversion Repositories SmartDukaan

Rev

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