Subversion Repositories SmartDukaan

Rev

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