Subversion Repositories SmartDukaan

Rev

Rev 37658 | Rev 37751 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 37658 Rev 37735
Line 82... Line 82...
82
import com.spice.profitmandi.dao.service.shopify.ShopifyProductSyncService;
82
import com.spice.profitmandi.dao.service.shopify.ShopifyProductSyncService;
83
import com.spice.profitmandi.dao.service.solr.FofoSolr;
83
import com.spice.profitmandi.dao.service.solr.FofoSolr;
84
import com.spice.profitmandi.service.*;
84
import com.spice.profitmandi.service.*;
85
import com.spice.profitmandi.service.integrations.CCAvenuePaymentService;
85
import com.spice.profitmandi.service.integrations.CCAvenuePaymentService;
86
import com.spice.profitmandi.service.integrations.RazorpayPaymentService;
86
import com.spice.profitmandi.service.integrations.RazorpayPaymentService;
87
import com.spice.profitmandi.service.integrations.bharti.model.BAGInsuranceModel;
-
 
88
import com.spice.profitmandi.service.integrations.gstpro.GstProAuthService;
87
import com.spice.profitmandi.service.integrations.gstpro.GstProAuthService;
89
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
88
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
90
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsAffordabilityService;
89
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsAffordabilityService;
91
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsAuthService;
90
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsAuthService;
92
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsOfferCacheService;
91
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsOfferCacheService;
93
import com.spice.profitmandi.service.integrations.pinelabs.dto.*;
92
import com.spice.profitmandi.service.integrations.pinelabs.dto.*;
94
import com.spice.profitmandi.service.integrations.psismart.PsiSmartService;
93
import com.spice.profitmandi.service.integrations.psismart.PsiSmartService;
95
import com.spice.profitmandi.service.integrations.smartping.SmartPingService;
-
 
96
import com.spice.profitmandi.service.integrations.toffee.ToffeeService;
-
 
97
import com.spice.profitmandi.service.inventory.*;
94
import com.spice.profitmandi.service.inventory.*;
98
import com.spice.profitmandi.service.AgendaSyncResult;
95
import com.spice.profitmandi.service.AgendaSyncResult;
99
import com.spice.profitmandi.service.mail.MailOutboxService;
96
import com.spice.profitmandi.service.mail.MailOutboxService;
100
import com.spice.profitmandi.service.offers.OfferService;
97
import com.spice.profitmandi.service.offers.OfferService;
101
import com.spice.profitmandi.service.order.OrderService;
98
import com.spice.profitmandi.service.order.OrderService;
Line 159... Line 156...
159
import java.util.stream.Collectors;
156
import java.util.stream.Collectors;
160
import java.util.stream.Stream;
157
import java.util.stream.Stream;
161
 
158
 
162
import static java.util.stream.Collectors.*;
159
import static java.util.stream.Collectors.*;
163
 
160
 
164
 
-
 
165
@Component
161
@Component
166
@Transactional(rollbackFor = {Throwable.class, ProfitMandiBusinessException.class})
162
@Transactional(rollbackFor = {Throwable.class, ProfitMandiBusinessException.class})
167
public class ScheduledTasks {
163
public class ScheduledTasks {
168
 
164
 
169
    // Lock to serialize all methods that write to sd_credit_requirement table.
165
    // Lock to serialize all methods that write to sd_credit_requirement table.
Line 187... Line 183...
187
 
183
 
188
    @Autowired
184
    @Autowired
189
    private com.spice.profitmandi.service.AgendaAutoRuleService agendaAutoRuleService;
185
    private com.spice.profitmandi.service.AgendaAutoRuleService agendaAutoRuleService;
190
 
186
 
191
    @Autowired
187
    @Autowired
192
    SmartPingService smartPingService;
-
 
193
 
-
 
194
    @Autowired
-
 
195
    private ASTRepository astRepository;
188
    private ASTRepository astRepository;
196
 
189
 
197
    @Autowired
190
    @Autowired
198
    private ServiceConfigService serviceConfigService;
191
    private ServiceConfigService serviceConfigService;
199
 
192
 
Line 209... Line 202...
209
    CarlcareImeiActivationService carlcareImeiActivationService;
202
    CarlcareImeiActivationService carlcareImeiActivationService;
210
 
203
 
211
    @Autowired
204
    @Autowired
212
    private PartnerTypeChangeService partnerTypeChangeService;
205
    private PartnerTypeChangeService partnerTypeChangeService;
213
 
206
 
214
 
-
 
215
    @Autowired
207
    @Autowired
216
    private LeadRepository leadRepository;
208
    private LeadRepository leadRepository;
217
 
209
 
218
    @Autowired
210
    @Autowired
219
    private AuthRepository authRepository;
211
    private AuthRepository authRepository;
Line 237... Line 229...
237
    private SaholicInventoryService saholicInventoryService;
229
    private SaholicInventoryService saholicInventoryService;
238
 
230
 
239
    @Autowired
231
    @Autowired
240
    private InsurancePolicyRepository insurancePolicyRepository;
232
    private InsurancePolicyRepository insurancePolicyRepository;
241
 
233
 
242
    @Autowired
-
 
243
    private ToffeeService toffeeService;
-
 
244
 
234
 
245
    @Value("${oxigen.recharge.auth.key}")
235
    @Value("${oxigen.recharge.auth.key}")
246
    private String oxigenRechargeAuthKey;
236
    private String oxigenRechargeAuthKey;
247
 
237
 
248
    @Value("${oxigen.recharge.validation.url}")
238
    @Value("${oxigen.recharge.validation.url}")
Line 489... Line 479...
489
    private CustomerRepository customerRepository;
479
    private CustomerRepository customerRepository;
490
 
480
 
491
    @Autowired
481
    @Autowired
492
    private RestClient restClient;
482
    private RestClient restClient;
493
 
483
 
494
 
-
 
495
    @Autowired
484
    @Autowired
496
    CreditAccountRepository creditAccountRepository;
485
    CreditAccountRepository creditAccountRepository;
497
 
486
 
498
    @Autowired
487
    @Autowired
499
    CustomerOfferRepository customerOfferRepository;
488
    CustomerOfferRepository customerOfferRepository;
Line 501... Line 490...
501
    @Autowired
490
    @Autowired
502
    CustomerOfferItemRepository customerOfferItemRepository;
491
    CustomerOfferItemRepository customerOfferItemRepository;
503
    @Autowired
492
    @Autowired
504
    private FofoSolr fofoSolr;
493
    private FofoSolr fofoSolr;
505
 
494
 
506
 
-
 
507
    private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
495
    private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
508
 
496
 
509
    private String FCM_URL = "https://fcm.googleapis.com/v1/projects/api-project-309385327230/messages:send";
497
    private String FCM_URL = "https://fcm.googleapis.com/v1/projects/api-project-309385327230/messages:send";
510
    private String FCM_SCOPED = "https://www.googleapis.com/auth/cloud-platform";
498
    private String FCM_SCOPED = "https://www.googleapis.com/auth/cloud-platform";
511
 
499
 
Line 750... Line 738...
750
                schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
738
                schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
751
            }
739
            }
