Subversion Repositories SmartDukaan

Rev

Rev 34946 | Rev 35132 | 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
 
28557 amit.gupta 3
import com.google.gson.Gson;
26214 amit.gupta 4
import com.smartdukaan.cron.scheduled.SamsungIMEIActivationService;
25043 amit.gupta 5
import com.smartdukaan.cron.scheduled.ScheduledTasks;
30335 amit.gupta 6
import com.smartdukaan.cron.scheduled.amazon.shop.AmazonPurchaseService;
32211 amit.gupta 7
import com.smartdukaan.cron.scheduled.amazon.shop.OrderSummary;
8
import com.smartdukaan.cron.scheduled.amazon.shop.model.OrderRow;
34946 ranu 9
import com.smartdukaan.cron.scheduled.ambreports.AbmReportSender;
26095 amit.gupta 10
import com.spice.profitmandi.common.enumuration.ItemType;
26033 amit.gupta 11
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27450 tejbeer 12
import com.spice.profitmandi.common.model.CustomRetailer;
30616 amit.gupta 13
import com.spice.profitmandi.common.model.ImeiDropSummaryModel;
28840 amit.gupta 14
import com.spice.profitmandi.common.model.ProfitMandiConstants;
29945 amit.gupta 15
import com.spice.profitmandi.common.services.mandii.*;
24819 amit.gupta 16
import com.spice.profitmandi.common.util.FileUtil;
25749 amit.gupta 17
import com.spice.profitmandi.common.util.FormattingUtils;
24819 amit.gupta 18
import com.spice.profitmandi.common.util.Utils;
31088 amit.gupta 19
import com.spice.profitmandi.dao.cart.CartService;
26033 amit.gupta 20
import com.spice.profitmandi.dao.entity.catalog.Item;
31918 amit.gupta 21
import com.spice.profitmandi.dao.entity.catalog.*;
30889 amit.gupta 22
import com.spice.profitmandi.dao.entity.dtr.*;
29945 amit.gupta 23
import com.spice.profitmandi.dao.entity.fofo.*;
24953 amit.gupta 24
import com.spice.profitmandi.dao.entity.inventory.SaholicInventorySnapshot;
28736 amit.gupta 25
import com.spice.profitmandi.dao.entity.inventory.SaholicReservationSnapshot;
28735 amit.gupta 26
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
29945 amit.gupta 27
import com.spice.profitmandi.dao.entity.transaction.*;
25530 amit.gupta 28
import com.spice.profitmandi.dao.entity.user.Address;
29
import com.spice.profitmandi.dao.entity.user.User;
28840 amit.gupta 30
import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;
27511 amit.gupta 31
import com.spice.profitmandi.dao.entity.warehouse.WarehouseInventoryItem;
28038 amit.gupta 32
import com.spice.profitmandi.dao.entity.warehouse.WarehouseScan;
25021 amit.gupta 33
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
25522 amit.gupta 34
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
34326 amit.gupta 35
import com.spice.profitmandi.dao.enumuration.catalog.StockTransactionType;
27286 amit.gupta 36
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
29893 tejbeer 37
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
26759 amit.gupta 38
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
34710 amit.gupta 39
import com.spice.profitmandi.dao.enumuration.transaction.LoanReferenceType;
30616 amit.gupta 40
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
31088 amit.gupta 41
import com.spice.profitmandi.dao.model.*;
24716 amit.gupta 42
import com.spice.profitmandi.dao.repository.GenericRepository;
29945 amit.gupta 43
import com.spice.profitmandi.dao.repository.catalog.*;
25749 amit.gupta 44
import com.spice.profitmandi.dao.repository.cs.CsService;
29945 amit.gupta 45
import com.spice.profitmandi.dao.repository.dtr.*;
46
import com.spice.profitmandi.dao.repository.fofo.*;
24953 amit.gupta 47
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
26928 amit.gupta 48
import com.spice.profitmandi.dao.repository.inventory.SaholicReservationSnapshotRepository;
28675 amit.gupta 49
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
28708 amit.gupta 50
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
29945 amit.gupta 51
import com.spice.profitmandi.dao.repository.transaction.*;
25530 amit.gupta 52
import com.spice.profitmandi.dao.repository.user.AddressRepository;
31088 amit.gupta 53
import com.spice.profitmandi.dao.repository.user.CartRepository;
29863 tejbeer 54
import com.spice.profitmandi.dao.repository.user.FofoKycRepository;
24002 amit.gupta 55
import com.spice.profitmandi.dao.repository.user.UserRepository;
28840 amit.gupta 56
import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;
27511 amit.gupta 57
import com.spice.profitmandi.dao.repository.warehouse.WarehouseInventoryItemRepository;
28038 amit.gupta 58
import com.spice.profitmandi.dao.repository.warehouse.WarehouseScanRepository;
34443 vikas.jang 59
import com.spice.profitmandi.dao.service.LiquidationService;
34770 vikas.jang 60
import com.spice.profitmandi.dao.service.LocationTrackingService;
35105 vikas 61
import com.spice.profitmandi.dao.service.SaleRewardService;
30727 amit.gupta 62
import com.spice.profitmandi.service.integrations.bharti.BAGService;
63
import com.spice.profitmandi.service.integrations.bharti.model.Sample;
30310 amit.gupta 64
import com.spice.profitmandi.service.integrations.gstpro.GstProAuthService;
65
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
31047 amit.gupta 66
import com.spice.profitmandi.service.integrations.oneassist.OneAssistService;
67
import com.spice.profitmandi.service.integrations.zest.InsuranceService;
23899 amit.gupta 68
import com.spice.profitmandi.service.inventory.InventoryService;
26033 amit.gupta 69
import com.spice.profitmandi.service.inventory.PurchaseService;
28736 amit.gupta 70
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
30576 amit.gupta 71
import com.spice.profitmandi.service.offers.ItemCriteria;
27948 amit.gupta 72
import com.spice.profitmandi.service.offers.OfferService;
28557 amit.gupta 73
import com.spice.profitmandi.service.offers.PartnerCriteria;
24266 amit.gupta 74
import com.spice.profitmandi.service.order.OrderService;
24005 amit.gupta 75
import com.spice.profitmandi.service.pricing.PriceDropService;
76
import com.spice.profitmandi.service.scheme.SchemeService;
23899 amit.gupta 77
import com.spice.profitmandi.service.transaction.TransactionService;
30310 amit.gupta 78
import com.spice.profitmandi.service.transaction.invoicing.InvoiceService;
23899 amit.gupta 79
import com.spice.profitmandi.service.user.RetailerService;
31090 amit.gupta 80
import com.spice.profitmandi.service.wallet.CommonPaymentService;
23899 amit.gupta 81
import com.spice.profitmandi.service.wallet.WalletService;
28046 amit.gupta 82
import com.spice.profitmandi.service.warehouse.WarehouseInventoryService;
24953 amit.gupta 83
import in.shop2020.model.v1.order.OrderStatus;
24002 amit.gupta 84
import in.shop2020.model.v1.order.WalletReferenceType;
27450 tejbeer 85
import okhttp3.OkHttpClient;
86
import okhttp3.Request;
87
import okhttp3.Response;
30727 amit.gupta 88
import org.apache.commons.csv.CSVRecord;
29945 amit.gupta 89
import org.apache.commons.io.output.ByteArrayOutputStream;
90
import org.apache.commons.lang.StringUtils;
91
import org.apache.logging.log4j.LogManager;
92
import org.apache.logging.log4j.Logger;
32211 amit.gupta 93
import org.apache.poi.ss.usermodel.CellType;
94
import org.apache.poi.ss.usermodel.DataFormatter;
95
import org.apache.poi.xssf.usermodel.XSSFCell;
96
import org.apache.poi.xssf.usermodel.XSSFRow;
97
import org.apache.poi.xssf.usermodel.XSSFSheet;
98
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
29945 amit.gupta 99
import org.json.JSONArray;
100
import org.json.JSONObject;
101
import org.openqa.selenium.Dimension;
102
import org.openqa.selenium.OutputType;
103
import org.openqa.selenium.TakesScreenshot;
104
import org.openqa.selenium.WebDriver;
105
import org.openqa.selenium.chrome.ChromeDriver;
106
import org.openqa.selenium.chrome.ChromeOptions;
107
import org.springframework.beans.factory.annotation.Autowired;
108
import org.springframework.core.io.ByteArrayResource;
109
import org.springframework.mail.javamail.JavaMailSender;
110
import org.springframework.stereotype.Component;
111
import org.springframework.transaction.annotation.Transactional;
24002 amit.gupta 112
 
29945 amit.gupta 113
import java.io.File;
114
import java.io.FileInputStream;
115
import java.io.IOException;
34710 amit.gupta 116
import java.math.BigDecimal;
31461 amit.gupta 117
import java.time.*;
29945 amit.gupta 118
import java.time.temporal.ChronoUnit;
119
import java.util.*;
120
import java.util.concurrent.TimeUnit;
121
import java.util.stream.Collectors;
122
 
23755 amit.gupta 123
@Component
124
@Transactional(rollbackFor = Throwable.class)
125
public class RunOnceTasks {
126
 
31461 amit.gupta 127
    private static final Logger LOGGER = LogManager.getLogger(RunOnceTasks.class);
128
    @Autowired
129
    private LineItemRepository lineItemRepository;
24711 amit.gupta 130
 
31461 amit.gupta 131
    @Autowired
132
    private LeadRepository leadRepository;
28731 amit.gupta 133
 
31461 amit.gupta 134
    @Autowired
135
    InsuranceService insuranceService;
31047 amit.gupta 136
 
31461 amit.gupta 137
    @Autowired
138
    private VendorItemPricingRepository vendorItemPricingRepository;
28731 amit.gupta 139
 
31461 amit.gupta 140
    @Autowired
141
    private WarehouseRepository warehouseRepository;
27277 amit.gupta 142
 
31461 amit.gupta 143
    @Autowired
144
    private PurchaseReturnItemRepository purchaseReturnItemRepository;
26928 amit.gupta 145
 
31461 amit.gupta 146
    @Autowired
147
    private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
25752 amit.gupta 148
 
31461 amit.gupta 149
    @Autowired
150
    private CsService csService;
28660 amit.gupta 151
 
31461 amit.gupta 152
    @Autowired
153
    private ManualPaymentRequestRepository manualPaymentRequestRepository;
28624 amit.gupta 154
 
31461 amit.gupta 155
    @Autowired
156
    private OfferRepository offerRepository;
26299 amit.gupta 157
 
31461 amit.gupta 158
    @Autowired
159
    private Mongo mongoClient;
27787 amit.gupta 160
 
31461 amit.gupta 161
    @Autowired
162
    private Gson gson;
28624 amit.gupta 163
 
31461 amit.gupta 164
    @Autowired
165
    private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
26579 amit.gupta 166
 
31461 amit.gupta 167
    @Autowired
168
    private SamsungIMEIActivationService samsungIMEIActivationService;
30209 amit.gupta 169
 
31461 amit.gupta 170
    @Autowired
171
    private PrebookingOrderRepository prebookingOrderRepository;
24953 amit.gupta 172
 
31461 amit.gupta 173
    @Autowired
174
    private PartnerTargetRepository partnerTargetRepository;
24883 amit.gupta 175
 
31461 amit.gupta 176
    @Autowired
177
    private SellerWarehouseRepository sellerWarehouseRepository;
24814 amit.gupta 178
 
31461 amit.gupta 179
    @Autowired
180
    private FofoOrderItemRepository fofoOrderItemRepository;
27787 amit.gupta 181
 
31461 amit.gupta 182
    @Autowired
183
    private FofoLineItemRepository fofoLineItemRepository;
24814 amit.gupta 184
 
31461 amit.gupta 185
    @Autowired
186
    private FofoOrderRepository fofoOrderRepository;
24814 amit.gupta 187
 
31461 amit.gupta 188
    @Autowired
189
    private UserWalletRepository userWalletRepository;
24767 amit.gupta 190
 
31461 amit.gupta 191
    @Autowired
192
    private UserWalletHistoryRepository userWalletHistoryRepository;
24767 amit.gupta 193
 
31461 amit.gupta 194
    @Autowired
195
    private UserRepository userRepository;
24711 amit.gupta 196
 
31461 amit.gupta 197
    @Autowired
198
    private WalletService walletService;
23899 amit.gupta 199
 
31461 amit.gupta 200
    @Autowired
201
    private ItemRepository itemRepository;
25034 amit.gupta 202
 
31461 amit.gupta 203
    @Autowired
204
    private InventoryService inventoryService;
23899 amit.gupta 205
 
31461 amit.gupta 206
    @Autowired
207
    private TransactionService transactionService;
26299 amit.gupta 208
 
31461 amit.gupta 209
    @Autowired
210
    private PurchaseService purchaseService;
23899 amit.gupta 211
 
31461 amit.gupta 212
    // Service for Tertiary/Partner Orders
213
    @Autowired
214
    private OrderService orderService;
23767 amit.gupta 215
 
31461 amit.gupta 216
    @Autowired
34443 vikas.jang 217
    private LiquidationService liquidationService;
218
 
219
    @Autowired
31461 amit.gupta 220
    private SchemeRepository schemeRepository;
25516 amit.gupta 221
 
31461 amit.gupta 222
    @Autowired
223
    private AddressRepository addressRepository;
25749 amit.gupta 224
 
31461 amit.gupta 225
    @Autowired
226
    private ScheduledTasks scheduledTasks;
25034 amit.gupta 227
 
31461 amit.gupta 228
    @Autowired
229
    private SchemeItemRepository schemeItemRepository;
25021 amit.gupta 230
 
31461 amit.gupta 231
    @Autowired
232
    private ReturnOrderRepository returnOrderRepository;
24772 amit.gupta 233
 
31461 amit.gupta 234
    @Autowired
235
    private FofoStoreRepository fofoStoreRepository;
23899 amit.gupta 236
 
31461 amit.gupta 237
    @Autowired
238
    private LineItemImeisRepository lineItemImeisRepository;
24711 amit.gupta 239
 
31461 amit.gupta 240
    @Autowired
241
    private InventoryItemRepository inventoryItemRepository;
24814 amit.gupta 242
 
31461 amit.gupta 243
    @Autowired
244
    private TagListingRepository tagListingRepository;
26579 amit.gupta 245
 
31461 amit.gupta 246
    @Autowired
247
    private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
23901 amit.gupta 248
 
31461 amit.gupta 249
    @Autowired
250
    private RetailerService retailerService;
24711 amit.gupta 251
 
31461 amit.gupta 252
    @Autowired
253
    private SchemeInOutRepository schemeInOutRepository;
24711 amit.gupta 254
 
31461 amit.gupta 255
    @Autowired
256
    private DebitNoteRepository debitNoteRepository;
28624 amit.gupta 257
 
31461 amit.gupta 258
    @Autowired
259
    private OfferService offerService;
23899 amit.gupta 260
 
31461 amit.gupta 261
    @Autowired
262
    private GenericRepository genericRepository;
24716 amit.gupta 263
 
31461 amit.gupta 264
    @Autowired
265
    private PurchaseRepository purchaseRepository;
24711 amit.gupta 266
 
31461 amit.gupta 267
    @Autowired
268
    private PriceDropService priceDropService;
24883 amit.gupta 269
 
31461 amit.gupta 270
    @Autowired
271
    private JavaMailSender googleMailSender;
24711 amit.gupta 272
 
31461 amit.gupta 273
    @Autowired
274
    private SchemeService schemeService;
24711 amit.gupta 275
 
31461 amit.gupta 276
    @Autowired
277
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
24716 amit.gupta 278
 
31461 amit.gupta 279
    @Autowired
280
    private OrderRepository orderRepository;
28731 amit.gupta 281
 
31461 amit.gupta 282
    @Autowired
283
    private ScanRecordRepository scanRecordRepository;
24716 amit.gupta 284
 
31461 amit.gupta 285
    @Autowired
286
    private JavaMailSender mailSender;
27451 tejbeer 287
 
34770 vikas.jang 288
    @Autowired
35105 vikas 289
    private LocationTrackingService locationTrackingService;
34946 ranu 290
 
291
    @Autowired
35105 vikas 292
    private AbmReportSender abmReportSender;
34770 vikas.jang 293
 
35105 vikas 294
    @Autowired
295
    private SaleRewardService saleRewardService;
296
 
31461 amit.gupta 297
    private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
298
    private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";
24767 amit.gupta 299
 
31461 amit.gupta 300
    @Autowired
301
    private WarehouseInventoryItemRepository warehouseInventoryItemRepository;
27787 amit.gupta 302
 
31461 amit.gupta 303
    public void populateGrnTimestamp() {
304
        List<Purchase> allPurchases = purchaseRepository.selectAll();
305
        for (Purchase p : allPurchases) {
306
            String invoiceNumber = p.getPurchaseReference();
307
            if (p.getCompleteTimestamp() == null) {
308
                LOGGER.info("GRN for invoice {} is delivered but partially Completed.", p.getPurchaseReference());
309
            } else {
310
                List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(invoiceNumber, p.getFofoId());
311
                for (Order order : orders) {
312
                    if (order.getPartnerGrnTimestamp() == null) {
313
                        order.setPartnerGrnTimestamp(p.getCompleteTimestamp());
314
                    }
315
                }
316
            }
317
        }
23899 amit.gupta 318
 
31461 amit.gupta 319
    }
23899 amit.gupta 320
 
31461 amit.gupta 321
    public void fetchImeiActivation(int ym) throws Exception {
322
        LocalDate startDate = null;
323
        LocalDate endDate = null;
324
        if (ym == 0) {
325
            startDate = LocalDate.now().minusDays(30);
326
            endDate = LocalDate.now();
327
        } else {
328
            startDate = LocalDate.now().minusMonths(ym);
329
            endDate = startDate.plusMonths(1);
330
        }
331
        samsungIMEIActivationService.getActivationsBetweenNew(startDate, endDate);
332
    }
26299 amit.gupta 333
 
31461 amit.gupta 334
    public void cancelOrder(List<String> invoiceNumbers) throws Exception {
335
        orderService.cancelOrder(invoiceNumbers);
336
    }
27787 amit.gupta 337
 
31461 amit.gupta 338
    @Autowired
339
    HdfcPaymentRepository hdfcPaymentRepository;
27787 amit.gupta 340
 
31461 amit.gupta 341
    public void addPayment() throws Exception {
342
        List<Integer> paymentIds = Arrays.asList(3777);
343
        for (int hdfcPaymentId : paymentIds) {
344
            HdfcPayment hdfcPayment = hdfcPaymentRepository.selectById(hdfcPaymentId);
345
            String virtualAccount = hdfcPayment.getVirtualAccount();
346
            String retailerIdString = virtualAccount.substring(6);
347
            int retailerId = Integer.parseInt(retailerIdString);
348
            String description = String.format("Advance payment received through %s, Utr# %s",
349
                    hdfcPayment.getTransferMode(), hdfcPayment.getUtr());
350
            walletService.addAmountToWallet(retailerId, hdfcPayment.getId(), WalletReferenceType.AUTOMATED_ADVANCE,
351
                    description, (float) hdfcPayment.getAmount(), hdfcPayment.getCreditTimestamp());
352
        }
353
    }
29863 tejbeer 354
 
31461 amit.gupta 355
    // Bug in original migrate purchase
356
    public void migratePurchase() throws Exception {
357
        List<Purchase> purchases = purchaseRepository.selectPurchaseAllPurchasesLessThanZero();
358
        for (Purchase purchase : purchases) {
359
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchase.getId());
360
            for (InventoryItem ii : inventoryItems) {
361
                List<ScanRecord> scans = scanRecordRepository.selectByInventoryItemId(ii.getId());
362
                if (scans.size() == 1 && scans.get(0).getQuantity() == 0) {
363
                    scanRecordRepository.delete(scans.get(0));
364
                    purchase.setNonSerializedQuantity(purchase.getNonSerializedQuantity() - ii.getInitialQuantity());
365
                    inventoryItemRepository.delete(ii);
366
                }
29863 tejbeer 367
 
31461 amit.gupta 368
            }
29863 tejbeer 369
 
31461 amit.gupta 370
        }
371
    }
