Subversion Repositories SmartDukaan

Rev

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