Subversion Repositories SmartDukaan

Rev

Rev 31170 | Rev 31340 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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