Subversion Repositories SmartDukaan

Rev

Rev 29925 | Rev 29947 | 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
 
25023 amit.gupta 497
	public void populateSchemes() {
25021 amit.gupta 498
		List<Integer> list05 = Arrays.asList(29093, 29094, 29095, 29096, 29097, 29098, 29099, 29101, 29102);
499
		List<Integer> list10 = Arrays.asList(29187, 29188);
500
		List<Integer> list13 = Arrays.asList(28095, 28097, 28098, 28101, 28102, 28104, 28106, 28107, 28108, 28227,
501
				28228, 28229, 28231, 29055, 29056, 29066, 29079);
502
		List<Integer> list15 = Arrays.asList(20891, 27938, 27939, 27940, 27941, 27943, 27947, 27948, 27953, 27954,
503
				27955, 28220, 28467, 29020, 29033, 29034, 29035, 29592, 29886, 29890, 29891, 29941, 29942, 27445, 27958,
504
				27960, 27961);
505
		List<Integer> list18 = Arrays.asList(28137, 28138, 28140, 28157, 28158, 28161, 28162, 28163, 28164, 28176,
506
				28177, 28178, 28199, 28200, 28208, 28209, 28210, 28211, 28215, 28216, 28217, 28230, 28380, 28381, 28382,
507
				28383, 28384, 28385, 28386, 28387, 28388, 28389, 28390, 28391, 28392, 28395, 28461, 28462, 28463, 28464,
508
				28465, 28466, 28488, 28489, 28490, 28491, 28564, 28565, 28762, 28773, 28871, 28872, 28873, 28874, 28880,
509
				28881, 28914, 28915, 28916, 28917, 28918, 28919, 28920, 29046, 29047, 29048, 29068, 29069, 29110, 29111,
510
				29112, 29113, 29114, 29115, 29116, 29117, 29207, 29208, 29217, 29218, 29225, 29474, 29475, 29476, 29477,
511
				29478, 29479, 29483, 29485, 29486, 29487, 29488, 29739, 29740, 29741, 29742, 29743, 29744, 29745, 29746,
512
				29747, 29748, 29749, 29753, 29756, 29757, 29758, 29760, 29761, 29762, 29763, 29764, 29765, 29766, 29767,
513
				29779, 29780, 29781, 29792, 29793, 29828, 29829, 29830, 29879, 29880, 29881, 29882, 29951);
514
		List<Integer> list20 = Arrays.asList(27975, 27976, 28091, 28363, 29023, 29024, 29025);
515
		List<Integer> list25 = Arrays.asList(28763, 28764, 28765, 29152, 29154, 29157, 29209, 29210, 29601, 29602,
516
				29720, 29721, 29722, 29723, 29725, 29726, 29727);
517
		List<Integer> list30 = Arrays.asList(27962, 27963, 27964, 27965, 27966, 27968, 27969, 28328, 28362, 28566,
518
				28567, 28568, 28571, 28572, 29073, 29074, 29075, 29080, 29081, 29120, 29121, 29122, 29124, 29189, 29190,
519
				29191, 29192, 29193, 29194, 29196, 29197, 29198, 29199, 29515, 29516, 29517, 29675, 29676, 29677, 29678,
520
				29679, 29707, 29708, 29794, 29795, 29883, 29884, 29885, 29887, 29888, 29889, 29931, 29932, 29935, 29936,
521
				29937, 29938, 29939, 29940);
522
		List<Integer> list35 = Arrays.asList(27996, 27998, 29067, 29071, 29643, 29644, 29945, 29946, 29987, 29052,
523
				29053, 29078, 29085, 29086, 29567, 29568, 29569, 29570, 29797, 29914, 29915, 29930, 28877, 28878, 29604,
524
				29605, 29606, 29775, 29776, 29777, 29778, 28862, 28863, 28864, 29026, 29103, 29104, 29105, 28979, 28980,
525
				28981, 28982, 28983, 29002, 29003, 29004, 29834, 29835, 29836, 29837, 29943);
526
		List<Integer> list40 = Arrays.asList(29082, 29083, 28766, 28767, 28768, 28769, 28771);
527
		List<Integer> list45 = Arrays.asList(28026, 28027, 28028, 29528, 29529, 29530, 29534, 29535, 29536, 29538,
528
				29755);
529
		List<Integer> list55 = Arrays.asList(28010, 28011, 28015, 28016, 28019, 28240, 28469, 28470, 28471, 28569,
530
				28570, 28674, 28759, 28761, 28909, 28910, 28911, 28912, 28913, 29108, 29109, 29143, 29144, 29145, 29146,
531
				29211, 29212, 29213, 29214, 29482, 29511, 29512, 29521, 29525, 29526, 29527, 29574, 29575, 29576, 29611,
532
				29612, 29616, 29641, 29642, 29728, 29729, 29750, 29771, 29782, 29783, 29784, 29923, 29924, 29944, 29953,
533
				29992, 29994, 27977, 27978, 28092, 28325, 28326, 28327, 28486, 28487, 29148, 29149, 29150, 29151, 29384,
534
				29385, 29386, 29427, 29489, 29518, 29519, 29520, 29577, 29578, 29579, 29580, 29586, 29660, 29661, 29662,
535
				29663, 29769, 29770, 29790, 29791, 29796, 29928, 29929, 29947, 29948, 28093, 28094, 28556, 28557, 28673,
536
				28867, 28868, 28870, 29089, 29090, 29091, 29106, 29107);
537
		List<Integer> list65 = Arrays.asList(28058, 28223, 28224, 28225, 28226, 28329, 29201, 29202, 29203, 29204,
538
				29205, 29206, 29466, 29467, 29468, 29469, 29470, 29471, 29472, 29573);
539
		Map<Float, List<Integer>> m = new HashMap<>();
540
		m.put(0.5f, list05);
541
		m.put(1.0f, list10);
542
		m.put(1.3f, list13);
543
		m.put(1.5f, list15);
544
		m.put(1.8f, list18);
545
		m.put(2.0f, list20);
546
		m.put(2.5f, list25);
547
		m.put(3.0f, list30);
548
		m.put(3.5f, list35);
549
		m.put(4.0f, list40);
550
		m.put(4.5f, list45);
551
		m.put(5.5f, list55);
552
		m.put(6.5f, list65);
553
		for (Map.Entry<Float, List<Integer>> itemsListEntry : m.entrySet()) {
554
			Scheme s1 = getScheme();
555
			s1.setAmount(itemsListEntry.getKey());
556
			schemeRepository.persist(s1);
25034 amit.gupta 557
			for (Integer itemId : itemsListEntry.getValue()) {
25021 amit.gupta 558
				SchemeItem schemeItem = new SchemeItem();
559
				schemeItem.setItemId(itemId);
560
				schemeItem.setSchemeId(s1.getId());
561
				schemeItemRepository.persist(schemeItem);
562
			}
563
		}
25034 amit.gupta 564
 
25021 amit.gupta 565
	}
566
 
567
	private Scheme getScheme() {
568
		Scheme s = new Scheme();
569
		s.setName("List Price Margin");
570
		s.setDescription("List Price Margin");
571
		s.setActiveTimestamp(null);
572
		s.setStartDateTime(LocalDate.of(2019, 6, 1).atStartOfDay());
573
		s.setEndDateTime(LocalDate.of(2019, 7, 1).atStartOfDay());
574
		s.setAmountType(AmountType.PERCENTAGE);
575
		s.setCreateTimestamp(LocalDateTime.now());
576
		s.setExpireTimestamp(null);
577
		s.setCreatedBy(175120474);
578
		return s;
579
	}
580
 
24957 amit.gupta 581
	public void findMismatchesInIndent() throws Exception {
582
		List<Order> allInProcessOrders = orderRepository.selectAllOrder(OrderStatus.SUBMITTED_FOR_PROCESSING);
24967 amit.gupta 583
 
25021 amit.gupta 584
		Map<String, Integer> lineItemWhQtyMap = allInProcessOrders.stream()
25734 amit.gupta 585
				.collect(Collectors.groupingBy(y -> y.getLineItem().getItemId() + "-" + y.getFulfilmentWarehouseId(),
24967 amit.gupta 586
						Collectors.summingInt(y -> y.getLineItem().getQuantity())));
25021 amit.gupta 587
 
588
		lineItemWhQtyMap.forEach((key, value) -> {
589
 
24967 amit.gupta 590
			int itemId = Integer.parseInt(key.split("-")[0]);
591
			int warehouseId = Integer.parseInt(key.split("-")[1]);
25021 amit.gupta 592
			System.out.printf("%d\t%d\t%d\n", itemId, warehouseId, value);
593
			SaholicInventorySnapshot cis = saholicInventorySnapshotRepository.selectByWarehouseIdandItemId(warehouseId,
594
					itemId);
595
			if (cis == null) {
24970 amit.gupta 596
				cis = new SaholicInventorySnapshot();
597
				cis.setItemId(itemId);
598
				cis.setWarehouseId(warehouseId);
599
				cis.setAvailability(0);
600
				saholicInventorySnapshotRepository.persist(cis);
601
			}
24967 amit.gupta 602
			cis.setReserved(value);
603
		});
24953 amit.gupta 604
	}
605
 
