Subversion Repositories SmartDukaan

Rev

Rev 30335 | Rev 30616 | 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
 
28557 amit.gupta 3
import com.google.gson.Gson;
30209 amit.gupta 4
import com.smartdukaan.cron.scheduled.OppoImeiActivationService;
26214 amit.gupta 5
import com.smartdukaan.cron.scheduled.SamsungIMEIActivationService;
25043 amit.gupta 6
import com.smartdukaan.cron.scheduled.ScheduledTasks;
30335 amit.gupta 7
import com.smartdukaan.cron.scheduled.amazon.shop.AmazonPurchaseService;
26095 amit.gupta 8
import com.spice.profitmandi.common.enumuration.ItemType;
26033 amit.gupta 9
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27450 tejbeer 10
import com.spice.profitmandi.common.model.CustomRetailer;
28840 amit.gupta 11
import com.spice.profitmandi.common.model.ProfitMandiConstants;
29945 amit.gupta 12
import com.spice.profitmandi.common.services.mandii.*;
24819 amit.gupta 13
import com.spice.profitmandi.common.util.FileUtil;
25749 amit.gupta 14
import com.spice.profitmandi.common.util.FormattingUtils;
24819 amit.gupta 15
import com.spice.profitmandi.common.util.Utils;
26033 amit.gupta 16
import com.spice.profitmandi.dao.entity.catalog.Item;
28557 amit.gupta 17
import com.spice.profitmandi.dao.entity.catalog.Offer;
25021 amit.gupta 18
import com.spice.profitmandi.dao.entity.catalog.Scheme;
26579 amit.gupta 19
import com.spice.profitmandi.dao.entity.catalog.TagListing;
29893 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
21
import com.spice.profitmandi.dao.entity.dtr.CreditStatus;
29863 tejbeer 22
import com.spice.profitmandi.dao.entity.dtr.Document;
27286 amit.gupta 23
import com.spice.profitmandi.dao.entity.dtr.PaymentOptionTransaction;
29945 amit.gupta 24
import com.spice.profitmandi.dao.entity.fofo.*;
24953 amit.gupta 25
import com.spice.profitmandi.dao.entity.inventory.SaholicInventorySnapshot;
28736 amit.gupta 26
import com.spice.profitmandi.dao.entity.inventory.SaholicReservationSnapshot;
28735 amit.gupta 27
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
28731 amit.gupta 28
import com.spice.profitmandi.dao.entity.inventory.Warehouse;
29945 amit.gupta 29
import com.spice.profitmandi.dao.entity.transaction.*;
25530 amit.gupta 30
import com.spice.profitmandi.dao.entity.user.Address;
31
import com.spice.profitmandi.dao.entity.user.User;
28840 amit.gupta 32
import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;
27511 amit.gupta 33
import com.spice.profitmandi.dao.entity.warehouse.WarehouseInventoryItem;
28038 amit.gupta 34
import com.spice.profitmandi.dao.entity.warehouse.WarehouseScan;
25021 amit.gupta 35
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
25522 amit.gupta 36
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
27286 amit.gupta 37
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
29893 tejbeer 38
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
26759 amit.gupta 39
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
26579 amit.gupta 40
import com.spice.profitmandi.dao.model.ContentPojo;
41
import com.spice.profitmandi.dao.model.MediaPojo;
30576 amit.gupta 42
import com.spice.profitmandi.dao.model.TargetSlab;
24716 amit.gupta 43
import com.spice.profitmandi.dao.repository.GenericRepository;
29945 amit.gupta 44
import com.spice.profitmandi.dao.repository.catalog.*;
25749 amit.gupta 45
import com.spice.profitmandi.dao.repository.cs.CsService;
29945 amit.gupta 46
import com.spice.profitmandi.dao.repository.dtr.*;
47
import com.spice.profitmandi.dao.repository.fofo.*;
24953 amit.gupta 48
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
26928 amit.gupta 49
import com.spice.profitmandi.dao.repository.inventory.SaholicReservationSnapshotRepository;
28675 amit.gupta 50
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
28708 amit.gupta 51
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
29945 amit.gupta 52
import com.spice.profitmandi.dao.repository.transaction.*;
25530 amit.gupta 53
import com.spice.profitmandi.dao.repository.user.AddressRepository;
29863 tejbeer 54
import com.spice.profitmandi.dao.repository.user.FofoKycRepository;
24002 amit.gupta 55
import com.spice.profitmandi.dao.repository.user.UserRepository;
28840 amit.gupta 56
import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;
27511 amit.gupta 57
import com.spice.profitmandi.dao.repository.warehouse.WarehouseInventoryItemRepository;
28038 amit.gupta 58
import com.spice.profitmandi.dao.repository.warehouse.WarehouseScanRepository;
30310 amit.gupta 59
import com.spice.profitmandi.service.integrations.gstpro.GstProAuthService;
60
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
23899 amit.gupta 61
import com.spice.profitmandi.service.inventory.InventoryService;
26033 amit.gupta 62
import com.spice.profitmandi.service.inventory.PurchaseService;
28736 amit.gupta 63
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
30576 amit.gupta 64
import com.spice.profitmandi.service.offers.ItemCriteria;
27948 amit.gupta 65
import com.spice.profitmandi.service.offers.OfferService;
28557 amit.gupta 66
import com.spice.profitmandi.service.offers.PartnerCriteria;
24266 amit.gupta 67
import com.spice.profitmandi.service.order.OrderService;
24005 amit.gupta 68
import com.spice.profitmandi.service.pricing.PriceDropService;
69
import com.spice.profitmandi.service.scheme.SchemeService;
23899 amit.gupta 70
import com.spice.profitmandi.service.transaction.TransactionService;
30310 amit.gupta 71
import com.spice.profitmandi.service.transaction.invoicing.InvoiceService;
23899 amit.gupta 72
import com.spice.profitmandi.service.user.RetailerService;
73
import com.spice.profitmandi.service.wallet.WalletService;
28046 amit.gupta 74
import com.spice.profitmandi.service.warehouse.WarehouseInventoryService;
24953 amit.gupta 75
import in.shop2020.model.v1.order.OrderStatus;
24002 amit.gupta 76
import in.shop2020.model.v1.order.WalletReferenceType;
27450 tejbeer 77
import okhttp3.OkHttpClient;
78
import okhttp3.Request;
79
import okhttp3.Response;
29945 amit.gupta 80
import org.apache.commons.io.output.ByteArrayOutputStream;
81
import org.apache.commons.lang.StringUtils;
82
import org.apache.logging.log4j.LogManager;
83
import org.apache.logging.log4j.Logger;
84
import org.json.JSONArray;
85
import org.json.JSONObject;
86
import org.openqa.selenium.Dimension;
87
import org.openqa.selenium.OutputType;
88
import org.openqa.selenium.TakesScreenshot;
89
import org.openqa.selenium.WebDriver;
90
import org.openqa.selenium.chrome.ChromeDriver;
91
import org.openqa.selenium.chrome.ChromeOptions;
92
import org.springframework.beans.factory.annotation.Autowired;
93
import org.springframework.core.io.ByteArrayResource;
94
import org.springframework.mail.javamail.JavaMailSender;
95
import org.springframework.stereotype.Component;
96
import org.springframework.transaction.annotation.Transactional;
24002 amit.gupta 97
 
29945 amit.gupta 98
import java.io.File;
99
import java.io.FileInputStream;
100
import java.io.IOException;
101
import java.time.LocalDate;
102
import java.time.LocalDateTime;
103
import java.time.LocalTime;
104
import java.time.Month;
105
import java.time.temporal.ChronoUnit;
106
import java.util.*;
107
import java.util.concurrent.TimeUnit;
108
import java.util.stream.Collectors;
109
 
