Subversion Repositories SmartDukaan

Rev

Rev 29927 | Rev 29940 | 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);
339
			sendNotificationModel.setMessageType(MessageType.scheme);
340
			notificationService.sendNotificationToAll(sendNotificationModel);
341
		}
342
	}
343
 
22653 ashik.ali 344
	@Override
25069 amit.gupta 345
	public void expireSchemeById(int schemeId, LocalDateTime expiryTime) throws ProfitMandiBusinessException {
22653 ashik.ali 346
		Scheme scheme = schemeRepository.selectById(schemeId);
25111 amit.gupta 347
		if (scheme == null || scheme.getActiveTimestamp() == null) {
23444 amit.gupta 348
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
349
					"SCHM_1007");
22653 ashik.ali 350
		}
23444 amit.gupta 351
		if (scheme.getExpireTimestamp() != null) {
352
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
353
					"SCHM_1008");
22653 ashik.ali 354
		}
22859 ashik.ali 355
		scheme.setExpireTimestamp(LocalDateTime.now());
29231 amit.gupta 356
		if (expiryTime.isAfter(scheme.getEndDateTime())) {
28749 amit.gupta 357
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
358
					"End Date cant be extended during expiry");
359
		}
25069 amit.gupta 360
		scheme.setEndDateTime(expiryTime);
22859 ashik.ali 361
		schemeRepository.persist(scheme);
22653 ashik.ali 362
	}
23444 amit.gupta 363
 
364
	private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
23019 ashik.ali 365
		Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
23444 amit.gupta 366
		for (Scheme scheme : schemes) {
23019 ashik.ali 367
			schemeIdSchemeMap.put(scheme.getId(), scheme);
22859 ashik.ali 368
		}
23019 ashik.ali 369
		return schemeIdSchemeMap;
22859 ashik.ali 370
	}
23444 amit.gupta 371
 
372
	private Set<Integer> inventoryItemsToItemIds(List<InventoryItem> inventoryItems) {
22859 ashik.ali 373
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 374
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 375
			itemIds.add(inventoryItem.getItemId());
376
		}
377
		return itemIds;
378
	}
23444 amit.gupta 379
 
380
	private Map<Integer, Set<Scheme>> toItemIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
23019 ashik.ali 381
		Map<Integer, Scheme> schemeIdSchemesMap = this.toSchemeIdSchemeMap(schemes);
22859 ashik.ali 382
		Map<Integer, Set<Scheme>> itemIdSchemesMap = new HashMap<>();
23444 amit.gupta 383
		for (SchemeItem schemeItem : schemeItems) {
384
			if (!itemIdSchemesMap.containsKey(schemeItem.getItemId())) {
22859 ashik.ali 385
				Set<Scheme> schemesSet = new HashSet<>();
386
				schemesSet.add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
387
				itemIdSchemesMap.put(schemeItem.getItemId(), schemesSet);
23444 amit.gupta 388
			} else {
22859 ashik.ali 389
				itemIdSchemesMap.get(schemeItem.getItemId()).add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
390
			}
391
		}
392
		return itemIdSchemesMap;
393
	}
22653 ashik.ali 394
 
23444 amit.gupta 395
	private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
29927 amit.gupta 396
																	  List<InventoryItem> inventoryItems) {
22859 ashik.ali 397
		Set<Integer> schemeIds = new HashSet<>();
23444 amit.gupta 398
		for (Scheme scheme : schemes) {
22859 ashik.ali 399
			schemeIds.add(scheme.getId());
400
		}
401
		Set<Integer> itemIds = this.inventoryItemsToItemIds(inventoryItems);
402
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndItemIds(schemeIds, itemIds);
23444 amit.gupta 403
 
22859 ashik.ali 404
		Map<Integer, Set<Scheme>> itemIdSchemesMap = this.toItemIdSchemesMap(schemeItems, schemes);
405
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemsMap = new HashMap<>();
23444 amit.gupta 406
		for (InventoryItem inventoryItem : inventoryItems) {
407
			if (itemIdSchemesMap.containsKey(inventoryItem.getItemId())) {
22859 ashik.ali 408
				inventoryItemSchemsMap.put(inventoryItem, itemIdSchemesMap.get(inventoryItem.getItemId()));
409
			}
410
		}
411
		return inventoryItemSchemsMap;
412
	}
23444 amit.gupta 413
 
22859 ashik.ali 414
	@Override