25034 amit.gupta 606
	public void fixSchemePayouts() throws Exception {
25524 amit.gupta 607
		LOGGER.info("In fix scheme Payouts");
25522 amit.gupta 608
		LocalDateTime startDate = LocalDate.of(2019, 9, 1).atStartOfDay();
609
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(startDate, LocalDateTime.now());
25530 amit.gupta 610
 
25034 amit.gupta 611
		for (SchemeInOut sio : sios) {
25530 amit.gupta 612
			if (sio.getSchemeId() != 347) {
25523 amit.gupta 613
				LOGGER.info("Skipping {}", sio.getSchemeId());
25522 amit.gupta 614
				continue;
615
			}
25043 amit.gupta 616
			genericRepository.delete(sio);
25522 amit.gupta 617
			InventoryItem ii = inventoryItemRepository.selectById(sio.getInventoryItemId());
618
			UserWallet userWallet = userWalletRepository.selectByRetailerId(ii.getFofoId());
619
			Scheme scheme = schemeRepository.selectById(sio.getSchemeId());
620
			if (scheme.getType().equals(SchemeType.IN)) {
621
				List<UserWalletHistory> historyList = userWalletHistoryRepository
622
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_IN);
623
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 624
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 625
						genericRepository.delete(uwh);
626
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
627
					}
628
				}
629
			} else {
630
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
631
				int orderId = scanRecords.get(0).getOrderId();
632
				List<UserWalletHistory> historyList = userWalletHistoryRepository
633
						.selectAllByreferenceIdandreferenceType(orderId, WalletReferenceType.SCHEME_OUT);
634
				for (UserWalletHistory uwh : historyList) {
25530 amit.gupta 635
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 636
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
637
						genericRepository.delete(uwh);
638
					}
639
				}
640
				List<UserWalletHistory> historyListBroken = userWalletHistoryRepository
25530 amit.gupta 641
						.selectAllByreferenceIdandreferenceType(ii.getPurchaseId(), WalletReferenceType.SCHEME_OUT);
25522 amit.gupta 642
				for (UserWalletHistory uwh : historyListBroken) {
25530 amit.gupta 643
					if (uwh.getTimestamp().isAfter(startDate)) {
25522 amit.gupta 644
						genericRepository.delete(uwh);
645
						userWallet.setAmount(userWallet.getAmount() - uwh.getAmount());
646
					}
647
				}
648
			}
649
 
25530 amit.gupta 650
			// System.out.println("Total Amount Rolled Back is " + totalRollbackAmount);
25516 amit.gupta 651
		}
25589 amit.gupta 652
		scheduledTasks.processScheme(startDate, startDate.plusDays(10), true);
25030 amit.gupta 653
	}
25530 amit.gupta 654
 
655
	public void fixWallet() throws Exception {
656
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
25536 amit.gupta 657
		System.out.println("id\tcode\tactive\tname\tcity\tstate\twallet amount\tsum\twallet amount-sum");
25530 amit.gupta 658
		for (FofoStore fofoStore : fofoStores) {
659
			UserWallet uw = userWalletRepository.selectByRetailerId(fofoStore.getId());
660
			User user = userRepository.selectById(fofoStore.getId());
25749 amit.gupta 661
			if (user == null) {
25533 amit.gupta 662
				LOGGER.info("store does not exist", fofoStore.getCode());
25535 amit.gupta 663
				continue;
25533 amit.gupta 664
			}
25536 amit.gupta 665
			Address address = null;
666
			try {
667
				address = addressRepository.selectById(user.getAddressId());
25749 amit.gupta 668
			} catch (Exception e) {
25536 amit.gupta 669
				LOGGER.info("Could not find address for Store", fofoStore.getCode());
670
				address = new Address();
671
			}
25539 amit.gupta 672
			double sum = userWalletHistoryRepository.selectSumByWallet(uw.getId());
25749 amit.gupta 673
			int calculated = (int) sum;
674
			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(),
675
					fofoStore.isActive(), address.getName(), address.getCity(), address.getState(), uw.getAmount(),
676
					calculated, uw.getAmount() - calculated);
25530 amit.gupta 677
		}
678
	}
25749 amit.gupta 679
 
25734 amit.gupta 680
	public void changeWarehouse() throws Exception {
681
		transactionService.moveWarehouses();
682
	}
25749 amit.gupta 683
 
684
	public void mailDashboardScreenshots() throws Exception {
685
		System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
686
 
25752 amit.gupta 687
		ChromeOptions options = new ChromeOptions();
688
		options.addArguments("--headless");
689
		options.addArguments("--no-sandbox");
690
		options.addArguments("start-maximized");
691
		options.addArguments("disable-infobars");
692
		options.addArguments("--disable-extensions");
693
 
25753 amit.gupta 694
		WebDriver driver = new ChromeDriver(options);
25774 amit.gupta 695
		driver.manage().window().setSize(new Dimension(1600, 900));
25749 amit.gupta 696
		driver.manage().window().maximize();
25752 amit.gupta 697
		// Deleting all the cookies
25749 amit.gupta 698
		driver.manage().deleteAllCookies();
25752 amit.gupta 699
		// Specifiying pageLoadTimeout and Implicit wait
25749 amit.gupta 700
		driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
701
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
25752 amit.gupta 702
 
25749 amit.gupta 703
		Map<String, Set<Integer>> authUserPartnerIdMapping = csService.getAuthUserPartnerIdMapping();
704
		Set<Integer> allPartners = new HashSet<>();
25765 amit.gupta 705
		Map<Integer, File> partnerSnapshotMap = new HashMap<>();
25752 amit.gupta 706
		authUserPartnerIdMapping.values().stream().forEach(x -> allPartners.addAll(x));
25749 amit.gupta 707
		System.out.println(allPartners.size());
25752 amit.gupta 708
		for (int fofoId : allPartners) {
25749 amit.gupta 709
			driver.get("https://partners.smartdukaan.com/12dashboard34?fofoId=" + fofoId);
25765 amit.gupta 710
			File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
711
			partnerSnapshotMap.put(fofoId, file);
25752 amit.gupta 712
 
25749 amit.gupta 713
		}
25752 amit.gupta 714
		for (Map.Entry<String, Set<Integer>> entry : authUserPartnerIdMapping.entrySet()) {
25749 amit.gupta 715
			String email = entry.getKey();
25996 amit.gupta 716
			LOGGER.info("Sending mail start to {}", email);
25749 amit.gupta 717
			Set<Integer> partnerIds = entry.getValue();
718
			StringBuffer body = new StringBuffer();
25769 amit.gupta 719
			Map<Integer, File> emailSnapshotMap = new HashMap<>();
25752 amit.gupta 720
			for (int fofoId : partnerIds) {
25769 amit.gupta 721
				body.append(String.format("<br/><img src=\"cid:%d\"/>", fofoId));
722
				emailSnapshotMap.put(fofoId, partnerSnapshotMap.get(fofoId));
25749 amit.gupta 723
			}
25837 amit.gupta 724
			Utils.sendEmbeddedHtmlMail(mailSender, new String[] { email }, new String[] {},
25752 amit.gupta 725
					String.format("Franchise Screenshots - %s", FormattingUtils.formatDate(LocalDateTime.now())),
25837 amit.gupta 726
					body.toString(), emailSnapshotMap);
25996 amit.gupta 727
			LOGGER.info("Sent mail to {}", email);
25749 amit.gupta 728
		}
729
		driver.quit();
730
	}
29893 tejbeer 731
 
26299 amit.gupta 732
	// Rollout prebooking orders amount in case the order is grned.
26033 amit.gupta 733
	public void pbfix() throws ProfitMandiBusinessException {
29870 amit.gupta 734
		List<PrebookingOrder> prebookingOrders = prebookingOrderRepository.selectAll();
735
		Map<Integer, Boolean> prebookingCleared = new HashMap<>();
736
		prebookingOrders = prebookingOrders.stream().collect(Collectors.toList());
737
		Map<Integer, List<PrebookingOrder>> catalogPrebookingMap = new HashMap<>();
29893 tejbeer 738
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
739
			if (!catalogPrebookingMap.containsKey(prebookingOrder.getCatalogId())) {
29870 amit.gupta 740
				catalogPrebookingMap.put(prebookingOrder.getCatalogId(), new ArrayList<>());
741
			}
742
			catalogPrebookingMap.get(prebookingOrder.getCatalogId()).add(prebookingOrder);
743
			int prebookingId = prebookingOrder.getId();
29893 tejbeer 744
			List<UserWalletHistory> history = walletService.getAllByReference(prebookingOrder.getFofoId(), prebookingId,
745
					WalletReferenceType.PREBOOKING_ORDER);
746
			long totalAmount = history.stream().collect(Collectors.summingLong(x -> x.getAmount()));
747
			// Refund is pending
748
			if (history.size() > 0) {
749
				if (totalAmount < 0) {
29870 amit.gupta 750
					prebookingCleared.put(prebookingId, false);
29893 tejbeer 751
					LOGGER.info("Amount pending for prebooking id " + prebookingId + " amount is " + -totalAmount
752
							+ " catalog id - {}", prebookingOrder.getCatalogId());
29870 amit.gupta 753
				} else {
754
					prebookingCleared.put(prebookingId, true);
26033 amit.gupta 755
				}
29870 amit.gupta 756
			} else {
757
				prebookingCleared.put(prebookingId, true);
758
				LOGGER.info("No entry in wallet for prebooking Id " + prebookingId);
26033 amit.gupta 759
			}
760
		}
