Subversion Repositories SmartDukaan

Rev

Rev 25051 | Rev 25054 | 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
 
22859 ashik.ali 3
import java.time.LocalDateTime;
23019 ashik.ali 4
import java.util.ArrayList;
22653 ashik.ali 5
import java.util.HashMap;
22859 ashik.ali 6
import java.util.HashSet;
22653 ashik.ali 7
import java.util.List;
8
import java.util.Map;
9
import java.util.Set;
23968 amit.gupta 10
import java.util.stream.Collectors;
22653 ashik.ali 11
 
23781 ashik.ali 12
import org.apache.logging.log4j.LogManager;
23568 govind 13
import org.apache.logging.log4j.Logger;
22653 ashik.ali 14
import org.springframework.beans.factory.annotation.Autowired;
23781 ashik.ali 15
import org.springframework.beans.factory.annotation.Qualifier;
22653 ashik.ali 16
import org.springframework.stereotype.Component;
17
 
24307 amit.gupta 18
import com.spice.profitmandi.common.enumuration.ItemType;
22653 ashik.ali 19
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
22859 ashik.ali 20
import com.spice.profitmandi.common.model.CreateSchemeRequest;
22653 ashik.ali 21
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23019 ashik.ali 22
import com.spice.profitmandi.common.model.SchemeModel;
22859 ashik.ali 23
import com.spice.profitmandi.common.util.StringUtils;
23339 ashik.ali 24
import com.spice.profitmandi.dao.entity.catalog.Item;
22653 ashik.ali 25
import com.spice.profitmandi.dao.entity.catalog.RetailerScheme;
26
import com.spice.profitmandi.dao.entity.catalog.Scheme;
27
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
23365 ashik.ali 28
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
22859 ashik.ali 29
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
22653 ashik.ali 30
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
23339 ashik.ali 31
import com.spice.profitmandi.dao.entity.fofo.Purchase;
25043 amit.gupta 32
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
22859 ashik.ali 33
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
34
import com.spice.profitmandi.dao.entity.fofo.SchemeItem;
23527 ashik.ali 35
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
22653 ashik.ali 36
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
22859 ashik.ali 37
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
22653 ashik.ali 38
import com.spice.profitmandi.dao.repository.catalog.RetailerSchemeRepository;
39
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
23995 amit.gupta 40
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
23968 amit.gupta 41
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
23019 ashik.ali 42
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
43
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
23365 ashik.ali 44
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
22653 ashik.ali 45
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
23339 ashik.ali 46
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
25043 amit.gupta 47
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
22859 ashik.ali 48
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
49
import com.spice.profitmandi.dao.repository.fofo.SchemeItemRepository;
23798 amit.gupta 50
import com.spice.profitmandi.service.authentication.RoleManager;
22859 ashik.ali 51
import com.spice.profitmandi.service.wallet.WalletService;
22653 ashik.ali 52
 
22859 ashik.ali 53
import in.shop2020.model.v1.order.WalletReferenceType;
54
 
22653 ashik.ali 55
@Component
56
public class SchemeServiceImpl implements SchemeService {
57
 
23568 govind 58
	private static final Logger LOGGER = LogManager.getLogger(SchemeServiceImpl.class);
23444 amit.gupta 59
 
22653 ashik.ali 60
	@Autowired
23781 ashik.ali 61
	@Qualifier("fofoInventoryItemRepository")
22653 ashik.ali 62
	private InventoryItemRepository inventoryItemRepository;
23444 amit.gupta 63
 
22653 ashik.ali 64
	@Autowired
25043 amit.gupta 65
	private ScanRecordRepository scanRecordRepository;
23444 amit.gupta 66
 
22653 ashik.ali 67
	@Autowired
68
	private SchemeRepository schemeRepository;
23444 amit.gupta 69
 
22653 ashik.ali 70
	@Autowired
23798 amit.gupta 71
	private RoleManager roleManager;
72
 
73
	@Autowired
22859 ashik.ali 74
	private RetailerRepository retailerRepository;
24562 amit.gupta 75
 
23995 amit.gupta 76
	@Autowired
77
	private TagListingRepository tagListingRepository;
23444 amit.gupta 78
 
22859 ashik.ali 79
	@Autowired
22653 ashik.ali 80
	private RetailerSchemeRepository retailerSchemeRepository;
23444 amit.gupta 81
 
22653 ashik.ali 82
	@Autowired
22859 ashik.ali 83
	private SchemeInOutRepository schemeInOutRepository;
23444 amit.gupta 84
 
22653 ashik.ali 85
	@Autowired
23781 ashik.ali 86
	@Qualifier("catalogItemRepository")
22859 ashik.ali 87
	private ItemRepository itemRepository;
23444 amit.gupta 88
 
22859 ashik.ali 89
	@Autowired
90
	private SchemeItemRepository schemeItemRepository;
23444 amit.gupta 91
 
22859 ashik.ali 92
	@Autowired
93
	private WalletService walletService;
23444 amit.gupta 94
 
23019 ashik.ali 95
	@Autowired
96
	private FofoOrderItemRepository fofoOrderItemRepository;
23444 amit.gupta 97
 
23019 ashik.ali 98
	@Autowired
99
	private FofoLineItemRepository fofoLineItemRepository;
23444 amit.gupta 100
 
23339 ashik.ali 101
	@Autowired
102
	private PurchaseRepository purchaseRepository;
23444 amit.gupta 103
 
23344 ashik.ali 104
	@Autowired
23365 ashik.ali 105
	private FofoOrderRepository fofoOrderRepository;
23796 amit.gupta 106
 
22653 ashik.ali 107
	@Override
22859 ashik.ali 108
	public void saveScheme(int creatorId, CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
23444 amit.gupta 109
 
23019 ashik.ali 110
		this.validateCreateSchemeRequest(createSchemeRequest);
23444 amit.gupta 111
 
22859 ashik.ali 112
		Scheme scheme = this.toScheme(creatorId, createSchemeRequest);
23444 amit.gupta 113
 
114
		if (scheme.getStartDateTime().isAfter(scheme.getEndDateTime())) {
115
			throw new ProfitMandiBusinessException(
116
					ProfitMandiConstants.START_DATE + ", " + ProfitMandiConstants.END_DATE,
117
					scheme.getStartDateTime() + ", " + scheme.getEndDateTime(), "SCHM_VE_1005");
22653 ashik.ali 118
		}
23444 amit.gupta 119
 
22859 ashik.ali 120
		this.validateItemIds(createSchemeRequest);
121
		schemeRepository.persist(scheme);
23444 amit.gupta 122
		if (!createSchemeRequest.isRetailerAll()) {
22859 ashik.ali 123
			this.validateRetailerIds(createSchemeRequest);
23444 amit.gupta 124
			for (int retailerId : createSchemeRequest.getRetailerIds()) {
22859 ashik.ali 125
				RetailerScheme retailerScheme = new RetailerScheme();
126
				retailerScheme.setRetailerId(retailerId);
127
				retailerScheme.setSchemeId(scheme.getId());
128
				retailerSchemeRepository.persist(retailerScheme);
129
			}
22653 ashik.ali 130
		}
23444 amit.gupta 131
		for (int itemId : createSchemeRequest.getItemIds()) {
22859 ashik.ali 132
			SchemeItem schemeItem = new SchemeItem();
133
			schemeItem.setSchemeId(scheme.getId());
134
			schemeItem.setItemId(itemId);
135
			schemeItemRepository.persist(schemeItem);
136
		}
23444 amit.gupta 137
 
22653 ashik.ali 138
	}
23444 amit.gupta 139
 
140
	private void validateCreateSchemeRequest(CreateSchemeRequest createSchemeRequest)
141
			throws ProfitMandiBusinessException {
142
		if (createSchemeRequest.getName() == null || createSchemeRequest.getName().isEmpty()) {
143
			throw new ProfitMandiBusinessException(ProfitMandiConstants.NAME, createSchemeRequest.getName(),
144
					"SCHM_VE_1000");
23019 ashik.ali 145
		}
23444 amit.gupta 146
		if (createSchemeRequest.getAmount() <= 0) {
147
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
148
					"SCHM_VE_1001");
23019 ashik.ali 149
		}
23444 amit.gupta 150
 
23527 ashik.ali 151
		if (AmountType.valueOf(createSchemeRequest.getAmountType()) == AmountType.PERCENTAGE
23444 amit.gupta 152
				&& createSchemeRequest.getAmount() > 100) {
153
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
154
					"SCHM_VE_1002");
23019 ashik.ali 155
		}
