Subversion Repositories SmartDukaan

Rev

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