Subversion Repositories SmartDukaan

Rev

Rev 24779 | Rev 24781 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
23755 amit.gupta 1
package com.smartdukaan.cron.migrations;
2
 
23824 amit.gupta 3
import java.time.LocalDate;
23755 amit.gupta 4
import java.time.LocalDateTime;
23824 amit.gupta 5
import java.time.LocalTime;
24767 amit.gupta 6
import java.util.ArrayList;
23755 amit.gupta 7
import java.util.Arrays;
23827 amit.gupta 8
import java.util.Collections;
24002 amit.gupta 9
import java.util.HashMap;
24005 amit.gupta 10
import java.util.HashSet;
23755 amit.gupta 11
import java.util.List;
24002 amit.gupta 12
import java.util.Map;
24641 amit.gupta 13
import java.util.stream.Collectors;
23755 amit.gupta 14
 
24767 amit.gupta 15
import org.apache.commons.io.output.ByteArrayOutputStream;
23755 amit.gupta 16
import org.apache.commons.lang.StringUtils;
17
import org.apache.logging.log4j.LogManager;
18
import org.apache.logging.log4j.Logger;
19
import org.springframework.beans.factory.annotation.Autowired;
24767 amit.gupta 20
import org.springframework.core.io.ByteArrayResource;
21
import org.springframework.mail.javamail.JavaMailSender;
23755 amit.gupta 22
import org.springframework.stereotype.Component;
23
import org.springframework.transaction.annotation.Transactional;
24
 
24767 amit.gupta 25
import com.spice.profitmandi.common.util.FileUtil;
26
import com.spice.profitmandi.common.util.Utils;
24716 amit.gupta 27
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
24005 amit.gupta 28
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
23898 amit.gupta 29
import com.spice.profitmandi.dao.entity.fofo.Purchase;
24716 amit.gupta 30
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
23824 amit.gupta 31
import com.spice.profitmandi.dao.entity.transaction.LineItem;
23755 amit.gupta 32
import com.spice.profitmandi.dao.entity.transaction.LineItemImei;
33
import com.spice.profitmandi.dao.entity.transaction.Order;
24772 amit.gupta 34
import com.spice.profitmandi.dao.entity.transaction.ReturnOrder;
24767 amit.gupta 35
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
36
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
24722 amit.gupta 37
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
24716 amit.gupta 38
import com.spice.profitmandi.dao.repository.GenericRepository;
23899 amit.gupta 39
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24716 amit.gupta 40
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24002 amit.gupta 41
import com.spice.profitmandi.dao.repository.fofo.DebitNoteRepository;
42
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
23898 amit.gupta 43
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
24716 amit.gupta 44
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
24002 amit.gupta 45
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
23755 amit.gupta 46
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
23824 amit.gupta 47
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
23755 amit.gupta 48
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
24772 amit.gupta 49
import com.spice.profitmandi.dao.repository.transaction.ReturnOrderRepository;
24767 amit.gupta 50
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
51
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
24002 amit.gupta 52
import com.spice.profitmandi.dao.repository.user.UserRepository;
23899 amit.gupta 53
import com.spice.profitmandi.service.inventory.InventoryService;
24266 amit.gupta 54
import com.spice.profitmandi.service.order.OrderService;
24005 amit.gupta 55
import com.spice.profitmandi.service.pricing.PriceDropService;
56
import com.spice.profitmandi.service.scheme.SchemeService;
23899 amit.gupta 57
import com.spice.profitmandi.service.transaction.TransactionService;
58
import com.spice.profitmandi.service.user.RetailerService;
59
import com.spice.profitmandi.service.wallet.WalletService;
23755 amit.gupta 60
 
24767 amit.gupta 61
import in.shop2020.model.v1.order.OrderStatus;
24002 amit.gupta 62
import in.shop2020.model.v1.order.WalletReferenceType;
63
 