29758 amit.gupta 372
 
31461 amit.gupta 373
    public void migratePurchaseFix() throws Exception {
374
        List<Purchase> purchases = purchaseRepository.selectPurchaseAllPurchasesLessThanZero();
375
        System.out.printf("Total Purchases count is %s", purchases.size());
376
        for (Purchase purchase : purchases) {
377
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchase.getId());
378
            Map<Integer, List<InventoryItem>> itemIdInventoryMap = inventoryItems.stream()
379
                    .collect(Collectors.groupingBy(InventoryItem::getItemId));
380
            List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(purchase.getPurchaseReference(),
381
                    purchase.getFofoId());
382
            Map<Integer, Integer> ourSaleItemQtyMap = orders.stream().collect(Collectors.groupingBy(
383
                    x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
384
            Map<Integer, Integer> theirPurchaseItemQtyMap = inventoryItems.stream().collect(Collectors
385
                    .groupingBy(InventoryItem::getItemId, Collectors.summingInt(InventoryItem::getInitialQuantity)));
386
            for (Map.Entry<Integer, Integer> itemQtyEntry : theirPurchaseItemQtyMap.entrySet()) {
387
                if (!ourSaleItemQtyMap.containsKey(itemQtyEntry.getKey())) {
388
                    LOGGER.info("Cannot find in Invoice {} item {}", purchase.getPurchaseReference(),
389
                            itemQtyEntry.getKey());
390
                    continue;
391
                }
392
                int ourSale = ourSaleItemQtyMap.get(itemQtyEntry.getKey());
393
                int quantityToReduce = itemQtyEntry.getValue() - ourSale;
394
                List<InventoryItem> itemIis = itemIdInventoryMap.get(itemQtyEntry.getKey());
33994 amit.gupta 395
                if (quantityToReduce > 0) {
396
                    LOGGER.info("Invoice {}, Item {}, Quantity to reduce {}", purchase.getPurchaseReference(), itemQtyEntry.getKey(), quantityToReduce);
397
                    if (itemIdInventoryMap != null) {
398
                        for (InventoryItem ii : itemIis) {
399
                            if (ii.getSerialNumber() == null && ii.getGoodQuantity() == ii.getInitialQuantity()
400
                                    && quantityToReduce >= ii.getInitialQuantity()) {
401
                                LOGGER.info("Changed in inventoryItems {}, {}, {}, {}, {}, {}",
402
                                        purchase.getPurchaseReference(), ii.getId(), ii.getItemId(),
403
                                        ii.getInitialQuantity(), ii.getGoodQuantity(), quantityToReduce);
404
                                List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
405
                                for (ScanRecord scanRecord : scanRecords) {
406
                                    CurrentInventorySnapshot cis = currentInventorySnapshotRepository
407
                                            .selectByItemIdAndFofoId(itemQtyEntry.getKey(), purchase.getFofoId());
408
 
409
                                    cis.setAvailability(cis.getAvailability() - ii.getInitialQuantity());
410
                                    purchase.setUnfullfilledNonSerializedQuantity(
411
                                            purchase.getUnfullfilledNonSerializedQuantity() + quantityToReduce);
412
 
413
                                    quantityToReduce = quantityToReduce - ii.getInitialQuantity();
414
                                    inventoryItemRepository.delete(ii);
415
                                    scanRecordRepository.delete(scanRecord);
416
                                    LOGGER.info("Rectified {}, {}, {}, {}, {}, {}", purchase.getPurchaseReference(),
417
                                            ii.getId(), ii.getItemId(), ii.getInitialQuantity(), ii.getGoodQuantity(),
418
                                            quantityToReduce);
419
 
420
                                }
31461 amit.gupta 421
                            }
422
                        }
423
                    }
424
                }
425
            }
426
        }
33994 amit.gupta 427
        //throw new Exception();
31461 amit.gupta 428
    }
24767 amit.gupta 429
 
31461 amit.gupta 430
    public void migrateChallansToInvoices() throws Exception {
431
        Map<String, List<Order>> invoiceOrdersMap = orderRepository.selectAllChallans().stream()
432
                .filter(x -> !x.getLineItem().getHsnCode().equals("NOGST"))
433
                .collect(Collectors.groupingBy(Order::getInvoiceNumber, Collectors.toList()));
24814 amit.gupta 434
 
31461 amit.gupta 435
        List<List<?>> rows = new ArrayList<>();
436
        for (String invoice : invoiceOrdersMap.keySet()) {
437
            Order oneOrder = invoiceOrdersMap.get(invoice).get(0);
438
            int totalOrders = invoiceOrdersMap.get(invoice).size();
439
            LineItem lineItem = oneOrder.getLineItem();
440
            oneOrder.setBillingTimestamp(LocalDateTime.now());
441
            oneOrder.setInvoiceNumber(getInvoiceNumber(oneOrder));
442
            rows.add(Arrays.asList(oneOrder.getId(), invoice, oneOrder.getInvoiceNumber(), lineItem.getQuantity()));
443
            LOGGER.info(invoice + "\t" + oneOrder.getInvoiceNumber() + oneOrder.getId() + "\t",
444
                    "\t" + totalOrders + "\t" + lineItem.getQuantity());
445
            Purchase p = null;
446
            try {
447
                p = purchaseRepository.selectByPurchaseReferenceAndFofoId(invoice, oneOrder.getRetailerId());
448
            } catch (Exception e) {
449
                LOGGER.info("Could not find purchase for invoice {}", invoice);
450
            }
451
            if (p != null) {
452
                List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(p.getId());
453
                for (InventoryItem inventoryItem : inventoryItems) {
454
                    LOGGER.info(inventoryItem.getItemId() + " " + inventoryItem.getGoodQuantity() + " "
455
                            + inventoryItem.getHsnCode() + " " + inventoryItem.getSerialNumber() + " "
456
                            + p.getPurchaseReference());
457
                }
458
            }
24814 amit.gupta 459
 
31461 amit.gupta 460
        }
461
        changePartnerInvoices();
462
        ByteArrayOutputStream baos = FileUtil
463
                .getCSVByteStream(Arrays.asList("Order id", "Challan", "Invoice", "Quantity"), rows);
24883 amit.gupta 464
 
31461 amit.gupta 465
        Utils.sendMailWithAttachment(googleMailSender,
466
                new String[]{"amit.gupta@shop2020.in", "sunny.yadav@smartdukaan.com"}, null,
467
                "Challans Converted to Invoice", "PFA", "Challans-To-Invoice.csv",
468
                new ByteArrayResource(baos.toByteArray()));
469
        throw new Exception();
470
    }
24767 amit.gupta 471
 
31461 amit.gupta 472
    private String getInvoiceNumber(Order oneOrder) {
473
        String prefix = oneOrder.getInvoiceNumber().split("-")[1].replaceAll("\\d*", "");
474
        System.out.println("Prefix is " + prefix);
475
        SellerWarehouse sellerWarehouse = sellerWarehouseRepository.selectByPrefix(prefix);
476
        int newSequence = sellerWarehouse.getInvoiceSequence() + 1;
477
        sellerWarehouse.setInvoiceSequence(newSequence);
478
        return prefix + newSequence;
479
    }
24814 amit.gupta 480
 
31461 amit.gupta 481
    private void changePartnerInvoices() throws Exception {
482
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectByInvoiceNumberLike("%SEC%");
483
        for (FofoOrder fofoOrder : fofoOrders) {
484
            FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
485
            if (fofoOrderItem.getBrand().equals("Vivo")) {
486
                String challanString = fofoOrder.getInvoiceNumber();
487
                String storeCode = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoOrder.getFofoId())
488
                        .getPrefix();
489
                String invoiceNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), storeCode);
490
                fofoOrder.setInvoiceNumber(invoiceNumber);
491
                fofoOrder.setCreateTimestamp(LocalDateTime.now());
492
                LOGGER.info(challanString + "\t" + invoiceNumber + "\t" + fofoOrderItem.getQuantity());
493
            }
24814 amit.gupta 494
 
31461 amit.gupta 495
        }
496
    }
24802 amit.gupta 497
 
31461 amit.gupta 498
    private Scheme getScheme() {
499
        Scheme s = new Scheme();
500
        s.setName("List Price Margin");
501
        s.setDescription("List Price Margin");
502
        s.setActiveTimestamp(null);
503
        s.setStartDateTime(LocalDate.of(2019, 6, 1).atStartOfDay());
504
        s.setEndDateTime(LocalDate.of(2019, 7, 1).atStartOfDay());
505
        s.setAmountType(AmountType.PERCENTAGE);
506
        s.setCreateTimestamp(LocalDateTime.now());
507
        s.setExpireTimestamp(null);
508
        s.setCreatedBy(175120474);
509
        return s;
510
    }
25021 amit.gupta 511
 
31461 amit.gupta 512
    public void findMismatchesInIndent() throws Exception {
32869 amit.gupta 513
        List<Order> allInProcessOrders = orderRepository.selectAllOrder(Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW));
24967 amit.gupta 514
 
31461 amit.gupta 515
        Map<String, Integer> lineItemWhQtyMap = allInProcessOrders.stream()
516
                .collect(Collectors.groupingBy(y -> y.getLineItem().getItemId() + "-" + y.getFulfilmentWarehouseId(),
517
                        Collectors.summingInt(y -> y.getLineItem().getQuantity())));
25021 amit.gupta 518
 
31461 amit.gupta 519
        lineItemWhQtyMap.forEach((key, value) -> {
25021 amit.gupta 520
 
31461 amit.gupta 521
            int itemId = Integer.parseInt(key.split("-")[0]);
522
            int warehouseId = Integer.parseInt(key.split("-")[1]);
523
            System.out.printf("%d\t%d\t%d\n", itemId, warehouseId, value);
524
            SaholicInventorySnapshot cis = saholicInventorySnapshotRepository.selectByWarehouseIdandItemId(warehouseId,
525
                    itemId);
526
            if (cis == null) {
527
                cis = new SaholicInventorySnapshot();
528
                cis.setItemId(itemId);
529
                cis.setWarehouseId(warehouseId);
530
                cis.setAvailability(0);
531
                saholicInventorySnapshotRepository.persist(cis);
532
            }
533
            cis.setReserved(value);
534
        });
535
    }
24953 amit.gupta 536
 
25530 amit.gupta 537
 
31461 amit.gupta 538
    public void fixWallet() throws Exception {
539
        List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
540
        System.out.println("id\tcode\tactive\tname\tcity\tstate\twallet amount\tsum\twallet amount-sum");
541
        for (FofoStore fofoStore : fofoStores) {
542
            UserWallet uw = userWalletRepository.selectByRetailerId(fofoStore.getId());
543
            User user = userRepository.selectById(fofoStore.getId());
544
            if (user == null) {
545
                LOGGER.info("store does not exist", fofoStore.getCode());
546
                continue;
547
            }
548
            Address address = null;
549
            try {
550
                address = addressRepository.selectById(user.getAddressId());
551
            } catch (Exception e) {
552
                LOGGER.info("Could not find address for Store", fofoStore.getCode());
553
                address = new Address();
554
            }
555
            double sum = userWalletHistoryRepository.selectSumByWallet(uw.getId());
556
            int calculated = (int) sum;
557
            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(),
558
                    fofoStore.isActive(), address.getName(), address.getCity(), address.getState(), uw.getAmount(),
559
                    calculated, uw.getAmount() - calculated);
560
        }
561
    }
25749 amit.gupta 562
 
31461 amit.gupta 563
    public void changeWarehouse() throws Exception {
33395 amit.gupta 564
        transactionService.moveOrdersFulfimentWarehouse(7573);
31461 amit.gupta 565
    }
25749 amit.gupta 566
 
