Subversion Repositories SmartDukaan

Rev

Rev 26725 | Rev 26802 | 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()
26725 amit.gupta 418
					.filter(x -> x.getEolDate()==null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
26722 amit.gupta 419
					.collect(Collectors.toSet());
26332 amit.gupta 420
			// Only consider inventory items that were not returned
26722 amit.gupta 421
			inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
422
					.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
423
					.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
25487 amit.gupta 424
			LOGGER.info(inventoryItems);
25438 amit.gupta 425
			if (inventoryItems.size() == 0)
426
				return;
23444 amit.gupta 427
			Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
428
					inventoryItems);
429
 
430
			if (inventoryItemSchemesMap.isEmpty()) {
23365 ashik.ali 431
				return;
432
			}
433
			Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 434
 
435
			for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
23365 ashik.ali 436
				Set<Scheme> allSchemes = new HashSet<>();
23444 amit.gupta 437
				for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
25503 amit.gupta 438
					allSchemes.add(scheme);
22859 ashik.ali 439
				}
23365 ashik.ali 440
				allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
22859 ashik.ali 441
			}
23444 amit.gupta 442
 
26722 amit.gupta 443
			//
444
 
23444 amit.gupta 445
			int itemsCount = 0;
446
			for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
447
					.entrySet()) {
448
				float inventoryItemCashback = 0;
449
				for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
23365 ashik.ali 450
					InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
451
					float cashback = this.createSchemeInOut(scheme, inventoryItem);
23444 amit.gupta 452
					inventoryItemCashback += cashback;
23339 ashik.ali 453
				}
23444 amit.gupta 454
				if (inventoryItemCashback > 0) {
455
					totalCashback += inventoryItemCashback;
456
					itemsCount++;
457
				}
22859 ashik.ali 458
			}
23444 amit.gupta 459
 
23511 amit.gupta 460
			LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
23796 amit.gupta 461
			if (itemsCount > 0) {
26684 amit.gupta 462
				walletService.addAmountToWallet(
463
						retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
464
								+ purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
26498 amit.gupta 465
						totalCashback, purchase.getCreateTimestamp());
23796 amit.gupta 466
				LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
467
						purchase.getPurchaseReference(), itemsCount);
23508 amit.gupta 468
				purchase.setCashback(purchase.getCashback() + totalCashback);
469
				purchaseRepository.persist(purchase);
470
			}
22653 ashik.ali 471
		}
472
	}
23444 amit.gupta 473
 
474
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
24562 amit.gupta 475
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
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());
26726 amit.gupta 542
		if (inventoryItems.size() == 0) {
543
			return;
544
		}
26722 amit.gupta 545
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
23444 amit.gupta 546
 
26722 amit.gupta 547
		Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
26725 amit.gupta 548
				.filter(x -> x.getEolDate()==null || x.getEolDate().isAfter(fofoOrder.getCreateTimestamp())).map(x -> x.getItemId())
26722 amit.gupta 549
				.collect(Collectors.toSet());
550
		// Only consider inventory items that were not returned
551
		inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
552
				.collect(Collectors.toSet());
553
 
25043 amit.gupta 554
		if (inventoryItems.size() == 0) {
23365 ashik.ali 555
			return;
22859 ashik.ali 556
		}
23444 amit.gupta 557
 
25043 amit.gupta 558
		float totalCashback = 0;
559
		int count = 0;
23444 amit.gupta 560
 
25507 amit.gupta 561
		Set<Scheme> allFixedSchemes = schemeRepository
26684 amit.gupta 562
				.selectActiveAll(SchemeType.OUT, partnerType, fofoOrder.getCreateTimestamp(), false).stream()
25507 amit.gupta 563
				.filter(scheme -> scheme.getAmountType().equals(AmountType.FIXED)).collect(Collectors.toSet());
25050 amit.gupta 564
 