29893 tejbeer 761
		for (Map.Entry<Integer, List<PrebookingOrder>> entrySet : catalogPrebookingMap.entrySet()) {
762
			LOGGER.info("Catalog id {}, Size {}", entrySet.getKey(), entrySet.getValue().size());
763
			Set<Integer> itemIds = itemRepository.selectAllByCatalogItemId(entrySet.getKey()).stream()
764
					.map(x -> x.getId()).collect(Collectors.toSet());
29870 amit.gupta 765
			List<PrebookingOrder> prebookings = entrySet.getValue();
29893 tejbeer 766
			Map<Integer, List<PrebookingOrder>> fofoMap = prebookings.stream()
767
					.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toList()));
29870 amit.gupta 768
			for (Map.Entry<Integer, List<PrebookingOrder>> fofoMapEntry : fofoMap.entrySet()) {
769
				int fofoId = fofoMapEntry.getKey();
770
				int totalGrnCount = inventoryItemRepository.selectByFofoIdItemIds(fofoId, itemIds).size();
771
				List<PrebookingOrder> partnerBookings = fofoMapEntry.getValue();
772
				for (PrebookingOrder partnerBooking : partnerBookings) {
29893 tejbeer 773
					if (prebookingCleared.get(partnerBooking.getId())) {
29870 amit.gupta 774
						totalGrnCount--;
29893 tejbeer 775
						if (totalGrnCount < 0) {
776
							totalGrnCount = 0;
777
							LOGGER.info("FofoId {}, No Grn But Refunded prebooking id {}", fofoId,
778
									partnerBooking.getId());
29870 amit.gupta 779
							break;
780
						}
781
					}
782
				}
29893 tejbeer 783
 
784
				long toBeRefunded = partnerBookings.stream().filter(x -> !prebookingCleared.get(x.getId()))
785
						.limit(totalGrnCount).count();
786
				LOGGER.info("FofoId {}, Remaining Grn {}, toBeRefunded Prebooking {}", fofoId, totalGrnCount,
787
						toBeRefunded);
788
				partnerBookings.stream().filter(x -> !prebookingCleared.get(x.getId()))
789
						.filter(x -> x.getCreateTimestamp().getYear() == 2022).limit(totalGrnCount).forEach(x -> {
790
							try {
791
								purchaseService.sendPrebookingNotifyMessage(x);
792
							} catch (Exception e) {
793
								LOGGER.info("could not notify");
794
							}
795
						});
796
 
29870 amit.gupta 797
			}
798
		}
26033 amit.gupta 799
	}
26092 amit.gupta 800
 
26299 amit.gupta 801
	public void fixGrn() throws Exception {
26092 amit.gupta 802
		List<Purchase> incompletePurchases = purchaseRepository.selectIncompletePurchase();
26299 amit.gupta 803
		for (Purchase incompletePurchase : incompletePurchases) {
804
			List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(
805
					incompletePurchase.getPurchaseReference(), incompletePurchase.getFofoId());
26093 amit.gupta 806
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(incompletePurchase.getId());
807
			Map<Integer, Integer> grnedItems = inventoryItems.stream().collect(
26299 amit.gupta 808
					Collectors.groupingBy(x -> x.getItemId(), Collectors.summingInt(x -> x.getInitialQuantity())));
809
			Map<Integer, Integer> billedItems = orders.stream().collect(Collectors.groupingBy(
810
					x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
811
			for (Integer billedItemId : billedItems.keySet()) {
812
				if (grnedItems.containsKey(billedItemId)) {
813
					if (grnedItems.get(billedItemId) > billedItems.get(billedItemId)) {
814
						LOGGER.info("Billed Qty {} ---- Grned {}, ItemId {}, Invoice Number {}({}), Grn Date {}",
815
								billedItems.get(billedItemId), grnedItems.get(billedItemId), billedItemId,
816
								incompletePurchase.getPurchaseReference(), incompletePurchase.getId(),
817
								incompletePurchase.getCreateTimestamp());
26095 amit.gupta 818
						Item item = itemRepository.selectById(billedItemId);
26299 amit.gupta 819
						if (item.getType().equals(ItemType.SERIALIZED)) {
820
 
26096 amit.gupta 821
						} else {
26299 amit.gupta 822
							for (InventoryItem inventoryItem : inventoryItems) {
823
								if (inventoryItem.getItemId() == billedItemId && inventoryItem.getGoodQuantity() == 0) {
824
									List<ScanRecord> scanRecords = scanRecordRepository
825
											.selectByInventoryItemId(inventoryItem.getId());
826
									if (scanRecords.size() == 1 && scanRecords.get(0).getQuantity() == 0) {
26096 amit.gupta 827
										LOGGER.info("Safe to remove InventoryItem Id {}", inventoryItem.getId());
26101 amit.gupta 828
										scanRecordRepository.delete(scanRecords.get(0));
829
										inventoryItemRepository.delete(inventoryItem);
26299 amit.gupta 830
										incompletePurchase.setUnfullfilledNonSerializedQuantity(
831
												incompletePurchase.getUnfullfilledNonSerializedQuantity()
832
														+ inventoryItem.getInitialQuantity());
26096 amit.gupta 833
									}
834
								}
835
							}
26095 amit.gupta 836
						}
26093 amit.gupta 837
					}
838
				}
26092 amit.gupta 839
			}
26299 amit.gupta 840
 
26092 amit.gupta 841
		}
26299 amit.gupta 842
 
26092 amit.gupta 843
	}
26265 amit.gupta 844
 
845
	public void fixDupGrns() throws Exception {
26412 amit.gupta 846
		List<Integer> duplicatePurchaseIds = Arrays.asList(14984);
26299 amit.gupta 847
		for (int duplicatePurchaseId : duplicatePurchaseIds) {
26265 amit.gupta 848
			Purchase purchase = purchaseRepository.selectById(duplicatePurchaseId);
849
			List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(duplicatePurchaseId);
26299 amit.gupta 850
			if (inventoryItems.size() == 0) {
26266 amit.gupta 851
				LOGGER.info("Could not find InventoryItems for {}", duplicatePurchaseId);
852
				continue;
853
			}
26299 amit.gupta 854
			schemeService.rollbackSchemes(inventoryItems.stream().map(x -> x.getId()).collect(Collectors.toList()),
855
					duplicatePurchaseId,
856
					"Rolled back duplicate grn for Purchase Invoice " + purchase.getPurchaseReference());
857
			for (InventoryItem inventoryItem : inventoryItems) {
26265 amit.gupta 858
				inventoryItemRepository.delete(inventoryItem);
859
				List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId());
26299 amit.gupta 860
				for (ScanRecord scanRecord : scanRecords) {
26265 amit.gupta 861
					scanRecordRepository.delete(scanRecord);
862
				}
26299 amit.gupta 863
				List<SchemeInOut> sios = schemeInOutRepository
864
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
865
				for (SchemeInOut sio : sios) {
26265 amit.gupta 866
					LOGGER.info("SIO - {}", sio);
867
					schemeInOutRepository.delete(sio);
868
				}
26299 amit.gupta 869
 
26265 amit.gupta 870
			}
871
		}
26299 amit.gupta 872
		// throw new Exception();
26265 amit.gupta 873
	}
26579 amit.gupta 874
 
875
	public void mongom() {
876
		List<TagListing> tls = tagListingRepository.selectAll(false);
877
		Set<Integer> itemIds = tls.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
878
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId())
879
				.collect(Collectors.toSet());
880
		for (int catalogId : catalogIds) {
881
			try {
882
				ContentPojo cp = mongoClient.getEntityById(catalogId);
26580 amit.gupta 883
				try {
884
					cp.setIconImageUrl(cp.getIconImageUrl().replace("saholic", "smartdukaan"));
26759 amit.gupta 885
				} catch (Exception e) {
886
 
26580 amit.gupta 887
				}
26759 amit.gupta 888
 
26580 amit.gupta 889
				try {
890
					cp.setThumbnailImageUrl(cp.getThumbnailImageUrl().replace("saholic", "smartdukaan"));
26759 amit.gupta 891
				} catch (Exception e) {
892
 
26580 amit.gupta 893
				}
26759 amit.gupta 894
 
26579 amit.gupta 895
				cp.setDefaultImageUrl(cp.getDefaultImageUrl().replace("saholic", "smartdukaan"));
896
				List<MediaPojo> mPojos = cp.getImages();
26759 amit.gupta 897
				if (mPojos != null) {
26580 amit.gupta 898
					mPojos.stream().forEach(mPojo -> {
899
						mPojo.setUrl(mPojo.getUrl().replace("saholic", "smartdukaan"));
900
					});
901
				}
26579 amit.gupta 902
				mongoClient.persistEntity(cp);
903
			} catch (Exception e) {
904
				continue;
905
			}
906
		}
907
	}
26759 amit.gupta 908
 
