Subversion Repositories SmartDukaan

Rev

Rev 27396 | Rev 27400 | 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
 
27395 amit.gupta 20
import org.apache.commons.collections.ListUtils;
23781 ashik.ali 21
import org.apache.logging.log4j.LogManager;
23568 govind 22
import org.apache.logging.log4j.Logger;
26332 amit.gupta 23
import org.hibernate.Session;
24
import org.hibernate.SessionFactory;
25
import org.hibernate.query.Query;
22653 ashik.ali 26
import org.springframework.beans.factory.annotation.Autowired;
23781 ashik.ali 27
import org.springframework.beans.factory.annotation.Qualifier;
26684 amit.gupta 28
import org.springframework.cache.annotation.Cacheable;
22653 ashik.ali 29
import org.springframework.stereotype.Component;
30
 
27395 amit.gupta 31
import com.mysql.fabric.xmlrpc.base.Array;
24307 amit.gupta 32
import com.spice.profitmandi.common.enumuration.ItemType;
22653 ashik.ali 33
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
34
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23019 ashik.ali 35
import com.spice.profitmandi.common.model.SchemeModel;
27395 amit.gupta 36
import com.spice.profitmandi.common.util.FormattingUtils;
22859 ashik.ali 37
import com.spice.profitmandi.common.util.StringUtils;
23339 ashik.ali 38
import com.spice.profitmandi.dao.entity.catalog.Item;
22653 ashik.ali 39
import com.spice.profitmandi.dao.entity.catalog.RetailerScheme;
40
import com.spice.profitmandi.dao.entity.catalog.Scheme;
27395 amit.gupta 41
import com.spice.profitmandi.dao.entity.fofo.ActivatedImei;
23365 ashik.ali 42
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
22653 ashik.ali 43
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
25503 amit.gupta 44
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
27395 amit.gupta 45
import com.spice.profitmandi.dao.entity.fofo.PendingOrder;
23339 ashik.ali 46
import com.spice.profitmandi.dao.entity.fofo.Purchase;
25043 amit.gupta 47
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
22859 ashik.ali 48
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
49
import com.spice.profitmandi.dao.entity.fofo.SchemeItem;
26498 amit.gupta 50
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
23527 ashik.ali 51
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
22653 ashik.ali 52
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25111 amit.gupta 53
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
27377 amit.gupta 54
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
25503 amit.gupta 55
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
22859 ashik.ali 56
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
22653 ashik.ali 57
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
23995 amit.gupta 58
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
23968 amit.gupta 59
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
27395 amit.gupta 60
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
23019 ashik.ali 61
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
62
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
23365 ashik.ali 63
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
22653 ashik.ali 64
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
25503 amit.gupta 65
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
23339 ashik.ali 66
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
25043 amit.gupta 67
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
22859 ashik.ali 68
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
69
import com.spice.profitmandi.dao.repository.fofo.SchemeItemRepository;
26498 amit.gupta 70
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
23798 amit.gupta 71
import com.spice.profitmandi.service.authentication.RoleManager;
26722 amit.gupta 72
import com.spice.profitmandi.service.inventory.PurchaseService;
22859 ashik.ali 73
import com.spice.profitmandi.service.wallet.WalletService;
22653 ashik.ali 74
 
22859 ashik.ali 75
import in.shop2020.model.v1.order.WalletReferenceType;
76
 