23365 ashik.ali 415
	public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
23369 ashik.ali 416
		LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
23344 ashik.ali 417
		Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
29231 amit.gupta 418
		// TODO - SCHEME
419
		PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
420
				YearMonth.from(purchase.getCreateTimestamp()));
421
		// PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
422
		// purchase.getCreateTimestamp().toLocalDate());
423
 
424
		List<Scheme> schemes = schemeRepository.selectActiveAll(Arrays.asList(SchemeType.IN), partnerType,
27898 amit.gupta 425
				purchase.getCreateTimestamp(), false);
426
		float totalCashback = 0;
427
		if (schemes.isEmpty()) {
428
			return;
429
		}
430
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
26332 amit.gupta 431
 
27898 amit.gupta 432
		Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
433
		LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
434
		Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
435
				.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
436
				.collect(Collectors.toSet());
437
		// Only consider inventory items that were not returned
438
		inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
439
				.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
440
				.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
441
		LOGGER.info(inventoryItems);
442
		if (inventoryItems.size() == 0)
443
			return;
444
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
445
				inventoryItems);
23444 amit.gupta 446
 
27898 amit.gupta 447
		if (inventoryItemSchemesMap.isEmpty()) {
448
			return;
449
		}
450
		Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 451
 
27898 amit.gupta 452
		for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
453
			Set<Scheme> allSchemes = new HashSet<>();
454
			for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
455
				allSchemes.add(scheme);
22859 ashik.ali 456
			}
27898 amit.gupta 457
			allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
458
		}
23444 amit.gupta 459
 
27898 amit.gupta 460
		//
26722 amit.gupta 461
 
27898 amit.gupta 462
		int itemsCount = 0;
463
		for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
464
				.entrySet()) {
465
			float inventoryItemCashback = 0;
466
			for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
467
				InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
468
				float cashback = this.createSchemeInOut(scheme, inventoryItem);
469
				inventoryItemCashback += cashback;
22859 ashik.ali 470
			}
27898 amit.gupta 471
			if (inventoryItemCashback > 0) {
472
				totalCashback += inventoryItemCashback;
473
				itemsCount++;
23508 amit.gupta 474
			}
22653 ashik.ali 475
		}
27898 amit.gupta 476
 
477
		LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
478
		if (itemsCount > 0) {
479
			walletService.addAmountToWallet(
480
					retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
481
							+ purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
482
					totalCashback, purchase.getCreateTimestamp());
483
			LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
484
					purchase.getPurchaseReference(), itemsCount);
485
			purchase.setCashback(purchase.getCashback() + totalCashback);
486
			purchaseRepository.persist(purchase);
487
		}
22653 ashik.ali 488
	}
29927 amit.gupta 489
 
29593 amit.gupta 490
	//Only in and activation margins are allowed to be rolled out more than twice
23444 amit.gupta 491
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
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
29927 amit.gupta 507
			if (!scheme.getType().equals(SchemeType.IN) && !scheme.getType().equals(SchemeType.ACTIVATION) && sios.size() > 0) {
29231 amit.gupta 508
 
29927 amit.gupta 509
				if (sios.size() > 1) {
29231 amit.gupta 510
					LOGGER.info("SAMESCHEMETYPE has already been credited twice for inventoryItem - {}", inventoryItem.getId());
511
					return 0;
512
				}
29927 amit.gupta 513
				if (amountToCredit > amountCredited + 1f) {
29231 amit.gupta 514
					for (SchemeInOut sio : sios) {
515
						sio.setRolledBackTimestamp(LocalDateTime.now());
516
						sio.setStatus(SchemePayoutStatus.REJECTED);
517
						sio.setStatusDescription("Partner Category upgraded, new entry added");
518
					}
519
					actualCredit = amountToCredit - amountCredited;
520
				} else {
521
					return 0;
522
				}
523
			} else {
524
				actualCredit = amountToCredit;
525
			}
29243 amit.gupta 526
			LOGGER.info("Actual Credit ==== {}", actualCredit);
29927 amit.gupta 527
 
24562 amit.gupta 528
			SchemeInOut schemeInOut = new SchemeInOut();
23443 amit.gupta 529
			schemeInOut.setSchemeId(scheme.getId());
530
			schemeInOut.setInventoryItemId(inventoryItem.getId());
27377 amit.gupta 531
			schemeInOut.setAmount(amountToCredit);
27433 amit.gupta 532
			schemeInOutRepository.persist(schemeInOut);