909
	public void cancelDn(String debitNoteNumber) throws Exception {
910
		DebitNote debitNote = debitNoteRepository.selectDebitNoteByNumber(debitNoteNumber);
26928 amit.gupta 911
 
912
		List<PurchaseReturnItem> purchaseReturnItems = purchaseReturnItemRepository
913
				.selectAllByDebitNoteId(debitNote.getId());
26759 amit.gupta 914
		// Select all inventory Item
915
		Set<Integer> inventoryItemIds = purchaseReturnItems.stream().map(x -> x.getInventoryItemId())
916
				.collect(Collectors.toSet());
917
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds);
918
		for (InventoryItem inventoryItem : inventoryItems) {
919
			if (!StringUtils.isEmpty(inventoryItem.getSerialNumber())) {
920
				inventoryItem.setGoodQuantity(1);
921
				inventoryItem.setLastScanType(ScanType.PURCHASE);
922
				ScanRecord sr = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId()).stream()
923
						.filter(x -> x.getType().equals(ScanType.PURCHASE_RET)).findFirst().get();
924
				scanRecordRepository.delete(sr);
925
				CurrentInventorySnapshot cis = currentInventorySnapshotRepository
926
						.selectByItemAndFofoId(inventoryItem.getItemId(), inventoryItem.getFofoId());
927
				if (cis == null) {
928
					cis = new CurrentInventorySnapshot();
929
					cis.setFofoId(inventoryItem.getFofoId());
930
					cis.setItemId(inventoryItem.getId());
931
					currentInventorySnapshotRepository.persist(cis);
932
				}
933
				cis.setAvailability(cis.getAvailability() + 1);
934
				schemeService.processSchemeIn(inventoryItem.getPurchaseId(), inventoryItem.getFofoId());
935
			}
26928 amit.gupta 936
		}
937
		purchaseReturnItems.stream().forEach(x -> purchaseReturnItemRepository.delete(x));
26759 amit.gupta 938
	}
26799 amit.gupta 939
 
940
	public void processPd(int priceDropId) throws ProfitMandiBusinessException {
27079 amit.gupta 941
		priceDropService.processPriceDrop(priceDropId, false);
26799 amit.gupta 942
	}
26928 amit.gupta 943
 
944
	public void fixScheme() throws Exception {
26936 amit.gupta 945
		LOGGER.info("Partner Types found\tPartnerType To Remove\tAmout to Rollback");
26928 amit.gupta 946
		final Map<Integer, Scheme> schemesMap = schemeRepository.selectAll().stream()
947
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
948
		List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(LocalDate.of(2019, 9, 1).atTime(0, 0),
949
				LocalDateTime.now());
27221 amit.gupta 950
		Map<SioTuple, Map<PartnerType, List<SchemeInOut>>> schemeTupleMap = sios.stream()
951
				.filter(x -> x.getRolledBackTimestamp() == null)
26928 amit.gupta 952
				.filter(x -> schemesMap.get(x.getSchemeId()).getPartnerType() != PartnerType.ALL)
953
				.collect(Collectors.groupingBy(
954
						x -> new SioTuple(x.getInventoryItemId(), schemesMap.get(x.getSchemeId()).getType()),
27221 amit.gupta 955
						Collectors.groupingBy(x -> schemesMap.get(x.getSchemeId()).getPartnerType(),
956
								Collectors.mapping(x -> x, Collectors.toList()))));
957
 
958
		schemeTupleMap.entrySet().stream().filter(x -> x.getValue().size() > 1).forEach(x -> {
26929 amit.gupta 959
			Map<PartnerType, List<SchemeInOut>> partnerTypeSchemeMap = x.getValue();
27221 amit.gupta 960
			PartnerType partnerTypeToRemove = partnerTypeSchemeMap.keySet().stream()
961
					.min(Comparator.comparing(y -> PartnerType.PartnerTypeRankMap.get(y))).get();
962
			LOGGER.info("{}\t{}\t{}\t{}\t{}\t{}", partnerTypeSchemeMap.keySet(), partnerTypeToRemove,
963
					partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
964
							.collect(Collectors.summingDouble(SchemeInOut::getAmount)),
965
					FormattingUtils.formatDate(partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
966
							.map(y -> y.getCreateTimestamp()).findFirst().get()));
967
 
26928 amit.gupta 968
		});
969
	}
970
 
971
	private class SioTuple {
972
		int inventoryId;
973
		SchemeType schemeType;
974
 
975
		public SioTuple(int inventoryItemId, SchemeType schemeType) {
976
			this.inventoryId = inventoryItemId;
977
			this.schemeType = schemeType;
978
		}
979
 
980
		public int getInventoryId() {
981
			return inventoryId;
982
		}
983
 
984
		public void setInventoryId(int inventoryId) {
985
			this.inventoryId = inventoryId;
986
		}
987
 
988
		public SchemeType getSchemeType() {
989
			return schemeType;
990
		}
991
 
992
		public void setSchemeType(SchemeType schemeType) {
993
			this.schemeType = schemeType;
994
		}
995
 
996
		@Override
997
		public int hashCode() {
998
			final int prime = 31;
999
			int result = 1;
1000
			result = prime * result + getOuterType().hashCode();
1001
			result = prime * result + inventoryId;
1002
			result = prime * result + ((schemeType == null) ? 0 : schemeType.hashCode());
1003
			return result;
1004
		}
1005
 
1006
		@Override
1007
		public boolean equals(Object obj) {
1008
			if (this == obj)
1009
				return true;
1010
			if (obj == null)
1011
				return false;
1012
			if (getClass() != obj.getClass())
1013
				return false;
1014
			SioTuple other = (SioTuple) obj;
1015
			if (!getOuterType().equals(other.getOuterType()))
1016
				return false;
1017
			if (inventoryId != other.inventoryId)
1018
				return false;
1019
			if (schemeType != other.schemeType)
1020
				return false;
1021
			return true;
1022
		}
1023
 
1024
		private RunOnceTasks getOuterType() {
1025
			return RunOnceTasks.this;
1026
		}
1027
 
1028
	}
27221 amit.gupta 1029
 
1030
	public void printPendingLeads() {
29863 tejbeer 1031
		LOGGER.info("PENDING LEADES {}", leadRepository.selectLeadsScheduledBetweenDate(null,
1032
				LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4)));
27221 amit.gupta 1033
	}
27277 amit.gupta 1034
 
27286 amit.gupta 1035
	public void removeDuplicateOrders() throws Exception {
27451 tejbeer 1036
		List<String> invoiceNumbers = Arrays.asList(/*
1037
													 * "DLWE066/1108", "DLWE066/299", "DLWE066/348", "HRFB004/242",
1038
													 * "HRFB004/243", "HRFB004/514", "HRFTB155/29", "HRJND076/1146",
1039
													 * "HRJND076/966", "HRKA134/295", "HRKA134/421", "HRKK091/381",
1040
													 * "HRMGH106/576", "HRSP056/139", "HRYN030/103", "UPGZ019/395",
1041
													 * "UPHRD130/1299", "UPHRD130/456", "UPHRD130/634", "UPLKO063/897",
1042
													 * "UPMRT149/54", "UPSJP119/748", "UPSJP119/980", "UPSTP065/1218",
1043
													 * "UPSTP065/2039", "UPSTP090/437", "UPSTP120/164",
1044
													 */
27312 amit.gupta 1045
				"HRMGH106/1576");
27451 tejbeer 1046
 
27288 amit.gupta 1047
		int totalAmount = 0;
1048
		float saleAmount = 0;
27289 amit.gupta 1049
		float schemeReverseAmount = 0;
27451 tejbeer 1050
		for (String invoiceNumber : invoiceNumbers) {
27281 amit.gupta 1051
			List<FofoOrder> orders = fofoOrderRepository.selectByInvoiceNumberLike(invoiceNumber);
27283 amit.gupta 1052
			orders = orders.stream().skip(1).collect(Collectors.toList());
27286 amit.gupta 1053
			for (FofoOrder fofoOrder : orders) {
27295 amit.gupta 1054
				LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
27286 amit.gupta 1055
				int inventoryItemId = 0;
27288 amit.gupta 1056
				saleAmount += fofoOrder.getTotalAmount();
27297 amit.gupta 1057
				fofoOrderRepository.delete(fofoOrder);
27302 amit.gupta 1058
				LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
27286 amit.gupta 1059
				List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
27451 tejbeer 1060
				List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
1061
						.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
1062
				for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
27297 amit.gupta 1063
					paymentOptionTransactionRepository.delete(paymentOptionTransaction);
27286 amit.gupta 1064
				}
27451 tejbeer 1065
				for (FofoOrderItem foi : fofoOrderItems) {
27302 amit.gupta 1066
					List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
27297 amit.gupta 1067
					fofoOrderItemRepository.delete(foi);
27451 tejbeer 1068
					for (FofoLineItem fli : flis) {
27302 amit.gupta 1069
						inventoryItemId = fli.getInventoryItemId();
27297 amit.gupta 1070
						fofoLineItemRepository.delete(fli);
27286 amit.gupta 1071
					}
1072
				}
27451 tejbeer 1073
				// Rollback entry with reversal reason
1074
				if (fofoOrder.getCreateTimestamp().isAfter(LocalDate.of(2020, 4, 1).atStartOfDay())) {
27293 amit.gupta 1075
					float invoiceSchemeReversalAmount = 0;
27451 tejbeer 1076
					List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository
1077
							.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
1078
					float invoiceWalletAmount = userWalletHistory.stream()
1079
							.collect(Collectors.summingInt(y -> y.getAmount()));
27303 amit.gupta 1080
					totalAmount += invoiceWalletAmount;
27299 amit.gupta 1081
					try {
27451 tejbeer 1082
						walletService.rollbackAmountFromWallet(fofoOrder.getFofoId(), invoiceWalletAmount,
1083
								fofoOrder.getId(), WalletReferenceType.SCHEME_OUT,
1084
								"Same order for Invoice-" + invoiceNumber + "created twice, duplicate invoice rollback",
1085
								fofoOrder.getCancelledTimestamp());
27299 amit.gupta 1086
					} catch (Exception e) {
1087
						LOGGER.info("Failed wallet update Reson [{}]", e.getMessage());
1088
					}
27301 amit.gupta 1089
					LOGGER.info("inventoryItemId - {}", inventoryItemId);
27451 tejbeer 1090
					List<SchemeInOut> schemeInOuts = schemeInOutRepository
1091
							.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId)));
