Subversion Repositories SmartDukaan

Rev

Rev 28045 | Rev 28047 | 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;
27450 tejbeer 4
import java.io.IOException;
23824 amit.gupta 5
import java.time.LocalDate;
23755 amit.gupta 6
import java.time.LocalDateTime;
23824 amit.gupta 7
import java.time.LocalTime;
27511 amit.gupta 8
import java.time.Month;
27310 amit.gupta 9
import java.time.temporal.ChronoUnit;
24819 amit.gupta 10
import java.util.ArrayList;
23755 amit.gupta 11
import java.util.Arrays;
27450 tejbeer 12
import java.util.Base64;
23827 amit.gupta 13
import java.util.Collections;
26928 amit.gupta 14
import java.util.Comparator;
24002 amit.gupta 15
import java.util.HashMap;
24005 amit.gupta 16
import java.util.HashSet;
23755 amit.gupta 17
import java.util.List;
24002 amit.gupta 18
import java.util.Map;
25749 amit.gupta 19
import java.util.Set;
20
import java.util.concurrent.TimeUnit;
24641 amit.gupta 21
import java.util.stream.Collectors;
23755 amit.gupta 22
 
24819 amit.gupta 23
import org.apache.commons.io.output.ByteArrayOutputStream;
23755 amit.gupta 24
import org.apache.commons.lang.StringUtils;
25
import org.apache.logging.log4j.LogManager;
26
import org.apache.logging.log4j.Logger;
27450 tejbeer 27
import org.json.JSONArray;
28
import org.json.JSONObject;
25773 amit.gupta 29
import org.openqa.selenium.Dimension;
25749 amit.gupta 30
import org.openqa.selenium.OutputType;
31
import org.openqa.selenium.TakesScreenshot;
32
import org.openqa.selenium.WebDriver;
33
import org.openqa.selenium.chrome.ChromeDriver;
25752 amit.gupta 34
import org.openqa.selenium.chrome.ChromeOptions;
23755 amit.gupta 35
import org.springframework.beans.factory.annotation.Autowired;
24819 amit.gupta 36
import org.springframework.core.io.ByteArrayResource;
24767 amit.gupta 37
import org.springframework.mail.javamail.JavaMailSender;
23755 amit.gupta 38
import org.springframework.stereotype.Component;
39
import org.springframework.transaction.annotation.Transactional;
40
 
26214 amit.gupta 41
import com.smartdukaan.cron.scheduled.SamsungIMEIActivationService;
25043 amit.gupta 42
import com.smartdukaan.cron.scheduled.ScheduledTasks;
26095 amit.gupta 43
import com.spice.profitmandi.common.enumuration.ItemType;
26033 amit.gupta 44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27450 tejbeer 45
import com.spice.profitmandi.common.model.CustomRetailer;
24819 amit.gupta 46
import com.spice.profitmandi.common.util.FileUtil;
25749 amit.gupta 47
import com.spice.profitmandi.common.util.FormattingUtils;
24819 amit.gupta 48
import com.spice.profitmandi.common.util.Utils;
26033 amit.gupta 49
import com.spice.profitmandi.dao.entity.catalog.Item;
25021 amit.gupta 50
import com.spice.profitmandi.dao.entity.catalog.Scheme;
26579 amit.gupta 51
import com.spice.profitmandi.dao.entity.catalog.TagListing;
27286 amit.gupta 52
import com.spice.profitmandi.dao.entity.dtr.PaymentOptionTransaction;
24716 amit.gupta 53
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
26759 amit.gupta 54
import com.spice.profitmandi.dao.entity.fofo.DebitNote;
27286 amit.gupta 55
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
24806 amit.gupta 56
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
57
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
25530 amit.gupta 58
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24005 amit.gupta 59
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
26928 amit.gupta 60
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
26033 amit.gupta 61
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrder;
23898 amit.gupta 62
import com.spice.profitmandi.dao.entity.fofo.Purchase;
26759 amit.gupta 63
import com.spice.profitmandi.dao.entity.fofo.PurchaseReturnItem;
24716 amit.gupta 64
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
25034 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
25021 amit.gupta 66
import com.spice.profitmandi.dao.entity.fofo.SchemeItem;
24953 amit.gupta 67
import com.spice.profitmandi.dao.entity.inventory.SaholicInventorySnapshot;
27721 amit.gupta 68
import com.spice.profitmandi.dao.entity.transaction.HdfcPayment;
23824 amit.gupta 69
import com.spice.profitmandi.dao.entity.transaction.LineItem;
23755 amit.gupta 70
import com.spice.profitmandi.dao.entity.transaction.LineItemImei;
71
import com.spice.profitmandi.dao.entity.transaction.Order;
24802 amit.gupta 72
import com.spice.profitmandi.dao.entity.transaction.SellerWarehouse;
25046 amit.gupta 73
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
25034 amit.gupta 74
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
25530 amit.gupta 75
import com.spice.profitmandi.dao.entity.user.Address;
76
import com.spice.profitmandi.dao.entity.user.User;
27511 amit.gupta 77
import com.spice.profitmandi.dao.entity.warehouse.WarehouseInventoryItem;
28038 amit.gupta 78
import com.spice.profitmandi.dao.entity.warehouse.WarehouseScan;
25021 amit.gupta 79
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
25522 amit.gupta 80
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
27286 amit.gupta 81
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
26759 amit.gupta 82
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
26579 amit.gupta 83
import com.spice.profitmandi.dao.model.ContentPojo;
27948 amit.gupta 84
import com.spice.profitmandi.dao.model.CreateOfferRequest;
26579 amit.gupta 85
import com.spice.profitmandi.dao.model.MediaPojo;
24716 amit.gupta 86
import com.spice.profitmandi.dao.repository.GenericRepository;
25034 amit.gupta 87
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
25021 amit.gupta 88
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
26579 amit.gupta 89
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25749 amit.gupta 90
import com.spice.profitmandi.dao.repository.cs.CsService;
23899 amit.gupta 91
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27221 amit.gupta 92
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
26579 amit.gupta 93
import com.spice.profitmandi.dao.repository.dtr.Mongo;
27286 amit.gupta 94
import com.spice.profitmandi.dao.repository.dtr.PaymentOptionTransactionRepository;
24716 amit.gupta 95
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24002 amit.gupta 96
import com.spice.profitmandi.dao.repository.fofo.DebitNoteRepository;
27286 amit.gupta 97
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
24806 amit.gupta 98
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
99
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
24002 amit.gupta 100
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24806 amit.gupta 101
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
24883 amit.gupta 102
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
26033 amit.gupta 103
import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderRepository;
23898 amit.gupta 104
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
26759 amit.gupta 105
import com.spice.profitmandi.dao.repository.fofo.PurchaseReturnItemRepository;
24716 amit.gupta 106
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
24002 amit.gupta 107
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
25021 amit.gupta 108
import com.spice.profitmandi.dao.repository.fofo.SchemeItemRepository;
24953 amit.gupta 109
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
26928 amit.gupta 110
import com.spice.profitmandi.dao.repository.inventory.SaholicReservationSnapshotRepository;
27721 amit.gupta 111
import com.spice.profitmandi.dao.repository.transaction.HdfcPaymentRepository;
23755 amit.gupta 112
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
23824 amit.gupta 113
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
23755 amit.gupta 114
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
24772 amit.gupta 115
import com.spice.profitmandi.dao.repository.transaction.ReturnOrderRepository;
24802 amit.gupta 116
import com.spice.profitmandi.dao.repository.transaction.SellerWarehouseRepository;
24767 amit.gupta 117
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
118
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
25530 amit.gupta 119
import com.spice.profitmandi.dao.repository.user.AddressRepository;
24002 amit.gupta 120
import com.spice.profitmandi.dao.repository.user.UserRepository;
27511 amit.gupta 121
import com.spice.profitmandi.dao.repository.warehouse.WarehouseInventoryItemRepository;
28038 amit.gupta 122
import com.spice.profitmandi.dao.repository.warehouse.WarehouseScanRepository;
23899 amit.gupta 123
import com.spice.profitmandi.service.inventory.InventoryService;
26033 amit.gupta 124
import com.spice.profitmandi.service.inventory.PurchaseService;
27948 amit.gupta 125
import com.spice.profitmandi.service.offers.OfferService;
24266 amit.gupta 126
import com.spice.profitmandi.service.order.OrderService;
24005 amit.gupta 127
import com.spice.profitmandi.service.pricing.PriceDropService;
128
import com.spice.profitmandi.service.scheme.SchemeService;
23899 amit.gupta 129
import com.spice.profitmandi.service.transaction.TransactionService;
130
import com.spice.profitmandi.service.user.RetailerService;
131
import com.spice.profitmandi.service.wallet.WalletService;
28046 amit.gupta 132
import com.spice.profitmandi.service.warehouse.WarehouseInventoryService;
23755 amit.gupta 133
 
24953 amit.gupta 134
import in.shop2020.model.v1.order.OrderStatus;
24002 amit.gupta 135
import in.shop2020.model.v1.order.WalletReferenceType;
27450 tejbeer 136
import okhttp3.OkHttpClient;
137
import okhttp3.Request;
138
import okhttp3.Response;
24002 amit.gupta 139
 
