Subversion Repositories SmartDukaan

Rev

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