23755 amit.gupta 64
@Component
65
@Transactional(rollbackFor = Throwable.class)
66
public class RunOnceTasks {
67
 
68
	private static final Logger LOGGER = LogManager.getLogger(RunOnceTasks.class);
69
 
70
	@Autowired
23824 amit.gupta 71
	private LineItemRepository lineItemRepository;
24711 amit.gupta 72
 
23905 amit.gupta 73
	@Autowired
24767 amit.gupta 74
	private UserWalletRepository userWalletRepository;
75
 
76
	@Autowired
77
	private UserWalletHistoryRepository userWalletHistoryRepository;
78
 
79
	@Autowired
24002 amit.gupta 80
	private UserRepository userRepository;
24711 amit.gupta 81
 
24002 amit.gupta 82
	@Autowired
23899 amit.gupta 83
	private WalletService walletService;
84
 
85
	@Autowired
86
	private InventoryService inventoryService;
87
 
88
	@Autowired
89
	private TransactionService transactionService;
90
 
24711 amit.gupta 91
	// Service for Tertiary/Partner Orders
24266 amit.gupta 92
	@Autowired
93
	private OrderService orderService;
23767 amit.gupta 94
 
23755 amit.gupta 95
	@Autowired
24772 amit.gupta 96
	private ReturnOrderRepository returnOrderRepository;
97
 
98
	@Autowired
23899 amit.gupta 99
	private FofoStoreRepository fofoStoreRepository;
100
 
101
	@Autowired
23755 amit.gupta 102
	private LineItemImeisRepository lineItemImeisRepository;
24711 amit.gupta 103
 
24002 amit.gupta 104
	@Autowired
105
	private InventoryItemRepository inventoryItemRepository;
23901 amit.gupta 106
 
23898 amit.gupta 107
	@Autowired
23899 amit.gupta 108
	private RetailerService retailerService;
24711 amit.gupta 109
 
24002 amit.gupta 110
	@Autowired
111
	private SchemeInOutRepository schemeInOutRepository;
24711 amit.gupta 112
 
24002 amit.gupta 113
	@Autowired
114
	private DebitNoteRepository debitNoteRepository;
23899 amit.gupta 115
 
116
	@Autowired
24716 amit.gupta 117
	private GenericRepository genericRepository;
118
 
119
	@Autowired
23898 amit.gupta 120
	private PurchaseRepository purchaseRepository;
24711 amit.gupta 121
 
24005 amit.gupta 122
	@Autowired
123
	private PriceDropService priceDropService;
24711 amit.gupta 124
 
24005 amit.gupta 125
	@Autowired
126
	private SchemeService schemeService;
24711 amit.gupta 127
 
24716 amit.gupta 128
	@Autowired
129
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
130
 
131
	@Autowired
24767 amit.gupta 132
	private OrderRepository orderRepository;
133
 
134
	@Autowired
24716 amit.gupta 135
	private ScanRecordRepository scanRecordRepository;
136
 
24767 amit.gupta 137
	@Autowired
138
	private JavaMailSender mailSender;
139
 
24005 amit.gupta 140
	public void dropCorrection() throws Exception {
141
 
24711 amit.gupta 142
		walletService.rollbackAmountFromWallet(175128034, 274, 4, WalletReferenceType.PRICE_DROP,
143
				"Scheme  differential for Price Drop of Rs.712 on Samsung J6 J600GG, on 01-08-2018 for missing 1pc");
144
		walletService.rollbackAmountFromWallet(175128034, -259, 4, WalletReferenceType.PRICE_DROP,
145
				"Scheme  differential for Price Drop of Rs.712 on Samsung J6 J600GG, on 01-08-2018 for missing 1pc");
146
		List<InventoryItem> iis = inventoryItemRepository.selectByIds(new HashSet<>(Arrays.asList(3518, 3516)));
147
		schemeService.reverseSchemes(iis, 8,
148
				"Scheme  differential for Price Drop of Rs.712 on Samsung J6 J600GG, on 01-08-2018. Total 2 item(s)");
149
		List<InventoryItem> iis1 = inventoryItemRepository.selectByIds(new HashSet<>(Arrays.asList(3502, 3334, 3503)));
150
		schemeService.reverseSchemes(iis1, 13,
151
				"Scheme  differential for Price Drop of Rs.485 on Samsung Galaxy J4 J400FD, on 18-07-2018. Total 3 item(s)");
152
 
153
		List<InventoryItem> iis2 = inventoryItemRepository.selectByIds(new HashSet<>(Arrays.asList(3319)));
154
		schemeService.reverseSchemes(iis2, 13,
155
				"Scheme  differential for Price Drop of Rs.485 on Samsung Galaxy J4 J400FD, on 18-07-2018. Total 1 item(s)");
24005 amit.gupta 156
	}
24711 amit.gupta 157
 
24002 amit.gupta 158
	public void schemeRollback() {
159
		Map<Integer, Float> fofoIdAmount = new HashMap<>();
24003 amit.gupta 160
		fofoIdAmount.put(175135218, 1942f);
161
		String description = "Price drop/differential rolled out as, they were already returned, Total 2pcs.";
24711 amit.gupta 162
		for (Map.Entry<Integer, Float> fofoIdAmountEntry : fofoIdAmount.entrySet()) {
163
			Integer fofoId = fofoIdAmountEntry.getKey();
24002 amit.gupta 164
			Float amount = fofoIdAmountEntry.getValue();
24003 amit.gupta 165
			walletService.rollbackAmountFromWallet(fofoId, amount, 4, WalletReferenceType.PRICE_DROP, description);
24002 amit.gupta 166
		}
24004 amit.gupta 167
		fofoIdAmount.put(175135218, 438f);
24711 amit.gupta 168
		for (Map.Entry<Integer, Float> fofoIdAmountEntry : fofoIdAmount.entrySet()) {
169
			Integer fofoId = fofoIdAmountEntry.getKey();
24004 amit.gupta 170
			Float amount = fofoIdAmountEntry.getValue();
171
			walletService.rollbackAmountFromWallet(fofoId, amount, 4, WalletReferenceType.PRICE_DROP, description);
172
		}
24002 amit.gupta 173
	}
23755 amit.gupta 174
 
23898 amit.gupta 175
	public void populateGrnTimestamp() {
176
		List<Purchase> allPurchases = purchaseRepository.selectAll();
23899 amit.gupta 177
		for (Purchase p : allPurchases) {
23898 amit.gupta 178
			String invoiceNumber = p.getPurchaseReference();
23899 amit.gupta 179
			if (p.getCompleteTimestamp() == null) {
23898 amit.gupta 180
				LOGGER.info("GRN for invoice {} is delivered but partially Completed.", p.getPurchaseReference());
181
			} else {
182
				List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(invoiceNumber, p.getFofoId());
23899 amit.gupta 183
				for (Order order : orders) {
23902 amit.gupta 184
					if (order.getPartnerGrnTimestamp() == null) {
185
						order.setPartnerGrnTimestamp(p.getCompleteTimestamp());
23898 amit.gupta 186
						orderRepository.persist(order);
187
					}
188
				}
189
			}
190
		}
23899 amit.gupta 191
 
23898 amit.gupta 192
	}
23899 amit.gupta 193
 
24716 amit.gupta 194
	public void migarateLineItemsToNewTable() throws Exception {
23755 amit.gupta 195
		LOGGER.info("Before Migrated LineItems Successfully");
23824 amit.gupta 196
		int lineItemImeiId = 0;
197
		LocalDateTime startDate = null;
198
		try {
199
			lineItemImeiId = lineItemImeisRepository.selectMaxId();
23899 amit.gupta 200
			LineItem lineItem = lineItemRepository
201
					.selectById(lineItemImeisRepository.selectById(lineItemImeiId).getLineItemId());
23824 amit.gupta 202
			Order order = orderRepository.selectById(lineItem.getOrderId());
203
			startDate = order.getBillingTimestamp();
204
		} catch (Exception e) {
205
			LOGGER.info("Running before first time");
23826 amit.gupta 206
			startDate = LocalDateTime.of(LocalDate.of(2017, 7, 1), LocalTime.MIDNIGHT);
23824 amit.gupta 207
		}
208
		List<Order> orders = orderRepository.selectAllByBillingDatesBetween(startDate, LocalDateTime.now());
23827 amit.gupta 209
		Collections.reverse(orders);
23899 amit.gupta 210
 
23755 amit.gupta 211
		for (Order order : orders) {
23824 amit.gupta 212
			try {
23767 amit.gupta 213
				String serialNumbers = order.getLineItem().getSerialNumber();
214
				if (!StringUtils.isEmpty(serialNumbers)) {
215
					List<String> serialNumberList = Arrays.asList(serialNumbers.split(","));
216
					for (String serialNumber : serialNumberList) {
217
						int lineItemId = order.getLineItem().getId();
218
						LineItemImei lineItemImei = new LineItemImei();
219
						lineItemImei.setSerialNumber(serialNumber);
220
						lineItemImei.setLineItemId(lineItemId);
221
						lineItemImeisRepository.persist(lineItemImei);
222
					}
223
				} else {
224
					LOGGER.info("Serial Numbers dont exist for Order {}", order.getId());
23755 amit.gupta 225
				}
23824 amit.gupta 226
			} catch (Exception e) {
23899 amit.gupta 227
				LOGGER.info("Error occurred while creating lineitem imei {}, because of {}", order.getId(),
228
						e.getMessage());
23755 amit.gupta 229
			}
230
		}
231
		LOGGER.info("Migrated LineItems Successfully");
232
	}
24266 amit.gupta 233
 
234
	public void cancelOrder(List<String> invoiceNumbers) throws Exception {
235
		orderService.cancelOrder(invoiceNumbers);
236
	}
24711 amit.gupta 237
 
24722 amit.gupta 238
	public void migratePurchase() throws Exception {
24641 amit.gupta 239
		List<Purchase> purchases = purchaseRepository.selectPurchaseAllPurchasesLessThanZero();
24706 amit.gupta 240
		System.out.printf("Total Purchases count is %s", purchases.size());
24711 amit.gupta 241
		for (Purchase purchase : purchases) {
242
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchase.getId());
243
			Map<Integer, List<InventoryItem>> itemIdInventoryMap = inventoryItems.stream()
244
					.collect(Collectors.groupingBy(InventoryItem::getItemId));
245
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(purchase.getPurchaseReference(),
246
					purchase.getFofoId());
247
			Map<Integer, Integer> ourSaleItemQtyMap = orders.stream().collect(Collectors.groupingBy(
248
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
249
			Map<Integer, Integer> theirPurchaseItemQtyMap = inventoryItems.stream().collect(Collectors
250
					.groupingBy(InventoryItem::getItemId, Collectors.summingInt(InventoryItem::getInitialQuantity)));
24709 amit.gupta 251
			for (Map.Entry<Integer, Integer> itemQtyEntry : theirPurchaseItemQtyMap.entrySet()) {
24711 amit.gupta 252
				if (!ourSaleItemQtyMap.containsKey(itemQtyEntry.getKey())) {
253
					LOGGER.info("Cannot find in Invoice {} item {}", purchase.getPurchaseReference(),
254
							itemQtyEntry.getKey());
24646 amit.gupta 255
					continue;
24645 amit.gupta 256
				}
24709 amit.gupta 257
				int ourSale = ourSaleItemQtyMap.get(itemQtyEntry.getKey());
24713 amit.gupta 258
				int quantityToReduce = itemQtyEntry.getValue() - ourSale;
24716 amit.gupta 259
				List<InventoryItem> itemIis = itemIdInventoryMap.get(itemQtyEntry.getKey());
260
				if (itemIdInventoryMap != null) {
261
					for (InventoryItem ii : itemIis) {
24732 amit.gupta 262
						if (quantityToReduce > 0 && ii.getGoodQuantity() > 0) {
24734 amit.gupta 263
							LOGGER.info("Changed in inventoryItems {}, {}, {}, {}, {}, {}",
24716 amit.gupta 264
									purchase.getPurchaseReference(), ii.getId(), ii.getItemId(),
24734 amit.gupta 265
									ii.getInitialQuantity(), ii.getGoodQuantity(), quantityToReduce);
24730 amit.gupta 266
							if (ii.getGoodQuantity() > 0) {
24716 amit.gupta 267
								List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
24722 amit.gupta 268
								for (ScanRecord scanRecord : scanRecords) {
269
									if (scanRecord.getType().equals(ScanType.PURCHASE)) {
270
										CurrentInventorySnapshot cis = currentInventorySnapshotRepository
271
												.selectByItemIdAndFofoId(itemQtyEntry.getKey(), purchase.getFofoId());
24733 amit.gupta 272
										scanRecord.setQuantity(scanRecord.getQuantity() - ii.getGoodQuantity());
273
										ii.setInitialQuantity(ii.getInitialQuantity() - ii.getBadQuantity());
24735 amit.gupta 274
										quantityToReduce = quantityToReduce - ii.getGoodQuantity();
24733 amit.gupta 275
										ii.setGoodQuantity(0);
276
										cis.setAvailability(cis.getAvailability() - ii.getGoodQuantity());
277
										purchase.setUnfullfilledNonSerializedQuantity(
278
												purchase.getUnfullfilledNonSerializedQuantity() + quantityToReduce);
24767 amit.gupta 279
										LOGGER.info("Rectified {}, {}, {}, {}, {}, {}", purchase.getPurchaseReference(),
280
												ii.getId(), ii.getItemId(), ii.getInitialQuantity(),
281
												ii.getGoodQuantity(), quantityToReduce);
24733 amit.gupta 282
										break;
24716 amit.gupta 283
									}
284
								}
24711 amit.gupta 285
							}
24641 amit.gupta 286
						}
287
					}
288
				}
289
			}
290
		}
24767 amit.gupta 291
		// throw new Exception();
24641 amit.gupta 292
	}
24767 amit.gupta 293
 
294
	// Lets work it up for The Mobile Planet
295
	// HRFB002 - 157112773
296
	public void dailyReconciliation() throws Exception {
297
		List<List<?>> rows = new ArrayList<>();
298
		UserWallet uw = userWalletRepository.selectByRetailerId(157112773);
299
		List<UserWalletHistory> walletHistory = userWalletHistoryRepository.selectByWalletId(uw.getId());
300
		Map<LocalDate, List<UserWalletHistory>> dateWiseWalletHistory = walletHistory.stream()
301
				.collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate(), Collectors.toList()));
302
		for (Map.Entry<LocalDate, List<UserWalletHistory>> entry : dateWiseWalletHistory.entrySet()) {
303
			LocalDate dateToReconcile = entry.getKey();
304
			List<UserWalletHistory> history = entry.getValue();
305
			rows.add(reconcileOrdersAndWallet(uw.getUserId(), dateToReconcile, history));
306
		}
24779 amit.gupta 307
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
308
				Arrays.asList("Date", "Wallet amount", "Ordered Total", "Cancelled Total", "Refunded Total"), rows);
