Subversion Repositories SmartDukaan

Rev

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