Subversion Repositories SmartDukaan

Rev

Rev 30150 | Rev 30186 | 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) {
23019 ashik.ali 352
		Map<Integer, Scheme> schemeIdSchemesMap = this.toSchemeIdSchemeMap(schemes);
30121 amit.gupta 353
		Map<Integer, Set<Scheme>> catalogIdSchemesMap = new HashMap<>();
23444 amit.gupta 354
		for (SchemeItem schemeItem : schemeItems) {
30121 amit.gupta 355
			if (!catalogIdSchemesMap.containsKey(schemeItem.getCatalogId())) {
22859 ashik.ali 356
				Set<Scheme> schemesSet = new HashSet<>();
357
				schemesSet.add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
30121 amit.gupta 358
				catalogIdSchemesMap.put(schemeItem.getCatalogId(), schemesSet);
23444 amit.gupta 359
			} else {
30121 amit.gupta 360
				catalogIdSchemesMap.get(schemeItem.getCatalogId()).add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
22859 ashik.ali 361
			}
362
		}
30121 amit.gupta 363
		return catalogIdSchemesMap;
22859 ashik.ali 364
	}
22653 ashik.ali 365
 
23444 amit.gupta 366
	private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
29927 amit.gupta 367
																	  List<InventoryItem> inventoryItems) {
22859 ashik.ali 368
		Set<Integer> schemeIds = new HashSet<>();
23444 amit.gupta 369
		for (Scheme scheme : schemes) {
22859 ashik.ali 370
			schemeIds.add(scheme.getId());
371
		}
30150 amit.gupta 372
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
373
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
374
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndCatalogIds(schemeIds, catalogIds);
23444 amit.gupta 375
 
30121 amit.gupta 376
		Map<Integer, Set<Scheme>> itemIdSchemesMap = this.toCatalogIdSchemesMap(schemeItems, schemes);
22859 ashik.ali 377
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemsMap = new HashMap<>();
23444 amit.gupta 378
		for (InventoryItem inventoryItem : inventoryItems) {
379
			if (itemIdSchemesMap.containsKey(inventoryItem.getItemId())) {
22859 ashik.ali 380
				inventoryItemSchemsMap.put(inventoryItem, itemIdSchemesMap.get(inventoryItem.getItemId()));
381
			}
382
		}
383
		return inventoryItemSchemsMap;
384
	}
23444 amit.gupta 385
 
22859 ashik.ali 386
	@Override
23365 ashik.ali 387
	public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
23369 ashik.ali 388
		LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
23344 ashik.ali 389
		Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
29231 amit.gupta 390
		// TODO - SCHEME
391
		PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
392
				YearMonth.from(purchase.getCreateTimestamp()));
393
		// PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
394
		// purchase.getCreateTimestamp().toLocalDate());
395
 
396
		List<Scheme> schemes = schemeRepository.selectActiveAll(Arrays.asList(SchemeType.IN), partnerType,
27898 amit.gupta 397
				purchase.getCreateTimestamp(), false);
398
		float totalCashback = 0;
399
		if (schemes.isEmpty()) {
400
			return;
401
		}
402
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
26332 amit.gupta 403
 
27898 amit.gupta 404
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
405
		LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
406
		Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
407
				.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
408
				.collect(Collectors.toSet());
409
		// Only consider inventory items that were not returned
410
		inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
411
				.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
412
				.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
413
		LOGGER.info(inventoryItems);
414
		if (inventoryItems.size() == 0)
415
			return;
416
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
417
				inventoryItems);
23444 amit.gupta 418
 
27898 amit.gupta 419
		if (inventoryItemSchemesMap.isEmpty()) {
420
			return;
421
		}
422
		Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 423
 
27898 amit.gupta 424
		for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
425
			Set<Scheme> allSchemes = new HashSet<>();
426
			for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
427
				allSchemes.add(scheme);
22859 ashik.ali 428
			}
27898 amit.gupta 429
			allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
430
		}
23444 amit.gupta 431
 
27898 amit.gupta 432
		//
26722 amit.gupta 433
 
27898 amit.gupta 434
		int itemsCount = 0;
435
		for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
436
				.entrySet()) {
437
			float inventoryItemCashback = 0;
438
			for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
439
				InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
440
				float cashback = this.createSchemeInOut(scheme, inventoryItem);
441
				inventoryItemCashback += cashback;
22859 ashik.ali 442
			}
27898 amit.gupta 443
			if (inventoryItemCashback > 0) {
444
				totalCashback += inventoryItemCashback;
445
				itemsCount++;
23508 amit.gupta 446
			}
22653 ashik.ali 447
		}
27898 amit.gupta 448
 
449
		LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
