Subversion Repositories SmartDukaan

Rev

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