27292 amit.gupta 1092
					Set<Integer> schemeIds = new HashSet<>();
27298 amit.gupta 1093
					Set<Integer> schemeIdsRolledback = new HashSet<>();
27451 tejbeer 1094
					for (SchemeInOut sio : schemeInOuts) {
1095
						if (Math.abs(sio.getCreateTimestamp().until(fofoOrder.getCreateTimestamp(),
1096
								ChronoUnit.MINUTES)) <= 35 && sio.getRolledBackTimestamp() == null) {
27289 amit.gupta 1097
							LOGGER.info(sio);
27451 tejbeer 1098
							if (!schemeIds.contains(sio.getSchemeId())) {
27292 amit.gupta 1099
								schemeIds.add(sio.getSchemeId());
27298 amit.gupta 1100
							} else if (!schemeIdsRolledback.contains(sio.getSchemeId())) {
1101
								schemeIdsRolledback.add(sio.getSchemeId());
27297 amit.gupta 1102
								sio.setRolledBackTimestamp(LocalDateTime.now());
27292 amit.gupta 1103
								schemeReverseAmount += sio.getAmount();
27293 amit.gupta 1104
								invoiceSchemeReversalAmount += sio.getAmount();
27292 amit.gupta 1105
							}
27289 amit.gupta 1106
						}
27286 amit.gupta 1107
					}
27451 tejbeer 1108
					if (Math.abs(invoiceWalletAmount - invoiceSchemeReversalAmount) > 3) {
27303 amit.gupta 1109
						LOGGER.info("No Matchhhh");
1110
					}
27451 tejbeer 1111
					LOGGER.info("invoiceWalletAmount - {}, invoiceSchemeReversalAmount {}", invoiceWalletAmount,
1112
							invoiceSchemeReversalAmount);
1113
				}
27283 amit.gupta 1114
			}
27277 amit.gupta 1115
		}
27451 tejbeer 1116
		LOGGER.info(
1117
				"Total Sale Amount Reversal - {}, Total Wallet Amount Reversal {}, Total Scheme Reversal Amount - {}",
1118
				saleAmount, totalAmount, schemeReverseAmount);
1119
		// throw new Exception();
27277 amit.gupta 1120
	}
27430 amit.gupta 1121
 
27450 tejbeer 1122
	public void createGeofence() throws IOException, ProfitMandiBusinessException {
1123
 
27486 tejbeer 1124
		// List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
1125
		// for (FofoStore fofoStore : fofoStores) {
1126
		// if (fofoStore.getLatitude() != null && fofoStore.getLongitude() != null) {
27503 tejbeer 1127
		CustomRetailer customRetailer = retailerService.getFofoRetailer(175138812);
27486 tejbeer 1128
		OkHttpClient client = new OkHttpClient();
1129
		okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
1130
		JSONObject geofe = new JSONObject();
1131
		JSONArray geofences = new JSONArray();
1132
		JSONObject geometry = new JSONObject();
1133
		JSONObject geo = new JSONObject();
1134
		JSONArray coordinates = new JSONArray();
1135
		ArrayList<Double> crds = new ArrayList<>();
1136
		// crds.add(Double.parseDouble(fofoStore.getLongitude()));
1137
		// crds.add(Double.parseDouble(fofoStore.getLatitude()));
27503 tejbeer 1138
		crds.add(79.739197);
1139
		crds.add(27.961215);
27486 tejbeer 1140
		// crds.add(77.08596155373755);
1141
		// crds.add(28.64944201113976);
1142
		// coordinates.put(fofoStore.getLongitude());
1143
		// coordinates.put(fofoStore.getLatitude());
1144
		geo.put("type", "Point");
1145
		geo.put("coordinates", crds);
1146
		geometry.put("geometry", geo);
1147
		JSONObject metadata = new JSONObject();
27503 tejbeer 1148
		metadata.put("name", customRetailer.getBusinessName());
1149
		metadata.put("city", customRetailer.getAddress().getCity());
1150
		metadata.put("Code", customRetailer.getCode());
27487 tejbeer 1151
		geometry.put("metadata", metadata);
27486 tejbeer 1152
		geometry.put("radius", 200);
27451 tejbeer 1153
 
27486 tejbeer 1154
		geofences.put(geometry);
1155
		geofe.put("geofences", geofences);
1156
		okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
1157
		String authString = "Basic "
1158
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27450 tejbeer 1159
 
27486 tejbeer 1160
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
1161
				.addHeader("Authorization", authString).build();
27450 tejbeer 1162
 
27486 tejbeer 1163
		Response response = client.newCall(request1).execute();
27450 tejbeer 1164
 
27486 tejbeer 1165
		JSONArray ja = new JSONArray(response.body().string());
1166
		LOGGER.info("geofence" + ja);
1167
		LOGGER.info("jalength" + ja.length());
1168
		/*
1169
		 * for (int i = 0; i < ja.length(); i++) { JSONObject c = ja.getJSONObject(i);
1170
		 * String geofenceId = c.getString("geofence_id"); LOGGER.info("geofenceId" +
1171
		 * geofenceId); FofoStoreGeofence fsg = new FofoStoreGeofence();
1172
		 * fsg.setFofoId(customRetailer.getPartnerId()); fsg.setGeofenceId(geofenceId);
1173
		 * fofoStoreGeofenceRepository.persist(fsg); }
1174
		 * 
1175
		 * }
1176
		 * 
1177
		 * }
1178
		 */
27482 tejbeer 1179
 
27462 tejbeer 1180
	}
1181
 
27451 tejbeer 1182
	public void getAllGeofences() throws IOException, ProfitMandiBusinessException {
27450 tejbeer 1183
 
1184
		OkHttpClient client = new OkHttpClient();
1185
 
1186
		String authString = "Basic "
1187
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
1188
 
1189
		// Get geofences created for all app users
1190
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences")
1191
				.addHeader("Authorization", authString).build();
1192
 
1193
		Response response = client.newCall(request1).execute();
27451 tejbeer 1194
 
27450 tejbeer 1195
		LOGGER.info("response" + response.body().string());
1196
	}
1197
 
27457 tejbeer 1198
	public void deleteGeofences(List<String> geofenceIds) throws IOException, ProfitMandiBusinessException {
1199
		OkHttpClient client = new OkHttpClient();
1200
 
1201
		String authString = "Basic "
1202
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
1203
 
1204
		for (String geofenceId : geofenceIds) {
27460 tejbeer 1205
			Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences/" + geofenceId)
27457 tejbeer 1206
					.delete().addHeader("Authorization", authString).build();
1207
			LOGGER.info("geofenceId" + geofenceId);
1208
			Response response = client.newCall(request1).execute();
1209
 
27460 tejbeer 1210
			LOGGER.info("response" + response.body().string());
27457 tejbeer 1211
		}
1212
 
1213
	}
1214
 
27430 amit.gupta 1215
	public void processSchemeOut(int fofoId, int orderId) throws Exception {
1216
		schemeService.processSchemeOut(orderId, fofoId);
27451 tejbeer 1217
 
27430 amit.gupta 1218
	}
27511 amit.gupta 1219
 
1220
	public void createDummyInvoices() {
27787 amit.gupta 1221
		List<WarehouseInventoryItem> lavaInventoryItems = warehouseInventoryItemRepository.getSerialNumbers("Lava",
1222
				LocalDate.of(2020, Month.SEPTEMBER, 1).atStartOfDay(), LocalDateTime.now());
27511 amit.gupta 1223
		LOGGER.info("Lava Inventory Size is {}", lavaInventoryItems.size());
1224
	}
28624 amit.gupta 1225
 
28038 amit.gupta 1226
	@Autowired
1227
	private WarehouseScanRepository warehouseScanRepository;
28046 amit.gupta 1228
 
1229
	@Autowired
1230
	private WarehouseInventoryService warehouseInventoryService;
28624 amit.gupta 1231
 
29860 amit.gupta 1232
	public void genericCreateCurrentInventorySnapshot() throws Exception {
1233
		purchaseService.genericCreateCurrentInventorySnapshot(175138856, 32820, 2);
1234
	}
29867 tejbeer 1235
 