24767 amit.gupta 309
 
310
		Utils.sendMailWithAttachment(mailSender, new String[] { "amit.gupta@shop2020.in" }, new String[] {}, "Test",
311
				"test", "File.csv", new ByteArrayResource(baos.toByteArray()));
312
	}
313
 
314
	private List<?> reconcileOrdersAndWallet(int fofoId, LocalDate localDate, List<UserWalletHistory> history)
315
			throws Exception {
316
		Map<Integer, Integer> transactionsOnThatDate = history.stream()
317
				.filter(x -> x.getReferenceType().equals(WalletReferenceType.PURCHASE))
318
				.collect(Collectors.groupingBy(x -> x.getReference(), Collectors.summingInt(x -> x.getAmount())));
319
 
24777 amit.gupta 320
		int totalWalletConsumed = 0;
24772 amit.gupta 321
		float cancelledAmount = 0;
322
		float returnedAmount = 0;
323
		float totalDeductedAmount = 0;
24767 amit.gupta 324
		for (int transactionId : transactionsOnThatDate.keySet()) {
325
			List<Order> orders = orderRepository.selectAllByTransactionId(transactionId);
326
			for (Order o : orders) {
24779 amit.gupta 327
				if (o.getCreateTimestamp().toLocalDate().equals(localDate)) {
24767 amit.gupta 328
					if (Arrays.asList(OrderStatus.PAYMENT_PENDING, OrderStatus.PAYMENT_FAILED)
329
							.contains(o.getStatus())) {
24772 amit.gupta 330
						cancelledAmount += o.getWalletAmount();
24779 amit.gupta 331
					} else if (o.getRefundTimestamp() != null
332
							&& o.getRefundTimestamp().toLocalDate().equals(localDate)) {
24772 amit.gupta 333
						ReturnOrder returnedOrder = returnOrderRepository.selectByOrderId(o.getId());
24779 amit.gupta 334
						if (returnedOrder == null) {
335
							cancelledAmount += o.getWalletAmount();
24776 amit.gupta 336
						} else {
337
							returnedAmount += returnedOrder.getTotalPrice();
338
						}
24779 amit.gupta 339
					}
24780 amit.gupta 340
					totalDeductedAmount += o.getWalletAmount();
341
 
24779 amit.gupta 342
				} else if (o.getRefundTimestamp() != null && o.getRefundTimestamp().toLocalDate().equals(localDate)) {
343
					ReturnOrder returnedOrder = returnOrderRepository.selectByOrderId(o.getId());
344
					if (returnedOrder == null) {
345
						cancelledAmount += o.getWalletAmount();
346
					} else {
347
						returnedAmount += returnedOrder.getTotalPrice();
348
					}
24767 amit.gupta 349
				}
24779 amit.gupta 350
				totalWalletConsumed -= transactionsOnThatDate.get(transactionId);
24767 amit.gupta 351
			}
24779 amit.gupta 352
 
24767 amit.gupta 353
		}
354
 
24777 amit.gupta 355
		return Arrays.asList(localDate, totalWalletConsumed, totalDeductedAmount, cancelledAmount, returnedAmount);
24767 amit.gupta 356
 
357
	}
358
 
359
	private void reconcileDailySchemeIn() {
360
 
361
	}
362
 
363
	private void reconcileDailySchemeOut() {
364
 
365
	}
23755 amit.gupta 366
}