Subversion Repositories SmartDukaan

Rev

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