Subversion Repositories SmartDukaan

Rev

Rev 25831 | Rev 26332 | 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
 
25507 amit.gupta 3
import java.time.LocalDate;
22859 ashik.ali 4
import java.time.LocalDateTime;
23019 ashik.ali 5
import java.util.ArrayList;
22653 ashik.ali 6
import java.util.HashMap;
22859 ashik.ali 7
import java.util.HashSet;
22653 ashik.ali 8
import java.util.List;
9
import java.util.Map;
10
import java.util.Set;
23968 amit.gupta 11
import java.util.stream.Collectors;
22653 ashik.ali 12
 
23781 ashik.ali 13
import org.apache.logging.log4j.LogManager;
23568 govind 14
import org.apache.logging.log4j.Logger;
22653 ashik.ali 15
import org.springframework.beans.factory.annotation.Autowired;
23781 ashik.ali 16
import org.springframework.beans.factory.annotation.Qualifier;
22653 ashik.ali 17
import org.springframework.stereotype.Component;
18
 
24307 amit.gupta 19
import com.spice.profitmandi.common.enumuration.ItemType;
22653 ashik.ali 20
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
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;
23365 ashik.ali 27
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
22653 ashik.ali 28
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
25503 amit.gupta 29
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
23339 ashik.ali 30
import com.spice.profitmandi.dao.entity.fofo.Purchase;
25043 amit.gupta 31
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
22859 ashik.ali 32
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
33
import com.spice.profitmandi.dao.entity.fofo.SchemeItem;
23527 ashik.ali 34
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
22653 ashik.ali 35
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25111 amit.gupta 36
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
25503 amit.gupta 37
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
22859 ashik.ali 38
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
22653 ashik.ali 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;
25503 amit.gupta 46
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
23339 ashik.ali 47
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
25043 amit.gupta 48
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
22859 ashik.ali 49
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
50
import com.spice.profitmandi.dao.repository.fofo.SchemeItemRepository;
23798 amit.gupta 51
import com.spice.profitmandi.service.authentication.RoleManager;
22859 ashik.ali 52
import com.spice.profitmandi.service.wallet.WalletService;
22653 ashik.ali 53
 
22859 ashik.ali 54
import in.shop2020.model.v1.order.WalletReferenceType;
55
 