23755 amit.gupta 140
@Component
141
@Transactional(rollbackFor = Throwable.class)
142
public class RunOnceTasks {
143
 
28038 amit.gupta 144
 
23755 amit.gupta 145
	private static final Logger LOGGER = LogManager.getLogger(RunOnceTasks.class);
146
	@Autowired
23824 amit.gupta 147
	private LineItemRepository lineItemRepository;
24711 amit.gupta 148
 
23905 amit.gupta 149
	@Autowired
27221 amit.gupta 150
	private LeadRepository leadRepository;
27277 amit.gupta 151
 
27221 amit.gupta 152
	@Autowired
26759 amit.gupta 153
	private PurchaseReturnItemRepository purchaseReturnItemRepository;
26928 amit.gupta 154
 
26759 amit.gupta 155
	@Autowired
24953 amit.gupta 156
	private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
25752 amit.gupta 157
 
25749 amit.gupta 158
	@Autowired
159
	private CsService csService;
26299 amit.gupta 160
 
26033 amit.gupta 161
	@Autowired
26579 amit.gupta 162
	private Mongo mongoClient;
27787 amit.gupta 163
 
27286 amit.gupta 164
	@Autowired
165
	private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
26579 amit.gupta 166
 
167
	@Autowired
26195 amit.gupta 168
	private SamsungIMEIActivationService samsungActivationService;
26299 amit.gupta 169
 
26195 amit.gupta 170
	@Autowired
26033 amit.gupta 171
	private PrebookingOrderRepository prebookingOrderRepository;
24953 amit.gupta 172
 
173
	@Autowired
26928 amit.gupta 174
	private SaholicReservationSnapshotRepository saholicReservationInventorySnapshotRepository;
24953 amit.gupta 175
 
176
	@Autowired
24883 amit.gupta 177
	private PartnerTargetRepository partnerTargetRepository;
178
 
179
	@Autowired
24802 amit.gupta 180
	private SellerWarehouseRepository sellerWarehouseRepository;
24814 amit.gupta 181
 
24802 amit.gupta 182
	@Autowired
24806 amit.gupta 183
	private FofoOrderItemRepository fofoOrderItemRepository;
27787 amit.gupta 184
 
27286 amit.gupta 185
	@Autowired
186
	private FofoLineItemRepository fofoLineItemRepository;
24814 amit.gupta 187
 
24806 amit.gupta 188
	@Autowired
189
	private FofoOrderRepository fofoOrderRepository;
24814 amit.gupta 190
 
24806 amit.gupta 191
	@Autowired
24767 amit.gupta 192
	private UserWalletRepository userWalletRepository;
193
 
194
	@Autowired
195
	private UserWalletHistoryRepository userWalletHistoryRepository;
196
 
197
	@Autowired
24002 amit.gupta 198
	private UserRepository userRepository;
24711 amit.gupta 199
 
24002 amit.gupta 200
	@Autowired
23899 amit.gupta 201
	private WalletService walletService;
202
 
203
	@Autowired
25034 amit.gupta 204
	private ItemRepository itemRepository;
205
 
206
	@Autowired
23899 amit.gupta 207
	private InventoryService inventoryService;
208
 
209
	@Autowired
210
	private TransactionService transactionService;
26299 amit.gupta 211
 
26033 amit.gupta 212
	@Autowired
213
	private PurchaseService purchaseService;
23899 amit.gupta 214
 
24711 amit.gupta 215
	// Service for Tertiary/Partner Orders
24266 amit.gupta 216
	@Autowired
217
	private OrderService orderService;
23767 amit.gupta 218
 
23755 amit.gupta 219
	@Autowired
25021 amit.gupta 220
	private SchemeRepository schemeRepository;
25516 amit.gupta 221
 
25043 amit.gupta 222
	@Autowired
25530 amit.gupta 223
	private AddressRepository addressRepository;
25749 amit.gupta 224
 
25530 amit.gupta 225
	@Autowired
25043 amit.gupta 226
	private ScheduledTasks scheduledTasks;
25034 amit.gupta 227
 
25021 amit.gupta 228
	@Autowired
229
	private SchemeItemRepository schemeItemRepository;
230
 
231
	@Autowired
24772 amit.gupta 232
	private ReturnOrderRepository returnOrderRepository;
233
 
234
	@Autowired
23899 amit.gupta 235
	private FofoStoreRepository fofoStoreRepository;
236
 
237
	@Autowired
23755 amit.gupta 238
	private LineItemImeisRepository lineItemImeisRepository;
24711 amit.gupta 239
 
24002 amit.gupta 240
	@Autowired
241
	private InventoryItemRepository inventoryItemRepository;
24814 amit.gupta 242
 
24806 amit.gupta 243
	@Autowired
26579 amit.gupta 244
	private TagListingRepository tagListingRepository;
245
 
246
	@Autowired
24806 amit.gupta 247
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
23901 amit.gupta 248
 
23898 amit.gupta 249
	@Autowired
23899 amit.gupta 250
	private RetailerService retailerService;
24711 amit.gupta 251
 
24002 amit.gupta 252
	@Autowired
253
	private SchemeInOutRepository schemeInOutRepository;
24711 amit.gupta 254
 
24002 amit.gupta 255
	@Autowired
256
	private DebitNoteRepository debitNoteRepository;
27948 amit.gupta 257
 
258
	@Autowired
259
	private OfferService offerService;
23899 amit.gupta 260
 
261
	@Autowired
24716 amit.gupta 262
	private GenericRepository genericRepository;
263
 
264
	@Autowired
23898 amit.gupta 265
	private PurchaseRepository purchaseRepository;
24711 amit.gupta 266
 
24005 amit.gupta 267
	@Autowired
268
	private PriceDropService priceDropService;
24883 amit.gupta 269
 
24819 amit.gupta 270
	@Autowired
271
	private JavaMailSender googleMailSender;
24711 amit.gupta 272
 
24005 amit.gupta 273
	@Autowired
274
	private SchemeService schemeService;
24711 amit.gupta 275
 
24716 amit.gupta 276
	@Autowired
277
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
278
 
279
	@Autowired
24767 amit.gupta 280
	private OrderRepository orderRepository;
281
 
282
	@Autowired
24716 amit.gupta 283
	private ScanRecordRepository scanRecordRepository;
284
 
24767 amit.gupta 285
	@Autowired
286
	private JavaMailSender mailSender;
27451 tejbeer 287
 
27450 tejbeer 288
	private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
289
	private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";
24767 amit.gupta 290
 
27511 amit.gupta 291
	@Autowired
292
	private WarehouseInventoryItemRepository warehouseInventoryItemRepository;
27787 amit.gupta 293
 
23898 amit.gupta 294
	public void populateGrnTimestamp() {
295
		List<Purchase> allPurchases = purchaseRepository.selectAll();
23899 amit.gupta 296
		for (Purchase p : allPurchases) {
23898 amit.gupta 297
			String invoiceNumber = p.getPurchaseReference();
23899 amit.gupta 298
			if (p.getCompleteTimestamp() == null) {
23898 amit.gupta 299
				LOGGER.info("GRN for invoice {} is delivered but partially Completed.", p.getPurchaseReference());
300
			} else {
301
				List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(invoiceNumber, p.getFofoId());
23899 amit.gupta 302
				for (Order order : orders) {
23902 amit.gupta 303
					if (order.getPartnerGrnTimestamp() == null) {
304
						order.setPartnerGrnTimestamp(p.getCompleteTimestamp());
23898 amit.gupta 305
						orderRepository.persist(order);
306
					}
307
				}
308
			}
309
		}
23899 amit.gupta 310
 
23898 amit.gupta 311
	}
23899 amit.gupta 312
 
26408 amit.gupta 313
	public void fetchImeiActivation(int ym) throws Exception {
27787 amit.gupta 314
		LocalDate startDate = null;
315
		LocalDate endDate = null;
316
		if (ym == 0) {
317
			startDate = LocalDate.now().minusDays(30);
318
			endDate = LocalDate.now();
319
		} else {
320
			startDate = LocalDate.now().minusMonths(ym);
321
			endDate = startDate.plusMonths(1);
322
		}
323
		samsungActivationService.getActivationsBetweenNew(startDate, endDate);
26195 amit.gupta 324
	}
26299 amit.gupta 325
 
24716 amit.gupta 326
	public void migarateLineItemsToNewTable() throws Exception {
23755 amit.gupta 327
		LOGGER.info("Before Migrated LineItems Successfully");
23824 amit.gupta 328
		int lineItemImeiId = 0;
329
		LocalDateTime startDate = null;
330
		try {
331
			lineItemImeiId = lineItemImeisRepository.selectMaxId();
23899 amit.gupta 332
			LineItem lineItem = lineItemRepository
333
					.selectById(lineItemImeisRepository.selectById(lineItemImeiId).getLineItemId());
23824 amit.gupta 334
			Order order = orderRepository.selectById(lineItem.getOrderId());
335
			startDate = order.getBillingTimestamp();
336
		} catch (Exception e) {
337
			LOGGER.info("Running before first time");
23826 amit.gupta 338
			startDate = LocalDateTime.of(LocalDate.of(2017, 7, 1), LocalTime.MIDNIGHT);
23824 amit.gupta 339
		}
340
		List<Order> orders = orderRepository.selectAllByBillingDatesBetween(startDate, LocalDateTime.now());
23827 amit.gupta 341
		Collections.reverse(orders);
23899 amit.gupta 342
 
23755 amit.gupta 343
		for (Order order : orders) {
23824 amit.gupta 344
			try {
23767 amit.gupta 345
				String serialNumbers = order.getLineItem().getSerialNumber();
346
				if (!StringUtils.isEmpty(serialNumbers)) {
347
					List<String> serialNumberList = Arrays.asList(serialNumbers.split(","));
348
					for (String serialNumber : serialNumberList) {
349
						int lineItemId = order.getLineItem().getId();
350
						LineItemImei lineItemImei = new LineItemImei();
351
						lineItemImei.setSerialNumber(serialNumber);
352
						lineItemImei.setLineItemId(lineItemId);
353
						lineItemImeisRepository.persist(lineItemImei);
354
					}
355
				} else {
356
					LOGGER.info("Serial Numbers dont exist for Order {}", order.getId());
23755 amit.gupta 357
				}
23824 amit.gupta 358
			} catch (Exception e) {
23899 amit.gupta 359
				LOGGER.info("Error occurred while creating lineitem imei {}, because of {}", order.getId(),
360
						e.getMessage());
23755 amit.gupta 361
			}
362
		}
363
		LOGGER.info("Migrated LineItems Successfully");
364
	}
24266 amit.gupta 365
 
366
	public void cancelOrder(List<String> invoiceNumbers) throws Exception {
367
		orderService.cancelOrder(invoiceNumbers);
368
	}
27787 amit.gupta 369
 
370
	@Autowired
371
	HdfcPaymentRepository hdfcPaymentRepository;
372
 
27721 amit.gupta 373
	public void addPayment() throws Exception {
27722 amit.gupta 374
		List<Integer> paymentIds = Arrays.asList(3777);
27721 amit.gupta 375
		for (int hdfcPaymentId : paymentIds) {
376
			HdfcPayment hdfcPayment = hdfcPaymentRepository.selectById(hdfcPaymentId);
377
			String virtualAccount = hdfcPayment.getVirtualAccount();
378
			String retailerIdString = virtualAccount.substring(6);
379
			int retailerId = Integer.parseInt(retailerIdString);
380
			String description = String.format("Advance payment received through %s, Utr# %s",
381
					hdfcPayment.getTransferMode(), hdfcPayment.getUtr());
382
			walletService.addAmountToWallet(retailerId, hdfcPayment.getId(), WalletReferenceType.AUTOMATED_ADVANCE,
383
					description, (float) hdfcPayment.getAmount(), hdfcPayment.getCreditTimestamp());
384
		}
385
	}
24711 amit.gupta 386
 
24722 amit.gupta 387
	public void migratePurchase() throws Exception {
24641 amit.gupta 388
		List<Purchase> purchases = purchaseRepository.selectPurchaseAllPurchasesLessThanZero();
24706 amit.gupta 389
		System.out.printf("Total Purchases count is %s", purchases.size());
24711 amit.gupta 390
		for (Purchase purchase : purchases) {
391
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchase.getId());
392
			Map<Integer, List<InventoryItem>> itemIdInventoryMap = inventoryItems.stream()
393
					.collect(Collectors.groupingBy(InventoryItem::getItemId));
394
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(purchase.getPurchaseReference(),
395
					purchase.getFofoId());
396
			Map<Integer, Integer> ourSaleItemQtyMap = orders.stream().collect(Collectors.groupingBy(
397
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
398
			Map<Integer, Integer> theirPurchaseItemQtyMap = inventoryItems.stream().collect(Collectors
399
					.groupingBy(InventoryItem::getItemId, Collectors.summingInt(InventoryItem::getInitialQuantity)));
24709 amit.gupta 400
			for (Map.Entry<Integer, Integer> itemQtyEntry : theirPurchaseItemQtyMap.entrySet()) {
24711 amit.gupta 401
				if (!ourSaleItemQtyMap.containsKey(itemQtyEntry.getKey())) {
402
					LOGGER.info("Cannot find in Invoice {} item {}", purchase.getPurchaseReference(),
403
							itemQtyEntry.getKey());
24646 amit.gupta 404
					continue;
24645 amit.gupta 405
				}
24709 amit.gupta 406
				int ourSale = ourSaleItemQtyMap.get(itemQtyEntry.getKey());
24713 amit.gupta 407
				int quantityToReduce = itemQtyEntry.getValue() - ourSale;
24716 amit.gupta 408
				List<InventoryItem> itemIis = itemIdInventoryMap.get(itemQtyEntry.getKey());
409
				if (itemIdInventoryMap != null) {
410
					for (InventoryItem ii : itemIis) {
24915 amit.gupta 411
						if (ii.getSerialNumber() == null && ii.getGoodQuantity() == ii.getInitialQuantity()
412
								&& quantityToReduce >= ii.getInitialQuantity()) {
24734 amit.gupta 413
							LOGGER.info("Changed in inventoryItems {}, {}, {}, {}, {}, {}",
24716 amit.gupta 414
									purchase.getPurchaseReference(), ii.getId(), ii.getItemId(),
24734 amit.gupta 415
									ii.getInitialQuantity(), ii.getGoodQuantity(), quantityToReduce);
24912 amit.gupta 416
							List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
417
							for (ScanRecord scanRecord : scanRecords) {
24915 amit.gupta 418
								CurrentInventorySnapshot cis = currentInventorySnapshotRepository
419
										.selectByItemIdAndFofoId(itemQtyEntry.getKey(), purchase.getFofoId());
420
								scanRecord.setQuantity(0);
421
								ii.setGoodQuantity(0);
422
								quantityToReduce = quantityToReduce - ii.getInitialQuantity();
423
								cis.setAvailability(cis.getAvailability() - ii.getInitialQuantity());
424
								purchase.setUnfullfilledNonSerializedQuantity(
425
										purchase.getUnfullfilledNonSerializedQuantity() + quantityToReduce);
426
								LOGGER.info("Rectified {}, {}, {}, {}, {}, {}", purchase.getPurchaseReference(),
427
										ii.getId(), ii.getItemId(), ii.getInitialQuantity(), ii.getGoodQuantity(),
428
										quantityToReduce);
24711 amit.gupta 429
							}
24641 amit.gupta 430
						}
431
					}
432
				}
433
			}
434
		}
24953 amit.gupta 435
		// throw new Exception();
24641 amit.gupta 436
	}
24767 amit.gupta 437
 
24802 amit.gupta 438
	public void migrateChallansToInvoices() throws Exception {
24814 amit.gupta 439
		Map<String, List<Order>> invoiceOrdersMap = orderRepository.selectAllChallans().stream()
440
				.filter(x -> !x.getLineItem().getHsnCode().equals("NOGST"))
24794 amit.gupta 441
				.collect(Collectors.groupingBy(Order::getInvoiceNumber, Collectors.toList()));
24814 amit.gupta 442
 
25837 amit.gupta 443
		List<List<?>> rows = new ArrayList<>();
24814 amit.gupta 444
		for (String invoice : invoiceOrdersMap.keySet()) {
24794 amit.gupta 445
			Order oneOrder = invoiceOrdersMap.get(invoice).get(0);
446
			int totalOrders = invoiceOrdersMap.get(invoice).size();
447
			LineItem lineItem = oneOrder.getLineItem();
24802 amit.gupta 448
			oneOrder.setBillingTimestamp(LocalDateTime.now());
449
			oneOrder.setInvoiceNumber(getInvoiceNumber(oneOrder));
24819 amit.gupta 450
			rows.add(Arrays.asList(oneOrder.getId(), invoice, oneOrder.getInvoiceNumber(), lineItem.getQuantity()));
24883 amit.gupta 451
			LOGGER.info(invoice + "\t" + oneOrder.getInvoiceNumber() + oneOrder.getId() + "\t",
452
					"\t" + totalOrders + "\t" + lineItem.getQuantity());
24814 amit.gupta 453
			Purchase p = null;
454
			try {
455
				p = purchaseRepository.selectByPurchaseReferenceAndFofoId(invoice, oneOrder.getRetailerId());
456
			} catch (Exception e) {
24815 amit.gupta 457
				LOGGER.info("Could not find purchase for invoice {}", invoice);
24812 amit.gupta 458
			}
24814 amit.gupta 459
			if (p != null) {
460
				List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(p.getId());
461
				for (InventoryItem inventoryItem : inventoryItems) {
24815 amit.gupta 462
					LOGGER.info(inventoryItem.getItemId() + " " + inventoryItem.getGoodQuantity() + " "
24883 amit.gupta 463
							+ inventoryItem.getHsnCode() + " " + inventoryItem.getSerialNumber() + " "
464
							+ p.getPurchaseReference());
24814 amit.gupta 465
				}
466
			}
467
 
24794 amit.gupta 468
		}
24818 amit.gupta 469
		changePartnerInvoices();
24883 amit.gupta 470
		ByteArrayOutputStream baos = FileUtil
471
				.getCSVByteStream(Arrays.asList("Order id", "Challan", "Invoice", "Quantity"), rows);
472
 
24819 amit.gupta 473
		Utils.sendMailWithAttachment(googleMailSender,
474
				new String[] { "amit.gupta@shop2020.in", "sunny.yadav@smartdukaan.com" }, null,
24883 amit.gupta 475
				"Challans Converted to Invoice", "PFA", "Challans-To-Invoice.csv",
476
				new ByteArrayResource(baos.toByteArray()));
24916 amit.gupta 477
		throw new Exception();
24794 amit.gupta 478
	}
24767 amit.gupta 479
 
24802 amit.gupta 480
	private String getInvoiceNumber(Order oneOrder) {
24805 amit.gupta 481
		String prefix = oneOrder.getInvoiceNumber().split("-")[1].replaceAll("\\d*", "");
24803 amit.gupta 482
		System.out.println("Prefix is " + prefix);
24802 amit.gupta 483
		SellerWarehouse sellerWarehouse = sellerWarehouseRepository.selectByPrefix(prefix);
484
		int newSequence = sellerWarehouse.getInvoiceSequence() + 1;
485
		sellerWarehouse.setInvoiceSequence(newSequence);
24814 amit.gupta 486
		return prefix + newSequence;
24802 amit.gupta 487
	}
24814 amit.gupta 488
 
24806 amit.gupta 489
	private void changePartnerInvoices() throws Exception {
24814 amit.gupta 490
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectByInvoiceNumberLike("%SEC%");
491
		for (FofoOrder fofoOrder : fofoOrders) {
24806 amit.gupta 492
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
24814 amit.gupta 493
			if (fofoOrderItem.getBrand().equals("Vivo")) {
24806 amit.gupta 494
				String challanString = fofoOrder.getInvoiceNumber();
24814 amit.gupta 495
				String storeCode = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoOrder.getFofoId())
496
						.getPrefix();
24806 amit.gupta 497
				String invoiceNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), storeCode);
498
				fofoOrder.setInvoiceNumber(invoiceNumber);
499
				fofoOrder.setCreateTimestamp(LocalDateTime.now());
24818 amit.gupta 500
				LOGGER.info(challanString + "\t" + invoiceNumber + "\t" + fofoOrderItem.getQuantity());
24806 amit.gupta 501
			}
24814 amit.gupta 502
 
24806 amit.gupta 503
		}
