Subversion Repositories SmartDukaan

Rev

Rev 26423 | Rev 26579 | 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
 
25765 amit.gupta 3
import java.io.File;
23824 amit.gupta 4
import java.time.LocalDate;
23755 amit.gupta 5
import java.time.LocalDateTime;
23824 amit.gupta 6
import java.time.LocalTime;
24819 amit.gupta 7
import java.util.ArrayList;
23755 amit.gupta 8
import java.util.Arrays;
23827 amit.gupta 9
import java.util.Collections;
24002 amit.gupta 10
import java.util.HashMap;
24005 amit.gupta 11
import java.util.HashSet;
23755 amit.gupta 12
import java.util.List;
24002 amit.gupta 13
import java.util.Map;
25749 amit.gupta 14
import java.util.Set;
15
import java.util.concurrent.TimeUnit;
24641 amit.gupta 16
import java.util.stream.Collectors;
23755 amit.gupta 17
 
24819 amit.gupta 18
import org.apache.commons.io.output.ByteArrayOutputStream;
23755 amit.gupta 19
import org.apache.commons.lang.StringUtils;
20
import org.apache.logging.log4j.LogManager;
21
import org.apache.logging.log4j.Logger;
25773 amit.gupta 22
import org.openqa.selenium.Dimension;
25749 amit.gupta 23
import org.openqa.selenium.OutputType;
24
import org.openqa.selenium.TakesScreenshot;
25
import org.openqa.selenium.WebDriver;
26
import org.openqa.selenium.chrome.ChromeDriver;
25752 amit.gupta 27
import org.openqa.selenium.chrome.ChromeOptions;
23755 amit.gupta 28
import org.springframework.beans.factory.annotation.Autowired;
24819 amit.gupta 29
import org.springframework.core.io.ByteArrayResource;
24767 amit.gupta 30
import org.springframework.mail.javamail.JavaMailSender;
23755 amit.gupta 31
import org.springframework.stereotype.Component;
32
import org.springframework.transaction.annotation.Transactional;
33
 
26214 amit.gupta 34
import com.smartdukaan.cron.scheduled.SamsungIMEIActivationService;
25043 amit.gupta 35
import com.smartdukaan.cron.scheduled.ScheduledTasks;
26095 amit.gupta 36
import com.spice.profitmandi.common.enumuration.ItemType;
26033 amit.gupta 37
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
24819 amit.gupta 38
import com.spice.profitmandi.common.util.FileUtil;
25749 amit.gupta 39
import com.spice.profitmandi.common.util.FormattingUtils;
24819 amit.gupta 40
import com.spice.profitmandi.common.util.Utils;
26033 amit.gupta 41
import com.spice.profitmandi.dao.entity.catalog.Item;
25021 amit.gupta 42
import com.spice.profitmandi.dao.entity.catalog.Scheme;
24716 amit.gupta 43
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
24806 amit.gupta 44
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
45
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
25530 amit.gupta 46
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24005 amit.gupta 47
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24883 amit.gupta 48
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
26033 amit.gupta 49
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrder;
23898 amit.gupta 50
import com.spice.profitmandi.dao.entity.fofo.Purchase;
24716 amit.gupta 51
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
25034 amit.gupta 52
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
25021 amit.gupta 53
import com.spice.profitmandi.dao.entity.fofo.SchemeItem;
24883 amit.gupta 54
import com.spice.profitmandi.dao.entity.fofo.TargetSlab;
24953 amit.gupta 55
import com.spice.profitmandi.dao.entity.inventory.SaholicInventorySnapshot;
23824 amit.gupta 56
import com.spice.profitmandi.dao.entity.transaction.LineItem;
23755 amit.gupta 57
import com.spice.profitmandi.dao.entity.transaction.LineItemImei;
58
import com.spice.profitmandi.dao.entity.transaction.Order;
24802 amit.gupta 59
import com.spice.profitmandi.dao.entity.transaction.SellerWarehouse;
25046 amit.gupta 60
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
25034 amit.gupta 61
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
25530 amit.gupta 62
import com.spice.profitmandi.dao.entity.user.Address;
63
import com.spice.profitmandi.dao.entity.user.User;
25021 amit.gupta 64
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
25522 amit.gupta 65
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
24716 amit.gupta 66
import com.spice.profitmandi.dao.repository.GenericRepository;
25034 amit.gupta 67
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
25021 amit.gupta 68
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
25749 amit.gupta 69
import com.spice.profitmandi.dao.repository.cs.CsService;
23899 amit.gupta 70
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24716 amit.gupta 71
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24002 amit.gupta 72
import com.spice.profitmandi.dao.repository.fofo.DebitNoteRepository;
24806 amit.gupta 73
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
74
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
24002 amit.gupta 75
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24806 amit.gupta 76
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
24883 amit.gupta 77
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
26033 amit.gupta 78
import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderRepository;
23898 amit.gupta 79
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
24716 amit.gupta 80
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
24002 amit.gupta 81
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
25021 amit.gupta 82
import com.spice.profitmandi.dao.repository.fofo.SchemeItemRepository;
24883 amit.gupta 83
import com.spice.profitmandi.dao.repository.fofo.TargetSlabRepository;
84
import com.spice.profitmandi.dao.repository.fofo.TargetSlabRepositoryImpl;
24953 amit.gupta 85
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
86
import com.spice.profitmandi.dao.repository.inventory.SaholicReservationInventorySnapshotRepository;
23755 amit.gupta 87
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
23824 amit.gupta 88
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
23755 amit.gupta 89
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
24772 amit.gupta 90
import com.spice.profitmandi.dao.repository.transaction.ReturnOrderRepository;
24802 amit.gupta 91
import com.spice.profitmandi.dao.repository.transaction.SellerWarehouseRepository;
24767 amit.gupta 92
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
93
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
25530 amit.gupta 94
import com.spice.profitmandi.dao.repository.user.AddressRepository;
24002 amit.gupta 95
import com.spice.profitmandi.dao.repository.user.UserRepository;
23899 amit.gupta 96
import com.spice.profitmandi.service.inventory.InventoryService;
26033 amit.gupta 97
import com.spice.profitmandi.service.inventory.PurchaseService;
24266 amit.gupta 98
import com.spice.profitmandi.service.order.OrderService;
24005 amit.gupta 99
import com.spice.profitmandi.service.pricing.PriceDropService;
100
import com.spice.profitmandi.service.scheme.SchemeService;
23899 amit.gupta 101
import com.spice.profitmandi.service.transaction.TransactionService;
102
import com.spice.profitmandi.service.user.RetailerService;
103
import com.spice.profitmandi.service.wallet.WalletService;
23755 amit.gupta 104
 