23444 amit.gupta 156
 
23886 amit.gupta 157
		if (createSchemeRequest.getStartDate() == null) {
23983 amit.gupta 158
			throw new ProfitMandiBusinessException(ProfitMandiConstants.START_DATE, createSchemeRequest.getStartDate(),
159
					"SCHM_VE_1003");
23019 ashik.ali 160
		}
23886 amit.gupta 161
		if (createSchemeRequest.getEndDate() == null) {
23983 amit.gupta 162
			throw new ProfitMandiBusinessException(ProfitMandiConstants.END_DATE, createSchemeRequest.getEndDate(),
163
					"SCHM_VE_1004");
23019 ashik.ali 164
		}
165
	}
23444 amit.gupta 166
 
167
	private Scheme toScheme(int creatorId, CreateSchemeRequest createSchemeRequest) {
22859 ashik.ali 168
		Scheme scheme = new Scheme();
169
		scheme.setName(createSchemeRequest.getName());
170
		scheme.setDescription(createSchemeRequest.getDescription());
171
		scheme.setType(SchemeType.valueOf(createSchemeRequest.getType()));
23527 ashik.ali 172
		scheme.setAmountType(AmountType.valueOf(createSchemeRequest.getAmountType()));
22859 ashik.ali 173
		scheme.setAmount(createSchemeRequest.getAmount());
23886 amit.gupta 174
		scheme.setStartDateTime(createSchemeRequest.getStartDate());
175
		scheme.setEndDateTime(createSchemeRequest.getEndDate());
22859 ashik.ali 176
		scheme.setCreatedBy(creatorId);
177
		scheme.setRetailerAll(createSchemeRequest.isRetailerAll());
178
		return scheme;
179
	}
23444 amit.gupta 180
 
181
	private void validateRetailerIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
182
		if (createSchemeRequest.getRetailerIds() == null || createSchemeRequest.getRetailerIds().isEmpty()) {
183
			throw new ProfitMandiBusinessException(ProfitMandiConstants.RETAILER_ID,
184
					createSchemeRequest.getRetailerIds(), "SCHM_1001");
22859 ashik.ali 185
		}
22870 ashik.ali 186
		List<Integer> foundRetailerIds = retailerRepository.selectIdsByIds(createSchemeRequest.getRetailerIds());
23444 amit.gupta 187
		if (foundRetailerIds.size() != createSchemeRequest.getRetailerIds().size()) {
22859 ashik.ali 188
			createSchemeRequest.getRetailerIds().removeAll(foundRetailerIds);
23444 amit.gupta 189
			throw new ProfitMandiBusinessException(ProfitMandiConstants.RETAILER_ID,
190
					createSchemeRequest.getRetailerIds(), "SCHM_1002");
22859 ashik.ali 191
		}
192
	}
23444 amit.gupta 193
 
194
	private void validateItemIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
195
		if (createSchemeRequest.getItemIds() == null || createSchemeRequest.getItemIds().isEmpty()) {
196
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
197
					"SCHM_1003");
22859 ashik.ali 198
		}
23444 amit.gupta 199
		List<Integer> foundItemIds = itemRepository.selectIdsByIdsAndType(createSchemeRequest.getItemIds(),
200
				ItemType.SERIALIZED);
201
		if (foundItemIds.size() != createSchemeRequest.getItemIds().size()) {
22859 ashik.ali 202
			createSchemeRequest.getItemIds().removeAll(foundItemIds);
23444 amit.gupta 203
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
204
					"SCHM_1004");
22859 ashik.ali 205
		}
206
	}
23444 amit.gupta 207
 
22859 ashik.ali 208
	@Override