752
        }
740
        }
753
    }
741
    }
754
 
742
 
755
 
-
 
756
    public void rollOutUpgardedMargins(List<Integer> fofoIds) throws Exception {
743
    public void rollOutUpgardedMargins(List<Integer> fofoIds) throws Exception {
757
        LocalDate today = LocalDate.now();
744
        LocalDate today = LocalDate.now();
758
        LocalDate yesterday = today.minusDays(1);
745
        LocalDate yesterday = today.minusDays(1);
759
        int upgradedCount = 0;
746
        int upgradedCount = 0;
760
        List<FofoStore> stores;
747
        List<FofoStore> stores;
Line 891... Line 878...
891
        Map<String, AgeingModel> ageingModelMap = ageingService.getAllAgeingForSecondary();
878
        Map<String, AgeingModel> ageingModelMap = ageingService.getAllAgeingForSecondary();
892
 
879
 
893
        System.out.println(ageingModelMap.size());
880
        System.out.println(ageingModelMap.size());
894
        List<PartnerAgeingModel> partnerAgeingModels = ageingService.getAllAgeingForTertiary();
881
        List<PartnerAgeingModel> partnerAgeingModels = ageingService.getAllAgeingForTertiary();
895
 
882
 
896
 
-
 
897
        ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("InventoryItemId", "Serial Number", "Item Id", "Brand", "Model Name", "ModelNumber", "Color", "Exceed Days", "Last ScanType", "Supplier Name", "Current Warehouse", "First Warehouse", "Invoice Number", "Invoice Date"), ageingModelMap.values().stream().map(x -> Arrays.asList(x.getInventoryItemId(), x.getSerialNumber(), x.getItemId(), x.getBrand(), x.getModelName(), x.getModelNumber(), x.getColor(), x.getExceedDays(), x.getLastScanType(), x.getSupplierName(), x.getCurrentWarehouse(), x.getFirstWarehouse(), x.getInvoiceNumber(), FormattingUtils.formatDate(x.getInvoiceDate()))).collect(Collectors.toList()));
883
        ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("InventoryItemId", "Serial Number", "Item Id", "Brand", "Model Name", "ModelNumber", "Color", "Exceed Days", "Last ScanType", "Supplier Name", "Current Warehouse", "First Warehouse", "Invoice Number", "Invoice Date"), ageingModelMap.values().stream().map(x -> Arrays.asList(x.getInventoryItemId(), x.getSerialNumber(), x.getItemId(), x.getBrand(), x.getModelName(), x.getModelNumber(), x.getColor(), x.getExceedDays(), x.getLastScanType(), x.getSupplierName(), x.getCurrentWarehouse(), x.getFirstWarehouse(), x.getInvoiceNumber(), FormattingUtils.formatDate(x.getInvoiceDate()))).collect(Collectors.toList()));
898
 
884
 
899
        ByteArrayOutputStream byteArrayOutputStream2 = FileUtil.getCSVByteStream(Arrays.asList("InventoryItemId", "Serial Number", "Item Id", "Brand", "Model Name", "ModelNumber", "Color", "Partner Id", "Partner Code", "Partner Name", "Activation Type", "City", "State", "Billing Date", "Exceed Days", "Max Ageing", "Activation Date"), partnerAgeingModels.stream().map(x -> Arrays.asList(x.getInventoryItemId(), x.getSerialNumber(), x.getItemId(), x.getBrand(), x.getModelName(), x.getModelNumber(), x.getColor(), x.getFofoId(), x.getFofoCode(), x.getFofoName(), x.getActivationType(), x.getFofoCity(), x.getFofoState(), FormattingUtils.formatDate(x.getBillingDate()), x.getExceedDays(), x.getMaxAgeingDays(), x.getActivationDate())).collect(Collectors.toList()));
885
        ByteArrayOutputStream byteArrayOutputStream2 = FileUtil.getCSVByteStream(Arrays.asList("InventoryItemId", "Serial Number", "Item Id", "Brand", "Model Name", "ModelNumber", "Color", "Partner Id", "Partner Code", "Partner Name", "Activation Type", "City", "State", "Billing Date", "Exceed Days", "Max Ageing", "Activation Date"), partnerAgeingModels.stream().map(x -> Arrays.asList(x.getInventoryItemId(), x.getSerialNumber(), x.getItemId(), x.getBrand(), x.getModelName(), x.getModelNumber(), x.getColor(), x.getFofoId(), x.getFofoCode(), x.getFofoName(), x.getActivationType(), x.getFofoCity(), x.getFofoState(), FormattingUtils.formatDate(x.getBillingDate()), x.getExceedDays(), x.getMaxAgeingDays(), x.getActivationDate())).collect(Collectors.toList()));
900
        Attachment attachment1 = new Attachment("secondary-alert.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
886
        Attachment attachment1 = new Attachment("secondary-alert.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
901
        Attachment attachment2 = new Attachment("tertiary-alert.csv", new ByteArrayResource(byteArrayOutputStream2.toByteArray()));
887
        Attachment attachment2 = new Attachment("tertiary-alert.csv", new ByteArrayResource(byteArrayOutputStream2.toByteArray()));
902
 
888
 
903
        String mailSubject = "Stock ageing Alert";
889
        String mailSubject = "Stock ageing Alert";
904
        mailOutboxService.queueMailWithAttachmentsViaGoogle(new String[]{"deena.nath@smartdukaan.com"}, null, mailSubject, "PFA", "ScheduledTasks.sendMailForAgeingAlert", attachment1, attachment2);
890
        mailOutboxService.queueMailWithAttachmentsViaGoogle(new String[]{"deena.nath@smartdukaan.com"}, null, mailSubject, "PFA", "ScheduledTasks.sendMailForAgeingAlert", attachment1, attachment2);
905
    }
891
    }
906
 
892
 
907
 
-
 
908
    public void processDeductions() {
893
    public void processDeductions() {
909
        sidbiService.processDeductions();
894
        sidbiService.processDeductions();
910
    }
895
    }
911
 
896
 
912
    public void resetHardLimit() throws ProfitMandiBusinessException {
897
    public void resetHardLimit() throws ProfitMandiBusinessException {
Line 1268... Line 1253...
1268
                sdCreditService.settleLoan(x);
1253
                sdCreditService.settleLoan(x);
1269
            } catch (ProfitMandiBusinessException e) {
1254
            } catch (ProfitMandiBusinessException e) {
1270
                throw new RuntimeException(e);
1255
                throw new RuntimeException(e);
1271
            }
1256
            }
1272
        });*/
1257
        });*/
1273
        //Utils.sendMailWithAttachments(googleMailSender, new String[]{"amit.gupta@smartdukaan.com"}, null, "DTDC AWb", "PFA");*/
-
 
1274
    }
1258
    }
1275
 
