Subversion Repositories SmartDukaan

Rev

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