Subversion Repositories SmartDukaan

Rev

Rev 30191 | Rev 30261 | 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
 
30121 amit.gupta 351
	private Map<Integer, Set<Scheme>> toCatalogIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
30186 amit.gupta 352
		Map<Integer, Scheme> schemesMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
353
		Map<Integer, Set<Scheme>> catalogSchemesMap = new HashMap<>();
23444 amit.gupta 354
		for (SchemeItem schemeItem : schemeItems) {
30186 amit.gupta 355
			if (!catalogSchemesMap.containsKey(schemeItem.getCatalogId())) {
356
				catalogSchemesMap.put(schemeItem.getCatalogId(), new HashSet<>());
22859 ashik.ali 357
			}
30186 amit.gupta 358
			Set<Scheme> schemesSet = catalogSchemesMap.get(schemeItem.getCatalogId());
359
			schemesSet.add(schemesMap.get(schemeItem.getSchemeId()));
22859 ashik.ali 360
		}
30186 amit.gupta 361
		return catalogSchemesMap;
22859 ashik.ali 362
	}
22653 ashik.ali 363
 
23444 amit.gupta 364
	private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
29927 amit.gupta 365
																	  List<InventoryItem> inventoryItems) {
30186 amit.gupta 366
		Set<Integer> schemeIds = schemes.stream().map(x -> x.getId()).collect(Collectors.toSet());
30150 amit.gupta 367
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
368
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
369
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndCatalogIds(schemeIds, catalogIds);
23444 amit.gupta 370
 
30186 amit.gupta 371
		Map<Integer, Set<Scheme>> catalogIdSchemesMap = this.toCatalogIdSchemesMap(schemeItems, schemes);
30191 amit.gupta 372
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 373
		for (InventoryItem inventoryItem : inventoryItems) {
30191 amit.gupta 374
			LOGGER.info("inventoryItem {}", inventoryItem);
375
			LOGGER.info("inventoryItem.getItem() {}", inventoryItem.getItem());
376
			LOGGER.info("catalogIdSchemesMap {}", catalogIdSchemesMap);
30186 amit.gupta 377
			if (catalogIdSchemesMap.containsKey(inventoryItem.getItem().getCatalogItemId())) {
30191 amit.gupta 378
				inventoryItemSchemesMap.put(inventoryItem, catalogIdSchemesMap.get(inventoryItem.getItem().getCatalogItemId()));
22859 ashik.ali 379
			}
380
		}
30191 amit.gupta 381
		return inventoryItemSchemesMap;
22859 ashik.ali 382
	}
23444 amit.gupta 383
 
22859 ashik.ali 384
	@Override
23365 ashik.ali 385
	public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
23369 ashik.ali 386
		LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
23344 ashik.ali 387
		Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
29231 amit.gupta 388
		// TODO - SCHEME
389
		PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
390
				YearMonth.from(purchase.getCreateTimestamp()));
391
		// PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
392
		// purchase.getCreateTimestamp().toLocalDate());
393
 
394
		List<Scheme> schemes = schemeRepository.selectActiveAll(Arrays.asList(SchemeType.IN), partnerType,
27898 amit.gupta 395
				purchase.getCreateTimestamp(), false);
396
		float totalCashback = 0;
397
		if (schemes.isEmpty()) {
398
			return;
399
		}
400
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
26332 amit.gupta 401
 
27898 amit.gupta 402
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
30191 amit.gupta 403
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
404
		inventoryItems.stream().forEach(x -> x.setItem(itemsMap.get(x.getItemId())));
405
 
27898 amit.gupta 406
		LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
407
		Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
408
				.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
409
				.collect(Collectors.toSet());
410
		// Only consider inventory items that were not returned
411
		inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
412
				.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
413
				.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
414
		LOGGER.info(inventoryItems);
415
		if (inventoryItems.size() == 0)
416
			return;
417
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
418
				inventoryItems);
23444 amit.gupta 419
 
27898 amit.gupta 420
		if (inventoryItemSchemesMap.isEmpty()) {
421
			return;
422
		}
423
		Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 424
 
27898 amit.gupta 425
		for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