22653 ashik.ali 56
@Component
57
public class SchemeServiceImpl implements SchemeService {
58
 
23568 govind 59
	private static final Logger LOGGER = LogManager.getLogger(SchemeServiceImpl.class);
23444 amit.gupta 60
 
22653 ashik.ali 61
	@Autowired
23781 ashik.ali 62
	@Qualifier("fofoInventoryItemRepository")
22653 ashik.ali 63
	private InventoryItemRepository inventoryItemRepository;
23444 amit.gupta 64
 
22653 ashik.ali 65
	@Autowired
25503 amit.gupta 66
	private PartnerTypeChangeService partnerTypeChangeService;
67
 
68
	@Autowired
25043 amit.gupta 69
	private ScanRecordRepository scanRecordRepository;
23444 amit.gupta 70
 
22653 ashik.ali 71
	@Autowired
72
	private SchemeRepository schemeRepository;
23444 amit.gupta 73
 
22653 ashik.ali 74
	@Autowired
23798 amit.gupta 75
	private RoleManager roleManager;
76
 
77
	@Autowired
22859 ashik.ali 78
	private RetailerRepository retailerRepository;
24562 amit.gupta 79
 
23995 amit.gupta 80
	@Autowired
81
	private TagListingRepository tagListingRepository;
23444 amit.gupta 82
 
22859 ashik.ali 83
	@Autowired
84
	private SchemeInOutRepository schemeInOutRepository;
23444 amit.gupta 85
 
22653 ashik.ali 86
	@Autowired
23781 ashik.ali 87
	@Qualifier("catalogItemRepository")
22859 ashik.ali 88
	private ItemRepository itemRepository;
23444 amit.gupta 89
 
22859 ashik.ali 90
	@Autowired
91
	private SchemeItemRepository schemeItemRepository;
23444 amit.gupta 92
 
22859 ashik.ali 93
	@Autowired
94
	private WalletService walletService;
23444 amit.gupta 95
 
23019 ashik.ali 96
	@Autowired
97
	private FofoOrderItemRepository fofoOrderItemRepository;
23444 amit.gupta 98
 
23019 ashik.ali 99
	@Autowired
100
	private FofoLineItemRepository fofoLineItemRepository;
23444 amit.gupta 101
 
23339 ashik.ali 102
	@Autowired
103
	private PurchaseRepository purchaseRepository;
23444 amit.gupta 104
 
23344 ashik.ali 105
	@Autowired
23365 ashik.ali 106
	private FofoOrderRepository fofoOrderRepository;
23796 amit.gupta 107
 
22653 ashik.ali 108
	@Override
22859 ashik.ali 109
	public void saveScheme(int creatorId, CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
23444 amit.gupta 110
 
23019 ashik.ali 111
		this.validateCreateSchemeRequest(createSchemeRequest);
23444 amit.gupta 112
 
22859 ashik.ali 113
		Scheme scheme = this.toScheme(creatorId, createSchemeRequest);
23444 amit.gupta 114
 
115
		if (scheme.getStartDateTime().isAfter(scheme.getEndDateTime())) {
116
			throw new ProfitMandiBusinessException(
117
					ProfitMandiConstants.START_DATE + ", " + ProfitMandiConstants.END_DATE,
118
					scheme.getStartDateTime() + ", " + scheme.getEndDateTime(), "SCHM_VE_1005");
22653 ashik.ali 119
		}
23444 amit.gupta 120
 
25831 amit.gupta 121
		//this.validateItemIds(createSchemeRequest);
22859 ashik.ali 122
		schemeRepository.persist(scheme);
23444 amit.gupta 123
		for (int itemId : createSchemeRequest.getItemIds()) {
22859 ashik.ali 124
			SchemeItem schemeItem = new SchemeItem();
125
			schemeItem.setSchemeId(scheme.getId());
126
			schemeItem.setItemId(itemId);
127
			schemeItemRepository.persist(schemeItem);
128
		}
23444 amit.gupta 129
 
22653 ashik.ali 130
	}
23444 amit.gupta 131
 
132
	private void validateCreateSchemeRequest(CreateSchemeRequest createSchemeRequest)
133
			throws ProfitMandiBusinessException {
134
		if (createSchemeRequest.getName() == null || createSchemeRequest.getName().isEmpty()) {
135
			throw new ProfitMandiBusinessException(ProfitMandiConstants.NAME, createSchemeRequest.getName(),
136
					"SCHM_VE_1000");
23019 ashik.ali 137
		}
23444 amit.gupta 138
		if (createSchemeRequest.getAmount() <= 0) {
139
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
140
					"SCHM_VE_1001");
23019 ashik.ali 141
		}
23444 amit.gupta 142
 
25503 amit.gupta 143
		if (createSchemeRequest.getAmountType().equals(AmountType.PERCENTAGE)
23444 amit.gupta 144
				&& createSchemeRequest.getAmount() > 100) {
145
			throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
146
					"SCHM_VE_1002");
23019 ashik.ali 147
		}
23444 amit.gupta 148
 
23886 amit.gupta 149
		if (createSchemeRequest.getStartDate() == null) {
23983 amit.gupta 150
			throw new ProfitMandiBusinessException(ProfitMandiConstants.START_DATE, createSchemeRequest.getStartDate(),
151
					"SCHM_VE_1003");
23019 ashik.ali 152
		}
23886 amit.gupta 153
		if (createSchemeRequest.getEndDate() == null) {
23983 amit.gupta 154
			throw new ProfitMandiBusinessException(ProfitMandiConstants.END_DATE, createSchemeRequest.getEndDate(),
155
					"SCHM_VE_1004");
23019 ashik.ali 156
		}
157
	}
23444 amit.gupta 158
 
159
	private Scheme toScheme(int creatorId, CreateSchemeRequest createSchemeRequest) {
22859 ashik.ali 160
		Scheme scheme = new Scheme();
161
		scheme.setName(createSchemeRequest.getName());
162
		scheme.setDescription(createSchemeRequest.getDescription());
25503 amit.gupta 163
		scheme.setType(createSchemeRequest.getType());
164
		scheme.setAmountType(createSchemeRequest.getAmountType());
22859 ashik.ali 165
		scheme.setAmount(createSchemeRequest.getAmount());
25503 amit.gupta 166
		scheme.setPartnerType(createSchemeRequest.getPartnerType());
25517 amit.gupta 167
		scheme.setStartDateTime(createSchemeRequest.getStartDate());
23886 amit.gupta 168
		scheme.setEndDateTime(createSchemeRequest.getEndDate());
22859 ashik.ali 169
		scheme.setCreatedBy(creatorId);
170
		return scheme;
171
	}
23444 amit.gupta 172
 
173
	private void validateItemIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
174
		if (createSchemeRequest.getItemIds() == null || createSchemeRequest.getItemIds().isEmpty()) {
175
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
176
					"SCHM_1003");
22859 ashik.ali 177
		}