209
	public Scheme getSchemeById(int schemeId) throws ProfitMandiBusinessException {
210
		Scheme scheme = schemeRepository.selectById(schemeId);
23444 amit.gupta 211
		if (!scheme.isRetailerAll()) {
23019 ashik.ali 212
			List<Integer> retailerIds = retailerSchemeRepository.selectRetailerIdsBySchemeId(scheme.getId());
213
			scheme.getRetailerIds().addAll(retailerIds);
22859 ashik.ali 214
		}
215
		List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(scheme.getId());
23914 govind 216
		if (itemIds.size() > 0) {
217
			List<Item> items = itemRepository.selectByIds(new HashSet<>(itemIds));
218
			scheme.setItemStringMap(this.toItemStringMap(items));
23983 amit.gupta 219
		}
22859 ashik.ali 220
		return scheme;
221
	}
23444 amit.gupta 222
 
223
	public Map<Integer, String> toItemStringMap(List<Item> items) {
23339 ashik.ali 224
		Map<Integer, String> itemMap = new HashMap<>();
23444 amit.gupta 225
		for (Item item : items) {
23339 ashik.ali 226
			itemMap.put(item.getId(), this.getItemString(item));
227
		}
228
		return itemMap;
229
	}
23444 amit.gupta 230
 
231
	public String getItemString(Item item) {
23339 ashik.ali 232
		StringBuilder itemString = new StringBuilder();
23444 amit.gupta 233
		if (item.getBrand() != null && !item.getBrand().isEmpty()) {
23339 ashik.ali 234
			itemString.append(item.getBrand().trim());
235
		}
236
		itemString.append(" ");
23444 amit.gupta 237
		if (item.getModelName() != null && !item.getModelName().isEmpty()) {
23339 ashik.ali 238
			itemString.append(item.getModelName().trim());
239
		}
240
		itemString.append(" ");
23444 amit.gupta 241
		if (item.getModelNumber() != null && !item.getModelNumber().isEmpty()) {
23339 ashik.ali 242
			itemString.append(item.getModelNumber().trim());
243
		}
244
		itemString.append(" ");
23444 amit.gupta 245
		if (item.getColor() != null && !item.getColor().isEmpty()) {
23339 ashik.ali 246
			itemString.append(item.getColor().trim());
247
		}
248
		return itemString.toString();
249
	}
23444 amit.gupta 250
 
251
	private Set<Integer> schemeItemsToItemIds(List<SchemeItem> schemeItems) {
23339 ashik.ali 252
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 253
		for (SchemeItem schemeItem : schemeItems) {
23339 ashik.ali 254
			itemIds.add(schemeItem.getItemId());
255
		}
256
		return itemIds;
257
	}
23444 amit.gupta 258
 
23019 ashik.ali 259
	@Override
260
	public List<SchemeModel> getAllSchemeModels(LocalDateTime startDateTime, LocalDateTime endDateTime) {
261
		List<Scheme> schemes = schemeRepository.selectAllBetweenCreateTimestamp(startDateTime, endDateTime);
262
		Map<Integer, Scheme> schemeIdSchemeMap = this.toSchemeIdSchemeMap(schemes);
263
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
23339 ashik.ali 264
		Set<Integer> itemIds = this.schemeItemsToItemIds(schemeItems);
265
		List<Item> items = itemRepository.selectByIds(itemIds);
266
		Map<Integer, String> itemStringMap = this.toItemStringMap(items);
267
		this.addItemIdsToSchemes(schemeItems, schemeIdSchemeMap, itemStringMap);
23019 ashik.ali 268
		List<RetailerScheme> retailerSchemes = retailerSchemeRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
269
		this.addRetailerIdsToSchemes(retailerSchemes, schemeIdSchemeMap);
270
		return this.toSchemeModels(schemeIdSchemeMap);
271
	}
23444 amit.gupta 272
 
273
	private void addItemIdsToSchemes(List<SchemeItem> schemeItems, Map<Integer, Scheme> schemeIdSchemeMap,
274
			Map<Integer, String> itemStringMap) {
275
		for (SchemeItem schemeItem : schemeItems) {
276
			schemeIdSchemeMap.get(schemeItem.getSchemeId()).getItemStringMap().put(schemeItem.getItemId(),
277
					itemStringMap.get(schemeItem.getItemId()));
23019 ashik.ali 278
		}
279
	}
23444 amit.gupta 280
 
281
	private void addRetailerIdsToSchemes(List<RetailerScheme> retailerSchemes, Map<Integer, Scheme> schemeIdSchemeMap) {
282
		for (RetailerScheme retailerScheme : retailerSchemes) {
283
			schemeIdSchemeMap.get(retailerScheme.getSchemeId()).getRetailerIds().add(retailerScheme.getRetailerId());
23019 ashik.ali 284
		}
285
	}
23444 amit.gupta 286
 
287
	private List<SchemeModel> toSchemeModels(Map<Integer, Scheme> schemeIdSchemeMap) {
23019 ashik.ali 288
		List<SchemeModel> schemeModels = new ArrayList<>();
23444 amit.gupta 289
		for (Map.Entry<Integer, Scheme> schemeIdSchemeEntry : schemeIdSchemeMap.entrySet()) {
23019 ashik.ali 290
			schemeModels.add(this.toSchemeModel(schemeIdSchemeEntry.getValue()));
291
		}
292
		return schemeModels;
293
	}
23444 amit.gupta 294
 
295
	private SchemeModel toSchemeModel(Scheme scheme) {
23019 ashik.ali 296
		SchemeModel schemeModel = new SchemeModel();
297
		schemeModel.setSchemeId(scheme.getId());
298
		schemeModel.setName(scheme.getName());
299
		schemeModel.setDescription(scheme.getDescription());
300
		schemeModel.setSchemeType(scheme.getType().toString());
301
		schemeModel.setAmountType(scheme.getAmountType().toString());
302
		schemeModel.setAmount(scheme.getAmount());
303
		schemeModel.setStartDateTime(StringUtils.toString(scheme.getStartDateTime()));
304
		schemeModel.setEndDateTime(StringUtils.toString(scheme.getEndDateTime()));
305
		schemeModel.setCreateTimestamp(StringUtils.toString(scheme.getCreateTimestamp()));
306
		schemeModel.setActiveTimestamp(StringUtils.toString(scheme.getActiveTimestamp()));
307
		schemeModel.setExpireTimestamp(StringUtils.toString(scheme.getExpireTimestamp()));
308
		schemeModel.setCreatedBy(scheme.getCreatedBy());
23339 ashik.ali 309
		schemeModel.setItemStringMap(scheme.getItemStringMap());
23019 ashik.ali 310
		schemeModel.setRetailerIds(scheme.getRetailerIds());
311
		return schemeModel;
312
	}
