Subversion Repositories SmartDukaan

Rev

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