25043 amit.gupta 565
		for (InventoryItem inventoryItem : inventoryItems) {
25710 amit.gupta 566
			float itemCashback = 0;
25043 amit.gupta 567
			Purchase purchase = purchaseRepository.selectByIdAndFofoId(inventoryItem.getPurchaseId(), retailerId);
568
			Set<Integer> schemeIds = new HashSet<>(
569
					schemeItemRepository.selectSchemeIdByItemId(inventoryItem.getItemId()));
25507 amit.gupta 570
			List<Scheme> schemes = null;
26332 amit.gupta 571
			if (purchase.getCompleteTimestamp() == null) {
25579 amit.gupta 572
				continue;
573
			}
25507 amit.gupta 574
			if (purchase.getCompleteTimestamp().isAfter(LocalDate.of(2019, 9, 1).atStartOfDay())) {
26684 amit.gupta 575
				schemes = schemeRepository.selectActiveAll(SchemeType.OUT, partnerType, fofoOrder.getCreateTimestamp(),
576
						false);
25507 amit.gupta 577
			} else {
26684 amit.gupta 578
				schemes = schemeRepository.selectActiveAll(SchemeType.OUT, partnerType, purchase.getCompleteTimestamp(),
579
						false);
25507 amit.gupta 580
			}
581
			Set<Scheme> schemesSet = schemes.stream().filter(x -> x.getAmountType().equals(AmountType.PERCENTAGE))
582
					.collect(Collectors.toSet());
583
			schemesSet.addAll(allFixedSchemes);
584
			schemesSet = schemesSet.stream().filter(x -> schemeIds.contains(x.getId())).collect(Collectors.toSet());
585
			for (Scheme scheme : schemesSet) {
25043 amit.gupta 586
				itemCashback += this.createSchemeInOut(scheme, inventoryItem);
22653 ashik.ali 587
			}
25043 amit.gupta 588
			if (itemCashback > 0) {
589
				count++;
590
				totalCashback += itemCashback;
22859 ashik.ali 591
			}
22653 ashik.ali 592
		}
25043 amit.gupta 593
		if (count > 0) {
23444 amit.gupta 594
			walletService.addAmountToWallet(retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT,
23796 amit.gupta 595
					"Sales margin for invoice number " + fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
26498 amit.gupta 596
					totalCashback, fofoOrder.getCreateTimestamp());
23365 ashik.ali 597
			fofoOrder.setCashback(totalCashback);
598
			fofoOrderRepository.persist(fofoOrder);
22859 ashik.ali 599
		}
22653 ashik.ali 600
	}
23444 amit.gupta 601
 
23508 amit.gupta 602
	@Override
23796 amit.gupta 603
	public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
604
			throws Exception {
23638 amit.gupta 605
		Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
23508 amit.gupta 606
		float amountToRollback = 0;
607
		List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
23796 amit.gupta 608
		for (SchemeInOut schemeInOut : schemes) {
23983 amit.gupta 609
			if (schemeInOut.getRolledBackTimestamp() == null) {
610
				schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
611
				schemeInOutRepository.persist(schemeInOut);
612
				amountToRollback += schemeInOut.getAmount();
613
			}
23508 amit.gupta 614
		}
23983 amit.gupta 615
		if (amountToRollback > 0) {
23638 amit.gupta 616
			int inventoryItemId = inventoryItemIds.get(0);
26498 amit.gupta 617
			InventoryItem ii = inventoryItemRepository.selectById(inventoryItemId);
618
			Purchase p = purchaseRepository.selectById(ii.getPurchaseId());
619
			Integer fofoId = ii.getFofoId();
26684 amit.gupta 620
			// TODO//
26693 amit.gupta 621
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, ii.getPurchaseId(),
26498 amit.gupta 622
					WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
23638 amit.gupta 623
		}
23508 amit.gupta 624
	}
23884 amit.gupta 625
 
23781 ashik.ali 626
	@Override
23796 amit.gupta 627
	public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
628
			throws ProfitMandiBusinessException {
23781 ashik.ali 629
		Map<String, Object> map = new HashMap<>();
630
		List<Scheme> schemes = null;
631
		long size = 0;
23798 amit.gupta 632
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 633
			schemes = schemeRepository.selectAll(offset, limit);
634
			size = schemeRepository.selectAllCount();
23796 amit.gupta 635
		} else {
23781 ashik.ali 636
			schemes = schemeRepository.selectActiveAll(offset, limit);
637
			size = schemeRepository.selectAllActiveCount();
638
		}
