Subversion Repositories SmartDukaan

Rev

Rev 28464 | Rev 28749 | 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);
28464 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());
28737 amit.gupta 496
				} else if(scheme.getType().equals(SchemeType.OUT)){
497
					schemeInOut.setStatusDescription("Credited for sale of IMEI#" + inventoryItem.getSerialNumber());
27713 amit.gupta 498
				}
27377 amit.gupta 499
				schemeInOut.setCreditTimestamp(LocalDateTime.now());
500
			}
23443 amit.gupta 501
		}
27377 amit.gupta 502
		return amountToCredit;
22859 ashik.ali 503
	}
23444 amit.gupta 504
 
25049 amit.gupta 505
	// We are maintaining price drop after grn
23444 amit.gupta 506
	private float getAmount(InventoryItem inventoryItem, Scheme scheme) {
22653 ashik.ali 507
		float amount = 0;
25049 amit.gupta 508
		float dpForCalc = 0;
509
		float taxableSellingPrice = 0;
26684 amit.gupta 510
		// float totalTaxRate = inventoryItem.getIgstRate() +
511
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
512
		// Hardcoding it to 18%
26568 amit.gupta 513
		float totalTaxRate = 18f;
26684 amit.gupta 514
		// float totalTaxRate = inventoryItem.getIgstRate() +
515
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
23527 ashik.ali 516
		if (scheme.getAmountType() == AmountType.PERCENTAGE) {
24562 amit.gupta 517
			if (scheme.getType().equals(SchemeType.IN)) {
25049 amit.gupta 518
				dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
23995 amit.gupta 519
			} else {
520
				try {
26684 amit.gupta 521
					dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
26550 amit.gupta 522
							tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
24562 amit.gupta 523
				} catch (Exception e) {
23995 amit.gupta 524
					LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
525
					e.printStackTrace();
526
				}
527
			}
25049 amit.gupta 528
			taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
22859 ashik.ali 529
			amount = taxableSellingPrice * scheme.getAmount() / 100;
25517 amit.gupta 530
			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 531
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 532
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
533
					scheme.getAmount(), amount));
23444 amit.gupta 534
		} else {
22653 ashik.ali 535
			amount = scheme.getAmount();
25517 amit.gupta 536
			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 537
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 538
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
539
					0, amount));
22653 ashik.ali 540
		}
25049 amit.gupta 541
 
22859 ashik.ali 542
		return amount;
22653 ashik.ali 543
	}
23444 amit.gupta 544
 
22653 ashik.ali 545
	@Override
23365 ashik.ali 546
	public void processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
547
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
23444 amit.gupta 548
 
25507 amit.gupta 549
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
550
				fofoOrder.getCreateTimestamp().toLocalDate());
551
 
25043 amit.gupta 552
		List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
553
		Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
554
				.collect(Collectors.toSet());
555
		Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
556
				.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
557
				.collect(Collectors.toSet());
26726 amit.gupta 558
		if (inventoryItems.size() == 0) {
559
			return;
560
		}
26722 amit.gupta 561
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
23444 amit.gupta 562
 
26722 amit.gupta 563
		Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
26802 tejbeer 564
				.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(fofoOrder.getCreateTimestamp()))
565
				.map(x -> x.getItemId()).collect(Collectors.toSet());
26722 amit.gupta 566
		// Only consider inventory items that were not returned
567
		inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
568
				.collect(Collectors.toSet());
569
 
25043 amit.gupta 570
		if (inventoryItems.size() == 0) {
23365 ashik.ali 571
			return;
22859 ashik.ali 572
		}
23444 amit.gupta 573
 
25043 amit.gupta 574
		float totalCashback = 0;
575
		int count = 0;
23444 amit.gupta 576
 
27898 amit.gupta 577
		List<Scheme> allActiveSchemes = schemeRepository.selectActiveAll(SchemeType.OUT, partnerType,
578
				fofoOrder.getCreateTimestamp(), false);
