Subversion Repositories SmartDukaan

Rev

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