Subversion Repositories SmartDukaan

Rev

Rev 35568 | 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
 
35568 amit 3133
    // REMOVED: Duplicate ticketClosed() - now handled by TicketRelatedScheduledTask.autoCloseResolvedTickets()
3134
    // which uses 8 working days instead of 7 calendar days
26790 tejbeer 3135
 
31697 amit.gupta 3136
    public void checkValidateReferral() throws Exception {
26790 tejbeer 3137
 
31697 amit.gupta 3138
        List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
3139
        LOGGER.info("referrals" + referrals);
3140
        if (!referrals.isEmpty()) {
3141
            String subject = "Referral Request";
3142
            String messageText = this.getMessageForReferral(referrals);
26790 tejbeer 3143
 
31697 amit.gupta 3144
            MimeMessage message = mailSender.createMimeMessage();
3145
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
3146
            String[] email = {"kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com"};
3147
            helper.setSubject(subject);
3148
            helper.setText(messageText, true);
3149
            helper.setTo(email);
3150
            InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
3151
            helper.setFrom(senderAddress);
3152
            mailSender.send(message);
26790 tejbeer 3153
 
31697 amit.gupta 3154
        }
3155
    }
26790 tejbeer 3156
 
31697 amit.gupta 3157
    private String getMessageForReferral(List<Refferal> referrals) {
3158
        StringBuilder sb = new StringBuilder();
31886 tejbeer 3159
        sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
3160
        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 3161
        for (Refferal entry : referrals) {
26790 tejbeer 3162
 
31697 amit.gupta 3163
            sb.append("<tr>");
3164
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
30421 tejbeer 3165
 
31697 amit.gupta 3166
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
3167
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
3168
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
3169
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
3170
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
30421 tejbeer 3171
 
31697 amit.gupta 3172
            sb.append("</tr>");
30421 tejbeer 3173
 
31697 amit.gupta 3174
        }
30421 tejbeer 3175
 
31697 amit.gupta 3176
        sb.append("</tbody></table></body></html>");
30421 tejbeer 3177
 
31697 amit.gupta 3178
        return sb.toString();
3179
    }
30421 tejbeer 3180
 
32832 amit.gupta 3181
    private String getMessageForRBMEscalatedPartners(List<PartnerCollectionRemark> pcrs) throws
32482 amit.gupta 3182
            ProfitMandiBusinessException {
31697 amit.gupta 3183
        StringBuilder sb = new StringBuilder();
32832 amit.gupta 3184
        sb.append("<html><body><p>Alert</p><p>Escalated by RBM-L1:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
3185
        sb.append("<tbody>" +
3186
                "<tr>" +
3187
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
3188
                "<th style='border:1px solid black;padding: 5px'>Escalated Since</th>" +
3189
                "<th style='border:1px solid black;padding: 5px'>Message</th>" +
3190
                "</tr>");
30421 tejbeer 3191
 
31697 amit.gupta 3192
        for (PartnerCollectionRemark entry : pcrs) {
30421 tejbeer 3193
 
31697 amit.gupta 3194
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30421 tejbeer 3195
 
31697 amit.gupta 3196
            sb.append("<tr>");
31886 tejbeer 3197
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
3198
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
32832 amit.gupta 3199
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMessage() + "</td>");
28205 tejbeer 3200
 
31697 amit.gupta 3201
            sb.append("</tr>");
28205 tejbeer 3202
 
31697 amit.gupta 3203
        }
28205 tejbeer 3204
 
31697 amit.gupta 3205
        sb.append("</tbody></table></body></html>");
28205 tejbeer 3206
 
31697 amit.gupta 3207
        return sb.toString();
3208
    }
28208 tejbeer 3209
 
32795 amit.gupta 3210
    private String getMessageForSalesEscalatedPartners(List<PartnerCollectionRemark> pcrs) throws
3211
            ProfitMandiBusinessException {
3212
        StringBuilder sb = new StringBuilder();
3213
        sb.append("<html><body><p>Alert</p><p>Escalated to Sales Team:-</p>" + "<br/>" +
3214
                "<table style='border:1px solid black ;padding: 5px';>");
3215
        sb.append("<tbody>" +
3216
                "<tr>" +
3217
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
3218
                "<th style='border:1px solid black;padding: 5px'>Escalated Since</th>" +
3219
                "<th style='border:1px solid black;padding: 5px'>Message</th>" +
3220
                "</tr>");
3221
        for (PartnerCollectionRemark entry : pcrs) {
3222
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
3223
            sb.append("<tr>");
3224
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
3225
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
3226
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMessage() + "</td>");
3227
            sb.append("</tr>");
3228
        }
3229
 
3230
        sb.append("</tbody></table></body></html>");
3231
 
3232
        return sb.toString();
3233
    }
3234
 
33078 ranu 3235
    private String getMessageForUnauthorizedBuying(List<NonSdBuying> nsb) throws
3236
            ProfitMandiBusinessException {
3237
        StringBuilder sb = new StringBuilder();
3238
        sb.append("<html><body><p>Alert</p><p>Unauthorized Buying-</p>" + "<br/>" +
3239
                "<table style='border:1px solid black ;padding: 5px';>");
3240
        sb.append("<tbody>" +
3241
                "<tr>" +
3242
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
3243
                "<th style='border:1px solid black;padding: 5px'>Brand Name</th>" +
3244
                "<th style='border:1px solid black;padding: 5px'>Brand Value</th>" +
3245
                "<th style='border:1px solid black;padding: 5px'>Created At</th>" +
3246
                "<th style='border:1px solid black;padding: 5px'>Reason</th>" +
3247
                "</tr>");
3248
        for (NonSdBuying entry : nsb) {
3249
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
3250
            List<Integer> brandIds = Collections.singletonList(entry.getBrandId());
3251
            BrandCatalog brandsDisplay = brandsRepository.selectByIds(brandIds).get(0);
3252
            sb.append("<tr>");
3253
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
3254
            sb.append("<td style='border:1px solid black;padding: 5px'>" + brandsDisplay.getName() + "</td>");
3255
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getBrandValue() + "</td>");
3256
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
3257
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getReason() + "</td>");
3258
            sb.append("</tr>");
3259
        }
3260
 
3261
        sb.append("</tbody></table></body></html>");
3262
 
3263
        return sb.toString();
3264
    }
3265
 
31697 amit.gupta 3266
    public void reverseWallet() throws Exception {
3267
        LocalDate localDate = LocalDate.of(2020, 10, 28);
31886 tejbeer 3268
        List<UserWalletHistory> uwhList = userWalletHistoryRepository.selectAllByDateType(localDate.atStartOfDay(), localDate.plusDays(1).atStartOfDay(), Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
31697 amit.gupta 3269
        for (UserWalletHistory uwh : uwhList) {
3270
            if (uwh.getBusinessTimestamp().getMonth().equals(Month.SEPTEMBER)) {
3271
                UserWallet uw = userWalletRepository.selectById(uwh.getWalletId());
3272
                // LOGGER.info("UWH - {}", uwh);
3273
                // amount += uwh.getAmount();
3274
                // System.out.println("Amount is - " + amount);
3275
                // walletService.rollbackAmountFromWallet(uw.getUserId(), uwh.getAmount(),
3276
                // uwh.getReference(), uwh.getReferenceType(), "Margin reversal for error prone
3277
                // run", uwh.getBusinessTimestamp());
3278
                int orderId = uwh.getReference();
3279
                FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
3280
                int inventoryItemId = 0;
3281
                // fofoOrderRepository.delete(fofoOrder);
3282
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3283
                /*
3284
                 * List<PaymentOptionTransaction> paymentOptionTransactions =
3285
                 * paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId
3286
                 * (), PaymentOptionReferenceType.ORDER); for(PaymentOptionTransaction
3287
                 * paymentOptionTransaction : paymentOptionTransactions) {
3288
                 * //paymentOptionTransactionRepository.delete(paymentOptionTransaction); }
3289
                 */
3290
                for (FofoOrderItem foi : fofoOrderItems) {
3291
                    // fofoOrderItemRepository.delete(foi);
3292
                    List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
3293
                    for (FofoLineItem fli : flis) {
3294
                        // fofoLineItemRepository.delete(fli);
3295
                        inventoryItemId = fli.getInventoryItemId();
3296
                    }
3297
                }
3298
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(
33452 amit.gupta 3299
                        Stream.of(inventoryItemId).collect(Collectors.toSet()));
31697 amit.gupta 3300
                for (SchemeInOut sio : schemeInOuts) {
3301
                    if (sio.getCreateTimestamp().toLocalDate().equals(localDate)) {
3302
                        LOGGER.info("SIO - {}", sio);
3303
                        sio.setRolledBackTimestamp(LocalDateTime.now());
3304
                    }
3305
                }
28208 tejbeer 3306
 
31697 amit.gupta 3307
            }
3308
        }
28208 tejbeer 3309
 
31697 amit.gupta 3310
    }
28208 tejbeer 3311
 
31697 amit.gupta 3312
    public void partnerProblemAlert() throws Exception {
3313
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
3314
        Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
3315
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
31886 tejbeer 3316
        Map<Integer, Double> mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), 0, false);
3317
        Map<Integer, PartnerDailyInvestment> pdi = partnerDailyInvestmentRepository.selectAll(LocalDate.now()).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 3318
 
31697 amit.gupta 3319
        for (Entry<Integer, Double> ls : lmtdSale.entrySet()) {
28208 tejbeer 3320
 
31697 amit.gupta 3321
            double lmtdTwentyPercentSale = ls.getValue() * 0.2;
28208 tejbeer 3322
 
31697 amit.gupta 3323
            LOGGER.info("lmtdTwentyPercentSale" + lmtdTwentyPercentSale);
28208 tejbeer 3324
 
31697 amit.gupta 3325
            double mtdSale = mtdSales.get(ls.getKey()) == null ? 0 : mtdSales.get(ls.getKey());
28205 tejbeer 3326
 
31697 amit.gupta 3327
            LOGGER.info("mtdSale" + mtdSale);
28205 tejbeer 3328
 
31886 tejbeer 3329
            double totalSixtyPercentInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getTotalInvestment() * 0.6;
28205 tejbeer 3330
 
31697 amit.gupta 3331
            LOGGER.info("totalSixtyPercentInvestment" + totalSixtyPercentInvestment);
28205 tejbeer 3332
 
31697 amit.gupta 3333
            double stockInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getInStockAmount();
28205 tejbeer 3334
 
31697 amit.gupta 3335
            LOGGER.info("stockInvestment" + stockInvestment);
28205 tejbeer 3336
 
31697 amit.gupta 3337
            boolean Investmentvalue = partnerInvestmentService.isInvestmentBelow(ls.getKey(), 25);
28205 tejbeer 3338
 
31697 amit.gupta 3339
            PartnerProblem partnerProblem = partnerProblemRepository.selectByFofoId(ls.getKey());
28205 tejbeer 3340
 
31697 amit.gupta 3341
            if (partnerProblem == null) {
3342
                partnerProblem = new PartnerProblem();
3343
                partnerProblem.setFofoId(ls.getKey());
3344
                if (mtdSale < lmtdTwentyPercentSale) {
3345
                    partnerProblem.setMtd(1);
3346
                }
3347
                if (Investmentvalue) {
3348
                    partnerProblem.setInvestment(1);
3349
                }
28205 tejbeer 3350
 
31697 amit.gupta 3351
                if (stockInvestment < totalSixtyPercentInvestment) {
3352
                    partnerProblem.setInvestment(1);
3353
                }
28205 tejbeer 3354
 
31697 amit.gupta 3355
                partnerProblemRepository.persist(partnerProblem);
3356
            } else {
3357
                if (mtdSale < lmtdTwentyPercentSale) {
3358
                    partnerProblem.setMtd(partnerProblem.getMtd() + 1);
28213 tejbeer 3359
 
31697 amit.gupta 3360
                } else {
3361
                    partnerProblem.setMtd(0);
28227 tejbeer 3362
 
31697 amit.gupta 3363
                }
3364
                if (Investmentvalue) {
3365
                    partnerProblem.setInvestment(partnerProblem.getInvestment() + 1);
3366
                } else {
3367
                    partnerProblem.setInvestment(0);
28227 tejbeer 3368
 
31697 amit.gupta 3369
                }
3370
                if (stockInvestment < totalSixtyPercentInvestment) {
3371
                    partnerProblem.setStockInvestment(partnerProblem.getStockInvestment() + 1);
3372
                } else {
3373
                    partnerProblem.setStockInvestment(0);
3374
                }
28213 tejbeer 3375
 
31697 amit.gupta 3376
            }
28213 tejbeer 3377
 
31697 amit.gupta 3378
        }
28213 tejbeer 3379
 
31886 tejbeer 3380
        List<PartnerProblem> partnerProblems = partnerProblemRepository.selectAll().stream().filter(x -> x.getMtd() + x.getInvestment() + x.getStockInvestment() > 0).collect(Collectors.toList());
28205 tejbeer 3381
 
31697 amit.gupta 3382
        partnerProblems = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 3383
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 3384
        }).collect(Collectors.toList());
28205 tejbeer 3385
 
31697 amit.gupta 3386
        Map<Integer, PartnerProblem> partnerProblemMap = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 3387
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 3388
        }).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 3389
 
31697 amit.gupta 3390
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
28205 tejbeer 3391
 
31697 amit.gupta 3392
        List<Integer> assignTo = Arrays.asList(15, 9, 54, 53);
28205 tejbeer 3393
 
35393 amit 3394
        Map<Integer, AuthUser> assignAuthUserMap = authRepository.selectByIds(assignTo).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
28222 tejbeer 3395
 
31886 tejbeer 3396
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "sm@smartdukaan.com");
31697 amit.gupta 3397
        LOGGER.info("partnerProblem" + partnerProblems);
3398
        StringBuilder sb = new StringBuilder();
3399
        sb.append("<htl><body>");
3400
        sb.append(
3401
                "<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 3402
        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 3403
 
31697 amit.gupta 3404
                + "	    				</tr>");
28218 tejbeer 3405
 
31697 amit.gupta 3406
        for (PartnerProblem pp : partnerProblems) {
3407
            int value = pp.getFofoId() % 4;
28218 tejbeer 3408
 
31697 amit.gupta 3409
            Map<EscalationType, AuthUser> authUserMap = csService.getAuthUserAndEsclationByPartnerId(pp.getFofoId());
3410
            LOGGER.info("authUserMap" + authUserMap);
3411
            sb.append("<tr>");
31886 tejbeer 3412
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
3413
            sb.append("<td style='border:1px solid black;padding: 5px'>" + assignAuthUserMap.get(assignTo.get(value)).getName() + "</td>");
31697 amit.gupta 3414
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
3415
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
3416
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
31886 tejbeer 3417
            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 3418
 
31697 amit.gupta 3419
            sb.append("</tr>");
3420
        }
3421
        sb.append("</tbody></table><br><br>");
3422
        String subject = "Partner Problem Alert!";
3423
        String[] email = sendTo.toArray(new String[sendTo.size()]);
28227 tejbeer 3424
 
32350 amit.gupta 3425
        this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
28227 tejbeer 3426
 
31697 amit.gupta 3427
        Map<Integer, List<Integer>> authUserPartnerMapping = csService.getAuthUserIdPartnerIdMapping();
28224 tejbeer 3428
 
31697 amit.gupta 3429
        for (Entry<Integer, List<Integer>> authUserPartner : authUserPartnerMapping.entrySet()) {
3430
            AuthUser authUser = authRepository.selectById(authUserPartner.getKey());
3431
            for (Integer patnerId : authUserPartner.getValue()) {
3432
                if (partnerProblemMap.get(patnerId) != null) {
28230 tejbeer 3433
 
31697 amit.gupta 3434
                    StringBuilder sbbuilder = new StringBuilder();
3435
                    sbbuilder.append("<hml><body>");
3436
                    sb.append(
3437
                            "<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 3438
                    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 3439
 
31697 amit.gupta 3440
                            + "	    				</tr>");
28205 tejbeer 3441
 
31697 amit.gupta 3442
                    for (Integer partnerId : authUserPartner.getValue()) {
3443
                        if (partnerProblemMap.get(partnerId) != null) {
3444
                            PartnerProblem pp = partnerProblemMap.get(partnerId);
3445
                            sbbuilder.append("<tr>");
31886 tejbeer 3446
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
3447
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
31697 amit.gupta 3448
                            sbbuilder.append(
3449
                                    "<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
31886 tejbeer 3450
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
28790 amit.gupta 3451
 
31697 amit.gupta 3452
                            sbbuilder.append("</tr>");
3453
                        }
28790 amit.gupta 3454
 
31697 amit.gupta 3455
                    }
3456
                    sbbuilder.append("</tbody></table><br><br>");
29488 manish 3457
 
32350 amit.gupta 3458
                    this.sendMailOfHtmlFormat(googleMailSender, new String[]{authUser.getEmailId()}, sbbuilder.toString(), null, subject);
31697 amit.gupta 3459
                }
29488 manish 3460
 
31697 amit.gupta 3461
            }
3462
        }
3463
    }
