Subversion Repositories SmartDukaan

Rev

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

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