22653 ashik.ali 77
@Component
78
public class SchemeServiceImpl implements SchemeService {
79
 
23568 govind 80
	private static final Logger LOGGER = LogManager.getLogger(SchemeServiceImpl.class);
23444 amit.gupta 81
 
22653 ashik.ali 82
	@Autowired
23781 ashik.ali 83
	@Qualifier("fofoInventoryItemRepository")
22653 ashik.ali 84
	private InventoryItemRepository inventoryItemRepository;
23444 amit.gupta 85
 
22653 ashik.ali 86
	@Autowired
27395 amit.gupta 87
	private ActivatedImeiRepository activatedImeiRepository;
88
 
89
	@Autowired
25503 amit.gupta 90
	private PartnerTypeChangeService partnerTypeChangeService;
91
 
92
	@Autowired
26722 amit.gupta 93
	private PurchaseService purchaseService;
94
 
95
	@Autowired
25043 amit.gupta 96
	private ScanRecordRepository scanRecordRepository;
23444 amit.gupta 97
 
22653 ashik.ali 98
	@Autowired
26332 amit.gupta 99
	private SessionFactory sessionFactory;
100
 
26722 amit.gupta 101
	private Set<Integer> tagIds = new HashSet<Integer>(Arrays.asList(4));
102
 
26332 amit.gupta 103
	@Autowired
22653 ashik.ali 104
	private SchemeRepository schemeRepository;
26684 amit.gupta 105
 
26498 amit.gupta 106
	@Autowired
107
	private PriceDropRepository priceDropRepository;
23444 amit.gupta 108
 
22653 ashik.ali 109
	@Autowired
23798 amit.gupta 110
	private RoleManager roleManager;
111
 
112
	@Autowired
22859 ashik.ali 113
	private RetailerRepository retailerRepository;
24562 amit.gupta 114
 
23995 amit.gupta 115
	@Autowired
116
	private TagListingRepository tagListingRepository;
23444 amit.gupta 117
 
22859 ashik.ali 118
	@Autowired
119
	private SchemeInOutRepository schemeInOutRepository;
23444 amit.gupta 120
 
22653 ashik.ali 121
	@Autowired
23781 ashik.ali 122
	@Qualifier("catalogItemRepository")
22859 ashik.ali 123
	private ItemRepository itemRepository;
23444 amit.gupta 124
 
22859 ashik.ali 125
	@Autowired
126
	private SchemeItemRepository schemeItemRepository;
23444 amit.gupta 127
 
22859 ashik.ali 128
	@Autowired
129
	private WalletService walletService;
23444 amit.gupta 130
 
23019 ashik.ali 131
	@Autowired
132
	private FofoOrderItemRepository fofoOrderItemRepository;
23444 amit.gupta 133
 
23019 ashik.ali 134
	@Autowired
135
	private FofoLineItemRepository fofoLineItemRepository;
23444 amit.gupta 136
 
23339 ashik.ali 137
	@Autowired
138
	private PurchaseRepository purchaseRepository;
23444 amit.gupta 139
 
23344 ashik.ali 140
	@Autowired
23365 ashik.ali 141
	private FofoOrderRepository fofoOrderRepository;
23796 amit.gupta 142
 
22653 ashik.ali 143
	@Override
22859 ashik.ali 144
	public void saveScheme(int creatorId, CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
23444 amit.gupta 145
 
23019 ashik.ali 146
		this.validateCreateSchemeRequest(createSchemeRequest);
23444 amit.gupta 147
 
22859 ashik.ali 148
		Scheme scheme = this.toScheme(creatorId, createSchemeRequest);
23444 amit.gupta 149
 
150
		if (scheme.getStartDateTime().isAfter(scheme.getEndDateTime())) {
151
			throw new ProfitMandiBusinessException(
152
					ProfitMandiConstants.START_DATE + ", " + ProfitMandiConstants.END_DATE,
153
					scheme.getStartDateTime() + ", " + scheme.getEndDateTime(), "SCHM_VE_1005");
22653 ashik.ali 154
		}
23444 amit.gupta 155
 
26332 amit.gupta 156
		// this.validateItemIds(createSchemeRequest);
22859 ashik.ali 157
		schemeRepository.persist(scheme);
23444 amit.gupta 158
		for (int itemId : createSchemeRequest.getItemIds()) {
22859 ashik.ali 159
			SchemeItem schemeItem = new SchemeItem();
160
			schemeItem.setSchemeId(scheme.getId());
161
			schemeItem.setItemId(itemId);
162
			schemeItemRepository.persist(schemeItem);
163
		}
23444 amit.gupta 164
 
22653 ashik.ali 165
	}
23444 amit.gupta 166
 
167
	private void validateCreateSchemeRequest(CreateSchemeRequest createSchemeRequest)
168
			throws ProfitMandiBusinessException {
169
		if (createSchemeRequest.getName() == null || createSchemeRequest.getName().isEmpty()) {
170
			throw new ProfitMandiBusinessException(ProfitMandiConstants.NAME, createSchemeRequest.getName(),
171
					"SCHM_VE_1000");
23019 ashik.ali 172
		}
23444 amit.gupta 173
		if (createSchemeRequest.getAmount() <= 0) {
174
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
175
					"SCHM_VE_1001");
23019 ashik.ali 176
		}
23444 amit.gupta 177
 
25503 amit.gupta 178
		if (createSchemeRequest.getAmountType().equals(AmountType.PERCENTAGE)
23444 amit.gupta 179
				&& createSchemeRequest.getAmount() > 100) {
180
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
181
					"SCHM_VE_1002");
23019 ashik.ali 182
		}