24953 amit.gupta 105
import in.shop2020.model.v1.order.OrderStatus;
24002 amit.gupta 106
import in.shop2020.model.v1.order.WalletReferenceType;
107
 
23755 amit.gupta 108
@Component
109
@Transactional(rollbackFor = Throwable.class)
110
public class RunOnceTasks {
111
 
112
	private static final Logger LOGGER = LogManager.getLogger(RunOnceTasks.class);
113
 
114
	@Autowired
23824 amit.gupta 115
	private LineItemRepository lineItemRepository;
24711 amit.gupta 116
 
23905 amit.gupta 117
	@Autowired
24953 amit.gupta 118
	private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
25752 amit.gupta 119
 
25749 amit.gupta 120
	@Autowired
121
	private CsService csService;
26299 amit.gupta 122
 
26033 amit.gupta 123
	@Autowired
26195 amit.gupta 124
	private SamsungIMEIActivationService samsungActivationService;
26299 amit.gupta 125
 
26195 amit.gupta 126
	@Autowired
26033 amit.gupta 127
	private PrebookingOrderRepository prebookingOrderRepository;
24953 amit.gupta 128
 
129
	@Autowired
130
	private SaholicReservationInventorySnapshotRepository saholicReservationInventorySnapshotRepository;
131
 
132
	@Autowired
24883 amit.gupta 133
	private TargetSlabRepository targetSlabRepository;
134
 
135
	@Autowired
136
	private PartnerTargetRepository partnerTargetRepository;
137
 
138
	@Autowired
24802 amit.gupta 139
	private SellerWarehouseRepository sellerWarehouseRepository;
24814 amit.gupta 140
 
24802 amit.gupta 141
	@Autowired
24806 amit.gupta 142
	private FofoOrderItemRepository fofoOrderItemRepository;
24814 amit.gupta 143
 
24806 amit.gupta 144
	@Autowired
145
	private FofoOrderRepository fofoOrderRepository;
24814 amit.gupta 146
 
24806 amit.gupta 147
	@Autowired
24767 amit.gupta 148
	private UserWalletRepository userWalletRepository;
149
 
150
	@Autowired
151
	private UserWalletHistoryRepository userWalletHistoryRepository;
152
 
153
	@Autowired
24002 amit.gupta 154
	private UserRepository userRepository;
24711 amit.gupta 155
 
24002 amit.gupta 156
	@Autowired
23899 amit.gupta 157
	private WalletService walletService;
158
 
159
	@Autowired
25034 amit.gupta 160
	private ItemRepository itemRepository;
161
 
162
	@Autowired
23899 amit.gupta 163
	private InventoryService inventoryService;
164
 
165
	@Autowired
166
	private TransactionService transactionService;
26299 amit.gupta 167
 
26033 amit.gupta 168
	@Autowired
169
	private PurchaseService purchaseService;
23899 amit.gupta 170
 
24711 amit.gupta 171
	// Service for Tertiary/Partner Orders
24266 amit.gupta 172
	@Autowired
173
	private OrderService orderService;
23767 amit.gupta 174
 
23755 amit.gupta 175
	@Autowired
25021 amit.gupta 176
	private SchemeRepository schemeRepository;
25516 amit.gupta 177
 
25043 amit.gupta 178
	@Autowired
25530 amit.gupta 179
	private AddressRepository addressRepository;
25749 amit.gupta 180
 
25530 amit.gupta 181
	@Autowired
25043 amit.gupta 182
	private ScheduledTasks scheduledTasks;
25034 amit.gupta 183
 
25021 amit.gupta 184
	@Autowired
185
	private SchemeItemRepository schemeItemRepository;
186
 
187
	@Autowired
24772 amit.gupta 188
	private ReturnOrderRepository returnOrderRepository;
189
 
190
	@Autowired
23899 amit.gupta 191
	private FofoStoreRepository fofoStoreRepository;
192
 
193
	@Autowired
23755 amit.gupta 194
	private LineItemImeisRepository lineItemImeisRepository;
24711 amit.gupta 195
 
24002 amit.gupta 196
	@Autowired
197
	private InventoryItemRepository inventoryItemRepository;
24814 amit.gupta 198
 
24806 amit.gupta 199
	@Autowired
200
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
23901 amit.gupta 201
 
23898 amit.gupta 202
	@Autowired
23899 amit.gupta 203
	private RetailerService retailerService;
24711 amit.gupta 204
 
24002 amit.gupta 205
	@Autowired
206
	private SchemeInOutRepository schemeInOutRepository;
24711 amit.gupta 207
 
24002 amit.gupta 208
	@Autowired
209
	private DebitNoteRepository debitNoteRepository;
23899 amit.gupta 210
 
211
	@Autowired
24716 amit.gupta 212
	private GenericRepository genericRepository;
213
 
214
	@Autowired
23898 amit.gupta 215
	private PurchaseRepository purchaseRepository;
24711 amit.gupta 216
 
24005 amit.gupta 217
	@Autowired
218
	private PriceDropService priceDropService;
24883 amit.gupta 219
 
24819 amit.gupta 220
	@Autowired
221
	private JavaMailSender googleMailSender;
24711 amit.gupta 222
 
24005 amit.gupta 223
	@Autowired
224
	private SchemeService schemeService;
24711 amit.gupta 225
 
24716 amit.gupta 226
	@Autowired
227
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
228
 
229
	@Autowired
24767 amit.gupta 230
	private OrderRepository orderRepository;
231
 
232
	@Autowired
24716 amit.gupta 233
	private ScanRecordRepository scanRecordRepository;
234
 
24767 amit.gupta 235
	@Autowired
236
	private JavaMailSender mailSender;
237
 
24005 amit.gupta 238
 
23898 amit.gupta 239
	public void populateGrnTimestamp() {
240
		List<Purchase> allPurchases = purchaseRepository.selectAll();
23899 amit.gupta 241
		for (Purchase p : allPurchases) {
23898 amit.gupta 242
			String invoiceNumber = p.getPurchaseReference();
23899 amit.gupta 243
			if (p.getCompleteTimestamp() == null) {
23898 amit.gupta 244
				LOGGER.info("GRN for invoice {} is delivered but partially Completed.", p.getPurchaseReference());
245
			} else {
246
				List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(invoiceNumber, p.getFofoId());
23899 amit.gupta 247
				for (Order order : orders) {
23902 amit.gupta 248
					if (order.getPartnerGrnTimestamp() == null) {
249
						order.setPartnerGrnTimestamp(p.getCompleteTimestamp());
23898 amit.gupta 250
						orderRepository.persist(order);
251
					}
252
				}
253
			}
254
		}
23899 amit.gupta 255
 
23898 amit.gupta 256
	}
23899 amit.gupta 257
 
26408 amit.gupta 258
	public void fetchImeiActivation(int ym) throws Exception {
259
		LocalDate endDate = LocalDate.now().minusMonths(ym);
26423 amit.gupta 260
		samsungActivationService.getActivationsBetweenNew(endDate.withDayOfMonth(1), endDate.withDayOfMonth(endDate.lengthOfMonth()));
26195 amit.gupta 261
	}
26299 amit.gupta 262
 
24716 amit.gupta 263
	public void migarateLineItemsToNewTable() throws Exception {
23755 amit.gupta 264
		LOGGER.info("Before Migrated LineItems Successfully");
23824 amit.gupta 265
		int lineItemImeiId = 0;
266
		LocalDateTime startDate = null;
267
		try {
268
			lineItemImeiId = lineItemImeisRepository.selectMaxId();
23899 amit.gupta 269
			LineItem lineItem = lineItemRepository
270
					.selectById(lineItemImeisRepository.selectById(lineItemImeiId).getLineItemId());
23824 amit.gupta 271
			Order order = orderRepository.selectById(lineItem.getOrderId());
272
			startDate = order.getBillingTimestamp();
273
		} catch (Exception e) {
274
			LOGGER.info("Running before first time");
23826 amit.gupta 275
			startDate = LocalDateTime.of(LocalDate.of(2017, 7, 1), LocalTime.MIDNIGHT);
23824 amit.gupta 276
		}
277
		List<Order> orders = orderRepository.selectAllByBillingDatesBetween(startDate, LocalDateTime.now());
23827 amit.gupta 278
		Collections.reverse(orders);
23899 amit.gupta 279
 
23755 amit.gupta 280
		for (Order order : orders) {
23824 amit.gupta 281
			try {
23767 amit.gupta 282
				String serialNumbers = order.getLineItem().getSerialNumber();
283
				if (!StringUtils.isEmpty(serialNumbers)) {
284
					List<String> serialNumberList = Arrays.asList(serialNumbers.split(","));
285
					for (String serialNumber : serialNumberList) {
286
						int lineItemId = order.getLineItem().getId();
287
						LineItemImei lineItemImei = new LineItemImei();
288
						lineItemImei.setSerialNumber(serialNumber);
289
						lineItemImei.setLineItemId(lineItemId);
290
						lineItemImeisRepository.persist(lineItemImei);
291
					}
292
				} else {
293
					LOGGER.info("Serial Numbers dont exist for Order {}", order.getId());
23755 amit.gupta 294
				}
23824 amit.gupta 295
			} catch (Exception e) {
23899 amit.gupta 296
				LOGGER.info("Error occurred while creating lineitem imei {}, because of {}", order.getId(),
297
						e.getMessage());
23755 amit.gupta 298
			}
299
		}
300
		LOGGER.info("Migrated LineItems Successfully");
301
	}
24266 amit.gupta 302
 
303
	public void cancelOrder(List<String> invoiceNumbers) throws Exception {
304
		orderService.cancelOrder(invoiceNumbers);
305
	}
24711 amit.gupta 306
 
24722 amit.gupta 307
	public void migratePurchase() throws Exception {
24641 amit.gupta 308
		List<Purchase> purchases = purchaseRepository.selectPurchaseAllPurchasesLessThanZero();
24706 amit.gupta 309
		System.out.printf("Total Purchases count is %s", purchases.size());
24711 amit.gupta 310
		for (Purchase purchase : purchases) {
311
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchase.getId());
312
			Map<Integer, List<InventoryItem>> itemIdInventoryMap = inventoryItems.stream()
313
					.collect(Collectors.groupingBy(InventoryItem::getItemId));
314
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(purchase.getPurchaseReference(),
315
					purchase.getFofoId());
316
			Map<Integer, Integer> ourSaleItemQtyMap = orders.stream().collect(Collectors.groupingBy(
317
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
318
			Map<Integer, Integer> theirPurchaseItemQtyMap = inventoryItems.stream().collect(Collectors
319
					.groupingBy(InventoryItem::getItemId, Collectors.summingInt(InventoryItem::getInitialQuantity)));
24709 amit.gupta 320
			for (Map.Entry<Integer, Integer> itemQtyEntry : theirPurchaseItemQtyMap.entrySet()) {
24711 amit.gupta 321
				if (!ourSaleItemQtyMap.containsKey(itemQtyEntry.getKey())) {
322
					LOGGER.info("Cannot find in Invoice {} item {}", purchase.getPurchaseReference(),
323
							itemQtyEntry.getKey());
24646 amit.gupta 324
					continue;
24645 amit.gupta 325
				}
24709 amit.gupta 326
				int ourSale = ourSaleItemQtyMap.get(itemQtyEntry.getKey());
24713 amit.gupta 327
				int quantityToReduce = itemQtyEntry.getValue() - ourSale;
24716 amit.gupta 328
				List<InventoryItem> itemIis = itemIdInventoryMap.get(itemQtyEntry.getKey());
329
				if (itemIdInventoryMap != null) {
330
					for (InventoryItem ii : itemIis) {
24915 amit.gupta 331
						if (ii.getSerialNumber() == null && ii.getGoodQuantity() == ii.getInitialQuantity()
332
								&& quantityToReduce >= ii.getInitialQuantity()) {
24734 amit.gupta 333
							LOGGER.info("Changed in inventoryItems {}, {}, {}, {}, {}, {}",
24716 amit.gupta 334
									purchase.getPurchaseReference(), ii.getId(), ii.getItemId(),
24734 amit.gupta 335
									ii.getInitialQuantity(), ii.getGoodQuantity(), quantityToReduce);
24912 amit.gupta 336
							List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
337
							for (ScanRecord scanRecord : scanRecords) {
24915 amit.gupta 338
								CurrentInventorySnapshot cis = currentInventorySnapshotRepository
339
										.selectByItemIdAndFofoId(itemQtyEntry.getKey(), purchase.getFofoId());
340
								scanRecord.setQuantity(0);
341
								ii.setGoodQuantity(0);
342
								quantityToReduce = quantityToReduce - ii.getInitialQuantity();
343
								cis.setAvailability(cis.getAvailability() - ii.getInitialQuantity());
344
								purchase.setUnfullfilledNonSerializedQuantity(
345
										purchase.getUnfullfilledNonSerializedQuantity() + quantityToReduce);
346
								LOGGER.info("Rectified {}, {}, {}, {}, {}, {}", purchase.getPurchaseReference(),
347
										ii.getId(), ii.getItemId(), ii.getInitialQuantity(), ii.getGoodQuantity(),
348
										quantityToReduce);
24711 amit.gupta 349
							}
24641 amit.gupta 350
						}
351
					}
352
				}
353
			}
354
		}
24953 amit.gupta 355
		// throw new Exception();
24641 amit.gupta 356
	}
24767 amit.gupta 357
 
24802 amit.gupta 358
	public void migrateChallansToInvoices() throws Exception {
24814 amit.gupta 359
		Map<String, List<Order>> invoiceOrdersMap = orderRepository.selectAllChallans().stream()
360
				.filter(x -> !x.getLineItem().getHsnCode().equals("NOGST"))
24794 amit.gupta 361
				.collect(Collectors.groupingBy(Order::getInvoiceNumber, Collectors.toList()));
24814 amit.gupta 362
 
25837 amit.gupta 363
		List<List<?>> rows = new ArrayList<>();
24814 amit.gupta 364
		for (String invoice : invoiceOrdersMap.keySet()) {
24794 amit.gupta 365
			Order oneOrder = invoiceOrdersMap.get(invoice).get(0);
366
			int totalOrders = invoiceOrdersMap.get(invoice).size();
367
			LineItem lineItem = oneOrder.getLineItem();
24802 amit.gupta 368
			oneOrder.setBillingTimestamp(LocalDateTime.now());
369
			oneOrder.setInvoiceNumber(getInvoiceNumber(oneOrder));
24819 amit.gupta 370
			rows.add(Arrays.asList(oneOrder.getId(), invoice, oneOrder.getInvoiceNumber(), lineItem.getQuantity()));
24883 amit.gupta 371
			LOGGER.info(invoice + "\t" + oneOrder.getInvoiceNumber() + oneOrder.getId() + "\t",
372
					"\t" + totalOrders + "\t" + lineItem.getQuantity());
24814 amit.gupta 373
			Purchase p = null;
374
			try {
375
				p = purchaseRepository.selectByPurchaseReferenceAndFofoId(invoice, oneOrder.getRetailerId());
376
			} catch (Exception e) {
24815 amit.gupta 377
				LOGGER.info("Could not find purchase for invoice {}", invoice);
24812 amit.gupta 378
			}
24814 amit.gupta 379
			if (p != null) {
380
				List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(p.getId());
381
				for (InventoryItem inventoryItem : inventoryItems) {
24815 amit.gupta 382
					LOGGER.info(inventoryItem.getItemId() + " " + inventoryItem.getGoodQuantity() + " "
24883 amit.gupta 383
							+ inventoryItem.getHsnCode() + " " + inventoryItem.getSerialNumber() + " "
384
							+ p.getPurchaseReference());
24814 amit.gupta 385
				}
386
			}
387
 
24794 amit.gupta 388
		}
24818 amit.gupta 389
		changePartnerInvoices();
24883 amit.gupta 390
		ByteArrayOutputStream baos = FileUtil
391
				.getCSVByteStream(Arrays.asList("Order id", "Challan", "Invoice", "Quantity"), rows);
392
 
24819 amit.gupta 393
		Utils.sendMailWithAttachment(googleMailSender,
394
				new String[] { "amit.gupta@shop2020.in", "sunny.yadav@smartdukaan.com" }, null,
24883 amit.gupta 395
				"Challans Converted to Invoice", "PFA", "Challans-To-Invoice.csv",
396
				new ByteArrayResource(baos.toByteArray()));
24916 amit.gupta 397
		throw new Exception();
24794 amit.gupta 398
	}
24767 amit.gupta 399
 
24802 amit.gupta 400
	private String getInvoiceNumber(Order oneOrder) {
24805 amit.gupta 401
		String prefix = oneOrder.getInvoiceNumber().split("-")[1].replaceAll("\\d*", "");
24803 amit.gupta 402
		System.out.println("Prefix is " + prefix);
24802 amit.gupta 403
		SellerWarehouse sellerWarehouse = sellerWarehouseRepository.selectByPrefix(prefix);
404
		int newSequence = sellerWarehouse.getInvoiceSequence() + 1;
405
		sellerWarehouse.setInvoiceSequence(newSequence);
24814 amit.gupta 406
		return prefix + newSequence;
24802 amit.gupta 407
	}
24814 amit.gupta 408
 
24806 amit.gupta 409
	private void changePartnerInvoices() throws Exception {
24814 amit.gupta 410
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectByInvoiceNumberLike("%SEC%");
411
		for (FofoOrder fofoOrder : fofoOrders) {
24806 amit.gupta 412
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
24814 amit.gupta 413
			if (fofoOrderItem.getBrand().equals("Vivo")) {
24806 amit.gupta 414
				String challanString = fofoOrder.getInvoiceNumber();
24814 amit.gupta 415
				String storeCode = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoOrder.getFofoId())
416
						.getPrefix();
24806 amit.gupta 417
				String invoiceNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), storeCode);
418
				fofoOrder.setInvoiceNumber(invoiceNumber);
419
				fofoOrder.setCreateTimestamp(LocalDateTime.now());
24818 amit.gupta 420
				LOGGER.info(challanString + "\t" + invoiceNumber + "\t" + fofoOrderItem.getQuantity());
24806 amit.gupta 421
			}
24814 amit.gupta 422
 
24806 amit.gupta 423
		}
