Subversion Repositories SmartDukaan

Rev

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