23444 amit.gupta 178
		List<Integer> foundItemIds = itemRepository.selectIdsByIdsAndType(createSchemeRequest.getItemIds(),
179
				ItemType.SERIALIZED);
180
		if (foundItemIds.size() != createSchemeRequest.getItemIds().size()) {
22859 ashik.ali 181
			createSchemeRequest.getItemIds().removeAll(foundItemIds);
23444 amit.gupta 182
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getItemIds(),
183
					"SCHM_1004");
22859 ashik.ali 184
		}
185
	}
23444 amit.gupta 186
 
22859 ashik.ali 187
	@Override
188
	public Scheme getSchemeById(int schemeId) throws ProfitMandiBusinessException {
189
		Scheme scheme = schemeRepository.selectById(schemeId);
190
		List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(scheme.getId());
23914 govind 191
		if (itemIds.size() > 0) {
192
			List<Item> items = itemRepository.selectByIds(new HashSet<>(itemIds));
193
			scheme.setItemStringMap(this.toItemStringMap(items));
23983 amit.gupta 194
		}
22859 ashik.ali 195
		return scheme;
196
	}
23444 amit.gupta 197
 
198
	public Map<Integer, String> toItemStringMap(List<Item> items) {
23339 ashik.ali 199
		Map<Integer, String> itemMap = new HashMap<>();
23444 amit.gupta 200
		for (Item item : items) {
23339 ashik.ali 201
			itemMap.put(item.getId(), this.getItemString(item));
202
		}
203
		return itemMap;
204
	}
23444 amit.gupta 205
 
206
	public String getItemString(Item item) {
23339 ashik.ali 207
		StringBuilder itemString = new StringBuilder();
23444 amit.gupta 208
		if (item.getBrand() != null && !item.getBrand().isEmpty()) {
23339 ashik.ali 209
			itemString.append(item.getBrand().trim());
210
		}
211
		itemString.append(" ");
23444 amit.gupta 212
		if (item.getModelName() != null && !item.getModelName().isEmpty()) {
23339 ashik.ali 213
			itemString.append(item.getModelName().trim());
214
		}
215
		itemString.append(" ");
23444 amit.gupta 216
		if (item.getModelNumber() != null && !item.getModelNumber().isEmpty()) {
23339 ashik.ali 217
			itemString.append(item.getModelNumber().trim());
218
		}
219
		itemString.append(" ");
23444 amit.gupta 220
		if (item.getColor() != null && !item.getColor().isEmpty()) {
23339 ashik.ali 221
			itemString.append(item.getColor().trim());
222
		}
223
		return itemString.toString();
224
	}
23444 amit.gupta 225
 
226
	private Set<Integer> schemeItemsToItemIds(List<SchemeItem> schemeItems) {
23339 ashik.ali 227
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 228
		for (SchemeItem schemeItem : schemeItems) {
23339 ashik.ali 229
			itemIds.add(schemeItem.getItemId());
230
		}
231
		return itemIds;
232
	}
23444 amit.gupta 233
 
23019 ashik.ali 234
	@Override
235
	public List<SchemeModel> getAllSchemeModels(LocalDateTime startDateTime, LocalDateTime endDateTime) {
236
		List<Scheme> schemes = schemeRepository.selectAllBetweenCreateTimestamp(startDateTime, endDateTime);
237
		Map<Integer, Scheme> schemeIdSchemeMap = this.toSchemeIdSchemeMap(schemes);
238
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
23339 ashik.ali 239
		Set<Integer> itemIds = this.schemeItemsToItemIds(schemeItems);
240
		List<Item> items = itemRepository.selectByIds(itemIds);
241
		Map<Integer, String> itemStringMap = this.toItemStringMap(items);
242
		this.addItemIdsToSchemes(schemeItems, schemeIdSchemeMap, itemStringMap);
23019 ashik.ali 243
		return this.toSchemeModels(schemeIdSchemeMap);
244
	}
23444 amit.gupta 245
 
246
	private void addItemIdsToSchemes(List<SchemeItem> schemeItems, Map<Integer, Scheme> schemeIdSchemeMap,
247
			Map<Integer, String> itemStringMap) {
248
		for (SchemeItem schemeItem : schemeItems) {
249
			schemeIdSchemeMap.get(schemeItem.getSchemeId()).getItemStringMap().put(schemeItem.getItemId(),
250
					itemStringMap.get(schemeItem.getItemId()));
23019 ashik.ali 251
		}
252
	}
23444 amit.gupta 253
 
254
	private void addRetailerIdsToSchemes(List<RetailerScheme> retailerSchemes, Map<Integer, Scheme> schemeIdSchemeMap) {
255
		for (RetailerScheme retailerScheme : retailerSchemes) {
256
			schemeIdSchemeMap.get(retailerScheme.getSchemeId()).getRetailerIds().add(retailerScheme.getRetailerId());
23019 ashik.ali 257
		}
258
	}