28775 amit.gupta 3464
 
31697 amit.gupta 3465
    @Autowired
3466
    WarehouseRepository warehouseRepository;
29488 manish 3467
 
33256 amit.gupta 3468
    public void getVendorWarehouses(int warehouseId) throws ProfitMandiBusinessException {
31697 amit.gupta 3469
        LOGGER.info("Warehouses - {}", warehouseRepository.getVendorWarehouses().get(warehouseId));
29488 manish 3470
 
31697 amit.gupta 3471
    }
29488 manish 3472
 
31697 amit.gupta 3473
    public void checkImeiActivation() {
29801 manish 3474
 
31697 amit.gupta 3475
        try {
3476
            vivoImeiActivationService.checkImeiActivation();
3477
        } catch (ProfitMandiBusinessException e) {
3478
            // TODO Auto-generated catch block
3479
            e.printStackTrace();
3480
        } catch (IOException e) {
3481
            // TODO Auto-generated catch block
3482
            e.printStackTrace();
3483
        } catch (Exception e) {
3484
            // TODO Auto-generated catch block
3485
            e.printStackTrace();
3486
        }
29807 manish 3487
 
31697 amit.gupta 3488
    }
29801 manish 3489
 
31697 amit.gupta 3490
    public void checkItelImeiActivation(LocalDate date, Integer day) {
3491
        LOGGER.info("Hello - {}", "hhh");
29488 manish 3492
 
31697 amit.gupta 3493
        try {
3494
            itelImeiActivationService.checkItelImeiActivation(date, day);
3495
        } catch (ProfitMandiBusinessException e) {
3496
            // TODO Auto-generated catch block
3497
            e.printStackTrace();
3498
        } catch (IOException e) {
3499
            // TODO Auto-generated catch block
3500
            e.printStackTrace();
3501
        } catch (Exception e) {
3502
            // TODO Auto-generated catch block
3503
            e.printStackTrace();
3504
        }
29488 manish 3505
 
31697 amit.gupta 3506
    }
29488 manish 3507
 
32482 amit.gupta 3508
    public void selectFinServiceFollowUpDateByCurrDate(LocalDate currentDate) throws
3509
            MessagingException, ProfitMandiBusinessException, IOException {
31697 amit.gupta 3510
        LOGGER.info("selectfinServiceFollow - {}", "selectfinServiceFollowUpDateByCurrDate");
29308 tejbeer 3511
 
31697 amit.gupta 3512
        serviceConfigService.selectFinServicePartnerfollowUpDateByCurrentDate(currentDate);
29252 amit.gupta 3513
 
31697 amit.gupta 3514
    }
29451 manish 3515
 
31697 amit.gupta 3516
    public void checkTecnoImeiActivation(LocalDate date, Integer day) {
3517
        LOGGER.info("Hello - {}", "hhh");
29308 tejbeer 3518
 
31697 amit.gupta 3519
        try {
3520
            tecnoImeiActivation.checkTecnoImeiActivation(date, day);
3521
        } catch (ProfitMandiBusinessException e) {
3522
            // TODO Auto-generated catch block
3523
            e.printStackTrace();
3524
        } catch (IOException e) {
3525
            // TODO Auto-generated catch block
3526
            e.printStackTrace();
3527
        } catch (Exception e) {
3528
            // TODO Auto-generated catch block
3529
            e.printStackTrace();
3530
        }
29308 tejbeer 3531
 
31697 amit.gupta 3532
    }
29441 tejbeer 3533
 
31697 amit.gupta 3534
    public void checkCancellationMargin() throws Exception {
3535
        LocalDateTime startDate = LocalDate.of(2021, 4, 1).atStartOfDay();
3536
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectCancelledBetweenSaleDate(startDate, LocalDateTime.now());
3537
        LOGGER.info("Total Orders =  {}", fofoOrders.size());
3538
        for (FofoOrder fofoOrder : fofoOrders) {
31886 tejbeer 3539
            List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
3540
            history.addAll(userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.ACTIVATION_SCHEME));
31697 amit.gupta 3541
            int walletSum = history.stream().mapToInt(x -> x.getAmount()).sum();
3542
            if (Math.abs(walletSum) > 1) {
3543
                // LOGGER.info("Cancelled invoice {}, Order Id = {}, = havent rolledback, Value
3544
                // = {}", fofoOrder.getInvoiceNumber(), fofoOrder.getId(), walletSum);
3545
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3546
                List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(fofoOrderItems.get(0).getId());
3547
                FofoLineItem fli = flis.get(0);
3548
                if (StringUtils.isEmpty(fli.getSerialNumber()))
3549
                    continue;
31886 tejbeer 3550
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(fli.getInventoryItemId())));
31697 amit.gupta 3551
                InventoryItem inventoryItem = inventoryItemRepository.selectById(fli.getInventoryItemId());
31886 tejbeer 3552
                double schemeSum = schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).mapToDouble(x -> x.getAmount()).sum();
31697 amit.gupta 3553
                /*
3554
                 * if(inventoryItem.getGoodQuantity()==1) {
3555
                 * LOGGER.info("GoodQty, Serial Number {}, InventoryItem = {}, Billed on {}",
3556
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3557
                 * inventoryItem.getUpdateTimestamp()); } else
3558
                 * if(inventoryItem.getBadQuantity()==1){
3559
                 * LOGGER.info("Bad Qty, Serial Number {}, InventoryItem = {}, Billed on {}",
3560
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3561
                 * inventoryItem.getUpdateTimestamp()); } else if
3562
                 * (inventoryItem.getLastScanType().equals(ScanType.SALE)) { LOGGER.
3563
                 * info("Problem Sold, Serial Number {}, InventoryItem = {}, Billed on {}",
3564
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3565
                 * inventoryItem.getUpdateTimestamp()); }
3566
                 */
31886 tejbeer 3567
                if (inventoryItem.getLastScanType().equals(ScanType.SALE) || inventoryItem.getLastScanType().equals(ScanType.SALE_RET)) {
3568
                    Map<String, Double> map = schemeInOuts.stream().collect(
3569
                            groupingBy(
3570
                                    x -> DateTimeFormatter.ofPattern("yyyyMMddHH").format(x.getCreateTimestamp()) + "- " + x.getSchemeId(), Collectors.summingDouble(x -> x.getAmount())));
33452 amit.gupta 3571
                    for (Entry<String, Double> entry : map.entrySet()) {
31697 amit.gupta 3572
                        LOGGER.info("{} = {}", entry.getKey(), entry.getValue());
3573
                    }
31886 tejbeer 3574
                    LOGGER.info("id- {}, imei- {}, lastScan = {}, Scheme sum - {}", inventoryItem.getId(), inventoryItem.getSerialNumber(), inventoryItem.getLastScanType(), schemeSum);
31697 amit.gupta 3575
                }
3576
            }
3577
        }
29441 tejbeer 3578
 
31697 amit.gupta 3579
    }
29308 tejbeer 3580
 
31697 amit.gupta 3581
    public static String readFileAsString(String file) throws Exception {
3582
        String data = "";
3583
        data = new String(Files.readAllBytes(Paths.get(file)));
3584
        return data;
3585
    }
29308 tejbeer 3586
 
31697 amit.gupta 3587
    @Autowired
3588
    private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
30421 tejbeer 3589
 
32832 amit.gupta 3590
    //RBM L2 Escalations
32482 amit.gupta 3591
    public void reviewUncontactablePartner() throws
3592
            ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
30421 tejbeer 3593
 
31697 amit.gupta 3594
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
30421 tejbeer 3595
 
32832 amit.gupta 3596
        List<Integer> partnerLastCollectionRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(customRetailerMap.keySet()));
30859 tejbeer 3597
 
32832 amit.gupta 3598
        if (!partnerLastCollectionRemarkIds.isEmpty()) {
3599
            List<PartnerCollectionRemark> partnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(partnerLastCollectionRemarkIds);
30421 tejbeer 3600
 
33064 ranu 3601
            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 3602
            Map<Integer, PartnerCollectionRemark> salesEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.SALES_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30859 tejbeer 3603
 
32832 amit.gupta 3604
 
3605
            if (!rbmEscalatedRemarksMap.isEmpty()) {
3606
                //
33452 amit.gupta 3607
                for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM), true).entrySet()) {
32832 amit.gupta 3608
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
3609
                            .map(x -> rbmEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
3610
                    String subject = "Partners escalated to RBM-L2";
3611
                    String messageText = this.getMessageForRBMEscalatedPartners(filteredRows);
3612
 
31697 amit.gupta 3613
                    MimeMessage message = mailSender.createMimeMessage();
3614
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
3615
                    String[] email = new String[]{storeGuyEntry.getKey()};
30859 tejbeer 3616
 
31697 amit.gupta 3617
                    helper.setSubject(subject);
3618
                    helper.setText(messageText, true);
3619
                    helper.setTo(email);
31886 tejbeer 3620
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
31697 amit.gupta 3621
                    helper.setFrom(senderAddress);
3622
                    mailSender.send(message);
30859 tejbeer 3623
 
31697 amit.gupta 3624
                    LOGGER.info("filteredRows {}", filteredRows);
30859 tejbeer 3625
 
31697 amit.gupta 3626
                }
3627
            }
32832 amit.gupta 3628
            if (!salesEscalatedRemarksMap.isEmpty()) {
3629
                //
35521 amit 3630
                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 3631
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
3632
                            .map(x -> salesEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
3633
                    String subject = "Partners escalated to Sales";
3634
                    String messageText = this.getMessageForSalesEscalatedPartners(filteredRows);
30936 tejbeer 3635
 
32832 amit.gupta 3636
                    MimeMessage message = mailSender.createMimeMessage();
3637
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
3638
                    String[] email = new String[]{storeGuyEntry.getKey()};
3639
 
3640
                    helper.setSubject(subject);
3641
                    helper.setText(messageText, true);
3642
                    helper.setTo(email);
3643
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
3644
                    helper.setFrom(senderAddress);
3645
                    mailSender.send(message);
3646
 
3647
                    LOGGER.info("filteredRows {}", filteredRows);
3648
 
3649
                }
3650
            }
3651
 
31697 amit.gupta 3652
        }
3653
    }
30936 tejbeer 3654
 
33078 ranu 3655
 
31697 amit.gupta 3656
    @Autowired
33078 ranu 3657
    private NonSdBuyingRepository nonSdBuyingRepository;
3658
 
3659
    //Non Sd Buying
3660
    public void reviewNonSdBuyingBrand() throws
3661
            ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
3662
        List<NonSdBuying> nonSdByuingActiveList = nonSdBuyingRepository.selectAllActiveNonSDBuyingList(true);
3663
        Map<Integer, NonSdBuying> unAuthorizedBuyingMap = nonSdByuingActiveList.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3664
 
3665
        if (!unAuthorizedBuyingMap.isEmpty()) {
35521 amit 3666
            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 3667
                List<NonSdBuying> unAuthorizedfilteredRows = storeGuyEntry.getValue().stream()
3668
                        .map(x -> unAuthorizedBuyingMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
33112 amit.gupta 3669
                if (!unAuthorizedfilteredRows.isEmpty()) {
33078 ranu 3670
                    String subject = "Unauthorized Buying";
3671
                    String messageText = this.getMessageForUnauthorizedBuying(unAuthorizedfilteredRows);
3672
 
3673
                    MimeMessage message = mailSender.createMimeMessage();
3674
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
3675
                    String[] email = new String[]{storeGuyEntry.getKey()};
3676
 
3677
                    helper.setSubject(subject);
3678
                    helper.setText(messageText, true);
3679
                    helper.setTo(email);
3680
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
3681
                    helper.setFrom(senderAddress);
3682
                    mailSender.send(message);
3683
                    LOGGER.info("unAuthorizedfilteredRows {}", unAuthorizedfilteredRows);
3684
                }
3685
 
3686
 
3687
            }
3688
 
3689
        }
3690
    }
3691
 
3692
    @Autowired
31697 amit.gupta 3693
    private LoanRepository loanRepository;
31020 tejbeer 3694
 
31697 amit.gupta 3695
    @Autowired
3696
    private LoanStatementRepository loanStatementRepository;
30859 tejbeer 3697
 
31697 amit.gupta 3698
    @Autowired
3699
    private SDCreditRequirementRepository sdCreditRequirementRepository;
30859 tejbeer 3700
 
31697 amit.gupta 3701
    @Autowired
3702
    private CurrentPartnerDailyInvestmentRepository currentPartnerDailyInvestmentRepository;
30859 tejbeer 3703
 
31697 amit.gupta 3704
    @Autowired
3705
    private TransactionRepository transactionRepository;
30859 tejbeer 3706
 
31697 amit.gupta 3707
    @Autowired
3708
    private SanctionRequestRepository sanctionRequestRepository;
30859 tejbeer 3709
 
31697 amit.gupta 3710
    public void calculateInterestAccured() throws ProfitMandiBusinessException {
34755 amit.gupta 3711
        List<Loan> loans = loanRepository.selectAllActiveLoan();
3712
        //List<Loan> loans = Arrays.asList(loanRepository.selectByLoanId(52669));
30859 tejbeer 3713
 
32724 amit.gupta 3714
        for (Loan loan : loans) {
3715
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
3716
            Map<LoanReferenceType, Double> loanStatusAmount = loanStatements.stream().collect(groupingBy(
3717
                    x -> x.getLoanReferenceType(), Collectors.summingDouble(x -> x.getAmount().doubleValue())));
30936 tejbeer 3718
 
32724 amit.gupta 3719
            int freeDays = loan.getFreeDays();
30936 tejbeer 3720
 
34710 amit.gupta 3721
            LocalDate freeDaysLimitDate = loan.getCreatedOn().plusDays(freeDays).toLocalDate();
30936 tejbeer 3722
 
34710 amit.gupta 3723
            LOGGER.info("Loan id - {}, freeDaysLimitDate {}", loan.getId(), freeDaysLimitDate);
3724
            if (LocalDate.now().isAfter(freeDaysLimitDate)) {
32724 amit.gupta 3725
                int loanStatementId = loanStatementRepository.selectLatestLoanSatement(loan.getFofoId(), loan.getId());
3726
                LOGGER.info("loanStatementId {}", loanStatementId);
3727
                if (loanStatementId != 0) {
3728
                    this.calculateInterest(loan, loanStatusAmount, loanStatementId);
31697 amit.gupta 3729
                } else {
34710 amit.gupta 3730
                    sdCreditService.addInterest(freeDaysLimitDate, LocalDate.now(), loan, loanStatusAmount);
31697 amit.gupta 3731
                }
32724 amit.gupta 3732
            }
31697 amit.gupta 3733
        }
3734
    }
30936 tejbeer 3735
 
31697 amit.gupta 3736
    @Autowired
3737
    FofoPaymentRepository fofoPaymentRepository;
30936 tejbeer 3738
 
31697 amit.gupta 3739
    @Autowired
3740
    CCAvenuePaymentService ccAvenuePaymentService;
30936 tejbeer 3741
 
31697 amit.gupta 3742
    public void settleCCAvePayments() throws Exception {
31886 tejbeer 3743
        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 3744
        for (FofoPayment fofoPayment : fofoPayments) {
3745
            ccAvenuePaymentService.updatePayment(fofoPayment);
3746
        }
3747
    }
30859 tejbeer 3748
 
31697 amit.gupta 3749
    /*
3750
     * public void getCCAvenuePendingOrderStatus(int pendingOrderId) { PendingOrder
3751
     * pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
3752
     * ccAvenuePaymentService.getPaymentStatusMap(pendingOrder); }
3753
     */
30859 tejbeer 3754
 
32482 amit.gupta 3755
    private void calculateInterest(Loan loan, Map<LoanReferenceType, Double> loanStatusAmount,
3756
                                   int loanStatementId) throws ProfitMandiBusinessException {
31697 amit.gupta 3757
        LoanStatement loanStatement = loanStatementRepository.selectById(loanStatementId);
30859 tejbeer 3758
 
31697 amit.gupta 3759
        if (loanStatement.getLoanId() == loan.getId()) {
34710 amit.gupta 3760
            sdCreditService.addInterest(loanStatement.getCreatedAt().toLocalDate().plusDays(1), LocalDate.now(), loan, loanStatusAmount);
31697 amit.gupta 3761
        } else {
3762
            throw new ProfitMandiBusinessException("loanstament", loanStatement.getLoanId(), "Invalid LoanId");
3763
        }
3764
    }
