Subversion Repositories SmartDukaan

Rev

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