Subversion Repositories SmartDukaan

Rev

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