Subversion Repositories SmartDukaan

Rev

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