426
			Set<Scheme> allSchemes = new HashSet<>();
427
			for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
428
				allSchemes.add(scheme);
22859 ashik.ali 429
			}
27898 amit.gupta 430
			allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
431
		}
23444 amit.gupta 432
 
27898 amit.gupta 433
		//
26722 amit.gupta 434
 
27898 amit.gupta 435
		int itemsCount = 0;
436
		for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
437
				.entrySet()) {
438
			float inventoryItemCashback = 0;
439
			for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
440
				InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
441
				float cashback = this.createSchemeInOut(scheme, inventoryItem);
442
				inventoryItemCashback += cashback;
22859 ashik.ali 443
			}
27898 amit.gupta 444
			if (inventoryItemCashback > 0) {
445
				totalCashback += inventoryItemCashback;
446
				itemsCount++;
23508 amit.gupta 447
			}
22653 ashik.ali 448
		}
27898 amit.gupta 449
 
450
		LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
451
		if (itemsCount > 0) {
452
			walletService.addAmountToWallet(
453
					retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
454
							+ purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
455
					totalCashback, purchase.getCreateTimestamp());
456
			LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
457
					purchase.getPurchaseReference(), itemsCount);
458
			purchase.setCashback(purchase.getCashback() + totalCashback);
459
			purchaseRepository.persist(purchase);
460
		}
22653 ashik.ali 461
	}
29927 amit.gupta 462
 
29593 amit.gupta 463
	//Only in and activation margins are allowed to be rolled out more than twice
23444 amit.gupta 464
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
29239 amit.gupta 465
		LOGGER.info("Scheme === {}", scheme);
29927 amit.gupta 466
		if ((scheme.getId() == 411 || scheme.getId() == 612) && inventoryItem.getCreateTimestamp().isAfter(LocalDate.of(2021, 12, 1).atStartOfDay())) {
29641 amit.gupta 467
			return 0;
468
		}
29231 amit.gupta 469
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByType(scheme.getType(), inventoryItem.getId());
470
		float actualCredit = 0;
471
		if (sios.stream().filter(x -> x.getRolledBackTimestamp() == null && x.getSchemeId() == scheme.getId())
472
				.collect(Collectors.toList()).size() == 0) {
29927 amit.gupta 473
			sios = sios.stream().filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList());
29249 amit.gupta 474
			//Rejected Scheme for types INVESTMENT and ACTIVATION are considered rolledback only if the item billing is cancelled.
475
			float amountCredited = (float) sios.stream().mapToDouble(e -> e.getAmount()).sum();
29927 amit.gupta 476
 
29243 amit.gupta 477
			LOGGER.info("SIOS ===== {}", sios);
29231 amit.gupta 478
			float amountToCredit = this.getAmount(inventoryItem, scheme);
29593 amit.gupta 479
			//Activation and in scheme
29927 amit.gupta 480
			if (!scheme.getType().equals(SchemeType.IN) && !scheme.getType().equals(SchemeType.ACTIVATION) && sios.size() > 0) {
29231 amit.gupta 481
 
29927 amit.gupta 482
				if (sios.size() > 1) {
29231 amit.gupta 483
					LOGGER.info("SAMESCHEMETYPE has already been credited twice for inventoryItem - {}", inventoryItem.getId());
484
					return 0;
485
				}
29927 amit.gupta 486
				if (amountToCredit > amountCredited + 1f) {
29231 amit.gupta 487
					for (SchemeInOut sio : sios) {
488
						sio.setRolledBackTimestamp(LocalDateTime.now());
489
						sio.setStatus(SchemePayoutStatus.REJECTED);
490
						sio.setStatusDescription("Partner Category upgraded, new entry added");
491
					}
492
					actualCredit = amountToCredit - amountCredited;
493
				} else {
494
					return 0;
495
				}
496
			} else {
497
				actualCredit = amountToCredit;
498
			}
29243 amit.gupta 499
			LOGGER.info("Actual Credit ==== {}", actualCredit);
29927 amit.gupta 500
 
24562 amit.gupta 501
			SchemeInOut schemeInOut = new SchemeInOut();
23443 amit.gupta 502
			schemeInOut.setSchemeId(scheme.getId());
