Subversion Repositories SmartDukaan

Rev

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