424
	}
24802 amit.gupta 425
 
24883 amit.gupta 426
	public void createMonthlyTargets() throws Exception {
427
		Map<String, List<TargetSlab>> defaultSlabs = targetSlabRepository.getAllDefaultSlabs();
428
		for (String memberType : defaultSlabs.keySet()) {
429
			PartnerTargetDetails ptd = new PartnerTargetDetails();
430
			ptd.setBrandName(null);
431
 
432
			LocalDate startDate = LocalDate.now().withDayOfMonth(1);
433
			int totalDays = startDate.lengthOfMonth();
434
			String monthName = startDate.getMonth().toString();
435
			ptd.setStartDate(startDate.atStartOfDay());
436
			ptd.setEndDate(startDate.plusDays(totalDays - 1).atTime(LocalTime.MAX));
437
			ptd.setTargetName(String.format("%s Sales Target for %s Partners", monthName, memberType));
438
			partnerTargetRepository.persist(ptd);
439
			TargetSlabRepositoryImpl.TYPE_PARTNER_MAPPING.get(memberType).forEach(x -> {
440
				x.setTargetId(ptd.getId());
441
				partnerTargetRepository.persist(x);
442
			});
443
 
444
			List<TargetSlab> slabs = defaultSlabs.get(memberType);
445
			slabs.stream().forEach(x -> {
446
				x.setTargetId(ptd.getId());
447
				targetSlabRepository.persist(x);
448
			});
449
		}
450
	}
