Subversion Repositories SmartDukaan

Rev

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