Subversion Repositories SmartDukaan

Rev

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