Subversion Repositories SmartDukaan

Rev

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

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