579
		allActiveSchemes.addAll(schemeRepository.selectActiveAll(SchemeType.ACTIVATION, partnerType,
580
				fofoOrder.getCreateTimestamp(), false));
581
		allActiveSchemes.addAll(schemeRepository.selectActiveAll(SchemeType.INVESTMENT, partnerType,
582
				fofoOrder.getCreateTimestamp(), false));
583
 
25043 amit.gupta 584
		for (InventoryItem inventoryItem : inventoryItems) {
25710 amit.gupta 585
			float itemCashback = 0;
25043 amit.gupta 586
			Set<Integer> schemeIds = new HashSet<>(
587
					schemeItemRepository.selectSchemeIdByItemId(inventoryItem.getItemId()));
27898 amit.gupta 588
			allActiveSchemes = allActiveSchemes.stream().filter(x -> schemeIds.contains(x.getId()))
589
					.collect(Collectors.toList());
27377 amit.gupta 590
			for (Scheme scheme : allActiveSchemes) {
25043 amit.gupta 591
				itemCashback += this.createSchemeInOut(scheme, inventoryItem);
22653 ashik.ali 592
			}
25043 amit.gupta 593
			if (itemCashback > 0) {
594
				count++;
595
				totalCashback += itemCashback;
22859 ashik.ali 596
			}
22653 ashik.ali 597
		}
25043 amit.gupta 598
		if (count > 0) {
23444 amit.gupta 599
			walletService.addAmountToWallet(retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT,
23796 amit.gupta 600
					"Sales margin for invoice number " + fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
26498 amit.gupta 601
					totalCashback, fofoOrder.getCreateTimestamp());
23365 ashik.ali 602
			fofoOrder.setCashback(totalCashback);
603
			fofoOrderRepository.persist(fofoOrder);
22859 ashik.ali 604
		}
22653 ashik.ali 605
	}
23444 amit.gupta 606
 
23508 amit.gupta 607
	@Override
23796 amit.gupta 608
	public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
609
			throws Exception {
23638 amit.gupta 610
		Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
23508 amit.gupta 611
		float amountToRollback = 0;
612
		List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
23796 amit.gupta 613
		for (SchemeInOut schemeInOut : schemes) {
23983 amit.gupta 614
			if (schemeInOut.getRolledBackTimestamp() == null) {
615
				schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
28464 amit.gupta 616
				if (schemeInOut.getStatus()==null || schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
27377 amit.gupta 617
					amountToRollback += schemeInOut.getAmount();
618
				}
619
				schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
620
				schemeInOut.setStatusDescription(rollbackReason);
23983 amit.gupta 621
			}
23508 amit.gupta 622
		}
23983 amit.gupta 623
		if (amountToRollback > 0) {
23638 amit.gupta 624
			int inventoryItemId = inventoryItemIds.get(0);
26498 amit.gupta 625
			InventoryItem ii = inventoryItemRepository.selectById(inventoryItemId);
626
			Integer fofoId = ii.getFofoId();
27898 amit.gupta 627
			// Purchase p = purchaseRepository.selectById(ii.getPurchaseId());
26684 amit.gupta 628
			// TODO//
26693 amit.gupta 629
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, ii.getPurchaseId(),
26498 amit.gupta 630
					WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
23638 amit.gupta 631
		}
23508 amit.gupta 632
	}
23884 amit.gupta 633
 
23781 ashik.ali 634
	@Override
23796 amit.gupta 635
	public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
636
			throws ProfitMandiBusinessException {
23781 ashik.ali 637
		Map<String, Object> map = new HashMap<>();
638
		List<Scheme> schemes = null;
639
		long size = 0;
23798 amit.gupta 640
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 641
			schemes = schemeRepository.selectAll(offset, limit);
642
			size = schemeRepository.selectAllCount();
23796 amit.gupta 643
		} else {
23781 ashik.ali 644
			schemes = schemeRepository.selectActiveAll(offset, limit);
645
			size = schemeRepository.selectAllActiveCount();
646
		}
647
		map.put("schemes", schemes);
