Subversion Repositories SmartDukaan

Rev

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