Subversion Repositories SmartDukaan

Rev

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