Subversion Repositories SmartDukaan

Rev

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