31175 tejbeer 3765
 
31697 amit.gupta 3766
    public void loanSettlement() throws Exception {
34766 amit.gupta 3767
        List<Loan> loans = loanRepository.selectAllActiveLoanForSettlement().stream().filter(x -> x.canBeSettled()).collect(toList());
34275 tejus.loha 3768
        //TODO:Upto here
3769
        if (!loans.isEmpty()) {
31020 tejbeer 3770
 
34275 tejus.loha 3771
            for (Loan loan : loans) {
34710 amit.gupta 3772
                LOGGER.info("Loan - {},  {}", loan.getId(), loan.canBeSettled());
34275 tejus.loha 3773
                double settledAmount = sdCreditService.settleLoan(loan);
30859 tejbeer 3774
 
34275 tejus.loha 3775
                List<SanctionRequest> sanctionRequests = sanctionRequestRepository.selectHoldSanctionByFofoId(loan.getFofoId());
3776
                for (SanctionRequest sanctionRequest : sanctionRequests) {
31175 tejbeer 3777
 
34275 tejus.loha 3778
                    List<Order> orders = orderRepository.selectAllByTransactionId(sanctionRequest.getTransactionId());
3779
                    if (orders.size() == 0) {
3780
                        LOGGER.info("Could not find orders - for Sanction Request {}", sanctionRequest);
3781
                        continue;
3782
                    }
30999 tejbeer 3783
 
34275 tejus.loha 3784
                    if (settledAmount >= sanctionRequest.getPendingAmount().doubleValue()) {
3785
                        settledAmount -= sanctionRequest.getPendingAmount().doubleValue();
3786
                        sanctionRequest.setPendingAmount(BigDecimal.valueOf(0));
3787
                        this.sendUnholdEmail(orders);
3788
                    } else {
3789
                        double pendinAmount = sanctionRequest.getPendingAmount().doubleValue() - settledAmount;
3790
                        System.out.println("Pending Amount - " + pendinAmount);
3791
                        sanctionRequest.setPendingAmount(BigDecimal.valueOf(pendinAmount));
3792
                        break;
33828 ranu 3793
 
34275 tejus.loha 3794
                    }
34162 ranu 3795
 
3796
                }
32439 tejbeer 3797
            }
31020 tejbeer 3798
 
34275 tejus.loha 3799
        }
33664 amit.gupta 3800
 
33828 ranu 3801
 
32439 tejbeer 3802
    }
31020 tejbeer 3803
 
3804
 
32439 tejbeer 3805
    private void sendUnholdEmail(List<Order> orders) throws Exception {
30859 tejbeer 3806
 
3807
 
32439 tejbeer 3808
        orders.forEach(x -> x.setShipmentHold(false));
33452 amit.gupta 3809
        orders = orders.stream().filter(x -> x.getRefundTimestamp() != null).collect(Collectors.toList());
33506 amit.gupta 3810
        if (orders.size() > 0) {
33427 amit.gupta 3811
 
33664 amit.gupta 3812
            double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));
30859 tejbeer 3813
 
33506 amit.gupta 3814
            List<String> authUserEmail = csService.getAuthUserIdByPartnerId(orders.get(0).getRetailerId()).stream().map(x -> x.getEmailId()).collect(Collectors.toList());
3815
            authUserEmail.add("vinay.p@smartdukaan.com");
3816
            authUserEmail.add("shivam.gupta@smartdukaan.com");
30859 tejbeer 3817
 
33506 amit.gupta 3818
            String[] emailTo = authUserEmail.toArray(new String[authUserEmail.size()]);
30859 tejbeer 3819
 
33506 amit.gupta 3820
            String[] ccTo = {"tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com"};
30859 tejbeer 3821
 
33664 amit.gupta 3822
            String subject = "Dispatch held orders of - " + (orders.get(0).getRetailerName());
3823
            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.");
3824
            Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
33506 amit.gupta 3825
        }
30859 tejbeer 3826
 
32439 tejbeer 3827
 
31697 amit.gupta 3828
    }
30859 tejbeer 3829
 
32307 amit.gupta 3830
    public void dailyLoanAlert() throws Exception {
31697 amit.gupta 3831
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30859 tejbeer 3832
 
31697 amit.gupta 3833
        Map<Integer, Double> partnerLoanAmount = new HashMap<>();
30859 tejbeer 3834
 
31697 amit.gupta 3835
        if (!loans.isEmpty()) {
30859 tejbeer 3836
 
31697 amit.gupta 3837
            for (Loan loan : loans) {
30859 tejbeer 3838
 
31697 amit.gupta 3839
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30859 tejbeer 3840
 
31886 tejbeer 3841
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31697 amit.gupta 3842
                if (partnerLoanAmount.get(loan.getFofoId()) != null) {
3843
                    amount += partnerLoanAmount.get(loan.getFofoId());
3844
                    partnerLoanAmount.put(loan.getFofoId(), amount);
3845
                } else {
3846
                    partnerLoanAmount.put(loan.getFofoId(), amount);
3847
                }
30965 tejbeer 3848
 
31697 amit.gupta 3849
            }
30965 tejbeer 3850
 
31697 amit.gupta 3851
        }
30859 tejbeer 3852
 
31697 amit.gupta 3853
        if (!partnerLoanAmount.isEmpty()) {
30965 tejbeer 3854
 
31697 amit.gupta 3855
            for (Entry<Integer, Double> partnerLoanAmountEnrty : partnerLoanAmount.entrySet()) {
30859 tejbeer 3856
 
31697 amit.gupta 3857
                int fofoId = partnerLoanAmountEnrty.getKey();
30859 tejbeer 3858
 
31697 amit.gupta 3859
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
30859 tejbeer 3860
 
31697 amit.gupta 3861
                Address address = addressRepository.selectById(user.getAddressId());
30896 amit.gupta 3862
 
31697 amit.gupta 3863
                String title = "Alert Credit Outstanding!";
3864
                String url = "http://app.smartdukaan.com/pages/home/credit";
34729 amit.gupta 3865
                String message = "Your total outstanding Credit Balance is Rs." + FormattingUtils.formatDecimal(Math.abs(partnerLoanAmountEnrty.getValue())) + ".";
31697 amit.gupta 3866
                notificationService.sendNotification(fofoId, title, MessageType.notification, title, message, url);
30913 tejbeer 3867
 
32841 amit.gupta 3868
                //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30913 tejbeer 3869
 
31697 amit.gupta 3870
            }
30917 tejbeer 3871
 
31697 amit.gupta 3872
        }
30917 tejbeer 3873
 
31697 amit.gupta 3874
    }
30920 tejbeer 3875
 
31697 amit.gupta 3876
    public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
3877
        schemeService.processActivatedImeisForSchemes();
3878
    }
30920 tejbeer 3879
 
33112 amit.gupta 3880
    @Autowired
33355 amit.gupta 3881
    SidbiService sidbiService;
33112 amit.gupta 3882
 
33364 amit.gupta 3883
    public void processSidbiDeductions() throws ProfitMandiBusinessException {
33434 amit.gupta 3884
        //sidbiService.migrateSanctions();
33355 amit.gupta 3885
        sidbiService.processDeductions();
3886
    }
35521 amit 3887
 
35326 amit 3888
    public void updatePartnerLimit(int fofoId) throws ProfitMandiBusinessException {
3889
        LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
33355 amit.gupta 3890
 
35326 amit 3891
        CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fofoId, Gateway.SDDIRECT);
35393 amit 3892
        BigDecimal utilizationAmount = sdCreditService.getUtilizationAmount(fofoId);
35326 amit 3893
        PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 0);
3894
        BigDecimal suggestedAmount = this.getSuggestedAmount(creditAccount, partnerDailyInvestment, utilizationAmount, null);
3895
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
3896
 
3897
        LOGGER.info("suggestedAmount {} ", suggestedAmount);
3898
 
3899
        if (sdCreditRequirement == null) {
3900
            sdCreditRequirement = new SDCreditRequirement();
3901
            sdCreditRequirement.setFofoId(fofoId);
3902
            sdCreditRequirement.setCreditDays(15);
3903
            sdCreditRequirement.setInterestRate(ProfitMandiConstants.NEW_INTEREST_RATE);
3904
            sdCreditRequirement.setRisk(CreditRisk.HIGH_RISK);
3905
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
3906
            sdCreditRequirement.setCreateTimestamp(LocalDateTime.now());
3907
            sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3908
            sdCreditRequirementRepository.persist(sdCreditRequirement);
3909
        }
3910
 
3911
        CreditRisk creditRisk = sdCreditService.getCurrentRisk(sdCreditRequirement, firstBillingDate);
3912
 
3913
        sdCreditRequirement.setRisk(creditRisk);
3914
        LOGGER.info("Suggested Amount - {}", suggestedAmount);
3915
        sdCreditRequirement.setSuggestedLimit(suggestedAmount);
3916
        if (!sdCreditRequirement.isHardLimit()) {
3917
            sdCreditRequirement.setLimit(suggestedAmount);
3918
        }
35393 amit 3919
        BigDecimal utilizedLimit = sdCreditService.getUtilizationAmount(fofoId);
35326 amit 3920
 
3921
        BigDecimal availableLimit = sdCreditRequirement.getLimit().subtract(utilizedLimit);
3922
 
3923
        LOGGER.info("utilizedLimit {} ", utilizedLimit);
3924
 
3925
        LOGGER.info("availableLimit {} ", availableLimit);
3926
 
3927
        sdCreditRequirement.setUtilizedAmount(utilizedLimit);
3928
 
3929
        sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3930
 
3931
        if (creditAccount != null) {
3932
 
3933
            creditAccount.setInterestRate(sdCreditRequirement.getInterestRate().floatValue());
3934
            creditAccount.setSanctionedAmount(sdCreditRequirement.getLimit().floatValue());
3935
            creditAccount.setAvailableAmount(availableLimit.floatValue());
3936
            creditAccount.setFreeDays(sdCreditRequirement.getFreeDays());
3937
            creditAccount.setUpdatedOn(LocalDateTime.now());
3938
        }
3939
 
3940
    }
35521 amit 3941
 
31697 amit.gupta 3942
    public void updatePartnerLimit() throws ProfitMandiBusinessException {
3943
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
33355 amit.gupta 3944
        Map<Integer, BigDecimal> fofoSidbiLimitMap = sidbiService.getSuggestedLimitMap();
31886 tejbeer 3945
        Map<Integer, SDCreditRequirement> sdCreditRequirementMap = sdCreditRequirementRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
33159 amit.gupta 3946
        Map<Integer, CreditAccount> creditAccountMap = creditAccountRepository.selectAllByGateways(Arrays.asList(Gateway.SIDBI, Gateway.SDDIRECT))
33112 amit.gupta 3947
                .stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31697 amit.gupta 3948
        for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
3949
            int fofoId = customRetailerEntry.getKey();
3950
            LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
33287 amit.gupta 3951
 
33112 amit.gupta 3952
            CreditAccount creditAccount = creditAccountMap.get(fofoId);
35393 amit 3953
            BigDecimal utilizationAmount = sdCreditService.getUtilizationAmount(fofoId);
35177 amit 3954
            PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 0);
3955
            BigDecimal suggestedAmount = this.getSuggestedAmount(creditAccount, partnerDailyInvestment, utilizationAmount, fofoSidbiLimitMap.get(fofoId));
33112 amit.gupta 3956
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementMap.get(fofoId);
30929 tejbeer 3957
 
31697 amit.gupta 3958
            LOGGER.info("suggestedAmount {} ", suggestedAmount);
30913 tejbeer 3959
 
31697 amit.gupta 3960
            if (sdCreditRequirement == null) {
3961
                sdCreditRequirement = new SDCreditRequirement();
3962
                sdCreditRequirement.setFofoId(fofoId);
3963
                sdCreditRequirement.setCreditDays(15);
33452 amit.gupta 3964
                sdCreditRequirement.setInterestRate(ProfitMandiConstants.NEW_INTEREST_RATE);
31697 amit.gupta 3965
                sdCreditRequirement.setRisk(CreditRisk.HIGH_RISK);
3966
                sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
3967
                sdCreditRequirement.setCreateTimestamp(LocalDateTime.now());
3968
                sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3969
                sdCreditRequirementRepository.persist(sdCreditRequirement);
3970
            }
30913 tejbeer 3971
 
31697 amit.gupta 3972
            CreditRisk creditRisk = sdCreditService.getCurrentRisk(sdCreditRequirement, firstBillingDate);
30913 tejbeer 3973
 
31697 amit.gupta 3974
            sdCreditRequirement.setRisk(creditRisk);
30913 tejbeer 3975
 
33874 ranu 3976
            sdCreditRequirement.setSuggestedLimit(suggestedAmount);
34275 tejus.loha 3977
            if (!sdCreditRequirement.isHardLimit()) {
34122 ranu 3978
                sdCreditRequirement.setLimit(suggestedAmount);
3979
            }
35393 amit 3980
            BigDecimal utilizedLimit = sdCreditService.getUtilizationAmount(fofoId);
30934 tejbeer 3981
 
31697 amit.gupta 3982
            BigDecimal availableLimit = sdCreditRequirement.getLimit().subtract(utilizedLimit);
30934 tejbeer 3983
 
31697 amit.gupta 3984
            LOGGER.info("utilizedLimit {} ", utilizedLimit);
30913 tejbeer 3985
 
31697 amit.gupta 3986
            LOGGER.info("availableLimit {} ", availableLimit);
30913 tejbeer 3987
 
31697 amit.gupta 3988
            sdCreditRequirement.setUtilizedAmount(utilizedLimit);
30929 tejbeer 3989
 
31697 amit.gupta 3990
            sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
30929 tejbeer 3991
 
31697 amit.gupta 3992
            if (creditAccount != null) {
30929 tejbeer 3993
 
31697 amit.gupta 3994
                creditAccount.setInterestRate(sdCreditRequirement.getInterestRate().floatValue());
3995
                creditAccount.setSanctionedAmount(sdCreditRequirement.getLimit().floatValue());
3996
                creditAccount.setAvailableAmount(availableLimit.floatValue());
3997
                creditAccount.setFreeDays(sdCreditRequirement.getFreeDays());
3998
                creditAccount.setUpdatedOn(LocalDateTime.now());
3999
            }
30929 tejbeer 4000
 
31697 amit.gupta 4001
        }
31177 tejbeer 4002
 
31697 amit.gupta 4003
    }
34502 amit.gupta 4004
 
34374 amit.gupta 4005
    private static final NavigableMap<Double, Double> discountMap = new TreeMap<>();
34502 amit.gupta 4006
 
34374 amit.gupta 4007
    static {
34852 amit 4008
        discountMap.put(4 * ProfitMandiConstants.ONE_LAC - 1, 0.2);    // Up to 3,99,999 -> 20%
4009
        discountMap.put(10 * ProfitMandiConstants.ONE_LAC - 1, 0.25);  // 4,00,000 to 9,99,999 -> 25%
4010
        discountMap.put(20 * ProfitMandiConstants.ONE_LAC - 1, 0.3);   // 10,00,000 to 19,99,999 -> 30%
4011
        discountMap.put(Double.MAX_VALUE, 0.4);                        // 20,00,000 and above -> 40%
34374 amit.gupta 4012
    }
34502 amit.gupta 4013
 
4014
    public BigDecimal getSuggestedLimit(double investmentValue) {
34374 amit.gupta 4015
        double percentageValue = discountMap.ceilingEntry(investmentValue).getValue();
34510 amit.gupta 4016
        return this.getSuggestedAmount(investmentValue, percentageValue);
4017
 
4018
    }
4019
 
4020
    private BigDecimal getSuggestedAmount(double investmentValue, double percentageValue) {
34374 amit.gupta 4021
        return BigDecimal.valueOf(investmentValue * percentageValue);
4022
    }
34502 amit.gupta 4023
 
35299 amit 4024
    /*private static List<Integer> hundredPercentLimitPartnerIds = Arrays.asList(175139630,
34510 amit.gupta 4025
            175139815,
4026
            175139844,
4027
            175140101
35299 amit 4028
    );*/
34510 amit.gupta 4029
 
35299 amit 4030
    private static List<Integer> hundredPercentLimitPartnerIds = Arrays.asList();
