Subversion Repositories SmartDukaan

Rev

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