23755 amit.gupta 110
@Component
111
@Transactional(rollbackFor = Throwable.class)
112
public class RunOnceTasks {
113
 
114
	private static final Logger LOGGER = LogManager.getLogger(RunOnceTasks.class);
115
	@Autowired
23824 amit.gupta 116
	private LineItemRepository lineItemRepository;
24711 amit.gupta 117
 
23905 amit.gupta 118
	@Autowired
27221 amit.gupta 119
	private LeadRepository leadRepository;
28731 amit.gupta 120
 
28675 amit.gupta 121
	@Autowired
122
	private VendorItemPricingRepository vendorItemPricingRepository;
28731 amit.gupta 123
 
28708 amit.gupta 124
	@Autowired
125
	private WarehouseRepository warehouseRepository;
27277 amit.gupta 126
 
27221 amit.gupta 127
	@Autowired
26759 amit.gupta 128
	private PurchaseReturnItemRepository purchaseReturnItemRepository;
26928 amit.gupta 129
 
26759 amit.gupta 130
	@Autowired
24953 amit.gupta 131
	private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
25752 amit.gupta 132
 
25749 amit.gupta 133
	@Autowired
134
	private CsService csService;
28660 amit.gupta 135
 
28557 amit.gupta 136
	@Autowired
28624 amit.gupta 137
	private ManualPaymentRequestRepository manualPaymentRequestRepository;
138
 
139
	@Autowired
28557 amit.gupta 140
	private OfferRepository offerRepository;
26299 amit.gupta 141
 
26033 amit.gupta 142
	@Autowired
26579 amit.gupta 143
	private Mongo mongoClient;
27787 amit.gupta 144
 
27286 amit.gupta 145
	@Autowired
28557 amit.gupta 146
	private Gson gson;
28624 amit.gupta 147
 
28557 amit.gupta 148
	@Autowired
27286 amit.gupta 149
	private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
26579 amit.gupta 150
 
151
	@Autowired
30209 amit.gupta 152
	private OppoImeiActivationService oppoImeiActivationService;
26299 amit.gupta 153
 
26195 amit.gupta 154
	@Autowired
30209 amit.gupta 155
	private SamsungIMEIActivationService samsungIMEIActivationService;
156
 
157
	@Autowired
26033 amit.gupta 158
	private PrebookingOrderRepository prebookingOrderRepository;
24953 amit.gupta 159
 
160
	@Autowired
24883 amit.gupta 161
	private PartnerTargetRepository partnerTargetRepository;
162
 
163
	@Autowired
24802 amit.gupta 164
	private SellerWarehouseRepository sellerWarehouseRepository;
24814 amit.gupta 165
 
24802 amit.gupta 166
	@Autowired
24806 amit.gupta 167
	private FofoOrderItemRepository fofoOrderItemRepository;
27787 amit.gupta 168
 
27286 amit.gupta 169
	@Autowired
170
	private FofoLineItemRepository fofoLineItemRepository;
24814 amit.gupta 171
 
24806 amit.gupta 172
	@Autowired
173
	private FofoOrderRepository fofoOrderRepository;
24814 amit.gupta 174
 
24806 amit.gupta 175
	@Autowired
24767 amit.gupta 176
	private UserWalletRepository userWalletRepository;
177
 
178
	@Autowired
179
	private UserWalletHistoryRepository userWalletHistoryRepository;
180
 
181
	@Autowired
24002 amit.gupta 182
	private UserRepository userRepository;
24711 amit.gupta 183
 
24002 amit.gupta 184
	@Autowired
23899 amit.gupta 185
	private WalletService walletService;
186
 
187
	@Autowired
25034 amit.gupta 188
	private ItemRepository itemRepository;
189
 
190
	@Autowired
23899 amit.gupta 191
	private InventoryService inventoryService;
192
 
193
	@Autowired
194
	private TransactionService transactionService;
26299 amit.gupta 195
 
26033 amit.gupta 196
	@Autowired
197
	private PurchaseService purchaseService;
23899 amit.gupta 198
 
24711 amit.gupta 199
	// Service for Tertiary/Partner Orders
24266 amit.gupta 200
	@Autowired
201
	private OrderService orderService;
23767 amit.gupta 202
 
23755 amit.gupta 203
	@Autowired
25021 amit.gupta 204
	private SchemeRepository schemeRepository;
25516 amit.gupta 205
 
25043 amit.gupta 206
	@Autowired
25530 amit.gupta 207
	private AddressRepository addressRepository;
25749 amit.gupta 208
 
25530 amit.gupta 209
	@Autowired
25043 amit.gupta 210
	private ScheduledTasks scheduledTasks;
25034 amit.gupta 211
 
25021 amit.gupta 212
	@Autowired
213
	private SchemeItemRepository schemeItemRepository;
214
 
215
	@Autowired
24772 amit.gupta 216
	private ReturnOrderRepository returnOrderRepository;
217
 
218
	@Autowired
23899 amit.gupta 219
	private FofoStoreRepository fofoStoreRepository;
220
 
221
	@Autowired
23755 amit.gupta 222
	private LineItemImeisRepository lineItemImeisRepository;
24711 amit.gupta 223
 
24002 amit.gupta 224
	@Autowired
225
	private InventoryItemRepository inventoryItemRepository;
24814 amit.gupta 226
 
24806 amit.gupta 227
	@Autowired
26579 amit.gupta 228
	private TagListingRepository tagListingRepository;
229
 
230
	@Autowired
24806 amit.gupta 231
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
23901 amit.gupta 232
 
23898 amit.gupta 233
	@Autowired
23899 amit.gupta 234
	private RetailerService retailerService;
24711 amit.gupta 235
 
24002 amit.gupta 236
	@Autowired
237
	private SchemeInOutRepository schemeInOutRepository;
24711 amit.gupta 238
 
24002 amit.gupta 239
	@Autowired
240
	private DebitNoteRepository debitNoteRepository;
28624 amit.gupta 241
 
27948 amit.gupta 242
	@Autowired
243
	private OfferService offerService;
23899 amit.gupta 244
 
245
	@Autowired
24716 amit.gupta 246
	private GenericRepository genericRepository;
247
 
248
	@Autowired
23898 amit.gupta 249
	private PurchaseRepository purchaseRepository;
24711 amit.gupta 250
 
24005 amit.gupta 251
	@Autowired
252
	private PriceDropService priceDropService;
24883 amit.gupta 253
 
24819 amit.gupta 254
	@Autowired
255
	private JavaMailSender googleMailSender;
24711 amit.gupta 256
 
24005 amit.gupta 257
	@Autowired
258
	private SchemeService schemeService;
24711 amit.gupta 259
 
24716 amit.gupta 260
	@Autowired
261
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
262
 
263
	@Autowired
24767 amit.gupta 264
	private OrderRepository orderRepository;
28731 amit.gupta 265
 
24767 amit.gupta 266
	@Autowired
24716 amit.gupta 267
	private ScanRecordRepository scanRecordRepository;
268
 
24767 amit.gupta 269
	@Autowired
270
	private JavaMailSender mailSender;
27451 tejbeer 271
 
27450 tejbeer 272
	private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
273
	private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";
24767 amit.gupta 274
 
27511 amit.gupta 275
	@Autowired
276
	private WarehouseInventoryItemRepository warehouseInventoryItemRepository;
27787 amit.gupta 277
 
23898 amit.gupta 278
	public void populateGrnTimestamp() {
279
		List<Purchase> allPurchases = purchaseRepository.selectAll();
23899 amit.gupta 280
		for (Purchase p : allPurchases) {
23898 amit.gupta 281
			String invoiceNumber = p.getPurchaseReference();
23899 amit.gupta 282
			if (p.getCompleteTimestamp() == null) {
23898 amit.gupta 283
				LOGGER.info("GRN for invoice {} is delivered but partially Completed.", p.getPurchaseReference());
284
			} else {
285
				List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(invoiceNumber, p.getFofoId());
23899 amit.gupta 286
				for (Order order : orders) {
23902 amit.gupta 287
					if (order.getPartnerGrnTimestamp() == null) {
288
						order.setPartnerGrnTimestamp(p.getCompleteTimestamp());
23898 amit.gupta 289
					}
290
				}
291
			}
292
		}
23899 amit.gupta 293
 
23898 amit.gupta 294
	}
23899 amit.gupta 295
 
26408 amit.gupta 296
	public void fetchImeiActivation(int ym) throws Exception {
27787 amit.gupta 297
		LocalDate startDate = null;
298
		LocalDate endDate = null;
299
		if (ym == 0) {
300
			startDate = LocalDate.now().minusDays(30);
301
			endDate = LocalDate.now();
302
		} else {
303
			startDate = LocalDate.now().minusMonths(ym);
304
			endDate = startDate.plusMonths(1);
305
		}
30209 amit.gupta 306
		samsungIMEIActivationService.getActivationsBetweenNew(startDate, endDate);
26195 amit.gupta 307
	}
26299 amit.gupta 308
 
24716 amit.gupta 309
	public void migarateLineItemsToNewTable() throws Exception {
23755 amit.gupta 310
		LOGGER.info("Before Migrated LineItems Successfully");
23824 amit.gupta 311
		int lineItemImeiId = 0;
312
		LocalDateTime startDate = null;
313
		try {
314
			lineItemImeiId = lineItemImeisRepository.selectMaxId();
23899 amit.gupta 315
			LineItem lineItem = lineItemRepository
316
					.selectById(lineItemImeisRepository.selectById(lineItemImeiId).getLineItemId());
23824 amit.gupta 317
			Order order = orderRepository.selectById(lineItem.getOrderId());
318
			startDate = order.getBillingTimestamp();
319
		} catch (Exception e) {
320
			LOGGER.info("Running before first time");
23826 amit.gupta 321
			startDate = LocalDateTime.of(LocalDate.of(2017, 7, 1), LocalTime.MIDNIGHT);
23824 amit.gupta 322
		}
323
		List<Order> orders = orderRepository.selectAllByBillingDatesBetween(startDate, LocalDateTime.now());
23827 amit.gupta 324
		Collections.reverse(orders);
23899 amit.gupta 325
 
23755 amit.gupta 326
		for (Order order : orders) {
23824 amit.gupta 327
			try {
23767 amit.gupta 328
				String serialNumbers = order.getLineItem().getSerialNumber();
329
				if (!StringUtils.isEmpty(serialNumbers)) {
330
					List<String> serialNumberList = Arrays.asList(serialNumbers.split(","));
331
					for (String serialNumber : serialNumberList) {
332
						int lineItemId = order.getLineItem().getId();
333
						LineItemImei lineItemImei = new LineItemImei();
334
						lineItemImei.setSerialNumber(serialNumber);
335
						lineItemImei.setLineItemId(lineItemId);
336
						lineItemImeisRepository.persist(lineItemImei);
337
					}
338
				} else {
339
					LOGGER.info("Serial Numbers dont exist for Order {}", order.getId());
23755 amit.gupta 340
				}
23824 amit.gupta 341
			} catch (Exception e) {
23899 amit.gupta 342
				LOGGER.info("Error occurred while creating lineitem imei {}, because of {}", order.getId(),
343
						e.getMessage());
23755 amit.gupta 344
			}
345
		}
346
		LOGGER.info("Migrated LineItems Successfully");
347
	}
24266 amit.gupta 348
 
349
	public void cancelOrder(List<String> invoiceNumbers) throws Exception {
350
		orderService.cancelOrder(invoiceNumbers);
351
	}
27787 amit.gupta 352
 
353
	@Autowired
354
	HdfcPaymentRepository hdfcPaymentRepository;
355
 
27721 amit.gupta 356
	public void addPayment() throws Exception {
27722 amit.gupta 357
		List<Integer> paymentIds = Arrays.asList(3777);
27721 amit.gupta 358
		for (int hdfcPaymentId : paymentIds) {
359
			HdfcPayment hdfcPayment = hdfcPaymentRepository.selectById(hdfcPaymentId);
360
			String virtualAccount = hdfcPayment.getVirtualAccount();
361
			String retailerIdString = virtualAccount.substring(6);
362
			int retailerId = Integer.parseInt(retailerIdString);
363
			String description = String.format("Advance payment received through %s, Utr# %s",
364
					hdfcPayment.getTransferMode(), hdfcPayment.getUtr());
365
			walletService.addAmountToWallet(retailerId, hdfcPayment.getId(), WalletReferenceType.AUTOMATED_ADVANCE,
366
					description, (float) hdfcPayment.getAmount(), hdfcPayment.getCreditTimestamp());
367
		}
368
	}
29863 tejbeer 369
 
370
	// Bug in original migrate purchase
24722 amit.gupta 371
	public void migratePurchase() throws Exception {
24641 amit.gupta 372
		List<Purchase> purchases = purchaseRepository.selectPurchaseAllPurchasesLessThanZero();
29758 amit.gupta 373
		for (Purchase purchase : purchases) {
374
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchase.getId());
29863 tejbeer 375
			for (InventoryItem ii : inventoryItems) {
29758 amit.gupta 376
				List<ScanRecord> scans = scanRecordRepository.selectByInventoryItemId(ii.getId());
29863 tejbeer 377
				if (scans.size() == 1 && scans.get(0).getQuantity() == 0) {
29758 amit.gupta 378
					scanRecordRepository.delete(scans.get(0));
29863 tejbeer 379
					purchase.setNonSerializedQuantity(purchase.getNonSerializedQuantity() - ii.getInitialQuantity());
29758 amit.gupta 380
					inventoryItemRepository.delete(ii);
381
				}
29863 tejbeer 382
 
29758 amit.gupta 383
			}
29863 tejbeer 384
 
29758 amit.gupta 385
		}
386
	}
387
 
388
	public void migratePurchaseFix() throws Exception {
389
		List<Purchase> purchases = purchaseRepository.selectPurchaseAllPurchasesLessThanZero();
24706 amit.gupta 390
		System.out.printf("Total Purchases count is %s", purchases.size());
24711 amit.gupta 391
		for (Purchase purchase : purchases) {
392
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchase.getId());
393
			Map<Integer, List<InventoryItem>> itemIdInventoryMap = inventoryItems.stream()
394
					.collect(Collectors.groupingBy(InventoryItem::getItemId));
395
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(purchase.getPurchaseReference(),
396
					purchase.getFofoId());
397
			Map<Integer, Integer> ourSaleItemQtyMap = orders.stream().collect(Collectors.groupingBy(
398
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
399
			Map<Integer, Integer> theirPurchaseItemQtyMap = inventoryItems.stream().collect(Collectors
400
					.groupingBy(InventoryItem::getItemId, Collectors.summingInt(InventoryItem::getInitialQuantity)));
24709 amit.gupta 401
			for (Map.Entry<Integer, Integer> itemQtyEntry : theirPurchaseItemQtyMap.entrySet()) {
24711 amit.gupta 402
				if (!ourSaleItemQtyMap.containsKey(itemQtyEntry.getKey())) {
403
					LOGGER.info("Cannot find in Invoice {} item {}", purchase.getPurchaseReference(),
404
							itemQtyEntry.getKey());
24646 amit.gupta 405
					continue;
24645 amit.gupta 406
				}
24709 amit.gupta 407
				int ourSale = ourSaleItemQtyMap.get(itemQtyEntry.getKey());
24713 amit.gupta 408
				int quantityToReduce = itemQtyEntry.getValue() - ourSale;
24716 amit.gupta 409
				List<InventoryItem> itemIis = itemIdInventoryMap.get(itemQtyEntry.getKey());
410
				if (itemIdInventoryMap != null) {
411
					for (InventoryItem ii : itemIis) {
24915 amit.gupta 412
						if (ii.getSerialNumber() == null && ii.getGoodQuantity() == ii.getInitialQuantity()
413
								&& quantityToReduce >= ii.getInitialQuantity()) {
24734 amit.gupta 414
							LOGGER.info("Changed in inventoryItems {}, {}, {}, {}, {}, {}",
24716 amit.gupta 415
									purchase.getPurchaseReference(), ii.getId(), ii.getItemId(),
24734 amit.gupta 416
									ii.getInitialQuantity(), ii.getGoodQuantity(), quantityToReduce);
24912 amit.gupta 417
							List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
418
							for (ScanRecord scanRecord : scanRecords) {
24915 amit.gupta 419
								CurrentInventorySnapshot cis = currentInventorySnapshotRepository
420
										.selectByItemIdAndFofoId(itemQtyEntry.getKey(), purchase.getFofoId());
421
								scanRecord.setQuantity(0);
422
								ii.setGoodQuantity(0);
423
								quantityToReduce = quantityToReduce - ii.getInitialQuantity();
424
								cis.setAvailability(cis.getAvailability() - ii.getInitialQuantity());
425
								purchase.setUnfullfilledNonSerializedQuantity(
426
										purchase.getUnfullfilledNonSerializedQuantity() + quantityToReduce);
427
								LOGGER.info("Rectified {}, {}, {}, {}, {}, {}", purchase.getPurchaseReference(),
428
										ii.getId(), ii.getItemId(), ii.getInitialQuantity(), ii.getGoodQuantity(),
429
										quantityToReduce);
24711 amit.gupta 430
							}
24641 amit.gupta 431
						}
432
					}
433
				}
434
			}
435
		}
24953 amit.gupta 436
		// throw new Exception();
24641 amit.gupta 437
	}
24767 amit.gupta 438
 
24802 amit.gupta 439
	public void migrateChallansToInvoices() throws Exception {
24814 amit.gupta 440
		Map<String, List<Order>> invoiceOrdersMap = orderRepository.selectAllChallans().stream()
441
				.filter(x -> !x.getLineItem().getHsnCode().equals("NOGST"))
24794 amit.gupta 442
				.collect(Collectors.groupingBy(Order::getInvoiceNumber, Collectors.toList()));
24814 amit.gupta 443
 
25837 amit.gupta 444
		List<List<?>> rows = new ArrayList<>();
24814 amit.gupta 445
		for (String invoice : invoiceOrdersMap.keySet()) {
24794 amit.gupta 446
			Order oneOrder = invoiceOrdersMap.get(invoice).get(0);
447
			int totalOrders = invoiceOrdersMap.get(invoice).size();
448
			LineItem lineItem = oneOrder.getLineItem();
24802 amit.gupta 449
			oneOrder.setBillingTimestamp(LocalDateTime.now());
450
			oneOrder.setInvoiceNumber(getInvoiceNumber(oneOrder));
24819 amit.gupta 451
			rows.add(Arrays.asList(oneOrder.getId(), invoice, oneOrder.getInvoiceNumber(), lineItem.getQuantity()));
24883 amit.gupta 452
			LOGGER.info(invoice + "\t" + oneOrder.getInvoiceNumber() + oneOrder.getId() + "\t",
453
					"\t" + totalOrders + "\t" + lineItem.getQuantity());
24814 amit.gupta 454
			Purchase p = null;
455
			try {
456
				p = purchaseRepository.selectByPurchaseReferenceAndFofoId(invoice, oneOrder.getRetailerId());
457
			} catch (Exception e) {
24815 amit.gupta 458
				LOGGER.info("Could not find purchase for invoice {}", invoice);
24812 amit.gupta 459
			}
24814 amit.gupta 460
			if (p != null) {
461
				List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(p.getId());
462
				for (InventoryItem inventoryItem : inventoryItems) {
24815 amit.gupta 463
					LOGGER.info(inventoryItem.getItemId() + " " + inventoryItem.getGoodQuantity() + " "
24883 amit.gupta 464
							+ inventoryItem.getHsnCode() + " " + inventoryItem.getSerialNumber() + " "
465
							+ p.getPurchaseReference());
24814 amit.gupta 466
				}
467
			}
468
 
24794 amit.gupta 469
		}
24818 amit.gupta 470
		changePartnerInvoices();
24883 amit.gupta 471
		ByteArrayOutputStream baos = FileUtil
472
				.getCSVByteStream(Arrays.asList("Order id", "Challan", "Invoice", "Quantity"), rows);
473
 
24819 amit.gupta 474
		Utils.sendMailWithAttachment(googleMailSender,
30209 amit.gupta 475
				new String[]{"amit.gupta@shop2020.in", "sunny.yadav@smartdukaan.com"}, null,
24883 amit.gupta 476
				"Challans Converted to Invoice", "PFA", "Challans-To-Invoice.csv",
477
				new ByteArrayResource(baos.toByteArray()));
24916 amit.gupta 478
		throw new Exception();
24794 amit.gupta 479
	}
24767 amit.gupta 480
 
24802 amit.gupta 481
	private String getInvoiceNumber(Order oneOrder) {
24805 amit.gupta 482
		String prefix = oneOrder.getInvoiceNumber().split("-")[1].replaceAll("\\d*", "");
24803 amit.gupta 483
		System.out.println("Prefix is " + prefix);
24802 amit.gupta 484
		SellerWarehouse sellerWarehouse = sellerWarehouseRepository.selectByPrefix(prefix);
485
		int newSequence = sellerWarehouse.getInvoiceSequence() + 1;
486
		sellerWarehouse.setInvoiceSequence(newSequence);
24814 amit.gupta 487
		return prefix + newSequence;
24802 amit.gupta 488
	}
24814 amit.gupta 489
 
24806 amit.gupta 490
	private void changePartnerInvoices() throws Exception {
24814 amit.gupta 491
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectByInvoiceNumberLike("%SEC%");
492
		for (FofoOrder fofoOrder : fofoOrders) {
24806 amit.gupta 493
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
24814 amit.gupta 494
			if (fofoOrderItem.getBrand().equals("Vivo")) {
24806 amit.gupta 495
				String challanString = fofoOrder.getInvoiceNumber();
24814 amit.gupta 496
				String storeCode = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoOrder.getFofoId())
497
						.getPrefix();
24806 amit.gupta 498
				String invoiceNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), storeCode);
499
				fofoOrder.setInvoiceNumber(invoiceNumber);
500
				fofoOrder.setCreateTimestamp(LocalDateTime.now());
24818 amit.gupta 501
				LOGGER.info(challanString + "\t" + invoiceNumber + "\t" + fofoOrderItem.getQuantity());
24806 amit.gupta 502
			}
