Subversion Repositories SmartDukaan

Rev

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