31461 amit.gupta 567
    public void mailDashboardScreenshots() throws Exception {
568
        System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
25749 amit.gupta 569
 
31461 amit.gupta 570
        ChromeOptions options = new ChromeOptions();
571
        options.addArguments("--headless");
572
        options.addArguments("--no-sandbox");
573
        options.addArguments("start-maximized");
574
        options.addArguments("disable-infobars");
575
        options.addArguments("--disable-extensions");
25752 amit.gupta 576
 
31461 amit.gupta 577
        WebDriver driver = new ChromeDriver(options);
578
        driver.manage().window().setSize(new Dimension(1600, 900));
579
        driver.manage().window().maximize();
580
        // Deleting all the cookies
581
        driver.manage().deleteAllCookies();
582
        // Specifiying pageLoadTimeout and Implicit wait
583
        driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
584
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
25752 amit.gupta 585
 
31461 amit.gupta 586
        Map<String, Set<Integer>> authUserPartnerIdMapping = csService.getAuthUserPartnerIdMapping();
587
        Set<Integer> allPartners = new HashSet<>();
588
        Map<Integer, File> partnerSnapshotMap = new HashMap<>();
589
        authUserPartnerIdMapping.values().stream().forEach(x -> allPartners.addAll(x));
590
        for (int fofoId : allPartners) {
591
            driver.get("https://partners.smartdukaan.com/12dashboard34?fofoId=" + fofoId);
592
            File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
593
            partnerSnapshotMap.put(fofoId, file);
25752 amit.gupta 594
 
31461 amit.gupta 595
        }
596
        for (Map.Entry<String, Set<Integer>> entry : authUserPartnerIdMapping.entrySet()) {
597
            String email = entry.getKey();
598
            LOGGER.info("Sending mail start to {}", email);
599
            Set<Integer> partnerIds = entry.getValue();
600
            StringBuffer body = new StringBuffer();
601
            Map<Integer, File> emailSnapshotMap = new HashMap<>();
602
            for (int fofoId : partnerIds) {
603
                body.append(String.format("<br/><img src=\"cid:%d\"/>", fofoId));
604
                emailSnapshotMap.put(fofoId, partnerSnapshotMap.get(fofoId));
605
            }
606
            Utils.sendEmbeddedHtmlMail(mailSender, new String[]{email}, new String[]{},
607
                    String.format("Franchise Screenshots - %s", FormattingUtils.formatDate(LocalDateTime.now())),
608
                    body.toString(), emailSnapshotMap);
609
            LOGGER.info("Sent mail to {}", email);
610
        }
611
        driver.quit();
612
    }
29893 tejbeer 613
 
31461 amit.gupta 614
    // Rollout prebooking orders amount in case the order is grned.
615
    public void pbfix() throws ProfitMandiBusinessException {
616
        List<PrebookingOrder> prebookingOrders = prebookingOrderRepository.selectAll();
617
        Map<Integer, Boolean> prebookingCleared = new HashMap<>();
618
        prebookingOrders = prebookingOrders.stream().collect(Collectors.toList());
619
        Map<Integer, List<PrebookingOrder>> catalogPrebookingMap = new HashMap<>();
620
        for (PrebookingOrder prebookingOrder : prebookingOrders) {
621
            if (!catalogPrebookingMap.containsKey(prebookingOrder.getCatalogId())) {
622
                catalogPrebookingMap.put(prebookingOrder.getCatalogId(), new ArrayList<>());
623
            }
624
            catalogPrebookingMap.get(prebookingOrder.getCatalogId()).add(prebookingOrder);
625
            int prebookingId = prebookingOrder.getId();
626
            List<UserWalletHistory> history = walletService.getAllByReference(prebookingOrder.getFofoId(), prebookingId,
627
                    WalletReferenceType.PREBOOKING_ORDER);
628
            long totalAmount = history.stream().collect(Collectors.summingLong(x -> x.getAmount()));
629
            // Refund is pending
630
            if (history.size() > 0) {
631
                if (totalAmount < 0) {
632
                    prebookingCleared.put(prebookingId, false);
633
                    LOGGER.info("Amount pending for prebooking id " + prebookingId + " amount is " + -totalAmount
634
                            + " catalog id - {}", prebookingOrder.getCatalogId());
635
                } else {
636
                    prebookingCleared.put(prebookingId, true);
637
                }
638
            } else {
639
                prebookingCleared.put(prebookingId, true);
640
                LOGGER.info("No entry in wallet for prebooking Id " + prebookingId);
641
            }
642
        }
643
        for (Map.Entry<Integer, List<PrebookingOrder>> entrySet : catalogPrebookingMap.entrySet()) {
644
            LOGGER.info("Catalog id {}, Size {}", entrySet.getKey(), entrySet.getValue().size());
645
            Set<Integer> itemIds = itemRepository.selectAllByCatalogItemId(entrySet.getKey()).stream()
646
                    .map(x -> x.getId()).collect(Collectors.toSet());
647
            List<PrebookingOrder> prebookings = entrySet.getValue();
648
            Map<Integer, List<PrebookingOrder>> fofoMap = prebookings.stream()
649
                    .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toList()));
650
            for (Map.Entry<Integer, List<PrebookingOrder>> fofoMapEntry : fofoMap.entrySet()) {
651
                int fofoId = fofoMapEntry.getKey();
652
                int totalGrnCount = inventoryItemRepository.selectByFofoIdItemIds(fofoId, itemIds).size();
653
                List<PrebookingOrder> partnerBookings = fofoMapEntry.getValue();
654
                for (PrebookingOrder partnerBooking : partnerBookings) {
655
                    if (prebookingCleared.get(partnerBooking.getId())) {
656
                        totalGrnCount--;
657
                        if (totalGrnCount < 0) {
658
                            totalGrnCount = 0;
659
                            LOGGER.info("FofoId {}, No Grn But Refunded prebooking id {}", fofoId,
660
                                    partnerBooking.getId());
661
                            break;
662
                        }
663
                    }
664
                }
29893 tejbeer 665
 
31461 amit.gupta 666
                long toBeRefunded = partnerBookings.stream().filter(x -> !prebookingCleared.get(x.getId()))
667
                        .limit(totalGrnCount).count();
668
                LOGGER.info("FofoId {}, Remaining Grn {}, toBeRefunded Prebooking {}", fofoId, totalGrnCount,
669
                        toBeRefunded);
670
                partnerBookings.stream().filter(x -> !prebookingCleared.get(x.getId()))
671
                        .filter(x -> x.getCreateTimestamp().getYear() == 2022).limit(totalGrnCount).forEach(x -> {
672
                            try {
673
                                purchaseService.sendPrebookingNotifyMessage(x);
674
                            } catch (Exception e) {
675
                                LOGGER.info("could not notify");
676
                            }
677
                        });
29893 tejbeer 678
 
31461 amit.gupta 679
            }
680
        }
681
    }
26092 amit.gupta 682
 
31461 amit.gupta 683
    public void fixGrn() throws Exception {
684
        List<Purchase> incompletePurchases = purchaseRepository.selectIncompletePurchase();
685
        for (Purchase incompletePurchase : incompletePurchases) {
686
            List<Order> orders = orderRepository.selectByAirwayBillOrInvoiceNumber(
687
                    incompletePurchase.getPurchaseReference(), incompletePurchase.getFofoId());
688
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(incompletePurchase.getId());
689
            Map<Integer, Integer> grnedItems = inventoryItems.stream().collect(
690
                    Collectors.groupingBy(x -> x.getItemId(), Collectors.summingInt(x -> x.getInitialQuantity())));
691
            Map<Integer, Integer> billedItems = orders.stream().collect(Collectors.groupingBy(
692
                    x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
693
            for (Integer billedItemId : billedItems.keySet()) {
694
                if (grnedItems.containsKey(billedItemId)) {
695
                    if (grnedItems.get(billedItemId) > billedItems.get(billedItemId)) {
696
                        LOGGER.info("Billed Qty {} ---- Grned {}, ItemId {}, Invoice Number {}({}), Grn Date {}",
697
                                billedItems.get(billedItemId), grnedItems.get(billedItemId), billedItemId,
698
                                incompletePurchase.getPurchaseReference(), incompletePurchase.getId(),
699
                                incompletePurchase.getCreateTimestamp());
700
                        Item item = itemRepository.selectById(billedItemId);
701
                        if (item.getType().equals(ItemType.SERIALIZED)) {
26299 amit.gupta 702
 
31461 amit.gupta 703
                        } else {
704
                            for (InventoryItem inventoryItem : inventoryItems) {
705
                                if (inventoryItem.getItemId() == billedItemId && inventoryItem.getGoodQuantity() == 0) {
706
                                    List<ScanRecord> scanRecords = scanRecordRepository
707
                                            .selectByInventoryItemId(inventoryItem.getId());
708
                                    if (scanRecords.size() == 1 && scanRecords.get(0).getQuantity() == 0) {
709
                                        LOGGER.info("Safe to remove InventoryItem Id {}", inventoryItem.getId());
710
                                        scanRecordRepository.delete(scanRecords.get(0));
711
                                        inventoryItemRepository.delete(inventoryItem);
712
                                        incompletePurchase.setUnfullfilledNonSerializedQuantity(
713
                                                incompletePurchase.getUnfullfilledNonSerializedQuantity()
714
                                                        + inventoryItem.getInitialQuantity());
715
                                    }
716
                                }
717
                            }
718
                        }
719
                    }
720
                }
721
            }
26299 amit.gupta 722
 
31461 amit.gupta 723
        }
26299 amit.gupta 724
 
31461 amit.gupta 725
    }
26265 amit.gupta 726
 
31461 amit.gupta 727
    public void fixDupGrns() throws Exception {
728
        List<Integer> duplicatePurchaseIds = Arrays.asList(14984);
729
        for (int duplicatePurchaseId : duplicatePurchaseIds) {
730
            Purchase purchase = purchaseRepository.selectById(duplicatePurchaseId);
731
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(duplicatePurchaseId);
732
            if (inventoryItems.size() == 0) {
733
                LOGGER.info("Could not find InventoryItems for {}", duplicatePurchaseId);
734
                continue;
735
            }
736
            schemeService.rollbackSchemes(inventoryItems.stream().map(x -> x.getId()).collect(Collectors.toList()),
737
                    "Rolled back duplicate grn for Purchase Invoice " + purchase.getPurchaseReference());
738
            for (InventoryItem inventoryItem : inventoryItems) {
739
                inventoryItemRepository.delete(inventoryItem);
740
                List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId());
741
                for (ScanRecord scanRecord : scanRecords) {
742
                    scanRecordRepository.delete(scanRecord);
743
                }
744
                List<SchemeInOut> sios = schemeInOutRepository
745
                        .selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
746
                for (SchemeInOut sio : sios) {
747
                    LOGGER.info("SIO - {}", sio);
748
                    schemeInOutRepository.delete(sio);
749
                }
26299 amit.gupta 750
 
31461 amit.gupta 751
            }
752
        }
753
        // throw new Exception();
754
    }
26579 amit.gupta 755
 
33260 amit.gupta 756
    public void mongom() throws ProfitMandiBusinessException {
31461 amit.gupta 757
        List<TagListing> tls = tagListingRepository.selectAll(false);
758
        Set<Integer> itemIds = tls.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
759
        Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId())
760
                .collect(Collectors.toSet());
761
        for (int catalogId : catalogIds) {
762
            try {
763
                ContentPojo cp = mongoClient.getEntityById(catalogId);
764
                try {
765
                    cp.setIconImageUrl(cp.getIconImageUrl().replace("saholic", "smartdukaan"));
766
                } catch (Exception e) {
26759 amit.gupta 767
 
31461 amit.gupta 768
                }
26759 amit.gupta 769
 
31461 amit.gupta 770
                try {
771
                    cp.setThumbnailImageUrl(cp.getThumbnailImageUrl().replace("saholic", "smartdukaan"));
772
                } catch (Exception e) {
26759 amit.gupta 773
 
31461 amit.gupta 774
                }
26759 amit.gupta 775
 
31461 amit.gupta 776
                cp.setDefaultImageUrl(cp.getDefaultImageUrl().replace("saholic", "smartdukaan"));
777
                List<MediaPojo> mPojos = cp.getImages();
778
                if (mPojos != null) {
779
                    mPojos.stream().forEach(mPojo -> {
780
                        mPojo.setUrl(mPojo.getUrl().replace("saholic", "smartdukaan"));
781
                    });
782
                }
783
                mongoClient.persistEntity(cp);
784
            } catch (Exception e) {
785
                continue;
786
            }
787
        }
788
    }
26759 amit.gupta 789
 
31461 amit.gupta 790
    public void cancelDn(String debitNoteNumber) throws Exception {
791
        DebitNote debitNote = debitNoteRepository.selectDebitNoteByNumber(debitNoteNumber);
26928 amit.gupta 792
 
31461 amit.gupta 793
        List<PurchaseReturnItem> purchaseReturnItems = purchaseReturnItemRepository
794
                .selectAllByDebitNoteId(debitNote.getId());
795
        // Select all inventory Item
796
        Set<Integer> inventoryItemIds = purchaseReturnItems.stream().map(x -> x.getInventoryItemId())
797
                .collect(Collectors.toSet());
798
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds);
799
        for (InventoryItem inventoryItem : inventoryItems) {
800
            if (!StringUtils.isEmpty(inventoryItem.getSerialNumber())) {
801
                inventoryItem.setGoodQuantity(1);
802
                inventoryItem.setLastScanType(ScanType.PURCHASE);
803
                ScanRecord sr = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId()).stream()
804
                        .filter(x -> x.getType().equals(ScanType.PURCHASE_RET)).findFirst().get();
805
                scanRecordRepository.delete(sr);
806
                CurrentInventorySnapshot cis = currentInventorySnapshotRepository
807
                        .selectByItemAndFofoId(inventoryItem.getItemId(), inventoryItem.getFofoId());
808
                if (cis == null) {
809
                    cis = new CurrentInventorySnapshot();
810
                    cis.setFofoId(inventoryItem.getFofoId());
811
                    cis.setItemId(inventoryItem.getId());
812
                    currentInventorySnapshotRepository.persist(cis);
813
                }
814
                cis.setAvailability(cis.getAvailability() + 1);
815
                schemeService.processSchemeIn(inventoryItem.getPurchaseId(), inventoryItem.getFofoId());
816
            }
817
        }
818
        purchaseReturnItems.stream().forEach(x -> purchaseReturnItemRepository.delete(x));
819
    }
26799 amit.gupta 820
 
31461 amit.gupta 821
    public void processPd(int priceDropId) throws ProfitMandiBusinessException {
822
        priceDropService.processPriceDrop(priceDropId, false);
823
    }
26928 amit.gupta 824
 
31461 amit.gupta 825
    public void fixScheme() throws Exception {
826
        LOGGER.info("Partner Types found\tPartnerType To Remove\tAmout to Rollback");
827
        final Map<Integer, Scheme> schemesMap = schemeRepository.selectAll().stream()
828
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
829
        List<SchemeInOut> sios = schemeInOutRepository.selectAllByCreateDate(LocalDate.of(2019, 9, 1).atTime(0, 0),
830
                LocalDateTime.now());
831
        Map<SioTuple, Map<PartnerType, List<SchemeInOut>>> schemeTupleMap = sios.stream()
832
                .filter(x -> x.getRolledBackTimestamp() == null)
833
                .filter(x -> schemesMap.get(x.getSchemeId()).getPartnerType() != PartnerType.ALL)
834
                .collect(Collectors.groupingBy(
835
                        x -> new SioTuple(x.getInventoryItemId(), schemesMap.get(x.getSchemeId()).getType()),
836
                        Collectors.groupingBy(x -> schemesMap.get(x.getSchemeId()).getPartnerType(),
837
                                Collectors.mapping(x -> x, Collectors.toList()))));
27221 amit.gupta 838
 
31461 amit.gupta 839
        schemeTupleMap.entrySet().stream().filter(x -> x.getValue().size() > 1).forEach(x -> {
840
            Map<PartnerType, List<SchemeInOut>> partnerTypeSchemeMap = x.getValue();
841
            PartnerType partnerTypeToRemove = partnerTypeSchemeMap.keySet().stream()
842
                    .min(Comparator.comparing(y -> PartnerType.PartnerTypeRankMap.get(y))).get();
843
            LOGGER.info("{}\t{}\t{}\t{}\t{}\t{}", partnerTypeSchemeMap.keySet(), partnerTypeToRemove,
844
                    partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
845
                            .collect(Collectors.summingDouble(SchemeInOut::getAmount)),
846
                    FormattingUtils.formatDate(partnerTypeSchemeMap.get(partnerTypeToRemove).stream()
847
                            .map(y -> y.getCreateTimestamp()).findFirst().get()));
27221 amit.gupta 848
 
31461 amit.gupta 849
        });
850
    }
