Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
28217 tejbeer 1
package com.smartdukaan.cron.scheduled;
23723 amit.gupta 2
 
34039 vikas.jang 3
import com.google.auth.oauth2.GoogleCredentials;
24542 amit.gupta 4
import com.google.common.collect.Lists;
25300 tejbeer 5
import com.google.gson.Gson;
29488 manish 6
import com.razorpay.Payment;
32421 amit.gupta 7
import com.smartdukaan.cron.itelImeiActivation.ItelImeiActivationNewService;
29488 manish 8
import com.smartdukaan.cron.itelImeiActivation.ItelImeiActivationService;
9
import com.smartdukaan.cron.itelImeiActivation.TecnoImeiActivation;
33994 amit.gupta 10
import com.smartdukaan.cron.migrations.RunOnceTasks;
35021 amit 11
import com.smartdukaan.cron.scheduled.ambreports.AbmReportSender;
32482 amit.gupta 12
import com.smartdukaan.cron.scheduled.runnables.PurchaseMigration;
32511 amit.gupta 13
import com.spice.profitmandi.common.enumuration.*;
24121 govind 14
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
32421 amit.gupta 15
import com.spice.profitmandi.common.model.*;
24681 amit.gupta 16
import com.spice.profitmandi.common.services.ReporticoService;
29814 tejbeer 17
import com.spice.profitmandi.common.services.mandii.MandiiService;
35295 amit 18
import com.spice.profitmandi.common.util.FileUtil;
19
import com.spice.profitmandi.common.util.FormattingUtils;
20
import com.spice.profitmandi.common.util.PdfUtils;
21
import com.spice.profitmandi.common.util.Utils;
24592 amit.gupta 22
import com.spice.profitmandi.common.util.Utils.Attachment;
29308 tejbeer 23
import com.spice.profitmandi.common.web.client.RestClient;
25300 tejbeer 24
import com.spice.profitmandi.dao.Interface.Campaign;
32511 amit.gupta 25
import com.spice.profitmandi.dao.cart.CartService;
34450 ranu 26
import com.spice.profitmandi.dao.cart.SmartCartService;
25590 amit.gupta 27
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30421 tejbeer 28
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionRemark;
33078 ranu 29
import com.spice.profitmandi.dao.entity.catalog.*;
35393 amit 30
import com.spice.profitmandi.dao.entity.catalog.Offer;
33078 ranu 31
import com.spice.profitmandi.dao.entity.cs.NonSdBuying;
25590 amit.gupta 32
import com.spice.profitmandi.dao.entity.cs.Position;
26283 tejbeer 33
import com.spice.profitmandi.dao.entity.cs.Ticket;
35295 amit 34
import com.spice.profitmandi.dao.entity.dtr.*;
28769 amit.gupta 35
import com.spice.profitmandi.dao.entity.dtr.User;
32421 amit.gupta 36
import com.spice.profitmandi.dao.entity.fofo.*;
37
import com.spice.profitmandi.dao.entity.inventory.*;
33553 ranu 38
import com.spice.profitmandi.dao.entity.logistics.AST;
39
import com.spice.profitmandi.dao.entity.logistics.ASTRepository;
32421 amit.gupta 40
import com.spice.profitmandi.dao.entity.transaction.*;
41
import com.spice.profitmandi.dao.entity.user.*;
32511 amit.gupta 42
import com.spice.profitmandi.dao.entity.warehouse.WarehouseInventoryItem;
43
import com.spice.profitmandi.dao.entity.warehouse.WarehouseScan;
30421 tejbeer 44
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
34324 amit.gupta 45
import com.spice.profitmandi.dao.enumuration.catalog.StockTransactionType;
25598 amit.gupta 46
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26790 tejbeer 47
import com.spice.profitmandi.dao.enumuration.dtr.RefferalStatus;
29814 tejbeer 48
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
31332 amit.gupta 49
import com.spice.profitmandi.dao.enumuration.fofo.PaymentStatus;
32511 amit.gupta 50
import com.spice.profitmandi.dao.enumuration.fofo.ReturnType;
24242 amit.gupta 51
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
34162 ranu 52
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
32081 tejbeer 53
import com.spice.profitmandi.dao.enumuration.inventory.VendorCatalogPricingStatus;
34324 amit.gupta 54
import com.spice.profitmandi.dao.enumuration.transaction.CreditRisk;
55
import com.spice.profitmandi.dao.enumuration.transaction.LoanReferenceType;
56
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
57
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
32421 amit.gupta 58
import com.spice.profitmandi.dao.model.*;
33452 amit.gupta 59
import com.spice.profitmandi.dao.repository.GenericRepository;
25590 amit.gupta 60
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
33078 ranu 61
import com.spice.profitmandi.dao.repository.auth.NonSdBuyingRepository;
30421 tejbeer 62
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionRemarkRepository;
32421 amit.gupta 63
import com.spice.profitmandi.dao.repository.catalog.*;
33874 ranu 64
import com.spice.profitmandi.dao.repository.cs.CsService;
65
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
66
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
67
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
32421 amit.gupta 68
import com.spice.profitmandi.dao.repository.dtr.*;
69
import com.spice.profitmandi.dao.repository.fofo.*;
70
import com.spice.profitmandi.dao.repository.inventory.*;
33817 amit.gupta 71
import com.spice.profitmandi.dao.repository.logistics.WarehouseProviderRepository;
32421 amit.gupta 72
import com.spice.profitmandi.dao.repository.transaction.*;
35295 amit 73
import com.spice.profitmandi.dao.repository.trialOnboarding.TrialFormRepository;
24542 amit.gupta 74
import com.spice.profitmandi.dao.repository.user.AddressRepository;
34160 tejus.loha 75
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
25721 tejbeer 76
import com.spice.profitmandi.dao.repository.user.UserRepository;
32421 amit.gupta 77
import com.spice.profitmandi.dao.repository.warehouse.*;
34547 vikas.jang 78
import com.spice.profitmandi.dao.service.LiquidationService;
34252 tejus.loha 79
import com.spice.profitmandi.dao.service.PurSaleService;
33355 amit.gupta 80
import com.spice.profitmandi.dao.service.SidbiService;
32817 amit.gupta 81
import com.spice.profitmandi.dao.service.biuedart.BluedartAuthService;
82
import com.spice.profitmandi.dao.service.biuedart.BluedartService;
31604 tejbeer 83
import com.spice.profitmandi.dao.service.solr.FofoSolr;
32421 amit.gupta 84
import com.spice.profitmandi.service.*;
31332 amit.gupta 85
import com.spice.profitmandi.service.integrations.CCAvenuePaymentService;
28368 tejbeer 86
import com.spice.profitmandi.service.integrations.RazorpayPaymentService;
30858 amit.gupta 87
import com.spice.profitmandi.service.integrations.bharti.model.BAGInsuranceModel;
33638 amit.gupta 88
import com.spice.profitmandi.service.integrations.gstpro.GstProAuthService;
33817 amit.gupta 89
import com.spice.profitmandi.service.integrations.gstpro.GstProService;
35393 amit 90
import com.spice.profitmandi.service.integrations.pinelabs.dto.*;
32872 amit.gupta 91
import com.spice.profitmandi.service.integrations.psismart.PsiSmartService;
32948 amit.gupta 92
import com.spice.profitmandi.service.integrations.smartping.SmartPingService;
25694 amit.gupta 93
import com.spice.profitmandi.service.integrations.toffee.ToffeeService;
32421 amit.gupta 94
import com.spice.profitmandi.service.inventory.*;
31746 amit.gupta 95
import com.spice.profitmandi.service.offers.OfferService;
25335 amit.gupta 96
import com.spice.profitmandi.service.order.OrderService;
33452 amit.gupta 97
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
24431 amit.gupta 98
import com.spice.profitmandi.service.pricing.PriceDropService;
23724 amit.gupta 99
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
100
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
101
import com.spice.profitmandi.service.scheme.SchemeService;
29668 tejbeer 102
import com.spice.profitmandi.service.serviceConfig.ServiceConfigService;
35295 amit 103
import com.spice.profitmandi.service.transaction.CreditBlockedExceptionPartnersRepository;
31008 amit.gupta 104
import com.spice.profitmandi.service.transaction.CreditNoteService;
30859 tejbeer 105
import com.spice.profitmandi.service.transaction.SDCreditService;
23929 amit.gupta 106
import com.spice.profitmandi.service.transaction.TransactionService;
32990 amit.gupta 107
import com.spice.profitmandi.service.transaction.invoicing.InvoiceService;
23929 amit.gupta 108
import com.spice.profitmandi.service.user.RetailerService;
34160 tejus.loha 109
import com.spice.profitmandi.service.user.StoreTimelineTatService;
32511 amit.gupta 110
import com.spice.profitmandi.service.wallet.CommonPaymentService;
23739 amit.gupta 111
import com.spice.profitmandi.service.wallet.WalletService;
32421 amit.gupta 112
import com.spice.profitmandi.service.warehouse.PurchaseOrderService;
32511 amit.gupta 113
import com.spice.profitmandi.service.warehouse.WarehouseInventoryService;
33384 amit.gupta 114
import com.spice.profitmandi.service.warehouse.WarehouseService;
25721 tejbeer 115
import in.shop2020.model.v1.order.OrderStatus;
29308 tejbeer 116
import in.shop2020.model.v1.order.WalletReferenceType;
32421 amit.gupta 117
import org.apache.commons.io.output.ByteArrayOutputStream;
118
import org.apache.commons.lang.StringUtils;
119
import org.apache.http.client.methods.CloseableHttpResponse;
120
import org.apache.http.client.methods.HttpPost;
121
import org.apache.http.conn.HttpHostConnectException;
122
import org.apache.http.entity.StringEntity;
123
import org.apache.http.impl.client.CloseableHttpClient;
124
import org.apache.http.impl.client.HttpClients;
125
import org.apache.logging.log4j.LogManager;
126
import org.apache.logging.log4j.Logger;
127
import org.hibernate.SessionFactory;
128
import org.json.JSONObject;
129
import org.springframework.beans.factory.annotation.Autowired;
130
import org.springframework.beans.factory.annotation.Qualifier;
131
import org.springframework.beans.factory.annotation.Value;
132
import org.springframework.core.io.ByteArrayResource;
133
import org.springframework.core.io.InputStreamSource;
134
import org.springframework.mail.javamail.JavaMailSender;
135
import org.springframework.mail.javamail.MimeMessageHelper;
136
import org.springframework.stereotype.Component;
137
import org.springframework.transaction.annotation.Transactional;
31640 tejbeer 138
 
32421 amit.gupta 139
import javax.mail.MessagingException;
140
import javax.mail.internet.InternetAddress;
141
import javax.mail.internet.MimeMessage;
142
import java.io.*;
143
import java.math.BigDecimal;
144
import java.math.RoundingMode;
145
import java.nio.file.Files;
146
import java.nio.file.Paths;
147
import java.sql.Timestamp;
148
import java.text.DecimalFormat;
149
import java.time.*;
150
import java.time.format.DateTimeFormatter;
151
import java.time.temporal.ChronoField;
152
import java.time.temporal.ChronoUnit;
153
import java.util.*;
154
import java.util.Map.Entry;
155
import java.util.stream.Collectors;
156
import java.util.stream.Stream;
32060 amit.gupta 157
 
33664 amit.gupta 158
import static java.util.stream.Collectors.*;
32421 amit.gupta 159
 
160
 
23723 amit.gupta 161
@Component
33384 amit.gupta 162
@Transactional(rollbackFor = {Throwable.class, ProfitMandiBusinessException.class})
23723 amit.gupta 163
public class ScheduledTasks {
164
 
31697 amit.gupta 165
    @Value("${oxigen.recharge.enquiry.url}")
166
    private String oxigenRechargeEnquiryUrl;
24533 govind 167
 
31697 amit.gupta 168
    @Autowired
32482 amit.gupta 169
    PurchaseMigration purchaseMigration;
170
 
171
    @Autowired
32795 amit.gupta 172
    SmartPingService smartPingService;
173
 
33553 ranu 174
    @Autowired
175
    private ASTRepository astRepository;
29668 tejbeer 176
 
31697 amit.gupta 177
    @Autowired
178
    private ServiceConfigService serviceConfigService;
29801 manish 179
 
31697 amit.gupta 180
    @Autowired
181
    private TecnoImeiActivation tecnoImeiActivation;
28205 tejbeer 182
 
31697 amit.gupta 183
    private static final DateTimeFormatter leadTimeFormatter = DateTimeFormatter.ofPattern("d LLL, hh:mm a");
27088 tejbeer 184
 
31697 amit.gupta 185
    @Autowired
186
    private PartnerRegionRepository partnerRegionRepository;
28790 amit.gupta 187
 
31697 amit.gupta 188
    @Autowired
189
    private EmployeeAttendanceRepository employeeAttendanceRepository;
27088 tejbeer 190
 
31697 amit.gupta 191
    @Autowired
192
    VivoImeiActivationService vivoImeiActivationService;
29488 manish 193
 
31697 amit.gupta 194
    @Autowired
195
    ItelImeiActivationService itelImeiActivationService;
29488 manish 196
 
31697 amit.gupta 197
    @Autowired
198
    private PartnerTypeChangeService partnerTypeChangeService;
25598 amit.gupta 199
 
26408 amit.gupta 200
 
31697 amit.gupta 201
    @Autowired
202
    private LeadRepository leadRepository;
25927 amit.gupta 203
 
31697 amit.gupta 204
    @Autowired
205
    private AuthRepository authRepository;
25503 amit.gupta 206
 
31697 amit.gupta 207
    @Autowired
208
    private PriceDropService priceDropService;
26283 tejbeer 209
 
31697 amit.gupta 210
    @Autowired
211
    private FranchiseeVisitRepository franchiseeVisitRepository;
26790 tejbeer 212
 
31697 amit.gupta 213
    @Autowired
214
    private FranchiseeActivityRepository franchiseeActivityRepository;
26790 tejbeer 215
 
31697 amit.gupta 216
    @Autowired
217
    private HdfcPaymentRepository hdfcPaymentRepository;
26790 tejbeer 218
 
31697 amit.gupta 219
    @Autowired
220
    private CsService csService;
25846 amit.gupta 221
 
31697 amit.gupta 222
    @Autowired
223
    private SaholicInventoryService saholicInventoryService;
27208 tejbeer 224
 
31697 amit.gupta 225
    @Autowired
226
    private InsurancePolicyRepository insurancePolicyRepository;
23723 amit.gupta 227
 
31697 amit.gupta 228
    @Autowired
229
    private ToffeeService toffeeService;
25694 amit.gupta 230
 
31697 amit.gupta 231
    @Value("${oxigen.recharge.auth.key}")
232
    private String oxigenRechargeAuthKey;
23724 amit.gupta 233
 
31697 amit.gupta 234
    @Value("${oxigen.recharge.validation.url}")
235
    private String oxigenRechargeValidationUrl;
23724 amit.gupta 236
 
31697 amit.gupta 237
    @Value("${oxigen.recharge.validation.auth.key}")
238
    private String oxigenRechargeValidationAuthKey;
23724 amit.gupta 239
 
31697 amit.gupta 240
    @Value("${think.walnut.digital.recharge.transaction.mobile.url}")
241
    private String thinkWalnutDigitalRechargeTransactionMobileUrl;
23724 amit.gupta 242
 
31697 amit.gupta 243
    @Value("${think.walnut.digital.recharge.transaction.dth.url}")
244
    private String thinkWalnutDigitalRechargeTransactionDthUrl;
23724 amit.gupta 245
 
31697 amit.gupta 246
    @Value("${think.walnut.digital.recharge.enquiry.url}")
247
    private String thinkWalnutDigitalRechargeEnquiryUrl;
23724 amit.gupta 248
 
31697 amit.gupta 249
    @Value("${think.walnut.digital.recharge.balance.url}")
250
    private String thinkWalnutDigitalRechargeBalanceUrl;
23724 amit.gupta 251
 
31697 amit.gupta 252
    @Value("${think.walnut.digital.recharge.username}")
253
    private String thinkWalnutDigitalRechargeUserName;
23724 amit.gupta 254
 
31697 amit.gupta 255
    @Value("${think.walnut.digital.recharge.password}")
256
    private String thinkWalnutDigitalRechargePassword;
23724 amit.gupta 257
 
31697 amit.gupta 258
    @Value("${think.walnut.digital.recharge.auth.key}")
259
    private String thinkWalnutDigitalRechargeAuthKey;
23724 amit.gupta 260
 
31697 amit.gupta 261
    @Autowired
262
    private PurchaseRepository purchaseRepository;
23724 amit.gupta 263
 
31697 amit.gupta 264
    @Autowired
265
    private PriceDropIMEIRepository priceDropIMEIRepository;
25609 amit.gupta 266
 
31697 amit.gupta 267
    @Autowired
268
    PriceDropRepository priceDropRepository;
25609 amit.gupta 269
 
31697 amit.gupta 270
    @Autowired
271
    private PartnerTypeChangeRepository partnerTypeChangeRepository;
28368 tejbeer 272
 
31697 amit.gupta 273
    @Autowired
274
    private SchemeService schemeService;
24683 amit.gupta 275
 
31697 amit.gupta 276
    @Autowired
277
    private ServiceConfigRepository serviceConfigRepository;
29668 tejbeer 278
 
32061 amit.gupta 279
    @Autowired
280
    private RetailerBlockBrandsRepository retailerBlockBrandsRepository;
281
 
34547 vikas.jang 282
    @Autowired
283
    private LiquidationService liquidationService;
284
 
34578 vikas.jang 285
    private static final String[] STOCK_AGEING_MAIL_LIST = new String[]{"uday.singh@smartudkaan.com", "mohinder.mutreja@smartdukaan.com", "ankit.bhatia@smartdukaan.com", "tarun.verma@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "manish.gupta1@smartdukaan.com"};
25609 amit.gupta 286
 
31886 tejbeer 287
    private static final String[] ITEMWISE_PENDING_INDENT_MAIL_LIST = new String[]{"kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "uday.singh@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "niranjan.kala@smartdukaan.com"};
25609 amit.gupta 288
 
33664 amit.gupta 289
    private static final String[] INDENT_TERTIARY_MAIL_LIST = new String[]{"uday.singh@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "nishant.ohri@smartdukaan.com", "vinay.p@smartdukaan.com", "deena.nath@smartdukaan.com", "shobhit.tandon@smartdukaan.com", "ritesh.chauhan1@smartdukaan.com"};
28709 amit.gupta 290
 
31886 tejbeer 291
    private static final String[] EMPLOYEE_ATTENDANCE_MAIL_LIST = new String[]{"sm@smartdukaan.com", "sm@smartdukaan.com"};
28790 amit.gupta 292
 
31697 amit.gupta 293
    private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING);
25721 tejbeer 294
 
31697 amit.gupta 295
    @Autowired
296
    private ReporticoService reporticoService;
23724 amit.gupta 297
 
31697 amit.gupta 298
    @Autowired
299
    private PartnerInvestmentService partnerInvestmentService;
25598 amit.gupta 300
 
31697 amit.gupta 301
    @Autowired
302
    private PositionRepository positionRepository;
24337 amit.gupta 303
 
31697 amit.gupta 304
    @Autowired
305
    private FofoOrderItemRepository fofoOrderItemRepository;
25865 amit.gupta 306
 
31697 amit.gupta 307
    @Autowired
308
    private NotificationService notificationService;
24542 amit.gupta 309
 
31697 amit.gupta 310
    @Autowired
311
    private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
24277 amit.gupta 312
 
31697 amit.gupta 313
    @Autowired
314
    private SchemeInOutRepository schemeInOutRepository;
24241 amit.gupta 315
 
31697 amit.gupta 316
    @Autowired
317
    private RechargeTransactionRepository rechargeTransactionRepository;
23724 amit.gupta 318
 
31697 amit.gupta 319
    @Autowired
320
    private CustomerAddressRepository customerAddressRepository;
24542 amit.gupta 321
 
31697 amit.gupta 322
    @Autowired
323
    private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
23724 amit.gupta 324
 
31697 amit.gupta 325
    @Autowired
326
    private FofoLineItemRepository fofoLineItemRepository;
24590 amit.gupta 327
 
31697 amit.gupta 328
    @Autowired
329
    private FofoOrderRepository fofoOrderRepository;
24587 amit.gupta 330
 
31697 amit.gupta 331
    @Autowired
332
    private UserWalletHistoryRepository userWalletHistoryRepository;
24250 amit.gupta 333
 
31697 amit.gupta 334
    @Autowired
335
    private UserWalletRepository userWalletRepository;
24587 amit.gupta 336
 
31697 amit.gupta 337
    @Autowired
338
    private InventoryItemRepository inventoryItemRepository;
23929 amit.gupta 339
 
31697 amit.gupta 340
    @Autowired
341
    private WalletService walletService;
23724 amit.gupta 342
 
31697 amit.gupta 343
    @Autowired
344
    private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
23724 amit.gupta 345
 
31697 amit.gupta 346
    @Autowired
347
    private OxigenRechargeProviderService oxigenRechargeProviderService;
23724 amit.gupta 348
 
31697 amit.gupta 349
    @Autowired
350
    private RechargeProviderRepository rechargeProviderRepository;
23724 amit.gupta 351
 
31697 amit.gupta 352
    @Autowired
353
    private ScanRecordRepository scanRecordRepository;
24242 amit.gupta 354
 
31697 amit.gupta 355
    @Autowired
356
    private DailyRechargeRepository dailyRechargeRepository;
23724 amit.gupta 357
 
31697 amit.gupta 358
    @Autowired
359
    private FofoStoreRepository fofoStoreRepository;
24177 govind 360
 
31697 amit.gupta 361
    @Value("${prod}")
362
    private boolean prod;
26945 amit.gupta 363
 
31697 amit.gupta 364
    @Autowired
365
    private StateGstRateRepository stateGstRateRepository;
23724 amit.gupta 366
 
31697 amit.gupta 367
    @Autowired
368
    private RetailerService retailerService;
23929 amit.gupta 369
 
31697 amit.gupta 370
    @Autowired
33078 ranu 371
    private BrandsRepository brandsRepository;
372
 
373
    @Autowired
31697 amit.gupta 374
    private TransactionService transactionService;
24250 amit.gupta 375
 
31697 amit.gupta 376
    @Autowired
377
    private ItemRepository itemRepository;
23929 amit.gupta 378
 
31697 amit.gupta 379
    @Autowired
380
    private OrderRepository orderRepository;
25351 tejbeer 381
 
31697 amit.gupta 382
    @Autowired
383
    private OrderService orderService;
23929 amit.gupta 384
 
31697 amit.gupta 385
    @Autowired
386
    private SchemeRepository schemeRepository;
24241 amit.gupta 387
 
31697 amit.gupta 388
    @Autowired
389
    private SchemeItemRepository schemeItemRepository;
31612 tejbeer 390
 
31697 amit.gupta 391
    @Autowired
392
    private JavaMailSender mailSender;
24177 govind 393
 
31697 amit.gupta 394
    @Autowired
395
    private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 396
 
31697 amit.gupta 397
    @Autowired
398
    @Qualifier(value = "googleMailSender")
399
    private JavaMailSender googleMailSender;
23929 amit.gupta 400
 
31697 amit.gupta 401
    @Autowired
402
    private InventoryService inventoryService;
23929 amit.gupta 403
 
31697 amit.gupta 404
    @Autowired
405
    private AddressRepository addressRepository;
24542 amit.gupta 406
 
31697 amit.gupta 407
    @Autowired
408
    private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
24542 amit.gupta 409
 
31697 amit.gupta 410
    @Autowired
411
    private Mongo mongoClient;
24683 amit.gupta 412
 
31697 amit.gupta 413
    @Autowired
414
    private DeviceRepository deviceRepository;
25300 tejbeer 415
 
31697 amit.gupta 416
    @Autowired
417
    private PushNotificationRepository pushNotificationRepository;
25300 tejbeer 418
 
31697 amit.gupta 419
    @Autowired
420
    private NotificationCampaignRepository notificationCampaignRepository;
25300 tejbeer 421
 
31697 amit.gupta 422
    @Autowired
423
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
25721 tejbeer 424
 
31697 amit.gupta 425
    @Autowired
426
    private FocusedModelRepository focusedModelRepository;
25721 tejbeer 427
 
31697 amit.gupta 428
    @Autowired
429
    private UserAccountRepository userAccountRepository;
24653 govind 430
 
31697 amit.gupta 431
    @Autowired
432
    private UserRepository userUserRepository;
25721 tejbeer 433
 
31697 amit.gupta 434
    @Autowired
435
    private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
25927 amit.gupta 436
 
31697 amit.gupta 437
    @Autowired
438
    private UserCampaignRepository userCampaignRepository;
25721 tejbeer 439
 
31697 amit.gupta 440
    @Autowired
441
    private Gson gson;
25721 tejbeer 442
 
31697 amit.gupta 443
    @Autowired
444
    private TicketRepository ticketRepository;
26283 tejbeer 445
 
31697 amit.gupta 446
    @Autowired
447
    private RefferalRepository refferalRepository;
26790 tejbeer 448
 
31697 amit.gupta 449
    @Autowired
450
    private PartnerProblemRepository partnerProblemRepository;
28205 tejbeer 451
 
31697 amit.gupta 452
    @Autowired
453
    private PendingOrderRepository pendingOrderRepository;
28368 tejbeer 454
 
31697 amit.gupta 455
    @Autowired
456
    private PendingOrderItemRepository pendingOrderItemRepository;
28368 tejbeer 457
 
31697 amit.gupta 458
    @Value("${razorpay.account.keyId}")
459
    private String keyId;
28368 tejbeer 460
 
31697 amit.gupta 461
    @Value("${razorpay.account.keySecret}")
462
    private String keySecret;
28368 tejbeer 463
 
31697 amit.gupta 464
    @Autowired
465
    private RazorpayPaymentService razorPaymentService;
28369 tejbeer 466
 
31697 amit.gupta 467
    @Autowired
468
    private RazorPayRepository razorPayRepository;
28369 tejbeer 469
 
31697 amit.gupta 470
    @Autowired
471
    private PendingOrderService pendingOrderService;
28377 tejbeer 472
 
31697 amit.gupta 473
    @Autowired
474
    private CustomerRepository customerRepository;
28377 tejbeer 475
 
31697 amit.gupta 476
    @Autowired
477
    private RestClient restClient;
29308 tejbeer 478
 
31697 amit.gupta 479
    @Autowired
480
    private MandiiService mandiiService;
29814 tejbeer 481
 
31697 amit.gupta 482
    @Autowired
483
    CreditAccountRepository creditAccountRepository;
31604 tejbeer 484
 
31697 amit.gupta 485
    @Autowired
486
    CustomerOfferRepository customerOfferRepository;
31612 tejbeer 487
 
31697 amit.gupta 488
    @Autowired
489
    CustomerOfferItemRepository customerOfferItemRepository;
490
    @Autowired
491
    private FofoSolr fofoSolr;
23724 amit.gupta 492
 
25300 tejbeer 493
 
31697 amit.gupta 494
    private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
31388 amit.gupta 495
 
34039 vikas.jang 496
    private String FCM_URL = "https://fcm.googleapis.com/v1/projects/api-project-309385327230/messages:send";
497
    private String FCM_SCOPED = "https://www.googleapis.com/auth/cloud-platform";
23724 amit.gupta 498
 
31697 amit.gupta 499
    @Autowired
500
    private TagListingRepository tagListingRepository;
33994 amit.gupta 501
    @Autowired
502
    private RunOnceTasks runOnceTasks;
23724 amit.gupta 503
 
31697 amit.gupta 504
    public void generateDailyRecharge() {
31886 tejbeer 505
        List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository.selectAll(0, 2000);
31697 amit.gupta 506
        List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
507
        rechargeProviders.stream().forEach(x -> x.setAmount(0));
23724 amit.gupta 508
 
31697 amit.gupta 509
        rechargeProviders.stream().forEach(x -> {
31886 tejbeer 510
            Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory.stream().filter(z -> z.getProviderId() == x.getId()).collect(groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
23724 amit.gupta 511
 
31697 amit.gupta 512
            LOGGER.info("dateWiseProviderCreditsMap -{}", dateWiseProviderCreditsMap);
513
            LocalDate endDate = LocalDate.now().plusDays(1);
514
            float previousDayClosing = 0;
515
            LocalDate date = LocalDate.of(2018, 4, 6);
516
            while (date.isBefore(endDate)) {
31886 tejbeer 517
                List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(), date.plusDays(1).atStartOfDay());
23724 amit.gupta 518
 
31886 tejbeer 519
                List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream().filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
23724 amit.gupta 520
 
31697 amit.gupta 521
                float dailyAmount = 0;
522
                float totalCommission = 0;
523
                for (RechargeTransaction rechargeTransaction : successfulTransactions) {
524
                    if (rechargeTransaction.getProviderId() == x.getId()) {
525
                        dailyAmount += rechargeTransaction.getAmount();
526
                        totalCommission += rechargeTransaction.getCommission();
527
                    }
528
                }
28205 tejbeer 529
 
31697 amit.gupta 530
                List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
531
                float dailyWalletRecharge = 0;
532
                if (rechargeHistoryList != null) {
533
                    for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
534
                        if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
535
                            dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
536
                        }
537
                    }
538
                }
539
                if (dailyAmount > 0 || dailyWalletRecharge > 0) {
540
                    DailyRecharge dailyRecharge = null;
541
                    try {
542
                        dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
543
                    } catch (Exception e) {
544
                        LOGGER.info("Could not find Recharge entry");
545
                    }
546
                    if (dailyRecharge == null) {
547
                        dailyRecharge = new DailyRecharge();
548
                        dailyRecharge.setCreateDate(date);
549
                    }
550
                    dailyRecharge.setOpeningBalance(previousDayClosing);
551
                    dailyRecharge.setProviderId(x.getId());
552
                    dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
553
                    dailyRecharge.setTotalAmount(dailyAmount);
554
                    dailyRecharge.setTotalCommission(totalCommission);
555
                    float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
556
                    dailyRecharge.setClosingBalance(closingBalance);
557
                    dailyRechargeRepository.persist(dailyRecharge);
558
                    x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
559
                    previousDayClosing = dailyRecharge.getClosingBalance();
560
                }
561
                date = date.plusDays(1);
562
            }
563
            rechargeProviderRepository.persist(x);
564
        });
565
        LOGGER.info("finished generating daily recharge");
566
    }
24240 amit.gupta 567
 
31697 amit.gupta 568
    public void reconcileRecharge() throws Exception {
569
        LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
570
        LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
571
        List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
572
        LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
573
        nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
574
        nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
575
        RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
576
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
577
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
578
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
579
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
580
        Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
31886 tejbeer 581
        List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
31697 amit.gupta 582
        for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
583
            try {
584
                int providerId = rechargeTransaction.getProviderId();
585
                if (providerId == 1) {
31886 tejbeer 586
                    oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey, rechargeTransaction);
31697 amit.gupta 587
                } else if (providerId == 2) {
31886 tejbeer 588
                    thinkWalnutDigitalRechargeProviderService.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
31697 amit.gupta 589
                }
31886 tejbeer 590
                if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS) || rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
591
                    requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(), rechargeTransaction.getStatus());
31697 amit.gupta 592
                }
593
            } catch (Exception e) {
594
                LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
595
            }
596
        }
597
        LOGGER.info("Reconcile recharge ran successfully");
598
    }
24241 amit.gupta 599
 
31697 amit.gupta 600
    public void processActivation() throws Exception {
601
        schemeService.processActivation();
602
    }
24241 amit.gupta 603
 
31697 amit.gupta 604
    // TemporaryMethod
605
    public void migrateInvoice() {
606
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
607
        Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
31886 tejbeer 608
        partnerOrdersMap = fofoOrders.stream().collect(groupingBy(FofoOrder::getFofoId, Collectors.toList()));
31697 amit.gupta 609
        for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
610
            int sequence = 0;
611
            String prefix = "";
31886 tejbeer 612
            List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId()).collect(Collectors.toList());
31697 amit.gupta 613
            for (FofoOrder order : sortedList) {
23724 amit.gupta 614
 
31697 amit.gupta 615
                LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
616
                if (!order.getInvoiceNumber().contains("SEC")) {
617
                    sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
618
                    prefix = order.getInvoiceNumber().split("/")[0];
619
                } else {
620
                    sequence += 1;
621
                    String invoiceNumber = prefix + "/" + sequence;
622
                    order.setInvoiceNumber(invoiceNumber);
623
                    fofoOrderRepository.persist(order);
624
                }
625
            }
24252 amit.gupta 626
 
31697 amit.gupta 627
        }
628
    }
28205 tejbeer 629
 
31697 amit.gupta 630
    @Autowired
631
    private ReporticoCacheTableRepository reporticoCacheTableRepository;
28205 tejbeer 632
 
31697 amit.gupta 633
    public void processSchemeOut(List<String> invoiceNumbers) throws Exception {
634
        for (String invoiceNumber : invoiceNumbers) {
635
            System.out.println("Invoice Number - " + invoiceNumber);
636
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
32147 amit.gupta 637
            //orderService.reverseScheme(fofoOrder);
31697 amit.gupta 638
            schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
639
        }
640
    }
24271 amit.gupta 641
 
31697 amit.gupta 642
    public void processSchemeIn(List<String> invoiceNumbers) throws Exception {
643
        for (String invoiceNumber : invoiceNumbers) {
644
            System.out.println("Invoice Number - " + invoiceNumber);
645
            Purchase purchase = purchaseRepository.selectByPurchaseReference(invoiceNumber);
646
            schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
647
        }
648
    }
24271 amit.gupta 649
 
31697 amit.gupta 650
    public void processScheme(LocalDateTime startDate, LocalDateTime endDate, boolean dryRun) throws Exception {
651
        LOGGER.info("Started execution at {}", LocalDateTime.now());
652
        System.out.println(
653
                "InventoryId\tSerialNumber\tItem Id\tScheme Id\tScheme Name\tScheme Type\tAmount Type\tDP\tTaxable\tScheme Amount\tAmount Paid");
654
        try {
655
            List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
656
            for (Purchase purchase : purchases) {
657
                schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
658
            }
29160 amit.gupta 659
 
31697 amit.gupta 660
            List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
661
            for (FofoOrder fofoOrder : fofoOrders) {
662
                schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
663
            }
664
        } catch (Exception e) {
665
            e.printStackTrace();
666
            throw e;
667
        }
31886 tejbeer 668
        List<UserWalletHistory> uwhs = userWalletHistoryRepository.selectAllByDateType(LocalDate.now().atStartOfDay(), endDate, Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
31697 amit.gupta 669
        System.out.println("Amount\tReference\tReferenceType\tTimestamp\tDescription");
670
        for (UserWalletHistory uwh : uwhs) {
31886 tejbeer 671
            System.out.println(String.format("%d\t%d\t%s\t%s\t%s", uwh.getAmount(), uwh.getReference(), uwh.getReferenceType(), uwh.getTimestamp().toString(), uwh.getDescription()));
31697 amit.gupta 672
        }
673
        LOGGER.info("Schemes processed successfully.");
674
        if (dryRun) {
675
            throw new Exception();
676
        }
677
    }
29160 amit.gupta 678
 
31697 amit.gupta 679
    public void processRechargeCashback() throws Throwable {
680
        LocalDateTime cashbackTime = LocalDateTime.now();
681
        int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
31886 tejbeer 682
        List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository.getPendingCashBackRehargeTransactions();
31697 amit.gupta 683
        Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
31724 amit.gupta 684
                groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
33452 amit.gupta 685
        for (Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
31697 amit.gupta 686
            int retailerId = (Integer) totalRetailerCashback.getKey();
687
            float amount = totalRetailerCashback.getValue().floatValue();
688
            if (Math.round(amount) > 0) {
31886 tejbeer 689
                walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK, "Recharge Cashback", Math.round(amount), LocalDateTime.now());
31697 amit.gupta 690
            }
691
        }
692
        for (RechargeTransaction rt : pendingTransactions) {
693
            rt.setCashbackTimestamp(cashbackTime);
694
            rt.setCashbackReference(referenceId);
695
            rechargeTransactionRepository.persist(rt);
696
        }
697
        LOGGER.info("Cashbacks for Recharge processed Successfully");
698
    }
29160 amit.gupta 699
 
35521 amit 700
    public void rollOutUpgardedMarginsNextMonth(List<Integer> fofoIds) throws Exception {
31697 amit.gupta 701
        LocalDate startOfPreviousMonth = LocalDate.now().with(ChronoField.DAY_OF_MONTH, 1).minusMonths(1);
35521 amit 702
        List<FofoStore> stores;
35530 amit 703
        if (fofoIds == null || fofoIds.isEmpty()) {
35521 amit 704
            stores = fofoStoreRepository.selectActiveStores();
705
        } else {
706
            stores = fofoStoreRepository.selectByRetailerIds(fofoIds);
707
        }
31697 amit.gupta 708
        for (FofoStore store : stores) {
32003 amit.gupta 709
            this.rolloutMarginForStoreOnMonth(store, startOfPreviousMonth);
710
        }
711
    }
29252 amit.gupta 712
 
32003 amit.gupta 713
    public void rolloutMarginForStoreOnMonth(FofoStore store, LocalDate startOfMonth) throws ProfitMandiBusinessException {
714
        int fofoId = store.getId();
29252 amit.gupta 715
 
35531 amit 716
        // Check if there's a manual partner type change on day 1 of the month
717
        PartnerTypeChange day1Change = partnerTypeChangeRepository.selectPartnerType(fofoId, startOfMonth);
718
        if (day1Change != null && day1Change.getSource() == PartnerTypeSource.MANUAL) {
719
            LOGGER.info("Manual partner type upgrade detected for code {} to {}", store.getCode(), day1Change.getPartnerType());
720
            List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startOfMonth.atStartOfDay(), startOfMonth.plusMonths(1).atStartOfDay(), 0, 0);
721
            for (FofoOrder fofoOrder : fofoOrders) {
722
                schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
723
            }
724
            return;
725
        }
726
 
727
        // Existing logic for calculated upgrades
32003 amit.gupta 728
        PartnerType startOfPreviousMonthPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth);
34777 amit.gupta 729
        PartnerType todayPartnerType = partnerTypeChangeService.getTypeOnMonth(fofoId, YearMonth.from(startOfMonth));
32003 amit.gupta 730
        if (!startOfPreviousMonthPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
731
            return;
732
        }
733
        if (!startOfPreviousMonthPartnerType.equals(todayPartnerType)) {
734
            LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(), startOfPreviousMonthPartnerType, todayPartnerType);
735
            List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startOfMonth.atStartOfDay(), startOfMonth.plusMonths(1).atStartOfDay(), 0, 0);
736
            for (FofoOrder fofoOrder : fofoOrders) {
737
                schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
31697 amit.gupta 738
            }
739
        }
740
    }
29252 amit.gupta 741
 
32003 amit.gupta 742
 
35521 amit 743
    public void rollOutUpgardedMargins(List<Integer> fofoIds) throws Exception {
31697 amit.gupta 744
        LocalDate today = LocalDate.now();
745
        LocalDate yesterday = today.minusDays(1);
746
        int upgradedCount = 0;
35521 amit 747
        List<FofoStore> stores;
748
        if (fofoIds == null || fofoIds.isEmpty()) {
749
            stores = fofoStoreRepository.selectActiveStores();
750
        } else {
751
            stores = fofoStoreRepository.selectByRetailerIds(fofoIds);
752
        }
35461 amit 753
 
754
        // Bulk fetch partner types to avoid N+1 queries
755
        Map<Integer, PartnerType> yesterdayTypeMap = partnerTypeChangeService.getTypesForFofoIds(fofoIds, yesterday);
756
        Map<Integer, PartnerType> todayTypeMap = partnerTypeChangeService.getTypesForFofoIds(fofoIds, today);
757
 
31697 amit.gupta 758
        StringBuilder sb = new StringBuilder();
759
        for (FofoStore store : stores) {
760
            int fofoId = store.getId();
23724 amit.gupta 761
 
35461 amit 762
            PartnerType yesterdayPartnerType = yesterdayTypeMap.get(fofoId);
763
            PartnerType todayPartnerType = todayTypeMap.get(fofoId);
764
            if (yesterdayPartnerType == null || todayPartnerType == null) {
765
                continue;
766
            }
31697 amit.gupta 767
            if (!yesterdayPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
768
                continue;
769
            }
770
            if (!yesterdayPartnerType.equals(todayPartnerType)) {
771
                upgradedCount++;
31886 tejbeer 772
                sb.append(String.format("Partner Type has been changed for code %s from %s to %s", store.getCode(), yesterdayPartnerType.toString(), todayPartnerType.toString()));
31697 amit.gupta 773
                sb.append("<br>");
31886 tejbeer 774
                LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(), yesterdayPartnerType, todayPartnerType);
775
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, yesterday.withDayOfMonth(1).atStartOfDay(), yesterday.atStartOfDay(), 0, 0);
31697 amit.gupta 776
                for (FofoOrder fofoOrder : fofoOrders) {
777
                    schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
778
                }
30390 amit.gupta 779
 
31697 amit.gupta 780
            }
781
        }
782
        if (upgradedCount > 0) {
32439 tejbeer 783
            sendMailOfHtmlFormat(googleMailSender, new String[]{"amit.gupta@smartdukaan.com", "tarun.verma@smartdukaan.com", "neeraj.gupta@smartdukaan.com"}, sb.toString(), null, "Few Partners Category have been Upgraded");
31697 amit.gupta 784
        } else {
32439 tejbeer 785
            sendMailOfHtmlFormat(googleMailSender, new String[]{"amit.gupta@smartdukaan.com", "tarun.verma@smartdukaan.com", "neeraj.gupta@smartdukaan.com"}, sb.toString(), null, "No partners Category have been upgraded today");
31697 amit.gupta 786
        }
787
    }
30393 amit.gupta 788
 
31697 amit.gupta 789
    @Autowired
790
    private PartnerStatsService partnerStatsService;
30393 amit.gupta 791
 
35521 amit 792
// Temporary Method
30393 amit.gupta 793
 
31697 amit.gupta 794
    public void fetchParnterStats() throws Exception {
795
        Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
796
        ObjectOutputStream oos = null;
797
        FileOutputStream fout = null;
798
        try {
34666 ranu 799
//            fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
800
            fout = new FileOutputStream("/var/www/partner_stats/partnerStat.tmp", false);
31697 amit.gupta 801
            oos = new ObjectOutputStream(fout);
802
            oos.writeObject(partnerStats);
30637 amit.gupta 803
 
31697 amit.gupta 804
        } catch (Exception ex) {
805
            ex.printStackTrace();
806
        } finally {
807
            if (oos != null) {
808
                oos.close();
809
            }
810
        }
32421 amit.gupta 811
        ReporticoCacheTable reporticoCacheTable = reporticoCacheTableRepository.selectByTableName("partnerStat");
812
        if (reporticoCacheTable == null) {
813
            reporticoCacheTable = new ReporticoCacheTable();
814
            reporticoCacheTable.setTableName("partnerStat");
815
            reporticoCacheTable.setLastCreatedTimestamp(LocalDateTime.now());
816
            reporticoCacheTableRepository.persist(reporticoCacheTable);
31697 amit.gupta 817
        } else {
32421 amit.gupta 818
            reporticoCacheTable.setLastCreatedTimestamp(LocalDateTime.now());
31697 amit.gupta 819
        }
820
    }
31008 amit.gupta 821
 
31697 amit.gupta 822
    public void processPriceDrop() throws Exception {
31886 tejbeer 823
        List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetween(LocalDateTime.now(), LocalDateTime.now().minusYears(1));
31697 amit.gupta 824
        for (PriceDrop priceDrop : priceDrops) {
825
            if (priceDrop.getDropAmount() > 0) {
826
                priceDropService.processPriceDrop(priceDrop.getId(), true);
827
            }
828
        }
829
    }
31008 amit.gupta 830
 
31697 amit.gupta 831
    @Autowired
832
    CreditNoteService creditNoteService;
25598 amit.gupta 833
 
31697 amit.gupta 834
    public void sendCreditNote(YearMonth yearMonth) throws Exception {
835
        creditNoteService.issueMonthlyMarginsCN(yearMonth);
836
    }
25598 amit.gupta 837
 
31918 amit.gupta 838
    @Autowired
839
    BrandAgeingLimitRepository brandAgeingLimitRepository;
840
 
841
    @Autowired
842
    AgeingService ageingService;
843
 
33928 ranu 844
    @Autowired
845
    RbmTargetService rbmTargetService;
846
 
31918 amit.gupta 847
    public void sendMailForAgeingAlert() throws Exception {
848
        //brandAgeingLimitRepository.selectAll();
849
        Map<String, AgeingModel> ageingModelMap = ageingService.getAllAgeingForSecondary();
850
 
851
        System.out.println(ageingModelMap.size());
852
        List<PartnerAgeingModel> partnerAgeingModels = ageingService.getAllAgeingForTertiary();
853
 
854
 
33452 amit.gupta 855
        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()));
31918 amit.gupta 856
 
33452 amit.gupta 857
        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()));
858
        Attachment attachment1 = new Attachment("secondary-alert.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
859
        Attachment attachment2 = new Attachment("tertiary-alert.csv", new ByteArrayResource(byteArrayOutputStream2.toByteArray()));
31918 amit.gupta 860
 
861
        String mailSubject = "Stock ageing Alert";
862
        Utils.sendMailWithAttachments(mailSender, new String[]{"deena.nath@smartdukaan.com"}, null, mailSubject, "PFA", attachment1, attachment2);
863
    }
864
 
32724 amit.gupta 865
    public void rejectPriceDropsOfApprovedImeis() throws ProfitMandiBusinessException {
32690 amit.gupta 866
        priceDropService.rejectPriceDropsOfApprovedImeis();
867
    }
868
 
33357 amit.gupta 869
    public void processDeductions() {
870
        sidbiService.processDeductions();
871
    }
872
 
35521 amit 873
    public void resetHardLimit() throws ProfitMandiBusinessException {
33904 amit.gupta 874
        sdCreditService.resetHardLimit();
875
    }
876
 
35021 amit 877
    public void testInvoiceFormat() throws ProfitMandiBusinessException {
878
        InvoicePdfModel invoicePdfModel = orderService.getInvoicePdfModel(560280);
879
        //System.out.println(InvoiceFormatter.buildInvoiceLines(invoicePdfModel, InvoiceFormatter.WIDTH_80MM));
880
    }
881
 
35326 amit 882
    public void sendTrialExpiry() {
883
        List<FofoStore> stores = fofoStoreRepository.selectAllTrial();
35521 amit 884
        List<FofoStore> twoDaysToExpiry = stores.stream().filter(x -> x.getTrialEnd().minusDays(2).equals(LocalDate.now())).collect(Collectors.toList());
35326 amit 885
 
35521 amit 886
        List<FofoStore> fiveDaysToExpiry = stores.stream().filter(x -> x.getTrialEnd().minusDays(5).equals(LocalDate.now())).collect(Collectors.toList());
887
        List<FofoStore> expiredToday = stores.stream().filter(x -> x.getTrialEnd().equals(LocalDate.now())).collect(Collectors.toList());
888
        List<FofoStore> expired = stores.stream().filter(x -> x.getTrialEnd().isAfter(LocalDate.now())).collect(Collectors.toList());
35326 amit 889
    }
890
 
34710 amit.gupta 891
    /*public void processCashDiscount() throws ProfitMandiBusinessException {
892
        System.out.println("processing cash discount");
893
        List<Loan> loansSettledYesterday = loanRepository.selectLoansSettledOn(LocalDate.now().minusDays(1));
894
        loansSettledYesterday.addAll(loanRepository.selectLoansSettledOn(LocalDate.now()));
895
        Map<Integer, List<Loan>> partnerSettledLoans = loansSettledYesterday.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
896
        for (Entry<Integer, List<Loan>> partnerLoans : partnerSettledLoans.entrySet()) {
897
            List<Loan> fullCdLoans = partnerLoans.getValue().stream().filter(x -> x.getInvoiceNumber() != null && x.getDays() <= ProfitMandiConstants.LOAN_PARTIAL_CREDIT_DAYS).collect(toList());
898
            List<Loan> partialCdLoans = partnerLoans.getValue().stream().filter(x -> x.getInvoiceNumber() != null && x.getDays() > ProfitMandiConstants.LOAN_PARTIAL_CREDIT_DAYS &&
899
                    x.getDays() <= ProfitMandiConstants.LOAN_FULL_CREDIT_DAYS).collect(toList());
900
            //List<Loan> noCdLoans = loanRepository.selectLoansDueByDays()
901
            //
902
            for (Loan fullCdLoan : fullCdLoans) {
903
                LOGGER.info("FullCdLoan - {}", fullCdLoan);
904
                schemeService.processFullCD(fullCdLoan.getInvoiceNumber());
905
            }
906
 
907
            for (Loan partialCdLoan : partialCdLoans) {
908
                schemeService.processPartialCD(partialCdLoan.getInvoiceNumber());
909
            }
910
 
911
            *//*for (Loan noCdLoan : noCdLoans) {
912
                schemeService.processNoCD(noCdLoan.getInvoiceNumber());
913
            }*//*
914
        }
915
 
916
    }*/
917
 
31697 amit.gupta 918
    private class SaleRoles {
25598 amit.gupta 919
 
31697 amit.gupta 920
        private List<String> l1;
921
        private List<String> l2;
25598 amit.gupta 922
 
31697 amit.gupta 923
        public SaleRoles() {
924
            l1 = new ArrayList<>();
925
            l2 = new ArrayList<>();
926
        }
25598 amit.gupta 927
 
31697 amit.gupta 928
        public List<String> getL1() {
929
            return l1;
930
        }
25598 amit.gupta 931
 
31697 amit.gupta 932
        public List<String> getL2() {
933
            return l2;
934
        }
26945 amit.gupta 935
 
31697 amit.gupta 936
    }
26945 amit.gupta 937
 
31697 amit.gupta 938
    private class FofoReportingModel {
939
        private String code;
940
        private int fofoId;
941
        private String businessName;
942
        private String territoryManager;
943
        private String regionalManager;
944
        private String businessManager;
26945 amit.gupta 945
 
31697 amit.gupta 946
        public String getCode() {
947
            return code;
948
        }
26945 amit.gupta 949
 
31697 amit.gupta 950
        public void setCode(String code) {
951
            this.code = code;
952
        }
26945 amit.gupta 953
 
31697 amit.gupta 954
        public String getBusinessName() {
955
            return businessName;
956
        }
26945 amit.gupta 957
 
31697 amit.gupta 958
        public void setBusinessName(String businessName) {
959
            this.businessName = businessName;
960
        }
26945 amit.gupta 961
 
31697 amit.gupta 962
        public String getTerritoryManager() {
963
            return territoryManager;
964
        }
26945 amit.gupta 965
 
31697 amit.gupta 966
        public void setTerritoryManager(String territoryManager) {
967
            this.territoryManager = territoryManager;
968
        }
26945 amit.gupta 969
 
31697 amit.gupta 970
        public String getRegionalManager() {
971
            return regionalManager;
972
        }
26945 amit.gupta 973
 
31697 amit.gupta 974
        public void setRegionalManager(String regionalManager) {
975
            this.regionalManager = regionalManager;
976
        }
26945 amit.gupta 977
 
31697 amit.gupta 978
        private ScheduledTasks getOuterType() {
979
            return ScheduledTasks.this;
980
        }
26945 amit.gupta 981
 
31697 amit.gupta 982
        @Override
983
        public String toString() {
31886 tejbeer 984
            return "FofoReportingModel{" + "code='" + code + '\'' + ", fofoId=" + fofoId + ", businessName='" + businessName + '\'' + ", territoryManager='" + territoryManager + '\'' + ", regionalManager='" + regionalManager + '\'' + ", businessManager='" + businessManager + '\'' + '}';
31697 amit.gupta 985
        }
26945 amit.gupta 986
 
31697 amit.gupta 987
        @Override
988
        public boolean equals(Object o) {
989
            if (this == o) return true;
990
            if (o == null || getClass() != o.getClass()) return false;
991
            FofoReportingModel that = (FofoReportingModel) o;
992
            return fofoId == that.fofoId && Objects.equals(code, that.code) && Objects.equals(businessName, that.businessName) && Objects.equals(territoryManager, that.territoryManager) && Objects.equals(regionalManager, that.regionalManager) && Objects.equals(businessManager, that.businessManager);
993
        }
26945 amit.gupta 994
 
31697 amit.gupta 995
        @Override
996
        public int hashCode() {
997
            return Objects.hash(code, fofoId, businessName, territoryManager, regionalManager, businessManager);
998
        }
26945 amit.gupta 999
 
31697 amit.gupta 1000
        public String getBusinessManager() {
1001
            return businessManager;
1002
        }
26945 amit.gupta 1003
 
31697 amit.gupta 1004
        public void setBusinessManager(String businessManager) {
1005
            this.businessManager = businessManager;
1006
        }
25351 tejbeer 1007
 
31697 amit.gupta 1008
        public int getFofoId() {
1009
            return fofoId;
1010
        }
25598 amit.gupta 1011
 
31697 amit.gupta 1012
        public void setFofoId(int fofoId) {
1013
            this.fofoId = fofoId;
1014
        }
25598 amit.gupta 1015
 
31697 amit.gupta 1016
    }
26945 amit.gupta 1017
 
31697 amit.gupta 1018
    @Autowired
1019
    WarehouseInventoryItemRepository warehouseInventoryItemRepository;
26945 amit.gupta 1020
 
31746 amit.gupta 1021
    @Autowired
1022
    OfferService offerService;
1023
 
1024
    @Autowired
1025
    PurchaseReturnItemRepository purchaseReturnItemRepository;
1026
 
31918 amit.gupta 1027
    @Autowired
1028
    BrandRegionMappingRepository brandRegionMappingRepository;
1029
 
32161 tejbeer 1030
    @Autowired
1031
    StandAlone standAlone;
32214 jai.hind 1032
    @Autowired
1033
    ItelImeiActivationNewService itelImeiActivationNewService;
32350 amit.gupta 1034
 
1035
    public void checkItelImeiActivationNew(LocalDate date, Integer day) throws Exception {
32063 amit.gupta 1036
        try {
32223 amit.gupta 1037
            itelImeiActivationNewService.checkItelImeiActivationNew(date, day);
32063 amit.gupta 1038
        } catch (Throwable e) {
1039
            throw new Exception(e);
1040
        }
32223 amit.gupta 1041
    }
32062 amit.gupta 1042
 
32511 amit.gupta 1043
    @Autowired
1044
    PurchaseReturnService purchaseReturnService;
1045
 
32682 amit.gupta 1046
    @Autowired
1047
    JavaMailSender javaMailSender;
1048
 
32795 amit.gupta 1049
    @Autowired
1050
    OfferPayoutRepository offerPayoutRepository;
1051
 
1052
    @Autowired
1053
    OfferRepository offerRepository;
1054
 
32817 amit.gupta 1055
    @Autowired
1056
    BluedartAuthService bluedartAuthService;
1057
    @Autowired
1058
    BluedartService bluedartService;
1059
 
1060
    @Autowired
1061
    TransactionRelatedTasks transactionRelatedTasks;
1062
 
32872 amit.gupta 1063
    @Autowired
1064
    PsiSmartService psiSmartService;
32948 amit.gupta 1065
 
32961 amit.gupta 1066
    private void migrateValentine() throws ProfitMandiBusinessException {
1067
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.now().atStartOfDay(), LocalDateTime.now());
1068
        for (FofoOrder fofoOrder : fofoOrders) {
1069
            orderService.processScratchOffer(fofoOrder);
1070
        }
1071
    }
33051 amit.gupta 1072
 
32990 amit.gupta 1073
    @Autowired
1074
    InvoiceService invoiceService;
1075
 
33384 amit.gupta 1076
    @Autowired
1077
    WarehouseService warehouseService;
1078
 
33452 amit.gupta 1079
    @Autowired
1080
    GenericRepository genericRepository;
1081
 
1082
    @Autowired
1083
    PriceCircularService priceCircularService;
1084
 
34611 ranu 1085
    /*@Autowired
1086
    RedisCacheManager redisFortnightlyCacheManage;*/
33638 amit.gupta 1087
 
1088
    @Autowired
1089
    GstProAuthService gstProAuthService;
33664 amit.gupta 1090
 
33817 amit.gupta 1091
    @Autowired
1092
    GstProService gstProService;
1093
 
1094
    @Autowired
1095
    WarehouseProviderRepository warehouseProviderRepository;
33928 ranu 1096
 
34160 tejus.loha 1097
    @Autowired
1098
    LoiFormRepository loiFormRepository;
1099
    @Autowired
1100
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
1101
    @Autowired
1102
    StoreTimelineTatService storeTimelineTatService;
1103
    @Autowired
1104
    PartnerDealerRepository partnerDealerRepository;
33664 amit.gupta 1105
 
34275 tejus.loha 1106
    @Autowired
1107
    PurSaleService purSaleService;
1108
 
34502 amit.gupta 1109
    @Autowired
1110
    CatalogRepository catalogRepository;
1111
 
34510 amit.gupta 1112
    private void rolloutOppoPayout() throws Exception {
34504 amit.gupta 1113
        //List<Integer> schemeIds = Arrays.asList(5540, 5542, 5544,5918, 5919, 5920, 5921, 5922);
1114
        List<Integer> schemeIds = Arrays.asList(5540, 5542, 5544, 5545, 5550, 5555, 5556, 5557, 5564, 5565, 5566, 5567, 5569, 5570, 5582, 5590, 5592, 5593, 5594,
34502 amit.gupta 1115
                5595, 5598, 5602, 5604, 5605, 5606, 5607, 5608, 5611, 5618, 5620, 5621, 5622, 5623, 5624, 5625, 5626, 5629, 5631,
1116
                5633, 5634, 5635, 5637, 5644, 5649, 5655, 5659, 5662, 5668, 5672, 5674, 5679, 5683, 5684, 5685, 5688, 5689, 5690,
1117
                5692, 5694, 5697, 5699, 5700, 5706, 5718, 5729, 5730, 5754, 5756, 5758, 5759, 5761, 5762, 5766, 5769, 5771, 5772,
1118
                5773, 5774, 5775, 5776, 5781, 5782, 5783, 5786, 5788, 5790, 5795, 5800, 5803, 5804, 5807, 5809, 5815, 5816, 5819,
1119
                5820, 5821, 5822, 5823, 5824, 5825, 5826, 5827, 5828, 5829, 5830, 5832, 5833, 5834, 5835, 5836, 5837, 5839, 5840,
1120
                5841, 5842, 5843, 5844, 5845, 5846, 5847, 5848, 5849, 5850, 5851, 5852, 5853, 5854, 5855, 5857, 5859, 5860, 5863,
1121
                5864, 5866, 5869, 5870, 5871, 5872, 5873, 5874, 5875, 5877, 5878, 5879, 5880, 5885, 5888, 5889, 5891, 5892, 5894,
1122
                5899, 5901, 5903, 5905, 5908, 5910, 5913, 5916, 5917, 5918, 5919, 5920, 5921, 5922, 5923, 5924, 5925, 5926, 5927,
1123
                5928, 5929, 5930, 5931, 5932, 5933, 5934, 5935, 5936, 5938, 5939, 5940, 5941, 5942, 5943, 5944, 5945, 5946, 5947,
1124
                5948, 5949, 5950, 5951, 5952, 5953, 5954, 5955, 5956, 5957, 5958, 5959, 5960, 5961, 5962, 5963, 5964, 5965, 5966,
1125
                5967, 5968, 5969, 5970, 5971, 5972, 5973, 5974, 5975, 5976, 5977, 5979, 5980, 5981, 5982, 5983, 5984, 5985, 5986,
1126
                5987, 5989, 5990, 5991, 5992, 5996, 5997, 5998, 5999, 6000, 6001, 6002, 6003, 6004, 6005, 6006, 6007, 6008, 6010,
1127
                6011, 6012, 6013, 6014, 6015, 6016, 6017, 6018, 6019, 6020, 6021, 6022, 6023, 6024, 6025, 6026, 6028, 6029, 6030,
1128
                6031, 6032, 6033, 6034, 6035, 6036, 6037, 6038, 6039, 6040, 6041, 6042, 6043, 6044, 6045, 6046, 6047, 6048, 6049,
1129
                6050, 6051, 6052, 6053, 6054, 6055, 6056, 6057, 6058, 6059, 6060, 6061, 6062, 6063, 6064, 6065, 6066, 6067, 6068,
1130
                6069, 6070, 6071, 6072, 6073, 6078, 6079, 6080, 6081, 6082, 6083, 6084, 6085, 6086, 6087, 6088, 6089, 6091, 6092,
34504 amit.gupta 1131
                6093, 6094, 6095, 6098, 6102);
34502 amit.gupta 1132
        Map<Integer, List<SchemeInOut>> inventoryItemSiosMap = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIds)).stream().collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
1133
        Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryItemSiosMap.keySet()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1134
        Set<Integer> itemIds = itemRepository.selectAllByBrand("Oppo", 10006).stream().map(x -> x.getId()).collect(toSet());
1135
        List<InventoryItem> filteredInventoryItems = inventoryItemMap.values().stream().filter(x -> itemIds.contains(x.getItemId())).collect(Collectors.toList());
34510 amit.gupta 1136
 
1137
        Map<Integer, List<InventoryItem>> purchaseInventoryItemsMap = filteredInventoryItems.stream().filter(x -> x.getCreateTimestamp().isAfter(YearMonth.now().atDay(1).atStartOfDay())).collect(Collectors.groupingBy(x -> x.getPurchaseId()));
1138
        List<Purchase> purchases = purchaseRepository.selectAllByIds(new ArrayList<>(purchaseInventoryItemsMap.keySet()));
1139
        for (Purchase purchase : purchases) {
1140
            String invoiceNumber = purchase.getPurchaseReference();
1141
            LocalDateTime billingTime = orderRepository.selectByInvoiceNumber(invoiceNumber).get(0).getBillingTimestamp();
1142
            if (billingTime.isAfter(YearMonth.now().atDay(1).atStartOfDay())) {
1143
                schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
1144
            }
1145
        }
1146
 
34502 amit.gupta 1147
        for (InventoryItem filteredInventoryItem : filteredInventoryItems) {
34504 amit.gupta 1148
            //System.out.println("Serial Number is - " + filteredInventoryItem.getSerialNumber());
34502 amit.gupta 1149
            List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(filteredInventoryItem.getId());
1150
            ScanRecord scanRecord = scanRecords.stream().filter(x -> x.getType().equals(ScanType.SALE)).findFirst().orElse(null);
1151
            if (scanRecord == null) {
1152
                continue;
1153
            }
34510 amit.gupta 1154
            schemeService.processSchemeOut(scanRecord.getOrderId(), scanRecord.getFofoId());
34502 amit.gupta 1155
        }
1156
    }
1157
 
35021 amit 1158
    @Autowired
1159
    AbmReportSender abmReportSender;
34510 amit.gupta 1160
 
35021 amit 1161
    public void sendOverDueReport() {
1162
        List<Loan> loans = loanRepository.selectAllActiveLoan();
35521 amit 1163
        Map<Integer, List<Loan>> partnerLoansMap = loans.stream().filter(x -> x.isOverdue()).collect(Collectors.groupingBy(x -> x.getFofoId()));
35021 amit 1164
        //sdCreditService.getDueDateCrossLoan()
35521 amit 1165
        partnerLoansMap.entrySet().stream().forEach(x -> {
34858 amit 1166
 
35021 amit 1167
            x.getKey();
1168
            x.getValue().size();
1169
        });
34858 amit 1170
 
35021 amit 1171
    }
1172
 
35295 amit 1173
    @Autowired
1174
    OnBoardingRelatedSchelduleTask onBoardingRelatedSchelduleTask;
1175
 
1176
    @Autowired
1177
    Migrations migrations;
1178
 
1179
    /*@Autowired
1180
    BenowService benowService;*/
1181
 
1182
    @Autowired
1183
    TrialFormRepository trialFormRepository;
1184
 
1185
    @Autowired
1186
    CreditBlockedExceptionPartnersRepository creditBlockedExceptionPartnersRepository;
1187
 
1188
    @Autowired
1189
    SDCreditService sdCreditService;
1190
 
35393 amit 1191
    @Autowired
1192
    com.spice.profitmandi.service.integrations.pinelabs.PinelabsAffordabilityService pinelabsAffordabilityService;
1193
 
1194
    @Autowired
1195
    com.spice.profitmandi.service.integrations.pinelabs.PinelabsAuthService pinelabsAuthService;
35521 amit 1196
 
35393 amit 1197
    public void testAffordability() {
1198
        Money orderAmount = new Money("1000000", "INR");
1199
        Money discountAmount = new Money("0", "INR");
1200
        List<ProductDetails> productDetails = Arrays.asList(new ProductDetails(orderAmount, discountAmount, "Alpha_2"));
1201
        OfferDiscoveryRequest offerDiscoveryRequest = new com.spice.profitmandi.service.integrations.pinelabs.dto.OfferDiscoveryRequest(orderAmount, productDetails, new AffordabilityIssuer("12345678"));
1202
        OfferDiscoveryResponse offerDiscoveryResponse = pinelabsAffordabilityService.discoverOffers(offerDiscoveryRequest);
1203
        System.out.println(offerDiscoveryResponse);
1204
    }
35521 amit 1205
 
35021 amit 1206
    public void test() throws Exception {
35393 amit 1207
 
1208
        System.out.println(pinelabsAuthService.getAccessToken());
1209
        testAffordability();
1210
 
35295 amit 1211
        //System.out.println(trialFormRepository.selectByEmailOrMobile("9990381568"));
1212
        /*CreditBlockedExceptionPartner creditBlockedExceptionPartner = creditBlockedExceptionPartnersRepository.select(175139430);
1213
        System.out.println(creditBlockedExceptionPartner);*/
35330 amit 1214
        //this.updatePartnerLimit(175139595);
35393 amit 1215
        //this.releaseBlockedLimit();
35326 amit 1216
        //sdCreditService.resetHardLimit();
35295 amit 1217
        //migrations.migrateSerialInvoiceMap();
35151 amit 1218
        //runOnceTasks.checkRewardsEligibility();
35295 amit 1219
        //hybridEncryptor.getJwt();
1220
        /*System.out.printf("Date|Transaction Id|Serial Number|Sale Amount|Swipe Payout|Discount Payout%n");
1221
        for(int i=0;i<10;i++){
1222
            benowService.parseBenowTransaction(LocalDate.now().minusDays(i));
1223
        }*/
1224
        //onBoardingRelatedSchelduleTask.onboardingEventDelays();
35177 amit 1225
        //runOnceTasks.migrateLimit();866009067657118
1226
        //TODO -- Sales Return Pending
1227
        //runOnceTasks.moveSaleReturnScanToDoa("866009067657118");
35295 amit 1228
        //runOnceTasks.sendCreditExposureReport();
35177 amit 1229
        //runOnceTasks.moveDoaScanToSaleReturn("868770072438608");
35150 vikas 1230
        //runOnceTasks.purchasePolicy();
35105 vikas 1231
        //purSaleService.moreThen10DaysEgedStockReport();
35102 amit 1232
        //System.out.println(schemeService.testRedis(1, 2L));
1233
        //System.out.println(schemeService.testRedis(1, null));
35177 amit 1234
        // abmReportSender.sendAbmSmartCartReport();
1235
        //this.sendOverDueReport();
35053 amit 1236
        /*List<Integer> orderIds = Arrays.asList(1929879,1932372,1932377,1932386,1932396,1935221,1935563,1935564,1945144,1955256,1955271,1955294,1961255,1961256,1972821,1972823,1972824,1972825,1972826,1974250,1974252,1974253,1974254,1974255,1974256,1974242,1974244,1974245,1974246,1974247,1974248,1976610,1978095,1978136,1978130,1978174,1978156,1978158,1978167,1978169,1978160,1978179,1978175,1978180,1978201,1978200,1978202,1978192,1978198,1978207,1978204,1978457,1979781,1979783,1979784,1979787,1982412,1982413,1986531,1986532,1986533,1991006,1991628,1991629,2016001,2018921,2042948,2047031,2058500,2058522,2058519,2058520,2058546,2058559,2058568,2058575,2058574,2058598,2058594,2058618,2058633,2066491,2067110,2067113,2067118,2067120,2067123,2067132,2067125,2067127,2069974,2069970,2069976,2069985,2069987);
35021 amit 1237
        for (Integer orderId : orderIds) {
1238
            System.out.println("Refund Started - " + orderId);
1239
            orderRepository.refundOrder(orderId, "vinay.p", "Long awaited cancellation", OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY);
1240
            System.out.println("Refund Ended");
35053 amit 1241
        }*/
1242
        //System.out.println(warehouseSupplierInvoiceRepository.selectWarehouseItemAgeing(LocalDateTime.now().minusDays(10), LocalDateTime.now(), null, 0, null));
35102 amit 1243
        /*Offer offer = offerRepository.selectById(6820);
1244
        offerService.sendWhatsapp(offer, Arrays.asList(175140233),"https://images.smartdukaan.com/uploads/campaigns/image2025-09-24/offer-6820.png");*/
1245
        /*List<String> invoices = Arrays.asList("NSDLNOI16527","NSDLNOI16366", "NSDLNOI16394", "NSDLNOI16460");
35056 amit 1246
        List<Loan> loans = new ArrayList<>();
1247
        for (String invoice : invoices) {
1248
            loans.add(loanRepository.selectLoanByInvoice(invoice));
1249
        }
1250
        loans.stream().sorted(Comparator.comparing(x->x.getCreatedOn())).forEach(x-> {
1251
            try {
1252
                sdCreditService.settleLoan(x);
1253
            } catch (ProfitMandiBusinessException e) {
1254
                throw new RuntimeException(e);
1255
            }
35102 amit 1256
        });*/
35021 amit 1257
        //Utils.sendMailWithAttachments(googleMailSender, new String[]{"amit.gupta@smartdukaan.com"}, null, "DTDC AWb", "PFA");*/
33452 amit.gupta 1258
    }
1259
 
35330 amit 1260
    private void releaseBlockedLimit() throws ProfitMandiBusinessException {
1261
        List<Loan> blockedLoans = loanRepository.selectAllBlockedLoans();
1262
        for (Loan blockedLoan : blockedLoans) {
1263
            LoanTransaction loanTransaction = loanTransactionRepository.selectByLoanId(blockedLoan.getId());
1264
            int transactionId = loanTransaction.getTransactionId();
1265
            List<UserWalletHistory> userWalletHistory = walletService.getAllByReference(blockedLoan.getFofoId(), transactionId, WalletReferenceType.PURCHASE);
35521 amit 1266
            int amount = userWalletHistory.get(userWalletHistory.size() - 1).getAmount();
35330 amit 1267
            int loanAmount = blockedLoan.getIntialAmount().intValue();
35521 amit 1268
            if (loanAmount > -amount) {
1269
                sdCreditService.settleBlockedLoan(transactionId, loanAmount + amount);
35330 amit 1270
            }
1271
 
1272
 
1273
        }
1274
    }
1275
 
34731 amit.gupta 1276
    @Autowired
1277
    LoanTransactionRepository loanTransactionRepository;
1278
 
1279
    private void fixBlockedCredit() throws ProfitMandiBusinessException {
1280
        List<Loan> unsettledBlockedLoans = loanRepository.selectAllActiveLoan().stream().filter(x -> x.getFreeDays() >= 365).collect(toList());
1281
        //unsettledBlockedLoans = unsettledBlockedLoans.stream().filter(x -> x.getId() == 52310).collect(toList());
1282
        for (Loan unsettledBlockedLoan : unsettledBlockedLoans) {
1283
            LoanTransaction loanTransaction = loanTransactionRepository.selectByLoanId(unsettledBlockedLoan.getId());
1284
            if (loanTransaction == null) {
1285
                System.out.println("Cant find Transaction Id for Loan - " + unsettledBlockedLoan.getId() + "-- Created On ->" + unsettledBlockedLoan.getCreatedOn());
1286
                continue;
1287
            }
1288
            List<Order> processedOrders = orderRepository.selectAllByTransactionId(loanTransaction.getTransactionId()).stream()
1289
                    .filter(x -> !x.getStatus().equals(OrderStatus.SUBMITTED_FOR_PROCESSING)).collect(toList());
1290
            List<OrderStatus> processedOrderIds = processedOrders.stream().map(x -> x.getStatus()).collect(Collectors.toList());
1291
            System.out.println("processedOrderIds " + processedOrderIds);
1292
            //if(unsettledBlockedLoan !=null) continue;
1293
            double limitToRelease = processedOrders.stream().collect(Collectors.summingDouble(x -> x.getWalletAmount()));
1294
            sdCreditService.releaseBlockedLimit(unsettledBlockedLoan, limitToRelease);
1295
 
1296
 
1297
        }
1298
    }
1299
 
34710 amit.gupta 1300
    public static byte[] toByteArray(InputStream input) throws IOException {
1301
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1302
        int nRead;
1303
        byte[] data = new byte[16384];
1304
        while ((nRead = input.read(data, 0, data.length)) != -1) {
1305
            buffer.write(data, 0, nRead);
1306
        }
1307
        return buffer.toByteArray();
1308
    }
1309
 
34547 vikas.jang 1310
    private void whatsappTest() throws Exception {
34603 ranu 1311
        //liquidationService.processBids(ProfitMandiConstants.BID_CRON_ENUM.TODAY);
34612 ranu 1312
        Utils.sendMailWithAttachments(googleMailSender, new String[]{"ranu.rajput@smartdukaan.com"}, null, "Test Mail", "Mail is working");
34532 amit.gupta 1313
    }
1314
 
34510 amit.gupta 1315
    private void debitLoanAmountFromWallet() {
1316
        List l1 = Arrays.asList(1234, 1420, 2694, 8129, 12182, 12880, 16289, 16462, 16551, 16625, 16819, 17606, 18902, 19152, 19663, 22409, 22410, 23924, 24058, 24206, 24215, 24220, 24459, 25977, 30585, 31590);
1317
        l1.addAll(Arrays.asList(11849, 12702, 14554, 14643, 19166, 19638, 32824, 33467, 33954, 34017, 34514, 35128, 35229, 35355, 36007, 36351, 36435, 36586, 36608, 36612, 36665, 37076, 37495, 37678, 38519, 38563, 38638, 38690, 38815, 38840, 39015, 39084, 39142, 39379, 39384, 39586, 39636, 39657, 39755, 39788, 39908, 40054, 40220, 40534, 41731, 41962, 42692));
1318
        l1.addAll(Arrays.asList());
1319
    }
1320
 
33452 amit.gupta 1321
    public void test4() throws Exception {
1322
        List<Integer> offerIds = Arrays.asList(2882, 2881, 2880, 2879, 2878, 2877, 2876, 2875, 2874, 2873, 2872, 2871, 2870, 2869, 2868, 2867, 2866, 2865, 2864, 2863, 2862, 2861, 2860, 2859, 2858, 2857, 2856, 2855, 2854, 2853, 2852, 2851, 2850, 2849, 2847, 2846, 2845, 2844, 2843, 2842, 2841, 2840, 2839, 2838, 2837, 2836, 2835, 2834, 2833, 2832, 2831, 2830, 2829, 2828, 2827, 2826, 2825, 2824, 2823, 2822, 2821, 2820, 2819, 2818, 2817, 2816, 2815, 2814, 2813, 2812, 2811, 2810, 2809, 2808, 2807, 2806, 2805, 2804, 2803, 2802, 2801, 2800, 2799, 2798, 2797, 2796, 2795, 2794, 2793, 2792, 2791, 2790, 2789, 2788, 2787, 2786, 2785, 2784, 2783, 2782, 2781, 2780, 2777, 2776, 2775, 2774, 2773, 2772, 2771, 2770, 2769, 2768, 2767, 2766, 2765, 2764, 2763, 2762, 2761, 2760, 2759, 2758, 2757, 2756, 2755, 2754, 2753, 2752, 2751, 2750, 2749, 2748, 2747, 2746, 2745, 2744, 2723, 2722, 2721, 2720, 2719, 2718, 2717, 2716, 2715, 2714, 2713, 2712, 2711, 2710, 2709, 2708, 2707, 2706, 2705, 2704, 2703, 2702, 2701, 2700, 2699, 2698, 2697, 2696, 2695, 2694, 2693, 2692, 2691, 2690, 2494, 2493, 2492, 2491, 2490, 2489, 2488, 2487, 2486, 2485, 2484, 2483, 2482, 2481, 2480, 2479, 2478, 2477, 2476, 2475, 2474, 2473, 2472, 2471, 2470, 2469, 2466, 2465, 2464, 2463, 2462, 2461, 2460, 2459, 2458, 2457, 2456, 2455, 2454, 2453, 2452, 2451, 2450, 2449, 2448, 2447, 2446, 2445, 2444, 2443, 2442, 2441, 2440, 2439, 2407, 2406, 2405, 2404, 2403, 2402, 2401, 2400, 2399, 2398, 2397, 2396, 2395, 2394, 2393, 2392, 2391, 2390, 2389, 2388, 2387, 2386, 2385, 2384, 2383, 2382, 2381, 2117, 2116, 2115, 2114, 2113, 2112, 2111, 2110, 2109, 2108, 2107, 2106, 2105, 2104, 2103, 2102, 2101, 2100, 2099, 2098, 2077);
1323
        for (Integer offerId : offerIds) {
1324
            Offer fromOffer = offerRepository.selectById(offerId);
1325
            CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(fromOffer);
1326
            System.out.println("Processing offer Id " + fromOffer);
1327
            offerService.processActivationtOffer(createOfferRequest);
1328
        }
34160 tejus.loha 1329
 
33433 amit.gupta 1330
        this.processSidbiDeductions();
32817 amit.gupta 1331
    }
1332
 
1333
    public void test3() throws Exception {
1334
        List<Long> payoutIds = Arrays.asList();
32795 amit.gupta 1335
        List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllByIds(payoutIds);
33452 amit.gupta 1336
        Map<Integer, List<OfferPayout>> offerPayoutMap = offerPayouts.stream().collect(groupingBy(x -> (int) x.getOfferId()));
1337
        for (Entry<Integer, List<OfferPayout>> offerPayoutEntry : offerPayoutMap.entrySet()) {
32795 amit.gupta 1338
            int offerId = offerPayoutEntry.getKey();
1339
            List<OfferPayout> offerPayoutList = offerPayoutEntry.getValue();
33452 amit.gupta 1340
            Map<Integer, List<OfferPayout>> partnerOfferPayoutMap = offerPayoutList.stream().collect(groupingBy(x -> (int) x.getFofoId()));
32795 amit.gupta 1341
            for (Entry<Integer, List<OfferPayout>> partnerOfferPayoutEntry : partnerOfferPayoutMap.entrySet()) {
1342
                int fofoId = partnerOfferPayoutEntry.getKey();
1343
                List<OfferPayout> partnerPayouts = partnerOfferPayoutEntry.getValue();
1344
                float amount = 0;
1345
                for (OfferPayout offerPayout : partnerPayouts) {
1346
                    amount += offerPayout.getAmount();
1347
                    offerPayout.setStatus(SchemePayoutStatus.REJECTED);
1348
                    offerPayout.setRejectTimestamp(LocalDateTime.now());
1349
                }
1350
                walletService.rollbackAmountFromWallet(fofoId, amount, offerId,
1351
                        WalletReferenceType.ADDITIONAL_SCHEME, "Imeis returned - " + partnerPayouts.size() + "pc(s)", LocalDateTime.now());
1352
            }
1353
        }
1354
    }
1355
 
33316 amit.gupta 1356
    public void test1() throws Exception {
32690 amit.gupta 1357
        System.out.println("Hello from test");
32724 amit.gupta 1358
        //this.calculateInterestAccured();
32690 amit.gupta 1359
        //sendMailOfHtmlFormat(javaMailSender, new String[]{"amit.gupta@smartdukaan.com"}, "hello", null, "Hello");
32698 amit.gupta 1360
        //priceDropService.rejectPriceDropsOfApprovedImeis();
32511 amit.gupta 1361
        //Create return
32600 amit.gupta 1362
        //this.updatePartnerLimit();
32607 ranu 1363
        //creditNoteService.sendCnMails(YearMonth.now().minusMonths(2));
32690 amit.gupta 1364
        //orderService.createMissingScratchOffers();
33315 amit.gupta 1365
        LocalDateTime debitNoteDate = LocalDate.of(2024, Month.APRIL, 30).atStartOfDay();
32698 amit.gupta 1366
        Map<Integer, Set<String>> fofoIdImeiReturnMap = new LinkedHashMap<>();
33355 amit.gupta 1367
        /*fofoIdImeiReturnMap.put(175139690,	new HashSet<>(Arrays.asList("862054078463472","863862077158219","866202075810858","866202077654494","866335072023651","866518078002718")));
33315 amit.gupta 1368
        fofoIdImeiReturnMap.put(175139414,	new HashSet<>(Arrays.asList("356494471684303","356494471857164","356494472062590","861753065078075","863511068904178","863511069732933","864179068109203","864179068112504","864259078789978","866202076254130","866202076254775","866657078259165","866657078272846","867492065809718","867907071107955","868565073021423","868565073022223","868565073386347")));
1369
        fofoIdImeiReturnMap.put(175139603,	new HashSet<>(Arrays.asList("350886063151961","356412387787135","357594162824701","357594162874771","860600078193972","863862077025350","863862077875796","863967075815072","866335073794995","866335074287874","869116067546048")));
1370
        fofoIdImeiReturnMap.put(175139657,	new HashSet<>(Arrays.asList("350933415734746","354324787135850","354324788766356","354990352512960","354990352580181","358142881241184","866611064207332","869116067600464")));
1371
        fofoIdImeiReturnMap.put(175139223,	new HashSet<>(Arrays.asList("350210770983048","350210771169027","350210771179844","350210771180784","863975067090596","866611060326797","868565075758196","869452074016992","869452074609515","869452074609556","869452074976674","869452074978654")));
1372
        fofoIdImeiReturnMap.put(175139557,	new HashSet<>(Arrays.asList("861977073551795","861977073552678","861977074486819","862046062571245","862046067278226","862046067734921","862046067756866","864468070394741","864468071225506","864468071668341","864468073604740","864468074854625","866993074734475")));
1373
        fofoIdImeiReturnMap.put(175139079,	new HashSet<>(Arrays.asList("862046068861921","862282079169299","865388071283496","866335072007753","866335073946256","866518073601712","866518077425993","866518078760471","868938062675394","868938062690799","868938064895552")));
1374
        fofoIdImeiReturnMap.put(175139711,	new HashSet<>(Arrays.asList("861753065266498","861888066009099","864468073703369","866993071640154","869116062800465")));
1375
        fofoIdImeiReturnMap.put(175139488,	new HashSet<>(Arrays.asList("862054076866114","862054076866650","866335071879079","866335077875998","866335077876095","866518078758939","868938062692878")));
1376
        fofoIdImeiReturnMap.put(175138934,	new HashSet<>(Arrays.asList("862054072810231","862054072823150","862054076867674","862054078659590","863862075768456","863862077158193","863975064472490","863975064473233","865388071160033","865610079408035","866335072117370","866335073899471","866335074306153","866335075664477","868938062669876","868938062677895","868938062685997")));
1377
        fofoIdImeiReturnMap.put(4149607	 ,   new HashSet<>(Arrays.asList("864468073415741","864468075548523","864468075549927","864468079499426","866657074106022","868938062686656","868938062696978","868938062699352","868938064895198","868938066363799")));
1378
        fofoIdImeiReturnMap.put(175139138,	new HashSet<>(Arrays.asList("862286066217631","864259076533691","864468073358842","864487061610014","864487061675918","866083066080028","866518078760950","866518078768979","866657075343848","868544061108518","868544061138432","869116065510848","869116065519781","869452074116891","869452074972939")));
1379
        fofoIdImeiReturnMap.put(175139608,	new HashSet<>(Arrays.asList("350201087552063","350201087559944","350201087635660","350201087649760","350201087843140","350201088470224","350201088696687","350201088697180","354324783756923","354324786101366","355472822024008","355472822025625","860388068055779","860388068262219","866518078762337","866518078767534","868544061141493","868544061141774","868544061141816","868938064895719","868938066360910")));
1380
        fofoIdImeiReturnMap.put(175139731,	new HashSet<>(Arrays.asList("860600079214413","861753063502217","861753065084172","861753065084636","863975064472094","863975064473076","863975064477218","864468074456462","865883068726994","866657074641481","866657078016946","868938062699832","868938062700754")));
1381
        fofoIdImeiReturnMap.put(175138958,	new HashSet<>(Arrays.asList("863862075766393","864179064784108","866202075811732","866202076252654","866202078005571","868544060277439")));
1382
        fofoIdImeiReturnMap.put(175139612,	new HashSet<>(Arrays.asList("864468073474946","864468073477808","864468075031082","864468075280689","864468075745723","864468079481747","864468079483123","866657074538125","866657074538141","866657074573106","867467071856465","867467071875465","867467071891223","867467071913845","867467072729125","867467072760088")));
1383
        fofoIdImeiReturnMap.put(175139479,	new HashSet<>(Arrays.asList("863975062106595","863975064472672","863975064472870","863975064472953","863975064482333","863975064483570","863975064484719","863975064662694","863975064666455","863975064668931","863975067090257","863975067090810","863975067230218","863975067232230","866186062852892","866186062853973","866186062855051","866186062855077","866186063250773","866186063251094","866186063251219","866186063251318")));
1384
        fofoIdImeiReturnMap.put(175139245,	new HashSet<>(Arrays.asList("354324787133962","354324787569397","354324787602750","863816078139719","863816078448318","866335070534139")));
1385
        fofoIdImeiReturnMap.put(175139324,	new HashSet<>(Arrays.asList("863718060410316","863862075060755","865610074109257","866518078844457","866518079735159")));
1386
        fofoIdImeiReturnMap.put(175139576,	new HashSet<>(Arrays.asList("354324789013261","861128071288044","862736064686138","863718062236859","863816074642674","863816074646691","864259078939631","867467071870367","867467072760625","868565073047048")));
1387
        fofoIdImeiReturnMap.put(175139150,	new HashSet<>(Arrays.asList("860492060436217","861977073052257","862054073026738","862054073052056","863862077158938","866993074147710","867907071407074","868938060257450","868956064835055")));
1388
        fofoIdImeiReturnMap.put(175139463,	new HashSet<>(Arrays.asList("862181066909552","863816077757719","863816078448516","864214068977273","866335070447936","866335071699212","866335071699592","866335071700291")));
1389
        fofoIdImeiReturnMap.put(175139722,	new HashSet<>(Arrays.asList("358250293364682","358250294683627","358250295102007","861858064421273","861888066009537","864214068983198","864259078491112","864259078787733","865883068445694","866335072878930","866518078371014","868492068014968","868565072254660","868565073401468","868565073465661")));
1390
        fofoIdImeiReturnMap.put(168311083,	new HashSet<>(Arrays.asList("863718064506176","864468070873488","865883068175572","866335071204435","866335072093738","866518077064313","866657077386209","866657077862282","868938061427359")));
1391
        fofoIdImeiReturnMap.put(175139691,	new HashSet<>(Arrays.asList("863718061338714","863718061339258")));
1392
        fofoIdImeiReturnMap.put(175139395,	new HashSet<>(Arrays.asList("860492060436910","861220079009850","862054077288730","863511068660374","863718060300574","863718060617936","866335072874111","869452070894897")));
1393
        fofoIdImeiReturnMap.put(175139621,	new HashSet<>(Arrays.asList("351240553452191","351240553483527","351240553502920","354990353485570","860492062979750","860492062980998","864214068585274","864214068784398","864214068795378","864214068946534","864214068946757","864214068982075","868938061418754","868938061427391","868938062623139")));
1394
        fofoIdImeiReturnMap.put(175139638,	new HashSet<>(Arrays.asList("863862077159191","866518078780438","866518079750471","868428060238049","868938061532836","868938062619517")));
1395
        fofoIdImeiReturnMap.put(175139313,	new HashSet<>(Arrays.asList("350837023070346","350837023075022","350837023075568","350837023075782","352256988699643","862054076944275","863862075060359","863862075520055","864468075575948","865388072943635","868938060248574","868938061422830","868938062630894","869116061122184","869452070893717","869452073157912","869452074054373","869452075220890")));
1396
        fofoIdImeiReturnMap.put(175139513,	new HashSet<>(Arrays.asList("861977073670355","863718060618439","864468075204986","868024064295935","868024065473754","868024065567811","868024065763972","868956063947893")));
1397
        fofoIdImeiReturnMap.put(175139524,	new HashSet<>(Arrays.asList("350933416006946","350933416007944","351115165469199","351115165471237","351115167775437","351115167778431","351115167784413","351688420101625","355300592141142","358250295005267","358250295284607","359197386833520","359197386864947","862054073974671","862054073979597","862054074261730","862054074425954","862054074426036","864468073609384","866518078777392","868544060023239","868938060253772","868938060258516","868938061419018")));
1398
        fofoIdImeiReturnMap.put(175139359,	new HashSet<>(Arrays.asList("358250293060942","358250293061387","863718063044252","863862077160991","866335072536793","866335072536975","866335072537130","866335072726691","866335072726733","866335073628532","866335073925250","866335073925292","866335073926233","866335075267156")));
1399
        fofoIdImeiReturnMap.put(175139397,	new HashSet<>(Arrays.asList("861977073659010","863511069721050","864468071611101","864468074432844","864468074435284")));
1400
        fofoIdImeiReturnMap.put(175139677,	new HashSet<>(Arrays.asList("351115165472839","351115165476095","351115165476251","351115165477739","351115165483430","351115165485377","351115165486516","351115165487191","351115166897992","351115166898438","351115166900416","351115166900879","351115166902438","351115166903816","351115166903857","351115166903915","351115166904475","351115166905753","351115166906454","351115166906595","351115166907015","351115166907759","351115166907957","351115166908872","351115166909813","864259078771372","864468075692644","864468079730101","864468079736744","866657076858687","868565073398649","869116061118042","869116061261081")));
1401
        fofoIdImeiReturnMap.put(175139460,	new HashSet<>(Arrays.asList("860492061918494","862054079983072","862054079983171","866335070533032","866518078995119","866518079014993","868938060095017")));
1402
        fofoIdImeiReturnMap.put(175139585,	new HashSet<>(Arrays.asList("358250293614706","358250293614904","358250294602908","358250294603120","358250295002181","861977074487718","863718061173699","863816078050254","865883068445777","866335070453439","866335070526812","866335071204351","866518078640293","869116067596803")));
1403
        fofoIdImeiReturnMap.put(175139726,	new HashSet<>(Arrays.asList("861858064489411","863718063927654","864468073702221","864468073928784","864468074193149","865883068445819","866657078378742","866657078498904","867949078179850","867949078180494","868544060023197")));
1404
        fofoIdImeiReturnMap.put(175139532,	new HashSet<>(Arrays.asList("863718060615096","863718060615617","863718060727537","863816077797897","866335073405139","868565072217287","868565072264560","868956065132510")));
1405
        fofoIdImeiReturnMap.put(175139462,	new HashSet<>(Arrays.asList("865610074119819","865610074120536","866335072878658","866335072882098","866335073617030")));
1406
        fofoIdImeiReturnMap.put(175139259,	new HashSet<>(Arrays.asList("350210771180644","355300593052348","860492061918213","861858064422651","864259078402572","864259078924310","866335070769719","866335071700556","866335071742558","866657073553208","867949078178530","867949078692472","868024065518616","868024065619091","869116067492540")));
1407
        fofoIdImeiReturnMap.put(175139344,	new HashSet<>(Arrays.asList("350115571135781","354990352587723","358250293362843","358250293363148","862736064732510","865610070849617","865610070851290","866518078899998","868938062623378","868956065234613")));
1408
        fofoIdImeiReturnMap.put(175139602,	new HashSet<>(Arrays.asList("861128070090482","868565072242160","868565072243044","868565072261004","868565073051644")));
1409
        fofoIdImeiReturnMap.put(175139605,	new HashSet<>(Arrays.asList("861515075217922","861515076369466","863816074206397","863816075080072","864259078661755","864468075627368","867467071860541","868565072177903","868565073075726","868565073401625","868938060248012","868938066709652","869452074088611","869452074609234")));
1410
        fofoIdImeiReturnMap.put(175139640,	new HashSet<>(Arrays.asList("358250293363429","358250293363684","861753065277792","863511069733998","864214068943713","864259078496574","864259078518773","864487060042870","864487060050352","865883069366170","866518079782391","867949078692639","867949078692852","868273068551617","868938066464571","869452073150115")));
1411
        fofoIdImeiReturnMap.put(175139346,	new HashSet<>(Arrays.asList("356494471614953","860600076022215","861765072074616","861977070097412","864468074885181","864468076046105","865610073263139","865883065558994","866335075002538","866657079093605","867907070983216")));
1412
        fofoIdImeiReturnMap.put(175139489,	new HashSet<>(Arrays.asList("354324789015209","354324789081797","861515075189824","861515075575501","861977070268997","864468072790144","864468072983921","864468075233225","866657077951960","869452071082492","869452071982378","869452074617070")));
1413
        fofoIdImeiReturnMap.put(175139508,	new HashSet<>(Arrays.asList("861515075367024","864468072781283","864468074453386","864468075200448","864468076050669","866083062293849")));
1414
        fofoIdImeiReturnMap.put(175139716,	new HashSet<>(Arrays.asList("350832440575209","358250295571425","860600076019492","861753063494373","861753063501151","864468073696100","864468074855689","865883065542311","865883067956030","866202075825450","866202077663297","866335073632591","866657078023769")));
1415
        fofoIdImeiReturnMap.put(175139727,	new HashSet<>(Arrays.asList("355300592353325","355300593005387","861765072344258","862046060196128","864468073908604","864468073910121","864468073911269","867437074118411","868024064300099","868024065464977","868024065468218","869116065414389")));
1416
        fofoIdImeiReturnMap.put(175139521,	new HashSet<>(Arrays.asList("860600071402594","860600071416719","861888064397496","861977073658616","864468070509587","864468073866406","866335074999056","866657077949642","866657078406964","866993072229072","867437070891698")));
1417
        fofoIdImeiReturnMap.put(175139523,	new HashSet<>(Arrays.asList("354324785409950","354324788632830","354990352587939","358250295736085","358250295805187","358311601935629","863967076359575","866657074163502","867907070986318","869452071963378","869452074611750")));
1418
        fofoIdImeiReturnMap.put(175139697,	new HashSet<>(Arrays.asList("862282078030112","862282078867117","863975067709930","863975068443810","864468072828860","864468073705786","864468075276489","864468075277685","865610073830739","866335073264577","866518079802116","866657074518903","866657077949980","868565073058664","868938060985639","869116065613949")));
1419
        fofoIdImeiReturnMap.put(175139622,	new HashSet<>(Arrays.asList("358250293381926","358250293382304","358250293382601","358250294076046","358250294078109","358250294078463","358250294602064","358250294602429","358250294603062","358250294603203")));
1420
        fofoIdImeiReturnMap.put(175139699,	new HashSet<>(Arrays.asList("863718064441317","865610074942897","866202077653173","866202077653553","866335072262671","866335073632211","866335074805519")));
1421
        fofoIdImeiReturnMap.put(175139741,	new HashSet<>(Arrays.asList("861515071386101","861515074123402","861515074124186","861977073047752","861977073658574","864468075082804","864468076049869","865883065542139","865883067957111","866518070599679","866518079800672","866657078018587","866657078270162","866657079236220")));
1422
        fofoIdImeiReturnMap.put(175139114,	new HashSet<>(Arrays.asList("861888066708856","861977074487692","866335070051217","866335070517274","866993074145631")));
1423
        fofoIdImeiReturnMap.put(175139531,	new HashSet<>(Arrays.asList("863816077976194","863816079685710","866335070997336","866335074729354","866335075514698")));
1424
        fofoIdImeiReturnMap.put(175139386,	new HashSet<>(Arrays.asList("350210771192805","358250295053846","860388068563434","863862077333374","864468075193221","864562077193757","864718076084310","866202077464092","866202077742190","866518077001513","868565079682020","868956065252516")));
1425
        fofoIdImeiReturnMap.put(175139452,	new HashSet<>(Arrays.asList("350835033581484","350835034344999","350835035973283","350886063052599","351115165490559","351115165492290","351115165492811","354324788947428","354996630411503","354996631256261","355480685142494","355480686969416","359197386860549","861977073020494","862046067791525","862054077982977","866335072889499","867467072712048","868938062127511")));
1426
        fofoIdImeiReturnMap.put(175139306,	new HashSet<>(Arrays.asList("863718064547394","864718076075516","864718076083478","866202077463631","866202077470057")));
1427
        fofoIdImeiReturnMap.put(175139733,	new HashSet<>(Arrays.asList("350210771180008","861515071845668","861888067164877","866335070489094","866518076378276","868565072242269")));
1428
        fofoIdImeiReturnMap.put(175138824,	new HashSet<>(Arrays.asList("862054078573478","863862074697490","863862075442375","864468074485545","866335070216315","866657078016169","866657078449402","869116065542247")));
1429
        fofoIdImeiReturnMap.put(175139511,	new HashSet<>(Arrays.asList("862054075642557","862054075643530","862054076379357","862054077978934","863816078158016","868938062108974")));
1430
        fofoIdImeiReturnMap.put(175139701,	new HashSet<>(Arrays.asList("863862078258331","866611061131790")));
1431
        fofoIdImeiReturnMap.put(175139552,	new HashSet<>(Arrays.asList("861753065084958","866202075814439","866202075825633","866202075864194","866202076138754","866202076252811","866202077646870","866202077651094","866202077653876","866202077659956","866202077660293","866202077663339","866202078006397","866202078006611","866202078008914","866657078023280")));
1432
        fofoIdImeiReturnMap.put(175139499,	new HashSet<>(Arrays.asList("351115165467359","351115166905951","355358277809813","355358277814052","356049795822532","358250290682060","863862075504950","864468073944906","864468076048721","866657079234365")));
1433
        fofoIdImeiReturnMap.put(175139630,	new HashSet<>(Arrays.asList("357349229650288","358250290499184","358250294552947","358250294590301","860946078570556","860946078571059","861977073552215","861977073657790","861977073657832","861977073658731","861977074660850","862054075627517","862054075632756","862054075642979","862054076374879","863967071220830")));
1434
        fofoIdImeiReturnMap.put(175139720,	new HashSet<>(Arrays.asList("865388072300075","866335073071691","866335073073697","866335073390398")));
1435
        fofoIdImeiReturnMap.put(175138854,	new HashSet<>(Arrays.asList("50115570082950","351688420279827","351688420575703","354324788647382","357594162666201","359333606194530","863862075760198")));
1436
        fofoIdImeiReturnMap.put(175139569,	new HashSet<>(Arrays.asList("350201087565545","350201087948386","350201087949087","350210771180081","351088890316094","351088890318454","351088896121530","351088896127776","351088896127958","351088896133410","351088896133832","352476512881224","352476512979242","354448512964985","357888147926932","357888147928292","357888147928557","357888147929050","357888147929795","357888147933094","861128070182420","861753065277115","863511069713933","866657077333680","868273068567092","868565072301768","869116062743905","869452071985157","869452073161393")));
1437
        fofoIdImeiReturnMap.put(175139610,	new HashSet<>(Arrays.asList("862736063981738","863718063044617","866335072870176","866335072870598")));
1438
        fofoIdImeiReturnMap.put(175139366,	new HashSet<>(Arrays.asList("354324783144864","354324788632608","354889661849990","354990353239423","863967070558271","864718076129396","866657077789543","866657078285368","866657078508066","869116060977828","869116061054429","869116061208546")));
1439
        fofoIdImeiReturnMap.put(175139412,	new HashSet<>(Arrays.asList("351115165488595","351115165491318","351115165491359","351115165491458","351115165492332","355358278026573","355358278081610","861888063460717","861977073052018","863816078633919","865883069477035","866335074538870","866993071639594")));
1440
        fofoIdImeiReturnMap.put(175139504,	new HashSet<>(Arrays.asList("862054072660792","862054075971873","862054076312374","862054077948630","863816075363171","863862075442334","864718075894230","868938062122017","868938065268932","869452071940632","869452073034897","869452073158233","869452073158498","869452074159735")));
1441
        fofoIdImeiReturnMap.put(175139201,	new HashSet<>(Arrays.asList("863718061956671","863862075497734","863862075596915","864718076078510","864718076134834","866335070211639","866611060437032","866611061133812")));
1442
        fofoIdImeiReturnMap.put(175139362,	new HashSet<>(Arrays.asList("350201087545646","350201087547048","350201087547709","350201087548764","350201087597043","350201087597167","350201087597464","350201087597787","350201087598165","350201087600789","863718062929271","865883069477191","865883069477530","866335071174133","866518078023870","866518078243072","868938061053494")));
33355 amit.gupta 1443
        fofoIdImeiReturnMap.put(175139661,	new HashSet<>(Arrays.asList("860946077691031","861977074661155","862054073218855","866335070523694","867940069973476","868938062656477")));*/
33452 amit.gupta 1444
        fofoIdImeiReturnMap.put(175139556, new HashSet<>(Arrays.asList("863718063534013", "866335072895173", "866335073390810")));
1445
        fofoIdImeiReturnMap.put(175139721, new HashSet<>(Arrays.asList("358250294549067", "865883067508138", "866993072210619")));
33355 amit.gupta 1446
        /*fofoIdImeiReturnMap.put(175139455,	new HashSet<>(Arrays.asList("358293804087913","866518078020694","866518078021650","866518078243676","866518078571936")));
33315 amit.gupta 1447
        fofoIdImeiReturnMap.put(175138674,	new HashSet<>(Arrays.asList("351115165482275","359197386868583","862054074428875","862054077945693","862054078556879","863967070559535","863975068705671","863975068705770","864468076196124","866186064235971","866186066185117","866186066186917","866518073607370","866518079641514","868938060476456","868938060501535","868938060717990","868938062656931")));
1448
        fofoIdImeiReturnMap.put(175139559,	new HashSet<>(Arrays.asList("863718069016890","863816078879256","864468075283881","866335073245436","866335073403571","866657074268327","868024065473853","868956065899993","869452070362895","869452074030274")));
1449
        fofoIdImeiReturnMap.put(175139575,	new HashSet<>(Arrays.asList("354324786659199","860388067452035","861220078009919","863816078878134","863862075841154","865388070857498","867907071407116")));
33355 amit.gupta 1450
        fofoIdImeiReturnMap.put(175139686,	new HashSet<>(Arrays.asList("866657078019106","866657078032869")));*/
33315 amit.gupta 1451
 
33355 amit.gupta 1452
        //this.processOrdersToRebill(fofoIdImeiReturnMap, debitNoteDate);
1453
        purchaseReturnService.fixReturns(fofoIdImeiReturnMap, debitNoteDate);
32513 amit.gupta 1454
 
32698 amit.gupta 1455
    }
1456
 
1457
 
33315 amit.gupta 1458
    private void processOrdersToRebill(Map<Integer, Set<String>> fofoIdImeiReturnMap, LocalDateTime debitNoteDate) throws Exception {
32698 amit.gupta 1459
 
1460
 
1461
        for (Entry<Integer, Set<String>> fofoIdImeiReturnEntry : fofoIdImeiReturnMap.entrySet()) {
32511 amit.gupta 1462
            int fofoId = fofoIdImeiReturnEntry.getKey();
1463
            Set<String> imeis = fofoIdImeiReturnEntry.getValue();
1464
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, imeis, true);
1465
            for (InventoryItem inventoryItem : inventoryItems) {
1466
                //inventoryItem.getId();
1467
                purchaseReturnService.returnInventoryItem(fofoId, true, inventoryItem.getId(), ReturnType.GOOD);
1468
                //Approve return
1469
                PurchaseReturnItem purchaseReturnItem = purchaseReturnItemRepository.selectByInventoryItemId(inventoryItem.getId());
1470
                purchaseReturnItem.setStatus(PurchaseReturnStatus.APPROVED);
1471
                purchaseReturnItem.setApproveTimestamp(LocalDateTime.now());
1472
            }
1473
            Map<Purchase, List<InventoryItem>> purchaseInventoryItemsMap = purchaseReturnService.getPurchaseMapForApprovedReturns(fofoId);
1474
            int walletAmount = walletService.getWalletAmount(fofoId);
1475
            List<DebitNote> debitNotes = purchaseReturnService.generateDebitNotes(purchaseInventoryItemsMap);
1476
            int walletDiff = walletAmount - walletService.getWalletAmount(fofoId);
1477
            if (walletDiff > 0) {
1478
                int reference = walletService.getManualReference(WalletReferenceType.OTHERS);
32514 amit.gupta 1479
                walletService.addAmountToWallet(fofoId, reference, WalletReferenceType.ADVANCE_AMOUNT, "Sytematically added for internal PO", (float) walletDiff + 5000, LocalDateTime.now());
32511 amit.gupta 1480
            }
32698 amit.gupta 1481
            List<CartItem> cartItems = new ArrayList<>();
32511 amit.gupta 1482
            for (DebitNote debitNote : debitNotes) {
33315 amit.gupta 1483
                debitNote.setCreateTimestamp(debitNoteDate);
32511 amit.gupta 1484
                //Try to refund amount per debit note
32698 amit.gupta 1485
                cartItems.addAll(this.refundDnAmount(debitNote));
32511 amit.gupta 1486
            }
32698 amit.gupta 1487
            //If order created
33452 amit.gupta 1488
            Map<Integer, List<CartItem>> warehouseCartItemsMap = cartItems.stream().collect(groupingBy(x -> x.getWarehouseId()));
1489
            for (Entry<Integer, List<CartItem>> warehouseCartItemsEntry : warehouseCartItemsMap.entrySet()) {
32223 amit.gupta 1490
 
32698 amit.gupta 1491
                List<CartItem> warehouseCartItems = warehouseCartItemsEntry.getValue();
1492
 
1493
                List<CartItem> mergedCartItems = warehouseCartItems.stream()
1494
                        .collect(Collectors.collectingAndThen(
33452 amit.gupta 1495
                                groupingBy(x -> x.getItemId(), Collectors.collectingAndThen(
32724 amit.gupta 1496
                                        Collectors.reducing((a, b) -> {
32698 amit.gupta 1497
                                            a.setQuantity(a.getQuantity() + b.getQuantity());
1498
                                            return a;
1499
                                        }), Optional::get)),
1500
                                m -> new ArrayList<>(m.values())));
1501
 
32724 amit.gupta 1502
                double walletTotalAmount = mergedCartItems.stream().mapToDouble(x -> x.getQuantity() * x.getSellingPrice()).sum();
32698 amit.gupta 1503
 
1504
                com.spice.profitmandi.dao.entity.user.User user = userRepository.selectById(fofoId);
1505
                cartService.clearCart(user.getActiveCartId());
1506
                cartService.addItemsToCart(user.getActiveCartId(), mergedCartItems);
1507
 
1508
                UserCart userCart = new UserCart();
1509
                userCart.setCartId(user.getActiveCartId());
1510
                userCart.setUserId(user.getId());
1511
 
1512
                int transactionId = transactionService.createTransactionInternally(userCart, walletTotalAmount, warehouseCartItemsEntry.getKey());
1513
                commonPaymentService.payThroughWallet(transactionId);
34352 amit.gupta 1514
                transactionService.processTransaction(transactionId, 0);
32698 amit.gupta 1515
            }
1516
        }
31697 amit.gupta 1517
    }
32048 tejbeer 1518
 
32384 amit.gupta 1519
    @Autowired
32511 amit.gupta 1520
    CartService cartService;
1521
    @Autowired
1522
    UserRepository userRepository;
1523
 
1524
    @Autowired
1525
    WarehouseScanRepository warehouseScanRepository;
1526
 
1527
    @Autowired
1528
    WarehouseInventoryService warehouseInventoryService;
1529
 
1530
    @Autowired
1531
    CommonPaymentService commonPaymentService;
1532
 
32533 amit.gupta 1533
    @Autowired
1534
    LineItemImeisRepository lineItemImeisRepository;
1535
 
32698 amit.gupta 1536
 
32511 amit.gupta 1537
    //Also create order
32698 amit.gupta 1538
    private List<CartItem> refundDnAmount(DebitNote debitNote) throws ProfitMandiBusinessException {
32511 amit.gupta 1539
        List<Integer> inventoryItemIds = purchaseReturnItemRepository.selectAllByDebitNoteId(debitNote.getId()).stream().map(x -> x.getInventoryItemId()).collect(Collectors.toList());
33452 amit.gupta 1540
        Map<Integer, Long> inventoryItemCountMap = inventoryItemIds.stream().collect(groupingBy(x -> x, Collectors.counting()));
32511 amit.gupta 1541
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(new ArrayList<>(inventoryItemCountMap.keySet()));
1542
        Purchase purchase = purchaseRepository.selectById(inventoryItems.get(0).getPurchaseId());
1543
        String invoice = purchase.getPurchaseReference();
1544
        List<Order> orders = orderRepository.selectByInvoiceNumber(invoice);
1545
        Set<Integer> orderIds = orders.stream().map(x -> x.getId()).collect(Collectors.toSet());
1546
        Order order = orders.get(0);
1547
        float totalAmount = 0;
1548
        int totalQty = 0;
1549
        Map<Integer, CartItem> itemIdCartItemMap = new HashMap<>();
1550
 
35447 amit 1551
        // Batch fetch all TagListings by itemIds to avoid N+1 queries
1552
        Set<Integer> allItemIds = inventoryItems.stream()
1553
                .map(InventoryItem::getItemId)
1554
                .collect(Collectors.toSet());
1555
        List<TagListing> allTagListings = tagListingRepository.selectByItemIdsAndTagIds(allItemIds, null);
1556
        Map<Integer, TagListing> itemIdTagListingMap = allTagListings.stream()
1557
                .collect(Collectors.toMap(TagListing::getItemId, t -> t, (u, v) -> u));
1558
 
32511 amit.gupta 1559
        List<CartItem> cartItems = new ArrayList<>();
1560
        for (InventoryItem inventoryItem : inventoryItems) {
35447 amit 1561
            TagListing tagListing = itemIdTagListingMap.get(inventoryItem.getItemId());
32511 amit.gupta 1562
            long quantity = inventoryItemCountMap.get(inventoryItem.getId());
1563
            totalAmount += inventoryItem.getUnitPrice() * quantity;
1564
            totalQty += quantity;
1565
            if (!itemIdCartItemMap.containsKey(inventoryItem.getItemId())) {
1566
                CartItem cartItem = new CartItem();
1567
                cartItem.setItemId(inventoryItem.getItemId());
1568
                cartItem.setSellingPrice(tagListing.getSellingPrice());
32698 amit.gupta 1569
                cartItem.setWarehouseId(order.getWarehouseId());
32511 amit.gupta 1570
                cartItems.add(cartItem);
1571
                itemIdCartItemMap.put(inventoryItem.getItemId(), cartItem);
1572
            }
1573
            CartItem cartItem = itemIdCartItemMap.get(inventoryItem.getItemId());
1574
            cartItem.setQuantity((int) quantity + cartItem.getQuantity());
1575
        }
1576
        String rollbackDescription = String.format("Refunded against DN %s, %d pc(s)", debitNote.getDebitNoteNumber(), totalQty);
1577
        walletService.addAmountToWallet(debitNote.getFofoId(), order.getTransactionId(), WalletReferenceType.PURCHASE, rollbackDescription, totalAmount, LocalDateTime.now());
1578
        //Before creating order lets try to in the stock
1579
 
1580
        //All scans pertaining to specific Invoices
1581
        List<WarehouseScan> warehouseScans = warehouseScanRepository.selectAllByOrderIds(new ArrayList<>(orderIds));
32698 amit.gupta 1582
        Map<Integer, Integer> inventoryItemIdOrderIdMap = new HashMap<>();
1583
        try {
1584
            inventoryItemIdOrderIdMap = warehouseScans.stream().collect(Collectors.toMap(x -> x.getInventoryItemId(), x -> x.getQuantity()));
32724 amit.gupta 1585
        } catch (Exception e) {
32698 amit.gupta 1586
            LOGGER.info("Could not process for fofoId - {}, {}", debitNote.getFofoId(), warehouseScans);
1587
        }
32511 amit.gupta 1588
        List<Integer> warehouseInventoryItemIds = warehouseScans.stream().filter(x -> !(x.getType().equals(in.shop2020.warehouse.ScanType.SALE_RET) || x.getType().equals(in.shop2020.warehouse.ScanType.SALE_RET_UNUSABLE)))
1589
                .map(x -> x.getInventoryItemId()).collect(Collectors.toList());
1590
        List<WarehouseInventoryItem> warehouseInventoryItems = warehouseInventoryItemRepository.selectAllByIds(warehouseInventoryItemIds);
1591
 
1592
        Map<String, WarehouseInventoryItem> serialNumberWarehouseInventoryItemMap = warehouseInventoryItems.stream().filter(x -> StringUtils.isNotBlank(x.getSerialNumber())).collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
1593
 
1594
        for (InventoryItem inventoryItem : inventoryItems) {
1595
            if (StringUtils.isBlank(inventoryItem.getSerialNumber())) {
1596
                //As of now this should be happening as  dn are specifically for serialized devices
1597
                /*int returnQty = inventoryItemCountMap.get(inventoryItem.getId()).intValue();
1598
                List<WarehouseInventoryItem> warehouseInventoryItemList = itemIdWarehouseInventoryItemsMap.get(inventoryItem.getItemId());
1599
                warehouseInventoryService.returnNonSerializedQty(warehouseInventoryItem)*/
1600
            } else if (StringUtils.isNotBlank(inventoryItem.getSerialNumber())) {
1601
                String serialNumber = inventoryItem.getSerialNumber();
1602
                WarehouseInventoryItem warehouseInventoryItem = serialNumberWarehouseInventoryItemMap.get(serialNumber);
1603
                warehouseInventoryItem.setLastScanType(in.shop2020.warehouse.ScanType.SALE_RET);
1604
                warehouseInventoryService.addQuantity(warehouseInventoryItem.getId(), 1);
1605
                WarehouseScan warehouseScan = new WarehouseScan();
1606
                warehouseScan.setInventoryItemId(warehouseInventoryItem.getId());
1607
                warehouseScan.setQuantity(1);
1608
                warehouseScan.setOrderId(inventoryItemIdOrderIdMap.get(warehouseInventoryItem.getItemId()));
1609
                warehouseScan.setScannedAt(LocalDateTime.now());
1610
                warehouseScan.setType(in.shop2020.warehouse.ScanType.SALE_RET);
1611
                warehouseScanRepository.persist(warehouseScan);
1612
 
1613
            }
1614
        }
1615
 
1616
        //Create Order as well
32724 amit.gupta 1617
        return cartItems;
32698 amit.gupta 1618
    }
32511 amit.gupta 1619
 
32698 amit.gupta 1620
    void addToCartAndCreateOrder() {
32511 amit.gupta 1621
 
1622
    }
1623
 
1624
    @Autowired
32384 amit.gupta 1625
    WarehouseDebitNoteRepository warehouseDebitNoteRepository;
1626
    @Autowired
1627
    WarehouseDebitNoteLineRepository warehouseDebitNoteLineRepository;
1628
 
1629
    @Autowired
1630
    WarehouseInvoiceItemRepository warehouseInvoiceItemRepository;
1631
    @Autowired
1632
    WarehouseSupplierInvoiceRepository warehouseSupplierInvoiceRepository;
1633
 
1634
    @Autowired
1635
    PurchaseOrderService purchaseOrderService;
1636
 
32482 amit.gupta 1637
    @Autowired
1638
    VendorCatalogPricingLogRepository vendorCatalogPricingLogRepository;
32384 amit.gupta 1639
 
32214 jai.hind 1640
//    private void checkItelImeiActivationNew(LocalDate now, int i) {
1641
//    }
1642
 
32169 amit.gupta 1643
    @Autowired
1644
    SessionFactory sessionFactory;
1645
 
1646
 
31697 amit.gupta 1647
    public void sendMailForSamsungRebilling() throws Exception {
1648
        List<BilledImeiModel> samsungModels = warehouseInventoryItemRepository.findByBillingDateBrand(LocalDate.now(), "Samsung");
1649
        LOGGER.info("SamsungModels {}", samsungModels);
1650
        samsungModels = samsungModels.stream().sorted(Comparator.comparing(x -> x.getPcmDate() == null ? -1 : 1)).collect(Collectors.toList());
1651
        if (samsungModels.size() > 0) {
1652
            List<String> headers = Arrays.asList("Partner Id", "Code", "Name", "City", "Brand", "Model Name", "Model Number", "Color", "Serial Number", "Remarks");
1653
            List<List<?>> rows = new ArrayList<>();
1654
            for (BilledImeiModel billedImeiModel : samsungModels) {
31886 tejbeer 1655
                List<Serializable> row = Arrays.asList(billedImeiModel.getFofoId(), billedImeiModel.getStoreCode(), billedImeiModel.getStoreName(), billedImeiModel.getStoreCity(), billedImeiModel.getBrand(), billedImeiModel.getModelName(), billedImeiModel.getModelNumber(), billedImeiModel.getColor(), billedImeiModel.getSerialNumber(), billedImeiModel.getPcmDate() == null ? "PCM date Missing" : "Rebill Imeis");
31697 amit.gupta 1656
                rows.add(row);
1657
            }
1658
            ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1659
            String[] sendToArray = new String[]{"kamini.sharma@smartdukaan.com", "praveen.sharma@smartdukaan.com"};
1660
            String fileName = "Imeis need Rebilling -" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
31886 tejbeer 1661
            Utils.sendMailWithAttachment(googleMailSender, sendToArray, new String[]{"tarun.verma@smartdukaan.com"}, "Samsung Rebilling IMEI Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 1662
        }
1663
    }
24002 amit.gupta 1664
 
31697 amit.gupta 1665
    public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
1666
        LocalDate yesterDay = LocalDate.now().minusDays(1);
1667
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
31886 tejbeer 1668
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25312 amit.gupta 1669
 
32169 amit.gupta 1670
        List<String> headers = Arrays.asList("Code", "Outlet name", "State Manager", "Territory/Team Lead", "Wallet Amount", "In Stock Amount", "Activated Stock", "Return In Transit Stock", "Unbilled Amount", "Grn Pending Amount", "Min Investment", "Investment Amount", "Investment Short", "Unbilled Qty", "Short Days");
31697 amit.gupta 1671
        List<List<?>> rows = new ArrayList<>();
1672
        Map<Integer, List<?>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 1673
 
31697 amit.gupta 1674
        Map<Integer, FofoReportingModel> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25312 amit.gupta 1675
 
31886 tejbeer 1676
        Map<Integer, Integer> shortDaysMap = partnerDailyInvestmentRepository.selectAll(LocalDate.now().withDayOfMonth(1), LocalDate.now()).stream().collect(groupingBy(
1677
                x -> x.getFofoId(), Collectors.summingInt(x -> x.getShortPercentage() > 10 ? 1 : 0)));
24271 amit.gupta 1678
 
31697 amit.gupta 1679
        for (FofoStore fofoStore : fofoStores) {
1680
            LOGGER.info("Fofo Store {},  {}", fofoStore.getId(), fofoStore.getCode());
1681
            int fofoId = fofoStore.getId();
1682
            PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 1);
1683
            partnerDailyInvestment.setDate(yesterDay);
24177 govind 1684
 
31697 amit.gupta 1685
            try {
1686
                partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
31886 tejbeer 1687
                shortDaysMap.put(fofoId, shortDaysMap.get(fofoId) + (partnerDailyInvestment.getShortPercentage() > 10 ? 1 : 0));
31697 amit.gupta 1688
            } catch (Exception e) {
1689
                // ignore the exceptions during persist
1690
            }
25598 amit.gupta 1691
 
31697 amit.gupta 1692
            CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
1693
            if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
1694
                LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
1695
                continue;
1696
            }
1697
            FofoReportingModel reportingModel = partnerIdSalesHeaderMap.get(fofoStore.getId());
1698
            List<Serializable> row = new ArrayList<>();
31886 tejbeer 1699
            row.addAll(Arrays.asList(reportingModel.getCode(), reportingModel.getBusinessName(), reportingModel.getRegionalManager(), reportingModel.getTerritoryManager()));
31697 amit.gupta 1700
            row.addAll(
31886 tejbeer 1701
                    Arrays.asList(partnerDailyInvestment.getWalletAmount(), partnerDailyInvestment.getInStockAmount(), partnerDailyInvestment.getActivatedStockAmount() == 0 ? "-" : "(" + partnerDailyInvestment.getActivatedStockAmount() + ")", 0, partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(), partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(), partnerDailyInvestment.getShortInvestment(), partnerDailyInvestment.getUnbilledQty(), shortDaysMap.get(fofoId)));
31697 amit.gupta 1702
            partnerRowsMap.put(fofoStore.getId(), row);
1703
            rows.add(row);
25837 amit.gupta 1704
 
31697 amit.gupta 1705
        }
25837 amit.gupta 1706
 
34611 ranu 1707
        String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25837 amit.gupta 1708
 
34337 amit.gupta 1709
        if (sendTo == null) {
33452 amit.gupta 1710
            for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
31886 tejbeer 1711
                List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
31697 amit.gupta 1712
                ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
1713
                String[] sendToArray = new String[]{storeGuyEntry.getKey()};
31886 tejbeer 1714
                Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 1715
            }
34578 vikas.jang 1716
            sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com", "amit.gupta@shop2020.in", "manish.gupta1@smartdukaan.com", "niranjan.kala@smartdukaan.com");
31697 amit.gupta 1717
        }
25837 amit.gupta 1718
 
31697 amit.gupta 1719
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1720
        String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
34611 ranu 1721
        Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
25837 amit.gupta 1722
 
31697 amit.gupta 1723
    }
25598 amit.gupta 1724
 
33256 amit.gupta 1725
    private Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() throws ProfitMandiBusinessException {
31697 amit.gupta 1726
        Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
1727
        Map<String, SaleRoles> partnerEmailRBMMap = new HashMap<>();
34903 ranu 1728
        Map<String, SaleRoles> partnerEmailABMMap = new HashMap<>();
24271 amit.gupta 1729
 
35521 amit 1730
        List<Position> positions = positionRepository.selectPositionByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_ABM));
31886 tejbeer 1731
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31697 amit.gupta 1732
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
1733
        for (Position position : positions) {
1734
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1735
            if (crList == null)
1736
                continue;
1737
            if (position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES) {
1738
                for (CustomRetailer cr : crList) {
1739
                    if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
1740
                        partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
1741
                    }
1742
                    SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
1743
                    AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1744
                    if (authUser == null) {
1745
                        continue;
1746
                    }
1747
                    String name = authUser.getFirstName() + " " + authUser.getLastName();
1748
                    if (position.getEscalationType().equals(EscalationType.L1)) {
1749
                        saleRoles.getL1().add(name);
1750
                    } else if (position.getEscalationType().equals(EscalationType.L2)) {
1751
                        saleRoles.getL2().add(name);
1752
                    }
1753
                }
1754
            }
1755
            if (position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM) {
1756
                for (CustomRetailer cr : crList) {
1757
                    if (!partnerEmailRBMMap.containsKey(cr.getEmail())) {
1758
                        partnerEmailRBMMap.put(cr.getEmail(), new SaleRoles());
1759
                    }
1760
                    SaleRoles saleRoles = partnerEmailRBMMap.get(cr.getEmail());
1761
                    AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1762
                    if (authUser == null) {
1763
                        continue;
1764
                    }
1765
                    String name = authUser.getFirstName() + " " + authUser.getLastName();
1766
                    if (position.getEscalationType().equals(EscalationType.L1) || position.getEscalationType().equals(EscalationType.L1)) {
1767
                        saleRoles.getL1().add(name);
1768
                    }
1769
                    /*else if (position.getEscalationType().equals(EscalationType.L2)) {
1770
                        saleRoles.getL2().add(name);
1771
                    }*/
1772
                }
1773
            }
24692 amit.gupta 1774
 
34903 ranu 1775
            if (position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_ABM) {
1776
                for (CustomRetailer cr : crList) {
1777
                    if (!partnerEmailABMMap.containsKey(cr.getEmail())) {
1778
                        partnerEmailABMMap.put(cr.getEmail(), new SaleRoles());
1779
                    }
1780
                    SaleRoles saleRoles = partnerEmailABMMap.get(cr.getEmail());
1781
                    AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1782
                    if (authUser == null) {
1783
                        continue;
1784
                    }
1785
                    String name = authUser.getFirstName() + " " + authUser.getLastName();
1786
                    if (position.getEscalationType().equals(EscalationType.L1) || position.getEscalationType().equals(EscalationType.L1)) {
1787
                        saleRoles.getL1().add(name);
35521 amit 1788
                    } else if (position.getEscalationType().equals(EscalationType.L2)) {
34903 ranu 1789
                        saleRoles.getL2().add(name);
1790
                    }
1791
                }
1792
            }
1793
 
31697 amit.gupta 1794
        }
25418 amit.gupta 1795
 
31697 amit.gupta 1796
        Set<CustomRetailer> allCrList = new HashSet<>();
1797
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1798
            allCrList.addAll(cr);
1799
        }
25609 amit.gupta 1800
 
31886 tejbeer 1801
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
25503 amit.gupta 1802
 
31697 amit.gupta 1803
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
25503 amit.gupta 1804
 
31697 amit.gupta 1805
        for (CustomRetailer cr : allCrList) {
1806
            FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
1807
            if (fofoStore == null) {
1808
                LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
1809
                continue;
1810
            }
1811
            String code = fofoStore.getCode();
1812
            // String storeName = "SmartDukaan-" +
1813
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
1814
            String businessName = cr.getBusinessName();
1815
            try {
1816
                String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
1817
                String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
1818
                String bdm = StringUtils.join(partnerEmailRBMMap.get(cr.getEmail()).getL1(), ", ");
1819
                FofoReportingModel reportingModel = new FofoReportingModel();
1820
                reportingModel.setBusinessName(businessName);
1821
                reportingModel.setCode(code);
1822
                reportingModel.setFofoId(fofoStore.getId());
1823
                reportingModel.setRegionalManager(stateManager);
1824
                reportingModel.setTerritoryManager(territoryManager);
1825
                reportingModel.setBusinessManager(bdm);
1826
                partnerIdSalesHeadersMap.put(fofoStore.getId(), reportingModel);
1827
            } catch (Exception e) {
1828
                LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
1829
            }
1830
        }
1831
        return partnerIdSalesHeadersMap;
24533 govind 1832
 
31697 amit.gupta 1833
    }
28709 amit.gupta 1834
 
34275 tejus.loha 1835
    public void persistRbmTodayTargets() throws Exception {
33928 ranu 1836
        rbmTargetService.setMovementWiseRbmTargets();
1837
    }
1838
 
34275 tejus.loha 1839
    public void persistRbmTodayAchievements() throws Exception {
33986 ranu 1840
        rbmTargetService.setMovementWiseRbmAchievement();
1841
    }
1842
 
31697 amit.gupta 1843
    public void sendPartnerInvestmentDetails() throws Exception {
1844
        this.sendPartnerInvestmentDetails(null);
1845
    }
28709 amit.gupta 1846
 
31697 amit.gupta 1847
    public void sendAgeingReport(String... sendTo) throws Exception {
28790 amit.gupta 1848
 
31886 tejbeer 1849
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW, "itemstockageing.xml");
1850
        InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "ItemwiseOverallPendingIndent.xml");
31697 amit.gupta 1851
        Attachment attachment = new Attachment(
1852
                "ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
1853
        Attachment attachment1 = new Attachment(
1854
                "pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
28790 amit.gupta 1855
 
31886 tejbeer 1856
        Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA", attachment);
1857
        Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null, "Itemwise Pending indent", "PFA", attachment1);
28790 amit.gupta 1858
 
31697 amit.gupta 1859
        // Reports to be sent to mapped partners
1860
        Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
28790 amit.gupta 1861
 
33452 amit.gupta 1862
        for (Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
31697 amit.gupta 1863
            Map<String, String> params = new HashMap<>();
1864
            if (storeGuyEntry.getValue().size() == 0)
1865
                continue;
1866
            params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
31886 tejbeer 1867
            InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "focostockreport.xml", params);
31697 amit.gupta 1868
            Attachment attache = new Attachment(
1869
                    "Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
1870
            System.out.println(storeGuyEntry.getValue());
31886 tejbeer 1871
            Utils.sendMailWithAttachments(googleMailSender, new String[]{storeGuyEntry.getKey()}, null, "Franchise Stock Report", "PFA", attache);
31697 amit.gupta 1872
        }
28839 tejbeer 1873
 
31697 amit.gupta 1874
    }
28839 tejbeer 1875
 
31697 amit.gupta 1876
    public void sendIndentTertiary() throws Exception {
28790 amit.gupta 1877
 
31886 tejbeer 1878
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "indentandtertiary.xml");
31697 amit.gupta 1879
        Attachment attachment = new Attachment(
1880
                "indentandtertiary-report-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr);
31886 tejbeer 1881
        Utils.sendMailWithAttachments(googleMailSender, INDENT_TERTIARY_MAIL_LIST, null, "Indent Tertiary Report", "PFA", attachment);
28790 amit.gupta 1882
 
31697 amit.gupta 1883
    }
28790 amit.gupta 1884
 
31697 amit.gupta 1885
    public void sendAttendanceMorningAlert() throws Exception {
1886
        LocalDateTime moriningTime = LocalDate.now().atTime(10, 31);
1887
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
31886 tejbeer 1888
        Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28775 amit.gupta 1889
 
31697 amit.gupta 1890
        List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
1891
        Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28790 amit.gupta 1892
 
31886 tejbeer 1893
        List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now());
28784 amit.gupta 1894
 
31886 tejbeer 1895
        Map<Integer, Optional<EmployeeAttendance>> employeeMorningAttendance = employeeAttendances.stream().collect(groupingBy(EmployeeAttendance::getUserId, Collectors.minBy(Comparator.comparing(EmployeeAttendance::getCreateTimestamp))));
31697 amit.gupta 1896
        for (AuthUser authUser : authUsers) {
1897
            User user = userMap.get(authUser.getEmailId());
1898
            Optional<EmployeeAttendance> employeeAttendanceOptional = employeeMorningAttendance.get(user.getId());
1899
            LOGGER.info("AuthUser - {}, employeeAttendanceOptional {}", authUser.getName(), employeeAttendanceOptional);
1900
            if (employeeAttendanceOptional != null) {
1901
                LOGGER.info("employeeAttendanceOptional.orElse {}", employeeAttendanceOptional.orElse(null));
1902
                if (employeeAttendanceOptional.orElse(null) != null) {
31886 tejbeer 1903
                    LOGGER.info("employeeAttendanceOptional.get().getCreateTimestamp() {}", employeeAttendanceOptional.get().getCreateTimestamp());
31697 amit.gupta 1904
                }
1905
            }
31886 tejbeer 1906
            if (employeeAttendanceOptional == null || employeeAttendanceOptional.orElse(null) == null || employeeAttendanceOptional.get().getCreateTimestamp().isAfter(moriningTime)) {
31697 amit.gupta 1907
                LOGGER.info("Will Send Email to {}", authUser.getFullName());
1908
                String body = String.format(
31886 tejbeer 1909
                        "Dear %s,\n Pls note that you haven't punched your attendance by 10:30am%s. You have been marked absent for half the day.\n\nRegards\nHR Team", authUser.getFullName(), (employeeAttendanceOptional == null || employeeAttendanceOptional.orElse(null) == null) ? "" : "(Punched at " + FormattingUtils.format(employeeAttendanceOptional.get().getCreateTimestamp()) + ")");
28790 amit.gupta 1910
 
31886 tejbeer 1911
                Utils.sendMailWithAttachments(googleMailSender, new String[]{authUser.getEmailId()}, new String[]{"kangan.monga@smartdukaan.com"}, "Attendance Alert", body);
28790 amit.gupta 1912
 
31697 amit.gupta 1913
            }
1914
        }
28790 amit.gupta 1915
 
31697 amit.gupta 1916
    }
28790 amit.gupta 1917
 
31697 amit.gupta 1918
    public void sendAttendanceEveningAlert() throws Exception {
1919
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
31886 tejbeer 1920
        Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28709 amit.gupta 1921
 
31697 amit.gupta 1922
        List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
1923
        Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28709 amit.gupta 1924
 
31886 tejbeer 1925
        Map<Integer, List<EmployeeAttendance>> employeeAttendancesMap = employeeAttendanceRepository.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now()).stream().collect(groupingBy(x -> x.getUserId()));
28709 amit.gupta 1926
 
31697 amit.gupta 1927
        for (AuthUser authUser : authUsers) {
1928
            User user = userMap.get(authUser.getEmailId());
1929
            String body = null;
1930
            List<EmployeeAttendance> employeeAttendances = employeeAttendancesMap.get(user.getId());
1931
            if (employeeAttendances == null) {
1932
                body = String.format(
31886 tejbeer 1933
                        "Dear %s,\n No attendance has been registered by you today. You have been marked absent for the day.\n\nRegards\nHR Team", authUser.getFullName());
31697 amit.gupta 1934
            } else {
31886 tejbeer 1935
                List<LocalDateTime> punchTimes = employeeAttendances.stream().sorted(Comparator.comparing(EmployeeAttendance::getCreateTimestamp)).map(x -> x.getCreateTimestamp()).collect(Collectors.toList());
31697 amit.gupta 1936
                if (punchTimes.size() == 1) {
1937
                    // body = String.format("Dear %s,\n Pls note that you haven't punched out yet.
1938
                    // You have been marked absent for half the day. You may contact your manager
1939
                    // and get it regularise.\n\nRegards\nHR Team", authUser.getFullName());
1940
                } else {
1941
                    LocalDateTime firstPunch = punchTimes.get(0);
1942
                    LocalDateTime lastPunch = punchTimes.get(punchTimes.size() - 1);
1943
                    Duration duration = Duration.between(firstPunch, lastPunch);
1944
                    boolean hoursCompleted = lastPunch.isAfter(firstPunch.plusHours(8).plusMinutes(30));
1945
                    if (!hoursCompleted) {
1946
                        body = String.format(
31886 tejbeer 1947
                                "Dear %s,\n Pls note that you haven't completed 8.30 Hrs (%d.%d Hrs). You have been marked absent for half the day.\n\nRegards\nHR Team", authUser.getFullName(), duration.toHours(), duration.toMinutes() - duration.toHours() * 60);
31697 amit.gupta 1948
                    }
1949
                }
28709 amit.gupta 1950
 
31697 amit.gupta 1951
            }
1952
            if (body != null) {
31886 tejbeer 1953
                Utils.sendMailWithAttachments(googleMailSender, new String[]{authUser.getEmailId()}, new String[]{"kangan.monga@smartdukaan.com"}, "Attendance Alert", body);
31697 amit.gupta 1954
            }
1955
        }
28709 amit.gupta 1956
 
31697 amit.gupta 1957
        this.sendMailToHR();
28709 amit.gupta 1958
 
31697 amit.gupta 1959
    }
28709 amit.gupta 1960
 
31697 amit.gupta 1961
    private void sendMailToHR() throws Exception {
1962
        Map<String, String> map = new HashMap<>();
1963
        String reporticoDate = FormattingUtils.formatReporitcoDate(LocalDateTime.now());
1964
        map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
1965
        map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
31886 tejbeer 1966
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "employeeattendance.xml");
1967
        Attachment attachment = new Attachment("attendance-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr);
1968
        Utils.sendMailWithAttachments(googleMailSender, EMPLOYEE_ATTENDANCE_MAIL_LIST, null, "Attendance - " + FormattingUtils.formatDate(LocalDateTime.now()), "PFA Attendance", attachment);
31697 amit.gupta 1969
    }
28709 amit.gupta 1970
 
31697 amit.gupta 1971
    public void checkPartnerActiveStore() throws Exception {
24697 amit.gupta 1972
 
31697 amit.gupta 1973
        List<FofoStore> fofoStores = fofoStoreRepository.selectByStatus(true);
23929 amit.gupta 1974
 
31697 amit.gupta 1975
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1976
        if (!fofoStores.isEmpty()) {
1977
            for (FofoStore fofoStore : fofoStores) {
24551 amit.gupta 1978
 
31697 amit.gupta 1979
                if (currentDate.isBefore(fofoStore.getActiveTimeStamp())) {
24542 amit.gupta 1980
 
31697 amit.gupta 1981
                    fofoStore.setActive(true);
1982
                    fofoStoreRepository.persist(fofoStore);
1983
                    LOGGER.info("inserted into InActiveFofoStore successfully");
29160 amit.gupta 1984
 
31697 amit.gupta 1985
                } else {
1986
                    fofoStore.setActive(false);
1987
                    fofoStore.setActiveTimeStamp(null);
1988
                    fofoStoreRepository.persist(fofoStore);
1989
                    LOGGER.info("inserted into InActiveFofoStore successfully");
1990
                }
24542 amit.gupta 1991
 
31697 amit.gupta 1992
            }
1993
        }
24542 amit.gupta 1994
 
31697 amit.gupta 1995
    }
24548 amit.gupta 1996
 
31697 amit.gupta 1997
    public void sendAgeingReport() throws Exception {
33820 ranu 1998
        sendAgeingReport("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "niranjan.kala@smartdukaan.com", "kuldeep.kumar@smartdukaan.com");
31697 amit.gupta 1999
    }
24542 amit.gupta 2000
 
31697 amit.gupta 2001
    public void moveImeisToPriceDropImeis() throws Exception {
2002
        List<PriceDrop> priceDrops = priceDropRepository.selectAll();
2003
        for (PriceDrop priceDrop : priceDrops) {
2004
            priceDropService.priceDropStatus(priceDrop.getId());
2005
        }
2006
    }
29160 amit.gupta 2007
 
31697 amit.gupta 2008
    public void walletmismatch() throws Exception {
2009
        LocalDate curDate = LocalDate.now();
2010
        List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
2011
        System.out.println(pdis.size());
2012
        for (PartnerDailyInvestment pdi : pdis) {
2013
            int fofoId = pdi.getFofoId();
31886 tejbeer 2014
            for (PartnerDailyInvestment investment : Lists.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
2015
                float statementAmount = walletService.getOpeningTill(fofoId, investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
31697 amit.gupta 2016
                CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
31886 tejbeer 2017
                LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(), investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
29160 amit.gupta 2018
 
31697 amit.gupta 2019
            }
2020
        }
29160 amit.gupta 2021
 
31697 amit.gupta 2022
    }
29160 amit.gupta 2023
 
31697 amit.gupta 2024
    @Autowired
2025
    StateRepository stateRepository;
29160 amit.gupta 2026
 
31697 amit.gupta 2027
    public void gst() throws Exception {
31886 tejbeer 2028
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2021, 8, 16).atStartOfDay(), LocalDateTime.now());
31697 amit.gupta 2029
        for (FofoOrder fofoOrder : fofoOrders) {
31886 tejbeer 2030
            int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24548 amit.gupta 2031
 
31697 amit.gupta 2032
            Address retailerAddress = addressRepository.selectById(retailerAddressId);
2033
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
2034
            Integer stateId = null;
2035
            if (customerAddress.getState().equals(retailerAddress.getState())) {
2036
                try {
2037
                    stateId = stateRepository.selectByName(customerAddress.getState()).getId();
2038
                } catch (Exception e) {
2039
                    LOGGER.error("Cannot found state named {}", customerAddress.getState());
2040
                    continue;
2041
                }
2042
            }
2043
            Map<Integer, GstRate> itemIdStateTaxRateMap = null;
24542 amit.gupta 2044
 
31697 amit.gupta 2045
            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
2046
            List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
2047
            if (stateId != null) {
2048
                itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
2049
            } else {
32145 tejbeer 2050
                itemIdStateTaxRateMap = stateGstRateRepository.getIgstTaxRate(itemIds);
31697 amit.gupta 2051
            }
24580 amit.gupta 2052
 
31697 amit.gupta 2053
            for (FofoOrderItem foi : fofoOrderItems) {
2054
                float sgstRate = foi.getSgstRate();
2055
                float cgstRate = foi.getCgstRate();
2056
                float igstRate = foi.getIgstRate();
32145 tejbeer 2057
                foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
2058
                foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
2059
                foi.setIgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
24587 amit.gupta 2060
 
32145 tejbeer 2061
                LOGGER.info("Invoice {}, Date {}", fofoOrder.getInvoiceNumber(), fofoOrder.getCreateTimestamp());
2062
                LOGGER.info("customerAddress.getState() {}, retailerAddress.getState() {}", customerAddress.getState(), retailerAddress.getState());
2063
                LOGGER.info("Rates getIgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
2064
                LOGGER.info("Rates getCgstRate() {}, getSgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate(), itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
24587 amit.gupta 2065
 
2066
 
31697 amit.gupta 2067
            }
2068
        }
26092 amit.gupta 2069
 
31697 amit.gupta 2070
    }
24590 amit.gupta 2071
 
33256 amit.gupta 2072
    public void schemewalletmismatch() throws ProfitMandiBusinessException {
31697 amit.gupta 2073
        LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
2074
        while (dateToReconcile.isBefore(LocalDate.now())) {
2075
            reconcileSchemes(dateToReconcile);
2076
            // reconcileOrders(dateTime);
2077
            // reconcileRecharges(dateTime);
2078
            dateToReconcile = dateToReconcile.plusDays(1);
2079
        }
2080
    }
24587 amit.gupta 2081
 
33256 amit.gupta 2082
    private void reconcileSchemes(LocalDate date) throws ProfitMandiBusinessException {
31697 amit.gupta 2083
        LocalDateTime startDate = date.atStartOfDay();
2084
        LocalDateTime endDate = startDate.plusDays(1);
2085
        List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
2086
        List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
2087
        double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
2088
        double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
2089
        double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
31886 tejbeer 2090
        List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT);
2091
        List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate, walletReferenceTypes);
31697 amit.gupta 2092
        double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
2093
        if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
2094
            LOGGER.info("Scheme Amount mismatched for Date {}", date);
24590 amit.gupta 2095
 
31724 amit.gupta 2096
            Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
24635 amit.gupta 2097
 
31886 tejbeer 2098
            Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet()).stream().collect(groupingBy(x -> x.getFofoId(), Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
24635 amit.gupta 2099
 
31724 amit.gupta 2100
            Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
24635 amit.gupta 2101
 
31886 tejbeer 2102
            Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream().collect(groupingBy(x -> x.getFofoId(), Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
24635 amit.gupta 2103
 
31697 amit.gupta 2104
            Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
24635 amit.gupta 2105
 
33452 amit.gupta 2106
            for (Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
31697 amit.gupta 2107
                if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
2108
                    finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
2109
                } else {
31886 tejbeer 2110
                    finalUserSchemeAmountMap.put(schemeAmount.getKey(), finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
31697 amit.gupta 2111
                }
2112
            }
31886 tejbeer 2113
            Map<Integer, Integer> userWalletMap = userWalletRepository.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24635 amit.gupta 2114
 
31724 amit.gupta 2115
            Map<Integer, Double> walletAmountMap = history.stream().collect(groupingBy(
31697 amit.gupta 2116
                    UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
33452 amit.gupta 2117
            for (Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
31697 amit.gupta 2118
                double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
2119
                if (diff > 5) {
2120
                    LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
2121
                }
2122
            }
2123
        }
24635 amit.gupta 2124
 
31697 amit.gupta 2125
    }
24635 amit.gupta 2126
 
31697 amit.gupta 2127
    public void sendDailySalesNotificationToPartner(Integer fofoIdInt) throws Exception {
30982 tejbeer 2128
 
31697 amit.gupta 2129
        LocalDateTime now = LocalDateTime.now();
2130
        LocalDateTime from = now.with(LocalTime.MIN);
2131
        String timeString = "Today %s";
2132
        // Send yesterday's report
2133
        /*
2134
         * if (now.getHour() < 13) { timeString = "Yesterday %s"; from =
2135
         * now.minusDays(1).; now = from.with(LocalTime.MAX);
2136
         *
2137
         * }
2138
         */
30982 tejbeer 2139
 
31697 amit.gupta 2140
        List<Integer> fofoIds = null;
31886 tejbeer 2141
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getId(), x -> x));
30982 tejbeer 2142
 
24653 govind 2143
 
31697 amit.gupta 2144
        if (fofoIdInt == null) {
2145
            fofoIds = new ArrayList<>(fofoStoreMap.keySet());
2146
        } else {
2147
            fofoIds = Arrays.asList(fofoIdInt);
2148
        }
2149
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
28368 tejbeer 2150
 
31886 tejbeer 2151
        Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now, null);
31697 amit.gupta 2152
        Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
28368 tejbeer 2153
 
31886 tejbeer 2154
        Map<Integer, Double> spPartnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0, true);
28377 tejbeer 2155
 
31886 tejbeer 2156
        Map<Integer, Double> spPartner3DaysOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from.minusDays(3), now, 0, true);
31697 amit.gupta 2157
        Map<Integer, Long> spPartnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
28368 tejbeer 2158
 
31886 tejbeer 2159
        Map<Integer, Double> partnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0, false);
31697 amit.gupta 2160
        Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, false);
28377 tejbeer 2161
 
31697 amit.gupta 2162
        //4 days + current day running
2163
        Map<Integer, Double> partnerBilledValueMap = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(from.minusDays(4), now);
28377 tejbeer 2164
 
31697 amit.gupta 2165
        Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
2166
        for (int fofoId : fofoIds) {
2167
            SaleTargetReportModel model = new SaleTargetReportModel();
2168
            model.setInsuranceSale(
2169
                    partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
2170
            model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
2171
            model.setSecondary(partnerBilledValueMap.containsKey(fofoId) ? partnerBilledValueMap.get(fofoId) : 0);
2172
            model.setSmartphoneSale(spPartnerOrderValMap.containsKey(fofoId) ? spPartnerOrderValMap.get(fofoId) : 0);
2173
            model.setSmartphoneQty(spPartnerOrderQtyMap.containsKey(fofoId) ? spPartnerOrderQtyMap.get(fofoId) : 0);
2174
            model.setTotalSale(partnerOrderValMap.containsKey(fofoId) ? partnerOrderValMap.get(fofoId) : 0);
2175
            model.setTotalQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
2176
            model.setPast3daysSale(
2177
                    spPartner3DaysOrderValMap.containsKey(fofoId) ? spPartner3DaysOrderValMap.get(fofoId) : 0);
2178
            model.setFofoId(fofoId);
2179
            model.setCode(fofoStoreMap.get(fofoId).getCode());
31724 amit.gupta 2180
            model.setActivationType(fofoStoreMap.get(fofoId).getActivationType());
31697 amit.gupta 2181
            saleTargetReportModelMap.put(fofoId, model);
2182
        }
28377 tejbeer 2183
 
31697 amit.gupta 2184
        Map<Integer, FofoReportingModel> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
2185
        for (Integer fofoId : fofoIds) {
2186
            SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
28368 tejbeer 2187
 
31697 amit.gupta 2188
            // com.spice.profitmandi.dao.entity.user.User user =
2189
            // userUserRepository.selectById(fofoId);
28377 tejbeer 2190
 
31697 amit.gupta 2191
            // Address address = addressRepository.selectById(user.getAddressId());
28377 tejbeer 2192
 
31697 amit.gupta 2193
            String title = "Sale Update";
31886 tejbeer 2194
            String messageTemplate = String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.", model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(), String.format(timeString, now.format(timeFormatter)));
31697 amit.gupta 2195
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
2196
            sendNotificationModel.setCampaignName("Sales update alert");
2197
            sendNotificationModel.setTitle(title);
2198
            sendNotificationModel.setMessage(messageTemplate);
2199
            sendNotificationModel.setType("url");
2200
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
2201
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2202
            sendNotificationModel.setMessageType(MessageType.notification);
2203
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
2204
            sendNotificationModel.setUserIds(Arrays.asList(userId));
2205
            notificationService.sendNotification(sendNotificationModel);
2206
            String whatsappMessageTemplate = String.format(
31886 tejbeer 2207
                    "Dear Partner, Your sale update is Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.", model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(), String.format(timeString, now.format(timeFormatter)));
31697 amit.gupta 2208
            // notificationService.sendWhatsappMessage(whatsappMessageTemplate, title,
2209
            // address.getPhoneNumber());
28377 tejbeer 2210
 
31697 amit.gupta 2211
        }
2212
        // String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap,
2213
        // saleTargetReportModelMap);
2214
        this.getStateWiseSales(saleTargetReportModelMap, partnerSalesHeadersMap);
2215
    }
28377 tejbeer 2216
 
31697 amit.gupta 2217
    public void checkRazorPayPaymentStatus() throws Exception {
31886 tejbeer 2218
        List<PendingOrder> pendingOrder = pendingOrderRepository.selectAllByStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PENDING);
28377 tejbeer 2219
 
31697 amit.gupta 2220
        for (PendingOrder po : pendingOrder) {
2221
            RazorPay razorPay = razorPayRepository.selectByOrdeId(po.getId());
2222
            List<PendingOrderItem> poItems = pendingOrderItemRepository.selectByOrderId(po.getId());
28369 tejbeer 2223
 
31697 amit.gupta 2224
            LOGGER.info("razorPay" + razorPay);
2225
            if (razorPay != null) {
2226
                List<Payment> payments = razorPaymentService.fetchOrderForPayment(razorPay.getRazorOrderId());
28368 tejbeer 2227
 
31697 amit.gupta 2228
                if (!payments.isEmpty()) {
2229
                    List<String> statusList = new ArrayList<>();
2230
                    for (Payment payment : payments) {
25880 amit.gupta 2231
 
31697 amit.gupta 2232
                        JSONObject jsonObj = new JSONObject(payment.toString());
25880 amit.gupta 2233
 
31697 amit.gupta 2234
                        String status = jsonObj.getString("status");
25880 amit.gupta 2235
 
31697 amit.gupta 2236
                        statusList.add(status);
25865 amit.gupta 2237
 
31697 amit.gupta 2238
                    }
2239
                    LOGGER.info("statusList" + statusList);
26941 amit.gupta 2240
 
31697 amit.gupta 2241
                    if (statusList.contains("authorized") || statusList.contains("captured")) {
2242
                        po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
2243
                        po.setPaidAmount(po.getTotalAmount());
2244
                        for (PendingOrderItem poi : poItems) {
2245
                            poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
2246
                        }
2247
                        Map<String, Object> emailModel = pendingOrderService.sendCreateOrderMail(po);
26941 amit.gupta 2248
 
31697 amit.gupta 2249
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(po.getFofoId());
2250
                        Customer customer = customerRepository.selectById(po.getCustomerId());
2251
                        String[] customerEmail = null;
2252
                        if (customer.getEmailId() != null) {
2253
                            customerEmail = new String[]{customer.getEmailId()};
2254
                        }
31886 tejbeer 2255
                        List<String> bccTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "niranjan.kala@smartdukaan.com", "sm@smartdukaan.com", "tejbeer.kaur@shop2020.in", customRetailer.getEmail());
31697 amit.gupta 2256
                        List<String> authUserEmails = csService.getAuthUserByPartnerId(customRetailer.getPartnerId());
2257
                        if (authUserEmails != null) {
2258
                            authUserEmails = new ArrayList<>();
2259
                        }
2260
                        authUserEmails.addAll(bccTo);
26945 amit.gupta 2261
 
31697 amit.gupta 2262
                        // emailService.sendMailWithAttachments("Order Created with SmartDukaan",
2263
                        // "order-confirm.vm",
2264
                        // emailModel, customerEmail, null, authUserEmails.toArray(new String[0]));
26945 amit.gupta 2265
 
31697 amit.gupta 2266
                    } else if (statusList.contains("refunded") || statusList.contains("failed")) {
2267
                        for (PendingOrderItem poi : poItems) {
2268
                            poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
2269
                        }
25865 amit.gupta 2270
 
31697 amit.gupta 2271
                        po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
2272
                    }
25865 amit.gupta 2273
 
31697 amit.gupta 2274
                }
2275
                // LOGGER.info("payment" + payments);
25865 amit.gupta 2276
 
31697 amit.gupta 2277
            }
2278
        }
2279
    }
25865 amit.gupta 2280
 
31697 amit.gupta 2281
    public static class SaleTargetReportModel {
2282
        private double totalSale;
2283
        private long totalQty;
2284
        private double past3daysSale;
2285
        private int fofoId;
2286
        private String code;
31724 amit.gupta 2287
        private ActivationType activationType;
25865 amit.gupta 2288
 
31724 amit.gupta 2289
 
2290
        @Override
2291
        public boolean equals(Object o) {
2292
            if (this == o) return true;
2293
            if (o == null || getClass() != o.getClass()) return false;
2294
            SaleTargetReportModel that = (SaleTargetReportModel) o;
2295
            return Double.compare(that.totalSale, totalSale) == 0 && totalQty == that.totalQty && Double.compare(that.past3daysSale, past3daysSale) == 0 && fofoId == that.fofoId && Double.compare(that.secondary, secondary) == 0 && Double.compare(that.smartphoneSale, smartphoneSale) == 0 && smartphoneQty == that.smartphoneQty && Double.compare(that.insuranceSale, insuranceSale) == 0 && insruanceQty == that.insruanceQty && Objects.equals(code, that.code) && activationType == that.activationType;
2296
        }
2297
 
2298
        @Override
2299
        public int hashCode() {
2300
            return Objects.hash(totalSale, totalQty, past3daysSale, fofoId, code, activationType, secondary, smartphoneSale, smartphoneQty, insuranceSale, insruanceQty);
2301
        }
2302
 
2303
        public ActivationType getActivationType() {
2304
            return activationType;
2305
        }
2306
 
2307
        public void setActivationType(ActivationType activationType) {
2308
            this.activationType = activationType;
2309
        }
2310
 
31697 amit.gupta 2311
        public double getSecondary() {
2312
            return secondary;
2313
        }
25865 amit.gupta 2314
 
31697 amit.gupta 2315
        public void setSecondary(double secondary) {
2316
            this.secondary = secondary;
2317
        }
25865 amit.gupta 2318
 
31697 amit.gupta 2319
        private double secondary;
25865 amit.gupta 2320
 
31697 amit.gupta 2321
        public int getFofoId() {
2322
            return fofoId;
2323
        }
25865 amit.gupta 2324
 
31697 amit.gupta 2325
        @Override
2326
        public String toString() {
31886 tejbeer 2327
            return "SaleTargetReportModel{" + "totalSale=" + totalSale + ", totalQty=" + totalQty + ", past3daysSale=" + past3daysSale + ", fofoId=" + fofoId + ", code='" + code + '\'' + ", secondary=" + secondary + ", smartphoneSale=" + smartphoneSale + ", smartphoneQty=" + smartphoneQty + ", insuranceSale=" + insuranceSale + ", insruanceQty=" + insruanceQty + '}';
31697 amit.gupta 2328
        }
25865 amit.gupta 2329
 
31697 amit.gupta 2330
        public String getCode() {
2331
            return code;
2332
        }
25865 amit.gupta 2333
 
31697 amit.gupta 2334
        public void setCode(String code) {
2335
            this.code = code;
2336
        }
25865 amit.gupta 2337
 
31697 amit.gupta 2338
        public void setFofoId(int fofoId) {
2339
            this.fofoId = fofoId;
2340
        }
25872 tejbeer 2341
 
31697 amit.gupta 2342
        private double smartphoneSale;
2343
        private long smartphoneQty;
2344
        private double insuranceSale;
2345
        private long insruanceQty;
26945 amit.gupta 2346
 
31697 amit.gupta 2347
        public long getTotalQty() {
2348
            return totalQty;
2349
        }
30765 tejbeer 2350
 
31697 amit.gupta 2351
        public void setTotalQty(long totalQty) {
2352
            this.totalQty = totalQty;
2353
        }
2354
 
2355
        public double getPast3daysSale() {
2356
            return past3daysSale;
2357
        }
2358
 
2359
        public void setPast3daysSale(double past3daysSale) {
2360
            this.past3daysSale = past3daysSale;
2361
        }
2362
 
2363
        public double getTotalSale() {
2364
            return totalSale;
2365
        }
2366
 
2367
        public void setTotalSale(double totalSale) {
2368
            this.totalSale = totalSale;
2369
        }
2370
 
2371
        public double getSmartphoneSale() {
2372
            return smartphoneSale;
2373
        }
2374
 
2375
        public void setSmartphoneSale(double smartphoneSale) {
2376
            this.smartphoneSale = smartphoneSale;
2377
        }
2378
 
2379
        public long getSmartphoneQty() {
2380
            return smartphoneQty;
2381
        }
2382
 
2383
        public void setSmartphoneQty(long smartphoneQty) {
2384
            this.smartphoneQty = smartphoneQty;
2385
        }
2386
 
2387
        public double getInsuranceSale() {
2388
            return insuranceSale;
2389
        }
2390
 
2391
        public void setInsuranceSale(double insuranceSale) {
2392
            this.insuranceSale = insuranceSale;
2393
        }
2394
 
2395
        public long getInsruanceQty() {
2396
            return insruanceQty;
2397
        }
2398
 
2399
        public void setInsruanceQty(long insruanceQty) {
2400
            this.insruanceQty = insruanceQty;
2401
        }
2402
 
2403
    }
2404
 
32482 amit.gupta 2405
    private void getStateWiseSales
2406
            (Map<Integer, SaleTargetReportModel> saleTargetReportModelMap, Map<Integer, FofoReportingModel> partnerSalesHeadersMap) throws
2407
            Exception {
31697 amit.gupta 2408
        String timeString = "Today %s";
2409
        LocalDateTime now = LocalDateTime.now();
2410
 
2411
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
35521 amit 2412
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_LOGISTICS, ProfitMandiConstants.TICKET_CATEGORY_FINANCIAL_SERVICES, 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, ProfitMandiConstants.TICKET_CATEGORY_TECHNOLOGY);
31697 amit.gupta 2413
 
2414
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false);
2415
 
31746 amit.gupta 2416
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
2417
            String email = storeGuyEntry.getKey();
2418
            Set<Integer> fofoIds = storeGuyEntry.getValue();
2419
            LOGGER.info("fofoIds {}", fofoIds);
24683 amit.gupta 2420
 
31746 amit.gupta 2421
            if (!fofoIds.isEmpty()) {
31886 tejbeer 2422
                List<FofoStore> stores = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds));
26945 amit.gupta 2423
 
31724 amit.gupta 2424
                Map<String, List<Integer>> stateMap = stores.stream().collect(groupingBy(
2425
                        x -> x.getCode().substring(0, 2), mapping(x -> x.getId(), Collectors.toList())));
31697 amit.gupta 2426
                List<List<Serializable>> stateWiseSales = new ArrayList<>();
33452 amit.gupta 2427
                for (Entry<String, List<Integer>> stateMapEntry : stateMap.entrySet()) {
31886 tejbeer 2428
                    long totalQty = stateMapEntry.getValue().stream().collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getTotalQty()));
2429
                    double totalSale = stateMapEntry.getValue().stream().collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getTotalSale()));
2430
                    long smartPhoneQty = stateMapEntry.getValue().stream().collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getSmartphoneQty()));
31697 amit.gupta 2431
                    double smartPhoneSale = stateMapEntry.getValue().stream().collect(
2432
                            Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getSmartphoneSale()));
2433
                    stateWiseSales.add(
2434
                            Arrays.asList(stateMapEntry.getKey(), smartPhoneQty, smartPhoneSale, totalQty, totalSale));
2435
                }
2436
                StringBuilder sb = new StringBuilder();
2437
                sb.append("<html><body>");
2438
                sb.append("<p>Statewise Sale Report:</p><br/><table style=\"border-collapse: collapse;\">");
31886 tejbeer 2439
                sb.append("<tbody>\n" + "	    <tr>" + "	    					<th style='border:1px solid black;padding: 5px'>State</th>" + "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>" + "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Value</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Total Qty</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Total Value</th>" + "	    				</tr>");
31697 amit.gupta 2440
                for (List<Serializable> stateSale : stateWiseSales) {
2441
                    sb.append("<tr>");
2442
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(0) + "</td>");
2443
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(1) + "</td>");
2444
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(2) + "</td>");
2445
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(3) + "</td>");
2446
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(4) + "</td>");
2447
                    sb.append("</tr>");
2448
                }
2449
                sb.append("</tbody></table><br><br>");
26945 amit.gupta 2450
 
31697 amit.gupta 2451
                sb.append("<p>Partnerwise Report:</p><br/><table style=\"border-collapse: collapse;\">");
31886 tejbeer 2452
                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>");
31169 tejbeer 2453
 
2454
 
31886 tejbeer 2455
                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());
31169 tejbeer 2456
 
31697 amit.gupta 2457
                String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
31169 tejbeer 2458
 
31886 tejbeer 2459
                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");
31697 amit.gupta 2460
                List<List<?>> rows = new ArrayList<>();
2461
                for (Integer fofoId : sortedSaleTargetReport) {
2462
                    FofoReportingModel fofoReportingModel = partnerSalesHeadersMap.get(fofoId);
31886 tejbeer 2463
                    rows.add(Arrays.asList(fofoId, fofoReportingModel.getCode(), fofoReportingModel.getBusinessName(), saleTargetReportModelMap.get(fofoId).getActivationType(), fofoReportingModel.getBusinessManager(), fofoReportingModel.getRegionalManager(), fofoReportingModel.getTerritoryManager(), saleTargetReportModelMap.get(fofoId).getSecondary(), saleTargetReportModelMap.get(fofoId).getTotalSale(), saleTargetReportModelMap.get(fofoId).getSmartphoneSale(), saleTargetReportModelMap.get(fofoId).getSmartphoneQty()
31697 amit.gupta 2464
                    ));
31169 tejbeer 2465
 
31724 amit.gupta 2466
                    //Now try to populate html rows
2467
                    if (!saleTargetReportModelMap.get(fofoId).getActivationType().equals(ActivationType.ACTIVE)) {
31697 amit.gupta 2468
                        continue;
2469
                    }
2470
                    if (saleTargetReportModelMap.get(fofoId).getSecondary() == 0) {
2471
                        sb.append("<tr style='background-color:#D21F3C;color:white'>");
2472
                    } else {
2473
                        sb.append("<tr>");
2474
                    }
31886 tejbeer 2475
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getCode() + "</td>");
2476
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getBusinessName() + "</td>");
2477
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getBusinessManager() + "</td>");
2478
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getRegionalManager() + "</td>");
2479
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getTerritoryManager() + "</td>");
2480
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSecondary() + "</td>");
2481
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
2482
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
2483
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
31697 amit.gupta 2484
                    sb.append("</tr>");
24841 govind 2485
 
25300 tejbeer 2486
 
31697 amit.gupta 2487
                }
2488
                sb.append("</tr>");
2489
                sb.append("</body></html>");
2490
                String statewiseSaleReport = sb.toString();
25300 tejbeer 2491
 
2492
 
31697 amit.gupta 2493
                ByteArrayOutputStream baos = null;
2494
                try {
2495
                    baos = FileUtil.getCSVByteStream(headers, rows);
2496
                } catch (Exception e2) {
2497
                    e2.printStackTrace();
2498
                }
2499
                Attachment attachment = new Attachment("PartnerSalePerformance.csv", new ByteArrayResource(baos.toByteArray()));
2500
                Utils.sendHtmlMailWithAttachments(googleMailSender, new String[]{email}, null, "Statewise " + subject, statewiseSaleReport, attachment);
2501
            }
2502
        }
2503
    }
29668 tejbeer 2504
 
32350 amit.gupta 2505
 
32482 amit.gupta 2506
    private void sendMailOfHtmlFormat(JavaMailSender sender, String[] email, String body, String cc[], String subject) throws
2507
            MessagingException, ProfitMandiBusinessException, IOException {
32350 amit.gupta 2508
        MimeMessage message = sender.createMimeMessage();
31697 amit.gupta 2509
        MimeMessageHelper helper = new MimeMessageHelper(message);
2510
        helper.setSubject(subject);
2511
        helper.setText(body, true);
2512
        helper.setTo(email);
2513
        if (cc != null) {
2514
            helper.setCc(cc);
2515
        }
2516
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
2517
        helper.setFrom(senderAddress);
2518
        mailSender.send(message);
2519
    }
25694 amit.gupta 2520
 
31697 amit.gupta 2521
    public void sendNotification() throws Exception {
34042 vikas.jang 2522
        LOGGER.info("FCM sendNotification");
32610 amit.gupta 2523
        List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllPendingNotifications();
31697 amit.gupta 2524
        if (!pushNotifications.isEmpty()) {
34042 vikas.jang 2525
            InputStream serviceAccount = getClass().getClassLoader().getResourceAsStream("service-account.json");
34039 vikas.jang 2526
            GoogleCredentials googleCredentials = GoogleCredentials.fromStream(serviceAccount).createScoped(FCM_SCOPED);
2527
            googleCredentials.refreshIfExpired();
2528
            String accessToken = googleCredentials.getAccessToken().getTokenValue();
2529
 
31697 amit.gupta 2530
            for (PushNotifications pushNotification : pushNotifications) {
2531
                Device device = deviceRepository.selectById(pushNotification.getDeviceId());
31886 tejbeer 2532
                NotificationCampaign notificationCampaign = notificationCampaignRepository.selectById(pushNotification.getNotificationCampaignid());
2533
                SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(), SimpleCampaignParams.class);
31697 amit.gupta 2534
                Campaign campaign = new SimpleCampaign(scp);
2535
                String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
34039 vikas.jang 2536
 
2537
                JSONObject message = new JSONObject();
2538
                message.put("token", device.getFcmId());
2539
 
2540
                JSONObject notification = new JSONObject();
2541
                notification.put("title", campaign.getTitle());
2542
                notification.put("body", campaign.getMessage());
2543
                message.put("notification", notification);
2544
 
2545
                JSONObject data = new JSONObject();
2546
                data.put("type", campaign.getType());
2547
                data.put("url", result_url);
2548
                data.put("time_to_live", campaign.getExpireTimestamp());
2549
                data.put("image", campaign.getImageUrl());
2550
                data.put("largeIcon", "large_icon");
2551
                data.put("smallIcon", "small_icon");
34043 vikas.jang 2552
                data.put("vibrate", "1");
34044 vikas.jang 2553
                data.put("pid", String.valueOf(pushNotification.getId()));
34043 vikas.jang 2554
                data.put("sound", "1");
34039 vikas.jang 2555
                data.put("priority", "high");
2556
                message.put("data", data);
2557
 
2558
                JSONObject payload = new JSONObject();
2559
                payload.put("message", message);
2560
 
31697 amit.gupta 2561
                try {
2562
                    CloseableHttpClient client = HttpClients.createDefault();
2563
                    HttpPost httpPost = new HttpPost(FCM_URL);
25694 amit.gupta 2564
 
34039 vikas.jang 2565
                    httpPost.setHeader("Authorization", "Bearer " + accessToken);
2566
                    httpPost.setHeader("Content-Type", "application/json");
2567
 
2568
                    StringEntity entity = new StringEntity(payload.toString());
31697 amit.gupta 2569
                    httpPost.setEntity(entity);
2570
                    CloseableHttpResponse response = client.execute(httpPost);
34275 tejus.loha 2571
                    LOGGER.info("google FCM status code: {}", response.getStatusLine().getStatusCode());
34043 vikas.jang 2572
                    String responseBody = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
2573
                            .lines().collect(Collectors.joining("\n"));
31697 amit.gupta 2574
                    if (response.getStatusLine().getStatusCode() == 200) {
2575
                        pushNotification.setSentTimestamp(LocalDateTime.now());
2576
                    } else {
2577
                        pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
34043 vikas.jang 2578
                        LOGGER.info("FCM Response message" + responseBody);
31697 amit.gupta 2579
                        response.toString();
2580
                    }
25694 amit.gupta 2581
 
31697 amit.gupta 2582
                } catch (Exception e) {
2583
                    e.printStackTrace();
2584
                    pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
2585
                    LOGGER.info("message " + "not sent " + e.getMessage());
2586
                }
2587
            }
2588
        }
2589
    }
25721 tejbeer 2590
 
31697 amit.gupta 2591
    public void grouping() throws Exception {
2592
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
2593
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
31886 tejbeer 2594
        System.out.println(String.join("\t", Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name", "Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
31697 amit.gupta 2595
        Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers(false);
2596
        for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
2597
            if (priceDropIMEI.getPartnerId() == 0)
2598
                continue;
2599
            HashSet<String> imeis = new HashSet<>();
2600
            PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
2601
            imeis.add(priceDropIMEI.getImei());
31886 tejbeer 2602
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
31697 amit.gupta 2603
            if (inventoryItems.size() == 0) {
2604
                LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
2605
                continue;
2606
            }
2607
            InventoryItem inventoryItem = inventoryItems.get(0);
2608
            CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
31886 tejbeer 2609
            if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) || inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
31697 amit.gupta 2610
                // check if pricedrop has been rolled out
31886 tejbeer 2611
                List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(), priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
31697 amit.gupta 2612
                if (uwh.size() > 0) {
2613
                    Item item = itemRepository.selectById(inventoryItem.getItemId());
31886 tejbeer 2614
                    System.out.println(String.join("\t", Arrays.asList(priceDropIMEI.getImei(), inventoryItem.getItemId() + "", item.getBrand(), item.getModelName(), item.getModelNumber(), inventoryItem.getFofoId() + "", customRetailer.getBusinessName(), inventoryItem.getCreateTimestamp().format(dtf), priceDrop.getAffectedOn().format(dtf), priceDropIMEI.getUpdateTimestamp().format(dtf), inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getAutoPartnerPayout(inventoryItem.getUpdateTimestamp()) + "", inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
31697 amit.gupta 2615
                }
2616
            }
2617
        }
2618
    }
25721 tejbeer 2619
 
31697 amit.gupta 2620
    public void toffeeRollback() throws Exception {
2621
        toffeeService.cancelPolicyCopy("110143521986");
2622
        toffeeService.getOrderId("110143521986");
2623
    }
27212 tejbeer 2624
 
31697 amit.gupta 2625
    public void attachToffeeInvoices() throws Exception {
31886 tejbeer 2626
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(3, Optional.of(false));
31697 amit.gupta 2627
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
2628
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
2629
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
2630
            InvoicePdfModel pdfModel = orderService.getInvoicePdfModel(fofoOrder.getId());
2631
            java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
2632
            PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
31886 tejbeer 2633
            String pdfInvoiceString = "data:application/pdf;base64," + Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
2634
            boolean attached = toffeeService.attachInvoice(insurancePolicy.getPolicyNumber().split("#")[1], pdfInvoiceString);
31697 amit.gupta 2635
            if (attached) {
2636
                insurancePolicy.setPosted(true);
2637
            }
2638
        }
2639
    }
25721 tejbeer 2640
 
31697 amit.gupta 2641
    public void sendBAGPendingPolicies() throws Exception {
31886 tejbeer 2642
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(4, Optional.of(false));
31697 amit.gupta 2643
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
2644
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
2645
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
2646
            FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
2647
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
2648
            Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
2649
            BAGInsuranceModel bagInsuranceModel = new BAGInsuranceModel();
2650
            // bagInsuranceModel.setModelId();
2651
            bagInsuranceModel.setAddressLine1(customerAddress.getLine1());
2652
            bagInsuranceModel.setAddressLine2(customerAddress.getLine2());
2653
            bagInsuranceModel.setCity(customerAddress.getCity());
2654
            bagInsuranceModel.setBrandWarranty("1 Year");
2655
            Item item = itemRepository.selectById(fofoOrderItem.getId());
2656
            bagInsuranceModel.setModelName(item.getItemDescription());
2657
            bagInsuranceModel.setDateOfPurchase(fofoOrder.getFormattedDate());
2658
            bagInsuranceModel.setEmail(customer.getEmailId());
2659
            bagInsuranceModel.setImei1(insurancePolicy.getSerialNumber());
2660
            bagInsuranceModel.setFirstName(customer.getFirstName());
2661
            bagInsuranceModel.setLastName(customer.getLastName());
2662
            bagInsuranceModel.setMobileNumber(customer.getMobileNumber());
2663
            bagInsuranceModel.setPlanId("");
2664
            insurancePolicy.setPosted(true);
2665
        }
2666
    }
25721 tejbeer 2667
 
31697 amit.gupta 2668
    public void schemeRollback(List<String> schemeIds) throws Exception {
2669
        List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
31886 tejbeer 2670
        Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31697 amit.gupta 2671
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
2672
        for (SchemeInOut sio : schemeInOuts) {
2673
            Scheme scheme = schemesMap.get(sio.getSchemeId());
34324 amit.gupta 2674
            if (scheme.getType().getTransactionType().equals(StockTransactionType.IN)) {
25721 tejbeer 2675
 
34324 amit.gupta 2676
            } else if (scheme.getType().getTransactionType().equals(StockTransactionType.OUT)) {
31697 amit.gupta 2677
                InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
2678
                List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
31886 tejbeer 2679
                ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE)).max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
2680
                if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime()) || scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
31697 amit.gupta 2681
                    sio.setRolledBackTimestamp(LocalDateTime.now());
2682
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
31886 tejbeer 2683
                    String rollbackReason = "Scheme reversed for " + itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - " + fofoOrder.getInvoiceNumber();
2684
                    walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(), scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason, LocalDateTime.now());
2685
                    System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(), rollbackReason);
31697 amit.gupta 2686
                }
2687
            }
2688
        }
2689
        // throw new Exception();
2690
    }
25721 tejbeer 2691
 
31697 amit.gupta 2692
    public void checkfocusedModelInPartnerStock() throws Exception {
25721 tejbeer 2693
 
35442 amit 2694
        // ========== PHASE 1: Batch fetch all data upfront ==========
2695
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectActiveStores().stream()
2696
                .collect(Collectors.toMap(FofoStore::getId, x -> x));
2697
        List<Integer> allPartnerIds = new ArrayList<>(fofoStoreMap.keySet());
2698
 
31886 tejbeer 2699
        Map<Integer, Map<Integer, List<SaholicCIS>>> warehouseItemAvailabilityMap = saholicInventoryService.getSaholicStock();
31697 amit.gupta 2700
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2701
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
35442 amit 2702
        Map<Integer, List<FocusedModel>> regionFocusedModelsMap = focusedModelRepository.selectAll().stream()
2703
                .collect(Collectors.groupingBy(FocusedModel::getRegionId));
2704
        LOGGER.info("regionFocusedModelsMap - {}", regionFocusedModelsMap);
31886 tejbeer 2705
        Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService.getSaholicPOItems();
35442 amit 2706
 
2707
        // Batch fetch all customRetailers upfront
2708
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(allPartnerIds);
2709
        LOGGER.info("Fetched {} customRetailers", customRetailerMap.size());
2710
 
2711
        // Batch fetch all inventory snapshots upfront
2712
        Map<Integer, List<CurrentInventorySnapshot>> allInventorySnapshotsMap = currentInventorySnapshotRepository
2713
                .selectByFofoId(allPartnerIds).stream()
2714
                .collect(Collectors.groupingBy(CurrentInventorySnapshot::getFofoId));
2715
        LOGGER.info("Fetched inventory snapshots for {} partners", allInventorySnapshotsMap.size());
2716
 
2717
        // Batch fetch all pending GRN orders upfront
2718
        Map<Integer, List<Order>> allGrnPendingOrdersMap = orderRepository.selectPendingGrnOrders(allPartnerIds).stream()
2719
                .collect(Collectors.groupingBy(Order::getRetailerId));
2720
        LOGGER.info("Fetched GRN pending orders for {} partners", allGrnPendingOrdersMap.size());
2721
 
2722
        // Batch fetch all processing orders upfront
2723
        Map<Integer, List<Order>> allProcessingOrdersMap = orderRepository.selectOrders(allPartnerIds, orderStatusList).stream()
2724
                .collect(Collectors.groupingBy(Order::getRetailerId));
2725
        LOGGER.info("Fetched processing orders for {} partners", allProcessingOrdersMap.size());
2726
 
2727
        // Collect all focused catalog IDs
2728
        Set<Integer> allFocusedCatalogIds = regionFocusedModelsMap.values().stream()
2729
                .flatMap(List::stream)
2730
                .map(FocusedModel::getCatalogId)
2731
                .collect(Collectors.toSet());
2732
 
2733
        // Batch fetch all items by catalog IDs upfront
35446 amit 2734
        List<Item> allItemsByCatalogId = itemRepository.selectAllByCatalogIds(allFocusedCatalogIds);
2735
        Map<Integer, List<Item>> itemsByCatalogIdMap = allItemsByCatalogId.stream()
35442 amit 2736
                .collect(Collectors.groupingBy(Item::getCatalogItemId));
2737
        LOGGER.info("Fetched items for {} catalog IDs", itemsByCatalogIdMap.size());
2738
 
35446 amit 2739
        // Batch fetch all tagListings using pre-fetched items to avoid duplicate item fetch
35442 amit 2740
        Map<Integer, TagListing> tagListingByCatalogIdMap = tagListingRepository
35446 amit 2741
                .selectAllByItems(allItemsByCatalogId);
35442 amit 2742
        LOGGER.info("Fetched {} tagListings", tagListingByCatalogIdMap.size());
2743
 
2744
        // Collect all item IDs from inventory, GRN orders, and processing orders for batch item lookup
2745
        Set<Integer> allItemIds = new HashSet<>();
2746
        allInventorySnapshotsMap.values().forEach(list ->
2747
                list.forEach(cis -> allItemIds.add(cis.getItemId())));
2748
        allGrnPendingOrdersMap.values().forEach(orders ->
2749
                orders.forEach(o -> allItemIds.add(o.getLineItem().getItemId())));
2750
        allProcessingOrdersMap.values().forEach(orders ->
2751
                orders.forEach(o -> allItemIds.add(o.getLineItem().getItemId())));
2752
 
2753
        // Batch fetch all items and create itemId -> catalogId mapping
2754
        Map<Integer, Integer> itemIdToCatalogIdMap = new HashMap<>();
2755
        if (!allItemIds.isEmpty()) {
2756
            itemRepository.selectByIds(allItemIds).forEach(item ->
2757
                    itemIdToCatalogIdMap.put(item.getId(), item.getCatalogItemId()));
2758
        }
2759
        LOGGER.info("Built itemId->catalogId mapping for {} items", itemIdToCatalogIdMap.size());
2760
 
2761
        // ========== PHASE 2: Build partner region mappings ==========
34352 amit.gupta 2762
        Map<Integer, Set<Integer>> partnerToRegions = partnerRegionRepository.selectAll().stream()
2763
                .collect(Collectors.groupingBy(
2764
                        pr -> pr.getFofoId(),
2765
                        Collectors.mapping(pr -> pr.getRegionId(), Collectors.toSet())
2766
                ));
2767
        Map<Set<Integer>, List<Integer>> regionPartnerMap = partnerToRegions.entrySet().stream()
2768
                .collect(Collectors.groupingBy(
2769
                        Map.Entry::getValue,
2770
                        Collectors.mapping(Map.Entry::getKey, Collectors.toList())
2771
                ));
35442 amit 2772
        LOGGER.info("regionPartnerMap - {}", regionPartnerMap.keySet());
2773
 
2774
        // ========== PHASE 3: Process partners using pre-fetched data ==========
2775
        Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
2776
 
34352 amit.gupta 2777
        for (Map.Entry<Set<Integer>, List<Integer>> regionPartnerEntry : regionPartnerMap.entrySet()) {
2778
            Set<Integer> regionIds = regionPartnerEntry.getKey();
35442 amit 2779
            List<Integer> partnerIds = new ArrayList<>(regionPartnerEntry.getValue());
2780
 
34502 amit.gupta 2781
            if (regionIds.stream().anyMatch(x -> !regionFocusedModelsMap.containsKey(x))) continue;
34383 amit.gupta 2782
 
35442 amit 2783
            LOGGER.info("Processing regionIds: {}", regionIds);
2784
            if (regionIds == null || regionIds.isEmpty()) {
34352 amit.gupta 2785
                LOGGER.info("No region found for partner {}", partnerIds);
34343 amit.gupta 2786
                continue;
2787
            }
34502 amit.gupta 2788
            if (regionIds.contains(5)) {
34383 amit.gupta 2789
                partnerIds.addAll(fofoStoreMap.keySet());
2790
            }
35442 amit 2791
 
2792
            Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = regionIds.stream()
2793
                    .map(regionFocusedModelsMap::get)
2794
                    .flatMap(x -> x != null ? x.stream() : Stream.empty())
2795
                    .collect(groupingBy(FocusedModel::getCatalogId,
2796
                            mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
2797
 
2798
            if (focusedCatalogIdAndQtyMap.isEmpty()) continue;
2799
 
34352 amit.gupta 2800
            for (int partnerId : partnerIds) {
34502 amit.gupta 2801
                if (partnerId == 0) continue;
34352 amit.gupta 2802
                FofoStore fofoStore = fofoStoreMap.get(partnerId);
35442 amit 2803
                if (fofoStore == null) continue;
2804
 
2805
                CustomRetailer customRetailer = customRetailerMap.get(partnerId);
2806
                if (customRetailer == null) continue;
2807
 
34352 amit.gupta 2808
                List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
2809
                focusedModelShortageReportMap.put(fofoStore.getId(), focusedModelShortageList);
34343 amit.gupta 2810
 
35442 amit 2811
                // Build catalogIdAndQtyMap from pre-fetched inventory snapshots
2812
                Map<Integer, Integer> catalogIdAndQtyMap = new HashMap<>();
2813
                List<CurrentInventorySnapshot> inventorySnapshots = allInventorySnapshotsMap.get(partnerId);
2814
                if (inventorySnapshots != null) {
2815
                    Map<Integer, Integer> itemQtyMap = inventorySnapshots.stream()
2816
                            .collect(Collectors.toMap(CurrentInventorySnapshot::getItemId, CurrentInventorySnapshot::getAvailability));
2817
                    for (Map.Entry<Integer, Integer> e : itemQtyMap.entrySet()) {
2818
                        Integer catalogId = itemIdToCatalogIdMap.get(e.getKey());
2819
                        if (catalogId != null) {
2820
                            catalogIdAndQtyMap.merge(catalogId, e.getValue(), Integer::sum);
2821
                        }
2822
                    }
34352 amit.gupta 2823
                }
25721 tejbeer 2824
 
35442 amit 2825
                // Build grnPendingOrdersMap from pre-fetched orders
2826
                Map<Integer, Integer> grnPendingOrdersMap = new HashMap<>();
2827
                List<Order> grnOrders = allGrnPendingOrdersMap.get(partnerId);
2828
                if (grnOrders != null) {
2829
                    for (Order order : grnOrders) {
2830
                        Integer catalogId = itemIdToCatalogIdMap.get(order.getLineItem().getItemId());
2831
                        if (catalogId != null) {
2832
                            grnPendingOrdersMap.merge(catalogId, order.getLineItem().getQuantity(), Integer::sum);
2833
                        }
2834
                    }
34352 amit.gupta 2835
                }
25800 tejbeer 2836
 
35442 amit 2837
                // Build processingOrderMap from pre-fetched orders
2838
                Map<Integer, Integer> processingOrderMap = new HashMap<>();
2839
                List<Order> processingOrders = allProcessingOrdersMap.get(partnerId);
2840
                if (processingOrders != null) {
2841
                    for (Order order : processingOrders) {
2842
                        Integer catalogId = itemIdToCatalogIdMap.get(order.getLineItem().getItemId());
2843
                        if (catalogId != null) {
2844
                            processingOrderMap.merge(catalogId, order.getLineItem().getQuantity(), Integer::sum);
2845
                        }
2846
                    }
34352 amit.gupta 2847
                }
25721 tejbeer 2848
 
35442 amit 2849
                Map<Integer, List<SaholicCIS>> itemAvailabilityMap = warehouseItemAvailabilityMap.get(fofoStore.getWarehouseId());
2850
                Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap.get(fofoStore.getWarehouseId());
25721 tejbeer 2851
 
34352 amit.gupta 2852
                for (Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
35442 amit 2853
                    int catalogId = entry.getKey();
2854
                    int minQty = entry.getValue().orElse(0);
2855
                    int inStockQty = catalogIdAndQtyMap.getOrDefault(catalogId, 0);
2856
                    int processingQty = processingOrderMap.getOrDefault(catalogId, 0);
2857
                    int grnPendingQty = grnPendingOrdersMap.getOrDefault(catalogId, 0);
28526 tejbeer 2858
 
34352 amit.gupta 2859
                    int grnStockQty = grnPendingQty + inStockQty;
2860
                    int totalQty = processingQty + grnPendingQty + inStockQty;
2861
                    int shortageQty = minQty - totalQty;
27213 tejbeer 2862
 
35442 amit 2863
                    // Use pre-fetched items
2864
                    List<Item> items = itemsByCatalogIdMap.get(catalogId);
2865
                    if (items == null || items.isEmpty()) continue;
25721 tejbeer 2866
 
35442 amit 2867
                    // Use pre-fetched tagListing
2868
                    TagListing tagListing = tagListingByCatalogIdMap.get(catalogId);
2869
                    if (tagListing == null) continue;
27208 tejbeer 2870
 
35442 amit 2871
                    int allColorNetAvailability = 0;
2872
                    int allColorPoAvailability = 0;
28528 tejbeer 2873
 
34352 amit.gupta 2874
                    for (Item item : items) {
2875
                        if (itemAvailabilityMap != null) {
35442 amit 2876
                            List<SaholicCIS> currentAvailability = itemAvailabilityMap.get(item.getId());
2877
                            if (currentAvailability != null) {
2878
                                allColorNetAvailability += currentAvailability.stream()
2879
                                        .mapToInt(SaholicCIS::getNetavailability).sum();
2880
                            }
34352 amit.gupta 2881
                        }
2882
                        if (poItemAvailabilityMap != null) {
35442 amit 2883
                            List<SaholicPOItem> poItemAvailability = poItemAvailabilityMap.get(item.getId());
2884
                            if (poItemAvailability != null) {
2885
                                allColorPoAvailability += poItemAvailability.stream()
2886
                                        .mapToInt(SaholicPOItem::getUnfulfilledQty).sum();
2887
                            }
34352 amit.gupta 2888
                        }
31697 amit.gupta 2889
                    }
25721 tejbeer 2890
 
34352 amit.gupta 2891
                    FocusedModelShortageModel fm = new FocusedModelShortageModel();
2892
                    fm.setFofoId(fofoStore.getId());
2893
                    fm.setStoreCode(fofoStore.getCode());
2894
                    fm.setStoreName(customRetailer.getBusinessName());
2895
                    fm.setBrandName(items.get(0).getBrand());
2896
                    fm.setModelName(items.get(0).getModelName());
2897
                    fm.setModelNumber(items.get(0).getModelNumber());
2898
                    fm.setGrnStockQty(grnStockQty);
2899
                    fm.setPendingIndentQty(processingQty);
2900
                    fm.setShortageQty(shortageQty);
2901
                    fm.setPoAvailability(allColorPoAvailability);
2902
                    fm.setDp(tagListing.getSellingPrice());
2903
                    fm.setWarehouseName(warehouseMap.get(customRetailer.getWarehouseId()));
35442 amit 2904
 
2905
                    // FIX: Use fofoStore.getId() instead of fofoStore object as key
2906
                    FofoReportingModel reportingModel = partnerIdSalesHeadersMap.get(fofoStore.getId());
2907
                    if (reportingModel != null) {
2908
                        fm.setStateManager(reportingModel.getRegionalManager());
2909
                        fm.setTerritoryManager(reportingModel.getTerritoryManager());
34352 amit.gupta 2910
                    } else {
2911
                        fm.setStateManager("");
2912
                        fm.setTerritoryManager("");
31697 amit.gupta 2913
                    }
25800 tejbeer 2914
 
34352 amit.gupta 2915
                    fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
2916
                    fm.setAvailability(allColorNetAvailability);
25800 tejbeer 2917
 
34352 amit.gupta 2918
                    focusedModelShortageList.add(fm);
31697 amit.gupta 2919
                }
2920
            }
34352 amit.gupta 2921
        }
25721 tejbeer 2922
 
35442 amit 2923
        // ========== PHASE 4: Send emails ==========
2924
        LOGGER.info("focusedModelShortageReportMap size: {}", focusedModelShortageReportMap.size());
31697 amit.gupta 2925
        if (!focusedModelShortageReportMap.isEmpty()) {
2926
            String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
2927
            Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2928
            Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
28526 tejbeer 2929
 
35442 amit 2930
            for (Map.Entry<Integer, List<FocusedModelShortageModel>> x : focusedModelShortageReportMap.entrySet()) {
2931
                for (Map.Entry<String, Set<Integer>> y : storeGuyMap.entrySet()) {
2932
                    if (y.getValue().contains(x.getKey())) {
2933
                        emailRowsMap.computeIfAbsent(y.getKey(), k -> new ArrayList<>());
2934
                        List<List<? extends Serializable>> fms = x.getValue().stream()
2935
                                .map(r -> Arrays.asList(r.getStoreCode(), r.getStoreName(), r.getBrandName(),
2936
                                        r.getModelName(), r.getModelNumber(), r.getDp(), r.getWarehouseName(),
2937
                                        r.getStateManager(), r.getTerritoryManager(), r.getPendingIndentQty(),
2938
                                        r.getGrnStockQty(), r.getShortageQty(), r.getAvailability()))
2939
                                .collect(Collectors.toList());
2940
                        emailRowsMap.get(y.getKey()).addAll(fms);
2941
                    }
31697 amit.gupta 2942
                }
35442 amit 2943
            }
25721 tejbeer 2944
 
35442 amit 2945
            List<String> headers = Arrays.asList("Store Code", "Store Name", "Brand", "Model Name", "Model Number",
2946
                    "DP", "Warehouse Name", "State Manager", "Territory Manager", "Pending Indent", "InStock",
2947
                    "Shortage Qty", "Availability");
25721 tejbeer 2948
 
35442 amit 2949
            for (Map.Entry<String, List<List<?>>> entry : emailRowsMap.entrySet()) {
31697 amit.gupta 2950
                try {
35442 amit 2951
                    ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, entry.getValue());
2952
                    String[] sendToArray = new String[]{entry.getKey()};
2953
                    Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA",
2954
                            fileName, new ByteArrayResource(baos.toByteArray()));
2955
                } catch (Exception e) {
2956
                    LOGGER.error("Failed to send email to {}", entry.getKey(), e);
31697 amit.gupta 2957
                }
35442 amit 2958
            }
31697 amit.gupta 2959
        }
2960
    }
25721 tejbeer 2961
 
31697 amit.gupta 2962
    private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2963
        StringBuilder sb = new StringBuilder();
2964
        sb.append("Focused Model Shortage in Your Stock : \n");
2965
        for (FocusedModelShortageModel entry : focusedModelShortageModel) {
25721 tejbeer 2966
 
31697 amit.gupta 2967
            sb.append(entry.getItemName() + "-" + entry.getShortageQty());
2968
            sb.append(String.format("%n", ""));
2969
        }
2970
        return sb.toString();
2971
    }
25721 tejbeer 2972
 
31697 amit.gupta 2973
    private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
2974
        MimeMessage message = mailSender.createMimeMessage();
2975
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
25721 tejbeer 2976
 
31697 amit.gupta 2977
        helper.setSubject(subject);
2978
        helper.setText(messageText, true);
2979
        helper.setTo(email);
2980
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
2981
        helper.setFrom(senderAddress);
2982
        mailSender.send(message);
25721 tejbeer 2983
 
31697 amit.gupta 2984
    }
25721 tejbeer 2985
 
31697 amit.gupta 2986
    private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2987
        StringBuilder sb = new StringBuilder();
31886 tejbeer 2988
        sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
2989
        sb.append("<tbody>\n" + "	    				<tr>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n" + "	    				</tr>");
31697 amit.gupta 2990
        for (FocusedModelShortageModel entry : focusedModelShortageModel) {
25721 tejbeer 2991
 
31697 amit.gupta 2992
            sb.append("<tr>");
2993
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
25936 amit.gupta 2994
 
31697 amit.gupta 2995
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
26790 tejbeer 2996
 
31697 amit.gupta 2997
            sb.append("</tr>");
25927 amit.gupta 2998
 
31697 amit.gupta 2999
        }
26790 tejbeer 3000
 
31697 amit.gupta 3001
        sb.append("</tbody></table></body></html>");
26945 amit.gupta 3002
 
31697 amit.gupta 3003
        return sb.toString();
3004
    }
26945 amit.gupta 3005
 
31697 amit.gupta 3006
    public void notifyLead() throws Exception {
31886 tejbeer 3007
        List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
3008
        Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
31697 amit.gupta 3009
        LOGGER.info("authUserEmailMap {}", authUserEmailMap);
31886 tejbeer 3010
        Map<String, Integer> dtrEmailMap = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25982 amit.gupta 3011
 
31697 amit.gupta 3012
        LOGGER.info("dtrEmailMap {}", dtrEmailMap);
26283 tejbeer 3013
 
31697 amit.gupta 3014
        Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26283 tejbeer 3015
 
33452 amit.gupta 3016
        for (Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
31697 amit.gupta 3017
            int authId = authUserEmail.getKey();
3018
            String email = authUserEmail.getValue();
3019
            authUserKeyMap.put(authId, dtrEmailMap.get(email));
3020
        }
3021
        LOGGER.info("authUserKeyMap", authUserKeyMap);
3022
        LOGGER.info("leadsToNotify {}", leadsToNotify);
26283 tejbeer 3023
 
31697 amit.gupta 3024
        String templateMessage = "Lead followup for %s %s, %s, %s is due by %s";
3025
        for (Lead lead : leadsToNotify) {
3026
            if (authUserKeyMap.get(lead.getAssignTo()) == null) {
3027
                LOGGER.info("Assignee no longer part of system {}", lead.getAssignTo());
3028
                continue;
3029
            }
3030
            String title = "Leads followup Reminder";
31886 tejbeer 3031
            String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(), lead.getAddress(), lead.getLeadMobile(), leadTimeFormatter.format(lead.getScheduledTimestamp()));
31697 amit.gupta 3032
            String url = "https://app.smartdukaan.com/pages/home/leadUpdate?leadId=" + lead.getId();
3033
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
3034
            sendNotificationModel.setCampaignName("Lead Reminder");
3035
            sendNotificationModel.setTitle(title);
3036
            sendNotificationModel.setMessage(notificationMessage);
3037
            sendNotificationModel.setType("url");
3038
            sendNotificationModel.setUrl(url);
3039
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
3040
            sendNotificationModel.setMessageType(MessageType.reminder);
3041
            sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAssignTo())));
3042
            System.out.println(sendNotificationModel);
3043
            notificationService.sendNotification(sendNotificationModel);
3044
        }
3045
    }
26790 tejbeer 3046
 
32350 amit.gupta 3047
    @Autowired
3048
    AuthService authService;
3049
 
3050
    public void sendUnscheduledFollowUpMail() throws Exception {
3051
        List<Lead> missedScheduleLeads = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDate.now().atStartOfDay().minusDays(30), LocalDateTime.now().toLocalDate().atStartOfDay());
3052
        List<Lead> leadsScheduledForToday = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDate.now().atStartOfDay(), LocalDate.now().atTime(LocalTime.MAX));
3053
        List<Integer> authIds = missedScheduleLeads.stream().map(x -> x.getAssignTo()).distinct().collect(Collectors.toList());
3054
        LOGGER.info(authIds.size());
35393 amit 3055
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
32350 amit.gupta 3056
        LOGGER.info(authUserMap.size());
3057
        //if(true) return;
3058
 
3059
        missedScheduleLeads = missedScheduleLeads.stream().sorted(Comparator.comparing(Lead::getState, String.CASE_INSENSITIVE_ORDER).thenComparing(Lead::getAssignTo).thenComparing(Lead::getScheduledTimestamp)).collect(Collectors.toList());
3060
        //leadsScheduledForToday
3061
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
3062
        LOGGER.info("Auth Users Size - {}", authUsers.size());
3063
        for (AuthUser authUser : authUsers) {
3064
            LOGGER.info("Auth Name - {}", authUser.getFullName());
3065
            List<Integer> reporteeAuthIds = authService.getAllReportees(authUser.getId());
3066
            reporteeAuthIds.add(authUser.getId());
3067
            StringBuilder sb = new StringBuilder();
3068
            sb.append("<html><body>");
3069
            List<Lead> authMissedScheduledLeads = missedScheduleLeads.stream().filter(x -> reporteeAuthIds.contains(x.getAssignTo())).collect(Collectors.toList());
3070
            LOGGER.info("authMissedScheduledLeads {}", authMissedScheduledLeads.size());
3071
            if (authMissedScheduledLeads.size() > 0) {
3072
                addMissedScheduledLeadsTable(sb, authMissedScheduledLeads, authUserMap);
3073
                sb.append("</body></html>");
3074
 
3075
                String subject = "Lead Updates Summary";
32421 amit.gupta 3076
                String[] email = Arrays.asList(authUser.getEmailId()).toArray(new String[1]);
3077
                //String[] email = Arrays.asList("amit.gupta@smartdukaan.com").toArray(new String[1]);
32350 amit.gupta 3078
                this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
32421 amit.gupta 3079
                //break;
32350 amit.gupta 3080
            }
3081
        }
3082
 
3083
    }
3084
 
32482 amit.gupta 3085
    private void addMissedScheduledLeadsTable(StringBuilder
3086
                                                      sb, List<Lead> missedScheduleLeads, Map<Integer, AuthUser> authUserMap) {
32350 amit.gupta 3087
        sb.append("<h3>Leads That Missed the schedule</h3>");
32439 tejbeer 3088
        sb.append("<table style='border:1px solid black' cellspacing='0'>").append("<tr>").append("<th style='border:1px solid black;padding: 5px'>").append("Lead Id").append("</th>").append("<th style='border:1px solid black;padding: 5px'>").append("Lead Name").append("</th>").append("<th style='border:1px solid black;padding: 5px'>").append("Mobile No").append("</th>").append("<th style='border:1px solid black;padding: 5px'>").append("City").append("</th>").append("<th style='border:1px solid black;padding: 5px'>").append("State").append("</th>").append("<th style='border:1px solid black;padding: 5px'>").append("Created On").append("</th>").append("<th style='border:1px solid black;padding: 5px'>").append("Assigned To").append("</th>").append("<th style='border:1px solid black;padding: 5px'>").append("Scheduled On").append("</th>").append("</tr>");
32350 amit.gupta 3089
        for (Lead lead : missedScheduleLeads) {
32439 tejbeer 3090
            sb.append("<tr style='background-color:").append(lead.getColor()).append("'>").append("<td style='border:1px solid black;padding: 5px'>").append(lead.getId()).append("</td>").append("<td style='border:1px solid black;padding: 5px'>").append(lead.getFullName()).append("</td>").append("<td style='border:1px solid black;padding: 5px'>").append(lead.getLeadMobile()).append("</td>").append("<td style='border:1px solid black;padding: 5px'>").append(lead.getCity()).append("</td>").append("<td style='border:1px solid black;padding: 5px'>").append(lead.getState()).append("</td>").append("<td style='border:1px solid black;padding: 5px'>").append(FormattingUtils.formatDate(lead.getCreatedTimestamp())).append("</td>").append("<td style='border:1px solid black;padding: 5px'>").append(
3091
                    authUserMap.containsKey(lead.getAssignTo()) ? authUserMap.get(lead.getAssignTo()).getFullName() : lead.getAssignTo()).append("</td>").append("<td style='border:1px solid black;padding: 5px'>").append(FormattingUtils.formatDate(lead.getScheduledTimestamp())).append("</td>").append("</tr>");
32350 amit.gupta 3092
        }
3093
        sb.append("</table>");
3094
    }
3095
 
31697 amit.gupta 3096
    public void notifyVisits() throws Exception {
31886 tejbeer 3097
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
3098
        Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
3099
        Map<String, Integer> dtrEmailMap = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
31697 amit.gupta 3100
        Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26790 tejbeer 3101
 
33452 amit.gupta 3102
        for (Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
31697 amit.gupta 3103
            int authId = authUserEmail.getKey();
3104
            String email = authUserEmail.getValue();
3105
            authUserKeyMap.put(authId, dtrEmailMap.get(email));
3106
        }
3107
        String visitTemplate = "Planned visit to franchisee %s is due by %s";
3108
        String followupTemplate = "Lead followup for franchisee %s is due by %s";
3109
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
3110
        for (FranchiseeVisit visit : franchiseeVisits) {
3111
            if (authUserKeyMap.containsKey(visit.getAuthId())) {
3112
                continue;
3113
            }
3114
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
3115
            String message = null;
3116
            if (visit.getFranchiseActivityId() == 0) {
31886 tejbeer 3117
                message = String.format(visitTemplate, visit.getPartnerName(), timeFormatter.format(visit.getScheduleTimestamp()));
31697 amit.gupta 3118
                sendNotificationModel.setCampaignName("Franchisee visit Reminder");
3119
            } else {
31886 tejbeer 3120
                message = String.format(followupTemplate, visit.getPartnerName(), timeFormatter.format(visit.getScheduleTimestamp()));
31697 amit.gupta 3121
                sendNotificationModel.setCampaignName("Franchisee followup Reminder");
3122
            }
3123
            sendNotificationModel.setMessage(message);
3124
            sendNotificationModel.setType("url");
3125
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
3126
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
3127
            sendNotificationModel.setMessageType(MessageType.reminder);
3128
            sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
3129
            // notificationService.sendNotification(sendNotificationModel);
3130
        }
3131
    }
26792 tejbeer 3132
 
31697 amit.gupta 3133
    public void ticketClosed() throws Exception {
26790 tejbeer 3134
 
31697 amit.gupta 3135
        List<Ticket> tickets = ticketRepository.selectAllNotClosedTicketsWithStatus(ActivityType.RESOLVED);
3136
        for (Ticket ticket : tickets) {
3137
            if (ticket.getUpdateTimestamp().toLocalDate().isBefore(LocalDate.now().minusDays(7))) {
3138
                ticket.setCloseTimestamp(LocalDateTime.now());
3139
                ticket.setLastActivity(ActivityType.RESOLVED_ACCEPTED);
3140
                ticket.setUpdateTimestamp(LocalDateTime.now());
3141
                ticketRepository.persist(ticket);
3142
            }
3143
        }
26790 tejbeer 3144
 
31697 amit.gupta 3145
    }
26790 tejbeer 3146
 
31697 amit.gupta 3147
    public void checkValidateReferral() throws Exception {
26790 tejbeer 3148
 
31697 amit.gupta 3149
        List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
3150
        LOGGER.info("referrals" + referrals);
3151
        if (!referrals.isEmpty()) {
3152
            String subject = "Referral Request";
3153
            String messageText = this.getMessageForReferral(referrals);
26790 tejbeer 3154
 
31697 amit.gupta 3155
            MimeMessage message = mailSender.createMimeMessage();
3156
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
3157
            String[] email = {"kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com"};
3158
            helper.setSubject(subject);
3159
            helper.setText(messageText, true);
3160
            helper.setTo(email);
3161
            InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
3162
            helper.setFrom(senderAddress);
3163
            mailSender.send(message);
26790 tejbeer 3164
 
31697 amit.gupta 3165
        }
3166
    }
26790 tejbeer 3167
 
31697 amit.gupta 3168
    private String getMessageForReferral(List<Refferal> referrals) {
3169
        StringBuilder sb = new StringBuilder();
31886 tejbeer 3170
        sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
3171
        sb.append("<tbody>\n" + "	    				<tr>\n" + "	    					<th style='border:1px solid black;padding: 5px'>RefereeName</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Referee Email</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Referral Name</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Refferal Mobile</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>city</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>state</th>\n" + "	    				</tr>");
31697 amit.gupta 3172
        for (Refferal entry : referrals) {
26790 tejbeer 3173
 
31697 amit.gupta 3174
            sb.append("<tr>");
3175
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
30421 tejbeer 3176
 
31697 amit.gupta 3177
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
3178
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
3179
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
3180
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
3181
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
30421 tejbeer 3182
 
31697 amit.gupta 3183
            sb.append("</tr>");
30421 tejbeer 3184
 
31697 amit.gupta 3185
        }
30421 tejbeer 3186
 
31697 amit.gupta 3187
        sb.append("</tbody></table></body></html>");
30421 tejbeer 3188
 
31697 amit.gupta 3189
        return sb.toString();
3190
    }
30421 tejbeer 3191
 
32832 amit.gupta 3192
    private String getMessageForRBMEscalatedPartners(List<PartnerCollectionRemark> pcrs) throws
32482 amit.gupta 3193
            ProfitMandiBusinessException {
31697 amit.gupta 3194
        StringBuilder sb = new StringBuilder();
32832 amit.gupta 3195
        sb.append("<html><body><p>Alert</p><p>Escalated by RBM-L1:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
3196
        sb.append("<tbody>" +
3197
                "<tr>" +
3198
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
3199
                "<th style='border:1px solid black;padding: 5px'>Escalated Since</th>" +
3200
                "<th style='border:1px solid black;padding: 5px'>Message</th>" +
3201
                "</tr>");
30421 tejbeer 3202
 
31697 amit.gupta 3203
        for (PartnerCollectionRemark entry : pcrs) {
30421 tejbeer 3204
 
31697 amit.gupta 3205
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30421 tejbeer 3206
 
31697 amit.gupta 3207
            sb.append("<tr>");
31886 tejbeer 3208
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
3209
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
32832 amit.gupta 3210
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMessage() + "</td>");
28205 tejbeer 3211
 
31697 amit.gupta 3212
            sb.append("</tr>");
28205 tejbeer 3213
 
31697 amit.gupta 3214
        }
28205 tejbeer 3215
 
31697 amit.gupta 3216
        sb.append("</tbody></table></body></html>");
28205 tejbeer 3217
 
31697 amit.gupta 3218
        return sb.toString();
3219
    }
28208 tejbeer 3220
 
32795 amit.gupta 3221
    private String getMessageForSalesEscalatedPartners(List<PartnerCollectionRemark> pcrs) throws
3222
            ProfitMandiBusinessException {
3223
        StringBuilder sb = new StringBuilder();
3224
        sb.append("<html><body><p>Alert</p><p>Escalated to Sales Team:-</p>" + "<br/>" +
3225
                "<table style='border:1px solid black ;padding: 5px';>");
3226
        sb.append("<tbody>" +
3227
                "<tr>" +
3228
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
3229
                "<th style='border:1px solid black;padding: 5px'>Escalated Since</th>" +
3230
                "<th style='border:1px solid black;padding: 5px'>Message</th>" +
3231
                "</tr>");
3232
        for (PartnerCollectionRemark entry : pcrs) {
3233
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
3234
            sb.append("<tr>");
3235
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
3236
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
3237
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMessage() + "</td>");
3238
            sb.append("</tr>");
3239
        }
3240
 
3241
        sb.append("</tbody></table></body></html>");
3242
 
3243
        return sb.toString();
3244
    }
3245
 
33078 ranu 3246
    private String getMessageForUnauthorizedBuying(List<NonSdBuying> nsb) throws
3247
            ProfitMandiBusinessException {
3248
        StringBuilder sb = new StringBuilder();
3249
        sb.append("<html><body><p>Alert</p><p>Unauthorized Buying-</p>" + "<br/>" +
3250
                "<table style='border:1px solid black ;padding: 5px';>");
3251
        sb.append("<tbody>" +
3252
                "<tr>" +
3253
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
3254
                "<th style='border:1px solid black;padding: 5px'>Brand Name</th>" +
3255
                "<th style='border:1px solid black;padding: 5px'>Brand Value</th>" +
3256
                "<th style='border:1px solid black;padding: 5px'>Created At</th>" +
3257
                "<th style='border:1px solid black;padding: 5px'>Reason</th>" +
3258
                "</tr>");
3259
        for (NonSdBuying entry : nsb) {
3260
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
3261
            List<Integer> brandIds = Collections.singletonList(entry.getBrandId());
3262
            BrandCatalog brandsDisplay = brandsRepository.selectByIds(brandIds).get(0);
3263
            sb.append("<tr>");
3264
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
3265
            sb.append("<td style='border:1px solid black;padding: 5px'>" + brandsDisplay.getName() + "</td>");
3266
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getBrandValue() + "</td>");
3267
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
3268
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getReason() + "</td>");
3269
            sb.append("</tr>");
3270
        }
3271
 
3272
        sb.append("</tbody></table></body></html>");
3273
 
3274
        return sb.toString();
3275
    }
3276
 
31697 amit.gupta 3277
    public void reverseWallet() throws Exception {
3278
        LocalDate localDate = LocalDate.of(2020, 10, 28);
31886 tejbeer 3279
        List<UserWalletHistory> uwhList = userWalletHistoryRepository.selectAllByDateType(localDate.atStartOfDay(), localDate.plusDays(1).atStartOfDay(), Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
31697 amit.gupta 3280
        for (UserWalletHistory uwh : uwhList) {
3281
            if (uwh.getBusinessTimestamp().getMonth().equals(Month.SEPTEMBER)) {
3282
                UserWallet uw = userWalletRepository.selectById(uwh.getWalletId());
3283
                // LOGGER.info("UWH - {}", uwh);
3284
                // amount += uwh.getAmount();
3285
                // System.out.println("Amount is - " + amount);
3286
                // walletService.rollbackAmountFromWallet(uw.getUserId(), uwh.getAmount(),
3287
                // uwh.getReference(), uwh.getReferenceType(), "Margin reversal for error prone
3288
                // run", uwh.getBusinessTimestamp());
3289
                int orderId = uwh.getReference();
3290
                FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
3291
                int inventoryItemId = 0;
3292
                // fofoOrderRepository.delete(fofoOrder);
3293
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3294
                /*
3295
                 * List<PaymentOptionTransaction> paymentOptionTransactions =
3296
                 * paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId
3297
                 * (), PaymentOptionReferenceType.ORDER); for(PaymentOptionTransaction
3298
                 * paymentOptionTransaction : paymentOptionTransactions) {
3299
                 * //paymentOptionTransactionRepository.delete(paymentOptionTransaction); }
3300
                 */
3301
                for (FofoOrderItem foi : fofoOrderItems) {
3302
                    // fofoOrderItemRepository.delete(foi);
3303
                    List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
3304
                    for (FofoLineItem fli : flis) {
3305
                        // fofoLineItemRepository.delete(fli);
3306
                        inventoryItemId = fli.getInventoryItemId();
3307
                    }
3308
                }
3309
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(
33452 amit.gupta 3310
                        Stream.of(inventoryItemId).collect(Collectors.toSet()));
31697 amit.gupta 3311
                for (SchemeInOut sio : schemeInOuts) {
3312
                    if (sio.getCreateTimestamp().toLocalDate().equals(localDate)) {
3313
                        LOGGER.info("SIO - {}", sio);
3314
                        sio.setRolledBackTimestamp(LocalDateTime.now());
3315
                    }
3316
                }
28208 tejbeer 3317
 
31697 amit.gupta 3318
            }
3319
        }
28208 tejbeer 3320
 
31697 amit.gupta 3321
    }
28208 tejbeer 3322
 
31697 amit.gupta 3323
    public void partnerProblemAlert() throws Exception {
3324
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
3325
        Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
3326
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
31886 tejbeer 3327
        Map<Integer, Double> mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), 0, false);
3328
        Map<Integer, PartnerDailyInvestment> pdi = partnerDailyInvestmentRepository.selectAll(LocalDate.now()).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 3329
 
31697 amit.gupta 3330
        for (Entry<Integer, Double> ls : lmtdSale.entrySet()) {
28208 tejbeer 3331
 
31697 amit.gupta 3332
            double lmtdTwentyPercentSale = ls.getValue() * 0.2;
28208 tejbeer 3333
 
31697 amit.gupta 3334
            LOGGER.info("lmtdTwentyPercentSale" + lmtdTwentyPercentSale);
28208 tejbeer 3335
 
31697 amit.gupta 3336
            double mtdSale = mtdSales.get(ls.getKey()) == null ? 0 : mtdSales.get(ls.getKey());
28205 tejbeer 3337
 
31697 amit.gupta 3338
            LOGGER.info("mtdSale" + mtdSale);
28205 tejbeer 3339
 
31886 tejbeer 3340
            double totalSixtyPercentInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getTotalInvestment() * 0.6;
28205 tejbeer 3341
 
31697 amit.gupta 3342
            LOGGER.info("totalSixtyPercentInvestment" + totalSixtyPercentInvestment);
28205 tejbeer 3343
 
31697 amit.gupta 3344
            double stockInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getInStockAmount();
28205 tejbeer 3345
 
31697 amit.gupta 3346
            LOGGER.info("stockInvestment" + stockInvestment);
28205 tejbeer 3347
 
31697 amit.gupta 3348
            boolean Investmentvalue = partnerInvestmentService.isInvestmentBelow(ls.getKey(), 25);
28205 tejbeer 3349
 
31697 amit.gupta 3350
            PartnerProblem partnerProblem = partnerProblemRepository.selectByFofoId(ls.getKey());
28205 tejbeer 3351
 
31697 amit.gupta 3352
            if (partnerProblem == null) {
3353
                partnerProblem = new PartnerProblem();
3354
                partnerProblem.setFofoId(ls.getKey());
3355
                if (mtdSale < lmtdTwentyPercentSale) {
3356
                    partnerProblem.setMtd(1);
3357
                }
3358
                if (Investmentvalue) {
3359
                    partnerProblem.setInvestment(1);
3360
                }
28205 tejbeer 3361
 
31697 amit.gupta 3362
                if (stockInvestment < totalSixtyPercentInvestment) {
3363
                    partnerProblem.setInvestment(1);
3364
                }
28205 tejbeer 3365
 
31697 amit.gupta 3366
                partnerProblemRepository.persist(partnerProblem);
3367
            } else {
3368
                if (mtdSale < lmtdTwentyPercentSale) {
3369
                    partnerProblem.setMtd(partnerProblem.getMtd() + 1);
28213 tejbeer 3370
 
31697 amit.gupta 3371
                } else {
3372
                    partnerProblem.setMtd(0);
28227 tejbeer 3373
 
31697 amit.gupta 3374
                }
3375
                if (Investmentvalue) {
3376
                    partnerProblem.setInvestment(partnerProblem.getInvestment() + 1);
3377
                } else {
3378
                    partnerProblem.setInvestment(0);
28227 tejbeer 3379
 
31697 amit.gupta 3380
                }
3381
                if (stockInvestment < totalSixtyPercentInvestment) {
3382
                    partnerProblem.setStockInvestment(partnerProblem.getStockInvestment() + 1);
3383
                } else {
3384
                    partnerProblem.setStockInvestment(0);
3385
                }
28213 tejbeer 3386
 
31697 amit.gupta 3387
            }
28213 tejbeer 3388
 
31697 amit.gupta 3389
        }
28213 tejbeer 3390
 
31886 tejbeer 3391
        List<PartnerProblem> partnerProblems = partnerProblemRepository.selectAll().stream().filter(x -> x.getMtd() + x.getInvestment() + x.getStockInvestment() > 0).collect(Collectors.toList());
28205 tejbeer 3392
 
31697 amit.gupta 3393
        partnerProblems = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 3394
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 3395
        }).collect(Collectors.toList());
28205 tejbeer 3396
 
31697 amit.gupta 3397
        Map<Integer, PartnerProblem> partnerProblemMap = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 3398
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 3399
        }).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 3400
 
31697 amit.gupta 3401
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
28205 tejbeer 3402
 
31697 amit.gupta 3403
        List<Integer> assignTo = Arrays.asList(15, 9, 54, 53);
28205 tejbeer 3404
 
35393 amit 3405
        Map<Integer, AuthUser> assignAuthUserMap = authRepository.selectByIds(assignTo).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
28222 tejbeer 3406
 
31886 tejbeer 3407
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "sm@smartdukaan.com");
31697 amit.gupta 3408
        LOGGER.info("partnerProblem" + partnerProblems);
3409
        StringBuilder sb = new StringBuilder();
3410
        sb.append("<htl><body>");
3411
        sb.append(
3412
                "<p>Number against MTD or Investment are the count of days the MTD is low VS LMTD OR Investment is below 75%.</p><br/><p>These partners needs immediate attention.</p><br/><table style='border:1px solid black';cellspacing=0>");
31886 tejbeer 3413
        sb.append("<tbody>\n" + "	    <tr>" + "	    					<th style='border:1px solid black;padding: 5px'>Partner Name</th>" + "                         <th style='border:1px solid black;padding: 5px'>Assign TO</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Mtd</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Investment</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Stock</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Manager</th>"
28218 tejbeer 3414
 
31697 amit.gupta 3415
                + "	    				</tr>");
28218 tejbeer 3416
 
31697 amit.gupta 3417
        for (PartnerProblem pp : partnerProblems) {
3418
            int value = pp.getFofoId() % 4;
28218 tejbeer 3419
 
31697 amit.gupta 3420
            Map<EscalationType, AuthUser> authUserMap = csService.getAuthUserAndEsclationByPartnerId(pp.getFofoId());
3421
            LOGGER.info("authUserMap" + authUserMap);
3422
            sb.append("<tr>");
31886 tejbeer 3423
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
3424
            sb.append("<td style='border:1px solid black;padding: 5px'>" + assignAuthUserMap.get(assignTo.get(value)).getName() + "</td>");
31697 amit.gupta 3425
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
3426
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
3427
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
31886 tejbeer 3428
            sb.append("<td style='border:1px solid black;padding: 5px'>" + (authUserMap.get(EscalationType.L1) == null ? "N/A" : authUserMap.get(EscalationType.L1).getFirstName()) + " ," + (authUserMap.get(EscalationType.L2) == null ? "N/A" : authUserMap.get(EscalationType.L2).getFirstName()) + "</td>");
28218 tejbeer 3429
 
31697 amit.gupta 3430
            sb.append("</tr>");
3431
        }
3432
        sb.append("</tbody></table><br><br>");
3433
        String subject = "Partner Problem Alert!";
3434
        String[] email = sendTo.toArray(new String[sendTo.size()]);
28227 tejbeer 3435
 
32350 amit.gupta 3436
        this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
28227 tejbeer 3437
 
31697 amit.gupta 3438
        Map<Integer, List<Integer>> authUserPartnerMapping = csService.getAuthUserIdPartnerIdMapping();
28224 tejbeer 3439
 
31697 amit.gupta 3440
        for (Entry<Integer, List<Integer>> authUserPartner : authUserPartnerMapping.entrySet()) {
3441
            AuthUser authUser = authRepository.selectById(authUserPartner.getKey());
3442
            for (Integer patnerId : authUserPartner.getValue()) {
3443
                if (partnerProblemMap.get(patnerId) != null) {
28230 tejbeer 3444
 
31697 amit.gupta 3445
                    StringBuilder sbbuilder = new StringBuilder();
3446
                    sbbuilder.append("<hml><body>");
3447
                    sb.append(
3448
                            "<p>Number against MTD or Investment are the count of days the MTD is low VS LMTD OR Investment is below 75%.</p><br/><p>These partners needs immediate attention.</p><br/><table style='border:1px solid black';cellspacing=0>");
31886 tejbeer 3449
                    sbbuilder.append("<tbody>\n" + "	    <tr>" + "	    					<th style='border:1px solid black;padding: 5px'>Partner Name</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Mtd</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Investment</th>" + "	    					<th style='border:1px solid black;padding: 5px'>Stock</th>"
28218 tejbeer 3450
 
31697 amit.gupta 3451
                            + "	    				</tr>");
28205 tejbeer 3452
 
31697 amit.gupta 3453
                    for (Integer partnerId : authUserPartner.getValue()) {
3454
                        if (partnerProblemMap.get(partnerId) != null) {
3455
                            PartnerProblem pp = partnerProblemMap.get(partnerId);
3456
                            sbbuilder.append("<tr>");
31886 tejbeer 3457
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
3458
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
31697 amit.gupta 3459
                            sbbuilder.append(
3460
                                    "<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
31886 tejbeer 3461
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
28790 amit.gupta 3462
 
31697 amit.gupta 3463
                            sbbuilder.append("</tr>");
3464
                        }
28790 amit.gupta 3465
 
31697 amit.gupta 3466
                    }
3467
                    sbbuilder.append("</tbody></table><br><br>");
29488 manish 3468
 
32350 amit.gupta 3469
                    this.sendMailOfHtmlFormat(googleMailSender, new String[]{authUser.getEmailId()}, sbbuilder.toString(), null, subject);
31697 amit.gupta 3470
                }
29488 manish 3471
 
31697 amit.gupta 3472
            }
3473
        }
3474
    }
28775 amit.gupta 3475
 
31697 amit.gupta 3476
    @Autowired
3477
    WarehouseRepository warehouseRepository;
29488 manish 3478
 
33256 amit.gupta 3479
    public void getVendorWarehouses(int warehouseId) throws ProfitMandiBusinessException {
31697 amit.gupta 3480
        LOGGER.info("Warehouses - {}", warehouseRepository.getVendorWarehouses().get(warehouseId));
29488 manish 3481
 
31697 amit.gupta 3482
    }
29488 manish 3483
 
31697 amit.gupta 3484
    public void checkImeiActivation() {
29801 manish 3485
 
31697 amit.gupta 3486
        try {
3487
            vivoImeiActivationService.checkImeiActivation();
3488
        } catch (ProfitMandiBusinessException e) {
3489
            // TODO Auto-generated catch block
3490
            e.printStackTrace();
3491
        } catch (IOException e) {
3492
            // TODO Auto-generated catch block
3493
            e.printStackTrace();
3494
        } catch (Exception e) {
3495
            // TODO Auto-generated catch block
3496
            e.printStackTrace();
3497
        }
29807 manish 3498
 
31697 amit.gupta 3499
    }
29801 manish 3500
 
31697 amit.gupta 3501
    public void checkItelImeiActivation(LocalDate date, Integer day) {
3502
        LOGGER.info("Hello - {}", "hhh");
29488 manish 3503
 
31697 amit.gupta 3504
        try {
3505
            itelImeiActivationService.checkItelImeiActivation(date, day);
3506
        } catch (ProfitMandiBusinessException e) {
3507
            // TODO Auto-generated catch block
3508
            e.printStackTrace();
3509
        } catch (IOException e) {
3510
            // TODO Auto-generated catch block
3511
            e.printStackTrace();
3512
        } catch (Exception e) {
3513
            // TODO Auto-generated catch block
3514
            e.printStackTrace();
3515
        }
29488 manish 3516
 
31697 amit.gupta 3517
    }
29488 manish 3518
 
32482 amit.gupta 3519
    public void selectFinServiceFollowUpDateByCurrDate(LocalDate currentDate) throws
3520
            MessagingException, ProfitMandiBusinessException, IOException {
31697 amit.gupta 3521
        LOGGER.info("selectfinServiceFollow - {}", "selectfinServiceFollowUpDateByCurrDate");
29308 tejbeer 3522
 
31697 amit.gupta 3523
        serviceConfigService.selectFinServicePartnerfollowUpDateByCurrentDate(currentDate);
29252 amit.gupta 3524
 
31697 amit.gupta 3525
    }
29451 manish 3526
 
31697 amit.gupta 3527
    public void checkTecnoImeiActivation(LocalDate date, Integer day) {
3528
        LOGGER.info("Hello - {}", "hhh");
29308 tejbeer 3529
 
31697 amit.gupta 3530
        try {
3531
            tecnoImeiActivation.checkTecnoImeiActivation(date, day);
3532
        } catch (ProfitMandiBusinessException e) {
3533
            // TODO Auto-generated catch block
3534
            e.printStackTrace();
3535
        } catch (IOException e) {
3536
            // TODO Auto-generated catch block
3537
            e.printStackTrace();
3538
        } catch (Exception e) {
3539
            // TODO Auto-generated catch block
3540
            e.printStackTrace();
3541
        }
29308 tejbeer 3542
 
31697 amit.gupta 3543
    }
29441 tejbeer 3544
 
31697 amit.gupta 3545
    public void checkCancellationMargin() throws Exception {
3546
        LocalDateTime startDate = LocalDate.of(2021, 4, 1).atStartOfDay();
3547
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectCancelledBetweenSaleDate(startDate, LocalDateTime.now());
3548
        LOGGER.info("Total Orders =  {}", fofoOrders.size());
3549
        for (FofoOrder fofoOrder : fofoOrders) {
31886 tejbeer 3550
            List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
3551
            history.addAll(userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.ACTIVATION_SCHEME));
31697 amit.gupta 3552
            int walletSum = history.stream().mapToInt(x -> x.getAmount()).sum();
3553
            if (Math.abs(walletSum) > 1) {
3554
                // LOGGER.info("Cancelled invoice {}, Order Id = {}, = havent rolledback, Value
3555
                // = {}", fofoOrder.getInvoiceNumber(), fofoOrder.getId(), walletSum);
3556
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3557
                List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(fofoOrderItems.get(0).getId());
3558
                FofoLineItem fli = flis.get(0);
3559
                if (StringUtils.isEmpty(fli.getSerialNumber()))
3560
                    continue;
31886 tejbeer 3561
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(fli.getInventoryItemId())));
31697 amit.gupta 3562
                InventoryItem inventoryItem = inventoryItemRepository.selectById(fli.getInventoryItemId());
31886 tejbeer 3563
                double schemeSum = schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).mapToDouble(x -> x.getAmount()).sum();
31697 amit.gupta 3564
                /*
3565
                 * if(inventoryItem.getGoodQuantity()==1) {
3566
                 * LOGGER.info("GoodQty, Serial Number {}, InventoryItem = {}, Billed on {}",
3567
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3568
                 * inventoryItem.getUpdateTimestamp()); } else
3569
                 * if(inventoryItem.getBadQuantity()==1){
3570
                 * LOGGER.info("Bad Qty, Serial Number {}, InventoryItem = {}, Billed on {}",
3571
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3572
                 * inventoryItem.getUpdateTimestamp()); } else if
3573
                 * (inventoryItem.getLastScanType().equals(ScanType.SALE)) { LOGGER.
3574
                 * info("Problem Sold, Serial Number {}, InventoryItem = {}, Billed on {}",
3575
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3576
                 * inventoryItem.getUpdateTimestamp()); }
3577
                 */
31886 tejbeer 3578
                if (inventoryItem.getLastScanType().equals(ScanType.SALE) || inventoryItem.getLastScanType().equals(ScanType.SALE_RET)) {
3579
                    Map<String, Double> map = schemeInOuts.stream().collect(
3580
                            groupingBy(
3581
                                    x -> DateTimeFormatter.ofPattern("yyyyMMddHH").format(x.getCreateTimestamp()) + "- " + x.getSchemeId(), Collectors.summingDouble(x -> x.getAmount())));
33452 amit.gupta 3582
                    for (Entry<String, Double> entry : map.entrySet()) {
31697 amit.gupta 3583
                        LOGGER.info("{} = {}", entry.getKey(), entry.getValue());
3584
                    }
31886 tejbeer 3585
                    LOGGER.info("id- {}, imei- {}, lastScan = {}, Scheme sum - {}", inventoryItem.getId(), inventoryItem.getSerialNumber(), inventoryItem.getLastScanType(), schemeSum);
31697 amit.gupta 3586
                }
3587
            }
3588
        }
29441 tejbeer 3589
 
31697 amit.gupta 3590
    }
29308 tejbeer 3591
 
31697 amit.gupta 3592
    public static String readFileAsString(String file) throws Exception {
3593
        String data = "";
3594
        data = new String(Files.readAllBytes(Paths.get(file)));
3595
        return data;
3596
    }
29308 tejbeer 3597
 
31697 amit.gupta 3598
    @Autowired
3599
    private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
30421 tejbeer 3600
 
32832 amit.gupta 3601
    //RBM L2 Escalations
32482 amit.gupta 3602
    public void reviewUncontactablePartner() throws
3603
            ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
30421 tejbeer 3604
 
31697 amit.gupta 3605
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
30421 tejbeer 3606
 
32832 amit.gupta 3607
        List<Integer> partnerLastCollectionRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(customRetailerMap.keySet()));
30859 tejbeer 3608
 
32832 amit.gupta 3609
        if (!partnerLastCollectionRemarkIds.isEmpty()) {
3610
            List<PartnerCollectionRemark> partnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(partnerLastCollectionRemarkIds);
30421 tejbeer 3611
 
33064 ranu 3612
            Map<Integer, PartnerCollectionRemark> rbmEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.RBM_L2_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
32832 amit.gupta 3613
            Map<Integer, PartnerCollectionRemark> salesEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.SALES_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30859 tejbeer 3614
 
32832 amit.gupta 3615
 
3616
            if (!rbmEscalatedRemarksMap.isEmpty()) {
3617
                //
33452 amit.gupta 3618
                for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM), true).entrySet()) {
32832 amit.gupta 3619
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
3620
                            .map(x -> rbmEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
3621
                    String subject = "Partners escalated to RBM-L2";
3622
                    String messageText = this.getMessageForRBMEscalatedPartners(filteredRows);
3623
 
31697 amit.gupta 3624
                    MimeMessage message = mailSender.createMimeMessage();
3625
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
3626
                    String[] email = new String[]{storeGuyEntry.getKey()};
30859 tejbeer 3627
 
31697 amit.gupta 3628
                    helper.setSubject(subject);
3629
                    helper.setText(messageText, true);
3630
                    helper.setTo(email);
31886 tejbeer 3631
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
31697 amit.gupta 3632
                    helper.setFrom(senderAddress);
3633
                    mailSender.send(message);
30859 tejbeer 3634
 
31697 amit.gupta 3635
                    LOGGER.info("filteredRows {}", filteredRows);
30859 tejbeer 3636
 
31697 amit.gupta 3637
                }
3638
            }
32832 amit.gupta 3639
            if (!salesEscalatedRemarksMap.isEmpty()) {
3640
                //
35521 amit 3641
                for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM, ProfitMandiConstants.TICKET_CATEGORY_RBM), true).entrySet()) {
32832 amit.gupta 3642
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
3643
                            .map(x -> salesEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
3644
                    String subject = "Partners escalated to Sales";
3645
                    String messageText = this.getMessageForSalesEscalatedPartners(filteredRows);
30936 tejbeer 3646
 
32832 amit.gupta 3647
                    MimeMessage message = mailSender.createMimeMessage();
3648
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
3649
                    String[] email = new String[]{storeGuyEntry.getKey()};
3650
 
3651
                    helper.setSubject(subject);
3652
                    helper.setText(messageText, true);
3653
                    helper.setTo(email);
3654
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
3655
                    helper.setFrom(senderAddress);
3656
                    mailSender.send(message);
3657
 
3658
                    LOGGER.info("filteredRows {}", filteredRows);
3659
 
3660
                }
3661
            }
3662
 
31697 amit.gupta 3663
        }
3664
    }
30936 tejbeer 3665
 
33078 ranu 3666
 
31697 amit.gupta 3667
    @Autowired
33078 ranu 3668
    private NonSdBuyingRepository nonSdBuyingRepository;
3669
 
3670
    //Non Sd Buying
3671
    public void reviewNonSdBuyingBrand() throws
3672
            ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
3673
        List<NonSdBuying> nonSdByuingActiveList = nonSdBuyingRepository.selectAllActiveNonSDBuyingList(true);
3674
        Map<Integer, NonSdBuying> unAuthorizedBuyingMap = nonSdByuingActiveList.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3675
 
3676
        if (!unAuthorizedBuyingMap.isEmpty()) {
35521 amit 3677
            for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM), true).entrySet()) {
33078 ranu 3678
                List<NonSdBuying> unAuthorizedfilteredRows = storeGuyEntry.getValue().stream()
3679
                        .map(x -> unAuthorizedBuyingMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
33112 amit.gupta 3680
                if (!unAuthorizedfilteredRows.isEmpty()) {
33078 ranu 3681
                    String subject = "Unauthorized Buying";
3682
                    String messageText = this.getMessageForUnauthorizedBuying(unAuthorizedfilteredRows);
3683
 
3684
                    MimeMessage message = mailSender.createMimeMessage();
3685
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
3686
                    String[] email = new String[]{storeGuyEntry.getKey()};
3687
 
3688
                    helper.setSubject(subject);
3689
                    helper.setText(messageText, true);
3690
                    helper.setTo(email);
3691
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
3692
                    helper.setFrom(senderAddress);
3693
                    mailSender.send(message);
3694
                    LOGGER.info("unAuthorizedfilteredRows {}", unAuthorizedfilteredRows);
3695
                }
3696
 
3697
 
3698
            }
3699
 
3700
        }
3701
    }
3702
 
3703
    @Autowired
31697 amit.gupta 3704
    private LoanRepository loanRepository;
31020 tejbeer 3705
 
31697 amit.gupta 3706
    @Autowired
3707
    private LoanStatementRepository loanStatementRepository;
30859 tejbeer 3708
 
31697 amit.gupta 3709
    @Autowired
3710
    private SDCreditRequirementRepository sdCreditRequirementRepository;
30859 tejbeer 3711
 
31697 amit.gupta 3712
    @Autowired
3713
    private CurrentPartnerDailyInvestmentRepository currentPartnerDailyInvestmentRepository;
30859 tejbeer 3714
 
31697 amit.gupta 3715
    @Autowired
3716
    private TransactionRepository transactionRepository;
30859 tejbeer 3717
 
31697 amit.gupta 3718
    @Autowired
3719
    private SanctionRequestRepository sanctionRequestRepository;
30859 tejbeer 3720
 
31697 amit.gupta 3721
    public void calculateInterestAccured() throws ProfitMandiBusinessException {
34755 amit.gupta 3722
        List<Loan> loans = loanRepository.selectAllActiveLoan();
3723
        //List<Loan> loans = Arrays.asList(loanRepository.selectByLoanId(52669));
30859 tejbeer 3724
 
32724 amit.gupta 3725
        for (Loan loan : loans) {
3726
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
3727
            Map<LoanReferenceType, Double> loanStatusAmount = loanStatements.stream().collect(groupingBy(
3728
                    x -> x.getLoanReferenceType(), Collectors.summingDouble(x -> x.getAmount().doubleValue())));
30936 tejbeer 3729
 
32724 amit.gupta 3730
            int freeDays = loan.getFreeDays();
30936 tejbeer 3731
 
34710 amit.gupta 3732
            LocalDate freeDaysLimitDate = loan.getCreatedOn().plusDays(freeDays).toLocalDate();
30936 tejbeer 3733
 
34710 amit.gupta 3734
            LOGGER.info("Loan id - {}, freeDaysLimitDate {}", loan.getId(), freeDaysLimitDate);
3735
            if (LocalDate.now().isAfter(freeDaysLimitDate)) {
32724 amit.gupta 3736
                int loanStatementId = loanStatementRepository.selectLatestLoanSatement(loan.getFofoId(), loan.getId());
3737
                LOGGER.info("loanStatementId {}", loanStatementId);
3738
                if (loanStatementId != 0) {
3739
                    this.calculateInterest(loan, loanStatusAmount, loanStatementId);
31697 amit.gupta 3740
                } else {
34710 amit.gupta 3741
                    sdCreditService.addInterest(freeDaysLimitDate, LocalDate.now(), loan, loanStatusAmount);
31697 amit.gupta 3742
                }
32724 amit.gupta 3743
            }
31697 amit.gupta 3744
        }
3745
    }
30936 tejbeer 3746
 
31697 amit.gupta 3747
    @Autowired
3748
    FofoPaymentRepository fofoPaymentRepository;
30936 tejbeer 3749
 
31697 amit.gupta 3750
    @Autowired
3751
    CCAvenuePaymentService ccAvenuePaymentService;
30936 tejbeer 3752
 
31697 amit.gupta 3753
    public void settleCCAvePayments() throws Exception {
31886 tejbeer 3754
        List<FofoPayment> fofoPayments = fofoPaymentRepository.selectAllByGatewayStatus(Gateway.CCAVENUE, PaymentStatus.INIT).stream().filter(x -> x.getCreateTimestamp().isBefore(LocalDateTime.now().minusMinutes(30l))).collect(Collectors.toList());
31697 amit.gupta 3755
        for (FofoPayment fofoPayment : fofoPayments) {
3756
            ccAvenuePaymentService.updatePayment(fofoPayment);
3757
        }
3758
    }
30859 tejbeer 3759
 
31697 amit.gupta 3760
    /*
3761
     * public void getCCAvenuePendingOrderStatus(int pendingOrderId) { PendingOrder
3762
     * pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
3763
     * ccAvenuePaymentService.getPaymentStatusMap(pendingOrder); }
3764
     */
30859 tejbeer 3765
 
32482 amit.gupta 3766
    private void calculateInterest(Loan loan, Map<LoanReferenceType, Double> loanStatusAmount,
3767
                                   int loanStatementId) throws ProfitMandiBusinessException {
31697 amit.gupta 3768
        LoanStatement loanStatement = loanStatementRepository.selectById(loanStatementId);
30859 tejbeer 3769
 
31697 amit.gupta 3770
        if (loanStatement.getLoanId() == loan.getId()) {
34710 amit.gupta 3771
            sdCreditService.addInterest(loanStatement.getCreatedAt().toLocalDate().plusDays(1), LocalDate.now(), loan, loanStatusAmount);
31697 amit.gupta 3772
        } else {
3773
            throw new ProfitMandiBusinessException("loanstament", loanStatement.getLoanId(), "Invalid LoanId");
3774
        }
3775
    }
31175 tejbeer 3776
 
31697 amit.gupta 3777
    public void loanSettlement() throws Exception {
34766 amit.gupta 3778
        List<Loan> loans = loanRepository.selectAllActiveLoanForSettlement().stream().filter(x -> x.canBeSettled()).collect(toList());
34275 tejus.loha 3779
        //TODO:Upto here
3780
        if (!loans.isEmpty()) {
31020 tejbeer 3781
 
34275 tejus.loha 3782
            for (Loan loan : loans) {
34710 amit.gupta 3783
                LOGGER.info("Loan - {},  {}", loan.getId(), loan.canBeSettled());
34275 tejus.loha 3784
                double settledAmount = sdCreditService.settleLoan(loan);
30859 tejbeer 3785
 
34275 tejus.loha 3786
                List<SanctionRequest> sanctionRequests = sanctionRequestRepository.selectHoldSanctionByFofoId(loan.getFofoId());
3787
                for (SanctionRequest sanctionRequest : sanctionRequests) {
31175 tejbeer 3788
 
34275 tejus.loha 3789
                    List<Order> orders = orderRepository.selectAllByTransactionId(sanctionRequest.getTransactionId());
3790
                    if (orders.size() == 0) {
3791
                        LOGGER.info("Could not find orders - for Sanction Request {}", sanctionRequest);
3792
                        continue;
3793
                    }
30999 tejbeer 3794
 
34275 tejus.loha 3795
                    if (settledAmount >= sanctionRequest.getPendingAmount().doubleValue()) {
3796
                        settledAmount -= sanctionRequest.getPendingAmount().doubleValue();
3797
                        sanctionRequest.setPendingAmount(BigDecimal.valueOf(0));
3798
                        this.sendUnholdEmail(orders);
3799
                    } else {
3800
                        double pendinAmount = sanctionRequest.getPendingAmount().doubleValue() - settledAmount;
3801
                        System.out.println("Pending Amount - " + pendinAmount);
3802
                        sanctionRequest.setPendingAmount(BigDecimal.valueOf(pendinAmount));
3803
                        break;
33828 ranu 3804
 
34275 tejus.loha 3805
                    }
34162 ranu 3806
 
3807
                }
32439 tejbeer 3808
            }
31020 tejbeer 3809
 
34275 tejus.loha 3810
        }
33664 amit.gupta 3811
 
33828 ranu 3812
 
32439 tejbeer 3813
    }
31020 tejbeer 3814
 
3815
 
32439 tejbeer 3816
    private void sendUnholdEmail(List<Order> orders) throws Exception {
30859 tejbeer 3817
 
3818
 
32439 tejbeer 3819
        orders.forEach(x -> x.setShipmentHold(false));
33452 amit.gupta 3820
        orders = orders.stream().filter(x -> x.getRefundTimestamp() != null).collect(Collectors.toList());
33506 amit.gupta 3821
        if (orders.size() > 0) {
33427 amit.gupta 3822
 
33664 amit.gupta 3823
            double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));
30859 tejbeer 3824
 
33506 amit.gupta 3825
            List<String> authUserEmail = csService.getAuthUserIdByPartnerId(orders.get(0).getRetailerId()).stream().map(x -> x.getEmailId()).collect(Collectors.toList());
3826
            authUserEmail.add("vinay.p@smartdukaan.com");
3827
            authUserEmail.add("shivam.gupta@smartdukaan.com");
30859 tejbeer 3828
 
33506 amit.gupta 3829
            String[] emailTo = authUserEmail.toArray(new String[authUserEmail.size()]);
30859 tejbeer 3830
 
33506 amit.gupta 3831
            String[] ccTo = {"tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com"};
30859 tejbeer 3832
 
33664 amit.gupta 3833
            String subject = "Dispatch held orders of - " + (orders.get(0).getRetailerName());
3834
            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.");
3835
            Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
33506 amit.gupta 3836
        }
30859 tejbeer 3837
 
32439 tejbeer 3838
 
31697 amit.gupta 3839
    }
30859 tejbeer 3840
 
32307 amit.gupta 3841
    public void dailyLoanAlert() throws Exception {
31697 amit.gupta 3842
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30859 tejbeer 3843
 
31697 amit.gupta 3844
        Map<Integer, Double> partnerLoanAmount = new HashMap<>();
30859 tejbeer 3845
 
31697 amit.gupta 3846
        if (!loans.isEmpty()) {
30859 tejbeer 3847
 
31697 amit.gupta 3848
            for (Loan loan : loans) {
30859 tejbeer 3849
 
31697 amit.gupta 3850
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30859 tejbeer 3851
 
31886 tejbeer 3852
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31697 amit.gupta 3853
                if (partnerLoanAmount.get(loan.getFofoId()) != null) {
3854
                    amount += partnerLoanAmount.get(loan.getFofoId());
3855
                    partnerLoanAmount.put(loan.getFofoId(), amount);
3856
                } else {
3857
                    partnerLoanAmount.put(loan.getFofoId(), amount);
3858
                }
30965 tejbeer 3859
 
31697 amit.gupta 3860
            }
30965 tejbeer 3861
 
31697 amit.gupta 3862
        }
30859 tejbeer 3863
 
31697 amit.gupta 3864
        if (!partnerLoanAmount.isEmpty()) {
30965 tejbeer 3865
 
31697 amit.gupta 3866
            for (Entry<Integer, Double> partnerLoanAmountEnrty : partnerLoanAmount.entrySet()) {
30859 tejbeer 3867
 
31697 amit.gupta 3868
                int fofoId = partnerLoanAmountEnrty.getKey();
30859 tejbeer 3869
 
31697 amit.gupta 3870
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
30859 tejbeer 3871
 
31697 amit.gupta 3872
                Address address = addressRepository.selectById(user.getAddressId());
30896 amit.gupta 3873
 
31697 amit.gupta 3874
                String title = "Alert Credit Outstanding!";
3875
                String url = "http://app.smartdukaan.com/pages/home/credit";
34729 amit.gupta 3876
                String message = "Your total outstanding Credit Balance is Rs." + FormattingUtils.formatDecimal(Math.abs(partnerLoanAmountEnrty.getValue())) + ".";
31697 amit.gupta 3877
                notificationService.sendNotification(fofoId, title, MessageType.notification, title, message, url);
30913 tejbeer 3878
 
32841 amit.gupta 3879
                //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30913 tejbeer 3880
 
31697 amit.gupta 3881
            }
30917 tejbeer 3882
 
31697 amit.gupta 3883
        }
30917 tejbeer 3884
 
31697 amit.gupta 3885
    }
30920 tejbeer 3886
 
31697 amit.gupta 3887
    public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
3888
        schemeService.processActivatedImeisForSchemes();
3889
    }
30920 tejbeer 3890
 
33112 amit.gupta 3891
    @Autowired
33355 amit.gupta 3892
    SidbiService sidbiService;
33112 amit.gupta 3893
 
33364 amit.gupta 3894
    public void processSidbiDeductions() throws ProfitMandiBusinessException {
33434 amit.gupta 3895
        //sidbiService.migrateSanctions();
33355 amit.gupta 3896
        sidbiService.processDeductions();
3897
    }
35521 amit 3898
 
35326 amit 3899
    public void updatePartnerLimit(int fofoId) throws ProfitMandiBusinessException {
3900
        LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
33355 amit.gupta 3901
 
35326 amit 3902
        CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fofoId, Gateway.SDDIRECT);
35393 amit 3903
        BigDecimal utilizationAmount = sdCreditService.getUtilizationAmount(fofoId);
35326 amit 3904
        PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 0);
3905
        BigDecimal suggestedAmount = this.getSuggestedAmount(creditAccount, partnerDailyInvestment, utilizationAmount, null);
3906
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
3907
 
3908
        LOGGER.info("suggestedAmount {} ", suggestedAmount);
3909
 
3910
        if (sdCreditRequirement == null) {
3911
            sdCreditRequirement = new SDCreditRequirement();
3912
            sdCreditRequirement.setFofoId(fofoId);
3913
            sdCreditRequirement.setCreditDays(15);
3914
            sdCreditRequirement.setInterestRate(ProfitMandiConstants.NEW_INTEREST_RATE);
3915
            sdCreditRequirement.setRisk(CreditRisk.HIGH_RISK);
3916
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
3917
            sdCreditRequirement.setCreateTimestamp(LocalDateTime.now());
3918
            sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3919
            sdCreditRequirementRepository.persist(sdCreditRequirement);
3920
        }
3921
 
3922
        CreditRisk creditRisk = sdCreditService.getCurrentRisk(sdCreditRequirement, firstBillingDate);
3923
 
3924
        sdCreditRequirement.setRisk(creditRisk);
3925
        LOGGER.info("Suggested Amount - {}", suggestedAmount);
3926
        sdCreditRequirement.setSuggestedLimit(suggestedAmount);
3927
        if (!sdCreditRequirement.isHardLimit()) {
3928
            sdCreditRequirement.setLimit(suggestedAmount);
3929
        }
35393 amit 3930
        BigDecimal utilizedLimit = sdCreditService.getUtilizationAmount(fofoId);
35326 amit 3931
 
3932
        BigDecimal availableLimit = sdCreditRequirement.getLimit().subtract(utilizedLimit);
3933
 
3934
        LOGGER.info("utilizedLimit {} ", utilizedLimit);
3935
 
3936
        LOGGER.info("availableLimit {} ", availableLimit);
3937
 
3938
        sdCreditRequirement.setUtilizedAmount(utilizedLimit);
3939
 
3940
        sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3941
 
3942
        if (creditAccount != null) {
3943
 
3944
            creditAccount.setInterestRate(sdCreditRequirement.getInterestRate().floatValue());
3945
            creditAccount.setSanctionedAmount(sdCreditRequirement.getLimit().floatValue());
3946
            creditAccount.setAvailableAmount(availableLimit.floatValue());
3947
            creditAccount.setFreeDays(sdCreditRequirement.getFreeDays());
3948
            creditAccount.setUpdatedOn(LocalDateTime.now());
3949
        }
3950
 
3951
    }
35521 amit 3952
 
31697 amit.gupta 3953
    public void updatePartnerLimit() throws ProfitMandiBusinessException {
3954
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
33355 amit.gupta 3955
        Map<Integer, BigDecimal> fofoSidbiLimitMap = sidbiService.getSuggestedLimitMap();
31886 tejbeer 3956
        Map<Integer, SDCreditRequirement> sdCreditRequirementMap = sdCreditRequirementRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
33159 amit.gupta 3957
        Map<Integer, CreditAccount> creditAccountMap = creditAccountRepository.selectAllByGateways(Arrays.asList(Gateway.SIDBI, Gateway.SDDIRECT))
33112 amit.gupta 3958
                .stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31697 amit.gupta 3959
        for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
3960
            int fofoId = customRetailerEntry.getKey();
3961
            LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
33287 amit.gupta 3962
 
33112 amit.gupta 3963
            CreditAccount creditAccount = creditAccountMap.get(fofoId);
35393 amit 3964
            BigDecimal utilizationAmount = sdCreditService.getUtilizationAmount(fofoId);
35177 amit 3965
            PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 0);
3966
            BigDecimal suggestedAmount = this.getSuggestedAmount(creditAccount, partnerDailyInvestment, utilizationAmount, fofoSidbiLimitMap.get(fofoId));
33112 amit.gupta 3967
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementMap.get(fofoId);
30929 tejbeer 3968
 
31697 amit.gupta 3969
            LOGGER.info("suggestedAmount {} ", suggestedAmount);
30913 tejbeer 3970
 
31697 amit.gupta 3971
            if (sdCreditRequirement == null) {
3972
                sdCreditRequirement = new SDCreditRequirement();
3973
                sdCreditRequirement.setFofoId(fofoId);
3974
                sdCreditRequirement.setCreditDays(15);
33452 amit.gupta 3975
                sdCreditRequirement.setInterestRate(ProfitMandiConstants.NEW_INTEREST_RATE);
31697 amit.gupta 3976
                sdCreditRequirement.setRisk(CreditRisk.HIGH_RISK);
3977
                sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
3978
                sdCreditRequirement.setCreateTimestamp(LocalDateTime.now());
3979
                sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3980
                sdCreditRequirementRepository.persist(sdCreditRequirement);
3981
            }
30913 tejbeer 3982
 
31697 amit.gupta 3983
            CreditRisk creditRisk = sdCreditService.getCurrentRisk(sdCreditRequirement, firstBillingDate);
30913 tejbeer 3984
 
31697 amit.gupta 3985
            sdCreditRequirement.setRisk(creditRisk);
30913 tejbeer 3986
 
33874 ranu 3987
            sdCreditRequirement.setSuggestedLimit(suggestedAmount);
34275 tejus.loha 3988
            if (!sdCreditRequirement.isHardLimit()) {
34122 ranu 3989
                sdCreditRequirement.setLimit(suggestedAmount);
3990
            }
35393 amit 3991
            BigDecimal utilizedLimit = sdCreditService.getUtilizationAmount(fofoId);
30934 tejbeer 3992
 
31697 amit.gupta 3993
            BigDecimal availableLimit = sdCreditRequirement.getLimit().subtract(utilizedLimit);
30934 tejbeer 3994
 
31697 amit.gupta 3995
            LOGGER.info("utilizedLimit {} ", utilizedLimit);
30913 tejbeer 3996
 
31697 amit.gupta 3997
            LOGGER.info("availableLimit {} ", availableLimit);
30913 tejbeer 3998
 
31697 amit.gupta 3999
            sdCreditRequirement.setUtilizedAmount(utilizedLimit);
30929 tejbeer 4000
 
31697 amit.gupta 4001
            sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
30929 tejbeer 4002
 
31697 amit.gupta 4003
            if (creditAccount != null) {
30929 tejbeer 4004
 
31697 amit.gupta 4005
                creditAccount.setInterestRate(sdCreditRequirement.getInterestRate().floatValue());
4006
                creditAccount.setSanctionedAmount(sdCreditRequirement.getLimit().floatValue());
4007
                creditAccount.setAvailableAmount(availableLimit.floatValue());
4008
                creditAccount.setFreeDays(sdCreditRequirement.getFreeDays());
4009
                creditAccount.setUpdatedOn(LocalDateTime.now());
4010
            }
30929 tejbeer 4011
 
31697 amit.gupta 4012
        }
31177 tejbeer 4013
 
31697 amit.gupta 4014
    }
34502 amit.gupta 4015
 
34374 amit.gupta 4016
    private static final NavigableMap<Double, Double> discountMap = new TreeMap<>();
34502 amit.gupta 4017
 
34374 amit.gupta 4018
    static {
34852 amit 4019
        discountMap.put(4 * ProfitMandiConstants.ONE_LAC - 1, 0.2);    // Up to 3,99,999 -> 20%
4020
        discountMap.put(10 * ProfitMandiConstants.ONE_LAC - 1, 0.25);  // 4,00,000 to 9,99,999 -> 25%
4021
        discountMap.put(20 * ProfitMandiConstants.ONE_LAC - 1, 0.3);   // 10,00,000 to 19,99,999 -> 30%
4022
        discountMap.put(Double.MAX_VALUE, 0.4);                        // 20,00,000 and above -> 40%
34374 amit.gupta 4023
    }
34502 amit.gupta 4024
 
4025
    public BigDecimal getSuggestedLimit(double investmentValue) {
34374 amit.gupta 4026
        double percentageValue = discountMap.ceilingEntry(investmentValue).getValue();
34510 amit.gupta 4027
        return this.getSuggestedAmount(investmentValue, percentageValue);
4028
 
4029
    }
4030
 
4031
    private BigDecimal getSuggestedAmount(double investmentValue, double percentageValue) {
34374 amit.gupta 4032
        return BigDecimal.valueOf(investmentValue * percentageValue);
4033
    }
34502 amit.gupta 4034
 
35299 amit 4035
    /*private static List<Integer> hundredPercentLimitPartnerIds = Arrays.asList(175139630,
34510 amit.gupta 4036
            175139815,
4037
            175139844,
4038
            175140101
35299 amit 4039
    );*/
34510 amit.gupta 4040
 
35299 amit 4041
    private static List<Integer> hundredPercentLimitPartnerIds = Arrays.asList();
4042
 
35177 amit 4043
    private BigDecimal getSuggestedAmount(CreditAccount creditAccount, PartnerDailyInvestment
35393 amit 4044
            partnerDailyInvestment, BigDecimal utilizationAmount, BigDecimal sidbiLimit) {
33112 amit.gupta 4045
        BigDecimal suggestedAmount = BigDecimal.ZERO;
35393 amit 4046
        double utilization = utilizationAmount != null ? utilizationAmount.doubleValue() : 0;
33112 amit.gupta 4047
        //1 LAC
33295 amit.gupta 4048
        if (creditAccount == null || creditAccount.getGateway().equals(Gateway.SDDIRECT)) {
33112 amit.gupta 4049
 
35177 amit 4050
            if (partnerDailyInvestment != null) {
4051
                if (hundredPercentLimitPartnerIds.contains(partnerDailyInvestment.getFofoId())) {
35393 amit 4052
                    suggestedAmount = getSuggestedAmount(partnerDailyInvestment.getTotalInvestment() - utilization, 1);
34512 amit.gupta 4053
                    suggestedAmount = suggestedAmount.min(BigDecimal.valueOf(1500000));
34510 amit.gupta 4054
                } else {
35393 amit 4055
                    suggestedAmount = getSuggestedLimit(partnerDailyInvestment.getTotalInvestment() - utilization);
34510 amit.gupta 4056
                }
33112 amit.gupta 4057
            }
4058
            if (suggestedAmount.doubleValue() < 0) {
4059
                suggestedAmount = BigDecimal.ZERO;
4060
            }
33355 amit.gupta 4061
        } else if (creditAccount.getGateway().equals(Gateway.SIDBI) && sidbiLimit != null) {
35393 amit 4062
            suggestedAmount = getSuggestedLimit(partnerDailyInvestment.getTotalInvestment() - utilization);
34993 ranu 4063
            suggestedAmount = suggestedAmount.max(sidbiLimit);
4064
 
4065
 
33112 amit.gupta 4066
        }
4067
        return suggestedAmount;
4068
    }
4069
 
31697 amit.gupta 4070
    public void notifyDefaultLoans() throws ProfitMandiBusinessException, MessagingException, IOException {
30929 tejbeer 4071
 
31697 amit.gupta 4072
        sdCreditService.updateRisk();
34729 amit.gupta 4073
        List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
31697 amit.gupta 4074
        if (!defaultLoans.isEmpty()) {
4075
            this.sendDefaultLoanAlert(defaultLoans);
4076
        }
30929 tejbeer 4077
 
31697 amit.gupta 4078
    }
30929 tejbeer 4079
 
32482 amit.gupta 4080
    public void sendDefaultLoanAlert(List<Loan> defaultLoans) throws
4081
            ProfitMandiBusinessException, MessagingException, IOException {
31697 amit.gupta 4082
        String subject = "Default Partners";
30931 tejbeer 4083
 
35521 amit 4084
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
30929 tejbeer 4085
 
33452 amit.gupta 4086
        for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
31697 amit.gupta 4087
            List<Loan> filteredRows = new ArrayList<>();
4088
            for (Loan loan : defaultLoans) {
30929 tejbeer 4089
 
31697 amit.gupta 4090
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30929 tejbeer 4091
 
31697 amit.gupta 4092
                    filteredRows.add(loan);
4093
                }
4094
            }
4095
            if (!filteredRows.isEmpty()) {
33628 tejus.loha 4096
                String[] email = new String[]{storeGuyEntry.getKey()};
31697 amit.gupta 4097
                String messageText = this.getMessageForDueDateExtend(filteredRows);
32350 amit.gupta 4098
                this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, subject);
30982 tejbeer 4099
 
31697 amit.gupta 4100
            }
30936 tejbeer 4101
 
31697 amit.gupta 4102
        }
33628 tejus.loha 4103
        String messageText = this.getMessageForDueDateExtend(defaultLoans);
34858 amit 4104
        this.sendMailOfHtmlFormat(googleMailSender, new String[]{"puneet.wahi@smartdukaan.com", "rahul.latwal@smartdukaan.com", "dilbag.singh@smartdukaan.com"}, messageText, null, subject);
30982 tejbeer 4105
 
31697 amit.gupta 4106
        for (Loan defaultLoan : defaultLoans) {
4107
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
30929 tejbeer 4108
 
31886 tejbeer 4109
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 4110
 
31697 amit.gupta 4111
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
30936 tejbeer 4112
 
31697 amit.gupta 4113
            Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 4114
 
34729 amit.gupta 4115
            String title = "Outstanding Credit Payment Overdue!";
31697 amit.gupta 4116
            String url = "http://app.smartdukaan.com/pages/home/credit";
34731 amit.gupta 4117
            String message = "Your Outstanding Credit payment due date " + defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + " has been exceeded. Please note " + ProfitMandiConstants.NEW_DELAYED_INTEREST_RATE + " shall be levied on daily basis." + " Your total pending Loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + ". !!Pay Now!!";
31886 tejbeer 4118
            notificationService.sendNotification(defaultLoan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 4119
 
31697 amit.gupta 4120
            // notificationService.sendWhatsappMessage(message, title,
4121
            // address.getPhoneNumber());
30929 tejbeer 4122
 
31697 amit.gupta 4123
        }
4124
    }
30929 tejbeer 4125
 
31697 amit.gupta 4126
    private String getMessageForDueDateExtend(List<Loan> loans) throws ProfitMandiBusinessException {
33553 ranu 4127
        Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
4128
        Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
4129
        List<AST> asts = astRepository.selectAll();
4130
        Map<Integer, AST> astMap = asts.stream()
4131
                .collect(Collectors.toMap(AST::getId, ast -> ast));
31697 amit.gupta 4132
        StringBuilder sb = new StringBuilder();
4133
        sb.append(
33553 ranu 4134
                "<html><body><p>Alert</p><p>Default Partners :-</p>" + "<br/><p>EveryDay Rs.100 charged as Penalty</p>" + "<br/>" +
4135
                        "<table style='border:1px solid black ;padding: 5px';>");
4136
        sb.append("<tbody>\n" +
4137
                "<tr>\n" +
4138
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" +
33555 ranu 4139
                "<th style='border:1px solid black;padding: 5px'>State Name</th>\n" +
4140
                "<th style='border:1px solid black;padding: 5px'>Area</th>\n" +
4141
                "<th style='border:1px solid black;padding: 5px'>Territory</th>\n" +
33553 ranu 4142
                "<th style='border:1px solid black;padding: 5px'>due date</th>\n" +
4143
                "<th style='border:1px solid black;padding: 5px'>Days</th>\n" +
33664 amit.gupta 4144
                "<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n" +
33810 ranu 4145
                "<th style='border:1px solid black;padding: 5px'>RBM L2</th>\n" +
33553 ranu 4146
                "<th style='border:1px solid black;padding: 5px'>RBM L1</th>\n" +
4147
                "<th style='border:1px solid black;padding: 5px'>Sales L1</th>\n" +
4148
                "<th style='border:1px solid black;padding: 5px'>Sales L2</th>\n" +
4149
                "</tr>");
31697 amit.gupta 4150
        for (Loan entry : loans) {
30929 tejbeer 4151
 
31697 amit.gupta 4152
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
30929 tejbeer 4153
 
31886 tejbeer 4154
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 4155
 
31697 amit.gupta 4156
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
30929 tejbeer 4157
 
31697 amit.gupta 4158
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30929 tejbeer 4159
 
31697 amit.gupta 4160
            sb.append("<tr>");
31886 tejbeer 4161
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
33555 ranu 4162
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getAddress().getState() + "</td>");
4163
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getArea() + "</td>");
4164
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getTerritory() + "</td>");
31886 tejbeer 4165
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 4166
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 4167
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
33553 ranu 4168
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager() + "</td>");
4169
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager() + "</td>");
4170
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager() + "</td>");
4171
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager() + "</td>");
31397 tejbeer 4172
 
33555 ranu 4173
 
31697 amit.gupta 4174
            sb.append("</tr>");
31397 tejbeer 4175
 
31697 amit.gupta 4176
        }
31397 tejbeer 4177
 
31697 amit.gupta 4178
        sb.append("</tbody></table></body></html>");
31397 tejbeer 4179
 
31697 amit.gupta 4180
        return sb.toString();
4181
    }
31397 tejbeer 4182
 
35111 ranu 4183
    private String getMessageForDueDateCross(List<Loan> dueDateCrossLoans) throws ProfitMandiBusinessException {
33161 ranu 4184
        Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
33452 amit.gupta 4185
        Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
33553 ranu 4186
        List<AST> asts = astRepository.selectAll();
4187
        Map<Integer, AST> astMap = asts.stream()
4188
                .collect(Collectors.toMap(AST::getId, ast -> ast));
4189
 
31697 amit.gupta 4190
        StringBuilder sb = new StringBuilder();
35110 ranu 4191
        sb.append("<html><body><p>Alert</p><p>Partner Credit Report :-</p>" + "<br/><p>Additional penal interest of  shall be levied on daily basis.</p>" + "<br/>" +
33161 ranu 4192
                "<table style='border:1px solid black ;padding: 5px';>");
4193
        sb.append("<tbody>\n" + "<tr>\n" +
33256 amit.gupta 4194
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" +
4195
                "<th style='border:1px solid black;padding: 5px'>State Name</th>\n" +
33555 ranu 4196
                "<th style='border:1px solid black;padding: 5px'>Area</th>\n" +
33553 ranu 4197
                "<th style='border:1px solid black;padding: 5px'>Territory</th>\n" +
33256 amit.gupta 4198
                "<th style='border:1px solid black;padding: 5px'>due date</th>\n" +
4199
                "<th style='border:1px solid black;padding: 5px'>Days</th>\n" +
4200
                "<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n" +
33810 ranu 4201
                "<th style='border:1px solid black;padding: 5px'>RBM L2</th>\n" +
33256 amit.gupta 4202
                "<th style='border:1px solid black;padding: 5px'>RBM L1</th>\n" +
4203
                "<th style='border:1px solid black;padding: 5px'>Sales L1</th>\n" +
4204
                "<th style='border:1px solid black;padding: 5px'>Sales L2</th>\n" +
35107 ranu 4205
                "<th style='border:1px solid black;padding: 5px'>Limit Assigned</th>\n" +
33161 ranu 4206
                "</tr>");
31397 tejbeer 4207
 
35111 ranu 4208
        for (Loan entry : dueDateCrossLoans) {
4209
            DecimalFormat df = new DecimalFormat("#.##");
31397 tejbeer 4210
 
31697 amit.gupta 4211
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
31397 tejbeer 4212
 
31886 tejbeer 4213
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31397 tejbeer 4214
 
31697 amit.gupta 4215
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
31397 tejbeer 4216
 
31697 amit.gupta 4217
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
31397 tejbeer 4218
 
35106 ranu 4219
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(customRetailer.getPartnerId());
4220
 
31697 amit.gupta 4221
            sb.append("<tr>");
31886 tejbeer 4222
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
33162 ranu 4223
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getAddress().getState() + "</td>");
33553 ranu 4224
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getArea() + "</td>");
4225
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getTerritory() + "</td>");
30936 tejbeer 4226
 
31886 tejbeer 4227
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 4228
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 4229
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
33161 ranu 4230
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager() + "</td>");
4231
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager() + "</td>");
4232
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager() + "</td>");
4233
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager() + "</td>");
35521 amit 4234
            sb.append("<td style='border:1px solid black;padding: 5px'>" + df.format(sdCreditRequirement.getLimit()) + "</td>");
31697 amit.gupta 4235
            sb.append("</tr>");
4236
        }
31397 tejbeer 4237
 
31697 amit.gupta 4238
        sb.append("</tbody></table></body></html>");
31397 tejbeer 4239
 
31697 amit.gupta 4240
        return sb.toString();
4241
    }
31397 tejbeer 4242
 
32307 amit.gupta 4243
    public void notifyLoanDueDateCross() throws Exception {
31397 tejbeer 4244
 
35111 ranu 4245
        List<Loan> dueDateCrossLoans = sdCreditService.getDueDateCrossLoan();
4246
        List<Loan> allActiveLoans = sdCreditService.getAllActiveLoan();
31697 amit.gupta 4247
        if (!dueDateCrossLoans.isEmpty()) {
35521 amit 4248
            this.sendDueDateCrossLoanAlert(dueDateCrossLoans, allActiveLoans);
31697 amit.gupta 4249
        }
31397 tejbeer 4250
 
31697 amit.gupta 4251
    }
31397 tejbeer 4252
 
35521 amit 4253
    private void sendDueDateCrossLoanAlert(List<Loan> dueDateCrossLoans, List<Loan> allActiveLoans) throws Exception {
4254
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
31397 tejbeer 4255
 
35115 ranu 4256
        for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
33631 tejus.loha 4257
            List<Loan> filteredRows = new ArrayList<>();
31697 amit.gupta 4258
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 4259
 
31697 amit.gupta 4260
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30982 tejbeer 4261
 
31697 amit.gupta 4262
                    filteredRows.add(loan);
4263
                }
4264
            }
35111 ranu 4265
 
35112 ranu 4266
            List<Loan> filteredAllActiveLoans = new ArrayList<>();
35111 ranu 4267
            for (Loan loan : allActiveLoans) {
4268
 
4269
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
4270
 
35112 ranu 4271
                    filteredAllActiveLoans.add(loan);
35111 ranu 4272
                }
4273
            }
4274
 
35112 ranu 4275
            ByteArrayOutputStream byteArrayOutputStream = null;
4276
            Utils.Attachment attachment1 = null;
35521 amit 4277
            if (!filteredAllActiveLoans.isEmpty()) {
4278
                byteArrayOutputStream = this.generateLoanCsv(filteredAllActiveLoans);
4279
                attachment1 = new Utils.Attachment("partnner-credit.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
35111 ranu 4280
 
4281
            }
4282
 
4283
 
31697 amit.gupta 4284
            if (!filteredRows.isEmpty()) {
4285
                String messageText = this.getMessageForDueDateCross(filteredRows);
33628 tejus.loha 4286
                String[] email = new String[]{storeGuyEntry.getKey()};
30982 tejbeer 4287
 
35521 amit 4288
                if (attachment1 != null) {
35112 ranu 4289
                    Utils.sendMailWithAttachments(googleMailSender, email, null, null, "Partner Credit Report", messageText, true, attachment1);
35521 amit 4290
                } else {
4291
                    this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, "Due Date Cross");
30936 tejbeer 4292
 
35521 amit 4293
                }
4294
 
31697 amit.gupta 4295
            }
30936 tejbeer 4296
 
35115 ranu 4297
        }
35113 ranu 4298
 
4299
        String messageText = this.getMessageForDueDateCross(dueDateCrossLoans);
4300
        ByteArrayOutputStream byteArrayOutputStream = this.generateLoanCsv(allActiveLoans);
4301
        Utils.Attachment attachment = null;
35521 amit 4302
        if (byteArrayOutputStream != null) {
4303
            attachment = new Utils.Attachment("partnner-credit.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
35113 ranu 4304
 
31697 amit.gupta 4305
        }
33628 tejus.loha 4306
 
35521 amit 4307
        if (attachment != null) {
35115 ranu 4308
            Utils.sendMailWithAttachments(googleMailSender, new String[]{"sdtech@smartdukaan.com"}, null, null, "Partner Credit Report", messageText, true, attachment);
35521 amit 4309
        } else {
35115 ranu 4310
            this.sendMailOfHtmlFormat(googleMailSender, new String[]{"sdtech@smartdukaan.com"}, messageText, null, "Due Date Cross");
35113 ranu 4311
        }
33628 tejus.loha 4312
 
35111 ranu 4313
 
31697 amit.gupta 4314
        if (!dueDateCrossLoans.isEmpty()) {
4315
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 4316
 
31697 amit.gupta 4317
                long noOfdaysBetween = ChronoUnit.DAYS.between(loan.getDueDate().toLocalDate(), LocalDate.now());
30989 tejbeer 4318
 
31697 amit.gupta 4319
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30989 tejbeer 4320
 
31697 amit.gupta 4321
                Address address = addressRepository.selectById(user.getAddressId());
30982 tejbeer 4322
 
31697 amit.gupta 4323
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 4324
 
31697 amit.gupta 4325
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30936 tejbeer 4326
 
31886 tejbeer 4327
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 4328
 
31697 amit.gupta 4329
                String url = "http://app.smartdukaan.com/pages/home/credit";
30936 tejbeer 4330
 
31697 amit.gupta 4331
                String title = "Alert!";
34729 amit.gupta 4332
                String message = "Your Outstanding Credit Payment due date " + loan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + " has been exceeded. Additional penal interest of " + loan.getInterestRate().setScale(2, RoundingMode.HALF_UP) + "% shall be levied on daily basis. Your total pending loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + ". !!Pay Now!!";
30936 tejbeer 4333
 
31886 tejbeer 4334
                notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 4335
 
32841 amit.gupta 4336
                //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4337
 
31697 amit.gupta 4338
            }
4339
        }
30982 tejbeer 4340
 
31697 amit.gupta 4341
    }
30936 tejbeer 4342
 
35112 ranu 4343
    private ByteArrayOutputStream generateLoanCsv(List<Loan> loans) throws ProfitMandiBusinessException {
4344
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = null;
4345
 
4346
 
4347
        if (!loans.isEmpty()) {
4348
            Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
4349
            Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
4350
            List<AST> asts = astRepository.selectAll();
4351
            Map<Integer, AST> astMap = asts.stream()
4352
                    .collect(Collectors.toMap(AST::getId, ast -> ast));
4353
            try {
4354
                List<String> headers = Arrays.asList(
4355
                        "PartnerName", "State Name", "Area", "Territory",
4356
                        "Due Date", "Days", "Pending Amount",
4357
                        "RBM L2", "RBM L1", "Sales L1", "Sales L2", "Limit Assigned"
4358
                );
4359
 
4360
                List<List<?>> rows = new ArrayList<>();
4361
 
4362
                for (Loan entry : loans) {
4363
 
4364
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
4365
                    double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
4366
 
35114 ranu 4367
//                    long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
4368
                    long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getCreatedOn().toLocalDate(), LocalDateTime.now());
35112 ranu 4369
 
4370
                    CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
4371
                    SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(customRetailer.getPartnerId());
4372
                    DecimalFormat df = new DecimalFormat("#.##");
4373
                    List<String> row = Arrays.asList(
4374
                            customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")",
4375
                            customRetailer.getAddress().getState(),
4376
                            astMap.get(customRetailer.getAstId()).getArea(),
4377
                            astMap.get(customRetailer.getAstId()).getTerritory(),
4378
                            entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")),
4379
                            String.valueOf(noOfdaysBetween),
4380
                            df.format(Math.abs(amount)),
4381
                            fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager(),
4382
                            fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager(),
4383
                            fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager(),
4384
                            fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager(),
4385
                            df.format(sdCreditRequirement.getLimit())
4386
                    );
4387
 
4388
                    rows.add(row);
4389
                }
4390
 
4391
                byteArrayOutputStream = FileUtil.getCSVByteStream(headers, rows);
4392
 
4393
 
4394
            } catch (Exception e) {
4395
                throw new RuntimeException(e);
4396
            }
4397
 
4398
        }
4399
        return byteArrayOutputStream;
4400
    }
4401
 
4402
 
32307 amit.gupta 4403
    public void alertForDueDate() throws Exception {
30936 tejbeer 4404
 
31697 amit.gupta 4405
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30936 tejbeer 4406
 
31697 amit.gupta 4407
        if (!loans.isEmpty()) {
4408
            for (Loan loan : loans) {
30936 tejbeer 4409
 
31697 amit.gupta 4410
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30936 tejbeer 4411
 
31697 amit.gupta 4412
                Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 4413
 
31697 amit.gupta 4414
                long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), loan.getDueDate().toLocalDate());
30936 tejbeer 4415
 
31697 amit.gupta 4416
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 4417
 
31697 amit.gupta 4418
                if (noOfdaysBetween <= 4 && noOfdaysBetween >= 0) {
4419
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
31886 tejbeer 4420
                    double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 4421
 
31697 amit.gupta 4422
                    String title = "Alert!";
4423
                    String url = "http://app.smartdukaan.com/pages/home/credit";
4424
                    String message = null;
4425
                    if (noOfdaysBetween == 0) {
30936 tejbeer 4426
 
34729 amit.gupta 4427
                        message = "Your total outstanding Credit amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + " is due for Today, Pay Now!!";
30982 tejbeer 4428
 
31697 amit.gupta 4429
                    } else {
30982 tejbeer 4430
 
34729 amit.gupta 4431
                        message = "Your total outstanding Credit amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + " is due by " + loan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + " , Pay Now!!";
30982 tejbeer 4432
 
31697 amit.gupta 4433
                    }
31886 tejbeer 4434
                    notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
32841 amit.gupta 4435
                    //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4436
 
31697 amit.gupta 4437
                }
4438
            }
4439
        }
30984 tejbeer 4440
 
31697 amit.gupta 4441
    }
30982 tejbeer 4442
 
32307 amit.gupta 4443
    public void userMobileNumberOptIn() throws Exception {
30982 tejbeer 4444
 
31697 amit.gupta 4445
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
30982 tejbeer 4446
 
31886 tejbeer 4447
        List<com.spice.profitmandi.dao.entity.user.User> users = userUserRepository.selectByIds(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
30982 tejbeer 4448
 
31886 tejbeer 4449
        List<Address> addresses = addressRepository.selectByIds(users.stream().map(x -> x.getAddressId()).collect(Collectors.toList()));
30982 tejbeer 4450
 
31697 amit.gupta 4451
        LOGGER.info("addresses" + addresses);
30984 tejbeer 4452
 
31697 amit.gupta 4453
        for (Address address : addresses) {
32307 amit.gupta 4454
            notificationService.optIn(address.getPhoneNumber());
30982 tejbeer 4455
 
31697 amit.gupta 4456
        }
30982 tejbeer 4457
 
31697 amit.gupta 4458
    }
30982 tejbeer 4459
 
31697 amit.gupta 4460
    public void authUserMobileNumberOptIn() throws HttpHostConnectException, ProfitMandiBusinessException {
31206 tejbeer 4461
 
31697 amit.gupta 4462
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
4463
        LOGGER.info("authUsers" + authUsers);
31206 tejbeer 4464
 
31697 amit.gupta 4465
        for (AuthUser authUser : authUsers) {
4466
            Map<String, String> requestheaders = new HashMap<>();
4467
            requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
4468
            Map<String, String> requestParams = new HashMap<>();
4469
            requestParams.put("userid", String.valueOf(2000215976));
4470
            requestParams.put("password", "MFRd!BBL");
4471
            requestParams.put("phone_number", authUser.getMobileNumber());
4472
            requestParams.put("auth_scheme", "plain");
4473
            requestParams.put("v", "1.1");
4474
            requestParams.put("format", "json");
31206 tejbeer 4475
 
31697 amit.gupta 4476
            requestParams.put("method", "OPT_IN");
31206 tejbeer 4477
 
31697 amit.gupta 4478
            requestParams.put("channel", "WHATSAPP");
31886 tejbeer 4479
            String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
31697 amit.gupta 4480
            LOGGER.info("response" + response);
4481
        }
31206 tejbeer 4482
 
31697 amit.gupta 4483
    }
31206 tejbeer 4484
 
31697 amit.gupta 4485
    @Autowired
4486
    private HygieneDataRepository hygieneDataRepository;
31209 tejbeer 4487
 
31697 amit.gupta 4488
    public void hygineAlertForPartner() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 4489
 
31697 amit.gupta 4490
        List<String> remarks = new ArrayList<>();
4491
        remarks.add("Out of Service");
4492
        remarks.add("Duplicate number");
4493
        remarks.add("Partner number");
31886 tejbeer 4494
        List<HygieneData> hygieneData = hygieneDataRepository.selectAllByDisposedDateAndRemark(LocalDate.now(), remarks);
31206 tejbeer 4495
 
31697 amit.gupta 4496
        if (!hygieneData.isEmpty()) {
31206 tejbeer 4497
 
31886 tejbeer 4498
            Map<Integer, List<HygieneData>> partnerHygieneDataMap = hygieneData.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 4499
 
31697 amit.gupta 4500
            for (Entry<Integer, List<HygieneData>> partnerHygieneDataMapEntry : partnerHygieneDataMap.entrySet()) {
31206 tejbeer 4501
 
31697 amit.gupta 4502
                CustomRetailer customRetailer = retailerService.getFofoRetailer(partnerHygieneDataMapEntry.getKey());
31206 tejbeer 4503
 
31697 amit.gupta 4504
                StringBuilder sb = new StringBuilder();
31886 tejbeer 4505
                sb.append("<html><body><p>Dear Partner," + "</p><br/><p>It has been observed in our calls to the respective customers that the contact no is either not correct or does not have incoming calls.\n"
31206 tejbeer 4506
 
31886 tejbeer 4507
                        + " </p>" + "<p>We would like to inform you that this will hinder all our marketing initiatives to bring this customer back to our smartdukaan or cross sell any product from your inventory." + "</p><p>Kindly ensure going forward that the details are correct so to avoid 1% margin loss.\n" + "</p><p>In case the data is found to be incorrect there is a loss of 1% margin on this sales under SmartDukaan hygiene guidelines.\n" + "				" + "</p>"
31206 tejbeer 4508
 
31697 amit.gupta 4509
                        + "<br/><table style='border:1px solid black ;padding: 5px';>");
4510
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4511
                sb.append("<th style='border:1px solid black;padding: 5px'>Invoice Number</th>\n");
4512
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Name</th>\n");
4513
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Number</th>\n");
4514
                sb.append("</tr>\n");
31206 tejbeer 4515
 
31697 amit.gupta 4516
                List<HygieneData> hygienes = partnerHygieneDataMapEntry.getValue();
31206 tejbeer 4517
 
31697 amit.gupta 4518
                List<Integer> orderIds = hygienes.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
31206 tejbeer 4519
 
31697 amit.gupta 4520
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectAllByOrderIds(orderIds);
31206 tejbeer 4521
 
31697 amit.gupta 4522
                for (FofoOrder fofoOrder : fofoOrders) {
4523
                    Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
4524
                    sb.append("<tr>");
31886 tejbeer 4525
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoOrder.getInvoiceNumber() + "</td>\n");
4526
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getFirstName() + "" + customer.getLastName() + "</td>\n");
4527
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getMobileNumber() + "</td>\n");
31206 tejbeer 4528
 
31697 amit.gupta 4529
                    sb.append("</tr>\n");
4530
                }
31206 tejbeer 4531
 
31697 amit.gupta 4532
                sb.append("</tbody></table></body></html>");
4533
                String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 4534
 
32350 amit.gupta 4535
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31206 tejbeer 4536
 
31697 amit.gupta 4537
            }
31206 tejbeer 4538
 
31697 amit.gupta 4539
        }
31206 tejbeer 4540
 
31697 amit.gupta 4541
    }
31206 tejbeer 4542
 
33046 amit.gupta 4543
    //
4544
    public void setInventoryItemIdToPriceDropImei() {
4545
        List<PriceDropIMEI> priceDropIMEIList = priceDropIMEIRepository.selectAllMissingInventoryItemIds();
4546
        LOGGER.info("Problems with - {} entries", priceDropIMEIList.size());
4547
        //priceDropIMEIList.stream().collect(C)
4548
        for (PriceDropIMEI priceDropIMEI : priceDropIMEIList) {
4549
            System.out.println(priceDropIMEI.getImei());
4550
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllBySerialNumberFofoId(priceDropIMEI.getImei(), priceDropIMEI.getPartnerId());
33051 amit.gupta 4551
            if (inventoryItems.size() == 0) {
33046 amit.gupta 4552
                LOGGER.info("Could not find Grn - FofoID {} , Imei {} ", priceDropIMEI);
33051 amit.gupta 4553
            } else if (inventoryItems.size() > 1) {
33046 amit.gupta 4554
                LOGGER.info("Found 2 such instance for - FofoID {} , Imei {} ", priceDropIMEI.getImei(), priceDropIMEI.getPartnerId());
4555
            } else {
4556
                priceDropIMEI.setInventoryItemId(inventoryItems.get(0).getId());
4557
            }
4558
 
4559
        }
4560
    }
4561
 
33051 amit.gupta 4562
    @Autowired
4563
    SaholicReservationSnapshotRepository saholicReservationSnapshotRepository;
4564
 
33256 amit.gupta 4565
    public void removePartialBillingForTransaction(int transactionId) throws ProfitMandiBusinessException {
35424 amit 4566
        // Fetch with pessimistic lock to prevent concurrent modifications
4567
        List<Order> orderList = orderRepository.selectAllByTransactionIdForUpdate(transactionId);
33051 amit.gupta 4568
        Map<Integer, Order> orderMap = orderList.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
4569
        //Delete scanRecords
4570
        List<WarehouseScan> warehouseScans = warehouseScanRepository.selectAllByOrderIds(new ArrayList<>(orderMap.keySet()));
4571
        for (WarehouseScan warehouseScan : warehouseScans) {
4572
            warehouseScanRepository.delete(warehouseScan);
4573
            WarehouseInventoryItem warehouseInventoryItem = warehouseInventoryItemRepository.selectById(warehouseScan.getInventoryItemId());
4574
            warehouseInventoryItem.setLastScanType(in.shop2020.warehouse.ScanType.PURCHASE);
4575
            warehouseInventoryItem.setCurrentQuantity(warehouseInventoryItem.getCurrentQuantity() + warehouseScan.getQuantity());
4576
        }
4577
 
4578
        for (Order order : orderList) {
33078 ranu 4579
            if (order.getBillingTimestamp() != null) {
33056 amit.gupta 4580
                order.setStatus(OrderStatus.ACCEPTED);
4581
                order.setStatusDescription("Submitted for Processing");
4582
                order.setBillingTimestamp(null);
4583
                order.setBilledBy(null);
33057 amit.gupta 4584
                order.setSerialNumber(null);
33056 amit.gupta 4585
                order.setJacketNumber(null);
33060 amit.gupta 4586
                order.getLineItem().setSerialNumber(null);
33056 amit.gupta 4587
                List<LineItemImei> lineItemImeis = lineItemImeisRepository.selectByLineItemId(order.getLineItem().getId());
4588
                for (LineItemImei lineItemImei : lineItemImeis) {
4589
                    lineItemImeisRepository.delete(lineItemImei);
4590
                }
4591
                SaholicReservationSnapshot saholicReservationSnapshot = saholicReservationSnapshotRepository
4592
                        .selectByOrderId(order.getId());
4593
                if (saholicReservationSnapshot == null) {
4594
                    saholicInventoryService.addReservationCount(order.getLineItem().getItemId(),
4595
                            order.getFulfilmentWarehouseId(), order.getLineItem().getQuantity(), order.getId());
4596
                }
33055 amit.gupta 4597
            }
33051 amit.gupta 4598
        }
4599
    }
4600
 
31697 amit.gupta 4601
    public void hygineAlertForInternalTeam() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 4602
 
31697 amit.gupta 4603
        List<String> remarks = new ArrayList<>();
4604
        remarks.add("Out of Service");
4605
        remarks.add("Duplicate number");
4606
        remarks.add("Partner number");
31886 tejbeer 4607
        List<HygieneData> hygieneDataLastThreeMonth = hygieneDataRepository.selectDisposedDateAndRemarks(
4608
                LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay(), LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX), remarks);
31206 tejbeer 4609
 
31886 tejbeer 4610
        List<HygieneData> hygieneDataRecentMonth = hygieneDataRepository.selectDisposedDateAndRemarks(LocalDate.now().withDayOfMonth(1), remarks);
31697 amit.gupta 4611
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
4612
        Map<Integer, List<HygieneData>> partnerHygieneLastThreeMonthMap = null;
31206 tejbeer 4613
 
31697 amit.gupta 4614
        Map<Integer, List<HygieneData>> partnerHygieneDataRecentMonth = null;
31206 tejbeer 4615
 
31697 amit.gupta 4616
        if (!hygieneDataLastThreeMonth.isEmpty()) {
31886 tejbeer 4617
            partnerHygieneLastThreeMonthMap = hygieneDataLastThreeMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 4618
 
31697 amit.gupta 4619
        }
31206 tejbeer 4620
 
31697 amit.gupta 4621
        if (!hygieneDataRecentMonth.isEmpty()) {
31886 tejbeer 4622
            partnerHygieneDataRecentMonth = hygieneDataRecentMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31697 amit.gupta 4623
        }
31206 tejbeer 4624
 
31697 amit.gupta 4625
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31206 tejbeer 4626
 
31697 amit.gupta 4627
            String email = storeGuyEntry.getKey();
31206 tejbeer 4628
 
31697 amit.gupta 4629
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
31206 tejbeer 4630
 
31697 amit.gupta 4631
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData = new HashMap<>();
4632
            Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData = new HashMap<>();
4633
            for (Integer fofoId : fofoIds) {
31206 tejbeer 4634
 
31697 amit.gupta 4635
                partnerYearMonthData.put(fofoId, null);
4636
                partnerDateWiseData.put(fofoId, null);
4637
                if (!partnerHygieneLastThreeMonthMap.isEmpty()) {
4638
                    List<HygieneData> hygienes = partnerHygieneLastThreeMonthMap.get(fofoId);
31206 tejbeer 4639
 
31697 amit.gupta 4640
                    if (hygienes != null) {
31886 tejbeer 4641
                        Map<YearMonth, List<HygieneData>> yearMonthData = hygienes.stream().collect(groupingBy(x -> YearMonth.from(x.getDisposedTimestamp())));
31206 tejbeer 4642
 
31697 amit.gupta 4643
                        partnerYearMonthData.put(fofoId, yearMonthData);
31206 tejbeer 4644
 
31697 amit.gupta 4645
                    }
4646
                    List<HygieneData> dateWiseHygienes = partnerHygieneDataRecentMonth.get(fofoId);
31206 tejbeer 4647
 
31697 amit.gupta 4648
                    if (dateWiseHygienes != null) {
31206 tejbeer 4649
 
31886 tejbeer 4650
                        Map<LocalDate, List<HygieneData>> dateWiseData = hygienes.stream().collect(groupingBy(x -> (x.getDisposedTimestamp()).toLocalDate()));
31206 tejbeer 4651
 
31697 amit.gupta 4652
                        partnerDateWiseData.put(fofoId, dateWiseData);
31206 tejbeer 4653
 
31697 amit.gupta 4654
                    }
31206 tejbeer 4655
 
31697 amit.gupta 4656
                }
31206 tejbeer 4657
 
31697 amit.gupta 4658
            }
31206 tejbeer 4659
 
31697 amit.gupta 4660
            String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 4661
 
31697 amit.gupta 4662
            LOGGER.info("hygieneData {}", partnerDateWiseData.values());
31206 tejbeer 4663
 
31697 amit.gupta 4664
            boolean partnerDateWise = partnerDateWiseData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 4665
 
31697 amit.gupta 4666
            boolean partnerYearMonth = partnerYearMonthData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 4667
 
31697 amit.gupta 4668
            if (!partnerDateWise && !partnerYearMonth) {
4669
                String sb = this.getMessageHygieneAlertForPartner(partnerYearMonthData, partnerDateWiseData);
32350 amit.gupta 4670
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb, null, subject);
31697 amit.gupta 4671
            }
31206 tejbeer 4672
 
31697 amit.gupta 4673
        }
31206 tejbeer 4674
 
31697 amit.gupta 4675
    }
31206 tejbeer 4676
 
31697 amit.gupta 4677
    private String getMessageHygieneAlertForPartner(
33256 amit.gupta 4678
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData, Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData)
4679
            throws ProfitMandiBusinessException {
31206 tejbeer 4680
 
31697 amit.gupta 4681
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31206 tejbeer 4682
 
31697 amit.gupta 4683
        LocalDateTime startDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
4684
        LocalDateTime endDate = LocalDateTime.now();
31206 tejbeer 4685
 
31697 amit.gupta 4686
        LocalDateTime startYearMonth = LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay();
31886 tejbeer 4687
        LocalDateTime endYearMonth = LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX);
31206 tejbeer 4688
 
31697 amit.gupta 4689
        DateTimeFormatter dateYearMonthFormatter = DateTimeFormatter.ofPattern("MMM''uu");
31206 tejbeer 4690
 
31697 amit.gupta 4691
        List<YearMonth> yearMonthRange = new ArrayList<>();
4692
        yearMonthRange.add(YearMonth.from(startYearMonth));
31206 tejbeer 4693
 
31697 amit.gupta 4694
        yearMonthRange.add(YearMonth.from(startYearMonth.plusMonths(1)));
31206 tejbeer 4695
 
31697 amit.gupta 4696
        yearMonthRange.add(YearMonth.from(endYearMonth));
31206 tejbeer 4697
 
31697 amit.gupta 4698
        long noOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate.plusDays(1));
31206 tejbeer 4699
 
31886 tejbeer 4700
        List<LocalDate> dateRange = Stream.iterate(startDate.toLocalDate(), date -> date.plusDays(1)).limit(noOfDaysBetween).collect(Collectors.toList());
31206 tejbeer 4701
 
31697 amit.gupta 4702
        StringBuilder sb = new StringBuilder();
31886 tejbeer 4703
        sb.append("<html><body><p>Hi," + "</p><br/><p>Kindly advise below mentioned partner to input correct details in the system else this will hinder all our marketing initiatives to bring this customer back to our smartdukaan or cross sell any product from partner's inventory.\n" + " </p>" + "<p>Kindly ensure going forward that the details are correct so to avoid 1% margin loss.\n" + "</p><p>In case the data is found to be incorrect there is a loss of 1% margin on this sales under SmartDukaan hygiene guidelines.\n</p>"
31206 tejbeer 4704
 
31697 amit.gupta 4705
                + "<table style='border:1px solid black ;padding: 5px';>");
4706
        sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4707
        sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31206 tejbeer 4708
 
31697 amit.gupta 4709
        for (YearMonth yearMonth : yearMonthRange) {
31886 tejbeer 4710
            sb.append("<th style='border:1px solid black;padding: 5px'>" + yearMonth.format(dateYearMonthFormatter) + "</th>\n");
31697 amit.gupta 4711
        }
31206 tejbeer 4712
 
31697 amit.gupta 4713
        for (LocalDate localDate : dateRange) {
4714
            sb.append("<th style='border:1px solid black;padding: 5px'>" + localDate + "</th>\n");
4715
        }
31206 tejbeer 4716
 
31697 amit.gupta 4717
        sb.append("</tr>\n");
31206 tejbeer 4718
 
31886 tejbeer 4719
        for (Entry<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthEntry : partnerYearMonthData.entrySet()) {
31206 tejbeer 4720
 
31697 amit.gupta 4721
            int fofoId = partnerYearMonthEntry.getKey();
31206 tejbeer 4722
 
31697 amit.gupta 4723
            Map<YearMonth, List<HygieneData>> yearMonthData = partnerYearMonthEntry.getValue();
31206 tejbeer 4724
 
31697 amit.gupta 4725
            Map<LocalDate, List<HygieneData>> dateWiseData = partnerDateWiseData.get(fofoId);
31206 tejbeer 4726
 
31697 amit.gupta 4727
            if (yearMonthData == null && dateWiseData == null) {
4728
                continue;
4729
            }
31206 tejbeer 4730
 
31697 amit.gupta 4731
            sb.append("<tr>");
31886 tejbeer 4732
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31697 amit.gupta 4733
            for (YearMonth yearMonth : yearMonthRange) {
31206 tejbeer 4734
 
31697 amit.gupta 4735
                if (yearMonthData == null) {
4736
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4737
 
31697 amit.gupta 4738
                } else {
4739
                    List<HygieneData> hygieneList = yearMonthData.get(yearMonth);
31206 tejbeer 4740
 
31697 amit.gupta 4741
                    if (hygieneList != null) {
4742
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31206 tejbeer 4743
 
31697 amit.gupta 4744
                    } else {
4745
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4746
 
31697 amit.gupta 4747
                    }
4748
                }
4749
            }
31206 tejbeer 4750
 
31697 amit.gupta 4751
            for (LocalDate localDate : dateRange) {
31206 tejbeer 4752
 
31697 amit.gupta 4753
                if (dateWiseData == null) {
4754
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4755
 
31697 amit.gupta 4756
                } else {
4757
                    List<HygieneData> hygieneList = dateWiseData.get(localDate);
31206 tejbeer 4758
 
31697 amit.gupta 4759
                    if (hygieneList != null) {
4760
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31218 tejbeer 4761
 
31697 amit.gupta 4762
                    } else {
4763
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31218 tejbeer 4764
 
31697 amit.gupta 4765
                    }
4766
                }
4767
            }
4768
            sb.append("</tr>");
31218 tejbeer 4769
 
31697 amit.gupta 4770
        }
31218 tejbeer 4771
 
31697 amit.gupta 4772
        sb.append("</tbody></table></body></html>");
31218 tejbeer 4773
 
31697 amit.gupta 4774
        return sb.toString();
4775
    }
31218 tejbeer 4776
 
33874 ranu 4777
    @Autowired
4778
    private MonthlyTargetRepository monthlyTargetRepository;
31218 tejbeer 4779
 
31697 amit.gupta 4780
    public void monthlyTargetForPartner() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 4781
 
31697 amit.gupta 4782
        LocalDateTime curDate = LocalDateTime.now();
4783
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 4784
 
31886 tejbeer 4785
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 4786
 
31886 tejbeer 4787
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
4788
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 4789
 
31697 amit.gupta 4790
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 4791
 
31697 amit.gupta 4792
        for (Entry<Integer, MonthlyTarget> partnerMonthlyTargetEntry : partnersMonthlyTarget.entrySet()) {
31249 tejbeer 4793
 
31697 amit.gupta 4794
            int fofoId = partnerMonthlyTargetEntry.getKey();
31249 tejbeer 4795
 
31697 amit.gupta 4796
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
31249 tejbeer 4797
 
31697 amit.gupta 4798
            Double purchaseTarget = partnerMonthlyTargetEntry.getValue().getPurchaseTarget();
31218 tejbeer 4799
 
31697 amit.gupta 4800
            Double saleTarget = partnerMonthlyTargetEntry.getValue().getSaleTarget();
31218 tejbeer 4801
 
31697 amit.gupta 4802
            if (purchaseTarget > 0) {
4803
                Double purchase = secondaryMtd.get(fofoId);
31249 tejbeer 4804
 
31697 amit.gupta 4805
                if (purchase == null) {
4806
                    purchase = 0.0;
4807
                }
31218 tejbeer 4808
 
31697 amit.gupta 4809
                Double balanceTarget = purchaseTarget - purchase;
31218 tejbeer 4810
 
31697 amit.gupta 4811
                if (balanceTarget <= 0) {
4812
                    balanceTarget = 0.0;
4813
                }
31651 tejbeer 4814
 
31697 amit.gupta 4815
                StringBuilder sb = new StringBuilder();
4816
                sb.append("<html><body><p>Dear Partner,\n");
31886 tejbeer 4817
                sb.append("<p>Pls note your agreed monthly target is Rs." + purchaseTarget + " and your achievement till date is Rs." + purchase + "</p>");
31697 amit.gupta 4818
                sb.append("<p>Pls note that your balance target is Rs." + balanceTarget + "</p>\n");
4819
                sb.append(
32350 amit.gupta 4820
                        "<p>We wish you all the best and we are confident that this focused approach towards our outlet sales will help us take our outlet to the best SmartDukaan in your city.\n" + "</p>\n");
31651 tejbeer 4821
 
32350 amit.gupta 4822
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31697 amit.gupta 4823
            }
31218 tejbeer 4824
 
31697 amit.gupta 4825
        }
31218 tejbeer 4826
 
31697 amit.gupta 4827
    }
31218 tejbeer 4828
 
33444 ranu 4829
 
34502 amit.gupta 4830
    public void findAllLiveDemoBrandItemsByBillingDate() throws
4831
            MessagingException, ProfitMandiBusinessException, IOException {
33444 ranu 4832
        LocalDateTime endDate = LocalDate.now().atStartOfDay().minusDays(8);
4833
 
4834
        List<LiveDemoOrderLineItemModel> liveDemoOrderLineItemModels = orderRepository.findAllLiveDemoBrandItemsByBillingDate(endDate.minusDays(60), endDate);
4835
        LOGGER.info("liveDemoOrderLineItemModels {}", liveDemoOrderLineItemModels);
4836
        String subject = "Billed Live Demo Model";
4837
        StringBuilder sb = new StringBuilder();
4838
 
4839
        sb.append("<html><body><p>Hi,\n");
4840
        sb.append("<p>Please check live demo billed order :</p>\n" + " <table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
4841
 
4842
        sb.append("<th style='border:1px solid black;padding: 5px'>Item Id</th>\n");
4843
        sb.append("<th style='border:1px solid black;padding: 5px'>Invoice Number</th>\n");
4844
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
4845
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
4846
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
4847
        sb.append("<th style='border:1px solid black;padding: 5px'>Serial Number</th>\n");
4848
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer Name</th>\n");
4849
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer City</th>\n");
4850
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer Pincode</th>\n");
4851
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer State</th>\n");
4852
        sb.append("<th style='border:1px solid black;padding: 5px'>Billing Date</th>\n");
4853
        sb.append("</tr>\n");
4854
        for (LiveDemoOrderLineItemModel liveDemoModel : liveDemoOrderLineItemModels) {
4855
            sb.append("<tr>");
4856
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getItemId() + "</td>\n");
4857
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getInvoiceNumber() + "</td>\n");
4858
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getBrand() + "</td>\n");
4859
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getModelNumber() + "</td>\n");
4860
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getModelName() + "</td>\n");
4861
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getSerialNumber() + "</td>\n");
4862
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerName() + "</td>\n");
4863
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerCity() + "</td>\n");
4864
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerPincode() + "</td>\n");
4865
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getState() + "</td>\n");
4866
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getFormattedBillingDate() + "</td>\n");
4867
 
4868
            sb.append("</tr>\n");
4869
 
33506 amit.gupta 4870
        }
33444 ranu 4871
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "niranjan.kala@smartdukaan.com",
33506 amit.gupta 4872
                "mohit.gulati@smartdukaan.com", "vinay.p@smartdukaan.com", "shivam.gupta@smartdukaan.com");
33444 ranu 4873
 
4874
 
4875
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4876
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
4877
 
4878
    }
4879
 
33464 ranu 4880
    public void findTodayPocoBillingItems() throws MessagingException, ProfitMandiBusinessException, IOException {
4881
        LocalDateTime endDate = LocalDate.now().atStartOfDay().plusDays(1);
4882
        LocalDateTime startDate = LocalDate.now().atStartOfDay().minusDays(1);
33444 ranu 4883
 
33464 ranu 4884
        List<LiveDemoOrderLineItemModel> pocoBillingOrderLineItemModels = orderRepository.findTodayPocoBillingItems(startDate, endDate);
4885
        LOGGER.info("pocoBillingOrderLineItemModels {}", pocoBillingOrderLineItemModels);
4886
        String subject = "Poco Billing";
4887
        StringBuilder sb = new StringBuilder();
4888
 
4889
        sb.append("<html><body><p>Hi,\n");
4890
        sb.append("<p>Please check poco billed order :</p>\n" + " <table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
4891
 
4892
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
4893
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
4894
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
4895
        sb.append("<th style='border:1px solid black;padding: 5px'>Serial Number</th>\n");
4896
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer State</th>\n");
4897
        sb.append("<th style='border:1px solid black;padding: 5px'>Billing Date</th>\n");
4898
        sb.append("</tr>\n");
4899
        for (LiveDemoOrderLineItemModel pocoModel : pocoBillingOrderLineItemModels) {
4900
            sb.append("<tr>");
4901
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getBrand() + "</td>\n");
4902
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getModelNumber() + "</td>\n");
4903
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getModelName() + "</td>\n");
4904
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getSerialNumber() + "</td>\n");
4905
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getState() + "</td>\n");
4906
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getFormattedBillingDate() + "</td>\n");
4907
 
4908
            sb.append("</tr>\n");
4909
 
33506 amit.gupta 4910
        }
33664 amit.gupta 4911
        List<String> sendTo = Arrays.asList("uday.singh@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "nishant.ohri@smartdukaan.com", "ritesh.chauhan1@smartdukaan.com");
33464 ranu 4912
 
4913
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4914
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
4915
 
4916
    }
4917
 
4918
 
31697 amit.gupta 4919
    public void monthlyTargetForInternalTeam() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 4920
 
31697 amit.gupta 4921
        LocalDateTime curDate = LocalDateTime.now();
31218 tejbeer 4922
 
34903 ranu 4923
        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);
31218 tejbeer 4924
 
31697 amit.gupta 4925
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false);
31218 tejbeer 4926
 
31697 amit.gupta 4927
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 4928
 
31697 amit.gupta 4929
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31218 tejbeer 4930
 
31886 tejbeer 4931
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 4932
 
31886 tejbeer 4933
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
4934
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 4935
 
31697 amit.gupta 4936
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 4937
 
31697 amit.gupta 4938
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31218 tejbeer 4939
 
31697 amit.gupta 4940
            String email = storeGuyEntry.getKey();
31218 tejbeer 4941
 
31697 amit.gupta 4942
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
4943
            Map<Integer, MonthlyTarget> monthlyTargetAchievement = new HashMap<>();
4944
            for (Integer fofoId : fofoIds) {
31218 tejbeer 4945
 
31697 amit.gupta 4946
                MonthlyTarget monthlyTarget = partnersMonthlyTarget.get(fofoId);
4947
                if (monthlyTarget != null) {
4948
                    Double purchaseTarget = monthlyTarget.getPurchaseTarget();
31218 tejbeer 4949
 
31697 amit.gupta 4950
                    Double saleTarget = monthlyTarget.getSaleTarget();
31218 tejbeer 4951
 
31697 amit.gupta 4952
                    if (purchaseTarget != null && purchaseTarget > 0) {
4953
                        Double purchase = secondaryMtd.get(fofoId);
4954
                        if (purchase == null) {
4955
                            purchase = 0.0;
4956
                        }
4957
                        monthlyTarget.setPurchaseAchievement(purchase);
4958
                        monthlyTargetAchievement.put(fofoId, monthlyTarget);
31218 tejbeer 4959
 
31697 amit.gupta 4960
                    }
4961
                }
4962
            }
31218 tejbeer 4963
 
31697 amit.gupta 4964
            if (!monthlyTargetAchievement.isEmpty()) {
31218 tejbeer 4965
 
31697 amit.gupta 4966
                StringBuilder sb = new StringBuilder();
31218 tejbeer 4967
 
31697 amit.gupta 4968
                sb.append("<html><body><p>Hi,\n");
31886 tejbeer 4969
                sb.append("<p>Pls note your Partners agreed monthly target foolowing are :</p>\n" + " <table style='border:1px solid black ;padding: 5px';>");
31697 amit.gupta 4970
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4971
                sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31218 tejbeer 4972
 
31697 amit.gupta 4973
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Target</th>\n");
31218 tejbeer 4974
 
31697 amit.gupta 4975
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Achievement</th>\n");
4976
                sb.append("</tr>\n");
31218 tejbeer 4977
 
31886 tejbeer 4978
                for (Entry<Integer, MonthlyTarget> monthlyTargetAchievementEntry : monthlyTargetAchievement.entrySet()) {
31697 amit.gupta 4979
                    sb.append("<tr>");
4980
                    int fofoId = monthlyTargetAchievementEntry.getKey();
31218 tejbeer 4981
 
31697 amit.gupta 4982
                    MonthlyTarget monthlyTarget = monthlyTargetAchievementEntry.getValue();
31886 tejbeer 4983
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31218 tejbeer 4984
 
31886 tejbeer 4985
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseTarget() + "</td>\n");
31218 tejbeer 4986
 
31886 tejbeer 4987
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseAchievement() + "</td>\n");
31218 tejbeer 4988
 
31697 amit.gupta 4989
                    sb.append("</tr>\n");
31218 tejbeer 4990
 
31697 amit.gupta 4991
                }
31218 tejbeer 4992
 
32350 amit.gupta 4993
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb.toString(), null, subject);
31697 amit.gupta 4994
                // this.sendMailOfHtmlFormat("tejbeer.kaur@smartdukaan.com", sb.toString(),
4995
                // null, subject);
31218 tejbeer 4996
 
31697 amit.gupta 4997
            }
31604 tejbeer 4998
 
31697 amit.gupta 4999
        }
31604 tejbeer 5000
 
31697 amit.gupta 5001
    }
31604 tejbeer 5002
 
32061 amit.gupta 5003
    @Autowired
5004
    private PerformanceService performanceService;
5005
 
5006
 
5007
    public void sendFilteredRetailerPerformance() throws Exception {
5008
        RetailerFilterModel retailerFilterModel = performanceService.getRetailerFilterModel();
5009
 
5010
        Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(true);
5011
 
5012
 
5013
        List<RetailerPeformanceFilterModel> partnersPerformance = performanceService.getPerformance(retailerFilterModel, customRetailers);
5014
 
5015
        Map<Integer, RetailerPeformanceFilterModel> partnersPerformanceMap = new HashMap<>();
5016
 
5017
        if (!partnersPerformance.isEmpty()) {
5018
            partnersPerformanceMap = partnersPerformance.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
5019
            performanceService.sendPartnerPerformanceEmail(partnersPerformanceMap, retailerFilterModel, customRetailers);
5020
 
5021
        }
5022
 
5023
 
5024
    }
5025
 
32081 tejbeer 5026
    @Autowired
5027
    private VendorItemPricingRepository vendorItemPricingRepository;
32061 amit.gupta 5028
 
32081 tejbeer 5029
 
5030
    @Autowired
5031
    private VendorCatalogPricingService vendorCatalogPricingService;
5032
 
5033
 
33256 amit.gupta 5034
    public void migrateVendorItemPricing() throws ProfitMandiBusinessException {
32081 tejbeer 5035
 
5036
        List<VendorItemPricing> vendorItemPricings = vendorItemPricingRepository.selectAll();
32350 amit.gupta 5037
        LOGGER.info("At migrate VendorItemPricing");
32092 tejbeer 5038
        Map<Integer, Item> items = itemRepository.selectByIds(vendorItemPricings.stream().map(x -> x.getItemId()).collect(Collectors.toSet())).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
32081 tejbeer 5039
        for (VendorItemPricing vendorItemPricing : vendorItemPricings) {
5040
            Item item = null;
32092 tejbeer 5041
            if (items.get(vendorItemPricing.getItemId()) != null) {
5042
                item = items.get(vendorItemPricing.getItemId());
5043
            } else {
32084 tejbeer 5044
                continue;
32081 tejbeer 5045
            }
32092 tejbeer 5046
 
32081 tejbeer 5047
            VendorCatalogPricingModel vendorCatalogPricingModel = new VendorCatalogPricingModel();
5048
            vendorCatalogPricingModel.setCatalogId(item.getCatalogItemId());
5049
            vendorCatalogPricingModel.setAuthId(13);
32088 tejbeer 5050
            vendorCatalogPricingModel.setDp(vendorItemPricing.getDp());
32081 tejbeer 5051
 
5052
            vendorCatalogPricingModel.setTp(vendorItemPricing.getTp());
5053
            vendorCatalogPricingModel.setMop(vendorItemPricing.getMop());
32384 amit.gupta 5054
            vendorCatalogPricingModel.setEffectedOn(LocalDate.of(2023, 8, 22));
32081 tejbeer 5055
            vendorCatalogPricingModel.setVendorId(vendorItemPricing.getVendorId());
5056
 
5057
 
5058
            try {
5059
                vendorCatalogPricingService.createVendorCatalogPricingLog(vendorCatalogPricingModel);
5060
            } catch (ProfitMandiBusinessException e) {
5061
                continue;
5062
            }
5063
 
5064
        }
5065
 
5066
    }
5067
 
5068
    public void approveVendorCatalogPricing() {
5069
        List<VendorCatalogPricingLog> vendorCatalogPricingLogs = vendorCatalogPricingLogRepository.selectByStatus(VendorCatalogPricingStatus.PENDING);
5070
 
32084 tejbeer 5071
 
32081 tejbeer 5072
        for (VendorCatalogPricingLog vendorCatalogPricingLog : vendorCatalogPricingLogs) {
32107 tejbeer 5073
            vendorCatalogPricingLog.setStatus(VendorCatalogPricingStatus.APPROVED);
5074
            vendorCatalogPricingLog.setUpdatedTimestamp(LocalDateTime.now());
5075
            vendorCatalogPricingLog.setApprovedBy(13);
5076
            vendorCatalogPricingLog.setApprovedTimestamp(LocalDateTime.now());
32114 tejbeer 5077
            vendorCatalogPricingService.createVendorCatalogPricing(vendorCatalogPricingLog);
5078
        }
32081 tejbeer 5079
 
32114 tejbeer 5080
    }
32108 tejbeer 5081
 
32822 ranu 5082
    public void sendMailWhatsAppAfterLoanDueDate() throws Exception {
5083
        sdCreditService.updateRisk();
34729 amit.gupta 5084
        List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
32822 ranu 5085
        if (!defaultLoans.isEmpty()) {
5086
            this.sendLoanAlert(defaultLoans);
5087
        }
32108 tejbeer 5088
 
32822 ranu 5089
 
5090
    }
5091
 
5092
    public void sendLoanAlert(List<Loan> defaultLoans) throws
5093
            Exception {
5094
 
5095
        List<Integer> categoryIds = Arrays.asList(
5096
                ProfitMandiConstants.TICKET_CATEGORY_CATEGORY,
5097
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
5098
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
34903 ranu 5099
                ProfitMandiConstants.TICKET_CATEGORY_ABM,
32822 ranu 5100
                ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS,
5101
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
5102
 
5103
        /*for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
5104
            List<Loan> filteredRows = defaultLoans.stream()
5105
                    .filter(loan -> storeGuyEntry.getValue().contains(loan.getFofoId()))
5106
                    .collect(Collectors.toList());
5107
 
5108
            if (!filteredRows.isEmpty()) {
5109
                for (Loan defaultLoan : filteredRows) {
5110
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
5111
                    double amount = loanStatements.stream().map(LoanStatement::getAmount).collect(Collectors.summingDouble(BigDecimal::doubleValue));
5112
                    String messageText = getMessageForDueDateExtend(defaultLoan,amount);
5113
                   // String[] email = new String[]{storeGuyEntry.getKey()};
33820 ranu 5114
 
32822 ranu 5115
                    sendMailOfHtmlFormat(mailSender, email, messageText, null, subject);
5116
 
5117
                }
5118
            }
5119
        }*/
32842 amit.gupta 5120
        //Send single whatsapp to tv
5121
        String title = "SD Credit Alert!";
32850 amit.gupta 5122
        boolean notYetSent = true;
32822 ranu 5123
        for (Loan defaultLoan : defaultLoans) {
5124
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
5125
 
5126
            double amount = loanStatements.stream().map(LoanStatement::getAmount).collect(Collectors.summingDouble(BigDecimal::doubleValue));
5127
 
5128
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
5129
 
5130
            Address address = addressRepository.selectById(user.getAddressId());
5131
 
32842 amit.gupta 5132
            //String url = "http://app.smartdukaan.com/pages/home/credit";
32822 ranu 5133
 
32842 amit.gupta 5134
            String message = getMessageForDueDateExtend(defaultLoan, amount);
5135
            String whatsAppMessage = getWhatsAppMessageForDueDateExtend(defaultLoan, amount);
32948 amit.gupta 5136
            if (whatsAppMessage != null) {
32850 amit.gupta 5137
                notificationService.sendWhatsappMessage(whatsAppMessage, title, address.getPhoneNumber());
32948 amit.gupta 5138
                if (notYetSent) {
32850 amit.gupta 5139
                    notificationService.sendWhatsappMessage(whatsAppMessage, title, "9911565032");
5140
                    notYetSent = false;
5141
                }
5142
            }
5143
 
32822 ranu 5144
            String[] email = {user.getEmailId()};
5145
            sendMailOfHtmlFormat(mailSender, email, message, null, "Loan Alert - SmartDukaan");
5146
        }
5147
    }
5148
 
5149
    private String getMessageForDueDateExtend(Loan defaultLoan, double amount) throws ProfitMandiBusinessException {
5150
 
5151
        double absoluteAmount = Math.abs(amount);
5152
        long roundedAmount = Math.round(absoluteAmount);
5153
        String formattedAmount = (amount < 0) ? "" + roundedAmount : "" + roundedAmount;
5154
 
5155
        LocalDate dueDate = defaultLoan.getDueDate().toLocalDate();
5156
        LocalDate defaultDate = defaultLoan.getDueDate().toLocalDate().plusDays(15);
5157
 
5158
        // Retrieve the name of the user associated with the loan
5159
        String name = userUserRepository.selectById(defaultLoan.getFofoId()).getName();
5160
 
5161
        // Initialize a StringBuilder to construct the HTML message
5162
        StringBuilder sb = new StringBuilder();
5163
 
32842 amit.gupta 5164
        if (LocalDate.now().isBefore(dueDate)) {
5165
            long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), defaultLoan.getDueDate().toLocalDate());
32822 ranu 5166
            String payDate = defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
5167
            // 5 Days Before Due Date - daily
5168
            if (noOfdaysBetween <= 5) {
5169
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
5170
                sb.append("<p>This is a friendly reminder that your loan payment is due in " + noOfdaysBetween + "days, on " +
5171
                        payDate +
5172
                        ". Please ensure that the payment is made on time to avoid any late fees or penalties.</p>");
5173
                sb.append("<p>As per the terms of your loan agreement, the total amount due is Rs. " + formattedAmount + ". " +
5174
                        "You can make the payment by adding money to your wallet. If you have any questions or need assistance, " +
5175
                        "our customer service team is available to help you.</p>");
5176
                sb.append("<p>Thank you for your cooperation and prompt attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
5177
            }
32842 amit.gupta 5178
        } else if (LocalDate.now().isBefore(defaultDate)) {
32822 ranu 5179
            long noOfdaysBetween = ChronoUnit.DAYS.between(defaultDate, LocalDate.now());
5180
 
5181
            // After Due Date – Alternate days
5182
            if ((noOfdaysBetween % 2 == 0) && (noOfdaysBetween > 5)) {
5183
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
5184
                sb.append("<p>We would like to remind you that your payment for the outstanding balance on your account is now overdue. " +
5185
                        "As per our terms and conditions, a higher interest rate will be levied on the overdue amount Rs. " + formattedAmount + ".</p>");
34729 amit.gupta 5186
                sb.append("<p>To avoid further charges and any negative impact on your Credit score, we kindly request that you settle the " +
32822 ranu 5187
                        "outstanding balance as soon as possible.</p>");
5188
                sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
5189
            }
5190
            // 5 Days before default - daily
32842 amit.gupta 5191
            if (noOfdaysBetween <= 5) {
32822 ranu 5192
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br>");
5193
                sb.append("<p>Attention: High Alert</p>");
5194
                sb.append("<p>Dear " + name + "</p>");
5195
                sb.append("<p>This is to inform you that the due date for your payment of Rs. " + formattedAmount + " has been crossed, " +
5196
                        "and you are approaching the default date on " + defaultDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + ". " +
34729 amit.gupta 5197
                        "Please be aware that this will have a significant impact on your Credit score and may result in substantial penalties as well.</p>");
32822 ranu 5198
                sb.append("<p>To rectify this situation, it is imperative that you take immediate action. " +
5199
                        "Please make the necessary payment immediately to avoid further consequences.</p>");
5200
                sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
5201
            }
32842 amit.gupta 5202
        } else {
32822 ranu 5203
            // Post Default - Daily
32842 amit.gupta 5204
            sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
5205
            sb.append("<p>We regret to inform you that you are currently in loan default. As a result, " +
34729 amit.gupta 5206
                    "higher penalties are being charged, which is also negatively impacting your Credit score. " +
32842 amit.gupta 5207
                    "It is imperative that you make an immediate payment to rectify this situation.</p>");
5208
            sb.append("<p>Please note that failing to make the payment promptly will result in further consequences, " +
5209
                    "including potential legal action and additional financial penalties. " +
5210
                    "We strongly urge you to take this matter seriously and settle the outstanding amount as soon as possible.</p>");
5211
            sb.append("<p>To make the payment, please add Rs. " + formattedAmount + " to your wallet. We are here to help you resolve this issue and get back on track.</p>");
5212
            sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
32822 ranu 5213
 
5214
        }
5215
 
5216
        // Return the constructed HTML message
5217
        sb.append("</body></html>");
5218
        return sb.toString();
5219
    }
5220
 
34502 amit.gupta 5221
    private String getWhatsAppMessageForDueDateExtend(Loan defaultLoan, double amount) throws
5222
            ProfitMandiBusinessException {
32822 ranu 5223
 
5224
        double absoluteAmount = Math.abs(amount);
5225
        long roundedAmount = Math.round(absoluteAmount);
5226
        String formattedAmount = (amount < 0) ? "" + roundedAmount : "" + roundedAmount;
5227
 
5228
        LocalDate dueDate = defaultLoan.getDueDate().toLocalDate();
5229
        LocalDate defaultDate = defaultLoan.getDueDate().toLocalDate().plusDays(15);
5230
 
5231
        // Retrieve the name of the user associated with the loan
5232
        String name = userUserRepository.selectById(defaultLoan.getFofoId()).getName();
5233
 
5234
        // Initialize a StringBuilder to construct the HTML message
5235
        String message = null;
5236
 
32842 amit.gupta 5237
        if (LocalDate.now().isBefore(dueDate)) {
32822 ranu 5238
            long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), defaultLoan.getDueDate().toLocalDate());
5239
            String payDate = defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
5240
            // 5 Days Before Due Date - daily
5241
            if (noOfdaysBetween <= 5) {
5242
 
34729 amit.gupta 5243
                message = "Dear %s, This is a friendly reminder that your outstanding credit payment is due in %d days, on %s.\n" +
32822 ranu 5244
                        "\n" +
5245
                        "Please ensure that the payment is made on time to avoid any late fees or penalties.As per the terms of your loan agreement, the total amount due is Rs. %s. You can make the payment by adding money to wallet.\n" +
5246
                        "\n" +
5247
                        "If you have any questions or need assistance, our customer service team is available to help you.\n" +
5248
                        "Thank you for your cooperation and prompt attention to this matter.\n" +
5249
                        "\n" +
5250
                        "Team SmartDukaan";
32842 amit.gupta 5251
                message = String.format(message, name, noOfdaysBetween, payDate, formattedAmount);
5252
            }
5253
        } else if (LocalDate.now().isBefore(defaultDate)) {
32822 ranu 5254
            long noOfdaysBetween = ChronoUnit.DAYS.between(defaultDate, LocalDate.now());
5255
            // After Due Date – Alternate days
5256
            if ((noOfdaysBetween % 2 == 0) && (noOfdaysBetween > 5)) {
5257
                message = "Dear %s, We would like to remind you that your payment for the outstanding balance on your account is now overdue. \n" +
5258
                        "As per our terms and conditions, a higher interest rate will be levied on the overdue amount Rs.%s.\n" +
34729 amit.gupta 5259
                        "To avoid further charges and any negative impact on your Credit ratings, we kindly request that you settle the outstanding balance as soon as possible.\n" +
32822 ranu 5260
                        "Thank you for your attention to this matter. \n" +
5261
                        "\n" +
5262
                        "Team SmartDukaan";
5263
                message = String.format(message, name, formattedAmount);
5264
            }
5265
            // 5 Days before default - daily
32842 amit.gupta 5266
            if (noOfdaysBetween <= 5) {
32822 ranu 5267
                String defaultPayDate = defaultDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
5268
                message = "Attention: High Alert!! Dear %s, \n" +
5269
                        "\n" +
5270
                        "This is to inform you that the due date for your payment of Rs. %s has been crossed, and as a result, you are now about to reach default date %s.\n" +
34729 amit.gupta 5271
                        "Please be aware that this will have a significant impact on your Credit score and may result in substantial penalties as well. To rectify this situation, it is imperative that you take immediate action.\n" +
32822 ranu 5272
                        "\n" +
5273
                        "Please make the necessary payment immediately to avoid further consequences. Thank you for your attention to this matter.\n" +
5274
                        "\n" +
5275
                        "Team SmartDukaan";
5276
                message = String.format(message, name, formattedAmount, defaultPayDate);
5277
            }
32842 amit.gupta 5278
        } else {
32822 ranu 5279
            // Post Default - Daily
34729 amit.gupta 5280
            message = "Dear %s, We regret to inform you that you are currently in Credit default. As a result, higher penalties are being charged, which is also negatively impacting your Credit score. \n" +
32822 ranu 5281
                    "\n" +
5282
                    "It is imperative that you make an immediate payment to rectify this situation. \n" +
5283
                    "\n" +
5284
                    "Please note that failing to make the payment promptly will result in further consequences, including potential legal action and additional financial penalties. \n" +
5285
                    "\n" +
5286
                    "We strongly urge you to take this matter seriously and settle the outstanding amount as soon as possible. \n" +
5287
                    "\n" +
5288
                    "To make the payment, please add Rs. %s  to wallet. We are here to help you resolve this issue and get back on track. Thank you for your attention to this matter. \n" +
5289
                    "\n" +
5290
                    "Team SmartDukaan";
5291
            message = String.format(message, name, formattedAmount);
5292
 
5293
        }
5294
        // Return the constructed HTML message
5295
        return message;
5296
    }
5297
 
33874 ranu 5298
    @Autowired
5299
    private FofoOpeningStockRepository fofoOpeningStockRepository;
34450 ranu 5300
    @Autowired
5301
    private SmartCartService smartCartService;
33874 ranu 5302
 
5303
    public void createOpeningStockPartyWise() throws Exception {
5304
        // Get all partner stock data
35329 ranu 5305
        Map<Integer, List<PartnerOpeningStockByTodayModel>> partnerOpeningStockByTodayInStockMap = currentInventorySnapshotRepository.getAllPartnerTodayInstock();
5306
        Map<Integer, List<PartnerOpeningStockByTodayModel>> partnerOpeningStockByTodayGrnPending = currentInventorySnapshotRepository.getAllPartnerTodayGrnPending();
5307
 
5308
        Map<Integer, List<PartnerOpeningStockByTodayModel>> partnerOpeningStockByTodayMap =
5309
                new HashMap<>();
5310
 
5311
// STEP 1: Copy in-stock data
5312
        partnerOpeningStockByTodayInStockMap.forEach((fofoId, list) ->
5313
                partnerOpeningStockByTodayMap.put(
5314
                        fofoId,
5315
                        new ArrayList<>(list)   // deep list copy
5316
                )
5317
        );
5318
 
5319
// STEP 2: Merge GRN pending using streams
5320
        partnerOpeningStockByTodayGrnPending.forEach((fofoId, grnList) -> {
5321
 
5322
            // If FOFO missing → simply insert GRN list (deep copy)
5323
            partnerOpeningStockByTodayMap
5324
                    .computeIfAbsent(fofoId, x -> new ArrayList<>())
5325
                    .addAll(
5326
                            grnList.stream()
5327
                                    .map(g -> new PartnerOpeningStockByTodayModel(
5328
                                            g.getFofoId(),
5329
                                            g.getCatalogId(),
5330
                                            g.getModelNumber(),
5331
                                            g.getOpeningQty()
5332
                                    ))
5333
                                    .collect(Collectors.toList())
5334
                    );
5335
        });
5336
 
5337
// STEP 3: Now merge duplicates per catalogId using grouping
5338
        partnerOpeningStockByTodayMap.replaceAll((fofoId, list) ->
5339
                list.stream()
5340
                        .collect(Collectors.toMap(
5341
                                PartnerOpeningStockByTodayModel::getCatalogId,
5342
                                m -> new PartnerOpeningStockByTodayModel(
5343
                                        m.getFofoId(),
5344
                                        m.getCatalogId(),
5345
                                        m.getModelNumber(),
5346
                                        m.getOpeningQty()
5347
                                ),
5348
                                // merge function: sum openingQty
5349
                                (m1, m2) -> {
5350
                                    m1.setOpeningQty(m1.getOpeningQty() + m2.getOpeningQty());
5351
                                    return m1;
5352
                                }
5353
                        ))
5354
                        .values()
5355
                        .stream()
5356
                        .collect(Collectors.toList())
5357
        );
5358
 
5359
 
34460 ranu 5360
        Map<Integer, Map<Integer, Integer>> activatedButNotBilledCatalogQtyMap = smartCartService.activatedButNotBilledCatalogQtyMap();
34502 amit.gupta 5361
        LOGGER.info("PartnerOpeningStockByTodayModel {}", partnerOpeningStockByTodayMap);
33874 ranu 5362
        for (Map.Entry<Integer, List<PartnerOpeningStockByTodayModel>> entry : partnerOpeningStockByTodayMap.entrySet()) {
5363
            int fofoId = entry.getKey();
5364
            List<PartnerOpeningStockByTodayModel> partnerStockList = entry.getValue();
34450 ranu 5365
            // Get the sold (activated-but-not-billed) quantity for this fofo and catalog
34460 ranu 5366
            Map<Integer, Integer> activatedButNotBilledQtyMap = activatedButNotBilledCatalogQtyMap.getOrDefault(fofoId, Collections.emptyMap());
33874 ranu 5367
 
34450 ranu 5368
            //  if stock is avaialble in snapshot
33874 ranu 5369
            for (PartnerOpeningStockByTodayModel partnerStock : partnerStockList) {
5370
                int catalogId = partnerStock.getCatalogId();
34450 ranu 5371
                int stockCurrentQty = partnerStock.getOpeningQty();
33874 ranu 5372
                LocalDate openingDate = partnerStock.getOpeningDate();
5373
 
34460 ranu 5374
                int soldButNotBilledQty = activatedButNotBilledQtyMap.getOrDefault(catalogId, 0);
34450 ranu 5375
 
35521 amit 5376
                if (catalogId == 1025656 && fofoId == 175140232) {
5377
                    LOGGER.info("catalogId {}", catalogId);
5378
                    LOGGER.info("fofoId {}", fofoId);
5379
                    LOGGER.info("soldButNotBilledQty {}", soldButNotBilledQty);
5380
                    LOGGER.info("stockCurrentQty {}", stockCurrentQty);
35329 ranu 5381
                }
5382
 
34450 ranu 5383
                // Subtract soldQty from partnerCurrentQty
34460 ranu 5384
                int partnerCurrentQty = Math.max(stockCurrentQty - soldButNotBilledQty, 0); // Ensure it doesn't go negative
34450 ranu 5385
 
5386
 
33874 ranu 5387
                // Check if an entry already exists in the FofoOpeningStock table
5388
                FofoOpeningStock existingStock = fofoOpeningStockRepository.findByFofoIdAndCatalogId(fofoId, catalogId);
5389
 
34162 ranu 5390
 
33874 ranu 5391
                if (existingStock != null) {
34363 ranu 5392
                    if (partnerCurrentQty < 1 && existingStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
34160 tejus.loha 5393
                        fofoOpeningStockRepository.delete(existingStock);
5394
                    }
34162 ranu 5395
                    if (existingStock.getOpeningQty() < partnerCurrentQty) {
5396
                        existingStock.setOpeningQty(partnerCurrentQty);
5397
                        existingStock.setCurrentQty(partnerCurrentQty);
33874 ranu 5398
                        existingStock.setOpeningDate(openingDate);
5399
                        LOGGER.info("if condition exist {}");
34275 tejus.loha 5400
                    } else if (existingStock.getCurrentQty() >= existingStock.getOpeningQty()) {
5401
                        existingStock.setOpeningQty(existingStock.getCurrentQty());
5402
                        existingStock.setCurrentQty(partnerCurrentQty);
5403
                        existingStock.setOpeningDate(LocalDate.now());
34363 ranu 5404
                    } else if (existingStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
33878 ranu 5405
                        int averageQty = Math.round((existingStock.getCurrentQty() + existingStock.getOpeningQty()) / 2.0f);
5406
 
5407
                        if (averageQty == 1 && existingStock.getOpeningQty() == 1 && existingStock.getCurrentQty() == 0) {
5408
                            // Delete the existing stock entry from the table
5409
                            fofoOpeningStockRepository.delete(existingStock);
5410
                            LOGGER.info("Deleted record with fofoId: {}, catalogId: {} because averageQty, openingQty, and currentQty meet deletion criteria", fofoId, catalogId);
5411
                        } else {
5412
                            // Update the existing stock with the new average quantity
5413
                            existingStock.setOpeningQty(averageQty);
34244 ranu 5414
                            existingStock.setCurrentQty(partnerCurrentQty);
33878 ranu 5415
                            existingStock.setOpeningDate(LocalDate.now());
34363 ranu 5416
                            LOGGER.info("Updated due to date being older than 5 days with average quantity: {}", averageQty);
33878 ranu 5417
                        }
34275 tejus.loha 5418
                    } else {
34244 ranu 5419
                        existingStock.setCurrentQty(partnerCurrentQty);
33874 ranu 5420
                    }
5421
                } else {
5422
                    LOGGER.info("else condition exist");
5423
                    FofoOpeningStock newStock = new FofoOpeningStock();
5424
                    newStock.setFofoId(fofoId);
5425
                    newStock.setCatalogId(catalogId);
34162 ranu 5426
                    newStock.setOpeningQty(partnerCurrentQty);
5427
                    newStock.setCurrentQty(partnerCurrentQty);
33874 ranu 5428
                    newStock.setOpeningDate(openingDate);
5429
                    fofoOpeningStockRepository.persist(newStock);
5430
 
5431
                }
5432
            }
34162 ranu 5433
 
5434
//            if stock is not available in snapshot but available in opening stock
34275 tejus.loha 5435
            List<FofoOpeningStock> fofoOpeningStockList = fofoOpeningStockRepository.selectAllByFofoId(fofoId);
34162 ranu 5436
 
34275 tejus.loha 5437
            for (FofoOpeningStock fofoOpeningStock : fofoOpeningStockList) {
34162 ranu 5438
 
34275 tejus.loha 5439
                if (!partnerStockList.stream().anyMatch(partnerStock -> partnerStock.getCatalogId() == fofoOpeningStock.getCatalogId())) {
34363 ranu 5440
                    if (fofoOpeningStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
34275 tejus.loha 5441
                        LOGGER.info("not match stock{}", fofoOpeningStock);
5442
                        fofoOpeningStockRepository.delete(fofoOpeningStock);
5443
                    } else {
5444
                        LOGGER.info("not match stock2{}", fofoOpeningStock);
5445
                        fofoOpeningStock.setCurrentQty(0);
5446
                    }
34162 ranu 5447
 
34275 tejus.loha 5448
                }
5449
            }
34162 ranu 5450
 
33874 ranu 5451
        }
5452
    }
5453
 
5454
 
34162 ranu 5455
    @Autowired
5456
    private CategorisedCatalogRepository categorisedCatalogRepository;
5457
 
5458
    public void groupHidCatalogsByWeeks() throws ProfitMandiBusinessException, MessagingException, IOException {
5459
        List<CategorisedCatalogListModel> categorisedCatalogs = categorisedCatalogRepository.getListByStatus(CatalogMovingEnum.HID);
5460
        LocalDate currentDate = LocalDate.now();
5461
        LocalDate oneWeekAgo = currentDate.minusDays(7);
5462
        LocalDate twoWeeksAgo = currentDate.minusDays(14);
5463
        LocalDate threeWeeksAgo = currentDate.minusDays(21);
5464
 
5465
        // This Week (inclusive of the current date)
5466
        List<CategorisedCatalogListModel> thisWeekCatalogs = categorisedCatalogs.stream()
5467
                .filter(catalog -> !catalog.getStatusCreatedDate().isBefore(oneWeekAgo))
5468
                .collect(Collectors.toList());
5469
 
5470
        // Last Week (from one week ago to two weeks ago, exclusive of this week)
5471
        List<CategorisedCatalogListModel> lastWeekCatalogs = categorisedCatalogs.stream()
5472
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(oneWeekAgo) && !catalog.getStatusCreatedDate().isBefore(twoWeeksAgo))
5473
                .collect(Collectors.toList());
5474
 
5475
        // Two Weeks Ago (from two weeks ago to three weeks ago, exclusive of last week)
5476
        List<CategorisedCatalogListModel> twoWeeksAgoCatalogs = categorisedCatalogs.stream()
5477
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(twoWeeksAgo) && !catalog.getStatusCreatedDate().isBefore(threeWeeksAgo))
5478
                .collect(Collectors.toList());
5479
 
5480
        // Older than Two Weeks Ago (anything older than three weeks ago)
5481
        List<CategorisedCatalogListModel> olderCatalogs = categorisedCatalogs.stream()
5482
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(threeWeeksAgo))
5483
                .collect(Collectors.toList());
5484
 
5485
 
5486
        String subject = "Hid Catalogs";
5487
        StringBuilder sb = new StringBuilder();
5488
 
5489
        sb.append("<html><body><p>Hi Catagory Team,\n");
5490
        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;'>");
5491
 
5492
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5493
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5494
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5495
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5496
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5497
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5498
        sb.append("</tr>\n");
5499
 
5500
        for (CategorisedCatalogListModel catalog : thisWeekCatalogs) {
5501
            sb.append("<tr>");
5502
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5503
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5504
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5505
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5506
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5507
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5508
 
5509
            sb.append("</tr>\n");
5510
 
5511
        }
5512
 
5513
        sb.append("</table>");
5514
 
5515
        sb.append("</br>");
5516
        sb.append("</br>");
5517
        sb.append("</br>");
5518
        sb.append("<p style='font-weight:500;'>Please review the HID catalogs for last week:</p>\n" + "<table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
5519
 
5520
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5521
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5522
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5523
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5524
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5525
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5526
        sb.append("</tr>\n");
5527
 
5528
        for (CategorisedCatalogListModel catalog : lastWeekCatalogs) {
5529
            sb.append("<tr>");
5530
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5531
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5532
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5533
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5534
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5535
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5536
 
5537
            sb.append("</tr>\n");
5538
 
5539
        }
5540
        sb.append("</table>");
5541
 
5542
        sb.append("</br>");
5543
        sb.append("</br>");
5544
        sb.append("</br>");
5545
        sb.append("<p style='font-weight:500;'>Please review the HID catalogs for two week ago:</p>\n" + "<table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
5546
 
5547
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5548
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5549
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5550
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5551
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5552
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5553
        sb.append("</tr>\n");
5554
 
5555
        for (CategorisedCatalogListModel catalog : twoWeeksAgoCatalogs) {
5556
            sb.append("<tr>");
5557
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5558
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5559
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5560
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5561
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5562
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5563
 
5564
            sb.append("</tr>\n");
5565
 
5566
        }
5567
        sb.append("</table>");
5568
 
5569
        sb.append("</br>");
5570
        sb.append("</br>");
5571
        sb.append("</br>");
5572
        sb.append("<p style='font-weight:500;'>Please review the HID catalogs for older than two weeks ago:</p>\n" + "<table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
5573
 
5574
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5575
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5576
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5577
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5578
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5579
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5580
        sb.append("</tr>\n");
5581
 
5582
        for (CategorisedCatalogListModel catalog : olderCatalogs) {
5583
            sb.append("<tr>");
5584
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5585
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5586
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5587
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5588
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5589
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5590
 
5591
            sb.append("</tr>\n");
5592
 
5593
        }
5594
        sb.append("</table>");
5595
        sb.append("</body></html>");
5596
 
34275 tejus.loha 5597
        List<String> sendTo = Arrays.asList("uday.singh@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "nishant.ohri@smartdukaan.com", "ritesh.chauhan1@smartdukaan.com", "shobhit.tandon@smartdukaan.com", "tarun.verma@smartdukaan.com", "niranjan.kala@smartdukaan.com");
34162 ranu 5598
 
5599
 
5600
        String[] email = sendTo.toArray(new String[sendTo.size()]);
5601
 
5602
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
5603
    }
5604
 
34275 tejus.loha 5605
    public void send10OrMoreOlderStockReport() throws Exception {
35094 ranu 5606
        System.out.print("testSTart");
34352 amit.gupta 5607
        purSaleService.moreThen10DaysEgedStockReport();
35094 ranu 5608
        System.out.print("testEnd");
34162 ranu 5609
 
34275 tejus.loha 5610
    }
34162 ranu 5611
 
34791 aman.kumar 5612
    public void sendUpdateMobileBrandMarketShareQuaterlyMail() throws Exception {
5613
        String subject = "Reminder: Please Update Brand-wise Market Share";
5614
 
5615
        String body = "Dear Team,\n\n" +
5616
                "This is a gentle reminder to kindly update the brand-wise market share data for the current quarter.\n\n" +
5617
                "Best regards,\n" +
5618
                "SmartDukaan Team";
5619
 
5620
        Utils.sendMailWithAttachments(
5621
                googleMailSender,
5622
                new String[]{"sm.@smartdukaan.com"},
5623
                new String[]{"tech@smartdukaan.com"},
5624
                subject,
5625
                body
5626
        );
5627
    }
5628
 
5629
 
32210 jai.hind 5630
}
33664 amit.gupta 5631
// 2284"