1259
 
1276
    private void regenerateDCInvoices() {
1260
    private void regenerateDCInvoices() {
1277
        List<String> dcInvoiceNumbers = Arrays.asList(
1261
        List<String> dcInvoiceNumbers = Arrays.asList(
1278
                "DCNSUPDL5", "DCNSUPDL4", "DCNSLCK2", "DCNSUPDL3",
1262
                "DCNSUPDL5", "DCNSUPDL4", "DCNSLCK2", "DCNSUPDL3",
Line 1300... Line 1284...
1300
            int loanAmount = blockedLoan.getIntialAmount().intValue();
1284
            int loanAmount = blockedLoan.getIntialAmount().intValue();
1301
            if (loanAmount > -amount) {
1285
            if (loanAmount > -amount) {
1302
                sdCreditService.settleBlockedLoan(transactionId, loanAmount + amount);
1286
                sdCreditService.settleBlockedLoan(transactionId, loanAmount + amount);
1303
            }
1287
            }
1304
 
1288
 
1305
 
-
 
1306
        }
1289
        }
1307
    }
1290
    }
1308
 
1291
 
1309
    @Autowired
1292
    @Autowired
1310
    LoanTransactionRepository loanTransactionRepository;
1293
    LoanTransactionRepository loanTransactionRepository;
Line 1324... Line 1307...
1324
            System.out.println("processedOrderIds " + processedOrderIds);
1307
            System.out.println("processedOrderIds " + processedOrderIds);
1325
            //if(unsettledBlockedLoan !=null) continue;
1308
            //if(unsettledBlockedLoan !=null) continue;
1326
            double limitToRelease = processedOrders.stream().collect(Collectors.summingDouble(x -> x.getWalletAmount()));
1309
            double limitToRelease = processedOrders.stream().collect(Collectors.summingDouble(x -> x.getWalletAmount()));
1327
            sdCreditService.releaseBlockedLimit(unsettledBlockedLoan, limitToRelease);
1310
            sdCreditService.releaseBlockedLimit(unsettledBlockedLoan, limitToRelease);
1328
 
1311
 
1329
 
-
 
1330
        }
1312
        }
1331
    }
1313
    }
1332
 
1314
 
1333
    private void fixStuckLimitBlocks(int maxFixes) {
1315
    private void fixStuckLimitBlocks(int maxFixes) {
1334
        int[] stuckIds = {100908, 100909, 102018, 104843, 105119, 105613, 105758, 105766, 105999};
1316
        int[] stuckIds = {100908, 100909, 102018, 104843, 105119, 105613, 105758, 105766, 105999};
Line 1584... Line 1566...
1584
        //this.processOrdersToRebill(fofoIdImeiReturnMap, debitNoteDate);
1566
        //this.processOrdersToRebill(fofoIdImeiReturnMap, debitNoteDate);
1585
        purchaseReturnService.fixReturns(fofoIdImeiReturnMap, debitNoteDate);
1567
        purchaseReturnService.fixReturns(fofoIdImeiReturnMap, debitNoteDate);
1586
 
1568
 
1587
    }
1569
    }
1588
 
1570
 
1589
 
-
 
