Subversion Repositories SmartDukaan

Rev

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