503
			schemeInOut.setInventoryItemId(inventoryItem.getId());
27377 amit.gupta 504
			schemeInOut.setAmount(amountToCredit);
27433 amit.gupta 505
			schemeInOutRepository.persist(schemeInOut);
29231 amit.gupta 506
 
27898 amit.gupta 507
			if (scheme.getType().equals(SchemeType.ACTIVATION)) {
27377 amit.gupta 508
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
509
				schemeInOut.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
510
				return 0;
27898 amit.gupta 511
			} else if (scheme.getType().equals(SchemeType.INVESTMENT)) {
512
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
513
				schemeInOut.setStatusDescription("Subject to investment days maintained");
514
				return 0;
27377 amit.gupta 515
			} else {
516
				schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
27898 amit.gupta 517
				if (scheme.getType().equals(SchemeType.IN)) {
27713 amit.gupta 518
					schemeInOut.setStatusDescription("Credited for GRN of IMEI#" + inventoryItem.getSerialNumber());
29231 amit.gupta 519
				} else if (SchemeService.OUT_SCHEME_TYPES.contains(scheme.getType())) {
28737 amit.gupta 520
					schemeInOut.setStatusDescription("Credited for sale of IMEI#" + inventoryItem.getSerialNumber());
27713 amit.gupta 521
				}
27377 amit.gupta 522
				schemeInOut.setCreditTimestamp(LocalDateTime.now());
523
			}
23443 amit.gupta 524
		}
29231 amit.gupta 525
		return actualCredit;
22859 ashik.ali 526
	}
23444 amit.gupta 527
 
25049 amit.gupta 528
	// We are maintaining price drop after grn
23444 amit.gupta 529
	private float getAmount(InventoryItem inventoryItem, Scheme scheme) {
22653 ashik.ali 530
		float amount = 0;
25049 amit.gupta 531
		float dpForCalc = 0;
532
		float taxableSellingPrice = 0;
26684 amit.gupta 533
		// float totalTaxRate = inventoryItem.getIgstRate() +
534
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
535
		// Hardcoding it to 18%
26568 amit.gupta 536
		float totalTaxRate = 18f;
26684 amit.gupta 537
		// float totalTaxRate = inventoryItem.getIgstRate() +
538
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
23527 ashik.ali 539
		if (scheme.getAmountType() == AmountType.PERCENTAGE) {
24562 amit.gupta 540
			if (scheme.getType().equals(SchemeType.IN)) {
25049 amit.gupta 541
				dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
23995 amit.gupta 542
			} else {
543
				try {
26684 amit.gupta 544
					dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
26550 amit.gupta 545
							tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
24562 amit.gupta 546
				} catch (Exception e) {
23995 amit.gupta 547
					LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
548
					e.printStackTrace();
549
				}
550
			}
25049 amit.gupta 551
			taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
22859 ashik.ali 552
			amount = taxableSellingPrice * scheme.getAmount() / 100;
25517 amit.gupta 553
			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 554
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 555
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
556
					scheme.getAmount(), amount));
23444 amit.gupta 557
		} else {
22653 ashik.ali 558
			amount = scheme.getAmount();
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%d\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
					0, amount));
22653 ashik.ali 563
		}
25049 amit.gupta 564
 
22859 ashik.ali 565
		return amount;
22653 ashik.ali 566
	}
23444 amit.gupta 567
 
22653 ashik.ali 568
	@Override
23365 ashik.ali 569
	public void processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
570
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
29231 amit.gupta 571
		// Process only if order is not cancelled
572
		if (fofoOrder.getCancelledTimestamp() == null) {
573
			// PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
574
			// fofoOrder.getCreateTimestamp().toLocalDate());
575
			// TODO - SCHEME
576
			PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
577
					YearMonth.from(fofoOrder.getCreateTimestamp()));
578
 
28969 amit.gupta 579
			List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
580
			Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
581
					.collect(Collectors.toSet());
582
			Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
583
					.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
584
					.collect(Collectors.toSet());
585
			if (inventoryItems.size() == 0) {
586
				return;
22653 ashik.ali 587
			}
