Subversion Repositories SmartDukaan

Rev

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