26928 amit.gupta 851
 
31461 amit.gupta 852
    @Autowired
853
    GstProAuthService gstProAuthService;
30310 amit.gupta 854
 
31461 amit.gupta 855
    @Autowired
856
    GstProService gstProService;
30310 amit.gupta 857
 
31461 amit.gupta 858
    @Autowired
859
    InvoiceService invoiceService;
30310 amit.gupta 860
 
31461 amit.gupta 861
    public void updateIrnsToInvoices() {
862
        try {
863
            invoiceService.updateIrnsToInvoices();
864
        } catch (Throwable t) {
865
            t.printStackTrace();
866
        }
867
    }
30310 amit.gupta 868
 
31461 amit.gupta 869
    @Autowired
870
    AmazonPurchaseService amazonPurchaseService;
30335 amit.gupta 871
 
32211 amit.gupta 872
    private static DataFormatter formatter = new DataFormatter();
873
 
31461 amit.gupta 874
    @Autowired
875
    OfferTargetSlabRepository offerTargetSlabRepository;
30576 amit.gupta 876
 
31461 amit.gupta 877
    public void amazonPurchase() throws Exception {
32211 amit.gupta 878
        //Read file
879
        FileInputStream fis = new FileInputStream(new File("/Users/amit/Downloads/amazon.xlsx"));
880
        //creating workbook instance that refers to .xls file
881
        XSSFWorkbook wb = new XSSFWorkbook(fis);
882
        //creating a Sheet object to retrieve the object
883
        XSSFSheet sheet = wb.getSheetAt(0);
884
 
885
        OrderSummary orderSummary = this.getOrderSummary(sheet);
886
        List<OrderRow> orderRows = new ArrayList<>();
887
        int rows = sheet.getLastRowNum();
888
        for (int rowNum = 3; rowNum < rows; rowNum++) {
889
            try {
890
                OrderRow orderRow = parseRow(orderSummary, sheet.getRow(rowNum));
891
                orderRows.add(orderRow);
892
            } catch (RuntimeException re) {
893
                System.out.println("Could not parse rownum - " + rowNum);
894
            }
895
        }
896
        amazonPurchaseService.purchaseAmazon(orderSummary, orderRows);
31461 amit.gupta 897
    }
30335 amit.gupta 898
 
32211 amit.gupta 899
    private OrderSummary getOrderSummary(XSSFSheet sheet) {
900
        XSSFRow firstRow = sheet.getRow(0);
901
        String asin = firstRow.getCell(1).getStringCellValue();
902
        int purchasePrice = (int) firstRow.getCell(3).getNumericCellValue();
903
        int qtyPerOrder = (int) firstRow.getCell(5).getNumericCellValue();
904
        boolean gst = Boolean.parseBoolean(getCellString(firstRow.getCell(7)));
905
        XSSFRow secondRow = sheet.getRow(1);
906
        boolean prepaid = Boolean.parseBoolean(getCellString(secondRow.getCell(1)));
907
        boolean noCostEmi = Boolean.parseBoolean(getCellString(secondRow.getCell(3)));
908
        OrderSummary orderSummary = new OrderSummary();
909
        orderSummary.setAsin(asin);
910
        orderSummary.setGst(gst);
911
        orderSummary.setQtyPerOrder(qtyPerOrder);
912
        orderSummary.setPrepaid(prepaid);
913
        orderSummary.setNoCostEmi(noCostEmi);
914
        return orderSummary;
915
    }
916
 
917
    private static String getCellString(XSSFCell xssfCell) {
918
        xssfCell.setCellType(CellType.STRING);
919
        return xssfCell.getStringCellValue();
920
    }
921
 
922
    private OrderRow parseRow(OrderSummary orderSummary, XSSFRow row) {
923
        int col = 0;
924
        OrderRow orderRow = new OrderRow();
925
        String userName = getCellString(row.getCell(col++));
926
        String password = getCellString(row.getCell(col++));
927
        orderRow.setUserName(userName);
928
        orderRow.setPassword(password);
929
 
930
        if (orderSummary.isPrepaid()) {
931
            String cardName = getCellString(row.getCell(col++));
932
            String cardNumber = getCellString(row.getCell(col++));
933
            String cardExpiryYr = getCellString(row.getCell(col++));
934
            String cardExpiryMonth = getCellString(row.getCell(col++));
935
            String cvv = getCellString(row.getCell(col++));
936
            String verificationPin = getCellString(row.getCell(col++));
937
            boolean orderPlaced = getCellString(row.getCell(col++)).equals("1") ? true : false;
938
            orderRow.setCardNumber(cardNumber);
33526 amit.gupta 939
            orderRow.setCvv(StringUtils.repeat("0", 3 - cvv.length()) + cvv);
32211 amit.gupta 940
            orderRow.setCardName(cardName);
941
            orderRow.setExpiryYr(cardExpiryYr);
942
            orderRow.setExpiryMonth(cardExpiryMonth);
943
            orderRow.setVerificationPin(verificationPin);
944
            orderRow.setOrderPlaced(orderPlaced);
945
        }
946
        return orderRow;
947
    }
948
 
31461 amit.gupta 949
    @Autowired
950
    ItemCriteriaRepository itemCriteriaRepository;
30335 amit.gupta 951
 
31461 amit.gupta 952
    public void createOfferCriteria() throws Exception {
953
        Offer offer = offerRepository.selectById(1099);
954
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
955
        createOfferRequest.setStartDate(LocalDate.of(2022, 7, 5).atStartOfDay());
956
        createOfferRequest.setEndDate(LocalDate.of(2022, 7, 31).atTime(LocalTime.MAX));
957
        createOfferRequest.setCreatedOn(LocalDateTime.now());
958
        offerService.addOfferService(createOfferRequest);
959
    }
30685 amit.gupta 960
 
31461 amit.gupta 961
    public void createOfferCriteria1() throws Exception {
962
        Map<Integer, List<Integer>> map = new HashMap<>();
963
        map.put(31960, Arrays.asList(57, 69));
964
        map.put(32844, Arrays.asList(57, 69));
965
        map.put(31964, Arrays.asList(65, 78));
966
        map.put(33493, Arrays.asList(70, 84));
967
        map.put(32847, Arrays.asList(65, 78));
968
        map.put(32623, Arrays.asList(72, 86));
969
        map.put(31972, Arrays.asList(74, 88));
970
        map.put(33495, Arrays.asList(78, 93));
971
        map.put(32699, Arrays.asList(78, 93));
972
        map.put(31967, Arrays.asList(78, 93));
973
        map.put(33424, Arrays.asList(86, 103));
974
        map.put(33441, Arrays.asList(94, 113));
975
        map.put(33491, Arrays.asList(102, 123));
976
        map.put(32664, Arrays.asList(94, 112));
977
        map.put(33430, Arrays.asList(159, 181));
978
        map.put(33381, Arrays.asList(172, 195));
979
        map.put(33484, Arrays.asList(184, 209));
980
        map.put(32698, Arrays.asList(171, 194));
981
        map.put(32665, Arrays.asList(171, 194));
982
        map.put(33428, Arrays.asList(146, 166));
983
        map.put(33499, Arrays.asList(196, 223));
984
        map.put(33427, Arrays.asList(184, 208));
985
        map.put(33385, Arrays.asList(203, 230));
986
        map.put(33373, Arrays.asList(196, 222));
987
        map.put(33429, Arrays.asList(171, 193));
988
        map.put(33387, Arrays.asList(215, 244));
989
        map.put(33432, Arrays.asList(208, 236));
990
        map.put(32546, Arrays.asList(196, 222));
991
        map.put(33389, Arrays.asList(227, 257));
992
        map.put(33498, Arrays.asList(233, 264));
993
        map.put(33496, Arrays.asList(202, 229));
994
        map.put(32088, Arrays.asList(233, 264));
995
        map.put(33377, Arrays.asList(233, 264));
996
        map.put(33395, Arrays.asList(327, 392));
997
        map.put(33393, Arrays.asList(344, 413));
998
        map.put(32277, Arrays.asList(360, 432));
999
        map.put(33397, Arrays.asList(377, 452));
1000
        map.put(32305, Arrays.asList(393, 472));
1001
        map.put(33492, Arrays.asList(409, 491));
1002
        map.put(33399, Arrays.asList(409, 491));
1003
        map.put(33405, Arrays.asList(442, 531));
1004
        map.put(33403, Arrays.asList(442, 531));
1005
        map.put(32854, Arrays.asList(442, 531));
1006
        map.put(32155, Arrays.asList(458, 550));
1007
        map.put(32151, Arrays.asList(458, 550));
1008
        map.put(33407, Arrays.asList(475, 570));
1009
        map.put(32855, Arrays.asList(475, 570));
1010
        map.put(33409, Arrays.asList(655, 786));
1011
        map.put(33411, Arrays.asList(688, 825));
1012
        map.put(32687, Arrays.asList(688, 825));
1013
        map.put(33413, Arrays.asList(720, 865));
1014
        map.put(33415, Arrays.asList(1032, 1238));
1015
        map.put(33417, Arrays.asList(1097, 1316));
30576 amit.gupta 1016
 
31461 amit.gupta 1017
        Offer offer = offerRepository.selectById(1099);
1018
        List<TargetSlab> targetSlabs = offerTargetSlabRepository.getByOfferId(offer.getId());
1019
        ItemCriteria itemCriteria = targetSlabs.get(0).getItemCriteriaPayouts().get(0).getItemCriteria();
30576 amit.gupta 1020
 
31461 amit.gupta 1021
        Map<List<Integer>, List<Integer>> payoutModelsMap = map.entrySet().stream().map(x ->
1022
        {
1023
            try {
1024
                int catalogId = itemRepository.selectById(x.getKey()).getCatalogItemId();
1025
                return new AbstractMap.SimpleEntry<>(catalogId, x.getValue());
1026
            } catch (Exception e) {
1027
                return new AbstractMap.SimpleEntry<>(0, new ArrayList());
1028
            }
1029
        }).collect(Collectors.groupingBy(x -> x.getValue(), Collectors.mapping(x -> x.getKey(), Collectors.toList())));
30576 amit.gupta 1030
 
31461 amit.gupta 1031
        payoutModelsMap.entrySet().stream().forEach(x ->
1032
        {
1033
            itemCriteria.setCatalogIds(x.getValue());
30576 amit.gupta 1034
 
31461 amit.gupta 1035
            com.spice.profitmandi.dao.entity.catalog.ItemCriteria itemCriteria1 = new com.spice.profitmandi.dao.entity.catalog.ItemCriteria();
1036
            itemCriteria1.setCriteria(gson.toJson(itemCriteria));
1037
            itemCriteriaRepository.persist(itemCriteria1);
31918 amit.gupta 1038
            TargetSlabEntity ts = new TargetSlabEntity();
31461 amit.gupta 1039
            ts.setOfferId(offer.getId());
1040
            ts.setAmountType(targetSlabs.get(0).getItemCriteriaPayouts().get(0).getAmountType());
1041
            ts.setPayoutTarget(25);
1042
            ts.setItemCriteriaId(itemCriteria1.getId());
1043
            ts.setPayoutValue(x.getKey().get(0));
1044
            offerTargetSlabRepository.persist(ts);
30576 amit.gupta 1045
 
31918 amit.gupta 1046
            TargetSlabEntity ts1 = new TargetSlabEntity();
31461 amit.gupta 1047
            ts1.setOfferId(offer.getId());
1048
            ts1.setAmountType(targetSlabs.get(0).getItemCriteriaPayouts().get(0).getAmountType());
1049
            ts1.setPayoutTarget(100);
1050
            ts1.setItemCriteriaId(itemCriteria1.getId());
1051
            ts1.setPayoutValue(x.getKey().get(1));
1052
            offerTargetSlabRepository.persist(ts1);
1053
        });
30576 amit.gupta 1054
 
31461 amit.gupta 1055
    }
30576 amit.gupta 1056
 
31461 amit.gupta 1057
    @Autowired
1058
    PriceDropRepository priceDropRepository;
30576 amit.gupta 1059
 
30616 amit.gupta 1060
 
31461 amit.gupta 1061
    @Autowired
1062
    PriceDropIMEIRepository priceDropIMEIRepository;
30616 amit.gupta 1063
 
31461 amit.gupta 1064
    public void fixPriceDrop() throws ProfitMandiBusinessException {
1065
        List<Integer> priceDropIds = Arrays.asList(609, 610, 611, 648, 649, 650, 651, 653, 667, 691, 692, 693, 695, 696, 697, 698, 645, 688);
1066
        for (int priceDropId : priceDropIds) {
1067
            PriceDrop pd = priceDropRepository.selectById(priceDropId);
1068
            LOGGER.info("Price Drop ---- {}", pd);
33203 amit.gupta 1069
            List<ImeiDropSummaryModel> actualList = priceDropService.getAllSerialNumbersByAffectedDate(pd.getAffectedOn(), pd.getCatalogItemId(), Optional.of(pd.getCreatedOn()));
31461 amit.gupta 1070
            Map<String, ImeiDropSummaryModel> actualMap = actualList.stream().collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
30616 amit.gupta 1071
 
31461 amit.gupta 1072
            List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByPriceDropId(pd.getId());
1073
            Map<String, PriceDropIMEI> oldImeisMap = priceDropIMEIs.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x));
30616 amit.gupta 1074
 
31461 amit.gupta 1075
            for (Map.Entry<String, PriceDropIMEI> entry : oldImeisMap.entrySet()) {
1076
                String imei = entry.getKey();
1077
                if (!actualMap.containsKey(imei)) {
1078
                    //This imei is invalid and need to be checked
1079
                    if (!entry.getValue().getStatus().equals(PriceDropImeiStatus.REJECTED)) {
1080
                        if (entry.getValue().getStatus().equals(PriceDropImeiStatus.PENDING)) {
1081
                            LOGGER.info("Invalid pending imei -- {} should be deleted", imei);
1082
                        } else if (entry.getValue().getStatus().equals(PriceDropImeiStatus.APPROVED)) {
1083
                            LOGGER.info("Invalid approved imei -- {} should be reversed", imei);
1084
                        }
1085
                        //These values should either be rejected or rolledBack
1086
                        LOGGER.info("Should be rejected or rolledBack -- Imei --- {}, Status --- {}", imei, entry.getValue().getStatus());
1087
                    } else {
1088
                        //Rejections can be ignored
1089
                    }
1090
                } else {
1091
                    if (entry.getValue().getStatus().equals(PriceDropImeiStatus.REJECTED)) {
1092
                        LOGGER.info("Valid but rejected imeis should be retried, marked pending --- {}", imei);
1093
                        entry.getValue().setStatus(PriceDropImeiStatus.PENDING);
1094
                    }
1095
                }
1096
            }
30616 amit.gupta 1097
 
31461 amit.gupta 1098
            for (Map.Entry<String, ImeiDropSummaryModel> entry : actualMap.entrySet()) {
1099
                ImeiDropSummaryModel imeiDropSummaryModel = entry.getValue();
1100
                String imei = entry.getKey();
1101
                if (!oldImeisMap.containsKey(imei)) {
1102
                    //this imei should be added for processing in pending state
1103
                    PriceDropIMEI priceDropIMEI = new PriceDropIMEI();
1104
                    priceDropIMEI.setPriceDropId(priceDropId);
1105
                    priceDropIMEI.setStatus(PriceDropImeiStatus.PENDING);
1106
                    priceDropIMEI.setImei(imei);
1107
                    priceDropIMEI.setPartnerId(imeiDropSummaryModel.getRetailerId());
1108
                    priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
1109
                    priceDropIMEIRepository.persist(priceDropIMEI);
1110
                    LOGGER.info("These imeis are added and were missing earlier --- {}", imei);
30616 amit.gupta 1111
 
31461 amit.gupta 1112
                }
1113
            }