1590
    private void processOrdersToRebill(Map<Integer, Set<String>> fofoIdImeiReturnMap, LocalDateTime debitNoteDate) throws Exception {
1571
    private void processOrdersToRebill(Map<Integer, Set<String>> fofoIdImeiReturnMap, LocalDateTime debitNoteDate) throws Exception {
1591
 
1572
 
1592
 
-
 
1593
        for (Entry<Integer, Set<String>> fofoIdImeiReturnEntry : fofoIdImeiReturnMap.entrySet()) {
1573
        for (Entry<Integer, Set<String>> fofoIdImeiReturnEntry : fofoIdImeiReturnMap.entrySet()) {
1594
            int fofoId = fofoIdImeiReturnEntry.getKey();
1574
            int fofoId = fofoIdImeiReturnEntry.getKey();
1595
            Set<String> imeis = fofoIdImeiReturnEntry.getValue();
1575
            Set<String> imeis = fofoIdImeiReturnEntry.getValue();
1596
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, imeis, true);
1576
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, imeis, true);
1597
            for (InventoryItem inventoryItem : inventoryItems) {
1577
            for (InventoryItem inventoryItem : inventoryItems) {
Line 1663... Line 1643...
1663
    CommonPaymentService commonPaymentService;
1643
    CommonPaymentService commonPaymentService;
1664
 
1644
 
1665
    @Autowired
1645
    @Autowired
1666
    LineItemImeisRepository lineItemImeisRepository;
1646
    LineItemImeisRepository lineItemImeisRepository;
1667
 
1647
 
1668
 
-
 
1669
    //Also create order
1648
    //Also create order
1670
    private List<CartItem> refundDnAmount(DebitNote debitNote) throws ProfitMandiBusinessException {
1649
    private List<CartItem> refundDnAmount(DebitNote debitNote) throws ProfitMandiBusinessException {
1671
        List<Integer> inventoryItemIds = purchaseReturnItemRepository.selectAllByDebitNoteId(debitNote.getId()).stream().map(x -> x.getInventoryItemId()).collect(Collectors.toList());
1650
        List<Integer> inventoryItemIds = purchaseReturnItemRepository.selectAllByDebitNoteId(debitNote.getId()).stream().map(x -> x.getInventoryItemId()).collect(Collectors.toList());
1672
        Map<Integer, Long> inventoryItemCountMap = inventoryItemIds.stream().collect(groupingBy(x -> x, Collectors.counting()));
1651
        Map<Integer, Long> inventoryItemCountMap = inventoryItemIds.stream().collect(groupingBy(x -> x, Collectors.counting()));
1673
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(new ArrayList<>(inventoryItemCountMap.keySet()));
1652
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(new ArrayList<>(inventoryItemCountMap.keySet()));
Line 1770... Line 1749...
1770
    VendorCatalogPricingLogRepository vendorCatalogPricingLogRepository;
1749
    VendorCatalogPricingLogRepository vendorCatalogPricingLogRepository;
1771
 
1750
 
1772
//    private void checkItelImeiActivationNew(LocalDate now, int i) {
1751
//    private void checkItelImeiActivationNew(LocalDate now, int i) {
1773
//    }
1752
//    }
1774
 
1753
 
1775
 
-
 
1776
 
-
 
1777
    public void sendMailForSamsungRebilling() throws Exception {
1754
    public void sendMailForSamsungRebilling() throws Exception {
1778
        List<BilledImeiModel> samsungModels = warehouseInventoryItemRepository.findByBillingDateBrand(LocalDate.now(), "Samsung");
1755
        List<BilledImeiModel> samsungModels = warehouseInventoryItemRepository.findByBillingDateBrand(LocalDate.now(), "Samsung");
1779
        LOGGER.info("SamsungModels {}", samsungModels);
1756
        LOGGER.info("SamsungModels {}", samsungModels);
1780
        samsungModels = samsungModels.stream().sorted(Comparator.comparing(x -> x.getPcmDate() == null ? -1 : 1)).collect(Collectors.toList());
1757
        samsungModels = samsungModels.stream().sorted(Comparator.comparing(x -> x.getPcmDate() == null ? -1 : 1)).collect(Collectors.toList());
1781
        if (samsungModels.size() > 0) {
1758
        if (samsungModels.size() > 0) {
Line 2219... Line 2196...
2219
                LOGGER.info("Invoice {}, Date {}", fofoOrder.getInvoiceNumber(), fofoOrder.getCreateTimestamp());
2196
                LOGGER.info("Invoice {}, Date {}", fofoOrder.getInvoiceNumber(), fofoOrder.getCreateTimestamp());
2220
                LOGGER.info("customerAddress.getState() {}, retailerAddress.getState() {}", customerAddress.getState(), retailerAddress.getState());
2197
                LOGGER.info("customerAddress.getState() {}, retailerAddress.getState() {}", customerAddress.getState(), retailerAddress.getState());
2221
                LOGGER.info("Rates getIgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
2198
                LOGGER.info("Rates getIgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
2222
                LOGGER.info("Rates getCgstRate() {}, getSgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate(), itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
2199
                LOGGER.info("Rates getCgstRate() {}, getSgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate(), itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
2223
 
2200
 
2224
 
-
 
2225
            }
2201
            }
2226
        }
2202
        }
2227
 
2203
 
2228
    }
2204
    }
2229
 
2205
 
Line 2296... Line 2272...
2296
         */
2272
         */
2297
 
2273
 
2298
        List<Integer> fofoIds = null;
2274
        List<Integer> fofoIds = null;
2299
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getId(), x -> x));
2275
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getId(), x -> x));
2300
 
2276
 
2301
 
-
 
2302
        if (fofoIdInt == null) {
2277
        if (fofoIdInt == null) {
2303
            fofoIds = new ArrayList<>(fofoStoreMap.keySet());
2278
            fofoIds = new ArrayList<>(fofoStoreMap.keySet());
2304
        } else {
2279
        } else {
2305
            fofoIds = Arrays.asList(fofoIdInt);
2280
            fofoIds = Arrays.asList(fofoIdInt);
2306
        }
2281
        }
Line 2442... Line 2417...
2442
        private double past3daysSale;
2417
        private double past3daysSale;
2443
        private int fofoId;
2418
        private int fofoId;
2444
        private String code;
2419
        private String code;
2445
        private ActivationType activationType;
2420
        private ActivationType activationType;
2446
 
2421
 
2447
 
-
 
2448
        @Override
2422
        @Override
2449
        public boolean equals(Object o) {
2423
        public boolean equals(Object o) {
2450
            if (this == o) return true;
2424
            if (this == o) return true;
2451
            if (o == null || getClass() != o.getClass()) return false;
2425
            if (o == null || getClass() != o.getClass()) return false;
2452
            SaleTargetReportModel that = (SaleTargetReportModel) o;
2426
            SaleTargetReportModel that = (SaleTargetReportModel) o;
Line 2607... Line 2581...
2607
                sb.append("</tbody></table><br><br>");
2581
                sb.append("</tbody></table><br><br>");
2608
 
2582
 
2609
                sb.append("<p>Partnerwise Report:</p><br/><table style=\"border-collapse: collapse;\">");
2583
                sb.append("<p>Partnerwise Report:</p><br/><table style=\"border-collapse: collapse;\">");
2610
                sb.append("<tbody>\n" + "	    				<tr>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Code</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Business Name</th>" + "	    					<th style='border:1px solid black;padding: 5px'>BDM Name</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Regional Manager</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Territory Manager</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Billed(4 days)</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>" + "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>" + "	    				</tr>");
2584
                sb.append("<tbody>\n" + "	    				<tr>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Code</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Business Name</th>" + "	    					<th style='border:1px solid black;padding: 5px'>BDM Name</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Regional Manager</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Territory Manager</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Billed(4 days)</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>" + "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>" + "	    				</tr>");
2611
 
2585
 
2612
 
-
 
2613
                List<Integer> sortedSaleTargetReport = saleTargetReportModelMap.values().stream().filter(x -> fofoIds.contains(x.getFofoId())).sorted(Comparator.comparing(SaleTargetReportModel::getCode).thenComparing(SaleTargetReportModel::getSecondary)).map(SaleTargetReportModel::getFofoId).collect(Collectors.toList());
2586
                List<Integer> sortedSaleTargetReport = saleTargetReportModelMap.values().stream().filter(x -> fofoIds.contains(x.getFofoId())).sorted(Comparator.comparing(SaleTargetReportModel::getCode).thenComparing(SaleTargetReportModel::getSecondary)).map(SaleTargetReportModel::getFofoId).collect(Collectors.toList());
2614
 
2587
 
2615
                String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
2588
                String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
2616
 
2589
 
2617
                List<String> headers = Arrays.asList("Store Id", "Store Code", "Store Name", "Activation Type", "BDM Name", "Regional Manager", "Territory Manager", "Secondary(4 days)", "Sale", "Smartphone Value", "Smartphone Qty");
2590
                List<String> headers = Arrays.asList("Store Id", "Store Code", "Store Name", "Activation Type", "BDM Name", "Regional Manager", "Territory Manager", "Secondary(4 days)", "Sale", "Smartphone Value", "Smartphone Qty");
Line 2639... Line 2612...
2639
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
2612
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
2640
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
2613
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
2641
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
2614
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
2642
                    sb.append("</tr>");
2615
                    sb.append("</tr>");
2643
 
2616
 
2644
 
-
 
2645
                }
2617
                }
2646
                sb.append("</tr>");
2618
                sb.append("</tr>");
2647
                sb.append("</body></html>");
2619
                sb.append("</body></html>");
2648
                String statewiseSaleReport = sb.toString();
2620
                String statewiseSaleReport = sb.toString();
2649
 
2621
 
2650
 
-
 
2651
                ByteArrayOutputStream baos = null;
2622
                ByteArrayOutputStream baos = null;
2652
                try {
2623
                try {
2653
                    baos = FileUtil.getCSVByteStream(headers, rows);
2624
                    baos = FileUtil.getCSVByteStream(headers, rows);
2654
                } catch (Exception e2) {
2625
                } catch (Exception e2) {
2655
                    e2.printStackTrace();
2626
                    e2.printStackTrace();
Line 2658... Line 2629...
2658
                Utils.sendHtmlMailWithAttachments(googleMailSender, new String[]{email}, null, "Statewise " + subject, statewiseSaleReport, attachment);
2629
                Utils.sendHtmlMailWithAttachments(googleMailSender, new String[]{email}, null, "Statewise " + subject, statewiseSaleReport, attachment);
2659
            }
2630
            }
2660
        }
2631
        }
2661
    }
2632
    }
2662
 
2633
 
2663
 
-
 