24814 amit.gupta 503
 
24806 amit.gupta 504
		}
505
	}
24802 amit.gupta 506
 
25021 amit.gupta 507
	private Scheme getScheme() {
508
		Scheme s = new Scheme();
509
		s.setName("List Price Margin");
510
		s.setDescription("List Price Margin");
511
		s.setActiveTimestamp(null);
512
		s.setStartDateTime(LocalDate.of(2019, 6, 1).atStartOfDay());
513
		s.setEndDateTime(LocalDate.of(2019, 7, 1).atStartOfDay());
514
		s.setAmountType(AmountType.PERCENTAGE);
515
		s.setCreateTimestamp(LocalDateTime.now());
516
		s.setExpireTimestamp(null);
517
		s.setCreatedBy(175120474);
518
		return s;
519
	}
520
 
24957 amit.gupta 521
	public void findMismatchesInIndent() throws Exception {
522
		List<Order> allInProcessOrders = orderRepository.selectAllOrder(OrderStatus.SUBMITTED_FOR_PROCESSING);
24967 amit.gupta 523
 
25021 amit.gupta 524
		Map<String, Integer> lineItemWhQtyMap = allInProcessOrders.stream()
25734 amit.gupta 525
				.collect(Collectors.groupingBy(y -> y.getLineItem().getItemId() + "-" + y.getFulfilmentWarehouseId(),
24967 amit.gupta 526
						Collectors.summingInt(y -> y.getLineItem().getQuantity())));
25021 amit.gupta 527
 
528
		lineItemWhQtyMap.forEach((key, value) -> {
529
 
24967 amit.gupta 530
			int itemId = Integer.parseInt(key.split("-")[0]);
531
			int warehouseId = Integer.parseInt(key.split("-")[1]);
25021 amit.gupta 532
			System.out.printf("%d\t%d\t%d\n", itemId, warehouseId, value);
533
			SaholicInventorySnapshot cis = saholicInventorySnapshotRepository.selectByWarehouseIdandItemId(warehouseId,
534
					itemId);
535
			if (cis == null) {
24970 amit.gupta 536
				cis = new SaholicInventorySnapshot();
537
				cis.setItemId(itemId);
538
				cis.setWarehouseId(warehouseId);
539
				cis.setAvailability(0);
540
				saholicInventorySnapshotRepository.persist(cis);
541
			}
24967 amit.gupta 542
			cis.setReserved(value);
543
		});
24953 amit.gupta 544
	}
545
 
25034 amit.gupta 546
	public void fixSchemePayouts() throws Exception {
25524 amit.gupta 547
		LOGGER.info("In fix scheme Payouts");
25522 amit.gupta 548
		LocalDateTime startDate = LocalDate.of(2019, 9, 1).atStartOfDay();
549
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(startDate, LocalDateTime.now());
25530 amit.gupta 550
 
25034 amit.gupta 551
		for (SchemeInOut sio : sios) {
25530 amit.gupta 552
			if (sio.getSchemeId() != 347) {
25523 amit.gupta 553
				LOGGER.info("Skipping {}", sio.getSchemeId());
25522 amit.gupta 554
				continue;
555
			}
25043 amit.gupta 556
			genericRepository.delete(sio);
25522 amit.gupta 557
			InventoryItem ii = inventoryItemRepository.selectById(sio.getInventoryItemId());
558
			UserWallet userWallet = userWalletRepository.selectByRetailerId(ii.getFofoId());
559
			Scheme scheme = schemeRepository.selectById(sio.getSchemeId());
560
			if (scheme.getType().equals(SchemeType.IN)) {
561
				List<UserWalletHistory> historyList = userWalletHistoryRepository
562
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_IN);
563
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 564
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 565
						genericRepository.delete(uwh);
566
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
567
					}
568
				}
569
			} else {
570
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
571
				int orderId = scanRecords.get(0).getOrderId();
572
				List<UserWalletHistory> historyList = userWalletHistoryRepository
573
						.selectAllByreferenceIdandreferenceType(orderId, WalletReferenceType.SCHEME_OUT);
574
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 575
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 576
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
577
						genericRepository.delete(uwh);
578
					}
579
				}
580
				List<UserWalletHistory> historyListBroken = userWalletHistoryRepository
25530 amit.gupta 581
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_OUT);
25522 amit.gupta 582
				for (UserWalletHistory uwh : historyListBroken) {
25530 amit.gupta 583
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 584
						genericRepository.delete(uwh);
585
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
586
					}
587
				}
588
			}
589
 
25530 amit.gupta 590
			// System.out.println("Total Amount Rolled Back is " + totalRollbackAmount);
25516 amit.gupta 591
		}
25589 amit.gupta 592
		scheduledTasks.processScheme(startDate, startDate.plusDays(10), true);
25030 amit.gupta 593
	}
25530 amit.gupta 594
 
595
	public void fixWallet() throws Exception {
596
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
25536 amit.gupta 597
		System.out.println("id\tcode\tactive\tname\tcity\tstate\twallet amount\tsum\twallet amount-sum");
25530 amit.gupta 598
		for (FofoStore fofoStore : fofoStores) {
599
			UserWallet uw = userWalletRepository.selectByRetailerId(fofoStore.getId());
600
			User user = userRepository.selectById(fofoStore.getId());
25749 amit.gupta 601
			if (user == null) {
25533 amit.gupta 602
				LOGGER.info("store does not exist", fofoStore.getCode());
25535 amit.gupta 603
				continue;
25533 amit.gupta 604
			}
25536 amit.gupta 605
			Address address = null;
606
			try {
607
				address = addressRepository.selectById(user.getAddressId());
25749 amit.gupta 608
			} catch (Exception e) {
25536 amit.gupta 609
				LOGGER.info("Could not find address for Store", fofoStore.getCode());
610
				address = new Address();
611
			}
25539 amit.gupta 612
			double sum = userWalletHistoryRepository.selectSumByWallet(uw.getId());
25749 amit.gupta 613
			int calculated = (int) sum;
614
			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(),
615
					fofoStore.isActive(), address.getName(), address.getCity(), address.getState(), uw.getAmount(),
616
					calculated, uw.getAmount() - calculated);
25530 amit.gupta 617
		}
618
	}
25749 amit.gupta 619
 
25734 amit.gupta 620
	public void changeWarehouse() throws Exception {
621
		transactionService.moveWarehouses();
622
	}
25749 amit.gupta 623
 
624
	public void mailDashboardScreenshots() throws Exception {
625
		System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
626
 
25752 amit.gupta 627
		ChromeOptions options = new ChromeOptions();
628
		options.addArguments("--headless");
629
		options.addArguments("--no-sandbox");
630
		options.addArguments("start-maximized");
631
		options.addArguments("disable-infobars");
632
		options.addArguments("--disable-extensions");
633
 
25753 amit.gupta 634
		WebDriver driver = new ChromeDriver(options);
25774 amit.gupta 635
		driver.manage().window().setSize(new Dimension(1600, 900));
25749 amit.gupta 636
		driver.manage().window().maximize();
25752 amit.gupta 637
		// Deleting all the cookies
25749 amit.gupta 638
		driver.manage().deleteAllCookies();
25752 amit.gupta 639
		// Specifiying pageLoadTimeout and Implicit wait
25749 amit.gupta 640
		driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
641
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
25752 amit.gupta 642
 
30215 amit.gupta 643
		Map<String, Set<Integer>> authUserPartnerIdMapping = csService.getAuthUserPartnerIdMapping();
25749 amit.gupta 644
		Set<Integer> allPartners = new HashSet<>();
25765 amit.gupta 645
		Map<Integer, File> partnerSnapshotMap = new HashMap<>();
25752 amit.gupta 646
		authUserPartnerIdMapping.values().stream().forEach(x -> allPartners.addAll(x));
647
		for (int fofoId : allPartners) {
25749 amit.gupta 648
			driver.get("https://partners.smartdukaan.com/12dashboard34?fofoId=" + fofoId);
25765 amit.gupta 649
			File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
650
			partnerSnapshotMap.put(fofoId, file);
25752 amit.gupta 651
 
25749 amit.gupta 652
		}
30215 amit.gupta 653
		for (Map.Entry<String, Set<Integer>> entry : authUserPartnerIdMapping.entrySet()) {
25749 amit.gupta 654
			String email = entry.getKey();
25996 amit.gupta 655
			LOGGER.info("Sending mail start to {}", email);
30215 amit.gupta 656
			Set<Integer> partnerIds = entry.getValue();
25749 amit.gupta 657
			StringBuffer body = new StringBuffer();
25769 amit.gupta 658
			Map<Integer, File> emailSnapshotMap = new HashMap<>();
25752 amit.gupta 659
			for (int fofoId : partnerIds) {
25769 amit.gupta 660
				body.append(String.format("<br/><img src=\"cid:%d\"/>", fofoId));
661
				emailSnapshotMap.put(fofoId, partnerSnapshotMap.get(fofoId));
25749 amit.gupta 662
			}
30209 amit.gupta 663
			Utils.sendEmbeddedHtmlMail(mailSender, new String[]{email}, new String[]{},
25752 amit.gupta 664
					String.format("Franchise Screenshots - %s", FormattingUtils.formatDate(LocalDateTime.now())),
25837 amit.gupta 665
					body.toString(), emailSnapshotMap);
25996 amit.gupta 666
			LOGGER.info("Sent mail to {}", email);
25749 amit.gupta 667
		}
668
		driver.quit();
669
	}
29893 tejbeer 670
 
26299 amit.gupta 671
	// Rollout prebooking orders amount in case the order is grned.
26033 amit.gupta 672
	public void pbfix() throws ProfitMandiBusinessException {
29870 amit.gupta 673
		List<PrebookingOrder> prebookingOrders = prebookingOrderRepository.selectAll();
674
		Map<Integer, Boolean> prebookingCleared = new HashMap<>();
675
		prebookingOrders = prebookingOrders.stream().collect(Collectors.toList());
676
		Map<Integer, List<PrebookingOrder>> catalogPrebookingMap = new HashMap<>();
29893 tejbeer 677
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
678
			if (!catalogPrebookingMap.containsKey(prebookingOrder.getCatalogId())) {
29870 amit.gupta 679
				catalogPrebookingMap.put(prebookingOrder.getCatalogId(), new ArrayList<>());
680
			}
681
			catalogPrebookingMap.get(prebookingOrder.getCatalogId()).add(prebookingOrder);
682
			int prebookingId = prebookingOrder.getId();
29893 tejbeer 683
			List<UserWalletHistory> history = walletService.getAllByReference(prebookingOrder.getFofoId(), prebookingId,
684
					WalletReferenceType.PREBOOKING_ORDER);
685
			long totalAmount = history.stream().collect(Collectors.summingLong(x -> x.getAmount()));
686
			// Refund is pending
687
			if (history.size() > 0) {
688
				if (totalAmount < 0) {
29870 amit.gupta 689
					prebookingCleared.put(prebookingId, false);
29893 tejbeer 690
					LOGGER.info("Amount pending for prebooking id " + prebookingId + " amount is " + -totalAmount
691
							+ " catalog id - {}", prebookingOrder.getCatalogId());
29870 amit.gupta 692
				} else {
693
					prebookingCleared.put(prebookingId, true);
26033 amit.gupta 694
				}
29870 amit.gupta 695
			} else {
696
				prebookingCleared.put(prebookingId, true);
697
				LOGGER.info("No entry in wallet for prebooking Id " + prebookingId);
26033 amit.gupta 698
			}
699
		}
29893 tejbeer 700
		for (Map.Entry<Integer, List<PrebookingOrder>> entrySet : catalogPrebookingMap.entrySet()) {
701
			LOGGER.info("Catalog id {}, Size {}", entrySet.getKey(), entrySet.getValue().size());
702
			Set<Integer> itemIds = itemRepository.selectAllByCatalogItemId(entrySet.getKey()).stream()
703
					.map(x -> x.getId()).collect(Collectors.toSet());
29870 amit.gupta 704
			List<PrebookingOrder> prebookings = entrySet.getValue();
29893 tejbeer 705
			Map<Integer, List<PrebookingOrder>> fofoMap = prebookings.stream()
706
					.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toList()));