450
		if (itemsCount > 0) {
451
			walletService.addAmountToWallet(
452
					retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
453
							+ purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
454
					totalCashback, purchase.getCreateTimestamp());
455
			LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
456
					purchase.getPurchaseReference(), itemsCount);
457
			purchase.setCashback(purchase.getCashback() + totalCashback);
458
			purchaseRepository.persist(purchase);
459
		}
22653 ashik.ali 460
	}
29927 amit.gupta 461
 
29593 amit.gupta 462
	//Only in and activation margins are allowed to be rolled out more than twice
23444 amit.gupta 463
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
29239 amit.gupta 464
		LOGGER.info("Scheme === {}", scheme);
29927 amit.gupta 465
		if ((scheme.getId() == 411 || scheme.getId() == 612) && inventoryItem.getCreateTimestamp().isAfter(LocalDate.of(2021, 12, 1).atStartOfDay())) {
29641 amit.gupta 466
			return 0;
467
		}
29231 amit.gupta 468
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByType(scheme.getType(), inventoryItem.getId());
469
		float actualCredit = 0;
470
		if (sios.stream().filter(x -> x.getRolledBackTimestamp() == null && x.getSchemeId() == scheme.getId())
471
				.collect(Collectors.toList()).size() == 0) {
29927 amit.gupta 472
			sios = sios.stream().filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList());
29249 amit.gupta 473
			//Rejected Scheme for types INVESTMENT and ACTIVATION are considered rolledback only if the item billing is cancelled.
474
			float amountCredited = (float) sios.stream().mapToDouble(e -> e.getAmount()).sum();
29927 amit.gupta 475
 
29243 amit.gupta 476
			LOGGER.info("SIOS ===== {}", sios);
29231 amit.gupta 477
			float amountToCredit = this.getAmount(inventoryItem, scheme);
29593 amit.gupta 478
			//Activation and in scheme
29927 amit.gupta 479
			if (!scheme.getType().equals(SchemeType.IN) && !scheme.getType().equals(SchemeType.ACTIVATION) && sios.size() > 0) {
29231 amit.gupta 480
 
29927 amit.gupta 481
				if (sios.size() > 1) {
29231 amit.gupta 482
					LOGGER.info("SAMESCHEMETYPE has already been credited twice for inventoryItem - {}", inventoryItem.getId());
483
					return 0;
484
				}
29927 amit.gupta 485
				if (amountToCredit > amountCredited + 1f) {
29231 amit.gupta 486
					for (SchemeInOut sio : sios) {
487
						sio.setRolledBackTimestamp(LocalDateTime.now());
488
						sio.setStatus(SchemePayoutStatus.REJECTED);
489
						sio.setStatusDescription("Partner Category upgraded, new entry added");
490
					}
491
					actualCredit = amountToCredit - amountCredited;
492
				} else {
493
					return 0;
494
				}
495
			} else {
496
				actualCredit = amountToCredit;
497
			}
29243 amit.gupta 498
			LOGGER.info("Actual Credit ==== {}", actualCredit);
29927 amit.gupta 499
 
24562 amit.gupta 500
			SchemeInOut schemeInOut = new SchemeInOut();
23443 amit.gupta 501
			schemeInOut.setSchemeId(scheme.getId());
502
			schemeInOut.setInventoryItemId(inventoryItem.getId());
27377 amit.gupta 503
			schemeInOut.setAmount(amountToCredit);
27433 amit.gupta 504
			schemeInOutRepository.persist(schemeInOut);
29231 amit.gupta 505
 
27898 amit.gupta 506
			if (scheme.getType().equals(SchemeType.ACTIVATION)) {
27377 amit.gupta 507
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
508
				schemeInOut.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
509
				return 0;
27898 amit.gupta 510
			} else if (scheme.getType().equals(SchemeType.INVESTMENT)) {
511
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
512
				schemeInOut.setStatusDescription("Subject to investment days maintained");
513
				return 0;
27377 amit.gupta 514
			} else {
515
				schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
27898 amit.gupta 516
				if (scheme.getType().equals(SchemeType.IN)) {
27713 amit.gupta 517
					schemeInOut.setStatusDescription("Credited for GRN of IMEI#" + inventoryItem.getSerialNumber());
29231 amit.gupta 518
				} else if (SchemeService.OUT_SCHEME_TYPES.contains(scheme.getType())) {
28737 amit.gupta 519
					schemeInOut.setStatusDescription("Credited for sale of IMEI#" + inventoryItem.getSerialNumber());
27713 amit.gupta 520
				}
27377 amit.gupta 521
				schemeInOut.setCreditTimestamp(LocalDateTime.now());
522
			}
23443 amit.gupta 523
		}
29231 amit.gupta 524
		return actualCredit;
22859 ashik.ali 525
	}
23444 amit.gupta 526
 