2664
    private void sendMailOfHtmlFormat(JavaMailSender sender, String[] email, String body, String cc[], String subject) throws
2634
    private void sendMailOfHtmlFormat(JavaMailSender sender, String[] email, String body, String cc[], String subject) throws
2665
            MessagingException, ProfitMandiBusinessException, IOException {
2635
            MessagingException, ProfitMandiBusinessException, IOException {
2666
        MimeMessage message = sender.createMimeMessage();
2636
        MimeMessage message = sender.createMimeMessage();
2667
        MimeMessageHelper helper = new MimeMessageHelper(message);
2637
        MimeMessageHelper helper = new MimeMessageHelper(message);
2668
        helper.setSubject(subject);
2638
        helper.setSubject(subject);
Line 2715... Line 2685...
2715
                }
2685
                }
2716
            }
2686
            }
2717
        }
2687
        }
2718
    }
2688
    }
2719
 
2689
 
2720
    public void toffeeRollback() throws Exception {
-
 
2721
        toffeeService.cancelPolicyCopy("110143521986");
-
 
2722
        toffeeService.getOrderId("110143521986");
-
 
2723
    }
-
 
2724
 
-
 
2725
    public void attachToffeeInvoices() throws Exception {
-
 
2726
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(3, Optional.of(false));
-
 
2727
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
-
 
2728
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
-
 
2729
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
-
 
2730
            com.spice.profitmandi.common.model.InvoicePdfModel pdfModel = orderService.getInvoicePdfModel(fofoOrder.getId());
-
 
2731
            java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
-
 
2732
            PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
-
 
2733
            String pdfInvoiceString = "data:application/pdf;base64," + Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
-
 
2734
            boolean attached = toffeeService.attachInvoice(insurancePolicy.getPolicyNumber().split("#")[1], pdfInvoiceString);
-
 
2735
            if (attached) {
-
 
2736
                insurancePolicy.setPosted(true);
-
 
2737
            }
-
 
2738
        }
-
 
2739
    }
-
 
2740
 
-
 
2741
    public void sendBAGPendingPolicies() throws Exception {
-
 
2742
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(4, Optional.of(false));
-
 
2743
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
-
 
2744
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
-
 
2745
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
-
 
2746
            FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
-
 
2747
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
-
 
2748
            Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
-
 
2749
            BAGInsuranceModel bagInsuranceModel = new BAGInsuranceModel();
-
 
2750
            // bagInsuranceModel.setModelId();
-
 
2751
            bagInsuranceModel.setAddressLine1(customerAddress.getLine1());
-
 
2752
            bagInsuranceModel.setAddressLine2(customerAddress.getLine2());
-
 
2753
            bagInsuranceModel.setCity(customerAddress.getCity());
-
 
2754
            bagInsuranceModel.setBrandWarranty("1 Year");
-
 
2755
            Item item = itemRepository.selectById(fofoOrderItem.getId());
-
 
2756
            bagInsuranceModel.setModelName(item.getItemDescription());
-
 
2757
            bagInsuranceModel.setDateOfPurchase(fofoOrder.getFormattedDate());
-
 
2758
            bagInsuranceModel.setEmail(customer.getEmailId());
-
 
2759
            bagInsuranceModel.setImei1(insurancePolicy.getSerialNumber());
-
 
2760
            bagInsuranceModel.setFirstName(customer.getFirstName());
-
 
2761
            bagInsuranceModel.setLastName(customer.getLastName());
-
 
2762
            bagInsuranceModel.setMobileNumber(customer.getMobileNumber());
-
 
2763
            bagInsuranceModel.setPlanId("");
-
 
2764
            insurancePolicy.setPosted(true);
-
 
2765
        }
-
 
2766
    }
-
 
2767
 
-
 
2768
    public void schemeRollback(List<String> schemeIds) throws Exception {
2690
    public void schemeRollback(List<String> schemeIds) throws Exception {
2769
        List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
2691
        List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
2770
        Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
2692
        Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
2771
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
2693
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
2772
        for (SchemeInOut sio : schemeInOuts) {
2694
        for (SchemeInOut sio : schemeInOuts) {
Line 3702... Line 3624...
3702
 
3624
 
3703
            Map<Integer, PartnerCollectionRemark> rbmEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.RBM_L2_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3625
            Map<Integer, PartnerCollectionRemark> rbmEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.RBM_L2_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3704
            Map<Integer, PartnerCollectionRemark> rbmL3EscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.RBM_L3_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3626
            Map<Integer, PartnerCollectionRemark> rbmL3EscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.RBM_L3_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3705
            Map<Integer, PartnerCollectionRemark> salesEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.SALES_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3627
            Map<Integer, PartnerCollectionRemark> salesEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.SALES_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3706
 
3628
 
3707
 
-
 
3708
            if (!rbmEscalatedRemarksMap.isEmpty()) {
3629
            if (!rbmEscalatedRemarksMap.isEmpty()) {
3709
                //
3630
                //
3710
                for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM), true).entrySet()) {
3631
                for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM), true).entrySet()) {
3711
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
3632
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
3712
                            .map(x -> rbmEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
3633
                            .map(x -> rbmEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
Line 3770... Line 3691...
3770
            }
3691
            }
3771
 
3692
 
3772
        }
3693
        }
3773
    }
3694
    }
3774
 
3695
 
3775
 
-
 
3776
    @Autowired
3696
    @Autowired
3777
    private NonSdBuyingRepository nonSdBuyingRepository;
3697
    private NonSdBuyingRepository nonSdBuyingRepository;
3778
 
3698
 
3779
    //Non Sd Buying
3699
    //Non Sd Buying
3780
    public void reviewNonSdBuyingBrand() throws
3700
    public void reviewNonSdBuyingBrand() throws
Line 3801... Line 3721...
3801
                    helper.setFrom(senderAddress);
3721
                    helper.setFrom(senderAddress);
3802
                    gmailRelaySender.send(message);
3722
                    gmailRelaySender.send(message);
3803
                    LOGGER.info("unAuthorizedfilteredRows {}", unAuthorizedfilteredRows);
3723
                    LOGGER.info("unAuthorizedfilteredRows {}", unAuthorizedfilteredRows);
3804
                }
3724
                }
3805
 
3725
 
3806
 
-
 
3807
            }
3726
            }
3808
 
3727
 
3809
        }
3728
        }
3810
    }
3729
    }
3811
 
3730
 
Line 3921... Line 3840...
3921
            }
3840
            }
3922
        }
3841
        }
3923
 
3842
 
3924
    }
3843
    }
3925
 
3844
 
3926
 
-
 
3927
    private void sendUnholdEmail(List<Order> orders) throws Exception {
3845
    private void sendUnholdEmail(List<Order> orders) throws Exception {
3928
 
3846
 
3929
 
-
 
3930
        orders.forEach(x -> x.setShipmentHold(false));
3847
        orders.forEach(x -> x.setShipmentHold(false));
3931
        orders = orders.stream().filter(x -> x.getRefundTimestamp() != null).collect(Collectors.toList());
3848
        orders = orders.stream().filter(x -> x.getRefundTimestamp() != null).collect(Collectors.toList());
3932
        if (orders.size() > 0) {
3849
        if (orders.size() > 0) {
3933
 
3850
 
3934
            double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));
3851
            double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));
