Subversion Repositories SmartDukaan

Rev

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