23444 amit.gupta 259
 
260
	private List<SchemeModel> toSchemeModels(Map<Integer, Scheme> schemeIdSchemeMap) {
23019 ashik.ali 261
		List<SchemeModel> schemeModels = new ArrayList<>();
23444 amit.gupta 262
		for (Map.Entry<Integer, Scheme> schemeIdSchemeEntry : schemeIdSchemeMap.entrySet()) {
23019 ashik.ali 263
			schemeModels.add(this.toSchemeModel(schemeIdSchemeEntry.getValue()));
264
		}
265
		return schemeModels;
266
	}
23444 amit.gupta 267
 
268
	private SchemeModel toSchemeModel(Scheme scheme) {
23019 ashik.ali 269
		SchemeModel schemeModel = new SchemeModel();
270
		schemeModel.setSchemeId(scheme.getId());
271
		schemeModel.setName(scheme.getName());
272
		schemeModel.setDescription(scheme.getDescription());
273
		schemeModel.setSchemeType(scheme.getType().toString());
274
		schemeModel.setAmountType(scheme.getAmountType().toString());
275
		schemeModel.setAmount(scheme.getAmount());
276
		schemeModel.setStartDateTime(StringUtils.toString(scheme.getStartDateTime()));
277
		schemeModel.setEndDateTime(StringUtils.toString(scheme.getEndDateTime()));
278
		schemeModel.setCreateTimestamp(StringUtils.toString(scheme.getCreateTimestamp()));
279
		schemeModel.setActiveTimestamp(StringUtils.toString(scheme.getActiveTimestamp()));
280
		schemeModel.setExpireTimestamp(StringUtils.toString(scheme.getExpireTimestamp()));
281
		schemeModel.setCreatedBy(scheme.getCreatedBy());
23339 ashik.ali 282
		schemeModel.setItemStringMap(scheme.getItemStringMap());
23019 ashik.ali 283
		schemeModel.setRetailerIds(scheme.getRetailerIds());
284
		return schemeModel;
285
	}
22653 ashik.ali 286
 
287
	@Override
288
	public void activeSchemeById(int schemeId) throws ProfitMandiBusinessException {
289
		Scheme scheme = schemeRepository.selectById(schemeId);
23444 amit.gupta 290
		if (scheme.getActiveTimestamp() != null) {
291
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
292
					"SCHM_1005");
22653 ashik.ali 293
		}
23444 amit.gupta 294
		if (scheme.getExpireTimestamp() != null) {
295
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
296
					"SCHM_1006");
22653 ashik.ali 297
		}
22859 ashik.ali 298
		scheme.setActiveTimestamp(LocalDateTime.now());
299
		schemeRepository.persist(scheme);
25438 amit.gupta 300
		/*
301
		 * if (scheme.getType() == SchemeType.IN) {
302
		 * this.processPreviousPurchases(scheme); } else if (scheme.getType() ==
303
		 * SchemeType.OUT) { this.processPreviousSales(scheme); }
304
		 */
22653 ashik.ali 305
	}
23444 amit.gupta 306
 
22653 ashik.ali 307
	@Override
25069 amit.gupta 308
	public void expireSchemeById(int schemeId, LocalDateTime expiryTime) throws ProfitMandiBusinessException {
22653 ashik.ali 309
		Scheme scheme = schemeRepository.selectById(schemeId);
25111 amit.gupta 310
		if (scheme == null || scheme.getActiveTimestamp() == null) {
23444 amit.gupta 311
			throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
312
					"SCHM_1007");
22653 ashik.ali 313
		}
23444 amit.gupta 314
		if (scheme.getExpireTimestamp() != null) {
315
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
316
					"SCHM_1008");
22653 ashik.ali 317
		}
22859 ashik.ali 318
		scheme.setExpireTimestamp(LocalDateTime.now());
25069 amit.gupta 319
		scheme.setEndDateTime(expiryTime);
22859 ashik.ali 320
		schemeRepository.persist(scheme);
22653 ashik.ali 321
	}
23444 amit.gupta 322
 
323
	private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
23019 ashik.ali 324
		Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
23444 amit.gupta 325
		for (Scheme scheme : schemes) {
23019 ashik.ali 326
			schemeIdSchemeMap.put(scheme.getId(), scheme);
22859 ashik.ali 327
		}
23019 ashik.ali 328
		return schemeIdSchemeMap;
22859 ashik.ali 329
	}
23444 amit.gupta 330
 
