Subversion Repositories SmartDukaan

Rev

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