28969 amit.gupta 588
			Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
29231 amit.gupta 589
 
590
			// Remove Items that are eol now.
28969 amit.gupta 591
			Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
592
					.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(fofoOrder.getCreateTimestamp()))
593
					.map(x -> x.getItemId()).collect(Collectors.toSet());
594
			// Only consider inventory items that were not returned
595
			inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
596
					.collect(Collectors.toSet());
29231 amit.gupta 597
 
28969 amit.gupta 598
			if (inventoryItems.size() == 0) {
599
				return;
22859 ashik.ali 600
			}
29231 amit.gupta 601
 
28969 amit.gupta 602
			float totalCashback = 0;
603
			int count = 0;
29231 amit.gupta 604
 
605
			List<SchemeType> allOutSchemeTypes = new ArrayList<>();
606
			allOutSchemeTypes.addAll(Arrays.asList(SchemeType.ACTIVATION, SchemeType.INVESTMENT));
607
			allOutSchemeTypes.addAll(OUT_SCHEME_TYPES);
608
 
609
			List<Scheme> allActiveSchemes = schemeRepository.selectActiveAll(allOutSchemeTypes, partnerType,
28969 amit.gupta 610
					fofoOrder.getCreateTimestamp(), false);
29231 amit.gupta 611
 
28969 amit.gupta 612
			for (InventoryItem inventoryItem : inventoryItems) {
613
				float itemCashback = 0;
614
				Set<Integer> schemeIds = new HashSet<>(
30121 amit.gupta 615
						schemeItemRepository.selectSchemeIdByCatalogId(inventoryItem.getItem().getCatalogItemId()));
29231 amit.gupta 616
				List<Scheme> itemActiveSchemes = allActiveSchemes.stream().filter(x -> schemeIds.contains(x.getId()))
28969 amit.gupta 617
						.collect(Collectors.toList());
29231 amit.gupta 618
				for (Scheme scheme : itemActiveSchemes) {
29239 amit.gupta 619
					LOGGER.info("Scheme ==== {}", scheme);
28969 amit.gupta 620
					itemCashback += this.createSchemeInOut(scheme, inventoryItem);
621
				}
29240 amit.gupta 622
				LOGGER.info("itemCashback ==== {}", itemCashback);
28969 amit.gupta 623
				if (itemCashback > 0) {
624
					count++;
625
					totalCashback += itemCashback;
626
				}
627
			}
628
			if (count > 0) {
29231 amit.gupta 629
				walletService.addAmountToWallet(
630
						retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT, "Sales margin for invoice number "
631
								+ fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
28969 amit.gupta 632
						totalCashback, fofoOrder.getCreateTimestamp());
633
				fofoOrder.setCashback(totalCashback);
634
			}
22653 ashik.ali 635
		}
636
	}
23444 amit.gupta 637
 
23508 amit.gupta 638
	@Override
23796 amit.gupta 639
	public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
640
			throws Exception {
23638 amit.gupta 641
		Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
23508 amit.gupta 642
		float amountToRollback = 0;
643
		List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
23796 amit.gupta 644
		for (SchemeInOut schemeInOut : schemes) {
23983 amit.gupta 645
			if (schemeInOut.getRolledBackTimestamp() == null) {
646
				schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
29231 amit.gupta 647
				if (schemeInOut.getStatus() == null || schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
27377 amit.gupta 648
					amountToRollback += schemeInOut.getAmount();
649
				}
650
				schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
651
				schemeInOut.setStatusDescription(rollbackReason);
23983 amit.gupta 652
			}
23508 amit.gupta 653
		}
23983 amit.gupta 654
		if (amountToRollback > 0) {
23638 amit.gupta 655
			int inventoryItemId = inventoryItemIds.get(0);
26498 amit.gupta 656
			InventoryItem ii = inventoryItemRepository.selectById(inventoryItemId);
657
			Integer fofoId = ii.getFofoId();
27898 amit.gupta 658
			// Purchase p = purchaseRepository.selectById(ii.getPurchaseId());
26684 amit.gupta 659
			// TODO//
26693 amit.gupta 660
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, ii.getPurchaseId(),
26498 amit.gupta 661
					WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
23638 amit.gupta 662
		}
23508 amit.gupta 663
	}
