Subversion Repositories SmartDukaan

Rev

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