504
	}
24802 amit.gupta 505
 
25023 amit.gupta 506
	public void populateSchemes() {
25021 amit.gupta 507
		List<Integer> list05 = Arrays.asList(29093, 29094, 29095, 29096, 29097, 29098, 29099, 29101, 29102);
508
		List<Integer> list10 = Arrays.asList(29187, 29188);
509
		List<Integer> list13 = Arrays.asList(28095, 28097, 28098, 28101, 28102, 28104, 28106, 28107, 28108, 28227,
510
				28228, 28229, 28231, 29055, 29056, 29066, 29079);
511
		List<Integer> list15 = Arrays.asList(20891, 27938, 27939, 27940, 27941, 27943, 27947, 27948, 27953, 27954,
512
				27955, 28220, 28467, 29020, 29033, 29034, 29035, 29592, 29886, 29890, 29891, 29941, 29942, 27445, 27958,
513
				27960, 27961);
514
		List<Integer> list18 = Arrays.asList(28137, 28138, 28140, 28157, 28158, 28161, 28162, 28163, 28164, 28176,
515
				28177, 28178, 28199, 28200, 28208, 28209, 28210, 28211, 28215, 28216, 28217, 28230, 28380, 28381, 28382,
516
				28383, 28384, 28385, 28386, 28387, 28388, 28389, 28390, 28391, 28392, 28395, 28461, 28462, 28463, 28464,
517
				28465, 28466, 28488, 28489, 28490, 28491, 28564, 28565, 28762, 28773, 28871, 28872, 28873, 28874, 28880,
518
				28881, 28914, 28915, 28916, 28917, 28918, 28919, 28920, 29046, 29047, 29048, 29068, 29069, 29110, 29111,
519
				29112, 29113, 29114, 29115, 29116, 29117, 29207, 29208, 29217, 29218, 29225, 29474, 29475, 29476, 29477,
520
				29478, 29479, 29483, 29485, 29486, 29487, 29488, 29739, 29740, 29741, 29742, 29743, 29744, 29745, 29746,
521
				29747, 29748, 29749, 29753, 29756, 29757, 29758, 29760, 29761, 29762, 29763, 29764, 29765, 29766, 29767,
522
				29779, 29780, 29781, 29792, 29793, 29828, 29829, 29830, 29879, 29880, 29881, 29882, 29951);
523
		List<Integer> list20 = Arrays.asList(27975, 27976, 28091, 28363, 29023, 29024, 29025);
524
		List<Integer> list25 = Arrays.asList(28763, 28764, 28765, 29152, 29154, 29157, 29209, 29210, 29601, 29602,
525
				29720, 29721, 29722, 29723, 29725, 29726, 29727);
526
		List<Integer> list30 = Arrays.asList(27962, 27963, 27964, 27965, 27966, 27968, 27969, 28328, 28362, 28566,
527
				28567, 28568, 28571, 28572, 29073, 29074, 29075, 29080, 29081, 29120, 29121, 29122, 29124, 29189, 29190,
528
				29191, 29192, 29193, 29194, 29196, 29197, 29198, 29199, 29515, 29516, 29517, 29675, 29676, 29677, 29678,
529
				29679, 29707, 29708, 29794, 29795, 29883, 29884, 29885, 29887, 29888, 29889, 29931, 29932, 29935, 29936,
530
				29937, 29938, 29939, 29940);
531
		List<Integer> list35 = Arrays.asList(27996, 27998, 29067, 29071, 29643, 29644, 29945, 29946, 29987, 29052,
532
				29053, 29078, 29085, 29086, 29567, 29568, 29569, 29570, 29797, 29914, 29915, 29930, 28877, 28878, 29604,
533
				29605, 29606, 29775, 29776, 29777, 29778, 28862, 28863, 28864, 29026, 29103, 29104, 29105, 28979, 28980,
534
				28981, 28982, 28983, 29002, 29003, 29004, 29834, 29835, 29836, 29837, 29943);
535
		List<Integer> list40 = Arrays.asList(29082, 29083, 28766, 28767, 28768, 28769, 28771);
536
		List<Integer> list45 = Arrays.asList(28026, 28027, 28028, 29528, 29529, 29530, 29534, 29535, 29536, 29538,
537
				29755);
538
		List<Integer> list55 = Arrays.asList(28010, 28011, 28015, 28016, 28019, 28240, 28469, 28470, 28471, 28569,
539
				28570, 28674, 28759, 28761, 28909, 28910, 28911, 28912, 28913, 29108, 29109, 29143, 29144, 29145, 29146,
540
				29211, 29212, 29213, 29214, 29482, 29511, 29512, 29521, 29525, 29526, 29527, 29574, 29575, 29576, 29611,
541
				29612, 29616, 29641, 29642, 29728, 29729, 29750, 29771, 29782, 29783, 29784, 29923, 29924, 29944, 29953,
542
				29992, 29994, 27977, 27978, 28092, 28325, 28326, 28327, 28486, 28487, 29148, 29149, 29150, 29151, 29384,
543
				29385, 29386, 29427, 29489, 29518, 29519, 29520, 29577, 29578, 29579, 29580, 29586, 29660, 29661, 29662,
544
				29663, 29769, 29770, 29790, 29791, 29796, 29928, 29929, 29947, 29948, 28093, 28094, 28556, 28557, 28673,
545
				28867, 28868, 28870, 29089, 29090, 29091, 29106, 29107);
546
		List<Integer> list65 = Arrays.asList(28058, 28223, 28224, 28225, 28226, 28329, 29201, 29202, 29203, 29204,
547
				29205, 29206, 29466, 29467, 29468, 29469, 29470, 29471, 29472, 29573);
548
		Map<Float, List<Integer>> m = new HashMap<>();
549
		m.put(0.5f, list05);
550
		m.put(1.0f, list10);
551
		m.put(1.3f, list13);
552
		m.put(1.5f, list15);
553
		m.put(1.8f, list18);
554
		m.put(2.0f, list20);
555
		m.put(2.5f, list25);
556
		m.put(3.0f, list30);
557
		m.put(3.5f, list35);
558
		m.put(4.0f, list40);
559
		m.put(4.5f, list45);
560
		m.put(5.5f, list55);
561
		m.put(6.5f, list65);
562
		for (Map.Entry<Float, List<Integer>> itemsListEntry : m.entrySet()) {
563
			Scheme s1 = getScheme();
564
			s1.setAmount(itemsListEntry.getKey());
565
			schemeRepository.persist(s1);
25034 amit.gupta 566
			for (Integer itemId : itemsListEntry.getValue()) {
25021 amit.gupta 567
				SchemeItem schemeItem = new SchemeItem();
568
				schemeItem.setItemId(itemId);
569
				schemeItem.setSchemeId(s1.getId());
570
				schemeItemRepository.persist(schemeItem);
571
			}
572
		}
25034 amit.gupta 573
 
25021 amit.gupta 574
	}