23884 amit.gupta 664
 
23781 ashik.ali 665
	@Override
23796 amit.gupta 666
	public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
667
			throws ProfitMandiBusinessException {
23781 ashik.ali 668
		Map<String, Object> map = new HashMap<>();
669
		List<Scheme> schemes = null;
670
		long size = 0;
23798 amit.gupta 671
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 672
			schemes = schemeRepository.selectAll(offset, limit);
673
			size = schemeRepository.selectAllCount();
23796 amit.gupta 674
		} else {
23781 ashik.ali 675
			schemes = schemeRepository.selectActiveAll(offset, limit);
676
			size = schemeRepository.selectAllActiveCount();
677
		}
678
		map.put("schemes", schemes);
679
		map.put("start", offset + 1);
680
		map.put("size", size);
23796 amit.gupta 681
		if (schemes.size() < limit) {
23781 ashik.ali 682
			map.put("end", offset + schemes.size());
23796 amit.gupta 683
		} else {
23781 ashik.ali 684
			map.put("end", offset + limit);
685
		}
686
		return map;
687
	}
23796 amit.gupta 688
 
23781 ashik.ali 689
	@Override
23796 amit.gupta 690
	public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
691
			throws ProfitMandiBusinessException {
23781 ashik.ali 692
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
693
		List<Scheme> schemes = null;
23798 amit.gupta 694
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 695
			schemes = schemeRepository.selectAll(offset, limit);
23796 amit.gupta 696
		} else {
23781 ashik.ali 697
			schemes = schemeRepository.selectActiveAll(offset, limit);
698
		}
699
		return schemes;
700
	}
23508 amit.gupta 701
 
23968 amit.gupta 702
	@Override
27898 amit.gupta 703
	// This is being called to reverse schemes while processing price Drop
24976 amit.gupta 704
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
26332 amit.gupta 705
			throws ProfitMandiBusinessException {
26498 amit.gupta 706
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
24976 amit.gupta 707
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
708
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
709
 
710
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
711
			float amountToCredit = 0;
712
			float amountToDebit = 0;
713
			int purchaseId = purchaseEntry.getKey();
714
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
715
 
716
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
717
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
718
 
719
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
27399 amit.gupta 720
			LOGGER.info("Scheme InOuts , {}", schemeInOuts);
27898 amit.gupta 721
			if (schemeInOuts.size() == 0) {
27400 amit.gupta 722
				continue;
723
			}
24976 amit.gupta 724
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
725
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
726
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
727
			for (SchemeInOut schemeInOut : schemeInOuts) {
728
				InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
729
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
730
				if (scheme.getAmountType().equals(AmountType.FIXED)) {
731
					continue;
23995 amit.gupta 732
				}
27713 amit.gupta 733
				if (scheme.getType().equals(SchemeType.IN) && schemeInOut.getRolledBackTimestamp() == null) {
24976 amit.gupta 734
					float newAmount = getAmount(ii, scheme);
735
					if (schemeInOut.getAmount() - newAmount >= 0.01f) {
736
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
27898 amit.gupta 737
 
24976 amit.gupta 738
						SchemeInOut sioNew = new SchemeInOut();
739
						sioNew.setAmount(newAmount);
27713 amit.gupta 740
						sioNew.setStatus(schemeInOut.getStatus());
741
						sioNew.setStatusDescription(schemeInOut.getStatusDescription());
24976 amit.gupta 742
						sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
743
						sioNew.setSchemeId(schemeInOut.getSchemeId());
744
						schemeInOutRepository.persist(sioNew);
27713 amit.gupta 745
 
746
						schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
747
						schemeInOut.setStatusDescription("Pricedrop processed, new entries added");
27898 amit.gupta 748
						// IF not credited then dont consider any credit/debit for that sio entry
749
						if (schemeInOut.getCreditTimestamp() != null) {
27713 amit.gupta 750
							amountToCredit += sioNew.getAmount();
751
							amountToDebit += schemeInOut.getAmount();
752
						}
24976 amit.gupta 753
					}
24562 amit.gupta 754
 
24976 amit.gupta 755
				}
23986 amit.gupta 756
			}
24976 amit.gupta 757
			int fofoId = inventoryItems.get(0).getFofoId();
758
			if (amountToDebit > 0) {
26684 amit.gupta 759
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
760
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
761
						priceDrop.getAffectedOn());
24976 amit.gupta 762
			}