648
		map.put("start", offset + 1);
649
		map.put("size", size);
23796 amit.gupta 650
		if (schemes.size() < limit) {
23781 ashik.ali 651
			map.put("end", offset + schemes.size());
23796 amit.gupta 652
		} else {
23781 ashik.ali 653
			map.put("end", offset + limit);
654
		}
655
		return map;
656
	}
23796 amit.gupta 657
 
23781 ashik.ali 658
	@Override
23796 amit.gupta 659
	public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
660
			throws ProfitMandiBusinessException {
23781 ashik.ali 661
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
662
		List<Scheme> schemes = null;
23798 amit.gupta 663
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 664
			schemes = schemeRepository.selectAll(offset, limit);
23796 amit.gupta 665
		} else {
23781 ashik.ali 666
			schemes = schemeRepository.selectActiveAll(offset, limit);
667
		}
668
		return schemes;
669
	}
23508 amit.gupta 670
 
23968 amit.gupta 671
	@Override
27898 amit.gupta 672
	// This is being called to reverse schemes while processing price Drop
24976 amit.gupta 673
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
26332 amit.gupta 674
			throws ProfitMandiBusinessException {
26498 amit.gupta 675
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
24976 amit.gupta 676
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
677
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
678
 
679
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
680
			float amountToCredit = 0;
681
			float amountToDebit = 0;
682
			int purchaseId = purchaseEntry.getKey();
683
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
684
 
685
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
686
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
687
 
688
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
27399 amit.gupta 689
			LOGGER.info("Scheme InOuts , {}", schemeInOuts);
27898 amit.gupta 690
			if (schemeInOuts.size() == 0) {
27400 amit.gupta 691
				continue;
692
			}
24976 amit.gupta 693
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
694
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
695
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
696
			for (SchemeInOut schemeInOut : schemeInOuts) {
697
				InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
698
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
699
				if (scheme.getAmountType().equals(AmountType.FIXED)) {
700
					continue;
23995 amit.gupta 701
				}
27713 amit.gupta 702
				if (scheme.getType().equals(SchemeType.IN) && schemeInOut.getRolledBackTimestamp() == null) {
24976 amit.gupta 703
					float newAmount = getAmount(ii, scheme);
704
					if (schemeInOut.getAmount() - newAmount >= 0.01f) {
705
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
27898 amit.gupta 706
 
24976 amit.gupta 707
						SchemeInOut sioNew = new SchemeInOut();
708
						sioNew.setAmount(newAmount);
27713 amit.gupta 709
						sioNew.setStatus(schemeInOut.getStatus());
710
						sioNew.setStatusDescription(schemeInOut.getStatusDescription());
24976 amit.gupta 711
						sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
712
						sioNew.setSchemeId(schemeInOut.getSchemeId());
713
						schemeInOutRepository.persist(sioNew);
27713 amit.gupta 714
 
715
						schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
716
						schemeInOut.setStatusDescription("Pricedrop processed, new entries added");
27898 amit.gupta 717
						// IF not credited then dont consider any credit/debit for that sio entry
718
						if (schemeInOut.getCreditTimestamp() != null) {
27713 amit.gupta 719
							amountToCredit += sioNew.getAmount();
720
							amountToDebit += schemeInOut.getAmount();
721
						}
24976 amit.gupta 722
					}
24562 amit.gupta 723
 
24976 amit.gupta 724
				}
23986 amit.gupta 725
			}
24976 amit.gupta 726
			int fofoId = inventoryItems.get(0).getFofoId();
727
			if (amountToDebit > 0) {
26684 amit.gupta 728
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
729
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
730
						priceDrop.getAffectedOn());
24976 amit.gupta 731
			}
732
			if (amountToCredit > 0) {
26403 amit.gupta 733
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
26684 amit.gupta 734
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), amountToCredit,
735
						priceDrop.getAffectedOn());
24976 amit.gupta 736
			}
23968 amit.gupta 737
		}
738
	}
24562 amit.gupta 739
 
24264 amit.gupta 740
	@Override
