Subversion Repositories SmartDukaan

Rev

Rev 30133 | Rev 30215 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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