4031
 
35177 amit 4032
    private BigDecimal getSuggestedAmount(CreditAccount creditAccount, PartnerDailyInvestment
35393 amit 4033
            partnerDailyInvestment, BigDecimal utilizationAmount, BigDecimal sidbiLimit) {
33112 amit.gupta 4034
        BigDecimal suggestedAmount = BigDecimal.ZERO;
35393 amit 4035
        double utilization = utilizationAmount != null ? utilizationAmount.doubleValue() : 0;
33112 amit.gupta 4036
        //1 LAC
33295 amit.gupta 4037
        if (creditAccount == null || creditAccount.getGateway().equals(Gateway.SDDIRECT)) {
33112 amit.gupta 4038
 
35177 amit 4039
            if (partnerDailyInvestment != null) {
4040
                if (hundredPercentLimitPartnerIds.contains(partnerDailyInvestment.getFofoId())) {
35393 amit 4041
                    suggestedAmount = getSuggestedAmount(partnerDailyInvestment.getTotalInvestment() - utilization, 1);
34512 amit.gupta 4042
                    suggestedAmount = suggestedAmount.min(BigDecimal.valueOf(1500000));
34510 amit.gupta 4043
                } else {
35393 amit 4044
                    suggestedAmount = getSuggestedLimit(partnerDailyInvestment.getTotalInvestment() - utilization);
34510 amit.gupta 4045
                }
33112 amit.gupta 4046
            }
4047
            if (suggestedAmount.doubleValue() < 0) {
4048
                suggestedAmount = BigDecimal.ZERO;
4049
            }
33355 amit.gupta 4050
        } else if (creditAccount.getGateway().equals(Gateway.SIDBI) && sidbiLimit != null) {
35393 amit 4051
            suggestedAmount = getSuggestedLimit(partnerDailyInvestment.getTotalInvestment() - utilization);
34993 ranu 4052
            suggestedAmount = suggestedAmount.max(sidbiLimit);
4053
 
4054
 
33112 amit.gupta 4055
        }
4056
        return suggestedAmount;
4057
    }
4058
 
31697 amit.gupta 4059
    public void notifyDefaultLoans() throws ProfitMandiBusinessException, MessagingException, IOException {
30929 tejbeer 4060
 
31697 amit.gupta 4061
        sdCreditService.updateRisk();
34729 amit.gupta 4062
        List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
31697 amit.gupta 4063
        if (!defaultLoans.isEmpty()) {
4064
            this.sendDefaultLoanAlert(defaultLoans);
4065
        }
30929 tejbeer 4066
 
31697 amit.gupta 4067
    }
30929 tejbeer 4068
 
32482 amit.gupta 4069
    public void sendDefaultLoanAlert(List<Loan> defaultLoans) throws
4070
            ProfitMandiBusinessException, MessagingException, IOException {
31697 amit.gupta 4071
        String subject = "Default Partners";
30931 tejbeer 4072
 
35591 aman 4073
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
30929 tejbeer 4074
 
33452 amit.gupta 4075
        for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
31697 amit.gupta 4076
            List<Loan> filteredRows = new ArrayList<>();
4077
            for (Loan loan : defaultLoans) {
30929 tejbeer 4078
 
31697 amit.gupta 4079
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30929 tejbeer 4080
 
31697 amit.gupta 4081
                    filteredRows.add(loan);
4082
                }
4083
            }
4084
            if (!filteredRows.isEmpty()) {
35591 aman 4085
                String[] email = new String[]{storeGuyEntry.getKey(),"neeraj.gupta@smartdukaan.com"};
31697 amit.gupta 4086
                String messageText = this.getMessageForDueDateExtend(filteredRows);
32350 amit.gupta 4087
                this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, subject);
30982 tejbeer 4088
 
31697 amit.gupta 4089
            }
30936 tejbeer 4090
 
31697 amit.gupta 4091
        }
33628 tejus.loha 4092
        String messageText = this.getMessageForDueDateExtend(defaultLoans);
34858 amit 4093
        this.sendMailOfHtmlFormat(googleMailSender, new String[]{"puneet.wahi@smartdukaan.com", "rahul.latwal@smartdukaan.com", "dilbag.singh@smartdukaan.com"}, messageText, null, subject);
30982 tejbeer 4094
 
31697 amit.gupta 4095
        for (Loan defaultLoan : defaultLoans) {
4096
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
30929 tejbeer 4097
 
31886 tejbeer 4098
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 4099
 
31697 amit.gupta 4100
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
30936 tejbeer 4101
 
31697 amit.gupta 4102
            Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 4103
 
34729 amit.gupta 4104
            String title = "Outstanding Credit Payment Overdue!";
31697 amit.gupta 4105
            String url = "http://app.smartdukaan.com/pages/home/credit";
34731 amit.gupta 4106
            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 4107
            notificationService.sendNotification(defaultLoan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 4108
 
31697 amit.gupta 4109
            // notificationService.sendWhatsappMessage(message, title,
4110
            // address.getPhoneNumber());
30929 tejbeer 4111
 
31697 amit.gupta 4112
        }
4113
    }
30929 tejbeer 4114
 
31697 amit.gupta 4115
    private String getMessageForDueDateExtend(List<Loan> loans) throws ProfitMandiBusinessException {
33553 ranu 4116
        Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
4117
        Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
4118
        List<AST> asts = astRepository.selectAll();
4119
        Map<Integer, AST> astMap = asts.stream()
4120
                .collect(Collectors.toMap(AST::getId, ast -> ast));
31697 amit.gupta 4121
        StringBuilder sb = new StringBuilder();
4122
        sb.append(
33553 ranu 4123
                "<html><body><p>Alert</p><p>Default Partners :-</p>" + "<br/><p>EveryDay Rs.100 charged as Penalty</p>" + "<br/>" +
4124
                        "<table style='border:1px solid black ;padding: 5px';>");
4125
        sb.append("<tbody>\n" +
4126
                "<tr>\n" +
4127
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" +
33555 ranu 4128
                "<th style='border:1px solid black;padding: 5px'>State Name</th>\n" +
4129
                "<th style='border:1px solid black;padding: 5px'>Area</th>\n" +
4130
                "<th style='border:1px solid black;padding: 5px'>Territory</th>\n" +
33553 ranu 4131
                "<th style='border:1px solid black;padding: 5px'>due date</th>\n" +
4132
                "<th style='border:1px solid black;padding: 5px'>Days</th>\n" +
33664 amit.gupta 4133
                "<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n" +
33810 ranu 4134
                "<th style='border:1px solid black;padding: 5px'>RBM L2</th>\n" +
33553 ranu 4135
                "<th style='border:1px solid black;padding: 5px'>RBM L1</th>\n" +
4136
                "<th style='border:1px solid black;padding: 5px'>Sales L1</th>\n" +
4137
                "<th style='border:1px solid black;padding: 5px'>Sales L2</th>\n" +
4138
                "</tr>");
31697 amit.gupta 4139
        for (Loan entry : loans) {
30929 tejbeer 4140
 
31697 amit.gupta 4141
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
30929 tejbeer 4142
 
31886 tejbeer 4143
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 4144
 
31697 amit.gupta 4145
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
30929 tejbeer 4146
 
31697 amit.gupta 4147
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30929 tejbeer 4148
 
31697 amit.gupta 4149
            sb.append("<tr>");
31886 tejbeer 4150
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
33555 ranu 4151
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getAddress().getState() + "</td>");
4152
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getArea() + "</td>");
4153
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getTerritory() + "</td>");
31886 tejbeer 4154
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 4155
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 4156
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
33553 ranu 4157
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager() + "</td>");
4158
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager() + "</td>");
4159
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager() + "</td>");
4160
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager() + "</td>");
31397 tejbeer 4161
 
33555 ranu 4162
 
31697 amit.gupta 4163
            sb.append("</tr>");
31397 tejbeer 4164
 
31697 amit.gupta 4165
        }
31397 tejbeer 4166
 
31697 amit.gupta 4167
        sb.append("</tbody></table></body></html>");
31397 tejbeer 4168
 
31697 amit.gupta 4169
        return sb.toString();
4170
    }
31397 tejbeer 4171
 
35111 ranu 4172
    private String getMessageForDueDateCross(List<Loan> dueDateCrossLoans) throws ProfitMandiBusinessException {
33161 ranu 4173
        Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
33452 amit.gupta 4174
        Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
33553 ranu 4175
        List<AST> asts = astRepository.selectAll();
4176
        Map<Integer, AST> astMap = asts.stream()
4177
                .collect(Collectors.toMap(AST::getId, ast -> ast));
4178
 
31697 amit.gupta 4179
        StringBuilder sb = new StringBuilder();
35110 ranu 4180
        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 4181
                "<table style='border:1px solid black ;padding: 5px';>");
4182
        sb.append("<tbody>\n" + "<tr>\n" +
33256 amit.gupta 4183
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" +
4184
                "<th style='border:1px solid black;padding: 5px'>State Name</th>\n" +
33555 ranu 4185
                "<th style='border:1px solid black;padding: 5px'>Area</th>\n" +
33553 ranu 4186
                "<th style='border:1px solid black;padding: 5px'>Territory</th>\n" +
33256 amit.gupta 4187
                "<th style='border:1px solid black;padding: 5px'>due date</th>\n" +
4188
                "<th style='border:1px solid black;padding: 5px'>Days</th>\n" +
4189
                "<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n" +
33810 ranu 4190
                "<th style='border:1px solid black;padding: 5px'>RBM L2</th>\n" +
33256 amit.gupta 4191
                "<th style='border:1px solid black;padding: 5px'>RBM L1</th>\n" +
4192
                "<th style='border:1px solid black;padding: 5px'>Sales L1</th>\n" +
4193
                "<th style='border:1px solid black;padding: 5px'>Sales L2</th>\n" +
35107 ranu 4194
                "<th style='border:1px solid black;padding: 5px'>Limit Assigned</th>\n" +
33161 ranu 4195
                "</tr>");
31397 tejbeer 4196
 
35111 ranu 4197
        for (Loan entry : dueDateCrossLoans) {
4198
            DecimalFormat df = new DecimalFormat("#.##");
31397 tejbeer 4199
 
31697 amit.gupta 4200
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
31397 tejbeer 4201
 
31886 tejbeer 4202
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31397 tejbeer 4203
 
31697 amit.gupta 4204
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
31397 tejbeer 4205
 
31697 amit.gupta 4206
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
31397 tejbeer 4207
 
35106 ranu 4208
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(customRetailer.getPartnerId());
4209
 
31697 amit.gupta 4210
            sb.append("<tr>");
31886 tejbeer 4211
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
33162 ranu 4212
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getAddress().getState() + "</td>");
33553 ranu 4213
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getArea() + "</td>");
4214
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getTerritory() + "</td>");
30936 tejbeer 4215
 
31886 tejbeer 4216
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 4217
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 4218
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
33161 ranu 4219
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager() + "</td>");
4220
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager() + "</td>");
4221
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager() + "</td>");
4222
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager() + "</td>");
35521 amit 4223
            sb.append("<td style='border:1px solid black;padding: 5px'>" + df.format(sdCreditRequirement.getLimit()) + "</td>");
31697 amit.gupta 4224
            sb.append("</tr>");
4225
        }
31397 tejbeer 4226
 
31697 amit.gupta 4227
        sb.append("</tbody></table></body></html>");
31397 tejbeer 4228
 
31697 amit.gupta 4229
        return sb.toString();
4230
    }
31397 tejbeer 4231
 
32307 amit.gupta 4232
    public void notifyLoanDueDateCross() throws Exception {
31397 tejbeer 4233
 
35111 ranu 4234
        List<Loan> dueDateCrossLoans = sdCreditService.getDueDateCrossLoan();
4235
        List<Loan> allActiveLoans = sdCreditService.getAllActiveLoan();
31697 amit.gupta 4236
        if (!dueDateCrossLoans.isEmpty()) {
35521 amit 4237
            this.sendDueDateCrossLoanAlert(dueDateCrossLoans, allActiveLoans);
31697 amit.gupta 4238
        }
31397 tejbeer 4239
 
31697 amit.gupta 4240
    }
31397 tejbeer 4241
 
35521 amit 4242
    private void sendDueDateCrossLoanAlert(List<Loan> dueDateCrossLoans, List<Loan> allActiveLoans) throws Exception {
35591 aman 4243
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ABM, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
31397 tejbeer 4244
 
35115 ranu 4245
        for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
33631 tejus.loha 4246
            List<Loan> filteredRows = new ArrayList<>();
31697 amit.gupta 4247
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 4248
 
31697 amit.gupta 4249
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30982 tejbeer 4250
 
31697 amit.gupta 4251
                    filteredRows.add(loan);
4252
                }
4253
            }
35111 ranu 4254
 
35112 ranu 4255
            List<Loan> filteredAllActiveLoans = new ArrayList<>();
35111 ranu 4256
            for (Loan loan : allActiveLoans) {
4257
 
4258
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
4259
 
35112 ranu 4260
                    filteredAllActiveLoans.add(loan);
35111 ranu 4261
                }
4262
            }
4263
 
35112 ranu 4264
            ByteArrayOutputStream byteArrayOutputStream = null;
4265
            Utils.Attachment attachment1 = null;
35521 amit 4266
            if (!filteredAllActiveLoans.isEmpty()) {
4267
                byteArrayOutputStream = this.generateLoanCsv(filteredAllActiveLoans);
4268
                attachment1 = new Utils.Attachment("partnner-credit.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
35111 ranu 4269
 
4270
            }
4271
 
4272
 
31697 amit.gupta 4273
            if (!filteredRows.isEmpty()) {
4274
                String messageText = this.getMessageForDueDateCross(filteredRows);
35591 aman 4275
                String[] email = new String[]{storeGuyEntry.getKey(),"neeraj.gupta@smartdukaan.com"};
30982 tejbeer 4276
 
35521 amit 4277
                if (attachment1 != null) {
35112 ranu 4278
                    Utils.sendMailWithAttachments(googleMailSender, email, null, null, "Partner Credit Report", messageText, true, attachment1);
35521 amit 4279
                } else {
4280
                    this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, "Due Date Cross");
30936 tejbeer 4281
 
35521 amit 4282
                }
4283
 
31697 amit.gupta 4284
            }
30936 tejbeer 4285
 
35115 ranu 4286
        }
35113 ranu 4287
 
4288
        String messageText = this.getMessageForDueDateCross(dueDateCrossLoans);
4289
        ByteArrayOutputStream byteArrayOutputStream = this.generateLoanCsv(allActiveLoans);
4290
        Utils.Attachment attachment = null;
35521 amit 4291
        if (byteArrayOutputStream != null) {
4292
            attachment = new Utils.Attachment("partnner-credit.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
35113 ranu 4293
 
31697 amit.gupta 4294
        }
33628 tejus.loha 4295
 
35521 amit 4296
        if (attachment != null) {
35115 ranu 4297
            Utils.sendMailWithAttachments(googleMailSender, new String[]{"sdtech@smartdukaan.com"}, null, null, "Partner Credit Report", messageText, true, attachment);
35521 amit 4298
        } else {
35115 ranu 4299
            this.sendMailOfHtmlFormat(googleMailSender, new String[]{"sdtech@smartdukaan.com"}, messageText, null, "Due Date Cross");
35113 ranu 4300
        }
33628 tejus.loha 4301
 
35111 ranu 4302
 
31697 amit.gupta 4303
        if (!dueDateCrossLoans.isEmpty()) {
4304
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 4305
 
31697 amit.gupta 4306
                long noOfdaysBetween = ChronoUnit.DAYS.between(loan.getDueDate().toLocalDate(), LocalDate.now());
30989 tejbeer 4307
 
31697 amit.gupta 4308
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30989 tejbeer 4309
 
31697 amit.gupta 4310
                Address address = addressRepository.selectById(user.getAddressId());
30982 tejbeer 4311
 
31697 amit.gupta 4312
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 4313
 
31697 amit.gupta 4314
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30936 tejbeer 4315
 
31886 tejbeer 4316
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 4317
 
31697 amit.gupta 4318
                String url = "http://app.smartdukaan.com/pages/home/credit";
30936 tejbeer 4319
 
31697 amit.gupta 4320
                String title = "Alert!";
34729 amit.gupta 4321
                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 4322
 
31886 tejbeer 4323
                notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 4324
 
32841 amit.gupta 4325
                //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4326
 
31697 amit.gupta 4327
            }
4328
        }
30982 tejbeer 4329
 
31697 amit.gupta 4330
    }
30936 tejbeer 4331
 
