Subversion Repositories SmartDukaan

Rev

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