22653 ashik.ali 313
 
314
	@Override
315
	public void activeSchemeById(int schemeId) throws ProfitMandiBusinessException {
316
		Scheme scheme = schemeRepository.selectById(schemeId);
23444 amit.gupta 317
		if (scheme.getActiveTimestamp() != null) {
318
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
319
					"SCHM_1005");
22653 ashik.ali 320
		}
23444 amit.gupta 321
		if (scheme.getExpireTimestamp() != null) {
322
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
323
					"SCHM_1006");
22653 ashik.ali 324
		}
22859 ashik.ali 325
		scheme.setActiveTimestamp(LocalDateTime.now());
326
		schemeRepository.persist(scheme);
23444 amit.gupta 327
		if (scheme.getType() == SchemeType.IN) {
23019 ashik.ali 328
			this.processPreviousPurchases(scheme);
23444 amit.gupta 329
		} else if (scheme.getType() == SchemeType.OUT) {
23019 ashik.ali 330
			this.processPreviousSales(scheme);
331
		}
22653 ashik.ali 332
	}
23444 amit.gupta 333
 
334
	private void processPreviousPurchases(Scheme scheme) throws ProfitMandiBusinessException {
335
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectBetweenDates(scheme.getStartDateTime(),
336
				scheme.getEndDateTime());
337
		if (inventoryItems.isEmpty()) {
23370 ashik.ali 338
			return;
339
		}
23019 ashik.ali 340
		List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(scheme.getId());
23444 amit.gupta 341
		if (itemIds.isEmpty()) {
23370 ashik.ali 342
			return;
343
		}
23339 ashik.ali 344
		List<Item> items = itemRepository.selectByIds(new HashSet<>(itemIds));
345
		Map<Integer, String> itemStringMap = this.toItemStringMap(items);
23444 amit.gupta 346
		List<InventoryItem> completedInventoryItems = this.toFilteredPurchaseCompletedInventoryItems(inventoryItems,
347
				itemIds, true);
348
		if (completedInventoryItems.isEmpty()) {
23370 ashik.ali 349
			return;
350
		}
23444 amit.gupta 351
		if (scheme.isRetailerAll()) {
352
			for (InventoryItem inventoryItem : completedInventoryItems) {
23019 ashik.ali 353
				float cashback = this.createSchemeInOut(scheme, inventoryItem);
24562 amit.gupta 354
				if (cashback > 0) {
355
					walletService.addAmountToWallet(inventoryItem.getFofoId(), inventoryItem.getPurchaseId(),
356
							WalletReferenceType.SCHEME_IN,
357
							"Added SCHEME_IN for item " + itemStringMap.get(inventoryItem.getItemId())
358
									+ " against invoiceNumber " + inventoryItem.getPurchase().getPurchaseReference(),
359
							cashback);
360
				}
23019 ashik.ali 361
			}
23444 amit.gupta 362
		} else {
23019 ashik.ali 363
			List<Integer> retailerIds = retailerSchemeRepository.selectRetailerIdsBySchemeId(scheme.getId());
23444 amit.gupta 364
			for (InventoryItem inventoryItem : completedInventoryItems) {
365
				if (retailerIds.contains(inventoryItem.getFofoId())) {
23019 ashik.ali 366
					float cashback = this.createSchemeInOut(scheme, inventoryItem);
24562 amit.gupta 367
					if (cashback > 0) {
368
						walletService.addAmountToWallet(inventoryItem.getFofoId(), inventoryItem.getPurchaseId(),
369
								WalletReferenceType.SCHEME_IN,
370
								"Added SCHEME_IN for item " + itemStringMap.get(inventoryItem.getItemId())
371
										+ " against invoiceNumber "
372
										+ inventoryItem.getPurchase().getPurchaseReference(),
373
								cashback);
374
					}
23019 ashik.ali 375
				}
376
			}
377
		}
23444 amit.gupta 378
 
23019 ashik.ali 379
	}
23444 amit.gupta 380
 
381
	private Map<Integer, Integer> toInventoryItemIdFofoOrderIdMap(List<FofoLineItem> fofoLineItems,
382
			Map<Integer, FofoOrderItem> fofoOrderItemIdFofoOrderItemMap) {
23019 ashik.ali 383
		Map<Integer, Integer> inventoryItemIdFofoOrderIdMap = new HashMap<>();
23444 amit.gupta 384
 
385
		for (FofoLineItem fofoLineItem : fofoLineItems) {
386
			inventoryItemIdFofoOrderIdMap.put(fofoLineItem.getInventoryItemId(),
23019 ashik.ali 387
					fofoOrderItemIdFofoOrderItemMap.get(fofoLineItem.getFofoOrderItemId()).getOrderId());
388
		}
389
		return inventoryItemIdFofoOrderIdMap;
390
	}
23444 amit.gupta 391
 
