Subversion Repositories SmartDukaan

Rev

Rev 27747 | Rev 27948 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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