30616 amit.gupta 1114
 
31461 amit.gupta 1115
        }
1116
    }
30616 amit.gupta 1117
 
31461 amit.gupta 1118
    @Autowired
1119
    private SaholicInventoryService saholicInventoryService;
30616 amit.gupta 1120
 
31461 amit.gupta 1121
    public void updateSaholicCISTable() {
1122
        saholicInventoryService.updateSaholicCIS();
1123
    }
30659 amit.gupta 1124
 
31461 amit.gupta 1125
    @Autowired
1126
    BAGService bagService;
30659 amit.gupta 1127
 
31461 amit.gupta 1128
    public void testBag() throws Exception {
1129
        //bagService.getPlans(10006, 10000f);
1130
        //bagService.getBrandsMaster();
1131
        bagService.getAllPlans();
1132
    }
30727 amit.gupta 1133
 
31461 amit.gupta 1134
    @Autowired
1135
    private OneAssistService oneAssistService;
31047 amit.gupta 1136
 
31461 amit.gupta 1137
    public void cancelOnceAssist(String invoiceNumber) throws Exception {
1138
        FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1139
        insuranceService.cancelInsurance(fofoOrder);
1140
    }
31047 amit.gupta 1141
 
34208 ranu 1142
    public void cancelOnceAssistByMemberShipNumber(String applicationNo, String membershipId) throws Exception {
1143
        insuranceService.cancelInsurance(applicationNo, membershipId);
1144
    }
1145
 
31461 amit.gupta 1146
    public void mapBag() throws Exception {
1147
        List<Item> items = itemRepository.selectAllItems(10006, Arrays.asList("OnePlus", "Oppo", "Realme", "Samsung", "Vivo", "Xiaomi"));
1148
        items.stream().collect(Collectors.groupingBy(x -> x.getBrand()));
30727 amit.gupta 1149
 
31461 amit.gupta 1150
        List<CSVRecord> csvRecordList = FileUtil.readFile(new File("/home/amit/Documents/sample.csv"));
1151
        for (CSVRecord csvRecord : csvRecordList) {
1152
            Sample sample = new Sample(csvRecord.get(0), csvRecord.get(1), csvRecord.get(2));
1153
            //StringUtils.getLevenshteinDistance()
1154
        }
1155
    }
30727 amit.gupta 1156
 
31461 amit.gupta 1157
    public void reverseInvalidActivation(List<Integer> inventoryItemIds) throws Exception {
1158
        orderService.reverseActivationScheme(inventoryItemIds);
1159
    }
31031 amit.gupta 1160
 
34443 vikas.jang 1161
    public void processBids(ProfitMandiConstants.BID_CRON_ENUM schedule) throws Exception {
1162
        liquidationService.processBids(schedule);
1163
    }
31088 amit.gupta 1164
 
34547 vikas.jang 1165
    public void consolidatedBiddingMessage() throws Exception {
1166
        liquidationService.consolidatedBiddingMessage();
1167
    }
1168
 
31461 amit.gupta 1169
    @Autowired
1170
    CartRepository cartRepository;
31088 amit.gupta 1171
 
31461 amit.gupta 1172
    @Autowired
1173
    CartService cartService;
31088 amit.gupta 1174
 
31461 amit.gupta 1175
    @Autowired
1176
    private CommonPaymentService commonPaymentService;
31090 amit.gupta 1177
 
1178
 
34710 amit.gupta 1179
    @Autowired
1180
    LoanRepository loanRepository;
1181
 
1182
    @Autowired
1183
    LoanStatementRepository loanStatementRepository;
1184
 
1185
 
1186
    //Reverse CD of a specified Loan
1187
    public void reverseCD() throws ProfitMandiBusinessException {
1188
        Loan loan = loanRepository.selectByLoanId(45975);
1189
        List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
1190
        loanStatements.stream().filter(x->x.getLoanReferenceType().equals(LoanReferenceType.PRINCIPAL) && x.getAmount().compareTo(BigDecimal.ZERO) > 0).forEach(x->loanStatementRepository.delete(x));
1191
        loan.setSettledOn(null);
1192
        loan.setPendingAmount(loan.getIntialAmount());
1193
        String invoiceNumber = loan.getInvoiceNumber();
1194
        Purchase purchase = purchaseRepository.selectByPurchaseReference(invoiceNumber);
1195
        List<Integer> iis = inventoryItemRepository.selectByPurchaseId(purchase.getId()).stream().map(x->x.getId()).collect(Collectors.toList());
1196
        for (Integer ii : iis) {
1197
            List<SchemeInOut> sios = schemeInOutRepository.selectAllByType(SchemeType.CASH_DISCOUNT, ii);
1198
            if(sios.size() > 0) {
1199
                schemeInOutRepository.delete(sios.get(0));
1200
            }
1201
            List<SchemeInOut> sios1 = schemeInOutRepository.selectAllByType(SchemeType.CASH_DISCOUNT1, ii);
1202
            if(sios1.size() > 0) {
1203
                schemeInOutRepository.delete(sios1.get(0));
1204
            }
1205
 
31461 amit.gupta 1206
        }
34710 amit.gupta 1207
        List<UserWalletHistory> uwhs = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(purchase.getId(), WalletReferenceType.SCHEME_IN);
1208
        for (UserWalletHistory uwh : uwhs) {
1209
            genericRepository.delete(uwh);
1210
        }
1211
 
31461 amit.gupta 1212
    }
31088 amit.gupta 1213
 
31461 amit.gupta 1214
    private class SioTuple {
1215
        int inventoryId;
1216
        SchemeType schemeType;
26928 amit.gupta 1217
 
31461 amit.gupta 1218
        public SioTuple(int inventoryItemId, SchemeType schemeType) {
1219
            this.inventoryId = inventoryItemId;
1220
            this.schemeType = schemeType;
1221
        }
26928 amit.gupta 1222
 
31461 amit.gupta 1223
        public int getInventoryId() {
1224
            return inventoryId;
1225
        }
26928 amit.gupta 1226
 
31461 amit.gupta 1227
        public void setInventoryId(int inventoryId) {
1228
            this.inventoryId = inventoryId;
1229
        }
26928 amit.gupta 1230
 
31461 amit.gupta 1231
        public SchemeType getSchemeType() {
1232
            return schemeType;
1233
        }
26928 amit.gupta 1234
 
31461 amit.gupta 1235
        public void setSchemeType(SchemeType schemeType) {
1236
            this.schemeType = schemeType;
1237
        }
26928 amit.gupta 1238
 
31461 amit.gupta 1239
        @Override
1240
        public int hashCode() {
1241
            final int prime = 31;
1242
            int result = 1;
1243
            result = prime * result + getOuterType().hashCode();
1244
            result = prime * result + inventoryId;
1245
            result = prime * result + ((schemeType == null) ? 0 : schemeType.hashCode());
1246
            return result;
1247
        }
26928 amit.gupta 1248
 
31461 amit.gupta 1249
        @Override
1250
        public boolean equals(Object obj) {
1251
            if (this == obj)
1252
                return true;
1253
            if (obj == null)
1254
                return false;
1255
            if (getClass() != obj.getClass())
1256
                return false;
1257
            SioTuple other = (SioTuple) obj;
1258
            if (!getOuterType().equals(other.getOuterType()))
1259
                return false;
1260
            if (inventoryId != other.inventoryId)
1261
                return false;
1262
            if (schemeType != other.schemeType)
1263
                return false;
1264
            return true;
1265
        }
26928 amit.gupta 1266
 
31461 amit.gupta 1267
        private RunOnceTasks getOuterType() {
1268
            return RunOnceTasks.this;
1269
        }
26928 amit.gupta 1270
 
31461 amit.gupta 1271
    }
27221 amit.gupta 1272
 
31461 amit.gupta 1273
    public void printPendingLeads() {
1274
        LOGGER.info("PENDING LEADES {}", leadRepository.selectLeadsScheduledBetweenDate(null,
1275
                LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4)));
1276
    }
27277 amit.gupta 1277
 
31461 amit.gupta 1278
    public void removeDuplicateOrders() throws Exception {
1279
        List<String> invoiceNumbers = Arrays.asList(/*
1280
                 * "DLWE066/1108", "DLWE066/299", "DLWE066/348", "HRFB004/242",
1281
                 * "HRFB004/243", "HRFB004/514", "HRFTB155/29", "HRJND076/1146",
1282
                 * "HRJND076/966", "HRKA134/295", "HRKA134/421", "HRKK091/381",
1283
                 * "HRMGH106/576", "HRSP056/139", "HRYN030/103", "UPGZ019/395",
1284
                 * "UPHRD130/1299", "UPHRD130/456", "UPHRD130/634", "UPLKO063/897",
1285
                 * "UPMRT149/54", "UPSJP119/748", "UPSJP119/980", "UPSTP065/1218",
1286
                 * "UPSTP065/2039", "UPSTP090/437", "UPSTP120/164",
1287
                 */
1288
                "HRMGH106/1576");
27451 tejbeer 1289
 
31461 amit.gupta 1290
        int totalAmount = 0;
1291
        float saleAmount = 0;
1292
        float schemeReverseAmount = 0;
1293
        for (String invoiceNumber : invoiceNumbers) {
1294
            List<FofoOrder> orders = fofoOrderRepository.selectByInvoiceNumberLike(invoiceNumber);
1295
            orders = orders.stream().skip(1).collect(Collectors.toList());
1296
            for (FofoOrder fofoOrder : orders) {
1297
                LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
1298
                int inventoryItemId = 0;
1299
                saleAmount += fofoOrder.getTotalAmount();
1300
                fofoOrderRepository.delete(fofoOrder);
1301
                LOGGER.info("Fofo Order Id - {}, Invoice {}", fofoOrder.getId(), invoiceNumber);
1302
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1303
                List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
1304
                        .selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
1305
                for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
1306
                    paymentOptionTransactionRepository.delete(paymentOptionTransaction);
1307
                }
1308
                for (FofoOrderItem foi : fofoOrderItems) {
1309
                    List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
1310
                    fofoOrderItemRepository.delete(foi);
1311
                    for (FofoLineItem fli : flis) {
1312
                        inventoryItemId = fli.getInventoryItemId();
1313
                        fofoLineItemRepository.delete(fli);
1314
                    }
1315
                }
1316
                // Rollback entry with reversal reason
1317
                if (fofoOrder.getCreateTimestamp().isAfter(LocalDate.of(2020, 4, 1).atStartOfDay())) {
1318
                    float invoiceSchemeReversalAmount = 0;
1319
                    List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository
1320
                            .selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
1321
                    float invoiceWalletAmount = userWalletHistory.stream()
1322
                            .collect(Collectors.summingInt(y -> y.getAmount()));
1323
                    totalAmount += invoiceWalletAmount;
1324
                    try {
1325
                        walletService.rollbackAmountFromWallet(fofoOrder.getFofoId(), invoiceWalletAmount,
1326
                                fofoOrder.getId(), WalletReferenceType.SCHEME_OUT,
1327
                                "Same order for Invoice-" + invoiceNumber + "created twice, duplicate invoice rollback",
1328
                                fofoOrder.getCancelledTimestamp());
1329
                    } catch (Exception e) {
1330
                        LOGGER.info("Failed wallet update Reson [{}]", e.getMessage());
1331
                    }
1332
                    LOGGER.info("inventoryItemId - {}", inventoryItemId);
1333
                    List<SchemeInOut> schemeInOuts = schemeInOutRepository
1334
                            .selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId)));
1335
                    Set<Integer> schemeIds = new HashSet<>();
1336
                    Set<Integer> schemeIdsRolledback = new HashSet<>();
1337
                    for (SchemeInOut sio : schemeInOuts) {
1338
                        if (Math.abs(sio.getCreateTimestamp().until(fofoOrder.getCreateTimestamp(),
1339
                                ChronoUnit.MINUTES)) <= 35 && sio.getRolledBackTimestamp() == null) {
1340
                            LOGGER.info(sio);
1341
                            if (!schemeIds.contains(sio.getSchemeId())) {
1342
                                schemeIds.add(sio.getSchemeId());
1343
                            } else if (!schemeIdsRolledback.contains(sio.getSchemeId())) {
1344
                                schemeIdsRolledback.add(sio.getSchemeId());
1345
                                sio.setRolledBackTimestamp(LocalDateTime.now());
1346
                                schemeReverseAmount += sio.getAmount();
1347
                                invoiceSchemeReversalAmount += sio.getAmount();
1348
                            }
1349
                        }
1350
                    }
1351
                    if (Math.abs(invoiceWalletAmount - invoiceSchemeReversalAmount) > 3) {
1352
                        LOGGER.info("No Matchhhh");
1353
                    }
1354
                    LOGGER.info("invoiceWalletAmount - {}, invoiceSchemeReversalAmount {}", invoiceWalletAmount,
1355
                            invoiceSchemeReversalAmount);
1356
                }
1357
            }
1358
        }
1359
        LOGGER.info(
1360
                "Total Sale Amount Reversal - {}, Total Wallet Amount Reversal {}, Total Scheme Reversal Amount - {}",
1361
                saleAmount, totalAmount, schemeReverseAmount);
1362
        // throw new Exception();
1363
    }
27430 amit.gupta 1364
 
31461 amit.gupta 1365
    public void createGeofence() throws IOException, ProfitMandiBusinessException {
27450 tejbeer 1366
 
31461 amit.gupta 1367
        // List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
1368
        // for (FofoStore fofoStore : fofoStores) {
1369
        // if (fofoStore.getLatitude() != null && fofoStore.getLongitude() != null) {
1370
        CustomRetailer customRetailer = retailerService.getFofoRetailer(175138812);
1371
        OkHttpClient client = new OkHttpClient();
1372
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
1373
        JSONObject geofe = new JSONObject();
1374
        JSONArray geofences = new JSONArray();
1375
        JSONObject geometry = new JSONObject();
1376
        JSONObject geo = new JSONObject();
1377
        JSONArray coordinates = new JSONArray();
1378
        ArrayList<Double> crds = new ArrayList<>();
1379
        // crds.add(Double.parseDouble(fofoStore.getLongitude()));
1380
        // crds.add(Double.parseDouble(fofoStore.getLatitude()));
1381
        crds.add(79.739197);
1382
        crds.add(27.961215);
1383
        // crds.add(77.08596155373755);
1384
        // crds.add(28.64944201113976);
1385
        // coordinates.put(fofoStore.getLongitude());
1386
        // coordinates.put(fofoStore.getLatitude());
1387
        geo.put("type", "Point");
1388
        geo.put("coordinates", crds);
1389
        geometry.put("geometry", geo);
1390
        JSONObject metadata = new JSONObject();
1391
        metadata.put("name", customRetailer.getBusinessName());
1392
        metadata.put("city", customRetailer.getAddress().getCity());
1393
        metadata.put("Code", customRetailer.getCode());
1394
        geometry.put("metadata", metadata);
1395
        geometry.put("radius", 200);
27451 tejbeer 1396
 
31461 amit.gupta 1397
        geofences.put(geometry);
1398
        geofe.put("geofences", geofences);
1399
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
1400
        String authString = "Basic "
1401
                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27450 tejbeer 1402
 
31461 amit.gupta 1403
        Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
1404
                .addHeader("Authorization", authString).build();
27450 tejbeer 1405
 
31461 amit.gupta 1406
        Response response = client.newCall(request1).execute();
27450 tejbeer 1407
 
31461 amit.gupta 1408
        JSONArray ja = new JSONArray(response.body().string());
1409
        LOGGER.info("geofence" + ja);
1410
        LOGGER.info("jalength" + ja.length());
1411
        /*
1412
         * for (int i = 0; i < ja.length(); i++) { JSONObject c = ja.getJSONObject(i);
1413
         * String geofenceId = c.getString("geofence_id"); LOGGER.info("geofenceId" +
1414
         * geofenceId); FofoStoreGeofence fsg = new FofoStoreGeofence();
1415
         * fsg.setFofoId(customRetailer.getPartnerId()); fsg.setGeofenceId(geofenceId);
1416
         * fofoStoreGeofenceRepository.persist(fsg); }
1417
         *
1418
         * }
1419
         *
1420
         * }
1421
         */
27482 tejbeer 1422
 
31461 amit.gupta 1423
    }