23444 amit.gupta 183
 
23886 amit.gupta 184
		if (createSchemeRequest.getStartDate() == null) {
23983 amit.gupta 185
			throw new ProfitMandiBusinessException(ProfitMandiConstants.START_DATE, createSchemeRequest.getStartDate(),
186
					"SCHM_VE_1003");
23019 ashik.ali 187
		}
23886 amit.gupta 188
		if (createSchemeRequest.getEndDate() == null) {
23983 amit.gupta 189
			throw new ProfitMandiBusinessException(ProfitMandiConstants.END_DATE, createSchemeRequest.getEndDate(),
190
					"SCHM_VE_1004");
23019 ashik.ali 191
		}
192
	}
23444 amit.gupta 193
 
194
	private Scheme toScheme(int creatorId, CreateSchemeRequest createSchemeRequest) {
22859 ashik.ali 195
		Scheme scheme = new Scheme();
196
		scheme.setName(createSchemeRequest.getName());
197
		scheme.setDescription(createSchemeRequest.getDescription());
25503 amit.gupta 198
		scheme.setType(createSchemeRequest.getType());
199
		scheme.setAmountType(createSchemeRequest.getAmountType());
22859 ashik.ali 200
		scheme.setAmount(createSchemeRequest.getAmount());
25503 amit.gupta 201
		scheme.setPartnerType(createSchemeRequest.getPartnerType());
25517 amit.gupta 202
		scheme.setStartDateTime(createSchemeRequest.getStartDate());
23886 amit.gupta 203
		scheme.setEndDateTime(createSchemeRequest.getEndDate());
22859 ashik.ali 204
		scheme.setCreatedBy(creatorId);
26686 amit.gupta 205
		scheme.setCashback(createSchemeRequest.isCashBack());
22859 ashik.ali 206
		return scheme;
207
	}
23444 amit.gupta 208
 
209
	private void validateItemIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
210
		if (createSchemeRequest.getItemIds() == null || createSchemeRequest.getItemIds().isEmpty()) {
211
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
212
					"SCHM_1003");
22859 ashik.ali 213
		}
23444 amit.gupta 214
		List<Integer> foundItemIds = itemRepository.selectIdsByIdsAndType(createSchemeRequest.getItemIds(),
215
				ItemType.SERIALIZED);
216
		if (foundItemIds.size() != createSchemeRequest.getItemIds().size()) {
22859 ashik.ali 217
			createSchemeRequest.getItemIds().removeAll(foundItemIds);
23444 amit.gupta 218
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
219
					"SCHM_1004");
22859 ashik.ali 220
		}
221
	}
23444 amit.gupta 222
 
22859 ashik.ali 223
	@Override
224
	public Scheme getSchemeById(int schemeId) throws ProfitMandiBusinessException {
225
		Scheme scheme = schemeRepository.selectById(schemeId);
226
		List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(scheme.getId());
23914 govind 227
		if (itemIds.size() > 0) {
228
			List<Item> items = itemRepository.selectByIds(new HashSet<>(itemIds));
229
			scheme.setItemStringMap(this.toItemStringMap(items));
23983 amit.gupta 230
		}
22859 ashik.ali 231
		return scheme;
232
	}