392
	private void processPreviousSales(Scheme scheme) throws ProfitMandiBusinessException {
393
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectBetweenDates(scheme.getStartDateTime(),
394
				scheme.getEndDateTime());
395
 
396
		if (fofoOrderItems.isEmpty()) {
23370 ashik.ali 397
			return;
398
		}
22653 ashik.ali 399
 
23444 amit.gupta 400
		Map<Integer, FofoOrderItem> fofoOrderItemIdFofoOrderItemMap = this
401
				.toFofoOrderItemIdFofoOrderItemMap(fofoOrderItems);
402
 
403
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository
404
				.selectByFofoOrderItemIds(fofoOrderItemIdFofoOrderItemMap.keySet());
405
 
406
		if (fofoLineItems.isEmpty()) {
23370 ashik.ali 407
			return;
408
		}
23444 amit.gupta 409
 
410
		Map<Integer, Integer> inventoryItemIdFofoOrderIdMap = this.toInventoryItemIdFofoOrderIdMap(fofoLineItems,
411
				fofoOrderItemIdFofoOrderItemMap);
412
 
413
		List<InventoryItem> inventoryItems = inventoryItemRepository
414
				.selectByIds(inventoryItemIdFofoOrderIdMap.keySet());
415
 
416
		if (inventoryItems.isEmpty()) {
23370 ashik.ali 417
			return;
418
		}
23444 amit.gupta 419
 
23019 ashik.ali 420
		List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(scheme.getId());
23444 amit.gupta 421
 
422
		if (itemIds.isEmpty()) {
23370 ashik.ali 423
			return;
424
		}
23444 amit.gupta 425
 
426
		List<InventoryItem> completedInventoryItems = this.toFilteredPurchaseCompletedInventoryItems(inventoryItems,
427
				itemIds, false);
428
 
429
		if (scheme.isRetailerAll()) {
430
			for (InventoryItem inventoryItem : completedInventoryItems) {
23019 ashik.ali 431
				float cashback = this.createSchemeInOut(scheme, inventoryItem);
24562 amit.gupta 432
				if (cashback > 0) {
433
					walletService.addAmountToWallet(inventoryItem.getFofoId(), inventoryItem.getPurchaseId(),
434
							WalletReferenceType.SCHEME_OUT, "Added for SCHEME_OUT", cashback);
435
				}
23019 ashik.ali 436
			}
23444 amit.gupta 437
		} else {
23019 ashik.ali 438
			List<Integer> retailerIds = retailerSchemeRepository.selectRetailerIdsBySchemeId(scheme.getId());
23444 amit.gupta 439
			for (InventoryItem inventoryItem : completedInventoryItems) {
440
				if (retailerIds.contains(inventoryItem.getFofoId())) {
23019 ashik.ali 441
					float cashback = this.createSchemeInOut(scheme, inventoryItem);
24562 amit.gupta 442
					if (cashback > 0) {
443
						walletService.addAmountToWallet(inventoryItem.getFofoId(),
444
								inventoryItemIdFofoOrderIdMap.get(inventoryItem.getId()),
445
								WalletReferenceType.SCHEME_OUT, "Added for SCHEME_OUT", cashback);
446
					}
23019 ashik.ali 447
				}
448
			}
449
		}
450
	}
23444 amit.gupta 451
 
452
	private Map<Integer, FofoOrderItem> toFofoOrderItemIdFofoOrderItemMap(List<FofoOrderItem> fofoOrderItems) {
23019 ashik.ali 453
		Map<Integer, FofoOrderItem> fofoOrderItemIdFofoOrderItemMap = new HashMap<>();
23444 amit.gupta 454
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
23019 ashik.ali 455
			fofoOrderItemIdFofoOrderItemMap.put(fofoOrderItem.getId(), fofoOrderItem);
456
		}
457
		return fofoOrderItemIdFofoOrderItemMap;
458
	}
23444 amit.gupta 459
 
460
	private List<InventoryItem> toFilteredPurchaseCompletedInventoryItems(List<InventoryItem> inventoryItems,
461
			List<Integer> itemIds, boolean purchase) {
23019 ashik.ali 462
		List<InventoryItem> completedInventoryItems = new ArrayList<>();
23444 amit.gupta 463
		for (InventoryItem inventoryItem : inventoryItems) {
464
			if (purchase && inventoryItem.getPurchase().getCompleteTimestamp() != null
465
					&& itemIds.contains(inventoryItem.getItemId())) {
23019 ashik.ali 466
				completedInventoryItems.add(inventoryItem);
23444 amit.gupta 467
			} else if (!purchase && itemIds.contains(inventoryItem.getItemId())) {
23297 ashik.ali 468
				completedInventoryItems.add(inventoryItem);
23019 ashik.ali 469
			}
470
		}
471
		return completedInventoryItems;
472
	}
23444 amit.gupta 473
 
22653 ashik.ali 474
	@Override
475
	public void expireSchemeById(int schemeId) throws ProfitMandiBusinessException {
476
		Scheme scheme = schemeRepository.selectById(schemeId);
23444 amit.gupta 477
		if (scheme.getActiveTimestamp() == null) {
478
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
479
					"SCHM_1007");
22653 ashik.ali 480
		}
23444 amit.gupta 481
		if (scheme.getExpireTimestamp() != null) {
482
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
483
					"SCHM_1008");
22653 ashik.ali 484
		}
22859 ashik.ali 485
		scheme.setExpireTimestamp(LocalDateTime.now());
486
		schemeRepository.persist(scheme);
22653 ashik.ali 487
	}
23444 amit.gupta 488
 
489
	private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
23019 ashik.ali 490
		Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
23444 amit.gupta 491
		for (Scheme scheme : schemes) {
23019 ashik.ali 492
			schemeIdSchemeMap.put(scheme.getId(), scheme);
22859 ashik.ali 493
		}
23019 ashik.ali 494
		return schemeIdSchemeMap;
22859 ashik.ali 495
	}
23444 amit.gupta 496
 
497
	private Set<Integer> inventoryItemSchemesMapToSchemeIds(Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap) {
22859 ashik.ali 498
		Set<Integer> schemeIds = new HashSet<>();
23444 amit.gupta 499
		for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
500
			for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
22859 ashik.ali 501
				schemeIds.add(scheme.getId());
502
			}
503
		}
504
		return schemeIds;
505
	}
23444 amit.gupta 506
 
507
	private Set<Integer> inventoryItemsToItemIds(List<InventoryItem> inventoryItems) {
22859 ashik.ali 508
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 509
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 510
			itemIds.add(inventoryItem.getItemId());
511
		}
512
		return itemIds;
513
	}
23444 amit.gupta 514
 
515
	private Map<Integer, Set<Scheme>> toItemIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
23019 ashik.ali 516
		Map<Integer, Scheme> schemeIdSchemesMap = this.toSchemeIdSchemeMap(schemes);
22859 ashik.ali 517
		Map<Integer, Set<Scheme>> itemIdSchemesMap = new HashMap<>();
23444 amit.gupta 518
		for (SchemeItem schemeItem : schemeItems) {
519
			if (!itemIdSchemesMap.containsKey(schemeItem.getItemId())) {
22859 ashik.ali 520
				Set<Scheme> schemesSet = new HashSet<>();
521
				schemesSet.add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
522
				itemIdSchemesMap.put(schemeItem.getItemId(), schemesSet);
23444 amit.gupta 523
			} else {
22859 ashik.ali 524
				itemIdSchemesMap.get(schemeItem.getItemId()).add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
525
			}
526
		}
527
		return itemIdSchemesMap;