Line 3944... Line 3861...
3944
            String subject = "Dispatch held orders of - " + (orders.get(0).getRetailerName());
3861
            String subject = "Dispatch held orders of - " + (orders.get(0).getRetailerName());
3945
            String message = String.format("Dear Team, \n" + "kindly note the material for the " + orders.get(0).getRetailerName() + "of Rs." + totalAmount + "is unhold now and needs to be dispatched.");
3862
            String message = String.format("Dear Team, \n" + "kindly note the material for the " + orders.get(0).getRetailerName() + "of Rs." + totalAmount + "is unhold now and needs to be dispatched.");
3946
            mailOutboxService.queueMailViaGoogle(emailTo, ccTo, subject, message, "ScheduledTasks.sendUnholdEmail");
3863
            mailOutboxService.queueMailViaGoogle(emailTo, ccTo, subject, message, "ScheduledTasks.sendUnholdEmail");
3947
        }
3864
        }
3948
 
3865
 
3949
 
-
 
3950
    }
3866
    }
3951
 
3867
 
3952
    // Nightly at 23:30: detect beat-days the assignee missed (no PUNCHIN, or punched
3868
    // Nightly at 23:30: detect beat-days the assignee missed (no PUNCHIN, or punched
3953
    // in but no stops worked) and fan out per-stop miss rows into beat_deferred_visit
3869
    // in but no stops worked) and fan out per-stop miss rows into beat_deferred_visit
3954
    // so the Deferred Partners panel surfaces them. Idempotent on repeat runs.
3870
    // so the Deferred Partners panel surfaces them. Idempotent on repeat runs.
Line 4122... Line 4038...
4122
            175140101
4038
            175140101
4123
    );*/
4039
    );*/
4124
 
4040
 
4125
    private static List<Integer> hundredPercentLimitPartnerIds = Arrays.asList();
4041
    private static List<Integer> hundredPercentLimitPartnerIds = Arrays.asList();
4126
 
4042
 
4127
 
-
 
4128
 
-
 
4129
    public void notifyDefaultLoans() throws ProfitMandiBusinessException, MessagingException, IOException {
4043
    public void notifyDefaultLoans() throws ProfitMandiBusinessException, MessagingException, IOException {
4130
        synchronized (SD_CREDIT_LOCK) {
4044
        synchronized (SD_CREDIT_LOCK) {
4131
            sdCreditService.updateRisk();
4045
            sdCreditService.updateRisk();
4132
            List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
4046
            List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
4133
            if (!defaultLoans.isEmpty()) {
4047
            if (!defaultLoans.isEmpty()) {
Line 4327... Line 4241...
4327
                byteArrayOutputStream = this.generateLoanCsv(filteredAllActiveLoans);
4241
                byteArrayOutputStream = this.generateLoanCsv(filteredAllActiveLoans);
4328
                attachment1 = new Utils.Attachment("partnner-credit.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
4242
                attachment1 = new Utils.Attachment("partnner-credit.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
4329
 
4243
 
4330
            }
4244
            }
4331
 
4245
 
4332
 
-
 
4333
            if (!filteredRows.isEmpty()) {
4246
            if (!filteredRows.isEmpty()) {
4334
                String messageText = this.getMessageForDueDateCross(filteredRows);
4247
                String messageText = this.getMessageForDueDateCross(filteredRows);
4335
                String[] email = new String[]{storeGuyEntry.getKey(),"neeraj.gupta@smartdukaan.com"};
4248
                String[] email = new String[]{storeGuyEntry.getKey(),"neeraj.gupta@smartdukaan.com"};
4336
 
4249
 
4337
                if (attachment1 != null) {
4250
                if (attachment1 != null) {
Line 4357... Line 4270...
4357
            mailOutboxService.queueMailWithAttachmentsViaGoogle(new String[]{"sdtech@smartdukaan.com"}, null, null, "Partner Credit Report", messageText, true, "ScheduledTasks.sendDueDateCrossLoanAlert", attachment);
4270
            mailOutboxService.queueMailWithAttachmentsViaGoogle(new String[]{"sdtech@smartdukaan.com"}, null, null, "Partner Credit Report", messageText, true, "ScheduledTasks.sendDueDateCrossLoanAlert", attachment);
4358
        } else {
4271
        } else {
4359
            this.sendMailOfHtmlFormat(googleMailSender, new String[]{"sdtech@smartdukaan.com"}, messageText, null, "Due Date Cross");
4272
            this.sendMailOfHtmlFormat(googleMailSender, new String[]{"sdtech@smartdukaan.com"}, messageText, null, "Due Date Cross");
4360
        }
4273
        }
4361
 
4274
 
4362
 
-
 
4363
        if (!dueDateCrossLoans.isEmpty()) {
4275
        if (!dueDateCrossLoans.isEmpty()) {
4364
            for (Loan loan : dueDateCrossLoans) {
4276
            for (Loan loan : dueDateCrossLoans) {
4365
                double principal = loan.getPendingAmount().doubleValue();
4277
                double principal = loan.getPendingAmount().doubleValue();
4366
                double interest = loan.getInterestAccrued().doubleValue() - loan.getInterestPaid().doubleValue();
4278
                double interest = loan.getInterestAccrued().doubleValue() - loan.getInterestPaid().doubleValue();
4367
                double total = principal + interest;
4279
                double total = principal + interest;
Line 4379... Line 4291...
4379
    }
4291
    }
4380
 
4292
 
4381
    private ByteArrayOutputStream generateLoanCsv(List<Loan> loans) throws ProfitMandiBusinessException {
4293
    private ByteArrayOutputStream generateLoanCsv(List<Loan> loans) throws ProfitMandiBusinessException {
4382
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = null;
4294
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = null;
4383
 
4295
 
4384
 
-
 
4385
        if (!loans.isEmpty()) {
4296
        if (!loans.isEmpty()) {
4386
            Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
4297
            Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
4387
            Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
4298
            Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
4388
            List<AST> asts = astRepository.selectAll();
4299
            List<AST> asts = astRepository.selectAll();
4389
            Map<Integer, AST> astMap = asts.stream()
4300
            Map<Integer, AST> astMap = asts.stream()
Line 4424... Line 4335...
4424
                    rows.add(row);
4335
                    rows.add(row);
4425
                }
4336
                }
4426
 
4337
 
4427
                byteArrayOutputStream = FileUtil.getCSVByteStream(headers, rows);
4338
                byteArrayOutputStream = FileUtil.getCSVByteStream(headers, rows);
4428
 
4339
 
4429
 
-
 
4430
            } catch (Exception e) {
4340
            } catch (Exception e) {
4431
                throw new RuntimeException(e);
4341
                throw new RuntimeException(e);
4432
            }
4342
            }
4433
 
4343
 
4434
        }
4344
        }
4435
        return byteArrayOutputStream;
4345
        return byteArrayOutputStream;
4436
    }
4346
    }
4437
 
4347
 
4438
 
-
 
4439
    public void alertForDueDate() throws Exception {
4348
    public void alertForDueDate() throws Exception {
4440
 
4349
 
4441
        List<Loan> loans = loanRepository.selectAllActiveLoan();
4350
        List<Loan> loans = loanRepository.selectAllActiveLoan();
4442
 
4351
 
4443
        for (Loan loan : loans) {
4352
        for (Loan loan : loans) {
Line 4804... Line 4713...
4804
 
4713
 
4805
        }
4714
        }
4806
 
4715
 
4807
    }
4716
    }
4808
 
4717
 
4809
 
-
 
4810
    public void findAllLiveDemoBrandItemsByBillingDate() throws
4718
    public void findAllLiveDemoBrandItemsByBillingDate() throws
4811
            MessagingException, ProfitMandiBusinessException, IOException {
4719
            MessagingException, ProfitMandiBusinessException, IOException {
4812
        LocalDateTime endDate = LocalDate.now().atStartOfDay().minusDays(8);
4720
        LocalDateTime endDate = LocalDate.now().atStartOfDay().minusDays(8);
4813
 
4721
 
4814
        List<LiveDemoOrderLineItemModel> liveDemoOrderLineItemModels = orderRepository.findAllLiveDemoBrandItemsByBillingDate(endDate.minusDays(60), endDate);
4722
        List<LiveDemoOrderLineItemModel> liveDemoOrderLineItemModels = orderRepository.findAllLiveDemoBrandItemsByBillingDate(endDate.minusDays(60), endDate);
Line 4849... Line 4757...
4849
 
4757
 
4850
        }
4758
        }
4851
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "niranjan.kala@smartdukaan.com",
4759
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "niranjan.kala@smartdukaan.com",
4852
                "mohit.gulati@smartdukaan.com", "vinay.p@smartdukaan.com", "shivam.gupta@smartdukaan.com");
4760
                "mohit.gulati@smartdukaan.com", "vinay.p@smartdukaan.com", "shivam.gupta@smartdukaan.com");
4853
 
4761
 
4854
 
-
 
4855
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4762
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4856
    this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
4763
    this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
4857
 
4764
 
4858
    }
4765
    }
4859
 
4766
 
Line 4893... Line 4800...
4893
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4800
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4894
        this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
4801
        this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
4895
 
4802
 
4896
    }
4803
    }