575
 
576
	private Scheme getScheme() {
577
		Scheme s = new Scheme();
578
		s.setName("List Price Margin");
579
		s.setDescription("List Price Margin");
580
		s.setActiveTimestamp(null);
581
		s.setStartDateTime(LocalDate.of(2019, 6, 1).atStartOfDay());
582
		s.setEndDateTime(LocalDate.of(2019, 7, 1).atStartOfDay());
583
		s.setAmountType(AmountType.PERCENTAGE);
584
		s.setCreateTimestamp(LocalDateTime.now());
585
		s.setExpireTimestamp(null);
586
		s.setCreatedBy(175120474);
587
		return s;
588
	}
589
 
24957 amit.gupta 590
	public void findMismatchesInIndent() throws Exception {
591
		List<Order> allInProcessOrders = orderRepository.selectAllOrder(OrderStatus.SUBMITTED_FOR_PROCESSING);
24967 amit.gupta 592
 
25021 amit.gupta 593
		Map<String, Integer> lineItemWhQtyMap = allInProcessOrders.stream()
25734 amit.gupta 594
				.collect(Collectors.groupingBy(y -> y.getLineItem().getItemId() + "-" + y.getFulfilmentWarehouseId(),
24967 amit.gupta 595
						Collectors.summingInt(y -> y.getLineItem().getQuantity())));
25021 amit.gupta 596
 
597
		lineItemWhQtyMap.forEach((key, value) -> {
598
 
24967 amit.gupta 599
			int itemId = Integer.parseInt(key.split("-")[0]);
600
			int warehouseId = Integer.parseInt(key.split("-")[1]);
25021 amit.gupta 601
			System.out.printf("%d\t%d\t%d\n", itemId, warehouseId, value);
602
			SaholicInventorySnapshot cis = saholicInventorySnapshotRepository.selectByWarehouseIdandItemId(warehouseId,
603
					itemId);
604
			if (cis == null) {
24970 amit.gupta 605
				cis = new SaholicInventorySnapshot();
606
				cis.setItemId(itemId);
607
				cis.setWarehouseId(warehouseId);
608
				cis.setAvailability(0);
609
				saholicInventorySnapshotRepository.persist(cis);
610
			}
24967 amit.gupta 611
			cis.setReserved(value);
612
		});
24953 amit.gupta 613
	}
614
 
