Subversion Repositories SmartDukaan

Rev

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