4897
 
4804
 
4898
 
-
 
4899
    public void monthlyTargetForInternalTeam() throws MessagingException, ProfitMandiBusinessException, IOException {
4805
    public void monthlyTargetForInternalTeam() throws MessagingException, ProfitMandiBusinessException, IOException {
4900
 
4806
 
4901
        LocalDateTime curDate = LocalDateTime.now();
4807
        LocalDateTime curDate = LocalDateTime.now();
4902
 
4808
 
4903
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM, ProfitMandiConstants.TICKET_CATEGORY_MARKETING, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
4809
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM, ProfitMandiConstants.TICKET_CATEGORY_MARKETING, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
Line 4979... Line 4885...
4979
    }
4885
    }
4980
 
4886
 
4981
    @Autowired
4887
    @Autowired
4982
    private PerformanceService performanceService;
4888
    private PerformanceService performanceService;
4983
 
4889
 
4984
 
-
 
4985
    public void sendFilteredRetailerPerformance() throws Exception {
4890
    public void sendFilteredRetailerPerformance() throws Exception {
4986
        RetailerFilterModel retailerFilterModel = performanceService.getRetailerFilterModel();
4891
        RetailerFilterModel retailerFilterModel = performanceService.getRetailerFilterModel();
4987
 
4892
 
4988
        Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(true);
4893
        Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(true);
4989
 
4894
 
4990
 
-
 
4991
        List<RetailerPeformanceFilterModel> partnersPerformance = performanceService.getPerformance(retailerFilterModel, customRetailers);
4895
        List<RetailerPeformanceFilterModel> partnersPerformance = performanceService.getPerformance(retailerFilterModel, customRetailers);
4992
 
4896
 
4993
        Map<Integer, RetailerPeformanceFilterModel> partnersPerformanceMap = new HashMap<>();
4897
        Map<Integer, RetailerPeformanceFilterModel> partnersPerformanceMap = new HashMap<>();
4994
 
4898
 
4995
        if (!partnersPerformance.isEmpty()) {
4899
        if (!partnersPerformance.isEmpty()) {
4996
            partnersPerformanceMap = partnersPerformance.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
4900
            partnersPerformanceMap = partnersPerformance.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
4997
            performanceService.sendPartnerPerformanceEmail(partnersPerformanceMap, retailerFilterModel, customRetailers);
4901
            performanceService.sendPartnerPerformanceEmail(partnersPerformanceMap, retailerFilterModel, customRetailers);
4998
 
4902
 
4999
        }
4903
        }
5000
 
4904
 
5001
 
-
 
5002
    }
4905
    }
5003
 
4906
 
5004
    @Autowired
4907
    @Autowired
5005
    private VendorCatalogPricingService vendorCatalogPricingService;
4908
    private VendorCatalogPricingService vendorCatalogPricingService;
5006
 
4909
 
5007
 
-
 
5008
    public void approveVendorCatalogPricing() {
4910
    public void approveVendorCatalogPricing() {
5009
        List<VendorCatalogPricingLog> vendorCatalogPricingLogs = vendorCatalogPricingLogRepository.selectByStatus(VendorCatalogPricingStatus.PENDING);
4911
        List<VendorCatalogPricingLog> vendorCatalogPricingLogs = vendorCatalogPricingLogRepository.selectByStatus(VendorCatalogPricingStatus.PENDING);
5010
 
4912
 
5011
 
-
 
5012
        for (VendorCatalogPricingLog vendorCatalogPricingLog : vendorCatalogPricingLogs) {
4913
        for (VendorCatalogPricingLog vendorCatalogPricingLog : vendorCatalogPricingLogs) {
5013
            vendorCatalogPricingLog.setStatus(VendorCatalogPricingStatus.APPROVED);
4914
            vendorCatalogPricingLog.setStatus(VendorCatalogPricingStatus.APPROVED);
5014
            vendorCatalogPricingLog.setUpdatedTimestamp(LocalDateTime.now());
4915
            vendorCatalogPricingLog.setUpdatedTimestamp(LocalDateTime.now());
5015
            vendorCatalogPricingLog.setApprovedBy(13);
4916
            vendorCatalogPricingLog.setApprovedBy(13);
5016
            vendorCatalogPricingLog.setApprovedTimestamp(LocalDateTime.now());
4917
            vendorCatalogPricingLog.setApprovedTimestamp(LocalDateTime.now());
Line 5080... Line 4981...
5080
        sb.append("<p>Team SmartDukaan</p>");
4981
        sb.append("<p>Team SmartDukaan</p>");
5081
        sb.append("</body></html>");
4982
        sb.append("</body></html>");
5082
        return sb.toString();
4983
        return sb.toString();
5083
    }
4984
    }
5084
 
4985
 
5085
 
-
 
5086
    @Autowired
4986
    @Autowired
5087
    private FofoOpeningStockRepository fofoOpeningStockRepository;
4987
    private FofoOpeningStockRepository fofoOpeningStockRepository;
5088
    @Autowired
4988
    @Autowired
5089
    private SmartCartService smartCartService;
4989
    private SmartCartService smartCartService;
5090
 
4990
 
Line 5142... Line 5042...
5142
                        .values()
5042
                        .values()
5143
                        .stream()
5043
                        .stream()
5144
                        .collect(Collectors.toList())
5044
                        .collect(Collectors.toList())
5145
        );
5045
        );
