Subversion Repositories SmartDukaan

Rev

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