Subversion Repositories SmartDukaan

Rev

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