Subversion Repositories SmartDukaan

Rev

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