Subversion Repositories SmartDukaan

Rev

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