Subversion Repositories SmartDukaan

Rev

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