29870 amit.gupta 707
			for (Map.Entry<Integer, List<PrebookingOrder>> fofoMapEntry : fofoMap.entrySet()) {
708
				int fofoId = fofoMapEntry.getKey();
709
				int totalGrnCount = inventoryItemRepository.selectByFofoIdItemIds(fofoId, itemIds).size();
710
				List<PrebookingOrder> partnerBookings = fofoMapEntry.getValue();
711
				for (PrebookingOrder partnerBooking : partnerBookings) {
29893 tejbeer 712
					if (prebookingCleared.get(partnerBooking.getId())) {
29870 amit.gupta 713
						totalGrnCount--;
29893 tejbeer 714
						if (totalGrnCount < 0) {
715
							totalGrnCount = 0;
716
							LOGGER.info("FofoId {}, No Grn But Refunded prebooking id {}", fofoId,
717
									partnerBooking.getId());
29870 amit.gupta 718
							break;
719
						}
720
					}
721
				}
29893 tejbeer 722
 
723
				long toBeRefunded = partnerBookings.stream().filter(x -> !prebookingCleared.get(x.getId()))
724
						.limit(totalGrnCount).count();
725
				LOGGER.info("FofoId {}, Remaining Grn {}, toBeRefunded Prebooking {}", fofoId, totalGrnCount,
726
						toBeRefunded);
727
				partnerBookings.stream().filter(x -> !prebookingCleared.get(x.getId()))
728
						.filter(x -> x.getCreateTimestamp().getYear() == 2022).limit(totalGrnCount).forEach(x -> {
729
							try {
730
								purchaseService.sendPrebookingNotifyMessage(x);
731
							} catch (Exception e) {
732
								LOGGER.info("could not notify");
733
							}
734
						});
735
 
29870 amit.gupta 736
			}
737
		}
26033 amit.gupta 738
	}
26092 amit.gupta 739
 
26299 amit.gupta 740
	public void fixGrn() throws Exception {
26092 amit.gupta 741
		List<Purchase> incompletePurchases = purchaseRepository.selectIncompletePurchase();
26299 amit.gupta 742
		for (Purchase incompletePurchase : incompletePurchases) {
743
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(
744
					incompletePurchase.getPurchaseReference(), incompletePurchase.getFofoId());
26093 amit.gupta 745
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(incompletePurchase.getId());
746
			Map<Integer, Integer> grnedItems = inventoryItems.stream().collect(
26299 amit.gupta 747
					Collectors.groupingBy(x -> x.getItemId(), Collectors.summingInt(x -> x.getInitialQuantity())));
748
			Map<Integer, Integer> billedItems = orders.stream().collect(Collectors.groupingBy(
749
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
750
			for (Integer billedItemId : billedItems.keySet()) {
751
				if (grnedItems.containsKey(billedItemId)) {
752
					if (grnedItems.get(billedItemId) > billedItems.get(billedItemId)) {
753
						LOGGER.info("Billed Qty {} ---- Grned {}, ItemId {}, Invoice Number {}({}), Grn Date {}",
754
								billedItems.get(billedItemId), grnedItems.get(billedItemId), billedItemId,
755
								incompletePurchase.getPurchaseReference(), incompletePurchase.getId(),
756
								incompletePurchase.getCreateTimestamp());
26095 amit.gupta 757
						Item item = itemRepository.selectById(billedItemId);
26299 amit.gupta 758
						if (item.getType().equals(ItemType.SERIALIZED)) {
759
 
26096 amit.gupta 760
						} else {
26299 amit.gupta 761
							for (InventoryItem inventoryItem : inventoryItems) {
762
								if (inventoryItem.getItemId() == billedItemId && inventoryItem.getGoodQuantity() == 0) {
763
									List<ScanRecord> scanRecords = scanRecordRepository
764
											.selectByInventoryItemId(inventoryItem.getId());
765
									if (scanRecords.size() == 1 && scanRecords.get(0).getQuantity() == 0) {
26096 amit.gupta 766
										LOGGER.info("Safe to remove InventoryItem Id {}", inventoryItem.getId());
26101 amit.gupta 767
										scanRecordRepository.delete(scanRecords.get(0));
768
										inventoryItemRepository.delete(inventoryItem);
26299 amit.gupta 769
										incompletePurchase.setUnfullfilledNonSerializedQuantity(
770
												incompletePurchase.getUnfullfilledNonSerializedQuantity()
771
														+ inventoryItem.getInitialQuantity());
26096 amit.gupta 772
									}
773
								}
774
							}
26095 amit.gupta 775
						}
26093 amit.gupta 776
					}
777
				}
26092 amit.gupta 778
			}
26299 amit.gupta 779
 
26092 amit.gupta 780
		}
26299 amit.gupta 781
 
26092 amit.gupta 782
	}
26265 amit.gupta 783
 
784
	public void fixDupGrns() throws Exception {
26412 amit.gupta 785
		List<Integer> duplicatePurchaseIds = Arrays.asList(14984);
26299 amit.gupta 786
		for (int duplicatePurchaseId : duplicatePurchaseIds) {
26265 amit.gupta 787
			Purchase purchase = purchaseRepository.selectById(duplicatePurchaseId);
788
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(duplicatePurchaseId);
26299 amit.gupta 789
			if (inventoryItems.size() == 0) {
26266 amit.gupta 790
				LOGGER.info("Could not find InventoryItems for {}", duplicatePurchaseId);
791
				continue;
792
			}
26299 amit.gupta 793
			schemeService.rollbackSchemes(inventoryItems.stream().map(x -> x.getId()).collect(Collectors.toList()),
794
					duplicatePurchaseId,
795
					"Rolled back duplicate grn for Purchase Invoice " + purchase.getPurchaseReference());
796
			for (InventoryItem inventoryItem : inventoryItems) {
26265 amit.gupta 797
				inventoryItemRepository.delete(inventoryItem);
798
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId());
26299 amit.gupta 799
				for (ScanRecord scanRecord : scanRecords) {
26265 amit.gupta 800
					scanRecordRepository.delete(scanRecord);
801
				}
26299 amit.gupta 802
				List<SchemeInOut> sios = schemeInOutRepository
803
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
804
				for (SchemeInOut sio : sios) {
26265 amit.gupta 805
					LOGGER.info("SIO - {}", sio);
806
					schemeInOutRepository.delete(sio);
807
				}
26299 amit.gupta 808
 
26265 amit.gupta 809
			}
810
		}
26299 amit.gupta 811
		// throw new Exception();
26265 amit.gupta 812
	}
26579 amit.gupta 813
 
814
	public void mongom() {
815
		List<TagListing> tls = tagListingRepository.selectAll(false);
816
		Set<Integer> itemIds = tls.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
817
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId())
818
				.collect(Collectors.toSet());
819
		for (int catalogId : catalogIds) {
820
			try {
821
				ContentPojo cp = mongoClient.getEntityById(catalogId);
26580 amit.gupta 822
				try {
823
					cp.setIconImageUrl(cp.getIconImageUrl().replace("saholic", "smartdukaan"));
26759 amit.gupta 824
				} catch (Exception e) {
825
 
26580 amit.gupta 826
				}
26759 amit.gupta 827
 
26580 amit.gupta 828
				try {
829
					cp.setThumbnailImageUrl(cp.getThumbnailImageUrl().replace("saholic", "smartdukaan"));
26759 amit.gupta 830
				} catch (Exception e) {
831
 
26580 amit.gupta 832
				}
26759 amit.gupta 833
 
26579 amit.gupta 834
				cp.setDefaultImageUrl(cp.getDefaultImageUrl().replace("saholic", "smartdukaan"));
835
				List<MediaPojo> mPojos = cp.getImages();
26759 amit.gupta 836
				if (mPojos != null) {
26580 amit.gupta 837
					mPojos.stream().forEach(mPojo -> {
838
						mPojo.setUrl(mPojo.getUrl().replace("saholic", "smartdukaan"));
839
					});
840
				}
26579 amit.gupta 841
				mongoClient.persistEntity(cp);
842
			} catch (Exception e) {
843
				continue;
844
			}
845
		}
846
	}
26759 amit.gupta 847
 
848
	public void cancelDn(String debitNoteNumber) throws Exception {
849
		DebitNote debitNote = debitNoteRepository.selectDebitNoteByNumber(debitNoteNumber);
26928 amit.gupta 850
 
851
		List<PurchaseReturnItem> purchaseReturnItems = purchaseReturnItemRepository
852
				.selectAllByDebitNoteId(debitNote.getId());
26759 amit.gupta 853
		// Select all inventory Item
854
		Set<Integer> inventoryItemIds = purchaseReturnItems.stream().map(x -> x.getInventoryItemId())
855
				.collect(Collectors.toSet());
856
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds);
857
		for (InventoryItem inventoryItem : inventoryItems) {
858
			if (!StringUtils.isEmpty(inventoryItem.getSerialNumber())) {
859
				inventoryItem.setGoodQuantity(1);
860
				inventoryItem.setLastScanType(ScanType.PURCHASE);
861
				ScanRecord sr = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId()).stream()
862
						.filter(x -> x.getType().equals(ScanType.PURCHASE_RET)).findFirst().get();
863
				scanRecordRepository.delete(sr);
864
				CurrentInventorySnapshot cis = currentInventorySnapshotRepository
865
						.selectByItemAndFofoId(inventoryItem.getItemId(), inventoryItem.getFofoId());
866
				if (cis == null) {
867
					cis = new CurrentInventorySnapshot();
868
					cis.setFofoId(inventoryItem.getFofoId());
869
					cis.setItemId(inventoryItem.getId());
870
					currentInventorySnapshotRepository.persist(cis);
871
				}
872
				cis.setAvailability(cis.getAvailability() + 1);
873
				schemeService.processSchemeIn(inventoryItem.getPurchaseId(), inventoryItem.getFofoId());
874
			}
26928 amit.gupta 875
		}
876
		purchaseReturnItems.stream().forEach(x -> purchaseReturnItemRepository.delete(x));
26759 amit.gupta 877
	}
26799 amit.gupta 878
 
879
	public void processPd(int priceDropId) throws ProfitMandiBusinessException {
27079 amit.gupta 880
		priceDropService.processPriceDrop(priceDropId, false);
26799 amit.gupta 881
	}
26928 amit.gupta 882
 
883
	public void fixScheme() throws Exception {
26936 amit.gupta 884
		LOGGER.info("Partner Types found\tPartnerType To Remove\tAmout to Rollback");
26928 amit.gupta 885
		final Map<Integer, Scheme> schemesMap = schemeRepository.selectAll().stream()
886
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
887
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(LocalDate.of(2019, 9, 1).atTime(0, 0),
888
				LocalDateTime.now());
27221 amit.gupta 889
		Map<SioTuple, Map<PartnerType, List<SchemeInOut>>> schemeTupleMap = sios.stream()
890
				.filter(x -> x.getRolledBackTimestamp() == null)
26928 amit.gupta 891
				.filter(x -> schemesMap.get(x.getSchemeId()).getPartnerType() != PartnerType.ALL)
892
				.collect(Collectors.groupingBy(
893
						x -> new SioTuple(x.getInventoryItemId(), schemesMap.get(x.getSchemeId()).getType()),
27221 amit.gupta 894
						Collectors.groupingBy(x -> schemesMap.get(x.getSchemeId()).getPartnerType(),
895
								Collectors.mapping(x -> x, Collectors.toList()))));
896
 
897
		schemeTupleMap.entrySet().stream().filter(x -> x.getValue().size() > 1).forEach(x -> {
26929 amit.gupta 898
			Map<PartnerType, List<SchemeInOut>> partnerTypeSchemeMap = x.getValue();
27221 amit.gupta 899
			PartnerType partnerTypeToRemove = partnerTypeSchemeMap.keySet().stream()
900
					.min(Comparator.comparing(y -> PartnerType.PartnerTypeRankMap.get(y))).get();
901
			LOGGER.info("{}\t{}\t{}\t{}\t{}\t{}", partnerTypeSchemeMap.keySet(), partnerTypeToRemove,
902
					partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
903
							.collect(Collectors.summingDouble(SchemeInOut::getAmount)),
904
					FormattingUtils.formatDate(partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
905
							.map(y -> y.getCreateTimestamp()).findFirst().get()));
906
 
26928 amit.gupta 907
		});
908
	}
909
 
30310 amit.gupta 910
	@Autowired
911
	GstProAuthService gstProAuthService;
912
 
913
	@Autowired
914
	GstProService gstProService;
915
 
916
	@Autowired
917
	InvoiceService invoiceService;
918
 
30321 amit.gupta 919
	public void updateIrnsToInvoices() {
30310 amit.gupta 920
		try {
921
			invoiceService.updateIrnsToInvoices();
922
		} catch (Throwable t) {
923
			t.printStackTrace();
924
		}
925
	}
926
 
30335 amit.gupta 927
	@Autowired
928
	AmazonPurchaseService amazonPurchaseService;
929
 
30576 amit.gupta 930
	@Autowired
931
	OfferTargetSlabRepository offerTargetSlabRepository;
932
 
30335 amit.gupta 933
	public void amazonPurchase() throws Exception {
934
		amazonPurchaseService.purchaseAmazon("B085M5R82K", 10, 3999);
935
	}
936
 
30576 amit.gupta 937
	@Autowired
938
	ItemCriteriaRepository itemCriteriaRepository;
30335 amit.gupta 939
 