451
 
25023 amit.gupta 452
	public void populateSchemes() {
25021 amit.gupta 453
		List<Integer> list05 = Arrays.asList(29093, 29094, 29095, 29096, 29097, 29098, 29099, 29101, 29102);
454
		List<Integer> list10 = Arrays.asList(29187, 29188);
455
		List<Integer> list13 = Arrays.asList(28095, 28097, 28098, 28101, 28102, 28104, 28106, 28107, 28108, 28227,
456
				28228, 28229, 28231, 29055, 29056, 29066, 29079);
457
		List<Integer> list15 = Arrays.asList(20891, 27938, 27939, 27940, 27941, 27943, 27947, 27948, 27953, 27954,
458
				27955, 28220, 28467, 29020, 29033, 29034, 29035, 29592, 29886, 29890, 29891, 29941, 29942, 27445, 27958,
459
				27960, 27961);
460
		List<Integer> list18 = Arrays.asList(28137, 28138, 28140, 28157, 28158, 28161, 28162, 28163, 28164, 28176,
461
				28177, 28178, 28199, 28200, 28208, 28209, 28210, 28211, 28215, 28216, 28217, 28230, 28380, 28381, 28382,
462
				28383, 28384, 28385, 28386, 28387, 28388, 28389, 28390, 28391, 28392, 28395, 28461, 28462, 28463, 28464,
463
				28465, 28466, 28488, 28489, 28490, 28491, 28564, 28565, 28762, 28773, 28871, 28872, 28873, 28874, 28880,
464
				28881, 28914, 28915, 28916, 28917, 28918, 28919, 28920, 29046, 29047, 29048, 29068, 29069, 29110, 29111,
465
				29112, 29113, 29114, 29115, 29116, 29117, 29207, 29208, 29217, 29218, 29225, 29474, 29475, 29476, 29477,
466
				29478, 29479, 29483, 29485, 29486, 29487, 29488, 29739, 29740, 29741, 29742, 29743, 29744, 29745, 29746,
467
				29747, 29748, 29749, 29753, 29756, 29757, 29758, 29760, 29761, 29762, 29763, 29764, 29765, 29766, 29767,
468
				29779, 29780, 29781, 29792, 29793, 29828, 29829, 29830, 29879, 29880, 29881, 29882, 29951);
469
		List<Integer> list20 = Arrays.asList(27975, 27976, 28091, 28363, 29023, 29024, 29025);
470
		List<Integer> list25 = Arrays.asList(28763, 28764, 28765, 29152, 29154, 29157, 29209, 29210, 29601, 29602,
471
				29720, 29721, 29722, 29723, 29725, 29726, 29727);
472
		List<Integer> list30 = Arrays.asList(27962, 27963, 27964, 27965, 27966, 27968, 27969, 28328, 28362, 28566,
473
				28567, 28568, 28571, 28572, 29073, 29074, 29075, 29080, 29081, 29120, 29121, 29122, 29124, 29189, 29190,
474
				29191, 29192, 29193, 29194, 29196, 29197, 29198, 29199, 29515, 29516, 29517, 29675, 29676, 29677, 29678,
475
				29679, 29707, 29708, 29794, 29795, 29883, 29884, 29885, 29887, 29888, 29889, 29931, 29932, 29935, 29936,
476
				29937, 29938, 29939, 29940);
477
		List<Integer> list35 = Arrays.asList(27996, 27998, 29067, 29071, 29643, 29644, 29945, 29946, 29987, 29052,
478
				29053, 29078, 29085, 29086, 29567, 29568, 29569, 29570, 29797, 29914, 29915, 29930, 28877, 28878, 29604,
479
				29605, 29606, 29775, 29776, 29777, 29778, 28862, 28863, 28864, 29026, 29103, 29104, 29105, 28979, 28980,
480
				28981, 28982, 28983, 29002, 29003, 29004, 29834, 29835, 29836, 29837, 29943);
481
		List<Integer> list40 = Arrays.asList(29082, 29083, 28766, 28767, 28768, 28769, 28771);
482
		List<Integer> list45 = Arrays.asList(28026, 28027, 28028, 29528, 29529, 29530, 29534, 29535, 29536, 29538,
483
				29755);
484
		List<Integer> list55 = Arrays.asList(28010, 28011, 28015, 28016, 28019, 28240, 28469, 28470, 28471, 28569,
485
				28570, 28674, 28759, 28761, 28909, 28910, 28911, 28912, 28913, 29108, 29109, 29143, 29144, 29145, 29146,
486
				29211, 29212, 29213, 29214, 29482, 29511, 29512, 29521, 29525, 29526, 29527, 29574, 29575, 29576, 29611,
487
				29612, 29616, 29641, 29642, 29728, 29729, 29750, 29771, 29782, 29783, 29784, 29923, 29924, 29944, 29953,
488
				29992, 29994, 27977, 27978, 28092, 28325, 28326, 28327, 28486, 28487, 29148, 29149, 29150, 29151, 29384,
489
				29385, 29386, 29427, 29489, 29518, 29519, 29520, 29577, 29578, 29579, 29580, 29586, 29660, 29661, 29662,
490
				29663, 29769, 29770, 29790, 29791, 29796, 29928, 29929, 29947, 29948, 28093, 28094, 28556, 28557, 28673,
491
				28867, 28868, 28870, 29089, 29090, 29091, 29106, 29107);
492
		List<Integer> list65 = Arrays.asList(28058, 28223, 28224, 28225, 28226, 28329, 29201, 29202, 29203, 29204,
493
				29205, 29206, 29466, 29467, 29468, 29469, 29470, 29471, 29472, 29573);
494
		Map<Float, List<Integer>> m = new HashMap<>();
495
		m.put(0.5f, list05);
496
		m.put(1.0f, list10);
497
		m.put(1.3f, list13);
498
		m.put(1.5f, list15);
499
		m.put(1.8f, list18);
500
		m.put(2.0f, list20);
501
		m.put(2.5f, list25);
502
		m.put(3.0f, list30);
503
		m.put(3.5f, list35);
504
		m.put(4.0f, list40);
505
		m.put(4.5f, list45);
506
		m.put(5.5f, list55);
507
		m.put(6.5f, list65);
508
		for (Map.Entry<Float, List<Integer>> itemsListEntry : m.entrySet()) {
509
			Scheme s1 = getScheme();
510
			s1.setAmount(itemsListEntry.getKey());
511
			schemeRepository.persist(s1);
25034 amit.gupta 512
			for (Integer itemId : itemsListEntry.getValue()) {
25021 amit.gupta 513
				SchemeItem schemeItem = new SchemeItem();
514
				schemeItem.setItemId(itemId);
515
				schemeItem.setSchemeId(s1.getId());
516
				schemeItemRepository.persist(schemeItem);
517
			}
518
		}
25034 amit.gupta 519
 
25021 amit.gupta 520
	}
