Subversion Repositories SmartDukaan

Rev

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