639
		map.put("schemes", schemes);
640
		map.put("start", offset + 1);
641
		map.put("size", size);
23796 amit.gupta 642
		if (schemes.size() < limit) {
23781 ashik.ali 643
			map.put("end", offset + schemes.size());
23796 amit.gupta 644
		} else {
23781 ashik.ali 645
			map.put("end", offset + limit);
646
		}
647
		return map;
648
	}
23796 amit.gupta 649
 
23781 ashik.ali 650
	@Override
23796 amit.gupta 651
	public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
652
			throws ProfitMandiBusinessException {
23781 ashik.ali 653
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
654
		List<Scheme> schemes = null;
23798 amit.gupta 655
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 656
			schemes = schemeRepository.selectAll(offset, limit);
23796 amit.gupta 657
		} else {
23781 ashik.ali 658
			schemes = schemeRepository.selectActiveAll(offset, limit);
659
		}
660
		return schemes;
661
	}
23508 amit.gupta 662
 
23968 amit.gupta 663
	@Override
24976 amit.gupta 664
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
26332 amit.gupta 665
			throws ProfitMandiBusinessException {
26498 amit.gupta 666
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
24976 amit.gupta 667
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
668
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
669
 
670
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
671
			float amountToCredit = 0;
672
			float amountToDebit = 0;
673
			int purchaseId = purchaseEntry.getKey();
674
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
675
 
676
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
677
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
678
 
679
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
680
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
681
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
682
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
683
			for (SchemeInOut schemeInOut : schemeInOuts) {
684
				InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
685
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
686
				if (scheme.getType().equals(SchemeType.OUT))
687
					continue;
688
				if (scheme.getAmountType().equals(AmountType.FIXED)) {
689
					continue;
23995 amit.gupta 690
				}
24976 amit.gupta 691
				if (schemeInOut.getRolledBackTimestamp() == null) {
692
					float newAmount = getAmount(ii, scheme);
693
					if (schemeInOut.getAmount() - newAmount >= 0.01f) {
694
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
695
						schemeInOutRepository.persist(schemeInOut);
696
						SchemeInOut sioNew = new SchemeInOut();
697
						sioNew.setAmount(newAmount);
698
						sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
699
						sioNew.setSchemeId(schemeInOut.getSchemeId());
700
						schemeInOutRepository.persist(sioNew);
701
						amountToCredit += sioNew.getAmount();
702
						amountToDebit += schemeInOut.getAmount();
703
					}
24562 amit.gupta 704
 
24976 amit.gupta 705
				}
23986 amit.gupta 706
			}
24976 amit.gupta 707
			int fofoId = inventoryItems.get(0).getFofoId();
708
			if (amountToDebit > 0) {
26684 amit.gupta 709
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
710
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
711
						priceDrop.getAffectedOn());
24976 amit.gupta 712
			}
713
			if (amountToCredit > 0) {
26403 amit.gupta 714
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
26684 amit.gupta 715
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), amountToCredit,
716
						priceDrop.getAffectedOn());
24976 amit.gupta 717
			}
23968 amit.gupta 718
		}
719
	}
24562 amit.gupta 720
 
24264 amit.gupta 721
	@Override
24562 amit.gupta 722
	public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
723
			SchemeType schemeType) throws ProfitMandiBusinessException {
24264 amit.gupta 724
		Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
725
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
726
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
727
		List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
728
		float amount = 0;
729
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size()).stream()
730
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
731
		for (SchemeInOut schemeInOut : schemeInOuts) {
732
			Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
24562 amit.gupta 733
			if (scheme.getType().equals(schemeType)) {
734
				if (schemeInOut.getRolledBackTimestamp() == null) {
24264 amit.gupta 735
					schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
736
					schemeInOutRepository.persist(schemeInOut);
737
					amount += schemeInOut.getAmount();
738
				}
739
			}
740
		}
741
		int fofoId = inventoryItems.get(0).getFofoId();
24562 amit.gupta 742
		WalletReferenceType walletReferenceType = schemeType.equals(SchemeType.OUT) ? WalletReferenceType.SCHEME_OUT