25034 amit.gupta 615
	public void fixSchemePayouts() throws Exception {
25524 amit.gupta 616
		LOGGER.info("In fix scheme Payouts");
25522 amit.gupta 617
		LocalDateTime startDate = LocalDate.of(2019, 9, 1).atStartOfDay();
618
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(startDate, LocalDateTime.now());
25530 amit.gupta 619
 
25034 amit.gupta 620
		for (SchemeInOut sio : sios) {
25530 amit.gupta 621
			if (sio.getSchemeId() != 347) {
25523 amit.gupta 622
				LOGGER.info("Skipping {}", sio.getSchemeId());
25522 amit.gupta 623
				continue;
624
			}
25043 amit.gupta 625
			genericRepository.delete(sio);
25522 amit.gupta 626
			InventoryItem ii = inventoryItemRepository.selectById(sio.getInventoryItemId());
627
			UserWallet userWallet = userWalletRepository.selectByRetailerId(ii.getFofoId());
628
			Scheme scheme = schemeRepository.selectById(sio.getSchemeId());
629
			if (scheme.getType().equals(SchemeType.IN)) {
630
				List<UserWalletHistory> historyList = userWalletHistoryRepository
631
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_IN);
632
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 633
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 634
						genericRepository.delete(uwh);
635
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
636
					}
637
				}
638
			} else {
639
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
640
				int orderId = scanRecords.get(0).getOrderId();
641
				List<UserWalletHistory> historyList = userWalletHistoryRepository
642
						.selectAllByreferenceIdandreferenceType(orderId, WalletReferenceType.SCHEME_OUT);
643
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 644
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 645
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
646
						genericRepository.delete(uwh);
647
					}
648
				}
649
				List<UserWalletHistory> historyListBroken = userWalletHistoryRepository
25530 amit.gupta 650
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_OUT);
25522 amit.gupta 651
				for (UserWalletHistory uwh : historyListBroken) {
25530 amit.gupta 652
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 653
						genericRepository.delete(uwh);
654
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
655
					}
656
				}
657
			}
658
 
25530 amit.gupta 659
			// System.out.println("Total Amount Rolled Back is " + totalRollbackAmount);
25516 amit.gupta 660
		}
25589 amit.gupta 661
		scheduledTasks.processScheme(startDate, startDate.plusDays(10), true);
25030 amit.gupta 662
	}
25530 amit.gupta 663
 
664
	public void fixWallet() throws Exception {
665
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
25536 amit.gupta 666
		System.out.println("id\tcode\tactive\tname\tcity\tstate\twallet amount\tsum\twallet amount-sum");
25530 amit.gupta 667
		for (FofoStore fofoStore : fofoStores) {
668
			UserWallet uw = userWalletRepository.selectByRetailerId(fofoStore.getId());
669
			User user = userRepository.selectById(fofoStore.getId());
25749 amit.gupta 670
			if (user == null) {
25533 amit.gupta 671
				LOGGER.info("store does not exist", fofoStore.getCode());
25535 amit.gupta 672
				continue;
25533 amit.gupta 673
			}
25536 amit.gupta 674
			Address address = null;
675
			try {
676
				address = addressRepository.selectById(user.getAddressId());
25749 amit.gupta 677
			} catch (Exception e) {
25536 amit.gupta 678
				LOGGER.info("Could not find address for Store", fofoStore.getCode());
679
				address = new Address();
680
			}
25539 amit.gupta 681
			double sum = userWalletHistoryRepository.selectSumByWallet(uw.getId());
25749 amit.gupta 682
			int calculated = (int) sum;
683
			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(),
684
					fofoStore.isActive(), address.getName(), address.getCity(), address.getState(), uw.getAmount(),
685
					calculated, uw.getAmount() - calculated);
25530 amit.gupta 686
		}
687
	}
25749 amit.gupta 688
 
25734 amit.gupta 689
	public void changeWarehouse() throws Exception {
690
		transactionService.moveWarehouses();
691
	}
25749 amit.gupta 692
 
693
	public void mailDashboardScreenshots() throws Exception {
694
		System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
695
 
25752 amit.gupta 696
		ChromeOptions options = new ChromeOptions();
697
		options.addArguments("--headless");
698
		options.addArguments("--no-sandbox");
699
		options.addArguments("start-maximized");
700
		options.addArguments("disable-infobars");
701
		options.addArguments("--disable-extensions");
702
 
25753 amit.gupta 703
		WebDriver driver = new ChromeDriver(options);
25774 amit.gupta 704
		driver.manage().window().setSize(new Dimension(1600, 900));
25749 amit.gupta 705
		driver.manage().window().maximize();
25752 amit.gupta 706
		// Deleting all the cookies
25749 amit.gupta 707
		driver.manage().deleteAllCookies();
25752 amit.gupta 708
		// Specifiying pageLoadTimeout and Implicit wait
25749 amit.gupta 709
		driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
710
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
25752 amit.gupta 711
 
25749 amit.gupta 712
		Map<String, Set<Integer>> authUserPartnerIdMapping = csService.getAuthUserPartnerIdMapping();
713
		Set<Integer> allPartners = new HashSet<>();
25765 amit.gupta 714
		Map<Integer, File> partnerSnapshotMap = new HashMap<>();
25752 amit.gupta 715
		authUserPartnerIdMapping.values().stream().forEach(x -> allPartners.addAll(x));
25749 amit.gupta 716
		System.out.println(allPartners.size());
25752 amit.gupta 717
		for (int fofoId : allPartners) {
25749 amit.gupta 718
			driver.get("https://partners.smartdukaan.com/12dashboard34?fofoId=" + fofoId);
25765 amit.gupta 719
			File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
720
			partnerSnapshotMap.put(fofoId, file);
25752 amit.gupta 721
 
25749 amit.gupta 722
		}
25752 amit.gupta 723
		for (Map.Entry<String, Set<Integer>> entry : authUserPartnerIdMapping.entrySet()) {
25749 amit.gupta 724
			String email = entry.getKey();
25996 amit.gupta 725
			LOGGER.info("Sending mail start to {}", email);
25749 amit.gupta 726
			Set<Integer> partnerIds = entry.getValue();
727
			StringBuffer body = new StringBuffer();
25769 amit.gupta 728
			Map<Integer, File> emailSnapshotMap = new HashMap<>();
25752 amit.gupta 729
			for (int fofoId : partnerIds) {
25769 amit.gupta 730
				body.append(String.format("<br/><img src=\"cid:%d\"/>", fofoId));
731
				emailSnapshotMap.put(fofoId, partnerSnapshotMap.get(fofoId));
25749 amit.gupta 732
			}
25837 amit.gupta 733
			Utils.sendEmbeddedHtmlMail(mailSender, new String[] { email }, new String[] {},
25752 amit.gupta 734
					String.format("Franchise Screenshots - %s", FormattingUtils.formatDate(LocalDateTime.now())),
25837 amit.gupta 735
					body.toString(), emailSnapshotMap);
25996 amit.gupta 736
			LOGGER.info("Sent mail to {}", email);
25749 amit.gupta 737
		}
738
		driver.quit();
739
	}
26033 amit.gupta 740
 
26299 amit.gupta 741
	// Rollout prebooking orders amount in case the order is grned.
26033 amit.gupta 742
	public void pbfix() throws ProfitMandiBusinessException {
743
		List<Item> items = itemRepository.selectAllByCatalogItemId(1022304);
26299 amit.gupta 744
		for (Item item : items) {
26033 amit.gupta 745
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByItemId(item.getId(), 0, 500);
26299 amit.gupta 746
			for (InventoryItem inventoryItem : inventoryItems) {
26033 amit.gupta 747
				List<PrebookingOrder> prebookingOrders = prebookingOrderRepository
26299 amit.gupta 748
						.selectByFofoIdAndCatalogIds(inventoryItem.getFofoId(), item.getCatalogItemId()).stream()
749
						.collect(Collectors.toList());
750
				if (prebookingOrders.size() > 0) {
751
					purchaseService.sendPrebookingNotifyMessage(prebookingOrders.get(0));
26033 amit.gupta 752
				}
26299 amit.gupta 753
				// inventoryItem.getFofoId()
26033 amit.gupta 754
			}
755
		}
26299 amit.gupta 756
		// throw new ProfitMandiBusinessException("", "", "");
757
		// prebookingOrderRepository.select
26033 amit.gupta 758
		// TODO Auto-generated method stub
26299 amit.gupta 759
 
26033 amit.gupta 760
	}
26092 amit.gupta 761
 
