Subversion Repositories SmartDukaan

Rev

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