521
 
522
	private Scheme getScheme() {
523
		Scheme s = new Scheme();
524
		s.setName("List Price Margin");
525
		s.setDescription("List Price Margin");
526
		s.setActiveTimestamp(null);
527
		s.setStartDateTime(LocalDate.of(2019, 6, 1).atStartOfDay());
528
		s.setEndDateTime(LocalDate.of(2019, 7, 1).atStartOfDay());
529
		s.setAmountType(AmountType.PERCENTAGE);
530
		s.setCreateTimestamp(LocalDateTime.now());
531
		s.setExpireTimestamp(null);
532
		s.setCreatedBy(175120474);
533
		return s;
534
	}
535
 
24957 amit.gupta 536
	public void findMismatchesInIndent() throws Exception {
537
		List<Order> allInProcessOrders = orderRepository.selectAllOrder(OrderStatus.SUBMITTED_FOR_PROCESSING);
24967 amit.gupta 538
 
25021 amit.gupta 539
		Map<String, Integer> lineItemWhQtyMap = allInProcessOrders.stream()
25734 amit.gupta 540
				.collect(Collectors.groupingBy(y -> y.getLineItem().getItemId() + "-" + y.getFulfilmentWarehouseId(),
24967 amit.gupta 541
						Collectors.summingInt(y -> y.getLineItem().getQuantity())));
25021 amit.gupta 542
 
543
		lineItemWhQtyMap.forEach((key, value) -> {
544
 
24967 amit.gupta 545
			int itemId = Integer.parseInt(key.split("-")[0]);
546
			int warehouseId = Integer.parseInt(key.split("-")[1]);
25021 amit.gupta 547
			System.out.printf("%d\t%d\t%d\n", itemId, warehouseId, value);
548
			SaholicInventorySnapshot cis = saholicInventorySnapshotRepository.selectByWarehouseIdandItemId(warehouseId,
549
					itemId);
550
			if (cis == null) {
24970 amit.gupta 551
				cis = new SaholicInventorySnapshot();
552
				cis.setItemId(itemId);
553
				cis.setWarehouseId(warehouseId);
554
				cis.setAvailability(0);
555
				saholicInventorySnapshotRepository.persist(cis);
556
			}
24967 amit.gupta 557
			cis.setReserved(value);
558
		});
24953 amit.gupta 559
	}
