Subversion Repositories SmartDukaan

Rev

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

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