23444 amit.gupta 233
 
234
	public Map<Integer, String> toItemStringMap(List<Item> items) {
23339 ashik.ali 235
		Map<Integer, String> itemMap = new HashMap<>();
23444 amit.gupta 236
		for (Item item : items) {
23339 ashik.ali 237
			itemMap.put(item.getId(), this.getItemString(item));
238
		}
239
		return itemMap;
240
	}
23444 amit.gupta 241
 
242
	public String getItemString(Item item) {
23339 ashik.ali 243
		StringBuilder itemString = new StringBuilder();
23444 amit.gupta 244
		if (item.getBrand() != null && !item.getBrand().isEmpty()) {
23339 ashik.ali 245
			itemString.append(item.getBrand().trim());
246
		}
247
		itemString.append(" ");
23444 amit.gupta 248
		if (item.getModelName() != null && !item.getModelName().isEmpty()) {
23339 ashik.ali 249
			itemString.append(item.getModelName().trim());
250
		}
251
		itemString.append(" ");
23444 amit.gupta 252
		if (item.getModelNumber() != null && !item.getModelNumber().isEmpty()) {
23339 ashik.ali 253
			itemString.append(item.getModelNumber().trim());
254
		}
255
		itemString.append(" ");
23444 amit.gupta 256
		if (item.getColor() != null && !item.getColor().isEmpty()) {
23339 ashik.ali 257
			itemString.append(item.getColor().trim());
258
		}
259
		return itemString.toString();
260
	}
23444 amit.gupta 261
 
262
	private Set<Integer> schemeItemsToItemIds(List<SchemeItem> schemeItems) {
23339 ashik.ali 263
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 264
		for (SchemeItem schemeItem : schemeItems) {
23339 ashik.ali 265
			itemIds.add(schemeItem.getItemId());
266
		}
267
		return itemIds;
268
	}
23444 amit.gupta 269
 
23019 ashik.ali 270
	@Override
271
	public List<SchemeModel> getAllSchemeModels(LocalDateTime startDateTime, LocalDateTime endDateTime) {
272
		List<Scheme> schemes = schemeRepository.selectAllBetweenCreateTimestamp(startDateTime, endDateTime);
273
		Map<Integer, Scheme> schemeIdSchemeMap = this.toSchemeIdSchemeMap(schemes);
274
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
23339 ashik.ali 275
		Set<Integer> itemIds = this.schemeItemsToItemIds(schemeItems);
276
		List<Item> items = itemRepository.selectByIds(itemIds);
277
		Map<Integer, String> itemStringMap = this.toItemStringMap(items);
278
		this.addItemIdsToSchemes(schemeItems, schemeIdSchemeMap, itemStringMap);
23019 ashik.ali 279
		return this.toSchemeModels(schemeIdSchemeMap);
280
	}
23444 amit.gupta 281
 
282
	private void addItemIdsToSchemes(List<SchemeItem> schemeItems, Map<Integer, Scheme> schemeIdSchemeMap,
283
			Map<Integer, String> itemStringMap) {
284
		for (SchemeItem schemeItem : schemeItems) {
285
			schemeIdSchemeMap.get(schemeItem.getSchemeId()).getItemStringMap().put(schemeItem.getItemId(),
286
					itemStringMap.get(schemeItem.getItemId()));
23019 ashik.ali 287
		}
288
	}
23444 amit.gupta 289
 
290
	private void addRetailerIdsToSchemes(List<RetailerScheme> retailerSchemes, Map<Integer, Scheme> schemeIdSchemeMap) {
291
		for (RetailerScheme retailerScheme : retailerSchemes) {
292
			schemeIdSchemeMap.get(retailerScheme.getSchemeId()).getRetailerIds().add(retailerScheme.getRetailerId());
23019 ashik.ali 293
		}
294
	}
23444 amit.gupta 295
 