560
 
25034 amit.gupta 561
	public void fixSchemePayouts() throws Exception {
25524 amit.gupta 562
		LOGGER.info("In fix scheme Payouts");
25522 amit.gupta 563
		LocalDateTime startDate = LocalDate.of(2019, 9, 1).atStartOfDay();
564
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(startDate, LocalDateTime.now());
25530 amit.gupta 565
 
25034 amit.gupta 566
		for (SchemeInOut sio : sios) {
25530 amit.gupta 567
			if (sio.getSchemeId() != 347) {
25523 amit.gupta 568
				LOGGER.info("Skipping {}", sio.getSchemeId());
25522 amit.gupta 569
				continue;
570
			}
25043 amit.gupta 571
			genericRepository.delete(sio);
25522 amit.gupta 572
			InventoryItem ii = inventoryItemRepository.selectById(sio.getInventoryItemId());
573
			UserWallet userWallet = userWalletRepository.selectByRetailerId(ii.getFofoId());
574
			Scheme scheme = schemeRepository.selectById(sio.getSchemeId());
575
			if (scheme.getType().equals(SchemeType.IN)) {
576
				List<UserWalletHistory> historyList = userWalletHistoryRepository
577
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_IN);
578
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 579
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 580
						genericRepository.delete(uwh);
581
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
582
					}
583
				}