25049 amit.gupta 527
	// We are maintaining price drop after grn
23444 amit.gupta 528
	private float getAmount(InventoryItem inventoryItem, Scheme scheme) {
22653 ashik.ali 529
		float amount = 0;
25049 amit.gupta 530
		float dpForCalc = 0;
531
		float taxableSellingPrice = 0;
26684 amit.gupta 532
		// float totalTaxRate = inventoryItem.getIgstRate() +
533
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
534
		// Hardcoding it to 18%
26568 amit.gupta 535
		float totalTaxRate = 18f;
26684 amit.gupta 536
		// float totalTaxRate = inventoryItem.getIgstRate() +
537
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
23527 ashik.ali 538
		if (scheme.getAmountType() == AmountType.PERCENTAGE) {
24562 amit.gupta 539
			if (scheme.getType().equals(SchemeType.IN)) {
25049 amit.gupta 540
				dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
23995 amit.gupta 541
			} else {
542
				try {
26684 amit.gupta 543
					dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
26550 amit.gupta 544
							tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
24562 amit.gupta 545
				} catch (Exception e) {
23995 amit.gupta 546
					LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
547
					e.printStackTrace();
548
				}
549
			}
25049 amit.gupta 550
			taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
22859 ashik.ali 551
			amount = taxableSellingPrice * scheme.getAmount() / 100;
25517 amit.gupta 552
			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 553
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 554
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
555
					scheme.getAmount(), amount));
23444 amit.gupta 556
		} else {
22653 ashik.ali 557
			amount = scheme.getAmount();
25517 amit.gupta 558
			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 559
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 560
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
561
					0, amount));
22653 ashik.ali 562
		}
25049 amit.gupta 563
 
22859 ashik.ali 564
		return amount;
22653 ashik.ali 565
	}
23444 amit.gupta 566
 
22653 ashik.ali 567
	@Override
23365 ashik.ali 568
	public void processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
569
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
29231 amit.gupta 570
		// Process only if order is not cancelled
571
		if (fofoOrder.getCancelledTimestamp() == null) {
572
			// PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
573
			// fofoOrder.getCreateTimestamp().toLocalDate());
574
			// TODO - SCHEME
575
			PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
576
					YearMonth.from(fofoOrder.getCreateTimestamp()));
577
 
28969 amit.gupta 578
			List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
579
			Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
580
					.collect(Collectors.toSet());
581
			Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
582
					.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
583
					.collect(Collectors.toSet());
584
			if (inventoryItems.size() == 0) {
585
				return;
22653 ashik.ali 586
			}
28969 amit.gupta 587
			Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
29231 amit.gupta 588
 
589
			// Remove Items that are eol now.
28969 amit.gupta 590
			Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
591
					.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(fofoOrder.getCreateTimestamp()))
592
					.map(x -> x.getItemId()).collect(Collectors.toSet());
593
			// Only consider inventory items that were not returned
594
			inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
595
					.collect(Collectors.toSet());
29231 amit.gupta 596
 
28969 amit.gupta 597
			if (inventoryItems.size() == 0) {
598
				return;
22859 ashik.ali 599
			}
29231 amit.gupta 600
 
28969 amit.gupta 601
			float totalCashback = 0;
602
			int count = 0;
29231 amit.gupta 603
 
604
			List<SchemeType> allOutSchemeTypes = new ArrayList<>();
605
			allOutSchemeTypes.addAll(Arrays.asList(SchemeType.ACTIVATION, SchemeType.INVESTMENT));
606
			allOutSchemeTypes.addAll(OUT_SCHEME_TYPES);
607
 
608
			List<Scheme> allActiveSchemes = schemeRepository.selectActiveAll(allOutSchemeTypes, partnerType,
28969 amit.gupta 609
					fofoOrder.getCreateTimestamp(), false);
29231 amit.gupta 610
 
28969 amit.gupta 611
			for (InventoryItem inventoryItem : inventoryItems) {
612
				float itemCashback = 0;
613
				Set<Integer> schemeIds = new HashSet<>(
30121 amit.gupta 614
						schemeItemRepository.selectSchemeIdByCatalogId(inventoryItem.getItem().getCatalogItemId()));
29231 amit.gupta 615
				List<Scheme> itemActiveSchemes = allActiveSchemes.stream().filter(x -> schemeIds.contains(x.getId()))
28969 amit.gupta 616
						.collect(Collectors.toList());
29231 amit.gupta 617
				for (Scheme scheme : itemActiveSchemes) {
29239 amit.gupta 618
					LOGGER.info("Scheme ==== {}", scheme);
28969 amit.gupta 619
					itemCashback += this.createSchemeInOut(scheme, inventoryItem);
620
				}
29240 amit.gupta 621
				LOGGER.info("itemCashback ==== {}", itemCashback);
28969 amit.gupta 622
				if (itemCashback > 0) {
623
					count++;
624
					totalCashback += itemCashback;
625
				}
626
			}