296
	private List<SchemeModel> toSchemeModels(Map<Integer, Scheme> schemeIdSchemeMap) {
23019 ashik.ali 297
		List<SchemeModel> schemeModels = new ArrayList<>();
23444 amit.gupta 298
		for (Map.Entry<Integer, Scheme> schemeIdSchemeEntry : schemeIdSchemeMap.entrySet()) {
23019 ashik.ali 299
			schemeModels.add(this.toSchemeModel(schemeIdSchemeEntry.getValue()));
300
		}
301
		return schemeModels;
302
	}
23444 amit.gupta 303
 
304
	private SchemeModel toSchemeModel(Scheme scheme) {
23019 ashik.ali 305
		SchemeModel schemeModel = new SchemeModel();
306
		schemeModel.setSchemeId(scheme.getId());
307
		schemeModel.setName(scheme.getName());
308
		schemeModel.setDescription(scheme.getDescription());
309
		schemeModel.setSchemeType(scheme.getType().toString());
310
		schemeModel.setAmountType(scheme.getAmountType().toString());
311
		schemeModel.setAmount(scheme.getAmount());
312
		schemeModel.setStartDateTime(StringUtils.toString(scheme.getStartDateTime()));
313
		schemeModel.setEndDateTime(StringUtils.toString(scheme.getEndDateTime()));
314
		schemeModel.setCreateTimestamp(StringUtils.toString(scheme.getCreateTimestamp()));
315
		schemeModel.setActiveTimestamp(StringUtils.toString(scheme.getActiveTimestamp()));
316
		schemeModel.setExpireTimestamp(StringUtils.toString(scheme.getExpireTimestamp()));
317
		schemeModel.setCreatedBy(scheme.getCreatedBy());
23339 ashik.ali 318
		schemeModel.setItemStringMap(scheme.getItemStringMap());
23019 ashik.ali 319
		schemeModel.setRetailerIds(scheme.getRetailerIds());
320
		return schemeModel;
321
	}
22653 ashik.ali 322
 
323
	@Override
324
	public void activeSchemeById(int schemeId) throws ProfitMandiBusinessException {
325
		Scheme scheme = schemeRepository.selectById(schemeId);
23444 amit.gupta 326
		if (scheme.getActiveTimestamp() != null) {
327
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
328
					"SCHM_1005");
22653 ashik.ali 329
		}
23444 amit.gupta 330
		if (scheme.getExpireTimestamp() != null) {
331
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
332
					"SCHM_1006");
22653 ashik.ali 333
		}
22859 ashik.ali 334
		scheme.setActiveTimestamp(LocalDateTime.now());
335
		schemeRepository.persist(scheme);
25438 amit.gupta 336
		/*
337
		 * if (scheme.getType() == SchemeType.IN) {
338
		 * this.processPreviousPurchases(scheme); } else if (scheme.getType() ==
339
		 * SchemeType.OUT) { this.processPreviousSales(scheme); }
340
		 */
22653 ashik.ali 341
	}
23444 amit.gupta 342
 
22653 ashik.ali 343
	@Override
25069 amit.gupta 344
	public void expireSchemeById(int schemeId, LocalDateTime expiryTime) throws ProfitMandiBusinessException {
22653 ashik.ali 345
		Scheme scheme = schemeRepository.selectById(schemeId);
25111 amit.gupta 346
		if (scheme == null || scheme.getActiveTimestamp() == null) {
23444 amit.gupta 347
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
348
					"SCHM_1007");
22653 ashik.ali 349
		}
23444 amit.gupta 350
		if (scheme.getExpireTimestamp() != null) {
351
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
352
					"SCHM_1008");
22653 ashik.ali 353
		}
22859 ashik.ali 354
		scheme.setExpireTimestamp(LocalDateTime.now());
25069 amit.gupta 355
		scheme.setEndDateTime(expiryTime);
22859 ashik.ali 356
		schemeRepository.persist(scheme);
22653 ashik.ali 357
	}
23444 amit.gupta 358
 
359
	private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
23019 ashik.ali 360
		Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
23444 amit.gupta 361
		for (Scheme scheme : schemes) {
23019 ashik.ali 362
			schemeIdSchemeMap.put(scheme.getId(), scheme);
22859 ashik.ali 363
		}
