Subversion Repositories SmartDukaan

Rev

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