29231 amit.gupta 533
 
27898 amit.gupta 534
			if (scheme.getType().equals(SchemeType.ACTIVATION)) {
27377 amit.gupta 535
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
536
				schemeInOut.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
537
				return 0;
27898 amit.gupta 538
			} else if (scheme.getType().equals(SchemeType.INVESTMENT)) {
539
				schemeInOut.setStatus(SchemePayoutStatus.PENDING);
540
				schemeInOut.setStatusDescription("Subject to investment days maintained");
541
				return 0;
27377 amit.gupta 542
			} else {
543
				schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
27898 amit.gupta 544
				if (scheme.getType().equals(SchemeType.IN)) {
27713 amit.gupta 545
					schemeInOut.setStatusDescription("Credited for GRN of IMEI#" + inventoryItem.getSerialNumber());
29231 amit.gupta 546
				} else if (SchemeService.OUT_SCHEME_TYPES.contains(scheme.getType())) {
28737 amit.gupta 547
					schemeInOut.setStatusDescription("Credited for sale of IMEI#" + inventoryItem.getSerialNumber());
27713 amit.gupta 548
				}
27377 amit.gupta 549
				schemeInOut.setCreditTimestamp(LocalDateTime.now());
550
			}
23443 amit.gupta 551
		}
29231 amit.gupta 552
		return actualCredit;
22859 ashik.ali 553
	}
23444 amit.gupta 554
 
25049 amit.gupta 555
	// We are maintaining price drop after grn
23444 amit.gupta 556
	private float getAmount(InventoryItem inventoryItem, Scheme scheme) {
22653 ashik.ali 557
		float amount = 0;
25049 amit.gupta 558
		float dpForCalc = 0;
559
		float taxableSellingPrice = 0;
26684 amit.gupta 560
		// float totalTaxRate = inventoryItem.getIgstRate() +
561
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
562
		// Hardcoding it to 18%
26568 amit.gupta 563
		float totalTaxRate = 18f;
26684 amit.gupta 564
		// float totalTaxRate = inventoryItem.getIgstRate() +
565
		// inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
23527 ashik.ali 566
		if (scheme.getAmountType() == AmountType.PERCENTAGE) {
24562 amit.gupta 567
			if (scheme.getType().equals(SchemeType.IN)) {
25049 amit.gupta 568
				dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
23995 amit.gupta 569
			} else {
570
				try {
26684 amit.gupta 571
					dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
26550 amit.gupta 572
							tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
24562 amit.gupta 573
				} catch (Exception e) {
23995 amit.gupta 574
					LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
575
					e.printStackTrace();
576
				}
577
			}
25049 amit.gupta 578
			taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
22859 ashik.ali 579
			amount = taxableSellingPrice * scheme.getAmount() / 100;
25517 amit.gupta 580
			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 581
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 582
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
583
					scheme.getAmount(), amount));
23444 amit.gupta 584
		} else {
22653 ashik.ali 585
			amount = scheme.getAmount();
25517 amit.gupta 586
			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 587
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
26332 amit.gupta 588
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
589
					0, amount));
22653 ashik.ali 590
		}
25049 amit.gupta 591
 
22859 ashik.ali 592
		return amount;
22653 ashik.ali 593
	}
23444 amit.gupta 594
 
22653 ashik.ali 595
	@Override
23365 ashik.ali 596
	public void processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
597
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
29231 amit.gupta 598
		// Process only if order is not cancelled
599
		if (fofoOrder.getCancelledTimestamp() == null) {
600
			// PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
601
			// fofoOrder.getCreateTimestamp().toLocalDate());
602
			// TODO - SCHEME
603
			PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
604
					YearMonth.from(fofoOrder.getCreateTimestamp()));
605
 
28969 amit.gupta 606
			List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
607
			Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
608
					.collect(Collectors.toSet());
609
			Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
610
					.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
611
					.collect(Collectors.toSet());
612
			if (inventoryItems.size() == 0) {
613
				return;
22653 ashik.ali 614
			}
28969 amit.gupta 615
			Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
29231 amit.gupta 616
 
617
			// Remove Items that are eol now.
28969 amit.gupta 618
			Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
619
					.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(fofoOrder.getCreateTimestamp()))
620
					.map(x -> x.getItemId()).collect(Collectors.toSet());
621
			// Only consider inventory items that were not returned
622
			inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