35112 ranu 4332
    private ByteArrayOutputStream generateLoanCsv(List<Loan> loans) throws ProfitMandiBusinessException {
4333
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = null;
4334
 
4335
 
4336
        if (!loans.isEmpty()) {
4337
            Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
4338
            Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
4339
            List<AST> asts = astRepository.selectAll();
4340
            Map<Integer, AST> astMap = asts.stream()
4341
                    .collect(Collectors.toMap(AST::getId, ast -> ast));
4342
            try {
4343
                List<String> headers = Arrays.asList(
4344
                        "PartnerName", "State Name", "Area", "Territory",
4345
                        "Due Date", "Days", "Pending Amount",
4346
                        "RBM L2", "RBM L1", "Sales L1", "Sales L2", "Limit Assigned"
4347
                );
4348
 
4349
                List<List<?>> rows = new ArrayList<>();
4350
 
4351
                for (Loan entry : loans) {
4352
 
4353
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
4354
                    double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
4355
 
35114 ranu 4356
//                    long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
4357
                    long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getCreatedOn().toLocalDate(), LocalDateTime.now());
35112 ranu 4358
 
4359
                    CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
4360
                    SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(customRetailer.getPartnerId());
4361
                    DecimalFormat df = new DecimalFormat("#.##");
4362
                    List<String> row = Arrays.asList(
4363
                            customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")",
4364
                            customRetailer.getAddress().getState(),
4365
                            astMap.get(customRetailer.getAstId()).getArea(),
4366
                            astMap.get(customRetailer.getAstId()).getTerritory(),
4367
                            entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")),
4368
                            String.valueOf(noOfdaysBetween),
4369
                            df.format(Math.abs(amount)),
4370
                            fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager(),
4371
                            fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager(),
4372
                            fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager(),
4373
                            fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager(),
4374
                            df.format(sdCreditRequirement.getLimit())
4375
                    );
4376
 
4377
                    rows.add(row);
4378
                }
4379
 
4380
                byteArrayOutputStream = FileUtil.getCSVByteStream(headers, rows);
4381
 
4382
 
4383
            } catch (Exception e) {
4384
                throw new RuntimeException(e);
4385
            }
4386
 
4387
        }
4388
        return byteArrayOutputStream;
4389
    }
4390
 
4391
 
32307 amit.gupta 4392
    public void alertForDueDate() throws Exception {
30936 tejbeer 4393
 
31697 amit.gupta 4394
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30936 tejbeer 4395
 
31697 amit.gupta 4396
        if (!loans.isEmpty()) {
4397
            for (Loan loan : loans) {
30936 tejbeer 4398
 
31697 amit.gupta 4399
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30936 tejbeer 4400
 
31697 amit.gupta 4401
                Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 4402
 
31697 amit.gupta 4403
                long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), loan.getDueDate().toLocalDate());
30936 tejbeer 4404
 
31697 amit.gupta 4405
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 4406
 
31697 amit.gupta 4407
                if (noOfdaysBetween <= 4 && noOfdaysBetween >= 0) {
4408
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
31886 tejbeer 4409
                    double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 4410
 
31697 amit.gupta 4411
                    String title = "Alert!";
4412
                    String url = "http://app.smartdukaan.com/pages/home/credit";
4413
                    String message = null;
4414
                    if (noOfdaysBetween == 0) {
30936 tejbeer 4415
 
34729 amit.gupta 4416
                        message = "Your total outstanding Credit amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + " is due for Today, Pay Now!!";
30982 tejbeer 4417
 
31697 amit.gupta 4418
                    } else {
30982 tejbeer 4419
 
34729 amit.gupta 4420
                        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 4421
 
31697 amit.gupta 4422
                    }
31886 tejbeer 4423
                    notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
32841 amit.gupta 4424
                    //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4425
 
31697 amit.gupta 4426
                }
4427
            }
4428
        }
30984 tejbeer 4429
 
31697 amit.gupta 4430
    }
30982 tejbeer 4431
 
32307 amit.gupta 4432
    public void userMobileNumberOptIn() throws Exception {
30982 tejbeer 4433
 
31697 amit.gupta 4434
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
30982 tejbeer 4435
 
31886 tejbeer 4436
        List<com.spice.profitmandi.dao.entity.user.User> users = userUserRepository.selectByIds(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
30982 tejbeer 4437
 
31886 tejbeer 4438
        List<Address> addresses = addressRepository.selectByIds(users.stream().map(x -> x.getAddressId()).collect(Collectors.toList()));
30982 tejbeer 4439
 
31697 amit.gupta 4440
        LOGGER.info("addresses" + addresses);
30984 tejbeer 4441
 
31697 amit.gupta 4442
        for (Address address : addresses) {
32307 amit.gupta 4443
            notificationService.optIn(address.getPhoneNumber());
30982 tejbeer 4444
 
31697 amit.gupta 4445
        }
30982 tejbeer 4446
 
31697 amit.gupta 4447
    }
30982 tejbeer 4448
 
31697 amit.gupta 4449
    public void authUserMobileNumberOptIn() throws HttpHostConnectException, ProfitMandiBusinessException {
31206 tejbeer 4450
 
31697 amit.gupta 4451
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
4452
        LOGGER.info("authUsers" + authUsers);
31206 tejbeer 4453
 
31697 amit.gupta 4454
        for (AuthUser authUser : authUsers) {
4455
            Map<String, String> requestheaders = new HashMap<>();
4456
            requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
4457
            Map<String, String> requestParams = new HashMap<>();
4458
            requestParams.put("userid", String.valueOf(2000215976));
4459
            requestParams.put("password", "MFRd!BBL");
4460
            requestParams.put("phone_number", authUser.getMobileNumber());
4461
            requestParams.put("auth_scheme", "plain");
4462
            requestParams.put("v", "1.1");
4463
            requestParams.put("format", "json");
31206 tejbeer 4464
 
31697 amit.gupta 4465
            requestParams.put("method", "OPT_IN");
31206 tejbeer 4466
 
31697 amit.gupta 4467
            requestParams.put("channel", "WHATSAPP");
31886 tejbeer 4468
            String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
31697 amit.gupta 4469
            LOGGER.info("response" + response);
4470
        }
31206 tejbeer 4471
 
31697 amit.gupta 4472
    }
31206 tejbeer 4473
 
31697 amit.gupta 4474
    @Autowired
4475
    private HygieneDataRepository hygieneDataRepository;
31209 tejbeer 4476
 
31697 amit.gupta 4477
    public void hygineAlertForPartner() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 4478
 
31697 amit.gupta 4479
        List<String> remarks = new ArrayList<>();
4480
        remarks.add("Out of Service");
4481
        remarks.add("Duplicate number");
4482
        remarks.add("Partner number");
31886 tejbeer 4483
        List<HygieneData> hygieneData = hygieneDataRepository.selectAllByDisposedDateAndRemark(LocalDate.now(), remarks);
31206 tejbeer 4484
 
31697 amit.gupta 4485
        if (!hygieneData.isEmpty()) {
31206 tejbeer 4486
 
31886 tejbeer 4487
            Map<Integer, List<HygieneData>> partnerHygieneDataMap = hygieneData.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 4488
 
31697 amit.gupta 4489
            for (Entry<Integer, List<HygieneData>> partnerHygieneDataMapEntry : partnerHygieneDataMap.entrySet()) {
31206 tejbeer 4490
 
31697 amit.gupta 4491
                CustomRetailer customRetailer = retailerService.getFofoRetailer(partnerHygieneDataMapEntry.getKey());
31206 tejbeer 4492
 
31697 amit.gupta 4493
                StringBuilder sb = new StringBuilder();
31886 tejbeer 4494
                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 4495
 
31886 tejbeer 4496
                        + " </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 4497
 
31697 amit.gupta 4498
                        + "<br/><table style='border:1px solid black ;padding: 5px';>");
4499
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4500
                sb.append("<th style='border:1px solid black;padding: 5px'>Invoice Number</th>\n");
4501
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Name</th>\n");
4502
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Number</th>\n");
4503
                sb.append("</tr>\n");
31206 tejbeer 4504
 
31697 amit.gupta 4505
                List<HygieneData> hygienes = partnerHygieneDataMapEntry.getValue();
31206 tejbeer 4506
 
31697 amit.gupta 4507
                List<Integer> orderIds = hygienes.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
31206 tejbeer 4508
 
31697 amit.gupta 4509
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectAllByOrderIds(orderIds);
31206 tejbeer 4510
 
31697 amit.gupta 4511
                for (FofoOrder fofoOrder : fofoOrders) {
4512
                    Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
4513
                    sb.append("<tr>");
31886 tejbeer 4514
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoOrder.getInvoiceNumber() + "</td>\n");
4515
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getFirstName() + "" + customer.getLastName() + "</td>\n");
4516
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getMobileNumber() + "</td>\n");
31206 tejbeer 4517
 
31697 amit.gupta 4518
                    sb.append("</tr>\n");
4519
                }
31206 tejbeer 4520
 
31697 amit.gupta 4521
                sb.append("</tbody></table></body></html>");
4522
                String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 4523
 
32350 amit.gupta 4524
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31206 tejbeer 4525
 
31697 amit.gupta 4526
            }
31206 tejbeer 4527
 
31697 amit.gupta 4528
        }
31206 tejbeer 4529
 
31697 amit.gupta 4530
    }
31206 tejbeer 4531
 
33046 amit.gupta 4532
    //
4533
    public void setInventoryItemIdToPriceDropImei() {
4534
        List<PriceDropIMEI> priceDropIMEIList = priceDropIMEIRepository.selectAllMissingInventoryItemIds();
4535
        LOGGER.info("Problems with - {} entries", priceDropIMEIList.size());
4536
        //priceDropIMEIList.stream().collect(C)
4537
        for (PriceDropIMEI priceDropIMEI : priceDropIMEIList) {
4538
            System.out.println(priceDropIMEI.getImei());
4539
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllBySerialNumberFofoId(priceDropIMEI.getImei(), priceDropIMEI.getPartnerId());
33051 amit.gupta 4540
            if (inventoryItems.size() == 0) {
33046 amit.gupta 4541
                LOGGER.info("Could not find Grn - FofoID {} , Imei {} ", priceDropIMEI);
33051 amit.gupta 4542
            } else if (inventoryItems.size() > 1) {
33046 amit.gupta 4543
                LOGGER.info("Found 2 such instance for - FofoID {} , Imei {} ", priceDropIMEI.getImei(), priceDropIMEI.getPartnerId());
4544
            } else {
4545
                priceDropIMEI.setInventoryItemId(inventoryItems.get(0).getId());
4546
            }
4547
 
4548
        }
4549
    }
4550
 
33051 amit.gupta 4551
    @Autowired
4552
    SaholicReservationSnapshotRepository saholicReservationSnapshotRepository;
4553
 
33256 amit.gupta 4554
    public void removePartialBillingForTransaction(int transactionId) throws ProfitMandiBusinessException {
35424 amit 4555
        // Fetch with pessimistic lock to prevent concurrent modifications
4556
        List<Order> orderList = orderRepository.selectAllByTransactionIdForUpdate(transactionId);
33051 amit.gupta 4557
        Map<Integer, Order> orderMap = orderList.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
4558
        //Delete scanRecords
4559
        List<WarehouseScan> warehouseScans = warehouseScanRepository.selectAllByOrderIds(new ArrayList<>(orderMap.keySet()));
4560
        for (WarehouseScan warehouseScan : warehouseScans) {
4561
            warehouseScanRepository.delete(warehouseScan);
4562
            WarehouseInventoryItem warehouseInventoryItem = warehouseInventoryItemRepository.selectById(warehouseScan.getInventoryItemId());
4563
            warehouseInventoryItem.setLastScanType(in.shop2020.warehouse.ScanType.PURCHASE);
4564
            warehouseInventoryItem.setCurrentQuantity(warehouseInventoryItem.getCurrentQuantity() + warehouseScan.getQuantity());
4565
        }
4566
 
4567
        for (Order order : orderList) {
33078 ranu 4568
            if (order.getBillingTimestamp() != null) {
33056 amit.gupta 4569
                order.setStatus(OrderStatus.ACCEPTED);
4570
                order.setStatusDescription("Submitted for Processing");
4571
                order.setBillingTimestamp(null);
4572
                order.setBilledBy(null);
33057 amit.gupta 4573
                order.setSerialNumber(null);
33056 amit.gupta 4574
                order.setJacketNumber(null);
33060 amit.gupta 4575
                order.getLineItem().setSerialNumber(null);
33056 amit.gupta 4576
                List<LineItemImei> lineItemImeis = lineItemImeisRepository.selectByLineItemId(order.getLineItem().getId());
4577
                for (LineItemImei lineItemImei : lineItemImeis) {
4578
                    lineItemImeisRepository.delete(lineItemImei);
4579
                }
4580
                SaholicReservationSnapshot saholicReservationSnapshot = saholicReservationSnapshotRepository
4581
                        .selectByOrderId(order.getId());
4582
                if (saholicReservationSnapshot == null) {
4583
                    saholicInventoryService.addReservationCount(order.getLineItem().getItemId(),
4584
                            order.getFulfilmentWarehouseId(), order.getLineItem().getQuantity(), order.getId());
4585
                }
33055 amit.gupta 4586
            }
33051 amit.gupta 4587
        }
4588
    }
4589
 
31697 amit.gupta 4590
    public void hygineAlertForInternalTeam() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 4591
 
31697 amit.gupta 4592
        List<String> remarks = new ArrayList<>();
4593
        remarks.add("Out of Service");
4594
        remarks.add("Duplicate number");
4595
        remarks.add("Partner number");
31886 tejbeer 4596
        List<HygieneData> hygieneDataLastThreeMonth = hygieneDataRepository.selectDisposedDateAndRemarks(
4597
                LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay(), LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX), remarks);
31206 tejbeer 4598
 
31886 tejbeer 4599
        List<HygieneData> hygieneDataRecentMonth = hygieneDataRepository.selectDisposedDateAndRemarks(LocalDate.now().withDayOfMonth(1), remarks);
31697 amit.gupta 4600
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
4601
        Map<Integer, List<HygieneData>> partnerHygieneLastThreeMonthMap = null;
31206 tejbeer 4602
 
31697 amit.gupta 4603
        Map<Integer, List<HygieneData>> partnerHygieneDataRecentMonth = null;
31206 tejbeer 4604
 
31697 amit.gupta 4605
        if (!hygieneDataLastThreeMonth.isEmpty()) {
31886 tejbeer 4606
            partnerHygieneLastThreeMonthMap = hygieneDataLastThreeMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 4607
 
31697 amit.gupta 4608
        }
31206 tejbeer 4609
 
31697 amit.gupta 4610
        if (!hygieneDataRecentMonth.isEmpty()) {
31886 tejbeer 4611
            partnerHygieneDataRecentMonth = hygieneDataRecentMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31697 amit.gupta 4612
        }
31206 tejbeer 4613
 
31697 amit.gupta 4614
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31206 tejbeer 4615
 
31697 amit.gupta 4616
            String email = storeGuyEntry.getKey();
31206 tejbeer 4617
 
31697 amit.gupta 4618
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
31206 tejbeer 4619
 
31697 amit.gupta 4620
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData = new HashMap<>();
4621
            Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData = new HashMap<>();
4622
            for (Integer fofoId : fofoIds) {
31206 tejbeer 4623
 
31697 amit.gupta 4624
                partnerYearMonthData.put(fofoId, null);
4625
                partnerDateWiseData.put(fofoId, null);
4626
                if (!partnerHygieneLastThreeMonthMap.isEmpty()) {
4627
                    List<HygieneData> hygienes = partnerHygieneLastThreeMonthMap.get(fofoId);
31206 tejbeer 4628
 
31697 amit.gupta 4629
                    if (hygienes != null) {
31886 tejbeer 4630
                        Map<YearMonth, List<HygieneData>> yearMonthData = hygienes.stream().collect(groupingBy(x -> YearMonth.from(x.getDisposedTimestamp())));
31206 tejbeer 4631
 
31697 amit.gupta 4632
                        partnerYearMonthData.put(fofoId, yearMonthData);
31206 tejbeer 4633
 
31697 amit.gupta 4634
                    }
4635
                    List<HygieneData> dateWiseHygienes = partnerHygieneDataRecentMonth.get(fofoId);
31206 tejbeer 4636
 
31697 amit.gupta 4637
                    if (dateWiseHygienes != null) {
31206 tejbeer 4638
 
31886 tejbeer 4639
                        Map<LocalDate, List<HygieneData>> dateWiseData = hygienes.stream().collect(groupingBy(x -> (x.getDisposedTimestamp()).toLocalDate()));
31206 tejbeer 4640
 
31697 amit.gupta 4641
                        partnerDateWiseData.put(fofoId, dateWiseData);
31206 tejbeer 4642
 
31697 amit.gupta 4643
                    }
31206 tejbeer 4644
 
31697 amit.gupta 4645
                }
31206 tejbeer 4646
 
31697 amit.gupta 4647
            }