331
	private Set<Integer> inventoryItemsToItemIds(List<InventoryItem> inventoryItems) {
22859 ashik.ali 332
		Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 333
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 334
			itemIds.add(inventoryItem.getItemId());
335
		}
336
		return itemIds;
337
	}
23444 amit.gupta 338
 
339
	private Map<Integer, Set<Scheme>> toItemIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
23019 ashik.ali 340
		Map<Integer, Scheme> schemeIdSchemesMap = this.toSchemeIdSchemeMap(schemes);
22859 ashik.ali 341
		Map<Integer, Set<Scheme>> itemIdSchemesMap = new HashMap<>();
23444 amit.gupta 342
		for (SchemeItem schemeItem : schemeItems) {
343
			if (!itemIdSchemesMap.containsKey(schemeItem.getItemId())) {
22859 ashik.ali 344
				Set<Scheme> schemesSet = new HashSet<>();
345
				schemesSet.add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
346
				itemIdSchemesMap.put(schemeItem.getItemId(), schemesSet);
23444 amit.gupta 347
			} else {
22859 ashik.ali 348
				itemIdSchemesMap.get(schemeItem.getItemId()).add(schemeIdSchemesMap.get(schemeItem.getSchemeId()));
349
			}
350
		}
351
		return itemIdSchemesMap;
352
	}
22653 ashik.ali 353
 
23444 amit.gupta 354
	private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
355
			List<InventoryItem> inventoryItems) {
22859 ashik.ali 356
		Set<Integer> schemeIds = new HashSet<>();
23444 amit.gupta 357
		for (Scheme scheme : schemes) {
22859 ashik.ali 358
			schemeIds.add(scheme.getId());
359
		}
360
		Set<Integer> itemIds = this.inventoryItemsToItemIds(inventoryItems);
361
		List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndItemIds(schemeIds, itemIds);
23444 amit.gupta 362
 
22859 ashik.ali 363
		Map<Integer, Set<Scheme>> itemIdSchemesMap = this.toItemIdSchemesMap(schemeItems, schemes);
364
		Map<InventoryItem, Set<Scheme>> inventoryItemSchemsMap = new HashMap<>();
23444 amit.gupta 365
		for (InventoryItem inventoryItem : inventoryItems) {
366
			if (itemIdSchemesMap.containsKey(inventoryItem.getItemId())) {
22859 ashik.ali 367
				inventoryItemSchemsMap.put(inventoryItem, itemIdSchemesMap.get(inventoryItem.getItemId()));
368
			}
369
		}
370
		return inventoryItemSchemsMap;
371
	}
23444 amit.gupta 372
 
22859 ashik.ali 373
	@Override
23365 ashik.ali 374
	public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
23369 ashik.ali 375
		LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
23344 ashik.ali 376
		Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
25503 amit.gupta 377
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
378
				purchase.getCreateTimestamp().toLocalDate());
23369 ashik.ali 379
		LOGGER.info("purchase is completed = {}", (purchase.getCompleteTimestamp() != null));
23444 amit.gupta 380
		if (purchase.getCompleteTimestamp() != null) {
25507 amit.gupta 381
			List<Scheme> schemes = schemeRepository.selectActiveAll(SchemeType.IN, partnerType,
382
					purchase.getCompleteTimestamp());
23365 ashik.ali 383
			float totalCashback = 0;
23444 amit.gupta 384
			if (schemes.isEmpty()) {
23365 ashik.ali 385
				return;
386
			}
387
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
26296 amit.gupta 388
 
389
			//Only consider inventory items that were not returned
390
			inventoryItems = inventoryItems.stream().filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD)
391
					&& !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
25487 amit.gupta 392
			LOGGER.info(inventoryItems);
25438 amit.gupta 393
			if (inventoryItems.size() == 0)
394
				return;
23444 amit.gupta 395
			Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
396
					inventoryItems);
397
 
398
			if (inventoryItemSchemesMap.isEmpty()) {
23365 ashik.ali 399
				return;
400
			}
401
			Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
402
			Set<Integer> itemIds = new HashSet<>();
23444 amit.gupta 403
 
404
			for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
23365 ashik.ali 405
				Set<Scheme> allSchemes = new HashSet<>();
23444 amit.gupta 406
				for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
25503 amit.gupta 407
					allSchemes.add(scheme);
22859 ashik.ali 408
				}
23365 ashik.ali 409
				allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
410
				itemIds.add(inventoryItemSchemesEntry.getKey().getItemId());
22859 ashik.ali 411
			}
23444 amit.gupta 412
 
413
			int itemsCount = 0;
414
			for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