623
					.collect(Collectors.toSet());
29231 amit.gupta 624
 
28969 amit.gupta 625
			if (inventoryItems.size() == 0) {
626
				return;
22859 ashik.ali 627
			}
29231 amit.gupta 628
 
28969 amit.gupta 629
			float totalCashback = 0;
630
			int count = 0;
29231 amit.gupta 631
 
632
			List<SchemeType> allOutSchemeTypes = new ArrayList<>();
633
			allOutSchemeTypes.addAll(Arrays.asList(SchemeType.ACTIVATION, SchemeType.INVESTMENT));
634
			allOutSchemeTypes.addAll(OUT_SCHEME_TYPES);
635
 
636
			List<Scheme> allActiveSchemes = schemeRepository.selectActiveAll(allOutSchemeTypes, partnerType,
28969 amit.gupta 637
					fofoOrder.getCreateTimestamp(), false);
29231 amit.gupta 638
 
28969 amit.gupta 639
			for (InventoryItem inventoryItem : inventoryItems) {
640
				float itemCashback = 0;
641
				Set<Integer> schemeIds = new HashSet<>(
642
						schemeItemRepository.selectSchemeIdByItemId(inventoryItem.getItemId()));
29231 amit.gupta 643
				List<Scheme> itemActiveSchemes = allActiveSchemes.stream().filter(x -> schemeIds.contains(x.getId()))
28969 amit.gupta 644
						.collect(Collectors.toList());
29231 amit.gupta 645
				for (Scheme scheme : itemActiveSchemes) {
29239 amit.gupta 646
					LOGGER.info("Scheme ==== {}", scheme);
28969 amit.gupta 647
					itemCashback += this.createSchemeInOut(scheme, inventoryItem);
648
				}
29240 amit.gupta 649
				LOGGER.info("itemCashback ==== {}", itemCashback);
28969 amit.gupta 650
				if (itemCashback > 0) {
651
					count++;
652
					totalCashback += itemCashback;
653
				}
654
			}
655
			if (count > 0) {
29231 amit.gupta 656
				walletService.addAmountToWallet(
657
						retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT, "Sales margin for invoice number "
658
								+ fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
28969 amit.gupta 659
						totalCashback, fofoOrder.getCreateTimestamp());
660
				fofoOrder.setCashback(totalCashback);
661
				fofoOrderRepository.persist(fofoOrder);
662
			}
22653 ashik.ali 663
		}
664
	}
23444 amit.gupta 665
 
23508 amit.gupta 666
	@Override
23796 amit.gupta 667
	public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
668
			throws Exception {
23638 amit.gupta 669
		Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
23508 amit.gupta 670
		float amountToRollback = 0;
671
		List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
23796 amit.gupta 672
		for (SchemeInOut schemeInOut : schemes) {
23983 amit.gupta 673
			if (schemeInOut.getRolledBackTimestamp() == null) {
674
				schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
29231 amit.gupta 675
				if (schemeInOut.getStatus() == null || schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
27377 amit.gupta 676
					amountToRollback += schemeInOut.getAmount();
677
				}
678
				schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
679
				schemeInOut.setStatusDescription(rollbackReason);
23983 amit.gupta 680
			}
23508 amit.gupta 681
		}
23983 amit.gupta 682
		if (amountToRollback > 0) {
23638 amit.gupta 683
			int inventoryItemId = inventoryItemIds.get(0);
26498 amit.gupta 684
			InventoryItem ii = inventoryItemRepository.selectById(inventoryItemId);
685
			Integer fofoId = ii.getFofoId();
27898 amit.gupta 686
			// Purchase p = purchaseRepository.selectById(ii.getPurchaseId());
26684 amit.gupta 687
			// TODO//
26693 amit.gupta 688
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, ii.getPurchaseId(),
26498 amit.gupta 689
					WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
23638 amit.gupta 690
		}
23508 amit.gupta 691
	}
23884 amit.gupta 692
 
23781 ashik.ali 693
	@Override
23796 amit.gupta 694
	public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
695
			throws ProfitMandiBusinessException {
23781 ashik.ali 696
		Map<String, Object> map = new HashMap<>();
697
		List<Scheme> schemes = null;
698
		long size = 0;
23798 amit.gupta 699
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 700
			schemes = schemeRepository.selectAll(offset, limit);
701
			size = schemeRepository.selectAllCount();
23796 amit.gupta 702
		} else {
23781 ashik.ali 703
			schemes = schemeRepository.selectActiveAll(offset, limit);
704
			size = schemeRepository.selectAllActiveCount();
705
		}