27462 tejbeer 1424
 
31461 amit.gupta 1425
    public void getAllGeofences() throws IOException, ProfitMandiBusinessException {
27450 tejbeer 1426
 
31461 amit.gupta 1427
        OkHttpClient client = new OkHttpClient();
27450 tejbeer 1428
 
31461 amit.gupta 1429
        String authString = "Basic "
1430
                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27450 tejbeer 1431
 
31461 amit.gupta 1432
        // Get geofences created for all app users
1433
        Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences")
1434
                .addHeader("Authorization", authString).build();
27450 tejbeer 1435
 
31461 amit.gupta 1436
        Response response = client.newCall(request1).execute();
27451 tejbeer 1437
 
31461 amit.gupta 1438
        LOGGER.info("response" + response.body().string());
1439
    }
27450 tejbeer 1440
 
31461 amit.gupta 1441
    public void deleteGeofences(List<String> geofenceIds) throws IOException, ProfitMandiBusinessException {
1442
        OkHttpClient client = new OkHttpClient();
27457 tejbeer 1443
 
31461 amit.gupta 1444
        String authString = "Basic "
1445
                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27457 tejbeer 1446
 
31461 amit.gupta 1447
        for (String geofenceId : geofenceIds) {
1448
            Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences/" + geofenceId)
1449
                    .delete().addHeader("Authorization", authString).build();
1450
            LOGGER.info("geofenceId" + geofenceId);
1451
            Response response = client.newCall(request1).execute();
27457 tejbeer 1452
 
31461 amit.gupta 1453
            LOGGER.info("response" + response.body().string());
1454
        }
27457 tejbeer 1455
 
31461 amit.gupta 1456
    }
27457 tejbeer 1457
 
31461 amit.gupta 1458
    public void processSchemeOut(int fofoId, int orderId) throws Exception {
1459
        schemeService.processSchemeOut(orderId, fofoId);
27451 tejbeer 1460
 
31461 amit.gupta 1461
    }
27511 amit.gupta 1462
 
31461 amit.gupta 1463
    public void createDummyInvoices() {
1464
        List<WarehouseInventoryItem> lavaInventoryItems = warehouseInventoryItemRepository.getSerialNumbers("Lava",
1465
                LocalDate.of(2020, Month.SEPTEMBER, 1).atStartOfDay(), LocalDateTime.now());
1466
        LOGGER.info("Lava Inventory Size is {}", lavaInventoryItems.size());
1467
    }
28624 amit.gupta 1468
 
31461 amit.gupta 1469
    @Autowired
1470
    private WarehouseScanRepository warehouseScanRepository;
28046 amit.gupta 1471
 
31461 amit.gupta 1472
    @Autowired
1473
    private WarehouseInventoryService warehouseInventoryService;
28624 amit.gupta 1474
 
31461 amit.gupta 1475
    public void genericCreateCurrentInventorySnapshot() throws Exception {
1476
        purchaseService.genericCreateCurrentInventorySnapshot(175138856, 32820, 2);
1477
    }
29867 tejbeer 1478
 
33260 amit.gupta 1479
    public void fixScans() throws ProfitMandiBusinessException {
31461 amit.gupta 1480
        Map<Integer, Integer> inventoryOrderMap = new HashMap<>();
1481
        inventoryOrderMap.put(348795, 1628598);
1482
        inventoryOrderMap.put(348796, 1628599);
1483
        inventoryOrderMap.put(329854, 1628600);
1484
        inventoryOrderMap.put(334197, 1628602);
1485
        inventoryOrderMap.put(330110, 1628603);
1486
        inventoryOrderMap.put(330111, 1628604);
1487
        inventoryOrderMap.put(332843, 1628605);
1488
        inventoryOrderMap.put(338067, 1628606);
1489
        inventoryOrderMap.put(338974, 1628609);
1490
        inventoryOrderMap.put(338975, 1628610);
1491
        inventoryOrderMap.put(338971, 1628612);
1492
        inventoryOrderMap.put(338588, 1628615);
1493
        inventoryOrderMap.put(368205, 1631619);
1494
        inventoryOrderMap.put(368206, 1631620);
1495
        inventoryOrderMap.put(368207, 1631621);
1496
        inventoryOrderMap.put(368208, 1631622);
1497
        inventoryOrderMap.put(368209, 1631623);
1498
        inventoryOrderMap.put(368211, 1631625);
1499
        inventoryOrderMap.put(368213, 1631627);
1500
        inventoryOrderMap.put(368214, 1631628);
1501
        inventoryOrderMap.put(368203, 1631629);
1502
        inventoryOrderMap.put(368216, 1631630);
1503
        inventoryOrderMap.put(368217, 1631631);
1504
        inventoryOrderMap.put(368218, 1631632);
1505
        inventoryOrderMap.put(368219, 1631633);
1506
        inventoryOrderMap.put(368222, 1631635);
1507
        List<WarehouseScan> scans = warehouseScanRepository
1508
                .selectAllByInventoryItemIds(new ArrayList<>(inventoryOrderMap.keySet()));
1509
        Map<Integer, List<WarehouseScan>> inventoryScansMap = scans.stream()
1510
                .collect(Collectors.groupingBy(WarehouseScan::getInventoryItemId));
28624 amit.gupta 1511
 
31461 amit.gupta 1512
        for (Map.Entry<Integer, List<WarehouseScan>> mapEntry : inventoryScansMap.entrySet()) {
1513
            int inventoryItemId = mapEntry.getKey();
1514
            List<WarehouseScan> duplicateScans = mapEntry.getValue().stream().filter(
1515
                            x -> x.getOrderId() != null && x.getOrderId().equals(inventoryOrderMap.get(inventoryItemId)))
1516
                    .collect(Collectors.toList());
1517
            WarehouseScan duplicateScan = duplicateScans.stream().skip(1).findFirst().get();
1518
            warehouseScanRepository.delete(duplicateScan);
1519
            warehouseInventoryService.addQuantity(duplicateScan.getInventoryItemId(), duplicateScan.getQuantity());
28624 amit.gupta 1520
 
31461 amit.gupta 1521
        }
28624 amit.gupta 1522
 
31461 amit.gupta 1523
    }
28038 amit.gupta 1524
 
31461 amit.gupta 1525
    public void fixOffer() throws Exception {
1526
        List<Integer> offerIds = Arrays.asList(228, 241, 242, 243, 244, 253);
1527
        List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.getWarehouseId() == 7678)
1528
                .map(x -> x.getId()).collect(Collectors.toList());
1529
        LOGGER.info("UP West Partner Ids - {}", fofoIds);
1530
        for (int offerId : offerIds) {
1531
            Offer offer = offerRepository.selectById(offerId);
28624 amit.gupta 1532
 
31461 amit.gupta 1533
            PartnerCriteria partnerCriteria = gson.fromJson(offer.getPartnerCriteria(), PartnerCriteria.class);
1534
            LOGGER.info("Offer Partner Ids - {}", partnerCriteria.getFofoIds());
1535
            for (Integer fofoId : fofoIds) {
1536
                if (partnerCriteria.getFofoIds().contains(fofoId)) {
1537
                    // This shoud be removed
1538
                    LOGGER.info("This shoud be removed FofoStore Code - {}",
1539
                            fofoStoreRepository.selectByRetailerId(fofoId).getCode());
1540
                    partnerCriteria.getFofoIds().remove(fofoId);
1541
                }
1542
            }
1543
            offer.setPartnerCriteria(gson.toJson(partnerCriteria));
1544
        }
1545
    }
28624 amit.gupta 1546
 
31461 amit.gupta 1547
    public void reverseMaa() throws Exception {
1548
        Purchase purchase = purchaseRepository.selectById(28877);
1549
        Set<Integer> inventoryItemIds = inventoryItemRepository.selectByPurchaseId(28877).stream().map(x -> x.getId())
1550
                .collect(Collectors.toSet());
1551
        double totalAmount = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIds).stream()
1552
                /*
1553
                 * .filter(x -> x.getRolledBackTimestamp() == null ||
1554
                 * x.getStatusDescription().contains("investment")) .map(x -> {
1555
                 * x.setRolledBackTimestamp(LocalDateTime.now());
1556
                 * x.setStatus(SchemePayoutStatus.REJECTED); x.
1557
                 * setStatusDescription("Invoice-NSLCK3350 was cancelled, hence all schemes were rolled back"
1558
                 * ); return x; })
1559
                 */
1560
                .collect(Collectors.summingDouble(x -> x.getAmount()));
1561
        WalletReferenceType walletReferenceType = WalletReferenceType.OTHERS;
1562
        ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(walletReferenceType);
1563
        if (paymentType == null) {
1564
            paymentType = new ManualPaymentType();
1565
            paymentType.setReferenceType(walletReferenceType);
1566
            manualPaymentRequestRepository.persist(paymentType);
1567
        }
1568
        paymentType.setCounter(paymentType.getCounter() + 1);
1569
        int reference = paymentType.getCounter();
1570
        walletService.consumeAmountFromWallet(purchase.getFofoId(), reference, WalletReferenceType.OTHERS,
1571
                "Invoice-NSLCK3350 was cancelled, hence all schemes were rolled back", (int) totalAmount,
1572
                LocalDateTime.now());
1573
        LOGGER.info("Total Deduction is around Rs. {}", totalAmount);
1574
    }
28557 amit.gupta 1575
 
31461 amit.gupta 1576
    public void opporeno() {
1577
        List<Integer> offerIds = Arrays.asList(270, 269, 267, 265, 264, 257, 253, 244, 243, 242, 241, 240, 239, 228,
1578
                227, 226, 225);
1579
        for (Integer offerId : offerIds) {
1580
            Offer offer = offerRepository.selectById(offerId);
1581
            com.spice.profitmandi.service.offers.ItemCriteria itemCriteria = gson.fromJson(offer.getItemCriteria(),
1582
                    com.spice.profitmandi.service.offers.ItemCriteria.class);
1583
            if (itemCriteria.getExcludeCatalogIds().contains(1022950)) {
1584
                System.out.println("Excludes reno");
1585
            } else {
1586
                System.out.println("Does not excludes reno.. excluding it");
1587
                itemCriteria.getExcludeCatalogIds().add(1022950);
1588
                offer.setItemCriteria(gson.toJson(itemCriteria));
1589
            }
28660 amit.gupta 1590
 
31461 amit.gupta 1591
        }
1592
    }
28810 amit.gupta 1593
 
31461 amit.gupta 1594
    @Autowired
1595
    SaholicReservationSnapshotRepository saholicReservationSnapshotRepository;
28810 amit.gupta 1596
 
31461 amit.gupta 1597
    public void fixReservations() throws Exception {
1598
        // Clear all Reservations
1599
        saholicInventorySnapshotRepository.selectAll().stream().forEach(x -> x.setReserved(0));
1600
        saholicReservationSnapshotRepository.selectAll().forEach(x -> saholicReservationSnapshotRepository.delete(x));
1601
        List<Order> orders = orderRepository.selectAllOrderDatesBetweenByStatus(
1602
                LocalDate.now().minusDays(40).atStartOfDay(), LocalDateTime.now(),
1603
                OrderStatus.SUBMITTED_FOR_PROCESSING);
1604
        for (Order order : orders) {
1605
            SaholicReservationSnapshot saholicReservationSnapshot = saholicReservationSnapshotRepository
1606
                    .selectByOrderId(order.getId());
1607
            if (saholicReservationSnapshot == null) {
1608
                saholicInventoryService.addReservationCount(order.getLineItem().getItemId(),
1609
                        order.getFulfilmentWarehouseId(), order.getLineItem().getQuantity(), order.getId());
1610
            }
1611
        }
1612
    }
28736 amit.gupta 1613
 
33526 amit.gupta 1614
    public void moveOrders() throws Exception {
1615
        // Clear all Reservations
1616
        for (Map.Entry<Integer, String> integerStringEntry : ProfitMandiConstants.WAREHOUSE_MAP.entrySet()) {
1617
            transactionService.moveOrdersFulfimentWarehouse(integerStringEntry.getKey());
1618
        }
1619
    }
1620
 
31461 amit.gupta 1621
    public void fixOrders() throws Exception {
1622
        List<Order> orders = orderRepository.selectAllOrderDatesBetweenByStatus(
1623
                LocalDate.now().minusDays(10).atStartOfDay(), LocalDateTime.now(),
1624
                OrderStatus.SUBMITTED_FOR_PROCESSING);
1625
        orders = orders.stream().filter(x -> x.getCreateTimestamp().isAfter(LocalDateTime.of(2021, 7, 21, 0, 0, 0)))
1626
                .collect(Collectors.toList());
1627
        for (Order order : orders) {
28731 amit.gupta 1628
 
31461 amit.gupta 1629
            LineItem lineItem = lineItemRepository.selectById(order.getLineItem().getId());
1630
            if (order.getOrderType() == null) {
1631
                order.setProductCondition(0);
1632
                order.setOrderType(0);
1633
                int itemId = order.getLineItem().getItemId();
1634
                int fulfillmentWarehouseId = order.getFulfilmentWarehouseId();
1635
                System.out.println("Item id " + itemId);
1636
                Item item = itemRepository.selectById(itemId);
28736 amit.gupta 1637
 
31461 amit.gupta 1638
                VendorItemPricing vendorItemPricing = vendorItemPricingRepository.selectByItemIdAndVendorId(itemId,
1639
                        fulfillmentWarehouseId);
1640
                if (vendorItemPricing == null) {
1641
                    vendorItemPricing = vendorItemPricingRepository.selectAll(itemId).get(0);
1642
                }
1643
                System.out.println("vendorItemPricing " + vendorItemPricing);
1644
                lineItem.setProductGoup(item.getProductGroup());
1645
                lineItem.setColor(item.getColor());
1646
                lineItem.setNlc(vendorItemPricing.getNlc());
1647
                lineItem.setTransferPrice(vendorItemPricing.getTp());
1648
                lineItem.setLogisticsCost(0f);
1649
                lineItem.setCodCollectionCharges(0f);
28736 amit.gupta 1650
 
31461 amit.gupta 1651
            }
28736 amit.gupta 1652
 
31461 amit.gupta 1653
            int warehouseTo = fofoStoreRepository.selectByRetailerId(order.getRetailerId()).getWarehouseId();
1654
            int itemId = order.getLineItem().getItemId();
31918 amit.gupta 1655
            /*Warehouse warehouse = transactionService.getFulfilmentWarehouseMap(Arrays.asList(itemId), warehouseTo)
1656
                    .get(itemId).entrySet().stream().findFirst().get().getKey();
31461 amit.gupta 1657
            LOGGER.info(
1658
                    "Order Id - {}, WarehouseTo - {}, Item Id - {}, Warehouse From - {}, Fulfilment Warehouse Id - {}",
1659
                    order.getId(), warehouseTo, itemId, warehouse.getBillingWarehouseId(), warehouse.getId());
1660
            order.setWarehouseId(warehouse.getBillingWarehouseId());
31918 amit.gupta 1661
            order.setFulfilmentWarehouseId(warehouse.getId());*/
28731 amit.gupta 1662
 
31461 amit.gupta 1663
        }
28731 amit.gupta 1664
 
31461 amit.gupta 1665
    }
28810 amit.gupta 1666
 
31461 amit.gupta 1667
    @Autowired
1668
    PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
28675 amit.gupta 1669
 