584
			} else {
585
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
586
				int orderId = scanRecords.get(0).getOrderId();
587
				List<UserWalletHistory> historyList = userWalletHistoryRepository
588
						.selectAllByreferenceIdandreferenceType(orderId, WalletReferenceType.SCHEME_OUT);
589
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 590
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 591
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
592
						genericRepository.delete(uwh);
593
					}
594
				}
595
				List<UserWalletHistory> historyListBroken = userWalletHistoryRepository
25530 amit.gupta 596
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_OUT);
25522 amit.gupta 597
				for (UserWalletHistory uwh : historyListBroken) {
25530 amit.gupta 598
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 599
						genericRepository.delete(uwh);
600
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
601
					}
602
				}
603
			}
604
 
25530 amit.gupta 605
			// System.out.println("Total Amount Rolled Back is " + totalRollbackAmount);
25516 amit.gupta 606
		}
25589 amit.gupta 607
		scheduledTasks.processScheme(startDate, startDate.plusDays(10), true);
25030 amit.gupta 608
	}
25530 amit.gupta 609
 
610
	public void fixWallet() throws Exception {
611
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
25536 amit.gupta 612
		System.out.println("id\tcode\tactive\tname\tcity\tstate\twallet amount\tsum\twallet amount-sum");
25530 amit.gupta 613
		for (FofoStore fofoStore : fofoStores) {
614
			UserWallet uw = userWalletRepository.selectByRetailerId(fofoStore.getId());
615
			User user = userRepository.selectById(fofoStore.getId());
25749 amit.gupta 616
			if (user == null) {
25533 amit.gupta 617
				LOGGER.info("store does not exist", fofoStore.getCode());
25535 amit.gupta 618
				continue;
25533 amit.gupta 619
			}
25536 amit.gupta 620
			Address address = null;
621
			try {
622
				address = addressRepository.selectById(user.getAddressId());
25749 amit.gupta 623
			} catch (Exception e) {
25536 amit.gupta 624
				LOGGER.info("Could not find address for Store", fofoStore.getCode());
625
				address = new Address();
626
			}
25539 amit.gupta 627
			double sum = userWalletHistoryRepository.selectSumByWallet(uw.getId());
25749 amit.gupta 628
			int calculated = (int) sum;
629
			System.out.printf("%d\t%s\t%b\t%s\t%s\t%s\t%d\t%d\t%d%n", fofoStore.getId(), fofoStore.getCode(),
630
					fofoStore.isActive(), address.getName(), address.getCity(), address.getState(), uw.getAmount(),
631
					calculated, uw.getAmount() - calculated);
25530 amit.gupta 632
		}
633
	}
25749 amit.gupta 634
 
25734 amit.gupta 635
	public void changeWarehouse() throws Exception {
636
		transactionService.moveWarehouses();
637
	}
25749 amit.gupta 638
 
639
	public void mailDashboardScreenshots() throws Exception {
640
		System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
641
 
25752 amit.gupta 642
		ChromeOptions options = new ChromeOptions();
643
		options.addArguments("--headless");
644
		options.addArguments("--no-sandbox");
645
		options.addArguments("start-maximized");
646
		options.addArguments("disable-infobars");
647
		options.addArguments("--disable-extensions");
648
 
25753 amit.gupta 649
		WebDriver driver = new ChromeDriver(options);
25774 amit.gupta 650
		driver.manage().window().setSize(new Dimension(1600, 900));
25749 amit.gupta 651
		driver.manage().window().maximize();
25752 amit.gupta 652
		// Deleting all the cookies
25749 amit.gupta 653
		driver.manage().deleteAllCookies();
25752 amit.gupta 654
		// Specifiying pageLoadTimeout and Implicit wait
25749 amit.gupta 655
		driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
656
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
25752 amit.gupta 657
 
25749 amit.gupta 658
		Map<String, Set<Integer>> authUserPartnerIdMapping = csService.getAuthUserPartnerIdMapping();
659
		Set<Integer> allPartners = new HashSet<>();
25765 amit.gupta 660
		Map<Integer, File> partnerSnapshotMap = new HashMap<>();
25752 amit.gupta 661
		authUserPartnerIdMapping.values().stream().forEach(x -> allPartners.addAll(x));
25749 amit.gupta 662
		System.out.println(allPartners.size());
25752 amit.gupta 663
		for (int fofoId : allPartners) {
25749 amit.gupta 664
			driver.get("https://partners.smartdukaan.com/12dashboard34?fofoId=" + fofoId);
25765 amit.gupta 665
			File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
666
			partnerSnapshotMap.put(fofoId, file);
25752 amit.gupta 667
 
25749 amit.gupta 668
		}
25752 amit.gupta 669
		for (Map.Entry<String, Set<Integer>> entry : authUserPartnerIdMapping.entrySet()) {
25749 amit.gupta 670
			String email = entry.getKey();
25996 amit.gupta 671
			LOGGER.info("Sending mail start to {}", email);
25749 amit.gupta 672
			Set<Integer> partnerIds = entry.getValue();
673
			StringBuffer body = new StringBuffer();
25769 amit.gupta 674
			Map<Integer, File> emailSnapshotMap = new HashMap<>();
25752 amit.gupta 675
			for (int fofoId : partnerIds) {
25769 amit.gupta 676
				body.append(String.format("<br/><img src=\"cid:%d\"/>", fofoId));
677
				emailSnapshotMap.put(fofoId, partnerSnapshotMap.get(fofoId));
25749 amit.gupta 678
			}
25837 amit.gupta 679
			Utils.sendEmbeddedHtmlMail(mailSender, new String[] { email }, new String[] {},
25752 amit.gupta 680
					String.format("Franchise Screenshots - %s", FormattingUtils.formatDate(LocalDateTime.now())),
25837 amit.gupta 681
					body.toString(), emailSnapshotMap);
25996 amit.gupta 682
			LOGGER.info("Sent mail to {}", email);
25749 amit.gupta 683
		}
684
		driver.quit();
685
	}