28038 amit.gupta 1236
	public void fixScans() {
1237
		Map<Integer, Integer> inventoryOrderMap = new HashMap<>();
28624 amit.gupta 1238
		inventoryOrderMap.put(348795, 1628598);
1239
		inventoryOrderMap.put(348796, 1628599);
1240
		inventoryOrderMap.put(329854, 1628600);
1241
		inventoryOrderMap.put(334197, 1628602);
1242
		inventoryOrderMap.put(330110, 1628603);
1243
		inventoryOrderMap.put(330111, 1628604);
1244
		inventoryOrderMap.put(332843, 1628605);
1245
		inventoryOrderMap.put(338067, 1628606);
1246
		inventoryOrderMap.put(338974, 1628609);
1247
		inventoryOrderMap.put(338975, 1628610);
1248
		inventoryOrderMap.put(338971, 1628612);
1249
		inventoryOrderMap.put(338588, 1628615);
1250
		inventoryOrderMap.put(368205, 1631619);
1251
		inventoryOrderMap.put(368206, 1631620);
1252
		inventoryOrderMap.put(368207, 1631621);
1253
		inventoryOrderMap.put(368208, 1631622);
1254
		inventoryOrderMap.put(368209, 1631623);
1255
		inventoryOrderMap.put(368211, 1631625);
1256
		inventoryOrderMap.put(368213, 1631627);
1257
		inventoryOrderMap.put(368214, 1631628);
1258
		inventoryOrderMap.put(368203, 1631629);
1259
		inventoryOrderMap.put(368216, 1631630);
1260
		inventoryOrderMap.put(368217, 1631631);
1261
		inventoryOrderMap.put(368218, 1631632);
1262
		inventoryOrderMap.put(368219, 1631633);
1263
		inventoryOrderMap.put(368222, 1631635);
1264
		List<WarehouseScan> scans = warehouseScanRepository
1265
				.selectAllByInventoryItemIds(new ArrayList<>(inventoryOrderMap.keySet()));
1266
		Map<Integer, List<WarehouseScan>> inventoryScansMap = scans.stream()
1267
				.collect(Collectors.groupingBy(WarehouseScan::getInventoryItemId));
1268
 
1269
		for (Map.Entry<Integer, List<WarehouseScan>> mapEntry : inventoryScansMap.entrySet()) {
28038 amit.gupta 1270
			int inventoryItemId = mapEntry.getKey();
28624 amit.gupta 1271
			List<WarehouseScan> duplicateScans = mapEntry.getValue().stream().filter(
1272
					x -> x.getOrderId() != null && x.getOrderId().equals(inventoryOrderMap.get(inventoryItemId)))
1273
					.collect(Collectors.toList());
28047 amit.gupta 1274
			WarehouseScan duplicateScan = duplicateScans.stream().skip(1).findFirst().get();
28046 amit.gupta 1275
			warehouseScanRepository.delete(duplicateScan);
1276
			warehouseInventoryService.addQuantity(duplicateScan.getInventoryItemId(), duplicateScan.getQuantity());
28624 amit.gupta 1277
 
28038 amit.gupta 1278
		}
28624 amit.gupta 1279
 
28038 amit.gupta 1280
	}
1281
 
28561 amit.gupta 1282
	public void fixOffer() throws Exception {
28624 amit.gupta 1283
		List<Integer> offerIds = Arrays.asList(228, 241, 242, 243, 244, 253);
1284
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.getWarehouseId() == 7678)
1285
				.map(x -> x.getId()).collect(Collectors.toList());
28563 amit.gupta 1286
		LOGGER.info("UP West Partner Ids - {}", fofoIds);
28624 amit.gupta 1287
		for (int offerId : offerIds) {
1288
			Offer offer = offerRepository.selectById(offerId);
1289
 
28557 amit.gupta 1290
			PartnerCriteria partnerCriteria = gson.fromJson(offer.getPartnerCriteria(), PartnerCriteria.class);
28563 amit.gupta 1291
			LOGGER.info("Offer Partner Ids - {}", partnerCriteria.getFofoIds());
28560 amit.gupta 1292
			for (Integer fofoId : fofoIds) {
28624 amit.gupta 1293
				if (partnerCriteria.getFofoIds().contains(fofoId)) {
1294
					// This shoud be removed
1295
					LOGGER.info("This shoud be removed FofoStore Code - {}",
1296
							fofoStoreRepository.selectByRetailerId(fofoId).getCode());
28557 amit.gupta 1297
					partnerCriteria.getFofoIds().remove(fofoId);
1298
				}
1299
			}
1300
			offer.setPartnerCriteria(gson.toJson(partnerCriteria));
1301
		}
1302
	}
28624 amit.gupta 1303
 
28622 amit.gupta 1304
	public void reverseMaa() throws Exception {
28624 amit.gupta 1305
		Purchase purchase = purchaseRepository.selectById(28877);
1306
		Set<Integer> inventoryItemIds = inventoryItemRepository.selectByPurchaseId(28877).stream().map(x -> x.getId())
1307
				.collect(Collectors.toSet());
1308
		double totalAmount = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIds).stream()
28625 amit.gupta 1309
				/*
1310
				 * .filter(x -> x.getRolledBackTimestamp() == null ||
1311
				 * x.getStatusDescription().contains("investment")) .map(x -> {
1312
				 * x.setRolledBackTimestamp(LocalDateTime.now());
1313
				 * x.setStatus(SchemePayoutStatus.REJECTED); x.
1314
				 * setStatusDescription("Invoice-NSLCK3350 was cancelled, hence all schemes were rolled back"
1315
				 * ); return x; })
1316
				 */
28624 amit.gupta 1317
				.collect(Collectors.summingDouble(x -> x.getAmount()));
1318
		WalletReferenceType walletReferenceType = WalletReferenceType.OTHERS;
1319
		ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(walletReferenceType);
1320
		if (paymentType == null) {
1321
			paymentType = new ManualPaymentType();
1322
			paymentType.setReferenceType(walletReferenceType);
1323
			manualPaymentRequestRepository.persist(paymentType);
1324
		}
1325
		paymentType.setCounter(paymentType.getCounter() + 1);
1326
		int reference = paymentType.getCounter();
28660 amit.gupta 1327
		walletService.consumeAmountFromWallet(purchase.getFofoId(), reference, WalletReferenceType.OTHERS,
1328
				"Invoice-NSLCK3350 was cancelled, hence all schemes were rolled back", (int) totalAmount,
1329
				LocalDateTime.now());
28624 amit.gupta 1330
		LOGGER.info("Total Deduction is around Rs. {}", totalAmount);
28622 amit.gupta 1331
	}
28557 amit.gupta 1332
 
28660 amit.gupta 1333
	public void opporeno() {
1334
		List<Integer> offerIds = Arrays.asList(270, 269, 267, 265, 264, 257, 253, 244, 243, 242, 241, 240, 239, 228,
1335
				227, 226, 225);
1336
		for (Integer offerId : offerIds) {
1337
			Offer offer = offerRepository.selectById(offerId);
1338
			com.spice.profitmandi.service.offers.ItemCriteria itemCriteria = gson.fromJson(offer.getItemCriteria(),
1339
					com.spice.profitmandi.service.offers.ItemCriteria.class);
1340
			if (itemCriteria.getExcludeCatalogIds().contains(1022950)) {
1341
				System.out.println("Excludes reno");
1342
			} else {
1343
				System.out.println("Does not excludes reno.. excluding it");
1344
				itemCriteria.getExcludeCatalogIds().add(1022950);
1345
				offer.setItemCriteria(gson.toJson(itemCriteria));
1346
			}
1347
 
1348
		}
1349
	}
28810 amit.gupta 1350
 
28736 amit.gupta 1351
	@Autowired
1352
	SaholicReservationSnapshotRepository saholicReservationSnapshotRepository;
28810 amit.gupta 1353
 
28736 amit.gupta 1354
	@Autowired
1355
	SaholicInventoryService saholicInventoryService;
28660 amit.gupta 1356
 
28736 amit.gupta 1357
	public void fixReservations() throws Exception {
28810 amit.gupta 1358
		// Clear all Reservations
1359
		saholicInventorySnapshotRepository.selectAll().stream().forEach(x -> x.setReserved(0));
1360
		saholicReservationSnapshotRepository.selectAll().forEach(x -> saholicReservationSnapshotRepository.delete(x));
28736 amit.gupta 1361
		List<Order> orders = orderRepository.selectAllOrderDatesBetweenByStatus(
1362
				LocalDate.now().minusDays(40).atStartOfDay(), LocalDateTime.now(),
1363
				OrderStatus.SUBMITTED_FOR_PROCESSING);
28810 amit.gupta 1364
		for (Order order : orders) {
1365
			SaholicReservationSnapshot saholicReservationSnapshot = saholicReservationSnapshotRepository
1366
					.selectByOrderId(order.getId());
1367
			if (saholicReservationSnapshot == null) {
1368
				saholicInventoryService.addReservationCount(order.getLineItem().getItemId(),
1369
						order.getFulfilmentWarehouseId(), order.getLineItem().getQuantity(), order.getId());
28736 amit.gupta 1370
			}
28810 amit.gupta 1371
		}
28736 amit.gupta 1372
	}
1373
 