706
		map.put("schemes", schemes);
707
		map.put("start", offset + 1);
708
		map.put("size", size);
23796 amit.gupta 709
		if (schemes.size() < limit) {
23781 ashik.ali 710
			map.put("end", offset + schemes.size());
23796 amit.gupta 711
		} else {
23781 ashik.ali 712
			map.put("end", offset + limit);
713
		}
714
		return map;
715
	}
23796 amit.gupta 716
 
23781 ashik.ali 717
	@Override
23796 amit.gupta 718
	public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
719
			throws ProfitMandiBusinessException {
23781 ashik.ali 720
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
721
		List<Scheme> schemes = null;
23798 amit.gupta 722
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 723
			schemes = schemeRepository.selectAll(offset, limit);
23796 amit.gupta 724
		} else {
23781 ashik.ali 725
			schemes = schemeRepository.selectActiveAll(offset, limit);
726
		}
727
		return schemes;
728
	}
23508 amit.gupta 729
 
23968 amit.gupta 730
	@Override
27898 amit.gupta 731
	// This is being called to reverse schemes while processing price Drop
24976 amit.gupta 732
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
26332 amit.gupta 733
			throws ProfitMandiBusinessException {
26498 amit.gupta 734
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
24976 amit.gupta 735
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
736
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
737
 
738
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
739
			float amountToCredit = 0;
740
			float amountToDebit = 0;
741
			int purchaseId = purchaseEntry.getKey();
742
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
743
 
744
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
745
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
746
 
747
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
27399 amit.gupta 748
			LOGGER.info("Scheme InOuts , {}", schemeInOuts);
27898 amit.gupta 749
			if (schemeInOuts.size() == 0) {
27400 amit.gupta 750
				continue;
751
			}
24976 amit.gupta 752
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
753
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
754
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
755
			for (SchemeInOut schemeInOut : schemeInOuts) {
756
				InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
757
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
758
				if (scheme.getAmountType().equals(AmountType.FIXED)) {
759
					continue;
23995 amit.gupta 760
				}
27713 amit.gupta 761
				if (scheme.getType().equals(SchemeType.IN) && schemeInOut.getRolledBackTimestamp() == null) {
24976 amit.gupta 762
					float newAmount = getAmount(ii, scheme);
763
					if (schemeInOut.getAmount() - newAmount >= 0.01f) {
764
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
27898 amit.gupta 765
 
24976 amit.gupta 766
						SchemeInOut sioNew = new SchemeInOut();
767
						sioNew.setAmount(newAmount);
27713 amit.gupta 768
						sioNew.setStatus(schemeInOut.getStatus());
769
						sioNew.setStatusDescription(schemeInOut.getStatusDescription());
24976 amit.gupta 770
						sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
771
						sioNew.setSchemeId(schemeInOut.getSchemeId());
772
						schemeInOutRepository.persist(sioNew);
27713 amit.gupta 773
 
774
						schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
775
						schemeInOut.setStatusDescription("Pricedrop processed, new entries added");
27898 amit.gupta 776
						// IF not credited then dont consider any credit/debit for that sio entry
777
						if (schemeInOut.getCreditTimestamp() != null) {
27713 amit.gupta 778
							amountToCredit += sioNew.getAmount();
779
							amountToDebit += schemeInOut.getAmount();
780
						}
24976 amit.gupta 781
					}
24562 amit.gupta 782
 
24976 amit.gupta 783
				}
23986 amit.gupta 784
			}
24976 amit.gupta 785
			int fofoId = inventoryItems.get(0).getFofoId();
786
			if (amountToDebit > 0) {
26684 amit.gupta 787
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
788
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
789
						priceDrop.getAffectedOn());
24976 amit.gupta 790
			}
791
			if (amountToCredit > 0) {
26403 amit.gupta 792
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
26684 amit.gupta 793
						MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), amountToCredit,
794
						priceDrop.getAffectedOn());
24976 amit.gupta 795
			}
23968 amit.gupta 796
		}
797
	}
24562 amit.gupta 798
 
24264 amit.gupta 799
	@Override
29593 amit.gupta 800
	// Always being called from cancel order/bad return means no SCHEME IN is considered
24562 amit.gupta 801
	public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