31206 tejbeer 4648
 
31697 amit.gupta 4649
            String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 4650
 
31697 amit.gupta 4651
            LOGGER.info("hygieneData {}", partnerDateWiseData.values());
31206 tejbeer 4652
 
31697 amit.gupta 4653
            boolean partnerDateWise = partnerDateWiseData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 4654
 
31697 amit.gupta 4655
            boolean partnerYearMonth = partnerYearMonthData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 4656
 
31697 amit.gupta 4657
            if (!partnerDateWise && !partnerYearMonth) {
4658
                String sb = this.getMessageHygieneAlertForPartner(partnerYearMonthData, partnerDateWiseData);
32350 amit.gupta 4659
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb, null, subject);
31697 amit.gupta 4660
            }
31206 tejbeer 4661
 
31697 amit.gupta 4662
        }
31206 tejbeer 4663
 
31697 amit.gupta 4664
    }
31206 tejbeer 4665
 
31697 amit.gupta 4666
    private String getMessageHygieneAlertForPartner(
33256 amit.gupta 4667
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData, Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData)
4668
            throws ProfitMandiBusinessException {
31206 tejbeer 4669
 
31697 amit.gupta 4670
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31206 tejbeer 4671
 
31697 amit.gupta 4672
        LocalDateTime startDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
4673
        LocalDateTime endDate = LocalDateTime.now();
31206 tejbeer 4674
 
31697 amit.gupta 4675
        LocalDateTime startYearMonth = LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay();
31886 tejbeer 4676
        LocalDateTime endYearMonth = LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX);
31206 tejbeer 4677
 
31697 amit.gupta 4678
        DateTimeFormatter dateYearMonthFormatter = DateTimeFormatter.ofPattern("MMM''uu");
31206 tejbeer 4679
 
31697 amit.gupta 4680
        List<YearMonth> yearMonthRange = new ArrayList<>();
4681
        yearMonthRange.add(YearMonth.from(startYearMonth));
31206 tejbeer 4682
 
31697 amit.gupta 4683
        yearMonthRange.add(YearMonth.from(startYearMonth.plusMonths(1)));
31206 tejbeer 4684
 
31697 amit.gupta 4685
        yearMonthRange.add(YearMonth.from(endYearMonth));
31206 tejbeer 4686
 
31697 amit.gupta 4687
        long noOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate.plusDays(1));
31206 tejbeer 4688
 
31886 tejbeer 4689
        List<LocalDate> dateRange = Stream.iterate(startDate.toLocalDate(), date -> date.plusDays(1)).limit(noOfDaysBetween).collect(Collectors.toList());
31206 tejbeer 4690
 
31697 amit.gupta 4691
        StringBuilder sb = new StringBuilder();
31886 tejbeer 4692
        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 4693
 
31697 amit.gupta 4694
                + "<table style='border:1px solid black ;padding: 5px';>");
4695
        sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4696
        sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31206 tejbeer 4697
 
31697 amit.gupta 4698
        for (YearMonth yearMonth : yearMonthRange) {
31886 tejbeer 4699
            sb.append("<th style='border:1px solid black;padding: 5px'>" + yearMonth.format(dateYearMonthFormatter) + "</th>\n");
31697 amit.gupta 4700
        }
31206 tejbeer 4701
 
31697 amit.gupta 4702
        for (LocalDate localDate : dateRange) {
4703
            sb.append("<th style='border:1px solid black;padding: 5px'>" + localDate + "</th>\n");
4704
        }
31206 tejbeer 4705
 
31697 amit.gupta 4706
        sb.append("</tr>\n");
31206 tejbeer 4707
 
31886 tejbeer 4708
        for (Entry<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthEntry : partnerYearMonthData.entrySet()) {
31206 tejbeer 4709
 
31697 amit.gupta 4710
            int fofoId = partnerYearMonthEntry.getKey();
31206 tejbeer 4711
 
31697 amit.gupta 4712
            Map<YearMonth, List<HygieneData>> yearMonthData = partnerYearMonthEntry.getValue();
31206 tejbeer 4713
 
31697 amit.gupta 4714
            Map<LocalDate, List<HygieneData>> dateWiseData = partnerDateWiseData.get(fofoId);
31206 tejbeer 4715
 
31697 amit.gupta 4716
            if (yearMonthData == null && dateWiseData == null) {
4717
                continue;
4718
            }
31206 tejbeer 4719
 
31697 amit.gupta 4720
            sb.append("<tr>");
31886 tejbeer 4721
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31697 amit.gupta 4722
            for (YearMonth yearMonth : yearMonthRange) {
31206 tejbeer 4723
 
31697 amit.gupta 4724
                if (yearMonthData == null) {
4725
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4726
 
31697 amit.gupta 4727
                } else {
4728
                    List<HygieneData> hygieneList = yearMonthData.get(yearMonth);
31206 tejbeer 4729
 
31697 amit.gupta 4730
                    if (hygieneList != null) {
4731
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31206 tejbeer 4732
 
31697 amit.gupta 4733
                    } else {
4734
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4735
 
31697 amit.gupta 4736
                    }
4737
                }
4738
            }
31206 tejbeer 4739
 
31697 amit.gupta 4740
            for (LocalDate localDate : dateRange) {
31206 tejbeer 4741
 
31697 amit.gupta 4742
                if (dateWiseData == null) {
4743
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4744
 
31697 amit.gupta 4745
                } else {
4746
                    List<HygieneData> hygieneList = dateWiseData.get(localDate);
31206 tejbeer 4747
 
31697 amit.gupta 4748
                    if (hygieneList != null) {
4749
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31218 tejbeer 4750
 
31697 amit.gupta 4751
                    } else {
4752
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31218 tejbeer 4753
 
31697 amit.gupta 4754
                    }
4755
                }
4756
            }
4757
            sb.append("</tr>");
31218 tejbeer 4758
 
31697 amit.gupta 4759
        }
31218 tejbeer 4760
 
31697 amit.gupta 4761
        sb.append("</tbody></table></body></html>");
31218 tejbeer 4762
 
31697 amit.gupta 4763
        return sb.toString();
4764
    }
31218 tejbeer 4765
 
33874 ranu 4766
    @Autowired
4767
    private MonthlyTargetRepository monthlyTargetRepository;
31218 tejbeer 4768
 
31697 amit.gupta 4769
    public void monthlyTargetForPartner() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 4770
 
31697 amit.gupta 4771
        LocalDateTime curDate = LocalDateTime.now();
4772
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 4773
 
31886 tejbeer 4774
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 4775
 
31886 tejbeer 4776
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
4777
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 4778
 
31697 amit.gupta 4779
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 4780
 
31697 amit.gupta 4781
        for (Entry<Integer, MonthlyTarget> partnerMonthlyTargetEntry : partnersMonthlyTarget.entrySet()) {
31249 tejbeer 4782
 
31697 amit.gupta 4783
            int fofoId = partnerMonthlyTargetEntry.getKey();
31249 tejbeer 4784
 
31697 amit.gupta 4785
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
31249 tejbeer 4786
 
31697 amit.gupta 4787
            Double purchaseTarget = partnerMonthlyTargetEntry.getValue().getPurchaseTarget();
31218 tejbeer 4788
 
31697 amit.gupta 4789
            Double saleTarget = partnerMonthlyTargetEntry.getValue().getSaleTarget();
31218 tejbeer 4790
 
31697 amit.gupta 4791
            if (purchaseTarget > 0) {
4792
                Double purchase = secondaryMtd.get(fofoId);
31249 tejbeer 4793
 
31697 amit.gupta 4794
                if (purchase == null) {
4795
                    purchase = 0.0;
4796
                }
31218 tejbeer 4797
 
31697 amit.gupta 4798
                Double balanceTarget = purchaseTarget - purchase;
31218 tejbeer 4799
 
31697 amit.gupta 4800
                if (balanceTarget <= 0) {
4801
                    balanceTarget = 0.0;
4802
                }
31651 tejbeer 4803
 
31697 amit.gupta 4804
                StringBuilder sb = new StringBuilder();
4805
                sb.append("<html><body><p>Dear Partner,\n");
31886 tejbeer 4806
                sb.append("<p>Pls note your agreed monthly target is Rs." + purchaseTarget + " and your achievement till date is Rs." + purchase + "</p>");
31697 amit.gupta 4807
                sb.append("<p>Pls note that your balance target is Rs." + balanceTarget + "</p>\n");
4808
                sb.append(
32350 amit.gupta 4809
                        "<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 4810
 
32350 amit.gupta 4811
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31697 amit.gupta 4812
            }
31218 tejbeer 4813
 
31697 amit.gupta 4814
        }
31218 tejbeer 4815
 
31697 amit.gupta 4816
    }
31218 tejbeer 4817
 
33444 ranu 4818
 
34502 amit.gupta 4819
    public void findAllLiveDemoBrandItemsByBillingDate() throws
4820
            MessagingException, ProfitMandiBusinessException, IOException {
33444 ranu 4821
        LocalDateTime endDate = LocalDate.now().atStartOfDay().minusDays(8);
4822
 
4823
        List<LiveDemoOrderLineItemModel> liveDemoOrderLineItemModels = orderRepository.findAllLiveDemoBrandItemsByBillingDate(endDate.minusDays(60), endDate);
4824
        LOGGER.info("liveDemoOrderLineItemModels {}", liveDemoOrderLineItemModels);
4825
        String subject = "Billed Live Demo Model";
4826
        StringBuilder sb = new StringBuilder();
4827
 
4828
        sb.append("<html><body><p>Hi,\n");
4829
        sb.append("<p>Please check live demo billed order :</p>\n" + " <table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
4830
 
4831
        sb.append("<th style='border:1px solid black;padding: 5px'>Item Id</th>\n");
4832
        sb.append("<th style='border:1px solid black;padding: 5px'>Invoice Number</th>\n");
4833
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
4834
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
4835
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
4836
        sb.append("<th style='border:1px solid black;padding: 5px'>Serial Number</th>\n");
4837
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer Name</th>\n");
4838
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer City</th>\n");
4839
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer Pincode</th>\n");
4840
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer State</th>\n");
4841
        sb.append("<th style='border:1px solid black;padding: 5px'>Billing Date</th>\n");
4842
        sb.append("</tr>\n");
4843
        for (LiveDemoOrderLineItemModel liveDemoModel : liveDemoOrderLineItemModels) {
4844
            sb.append("<tr>");
4845
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getItemId() + "</td>\n");
4846
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getInvoiceNumber() + "</td>\n");
4847
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getBrand() + "</td>\n");
4848
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getModelNumber() + "</td>\n");
4849
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getModelName() + "</td>\n");
4850
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getSerialNumber() + "</td>\n");
4851
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerName() + "</td>\n");
4852
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerCity() + "</td>\n");
4853
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerPincode() + "</td>\n");
4854
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getState() + "</td>\n");
4855
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getFormattedBillingDate() + "</td>\n");
4856
 
4857
            sb.append("</tr>\n");
4858
 
33506 amit.gupta 4859
        }
33444 ranu 4860
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "niranjan.kala@smartdukaan.com",
33506 amit.gupta 4861
                "mohit.gulati@smartdukaan.com", "vinay.p@smartdukaan.com", "shivam.gupta@smartdukaan.com");
33444 ranu 4862
 
4863
 
4864
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4865
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
4866
 
4867
    }
4868
 
33464 ranu 4869
    public void findTodayPocoBillingItems() throws MessagingException, ProfitMandiBusinessException, IOException {
4870
        LocalDateTime endDate = LocalDate.now().atStartOfDay().plusDays(1);
4871
        LocalDateTime startDate = LocalDate.now().atStartOfDay().minusDays(1);
33444 ranu 4872
 
33464 ranu 4873
        List<LiveDemoOrderLineItemModel> pocoBillingOrderLineItemModels = orderRepository.findTodayPocoBillingItems(startDate, endDate);
4874
        LOGGER.info("pocoBillingOrderLineItemModels {}", pocoBillingOrderLineItemModels);
4875
        String subject = "Poco Billing";
4876
        StringBuilder sb = new StringBuilder();
4877
 
4878
        sb.append("<html><body><p>Hi,\n");
4879
        sb.append("<p>Please check poco billed order :</p>\n" + " <table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
4880
 
4881
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
4882
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
4883
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
4884
        sb.append("<th style='border:1px solid black;padding: 5px'>Serial Number</th>\n");
4885
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer State</th>\n");
4886
        sb.append("<th style='border:1px solid black;padding: 5px'>Billing Date</th>\n");
4887
        sb.append("</tr>\n");
4888
        for (LiveDemoOrderLineItemModel pocoModel : pocoBillingOrderLineItemModels) {
4889
            sb.append("<tr>");
4890
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getBrand() + "</td>\n");
4891
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getModelNumber() + "</td>\n");
4892
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getModelName() + "</td>\n");
4893
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getSerialNumber() + "</td>\n");
4894
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getState() + "</td>\n");
4895
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getFormattedBillingDate() + "</td>\n");
4896
 
4897
            sb.append("</tr>\n");
4898
 
33506 amit.gupta 4899
        }
33664 amit.gupta 4900
        List<String> sendTo = Arrays.asList("uday.singh@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "nishant.ohri@smartdukaan.com", "ritesh.chauhan1@smartdukaan.com");
33464 ranu 4901
 
4902
        String[] email = sendTo.toArray(new String[sendTo.size()]);
4903
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
4904
 
4905
    }
4906
 
4907
 
31697 amit.gupta 4908
    public void monthlyTargetForInternalTeam() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 4909
 
31697 amit.gupta 4910
        LocalDateTime curDate = LocalDateTime.now();
31218 tejbeer 4911
 
34903 ranu 4912
        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 4913
 
31697 amit.gupta 4914
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false);
31218 tejbeer 4915
 
31697 amit.gupta 4916
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 4917
 
31697 amit.gupta 4918
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31218 tejbeer 4919
 
31886 tejbeer 4920
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 4921
 
31886 tejbeer 4922
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
4923
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 4924
 
31697 amit.gupta 4925
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 4926
 
31697 amit.gupta 4927
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31218 tejbeer 4928
 
31697 amit.gupta 4929
            String email = storeGuyEntry.getKey();
31218 tejbeer 4930
 
31697 amit.gupta 4931
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
4932
            Map<Integer, MonthlyTarget> monthlyTargetAchievement = new HashMap<>();
4933
            for (Integer fofoId : fofoIds) {
31218 tejbeer 4934
 
31697 amit.gupta 4935
                MonthlyTarget monthlyTarget = partnersMonthlyTarget.get(fofoId);
4936
                if (monthlyTarget != null) {
4937
                    Double purchaseTarget = monthlyTarget.getPurchaseTarget();
31218 tejbeer 4938
 
31697 amit.gupta 4939
                    Double saleTarget = monthlyTarget.getSaleTarget();
31218 tejbeer 4940
 
31697 amit.gupta 4941
                    if (purchaseTarget != null && purchaseTarget > 0) {
4942
                        Double purchase = secondaryMtd.get(fofoId);
4943
                        if (purchase == null) {
4944
                            purchase = 0.0;
4945
                        }
4946
                        monthlyTarget.setPurchaseAchievement(purchase);
4947
                        monthlyTargetAchievement.put(fofoId, monthlyTarget);
31218 tejbeer 4948
 
31697 amit.gupta 4949
                    }
4950
                }
4951
            }
31218 tejbeer 4952
 
31697 amit.gupta 4953
            if (!monthlyTargetAchievement.isEmpty()) {
31218 tejbeer 4954
 
31697 amit.gupta 4955
                StringBuilder sb = new StringBuilder();
31218 tejbeer 4956
 
31697 amit.gupta 4957
                sb.append("<html><body><p>Hi,\n");
31886 tejbeer 4958
                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 4959
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4960
                sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31218 tejbeer 4961
 
31697 amit.gupta 4962
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Target</th>\n");
31218 tejbeer 4963
 
31697 amit.gupta 4964
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Achievement</th>\n");
4965
                sb.append("</tr>\n");
31218 tejbeer 4966
 
31886 tejbeer 4967
                for (Entry<Integer, MonthlyTarget> monthlyTargetAchievementEntry : monthlyTargetAchievement.entrySet()) {
31697 amit.gupta 4968
                    sb.append("<tr>");
4969
                    int fofoId = monthlyTargetAchievementEntry.getKey();
31218 tejbeer 4970
 
31697 amit.gupta 4971
                    MonthlyTarget monthlyTarget = monthlyTargetAchievementEntry.getValue();
31886 tejbeer 4972
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31218 tejbeer 4973
 
31886 tejbeer 4974
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseTarget() + "</td>\n");
31218 tejbeer 4975
 
31886 tejbeer 4976
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseAchievement() + "</td>\n");
31218 tejbeer 4977
 