30576 amit.gupta 940
	public void createOfferCriteria() throws Exception {
941
		Map<Integer, List<Integer>> map = new HashMap<>();
942
		map.put(31960, Arrays.asList(57, 69));
943
		map.put(32844, Arrays.asList(57, 69));
944
		map.put(31964, Arrays.asList(65, 78));
945
		map.put(33493, Arrays.asList(70, 84));
946
		map.put(32847, Arrays.asList(65, 78));
947
		map.put(32623, Arrays.asList(72, 86));
948
		map.put(31972, Arrays.asList(74, 88));
949
		map.put(33495, Arrays.asList(78, 93));
950
		map.put(32699, Arrays.asList(78, 93));
951
		map.put(31967, Arrays.asList(78, 93));
952
		map.put(33424, Arrays.asList(86, 103));
953
		map.put(33441, Arrays.asList(94, 113));
954
		map.put(33491, Arrays.asList(102, 123));
955
		map.put(32664, Arrays.asList(94, 112));
956
		map.put(33430, Arrays.asList(159, 181));
957
		map.put(33381, Arrays.asList(172, 195));
958
		map.put(33484, Arrays.asList(184, 209));
959
		map.put(32698, Arrays.asList(171, 194));
960
		map.put(32665, Arrays.asList(171, 194));
961
		map.put(33428, Arrays.asList(146, 166));
962
		map.put(33499, Arrays.asList(196, 223));
963
		map.put(33427, Arrays.asList(184, 208));
964
		map.put(33385, Arrays.asList(203, 230));
965
		map.put(33373, Arrays.asList(196, 222));
966
		map.put(33429, Arrays.asList(171, 193));
967
		map.put(33387, Arrays.asList(215, 244));
968
		map.put(33432, Arrays.asList(208, 236));
969
		map.put(32546, Arrays.asList(196, 222));
970
		map.put(33389, Arrays.asList(227, 257));
971
		map.put(33498, Arrays.asList(233, 264));
972
		map.put(33496, Arrays.asList(202, 229));
973
		map.put(32088, Arrays.asList(233, 264));
974
		map.put(33377, Arrays.asList(233, 264));
975
		map.put(33395, Arrays.asList(327, 392));
976
		map.put(33393, Arrays.asList(344, 413));
977
		map.put(32277, Arrays.asList(360, 432));
978
		map.put(33397, Arrays.asList(377, 452));
979
		map.put(32305, Arrays.asList(393, 472));
980
		map.put(33492, Arrays.asList(409, 491));
981
		map.put(33399, Arrays.asList(409, 491));
982
		map.put(33405, Arrays.asList(442, 531));
983
		map.put(33403, Arrays.asList(442, 531));
984
		map.put(32854, Arrays.asList(442, 531));
985
		map.put(32155, Arrays.asList(458, 550));
986
		map.put(32151, Arrays.asList(458, 550));
987
		map.put(33407, Arrays.asList(475, 570));
988
		map.put(32855, Arrays.asList(475, 570));
989
		map.put(33409, Arrays.asList(655, 786));
990
		map.put(33411, Arrays.asList(688, 825));
991
		map.put(32687, Arrays.asList(688, 825));
992
		map.put(33413, Arrays.asList(720, 865));
993
		map.put(33415, Arrays.asList(1032, 1238));
994
		map.put(33417, Arrays.asList(1097, 1316));
995
 
996
		Offer offer = offerRepository.selectById(1099);
997
		List<TargetSlab> targetSlabs = offerTargetSlabRepository.getByOfferId(offer.getId());
998
		ItemCriteria itemCriteria = targetSlabs.get(0).getItemCriteriaPayouts().get(0).getItemCriteria();
999
 
1000
		Map<List<Integer>, List<Integer>> payoutModelsMap = map.entrySet().stream().map(x ->
1001
		{
1002
			try {
1003
				int catalogId = itemRepository.selectById(x.getKey()).getCatalogItemId();
1004
				return new AbstractMap.SimpleEntry<>(catalogId, x.getValue());
1005
			} catch (Exception e) {
1006
				return new AbstractMap.SimpleEntry<>(0, new ArrayList());
1007
			}
1008
		}).collect(Collectors.groupingBy(x -> x.getValue(), Collectors.mapping(x -> x.getKey(), Collectors.toList())));
1009
 
1010
		payoutModelsMap.entrySet().stream().forEach(x ->
1011
		{
1012
			itemCriteria.setCatalogIds(x.getValue());
1013
 
1014
			com.spice.profitmandi.dao.entity.catalog.ItemCriteria itemCriteria1 = new com.spice.profitmandi.dao.entity.catalog.ItemCriteria();
1015
			itemCriteria1.setCriteria(gson.toJson(itemCriteria));
1016
			itemCriteriaRepository.persist(itemCriteria1);
1017
			com.spice.profitmandi.dao.entity.catalog.TargetSlab ts = new com.spice.profitmandi.dao.entity.catalog.TargetSlab();
1018
			ts.setOfferId(offer.getId());
1019
			ts.setAmountType(targetSlabs.get(0).getItemCriteriaPayouts().get(0).getAmountType());
1020
			ts.setPayoutTarget(25);
1021
			ts.setItemCriteriaId(itemCriteria1.getId());
1022
			ts.setPayoutValue(x.getKey().get(0));
1023
			offerTargetSlabRepository.persist(ts);
1024
 
1025
			com.spice.profitmandi.dao.entity.catalog.TargetSlab ts1 = new com.spice.profitmandi.dao.entity.catalog.TargetSlab();
1026
			ts1.setOfferId(offer.getId());
1027
			ts1.setAmountType(targetSlabs.get(0).getItemCriteriaPayouts().get(0).getAmountType());
1028
			ts1.setPayoutTarget(100);
1029
			ts1.setItemCriteriaId(itemCriteria1.getId());
1030
			ts1.setPayoutValue(x.getKey().get(1));
1031
			offerTargetSlabRepository.persist(ts1);
1032
		});
1033
 
1034
	}
1035
 
1036
 
26928 amit.gupta 1037
	private class SioTuple {
1038
		int inventoryId;
1039
		SchemeType schemeType;
1040
 
1041
		public SioTuple(int inventoryItemId, SchemeType schemeType) {
1042
			this.inventoryId = inventoryItemId;
1043
			this.schemeType = schemeType;
1044
		}
1045
 
1046
		public int getInventoryId() {
1047
			return inventoryId;
1048
		}
1049
 
1050
		public void setInventoryId(int inventoryId) {
1051
			this.inventoryId = inventoryId;
1052
		}
1053
 
1054
		public SchemeType getSchemeType() {
1055
			return schemeType;
1056
		}
1057
 
1058
		public void setSchemeType(SchemeType schemeType) {
1059
			this.schemeType = schemeType;
1060
		}
1061
 
1062
		@Override
1063
		public int hashCode() {
1064
			final int prime = 31;
1065
			int result = 1;
1066
			result = prime * result + getOuterType().hashCode();
1067
			result = prime * result + inventoryId;
1068
			result = prime * result + ((schemeType == null) ? 0 : schemeType.hashCode());
1069
			return result;
1070
		}
1071
 
1072
		@Override
1073
		public boolean equals(Object obj) {
1074
			if (this == obj)
1075
				return true;
1076
			if (obj == null)
1077
				return false;
1078
			if (getClass() != obj.getClass())
1079
				return false;
1080
			SioTuple other = (SioTuple) obj;
1081
			if (!getOuterType().equals(other.getOuterType()))
1082
				return false;
1083
			if (inventoryId != other.inventoryId)
1084
				return false;
1085
			if (schemeType != other.schemeType)
1086
				return false;
1087
			return true;
1088
		}
1089
 
1090
		private RunOnceTasks getOuterType() {
1091
			return RunOnceTasks.this;
1092
		}
1093
 
1094
	}
27221 amit.gupta 1095
 
1096
	public void printPendingLeads() {
29863 tejbeer 1097
		LOGGER.info("PENDING LEADES {}", leadRepository.selectLeadsScheduledBetweenDate(null,
1098
				LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4)));
27221 amit.gupta 1099
	}
27277 amit.gupta 1100
 
27286 amit.gupta 1101
	public void removeDuplicateOrders() throws Exception {
27451 tejbeer 1102
		List<String> invoiceNumbers = Arrays.asList(/*
30209 amit.gupta 1103
				 * "DLWE066/1108", "DLWE066/299", "DLWE066/348", "HRFB004/242",
1104
				 * "HRFB004/243", "HRFB004/514", "HRFTB155/29", "HRJND076/1146",
1105
				 * "HRJND076/966", "HRKA134/295", "HRKA134/421", "HRKK091/381",
1106
				 * "HRMGH106/576", "HRSP056/139", "HRYN030/103", "UPGZ019/395",
1107
				 * "UPHRD130/1299", "UPHRD130/456", "UPHRD130/634", "UPLKO063/897",
1108
				 * "UPMRT149/54", "UPSJP119/748", "UPSJP119/980", "UPSTP065/1218",
1109
				 * "UPSTP065/2039", "UPSTP090/437", "UPSTP120/164",
1110
				 */
27312 amit.gupta 1111
				"HRMGH106/1576");
27451 tejbeer 1112
 
27288 amit.gupta 1113
		int totalAmount = 0;
1114
		float saleAmount = 0;
27289 amit.gupta 1115
		float schemeReverseAmount = 0;
27451 tejbeer 1116
		for (String invoiceNumber : invoiceNumbers) {
27281 amit.gupta 1117
			List<FofoOrder> orders = fofoOrderRepository.selectByInvoiceNumberLike(invoiceNumber);
27283 amit.gupta 1118
			orders = orders.stream().skip(1).collect(Collectors.toList());
27286 amit.gupta 1119
			for (FofoOrder fofoOrder : orders) {
27295 amit.gupta 1120
				LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
27286 amit.gupta 1121
				int inventoryItemId = 0;
27288 amit.gupta 1122
				saleAmount += fofoOrder.getTotalAmount();
27297 amit.gupta 1123
				fofoOrderRepository.delete(fofoOrder);
27302 amit.gupta 1124
				LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
27286 amit.gupta 1125
				List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
27451 tejbeer 1126
				List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
1127
						.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
1128
				for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
27297 amit.gupta 1129
					paymentOptionTransactionRepository.delete(paymentOptionTransaction);
27286 amit.gupta 1130
				}
27451 tejbeer 1131
				for (FofoOrderItem foi : fofoOrderItems) {
27302 amit.gupta 1132
					List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
27297 amit.gupta 1133
					fofoOrderItemRepository.delete(foi);
27451 tejbeer 1134
					for (FofoLineItem fli : flis) {
27302 amit.gupta 1135
						inventoryItemId = fli.getInventoryItemId();
27297 amit.gupta 1136
						fofoLineItemRepository.delete(fli);
27286 amit.gupta 1137
					}
1138
				}
27451 tejbeer 1139
				// Rollback entry with reversal reason
1140
				if (fofoOrder.getCreateTimestamp().isAfter(LocalDate.of(2020, 4, 1).atStartOfDay())) {
27293 amit.gupta 1141
					float invoiceSchemeReversalAmount = 0;
27451 tejbeer 1142
					List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository
1143
							.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
1144
					float invoiceWalletAmount = userWalletHistory.stream()
1145
							.collect(Collectors.summingInt(y -> y.getAmount()));
27303 amit.gupta 1146
					totalAmount += invoiceWalletAmount;
27299 amit.gupta 1147
					try {
27451 tejbeer 1148
						walletService.rollbackAmountFromWallet(fofoOrder.getFofoId(), invoiceWalletAmount,
1149
								fofoOrder.getId(), WalletReferenceType.SCHEME_OUT,
1150
								"Same order for Invoice-" + invoiceNumber + "created twice, duplicate invoice rollback",
1151
								fofoOrder.getCancelledTimestamp());
27299 amit.gupta 1152
					} catch (Exception e) {
1153
						LOGGER.info("Failed wallet update Reson [{}]", e.getMessage());
1154
					}
27301 amit.gupta 1155
					LOGGER.info("inventoryItemId - {}", inventoryItemId);
27451 tejbeer 1156
					List<SchemeInOut> schemeInOuts = schemeInOutRepository
1157
							.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId)));
27292 amit.gupta 1158
					Set<Integer> schemeIds = new HashSet<>();
27298 amit.gupta 1159
					Set<Integer> schemeIdsRolledback = new HashSet<>();
27451 tejbeer 1160
					for (SchemeInOut sio : schemeInOuts) {
1161
						if (Math.abs(sio.getCreateTimestamp().until(fofoOrder.getCreateTimestamp(),
1162
								ChronoUnit.MINUTES)) <= 35 && sio.getRolledBackTimestamp() == null) {
27289 amit.gupta 1163
							LOGGER.info(sio);
27451 tejbeer 1164
							if (!schemeIds.contains(sio.getSchemeId())) {
27292 amit.gupta 1165
								schemeIds.add(sio.getSchemeId());
27298 amit.gupta 1166
							} else if (!schemeIdsRolledback.contains(sio.getSchemeId())) {
1167
								schemeIdsRolledback.add(sio.getSchemeId());
27297 amit.gupta 1168
								sio.setRolledBackTimestamp(LocalDateTime.now());
27292 amit.gupta 1169
								schemeReverseAmount += sio.getAmount();
27293 amit.gupta 1170
								invoiceSchemeReversalAmount += sio.getAmount();
27292 amit.gupta 1171
							}
27289 amit.gupta 1172
						}
27286 amit.gupta 1173
					}
27451 tejbeer 1174
					if (Math.abs(invoiceWalletAmount - invoiceSchemeReversalAmount) > 3) {
27303 amit.gupta 1175
						LOGGER.info("No Matchhhh");
1176
					}
27451 tejbeer 1177
					LOGGER.info("invoiceWalletAmount - {}, invoiceSchemeReversalAmount {}", invoiceWalletAmount,
1178
							invoiceSchemeReversalAmount);
1179
				}
27283 amit.gupta 1180
			}
27277 amit.gupta 1181
		}
27451 tejbeer 1182
		LOGGER.info(
1183
				"Total Sale Amount Reversal - {}, Total Wallet Amount Reversal {}, Total Scheme Reversal Amount - {}",
1184
				saleAmount, totalAmount, schemeReverseAmount);
1185
		// throw new Exception();
27277 amit.gupta 1186
	}
27430 amit.gupta 1187
 