26299 amit.gupta 762
	public void fixGrn() throws Exception {
26092 amit.gupta 763
		List<Purchase> incompletePurchases = purchaseRepository.selectIncompletePurchase();
26299 amit.gupta 764
		for (Purchase incompletePurchase : incompletePurchases) {
765
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(
766
					incompletePurchase.getPurchaseReference(), incompletePurchase.getFofoId());
26093 amit.gupta 767
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(incompletePurchase.getId());
768
			Map<Integer, Integer> grnedItems = inventoryItems.stream().collect(
26299 amit.gupta 769
					Collectors.groupingBy(x -> x.getItemId(), Collectors.summingInt(x -> x.getInitialQuantity())));
770
			Map<Integer, Integer> billedItems = orders.stream().collect(Collectors.groupingBy(
771
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
772
			for (Integer billedItemId : billedItems.keySet()) {
773
				if (grnedItems.containsKey(billedItemId)) {
774
					if (grnedItems.get(billedItemId) > billedItems.get(billedItemId)) {
775
						LOGGER.info("Billed Qty {} ---- Grned {}, ItemId {}, Invoice Number {}({}), Grn Date {}",
776
								billedItems.get(billedItemId), grnedItems.get(billedItemId), billedItemId,
777
								incompletePurchase.getPurchaseReference(), incompletePurchase.getId(),
778
								incompletePurchase.getCreateTimestamp());
26095 amit.gupta 779
						Item item = itemRepository.selectById(billedItemId);
26299 amit.gupta 780
						if (item.getType().equals(ItemType.SERIALIZED)) {
781
 
26096 amit.gupta 782
						} else {
26299 amit.gupta 783
							for (InventoryItem inventoryItem : inventoryItems) {
784
								if (inventoryItem.getItemId() == billedItemId && inventoryItem.getGoodQuantity() == 0) {
785
									List<ScanRecord> scanRecords = scanRecordRepository
786
											.selectByInventoryItemId(inventoryItem.getId());
787
									if (scanRecords.size() == 1 && scanRecords.get(0).getQuantity() == 0) {
26096 amit.gupta 788
										LOGGER.info("Safe to remove InventoryItem Id {}", inventoryItem.getId());
26101 amit.gupta 789
										scanRecordRepository.delete(scanRecords.get(0));
790
										inventoryItemRepository.delete(inventoryItem);
26299 amit.gupta 791
										incompletePurchase.setUnfullfilledNonSerializedQuantity(
792
												incompletePurchase.getUnfullfilledNonSerializedQuantity()
793
														+ inventoryItem.getInitialQuantity());
26096 amit.gupta 794
									}
795
								}
796
							}
26095 amit.gupta 797
						}
26093 amit.gupta 798
					}
799
				}
26092 amit.gupta 800
			}
26299 amit.gupta 801
 
26092 amit.gupta 802
		}
26299 amit.gupta 803
 
26092 amit.gupta 804
	}
26265 amit.gupta 805
 
806
	public void fixDupGrns() throws Exception {
26412 amit.gupta 807
		List<Integer> duplicatePurchaseIds = Arrays.asList(14984);
26299 amit.gupta 808
		for (int duplicatePurchaseId : duplicatePurchaseIds) {
26265 amit.gupta 809
			Purchase purchase = purchaseRepository.selectById(duplicatePurchaseId);
810
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(duplicatePurchaseId);
26299 amit.gupta 811
			if (inventoryItems.size() == 0) {
26266 amit.gupta 812
				LOGGER.info("Could not find InventoryItems for {}", duplicatePurchaseId);
813
				continue;
814
			}
26299 amit.gupta 815
			schemeService.rollbackSchemes(inventoryItems.stream().map(x -> x.getId()).collect(Collectors.toList()),
816
					duplicatePurchaseId,
817
					"Rolled back duplicate grn for Purchase Invoice " + purchase.getPurchaseReference());
818
			for (InventoryItem inventoryItem : inventoryItems) {
26265 amit.gupta 819
				inventoryItemRepository.delete(inventoryItem);
820
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId());
26299 amit.gupta 821
				for (ScanRecord scanRecord : scanRecords) {
26265 amit.gupta 822
					scanRecordRepository.delete(scanRecord);
823
				}
26299 amit.gupta 824
				List<SchemeInOut> sios = schemeInOutRepository
825
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
826
				for (SchemeInOut sio : sios) {
26265 amit.gupta 827
					LOGGER.info("SIO - {}", sio);
828
					schemeInOutRepository.delete(sio);
829
				}
26299 amit.gupta 830
 
26265 amit.gupta 831
			}
832
		}
26299 amit.gupta 833
		// throw new Exception();
26265 amit.gupta 834
	}
26579 amit.gupta 835
 
836
	public void mongom() {
837
		List<TagListing> tls = tagListingRepository.selectAll(false);
838
		Set<Integer> itemIds = tls.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
839
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId())
840
				.collect(Collectors.toSet());
841
		for (int catalogId : catalogIds) {
842
			try {
843
				ContentPojo cp = mongoClient.getEntityById(catalogId);
26580 amit.gupta 844
				try {
845
					cp.setIconImageUrl(cp.getIconImageUrl().replace("saholic", "smartdukaan"));
26759 amit.gupta 846
				} catch (Exception e) {
847
 
26580 amit.gupta 848
				}
26759 amit.gupta 849
 
26580 amit.gupta 850
				try {
851
					cp.setThumbnailImageUrl(cp.getThumbnailImageUrl().replace("saholic", "smartdukaan"));
26759 amit.gupta 852
				} catch (Exception e) {
853
 
26580 amit.gupta 854
				}
26759 amit.gupta 855
 
26579 amit.gupta 856
				cp.setDefaultImageUrl(cp.getDefaultImageUrl().replace("saholic", "smartdukaan"));
857
				List<MediaPojo> mPojos = cp.getImages();
26759 amit.gupta 858
				if (mPojos != null) {
26580 amit.gupta 859
					mPojos.stream().forEach(mPojo -> {
860
						mPojo.setUrl(mPojo.getUrl().replace("saholic", "smartdukaan"));
861
					});
862
				}
26579 amit.gupta 863
				mongoClient.persistEntity(cp);
864
			} catch (Exception e) {
865
				continue;
866
			}
867
		}
868
	}
26759 amit.gupta 869
 
870
	public void cancelDn(String debitNoteNumber) throws Exception {
871
		DebitNote debitNote = debitNoteRepository.selectDebitNoteByNumber(debitNoteNumber);
26928 amit.gupta 872
 
873
		List<PurchaseReturnItem> purchaseReturnItems = purchaseReturnItemRepository
874
				.selectAllByDebitNoteId(debitNote.getId());
26759 amit.gupta 875
		// Select all inventory Item
876
		Set<Integer> inventoryItemIds = purchaseReturnItems.stream().map(x -> x.getInventoryItemId())
877
				.collect(Collectors.toSet());
878
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds);
879
		for (InventoryItem inventoryItem : inventoryItems) {
880
			if (!StringUtils.isEmpty(inventoryItem.getSerialNumber())) {
881
				inventoryItem.setGoodQuantity(1);
882
				inventoryItem.setLastScanType(ScanType.PURCHASE);
883
				ScanRecord sr = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId()).stream()
884
						.filter(x -> x.getType().equals(ScanType.PURCHASE_RET)).findFirst().get();
885
				scanRecordRepository.delete(sr);
886
				CurrentInventorySnapshot cis = currentInventorySnapshotRepository
887
						.selectByItemAndFofoId(inventoryItem.getItemId(), inventoryItem.getFofoId());
888
				if (cis == null) {
889
					cis = new CurrentInventorySnapshot();
890
					cis.setFofoId(inventoryItem.getFofoId());
891
					cis.setItemId(inventoryItem.getId());
892
					currentInventorySnapshotRepository.persist(cis);
893
				}
894
				cis.setAvailability(cis.getAvailability() + 1);
895
				schemeService.processSchemeIn(inventoryItem.getPurchaseId(), inventoryItem.getFofoId());
896
			}
26928 amit.gupta 897
		}
898
		purchaseReturnItems.stream().forEach(x -> purchaseReturnItemRepository.delete(x));
26759 amit.gupta 899
	}
26799 amit.gupta 900
 
901
	public void processPd(int priceDropId) throws ProfitMandiBusinessException {
27079 amit.gupta 902
		priceDropService.processPriceDrop(priceDropId, false);
26799 amit.gupta 903
	}
26928 amit.gupta 904
 
905
	public void fixScheme() throws Exception {
26936 amit.gupta 906
		LOGGER.info("Partner Types found\tPartnerType To Remove\tAmout to Rollback");
26928 amit.gupta 907
		final Map<Integer, Scheme> schemesMap = schemeRepository.selectAll().stream()
908
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
909
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(LocalDate.of(2019, 9, 1).atTime(0, 0),
910
				LocalDateTime.now());
27221 amit.gupta 911
		Map<SioTuple, Map<PartnerType, List<SchemeInOut>>> schemeTupleMap = sios.stream()
912
				.filter(x -> x.getRolledBackTimestamp() == null)
26928 amit.gupta 913
				.filter(x -> schemesMap.get(x.getSchemeId()).getPartnerType() != PartnerType.ALL)
914
				.collect(Collectors.groupingBy(
915
						x -> new SioTuple(x.getInventoryItemId(), schemesMap.get(x.getSchemeId()).getType()),
27221 amit.gupta 916
						Collectors.groupingBy(x -> schemesMap.get(x.getSchemeId()).getPartnerType(),
917
								Collectors.mapping(x -> x, Collectors.toList()))));
918
 
919
		schemeTupleMap.entrySet().stream().filter(x -> x.getValue().size() > 1).forEach(x -> {
26929 amit.gupta 920
			Map<PartnerType, List<SchemeInOut>> partnerTypeSchemeMap = x.getValue();
27221 amit.gupta 921
			PartnerType partnerTypeToRemove = partnerTypeSchemeMap.keySet().stream()
922
					.min(Comparator.comparing(y -> PartnerType.PartnerTypeRankMap.get(y))).get();
923
			LOGGER.info("{}\t{}\t{}\t{}\t{}\t{}", partnerTypeSchemeMap.keySet(), partnerTypeToRemove,
924
					partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
925
							.collect(Collectors.summingDouble(SchemeInOut::getAmount)),
926
					FormattingUtils.formatDate(partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
927
							.map(y -> y.getCreateTimestamp()).findFirst().get()));
928
 
26928 amit.gupta 929
		});
930
	}
931
 
932
	private class SioTuple {
933
		int inventoryId;
934
		SchemeType schemeType;
935
 
936
		public SioTuple(int inventoryItemId, SchemeType schemeType) {
937
			this.inventoryId = inventoryItemId;
938
			this.schemeType = schemeType;
939
		}
940
 
941
		public int getInventoryId() {
942
			return inventoryId;
943
		}
944
 
945
		public void setInventoryId(int inventoryId) {
946
			this.inventoryId = inventoryId;
947
		}
948
 
949
		public SchemeType getSchemeType() {
950
			return schemeType;
951
		}
952
 
953
		public void setSchemeType(SchemeType schemeType) {
954
			this.schemeType = schemeType;
955
		}
956
 
957
		@Override
958
		public int hashCode() {
959
			final int prime = 31;
960
			int result = 1;
961
			result = prime * result + getOuterType().hashCode();
962
			result = prime * result + inventoryId;
963
			result = prime * result + ((schemeType == null) ? 0 : schemeType.hashCode());
964
			return result;
965
		}
966
 
967
		@Override
968
		public boolean equals(Object obj) {
969
			if (this == obj)
970
				return true;
971
			if (obj == null)
972
				return false;
973
			if (getClass() != obj.getClass())
974
				return false;
975
			SioTuple other = (SioTuple) obj;
976
			if (!getOuterType().equals(other.getOuterType()))
977
				return false;
978
			if (inventoryId != other.inventoryId)
979
				return false;
980
			if (schemeType != other.schemeType)
981
				return false;
982
			return true;
983
		}
984
 
985
		private RunOnceTasks getOuterType() {
986
			return RunOnceTasks.this;
987
		}
988
 
989
	}