763
			if (amountToCredit > 0) {
26403 amit.gupta 764
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
26684 amit.gupta 765
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), amountToCredit,
766
						priceDrop.getAffectedOn());
24976 amit.gupta 767
			}
23968 amit.gupta 768
		}
769
	}
24562 amit.gupta 770
 
24264 amit.gupta 771
	@Override
29593 amit.gupta 772
	// Always being called from cancel order/bad return means no SCHEME IN is considered
24562 amit.gupta 773
	public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
29927 amit.gupta 774
							   List<SchemeType> schemeTypes) throws ProfitMandiBusinessException {
24264 amit.gupta 775
		Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
28419 tejbeer 776
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
28417 tejbeer 777
		LOGGER.info("inventoryItems" + inventoryItems);
778
 
24264 amit.gupta 779
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
28416 tejbeer 780
		LOGGER.info("schemeInOuts" + schemeInOuts);
28417 tejbeer 781
		float amountToRollback = 0;
28416 tejbeer 782
 
28417 tejbeer 783
		if (!schemeInOuts.isEmpty()) {
784
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
785
			LOGGER.info("schemeIds" + schemeIds);
28416 tejbeer 786
 
28417 tejbeer 787
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
788
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
789
			for (SchemeInOut schemeInOut : schemeInOuts) {
790
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
29231 amit.gupta 791
				if (schemeTypes.contains(scheme.getType())) {
28417 tejbeer 792
					if (schemeInOut.getRolledBackTimestamp() == null) {
793
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
794
						if (schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
795
							amountToRollback += schemeInOut.getAmount();
796
						}
797
						schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
798
						schemeInOut.setStatusDescription(reversalReason);
27377 amit.gupta 799
					}
24264 amit.gupta 800
				}
801
			}
28417 tejbeer 802
 
24264 amit.gupta 803
		}
804
		int fofoId = inventoryItems.get(0).getFofoId();
29231 amit.gupta 805
		WalletReferenceType walletReferenceType = schemeTypes.containsAll(SchemeService.OUT_SCHEME_TYPES)
806
				? WalletReferenceType.SCHEME_OUT
807
				: (schemeTypes.contains(SchemeType.ACTIVATION) ? WalletReferenceType.ACTIVATION_SCHEME
29927 amit.gupta 808
				: WalletReferenceType.INVESTMENT_PAYOUT);
27377 amit.gupta 809
		if (amountToRollback > 0) {
29231 amit.gupta 810
			// Mark appropriate reference of rollback investment margin
811
			if (schemeTypes.contains(SchemeType.INVESTMENT)) {
812
				reversalReference = Integer
29664 amit.gupta 813
						.parseInt(FormattingUtils.getYearMonth(schemeInOuts.get(0).getCreditTimestamp().minusMonths(1)));
29231 amit.gupta 814
			}
27377 amit.gupta 815
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, reversalReference, walletReferenceType,
26498 amit.gupta 816
					reversalReason, LocalDateTime.now());
24268 amit.gupta 817
		}
24264 amit.gupta 818
	}
23968 amit.gupta 819
 
26332 amit.gupta 820
	@Override