5146
 
5046
 
5147
 
-
 
5148
        Map<Integer, Map<Integer, Integer>> activatedButNotBilledCatalogQtyMap = smartCartService.activatedButNotBilledCatalogQtyMap();
5047
        Map<Integer, Map<Integer, Integer>> activatedButNotBilledCatalogQtyMap = smartCartService.activatedButNotBilledCatalogQtyMap();
5149
        LOGGER.info("PartnerOpeningStockByTodayModel {}", partnerOpeningStockByTodayMap);
5048
        LOGGER.info("PartnerOpeningStockByTodayModel {}", partnerOpeningStockByTodayMap);
5150
        for (Map.Entry<Integer, List<PartnerOpeningStockByTodayModel>> entry : partnerOpeningStockByTodayMap.entrySet()) {
5049
        for (Map.Entry<Integer, List<PartnerOpeningStockByTodayModel>> entry : partnerOpeningStockByTodayMap.entrySet()) {
5151
            int fofoId = entry.getKey();
5050
            int fofoId = entry.getKey();
5152
            List<PartnerOpeningStockByTodayModel> partnerStockList = entry.getValue();
5051
            List<PartnerOpeningStockByTodayModel> partnerStockList = entry.getValue();
Line 5169... Line 5068...
5169
                }
5068
                }
5170
 
5069
 
5171
                // Subtract soldQty from partnerCurrentQty
5070
                // Subtract soldQty from partnerCurrentQty
5172
                int partnerCurrentQty = Math.max(stockCurrentQty - soldButNotBilledQty, 0); // Ensure it doesn't go negative
5071
                int partnerCurrentQty = Math.max(stockCurrentQty - soldButNotBilledQty, 0); // Ensure it doesn't go negative
5173
 
5072
 
5174
 
-
 
5175
                // Check if an entry already exists in the FofoOpeningStock table
5073
                // Check if an entry already exists in the FofoOpeningStock table
5176
                FofoOpeningStock existingStock = fofoOpeningStockRepository.findByFofoIdAndCatalogId(fofoId, catalogId);
5074
                FofoOpeningStock existingStock = fofoOpeningStockRepository.findByFofoIdAndCatalogId(fofoId, catalogId);
5177
 
5075
 
5178
 
-
 
5179
                if (existingStock != null) {
5076
                if (existingStock != null) {
5180
                    if (partnerCurrentQty < 1 && existingStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
5077
                    if (partnerCurrentQty < 1 && existingStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
5181
                        fofoOpeningStockRepository.delete(existingStock);
5078
                        fofoOpeningStockRepository.delete(existingStock);
5182
                    }
5079
                    }
5183
                    if (existingStock.getOpeningQty() < partnerCurrentQty) {
5080
                    if (existingStock.getOpeningQty() < partnerCurrentQty) {
Line 5237... Line 5134...
5237
            }
5134
            }
5238
 
5135
 
5239
        }
5136
        }
5240
    }
5137
    }
5241
 
5138
 
5242
 
-
 
5243
    @Autowired
5139
    @Autowired
5244
    private CategorisedCatalogRepository categorisedCatalogRepository;
5140
    private CategorisedCatalogRepository categorisedCatalogRepository;
5245
 
5141
 
5246
    public void groupHidCatalogsByWeeks() throws ProfitMandiBusinessException, MessagingException, IOException {
5142
    public void groupHidCatalogsByWeeks() throws ProfitMandiBusinessException, MessagingException, IOException {
5247
        List<CategorisedCatalogListModel> categorisedCatalogs = categorisedCatalogRepository.getListByStatus(CatalogMovingEnum.HID);
5143
        List<CategorisedCatalogListModel> categorisedCatalogs = categorisedCatalogRepository.getListByStatus(CatalogMovingEnum.HID);
Line 5268... Line 5164...
5268
        // Older than Two Weeks Ago (anything older than three weeks ago)
5164
        // Older than Two Weeks Ago (anything older than three weeks ago)
5269
        List<CategorisedCatalogListModel> olderCatalogs = categorisedCatalogs.stream()
5165
        List<CategorisedCatalogListModel> olderCatalogs = categorisedCatalogs.stream()
5270
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(threeWeeksAgo))
5166
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(threeWeeksAgo))
5271
                .collect(Collectors.toList());
5167
                .collect(Collectors.toList());
5272
 
5168
 
5273
 
-
 
5274
        String subject = "Hid Catalogs";
5169
        String subject = "Hid Catalogs";
5275
        StringBuilder sb = new StringBuilder();
5170
        StringBuilder sb = new StringBuilder();
5276
 
5171
 
5277
        sb.append("<html><body><p>Hi Catagory Team,\n");
5172
        sb.append("<html><body><p>Hi Catagory Team,\n");
5278
        sb.append("<p style='font-weight:500;'>Please review the HID catalogs for this week:</p>\n" + "<table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
5173
        sb.append("<p style='font-weight:500;'>Please review the HID catalogs for this week:</p>\n" + "<table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
Line 5382... Line 5277...
5382
        sb.append("</table>");
5277
        sb.append("</table>");
5383
        sb.append("</body></html>");
5278
        sb.append("</body></html>");
5384
 
5279
 
5385
        List<String> sendTo = Arrays.asList("sourcing@smartdukaan.com", "tarun.verma@smartdukaan.com");
5280
        List<String> sendTo = Arrays.asList("sourcing@smartdukaan.com", "tarun.verma@smartdukaan.com");
5386
 
5281
 
5387
 
-
 
5388
        String[] email = sendTo.toArray(new String[sendTo.size()]);
5282
        String[] email = sendTo.toArray(new String[sendTo.size()]);
5389
 
5283
 
5390
        this.sendMailOfHtmlFormat(gmailRelaySender, email, sb.toString(), null, subject);
5284
        this.sendMailOfHtmlFormat(gmailRelaySender, email, sb.toString(), null, subject);
5391
    }
5285
    }
5392
 
5286