Subversion Repositories SmartDukaan

Rev

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