23019 ashik.ali 364
		return schemeIdSchemeMap;
22859 ashik.ali 365
	}
23444 amit.gupta 366
 
367
	private Set<Integer> inventoryItemsToItemIds(List<InventoryItem> inventoryItems) {
22859 ashik.ali 368
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 369
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 370
			itemIds.add(inventoryItem.getItemId());
371
		}
372
		return itemIds;
373
	}
23444 amit.gupta 374
 
375
	private Map<Integer, Set<Scheme>> toItemIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
23019 ashik.ali 376
		Map<Integer, Scheme> schemeIdSchemesMap = this.toSchemeIdSchemeMap(schemes);
22859 ashik.ali 377
		Map<Integer, Set<Scheme>> itemIdSchemesMap = new HashMap<>();
23444 amit.gupta 378
		for (SchemeItem schemeItem : schemeItems) {
379
			if (!itemIdSchemesMap.containsKey(schemeItem.getItemId())) {
22859 ashik.ali 380
				Set<Scheme> schemesSet = new HashSet<>();
381
				schemesSet.add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
382
				itemIdSchemesMap.put(schemeItem.getItemId(), schemesSet);
23444 amit.gupta 383
			} else {
22859 ashik.ali 384
				itemIdSchemesMap.get(schemeItem.getItemId()).add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
385
			}
386
		}
387
		return itemIdSchemesMap;
388
	}
22653 ashik.ali 389
 
23444 amit.gupta 390
	private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
391
			List<InventoryItem> inventoryItems) {
22859 ashik.ali 392
		Set<Integer> schemeIds = new HashSet<>();
23444 amit.gupta 393
		for (Scheme scheme : schemes) {
22859 ashik.ali 394
			schemeIds.add(scheme.getId());
395
		}
396
		Set<Integer> itemIds = this.inventoryItemsToItemIds(inventoryItems);
397
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndItemIds(schemeIds, itemIds);
23444 amit.gupta 398
 
22859 ashik.ali 399
		Map<Integer, Set<Scheme>> itemIdSchemesMap = this.toItemIdSchemesMap(schemeItems, schemes);
400
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemsMap = new HashMap<>();
23444 amit.gupta 401
		for (InventoryItem inventoryItem : inventoryItems) {
402
			if (itemIdSchemesMap.containsKey(inventoryItem.getItemId())) {
22859 ashik.ali 403
				inventoryItemSchemsMap.put(inventoryItem, itemIdSchemesMap.get(inventoryItem.getItemId()));
404
			}
405
		}
406
		return inventoryItemSchemsMap;
407
	}
23444 amit.gupta 408
 
22859 ashik.ali 409
	@Override
23365 ashik.ali 410
	public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
23369 ashik.ali 411
		LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
23344 ashik.ali 412
		Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
25503 amit.gupta 413
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
414
				purchase.getCreateTimestamp().toLocalDate());
23369 ashik.ali 415
		LOGGER.info("purchase is completed = {}", (purchase.getCompleteTimestamp() != null));
23444 amit.gupta 416
		if (purchase.getCompleteTimestamp() != null) {
25507 amit.gupta 417
			List<Scheme> schemes = schemeRepository.selectActiveAll(SchemeType.IN, partnerType,
26684 amit.gupta 418
					purchase.getCompleteTimestamp(), false);
23365 ashik.ali 419
			float totalCashback = 0;
23444 amit.gupta 420
			if (schemes.isEmpty()) {
23365 ashik.ali 421
				return;
422
			}
423
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
26332 amit.gupta 424
 
26722 amit.gupta 425
			Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
426
			LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
427
			Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
26802 tejbeer 428
					.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
26722 amit.gupta 429
					.collect(Collectors.toSet());
26332 amit.gupta 430
			// Only consider inventory items that were not returned
26722 amit.gupta 431
			inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
432
					.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
433
					.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
25487 amit.gupta 434
			LOGGER.info(inventoryItems);
25438 amit.gupta 435
			if (inventoryItems.size() == 0)
436
				return;
23444 amit.gupta 437
			Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
438
					inventoryItems);
