Subversion Repositories SmartDukaan

Rev

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