27221 amit.gupta 990
 
991
	public void printPendingLeads() {
27277 amit.gupta 992
		LOGGER.info("PENDING LEADES {}", leadRepository
993
				.selectLeadsScheduledBetweenDate(LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4)));
27221 amit.gupta 994
	}
27277 amit.gupta 995
 
27286 amit.gupta 996
	public void removeDuplicateOrders() throws Exception {
27451 tejbeer 997
		List<String> invoiceNumbers = Arrays.asList(/*
998
													 * "DLWE066/1108", "DLWE066/299", "DLWE066/348", "HRFB004/242",
999
													 * "HRFB004/243", "HRFB004/514", "HRFTB155/29", "HRJND076/1146",
1000
													 * "HRJND076/966", "HRKA134/295", "HRKA134/421", "HRKK091/381",
1001
													 * "HRMGH106/576", "HRSP056/139", "HRYN030/103", "UPGZ019/395",
1002
													 * "UPHRD130/1299", "UPHRD130/456", "UPHRD130/634", "UPLKO063/897",
1003
													 * "UPMRT149/54", "UPSJP119/748", "UPSJP119/980", "UPSTP065/1218",
1004
													 * "UPSTP065/2039", "UPSTP090/437", "UPSTP120/164",
1005
													 */
27312 amit.gupta 1006
				"HRMGH106/1576");
27451 tejbeer 1007
 
27288 amit.gupta 1008
		int totalAmount = 0;
1009
		float saleAmount = 0;
27289 amit.gupta 1010
		float schemeReverseAmount = 0;
27451 tejbeer 1011
		for (String invoiceNumber : invoiceNumbers) {
27281 amit.gupta 1012
			List<FofoOrder> orders = fofoOrderRepository.selectByInvoiceNumberLike(invoiceNumber);
27283 amit.gupta 1013
			orders = orders.stream().skip(1).collect(Collectors.toList());
27286 amit.gupta 1014
			for (FofoOrder fofoOrder : orders) {
27295 amit.gupta 1015
				LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
27286 amit.gupta 1016
				int inventoryItemId = 0;
27288 amit.gupta 1017
				saleAmount += fofoOrder.getTotalAmount();
27297 amit.gupta 1018
				fofoOrderRepository.delete(fofoOrder);
27302 amit.gupta 1019
				LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
27286 amit.gupta 1020
				List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
27451 tejbeer 1021
				List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
1022
						.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
1023
				for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
27297 amit.gupta 1024
					paymentOptionTransactionRepository.delete(paymentOptionTransaction);
27286 amit.gupta 1025
				}
27451 tejbeer 1026
				for (FofoOrderItem foi : fofoOrderItems) {
27302 amit.gupta 1027
					List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
27297 amit.gupta 1028
					fofoOrderItemRepository.delete(foi);
27451 tejbeer 1029
					for (FofoLineItem fli : flis) {
27302 amit.gupta 1030
						inventoryItemId = fli.getInventoryItemId();
27297 amit.gupta 1031
						fofoLineItemRepository.delete(fli);
27286 amit.gupta 1032
					}
1033
				}
27451 tejbeer 1034
				// Rollback entry with reversal reason
1035
				if (fofoOrder.getCreateTimestamp().isAfter(LocalDate.of(2020, 4, 1).atStartOfDay())) {
27293 amit.gupta 1036
					float invoiceSchemeReversalAmount = 0;
27451 tejbeer 1037
					List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository
1038
							.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
1039
					float invoiceWalletAmount = userWalletHistory.stream()
1040
							.collect(Collectors.summingInt(y -> y.getAmount()));
27303 amit.gupta 1041
					totalAmount += invoiceWalletAmount;
27299 amit.gupta 1042
					try {
27451 tejbeer 1043
						walletService.rollbackAmountFromWallet(fofoOrder.getFofoId(), invoiceWalletAmount,
1044
								fofoOrder.getId(), WalletReferenceType.SCHEME_OUT,
1045
								"Same order for Invoice-" + invoiceNumber + "created twice, duplicate invoice rollback",
1046
								fofoOrder.getCancelledTimestamp());
27299 amit.gupta 1047
					} catch (Exception e) {
1048
						LOGGER.info("Failed wallet update Reson [{}]", e.getMessage());
1049
					}
27301 amit.gupta 1050
					LOGGER.info("inventoryItemId - {}", inventoryItemId);
27451 tejbeer 1051
					List<SchemeInOut> schemeInOuts = schemeInOutRepository
1052
							.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId)));
27292 amit.gupta 1053
					Set<Integer> schemeIds = new HashSet<>();
27298 amit.gupta 1054
					Set<Integer> schemeIdsRolledback = new HashSet<>();
27451 tejbeer 1055
					for (SchemeInOut sio : schemeInOuts) {
1056
						if (Math.abs(sio.getCreateTimestamp().until(fofoOrder.getCreateTimestamp(),
1057
								ChronoUnit.MINUTES)) <= 35 && sio.getRolledBackTimestamp() == null) {
27289 amit.gupta 1058
							LOGGER.info(sio);
27451 tejbeer 1059
							if (!schemeIds.contains(sio.getSchemeId())) {
27292 amit.gupta 1060
								schemeIds.add(sio.getSchemeId());
27298 amit.gupta 1061
							} else if (!schemeIdsRolledback.contains(sio.getSchemeId())) {
1062
								schemeIdsRolledback.add(sio.getSchemeId());
27297 amit.gupta 1063
								sio.setRolledBackTimestamp(LocalDateTime.now());
27292 amit.gupta 1064
								schemeReverseAmount += sio.getAmount();
27293 amit.gupta 1065
								invoiceSchemeReversalAmount += sio.getAmount();
27292 amit.gupta 1066
							}
27289 amit.gupta 1067
						}
27286 amit.gupta 1068
					}
27451 tejbeer 1069
					if (Math.abs(invoiceWalletAmount - invoiceSchemeReversalAmount) > 3) {
27303 amit.gupta 1070
						LOGGER.info("No Matchhhh");
1071
					}
27451 tejbeer 1072
					LOGGER.info("invoiceWalletAmount - {}, invoiceSchemeReversalAmount {}", invoiceWalletAmount,
1073
							invoiceSchemeReversalAmount);
1074
				}
27283 amit.gupta 1075
			}
27277 amit.gupta 1076
		}
27451 tejbeer 1077
		LOGGER.info(
1078
				"Total Sale Amount Reversal - {}, Total Wallet Amount Reversal {}, Total Scheme Reversal Amount - {}",
1079
				saleAmount, totalAmount, schemeReverseAmount);
1080
		// throw new Exception();
27277 amit.gupta 1081
	}
27430 amit.gupta 1082
 
27450 tejbeer 1083
	public void createGeofence() throws IOException, ProfitMandiBusinessException {
1084
 
27486 tejbeer 1085
		// List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
1086
		// for (FofoStore fofoStore : fofoStores) {
1087
		// if (fofoStore.getLatitude() != null && fofoStore.getLongitude() != null) {
27503 tejbeer 1088
		CustomRetailer customRetailer = retailerService.getFofoRetailer(175138812);
27486 tejbeer 1089
		OkHttpClient client = new OkHttpClient();
1090
		okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
1091
		JSONObject geofe = new JSONObject();
1092
		JSONArray geofences = new JSONArray();
1093
		JSONObject geometry = new JSONObject();
1094
		JSONObject geo = new JSONObject();
1095
		JSONArray coordinates = new JSONArray();
1096
		ArrayList<Double> crds = new ArrayList<>();
1097
		// crds.add(Double.parseDouble(fofoStore.getLongitude()));
1098
		// crds.add(Double.parseDouble(fofoStore.getLatitude()));
27503 tejbeer 1099
		crds.add(79.739197);
1100
		crds.add(27.961215);
27486 tejbeer 1101
		// crds.add(77.08596155373755);
1102
		// crds.add(28.64944201113976);
1103
		// coordinates.put(fofoStore.getLongitude());
1104
		// coordinates.put(fofoStore.getLatitude());
1105
		geo.put("type", "Point");
1106
		geo.put("coordinates", crds);
1107
		geometry.put("geometry", geo);
1108
		JSONObject metadata = new JSONObject();
27503 tejbeer 1109
		metadata.put("name", customRetailer.getBusinessName());
1110
		metadata.put("city", customRetailer.getAddress().getCity());
1111
		metadata.put("Code", customRetailer.getCode());
27487 tejbeer 1112
		geometry.put("metadata", metadata);
27486 tejbeer 1113
		geometry.put("radius", 200);
27451 tejbeer 1114
 
27486 tejbeer 1115
		geofences.put(geometry);
1116
		geofe.put("geofences", geofences);
1117
		okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
1118
		String authString = "Basic "
1119
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27450 tejbeer 1120
 
27486 tejbeer 1121
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
1122
				.addHeader("Authorization", authString).build();
27450 tejbeer 1123
 
27486 tejbeer 1124
		Response response = client.newCall(request1).execute();
27450 tejbeer 1125
 
27486 tejbeer 1126
		JSONArray ja = new JSONArray(response.body().string());
1127
		LOGGER.info("geofence" + ja);
1128
		LOGGER.info("jalength" + ja.length());
1129
		/*
1130
		 * for (int i = 0; i < ja.length(); i++) { JSONObject c = ja.getJSONObject(i);
1131
		 * String geofenceId = c.getString("geofence_id"); LOGGER.info("geofenceId" +
1132
		 * geofenceId); FofoStoreGeofence fsg = new FofoStoreGeofence();
1133
		 * fsg.setFofoId(customRetailer.getPartnerId()); fsg.setGeofenceId(geofenceId);
1134
		 * fofoStoreGeofenceRepository.persist(fsg); }
1135
		 * 
1136
		 * }
1137
		 * 
1138
		 * }
1139
		 */
27482 tejbeer 1140
 
27462 tejbeer 1141
	}