28675 amit.gupta 1374
	public void fixOrders() throws Exception {
28736 amit.gupta 1375
		List<Order> orders = orderRepository.selectAllOrderDatesBetweenByStatus(
1376
				LocalDate.now().minusDays(10).atStartOfDay(), LocalDateTime.now(),
1377
				OrderStatus.SUBMITTED_FOR_PROCESSING);
28731 amit.gupta 1378
		orders = orders.stream().filter(x -> x.getCreateTimestamp().isAfter(LocalDateTime.of(2021, 7, 21, 0, 0, 0)))
1379
				.collect(Collectors.toList());
1380
		for (Order order : orders) {
1381
 
28736 amit.gupta 1382
			LineItem lineItem = lineItemRepository.selectById(order.getLineItem().getId());
1383
			if (order.getOrderType() == null) {
1384
				order.setProductCondition(0);
1385
				order.setOrderType(0);
1386
				int itemId = order.getLineItem().getItemId();
1387
				int fulfillmentWarehouseId = order.getFulfilmentWarehouseId();
1388
				System.out.println("Item id " + itemId);
1389
				Item item = itemRepository.selectById(itemId);
1390
 
1391
				VendorItemPricing vendorItemPricing = vendorItemPricingRepository.selectByItemIdAndVendorId(itemId,
1392
						fulfillmentWarehouseId);
1393
				if (vendorItemPricing == null) {
1394
					vendorItemPricing = vendorItemPricingRepository.selectAll(itemId).get(0);
1395
				}
1396
				System.out.println("vendorItemPricing " + vendorItemPricing);
1397
				lineItem.setProductGoup(item.getProductGroup());
1398
				lineItem.setColor(item.getColor());
1399
				lineItem.setNlc(vendorItemPricing.getNlc());
1400
				lineItem.setTransferPrice(vendorItemPricing.getTp());
1401
				lineItem.setLogisticsCost(0f);
1402
				lineItem.setCodCollectionCharges(0f);
1403
 
1404
			}
1405
 
28731 amit.gupta 1406
			int warehouseTo = fofoStoreRepository.selectByRetailerId(order.getRetailerId()).getWarehouseId();
1407
			int itemId = order.getLineItem().getItemId();
28736 amit.gupta 1408
			Warehouse warehouse = transactionService.getFulfilmentWarehouseMap(Arrays.asList(itemId), warehouseTo)
1409
					.get(itemId);
1410
			LOGGER.info(
1411
					"Order Id - {}, WarehouseTo - {}, Item Id - {}, Warehouse From - {}, Fulfilment Warehouse Id - {}",
28732 amit.gupta 1412
					order.getId(), warehouseTo, itemId, warehouse.getBillingWarehouseId(), warehouse.getId());
28733 amit.gupta 1413
			order.setWarehouseId(warehouse.getBillingWarehouseId());
1414
			order.setFulfilmentWarehouseId(warehouse.getId());
28731 amit.gupta 1415
 
28675 amit.gupta 1416
		}
28731 amit.gupta 1417
 
28675 amit.gupta 1418
	}
28810 amit.gupta 1419
 
28808 amit.gupta 1420
	@Autowired
1421
	PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
28675 amit.gupta 1422
 
28808 amit.gupta 1423
	public void addInvestment() {
29863 tejbeer 1424
		List<LocalDate> dates = Arrays.asList(LocalDate.of(2021, 12, 19));
28846 amit.gupta 1425
		// List<Integer> fofoIds = Arrays.asList(175136207, 175138910, 175138967,
1426
		// 175138990, 175138999);
28810 amit.gupta 1427
		for (LocalDate date : dates) {
28808 amit.gupta 1428
			LOGGER.info("Date - {}", date);
28846 amit.gupta 1429
			Map<Integer, PartnerDailyInvestment> investmentMap = partnerDailyInvestmentRepository
1430
					.selectAll(date.plusDays(1)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28808 amit.gupta 1431
			List<PartnerDailyInvestment> investments = partnerDailyInvestmentRepository.selectAll(date.minusDays(1));
28810 amit.gupta 1432
			for (PartnerDailyInvestment investment : investments) {
28846 amit.gupta 1433
				if (investmentMap.get(investment.getFofoId()) == null || (investmentMap.get(investment.getFofoId())
1434
						.getShortPercentage() <= 10) == (investment.getShortPercentage() <= 10)) {
1435
					// Do nothing add investment as is
28811 amit.gupta 1436
				} else {
28808 amit.gupta 1437
					LOGGER.info("Problem with fofo id => {}", investment.getFofoId());
28846 amit.gupta 1438
					// Lets give benefit of doubt
1439
					if (investment.getShortPercentage() > 10) {
28811 amit.gupta 1440
						investment = investmentMap.get(investment.getFofoId());
1441
					}
28808 amit.gupta 1442
				}
28811 amit.gupta 1443
				PartnerDailyInvestment partnerDailyInvestment = new PartnerDailyInvestment();
1444
				partnerDailyInvestment.setActivatedStockAmount(investment.getActivatedStockAmount());
1445
				partnerDailyInvestment.setDate(date);
1446
				partnerDailyInvestment.setFofoId(investment.getFofoId());
1447
				partnerDailyInvestment.setMinInvestment(investment.getMinInvestment());
1448
				partnerDailyInvestment.setGrnPendingAmount(investment.getGrnPendingAmount());
1449
				partnerDailyInvestment.setActivatedStockAmount(investment.getActivatedStockAmount());
1450
				partnerDailyInvestment.setUnbilledAmount(investment.getUnbilledAmount());
1451
				partnerDailyInvestment.setReturnInTransitAmount(investment.getReturnInTransitAmount());
1452
				partnerDailyInvestment.setSalesAmount(investment.getSalesAmount());
1453
				partnerDailyInvestment.setInStockAmount(investment.getInStockAmount());
28823 amit.gupta 1454
				partnerDailyInvestment.setWalletAmount(investment.getWalletAmount());
28811 amit.gupta 1455
				partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
28808 amit.gupta 1456
			}
1457
		}
1458
	}
1459
 
28840 amit.gupta 1460
	@Autowired
1461
	BrandRegionMappingRepository brandRegionMappingRepository;
28846 amit.gupta 1462
 
28840 amit.gupta 1463
	public void brandRegion() {
1464
		Set<Integer> warehouseIds = ProfitMandiConstants.WAREHOUSE_MAP.keySet();
28846 amit.gupta 1465
		Map<String, Map<Boolean, List<BrandRegionMapping>>> mapping = brandRegionMappingRepository.selectAll().stream()
1466
				.collect(Collectors.groupingBy(BrandRegionMapping::getBrand,
1467
						Collectors.collectingAndThen(Collectors.toList(),
1468
								x -> x.stream().collect(Collectors.groupingBy(BrandRegionMapping::isAccessory)))));
1469
		for (Map.Entry<String, Map<Boolean, List<BrandRegionMapping>>> entry : mapping.entrySet()) {
28840 amit.gupta 1470
			String brand = entry.getKey();
28846 amit.gupta 1471
			for (Map.Entry<Boolean, List<BrandRegionMapping>> isAccessoryEntry : entry.getValue().entrySet()) {
28840 amit.gupta 1472
				boolean isAccessory = isAccessoryEntry.getKey();
28846 amit.gupta 1473
				Map<Integer, List<Integer>> warehouseToIdsMap = isAccessoryEntry.getValue().stream()
1474
						.collect(Collectors.groupingBy(BrandRegionMapping::getToWarehouseId,
1475
								Collectors.mapping(BrandRegionMapping::getFromWarehouseId, Collectors.toList())));
1476
				for (int warehouseIdTo : warehouseIds) {
28840 amit.gupta 1477
					List<Integer> warehouseIdsFrom = warehouseToIdsMap.get(warehouseIdTo);
28846 amit.gupta 1478
					if (warehouseIdsFrom == null || !warehouseIdsFrom.contains(warehouseIdTo)) {
1479
						LOGGER.info("Missing entries for brand region mapping = {}, {}, {}", brand, isAccessory,
1480
								warehouseIdTo);
1481
 
1482
						BrandRegionMapping brandRegionMapping = new BrandRegionMapping();
1483
						brandRegionMapping.setAccessory(isAccessory);
1484
						brandRegionMapping.setBrand(brand);
1485
						brandRegionMapping.setFromWarehouseId(warehouseIdTo);
1486
						brandRegionMapping.setToWarehouseId(warehouseIdTo);
1487
						brandRegionMappingRepository.persist(brandRegionMapping);
1488
 
28840 amit.gupta 1489
					}
1490
				}
1491
			}
1492
		}
1493
	}
1494
 
29556 amit.gupta 1495
	public void reverseSchemes(String invoiceNumber) throws Exception {
1496
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
29863 tejbeer 1497
		if (fofoOrder.getCancelledTimestamp() != null) {
29563 amit.gupta 1498
			orderService.reverseScheme(fofoOrder);
1499
		}
29556 amit.gupta 1500
	}
1501
 
29709 amit.gupta 1502
	@Autowired
1503
	PartnerTypeChangeService partnerTypeChangeService;
29863 tejbeer 1504
 
29945 amit.gupta 1505
	public void runMe() throws Exception {
1506
		/*System.out.println("runme ==== " + fofoOrderItemRepository.selectSumMopGroupByRetailer(
29863 tejbeer 1507
				LocalDate.of(2021, 11, 1).atStartOfDay(), LocalDate.of(2021, 12, 1).atStartOfDay(), 175138408, false));
29945 amit.gupta 1508
		System.out.println("change " + partnerTypeChangeService.getTypeOnDate(175138408, LocalDate.now()));*/
1509
 
1510
		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);
1511
		for (Integer catalogItemId : catalogItemIds) {
1512
			ContentPojo cp = mongoClient.getEntityById(catalogItemId);
1513
			System.out.println(cp.getDefaultImageUrl());
1514
		}
29709 amit.gupta 1515
	}