821
	public double getTotalMargin(int itemId, PartnerType partnerType, LocalDateTime dateTime) {
822
		Session session = sessionFactory.getCurrentSession();
823
		CriteriaBuilder cb = session.getCriteriaBuilder();
824
		CriteriaQuery<Double> criteriaQuery = cb.createQuery(Double.class);
825
		Root<SchemeItem> schemeItem = criteriaQuery.from(SchemeItem.class);
826
		Root<Scheme> scheme = criteriaQuery.from(Scheme.class);
827
		Predicate schemePredicate = cb.equal(scheme.get(ProfitMandiConstants.AMOUNT_TYPE), AmountType.PERCENTAGE);
828
		Predicate lessThanPredicate = cb.lessThanOrEqualTo(scheme.get(ProfitMandiConstants.END_DATE_TIME), dateTime);
829
		Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(scheme.get(ProfitMandiConstants.START_DATE_TIME),
830
				dateTime);
831
		Predicate joinPredicate = cb.equal(scheme.get("id"), schemeItem.get("schemeId"));
832
		Predicate schemeItemPredicate = cb.equal(schemeItem.get(ProfitMandiConstants.ITEM_ID), itemId);
833
		criteriaQuery.select(cb.sum(scheme.get(ProfitMandiConstants.AMOUNT))).where(schemePredicate, lessThanPredicate,
834
				greaterThanPredicate, schemeItemPredicate, joinPredicate);
835
 
836
		Query<Double> query = session.createQuery(criteriaQuery);
837
		return query.getSingleResult() + ProfitMandiConstants.SCHEME_INVESTMENT_MARGIN;
838
 
839
	}
840
 
26684 amit.gupta 841
	@Override
842
	@Cacheable(value = "itemSchemeCashback", cacheManager = "timeoutCacheManager")
30121 amit.gupta 843
	public Map<Integer, Float> getCatalogSchemeCashBack() {
26684 amit.gupta 844
		Map<Integer, Float> itemCashbackMap = new HashMap<>();
845
		Map<Integer, Scheme> cashbackSchemesMap = schemeRepository
30005 amit.gupta 846
				.selectActiveAll(Arrays.asList(SchemeType.ACTIVATION), PartnerType.ALL, LocalDateTime.now(), false)
29231 amit.gupta 847
				.stream().filter(x -> x.getAmountType().equals(AmountType.FIXED))
26684 amit.gupta 848
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
26722 amit.gupta 849
		if (cashbackSchemesMap.size() > 0) {
26713 amit.gupta 850
			List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(cashbackSchemesMap.keySet());
851
			schemeItems.stream().forEach(x -> {
29864 amit.gupta 852
				float cashbackAmount = cashbackSchemesMap.get(x.getSchemeId()).getAmount();
30121 amit.gupta 853
				if (!itemCashbackMap.containsKey(x.getCatalogId())) {
854
					itemCashbackMap.put(x.getCatalogId(), cashbackAmount);
29864 amit.gupta 855
				} else {
30121 amit.gupta 856
					itemCashbackMap.put(x.getCatalogId(), itemCashbackMap.get(x.getCatalogId()) + cashbackAmount);
29864 amit.gupta 857
				}
26713 amit.gupta 858
			});
859
		}
26722 amit.gupta 860
		// A107FD Model needs to removed
26703 amit.gupta 861
		itemCashbackMap.remove(30211);
862
		itemCashbackMap.remove(30212);
863
		itemCashbackMap.remove(30213);
864
		itemCashbackMap.remove(30756);
26684 amit.gupta 865
		return itemCashbackMap;
866
	}
867
 
24976 amit.gupta 868
	/*
869
	 * @Override public void updateSchmesForModel(int catalogId) throws
870
	 * ProfitMandiBusinessException { List<Item> items =
871
	 * itemRepository.selectAllByCatalogItemId(catalogId); Map<Integer, Scheme>
872
	 * schemes = schemeRepository .selectAllByItemIds(items.stream().map(x ->
873
	 * x.getId()).collect(Collectors.toList()));
29927 amit.gupta 874
	 *
24976 amit.gupta 875
	 * }
876
	 */
24562 amit.gupta 877
 
26802 tejbeer 878
	@Override