27450 tejbeer 1188
	public void createGeofence() throws IOException, ProfitMandiBusinessException {
1189
 
27486 tejbeer 1190
		// List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
1191
		// for (FofoStore fofoStore : fofoStores) {
1192
		// if (fofoStore.getLatitude() != null && fofoStore.getLongitude() != null) {
27503 tejbeer 1193
		CustomRetailer customRetailer = retailerService.getFofoRetailer(175138812);
27486 tejbeer 1194
		OkHttpClient client = new OkHttpClient();
1195
		okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
1196
		JSONObject geofe = new JSONObject();
1197
		JSONArray geofences = new JSONArray();
1198
		JSONObject geometry = new JSONObject();
1199
		JSONObject geo = new JSONObject();
1200
		JSONArray coordinates = new JSONArray();
1201
		ArrayList<Double> crds = new ArrayList<>();
1202
		// crds.add(Double.parseDouble(fofoStore.getLongitude()));
1203
		// crds.add(Double.parseDouble(fofoStore.getLatitude()));
27503 tejbeer 1204
		crds.add(79.739197);
1205
		crds.add(27.961215);
27486 tejbeer 1206
		// crds.add(77.08596155373755);
1207
		// crds.add(28.64944201113976);
1208
		// coordinates.put(fofoStore.getLongitude());
1209
		// coordinates.put(fofoStore.getLatitude());
1210
		geo.put("type", "Point");
1211
		geo.put("coordinates", crds);
1212
		geometry.put("geometry", geo);
1213
		JSONObject metadata = new JSONObject();
27503 tejbeer 1214
		metadata.put("name", customRetailer.getBusinessName());
1215
		metadata.put("city", customRetailer.getAddress().getCity());
1216
		metadata.put("Code", customRetailer.getCode());
27487 tejbeer 1217
		geometry.put("metadata", metadata);
27486 tejbeer 1218
		geometry.put("radius", 200);
27451 tejbeer 1219
 
27486 tejbeer 1220
		geofences.put(geometry);
1221
		geofe.put("geofences", geofences);
1222
		okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
1223
		String authString = "Basic "
1224
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27450 tejbeer 1225
 
27486 tejbeer 1226
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
1227
				.addHeader("Authorization", authString).build();
27450 tejbeer 1228
 
27486 tejbeer 1229
		Response response = client.newCall(request1).execute();
27450 tejbeer 1230
 
27486 tejbeer 1231
		JSONArray ja = new JSONArray(response.body().string());
1232
		LOGGER.info("geofence" + ja);
1233
		LOGGER.info("jalength" + ja.length());
1234
		/*
1235
		 * for (int i = 0; i < ja.length(); i++) { JSONObject c = ja.getJSONObject(i);
1236
		 * String geofenceId = c.getString("geofence_id"); LOGGER.info("geofenceId" +
1237
		 * geofenceId); FofoStoreGeofence fsg = new FofoStoreGeofence();
1238
		 * fsg.setFofoId(customRetailer.getPartnerId()); fsg.setGeofenceId(geofenceId);
1239
		 * fofoStoreGeofenceRepository.persist(fsg); }
30209 amit.gupta 1240
		 *
27486 tejbeer 1241
		 * }
30209 amit.gupta 1242
		 *
27486 tejbeer 1243
		 * }
1244
		 */
27482 tejbeer 1245
 
27462 tejbeer 1246
	}
1247
 
27451 tejbeer 1248
	public void getAllGeofences() throws IOException, ProfitMandiBusinessException {
27450 tejbeer 1249
 
1250
		OkHttpClient client = new OkHttpClient();
1251
 
1252
		String authString = "Basic "
1253
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
1254
 
1255
		// Get geofences created for all app users
1256
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences")
1257
				.addHeader("Authorization", authString).build();
1258
 
1259
		Response response = client.newCall(request1).execute();
27451 tejbeer 1260
 
27450 tejbeer 1261
		LOGGER.info("response" + response.body().string());
1262
	}
1263
 
27457 tejbeer 1264
	public void deleteGeofences(List<String> geofenceIds) throws IOException, ProfitMandiBusinessException {
1265
		OkHttpClient client = new OkHttpClient();
1266
 
1267
		String authString = "Basic "
1268
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
1269
 
1270
		for (String geofenceId : geofenceIds) {
27460 tejbeer 1271
			Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences/" + geofenceId)
27457 tejbeer 1272
					.delete().addHeader("Authorization", authString).build();
1273
			LOGGER.info("geofenceId" + geofenceId);
1274
			Response response = client.newCall(request1).execute();
1275
 
27460 tejbeer 1276
			LOGGER.info("response" + response.body().string());
27457 tejbeer 1277
		}
1278
 
1279
	}
1280
 
27430 amit.gupta 1281
	public void processSchemeOut(int fofoId, int orderId) throws Exception {
1282
		schemeService.processSchemeOut(orderId, fofoId);
27451 tejbeer 1283
 
27430 amit.gupta 1284
	}
27511 amit.gupta 1285
 
1286
	public void createDummyInvoices() {
27787 amit.gupta 1287
		List<WarehouseInventoryItem> lavaInventoryItems = warehouseInventoryItemRepository.getSerialNumbers("Lava",
1288
				LocalDate.of(2020, Month.SEPTEMBER, 1).atStartOfDay(), LocalDateTime.now());
27511 amit.gupta 1289
		LOGGER.info("Lava Inventory Size is {}", lavaInventoryItems.size());
1290
	}
28624 amit.gupta 1291
 
28038 amit.gupta 1292
	@Autowired
1293
	private WarehouseScanRepository warehouseScanRepository;
28046 amit.gupta 1294
 
1295
	@Autowired
1296
	private WarehouseInventoryService warehouseInventoryService;
28624 amit.gupta 1297
 
29860 amit.gupta 1298
	public void genericCreateCurrentInventorySnapshot() throws Exception {
1299
		purchaseService.genericCreateCurrentInventorySnapshot(175138856, 32820, 2);
1300
	}
29867 tejbeer 1301
 
28038 amit.gupta 1302
	public void fixScans() {
1303
		Map<Integer, Integer> inventoryOrderMap = new HashMap<>();
28624 amit.gupta 1304
		inventoryOrderMap.put(348795, 1628598);
1305
		inventoryOrderMap.put(348796, 1628599);
1306
		inventoryOrderMap.put(329854, 1628600);
1307
		inventoryOrderMap.put(334197, 1628602);
1308
		inventoryOrderMap.put(330110, 1628603);
1309
		inventoryOrderMap.put(330111, 1628604);
1310
		inventoryOrderMap.put(332843, 1628605);
1311
		inventoryOrderMap.put(338067, 1628606);
1312
		inventoryOrderMap.put(338974, 1628609);
1313
		inventoryOrderMap.put(338975, 1628610);
1314
		inventoryOrderMap.put(338971, 1628612);
1315
		inventoryOrderMap.put(338588, 1628615);
1316
		inventoryOrderMap.put(368205, 1631619);
1317
		inventoryOrderMap.put(368206, 1631620);
1318
		inventoryOrderMap.put(368207, 1631621);
1319
		inventoryOrderMap.put(368208, 1631622);
1320
		inventoryOrderMap.put(368209, 1631623);
1321
		inventoryOrderMap.put(368211, 1631625);
1322
		inventoryOrderMap.put(368213, 1631627);
1323
		inventoryOrderMap.put(368214, 1631628);
1324
		inventoryOrderMap.put(368203, 1631629);
1325
		inventoryOrderMap.put(368216, 1631630);
1326
		inventoryOrderMap.put(368217, 1631631);
1327
		inventoryOrderMap.put(368218, 1631632);
1328
		inventoryOrderMap.put(368219, 1631633);
1329
		inventoryOrderMap.put(368222, 1631635);
1330
		List<WarehouseScan> scans = warehouseScanRepository
1331
				.selectAllByInventoryItemIds(new ArrayList<>(inventoryOrderMap.keySet()));
1332
		Map<Integer, List<WarehouseScan>> inventoryScansMap = scans.stream()
1333
				.collect(Collectors.groupingBy(WarehouseScan::getInventoryItemId));
1334
 
1335
		for (Map.Entry<Integer, List<WarehouseScan>> mapEntry : inventoryScansMap.entrySet()) {
28038 amit.gupta 1336
			int inventoryItemId = mapEntry.getKey();
28624 amit.gupta 1337
			List<WarehouseScan> duplicateScans = mapEntry.getValue().stream().filter(
30209 amit.gupta 1338
							x -> x.getOrderId() != null && x.getOrderId().equals(inventoryOrderMap.get(inventoryItemId)))
28624 amit.gupta 1339
					.collect(Collectors.toList());
28047 amit.gupta 1340
			WarehouseScan duplicateScan = duplicateScans.stream().skip(1).findFirst().get();
28046 amit.gupta 1341
			warehouseScanRepository.delete(duplicateScan);
1342
			warehouseInventoryService.addQuantity(duplicateScan.getInventoryItemId(), duplicateScan.getQuantity());
28624 amit.gupta 1343
 
28038 amit.gupta 1344
		}
28624 amit.gupta 1345
 
28038 amit.gupta 1346
	}
1347
 
28561 amit.gupta 1348
	public void fixOffer() throws Exception {
28624 amit.gupta 1349
		List<Integer> offerIds = Arrays.asList(228, 241, 242, 243, 244, 253);
1350
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.getWarehouseId() == 7678)
1351
				.map(x -> x.getId()).collect(Collectors.toList());
28563 amit.gupta 1352
		LOGGER.info("UP West Partner Ids - {}", fofoIds);
28624 amit.gupta 1353
		for (int offerId : offerIds) {
1354
			Offer offer = offerRepository.selectById(offerId);
1355
 
28557 amit.gupta 1356
			PartnerCriteria partnerCriteria = gson.fromJson(offer.getPartnerCriteria(), PartnerCriteria.class);
28563 amit.gupta 1357
			LOGGER.info("Offer Partner Ids - {}", partnerCriteria.getFofoIds());
28560 amit.gupta 1358
			for (Integer fofoId : fofoIds) {
28624 amit.gupta 1359
				if (partnerCriteria.getFofoIds().contains(fofoId)) {
1360
					// This shoud be removed
1361
					LOGGER.info("This shoud be removed FofoStore Code - {}",
1362
							fofoStoreRepository.selectByRetailerId(fofoId).getCode());
28557 amit.gupta 1363
					partnerCriteria.getFofoIds().remove(fofoId);
1364
				}
1365
			}
1366
			offer.setPartnerCriteria(gson.toJson(partnerCriteria));
1367
		}
1368
	}
28624 amit.gupta 1369
 
28622 amit.gupta 1370
	public void reverseMaa() throws Exception {
28624 amit.gupta 1371
		Purchase purchase = purchaseRepository.selectById(28877);
1372
		Set<Integer> inventoryItemIds = inventoryItemRepository.selectByPurchaseId(28877).stream().map(x -> x.getId())
1373
				.collect(Collectors.toSet());
1374
		double totalAmount = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIds).stream()
28625 amit.gupta 1375
				/*
1376
				 * .filter(x -> x.getRolledBackTimestamp() == null ||
1377
				 * x.getStatusDescription().contains("investment")) .map(x -> {
1378
				 * x.setRolledBackTimestamp(LocalDateTime.now());
1379
				 * x.setStatus(SchemePayoutStatus.REJECTED); x.
1380
				 * setStatusDescription("Invoice-NSLCK3350 was cancelled, hence all schemes were rolled back"
1381
				 * ); return x; })
1382
				 */
28624 amit.gupta 1383
				.collect(Collectors.summingDouble(x -> x.getAmount()));
1384
		WalletReferenceType walletReferenceType = WalletReferenceType.OTHERS;
1385
		ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(walletReferenceType);
1386
		if (paymentType == null) {
1387
			paymentType = new ManualPaymentType();
1388
			paymentType.setReferenceType(walletReferenceType);
1389
			manualPaymentRequestRepository.persist(paymentType);
1390
		}
1391
		paymentType.setCounter(paymentType.getCounter() + 1);
1392
		int reference = paymentType.getCounter();
28660 amit.gupta 1393
		walletService.consumeAmountFromWallet(purchase.getFofoId(), reference, WalletReferenceType.OTHERS,
1394
				"Invoice-NSLCK3350 was cancelled, hence all schemes were rolled back", (int) totalAmount,
1395
				LocalDateTime.now());
28624 amit.gupta 1396
		LOGGER.info("Total Deduction is around Rs. {}", totalAmount);
28622 amit.gupta 1397
	}
28557 amit.gupta 1398
 
28660 amit.gupta 1399
	public void opporeno() {
1400
		List<Integer> offerIds = Arrays.asList(270, 269, 267, 265, 264, 257, 253, 244, 243, 242, 241, 240, 239, 228,
1401
				227, 226, 225);
1402
		for (Integer offerId : offerIds) {
1403
			Offer offer = offerRepository.selectById(offerId);
1404
			com.spice.profitmandi.service.offers.ItemCriteria itemCriteria = gson.fromJson(offer.getItemCriteria(),
1405
					com.spice.profitmandi.service.offers.ItemCriteria.class);
1406
			if (itemCriteria.getExcludeCatalogIds().contains(1022950)) {
1407
				System.out.println("Excludes reno");
1408
			} else {
1409
				System.out.println("Does not excludes reno.. excluding it");
1410
				itemCriteria.getExcludeCatalogIds().add(1022950);
1411
				offer.setItemCriteria(gson.toJson(itemCriteria));
1412
			}
1413
 
1414
		}
1415
	}
28810 amit.gupta 1416
 
28736 amit.gupta 1417
	@Autowired
1418
	SaholicReservationSnapshotRepository saholicReservationSnapshotRepository;
28810 amit.gupta 1419
 
28736 amit.gupta 1420
	@Autowired
1421
	SaholicInventoryService saholicInventoryService;
28660 amit.gupta 1422
 
28736 amit.gupta 1423
	public void fixReservations() throws Exception {
28810 amit.gupta 1424
		// Clear all Reservations
1425
		saholicInventorySnapshotRepository.selectAll().stream().forEach(x -> x.setReserved(0));
1426
		saholicReservationSnapshotRepository.selectAll().forEach(x -> saholicReservationSnapshotRepository.delete(x));
28736 amit.gupta 1427
		List<Order> orders = orderRepository.selectAllOrderDatesBetweenByStatus(
1428
				LocalDate.now().minusDays(40).atStartOfDay(), LocalDateTime.now(),
1429
				OrderStatus.SUBMITTED_FOR_PROCESSING);
28810 amit.gupta 1430
		for (Order order : orders) {
1431
			SaholicReservationSnapshot saholicReservationSnapshot = saholicReservationSnapshotRepository
1432
					.selectByOrderId(order.getId());
1433
			if (saholicReservationSnapshot == null) {
1434
				saholicInventoryService.addReservationCount(order.getLineItem().getItemId(),
1435
						order.getFulfilmentWarehouseId(), order.getLineItem().getQuantity(), order.getId());
28736 amit.gupta 1436
			}
28810 amit.gupta 1437
		}
28736 amit.gupta 1438
	}
1439
 