415
					.entrySet()) {
416
				float inventoryItemCashback = 0;
417
				for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
23365 ashik.ali 418
					InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
419
					float cashback = this.createSchemeInOut(scheme, inventoryItem);
23444 amit.gupta 420
					inventoryItemCashback += cashback;
23339 ashik.ali 421
				}
23444 amit.gupta 422
				if (inventoryItemCashback > 0) {
423
					totalCashback += inventoryItemCashback;
424
					itemsCount++;
425
				}
22859 ashik.ali 426
			}
23444 amit.gupta 427
 
23511 amit.gupta 428
			LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
23796 amit.gupta 429
			if (itemsCount > 0) {
23508 amit.gupta 430
				walletService.addAmountToWallet(retailerId, purchaseId, WalletReferenceType.SCHEME_IN,
23796 amit.gupta 431
						"Added for SCHEME IN against invoice " + purchase.getPurchaseReference() + " (total "
432
								+ itemsCount + " pcs)",
433
						totalCashback);
434
				LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
435
						purchase.getPurchaseReference(), itemsCount);
23508 amit.gupta 436
				purchase.setCashback(purchase.getCashback() + totalCashback);
437
				purchaseRepository.persist(purchase);
438
			}
22653 ashik.ali 439
		}
440
	}
23444 amit.gupta 441
 
442
	private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem) {
24562 amit.gupta 443
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
23443 amit.gupta 444
		float amount = 0;
24581 amit.gupta 445
		if (schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList())
24562 amit.gupta 446
				.size() == 0) {
447
			SchemeInOut schemeInOut = new SchemeInOut();
23443 amit.gupta 448
			amount = this.getAmount(inventoryItem, scheme);
449
			schemeInOut.setSchemeId(scheme.getId());
450
			schemeInOut.setInventoryItemId(inventoryItem.getId());
451
			schemeInOut.setAmount(amount);
452
			schemeInOutRepository.persist(schemeInOut);
453
		}
22859 ashik.ali 454
		return amount;
455
	}
23444 amit.gupta 456
 
25049 amit.gupta 457
	// We are maintaining price drop after grn
23444 amit.gupta 458
	private float getAmount(InventoryItem inventoryItem, Scheme scheme) {
22653 ashik.ali 459
		float amount = 0;
25049 amit.gupta 460
		float dpForCalc = 0;
461
		float taxableSellingPrice = 0;
22859 ashik.ali 462
		float totalTaxRate = inventoryItem.getIgstRate() + inventoryItem.getSgstRate() + inventoryItem.getCgstRate();
23527 ashik.ali 463
		if (scheme.getAmountType() == AmountType.PERCENTAGE) {
24562 amit.gupta 464
			if (scheme.getType().equals(SchemeType.IN)) {
25049 amit.gupta 465
				dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
23995 amit.gupta 466
			} else {
467
				try {
25049 amit.gupta 468
					dpForCalc = tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice();
24562 amit.gupta 469
				} catch (Exception e) {
23995 amit.gupta 470
					LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
471
					e.printStackTrace();
472
				}
473
			}
25049 amit.gupta 474
			taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
22859 ashik.ali 475
			amount = taxableSellingPrice * scheme.getAmount() / 100;
25517 amit.gupta 476
			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 477
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
25517 amit.gupta 478
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice, scheme.getAmount(),
25054 amit.gupta 479
					amount));
23444 amit.gupta 480
		} else {
22653 ashik.ali 481
			amount = scheme.getAmount();
25517 amit.gupta 482
			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 483
					inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
25517 amit.gupta 484
					scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice, 0, amount));
22653 ashik.ali 485
		}
25049 amit.gupta 486
 
22859 ashik.ali 487
		return amount;
22653 ashik.ali 488
	}
23444 amit.gupta 489
 
22653 ashik.ali 490
	@Override
23365 ashik.ali 491
	public void processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
492
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
23444 amit.gupta 493
 
25507 amit.gupta 494
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
495
				fofoOrder.getCreateTimestamp().toLocalDate());
496
 
25043 amit.gupta 497
		List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
498
		Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
499
				.collect(Collectors.toSet());
500
		Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
501
				.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
502
				.collect(Collectors.toSet());
23444 amit.gupta 503
 
25043 amit.gupta 504
		if (inventoryItems.size() == 0) {
23365 ashik.ali 505
			return;
22859 ashik.ali 506
		}
23444 amit.gupta 507
 
25043 amit.gupta 508
		float totalCashback = 0;
509
		int count = 0;
23444 amit.gupta 510
 
25507 amit.gupta 511
		Set<Scheme> allFixedSchemes = schemeRepository
512
				.selectActiveAll(SchemeType.OUT, partnerType, fofoOrder.getCreateTimestamp()).stream()
