Subversion Repositories SmartDukaan

Rev

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