439
 
440
			if (inventoryItemSchemesMap.isEmpty()) {
23365 ashik.ali 441
				return;
442
			}
443
			Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 444
 
445
			for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
23365 ashik.ali 446
				Set<Scheme> allSchemes = new HashSet<>();
23444 amit.gupta 447
				for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
25503 amit.gupta 448
					allSchemes.add(scheme);
22859 ashik.ali 449
				}
23365 ashik.ali 450
				allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
22859 ashik.ali 451
			}
23444 amit.gupta 452
 
26722 amit.gupta 453
			//
454
 
23444 amit.gupta 455
			int itemsCount = 0;
456
			for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
457
					.entrySet()) {
458
				float inventoryItemCashback = 0;
459
				for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
23365 ashik.ali 460
					InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
461
					float cashback = this.createSchemeInOut(scheme, inventoryItem);
23444 amit.gupta 462
					inventoryItemCashback += cashback;
23339 ashik.ali 463
				}
23444 amit.gupta 464
				if (inventoryItemCashback > 0) {
465
					totalCashback += inventoryItemCashback;
466
					itemsCount++;
467
				}
22859 ashik.ali 468
			}
23444 amit.gupta 469
 
23511 amit.gupta 470
			LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
23796 amit.gupta 471
			if (itemsCount > 0) {
26684 amit.gupta 472
				walletService.addAmountToWallet(
473
						retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
474
								+ purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
26498 amit.gupta 475
						totalCashback, purchase.getCreateTimestamp());
23796 amit.gupta 476
				LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
477
						purchase.getPurchaseReference(), itemsCount);
23508 amit.gupta 478
				purchase.setCashback(purchase.getCashback() + totalCashback);
479
				purchaseRepository.persist(purchase);
480
			}
22653 ashik.ali 481
		}
482
	}
23444 amit.gupta 483
 
484
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
24562 amit.gupta 485
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
27377 amit.gupta 486
		float amountToCredit = 0;
24581 amit.gupta 487
		if (schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList())
24562 amit.gupta 488
				.size() == 0) {
489
			SchemeInOut schemeInOut = new SchemeInOut();
27377 amit.gupta 490
			amountToCredit = this.getAmount(inventoryItem, scheme);
23443 amit.gupta 491
			schemeInOut.setSchemeId(scheme.getId());
492
			schemeInOut.setInventoryItemId(inventoryItem.getId());
27377 amit.gupta 493
			schemeInOut.setAmount(amountToCredit);
494
			if(scheme.getType().equals(SchemeType.ACTIVATION)) {
495
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
496
				schemeInOut.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
497
				return 0;
27396 amit.gupta 498
			} else if(scheme.getType().equals(SchemeType.INVESTMENT)) {
499
					schemeInOut.setStatus(SchemePayoutStatus.PENDING);
500
					schemeInOut.setStatusDescription("Subject to investment days maintained");
501
					return 0;
27377 amit.gupta 502
			} else {
503
				schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
504
				schemeInOut.setStatusDescription("Credited for sale of IMEI#" + inventoryItem.getSerialNumber());
505
				schemeInOut.setCreditTimestamp(LocalDateTime.now());
506
			}
23443 amit.gupta 507
			schemeInOutRepository.persist(schemeInOut);
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
24976 amit.gupta 680
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
26332 amit.gupta 681
			throws ProfitMandiBusinessException {
26498 amit.gupta 682
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
24976 amit.gupta 683
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
684
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
685
 
686
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
687
			float amountToCredit = 0;
688
			float amountToDebit = 0;
689
			int purchaseId = purchaseEntry.getKey();
690
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
691
 
692
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
693
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
694
 
695
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
27399 amit.gupta 696
			LOGGER.info("Scheme InOuts , {}", schemeInOuts);
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,
826
			int limit) {
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) {
841
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
842
			p3 = cb.in(scheme.get("id")).value(schemeIds);
843
			if (!isAdmin) {
844
 
845
				finalPredicate = cb.and(p1, p2, p3);
846
				query.where(finalPredicate);
847
			} else {
848
				finalPredicate = cb.and(p1, p3);
849
				query.where(finalPredicate);
850
			}
851
		} else {
852
 
853
			if (!isAdmin) {
854
 
855
				finalPredicate = cb.and(p1, p2);
26912 tejbeer 856
				query.where(finalPredicate);
26802 tejbeer 857
			} else {
858
				query.where(p1);
859
			}
860
		}
861
		query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
862
 
863
		return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
864
 
865
	}