31461 amit.gupta 1670
    public void addInvestment() {
1671
        LocalDate currentDate = LocalDate.now();
1672
        YearMonth currentMonth = YearMonth.from(currentDate);
1673
        List<LocalDate> dates = new ArrayList<>();
1674
        for (int i = 1; i < currentDate.getDayOfMonth(); i++) {
1675
            LocalDate date = currentMonth.atDay(i);
1676
            boolean exists = partnerDailyInvestmentRepository.isDateExist(date);
32211 amit.gupta 1677
            if (!exists) {
31461 amit.gupta 1678
                dates.add(date);
1679
            }
1680
        }
1681
        for (LocalDate date : dates) {
1682
            LOGGER.info("Date - {}", date);
1683
            Map<Integer, PartnerDailyInvestment> investmentMap = partnerDailyInvestmentRepository
1684
                    .selectAll(date.plusDays(1)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1685
            List<PartnerDailyInvestment> investments = partnerDailyInvestmentRepository.selectAll(date.minusDays(1));
1686
            for (PartnerDailyInvestment investment : investments) {
1687
                if (investmentMap.get(investment.getFofoId()) == null || (investmentMap.get(investment.getFofoId())
1688
                        .getShortPercentage() <= 10) == (investment.getShortPercentage() <= 10)) {
1689
                    // Do nothing add investment as is
1690
                } else {
1691
                    LOGGER.info("Problem with fofo id => {}", investment.getFofoId());
1692
                    // Lets give benefit of doubt
1693
                    if (investment.getShortPercentage() > 10) {
1694
                        investment = investmentMap.get(investment.getFofoId());
1695
                    }
1696
                }
1697
                PartnerDailyInvestment partnerDailyInvestment = new PartnerDailyInvestment();
1698
                partnerDailyInvestment.setActivatedStockAmount(investment.getActivatedStockAmount());
1699
                partnerDailyInvestment.setDate(date);
1700
                partnerDailyInvestment.setFofoId(investment.getFofoId());
1701
                partnerDailyInvestment.setMinInvestment(investment.getMinInvestment());
1702
                partnerDailyInvestment.setGrnPendingAmount(investment.getGrnPendingAmount());
1703
                partnerDailyInvestment.setActivatedStockAmount(investment.getActivatedStockAmount());
1704
                partnerDailyInvestment.setUnbilledAmount(investment.getUnbilledAmount());
1705
                partnerDailyInvestment.setReturnInTransitAmount(investment.getReturnInTransitAmount());
1706
                partnerDailyInvestment.setSalesAmount(investment.getSalesAmount());
1707
                partnerDailyInvestment.setInStockAmount(investment.getInStockAmount());
1708
                partnerDailyInvestment.setWalletAmount(investment.getWalletAmount());
1709
                partnerDailyInvestment.setActivatedGrnPendingAmount(investment.getActivatedGrnPendingAmount());
1710
                partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
1711
            }
1712
        }
1713
    }
28808 amit.gupta 1714
 
31461 amit.gupta 1715
    @Autowired
1716
    BrandRegionMappingRepository brandRegionMappingRepository;
28846 amit.gupta 1717
 
31461 amit.gupta 1718
    public void brandRegion() {
1719
        Set<Integer> warehouseIds = ProfitMandiConstants.WAREHOUSE_MAP.keySet();
1720
        Map<String, Map<Boolean, List<BrandRegionMapping>>> mapping = brandRegionMappingRepository.selectAll().stream()
1721
                .collect(Collectors.groupingBy(BrandRegionMapping::getBrand,
1722
                        Collectors.collectingAndThen(Collectors.toList(),
1723
                                x -> x.stream().collect(Collectors.groupingBy(BrandRegionMapping::isAccessory)))));
1724
        for (Map.Entry<String, Map<Boolean, List<BrandRegionMapping>>> entry : mapping.entrySet()) {
1725
            String brand = entry.getKey();
1726
            for (Map.Entry<Boolean, List<BrandRegionMapping>> isAccessoryEntry : entry.getValue().entrySet()) {
1727
                boolean isAccessory = isAccessoryEntry.getKey();
1728
                Map<Integer, List<Integer>> warehouseToIdsMap = isAccessoryEntry.getValue().stream()
1729
                        .collect(Collectors.groupingBy(BrandRegionMapping::getToWarehouseId,
1730
                                Collectors.mapping(BrandRegionMapping::getFromWarehouseId, Collectors.toList())));
1731
                for (int warehouseIdTo : warehouseIds) {
1732
                    List<Integer> warehouseIdsFrom = warehouseToIdsMap.get(warehouseIdTo);
1733
                    if (warehouseIdsFrom == null || !warehouseIdsFrom.contains(warehouseIdTo)) {
1734
                        LOGGER.info("Missing entries for brand region mapping = {}, {}, {}", brand, isAccessory,
1735
                                warehouseIdTo);
28846 amit.gupta 1736
 
31461 amit.gupta 1737
                        BrandRegionMapping brandRegionMapping = new BrandRegionMapping();
1738
                        brandRegionMapping.setAccessory(isAccessory);
1739
                        brandRegionMapping.setBrand(brand);
1740
                        brandRegionMapping.setFromWarehouseId(warehouseIdTo);
1741
                        brandRegionMapping.setToWarehouseId(warehouseIdTo);
1742
                        brandRegionMappingRepository.persist(brandRegionMapping);
28846 amit.gupta 1743
 
31461 amit.gupta 1744
                    }
1745
                }
1746
            }
1747
        }
1748
    }
28840 amit.gupta 1749
 
31461 amit.gupta 1750
    public void reverseSchemes(String invoiceNumber) throws Exception {
1751
        FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1752
        if (fofoOrder.getCancelledTimestamp() != null) {
1753
            orderService.reverseScheme(fofoOrder);
1754
        }
1755
    }
29556 amit.gupta 1756
 
31461 amit.gupta 1757
    @Autowired
1758
    PartnerTypeChangeService partnerTypeChangeService;
29863 tejbeer 1759
 
31461 amit.gupta 1760
    public void runMe() throws Exception {
29945 amit.gupta 1761
		/*System.out.println("runme ==== " + fofoOrderItemRepository.selectSumMopGroupByRetailer(
29863 tejbeer 1762
				LocalDate.of(2021, 11, 1).atStartOfDay(), LocalDate.of(2021, 12, 1).atStartOfDay(), 175138408, false));
29945 amit.gupta 1763
		System.out.println("change " + partnerTypeChangeService.getTypeOnDate(175138408, LocalDate.now()));*/
1764
 
31461 amit.gupta 1765
        List<Integer> catalogItemIds = Arrays.asList(1023209, 1023209, 1023208, 1023208, 1023199, 1023199, 1023198, 1023198, 1023200, 1023200, 1023197, 1023196, 1023113, 1023112, 1023194, 1023194, 1023194, 1023193, 1023193, 1023190, 1023190, 1023190, 1023189, 1023189, 1023189, 1023188, 1023188, 1023181, 1023181, 1023180, 1023180, 1023179, 1023179, 1023178, 1023178, 1023183, 1023183, 1023182, 1023182, 1022511, 1023066, 1023164, 1023163, 1023064, 1023174, 1023174, 1023173, 1023173, 1023172, 1023172, 1023171, 1023171, 1023171, 1022765, 1023170, 1023170, 1023166, 1023166, 1023166, 1023012, 1023073, 1023168, 1023167, 1023167, 1023118, 1023118, 1023118, 1023164, 1023163, 1023162, 1022971, 1023161, 1023160, 1023159, 1023158, 1023157, 1023156, 1023058, 1023142, 1023142, 1023141, 1023141, 1023145, 1023145, 1023145, 1023145, 1023144, 1023144, 1023144, 1023144, 1023143, 1023143, 1023143, 1023139, 1023137, 1023135, 1023134, 1023133, 1023130, 1023129, 1023126, 1023125, 1023124, 1023121, 1023128, 1023116, 1023077, 1023102, 1023079, 1023113, 1023113, 1023112, 1023112, 1023110, 1023110, 1023109, 1023109, 1023108, 1023108, 1023107, 1023107, 1022809, 1022871, 1023078, 1023101, 1023103, 1023102, 1023102, 1023100, 1023100, 1023099, 1023099, 1023079, 1023079, 1023078, 1023078, 1023081, 1023081, 1023080, 1023080, 1023080, 1022872, 1023077, 1023077, 1023076, 1023076, 1023076, 1022861, 1022970, 1023074, 1023073, 1023073, 1023072, 1023072, 1023071, 1023071, 1023045, 1023070, 1023070, 1023069, 1023063, 1023063, 1023062, 1023062, 1023061, 1023061, 1023057, 1023056, 1023055, 1023054, 1023053, 1023052, 1023068, 1023068, 1023067, 1023067, 1023066, 1023066, 1023065, 1023065, 1023064, 1023064, 1023059, 1023058, 1023058, 1023059, 1023050, 1023050, 1023049, 1023049, 1023048, 1023048, 1023047, 1023047, 1022845, 1023046, 1023046, 1023045, 1023045, 1022955, 1023044, 1023042, 1023043, 1023043, 1023043, 1023018, 1023017, 1023017, 1023016, 1023016, 1023015, 1023015, 1023041, 1023041, 1023041, 1023040, 1023039, 1023039, 1022769, 1023038, 1023038, 1023037, 1023037, 1023036, 1023036, 1023035, 1023035, 1023027, 1023027, 1023034, 1023034, 1023033, 1023033, 1023031, 1023031, 1023030, 1023029, 1023028, 1022630, 1022630, 1022630, 1023026, 1023013, 1022987, 1022982, 1023019, 1023019, 1022979, 1022978, 1022977, 1023023, 1023022, 1023022, 1023014, 1023014, 1023013, 1023013, 1022956, 1022816, 1023012, 1023012, 1023011, 1023011, 1023010, 1023010, 1023010, 1023009, 1023009, 1023006, 1023006, 1023006, 1023005, 1023005, 1023005, 1023004, 1023004, 1023004, 1023003, 1023003, 1023002, 1023002, 1023001, 1023001, 1022971, 1022970, 1022974, 1022973, 1022976, 1022976, 1022764, 1022782, 1022972, 1022972, 1022971, 1022970, 1022955, 1022956, 1022833, 1022967, 1022967, 1022967, 1022965, 1022965, 1022965, 1022965, 1022963, 1022963, 1022767, 1022962, 1022962, 1022960, 1022960, 1022957, 1022956, 1022956, 1022955, 1022955, 1022955, 1022950, 1022950, 1022944, 1022949, 1022949, 1022784, 1022566, 1022871, 1022947, 1022947, 1022946, 1022946, 1022946, 1022944, 1022944, 1022943, 1022943, 1022941, 1022941, 1022941, 1022800, 1022937, 1022937, 1022936, 1022936, 1022940, 1022940, 1022939, 1022939, 1022938, 1022931, 1022931, 1022930, 1022929, 1022934, 1022934, 1022932, 1022932, 1022783, 1022917, 1022897, 1022896, 1022893, 1022892, 1022888, 1022882, 1022833, 1022928, 1022928, 1022877, 1022877, 1022876, 1022876, 1022842, 1022875, 1022875, 1022874, 1022874, 1022872, 1022872, 1022871, 1022871, 1022809, 1022868, 1022868, 1022868, 1022867, 1022867, 1022867, 1022866, 1022866, 1022866, 1022862, 1022862, 1022862, 1022861, 1022861, 1022861, 1022859, 1022858, 1022808, 1022851, 1022851, 1022851, 1022850, 1022850, 1022850, 1022835, 1022846, 1022846, 1022845, 1022845, 1022844, 1022844, 1022843, 1022843, 1022842, 1022842, 1022841, 1022841, 1022840, 1022840, 1022839, 1022839, 1022799, 1022834, 1022834, 1022833, 1022833, 1022830, 1022830, 1022830, 1022825, 1022825, 1022824, 1022783, 1022817, 1022817, 1022816, 1022816, 1022815, 1022815, 1022814, 1022814, 1022401, 1022402, 1022400, 1022399, 1022813, 1022813, 1022813, 1022813, 1022812, 1022812, 1022812, 1022812, 1022811, 1022811, 1022811, 1022811, 1022811, 1022810, 1022810, 1022810, 1022810, 1022810, 1022809, 1022808, 1022808, 1022806, 1022806, 1022806, 1022805, 1022805, 1022805, 1022804, 1022804, 1022804, 1022803, 1022803, 1022803, 1022802, 1022802, 1022802, 1022802, 1022801, 1022801, 1022801, 1022801, 1022800, 1022800, 1022800, 1022799, 1022799, 1022799, 1022798, 1022798, 1022798, 1022797, 1022797, 1022797, 1022796, 1022796, 1022796, 1022794, 1022793, 1022792, 1022792, 1022792, 1022791, 1022791, 1022791, 1022790, 1022790, 1022790, 1022789, 1022789, 1022789, 1022785, 1022785, 1022788, 1022788, 1022784, 1022784, 1022783, 1022783, 1022782, 1022782, 1022546, 1022546, 1022781, 1022781, 1022781, 1022773, 1021600, 1022779, 1022779, 1022778, 1022774, 1022774, 1022774, 1022773, 1022773, 1022773, 1022770, 1022771, 1022771, 1022770, 1022770, 1022770, 1022769, 1022769, 1022769, 1022759, 1022758, 1022754, 1022753, 1022752, 1022757, 1022757, 1022756, 1022755, 1022767, 1022765, 1022743, 1022742, 1022742, 1022741, 1022741, 1022741, 1022740, 1022740, 1022740, 1022739, 1022739, 1022739, 1022738, 1022738, 1022738, 1022748, 1022748, 1022737, 1022677, 1022736, 1022736, 1022736, 1022735, 1022735, 1022735, 1022734, 1022734, 1022592, 1022705, 1022705, 1022699, 1022699, 1022694, 1022694, 1022693, 1022693, 1022629, 1022461, 1022592, 1022590, 1022590, 1022590, 1022590, 1022582, 1022582, 1022566, 1022565, 1022565, 1022559, 1022559, 1022559, 1022558, 1022558, 1022558, 1022546, 1022546, 1022542, 1022542, 1022541, 1022541, 1022541, 1022521, 1022521, 1022521, 1022521, 1022520, 1022520, 1022520, 1022518, 1022518, 1022518, 1022515, 1022515, 1022515, 1022514, 1022514, 1022514, 1022514, 1022511, 1022511, 1022511, 1022501, 1022501, 1022501, 1022500, 1022500, 1022500, 1021443, 1022467, 1022467, 1022467, 1022467, 1022461, 1022461, 1022465, 1022465, 1022465, 1022443, 1022451, 1022451, 1022451, 1022435, 1022435, 1022419, 1022419, 1022418, 1022418, 1022402, 1022402, 1022402, 1022401, 1022401, 1022401, 1022400, 1022400, 1022400, 1022399, 1022399, 1022399, 1022395, 1022395, 1022392, 1022392, 1015059, 1022361, 1022361, 1022010, 1021600, 1022017, 1022017, 1021848, 1022010, 1022009, 1021848, 1021848, 1021848, 1021958, 1021958, 1021958, 1021443, 1021431, 1021430, 1021429, 1021428, 1021427, 1021425, 1021424, 1021422, 1021421, 1021420, 1021419, 1021417, 1021600, 1015060, 1015061, 1003800, 1015061, 1015059, 1015059, 1015059, 1015060, 1015060, 1015060, 1003800, 1003800, 1003800, 1015061, 1015061);
1766
        for (Integer catalogItemId : catalogItemIds) {
1767
            try {
29947 amit.gupta 1768
 
31461 amit.gupta 1769
                ContentPojo cp = mongoClient.getEntityById(catalogItemId);
1770
                System.out.println(cp.getDefaultImageUrl());
1771
            } catch (Exception e) {
1772
                System.out.println("------");
1773
            }
1774
        }
1775
    }
29709 amit.gupta 1776
 
31461 amit.gupta 1777
    public void createOffers(FileInputStream stream) throws Exception {
1778
        offerService.createOffers(stream);
1779
    }
29709 amit.gupta 1780
 
31461 amit.gupta 1781
    @Autowired
1782
    MandiiService mandiiService;
29863 tejbeer 1783
 
31461 amit.gupta 1784
    @Autowired
1785
    FofoKycRepository fofoKycRepository;
29863 tejbeer 1786
 
31461 amit.gupta 1787
    @Autowired
1788
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
29863 tejbeer 1789
 
31461 amit.gupta 1790
    @Autowired
1791
    DocumentRepository documentRepository;
29863 tejbeer 1792
 
31461 amit.gupta 1793
    @Autowired
1794
    com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
29863 tejbeer 1795
 
31461 amit.gupta 1796
    public void mandiiUser(String firstName, String lastName, String pan, String dob, String aadhaar, String gender,
1797
                           String father) throws Exception {
1798
        FofoStore fs = fofoStoreRepository.selectByPan(pan);
1799
        CustomRetailer cr = retailerService.getFofoRetailer(fs.getId());
1800
        com.spice.profitmandi.dao.entity.dtr.User dtrUser = dtrUserRepository.selectByEmailId(cr.getEmail());
1801
        MandiiUser mandiiUser = mandiiService.getUser(dtrUser.getFirstName(), dtrUser.getLastName(), father,
1802
                Gender.valueOf(gender), cr.getEmail(), pan, cr.getMobileNumber(), LocalDate.parse(dob),
1803
                cr.getAddress().getLine1() + " " + cr.getAddress().getLine2(), cr.getAddress().getCity(),
1804
                cr.getAddress().getState(), cr.getAddress().getPinCode());
1805
        mandiiUser.setFatherName(father);
1806
        if (StringUtils.isNotEmpty(firstName)) {
1807
            mandiiUser.setFirstName(firstName);
1808
            mandiiUser.setLastName(lastName);
1809
        }
1810
        if (StringUtils.isNotEmpty(father)) {
1811
            mandiiUser.setFatherName(father);
1812
        }
1813
        if (StringUtils.isNotEmpty(aadhaar)) {
1814
            mandiiUser.setAadharNumber(aadhaar);
1815
        }
1816
        mandiiUser.setGender(Gender.valueOf(gender));
1817
        mandiiService.createAccount(cr.getBusinessName(), mandiiUser);
1818
    }
30209 amit.gupta 1819
 
31461 amit.gupta 1820
    @Autowired
1821
    CreditAccountRepository creditAccountRepository;
30209 amit.gupta 1822
 
31461 amit.gupta 1823
    public void mandiiUsers() throws Exception {
1824
        List<CreditAccount> creditAccounts = creditAccountRepository.selectAll();
1825
        List<Integer> fofoIds = creditAccounts.stream().filter(x -> x.getGateway().equals(Gateway.MANDII) && (x.getCreditStatus().equals(CreditStatus.UNKNOWN) || x.getCreditStatus().equals(CreditStatus.TO_BE_EVALUATED))).map(x -> x.getFofoId()).collect(Collectors.toList());
1826
        List<FofoStore> fsList = fofoStoreRepository.selectByRetailerIds(fofoIds);
1827
        for (FofoStore store : fsList) {
1828
            this.mandiiUsers(store.getPan());
1829
        }
30209 amit.gupta 1830
 
31461 amit.gupta 1831
    }
29709 amit.gupta 1832
 
31461 amit.gupta 1833
    public void mandiiUsers(String pan) throws Exception {
1834
        FofoStore fs = fofoStoreRepository.selectByPan(pan);
29863 tejbeer 1835
 
31461 amit.gupta 1836
        PartnerOnBoardingPanel pob = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
1837
        List<FofoKyc> fofoKycs = fofoKycRepository.selectByPartnerOnBoardingId(pob.getId());
1838
        CustomRetailer cr = retailerService.getFofoRetailer(fs.getId());
1839
        com.spice.profitmandi.dao.entity.dtr.User dtrUser = dtrUserRepository.selectByEmailId(cr.getEmail());
1840
        boolean ca = false;
1841
        for (FofoKyc fk : fofoKycs) {
29863 tejbeer 1842
 
31461 amit.gupta 1843
            MandiiUser mandiiUser = mandiiService.getUser(fk.getFirstName(), fk.getLastName(), fk.getFatherName(),
1844
                    fk.getGender(), fk.getEmail(), pan, fk.getMobile(), fk.getDob(),
1845
                    fk.getAddress1() + " " + fk.getAddress2() + " " + fk.getAddress3(), fk.getCity(), fk.getState(),
1846
                    fk.getPincode());
29863 tejbeer 1847
 
31461 amit.gupta 1848
            LOGGER.info("mandiiUser" + mandiiUser);
29863 tejbeer 1849
 
31461 amit.gupta 1850
            ca = mandiiService.createAccount(cr.getBusinessName(), mandiiUser);
29906 tejbeer 1851
 
31461 amit.gupta 1852
            Document panDoc = documentRepository.selectById(fk.getPanDoc());
1853
            File fPan = new File(panDoc.getPath() + panDoc.getName());
1854
            String encodeString = encodeFileToBase64Binary(fPan);
29863 tejbeer 1855
 
31461 amit.gupta 1856
            mandiiService.documentUpload(pan, fk.getMobile(), "PROPRIETOR_PAN", encodeString, null);
29863 tejbeer 1857
 
31461 amit.gupta 1858
            Document adhaarF = documentRepository.selectById(fk.getPoaFront());
1859
            File adharf = new File(adhaarF.getPath() + adhaarF.getName());
1860
            String adhaarFEncodstring = encodeFileToBase64Binary(adharf);
1861
            mandiiService.documentUpload(pan, fk.getMobile(), "AADHAAR", adhaarFEncodstring, "FRONT");
29863 tejbeer 1862
 
31461 amit.gupta 1863
            Document adhaarB = documentRepository.selectById(fk.getPoaBack());
1864
            File adharb = new File(adhaarB.getPath() + adhaarF.getName());
1865
            String adhaarBEncodstring = encodeFileToBase64Binary(adharb);
1866
            mandiiService.documentUpload(pan, fk.getMobile(), "AADHAAR", adhaarBEncodstring, "BACK");
29863 tejbeer 1867
 
31461 amit.gupta 1868
            if (ca == true) {
1869
                AccountStatusResponseOut accountStatusResponseOut = mandiiService.getStatus(fs.getPan());
1870
                this.setCreditAccount(fs.getId(), accountStatusResponseOut);
1871
            }
29893 tejbeer 1872
 
31461 amit.gupta 1873
        }
29893 tejbeer 1874
 
31461 amit.gupta 1875
    }
29863 tejbeer 1876
 
31461 amit.gupta 1877
    private void setCreditAccount(int fofoId, AccountStatusResponseOut accountStatusResponseOut) {
29893 tejbeer 1878
 
31461 amit.gupta 1879
        CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fofoId, Gateway.MANDII);
29893 tejbeer 1880
 
31461 amit.gupta 1881
        if (creditAccount == null) {
1882
            creditAccount = new CreditAccount();
1883
            creditAccount.setFofoId(fofoId);
1884
            creditAccount.setGateway(Gateway.MANDII);
1885
        }
29893 tejbeer 1886
 
31461 amit.gupta 1887
        if (accountStatusResponseOut == null) {
1888
            creditAccount.setCreditStatus(CreditStatus.UNKNOWN);
1889
            creditAccount.setDescription("User company not found");
29893 tejbeer 1890
 
31461 amit.gupta 1891
        } else {
1892
            if (accountStatusResponseOut.getSanctionLimit() != null) {
1893
                creditAccount.setSanctionedAmount(accountStatusResponseOut.getSanctionLimit().floatValue());
1894
            } else {
1895
                creditAccount.setSanctionedAmount(0);
1896
            }
29893 tejbeer 1897
 
31461 amit.gupta 1898
            creditAccount.setInterestRate(accountStatusResponseOut.getRateOfInterest());
1899
            if (accountStatusResponseOut.getBalanceAmount() != null) {
1900
                creditAccount.setAvailableAmount(accountStatusResponseOut.getBalanceAmount().floatValue());
1901
            } else {
1902
                creditAccount.setAvailableAmount(0);
1903
            }
29893 tejbeer 1904
 
31461 amit.gupta 1905
            if (accountStatusResponseOut.getCurrentStage() != null) {
1906
                creditAccount.setDescription(accountStatusResponseOut.getCurrentStage().toString());
1907
            }
1908
            if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.SANCTION_AVAILABLE)) {
1909
                creditAccount.setCreditStatus(CreditStatus.SANCTIONED);
1910
            } else if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.IN_ELIGIBLE)) {
1911
                creditAccount.setCreditStatus(CreditStatus.INELIGIBLE);
1912
            } else {
29893 tejbeer 1913
 
31461 amit.gupta 1914
                creditAccount.setCreditStatus(CreditStatus.TO_BE_EVALUATED);
1915
            }
