Subversion Repositories SmartDukaan

Rev

Rev 35613 | Details | Compare with Previous | Last modification | View Log | RSS feed

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