528
	}
22653 ashik.ali 529
 
23444 amit.gupta 530
	private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
531
			List<InventoryItem> inventoryItems) {
22859 ashik.ali 532
		Set<Integer> schemeIds = new HashSet<>();
23444 amit.gupta 533
		for (Scheme scheme : schemes) {
22859 ashik.ali 534
			schemeIds.add(scheme.getId());
535
		}
536
		Set<Integer> itemIds = this.inventoryItemsToItemIds(inventoryItems);
537
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndItemIds(schemeIds, itemIds);
23444 amit.gupta 538
 
22859 ashik.ali 539
		Map<Integer, Set<Scheme>> itemIdSchemesMap = this.toItemIdSchemesMap(schemeItems, schemes);
540
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemsMap = new HashMap<>();
23444 amit.gupta 541
		for (InventoryItem inventoryItem : inventoryItems) {
542
			if (itemIdSchemesMap.containsKey(inventoryItem.getItemId())) {
22859 ashik.ali 543
				inventoryItemSchemsMap.put(inventoryItem, itemIdSchemesMap.get(inventoryItem.getItemId()));
544
			}
545
		}
546
		return inventoryItemSchemsMap;
547
	}
23444 amit.gupta 548
 
22859 ashik.ali 549
	@Override
23365 ashik.ali 550
	public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
23369 ashik.ali 551
		LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
23344 ashik.ali 552
		Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
23369 ashik.ali 553
		LOGGER.info("purchase is completed = {}", (purchase.getCompleteTimestamp() != null));
23444 amit.gupta 554
		if (purchase.getCompleteTimestamp() != null) {
25043 amit.gupta 555
			/*
556
			 * List<Order> orders =
557
			 * orderRepository.selectByAirwayBillOrInvoiceNumber(purchase.
558
			 * getPurchaseReference(), retailerId);
559
			 */
560
			/*
561
			 * if (!orders.isEmpty()) { billingTimestamp =
562
			 * orders.get(0).getBillingTimestamp(); }
563
			 */
564
			List<Scheme> schemes = schemeRepository.selectActiveAll(SchemeType.IN, purchase.getCompleteTimestamp());
23365 ashik.ali 565
			float totalCashback = 0;
23444 amit.gupta 566
			if (schemes.isEmpty()) {
23365 ashik.ali 567
				return;
568
			}
569
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
23444 amit.gupta 570
 
571
			Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
572
					inventoryItems);
573
 
574
			if (inventoryItemSchemesMap.isEmpty()) {
23365 ashik.ali 575
				return;
576
			}
577
			Map<InventoryItem, Set<Scheme>> notAllInventoryItemSchemesMap = new HashMap<>();
578
			Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
579
			Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 580
 
581
			for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
23365 ashik.ali 582
				Set<Scheme> notAllSchemes = new HashSet<>();
583
				Set<Scheme> allSchemes = new HashSet<>();
23444 amit.gupta 584
				for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
585
					if (!scheme.isRetailerAll()) {
23365 ashik.ali 586
						notAllSchemes.add(scheme);
23444 amit.gupta 587
					} else {
23365 ashik.ali 588
						allSchemes.add(scheme);
589
					}
22859 ashik.ali 590
				}
23365 ashik.ali 591
				notAllInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), notAllSchemes);
592
				allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
593
				itemIds.add(inventoryItemSchemesEntry.getKey().getItemId());
22859 ashik.ali 594
			}
23444 amit.gupta 595
 
596
			int itemsCount = 0;
597
			for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
598
					.entrySet()) {
599
				float inventoryItemCashback = 0;
600
				for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
23365 ashik.ali 601
					InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
602
					float cashback = this.createSchemeInOut(scheme, inventoryItem);
23444 amit.gupta 603
					inventoryItemCashback += cashback;
23339 ashik.ali 604
				}
23444 amit.gupta 605
				if (inventoryItemCashback > 0) {
606
					totalCashback += inventoryItemCashback;
607
					itemsCount++;
608
				}
22859 ashik.ali 609
			}
23444 amit.gupta 610
 
23365 ashik.ali 611
			Set<Integer> schemeIds = this.inventoryItemSchemesMapToSchemeIds(notAllInventoryItemSchemesMap);
23444 amit.gupta 612
			if (!schemeIds.isEmpty()) {
23365 ashik.ali 613
				List<Integer> foundSchemeIds = retailerSchemeRepository.selectSchemeIds(schemeIds, retailerId);
23444 amit.gupta 614
				for (Map.Entry<InventoryItem, Set<Scheme>> notAllInventoryItemSchemesEntry : notAllInventoryItemSchemesMap
615
						.entrySet()) {
616
					float inventoryItemCashback = 0;
617
					for (Scheme scheme : notAllInventoryItemSchemesEntry.getValue()) {
618
						if (foundSchemeIds.contains(scheme.getId())) {
23365 ashik.ali 619
							InventoryItem inventoryItem = notAllInventoryItemSchemesEntry.getKey();
620
							float cashback = this.createSchemeInOut(scheme, inventoryItem);
23444 amit.gupta 621
							inventoryItemCashback += cashback;
23339 ashik.ali 622
						}
22653 ashik.ali 623
					}
23444 amit.gupta 624
					if (inventoryItemCashback > 0) {
625
						totalCashback += inventoryItemCashback;
626
						itemsCount++;
627
					}
22653 ashik.ali 628
				}
629
			}
23511 amit.gupta 630
			LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
23796 amit.gupta 631
			if (itemsCount > 0) {
23508 amit.gupta 632
				walletService.addAmountToWallet(retailerId, purchaseId, WalletReferenceType.SCHEME_IN,
23796 amit.gupta 633
						"Added for SCHEME IN against invoice " + purchase.getPurchaseReference() + " (total "
634
								+ itemsCount + " pcs)",
635
						totalCashback);
636
				LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
637
						purchase.getPurchaseReference(), itemsCount);
23508 amit.gupta 638
				purchase.setCashback(purchase.getCashback() + totalCashback);
639
				purchaseRepository.persist(purchase);
640
			}
22653 ashik.ali 641
		}
642
	}
23444 amit.gupta 643
 
644
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
24562 amit.gupta 645
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
23443 amit.gupta 646
		float amount = 0;
24581 amit.gupta 647
		if (schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList())