1916
        }
29893 tejbeer 1917
 
31461 amit.gupta 1918
        creditAccount.setUpdatedOn(LocalDateTime.now());
1919
        creditAccountRepository.persist(creditAccount);
1920
    }
29893 tejbeer 1921
 
31461 amit.gupta 1922
    private static String encodeFileToBase64Binary(File file) throws Exception {
1923
        FileInputStream fileInputStreamReader = new FileInputStream(file);
1924
        byte[] bytes = new byte[(int) file.length()];
1925
        fileInputStreamReader.read(bytes);
1926
        return new String(Base64.getEncoder().encodeToString(bytes));
1927
    }
29863 tejbeer 1928
 
31461 amit.gupta 1929
    public void testIrnLive(String invoiceNumber) throws Exception {
1930
        List<Order> orders = orderRepository.selectByInvoiceNumber(invoiceNumber);
1931
        gstProService.getEInvoice(orders);
1932
    }
30209 amit.gupta 1933
 
31461 amit.gupta 1934
    public void processSchemeByIds(List<Integer> schemeIds) throws Exception {
1935
        List<Scheme> schemes = schemeRepository.selectBySchemeIds(schemeIds);
1936
        for (Scheme scheme : schemes) {
1937
            List<Integer> catalogIds = schemeItemRepository.selectBySchemeIds(new HashSet<>(Arrays.asList(scheme.getId()))).stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
34326 amit.gupta 1938
            if (scheme.getType().getTransactionType().equals(StockTransactionType.OUT)) {
31461 amit.gupta 1939
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectOrderByModelAndSaleBetween(catalogIds, scheme.getStartDateTime(), scheme.getEndDateTime());
1940
                for (FofoOrder fofoOrder : fofoOrders) {
1941
                    System.out.println("Processing fofoOrder --- " + fofoOrder.getInvoiceNumber());
1942
                    System.out.println("Processing fofoOrder --- " + fofoOrder.getInvoiceNumber());
1943
                    schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
1944
                }
34326 amit.gupta 1945
            } else if (Arrays.asList(StockTransactionType.IN).contains(scheme.getType())) {
31461 amit.gupta 1946
                List<Purchase> purchases = purchaseRepository.selectPurchaseByCatalogsAndSaleBetween(catalogIds, scheme.getStartDateTime(), scheme.getEndDateTime());
1947
                for (Purchase purchase : purchases) {
1948
                    System.out.println("Processing purchase --- " + purchase.getPurchaseReference());
1949
                    schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
1950
                }
30644 amit.gupta 1951
 
31461 amit.gupta 1952
            }
1953
        }
1954
    }
30642 amit.gupta 1955
 
31461 amit.gupta 1956
    @Autowired
1957
    InsurancePolicyRepository insurancePolicyRepository;
30642 amit.gupta 1958
 
34326 amit.gupta 1959
    @Autowired
1960
    CreditNoteLineRepository creditNoteLineRepository;
1961
 
1962
    @Autowired
1963
    CreditNoteRepository creditNoteRepository;
1964
 
31461 amit.gupta 1965
    public void addMissingWalletDebitsForInsurance() throws Exception {
1966
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(5, Optional.empty());
1967
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
1968
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(insurancePolicy.getInvoiceNumber());
1969
            List<UserWalletHistory> userWalletHistories = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(insurancePolicy.getId(), WalletReferenceType.DAMAGE_PROTECTION);
1970
            if (userWalletHistories.size() > 1) {
1971
                UserWalletHistory userWalletHistory = userWalletHistories.get(0);
1972
                walletService.addAmountToWallet(insurancePolicy.getRetailerId(), userWalletHistory.getReference(), WalletReferenceType.DAMAGE_PROTECTION, "Excess deduction - settled", 198, LocalDateTime.now());
1973
            }
1974
        }
1975
    }
33260 amit.gupta 1976
 
1977
    public void changeFulfillmentWarehouse(int orderId, int whId) throws ProfitMandiBusinessException {
1978
        transactionService.changeFulfillmentWarehouse(orderId, whId);
1979
    }
34326 amit.gupta 1980
 
1981
 
1982
    public void findCNDiff() throws ProfitMandiBusinessException {
1983
        LocalDate startDate = LocalDate.of(2022, 9, 01);
1984
        List<UserWalletHistory> userWalletHistories = userWalletHistoryRepository.selectAllByDateType(startDate.atStartOfDay(), startDate.plusYears(3).atStartOfDay().withMonth(Month.JANUARY.getValue()), Arrays.asList(WalletReferenceType.ACTIVATION_SCHEME, WalletReferenceType.ADDITIONAL_SCHEME, WalletReferenceType.INVESTMENT_PAYOUT
1985
                , WalletReferenceType.SPECIAL_SUPPORT, WalletReferenceType.PRICE_DROP, WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
1986
 
1987
        Map<Integer, Map<YearMonth, Double>> fofoMonthAmount = userWalletHistories.stream().collect(Collectors.groupingBy(x -> x.getWalletId(),
1988
                Collectors.groupingBy(x -> YearMonth.from(x.getTimestamp()), Collectors.summingDouble(x -> x.getAmount()))));
1989
 
1990
        System.out.println("FofoId\tYearMonth\tWallet\tCN");
1991
        for (Map.Entry<Integer, Map<YearMonth, Double>> fofoMonthAmountEntry : fofoMonthAmount.entrySet()) {
1992
            int walletId = fofoMonthAmountEntry.getKey();
1993
            int fofoId = userWalletRepository.selectById(walletId).getUserId();
1994
            for (Map.Entry<YearMonth, Double> yearMonthAmountEntry : fofoMonthAmountEntry.getValue().entrySet()) {
1995
                YearMonth yearMonth = yearMonthAmountEntry.getKey();
1996
                double walletAmount = yearMonthAmountEntry.getValue();
1997
                double cnAmount = 0;
1998
                List<Integer> creditNoteIds = creditNoteRepository.selectAll(fofoId, yearMonth).stream().map(cn -> cn.getId()).collect(Collectors.toList());
34710 amit.gupta 1999
                if (creditNoteIds.size() > 0) {
34326 amit.gupta 2000
                    cnAmount = creditNoteLineRepository.selectAllByCreditNoteIds(creditNoteIds).stream().collect(Collectors.summingDouble(CreditNoteLine::getAmount));
2001
                }
34710 amit.gupta 2002
                if (cnAmount != walletAmount) {
34326 amit.gupta 2003
                    System.out.println(fofoId + "\t" + yearMonth + "\t" + walletAmount + "\t" + cnAmount);
2004
                }
2005
            }
2006
        }
2007
 
2008
    }
34770 vikas.jang 2009
 
34836 vikas 2010
    public void yesterdayTrackingReport() throws Exception{
2011
        locationTrackingService.generateReport(0, LocalDate.now().minusDays(1).toString(),LocalDate.now().minusDays(1).toString());
34770 vikas.jang 2012
    }
34836 vikas 2013
 
2014
    public void dailyTrackingReport() throws Exception{
2015
        locationTrackingService.generateReport(0, LocalDate.now().toString(),LocalDate.now().toString());
2016
    }
34946 ranu 2017
 
2018
    public void setAbmReportSender() throws Exception{
2019
        abmReportSender.abmSendertest();
2020
    }
35105 vikas 2021
 
2022
    public void checkRewardsEligibility() throws Exception {
2023
        saleRewardService.disburseRewardsByEligibility(LocalDate.now());
2024
    }
25043 amit.gupta 2025
}
2026
 
2027
//7015845171