27898 amit.gupta 741
	// Always being called from cancel order means no SCHEME IN is considered
24562 amit.gupta 742
	public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
743
			SchemeType schemeType) throws ProfitMandiBusinessException {
24264 amit.gupta 744
		Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
28419 tejbeer 745
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
28417 tejbeer 746
		LOGGER.info("inventoryItems" + inventoryItems);
747
 
24264 amit.gupta 748
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
28416 tejbeer 749
		LOGGER.info("schemeInOuts" + schemeInOuts);
28417 tejbeer 750
		float amountToRollback = 0;
28416 tejbeer 751
 
28417 tejbeer 752
		if (!schemeInOuts.isEmpty()) {
753
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
754
			LOGGER.info("schemeIds" + schemeIds);
28416 tejbeer 755
 
28417 tejbeer 756
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
757
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
758
			for (SchemeInOut schemeInOut : schemeInOuts) {
759
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
760
				if (scheme.getType().equals(schemeType)) {
761
					if (schemeInOut.getRolledBackTimestamp() == null) {
762
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
763
						if (schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
764
							amountToRollback += schemeInOut.getAmount();
765
						}
766
						schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
767
						schemeInOut.setStatusDescription(reversalReason);
27377 amit.gupta 768
					}
24264 amit.gupta 769
				}
770
			}
28417 tejbeer 771
 
24264 amit.gupta 772
		}
773
		int fofoId = inventoryItems.get(0).getFofoId();
24562 amit.gupta 774
		WalletReferenceType walletReferenceType = schemeType.equals(SchemeType.OUT) ? WalletReferenceType.SCHEME_OUT
27898 amit.gupta 775
				: schemeType.equals(SchemeType.INVESTMENT) ? WalletReferenceType.INVESTMENT_PAYOUT
776
						: WalletReferenceType.ACTIVATION_SCHEME;
27377 amit.gupta 777
		if (amountToRollback > 0) {
26684 amit.gupta 778
			// TODO//
27377 amit.gupta 779
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, reversalReference, walletReferenceType,
26498 amit.gupta 780
					reversalReason, LocalDateTime.now());
24268 amit.gupta 781
		}
24264 amit.gupta 782
	}
23968 amit.gupta 783
 
26332 amit.gupta 784
	@Override
785
	public double getTotalMargin(int itemId, PartnerType partnerType, LocalDateTime dateTime) {
786
		Session session = sessionFactory.getCurrentSession();
787
		CriteriaBuilder cb = session.getCriteriaBuilder();
788
		CriteriaQuery<Double> criteriaQuery = cb.createQuery(Double.class);
789
		Root<SchemeItem> schemeItem = criteriaQuery.from(SchemeItem.class);
790
		Root<Scheme> scheme = criteriaQuery.from(Scheme.class);
791
		Predicate schemePredicate = cb.equal(scheme.get(ProfitMandiConstants.AMOUNT_TYPE), AmountType.PERCENTAGE);
792
		Predicate lessThanPredicate = cb.lessThanOrEqualTo(scheme.get(ProfitMandiConstants.END_DATE_TIME), dateTime);
793
		Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(scheme.get(ProfitMandiConstants.START_DATE_TIME),
794
				dateTime);
795
		Predicate joinPredicate = cb.equal(scheme.get("id"), schemeItem.get("schemeId"));
796
		Predicate schemeItemPredicate = cb.equal(schemeItem.get(ProfitMandiConstants.ITEM_ID), itemId);
797
		criteriaQuery.select(cb.sum(scheme.get(ProfitMandiConstants.AMOUNT))).where(schemePredicate, lessThanPredicate,
798
				greaterThanPredicate, schemeItemPredicate, joinPredicate);
799
 
800
		Query<Double> query = session.createQuery(criteriaQuery);
801
		return query.getSingleResult() + ProfitMandiConstants.SCHEME_INVESTMENT_MARGIN;
802
 
803
	}
804
 
26684 amit.gupta 805
	@Override
