Subversion Repositories SmartDukaan

Rev

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

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