1142
 
27451 tejbeer 1143
	public void getAllGeofences() throws IOException, ProfitMandiBusinessException {
27450 tejbeer 1144
 
1145
		OkHttpClient client = new OkHttpClient();
1146
 
1147
		String authString = "Basic "
1148
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
1149
 
1150
		// Get geofences created for all app users
1151
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences")
1152
				.addHeader("Authorization", authString).build();
1153
 
1154
		Response response = client.newCall(request1).execute();
27451 tejbeer 1155
 
27450 tejbeer 1156
		LOGGER.info("response" + response.body().string());
1157
	}
1158
 
27457 tejbeer 1159
	public void deleteGeofences(List<String> geofenceIds) throws IOException, ProfitMandiBusinessException {
1160
		OkHttpClient client = new OkHttpClient();
1161
 
1162
		String authString = "Basic "
1163
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
1164
 
1165
		for (String geofenceId : geofenceIds) {
27460 tejbeer 1166
			Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences/" + geofenceId)
27457 tejbeer 1167
					.delete().addHeader("Authorization", authString).build();
1168
			LOGGER.info("geofenceId" + geofenceId);
1169
			Response response = client.newCall(request1).execute();
1170
 
27460 tejbeer 1171
			LOGGER.info("response" + response.body().string());
27457 tejbeer 1172
		}
1173
 
1174
	}
1175
 
27430 amit.gupta 1176
	public void processSchemeOut(int fofoId, int orderId) throws Exception {
1177
		schemeService.processSchemeOut(orderId, fofoId);
27451 tejbeer 1178
 
27430 amit.gupta 1179
	}
27511 amit.gupta 1180
 
1181
	public void createDummyInvoices() {
27787 amit.gupta 1182
		List<WarehouseInventoryItem> lavaInventoryItems = warehouseInventoryItemRepository.getSerialNumbers("Lava",
1183
				LocalDate.of(2020, Month.SEPTEMBER, 1).atStartOfDay(), LocalDateTime.now());
27511 amit.gupta 1184
		LOGGER.info("Lava Inventory Size is {}", lavaInventoryItems.size());
1185
	}
27948 amit.gupta 1186
 
1187
	public void createOffers(int offerId) throws Exception {
28042 amit.gupta 1188
		Map<List<Integer>, List<Integer>> targetMap = new HashMap<>();
28043 amit.gupta 1189
		targetMap.put(Arrays.asList(175138842,175138838,175138893,175127215,175138883,175135923,172157716,175138910,175138909,175138867,175138717,175138823,175138847,175138887,175138843,175138816,175135227,175138878,175138840,175138901,175138839,175138897,175138801,175138873,175138799,175138855,175138825,175138913,175138851,175138914,175138733,175138821,175138882,175138876,175138834,175138934,175138866,175138174,175138845,175136389,175138833,175138522,175138920,175138903,175138716,175138859,175138906,175138520,175136207,175138844,175138804,175138902,175138800,156232687,175138908,175135707,175138541,175138892,175138854,175138853,175138877,175138857,175138895,175138916,175138674,175138868,175138888,175138856,175138863,175138936,175138922,175138918,175138939,4149607,175138813,175138832,175138835,175138900,175138911,175138917,175138923,175138926,175138940,175138941,175138942,175138949), Arrays.asList(22000,26000,29000));
1190
		targetMap.put(Arrays.asList(175138820,175138889,175138824), Arrays.asList(24300,28700,32000));
1191
		targetMap.put(Arrays.asList(175138875), Arrays.asList(24800,29300,32700));
1192
		targetMap.put(Arrays.asList(175138907), Arrays.asList(25900,30600,34100));
1193
		targetMap.put(Arrays.asList(175138871), Arrays.asList(26000,30700,34200));
1194
		targetMap.put(Arrays.asList(175138805),Arrays.asList(26800,31600,35300));
1195
		targetMap.put(Arrays.asList(175138829),Arrays.asList(28600,33800,37700));
1196
		targetMap.put(Arrays.asList(175138870),Arrays.asList(29300,34600,38600));
1197
		targetMap.put(Arrays.asList(175138896,175135376), Arrays.asList(31900,37700,42100));
1198
		targetMap.put(Arrays.asList(175138874), Arrays.asList(34200,40500,45100));
1199
		targetMap.put(Arrays.asList(175138812),Arrays.asList(35400,41800,46600));
1200
		targetMap.put(Arrays.asList(175138827), Arrays.asList(35900,42400,47300));
1201
		targetMap.put(Arrays.asList(175138864),Arrays.asList(36400,43000,48000));
1202
		targetMap.put(Arrays.asList(157112773),Arrays.asList(36900,43600,48600));
1203
		targetMap.put(Arrays.asList(175138862),Arrays.asList(42900,50700,56600));
1204
		targetMap.put(Arrays.asList(175138879),Arrays.asList(50700,59900,66800));
1205
		targetMap.put(Arrays.asList(175138886),Arrays.asList(62300,73600,82000));
1206
		targetMap.put(Arrays.asList(175138836),Arrays.asList(67500,79700,88900));
1207
		targetMap.put(Arrays.asList(175138885),Arrays.asList(69400,82000,91400));
1208
		targetMap.put(Arrays.asList(175138408),Arrays.asList(70500,83400,93000));
1209
		targetMap.put(Arrays.asList(175138858),Arrays.asList(130400,154100,171900));
1210
		targetMap.put(Arrays.asList(175138372),Arrays.asList(237800,281000,313400));
28042 amit.gupta 1211
 
27948 amit.gupta 1212
 
1213
		CreateOfferRequest createOfferRequest = offerService.getOffer(offerId);
28042 amit.gupta 1214
		for(Map.Entry<List<Integer>, List<Integer>> targetEntry : targetMap.entrySet()) {
27948 amit.gupta 1215
			List<Integer> targets = targetEntry.getValue();
28042 amit.gupta 1216
 
1217
			createOfferRequest.getPartnerCriteria().setFofoIds(targetEntry.getKey());
27948 amit.gupta 1218
			int counter = 0;
1219
			for(com.spice.profitmandi.dao.model.TargetSlab targetSlab : createOfferRequest.getTargetSlabs()) {
1220
				targetSlab.setOnwardsAmount(targets.get(counter));
1221
				counter++;
1222
			}
1223
			offerService.addOfferService(createOfferRequest);
1224
		}
1225
	}
27747 amit.gupta 1226
 
28038 amit.gupta 1227
 
1228
	@Autowired
1229
	private WarehouseScanRepository warehouseScanRepository;
28046 amit.gupta 1230
 
1231
	@Autowired
1232
	private WarehouseInventoryService warehouseInventoryService;
1233
 
28038 amit.gupta 1234
	public void fixScans() {
1235
		Map<Integer, Integer> inventoryOrderMap = new HashMap<>();
1236
		inventoryOrderMap.put(348795,1628598);
1237
		inventoryOrderMap.put(348796,1628599);
1238
		inventoryOrderMap.put(329854,1628600);
1239
		inventoryOrderMap.put(334197,1628602);
1240
		inventoryOrderMap.put(330110,1628603);
1241
		inventoryOrderMap.put(330111,1628604);
1242
		inventoryOrderMap.put(332843,1628605);
1243
		inventoryOrderMap.put(338067,1628606);
1244
		inventoryOrderMap.put(338974,1628609);
1245
		inventoryOrderMap.put(338975,1628610);
1246
		inventoryOrderMap.put(338971,1628612);
1247
		inventoryOrderMap.put(338588,1628615);
1248
		inventoryOrderMap.put(368205,1631619);
1249
		inventoryOrderMap.put(368206,1631620);
1250
		inventoryOrderMap.put(368207,1631621);
1251
		inventoryOrderMap.put(368208,1631622);
1252
		inventoryOrderMap.put(368209,1631623);
1253
		inventoryOrderMap.put(368211,1631625);
1254
		inventoryOrderMap.put(368213,1631627);
1255
		inventoryOrderMap.put(368214,1631628);
1256
		inventoryOrderMap.put(368203,1631629);
1257
		inventoryOrderMap.put(368216,1631630);
1258
		inventoryOrderMap.put(368217,1631631);
1259
		inventoryOrderMap.put(368218,1631632);
1260
		inventoryOrderMap.put(368219,1631633);
1261
		inventoryOrderMap.put(368222,1631635);
28039 amit.gupta 1262
		List<WarehouseScan> scans = warehouseScanRepository.selectAllByInventoryItemIds(new ArrayList<>(inventoryOrderMap.keySet()));
1263
		Map<Integer, List<WarehouseScan>> inventoryScansMap = scans.stream().collect(Collectors.groupingBy(WarehouseScan::getInventoryItemId));
28038 amit.gupta 1264
 
1265
		for(Map.Entry<Integer, List<WarehouseScan>> mapEntry : inventoryScansMap.entrySet()) {
1266
			int inventoryItemId = mapEntry.getKey();
28045 amit.gupta 1267
			List<WarehouseScan> duplicateScans = mapEntry.getValue().stream().filter(x->x.getOrderId() != null && x.getOrderId().equals(inventoryOrderMap.get(inventoryItemId))).collect(Collectors.toList());
28046 amit.gupta 1268
			WarehouseScan duplicateScan = duplicateScans.stream().findFirst().get();
1269
			warehouseScanRepository.delete(duplicateScan);
1270
			warehouseInventoryService.addQuantity(duplicateScan.getInventoryItemId(), duplicateScan.getQuantity());
1271
 
28038 amit.gupta 1272
		}
1273
 
1274
	}
1275
 
25043 amit.gupta 1276
}
1277
 
1278
//7015845171