29927 amit.gupta 802
							   List<SchemeType> schemeTypes) throws ProfitMandiBusinessException {
24264 amit.gupta 803
		Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
28419 tejbeer 804
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
28417 tejbeer 805
		LOGGER.info("inventoryItems" + inventoryItems);
806
 
24264 amit.gupta 807
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
28416 tejbeer 808
		LOGGER.info("schemeInOuts" + schemeInOuts);
28417 tejbeer 809
		float amountToRollback = 0;
28416 tejbeer 810
 
28417 tejbeer 811
		if (!schemeInOuts.isEmpty()) {
812
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
813
			LOGGER.info("schemeIds" + schemeIds);
28416 tejbeer 814
 
28417 tejbeer 815
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
816
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
817
			for (SchemeInOut schemeInOut : schemeInOuts) {
818
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
29231 amit.gupta 819
				if (schemeTypes.contains(scheme.getType())) {
28417 tejbeer 820
					if (schemeInOut.getRolledBackTimestamp() == null) {
821
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
822
						if (schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
823
							amountToRollback += schemeInOut.getAmount();
824
						}
825
						schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
826
						schemeInOut.setStatusDescription(reversalReason);
27377 amit.gupta 827
					}
24264 amit.gupta 828
				}
829
			}
28417 tejbeer 830
 
24264 amit.gupta 831
		}
832
		int fofoId = inventoryItems.get(0).getFofoId();
29231 amit.gupta 833
		WalletReferenceType walletReferenceType = schemeTypes.containsAll(SchemeService.OUT_SCHEME_TYPES)
834
				? WalletReferenceType.SCHEME_OUT
835
				: (schemeTypes.contains(SchemeType.ACTIVATION) ? WalletReferenceType.ACTIVATION_SCHEME
29927 amit.gupta 836
				: WalletReferenceType.INVESTMENT_PAYOUT);
27377 amit.gupta 837
		if (amountToRollback > 0) {
29231 amit.gupta 838
			// Mark appropriate reference of rollback investment margin
839
			if (schemeTypes.contains(SchemeType.INVESTMENT)) {
840
				reversalReference = Integer
29664 amit.gupta 841
						.parseInt(FormattingUtils.getYearMonth(schemeInOuts.get(0).getCreditTimestamp().minusMonths(1)));
29231 amit.gupta 842
			}
27377 amit.gupta 843
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, reversalReference, walletReferenceType,
26498 amit.gupta 844
					reversalReason, LocalDateTime.now());
24268 amit.gupta 845
		}
24264 amit.gupta 846
	}
23968 amit.gupta 847
 
26332 amit.gupta 848
	@Override
849
	public double getTotalMargin(int itemId, PartnerType partnerType, LocalDateTime dateTime) {
850
		Session session = sessionFactory.getCurrentSession();
851
		CriteriaBuilder cb = session.getCriteriaBuilder();
852
		CriteriaQuery<Double> criteriaQuery = cb.createQuery(Double.class);
853
		Root<SchemeItem> schemeItem = criteriaQuery.from(SchemeItem.class);
854
		Root<Scheme> scheme = criteriaQuery.from(Scheme.class);
855
		Predicate schemePredicate = cb.equal(scheme.get(ProfitMandiConstants.AMOUNT_TYPE), AmountType.PERCENTAGE);
856
		Predicate lessThanPredicate = cb.lessThanOrEqualTo(scheme.get(ProfitMandiConstants.END_DATE_TIME), dateTime);
857
		Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(scheme.get(ProfitMandiConstants.START_DATE_TIME),
858
				dateTime);
859
		Predicate joinPredicate = cb.equal(scheme.get("id"), schemeItem.get("schemeId"));
860
		Predicate schemeItemPredicate = cb.equal(schemeItem.get(ProfitMandiConstants.ITEM_ID), itemId);
861
		criteriaQuery.select(cb.sum(scheme.get(ProfitMandiConstants.AMOUNT))).where(schemePredicate, lessThanPredicate,
862
				greaterThanPredicate, schemeItemPredicate, joinPredicate);
863
 
864
		Query<Double> query = session.createQuery(criteriaQuery);
865
		return query.getSingleResult() + ProfitMandiConstants.SCHEME_INVESTMENT_MARGIN;
866
 
867
	}
868
 
26684 amit.gupta 869
	@Override
870
	@Cacheable(value = "itemSchemeCashback", cacheManager = "timeoutCacheManager")