806
	@Cacheable(value = "itemSchemeCashback", cacheManager = "timeoutCacheManager")
807
	public Map<Integer, Float> getItemSchemeCashBack() {
808
		Map<Integer, Float> itemCashbackMap = new HashMap<>();
809
		Map<Integer, Scheme> cashbackSchemesMap = schemeRepository
28357 amit.gupta 810
				.selectActiveAll(SchemeType.ACTIVATION, PartnerType.ALL, LocalDateTime.now(), true).stream()
26684 amit.gupta 811
				.filter(x -> x.getAmountType().equals(AmountType.FIXED))
812
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
26722 amit.gupta 813
		if (cashbackSchemesMap.size() > 0) {
26713 amit.gupta 814
			List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(cashbackSchemesMap.keySet());
815
			schemeItems.stream().forEach(x -> {
816
				itemCashbackMap.put(x.getItemId(), cashbackSchemesMap.get(x.getSchemeId()).getAmount());
817
			});
818
		}
26722 amit.gupta 819
		// A107FD Model needs to removed
26703 amit.gupta 820
		itemCashbackMap.remove(30211);
821
		itemCashbackMap.remove(30212);
822
		itemCashbackMap.remove(30213);
823
		itemCashbackMap.remove(30756);
26684 amit.gupta 824
		return itemCashbackMap;
825
	}
826
 
24976 amit.gupta 827
	/*
828
	 * @Override public void updateSchmesForModel(int catalogId) throws
829
	 * ProfitMandiBusinessException { List<Item> items =
830
	 * itemRepository.selectAllByCatalogItemId(catalogId); Map<Integer, Scheme>
831
	 * schemes = schemeRepository .selectAllByItemIds(items.stream().map(x ->
832
	 * x.getId()).collect(Collectors.toList()));
833
	 * 
834
	 * }
835
	 */
24562 amit.gupta 836
 
26802 tejbeer 837
	@Override
27898 amit.gupta 838
	public List<Scheme> selectSchemeByPartnerType(PartnerType partnerType, LocalDate onDate, int itemId,
839
			boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
26802 tejbeer 840
		Session session = sessionFactory.getCurrentSession();
841
		CriteriaBuilder cb = session.getCriteriaBuilder();
842
		CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
843
		Root<Scheme> scheme = query.from(Scheme.class);
844
		List<PartnerType> pt = new ArrayList<>();
845
		pt.add(PartnerType.ALL);
846
		pt.add(partnerType);
847
		Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
848
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
849
		cb.desc(cb.isNull(scheme.get("expireTimestamp")));
850
 
851
		Predicate p3 = null;
852
		Predicate finalPredicate = null;
853
		if (itemId != 0) {
27898 amit.gupta 854
 
26802 tejbeer 855
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
27424 tejbeer 856
			LOGGER.info("schemeId" + schemeIds);
27898 amit.gupta 857
			if (schemeIds.isEmpty()) {
27424 tejbeer 858
				return new ArrayList<>();
859
			}
26802 tejbeer 860
			p3 = cb.in(scheme.get("id")).value(schemeIds);
861
			if (!isAdmin) {
862
 
27877 amit.gupta 863
				finalPredicate = cb.and(p1, p2, p3, cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()),
864
						cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
26802 tejbeer 865
				query.where(finalPredicate);
866
			} else {
867
				finalPredicate = cb.and(p1, p3);
868
				query.where(finalPredicate);
869
			}
870
		} else {
871
 
872
			if (!isAdmin) {
873
 
874
				finalPredicate = cb.and(p1, p2);
26912 tejbeer 875
				query.where(finalPredicate);
26802 tejbeer 876
			} else {
877
				query.where(p1);
878
			}
879
		}
880
		query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
881
 
882
		return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
883
 
884
	}
885
 
886
	@Override
