Subversion Repositories SmartDukaan

Rev

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