743
				: WalletReferenceType.SCHEME_IN;
744
		if (amount > 0) {
26684 amit.gupta 745
			// TODO//
24562 amit.gupta 746
			walletService.rollbackAmountFromWallet(fofoId, amount, reversalReference, walletReferenceType,
26498 amit.gupta 747
					reversalReason, LocalDateTime.now());
24268 amit.gupta 748
		}
24264 amit.gupta 749
	}
23968 amit.gupta 750
 
26332 amit.gupta 751
	@Override
752
	public double getTotalMargin(int itemId, PartnerType partnerType, LocalDateTime dateTime) {
753
		Session session = sessionFactory.getCurrentSession();
754
		CriteriaBuilder cb = session.getCriteriaBuilder();
755
		CriteriaQuery<Double> criteriaQuery = cb.createQuery(Double.class);
756
		Root<SchemeItem> schemeItem = criteriaQuery.from(SchemeItem.class);
757
		Root<Scheme> scheme = criteriaQuery.from(Scheme.class);
758
		Predicate schemePredicate = cb.equal(scheme.get(ProfitMandiConstants.AMOUNT_TYPE), AmountType.PERCENTAGE);
759
		Predicate lessThanPredicate = cb.lessThanOrEqualTo(scheme.get(ProfitMandiConstants.END_DATE_TIME), dateTime);
760
		Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(scheme.get(ProfitMandiConstants.START_DATE_TIME),
761
				dateTime);
762
		Predicate joinPredicate = cb.equal(scheme.get("id"), schemeItem.get("schemeId"));
763
		Predicate schemeItemPredicate = cb.equal(schemeItem.get(ProfitMandiConstants.ITEM_ID), itemId);
764
		criteriaQuery.select(cb.sum(scheme.get(ProfitMandiConstants.AMOUNT))).where(schemePredicate, lessThanPredicate,
765
				greaterThanPredicate, schemeItemPredicate, joinPredicate);
766
 
767
		Query<Double> query = session.createQuery(criteriaQuery);
768
		return query.getSingleResult() + ProfitMandiConstants.SCHEME_INVESTMENT_MARGIN;
769
 
770
	}
771
 
26684 amit.gupta 772
	@Override
773
	@Cacheable(value = "itemSchemeCashback", cacheManager = "timeoutCacheManager")
774
	public Map<Integer, Float> getItemSchemeCashBack() {
775
		Map<Integer, Float> itemCashbackMap = new HashMap<>();
776
		Map<Integer, Scheme> cashbackSchemesMap = schemeRepository
777
				.selectActiveAll(SchemeType.OUT, PartnerType.ALL, LocalDateTime.now(), true).stream()
778
				.filter(x -> x.getAmountType().equals(AmountType.FIXED))
779
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
26722 amit.gupta 780
		if (cashbackSchemesMap.size() > 0) {
26713 amit.gupta 781
			List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(cashbackSchemesMap.keySet());
782
			schemeItems.stream().forEach(x -> {
783
				itemCashbackMap.put(x.getItemId(), cashbackSchemesMap.get(x.getSchemeId()).getAmount());
784
			});
785
		}
26722 amit.gupta 786
		// A107FD Model needs to removed
26703 amit.gupta 787
		itemCashbackMap.remove(30211);
788
		itemCashbackMap.remove(30212);
789
		itemCashbackMap.remove(30213);
790
		itemCashbackMap.remove(30756);
26684 amit.gupta 791
		return itemCashbackMap;
792
	}
793
 
24976 amit.gupta 794
	/*
795
	 * @Override public void updateSchmesForModel(int catalogId) throws
796
	 * ProfitMandiBusinessException { List<Item> items =
797
	 * itemRepository.selectAllByCatalogItemId(catalogId); Map<Integer, Scheme>
798
	 * schemes = schemeRepository .selectAllByItemIds(items.stream().map(x ->
799
	 * x.getId()).collect(Collectors.toList()));
800
	 * 
801
	 * }
802
	 */
24562 amit.gupta 803
 
22653 ashik.ali 804
}