31697 amit.gupta 4978
                    sb.append("</tr>\n");
31218 tejbeer 4979
 
31697 amit.gupta 4980
                }
31218 tejbeer 4981
 
32350 amit.gupta 4982
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb.toString(), null, subject);
31697 amit.gupta 4983
                // this.sendMailOfHtmlFormat("tejbeer.kaur@smartdukaan.com", sb.toString(),
4984
                // null, subject);
31218 tejbeer 4985
 
31697 amit.gupta 4986
            }
31604 tejbeer 4987
 
31697 amit.gupta 4988
        }
31604 tejbeer 4989
 
31697 amit.gupta 4990
    }
31604 tejbeer 4991
 
32061 amit.gupta 4992
    @Autowired
4993
    private PerformanceService performanceService;
4994
 
4995
 
4996
    public void sendFilteredRetailerPerformance() throws Exception {
4997
        RetailerFilterModel retailerFilterModel = performanceService.getRetailerFilterModel();
4998
 
4999
        Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(true);
5000
 
5001
 
5002
        List<RetailerPeformanceFilterModel> partnersPerformance = performanceService.getPerformance(retailerFilterModel, customRetailers);
5003
 
5004
        Map<Integer, RetailerPeformanceFilterModel> partnersPerformanceMap = new HashMap<>();
5005
 
5006
        if (!partnersPerformance.isEmpty()) {
5007
            partnersPerformanceMap = partnersPerformance.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
5008
            performanceService.sendPartnerPerformanceEmail(partnersPerformanceMap, retailerFilterModel, customRetailers);
5009
 
5010
        }
5011
 
5012
 
5013
    }
5014
 
32081 tejbeer 5015
    @Autowired
5016
    private VendorItemPricingRepository vendorItemPricingRepository;
32061 amit.gupta 5017
 
32081 tejbeer 5018
 
5019
    @Autowired
5020
    private VendorCatalogPricingService vendorCatalogPricingService;
5021
 
5022
 
33256 amit.gupta 5023
    public void migrateVendorItemPricing() throws ProfitMandiBusinessException {
32081 tejbeer 5024
 
5025
        List<VendorItemPricing> vendorItemPricings = vendorItemPricingRepository.selectAll();
32350 amit.gupta 5026
        LOGGER.info("At migrate VendorItemPricing");
32092 tejbeer 5027
        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 5028
        for (VendorItemPricing vendorItemPricing : vendorItemPricings) {
5029
            Item item = null;
32092 tejbeer 5030
            if (items.get(vendorItemPricing.getItemId()) != null) {
5031
                item = items.get(vendorItemPricing.getItemId());
5032
            } else {
32084 tejbeer 5033
                continue;
32081 tejbeer 5034
            }
32092 tejbeer 5035
 
32081 tejbeer 5036
            VendorCatalogPricingModel vendorCatalogPricingModel = new VendorCatalogPricingModel();
5037
            vendorCatalogPricingModel.setCatalogId(item.getCatalogItemId());
5038
            vendorCatalogPricingModel.setAuthId(13);
32088 tejbeer 5039
            vendorCatalogPricingModel.setDp(vendorItemPricing.getDp());
32081 tejbeer 5040
 
5041
            vendorCatalogPricingModel.setTp(vendorItemPricing.getTp());
5042
            vendorCatalogPricingModel.setMop(vendorItemPricing.getMop());
32384 amit.gupta 5043
            vendorCatalogPricingModel.setEffectedOn(LocalDate.of(2023, 8, 22));
32081 tejbeer 5044
            vendorCatalogPricingModel.setVendorId(vendorItemPricing.getVendorId());
5045
 
5046
 
5047
            try {
5048
                vendorCatalogPricingService.createVendorCatalogPricingLog(vendorCatalogPricingModel);
5049
            } catch (ProfitMandiBusinessException e) {
5050
                continue;
5051
            }
5052
 
5053
        }
5054
 
5055
    }
5056
 
5057
    public void approveVendorCatalogPricing() {
5058
        List<VendorCatalogPricingLog> vendorCatalogPricingLogs = vendorCatalogPricingLogRepository.selectByStatus(VendorCatalogPricingStatus.PENDING);
5059
 
32084 tejbeer 5060
 
32081 tejbeer 5061
        for (VendorCatalogPricingLog vendorCatalogPricingLog : vendorCatalogPricingLogs) {
32107 tejbeer 5062
            vendorCatalogPricingLog.setStatus(VendorCatalogPricingStatus.APPROVED);
5063
            vendorCatalogPricingLog.setUpdatedTimestamp(LocalDateTime.now());
5064
            vendorCatalogPricingLog.setApprovedBy(13);
5065
            vendorCatalogPricingLog.setApprovedTimestamp(LocalDateTime.now());
32114 tejbeer 5066
            vendorCatalogPricingService.createVendorCatalogPricing(vendorCatalogPricingLog);
5067
        }
32081 tejbeer 5068
 
32114 tejbeer 5069
    }
32108 tejbeer 5070
 
32822 ranu 5071
    public void sendMailWhatsAppAfterLoanDueDate() throws Exception {
5072
        sdCreditService.updateRisk();
34729 amit.gupta 5073
        List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
32822 ranu 5074
        if (!defaultLoans.isEmpty()) {
5075
            this.sendLoanAlert(defaultLoans);
5076
        }
32108 tejbeer 5077
 
32822 ranu 5078
 
5079
    }
5080
 
5081
    public void sendLoanAlert(List<Loan> defaultLoans) throws
5082
            Exception {
5083
 
5084
        List<Integer> categoryIds = Arrays.asList(
5085
                ProfitMandiConstants.TICKET_CATEGORY_CATEGORY,
5086
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
5087
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
34903 ranu 5088
                ProfitMandiConstants.TICKET_CATEGORY_ABM,
32822 ranu 5089
                ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS,
5090
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
5091
 
5092
        /*for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
5093
            List<Loan> filteredRows = defaultLoans.stream()
5094
                    .filter(loan -> storeGuyEntry.getValue().contains(loan.getFofoId()))
5095
                    .collect(Collectors.toList());
5096
 
5097
            if (!filteredRows.isEmpty()) {
5098
                for (Loan defaultLoan : filteredRows) {
5099
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
5100
                    double amount = loanStatements.stream().map(LoanStatement::getAmount).collect(Collectors.summingDouble(BigDecimal::doubleValue));
5101
                    String messageText = getMessageForDueDateExtend(defaultLoan,amount);
5102
                   // String[] email = new String[]{storeGuyEntry.getKey()};
33820 ranu 5103
 
32822 ranu 5104
                    sendMailOfHtmlFormat(mailSender, email, messageText, null, subject);
5105
 
5106
                }
5107
            }
5108
        }*/
32842 amit.gupta 5109
        //Send single whatsapp to tv
5110
        String title = "SD Credit Alert!";
32850 amit.gupta 5111
        boolean notYetSent = true;
32822 ranu 5112
        for (Loan defaultLoan : defaultLoans) {
5113
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
5114
 
5115
            double amount = loanStatements.stream().map(LoanStatement::getAmount).collect(Collectors.summingDouble(BigDecimal::doubleValue));
5116
 
5117
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
5118
 
5119
            Address address = addressRepository.selectById(user.getAddressId());
5120
 
32842 amit.gupta 5121
            //String url = "http://app.smartdukaan.com/pages/home/credit";
32822 ranu 5122
 
32842 amit.gupta 5123
            String message = getMessageForDueDateExtend(defaultLoan, amount);
5124
            String whatsAppMessage = getWhatsAppMessageForDueDateExtend(defaultLoan, amount);
32948 amit.gupta 5125
            if (whatsAppMessage != null) {
32850 amit.gupta 5126
                notificationService.sendWhatsappMessage(whatsAppMessage, title, address.getPhoneNumber());
32948 amit.gupta 5127
                if (notYetSent) {
32850 amit.gupta 5128
                    notificationService.sendWhatsappMessage(whatsAppMessage, title, "9911565032");
5129
                    notYetSent = false;
5130
                }
5131
            }
5132
 
32822 ranu 5133
            String[] email = {user.getEmailId()};
5134
            sendMailOfHtmlFormat(mailSender, email, message, null, "Loan Alert - SmartDukaan");
5135
        }
5136
    }
5137
 
5138
    private String getMessageForDueDateExtend(Loan defaultLoan, double amount) throws ProfitMandiBusinessException {
5139
 
5140
        double absoluteAmount = Math.abs(amount);
5141
        long roundedAmount = Math.round(absoluteAmount);
5142
        String formattedAmount = (amount < 0) ? "" + roundedAmount : "" + roundedAmount;
5143
 
5144
        LocalDate dueDate = defaultLoan.getDueDate().toLocalDate();
5145
        LocalDate defaultDate = defaultLoan.getDueDate().toLocalDate().plusDays(15);
5146
 
5147
        // Retrieve the name of the user associated with the loan
5148
        String name = userUserRepository.selectById(defaultLoan.getFofoId()).getName();
5149
 
5150
        // Initialize a StringBuilder to construct the HTML message
5151
        StringBuilder sb = new StringBuilder();
5152
 
32842 amit.gupta 5153
        if (LocalDate.now().isBefore(dueDate)) {
5154
            long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), defaultLoan.getDueDate().toLocalDate());
32822 ranu 5155
            String payDate = defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
5156
            // 5 Days Before Due Date - daily
5157
            if (noOfdaysBetween <= 5) {
5158
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
5159
                sb.append("<p>This is a friendly reminder that your loan payment is due in " + noOfdaysBetween + "days, on " +
5160
                        payDate +
5161
                        ". Please ensure that the payment is made on time to avoid any late fees or penalties.</p>");
5162
                sb.append("<p>As per the terms of your loan agreement, the total amount due is Rs. " + formattedAmount + ". " +
5163
                        "You can make the payment by adding money to your wallet. If you have any questions or need assistance, " +
5164
                        "our customer service team is available to help you.</p>");
5165
                sb.append("<p>Thank you for your cooperation and prompt attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
5166
            }
32842 amit.gupta 5167
        } else if (LocalDate.now().isBefore(defaultDate)) {
32822 ranu 5168
            long noOfdaysBetween = ChronoUnit.DAYS.between(defaultDate, LocalDate.now());
5169
 
5170
            // After Due Date – Alternate days
5171
            if ((noOfdaysBetween % 2 == 0) && (noOfdaysBetween > 5)) {
5172
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
5173
                sb.append("<p>We would like to remind you that your payment for the outstanding balance on your account is now overdue. " +
5174
                        "As per our terms and conditions, a higher interest rate will be levied on the overdue amount Rs. " + formattedAmount + ".</p>");
34729 amit.gupta 5175
                sb.append("<p>To avoid further charges and any negative impact on your Credit score, we kindly request that you settle the " +
32822 ranu 5176
                        "outstanding balance as soon as possible.</p>");
5177
                sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
5178
            }
5179
            // 5 Days before default - daily
32842 amit.gupta 5180
            if (noOfdaysBetween <= 5) {
32822 ranu 5181
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br>");
5182
                sb.append("<p>Attention: High Alert</p>");
5183
                sb.append("<p>Dear " + name + "</p>");
5184
                sb.append("<p>This is to inform you that the due date for your payment of Rs. " + formattedAmount + " has been crossed, " +
5185
                        "and you are approaching the default date on " + defaultDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + ". " +
34729 amit.gupta 5186
                        "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 5187
                sb.append("<p>To rectify this situation, it is imperative that you take immediate action. " +
5188
                        "Please make the necessary payment immediately to avoid further consequences.</p>");
5189
                sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
5190
            }
32842 amit.gupta 5191
        } else {
32822 ranu 5192
            // Post Default - Daily
32842 amit.gupta 5193
            sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
5194
            sb.append("<p>We regret to inform you that you are currently in loan default. As a result, " +
34729 amit.gupta 5195
                    "higher penalties are being charged, which is also negatively impacting your Credit score. " +
32842 amit.gupta 5196
                    "It is imperative that you make an immediate payment to rectify this situation.</p>");
5197
            sb.append("<p>Please note that failing to make the payment promptly will result in further consequences, " +
5198
                    "including potential legal action and additional financial penalties. " +
5199
                    "We strongly urge you to take this matter seriously and settle the outstanding amount as soon as possible.</p>");
5200
            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>");
5201
            sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
32822 ranu 5202
 
5203
        }
5204
 
5205
        // Return the constructed HTML message
5206
        sb.append("</body></html>");
5207
        return sb.toString();
5208
    }
5209
 
34502 amit.gupta 5210
    private String getWhatsAppMessageForDueDateExtend(Loan defaultLoan, double amount) throws
5211
            ProfitMandiBusinessException {
32822 ranu 5212
 
5213
        double absoluteAmount = Math.abs(amount);
5214
        long roundedAmount = Math.round(absoluteAmount);
5215
        String formattedAmount = (amount < 0) ? "" + roundedAmount : "" + roundedAmount;
5216
 
5217
        LocalDate dueDate = defaultLoan.getDueDate().toLocalDate();
5218
        LocalDate defaultDate = defaultLoan.getDueDate().toLocalDate().plusDays(15);
5219
 
5220
        // Retrieve the name of the user associated with the loan
5221
        String name = userUserRepository.selectById(defaultLoan.getFofoId()).getName();
5222
 
5223
        // Initialize a StringBuilder to construct the HTML message
5224
        String message = null;
5225
 
32842 amit.gupta 5226
        if (LocalDate.now().isBefore(dueDate)) {
32822 ranu 5227
            long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), defaultLoan.getDueDate().toLocalDate());
5228
            String payDate = defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
5229
            // 5 Days Before Due Date - daily
5230
            if (noOfdaysBetween <= 5) {
5231
 
34729 amit.gupta 5232
                message = "Dear %s, This is a friendly reminder that your outstanding credit payment is due in %d days, on %s.\n" +
32822 ranu 5233
                        "\n" +
5234
                        "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" +
5235
                        "\n" +
5236
                        "If you have any questions or need assistance, our customer service team is available to help you.\n" +
5237
                        "Thank you for your cooperation and prompt attention to this matter.\n" +
5238
                        "\n" +
5239
                        "Team SmartDukaan";
32842 amit.gupta 5240
                message = String.format(message, name, noOfdaysBetween, payDate, formattedAmount);
5241
            }
5242
        } else if (LocalDate.now().isBefore(defaultDate)) {
32822 ranu 5243
            long noOfdaysBetween = ChronoUnit.DAYS.between(defaultDate, LocalDate.now());
5244
            // After Due Date – Alternate days
5245
            if ((noOfdaysBetween % 2 == 0) && (noOfdaysBetween > 5)) {
5246
                message = "Dear %s, We would like to remind you that your payment for the outstanding balance on your account is now overdue. \n" +
5247
                        "As per our terms and conditions, a higher interest rate will be levied on the overdue amount Rs.%s.\n" +
34729 amit.gupta 5248
                        "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 5249
                        "Thank you for your attention to this matter. \n" +
5250
                        "\n" +
5251
                        "Team SmartDukaan";
5252
                message = String.format(message, name, formattedAmount);
5253
            }
5254
            // 5 Days before default - daily
32842 amit.gupta 5255
            if (noOfdaysBetween <= 5) {
32822 ranu 5256
                String defaultPayDate = defaultDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
5257
                message = "Attention: High Alert!! Dear %s, \n" +
5258
                        "\n" +
5259
                        "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 5260
                        "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 5261
                        "\n" +
5262
                        "Please make the necessary payment immediately to avoid further consequences. Thank you for your attention to this matter.\n" +
5263
                        "\n" +
5264
                        "Team SmartDukaan";
5265
                message = String.format(message, name, formattedAmount, defaultPayDate);
5266
            }
32842 amit.gupta 5267
        } else {
32822 ranu 5268
            // Post Default - Daily
34729 amit.gupta 5269
            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 5270
                    "\n" +
5271
                    "It is imperative that you make an immediate payment to rectify this situation. \n" +
5272
                    "\n" +
5273
                    "Please note that failing to make the payment promptly will result in further consequences, including potential legal action and additional financial penalties. \n" +
5274
                    "\n" +
5275
                    "We strongly urge you to take this matter seriously and settle the outstanding amount as soon as possible. \n" +
5276
                    "\n" +
5277
                    "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" +
5278
                    "\n" +
5279
                    "Team SmartDukaan";
5280
            message = String.format(message, name, formattedAmount);
5281
 
5282
        }