1516
 
1517
	public void createOffers(FileInputStream stream) throws Exception {
1518
		offerService.createOffers(stream);
1519
	}
1520
 
1521
	@Autowired
1522
	MandiiService mandiiService;
29863 tejbeer 1523
 
29709 amit.gupta 1524
	@Autowired
29863 tejbeer 1525
	FofoKycRepository fofoKycRepository;
1526
 
1527
	@Autowired
1528
	PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
1529
 
1530
	@Autowired
1531
	DocumentRepository documentRepository;
1532
 
1533
	@Autowired
29709 amit.gupta 1534
	com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
29863 tejbeer 1535
 
1536
	public void mandiiUser(String firstName, String lastName, String pan, String dob, String aadhaar, String gender,
1537
			String father) throws Exception {
29709 amit.gupta 1538
		FofoStore fs = fofoStoreRepository.selectByPan(pan);
1539
		CustomRetailer cr = retailerService.getFofoRetailer(fs.getId());
1540
		com.spice.profitmandi.dao.entity.dtr.User dtrUser = dtrUserRepository.selectByEmailId(cr.getEmail());
29863 tejbeer 1541
		MandiiUser mandiiUser = mandiiService.getUser(dtrUser.getFirstName(), dtrUser.getLastName(), father,
1542
				Gender.valueOf(gender), cr.getEmail(), pan, cr.getMobileNumber(), LocalDate.parse(dob),
1543
				cr.getAddress().getLine1() + " " + cr.getAddress().getLine2(), cr.getAddress().getCity(),
1544
				cr.getAddress().getState(), cr.getAddress().getPinCode());
29709 amit.gupta 1545
		mandiiUser.setFatherName(father);
29863 tejbeer 1546
		if (StringUtils.isNotEmpty(firstName)) {
29709 amit.gupta 1547
			mandiiUser.setFirstName(firstName);
1548
			mandiiUser.setLastName(lastName);
1549
		}
29863 tejbeer 1550
		if (StringUtils.isNotEmpty(father)) {
29709 amit.gupta 1551
			mandiiUser.setFatherName(father);
1552
		}
29863 tejbeer 1553
		if (StringUtils.isNotEmpty(aadhaar)) {
29709 amit.gupta 1554
			mandiiUser.setAadharNumber(aadhaar);
1555
		}
1556
		mandiiUser.setGender(Gender.valueOf(gender));
1557
		mandiiService.createAccount(cr.getBusinessName(), mandiiUser);
1558
	}
29924 amit.gupta 1559
 
1560
	@Autowired
1561
	CreditAccountRepository creditAccountRepository;
1562
	public void mandiiUsers() throws Exception {
1563
		List<CreditAccount> creditAccounts =  creditAccountRepository.selectAll();
1564
		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());
1565
		List<FofoStore> fsList = fofoStoreRepository.selectByRetailerIds(fofoIds);
1566
		for(FofoStore store : fsList) {
1567
			this.mandiiUsers(store.getPan());
1568
		}
1569
 
1570
	}
29709 amit.gupta 1571
 
29863 tejbeer 1572
	public void mandiiUsers(String pan) throws Exception {
1573
		FofoStore fs = fofoStoreRepository.selectByPan(pan);
1574
 
1575
		PartnerOnBoardingPanel pob = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
1576
		List<FofoKyc> fofoKycs = fofoKycRepository.selectByPartnerOnBoardingId(pob.getId());
1577
		CustomRetailer cr = retailerService.getFofoRetailer(fs.getId());
1578
		com.spice.profitmandi.dao.entity.dtr.User dtrUser = dtrUserRepository.selectByEmailId(cr.getEmail());
29906 tejbeer 1579
		boolean ca = false;
29863 tejbeer 1580
		for (FofoKyc fk : fofoKycs) {
1581
 
1582
			MandiiUser mandiiUser = mandiiService.getUser(fk.getFirstName(), fk.getLastName(), fk.getFatherName(),
1583
					fk.getGender(), fk.getEmail(), pan, fk.getMobile(), fk.getDob(),
1584
					fk.getAddress1() + " " + fk.getAddress2() + " " + fk.getAddress3(), fk.getCity(), fk.getState(),
1585
					fk.getPincode());
1586
 
1587
			LOGGER.info("mandiiUser" + mandiiUser);
1588
 
29906 tejbeer 1589
			ca = mandiiService.createAccount(cr.getBusinessName(), mandiiUser);
1590
 
29863 tejbeer 1591
			Document panDoc = documentRepository.selectById(fk.getPanDoc());
1592
			File fPan = new File(panDoc.getPath() + panDoc.getName());
1593
			String encodeString = encodeFileToBase64Binary(fPan);
1594
 
29869 tejbeer 1595
			mandiiService.documentUpload(pan, fk.getMobile(), "PROPRIETOR_PAN", encodeString, null);
29863 tejbeer 1596
 
1597
			Document adhaarF = documentRepository.selectById(fk.getPoaFront());
1598
			File adharf = new File(adhaarF.getPath() + adhaarF.getName());
1599
			String adhaarFEncodstring = encodeFileToBase64Binary(adharf);
1600
			mandiiService.documentUpload(pan, fk.getMobile(), "AADHAAR", adhaarFEncodstring, "FRONT");
1601
 
1602
			Document adhaarB = documentRepository.selectById(fk.getPoaBack());
1603
			File adharb = new File(adhaarB.getPath() + adhaarF.getName());
1604
			String adhaarBEncodstring = encodeFileToBase64Binary(adharb);
1605
			mandiiService.documentUpload(pan, fk.getMobile(), "AADHAAR", adhaarBEncodstring, "BACK");
1606
 
29906 tejbeer 1607
			if (ca == true) {
1608
				AccountStatusResponseOut accountStatusResponseOut = mandiiService.getStatus(fs.getPan());
29863 tejbeer 1609
 
29906 tejbeer 1610
				this.setCreditAccount(fs.getId(), accountStatusResponseOut);
29893 tejbeer 1611
			}
1612
 
29863 tejbeer 1613
		}
29893 tejbeer 1614
 
29863 tejbeer 1615
	}
1616
 
29893 tejbeer 1617
	private void setCreditAccount(int fofoId, AccountStatusResponseOut accountStatusResponseOut) {
1618
 
1619
		CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fofoId, Gateway.MANDII);
1620
 
1621
		if (creditAccount == null) {
1622
 
1623
			creditAccount = new CreditAccount();
1624
 
1625
			creditAccount.setFofoId(fofoId);
1626
			creditAccount.setGateway(Gateway.MANDII);
1627
 
1628
		}
1629
 
1630
		if (accountStatusResponseOut == null) {
1631
			creditAccount.setCreditStatus(CreditStatus.UNKNOWN);
1632
			creditAccount.setDescription("User company not found");
1633
 
1634
		} else {
1635
			if (accountStatusResponseOut.getSanctionLimit() != null) {
1636
				creditAccount.setSanctionedAmount(accountStatusResponseOut.getSanctionLimit().floatValue());
1637
			} else {
1638
				creditAccount.setSanctionedAmount(0);
1639
			}
1640
 
1641
			creditAccount.setInterestRate(accountStatusResponseOut.getRateOfInterest());
1642
			if (accountStatusResponseOut.getBalanceAmount() != null) {
1643
				creditAccount.setAvailableAmount(accountStatusResponseOut.getBalanceAmount().floatValue());
1644
			} else {
1645
				creditAccount.setAvailableAmount(0);
1646
			}
1647
 
1648
			if (accountStatusResponseOut.getCurrentStage() != null) {
1649
				creditAccount.setDescription(accountStatusResponseOut.getCurrentStage().toString());
1650
			}
1651
			if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.SANCTION_AVAILABLE)) {
1652
				creditAccount.setCreditStatus(CreditStatus.SANCTIONED);
1653
			} else if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.IN_ELIGIBLE)) {
1654
				creditAccount.setCreditStatus(CreditStatus.INELIGIBLE);
1655
			} else {
1656
 
1657
				creditAccount.setCreditStatus(CreditStatus.TO_BE_EVALUATED);
1658
			}
1659
		}
1660
 
1661
		creditAccount.setUpdatedOn(LocalDateTime.now());
1662
		creditAccountRepository.persist(creditAccount);
1663
	}
1664
 
29863 tejbeer 1665
	private static String encodeFileToBase64Binary(File file) throws Exception {
1666
		FileInputStream fileInputStreamReader = new FileInputStream(file);
1667
		byte[] bytes = new byte[(int) file.length()];
1668
		fileInputStreamReader.read(bytes);
1669
		return new String(Base64.getEncoder().encodeToString(bytes));
1670
	}
1671
 
25043 amit.gupta 1672
}
1673
 
1674
//7015845171