28675 amit.gupta 1440
	public void fixOrders() throws Exception {
28736 amit.gupta 1441
		List<Order> orders = orderRepository.selectAllOrderDatesBetweenByStatus(
1442
				LocalDate.now().minusDays(10).atStartOfDay(), LocalDateTime.now(),
1443
				OrderStatus.SUBMITTED_FOR_PROCESSING);
28731 amit.gupta 1444
		orders = orders.stream().filter(x -> x.getCreateTimestamp().isAfter(LocalDateTime.of(2021, 7, 21, 0, 0, 0)))
1445
				.collect(Collectors.toList());
1446
		for (Order order : orders) {
1447
 
28736 amit.gupta 1448
			LineItem lineItem = lineItemRepository.selectById(order.getLineItem().getId());
1449
			if (order.getOrderType() == null) {
1450
				order.setProductCondition(0);
1451
				order.setOrderType(0);
1452
				int itemId = order.getLineItem().getItemId();
1453
				int fulfillmentWarehouseId = order.getFulfilmentWarehouseId();
1454
				System.out.println("Item id " + itemId);
1455
				Item item = itemRepository.selectById(itemId);
1456
 
1457
				VendorItemPricing vendorItemPricing = vendorItemPricingRepository.selectByItemIdAndVendorId(itemId,
1458
						fulfillmentWarehouseId);
1459
				if (vendorItemPricing == null) {
1460
					vendorItemPricing = vendorItemPricingRepository.selectAll(itemId).get(0);
1461
				}
1462
				System.out.println("vendorItemPricing " + vendorItemPricing);
1463
				lineItem.setProductGoup(item.getProductGroup());
1464
				lineItem.setColor(item.getColor());
1465
				lineItem.setNlc(vendorItemPricing.getNlc());
1466
				lineItem.setTransferPrice(vendorItemPricing.getTp());
1467
				lineItem.setLogisticsCost(0f);
1468
				lineItem.setCodCollectionCharges(0f);
1469
 
1470
			}
1471
 
28731 amit.gupta 1472
			int warehouseTo = fofoStoreRepository.selectByRetailerId(order.getRetailerId()).getWarehouseId();
1473
			int itemId = order.getLineItem().getItemId();
28736 amit.gupta 1474
			Warehouse warehouse = transactionService.getFulfilmentWarehouseMap(Arrays.asList(itemId), warehouseTo)
1475
					.get(itemId);
1476
			LOGGER.info(
1477
					"Order Id - {}, WarehouseTo - {}, Item Id - {}, Warehouse From - {}, Fulfilment Warehouse Id - {}",
28732 amit.gupta 1478
					order.getId(), warehouseTo, itemId, warehouse.getBillingWarehouseId(), warehouse.getId());
28733 amit.gupta 1479
			order.setWarehouseId(warehouse.getBillingWarehouseId());
1480
			order.setFulfilmentWarehouseId(warehouse.getId());
28731 amit.gupta 1481
 
28675 amit.gupta 1482
		}
28731 amit.gupta 1483
 
28675 amit.gupta 1484
	}
28810 amit.gupta 1485
 
28808 amit.gupta 1486
	@Autowired
1487
	PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
28675 amit.gupta 1488
 