5283
        // Return the constructed HTML message
5284
        return message;
5285
    }
5286
 
33874 ranu 5287
    @Autowired
5288
    private FofoOpeningStockRepository fofoOpeningStockRepository;
34450 ranu 5289
    @Autowired
5290
    private SmartCartService smartCartService;
33874 ranu 5291
 
5292
    public void createOpeningStockPartyWise() throws Exception {
5293
        // Get all partner stock data
35329 ranu 5294
        Map<Integer, List<PartnerOpeningStockByTodayModel>> partnerOpeningStockByTodayInStockMap = currentInventorySnapshotRepository.getAllPartnerTodayInstock();
5295
        Map<Integer, List<PartnerOpeningStockByTodayModel>> partnerOpeningStockByTodayGrnPending = currentInventorySnapshotRepository.getAllPartnerTodayGrnPending();
5296
 
5297
        Map<Integer, List<PartnerOpeningStockByTodayModel>> partnerOpeningStockByTodayMap =
5298
                new HashMap<>();
5299
 
5300
// STEP 1: Copy in-stock data
5301
        partnerOpeningStockByTodayInStockMap.forEach((fofoId, list) ->
5302
                partnerOpeningStockByTodayMap.put(
5303
                        fofoId,
5304
                        new ArrayList<>(list)   // deep list copy
5305
                )
5306
        );
5307
 
5308
// STEP 2: Merge GRN pending using streams
5309
        partnerOpeningStockByTodayGrnPending.forEach((fofoId, grnList) -> {
5310
 
5311
            // If FOFO missing → simply insert GRN list (deep copy)
5312
            partnerOpeningStockByTodayMap
5313
                    .computeIfAbsent(fofoId, x -> new ArrayList<>())
5314
                    .addAll(
5315
                            grnList.stream()
5316
                                    .map(g -> new PartnerOpeningStockByTodayModel(
5317
                                            g.getFofoId(),
5318
                                            g.getCatalogId(),
5319
                                            g.getModelNumber(),
5320
                                            g.getOpeningQty()
5321
                                    ))
5322
                                    .collect(Collectors.toList())
5323
                    );
5324
        });
5325
 
5326
// STEP 3: Now merge duplicates per catalogId using grouping
5327
        partnerOpeningStockByTodayMap.replaceAll((fofoId, list) ->
5328
                list.stream()
5329
                        .collect(Collectors.toMap(
5330
                                PartnerOpeningStockByTodayModel::getCatalogId,
5331
                                m -> new PartnerOpeningStockByTodayModel(
5332
                                        m.getFofoId(),
5333
                                        m.getCatalogId(),
5334
                                        m.getModelNumber(),
5335
                                        m.getOpeningQty()
5336
                                ),
5337
                                // merge function: sum openingQty
5338
                                (m1, m2) -> {
5339
                                    m1.setOpeningQty(m1.getOpeningQty() + m2.getOpeningQty());
5340
                                    return m1;
5341
                                }
5342
                        ))
5343
                        .values()
5344
                        .stream()
5345
                        .collect(Collectors.toList())
5346
        );
5347
 
5348
 
34460 ranu 5349
        Map<Integer, Map<Integer, Integer>> activatedButNotBilledCatalogQtyMap = smartCartService.activatedButNotBilledCatalogQtyMap();
34502 amit.gupta 5350
        LOGGER.info("PartnerOpeningStockByTodayModel {}", partnerOpeningStockByTodayMap);
33874 ranu 5351
        for (Map.Entry<Integer, List<PartnerOpeningStockByTodayModel>> entry : partnerOpeningStockByTodayMap.entrySet()) {
5352
            int fofoId = entry.getKey();
5353
            List<PartnerOpeningStockByTodayModel> partnerStockList = entry.getValue();
34450 ranu 5354
            // Get the sold (activated-but-not-billed) quantity for this fofo and catalog
34460 ranu 5355
            Map<Integer, Integer> activatedButNotBilledQtyMap = activatedButNotBilledCatalogQtyMap.getOrDefault(fofoId, Collections.emptyMap());
33874 ranu 5356
 
34450 ranu 5357
            //  if stock is avaialble in snapshot
33874 ranu 5358
            for (PartnerOpeningStockByTodayModel partnerStock : partnerStockList) {
5359
                int catalogId = partnerStock.getCatalogId();
34450 ranu 5360
                int stockCurrentQty = partnerStock.getOpeningQty();
33874 ranu 5361
                LocalDate openingDate = partnerStock.getOpeningDate();
5362
 
34460 ranu 5363
                int soldButNotBilledQty = activatedButNotBilledQtyMap.getOrDefault(catalogId, 0);
34450 ranu 5364
 
35521 amit 5365
                if (catalogId == 1025656 && fofoId == 175140232) {
5366
                    LOGGER.info("catalogId {}", catalogId);
5367
                    LOGGER.info("fofoId {}", fofoId);
5368
                    LOGGER.info("soldButNotBilledQty {}", soldButNotBilledQty);
5369
                    LOGGER.info("stockCurrentQty {}", stockCurrentQty);
35329 ranu 5370
                }
5371
 
34450 ranu 5372
                // Subtract soldQty from partnerCurrentQty
34460 ranu 5373
                int partnerCurrentQty = Math.max(stockCurrentQty - soldButNotBilledQty, 0); // Ensure it doesn't go negative
34450 ranu 5374
 
5375
 
33874 ranu 5376
                // Check if an entry already exists in the FofoOpeningStock table
5377
                FofoOpeningStock existingStock = fofoOpeningStockRepository.findByFofoIdAndCatalogId(fofoId, catalogId);
5378
 
34162 ranu 5379
 
33874 ranu 5380
                if (existingStock != null) {
34363 ranu 5381
                    if (partnerCurrentQty < 1 && existingStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
34160 tejus.loha 5382
                        fofoOpeningStockRepository.delete(existingStock);
5383
                    }
34162 ranu 5384
                    if (existingStock.getOpeningQty() < partnerCurrentQty) {
5385
                        existingStock.setOpeningQty(partnerCurrentQty);
5386
                        existingStock.setCurrentQty(partnerCurrentQty);
33874 ranu 5387
                        existingStock.setOpeningDate(openingDate);
5388
                        LOGGER.info("if condition exist {}");
34275 tejus.loha 5389
                    } else if (existingStock.getCurrentQty() >= existingStock.getOpeningQty()) {
5390
                        existingStock.setOpeningQty(existingStock.getCurrentQty());
5391
                        existingStock.setCurrentQty(partnerCurrentQty);
5392
                        existingStock.setOpeningDate(LocalDate.now());
34363 ranu 5393
                    } else if (existingStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
33878 ranu 5394
                        int averageQty = Math.round((existingStock.getCurrentQty() + existingStock.getOpeningQty()) / 2.0f);
5395
 
5396
                        if (averageQty == 1 && existingStock.getOpeningQty() == 1 && existingStock.getCurrentQty() == 0) {
5397
                            // Delete the existing stock entry from the table
5398
                            fofoOpeningStockRepository.delete(existingStock);
5399
                            LOGGER.info("Deleted record with fofoId: {}, catalogId: {} because averageQty, openingQty, and currentQty meet deletion criteria", fofoId, catalogId);
5400
                        } else {
5401
                            // Update the existing stock with the new average quantity
5402
                            existingStock.setOpeningQty(averageQty);
34244 ranu 5403
                            existingStock.setCurrentQty(partnerCurrentQty);
33878 ranu 5404
                            existingStock.setOpeningDate(LocalDate.now());
34363 ranu 5405
                            LOGGER.info("Updated due to date being older than 5 days with average quantity: {}", averageQty);
33878 ranu 5406
                        }
34275 tejus.loha 5407
                    } else {
34244 ranu 5408
                        existingStock.setCurrentQty(partnerCurrentQty);
33874 ranu 5409
                    }
5410
                } else {
5411
                    LOGGER.info("else condition exist");
5412
                    FofoOpeningStock newStock = new FofoOpeningStock();
5413
                    newStock.setFofoId(fofoId);
5414
                    newStock.setCatalogId(catalogId);
34162 ranu 5415
                    newStock.setOpeningQty(partnerCurrentQty);
5416
                    newStock.setCurrentQty(partnerCurrentQty);
33874 ranu 5417
                    newStock.setOpeningDate(openingDate);
5418
                    fofoOpeningStockRepository.persist(newStock);
5419
 
5420
                }
5421
            }
34162 ranu 5422
 
5423
//            if stock is not available in snapshot but available in opening stock
34275 tejus.loha 5424
            List<FofoOpeningStock> fofoOpeningStockList = fofoOpeningStockRepository.selectAllByFofoId(fofoId);
34162 ranu 5425
 
34275 tejus.loha 5426
            for (FofoOpeningStock fofoOpeningStock : fofoOpeningStockList) {
34162 ranu 5427
 
34275 tejus.loha 5428
                if (!partnerStockList.stream().anyMatch(partnerStock -> partnerStock.getCatalogId() == fofoOpeningStock.getCatalogId())) {
34363 ranu 5429
                    if (fofoOpeningStock.getOpeningDate().isBefore(LocalDate.now().minusDays(5))) {
34275 tejus.loha 5430
                        LOGGER.info("not match stock{}", fofoOpeningStock);
5431
                        fofoOpeningStockRepository.delete(fofoOpeningStock);
5432
                    } else {
5433
                        LOGGER.info("not match stock2{}", fofoOpeningStock);
5434
                        fofoOpeningStock.setCurrentQty(0);
5435
                    }
34162 ranu 5436
 
34275 tejus.loha 5437
                }
5438
            }
34162 ranu 5439
 
33874 ranu 5440
        }
5441
    }
5442
 
5443
 
34162 ranu 5444
    @Autowired
5445
    private CategorisedCatalogRepository categorisedCatalogRepository;
5446
 
5447
    public void groupHidCatalogsByWeeks() throws ProfitMandiBusinessException, MessagingException, IOException {
5448
        List<CategorisedCatalogListModel> categorisedCatalogs = categorisedCatalogRepository.getListByStatus(CatalogMovingEnum.HID);
5449
        LocalDate currentDate = LocalDate.now();
5450
        LocalDate oneWeekAgo = currentDate.minusDays(7);
5451
        LocalDate twoWeeksAgo = currentDate.minusDays(14);
5452
        LocalDate threeWeeksAgo = currentDate.minusDays(21);
5453
 
5454
        // This Week (inclusive of the current date)
5455
        List<CategorisedCatalogListModel> thisWeekCatalogs = categorisedCatalogs.stream()
5456
                .filter(catalog -> !catalog.getStatusCreatedDate().isBefore(oneWeekAgo))
5457
                .collect(Collectors.toList());
5458
 
5459
        // Last Week (from one week ago to two weeks ago, exclusive of this week)
5460
        List<CategorisedCatalogListModel> lastWeekCatalogs = categorisedCatalogs.stream()
5461
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(oneWeekAgo) && !catalog.getStatusCreatedDate().isBefore(twoWeeksAgo))
5462
                .collect(Collectors.toList());
5463
 
5464
        // Two Weeks Ago (from two weeks ago to three weeks ago, exclusive of last week)
5465
        List<CategorisedCatalogListModel> twoWeeksAgoCatalogs = categorisedCatalogs.stream()
5466
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(twoWeeksAgo) && !catalog.getStatusCreatedDate().isBefore(threeWeeksAgo))
5467
                .collect(Collectors.toList());
5468
 
5469
        // Older than Two Weeks Ago (anything older than three weeks ago)
5470
        List<CategorisedCatalogListModel> olderCatalogs = categorisedCatalogs.stream()
5471
                .filter(catalog -> catalog.getStatusCreatedDate().isBefore(threeWeeksAgo))
5472
                .collect(Collectors.toList());
5473
 
5474
 
5475
        String subject = "Hid Catalogs";
5476
        StringBuilder sb = new StringBuilder();
5477
 
5478
        sb.append("<html><body><p>Hi Catagory Team,\n");
5479
        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;'>");
5480
 
5481
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5482
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5483
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5484
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5485
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5486
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5487
        sb.append("</tr>\n");
5488
 
5489
        for (CategorisedCatalogListModel catalog : thisWeekCatalogs) {
5490
            sb.append("<tr>");
5491
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5492
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5493
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5494
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5495
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5496
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5497
 
5498
            sb.append("</tr>\n");
5499
 
5500
        }
5501
 
5502
        sb.append("</table>");
5503
 
5504
        sb.append("</br>");
5505
        sb.append("</br>");
5506
        sb.append("</br>");
5507
        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;'>");
5508
 
5509
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5510
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5511
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5512
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5513
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5514
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5515
        sb.append("</tr>\n");
5516
 
5517
        for (CategorisedCatalogListModel catalog : lastWeekCatalogs) {
5518
            sb.append("<tr>");
5519
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5520
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5521
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5522
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5523
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5524
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5525
 
5526
            sb.append("</tr>\n");
5527
 
5528
        }
5529
        sb.append("</table>");
5530
 
5531
        sb.append("</br>");
5532
        sb.append("</br>");
5533
        sb.append("</br>");
5534
        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;'>");
5535
 
5536
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5537
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5538
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5539
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5540
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5541
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5542
        sb.append("</tr>\n");
5543
 
5544
        for (CategorisedCatalogListModel catalog : twoWeeksAgoCatalogs) {
5545
            sb.append("<tr>");
5546
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5547
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5548
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5549
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5550
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5551
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5552
 
5553
            sb.append("</tr>\n");
5554
 
5555
        }
5556
        sb.append("</table>");
5557
 
5558
        sb.append("</br>");
5559
        sb.append("</br>");
5560
        sb.append("</br>");
5561
        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;'>");
5562
 
5563
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5564
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5565
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5566
        sb.append("<th style='border:1px solid black;padding: 5px'>Catalog Id</th>\n");
5567
        sb.append("<th style='border:1px solid black;padding: 5px'>Start Date</th>\n");
5568
        sb.append("<th style='border:1px solid black;padding: 5px'>End Date</th>\n");
5569
        sb.append("</tr>\n");
5570
 
5571
        for (CategorisedCatalogListModel catalog : olderCatalogs) {
5572
            sb.append("<tr>");
5573
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getBrand() + "</td>\n");
5574
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelNumber() + "</td>\n");
5575
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getModelId() + "</td>\n");
5576
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getCurrentStatus() + "</td>\n");
5577
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusCreatedDate() + "</td>\n");
5578
            sb.append("<td style='border:1px solid black;padding: 5px'>" + catalog.getStatusEndDate() + "</td>\n");
5579
 
5580
            sb.append("</tr>\n");
5581
 
5582
        }
5583
        sb.append("</table>");
5584
        sb.append("</body></html>");
5585
 
34275 tejus.loha 5586
        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 5587
 
5588
 
5589
        String[] email = sendTo.toArray(new String[sendTo.size()]);
5590
 
5591
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
5592
    }
5593
 
34275 tejus.loha 5594
    public void send10OrMoreOlderStockReport() throws Exception {
35094 ranu 5595
        System.out.print("testSTart");
34352 amit.gupta 5596
        purSaleService.moreThen10DaysEgedStockReport();
35094 ranu 5597
        System.out.print("testEnd");
34162 ranu 5598
 
34275 tejus.loha 5599
    }
34162 ranu 5600
 
34791 aman.kumar 5601
    public void sendUpdateMobileBrandMarketShareQuaterlyMail() throws Exception {
5602
        String subject = "Reminder: Please Update Brand-wise Market Share";
5603
 
5604
        String body = "Dear Team,\n\n" +
5605
                "This is a gentle reminder to kindly update the brand-wise market share data for the current quarter.\n\n" +
5606
                "Best regards,\n" +
5607
                "SmartDukaan Team";
5608
 
5609
        Utils.sendMailWithAttachments(
5610
                googleMailSender,
5611
                new String[]{"sm.@smartdukaan.com"},
5612
                new String[]{"tech@smartdukaan.com"},
5613
                subject,
5614
                body
5615
        );
5616
    }
5617
 
5618
 
32210 jai.hind 5619
}
33664 amit.gupta 5620
// 2284"