627
			if (count > 0) {
29231 amit.gupta 628
				walletService.addAmountToWallet(
629
						retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT, "Sales margin for invoice number "
630
								+ fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
28969 amit.gupta 631
						totalCashback, fofoOrder.getCreateTimestamp());
632
				fofoOrder.setCashback(totalCashback);
633
				fofoOrderRepository.persist(fofoOrder);
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();
882
		CriteriaBuilder cb = session.getCriteriaBuilder();
883
		CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
884
		Root<Scheme> scheme = query.from(Scheme.class);
30121 amit.gupta 885
		Predicate finalPredicate = cb.and();
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);
890
			Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
891
			finalPredicate = cb.and(p1);
892
		}
26802 tejbeer 893
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
894
		cb.desc(cb.isNull(scheme.get("expireTimestamp")));
895
 
30121 amit.gupta 896
		if (catalogId > 0) {
27898 amit.gupta 897
 
30121 amit.gupta 898
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByCatalogId(catalogId);
27424 tejbeer 899
			LOGGER.info("schemeId" + schemeIds);
27898 amit.gupta 900
			if (schemeIds.isEmpty()) {
27424 tejbeer 901
				return new ArrayList<>();
902
			}
30121 amit.gupta 903
			Predicate p3 = cb.in(scheme.get("id")).value(schemeIds);
904
			if (onDate != null) {
905
				finalPredicate = cb.and(p2, p3, cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()),
27877 amit.gupta 906
						cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
26802 tejbeer 907
			} else {
30121 amit.gupta 908
				finalPredicate = cb.and(p3);
26802 tejbeer 909
			}
910
		} else {
911
			if (!isAdmin) {
30121 amit.gupta 912
				finalPredicate = cb.and(p2);
26802 tejbeer 913
			}
914
		}
30121 amit.gupta 915
		query.where(finalPredicate);
26802 tejbeer 916
		query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
917
 
918
		return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
919
 
920
	}
921
 
922
	@Override
27395 amit.gupta 923
	public void processActivation() throws ProfitMandiBusinessException {
924
		List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
925
		List<Integer> schemeIds = new ArrayList<>();
926
		Set<Integer> inventoryIds = new HashSet<>();
27898 amit.gupta 927
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 928
			schemeIds.add(pendingPayout.getSchemeId());
27440 amit.gupta 929
		}
930
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream()
27898 amit.gupta 931
				.filter(x -> x.getType().equals(SchemeType.ACTIVATION))
932
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
933
		pendingPayouts = pendingPayouts.stream().filter(x -> schemesMap.get(x.getSchemeId()) != null)
934
				.collect(Collectors.toList());
27440 amit.gupta 935
 
27898 amit.gupta 936
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 937
			inventoryIds.add(pendingPayout.getInventoryItemId());
938
		}
27898 amit.gupta 939
		Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
940
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
941
		Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream()
942
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
943
 
944
		List<ActivatedImei> activatedImeis = activatedImeiRepository
945
				.selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet()));
946
 
947
		Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream()
948
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
949
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 950
			InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
951
			String serialNumber = ii.getSerialNumber();
952
			ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
27898 amit.gupta 953
			if (activatedImei == null) {
27395 amit.gupta 954
				continue;
955
			}
956
			Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
27898 amit.gupta 957
			if (activatedImei.getActivationTimestamp().isBefore(scheme.getEndDateTime())
958
					&& activatedImei.getActivationTimestamp().isAfter(scheme.getStartDateTime())) {
27395 amit.gupta 959
				int fofoId = ii.getFofoId();
27898 amit.gupta 960
				// Get latest order Id
961
				int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream()
962
						.filter(x -> x.getOrderId() > 0)
963
						.sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get()
964
						.getOrderId();
27395 amit.gupta 965
				FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
27898 amit.gupta 966
				walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.ACTIVATION_SCHEME,
967
						"Activation margin for Imei#" + serialNumber, pendingPayout.getAmount(),
968
						fofoOrder.getCreateTimestamp());
27395 amit.gupta 969
				pendingPayout.setCreditTimestamp(LocalDateTime.now());
970
				pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
971
				pendingPayout.setStatusDescription("Activation margin credited");
972
			} else {
973
				pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
27898 amit.gupta 974
				pendingPayout.setRolledBackTimestamp(LocalDateTime.now());
975
				;
976
				pendingPayout.setStatusDescription(
977
						"Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
27395 amit.gupta 978
			}
979
		}
980
	}
26802 tejbeer 981
 
22653 ashik.ali 982
}