Subversion Repositories SmartDukaan

Rev

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

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