Subversion Repositories SmartDukaan

Rev

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