513
				.filter(scheme -> scheme.getAmountType().equals(AmountType.FIXED)).collect(Collectors.toSet());
25050 amit.gupta 514
 
25043 amit.gupta 515
		for (InventoryItem inventoryItem : inventoryItems) {
25710 amit.gupta 516
			float itemCashback = 0;
25043 amit.gupta 517
			Purchase purchase = purchaseRepository.selectByIdAndFofoId(inventoryItem.getPurchaseId(), retailerId);
518
			Set<Integer> schemeIds = new HashSet<>(
519
					schemeItemRepository.selectSchemeIdByItemId(inventoryItem.getItemId()));
25507 amit.gupta 520
			List<Scheme> schemes = null;
25579 amit.gupta 521
			if(purchase.getCompleteTimestamp()==null) {
522
				continue;
523
			}
25507 amit.gupta 524
			if (purchase.getCompleteTimestamp().isAfter(LocalDate.of(2019, 9, 1).atStartOfDay())) {
525
				schemes = schemeRepository.selectActiveAll(SchemeType.OUT, partnerType, fofoOrder.getCreateTimestamp());
526
			} else {
527
				schemes = schemeRepository.selectActiveAll(SchemeType.OUT, partnerType,
528
						purchase.getCompleteTimestamp());
529
			}
530
			Set<Scheme> schemesSet = schemes.stream().filter(x -> x.getAmountType().equals(AmountType.PERCENTAGE))
531
					.collect(Collectors.toSet());
532
			schemesSet.addAll(allFixedSchemes);
533
			schemesSet = schemesSet.stream().filter(x -> schemeIds.contains(x.getId())).collect(Collectors.toSet());
534
			for (Scheme scheme : schemesSet) {
25043 amit.gupta 535
				itemCashback += this.createSchemeInOut(scheme, inventoryItem);
22653 ashik.ali 536
			}
25043 amit.gupta 537
			if (itemCashback > 0) {
538
				count++;
539
				totalCashback += itemCashback;
22859 ashik.ali 540
			}
22653 ashik.ali 541
		}
25043 amit.gupta 542
		if (count > 0) {
23444 amit.gupta 543
			walletService.addAmountToWallet(retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT,
23796 amit.gupta 544
					"Sales margin for invoice number " + fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
545
					totalCashback);
23365 ashik.ali 546
			fofoOrder.setCashback(totalCashback);
547
			fofoOrderRepository.persist(fofoOrder);
22859 ashik.ali 548
		}
22653 ashik.ali 549
	}
23444 amit.gupta 550
 
23508 amit.gupta 551
	@Override
23796 amit.gupta 552
	public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
553
			throws Exception {
23638 amit.gupta 554
		Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
23508 amit.gupta 555
		float amountToRollback = 0;
556
		List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
23796 amit.gupta 557
		for (SchemeInOut schemeInOut : schemes) {
23983 amit.gupta 558
			if (schemeInOut.getRolledBackTimestamp() == null) {
559
				schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
560
				schemeInOutRepository.persist(schemeInOut);
561
				amountToRollback += schemeInOut.getAmount();
562
			}
23508 amit.gupta 563
		}
23983 amit.gupta 564
		if (amountToRollback > 0) {
23638 amit.gupta 565
			int inventoryItemId = inventoryItemIds.get(0);
566
			Integer fofoId = inventoryItemRepository.selectById(inventoryItemId).getFofoId();
23796 amit.gupta 567
			walletService.rollbackAmountFromWallet(fofoId, amountToRollback, rollbackReference,
568
					WalletReferenceType.SCHEME_IN, rollbackReason);
23638 amit.gupta 569
		}
23508 amit.gupta 570
	}
23884 amit.gupta 571
 
23781 ashik.ali 572
	@Override
23796 amit.gupta 573
	public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
574
			throws ProfitMandiBusinessException {
23781 ashik.ali 575
		Map<String, Object> map = new HashMap<>();
576
		List<Scheme> schemes = null;
577
		long size = 0;
23798 amit.gupta 578
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 579
			schemes = schemeRepository.selectAll(offset, limit);
580
			size = schemeRepository.selectAllCount();
23796 amit.gupta 581
		} else {
23781 ashik.ali 582
			schemes = schemeRepository.selectActiveAll(offset, limit);
583
			size = schemeRepository.selectAllActiveCount();
584
		}
585
		map.put("schemes", schemes);
586
		map.put("start", offset + 1);
587
		map.put("size", size);
23796 amit.gupta 588
		if (schemes.size() < limit) {
23781 ashik.ali 589
			map.put("end", offset + schemes.size());
23796 amit.gupta 590
		} else {
23781 ashik.ali 591
			map.put("end", offset + limit);
592
		}