24562 amit.gupta 648
				.size() == 0) {
649
			SchemeInOut schemeInOut = new SchemeInOut();
23443 amit.gupta 650
			amount = this.getAmount(inventoryItem, scheme);
651
			schemeInOut.setSchemeId(scheme.getId());
652
			schemeInOut.setInventoryItemId(inventoryItem.getId());
653
			schemeInOut.setAmount(amount);
654
			schemeInOutRepository.persist(schemeInOut);
655
		}
22859 ashik.ali 656
		return amount;
657
	}
23444 amit.gupta 658
 
25049 amit.gupta 659
	// We are maintaining price drop after grn
23444 amit.gupta 660
	private float getAmount(InventoryItem inventoryItem, Scheme scheme) {
22653 ashik.ali 661
		float amount = 0;
25049 amit.gupta 662
		float dpForCalc = 0;
663
		float taxableSellingPrice = 0;
22859 ashik.ali 664
		float totalTaxRate = inventoryItem.getIgstRate() + inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
23527 ashik.ali 665
		if (scheme.getAmountType() == AmountType.PERCENTAGE) {
24562 amit.gupta 666
			if (scheme.getType().equals(SchemeType.IN)) {
25049 amit.gupta 667
				dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
23995 amit.gupta 668
			} else {
669
				try {
25049 amit.gupta 670
					dpForCalc = tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice();
24562 amit.gupta 671
				} catch (Exception e) {
23995 amit.gupta 672
					LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
673
					e.printStackTrace();
674
				}
675
			}
25049 amit.gupta 676
			taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
22859 ashik.ali 677
			amount = taxableSellingPrice * scheme.getAmount() / 100;
25050 amit.gupta 678
			System.out.println(String.format("%d\t%s\t%d\t%d\t%s\t%s\t%s\t%f\t%f\t%f", inventoryItem.getId(),
679
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
680
					scheme.getType(), scheme.getAmountType(), dpForCalc, taxableSellingPrice, amount));
23444 amit.gupta 681
		} else {
25043 amit.gupta 682
			/*
683
			 * List<SchemeInOut> sios = schemeInOutRepository.selectByInventoryItemIds(new
684
			 * HashSet<>(Arrays.asList(inventoryItem.getId()))); List<Integer> schemeIds =
685
			 * sios.stream().filter(x->x.getSchemeType().equals(SchemeType.IN)).map(x->x.
686
			 * getSchemeId()).collect(Collectors.toList()); List<Scheme> schemes =
687
			 * schemeRepository.selectBySchemeIds(schemeIds, 0, 0); if(schemes.
688
			 */
22653 ashik.ali 689
			amount = scheme.getAmount();
25050 amit.gupta 690
			System.out.println(String.format("%d\t%s\t%d\t%d\t%s\t%s\t%s\t%f\t%f\t%f", inventoryItem.getId(),
691
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
692
					scheme.getType(), scheme.getAmountType(), dpForCalc, taxableSellingPrice, amount));
22653 ashik.ali 693
		}
25049 amit.gupta 694
 
22859 ashik.ali 695
		return amount;
22653 ashik.ali 696
	}
23444 amit.gupta 697
 
22653 ashik.ali 698
	@Override
23365 ashik.ali 699
	public void processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
700
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
23444 amit.gupta 701
 
25043 amit.gupta 702
		List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
703
		Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
704
				.collect(Collectors.toSet());
705
		Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
706
				.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
707
				.collect(Collectors.toSet());
23444 amit.gupta 708
 
25043 amit.gupta 709
		if (inventoryItems.size() == 0) {
23365 ashik.ali 710
			return;
22859 ashik.ali 711
		}
23444 amit.gupta 712
 
25043 amit.gupta 713
		float totalCashback = 0;
714
		int count = 0;
23444 amit.gupta 715
 
25051 amit.gupta 716
		Set<Scheme> allFixedSchemes = schemeRepository.selectActiveAll(SchemeType.OUT, fofoOrder.getCreateTimestamp())
25050 amit.gupta 717
				.stream().filter(scheme -> scheme.getAmountType().equals(AmountType.FIXED))
25051 amit.gupta 718
				.collect(Collectors.toSet());
25050 amit.gupta 719
 
25043 amit.gupta 720
		for (InventoryItem inventoryItem : inventoryItems) {
721
			int itemCashback = 0;
722
			Purchase purchase = purchaseRepository.selectByIdAndFofoId(inventoryItem.getPurchaseId(), retailerId);
723
			Set<Integer> schemeIds = new HashSet<>(
724
					schemeItemRepository.selectSchemeIdByItemId(inventoryItem.getItemId()));
25051 amit.gupta 725
			Set<Scheme> schemes = schemeRepository.selectActiveAll(SchemeType.OUT, purchase.getCompleteTimestamp())
726
					.stream().filter(x->x.getAmountType().equals(AmountType.PERCENTAGE)).collect(Collectors.toSet());
25050 amit.gupta 727
			schemes.addAll(allFixedSchemes);
25052 amit.gupta 728
			schemes = schemes.stream()
25050 amit.gupta 729
				.filter(x -> schemeIds.contains(x.getId()))
25052 amit.gupta 730
				.collect(Collectors.toSet());
25043 amit.gupta 731
			for (Scheme scheme : schemes) {
732
				itemCashback += this.createSchemeInOut(scheme, inventoryItem);
22653 ashik.ali 733
			}
25043 amit.gupta 734
			if (itemCashback > 0) {
735
				count++;
736
				totalCashback += itemCashback;
22859 ashik.ali 737
			}
22653 ashik.ali 738
		}
25043 amit.gupta 739
		if (count > 0) {
23444 amit.gupta 740
			walletService.addAmountToWallet(retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT,
23796 amit.gupta 741
					"Sales margin for invoice number " + fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
742
					totalCashback);
23365 ashik.ali 743
			fofoOrder.setCashback(totalCashback);
744
			fofoOrderRepository.persist(fofoOrder);
22859 ashik.ali 745
		}
22653 ashik.ali 746
	}
23444 amit.gupta 747
 
23508 amit.gupta 748
	@Override
23796 amit.gupta 749
	public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