871
	public Map<Integer, Float> getItemSchemeCashBack() {
872
		Map<Integer, Float> itemCashbackMap = new HashMap<>();
873
		Map<Integer, Scheme> cashbackSchemesMap = schemeRepository
29231 amit.gupta 874
				.selectActiveAll(Arrays.asList(SchemeType.ACTIVATION), PartnerType.ALL, LocalDateTime.now(), true)
875
				.stream().filter(x -> x.getAmountType().equals(AmountType.FIXED))
26684 amit.gupta 876
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
26722 amit.gupta 877
		if (cashbackSchemesMap.size() > 0) {
26713 amit.gupta 878
			List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(cashbackSchemesMap.keySet());
879
			schemeItems.stream().forEach(x -> {
29864 amit.gupta 880
				float cashbackAmount = cashbackSchemesMap.get(x.getSchemeId()).getAmount();
29927 amit.gupta 881
				if (!itemCashbackMap.containsKey(x.getItemId())) {
29864 amit.gupta 882
					itemCashbackMap.put(x.getItemId(), cashbackAmount);
883
				} else {
29927 amit.gupta 884
					itemCashbackMap.put(x.getItemId(), itemCashbackMap.get(x.getItemId()) + cashbackAmount);
29864 amit.gupta 885
				}
26713 amit.gupta 886
			});
887
		}
26722 amit.gupta 888
		// A107FD Model needs to removed
26703 amit.gupta 889
		itemCashbackMap.remove(30211);
890
		itemCashbackMap.remove(30212);
891
		itemCashbackMap.remove(30213);
892
		itemCashbackMap.remove(30756);
26684 amit.gupta 893
		return itemCashbackMap;
894
	}
895
 
24976 amit.gupta 896
	/*
897
	 * @Override public void updateSchmesForModel(int catalogId) throws
898
	 * ProfitMandiBusinessException { List<Item> items =
899
	 * itemRepository.selectAllByCatalogItemId(catalogId); Map<Integer, Scheme>
900
	 * schemes = schemeRepository .selectAllByItemIds(items.stream().map(x ->
901
	 * x.getId()).collect(Collectors.toList()));
29927 amit.gupta 902
	 *
24976 amit.gupta 903
	 * }
904
	 */
24562 amit.gupta 905
 
26802 tejbeer 906
	@Override
27898 amit.gupta 907
	public List<Scheme> selectSchemeByPartnerType(PartnerType partnerType, LocalDate onDate, int itemId,
29927 amit.gupta 908
												  boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
26802 tejbeer 909
		Session session = sessionFactory.getCurrentSession();
910
		CriteriaBuilder cb = session.getCriteriaBuilder();
911
		CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
912
		Root<Scheme> scheme = query.from(Scheme.class);
913
		List<PartnerType> pt = new ArrayList<>();
914
		pt.add(PartnerType.ALL);
915
		pt.add(partnerType);
916
		Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
917
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
918
		cb.desc(cb.isNull(scheme.get("expireTimestamp")));
919
 
920
		Predicate p3 = null;
921
		Predicate finalPredicate = null;
922
		if (itemId != 0) {
27898 amit.gupta 923
 
26802 tejbeer 924
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
27424 tejbeer 925
			LOGGER.info("schemeId" + schemeIds);
27898 amit.gupta 926
			if (schemeIds.isEmpty()) {
27424 tejbeer 927
				return new ArrayList<>();
928
			}
26802 tejbeer 929
			p3 = cb.in(scheme.get("id")).value(schemeIds);
930
			if (!isAdmin) {
931
 
27877 amit.gupta 932
				finalPredicate = cb.and(p1, p2, p3, cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()),
933
						cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
26802 tejbeer 934
				query.where(finalPredicate);
935
			} else {
936
				finalPredicate = cb.and(p1, p3);
937
				query.where(finalPredicate);
938
			}
939
		} else {
940
 
941
			if (!isAdmin) {
942
 
943
				finalPredicate = cb.and(p1, p2);
26912 tejbeer 944
				query.where(finalPredicate);
26802 tejbeer 945
			} else {
946
				query.where(p1);
947
			}
948
		}
949
		query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
950
 
951
		return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
952
 
953
	}
954
 
955
	@Override
