Subversion Repositories SmartDukaan

Rev

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