28808 amit.gupta 1489
	public void addInvestment() {
29863 tejbeer 1490
		List<LocalDate> dates = Arrays.asList(LocalDate.of(2021, 12, 19));
28846 amit.gupta 1491
		// List<Integer> fofoIds = Arrays.asList(175136207, 175138910, 175138967,
1492
		// 175138990, 175138999);
28810 amit.gupta 1493
		for (LocalDate date : dates) {
28808 amit.gupta 1494
			LOGGER.info("Date - {}", date);
28846 amit.gupta 1495
			Map<Integer, PartnerDailyInvestment> investmentMap = partnerDailyInvestmentRepository
1496
					.selectAll(date.plusDays(1)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28808 amit.gupta 1497
			List<PartnerDailyInvestment> investments = partnerDailyInvestmentRepository.selectAll(date.minusDays(1));
28810 amit.gupta 1498
			for (PartnerDailyInvestment investment : investments) {
28846 amit.gupta 1499
				if (investmentMap.get(investment.getFofoId()) == null || (investmentMap.get(investment.getFofoId())
1500
						.getShortPercentage() <= 10) == (investment.getShortPercentage() <= 10)) {
1501
					// Do nothing add investment as is
28811 amit.gupta 1502
				} else {
28808 amit.gupta 1503
					LOGGER.info("Problem with fofo id => {}", investment.getFofoId());
28846 amit.gupta 1504
					// Lets give benefit of doubt
1505
					if (investment.getShortPercentage() > 10) {
28811 amit.gupta 1506
						investment = investmentMap.get(investment.getFofoId());
1507
					}
28808 amit.gupta 1508
				}
28811 amit.gupta 1509
				PartnerDailyInvestment partnerDailyInvestment = new PartnerDailyInvestment();
1510
				partnerDailyInvestment.setActivatedStockAmount(investment.getActivatedStockAmount());
1511
				partnerDailyInvestment.setDate(date);
1512
				partnerDailyInvestment.setFofoId(investment.getFofoId());
1513
				partnerDailyInvestment.setMinInvestment(investment.getMinInvestment());
1514
				partnerDailyInvestment.setGrnPendingAmount(investment.getGrnPendingAmount());
1515
				partnerDailyInvestment.setActivatedStockAmount(investment.getActivatedStockAmount());
1516
				partnerDailyInvestment.setUnbilledAmount(investment.getUnbilledAmount());
1517
				partnerDailyInvestment.setReturnInTransitAmount(investment.getReturnInTransitAmount());
1518
				partnerDailyInvestment.setSalesAmount(investment.getSalesAmount());
1519
				partnerDailyInvestment.setInStockAmount(investment.getInStockAmount());
28823 amit.gupta 1520
				partnerDailyInvestment.setWalletAmount(investment.getWalletAmount());
30576 amit.gupta 1521
				partnerDailyInvestment.setActivatedGrnPendingAmount(investment.getActivatedGrnPendingAmount());
28811 amit.gupta 1522
				partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
28808 amit.gupta 1523
			}
1524
		}
1525
	}
1526
 
28840 amit.gupta 1527
	@Autowired
1528
	BrandRegionMappingRepository brandRegionMappingRepository;
28846 amit.gupta 1529
 
28840 amit.gupta 1530
	public void brandRegion() {
1531
		Set<Integer> warehouseIds = ProfitMandiConstants.WAREHOUSE_MAP.keySet();
28846 amit.gupta 1532
		Map<String, Map<Boolean, List<BrandRegionMapping>>> mapping = brandRegionMappingRepository.selectAll().stream()
1533
				.collect(Collectors.groupingBy(BrandRegionMapping::getBrand,
1534
						Collectors.collectingAndThen(Collectors.toList(),
1535
								x -> x.stream().collect(Collectors.groupingBy(BrandRegionMapping::isAccessory)))));
1536
		for (Map.Entry<String, Map<Boolean, List<BrandRegionMapping>>> entry : mapping.entrySet()) {
28840 amit.gupta 1537
			String brand = entry.getKey();
28846 amit.gupta 1538
			for (Map.Entry<Boolean, List<BrandRegionMapping>> isAccessoryEntry : entry.getValue().entrySet()) {
28840 amit.gupta 1539
				boolean isAccessory = isAccessoryEntry.getKey();
28846 amit.gupta 1540
				Map<Integer, List<Integer>> warehouseToIdsMap = isAccessoryEntry.getValue().stream()
1541
						.collect(Collectors.groupingBy(BrandRegionMapping::getToWarehouseId,
1542
								Collectors.mapping(BrandRegionMapping::getFromWarehouseId, Collectors.toList())));
1543
				for (int warehouseIdTo : warehouseIds) {
28840 amit.gupta 1544
					List<Integer> warehouseIdsFrom = warehouseToIdsMap.get(warehouseIdTo);
28846 amit.gupta 1545
					if (warehouseIdsFrom == null || !warehouseIdsFrom.contains(warehouseIdTo)) {
1546
						LOGGER.info("Missing entries for brand region mapping = {}, {}, {}", brand, isAccessory,
1547
								warehouseIdTo);
1548
 
1549
						BrandRegionMapping brandRegionMapping = new BrandRegionMapping();
1550
						brandRegionMapping.setAccessory(isAccessory);
1551
						brandRegionMapping.setBrand(brand);
1552
						brandRegionMapping.setFromWarehouseId(warehouseIdTo);
1553
						brandRegionMapping.setToWarehouseId(warehouseIdTo);
1554
						brandRegionMappingRepository.persist(brandRegionMapping);
1555
 
28840 amit.gupta 1556
					}
1557
				}
1558
			}
1559
		}
1560
	}
1561
 
29556 amit.gupta 1562
	public void reverseSchemes(String invoiceNumber) throws Exception {
1563
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
29863 tejbeer 1564
		if (fofoOrder.getCancelledTimestamp() != null) {
29563 amit.gupta 1565
			orderService.reverseScheme(fofoOrder);
1566
		}
29556 amit.gupta 1567
	}
1568
 
29709 amit.gupta 1569
	@Autowired
1570
	PartnerTypeChangeService partnerTypeChangeService;
29863 tejbeer 1571
 
29945 amit.gupta 1572
	public void runMe() throws Exception {
1573
		/*System.out.println("runme ==== " + fofoOrderItemRepository.selectSumMopGroupByRetailer(
29863 tejbeer 1574
				LocalDate.of(2021, 11, 1).atStartOfDay(), LocalDate.of(2021, 12, 1).atStartOfDay(), 175138408, false));
29945 amit.gupta 1575
		System.out.println("change " + partnerTypeChangeService.getTypeOnDate(175138408, LocalDate.now()));*/
1576
 
1577
		List<Integer> catalogItemIds = Arrays.asList(1023209, 1023209, 1023208, 1023208, 1023199, 1023199, 1023198, 1023198, 1023200, 1023200, 1023197, 1023196, 1023113, 1023112, 1023194, 1023194, 1023194, 1023193, 1023193, 1023190, 1023190, 1023190, 1023189, 1023189, 1023189, 1023188, 1023188, 1023181, 1023181, 1023180, 1023180, 1023179, 1023179, 1023178, 1023178, 1023183, 1023183, 1023182, 1023182, 1022511, 1023066, 1023164, 1023163, 1023064, 1023174, 1023174, 1023173, 1023173, 1023172, 1023172, 1023171, 1023171, 1023171, 1022765, 1023170, 1023170, 1023166, 1023166, 1023166, 1023012, 1023073, 1023168, 1023167, 1023167, 1023118, 1023118, 1023118, 1023164, 1023163, 1023162, 1022971, 1023161, 1023160, 1023159, 1023158, 1023157, 1023156, 1023058, 1023142, 1023142, 1023141, 1023141, 1023145, 1023145, 1023145, 1023145, 1023144, 1023144, 1023144, 1023144, 1023143, 1023143, 1023143, 1023139, 1023137, 1023135, 1023134, 1023133, 1023130, 1023129, 1023126, 1023125, 1023124, 1023121, 1023128, 1023116, 1023077, 1023102, 1023079, 1023113, 1023113, 1023112, 1023112, 1023110, 1023110, 1023109, 1023109, 1023108, 1023108, 1023107, 1023107, 1022809, 1022871, 1023078, 1023101, 1023103, 1023102, 1023102, 1023100, 1023100, 1023099, 1023099, 1023079, 1023079, 1023078, 1023078, 1023081, 1023081, 1023080, 1023080, 1023080, 1022872, 1023077, 1023077, 1023076, 1023076, 1023076, 1022861, 1022970, 1023074, 1023073, 1023073, 1023072, 1023072, 1023071, 1023071, 1023045, 1023070, 1023070, 1023069, 1023063, 1023063, 1023062, 1023062, 1023061, 1023061, 1023057, 1023056, 1023055, 1023054, 1023053, 1023052, 1023068, 1023068, 1023067, 1023067, 1023066, 1023066, 1023065, 1023065, 1023064, 1023064, 1023059, 1023058, 1023058, 1023059, 1023050, 1023050, 1023049, 1023049, 1023048, 1023048, 1023047, 1023047, 1022845, 1023046, 1023046, 1023045, 1023045, 1022955, 1023044, 1023042, 1023043, 1023043, 1023043, 1023018, 1023017, 1023017, 1023016, 1023016, 1023015, 1023015, 1023041, 1023041, 1023041, 1023040, 1023039, 1023039, 1022769, 1023038, 1023038, 1023037, 1023037, 1023036, 1023036, 1023035, 1023035, 1023027, 1023027, 1023034, 1023034, 1023033, 1023033, 1023031, 1023031, 1023030, 1023029, 1023028, 1022630, 1022630, 1022630, 1023026, 1023013, 1022987, 1022982, 1023019, 1023019, 1022979, 1022978, 1022977, 1023023, 1023022, 1023022, 1023014, 1023014, 1023013, 1023013, 1022956, 1022816, 1023012, 1023012, 1023011, 1023011, 1023010, 1023010, 1023010, 1023009, 1023009, 1023006, 1023006, 1023006, 1023005, 1023005, 1023005, 1023004, 1023004, 1023004, 1023003, 1023003, 1023002, 1023002, 1023001, 1023001, 1022971, 1022970, 1022974, 1022973, 1022976, 1022976, 1022764, 1022782, 1022972, 1022972, 1022971, 1022970, 1022955, 1022956, 1022833, 1022967, 1022967, 1022967, 1022965, 1022965, 1022965, 1022965, 1022963, 1022963, 1022767, 1022962, 1022962, 1022960, 1022960, 1022957, 1022956, 1022956, 1022955, 1022955, 1022955, 1022950, 1022950, 1022944, 1022949, 1022949, 1022784, 1022566, 1022871, 1022947, 1022947, 1022946, 1022946, 1022946, 1022944, 1022944, 1022943, 1022943, 1022941, 1022941, 1022941, 1022800, 1022937, 1022937, 1022936, 1022936, 1022940, 1022940, 1022939, 1022939, 1022938, 1022931, 1022931, 1022930, 1022929, 1022934, 1022934, 1022932, 1022932, 1022783, 1022917, 1022897, 1022896, 1022893, 1022892, 1022888, 1022882, 1022833, 1022928, 1022928, 1022877, 1022877, 1022876, 1022876, 1022842, 1022875, 1022875, 1022874, 1022874, 1022872, 1022872, 1022871, 1022871, 1022809, 1022868, 1022868, 1022868, 1022867, 1022867, 1022867, 1022866, 1022866, 1022866, 1022862, 1022862, 1022862, 1022861, 1022861, 1022861, 1022859, 1022858, 1022808, 1022851, 1022851, 1022851, 1022850, 1022850, 1022850, 1022835, 1022846, 1022846, 1022845, 1022845, 1022844, 1022844, 1022843, 1022843, 1022842, 1022842, 1022841, 1022841, 1022840, 1022840, 1022839, 1022839, 1022799, 1022834, 1022834, 1022833, 1022833, 1022830, 1022830, 1022830, 1022825, 1022825, 1022824, 1022783, 1022817, 1022817, 1022816, 1022816, 1022815, 1022815, 1022814, 1022814, 1022401, 1022402, 1022400, 1022399, 1022813, 1022813, 1022813, 1022813, 1022812, 1022812, 1022812, 1022812, 1022811, 1022811, 1022811, 1022811, 1022811, 1022810, 1022810, 1022810, 1022810, 1022810, 1022809, 1022808, 1022808, 1022806, 1022806, 1022806, 1022805, 1022805, 1022805, 1022804, 1022804, 1022804, 1022803, 1022803, 1022803, 1022802, 1022802, 1022802, 1022802, 1022801, 1022801, 1022801, 1022801, 1022800, 1022800, 1022800, 1022799, 1022799, 1022799, 1022798, 1022798, 1022798, 1022797, 1022797, 1022797, 1022796, 1022796, 1022796, 1022794, 1022793, 1022792, 1022792, 1022792, 1022791, 1022791, 1022791, 1022790, 1022790, 1022790, 1022789, 1022789, 1022789, 1022785, 1022785, 1022788, 1022788, 1022784, 1022784, 1022783, 1022783, 1022782, 1022782, 1022546, 1022546, 1022781, 1022781, 1022781, 1022773, 1021600, 1022779, 1022779, 1022778, 1022774, 1022774, 1022774, 1022773, 1022773, 1022773, 1022770, 1022771, 1022771, 1022770, 1022770, 1022770, 1022769, 1022769, 1022769, 1022759, 1022758, 1022754, 1022753, 1022752, 1022757, 1022757, 1022756, 1022755, 1022767, 1022765, 1022743, 1022742, 1022742, 1022741, 1022741, 1022741, 1022740, 1022740, 1022740, 1022739, 1022739, 1022739, 1022738, 1022738, 1022738, 1022748, 1022748, 1022737, 1022677, 1022736, 1022736, 1022736, 1022735, 1022735, 1022735, 1022734, 1022734, 1022592, 1022705, 1022705, 1022699, 1022699, 1022694, 1022694, 1022693, 1022693, 1022629, 1022461, 1022592, 1022590, 1022590, 1022590, 1022590, 1022582, 1022582, 1022566, 1022565, 1022565, 1022559, 1022559, 1022559, 1022558, 1022558, 1022558, 1022546, 1022546, 1022542, 1022542, 1022541, 1022541, 1022541, 1022521, 1022521, 1022521, 1022521, 1022520, 1022520, 1022520, 1022518, 1022518, 1022518, 1022515, 1022515, 1022515, 1022514, 1022514, 1022514, 1022514, 1022511, 1022511, 1022511, 1022501, 1022501, 1022501, 1022500, 1022500, 1022500, 1021443, 1022467, 1022467, 1022467, 1022467, 1022461, 1022461, 1022465, 1022465, 1022465, 1022443, 1022451, 1022451, 1022451, 1022435, 1022435, 1022419, 1022419, 1022418, 1022418, 1022402, 1022402, 1022402, 1022401, 1022401, 1022401, 1022400, 1022400, 1022400, 1022399, 1022399, 1022399, 1022395, 1022395, 1022392, 1022392, 1015059, 1022361, 1022361, 1022010, 1021600, 1022017, 1022017, 1021848, 1022010, 1022009, 1021848, 1021848, 1021848, 1021958, 1021958, 1021958, 1021443, 1021431, 1021430, 1021429, 1021428, 1021427, 1021425, 1021424, 1021422, 1021421, 1021420, 1021419, 1021417, 1021600, 1015060, 1015061, 1003800, 1015061, 1015059, 1015059, 1015059, 1015060, 1015060, 1015060, 1003800, 1003800, 1003800, 1015061, 1015061);
1578
		for (Integer catalogItemId : catalogItemIds) {
29947 amit.gupta 1579
			try {
1580
 
1581
				ContentPojo cp = mongoClient.getEntityById(catalogItemId);
1582
				System.out.println(cp.getDefaultImageUrl());
1583
			} catch (Exception e) {
1584
				System.out.println("------");
1585
			}
29945 amit.gupta 1586
		}
29709 amit.gupta 1587
	}
1588
 
1589
	public void createOffers(FileInputStream stream) throws Exception {
1590
		offerService.createOffers(stream);
1591
	}
1592
 
1593
	@Autowired
1594
	MandiiService mandiiService;
29863 tejbeer 1595
 
29709 amit.gupta 1596
	@Autowired
29863 tejbeer 1597
	FofoKycRepository fofoKycRepository;
1598
 
1599
	@Autowired
1600
	PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
1601
 
1602
	@Autowired
1603
	DocumentRepository documentRepository;
1604
 
1605
	@Autowired
29709 amit.gupta 1606
	com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
29863 tejbeer 1607
 
1608
	public void mandiiUser(String firstName, String lastName, String pan, String dob, String aadhaar, String gender,
30209 amit.gupta 1609
						   String father) throws Exception {
29709 amit.gupta 1610
		FofoStore fs = fofoStoreRepository.selectByPan(pan);
1611
		CustomRetailer cr = retailerService.getFofoRetailer(fs.getId());
1612
		com.spice.profitmandi.dao.entity.dtr.User dtrUser = dtrUserRepository.selectByEmailId(cr.getEmail());
29863 tejbeer 1613
		MandiiUser mandiiUser = mandiiService.getUser(dtrUser.getFirstName(), dtrUser.getLastName(), father,
1614
				Gender.valueOf(gender), cr.getEmail(), pan, cr.getMobileNumber(), LocalDate.parse(dob),
1615
				cr.getAddress().getLine1() + " " + cr.getAddress().getLine2(), cr.getAddress().getCity(),
1616
				cr.getAddress().getState(), cr.getAddress().getPinCode());
29709 amit.gupta 1617
		mandiiUser.setFatherName(father);
29863 tejbeer 1618
		if (StringUtils.isNotEmpty(firstName)) {
29709 amit.gupta 1619
			mandiiUser.setFirstName(firstName);
1620
			mandiiUser.setLastName(lastName);
1621
		}
29863 tejbeer 1622
		if (StringUtils.isNotEmpty(father)) {
29709 amit.gupta 1623
			mandiiUser.setFatherName(father);
1624
		}
29863 tejbeer 1625
		if (StringUtils.isNotEmpty(aadhaar)) {
29709 amit.gupta 1626
			mandiiUser.setAadharNumber(aadhaar);
1627
		}
1628
		mandiiUser.setGender(Gender.valueOf(gender));
1629
		mandiiService.createAccount(cr.getBusinessName(), mandiiUser);
1630
	}
30209 amit.gupta 1631
 
29924 amit.gupta 1632
	@Autowired
1633
	CreditAccountRepository creditAccountRepository;
30209 amit.gupta 1634
 
29924 amit.gupta 1635
	public void mandiiUsers() throws Exception {
30209 amit.gupta 1636
		List<CreditAccount> creditAccounts = creditAccountRepository.selectAll();
1637
		List<Integer> fofoIds = creditAccounts.stream().filter(x -> x.getGateway().equals(Gateway.MANDII) && (x.getCreditStatus().equals(CreditStatus.UNKNOWN) || x.getCreditStatus().equals(CreditStatus.TO_BE_EVALUATED))).map(x -> x.getFofoId()).collect(Collectors.toList());
29924 amit.gupta 1638
		List<FofoStore> fsList = fofoStoreRepository.selectByRetailerIds(fofoIds);
30209 amit.gupta 1639
		for (FofoStore store : fsList) {
29924 amit.gupta 1640
			this.mandiiUsers(store.getPan());
1641
		}
30209 amit.gupta 1642
 
29924 amit.gupta 1643
	}
29709 amit.gupta 1644
 
29863 tejbeer 1645
	public void mandiiUsers(String pan) throws Exception {
1646
		FofoStore fs = fofoStoreRepository.selectByPan(pan);
1647
 
1648
		PartnerOnBoardingPanel pob = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
1649
		List<FofoKyc> fofoKycs = fofoKycRepository.selectByPartnerOnBoardingId(pob.getId());
1650
		CustomRetailer cr = retailerService.getFofoRetailer(fs.getId());
1651
		com.spice.profitmandi.dao.entity.dtr.User dtrUser = dtrUserRepository.selectByEmailId(cr.getEmail());
29906 tejbeer 1652
		boolean ca = false;
29863 tejbeer 1653
		for (FofoKyc fk : fofoKycs) {
1654
 
1655
			MandiiUser mandiiUser = mandiiService.getUser(fk.getFirstName(), fk.getLastName(), fk.getFatherName(),
1656
					fk.getGender(), fk.getEmail(), pan, fk.getMobile(), fk.getDob(),
1657
					fk.getAddress1() + " " + fk.getAddress2() + " " + fk.getAddress3(), fk.getCity(), fk.getState(),
1658
					fk.getPincode());
1659
 
1660
			LOGGER.info("mandiiUser" + mandiiUser);
1661
 
29906 tejbeer 1662
			ca = mandiiService.createAccount(cr.getBusinessName(), mandiiUser);
1663
 
29863 tejbeer 1664
			Document panDoc = documentRepository.selectById(fk.getPanDoc());
1665
			File fPan = new File(panDoc.getPath() + panDoc.getName());
1666
			String encodeString = encodeFileToBase64Binary(fPan);
1667
 
29869 tejbeer 1668
			mandiiService.documentUpload(pan, fk.getMobile(), "PROPRIETOR_PAN", encodeString, null);
29863 tejbeer 1669
 
1670
			Document adhaarF = documentRepository.selectById(fk.getPoaFront());
1671
			File adharf = new File(adhaarF.getPath() + adhaarF.getName());
1672
			String adhaarFEncodstring = encodeFileToBase64Binary(adharf);
1673
			mandiiService.documentUpload(pan, fk.getMobile(), "AADHAAR", adhaarFEncodstring, "FRONT");
1674
 
1675
			Document adhaarB = documentRepository.selectById(fk.getPoaBack());
1676
			File adharb = new File(adhaarB.getPath() + adhaarF.getName());
1677
			String adhaarBEncodstring = encodeFileToBase64Binary(adharb);
1678
			mandiiService.documentUpload(pan, fk.getMobile(), "AADHAAR", adhaarBEncodstring, "BACK");
1679
 
29906 tejbeer 1680
			if (ca == true) {
1681
				AccountStatusResponseOut accountStatusResponseOut = mandiiService.getStatus(fs.getPan());
29863 tejbeer 1682
 
29906 tejbeer 1683
				this.setCreditAccount(fs.getId(), accountStatusResponseOut);
29893 tejbeer 1684
			}
1685
 
29863 tejbeer 1686
		}
29893 tejbeer 1687
 
29863 tejbeer 1688
	}
1689
 
29893 tejbeer 1690
	private void setCreditAccount(int fofoId, AccountStatusResponseOut accountStatusResponseOut) {
1691
 
1692
		CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fofoId, Gateway.MANDII);
1693
 
1694
		if (creditAccount == null) {
1695
 
1696
			creditAccount = new CreditAccount();
1697
 
1698
			creditAccount.setFofoId(fofoId);
1699
			creditAccount.setGateway(Gateway.MANDII);
1700
 
1701
		}
1702
 
1703
		if (accountStatusResponseOut == null) {
1704
			creditAccount.setCreditStatus(CreditStatus.UNKNOWN);
1705
			creditAccount.setDescription("User company not found");
1706
 
1707
		} else {
1708
			if (accountStatusResponseOut.getSanctionLimit() != null) {
1709
				creditAccount.setSanctionedAmount(accountStatusResponseOut.getSanctionLimit().floatValue());
1710
			} else {
1711
				creditAccount.setSanctionedAmount(0);
1712
			}
1713
 
1714
			creditAccount.setInterestRate(accountStatusResponseOut.getRateOfInterest());
1715
			if (accountStatusResponseOut.getBalanceAmount() != null) {
1716
				creditAccount.setAvailableAmount(accountStatusResponseOut.getBalanceAmount().floatValue());
1717
			} else {
1718
				creditAccount.setAvailableAmount(0);
1719
			}
1720
 
1721
			if (accountStatusResponseOut.getCurrentStage() != null) {
1722
				creditAccount.setDescription(accountStatusResponseOut.getCurrentStage().toString());
1723
			}
1724
			if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.SANCTION_AVAILABLE)) {
1725
				creditAccount.setCreditStatus(CreditStatus.SANCTIONED);
1726
			} else if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.IN_ELIGIBLE)) {
1727
				creditAccount.setCreditStatus(CreditStatus.INELIGIBLE);
1728
			} else {
1729
 
1730
				creditAccount.setCreditStatus(CreditStatus.TO_BE_EVALUATED);
1731
			}
1732
		}
1733
 
1734
		creditAccount.setUpdatedOn(LocalDateTime.now());
1735
		creditAccountRepository.persist(creditAccount);
1736
	}
1737
 
29863 tejbeer 1738
	private static String encodeFileToBase64Binary(File file) throws Exception {
1739
		FileInputStream fileInputStreamReader = new FileInputStream(file);
1740
		byte[] bytes = new byte[(int) file.length()];
1741
		fileInputStreamReader.read(bytes);
1742
		return new String(Base64.getEncoder().encodeToString(bytes));
1743
	}
1744
 
30313 amit.gupta 1745
	public void testIrnLive(String invoiceNumber) throws Exception {
1746
		List<Order> orders = orderRepository.selectByInvoiceNumber(invoiceNumber);
1747
		gstProService.getEInvoice(orders);
1748
	}
30209 amit.gupta 1749
 
30313 amit.gupta 1750
 
25043 amit.gupta 1751
}
1752
 
1753
//7015845171