26033 amit.gupta 686
 
26299 amit.gupta 687
	// Rollout prebooking orders amount in case the order is grned.
26033 amit.gupta 688
	public void pbfix() throws ProfitMandiBusinessException {
689
		List<Item> items = itemRepository.selectAllByCatalogItemId(1022304);
26299 amit.gupta 690
		for (Item item : items) {
26033 amit.gupta 691
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByItemId(item.getId(), 0, 500);
26299 amit.gupta 692
			for (InventoryItem inventoryItem : inventoryItems) {
26033 amit.gupta 693
				List<PrebookingOrder> prebookingOrders = prebookingOrderRepository
26299 amit.gupta 694
						.selectByFofoIdAndCatalogIds(inventoryItem.getFofoId(), item.getCatalogItemId()).stream()
695
						.collect(Collectors.toList());
696
				if (prebookingOrders.size() > 0) {
697
					purchaseService.sendPrebookingNotifyMessage(prebookingOrders.get(0));
26033 amit.gupta 698
				}
26299 amit.gupta 699
				// inventoryItem.getFofoId()
26033 amit.gupta 700
			}
701
		}
26299 amit.gupta 702
		// throw new ProfitMandiBusinessException("", "", "");
703
		// prebookingOrderRepository.select
26033 amit.gupta 704
		// TODO Auto-generated method stub
26299 amit.gupta 705
 
26033 amit.gupta 706
	}
26092 amit.gupta 707
 
26299 amit.gupta 708
	public void fixGrn() throws Exception {
26092 amit.gupta 709
		List<Purchase> incompletePurchases = purchaseRepository.selectIncompletePurchase();
26299 amit.gupta 710
		for (Purchase incompletePurchase : incompletePurchases) {
711
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(
712
					incompletePurchase.getPurchaseReference(), incompletePurchase.getFofoId());
26093 amit.gupta 713
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(incompletePurchase.getId());
714
			Map<Integer, Integer> grnedItems = inventoryItems.stream().collect(
26299 amit.gupta 715
					Collectors.groupingBy(x -> x.getItemId(), Collectors.summingInt(x -> x.getInitialQuantity())));
716
			Map<Integer, Integer> billedItems = orders.stream().collect(Collectors.groupingBy(
717
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
718
			for (Integer billedItemId : billedItems.keySet()) {
719
				if (grnedItems.containsKey(billedItemId)) {
720
					if (grnedItems.get(billedItemId) > billedItems.get(billedItemId)) {
721
						LOGGER.info("Billed Qty {} ---- Grned {}, ItemId {}, Invoice Number {}({}), Grn Date {}",
722
								billedItems.get(billedItemId), grnedItems.get(billedItemId), billedItemId,
723
								incompletePurchase.getPurchaseReference(), incompletePurchase.getId(),
724
								incompletePurchase.getCreateTimestamp());
26095 amit.gupta 725
						Item item = itemRepository.selectById(billedItemId);
26299 amit.gupta 726
						if (item.getType().equals(ItemType.SERIALIZED)) {
727
 
26096 amit.gupta 728
						} else {
26299 amit.gupta 729
							for (InventoryItem inventoryItem : inventoryItems) {
730
								if (inventoryItem.getItemId() == billedItemId && inventoryItem.getGoodQuantity() == 0) {
731
									List<ScanRecord> scanRecords = scanRecordRepository
732
											.selectByInventoryItemId(inventoryItem.getId());
733
									if (scanRecords.size() == 1 && scanRecords.get(0).getQuantity() == 0) {
26096 amit.gupta 734
										LOGGER.info("Safe to remove InventoryItem Id {}", inventoryItem.getId());
26101 amit.gupta 735
										scanRecordRepository.delete(scanRecords.get(0));
736
										inventoryItemRepository.delete(inventoryItem);
26299 amit.gupta 737
										incompletePurchase.setUnfullfilledNonSerializedQuantity(
738
												incompletePurchase.getUnfullfilledNonSerializedQuantity()
739
														+ inventoryItem.getInitialQuantity());
26096 amit.gupta 740
									}
741
								}
742
							}
26095 amit.gupta 743
						}
26093 amit.gupta 744
					}
745
				}
26092 amit.gupta 746
			}
26299 amit.gupta 747
 
26092 amit.gupta 748
		}
26299 amit.gupta 749
 
26092 amit.gupta 750
	}
26265 amit.gupta 751
 
752
	public void fixDupGrns() throws Exception {
26412 amit.gupta 753
		List<Integer> duplicatePurchaseIds = Arrays.asList(14984);
26299 amit.gupta 754
		for (int duplicatePurchaseId : duplicatePurchaseIds) {
26265 amit.gupta 755
			Purchase purchase = purchaseRepository.selectById(duplicatePurchaseId);
756
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(duplicatePurchaseId);
26299 amit.gupta 757
			if (inventoryItems.size() == 0) {
26266 amit.gupta 758
				LOGGER.info("Could not find InventoryItems for {}", duplicatePurchaseId);
759
				continue;
760
			}
26299 amit.gupta 761
			schemeService.rollbackSchemes(inventoryItems.stream().map(x -> x.getId()).collect(Collectors.toList()),
762
					duplicatePurchaseId,
763
					"Rolled back duplicate grn for Purchase Invoice " + purchase.getPurchaseReference());
764
			for (InventoryItem inventoryItem : inventoryItems) {
26265 amit.gupta 765
				inventoryItemRepository.delete(inventoryItem);
766
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId());
26299 amit.gupta 767
				for (ScanRecord scanRecord : scanRecords) {
26265 amit.gupta 768
					scanRecordRepository.delete(scanRecord);
769
				}
26299 amit.gupta 770
				List<SchemeInOut> sios = schemeInOutRepository
771
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
772
				for (SchemeInOut sio : sios) {
26265 amit.gupta 773
					LOGGER.info("SIO - {}", sio);
774
					schemeInOutRepository.delete(sio);
775
				}
26299 amit.gupta 776
 
26265 amit.gupta 777
			}
778
		}
26299 amit.gupta 779
		// throw new Exception();
26265 amit.gupta 780
	}
25043 amit.gupta 781
}
782
 
783
//7015845171