Subversion Repositories SmartDukaan

Rev

Rev 29893 | Rev 29924 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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