Subversion Repositories SmartDukaan

Rev

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