593
		return map;
594
	}
23796 amit.gupta 595
 
23781 ashik.ali 596
	@Override
23796 amit.gupta 597
	public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
598
			throws ProfitMandiBusinessException {
23781 ashik.ali 599
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
600
		List<Scheme> schemes = null;
23798 amit.gupta 601
		if (roleManager.isAdmin(roleIds)) {
23781 ashik.ali 602
			schemes = schemeRepository.selectAll(offset, limit);
23796 amit.gupta 603
		} else {
23781 ashik.ali 604
			schemes = schemeRepository.selectActiveAll(offset, limit);
605
		}
606
		return schemes;
607
	}
23508 amit.gupta 608
 
23968 amit.gupta 609
	@Override
24976 amit.gupta 610
	public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
23968 amit.gupta 611
			throws Exception {
24976 amit.gupta 612
 
613
		Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
614
				.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
615
 
616
		for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
617
			float amountToCredit = 0;
618
			float amountToDebit = 0;
619
			int purchaseId = purchaseEntry.getKey();
620
			List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
621
 
622
			Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
623
					.collect(Collectors.toMap(x -> x.getId(), x -> x));
624
 
625
			List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
626
			List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
627
			Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
628
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
629
			for (SchemeInOut schemeInOut : schemeInOuts) {
630
				InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
631
				Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
632
				if (scheme.getType().equals(SchemeType.OUT))
633
					continue;
634
				if (scheme.getAmountType().equals(AmountType.FIXED)) {
635
					continue;
23995 amit.gupta 636
				}
24976 amit.gupta 637
				if (schemeInOut.getRolledBackTimestamp() == null) {
638
					float newAmount = getAmount(ii, scheme);
639
					if (schemeInOut.getAmount() - newAmount >= 0.01f) {
640
						schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
641
						schemeInOutRepository.persist(schemeInOut);
642
						SchemeInOut sioNew = new SchemeInOut();
643
						sioNew.setAmount(newAmount);
644
						sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
645
						sioNew.setSchemeId(schemeInOut.getSchemeId());
646
						schemeInOutRepository.persist(sioNew);
647
						amountToCredit += sioNew.getAmount();
648
						amountToDebit += schemeInOut.getAmount();
649
					}
24562 amit.gupta 650
 
24976 amit.gupta 651
				}
23986 amit.gupta 652
			}
24976 amit.gupta 653
			int fofoId = inventoryItems.get(0).getFofoId();
654
			if (amountToDebit > 0) {
655
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN, reversalReason,
656
						-amountToDebit);
657
			}
658
			if (amountToCredit > 0) {
659
				walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN, reversalReason,
660
						amountToCredit);
661
			}
23968 amit.gupta 662
		}
663
	}
24562 amit.gupta 664
 
24264 amit.gupta 665
	@Override
24562 amit.gupta 666
	public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
667
			SchemeType schemeType) throws ProfitMandiBusinessException {
24264 amit.gupta 668
		Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
669
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
670
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
671
		List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
672
		float amount = 0;
673
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size()).stream()
674
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
675
		for (SchemeInOut schemeInOut : schemeInOuts) {
676
			Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
24562 amit.gupta 677
			if (scheme.getType().equals(schemeType)) {
678
				if (schemeInOut.getRolledBackTimestamp() == null) {
24264 amit.gupta 679
					schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
680
					schemeInOutRepository.persist(schemeInOut);
681
					amount += schemeInOut.getAmount();
682
				}
683
			}
684
		}
685
		int fofoId = inventoryItems.get(0).getFofoId();
24562 amit.gupta 686
		WalletReferenceType walletReferenceType = schemeType.equals(SchemeType.OUT) ? WalletReferenceType.SCHEME_OUT
687
				: WalletReferenceType.SCHEME_IN;
688
		if (amount > 0) {
689
			walletService.rollbackAmountFromWallet(fofoId, amount, reversalReference, walletReferenceType,
690
					reversalReason);
24268 amit.gupta 691
		}
24264 amit.gupta 692
	}
23968 amit.gupta 693
 
24976 amit.gupta 694
	/*
695
	 * @Override public void updateSchmesForModel(int catalogId) throws
696
	 * ProfitMandiBusinessException { List<Item> items =
697
	 * itemRepository.selectAllByCatalogItemId(catalogId); Map<Integer, Scheme>
698
	 * schemes = schemeRepository .selectAllByItemIds(items.stream().map(x ->
699
	 * x.getId()).collect(Collectors.toList()));
700
	 * 
701
	 * }
702
	 */
24562 amit.gupta 703
 
22653 ashik.ali 704
}