Subversion Repositories SmartDukaan

Rev

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