27877 amit.gupta 956
	public long selectSchemeCount(PartnerType partnerType, LocalDate onDate, int itemId, boolean isAdmin) {
26802 tejbeer 957
		Session session = sessionFactory.getCurrentSession();
958
		CriteriaBuilder cb = session.getCriteriaBuilder();
959
		CriteriaQuery<Long> query = cb.createQuery(Long.class);
960
		Root<Scheme> scheme = query.from(Scheme.class);
961
		List<PartnerType> pt = new ArrayList<>();
962
		pt.add(PartnerType.ALL);
963
		pt.add(partnerType);
964
		Predicate p1 = cb.in(scheme.get("partnerType")).value(pt);
965
		Predicate p2 = cb.isNotNull(scheme.get("activeTimestamp"));
966
		Predicate finalPredicate = null;
967
		if (itemId != 0) {
968
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(itemId);
969
			Predicate p3 = cb.in(scheme.get("id")).value(schemeIds);
970
			if (!isAdmin) {
971
 
27877 amit.gupta 972
				finalPredicate = cb.and(p1, p2, p3, cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()),
973
						cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
26802 tejbeer 974
				query.select(cb.count(scheme)).where(finalPredicate);
975
			} else {
976
				finalPredicate = cb.and(p1, p3);
977
				query.select(cb.count(scheme)).where(finalPredicate);
978
			}
979
		} else {
980
			if (!isAdmin) {
981
				finalPredicate = cb.and(p1, p2);
982
				query.select(cb.count(scheme)).where(finalPredicate);
983
 
984
			} else {
985
				query.select(cb.count(scheme)).where(p1);
986
 
987
			}
988
		}
989
 
990
		return session.createQuery(query).getSingleResult();
991
 
992
	}
27898 amit.gupta 993
 
27395 amit.gupta 994
	@Override
995
	public void processActivation() throws ProfitMandiBusinessException {
996
		List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
997
		List<Integer> schemeIds = new ArrayList<>();
998
		Set<Integer> inventoryIds = new HashSet<>();
27898 amit.gupta 999
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 1000
			schemeIds.add(pendingPayout.getSchemeId());
27440 amit.gupta 1001
		}
1002
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream()
27898 amit.gupta 1003
				.filter(x -> x.getType().equals(SchemeType.ACTIVATION))
1004
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1005
		pendingPayouts = pendingPayouts.stream().filter(x -> schemesMap.get(x.getSchemeId()) != null)
1006
				.collect(Collectors.toList());
27440 amit.gupta 1007
 
27898 amit.gupta 1008
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 1009
			inventoryIds.add(pendingPayout.getInventoryItemId());
1010
		}
27898 amit.gupta 1011
		Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
1012
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1013
		Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream()
1014
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
1015
 
1016
		List<ActivatedImei> activatedImeis = activatedImeiRepository
1017
				.selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet()));
1018
 
1019
		Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream()
1020
				.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
1021
		for (SchemeInOut pendingPayout : pendingPayouts) {
27395 amit.gupta 1022
			InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
1023
			String serialNumber = ii.getSerialNumber();
1024
			ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
27898 amit.gupta 1025
			if (activatedImei == null) {
27395 amit.gupta 1026
				continue;
1027
			}
1028
			Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
27898 amit.gupta 1029
			if (activatedImei.getActivationTimestamp().isBefore(scheme.getEndDateTime())
1030
					&& activatedImei.getActivationTimestamp().isAfter(scheme.getStartDateTime())) {
27395 amit.gupta 1031
				int fofoId = ii.getFofoId();
27898 amit.gupta 1032
				// Get latest order Id
1033
				int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream()
1034
						.filter(x -> x.getOrderId() > 0)
1035
						.sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get()
1036
						.getOrderId();
27395 amit.gupta 1037
				FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
27898 amit.gupta 1038
				walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.ACTIVATION_SCHEME,
1039
						"Activation margin for Imei#" + serialNumber, pendingPayout.getAmount(),
1040
						fofoOrder.getCreateTimestamp());
27395 amit.gupta 1041
				pendingPayout.setCreditTimestamp(LocalDateTime.now());
1042
				pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
1043
				pendingPayout.setStatusDescription("Activation margin credited");
1044
			} else {
1045
				pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
27898 amit.gupta 1046
				pendingPayout.setRolledBackTimestamp(LocalDateTime.now());
1047
				;
1048
				pendingPayout.setStatusDescription(
1049
						"Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
27395 amit.gupta 1050
			}
1051
		}
1052
	}
26802 tejbeer 1053
 
22653 ashik.ali 1054
}