Subversion Repositories SmartDukaan

Rev

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