Subversion Repositories SmartDukaan

Rev

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