Subversion Repositories SmartDukaan

Rev

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