Subversion Repositories SmartDukaan

Rev

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