750
			throws Exception {
23638 amit.gupta 751
		Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
23508 amit.gupta 752
		float amountToRollback = 0;
753
		List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
23796 amit.gupta 754
		for (SchemeInOut schemeInOut : schemes) {
23983 amit.gupta 755
			if (schemeInOut.getRolledBackTimestamp() == null) {
756
				schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
757
				schemeInOutRepository.persist(schemeInOut);
758
				amountToRollback += schemeInOut.getAmount();
759
			}
23508 amit.gupta 760
		}
23983 amit.gupta 761
		if (amountToRollback > 0) {
23638 amit.gupta 762
			int inventoryItemId = inventoryItemIds.get(0);
763
			Integer fofoId = inventoryItemRepository.selectById(inventoryItemId).getFofoId();
23796 amit.gupta 764
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, rollbackReference,
765
					WalletReferenceType.SCHEME_IN, rollbackReason);
23638 amit.gupta 766
		}
23508 amit.gupta 767
	}
23884 amit.gupta 768
 
23781 ashik.ali 769
	@Override
23796 amit.gupta 770
	public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
771
			throws ProfitMandiBusinessException {
23781 ashik.ali 772
		Map<String, Object> map = new HashMap<>();
773
		List<Scheme> schemes = null;
774
		long size = 0;
23798 amit.gupta 775
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 776
			schemes = schemeRepository.selectAll(offset, limit);
777
			size = schemeRepository.selectAllCount();
23796 amit.gupta 778
		} else {
23781 ashik.ali 779
			schemes = schemeRepository.selectActiveAll(offset, limit);
780
			size = schemeRepository.selectAllActiveCount();
781
		}
782
		map.put("schemes", schemes);
783
		map.put("start", offset + 1);
784
		map.put("size", size);
23796 amit.gupta 785
		if (schemes.size() < limit) {
23781 ashik.ali 786
			map.put("end", offset + schemes.size());
23796 amit.gupta 787
		} else {
23781 ashik.ali 788
			map.put("end", offset + limit);
789
		}
790
		return map;
791
	}
23796 amit.gupta 792
 
23781 ashik.ali 793
	@Override
23796 amit.gupta 794
	public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
795
			throws ProfitMandiBusinessException {
23781 ashik.ali 796
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
797
		List<Scheme> schemes = null;
23798 amit.gupta 798
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 799
			schemes = schemeRepository.selectAll(offset, limit);
23796 amit.gupta 800
		} else {
23781 ashik.ali 801
			schemes = schemeRepository.selectActiveAll(offset, limit);
802
		}
803
		return schemes;
804
	}
23508 amit.gupta 805
 
23968 amit.gupta 806
	@Override
24976 amit.gupta 807
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
23968 amit.gupta 808
			throws Exception {
24976 amit.gupta 809
 
810
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
811
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
812
 
813
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
814
			float amountToCredit = 0;
815
			float amountToDebit = 0;
816
			int purchaseId = purchaseEntry.getKey();
817
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
818
 
819
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
820
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
821
 
822
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
823
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
824
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
825
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
826
			for (SchemeInOut schemeInOut : schemeInOuts) {
827
				InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
828
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
829
				if (scheme.getType().equals(SchemeType.OUT))
830
					continue;
831
				if (scheme.getAmountType().equals(AmountType.FIXED)) {
832
					continue;
23995 amit.gupta 833
				}
24976 amit.gupta 834
				if (schemeInOut.getRolledBackTimestamp() == null) {
835
					float newAmount = getAmount(ii, scheme);
836
					if (schemeInOut.getAmount() - newAmount >= 0.01f) {
837
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
838
						schemeInOutRepository.persist(schemeInOut);
839
						SchemeInOut sioNew = new SchemeInOut();
840
						sioNew.setAmount(newAmount);
841
						sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
842
						sioNew.setSchemeId(schemeInOut.getSchemeId());
843
						schemeInOutRepository.persist(sioNew);
844
						amountToCredit += sioNew.getAmount();
845
						amountToDebit += schemeInOut.getAmount();
846
					}
24562 amit.gupta 847
 
24976 amit.gupta 848
				}
23986 amit.gupta 849
			}
24976 amit.gupta 850
			int fofoId = inventoryItems.get(0).getFofoId();
851
			if (amountToDebit > 0) {
852
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN, reversalReason,
853
						-amountToDebit);
854
			}
855
			if (amountToCredit > 0) {
856
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN, reversalReason,
857
						amountToCredit);
858
			}
23968 amit.gupta 859
		}
860
	}
24562 amit.gupta 861
 
24264 amit.gupta 862
	@Override
24562 amit.gupta 863
	public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
864
			SchemeType schemeType) throws ProfitMandiBusinessException {
24264 amit.gupta 865
		Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
866
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
867
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
868
		List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
869
		float amount = 0;
870
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size()).stream()
871
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
872
		for (SchemeInOut schemeInOut : schemeInOuts) {
873
			Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
24562 amit.gupta 874
			if (scheme.getType().equals(schemeType)) {
875
				if (schemeInOut.getRolledBackTimestamp() == null) {
24264 amit.gupta 876
					schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
877
					schemeInOutRepository.persist(schemeInOut);
878
					amount += schemeInOut.getAmount();
879
				}
880
			}
881
		}
882
		int fofoId = inventoryItems.get(0).getFofoId();
24562 amit.gupta 883
		WalletReferenceType walletReferenceType = schemeType.equals(SchemeType.OUT) ? WalletReferenceType.SCHEME_OUT
884
				: WalletReferenceType.SCHEME_IN;
885
		if (amount > 0) {
886
			walletService.rollbackAmountFromWallet(fofoId, amount, reversalReference, walletReferenceType,
887
					reversalReason);
24268 amit.gupta 888
		}
24264 amit.gupta 889
	}
23968 amit.gupta 890
 
24976 amit.gupta 891
	/*
892
	 * @Override public void updateSchmesForModel(int catalogId) throws
893
	 * ProfitMandiBusinessException { List<Item> items =
894
	 * itemRepository.selectAllByCatalogItemId(catalogId); Map<Integer, Scheme>
895
	 * schemes = schemeRepository .selectAllByItemIds(items.stream().map(x ->
896
	 * x.getId()).collect(Collectors.toList()));
897
	 * 
898
	 * }
899
	 */
24562 amit.gupta 900
 
22653 ashik.ali 901
}