866
 
867
	@Override
868
	public long selectSchemeCount(PartnerType partnerType, int itemId, boolean isAdmin) {
869
		Session session = sessionFactory.getCurrentSession();
870
		CriteriaBuilder cb = session.getCriteriaBuilder();
871
		CriteriaQuery<Long> query = cb.createQuery(Long.class);
872
		Root<Scheme> scheme = query.from(Scheme.class);
873
		List<PartnerType> pt = new ArrayList<>();
874
		pt.add(PartnerType.ALL);
875
		pt.add(partnerType);
876
		Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
877
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
878
		Predicate finalPredicate = null;
879
		if (itemId != 0) {
880
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
881
			Predicate p3 = cb.in(scheme.get("id")).value(schemeIds);
882
			if (!isAdmin) {
883
 
884
				finalPredicate = cb.and(p1, p2, p3);
885
				query.select(cb.count(scheme)).where(finalPredicate);
886
			} else {
887
				finalPredicate = cb.and(p1, p3);
888
				query.select(cb.count(scheme)).where(finalPredicate);
889
			}
890
		} else {
891
			if (!isAdmin) {
892
				finalPredicate = cb.and(p1, p2);
893
				query.select(cb.count(scheme)).where(finalPredicate);
894
 
895
			} else {
896
				query.select(cb.count(scheme)).where(p1);
897
 
898
			}
899
		}
900
 
901
		return session.createQuery(query).getSingleResult();
902
 
903
	}
27395 amit.gupta 904
 
905
	@Override
906
	public void processActivation() throws ProfitMandiBusinessException {
907
		List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
908
		List<Integer> schemeIds = new ArrayList<>();
909
		Set<Integer> inventoryIds = new HashSet<>();
910
		for (SchemeInOut pendingPayout: pendingPayouts) {
911
			schemeIds.add(pendingPayout.getSchemeId());
912
			inventoryIds.add(pendingPayout.getInventoryItemId());
913
		}
914
		Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream().collect(Collectors.toMap(x->x.getId(), x->x));
915
		Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream(). collect(Collectors.toMap(x->x.getSerialNumber(), x->x));
916
 
917
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream().collect(Collectors.toMap(x->x.getId(), x->x));
918
		List<ActivatedImei> activatedImeis = activatedImeiRepository.selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet()));
919
 
920
		Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream().collect(Collectors.toMap(x->x.getSerialNumber(), x->x));
921
		for(SchemeInOut pendingPayout : pendingPayouts) {
922
			InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
923
			String serialNumber = ii.getSerialNumber();
924
			ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
925
			if(activatedImei == null) {
926
				continue;
927
			}
928
			Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
929
			if(activatedImei.getActivationTimestamp().isBefore(scheme.getEndDateTime()) 
930
				&& activatedImei.getActivationTimestamp().isAfter(scheme.getStartDateTime())) {
931
				int fofoId = ii.getFofoId();
932
				//Get latest order Id
933
				int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream().filter(x->x.getOrderId() > 0).
934
				sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get().getOrderId();
935
				FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
936
				walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.ACTIVATION_SCHEME, "Activation margin for Imei#" + serialNumber, 
937
						pendingPayout.getAmount(), fofoOrder.getCreateTimestamp());
938
				pendingPayout.setCreditTimestamp(LocalDateTime.now());
939
				pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
940
				pendingPayout.setStatusDescription("Activation margin credited");
941
			} else {
942
				pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
943
				pendingPayout.setStatusDescription("Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
944
			}
945
		}
946
	}
26802 tejbeer 947
 
22653 ashik.ali 948
}