27877 amit.gupta 887
	public long selectSchemeCount(PartnerType partnerType, LocalDate onDate, int itemId, boolean isAdmin) {
26802 tejbeer 888
		Session session = sessionFactory.getCurrentSession();
889
		CriteriaBuilder cb = session.getCriteriaBuilder();
890
		CriteriaQuery<Long> query = cb.createQuery(Long.class);
891
		Root<Scheme> scheme = query.from(Scheme.class);
892
		List<PartnerType> pt = new ArrayList<>();
893
		pt.add(PartnerType.ALL);
894
		pt.add(partnerType);
895
		Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
896
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
897
		Predicate finalPredicate = null;
898
		if (itemId != 0) {
899
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
900
			Predicate p3 = cb.in(scheme.get("id")).value(schemeIds);
901
			if (!isAdmin) {
902
 
27877 amit.gupta 903
				finalPredicate = cb.and(p1, p2, p3, cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()),
904
						cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
26802 tejbeer 905
				query.select(cb.count(scheme)).where(finalPredicate);
906
			} else {
907
				finalPredicate = cb.and(p1, p3);
908
				query.select(cb.count(scheme)).where(finalPredicate);
909
			}
910
		} else {
911
			if (!isAdmin) {
912
				finalPredicate = cb.and(p1, p2);
913
				query.select(cb.count(scheme)).where(finalPredicate);
914
 
915
			} else {
916
				query.select(cb.count(scheme)).where(p1);
917
 
918
			}
919
		}
920
 
921
		return session.createQuery(query).getSingleResult();
922
 
923
	}
27898 amit.gupta 924
 
27395 amit.gupta 925
	@Override
926
	public void processActivation() throws ProfitMandiBusinessException {
927
		List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
928
		List<Integer> schemeIds = new ArrayList<>();
929
		Set<Integer> inventoryIds = new HashSet<>();
27898 amit.gupta 930
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 931
			schemeIds.add(pendingPayout.getSchemeId());
27440 amit.gupta 932
		}
933
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream()
27898 amit.gupta 934
				.filter(x -> x.getType().equals(SchemeType.ACTIVATION))
935
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
936
		pendingPayouts = pendingPayouts.stream().filter(x -> schemesMap.get(x.getSchemeId()) != null)
937
				.collect(Collectors.toList());
27440 amit.gupta 938
 
27898 amit.gupta 939
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 940
			inventoryIds.add(pendingPayout.getInventoryItemId());
941
		}
27898 amit.gupta 942
		Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
943
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
944
		Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream()
945
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
946
 
947
		List<ActivatedImei> activatedImeis = activatedImeiRepository
948
				.selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet()));
949
 
950
		Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream()
951
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
952
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 953
			InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
954
			String serialNumber = ii.getSerialNumber();
955
			ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
27898 amit.gupta 956
			if (activatedImei == null) {
27395 amit.gupta 957
				continue;
958
			}
959
			Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
27898 amit.gupta 960
			if (activatedImei.getActivationTimestamp().isBefore(scheme.getEndDateTime())
961
					&& activatedImei.getActivationTimestamp().isAfter(scheme.getStartDateTime())) {
27395 amit.gupta 962
				int fofoId = ii.getFofoId();
27898 amit.gupta 963
				// Get latest order Id
964
				int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream()
965
						.filter(x -> x.getOrderId() > 0)
966
						.sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get()
967
						.getOrderId();
27395 amit.gupta 968
				FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
27898 amit.gupta 969
				walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.ACTIVATION_SCHEME,
970
						"Activation margin for Imei#" + serialNumber, pendingPayout.getAmount(),
971
						fofoOrder.getCreateTimestamp());
27395 amit.gupta 972
				pendingPayout.setCreditTimestamp(LocalDateTime.now());
973
				pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
974
				pendingPayout.setStatusDescription("Activation margin credited");
975
			} else {
976
				pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
27898 amit.gupta 977
				pendingPayout.setRolledBackTimestamp(LocalDateTime.now());
978
				;
979
				pendingPayout.setStatusDescription(
980
						"Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
27395 amit.gupta 981
			}
982
		}
983
	}
26802 tejbeer 984
 
22653 ashik.ali 985
}