30121 amit.gupta 879
	public List<Scheme> selectSchemeByPartnerType(PartnerType partnerType, LocalDate onDate, int catalogId,
29927 amit.gupta 880
												  boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
26802 tejbeer 881
		Session session = sessionFactory.getCurrentSession();
30253 amit.gupta 882
		List<Predicate> andPredicates = new ArrayList<>();
26802 tejbeer 883
		CriteriaBuilder cb = session.getCriteriaBuilder();
884
		CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
885
		Root<Scheme> scheme = query.from(Scheme.class);
30153 amit.gupta 886
		if (!partnerType.equals(PartnerType.ALL)) {
30121 amit.gupta 887
			List<PartnerType> pt = new ArrayList<>();
888
			pt.add(PartnerType.ALL);
889
			pt.add(partnerType);
30253 amit.gupta 890
			andPredicates.add(cb.in(scheme.get("partnerType")).value(pt));
30121 amit.gupta 891
		}
26802 tejbeer 892
		cb.desc(cb.isNull(scheme.get("expireTimestamp")));
30121 amit.gupta 893
		if (catalogId > 0) {
27898 amit.gupta 894
 
30121 amit.gupta 895
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByCatalogId(catalogId);
27424 tejbeer 896
			LOGGER.info("schemeId" + schemeIds);
27898 amit.gupta 897
			if (schemeIds.isEmpty()) {
27424 tejbeer 898
				return new ArrayList<>();
899
			}
30253 amit.gupta 900
			andPredicates.add(cb.in(scheme.get("id")).value(schemeIds));
30121 amit.gupta 901
			if (onDate != null) {
30253 amit.gupta 902
				andPredicates.add(cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()));
903
				andPredicates.add(cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
26802 tejbeer 904
			}
905
		}
30253 amit.gupta 906
		if (!isAdmin) {
907
			andPredicates.add(cb.isNotNull(scheme.get("activeTimestamp")));
908
		}
909
		query.where(cb.and(andPredicates.toArray(new Predicate[0])));
26802 tejbeer 910
		query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
911
 
912
		return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
913
 
914
	}
915
 
916
	@Override
27395 amit.gupta 917
	public void processActivation() throws ProfitMandiBusinessException {
918
		List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
919
		List<Integer> schemeIds = new ArrayList<>();
920
		Set<Integer> inventoryIds = new HashSet<>();
27898 amit.gupta 921
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 922
			schemeIds.add(pendingPayout.getSchemeId());
27440 amit.gupta 923
		}
924
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream()
27898 amit.gupta 925
				.filter(x -> x.getType().equals(SchemeType.ACTIVATION))
926
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
927
		pendingPayouts = pendingPayouts.stream().filter(x -> schemesMap.get(x.getSchemeId()) != null)
928
				.collect(Collectors.toList());
27440 amit.gupta 929
 
27898 amit.gupta 930
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 931
			inventoryIds.add(pendingPayout.getInventoryItemId());
932
		}
27898 amit.gupta 933
		Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
934
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
935
		Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream()
936
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
937
 
938
		List<ActivatedImei> activatedImeis = activatedImeiRepository
939
				.selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet()));
940
 
941
		Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream()
942
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
943
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 944
			InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
945
			String serialNumber = ii.getSerialNumber();
946
			ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
27898 amit.gupta 947
			if (activatedImei == null) {
27395 amit.gupta 948
				continue;
949
			}
950
			Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
27898 amit.gupta 951
			if (activatedImei.getActivationTimestamp().isBefore(scheme.getEndDateTime())
952
					&& activatedImei.getActivationTimestamp().isAfter(scheme.getStartDateTime())) {
27395 amit.gupta 953
				int fofoId = ii.getFofoId();
27898 amit.gupta 954
				// Get latest order Id
955
				int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream()
956
						.filter(x -> x.getOrderId() > 0)
957
						.sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get()
958
						.getOrderId();
27395 amit.gupta 959
				FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
27898 amit.gupta 960
				walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.ACTIVATION_SCHEME,
961
						"Activation margin for Imei#" + serialNumber, pendingPayout.getAmount(),
962
						fofoOrder.getCreateTimestamp());
27395 amit.gupta 963
				pendingPayout.setCreditTimestamp(LocalDateTime.now());
964
				pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
965
				pendingPayout.setStatusDescription("Activation margin credited");
966
			} else {
967
				pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
27898 amit.gupta 968
				pendingPayout.setRolledBackTimestamp(LocalDateTime.now());
969
				;
970
				pendingPayout.setStatusDescription(
971
						"Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
27395 amit.gupta 972
			}
973
		}
974
	}
26802 tejbeer 975
 
22653 ashik.ali 976
}