Subversion Repositories SmartDukaan

Rev

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