Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
28217 tejbeer 1
package com.smartdukaan.cron.scheduled;
23723 amit.gupta 2
 
24542 amit.gupta 3
import com.google.common.collect.Lists;
25300 tejbeer 4
import com.google.gson.Gson;
29488 manish 5
import com.razorpay.Payment;
32421 amit.gupta 6
import com.smartdukaan.cron.itelImeiActivation.ItelImeiActivationNewService;
29488 manish 7
import com.smartdukaan.cron.itelImeiActivation.ItelImeiActivationService;
8
import com.smartdukaan.cron.itelImeiActivation.TecnoImeiActivation;
32482 amit.gupta 9
import com.smartdukaan.cron.scheduled.runnables.PurchaseMigration;
32511 amit.gupta 10
import com.spice.profitmandi.common.enumuration.*;
24121 govind 11
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
32421 amit.gupta 12
import com.spice.profitmandi.common.model.*;
24681 amit.gupta 13
import com.spice.profitmandi.common.services.ReporticoService;
29814 tejbeer 14
import com.spice.profitmandi.common.services.mandii.AccountStatusResponseOut;
15
import com.spice.profitmandi.common.services.mandii.EligibilityStatusEnum;
16
import com.spice.profitmandi.common.services.mandii.MandiiService;
24002 amit.gupta 17
import com.spice.profitmandi.common.util.FileUtil;
23929 amit.gupta 18
import com.spice.profitmandi.common.util.FormattingUtils;
27678 amit.gupta 19
import com.spice.profitmandi.common.util.PdfUtils;
23929 amit.gupta 20
import com.spice.profitmandi.common.util.Utils;
24592 amit.gupta 21
import com.spice.profitmandi.common.util.Utils.Attachment;
29308 tejbeer 22
import com.spice.profitmandi.common.web.client.RestClient;
25300 tejbeer 23
import com.spice.profitmandi.dao.Interface.Campaign;
32511 amit.gupta 24
import com.spice.profitmandi.dao.cart.CartService;
25590 amit.gupta 25
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30421 tejbeer 26
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionRemark;
33078 ranu 27
import com.spice.profitmandi.dao.entity.catalog.*;
28
import com.spice.profitmandi.dao.entity.cs.NonSdBuying;
25590 amit.gupta 29
import com.spice.profitmandi.dao.entity.cs.Position;
26283 tejbeer 30
import com.spice.profitmandi.dao.entity.cs.Ticket;
28769 amit.gupta 31
import com.spice.profitmandi.dao.entity.dtr.User;
32421 amit.gupta 32
import com.spice.profitmandi.dao.entity.dtr.*;
33
import com.spice.profitmandi.dao.entity.fofo.*;
34
import com.spice.profitmandi.dao.entity.inventory.*;
33553 ranu 35
import com.spice.profitmandi.dao.entity.logistics.AST;
36
import com.spice.profitmandi.dao.entity.logistics.ASTRepository;
32421 amit.gupta 37
import com.spice.profitmandi.dao.entity.transaction.*;
38
import com.spice.profitmandi.dao.entity.user.*;
32511 amit.gupta 39
import com.spice.profitmandi.dao.entity.warehouse.WarehouseInventoryItem;
40
import com.spice.profitmandi.dao.entity.warehouse.WarehouseScan;
30421 tejbeer 41
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
24250 amit.gupta 42
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25598 amit.gupta 43
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26790 tejbeer 44
import com.spice.profitmandi.dao.enumuration.dtr.RefferalStatus;
29814 tejbeer 45
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
31332 amit.gupta 46
import com.spice.profitmandi.dao.enumuration.fofo.PaymentStatus;
32511 amit.gupta 47
import com.spice.profitmandi.dao.enumuration.fofo.ReturnType;
24242 amit.gupta 48
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
32081 tejbeer 49
import com.spice.profitmandi.dao.enumuration.inventory.VendorCatalogPricingStatus;
30913 tejbeer 50
import com.spice.profitmandi.dao.enumuration.transaction.CreditRisk;
30859 tejbeer 51
import com.spice.profitmandi.dao.enumuration.transaction.LoanReferenceType;
25609 amit.gupta 52
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
32421 amit.gupta 53
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
54
import com.spice.profitmandi.dao.model.*;
33452 amit.gupta 55
import com.spice.profitmandi.dao.repository.GenericRepository;
25590 amit.gupta 56
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
33078 ranu 57
import com.spice.profitmandi.dao.repository.auth.NonSdBuyingRepository;
30421 tejbeer 58
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionRemarkRepository;
32421 amit.gupta 59
import com.spice.profitmandi.dao.repository.catalog.*;
32980 amit.gupta 60
import com.spice.profitmandi.dao.repository.cs.CsService;
61
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
62
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
63
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
32421 amit.gupta 64
import com.spice.profitmandi.dao.repository.dtr.*;
65
import com.spice.profitmandi.dao.repository.fofo.*;
66
import com.spice.profitmandi.dao.repository.inventory.*;
67
import com.spice.profitmandi.dao.repository.transaction.*;
24542 amit.gupta 68
import com.spice.profitmandi.dao.repository.user.AddressRepository;
25721 tejbeer 69
import com.spice.profitmandi.dao.repository.user.UserRepository;
32421 amit.gupta 70
import com.spice.profitmandi.dao.repository.warehouse.*;
33355 amit.gupta 71
import com.spice.profitmandi.dao.service.SidbiService;
32817 amit.gupta 72
import com.spice.profitmandi.dao.service.biuedart.BluedartAuthService;
73
import com.spice.profitmandi.dao.service.biuedart.BluedartService;
31604 tejbeer 74
import com.spice.profitmandi.dao.service.solr.FofoSolr;
32421 amit.gupta 75
import com.spice.profitmandi.service.*;
31332 amit.gupta 76
import com.spice.profitmandi.service.integrations.CCAvenuePaymentService;
28368 tejbeer 77
import com.spice.profitmandi.service.integrations.RazorpayPaymentService;
30858 amit.gupta 78
import com.spice.profitmandi.service.integrations.bharti.model.BAGInsuranceModel;
33638 amit.gupta 79
import com.spice.profitmandi.service.integrations.gstpro.GstProAuthService;
32872 amit.gupta 80
import com.spice.profitmandi.service.integrations.psismart.PsiSmartService;
32948 amit.gupta 81
import com.spice.profitmandi.service.integrations.smartping.SmartPingService;
25694 amit.gupta 82
import com.spice.profitmandi.service.integrations.toffee.ToffeeService;
32421 amit.gupta 83
import com.spice.profitmandi.service.inventory.*;
31746 amit.gupta 84
import com.spice.profitmandi.service.offers.OfferService;
25335 amit.gupta 85
import com.spice.profitmandi.service.order.OrderService;
33452 amit.gupta 86
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
24431 amit.gupta 87
import com.spice.profitmandi.service.pricing.PriceDropService;
23724 amit.gupta 88
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
89
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
90
import com.spice.profitmandi.service.scheme.SchemeService;
29668 tejbeer 91
import com.spice.profitmandi.service.serviceConfig.ServiceConfigService;
31008 amit.gupta 92
import com.spice.profitmandi.service.transaction.CreditNoteService;
30859 tejbeer 93
import com.spice.profitmandi.service.transaction.SDCreditService;
23929 amit.gupta 94
import com.spice.profitmandi.service.transaction.TransactionService;
32990 amit.gupta 95
import com.spice.profitmandi.service.transaction.invoicing.InvoiceService;
23929 amit.gupta 96
import com.spice.profitmandi.service.user.RetailerService;
32511 amit.gupta 97
import com.spice.profitmandi.service.wallet.CommonPaymentService;
23739 amit.gupta 98
import com.spice.profitmandi.service.wallet.WalletService;
32421 amit.gupta 99
import com.spice.profitmandi.service.warehouse.PurchaseOrderService;
32511 amit.gupta 100
import com.spice.profitmandi.service.warehouse.WarehouseInventoryService;
33384 amit.gupta 101
import com.spice.profitmandi.service.warehouse.WarehouseService;
25721 tejbeer 102
import in.shop2020.model.v1.order.OrderStatus;
29308 tejbeer 103
import in.shop2020.model.v1.order.WalletReferenceType;
32421 amit.gupta 104
import org.apache.commons.io.output.ByteArrayOutputStream;
105
import org.apache.commons.lang.StringUtils;
33664 amit.gupta 106
import org.apache.commons.lang3.tuple.Pair;
32421 amit.gupta 107
import org.apache.http.client.methods.CloseableHttpResponse;
108
import org.apache.http.client.methods.HttpPost;
109
import org.apache.http.conn.HttpHostConnectException;
110
import org.apache.http.entity.StringEntity;
111
import org.apache.http.impl.client.CloseableHttpClient;
112
import org.apache.http.impl.client.HttpClients;
113
import org.apache.logging.log4j.LogManager;
114
import org.apache.logging.log4j.Logger;
115
import org.hibernate.Session;
116
import org.hibernate.SessionFactory;
117
import org.hibernate.query.NativeQuery;
118
import org.json.JSONObject;
119
import org.springframework.beans.factory.annotation.Autowired;
120
import org.springframework.beans.factory.annotation.Qualifier;
121
import org.springframework.beans.factory.annotation.Value;
122
import org.springframework.core.io.ByteArrayResource;
123
import org.springframework.core.io.InputStreamSource;
33638 amit.gupta 124
import org.springframework.data.redis.cache.RedisCacheManager;
32421 amit.gupta 125
import org.springframework.mail.javamail.JavaMailSender;
126
import org.springframework.mail.javamail.MimeMessageHelper;
127
import org.springframework.stereotype.Component;
128
import org.springframework.transaction.annotation.Transactional;
31640 tejbeer 129
 
32421 amit.gupta 130
import javax.mail.MessagingException;
131
import javax.mail.internet.InternetAddress;
132
import javax.mail.internet.MimeMessage;
133
import java.io.*;
134
import java.math.BigDecimal;
135
import java.math.RoundingMode;
136
import java.nio.file.Files;
137
import java.nio.file.Paths;
138
import java.sql.Timestamp;
139
import java.text.DecimalFormat;
140
import java.time.*;
141
import java.time.format.DateTimeFormatter;
142
import java.time.temporal.ChronoField;
143
import java.time.temporal.ChronoUnit;
144
import java.util.*;
145
import java.util.Map.Entry;
146
import java.util.stream.Collectors;
147
import java.util.stream.Stream;
32060 amit.gupta 148
 
33664 amit.gupta 149
import static java.util.stream.Collectors.*;
32421 amit.gupta 150
 
151
 
23723 amit.gupta 152
@Component
33384 amit.gupta 153
@Transactional(rollbackFor = {Throwable.class, ProfitMandiBusinessException.class})
23723 amit.gupta 154
public class ScheduledTasks {
155
 
31697 amit.gupta 156
    @Value("${oxigen.recharge.enquiry.url}")
157
    private String oxigenRechargeEnquiryUrl;
24533 govind 158
 
31697 amit.gupta 159
    @Autowired
32482 amit.gupta 160
    PurchaseMigration purchaseMigration;
161
 
162
    @Autowired
32795 amit.gupta 163
    SmartPingService smartPingService;
164
 
33553 ranu 165
    @Autowired
166
    private ASTRepository astRepository;
29668 tejbeer 167
 
31697 amit.gupta 168
    @Autowired
169
    private ServiceConfigService serviceConfigService;
29801 manish 170
 
31697 amit.gupta 171
    @Autowired
172
    private TecnoImeiActivation tecnoImeiActivation;
28205 tejbeer 173
 
31697 amit.gupta 174
    private static final DateTimeFormatter leadTimeFormatter = DateTimeFormatter.ofPattern("d LLL, hh:mm a");
27088 tejbeer 175
 
31697 amit.gupta 176
    @Autowired
177
    private PartnerRegionRepository partnerRegionRepository;
28790 amit.gupta 178
 
31697 amit.gupta 179
    @Autowired
180
    private EmployeeAttendanceRepository employeeAttendanceRepository;
27088 tejbeer 181
 
31697 amit.gupta 182
    @Autowired
183
    VivoImeiActivationService vivoImeiActivationService;
29488 manish 184
 
31697 amit.gupta 185
    @Autowired
186
    ItelImeiActivationService itelImeiActivationService;
29488 manish 187
 
31697 amit.gupta 188
    @Autowired
189
    private PartnerTypeChangeService partnerTypeChangeService;
25598 amit.gupta 190
 
26408 amit.gupta 191
 
31697 amit.gupta 192
    @Autowired
193
    private LeadRepository leadRepository;
25927 amit.gupta 194
 
31697 amit.gupta 195
    @Autowired
196
    private AuthRepository authRepository;
25503 amit.gupta 197
 
31697 amit.gupta 198
    @Autowired
199
    private PriceDropService priceDropService;
26283 tejbeer 200
 
31697 amit.gupta 201
    @Autowired
202
    private FranchiseeVisitRepository franchiseeVisitRepository;
26790 tejbeer 203
 
31697 amit.gupta 204
    @Autowired
205
    private FranchiseeActivityRepository franchiseeActivityRepository;
26790 tejbeer 206
 
31697 amit.gupta 207
    @Autowired
208
    private HdfcPaymentRepository hdfcPaymentRepository;
26790 tejbeer 209
 
31697 amit.gupta 210
    @Autowired
211
    private CsService csService;
25846 amit.gupta 212
 
31697 amit.gupta 213
    @Autowired
214
    private SaholicInventoryService saholicInventoryService;
27208 tejbeer 215
 
31697 amit.gupta 216
    @Autowired
217
    private InsurancePolicyRepository insurancePolicyRepository;
23723 amit.gupta 218
 
31697 amit.gupta 219
    @Autowired
220
    private ToffeeService toffeeService;
25694 amit.gupta 221
 
31697 amit.gupta 222
    @Value("${oxigen.recharge.auth.key}")
223
    private String oxigenRechargeAuthKey;
23724 amit.gupta 224
 
31697 amit.gupta 225
    @Value("${oxigen.recharge.validation.url}")
226
    private String oxigenRechargeValidationUrl;
23724 amit.gupta 227
 
31697 amit.gupta 228
    @Value("${oxigen.recharge.validation.auth.key}")
229
    private String oxigenRechargeValidationAuthKey;
23724 amit.gupta 230
 
31697 amit.gupta 231
    @Value("${think.walnut.digital.recharge.transaction.mobile.url}")
232
    private String thinkWalnutDigitalRechargeTransactionMobileUrl;
23724 amit.gupta 233
 
31697 amit.gupta 234
    @Value("${think.walnut.digital.recharge.transaction.dth.url}")
235
    private String thinkWalnutDigitalRechargeTransactionDthUrl;
23724 amit.gupta 236
 
31697 amit.gupta 237
    @Value("${think.walnut.digital.recharge.enquiry.url}")
238
    private String thinkWalnutDigitalRechargeEnquiryUrl;
23724 amit.gupta 239
 
31697 amit.gupta 240
    @Value("${think.walnut.digital.recharge.balance.url}")
241
    private String thinkWalnutDigitalRechargeBalanceUrl;
23724 amit.gupta 242
 
31697 amit.gupta 243
    @Value("${think.walnut.digital.recharge.username}")
244
    private String thinkWalnutDigitalRechargeUserName;
23724 amit.gupta 245
 
31697 amit.gupta 246
    @Value("${think.walnut.digital.recharge.password}")
247
    private String thinkWalnutDigitalRechargePassword;
23724 amit.gupta 248
 
31697 amit.gupta 249
    @Value("${think.walnut.digital.recharge.auth.key}")
250
    private String thinkWalnutDigitalRechargeAuthKey;
23724 amit.gupta 251
 
31697 amit.gupta 252
    @Autowired
253
    private PurchaseRepository purchaseRepository;
23724 amit.gupta 254
 
31697 amit.gupta 255
    @Autowired
256
    private PriceDropIMEIRepository priceDropIMEIRepository;
25609 amit.gupta 257
 
31697 amit.gupta 258
    @Autowired
259
    PriceDropRepository priceDropRepository;
25609 amit.gupta 260
 
31697 amit.gupta 261
    @Autowired
262
    private PartnerTypeChangeRepository partnerTypeChangeRepository;
28368 tejbeer 263
 
31697 amit.gupta 264
    @Autowired
265
    private SchemeService schemeService;
24683 amit.gupta 266
 
31697 amit.gupta 267
    @Autowired
268
    private ServiceConfigRepository serviceConfigRepository;
29668 tejbeer 269
 
32061 amit.gupta 270
    @Autowired
271
    private RetailerBlockBrandsRepository retailerBlockBrandsRepository;
272
 
31886 tejbeer 273
    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.gupta@smartdukaan.com"};
25609 amit.gupta 274
 
31886 tejbeer 275
    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 276
 
33664 amit.gupta 277
    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 278
 
31886 tejbeer 279
    private static final String[] EMPLOYEE_ATTENDANCE_MAIL_LIST = new String[]{"sm@smartdukaan.com", "sm@smartdukaan.com"};
28790 amit.gupta 280
 
31697 amit.gupta 281
    private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING);
25721 tejbeer 282
 
31697 amit.gupta 283
    @Autowired
284
    private ReporticoService reporticoService;
23724 amit.gupta 285
 
31697 amit.gupta 286
    @Autowired
287
    private PartnerInvestmentService partnerInvestmentService;
25598 amit.gupta 288
 
31697 amit.gupta 289
    @Autowired
290
    private PositionRepository positionRepository;
24337 amit.gupta 291
 
31697 amit.gupta 292
    @Autowired
293
    private FofoOrderItemRepository fofoOrderItemRepository;
25865 amit.gupta 294
 
31697 amit.gupta 295
    @Autowired
296
    private NotificationService notificationService;
24542 amit.gupta 297
 
31697 amit.gupta 298
    @Autowired
299
    private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
24277 amit.gupta 300
 
31697 amit.gupta 301
    @Autowired
302
    private SchemeInOutRepository schemeInOutRepository;
24241 amit.gupta 303
 
31697 amit.gupta 304
    @Autowired
305
    private RechargeTransactionRepository rechargeTransactionRepository;
23724 amit.gupta 306
 
31697 amit.gupta 307
    @Autowired
308
    private CustomerAddressRepository customerAddressRepository;
24542 amit.gupta 309
 
31697 amit.gupta 310
    @Autowired
311
    private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
23724 amit.gupta 312
 
31697 amit.gupta 313
    @Autowired
314
    private FofoLineItemRepository fofoLineItemRepository;
24590 amit.gupta 315
 
31697 amit.gupta 316
    @Autowired
317
    private FofoOrderRepository fofoOrderRepository;
24587 amit.gupta 318
 
31697 amit.gupta 319
    @Autowired
320
    private UserWalletHistoryRepository userWalletHistoryRepository;
24250 amit.gupta 321
 
31697 amit.gupta 322
    @Autowired
323
    private UserWalletRepository userWalletRepository;
24587 amit.gupta 324
 
31697 amit.gupta 325
    @Autowired
326
    private InventoryItemRepository inventoryItemRepository;
23929 amit.gupta 327
 
31697 amit.gupta 328
    @Autowired
329
    private WalletService walletService;
23724 amit.gupta 330
 
31697 amit.gupta 331
    @Autowired
332
    private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
23724 amit.gupta 333
 
31697 amit.gupta 334
    @Autowired
335
    private OxigenRechargeProviderService oxigenRechargeProviderService;
23724 amit.gupta 336
 
31697 amit.gupta 337
    @Autowired
338
    private RechargeProviderRepository rechargeProviderRepository;
23724 amit.gupta 339
 
31697 amit.gupta 340
    @Autowired
341
    private ScanRecordRepository scanRecordRepository;
24242 amit.gupta 342
 
31697 amit.gupta 343
    @Autowired
344
    private DailyRechargeRepository dailyRechargeRepository;
23724 amit.gupta 345
 
31697 amit.gupta 346
    @Autowired
347
    private FofoStoreRepository fofoStoreRepository;
24177 govind 348
 
31697 amit.gupta 349
    @Value("${prod}")
350
    private boolean prod;
26945 amit.gupta 351
 
31697 amit.gupta 352
    @Autowired
353
    private StateGstRateRepository stateGstRateRepository;
23724 amit.gupta 354
 
31697 amit.gupta 355
    @Autowired
356
    private RetailerService retailerService;
23929 amit.gupta 357
 
31697 amit.gupta 358
    @Autowired
33078 ranu 359
    private BrandsRepository brandsRepository;
360
 
361
    @Autowired
31697 amit.gupta 362
    private TransactionService transactionService;
24250 amit.gupta 363
 
31697 amit.gupta 364
    @Autowired
365
    private ItemRepository itemRepository;
23929 amit.gupta 366
 
31697 amit.gupta 367
    @Autowired
368
    private OrderRepository orderRepository;
25351 tejbeer 369
 
31697 amit.gupta 370
    @Autowired
371
    private OrderService orderService;
23929 amit.gupta 372
 
31697 amit.gupta 373
    @Autowired
374
    private SchemeRepository schemeRepository;
24241 amit.gupta 375
 
31697 amit.gupta 376
    @Autowired
377
    private SchemeItemRepository schemeItemRepository;
31612 tejbeer 378
 
31697 amit.gupta 379
    @Autowired
380
    private JavaMailSender mailSender;
24177 govind 381
 
31697 amit.gupta 382
    @Autowired
383
    private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 384
 
31697 amit.gupta 385
    @Autowired
386
    @Qualifier(value = "googleMailSender")
387
    private JavaMailSender googleMailSender;
23929 amit.gupta 388
 
31697 amit.gupta 389
    @Autowired
390
    private InventoryService inventoryService;
23929 amit.gupta 391
 
31697 amit.gupta 392
    @Autowired
393
    private AddressRepository addressRepository;
24542 amit.gupta 394
 
31697 amit.gupta 395
    @Autowired
396
    private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
24542 amit.gupta 397
 
31697 amit.gupta 398
    @Autowired
399
    private Mongo mongoClient;
24683 amit.gupta 400
 
31697 amit.gupta 401
    @Autowired
402
    private DeviceRepository deviceRepository;
25300 tejbeer 403
 
31697 amit.gupta 404
    @Autowired
405
    private PushNotificationRepository pushNotificationRepository;
25300 tejbeer 406
 
31697 amit.gupta 407
    @Autowired
408
    private NotificationCampaignRepository notificationCampaignRepository;
25300 tejbeer 409
 
31697 amit.gupta 410
    @Autowired
411
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
25721 tejbeer 412
 
31697 amit.gupta 413
    @Autowired
414
    private FocusedModelRepository focusedModelRepository;
25721 tejbeer 415
 
31697 amit.gupta 416
    @Autowired
417
    private UserAccountRepository userAccountRepository;
24653 govind 418
 
31697 amit.gupta 419
    @Autowired
420
    private UserRepository userUserRepository;
25721 tejbeer 421
 
31697 amit.gupta 422
    @Autowired
423
    private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
25927 amit.gupta 424
 
31697 amit.gupta 425
    @Autowired
426
    private UserCampaignRepository userCampaignRepository;
25721 tejbeer 427
 
31697 amit.gupta 428
    @Autowired
429
    private Gson gson;
25721 tejbeer 430
 
31697 amit.gupta 431
    @Autowired
432
    private TicketRepository ticketRepository;
26283 tejbeer 433
 
31697 amit.gupta 434
    @Autowired
435
    private RefferalRepository refferalRepository;
26790 tejbeer 436
 
31697 amit.gupta 437
    @Autowired
438
    private PartnerProblemRepository partnerProblemRepository;
28205 tejbeer 439
 
31697 amit.gupta 440
    @Autowired
441
    private PendingOrderRepository pendingOrderRepository;
28368 tejbeer 442
 
31697 amit.gupta 443
    @Autowired
444
    private PendingOrderItemRepository pendingOrderItemRepository;
28368 tejbeer 445
 
31697 amit.gupta 446
    @Value("${razorpay.account.keyId}")
447
    private String keyId;
28368 tejbeer 448
 
31697 amit.gupta 449
    @Value("${razorpay.account.keySecret}")
450
    private String keySecret;
28368 tejbeer 451
 
31697 amit.gupta 452
    @Autowired
453
    private RazorpayPaymentService razorPaymentService;
28369 tejbeer 454
 
31697 amit.gupta 455
    @Autowired
456
    private RazorPayRepository razorPayRepository;
28369 tejbeer 457
 
31697 amit.gupta 458
    @Autowired
459
    private PendingOrderService pendingOrderService;
28377 tejbeer 460
 
31697 amit.gupta 461
    @Autowired
462
    private CustomerRepository customerRepository;
28377 tejbeer 463
 
31697 amit.gupta 464
    @Autowired
465
    private RestClient restClient;
29308 tejbeer 466
 
31697 amit.gupta 467
    @Autowired
468
    private MandiiService mandiiService;
29814 tejbeer 469
 
31697 amit.gupta 470
    @Autowired
471
    CreditAccountRepository creditAccountRepository;
31604 tejbeer 472
 
31697 amit.gupta 473
    @Autowired
474
    CustomerOfferRepository customerOfferRepository;
31612 tejbeer 475
 
31697 amit.gupta 476
    @Autowired
477
    CustomerOfferItemRepository customerOfferItemRepository;
478
    @Autowired
479
    private FofoSolr fofoSolr;
23724 amit.gupta 480
 
25300 tejbeer 481
 
31697 amit.gupta 482
    private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
31388 amit.gupta 483
 
31697 amit.gupta 484
    private String FCM_URL = "https://fcm.googleapis.com/fcm/send";
485
    private String FCM_API_KEY = "AAAASAjNcn4:APA91bG6fWRIgYJI0L9gCjP5ynaXz2hJHYKtD9dfH7Depdv31Nd9APJwhx-OPkAJ1WSz4BGNYG8lHThLFSjDGFxIwUZv241YcAJEGDLgt86mxq9FXJe-yBRu-S0_ZwHqmX-QaVKl5F_A";
23724 amit.gupta 486
 
31697 amit.gupta 487
    @Autowired
488
    private TagListingRepository tagListingRepository;
23724 amit.gupta 489
 
31697 amit.gupta 490
    public void generateDailyRecharge() {
31886 tejbeer 491
        List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository.selectAll(0, 2000);
31697 amit.gupta 492
        List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
493
        rechargeProviders.stream().forEach(x -> x.setAmount(0));
23724 amit.gupta 494
 
31697 amit.gupta 495
        rechargeProviders.stream().forEach(x -> {
31886 tejbeer 496
            Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory.stream().filter(z -> z.getProviderId() == x.getId()).collect(groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
23724 amit.gupta 497
 
31697 amit.gupta 498
            LOGGER.info("dateWiseProviderCreditsMap -{}", dateWiseProviderCreditsMap);
499
            LocalDate endDate = LocalDate.now().plusDays(1);
500
            float previousDayClosing = 0;
501
            LocalDate date = LocalDate.of(2018, 4, 6);
502
            while (date.isBefore(endDate)) {
31886 tejbeer 503
                List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(), date.plusDays(1).atStartOfDay());
23724 amit.gupta 504
 
31886 tejbeer 505
                List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream().filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
23724 amit.gupta 506
 
31697 amit.gupta 507
                float dailyAmount = 0;
508
                float totalCommission = 0;
509
                for (RechargeTransaction rechargeTransaction : successfulTransactions) {
510
                    if (rechargeTransaction.getProviderId() == x.getId()) {
511
                        dailyAmount += rechargeTransaction.getAmount();
512
                        totalCommission += rechargeTransaction.getCommission();
513
                    }
514
                }
28205 tejbeer 515
 
31697 amit.gupta 516
                List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
517
                float dailyWalletRecharge = 0;
518
                if (rechargeHistoryList != null) {
519
                    for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
520
                        if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
521
                            dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
522
                        }
523
                    }
524
                }
525
                if (dailyAmount > 0 || dailyWalletRecharge > 0) {
526
                    DailyRecharge dailyRecharge = null;
527
                    try {
528
                        dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
529
                    } catch (Exception e) {
530
                        LOGGER.info("Could not find Recharge entry");
531
                    }
532
                    if (dailyRecharge == null) {
533
                        dailyRecharge = new DailyRecharge();
534
                        dailyRecharge.setCreateDate(date);
535
                    }
536
                    dailyRecharge.setOpeningBalance(previousDayClosing);
537
                    dailyRecharge.setProviderId(x.getId());
538
                    dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
539
                    dailyRecharge.setTotalAmount(dailyAmount);
540
                    dailyRecharge.setTotalCommission(totalCommission);
541
                    float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
542
                    dailyRecharge.setClosingBalance(closingBalance);
543
                    dailyRechargeRepository.persist(dailyRecharge);
544
                    x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
545
                    previousDayClosing = dailyRecharge.getClosingBalance();
546
                }
547
                date = date.plusDays(1);
548
            }
549
            rechargeProviderRepository.persist(x);
550
        });
551
        LOGGER.info("finished generating daily recharge");
552
    }
24240 amit.gupta 553
 
31697 amit.gupta 554
    public void reconcileRecharge() throws Exception {
555
        LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
556
        LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
557
        List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
558
        LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
559
        nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
560
        nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
561
        RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
562
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
563
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
564
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
565
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
566
        Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
31886 tejbeer 567
        List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
31697 amit.gupta 568
        for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
569
            try {
570
                int providerId = rechargeTransaction.getProviderId();
571
                if (providerId == 1) {
31886 tejbeer 572
                    oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey, rechargeTransaction);
31697 amit.gupta 573
                } else if (providerId == 2) {
31886 tejbeer 574
                    thinkWalnutDigitalRechargeProviderService.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
31697 amit.gupta 575
                }
31886 tejbeer 576
                if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS) || rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
577
                    requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(), rechargeTransaction.getStatus());
31697 amit.gupta 578
                }
579
            } catch (Exception e) {
580
                LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
581
            }
582
        }
583
        LOGGER.info("Reconcile recharge ran successfully");
584
    }
24241 amit.gupta 585
 
31697 amit.gupta 586
    public void processActivation() throws Exception {
587
        schemeService.processActivation();
588
    }
24241 amit.gupta 589
 
31697 amit.gupta 590
    // TemporaryMethod
591
    public void migrateInvoice() {
592
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
593
        Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
31886 tejbeer 594
        partnerOrdersMap = fofoOrders.stream().collect(groupingBy(FofoOrder::getFofoId, Collectors.toList()));
31697 amit.gupta 595
        for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
596
            int sequence = 0;
597
            String prefix = "";
31886 tejbeer 598
            List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId()).collect(Collectors.toList());
31697 amit.gupta 599
            for (FofoOrder order : sortedList) {
23724 amit.gupta 600
 
31697 amit.gupta 601
                LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
602
                if (!order.getInvoiceNumber().contains("SEC")) {
603
                    sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
604
                    prefix = order.getInvoiceNumber().split("/")[0];
605
                } else {
606
                    sequence += 1;
607
                    String invoiceNumber = prefix + "/" + sequence;
608
                    order.setInvoiceNumber(invoiceNumber);
609
                    fofoOrderRepository.persist(order);
610
                }
611
            }
24252 amit.gupta 612
 
31697 amit.gupta 613
        }
614
    }
28205 tejbeer 615
 
31697 amit.gupta 616
    @Autowired
617
    private ReporticoCacheTableRepository reporticoCacheTableRepository;
28205 tejbeer 618
 
31697 amit.gupta 619
    public void processSchemeOut(List<String> invoiceNumbers) throws Exception {
620
        for (String invoiceNumber : invoiceNumbers) {
621
            System.out.println("Invoice Number - " + invoiceNumber);
622
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
32147 amit.gupta 623
            //orderService.reverseScheme(fofoOrder);
31697 amit.gupta 624
            schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
625
        }
626
    }
24271 amit.gupta 627
 
31697 amit.gupta 628
    public void processSchemeIn(List<String> invoiceNumbers) throws Exception {
629
        for (String invoiceNumber : invoiceNumbers) {
630
            System.out.println("Invoice Number - " + invoiceNumber);
631
            Purchase purchase = purchaseRepository.selectByPurchaseReference(invoiceNumber);
632
            schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
633
        }
634
    }
24271 amit.gupta 635
 
31697 amit.gupta 636
    public void processScheme(LocalDateTime startDate, LocalDateTime endDate, boolean dryRun) throws Exception {
637
        LOGGER.info("Started execution at {}", LocalDateTime.now());
638
        System.out.println(
639
                "InventoryId\tSerialNumber\tItem Id\tScheme Id\tScheme Name\tScheme Type\tAmount Type\tDP\tTaxable\tScheme Amount\tAmount Paid");
640
        try {
641
            List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
642
            for (Purchase purchase : purchases) {
643
                schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
644
            }
29160 amit.gupta 645
 
31697 amit.gupta 646
            List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
647
            for (FofoOrder fofoOrder : fofoOrders) {
648
                schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
649
            }
650
        } catch (Exception e) {
651
            e.printStackTrace();
652
            throw e;
653
        }
31886 tejbeer 654
        List<UserWalletHistory> uwhs = userWalletHistoryRepository.selectAllByDateType(LocalDate.now().atStartOfDay(), endDate, Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
31697 amit.gupta 655
        System.out.println("Amount\tReference\tReferenceType\tTimestamp\tDescription");
656
        for (UserWalletHistory uwh : uwhs) {
31886 tejbeer 657
            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 658
        }
659
        LOGGER.info("Schemes processed successfully.");
660
        if (dryRun) {
661
            throw new Exception();
662
        }
663
    }
29160 amit.gupta 664
 
31697 amit.gupta 665
    public void processRechargeCashback() throws Throwable {
666
        LocalDateTime cashbackTime = LocalDateTime.now();
667
        int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
31886 tejbeer 668
        List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository.getPendingCashBackRehargeTransactions();
31697 amit.gupta 669
        Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
31724 amit.gupta 670
                groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
33452 amit.gupta 671
        for (Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
31697 amit.gupta 672
            int retailerId = (Integer) totalRetailerCashback.getKey();
673
            float amount = totalRetailerCashback.getValue().floatValue();
674
            if (Math.round(amount) > 0) {
31886 tejbeer 675
                walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK, "Recharge Cashback", Math.round(amount), LocalDateTime.now());
31697 amit.gupta 676
            }
677
        }
678
        for (RechargeTransaction rt : pendingTransactions) {
679
            rt.setCashbackTimestamp(cashbackTime);
680
            rt.setCashbackReference(referenceId);
681
            rechargeTransactionRepository.persist(rt);
682
        }
683
        LOGGER.info("Cashbacks for Recharge processed Successfully");
684
    }
29160 amit.gupta 685
 
31697 amit.gupta 686
    public void rollOutUpgardedMarginsNextMonth() throws Exception {
687
        LocalDate startOfPreviousMonth = LocalDate.now().with(ChronoField.DAY_OF_MONTH, 1).minusMonths(1);
29160 amit.gupta 688
 
31697 amit.gupta 689
        List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
690
        for (FofoStore store : stores) {
32003 amit.gupta 691
            this.rolloutMarginForStoreOnMonth(store, startOfPreviousMonth);
692
        }
693
    }
29252 amit.gupta 694
 
32003 amit.gupta 695
    public void rolloutMarginForStoreOnMonth(FofoStore store, LocalDate startOfMonth) throws ProfitMandiBusinessException {
696
        int fofoId = store.getId();
29252 amit.gupta 697
 
32003 amit.gupta 698
        PartnerType startOfPreviousMonthPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth);
699
        PartnerType todayPartnerType = partnerTypeChangeService.getTypeOnMonth(fofoId, YearMonth.from(startOfMonth.atStartOfDay()));
700
        if (!startOfPreviousMonthPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
701
            return;
702
        }
703
        if (!startOfPreviousMonthPartnerType.equals(todayPartnerType)) {
704
            LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(), startOfPreviousMonthPartnerType, todayPartnerType);
705
            List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startOfMonth.atStartOfDay(), startOfMonth.plusMonths(1).atStartOfDay(), 0, 0);
706
            for (FofoOrder fofoOrder : fofoOrders) {
707
                schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
31697 amit.gupta 708
            }
709
        }
710
    }
29252 amit.gupta 711
 
32003 amit.gupta 712
 
31697 amit.gupta 713
    public void rollOutUpgardedMargins() throws Exception {
714
        LocalDate today = LocalDate.now();
715
        LocalDate yesterday = today.minusDays(1);
716
        int upgradedCount = 0;
717
        List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
718
        StringBuilder sb = new StringBuilder();
719
        for (FofoStore store : stores) {
720
            int fofoId = store.getId();
23724 amit.gupta 721
 
31697 amit.gupta 722
            PartnerType yesterdayPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, yesterday);
723
            PartnerType todayPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, today);
724
            if (!yesterdayPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
725
                continue;
726
            }
727
            if (!yesterdayPartnerType.equals(todayPartnerType)) {
728
                upgradedCount++;
31886 tejbeer 729
                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 730
                sb.append("<br>");
31886 tejbeer 731
                LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(), yesterdayPartnerType, todayPartnerType);
732
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, yesterday.withDayOfMonth(1).atStartOfDay(), yesterday.atStartOfDay(), 0, 0);
31697 amit.gupta 733
                for (FofoOrder fofoOrder : fofoOrders) {
734
                    schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
735
                }
30390 amit.gupta 736
 
31697 amit.gupta 737
            }
738
        }
739
        if (upgradedCount > 0) {
32439 tejbeer 740
            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 741
        } else {
32439 tejbeer 742
            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 743
        }
744
    }
30393 amit.gupta 745
 
31697 amit.gupta 746
    @Autowired
747
    private PartnerStatsService partnerStatsService;
30393 amit.gupta 748
 
31697 amit.gupta 749
    // Temporary Method
750
    public void evaluateExcessSchemeOut() throws Exception {
751
        Map<Integer, String> userNameMap = retailerService.getAllFofoRetailerIdNameMap();
752
        Map<Integer, Float> userAmountMap = new HashMap<>();
30393 amit.gupta 753
 
31697 amit.gupta 754
        List<List<?>> rows = new ArrayList<>();
31886 tejbeer 755
        List<String> headers = Arrays.asList("Scheme", "Item", "Partner", "Amount", "Credited On", "Invoice Number", "Sale On", "Scheme Start", "Scheme End", "Active On", "Expired On");
33256 amit.gupta 756
        for (Scheme scheme : schemeRepository.selectAll()) {
757
            if (scheme.getType().equals(SchemeType.OUT)) {
758
                List<SchemeInOut> sioList = schemeInOutRepository.selectBySchemeIds(new HashSet<>(Arrays.asList(scheme.getId())));
759
                if (scheme.getActiveTimestamp() != null) {
760
                    LocalDateTime endDateTime = scheme.getEndDateTime();
761
                    if (scheme.getExpireTimestamp() != null && scheme.getExpireTimestamp().isBefore(scheme.getEndDateTime())) {
762
                        endDateTime = scheme.getExpireTimestamp();
31697 amit.gupta 763
                    }
764
                    for (SchemeInOut sio : sioList) {
765
                        InventoryItem inventoryItem = null;
766
                        inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
767
                        FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndSerialNumber(
768
                                inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), null, null, 0, 1).get(0);
31886 tejbeer 769
                        Optional<ScanRecord> record = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId()).stream().filter(y -> y.getType().equals(ScanType.SALE)).findFirst();
31697 amit.gupta 770
                        if (record.isPresent()) {
771
                            int fofoId = record.get().getFofoId();
33256 amit.gupta 772
                            if (record.get().getCreateTimestamp().isAfter(endDateTime) || record.get().getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
31697 amit.gupta 773
                                if (!userAmountMap.containsKey(fofoId)) {
774
                                    userAmountMap.put(fofoId, 0f);
775
                                }
776
                                userAmountMap.put(fofoId, sio.getAmount() + userAmountMap.get(fofoId));
777
                                try {
33256 amit.gupta 778
                                    rows.add(Arrays.asList(scheme.getDescription(), itemRepository.selectById(inventoryItem.getItemId()).getItemDescription(), userNameMap.get(fofoId), sio.getAmount(), FormattingUtils.formatDate(sio.getCreateTimestamp()), fofoOrder.getInvoiceNumber(), FormattingUtils.formatDate(record.get().getCreateTimestamp()), FormattingUtils.formatDate(scheme.getStartDateTime()), FormattingUtils.formatDate(scheme.getEndDateTime()), FormattingUtils.formatDate(scheme.getActiveTimestamp()), FormattingUtils.formatDate(scheme.getExpireTimestamp())));
31697 amit.gupta 779
                                } catch (Exception e) {
780
                                    e.printStackTrace();
781
                                }
782
                            }
783
                        }
784
                    }
785
                }
786
            }
33256 amit.gupta 787
        }
31886 tejbeer 788
        userAmountMap.entrySet().stream().forEach(x -> LOGGER.info("{} to be deducted from {}({}) for wrongly disbursed due to technical error.", x.getValue(), userNameMap.get(x.getKey())));
30393 amit.gupta 789
 
31697 amit.gupta 790
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
31886 tejbeer 791
        Utils.sendMailWithAttachment(googleMailSender, new String[]{"amit.gupta@shop2020.in"}, null, "Partner Excess Amount", "PFA", "ListofSchemes.csv", new ByteArrayResource(baos.toByteArray()));
30390 amit.gupta 792
 
31697 amit.gupta 793
    }
30390 amit.gupta 794
 
31697 amit.gupta 795
    public void fetchParnterStats() throws Exception {
796
        Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
797
        ObjectOutputStream oos = null;
798
        FileOutputStream fout = null;
799
        try {
800
            fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
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
 
844
    public void sendMailForAgeingAlert() throws Exception {
845
        //brandAgeingLimitRepository.selectAll();
846
        Map<String, AgeingModel> ageingModelMap = ageingService.getAllAgeingForSecondary();
847
 
848
        System.out.println(ageingModelMap.size());
849
        List<PartnerAgeingModel> partnerAgeingModels = ageingService.getAllAgeingForTertiary();
850
 
851
 
33452 amit.gupta 852
        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 853
 
33452 amit.gupta 854
        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()));
855
        Attachment attachment1 = new Attachment("secondary-alert.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
856
        Attachment attachment2 = new Attachment("tertiary-alert.csv", new ByteArrayResource(byteArrayOutputStream2.toByteArray()));
31918 amit.gupta 857
 
858
        String mailSubject = "Stock ageing Alert";
859
        Utils.sendMailWithAttachments(mailSender, new String[]{"deena.nath@smartdukaan.com"}, null, mailSubject, "PFA", attachment1, attachment2);
860
    }
861
 
32724 amit.gupta 862
    public void rejectPriceDropsOfApprovedImeis() throws ProfitMandiBusinessException {
32690 amit.gupta 863
        priceDropService.rejectPriceDropsOfApprovedImeis();
864
    }
865
 
33357 amit.gupta 866
    public void processDeductions() {
867
        sidbiService.processDeductions();
868
    }
869
 
31697 amit.gupta 870
    private class SaleRoles {
25598 amit.gupta 871
 
31697 amit.gupta 872
        private List<String> l1;
873
        private List<String> l2;
25598 amit.gupta 874
 
31697 amit.gupta 875
        public SaleRoles() {
876
            l1 = new ArrayList<>();
877
            l2 = new ArrayList<>();
878
        }
25598 amit.gupta 879
 
31697 amit.gupta 880
        public List<String> getL1() {
881
            return l1;
882
        }
25598 amit.gupta 883
 
31697 amit.gupta 884
        public List<String> getL2() {
885
            return l2;
886
        }
26945 amit.gupta 887
 
31697 amit.gupta 888
    }
26945 amit.gupta 889
 
31697 amit.gupta 890
    private class FofoReportingModel {
891
        private String code;
892
        private int fofoId;
893
        private String businessName;
894
        private String territoryManager;
895
        private String regionalManager;
896
        private String businessManager;
26945 amit.gupta 897
 
31697 amit.gupta 898
        public String getCode() {
899
            return code;
900
        }
26945 amit.gupta 901
 
31697 amit.gupta 902
        public void setCode(String code) {
903
            this.code = code;
904
        }
26945 amit.gupta 905
 
31697 amit.gupta 906
        public String getBusinessName() {
907
            return businessName;
908
        }
26945 amit.gupta 909
 
31697 amit.gupta 910
        public void setBusinessName(String businessName) {
911
            this.businessName = businessName;
912
        }
26945 amit.gupta 913
 
31697 amit.gupta 914
        public String getTerritoryManager() {
915
            return territoryManager;
916
        }
26945 amit.gupta 917
 
31697 amit.gupta 918
        public void setTerritoryManager(String territoryManager) {
919
            this.territoryManager = territoryManager;
920
        }
26945 amit.gupta 921
 
31697 amit.gupta 922
        public String getRegionalManager() {
923
            return regionalManager;
924
        }
26945 amit.gupta 925
 
31697 amit.gupta 926
        public void setRegionalManager(String regionalManager) {
927
            this.regionalManager = regionalManager;
928
        }
26945 amit.gupta 929
 
31697 amit.gupta 930
        private ScheduledTasks getOuterType() {
931
            return ScheduledTasks.this;
932
        }
26945 amit.gupta 933
 
31697 amit.gupta 934
        @Override
935
        public String toString() {
31886 tejbeer 936
            return "FofoReportingModel{" + "code='" + code + '\'' + ", fofoId=" + fofoId + ", businessName='" + businessName + '\'' + ", territoryManager='" + territoryManager + '\'' + ", regionalManager='" + regionalManager + '\'' + ", businessManager='" + businessManager + '\'' + '}';
31697 amit.gupta 937
        }
26945 amit.gupta 938
 
31697 amit.gupta 939
        @Override
940
        public boolean equals(Object o) {
941
            if (this == o) return true;
942
            if (o == null || getClass() != o.getClass()) return false;
943
            FofoReportingModel that = (FofoReportingModel) o;
944
            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);
945
        }
26945 amit.gupta 946
 
31697 amit.gupta 947
        @Override
948
        public int hashCode() {
949
            return Objects.hash(code, fofoId, businessName, territoryManager, regionalManager, businessManager);
950
        }
26945 amit.gupta 951
 
31697 amit.gupta 952
        public String getBusinessManager() {
953
            return businessManager;
954
        }
26945 amit.gupta 955
 
31697 amit.gupta 956
        public void setBusinessManager(String businessManager) {
957
            this.businessManager = businessManager;
958
        }
25351 tejbeer 959
 
31697 amit.gupta 960
        public int getFofoId() {
961
            return fofoId;
962
        }
25598 amit.gupta 963
 
31697 amit.gupta 964
        public void setFofoId(int fofoId) {
965
            this.fofoId = fofoId;
966
        }
25598 amit.gupta 967
 
31697 amit.gupta 968
    }
26945 amit.gupta 969
 
31697 amit.gupta 970
    @Autowired
971
    WarehouseInventoryItemRepository warehouseInventoryItemRepository;
26945 amit.gupta 972
 
31746 amit.gupta 973
    @Autowired
974
    OfferService offerService;
975
 
976
    @Autowired
977
    PurchaseReturnItemRepository purchaseReturnItemRepository;
978
 
31918 amit.gupta 979
    @Autowired
980
    BrandRegionMappingRepository brandRegionMappingRepository;
981
 
32161 tejbeer 982
    @Autowired
983
    StandAlone standAlone;
32214 jai.hind 984
    @Autowired
985
    ItelImeiActivationNewService itelImeiActivationNewService;
32350 amit.gupta 986
 
987
    public void checkItelImeiActivationNew(LocalDate date, Integer day) throws Exception {
32063 amit.gupta 988
        try {
32223 amit.gupta 989
            itelImeiActivationNewService.checkItelImeiActivationNew(date, day);
32063 amit.gupta 990
        } catch (Throwable e) {
991
            throw new Exception(e);
992
        }
32223 amit.gupta 993
    }
32062 amit.gupta 994
 
32511 amit.gupta 995
    @Autowired
996
    PurchaseReturnService purchaseReturnService;
997
 
32682 amit.gupta 998
    @Autowired
999
    JavaMailSender javaMailSender;
1000
 
32795 amit.gupta 1001
    @Autowired
1002
    OfferPayoutRepository offerPayoutRepository;
1003
 
1004
    @Autowired
1005
    OfferRepository offerRepository;
1006
 
32817 amit.gupta 1007
    @Autowired
1008
    BluedartAuthService bluedartAuthService;
1009
    @Autowired
1010
    BluedartService bluedartService;
1011
 
1012
    @Autowired
1013
    TransactionRelatedTasks transactionRelatedTasks;
1014
 
32872 amit.gupta 1015
    @Autowired
1016
    PsiSmartService psiSmartService;
32948 amit.gupta 1017
 
32961 amit.gupta 1018
    private void migrateValentine() throws ProfitMandiBusinessException {
1019
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.now().atStartOfDay(), LocalDateTime.now());
1020
        for (FofoOrder fofoOrder : fofoOrders) {
1021
            orderService.processScratchOffer(fofoOrder);
1022
        }
1023
    }
33051 amit.gupta 1024
 
32990 amit.gupta 1025
    @Autowired
1026
    InvoiceService invoiceService;
1027
 
33384 amit.gupta 1028
    @Autowired
1029
    WarehouseService warehouseService;
1030
 
33452 amit.gupta 1031
    @Autowired
1032
    GenericRepository genericRepository;
1033
 
1034
    @Autowired
1035
    PriceCircularService priceCircularService;
1036
 
33638 amit.gupta 1037
    @Autowired
1038
    RedisCacheManager redisFortnightlyCacheManage;
1039
 
1040
    @Autowired
1041
    GstProAuthService gstProAuthService;
33664 amit.gupta 1042
 
33316 amit.gupta 1043
    public void test() throws Exception {
33664 amit.gupta 1044
        List<Pair<Integer, String>> offerList = new ArrayList<>();
1045
        offerList.add(Pair.of(1448, "860229064166451"));
1046
        offerList.add(Pair.of(1448, "860229064167590"));
1047
        offerList.add(Pair.of(1448, "860229064170016"));
1048
        offerList.add(Pair.of(1448, "860229064182599"));
1049
        offerList.add(Pair.of(1448, "860229064182813"));
1050
        offerList.add(Pair.of(1448, "860229064227436"));
1051
        offerList.add(Pair.of(1448, "860229064227774"));
1052
        offerList.add(Pair.of(1448, "860229064228590"));
1053
        offerList.add(Pair.of(1448, "860229064228616"));
1054
        offerList.add(Pair.of(1448, "860229065757712"));
1055
        offerList.add(Pair.of(1448, "866018061686957"));
1056
        offerList.add(Pair.of(1834, "861530062165067"));
1057
        offerList.add(Pair.of(1834, "861530062195841"));
1058
        offerList.add(Pair.of(1834, "861530062870823"));
1059
        offerList.add(Pair.of(1834, "861530063602902"));
1060
        offerList.add(Pair.of(1834, "861530069716623"));
1061
        offerList.add(Pair.of(1834, "861530069721201"));
1062
        offerList.add(Pair.of(1943, "862965063969779"));
1063
        offerList.add(Pair.of(1967, "356052832042411"));
1064
        offerList.add(Pair.of(1967, "356052833682363"));
1065
        offerList.add(Pair.of(1967, "356052833691687"));
1066
        offerList.add(Pair.of(1967, "356052833738090"));
1067
        offerList.add(Pair.of(1967, "356052834058977"));
1068
        offerList.add(Pair.of(1967, "356052834345051"));
1069
        offerList.add(Pair.of(1967, "356052834409279"));
1070
        offerList.add(Pair.of(1967, "356052834880578"));
1071
        offerList.add(Pair.of(1967, "356052835049975"));
1072
        offerList.add(Pair.of(1967, "356052835171522"));
1073
        offerList.add(Pair.of(1967, "356052835238230"));
1074
        offerList.add(Pair.of(1967, "356052835345571"));
1075
        offerList.add(Pair.of(1967, "356052835351595"));
1076
        offerList.add(Pair.of(1967, "356052835374316"));
1077
        offerList.add(Pair.of(1967, "356052835523839"));
1078
        offerList.add(Pair.of(1967, "356052835637316"));
1079
        offerList.add(Pair.of(1967, "356052835637340"));
1080
        offerList.add(Pair.of(1967, "356052835639593"));
1081
        offerList.add(Pair.of(1967, "356052835649816"));
1082
        offerList.add(Pair.of(1967, "356052835679789"));
1083
        offerList.add(Pair.of(1967, "356052835685828"));
1084
        offerList.add(Pair.of(1967, "356052835708752"));
1085
        offerList.add(Pair.of(1967, "356052835729444"));
1086
        offerList.add(Pair.of(1967, "356052835730392"));
1087
        offerList.add(Pair.of(1967, "356052835968778"));
1088
        offerList.add(Pair.of(1967, "356052836002833"));
1089
        offerList.add(Pair.of(1967, "356052836067877"));
1090
        offerList.add(Pair.of(1967, "356052836116310"));
1091
        offerList.add(Pair.of(1967, "356052836765306"));
1092
        offerList.add(Pair.of(1967, "356052837844787"));
1093
        offerList.add(Pair.of(1967, "356052838415090"));
1094
        offerList.add(Pair.of(1967, "356052839615995"));
1095
        offerList.add(Pair.of(1967, "356052839968873"));
1096
        offerList.add(Pair.of(2590, "862282072349096"));
1097
        offerList.add(Pair.of(2590, "863055063069272"));
1098
        offerList.add(Pair.of(2590, "863055063524771"));
1099
        offerList.add(Pair.of(2590, "863055064402159"));
1100
        offerList.add(Pair.of(2590, "865303063229514"));
1101
        offerList.add(Pair.of(2590, "865388070497097"));
1102
        offerList.add(Pair.of(2590, "865388071543774"));
1103
        offerList.add(Pair.of(2590, "865883062545150"));
1104
        offerList.add(Pair.of(2590, "865883065204417"));
1105
        offerList.add(Pair.of(2590, "865883067203516"));
1106
        offerList.add(Pair.of(2590, "865883068436958"));
1107
        offerList.add(Pair.of(2590, "866518077066912"));
1108
        offerList.add(Pair.of(2590, "866518078367038"));
1109
        offerList.add(Pair.of(2590, "866518078369216"));
1110
        offerList.add(Pair.of(2590, "866518078640913"));
1111
        offerList.add(Pair.of(2590, "866518078777830"));
1112
        offerList.add(Pair.of(2590, "866518079106039"));
1113
        offerList.add(Pair.of(2590, "866518079732412"));
1114
        offerList.add(Pair.of(2590, "868544060022835"));
1115
        offerList.add(Pair.of(2590, "868938060097518"));
1116
        offerList.add(Pair.of(2590, "868938060268119"));
1117
        offerList.add(Pair.of(2590, "868938061524171"));
1118
        offerList.add(Pair.of(2590, "868938062621315"));
1119
        offerList.add(Pair.of(2888, "860538070443138"));
1120
        offerList.add(Pair.of(2888, "860538072146754"));
1121
        offerList.add(Pair.of(2888, "860538072989955"));
1122
        offerList.add(Pair.of(2888, "860538072990938"));
1123
        offerList.add(Pair.of(2888, "860538074608413"));
1124
        offerList.add(Pair.of(2888, "860538074609650"));
1125
        offerList.add(Pair.of(2888, "860538074609718"));
1126
        offerList.add(Pair.of(2888, "860538074610179"));
1127
        offerList.add(Pair.of(2888, "860538075012631"));
1128
        offerList.add(Pair.of(2888, "860538075046373"));
1129
        offerList.add(Pair.of(2888, "860538075048619"));
1130
        offerList.add(Pair.of(2888, "860538075049674"));
1131
        offerList.add(Pair.of(2888, "860538075050219"));
1132
        offerList.add(Pair.of(2888, "860538075104719"));
1133
        offerList.add(Pair.of(2888, "860538075106177"));
1134
        offerList.add(Pair.of(2888, "860538075106458"));
1135
        offerList.add(Pair.of(2888, "860538075107712"));
1136
        offerList.add(Pair.of(2888, "860538075109056"));
1137
        offerList.add(Pair.of(2888, "860538075111292"));
1138
        offerList.add(Pair.of(2888, "861288074171272"));
1139
        offerList.add(Pair.of(2888, "861288074520072"));
1140
        offerList.add(Pair.of(2888, "865106074441972"));
1141
        offerList.add(Pair.of(2888, "865106074450411"));
1142
        offerList.add(Pair.of(2888, "865106075324854"));
1143
        offerList.add(Pair.of(2888, "865106075624675"));
1144
        offerList.add(Pair.of(2888, "865883069364696"));
1145
        offerList.add(Pair.of(2888, "868544061909170"));
1146
        offerList.add(Pair.of(2888, "868544063696338"));
1147
        offerList.add(Pair.of(2888, "868938069806216"));
1148
        offerList.add(Pair.of(2888, "868938069813451"));
1149
        offerList.add(Pair.of(2888, "869425071868714"));
1150
        offerList.add(Pair.of(2888, "869425071884653"));
1151
        offerList.add(Pair.of(1912, "350592162065959"));
1152
        offerList.add(Pair.of(1912, "350592162072112"));
1153
        offerList.add(Pair.of(1912, "350592162087698"));
1154
        offerList.add(Pair.of(1912, "350592162089553"));
1155
        offerList.add(Pair.of(1912, "350592162089819"));
1156
        offerList.add(Pair.of(1912, "350592162090478"));
1157
        offerList.add(Pair.of(1912, "350592162091476"));
1158
        offerList.add(Pair.of(1912, "350592162091492"));
1159
        offerList.add(Pair.of(1912, "350592162093472"));
1160
        offerList.add(Pair.of(1912, "350592162093498"));
1161
        offerList.add(Pair.of(1912, "350592162094553"));
1162
        offerList.add(Pair.of(1912, "350592162095196"));
1163
        offerList.add(Pair.of(1912, "350592162095618"));
1164
        offerList.add(Pair.of(1912, "350592162095857"));
1165
        offerList.add(Pair.of(1912, "350592162095873"));
1166
        offerList.add(Pair.of(1912, "350592162096251"));
1167
        offerList.add(Pair.of(1912, "350592162096731"));
1168
        offerList.add(Pair.of(1912, "350592162096996"));
1169
        offerList.add(Pair.of(1912, "350592162097234"));
1170
        offerList.add(Pair.of(1912, "350592162097374"));
1171
        offerList.add(Pair.of(1912, "350592162097416"));
1172
        offerList.add(Pair.of(1912, "350592162097713"));
1173
        offerList.add(Pair.of(1912, "350592162098034"));
1174
        offerList.add(Pair.of(1912, "350592162098059"));
1175
        offerList.add(Pair.of(1912, "350592162098190"));
1176
        offerList.add(Pair.of(1912, "350592162098554"));
1177
        offerList.add(Pair.of(1912, "350592162098638"));
1178
        offerList.add(Pair.of(1912, "350592162098851"));
1179
        offerList.add(Pair.of(1912, "350592162099115"));
1180
        offerList.add(Pair.of(1912, "350592162099156"));
1181
        offerList.add(Pair.of(1912, "350592162099537"));
1182
        offerList.add(Pair.of(1912, "350592162099636"));
1183
        offerList.add(Pair.of(1912, "350592162099818"));
1184
        offerList.add(Pair.of(1912, "350592162099875"));
1185
        offerList.add(Pair.of(1912, "350592162100236"));
1186
        offerList.add(Pair.of(1912, "350592162100293"));
1187
        offerList.add(Pair.of(1912, "350592162100475"));
1188
        offerList.add(Pair.of(1912, "350592162100590"));
1189
        offerList.add(Pair.of(1912, "350592162100897"));
1190
        offerList.add(Pair.of(1912, "350592162101390"));
1191
        offerList.add(Pair.of(1912, "350592162101499"));
1192
        offerList.add(Pair.of(1912, "350592162101531"));
1193
        offerList.add(Pair.of(1912, "350592162101655"));
1194
        offerList.add(Pair.of(1912, "350592162101671"));
1195
        offerList.add(Pair.of(1912, "350592162101697"));
1196
        offerList.add(Pair.of(1912, "350592162102034"));
1197
        offerList.add(Pair.of(1912, "350592162102075"));
1198
        offerList.add(Pair.of(1912, "350592162102117"));
1199
        offerList.add(Pair.of(1912, "350592162102232"));
1200
        offerList.add(Pair.of(1912, "350592162102273"));
1201
        offerList.add(Pair.of(1912, "350592162102398"));
1202
        offerList.add(Pair.of(1912, "350592162102638"));
1203
        offerList.add(Pair.of(1912, "350592162103156"));
1204
        offerList.add(Pair.of(1912, "350592162103198"));
1205
        offerList.add(Pair.of(1912, "350592162103370"));
1206
        offerList.add(Pair.of(1912, "350592162103396"));
1207
        offerList.add(Pair.of(1912, "350592162105235"));
1208
        offerList.add(Pair.of(1912, "350592162106258"));
1209
        offerList.add(Pair.of(1912, "350592162107850"));
1210
        offerList.add(Pair.of(1912, "350592162108312"));
1211
        offerList.add(Pair.of(1912, "350592162108478"));
1212
        offerList.add(Pair.of(1912, "350592162109971"));
1213
        offerList.add(Pair.of(1912, "350592162110250"));
1214
        offerList.add(Pair.of(1912, "350592162110292"));
1215
        offerList.add(Pair.of(1912, "350592162110631"));
1216
        offerList.add(Pair.of(1912, "350592162110912"));
1217
        offerList.add(Pair.of(1912, "350592162111373"));
1218
        offerList.add(Pair.of(1912, "350592162111399"));
1219
        offerList.add(Pair.of(1912, "350592162111472"));
1220
        offerList.add(Pair.of(1912, "350592162111670"));
1221
        offerList.add(Pair.of(1912, "350592162111951"));
1222
        offerList.add(Pair.of(1912, "350592162111977"));
1223
        offerList.add(Pair.of(1912, "350592162112470"));
1224
        offerList.add(Pair.of(1912, "350592162112736"));
1225
        offerList.add(Pair.of(1912, "350592162112751"));
1226
        offerList.add(Pair.of(1912, "350592162112819"));
1227
        offerList.add(Pair.of(1912, "350592162113213"));
1228
        offerList.add(Pair.of(1912, "350592162113379"));
1229
        offerList.add(Pair.of(1912, "350592162113593"));
1230
        offerList.add(Pair.of(1912, "350592162113734"));
1231
        offerList.add(Pair.of(1912, "350592162113759"));
1232
        offerList.add(Pair.of(1912, "350592162114914"));
1233
        offerList.add(Pair.of(1912, "350592162115374"));
1234
        offerList.add(Pair.of(1912, "350592162115598"));
1235
        offerList.add(Pair.of(1912, "350592162115879"));
1236
        offerList.add(Pair.of(1912, "350592162115994"));
1237
        offerList.add(Pair.of(1912, "350592162116174"));
1238
        offerList.add(Pair.of(1912, "350592162116356"));
1239
        offerList.add(Pair.of(1912, "350592162116372"));
1240
        offerList.add(Pair.of(1912, "350592162116539"));
1241
        offerList.add(Pair.of(1912, "350592162116778"));
1242
        offerList.add(Pair.of(1912, "350592162116992"));
1243
        offerList.add(Pair.of(1912, "350592162117131"));
1244
        offerList.add(Pair.of(1912, "350592162117271"));
1245
        offerList.add(Pair.of(1912, "350592162117354"));
1246
        offerList.add(Pair.of(1912, "350592162117370"));
1247
        offerList.add(Pair.of(1912, "350592162118337"));
1248
        offerList.add(Pair.of(1912, "350592162118410"));
1249
        offerList.add(Pair.of(1912, "350592162406435"));
1250
        offerList.add(Pair.of(1912, "350592162407052"));
1251
        offerList.add(Pair.of(1912, "350592162707634"));
1252
        offerList.add(Pair.of(1912, "350592162710596"));
1253
        offerList.add(Pair.of(1912, "350592162711214"));
1254
        offerList.add(Pair.of(1912, "350592162715892"));
1255
        offerList.add(Pair.of(1912, "350592165298755"));
1256
        offerList.add(Pair.of(1912, "350592165309792"));
1257
        offerList.add(Pair.of(1912, "350592167314311"));
1258
        offerList.add(Pair.of(1912, "350592167316076"));
1259
        offerList.add(Pair.of(1912, "350592167324872"));
1260
        offerList.add(Pair.of(1912, "350592167325937"));
1261
        offerList.add(Pair.of(1912, "350592167326133"));
1262
        offerList.add(Pair.of(1912, "350592167327552"));
1263
        offerList.add(Pair.of(1912, "350592167327917"));
1264
        offerList.add(Pair.of(1912, "350592167328238"));
1265
        offerList.add(Pair.of(1912, "350592167328535"));
1266
        offerList.add(Pair.of(1912, "350592167328550"));
1267
        offerList.add(Pair.of(1912, "350592167328717"));
1268
        offerList.add(Pair.of(1912, "350592167328931"));
1269
        offerList.add(Pair.of(1912, "350592167329558"));
1270
        offerList.add(Pair.of(1912, "350592167329772"));
1271
        offerList.add(Pair.of(1912, "350592167329970"));
1272
        offerList.add(Pair.of(1912, "350592167330416"));
1273
        offerList.add(Pair.of(1912, "350592167330697"));
1274
        offerList.add(Pair.of(1912, "350592167330853"));
1275
        offerList.add(Pair.of(1912, "350592167330911"));
1276
        offerList.add(Pair.of(1912, "350592167331018"));
1277
        offerList.add(Pair.of(1912, "350592167331059"));
1278
        offerList.add(Pair.of(1912, "350592167331232"));
1279
        offerList.add(Pair.of(1912, "350592167331299"));
1280
        offerList.add(Pair.of(1912, "350592167331398"));
1281
        offerList.add(Pair.of(1912, "350592167331513"));
1282
        offerList.add(Pair.of(1912, "350592167332172"));
1283
        offerList.add(Pair.of(1912, "350592167332271"));
1284
        offerList.add(Pair.of(1912, "350592167332651"));
1285
        offerList.add(Pair.of(1912, "350592167333097"));
1286
        offerList.add(Pair.of(1912, "350592167333238"));
1287
        offerList.add(Pair.of(1912, "350592167333477"));
1288
        offerList.add(Pair.of(1912, "350592167333550"));
1289
        offerList.add(Pair.of(1912, "350592167333618"));
1290
        offerList.add(Pair.of(1912, "350592167333790"));
1291
        offerList.add(Pair.of(1912, "350592167334038"));
1292
        offerList.add(Pair.of(1912, "350592167334673"));
1293
        offerList.add(Pair.of(1912, "350592167334731"));
1294
        offerList.add(Pair.of(1912, "350592167334772"));
1295
        offerList.add(Pair.of(1912, "350592167335290"));
1296
        offerList.add(Pair.of(1912, "350592167335415"));
1297
        offerList.add(Pair.of(1912, "350592167335514"));
1298
        offerList.add(Pair.of(1912, "350592167336694"));
1299
        offerList.add(Pair.of(1912, "350592167336736"));
1300
        offerList.add(Pair.of(1912, "350592167336751"));
1301
        offerList.add(Pair.of(1912, "350592167336850"));
1302
        offerList.add(Pair.of(1912, "350592167337098"));
1303
        offerList.add(Pair.of(1912, "350592167337338"));
1304
        offerList.add(Pair.of(1912, "350592167337692"));
1305
        offerList.add(Pair.of(1912, "350592167337916"));
1306
        offerList.add(Pair.of(1912, "350592167338054"));
1307
        offerList.add(Pair.of(1912, "350592167338179"));
1308
        offerList.add(Pair.of(1912, "350592167338336"));
1309
        offerList.add(Pair.of(1912, "350592167338377"));
1310
        offerList.add(Pair.of(1912, "350592167338492"));
1311
        offerList.add(Pair.of(1912, "350592167338534"));
1312
        offerList.add(Pair.of(1912, "350592167338617"));
1313
        offerList.add(Pair.of(1912, "350592167338799"));
1314
        offerList.add(Pair.of(1912, "350592167338815"));
1315
        offerList.add(Pair.of(1912, "350592167338898"));
1316
        offerList.add(Pair.of(1912, "350592167339052"));
1317
        offerList.add(Pair.of(1912, "350592167339078"));
1318
        offerList.add(Pair.of(1912, "350592167339094"));
1319
        offerList.add(Pair.of(1912, "350592167339110"));
1320
        offerList.add(Pair.of(1912, "350592167339151"));
1321
        offerList.add(Pair.of(1912, "350592167339177"));
1322
        offerList.add(Pair.of(1912, "350592167339193"));
1323
        offerList.add(Pair.of(1912, "350592167339219"));
1324
        offerList.add(Pair.of(1912, "350592167339235"));
1325
        offerList.add(Pair.of(1912, "350592167339359"));
1326
        offerList.add(Pair.of(1912, "350592167339375"));
1327
        offerList.add(Pair.of(1912, "350592167339557"));
1328
        offerList.add(Pair.of(1912, "350592167339854"));
1329
        offerList.add(Pair.of(1912, "350592167339979"));
1330
        offerList.add(Pair.of(1912, "350592167339995"));
1331
        offerList.add(Pair.of(1912, "350592167340035"));
1332
        offerList.add(Pair.of(1912, "350592167340092"));
1333
        offerList.add(Pair.of(1912, "350592167340290"));
1334
        offerList.add(Pair.of(1912, "350592167340415"));
1335
        offerList.add(Pair.of(1912, "350592167340597"));
1336
        offerList.add(Pair.of(1912, "350592167340878"));
1337
        offerList.add(Pair.of(1912, "350592167340910"));
1338
        offerList.add(Pair.of(1912, "350592167341157"));
1339
        offerList.add(Pair.of(1912, "350592167341215"));
1340
        offerList.add(Pair.of(1912, "350592167341454"));
1341
        offerList.add(Pair.of(1912, "350592167341496"));
1342
        offerList.add(Pair.of(1912, "350592167341678"));
1343
        offerList.add(Pair.of(1912, "350592167341694"));
1344
        offerList.add(Pair.of(1912, "350592167341777"));
1345
        offerList.add(Pair.of(1912, "350592167341793"));
1346
        offerList.add(Pair.of(1912, "350592167341819"));
1347
        offerList.add(Pair.of(1912, "350592167341850"));
1348
        offerList.add(Pair.of(1912, "350592167341934"));
1349
        offerList.add(Pair.of(1912, "350592167342015"));
1350
        offerList.add(Pair.of(1912, "350592167342155"));
1351
        offerList.add(Pair.of(1912, "350592167342254"));
1352
        offerList.add(Pair.of(1912, "350592167342379"));
1353
        offerList.add(Pair.of(1912, "350592167342510"));
1354
        offerList.add(Pair.of(1912, "350592167342593"));
1355
        offerList.add(Pair.of(1912, "350592167342619"));
1356
        offerList.add(Pair.of(1912, "350592167342650"));
1357
        offerList.add(Pair.of(1912, "350592167342833"));
1358
        offerList.add(Pair.of(1912, "350592167342858"));
1359
        offerList.add(Pair.of(1912, "350592167342874"));
1360
        offerList.add(Pair.of(1912, "350592167343054"));
1361
        offerList.add(Pair.of(1912, "350592167343070"));
1362
        offerList.add(Pair.of(1912, "350592167343112"));
1363
        offerList.add(Pair.of(1912, "350592167343393"));
1364
        offerList.add(Pair.of(1912, "350592167343419"));
1365
        offerList.add(Pair.of(1912, "350592167343435"));
1366
        offerList.add(Pair.of(1912, "350592167343476"));
1367
        offerList.add(Pair.of(1912, "350592167343591"));
1368
        offerList.add(Pair.of(1912, "350592167343658"));
1369
        offerList.add(Pair.of(1912, "350592167343690"));
1370
        offerList.add(Pair.of(1912, "350592167343799"));
1371
        offerList.add(Pair.of(1912, "350592167343856"));
1372
        offerList.add(Pair.of(1912, "350592167343872"));
1373
        offerList.add(Pair.of(1912, "350592167343898"));
1374
        offerList.add(Pair.of(1912, "350592167343955"));
1375
        offerList.add(Pair.of(1912, "350592167344177"));
1376
        offerList.add(Pair.of(1912, "350592167344235"));
1377
        offerList.add(Pair.of(1912, "350592167344458"));
1378
        offerList.add(Pair.of(1912, "350592167344730"));
1379
        offerList.add(Pair.of(1912, "350592167344854"));
1380
        offerList.add(Pair.of(1912, "350592167345034"));
1381
        offerList.add(Pair.of(1912, "350592167345117"));
1382
        offerList.add(Pair.of(1912, "350592167345158"));
1383
        offerList.add(Pair.of(1912, "350592167345190"));
1384
        offerList.add(Pair.of(1912, "350592167345356"));
1385
        offerList.add(Pair.of(1912, "350592167345398"));
1386
        offerList.add(Pair.of(1912, "350592167345414"));
1387
        offerList.add(Pair.of(1912, "350592167345539"));
1388
        offerList.add(Pair.of(1912, "350592167345695"));
1389
        offerList.add(Pair.of(1912, "350592167345711"));
1390
        offerList.add(Pair.of(1912, "350592167345737"));
1391
        offerList.add(Pair.of(1912, "350592167345919"));
1392
        offerList.add(Pair.of(1912, "350592167346214"));
1393
        offerList.add(Pair.of(1912, "350592167346255"));
1394
        offerList.add(Pair.of(1912, "350592167346354"));
1395
        offerList.add(Pair.of(1912, "350592167346792"));
1396
        offerList.add(Pair.of(1912, "350592167347014"));
1397
        offerList.add(Pair.of(1912, "350592167347774"));
1398
        offerList.add(Pair.of(1912, "350592167440538"));
1399
        offerList.add(Pair.of(1912, "350592167445792"));
1400
        offerList.add(Pair.of(1912, "350592167446634"));
1401
        offerList.add(Pair.of(1912, "350592167447012"));
1402
        offerList.add(Pair.of(1912, "350592167447194"));
1403
        offerList.add(Pair.of(1912, "350592168757997"));
1404
        offerList.add(Pair.of(1912, "350592168834911"));
1405
        offerList.add(Pair.of(1912, "350592168835058"));
1406
        offerList.add(Pair.of(1912, "350592168835173"));
1407
        offerList.add(Pair.of(1912, "350592168851774"));
1408
        offerList.add(Pair.of(1912, "350592168869412"));
1409
        offerList.add(Pair.of(1912, "350592168879197"));
1410
        offerList.add(Pair.of(1912, "350592168880039"));
1411
        offerList.add(Pair.of(1912, "350592168908772"));
1412
        offerList.add(Pair.of(1912, "350592168920710"));
1413
        offerList.add(Pair.of(1912, "355358276015610"));
1414
        offerList.add(Pair.of(1912, "355358276019430"));
1415
        offerList.add(Pair.of(1912, "355358276019539"));
1416
        offerList.add(Pair.of(1912, "355358276019737"));
1417
        offerList.add(Pair.of(1912, "355358276020735"));
1418
        offerList.add(Pair.of(1912, "355358276020750"));
1419
        offerList.add(Pair.of(1912, "355358276021279"));
1420
        offerList.add(Pair.of(1912, "355358276022632"));
1421
        offerList.add(Pair.of(1912, "355358276024174"));
1422
        offerList.add(Pair.of(1912, "355358276032292"));
1423
        offerList.add(Pair.of(1912, "355358276036616"));
1424
        offerList.add(Pair.of(1912, "355358276044974"));
1425
        offerList.add(Pair.of(1912, "355358276047290"));
1426
        offerList.add(Pair.of(1912, "355358276047779"));
1427
        offerList.add(Pair.of(1912, "355358276048611"));
1428
        offerList.add(Pair.of(1912, "355358276049015"));
1429
        offerList.add(Pair.of(1912, "355358276051532"));
1430
        offerList.add(Pair.of(1912, "355358276051979"));
1431
        offerList.add(Pair.of(1912, "355358276052878"));
1432
        offerList.add(Pair.of(1912, "355358276053256"));
1433
        offerList.add(Pair.of(1912, "355358276053439"));
1434
        offerList.add(Pair.of(1912, "355358276053470"));
1435
        offerList.add(Pair.of(1912, "355358276054197"));
1436
        offerList.add(Pair.of(1912, "355358276054411"));
1437
        offerList.add(Pair.of(1912, "355358276054536"));
1438
        offerList.add(Pair.of(1912, "355358276054817"));
1439
        offerList.add(Pair.of(1912, "355358276055210"));
1440
        offerList.add(Pair.of(1912, "355358276055897"));
1441
        offerList.add(Pair.of(1912, "355358276055970"));
1442
        offerList.add(Pair.of(1912, "355358276056499"));
1443
        offerList.add(Pair.of(1912, "355358276056572"));
1444
        offerList.add(Pair.of(1912, "355358276057190"));
1445
        offerList.add(Pair.of(1912, "355358276057299"));
1446
        offerList.add(Pair.of(1912, "355358276059410"));
1447
        offerList.add(Pair.of(1912, "355358276059832"));
1448
        offerList.add(Pair.of(1912, "355358276061119"));
1449
        offerList.add(Pair.of(1912, "355358276067116"));
1450
        offerList.add(Pair.of(1912, "355358276067637"));
1451
        offerList.add(Pair.of(1912, "355358276067975"));
1452
        offerList.add(Pair.of(1912, "355358276068056"));
1453
        offerList.add(Pair.of(1912, "355358276068577"));
1454
        offerList.add(Pair.of(1912, "355358276068593"));
1455
        offerList.add(Pair.of(1912, "355358276069674"));
1456
        offerList.add(Pair.of(1912, "355358276069732"));
1457
        offerList.add(Pair.of(1912, "355358276071878"));
1458
        offerList.add(Pair.of(1912, "355358276072272"));
1459
        offerList.add(Pair.of(1912, "355358276072652"));
1460
        offerList.add(Pair.of(1912, "355358276073130"));
1461
        offerList.add(Pair.of(1912, "355358276073296"));
1462
        offerList.add(Pair.of(1912, "355358276073650"));
1463
        offerList.add(Pair.of(1912, "355358276074476"));
1464
        offerList.add(Pair.of(1912, "355358276074732"));
1465
        offerList.add(Pair.of(1912, "355358276074815"));
1466
        offerList.add(Pair.of(1912, "355358276076430"));
1467
        offerList.add(Pair.of(1912, "355358276079095"));
1468
        offerList.add(Pair.of(1912, "355358276079699"));
1469
        offerList.add(Pair.of(1912, "355358276079897"));
1470
        offerList.add(Pair.of(1912, "355358276716555"));
1471
        offerList.add(Pair.of(1912, "355358276722637"));
1472
        offerList.add(Pair.of(1912, "355358276724310"));
1473
        offerList.add(Pair.of(1912, "355358276729996"));
1474
        offerList.add(Pair.of(1912, "355358276730218"));
1475
        offerList.add(Pair.of(1912, "355358276730994"));
1476
        offerList.add(Pair.of(1912, "355358276732230"));
1477
        offerList.add(Pair.of(1912, "355358276733592"));
1478
        offerList.add(Pair.of(1912, "355358276734517"));
1479
        offerList.add(Pair.of(1912, "355358276736611"));
1480
        offerList.add(Pair.of(1912, "355358276738591"));
1481
        offerList.add(Pair.of(1912, "355480685059235"));
1482
        offerList.add(Pair.of(1912, "355480686961116"));
1483
        offerList.add(Pair.of(1912, "355480686961876"));
1484
        offerList.add(Pair.of(1912, "355480686962890"));
1485
        offerList.add(Pair.of(1912, "355480686965034"));
1486
        offerList.add(Pair.of(1912, "355480686966115"));
1487
        offerList.add(Pair.of(1912, "355480687449277"));
1488
        offerList.add(Pair.of(1912, "355480687491337"));
1489
        offerList.add(Pair.of(1912, "355480687491394"));
1490
        offerList.add(Pair.of(1912, "355480687491576"));
1491
        offerList.add(Pair.of(1912, "355480687491592"));
1492
        offerList.add(Pair.of(1912, "355480687491675"));
1493
        offerList.add(Pair.of(1912, "355480687491717"));
1494
        offerList.add(Pair.of(1912, "355480687491972"));
1495
        offerList.add(Pair.of(1912, "355480687492038"));
1496
        offerList.add(Pair.of(1912, "355480687492095"));
1497
        offerList.add(Pair.of(1912, "355480687492376"));
1498
        offerList.add(Pair.of(1912, "355480687492418"));
1499
        offerList.add(Pair.of(1912, "355480687492517"));
1500
        offerList.add(Pair.of(1912, "355480687492673"));
1501
        offerList.add(Pair.of(1912, "355480687492699"));
1502
        offerList.add(Pair.of(1912, "355480687492731"));
1503
        offerList.add(Pair.of(1912, "355480687492756"));
1504
        offerList.add(Pair.of(1912, "355480687492897"));
1505
        offerList.add(Pair.of(1912, "355480687492913"));
1506
        offerList.add(Pair.of(1912, "355480687492939"));
1507
        offerList.add(Pair.of(1912, "355480687493051"));
1508
        offerList.add(Pair.of(1912, "355480687493077"));
1509
        offerList.add(Pair.of(1912, "355480687493119"));
1510
        offerList.add(Pair.of(1912, "355480687493192"));
1511
        offerList.add(Pair.of(1912, "355480687493234"));
1512
        offerList.add(Pair.of(1912, "355480687493515"));
1513
        offerList.add(Pair.of(1912, "355480687493630"));
1514
        offerList.add(Pair.of(1912, "355480687493713"));
1515
        offerList.add(Pair.of(1912, "355480687493739"));
1516
        offerList.add(Pair.of(1912, "355480687493796"));
1517
        offerList.add(Pair.of(1912, "355480687493853"));
1518
        offerList.add(Pair.of(1912, "355480687494398"));
1519
        offerList.add(Pair.of(1912, "355480687494497"));
1520
        offerList.add(Pair.of(1912, "355480687494570"));
1521
        offerList.add(Pair.of(1912, "355480687494653"));
1522
        offerList.add(Pair.of(1912, "355480687494711"));
1523
        offerList.add(Pair.of(1912, "355480687494851"));
1524
        offerList.add(Pair.of(1912, "355480687494877"));
1525
        offerList.add(Pair.of(1912, "355480687494935"));
1526
        offerList.add(Pair.of(1912, "355480687495015"));
1527
        offerList.add(Pair.of(1912, "355480687495114"));
1528
        offerList.add(Pair.of(1912, "355480687495130"));
1529
        offerList.add(Pair.of(1912, "355480687495411"));
1530
        offerList.add(Pair.of(1912, "355480687495510"));
1531
        offerList.add(Pair.of(1912, "355480687495536"));
1532
        offerList.add(Pair.of(1912, "355480687495593"));
1533
        offerList.add(Pair.of(1912, "355480687495650"));
1534
        offerList.add(Pair.of(1912, "355480687495775"));
1535
        offerList.add(Pair.of(1912, "355480687496013"));
1536
        offerList.add(Pair.of(1912, "355480687496179"));
1537
        offerList.add(Pair.of(1912, "355480687496237"));
1538
        offerList.add(Pair.of(1912, "355480687496393"));
1539
        offerList.add(Pair.of(1912, "355480687496435"));
1540
        offerList.add(Pair.of(1912, "355480687496518"));
1541
        offerList.add(Pair.of(1912, "355480687496575"));
1542
        offerList.add(Pair.of(1912, "355480687496658"));
1543
        offerList.add(Pair.of(1912, "355480687496815"));
1544
        offerList.add(Pair.of(1912, "355480687496872"));
1545
        offerList.add(Pair.of(1912, "355480687496898"));
1546
        offerList.add(Pair.of(1912, "355480687496914"));
1547
        offerList.add(Pair.of(1912, "355480687496930"));
1548
        offerList.add(Pair.of(1912, "355480687497011"));
1549
        offerList.add(Pair.of(1912, "355480687497037"));
1550
        offerList.add(Pair.of(1912, "355480687497193"));
1551
        offerList.add(Pair.of(1912, "355480687497235"));
1552
        offerList.add(Pair.of(1912, "355480687497359"));
1553
        offerList.add(Pair.of(1912, "355480687497417"));
1554
        offerList.add(Pair.of(1912, "355480687497433"));
1555
        offerList.add(Pair.of(1912, "355480687497474"));
1556
        offerList.add(Pair.of(1912, "355480687497490"));
1557
        offerList.add(Pair.of(1912, "355480687497532"));
1558
        offerList.add(Pair.of(1912, "355480687497599"));
1559
        offerList.add(Pair.of(1912, "355480687497896"));
1560
        offerList.add(Pair.of(1912, "355480687498571"));
1561
        offerList.add(Pair.of(1912, "355480687498779"));
1562
        offerList.add(Pair.of(1912, "355480687498993"));
1563
        offerList.add(Pair.of(1912, "355480687499033"));
1564
        offerList.add(Pair.of(1912, "355480687499090"));
1565
        offerList.add(Pair.of(1912, "355480687499157"));
1566
        offerList.add(Pair.of(1912, "355480687499272"));
1567
        offerList.add(Pair.of(1912, "355480687499298"));
1568
        offerList.add(Pair.of(1912, "355480687499538"));
1569
        offerList.add(Pair.of(1912, "355480687499595"));
1570
        offerList.add(Pair.of(1912, "355480687499637"));
1571
        offerList.add(Pair.of(1912, "355480687499694"));
1572
        offerList.add(Pair.of(1912, "355480687499751"));
1573
        offerList.add(Pair.of(1912, "355480687499959"));
1574
        offerList.add(Pair.of(1912, "355480687499991"));
1575
        offerList.add(Pair.of(1912, "355480687500095"));
1576
        offerList.add(Pair.of(1912, "355480687500111"));
1577
        offerList.add(Pair.of(1912, "355480687500293"));
1578
        offerList.add(Pair.of(1912, "355480687500319"));
1579
        offerList.add(Pair.of(1912, "355480687500392"));
1580
        offerList.add(Pair.of(1912, "355480687500434"));
1581
        offerList.add(Pair.of(1912, "355480687500517"));
1582
        offerList.add(Pair.of(1912, "355480687500772"));
1583
        offerList.add(Pair.of(1912, "355480687500830"));
1584
        offerList.add(Pair.of(1912, "355480687500897"));
1585
        offerList.add(Pair.of(1912, "355480687500970"));
1586
        offerList.add(Pair.of(1912, "355480687501010"));
1587
        offerList.add(Pair.of(1912, "355480687501036"));
1588
        offerList.add(Pair.of(1912, "355480687501077"));
1589
        offerList.add(Pair.of(1912, "355480687501119"));
1590
        offerList.add(Pair.of(1912, "355480687501218"));
1591
        offerList.add(Pair.of(1912, "355480687501317"));
1592
        offerList.add(Pair.of(1912, "355480687501358"));
1593
        offerList.add(Pair.of(1912, "355480687501556"));
1594
        offerList.add(Pair.of(1912, "355480687501697"));
1595
        offerList.add(Pair.of(1912, "355480687501853"));
1596
        offerList.add(Pair.of(1912, "355480687501978"));
1597
        offerList.add(Pair.of(1912, "355480687502059"));
1598
        offerList.add(Pair.of(1912, "355480687502091"));
1599
        offerList.add(Pair.of(1912, "355480687502133"));
1600
        offerList.add(Pair.of(1912, "355480687502570"));
1601
        offerList.add(Pair.of(1912, "355480688566350"));
1602
        offerList.add(Pair.of(1912, "355480688568653"));
1603
        offerList.add(Pair.of(1912, "355480688569370"));
1604
        offerList.add(Pair.of(1912, "355480688570378"));
1605
        offerList.add(Pair.of(1912, "355480688572374"));
1606
        offerList.add(Pair.of(1912, "355480688573976"));
1607
        offerList.add(Pair.of(1912, "355480688574131"));
1608
        offerList.add(Pair.of(1912, "355480688576334"));
1609
        offerList.add(Pair.of(1912, "355480688577936"));
1610
        offerList.add(Pair.of(1912, "355480688578470"));
1611
        offerList.add(Pair.of(1912, "355480688579452"));
1612
        offerList.add(Pair.of(1912, "355480688580179"));
1613
        offerList.add(Pair.of(1912, "355480688586572"));
1614
        offerList.add(Pair.of(1912, "355480688586879"));
1615
        offerList.add(Pair.of(1912, "355480688587075"));
1616
        offerList.add(Pair.of(1912, "355480688587539"));
1617
        offerList.add(Pair.of(1912, "355480688588230"));
1618
        offerList.add(Pair.of(1912, "355480688588354"));
1619
        offerList.add(Pair.of(1912, "355480688588438"));
1620
        offerList.add(Pair.of(1912, "355480688588537"));
1621
        offerList.add(Pair.of(1912, "355480688589873"));
1622
        offerList.add(Pair.of(1912, "355480688590699"));
1623
        offerList.add(Pair.of(1912, "355480688591150"));
1624
        offerList.add(Pair.of(1912, "355480688591291"));
1625
        offerList.add(Pair.of(1912, "355480688591473"));
1626
        offerList.add(Pair.of(1912, "355480688591879"));
1627
        offerList.add(Pair.of(1912, "355480688591952"));
1628
        offerList.add(Pair.of(1912, "355480688592695"));
1629
        offerList.add(Pair.of(1912, "355480688593198"));
1630
        offerList.add(Pair.of(1912, "355480688593339"));
1631
        offerList.add(Pair.of(1912, "355480688593693"));
1632
        offerList.add(Pair.of(1912, "355480688594618"));
1633
        offerList.add(Pair.of(1912, "355480688594998"));
1634
        offerList.add(Pair.of(1912, "355480688595094"));
1635
        offerList.add(Pair.of(1912, "355480688595193"));
1636
        offerList.add(Pair.of(1912, "355480688595276"));
1637
        offerList.add(Pair.of(1912, "355480688595516"));
1638
        offerList.add(Pair.of(1912, "355480688595557"));
1639
        offerList.add(Pair.of(1912, "355480688595870"));
1640
        offerList.add(Pair.of(1912, "355480688596175"));
1641
        offerList.add(Pair.of(1912, "355480688596217"));
1642
        offerList.add(Pair.of(1912, "355480688596373"));
1643
        offerList.add(Pair.of(1912, "355480688596555"));
1644
        offerList.add(Pair.of(1912, "355480688596894"));
1645
        offerList.add(Pair.of(1912, "355480688597017"));
1646
        offerList.add(Pair.of(1912, "355480688597215"));
1647
        offerList.add(Pair.of(1912, "355480688597272"));
1648
        offerList.add(Pair.of(1912, "355480688597330"));
1649
        offerList.add(Pair.of(1912, "355480688597355"));
1650
        offerList.add(Pair.of(1912, "355480688597371"));
1651
        offerList.add(Pair.of(1912, "355480688597439"));
1652
        offerList.add(Pair.of(1912, "355480688597678"));
1653
        offerList.add(Pair.of(1912, "355480688597835"));
1654
        offerList.add(Pair.of(1912, "355480688597876"));
1655
        offerList.add(Pair.of(1912, "355480688598072"));
1656
        offerList.add(Pair.of(1912, "355480688598114"));
1657
        offerList.add(Pair.of(1912, "355480688598197"));
1658
        offerList.add(Pair.of(1912, "355480688598254"));
1659
        offerList.add(Pair.of(1912, "355480688598379"));
1660
        offerList.add(Pair.of(1912, "355480688598619"));
1661
        offerList.add(Pair.of(1912, "355480688598650"));
1662
        offerList.add(Pair.of(1912, "355480688598817"));
1663
        offerList.add(Pair.of(1912, "355480688598858"));
1664
        offerList.add(Pair.of(1912, "355480688598916"));
1665
        offerList.add(Pair.of(1912, "355480688599013"));
1666
        offerList.add(Pair.of(1912, "355480688599153"));
1667
        offerList.add(Pair.of(1912, "355480688599278"));
1668
        offerList.add(Pair.of(1912, "355480688599310"));
1669
        offerList.add(Pair.of(1912, "355480688599351"));
1670
        offerList.add(Pair.of(1912, "355480688599435"));
1671
        offerList.add(Pair.of(1912, "355480688599492"));
1672
        offerList.add(Pair.of(1912, "355480688599534"));
1673
        offerList.add(Pair.of(1912, "355480688599575"));
1674
        offerList.add(Pair.of(1912, "355480688599591"));
1675
        offerList.add(Pair.of(1912, "355480688599658"));
1676
        offerList.add(Pair.of(1912, "355480688599799"));
1677
        offerList.add(Pair.of(1912, "355480688599898"));
1678
        offerList.add(Pair.of(1912, "355480688599955"));
1679
        offerList.add(Pair.of(1912, "357375370735057"));
1680
        offerList.add(Pair.of(1912, "357375370738598"));
1681
        offerList.add(Pair.of(1912, "357375370741295"));
1682
        offerList.add(Pair.of(1912, "357375370741758"));
1683
        offerList.add(Pair.of(1912, "357375370742152"));
1684
        offerList.add(Pair.of(1912, "357375370742251"));
1685
        offerList.add(Pair.of(1912, "357375370742616"));
1686
        offerList.add(Pair.of(1912, "357375370744273"));
1687
        offerList.add(Pair.of(1912, "357375370745015"));
1688
        offerList.add(Pair.of(1912, "357375370746310"));
1689
        offerList.add(Pair.of(1912, "357375370746419"));
1690
        offerList.add(Pair.of(1912, "357375370751013"));
1691
        offerList.add(Pair.of(1912, "357375370751617"));
1692
        offerList.add(Pair.of(1912, "357375370752193"));
1693
        offerList.add(Pair.of(1912, "357375370754819"));
1694
        offerList.add(Pair.of(1912, "357375370779535"));
1695
        offerList.add(Pair.of(1912, "357375370780954"));
1696
        offerList.add(Pair.of(1912, "357375370781390"));
1697
        offerList.add(Pair.of(1912, "357375370781937"));
1698
        offerList.add(Pair.of(1912, "357375370781952"));
1699
        offerList.add(Pair.of(1912, "357375370782133"));
1700
        offerList.add(Pair.of(1912, "357375370783552"));
1701
        offerList.add(Pair.of(1912, "357375370783875"));
1702
        offerList.add(Pair.of(1912, "357375370784659"));
1703
        offerList.add(Pair.of(1912, "357375370785052"));
1704
        offerList.add(Pair.of(1912, "357375370785136"));
1705
        offerList.add(Pair.of(1912, "357375370785938"));
1706
        offerList.add(Pair.of(1912, "357375370786415"));
1707
        offerList.add(Pair.of(1912, "357375370787090"));
1708
        offerList.add(Pair.of(1912, "357375370788130"));
1709
        offerList.add(Pair.of(1912, "357375370788775"));
1710
        offerList.add(Pair.of(1912, "357375370789559"));
1711
        offerList.add(Pair.of(1912, "357375370789633"));
1712
        offerList.add(Pair.of(1912, "357375370789716"));
1713
        offerList.add(Pair.of(1912, "357375370790094"));
1714
        offerList.add(Pair.of(1912, "357375370790334"));
1715
        offerList.add(Pair.of(1912, "357375370790631"));
1716
        offerList.add(Pair.of(1912, "357375370790698"));
1717
        offerList.add(Pair.of(1912, "357375370791050"));
1718
        offerList.add(Pair.of(1912, "357375370791639"));
1719
        offerList.add(Pair.of(1912, "357375370792439"));
1720
        offerList.add(Pair.of(1912, "357375370792991"));
1721
        offerList.add(Pair.of(1912, "357375370793155"));
1722
        offerList.add(Pair.of(1912, "357375370794773"));
1723
        offerList.add(Pair.of(1912, "357375370794856"));
1724
        offerList.add(Pair.of(1912, "357375370796158"));
1725
        offerList.add(Pair.of(1912, "357375370796919"));
1726
        offerList.add(Pair.of(1912, "357375370797057"));
1727
        offerList.add(Pair.of(1912, "357375370797933"));
1728
        offerList.add(Pair.of(1912, "357375370798733"));
1729
        offerList.add(Pair.of(1912, "357375370798998"));
1730
        offerList.add(Pair.of(1912, "357375370799319"));
1731
        offerList.add(Pair.of(1912, "357375370800471"));
1732
        offerList.add(Pair.of(1912, "357375370801057"));
1733
        offerList.add(Pair.of(1912, "357375370802337"));
1734
        offerList.add(Pair.of(1912, "357375370804838"));
1735
        offerList.add(Pair.of(1912, "357375370805017"));
1736
        offerList.add(Pair.of(1912, "357375370805272"));
1737
        offerList.add(Pair.of(1912, "357375370809159"));
1738
        offerList.add(Pair.of(1912, "357375370810173"));
1739
        offerList.add(Pair.of(1912, "357375370810512"));
1740
        offerList.add(Pair.of(1912, "357375370814597"));
1741
        offerList.add(Pair.of(1912, "357375370819315"));
1742
        offerList.add(Pair.of(1912, "357375370827490"));
1743
        offerList.add(Pair.of(1912, "357375370832755"));
1744
        offerList.add(Pair.of(1912, "357375370833811"));
1745
        offerList.add(Pair.of(1912, "357375370839594"));
1746
        offerList.add(Pair.of(1912, "357375370839750"));
1747
        offerList.add(Pair.of(1912, "357375370840956"));
1748
        offerList.add(Pair.of(1912, "357375370841095"));
1749
        offerList.add(Pair.of(1912, "357375370841731"));
1750
        offerList.add(Pair.of(1912, "357375370841772"));
1751
        offerList.add(Pair.of(1912, "357375370841830"));
1752
        offerList.add(Pair.of(1912, "357375370841939"));
1753
        offerList.add(Pair.of(1912, "357375370842416"));
1754
        offerList.add(Pair.of(1912, "357375370842473"));
1755
        offerList.add(Pair.of(1912, "357375370842754"));
1756
        offerList.add(Pair.of(1912, "357375370843273"));
1757
        offerList.add(Pair.of(1912, "357375370843919"));
1758
        offerList.add(Pair.of(1912, "357375370844214"));
1759
        offerList.add(Pair.of(1912, "357375370844610"));
1760
        offerList.add(Pair.of(1912, "357375370845070"));
1761
        offerList.add(Pair.of(1912, "357375370846052"));
1762
        offerList.add(Pair.of(1912, "357375370847332"));
1763
        offerList.add(Pair.of(1912, "357375370847654"));
1764
        offerList.add(Pair.of(1912, "357375370848215"));
1765
        offerList.add(Pair.of(1912, "357375370848611"));
1766
        offerList.add(Pair.of(1912, "357375370848678"));
1767
        offerList.add(Pair.of(1912, "357375370849296"));
1768
        offerList.add(Pair.of(1912, "357375370849353"));
1769
        offerList.add(Pair.of(1912, "357375370849437"));
1770
        offerList.add(Pair.of(1912, "357375370849833"));
1771
        offerList.add(Pair.of(1912, "357375370849874"));
1772
        offerList.add(Pair.of(1912, "357375370850534"));
1773
        offerList.add(Pair.of(1912, "357375370850757"));
1774
        offerList.add(Pair.of(1912, "357375370850997"));
1775
        offerList.add(Pair.of(1912, "357375370851417"));
1776
        offerList.add(Pair.of(1912, "357375370851573"));
1777
        offerList.add(Pair.of(1912, "357375370851730"));
1778
        offerList.add(Pair.of(1912, "357375370853694"));
1779
        offerList.add(Pair.of(1912, "357375370853991"));
1780
        offerList.add(Pair.of(1912, "357375370855350"));
1781
        offerList.add(Pair.of(1912, "357375370857133"));
1782
        offerList.add(Pair.of(1912, "357375370857679"));
1783
        offerList.add(Pair.of(1912, "357375370858115"));
1784
        offerList.add(Pair.of(1912, "357375370858354"));
1785
        offerList.add(Pair.of(1912, "357375370858693"));
1786
        offerList.add(Pair.of(1912, "357375370858818"));
1787
        offerList.add(Pair.of(1912, "357375370859253"));
1788
        offerList.add(Pair.of(1912, "357375370859311"));
1789
        offerList.add(Pair.of(1912, "357375370859378"));
1790
        offerList.add(Pair.of(1912, "357375370859618"));
1791
        offerList.add(Pair.of(1912, "357375370859717"));
1792
        offerList.add(Pair.of(1912, "357375370864899"));
1793
        offerList.add(Pair.of(1912, "357375370880598"));
1794
        offerList.add(Pair.of(1912, "357375370892551"));
1795
        offerList.add(Pair.of(1912, "357375370906278"));
1796
        offerList.add(Pair.of(1912, "357375371735379"));
1797
        offerList.add(Pair.of(1912, "357375371738357"));
1798
        offerList.add(Pair.of(1912, "357375371738977"));
1799
        offerList.add(Pair.of(1912, "357375371739298"));
1800
        offerList.add(Pair.of(1912, "357375371740734"));
1801
        offerList.add(Pair.of(1912, "357375371751558"));
1802
        offerList.add(Pair.of(1912, "357375371753216"));
1803
        offerList.add(Pair.of(1912, "357375371754370"));
1804
        offerList.add(Pair.of(1912, "357375371756052"));
1805
        offerList.add(Pair.of(1912, "357375371759551"));
1806
        offerList.add(Pair.of(1912, "357375371759718"));
1807
        offerList.add(Pair.of(1912, "357375371763736"));
1808
        offerList.add(Pair.of(1912, "357375371763819"));
1809
        offerList.add(Pair.of(1912, "357375371764411"));
1810
        offerList.add(Pair.of(1912, "357375371764775"));
1811
        offerList.add(Pair.of(1912, "357375371765038"));
1812
        offerList.add(Pair.of(1912, "357375371765350"));
1813
        offerList.add(Pair.of(1912, "357375371765533"));
1814
        offerList.add(Pair.of(1912, "357375371765657"));
1815
        offerList.add(Pair.of(1912, "357375371766358"));
1816
        offerList.add(Pair.of(1912, "357375371767794"));
1817
        offerList.add(Pair.of(1912, "357375371767836"));
1818
        offerList.add(Pair.of(1912, "357375371768115"));
1819
        offerList.add(Pair.of(1912, "357375371768255"));
1820
        offerList.add(Pair.of(1912, "357375371768339"));
1821
        offerList.add(Pair.of(1912, "357375371768396"));
1822
        offerList.add(Pair.of(1912, "357375371768792"));
1823
        offerList.add(Pair.of(1912, "357375371768990"));
1824
        offerList.add(Pair.of(1912, "357375371769436"));
1825
        offerList.add(Pair.of(1912, "357375371769816"));
1826
        offerList.add(Pair.of(1912, "357375371770251"));
1827
        offerList.add(Pair.of(1912, "357375371770350"));
1828
        offerList.add(Pair.of(1912, "357375371770558"));
1829
        offerList.add(Pair.of(1912, "357375371771770"));
1830
        offerList.add(Pair.of(1912, "357375371772133"));
1831
        offerList.add(Pair.of(1912, "357375371773016"));
1832
        offerList.add(Pair.of(1912, "357375371774295"));
1833
        offerList.add(Pair.of(1912, "357375371775250"));
1834
        offerList.add(Pair.of(1912, "357375371776050"));
1835
        offerList.add(Pair.of(1912, "357375371776217"));
1836
        offerList.add(Pair.of(1912, "357375371776399"));
1837
        offerList.add(Pair.of(1912, "357375371777512"));
1838
        offerList.add(Pair.of(1912, "357375371781399"));
1839
        offerList.add(Pair.of(1912, "357375371781514"));
1840
        offerList.add(Pair.of(1912, "357375371784377"));
1841
        offerList.add(Pair.of(1912, "357375371785499"));
1842
        offerList.add(Pair.of(1912, "357375371785770"));
1843
        offerList.add(Pair.of(1912, "357375371789194"));
1844
        offerList.add(Pair.of(1912, "357375371789996"));
1845
        offerList.add(Pair.of(1912, "357375371790671"));
1846
        offerList.add(Pair.of(1912, "357375371791059"));
1847
        offerList.add(Pair.of(1912, "357375371791893"));
1848
        offerList.add(Pair.of(1912, "357375371814414"));
1849
        offerList.add(Pair.of(1912, "357375371816732"));
1850
        offerList.add(Pair.of(1912, "357375371817359"));
1851
        offerList.add(Pair.of(1912, "357375371847455"));
1852
        offerList.add(Pair.of(1912, "357375371848255"));
1853
        offerList.add(Pair.of(1912, "357375371852950"));
1854
        offerList.add(Pair.of(1912, "357375371855417"));
1855
        offerList.add(Pair.of(1912, "357375371856258"));
1856
        offerList.add(Pair.of(1912, "357375371857454"));
1857
        offerList.add(Pair.of(1912, "357375371862355"));
1858
        offerList.add(Pair.of(1912, "357375371862652"));
1859
        offerList.add(Pair.of(1912, "357375371863270"));
1860
        offerList.add(Pair.of(1912, "357375371863916"));
1861
        offerList.add(Pair.of(1912, "357375371864237"));
1862
        offerList.add(Pair.of(1912, "357375371865119"));
1863
        offerList.add(Pair.of(1912, "357375371866638"));
1864
        offerList.add(Pair.of(1912, "357375371868337"));
1865
        offerList.add(Pair.of(1912, "357375371868436"));
1866
        offerList.add(Pair.of(1912, "357375371868873"));
1867
        offerList.add(Pair.of(1912, "357375371869137"));
1868
        offerList.add(Pair.of(1912, "357375371870291"));
1869
        offerList.add(Pair.of(1912, "357375371871174"));
1870
        offerList.add(Pair.of(1912, "357375371872198"));
1871
        offerList.add(Pair.of(1912, "357375371872271"));
1872
        offerList.add(Pair.of(1912, "357375371872495"));
1873
        offerList.add(Pair.of(1912, "357375371873170"));
1874
        offerList.add(Pair.of(1912, "357375371873857"));
1875
        offerList.add(Pair.of(1912, "357375371873873"));
1876
        offerList.add(Pair.of(1912, "357375371874038"));
1877
        offerList.add(Pair.of(1912, "357375371874111"));
1878
        offerList.add(Pair.of(1912, "357375371874194"));
1879
        offerList.add(Pair.of(1912, "357375371874491"));
1880
        offerList.add(Pair.of(1912, "357375371874772"));
1881
        offerList.add(Pair.of(1912, "357375371874996"));
1882
        offerList.add(Pair.of(1912, "357375371875175"));
1883
        offerList.add(Pair.of(1912, "357375371875274"));
1884
        offerList.add(Pair.of(1912, "357375371875431"));
1885
        offerList.add(Pair.of(1912, "357375371875852"));
1886
        offerList.add(Pair.of(1912, "357375371875894"));
1887
        offerList.add(Pair.of(1912, "357375371875910"));
1888
        offerList.add(Pair.of(1912, "357375371876017"));
1889
        offerList.add(Pair.of(1912, "357375371876231"));
1890
        offerList.add(Pair.of(1912, "357375371876298"));
1891
        offerList.add(Pair.of(1912, "357375371876850"));
1892
        offerList.add(Pair.of(1912, "357375371877718"));
1893
        offerList.add(Pair.of(1912, "357375371877775"));
1894
        offerList.add(Pair.of(1912, "357375371877874"));
1895
        offerList.add(Pair.of(1912, "357375371878237"));
1896
        offerList.add(Pair.of(1912, "357375371878419"));
1897
        offerList.add(Pair.of(1912, "357375371879292"));
1898
        offerList.add(Pair.of(1912, "357375371880571"));
1899
        offerList.add(Pair.of(1912, "357375371881199"));
1900
        offerList.add(Pair.of(1912, "357375371882098"));
1901
        offerList.add(Pair.of(1912, "357375371882296"));
1902
        offerList.add(Pair.of(1912, "357375371883534"));
1903
        offerList.add(Pair.of(1912, "357375371884599"));
1904
        offerList.add(Pair.of(1912, "357375371885331"));
1905
        offerList.add(Pair.of(1912, "357375371885497"));
1906
        offerList.add(Pair.of(1912, "357375371885554"));
1907
        offerList.add(Pair.of(1912, "357375371886214"));
1908
        offerList.add(Pair.of(1912, "357375371897112"));
1909
        offerList.add(Pair.of(1912, "357375371897435"));
1910
        offerList.add(Pair.of(1912, "357375371898433"));
1911
        offerList.add(Pair.of(1912, "357375371898698"));
1912
        offerList.add(Pair.of(1912, "357375371915815"));
1913
        offerList.add(Pair.of(1912, "358177964066850"));
1914
        offerList.add(Pair.of(1912, "358177964076479"));
1915
        offerList.add(Pair.of(1912, "358177964102713"));
1916
        offerList.add(Pair.of(1912, "358177964770519"));
1917
        offerList.add(Pair.of(1912, "358177964770790"));
1918
        offerList.add(Pair.of(1912, "358177964773133"));
1919
        offerList.add(Pair.of(1912, "358177964773778"));
1920
        offerList.add(Pair.of(1912, "358382749330593"));
1921
        offerList.add(Pair.of(1912, "358382749330817"));
1922
        offerList.add(Pair.of(1912, "358382749330874"));
1923
        offerList.add(Pair.of(1912, "358382749337978"));
1924
        offerList.add(Pair.of(1912, "358382749356390"));
1925
        offerList.add(Pair.of(1912, "358382749356812"));
1926
        offerList.add(Pair.of(1912, "358382749359477"));
1927
        offerList.add(Pair.of(1912, "358382749359956"));
1928
        offerList.add(Pair.of(1912, "358382749360012"));
1929
        offerList.add(Pair.of(1912, "358382749361036"));
1930
        offerList.add(Pair.of(1912, "358382749361358"));
1931
        offerList.add(Pair.of(1912, "358382749361374"));
1932
        offerList.add(Pair.of(1912, "358382749362034"));
1933
        offerList.add(Pair.of(1912, "358382749363297"));
1934
        offerList.add(Pair.of(1912, "358382749363412"));
1935
        offerList.add(Pair.of(1912, "358382749363438"));
1936
        offerList.add(Pair.of(1912, "358382749363479"));
1937
        offerList.add(Pair.of(1912, "358382749364618"));
1938
        offerList.add(Pair.of(1912, "358382749365318"));
1939
        offerList.add(Pair.of(1912, "358382749365730"));
1940
        offerList.add(Pair.of(1912, "358382749365755"));
1941
        offerList.add(Pair.of(1912, "358382749365771"));
1942
        offerList.add(Pair.of(1912, "358382749366274"));
1943
        offerList.add(Pair.of(1912, "358382749366415"));
1944
        offerList.add(Pair.of(1912, "358382749366431"));
1945
        offerList.add(Pair.of(1912, "358382749366456"));
1946
        offerList.add(Pair.of(1912, "358382749366696"));
1947
        offerList.add(Pair.of(1912, "358382749366753"));
1948
        offerList.add(Pair.of(1912, "358382749366795"));
1949
        offerList.add(Pair.of(1912, "358382749366852"));
1950
        offerList.add(Pair.of(1912, "358382749366951"));
1951
        offerList.add(Pair.of(1912, "358382749367058"));
1952
        offerList.add(Pair.of(1912, "358382749367157"));
1953
        offerList.add(Pair.of(1912, "358382749367272"));
1954
        offerList.add(Pair.of(1912, "358382749367439"));
1955
        offerList.add(Pair.of(1912, "358382749367579"));
1956
        offerList.add(Pair.of(1912, "358382749367991"));
1957
        offerList.add(Pair.of(1912, "358382749368072"));
1958
        offerList.add(Pair.of(1912, "358382749368114"));
1959
        offerList.add(Pair.of(1912, "358382749368213"));
1960
        offerList.add(Pair.of(1912, "358382749368312"));
1961
        offerList.add(Pair.of(1912, "358382749369013"));
1962
        offerList.add(Pair.of(1912, "358382749369153"));
1963
        offerList.add(Pair.of(1912, "358382749369377"));
1964
        offerList.add(Pair.of(1912, "358382749369450"));
1965
        offerList.add(Pair.of(1912, "358382749369633"));
1966
        offerList.add(Pair.of(1912, "358382749370417"));
1967
        offerList.add(Pair.of(1912, "358382749370458"));
1968
        offerList.add(Pair.of(1912, "358382749370698"));
1969
        offerList.add(Pair.of(1912, "358382749370953"));
1970
        offerList.add(Pair.of(1912, "358382749371118"));
1971
        offerList.add(Pair.of(1912, "358382749371134"));
1972
        offerList.add(Pair.of(1912, "358382749371233"));
1973
        offerList.add(Pair.of(1912, "358382749371977"));
1974
        offerList.add(Pair.of(1912, "358382749372694"));
1975
        offerList.add(Pair.of(1912, "358382749373114"));
1976
        offerList.add(Pair.of(1912, "358382749373213"));
1977
        offerList.add(Pair.of(1912, "358382749373296"));
1978
        offerList.add(Pair.of(1912, "358382749373718"));
1979
        offerList.add(Pair.of(1912, "358382749374138"));
1980
        offerList.add(Pair.of(1912, "358382749374195"));
1981
        offerList.add(Pair.of(1912, "358382749374294"));
1982
        offerList.add(Pair.of(1912, "358382749375234"));
1983
        offerList.add(Pair.of(1912, "358382749375374"));
1984
        offerList.add(Pair.of(1912, "358382749375697"));
1985
        offerList.add(Pair.of(1912, "358382749375812"));
1986
        offerList.add(Pair.of(1912, "358382749376653"));
1987
        offerList.add(Pair.of(1912, "358382749376711"));
1988
        offerList.add(Pair.of(1912, "358382749381372"));
1989
        offerList.add(Pair.of(1912, "358382749385779"));
1990
        offerList.add(Pair.of(1912, "358382749391470"));
1991
        offerList.add(Pair.of(1912, "358382749392338"));
1992
        offerList.add(Pair.of(1912, "358382749393153"));
1993
        offerList.add(Pair.of(1912, "358382749394094"));
1994
        offerList.add(Pair.of(1912, "358382749394698"));
1995
        offerList.add(Pair.of(1912, "358382749395091"));
1996
        offerList.add(Pair.of(1912, "358382749395331"));
1997
        offerList.add(Pair.of(1912, "358382749395612"));
1998
        offerList.add(Pair.of(1912, "358382749395711"));
1999
        offerList.add(Pair.of(1912, "358382749396453"));
2000
        offerList.add(Pair.of(1912, "358382749397196"));
2001
        offerList.add(Pair.of(1912, "358382749397253"));
2002
        offerList.add(Pair.of(1912, "358382749397436"));
2003
        offerList.add(Pair.of(1912, "358382749397675"));
2004
        offerList.add(Pair.of(1912, "358382749397717"));
2005
        offerList.add(Pair.of(1912, "358382749397998"));
2006
        offerList.add(Pair.of(1912, "358382749398111"));
2007
        offerList.add(Pair.of(1912, "358382749398392"));
2008
        offerList.add(Pair.of(1912, "358382749398475"));
2009
        offerList.add(Pair.of(1912, "358382749398533"));
2010
        offerList.add(Pair.of(1912, "358382749399218"));
2011
        offerList.add(Pair.of(1912, "358710494639034"));
2012
        offerList.add(Pair.of(1912, "359197384149648"));
2013
        offerList.add(Pair.of(1912, "359197384150745"));
2014
        offerList.add(Pair.of(1912, "359197384155140"));
2015
        offerList.add(Pair.of(1912, "359197384156668"));
2016
        offerList.add(Pair.of(1912, "359197384158540"));
2017
        offerList.add(Pair.of(1912, "359197384158748"));
2018
        offerList.add(Pair.of(1912, "359197384159027"));
2019
        offerList.add(Pair.of(1912, "359197384159183"));
2020
        offerList.add(Pair.of(1912, "359197384159548"));
2021
        offerList.add(Pair.of(1912, "359197384159688"));
2022
        offerList.add(Pair.of(1912, "359197384159944"));
2023
        offerList.add(Pair.of(1912, "359197384161221"));
2024
        offerList.add(Pair.of(1912, "359197384161684"));
2025
        offerList.add(Pair.of(1912, "359197384163227"));
2026
        offerList.add(Pair.of(1912, "359197384163441"));
2027
        offerList.add(Pair.of(1912, "359197384171543"));
2028
        offerList.add(Pair.of(1912, "359197384173622"));
2029
        offerList.add(Pair.of(1912, "359197384173788"));
2030
        offerList.add(Pair.of(1912, "359197384175502"));
2031
        offerList.add(Pair.of(1912, "359197384176203"));
2032
        offerList.add(Pair.of(1912, "359197384176468"));
2033
        offerList.add(Pair.of(1912, "359197384176682"));
2034
        offerList.add(Pair.of(1912, "359197384176906"));
2035
        offerList.add(Pair.of(1912, "359197384254307"));
2036
        offerList.add(Pair.of(1912, "359197384254646"));
2037
        offerList.add(Pair.of(1912, "359197384254802"));
2038
        offerList.add(Pair.of(1912, "359197384254885"));
2039
        offerList.add(Pair.of(1912, "359197384255767"));
2040
        offerList.add(Pair.of(1912, "359197384255809"));
2041
        offerList.add(Pair.of(1912, "359197384255825"));
2042
        offerList.add(Pair.of(1912, "359197384255965"));
2043
        offerList.add(Pair.of(1912, "359197384255981"));
2044
        offerList.add(Pair.of(1912, "359197384257524"));
2045
        offerList.add(Pair.of(1912, "359197384575966"));
2046
        offerList.add(Pair.of(1912, "359197386828389"));
2047
        offerList.add(Pair.of(1912, "359197386831185"));
2048
        offerList.add(Pair.of(1912, "359197386833900"));
2049
        offerList.add(Pair.of(1912, "359197386834569"));
2050
        offerList.add(Pair.of(1912, "359197386837109"));
2051
        offerList.add(Pair.of(1912, "359197386837646"));
2052
        offerList.add(Pair.of(1912, "359197386840087"));
2053
        offerList.add(Pair.of(1912, "359197386844147"));
2054
        offerList.add(Pair.of(1912, "359197386844188"));
2055
        offerList.add(Pair.of(1912, "359197386845805"));
2056
        offerList.add(Pair.of(1912, "359197386845920"));
2057
        offerList.add(Pair.of(1912, "359197386849062"));
2058
        offerList.add(Pair.of(1912, "359197386849989"));
2059
        offerList.add(Pair.of(1912, "359197386851167"));
2060
        offerList.add(Pair.of(1912, "359197386853106"));
2061
        offerList.add(Pair.of(1912, "359197386854021"));
2062
        offerList.add(Pair.of(1912, "359197386854641"));
2063
        offerList.add(Pair.of(1912, "359197386855507"));
2064
        offerList.add(Pair.of(1912, "359197386855747"));
2065
        offerList.add(Pair.of(1912, "359197386856588"));
2066
        offerList.add(Pair.of(1912, "359197386857768"));
2067
        offerList.add(Pair.of(1912, "359197386857966"));
2068
        offerList.add(Pair.of(1912, "359197386858204"));
2069
        offerList.add(Pair.of(1912, "359197386858824"));
2070
        offerList.add(Pair.of(1912, "359197386858840"));
2071
        offerList.add(Pair.of(1912, "359197386858949"));
2072
        offerList.add(Pair.of(1912, "359197386859020"));
2073
        offerList.add(Pair.of(1912, "359197386859285"));
2074
        offerList.add(Pair.of(1912, "359197386859400"));
2075
        offerList.add(Pair.of(1912, "359197386859749"));
2076
        offerList.add(Pair.of(1912, "359197386860325"));
2077
        offerList.add(Pair.of(1912, "359197386860689"));
2078
        offerList.add(Pair.of(1912, "359197386860945"));
2079
        offerList.add(Pair.of(1912, "359197386860986"));
2080
        offerList.add(Pair.of(1912, "359197386861042"));
2081
        offerList.add(Pair.of(1912, "359197386861240"));
2082
        offerList.add(Pair.of(1912, "359197386861307"));
2083
        offerList.add(Pair.of(1912, "359197386861547"));
2084
        offerList.add(Pair.of(1912, "359197386861869"));
2085
        offerList.add(Pair.of(1912, "359197386861885"));
2086
        offerList.add(Pair.of(1912, "359197386861968"));
2087
        offerList.add(Pair.of(1912, "359197386862065"));
2088
        offerList.add(Pair.of(1912, "359197386862222"));
2089
        offerList.add(Pair.of(1912, "359197386862768"));
2090
        offerList.add(Pair.of(1912, "359197386862941"));
2091
        offerList.add(Pair.of(1912, "359197386863089"));
2092
        offerList.add(Pair.of(1912, "359197386863204"));
2093
        offerList.add(Pair.of(1912, "359197386863220"));
2094
        offerList.add(Pair.of(1912, "359197386863303"));
2095
        offerList.add(Pair.of(1912, "359197386863345"));
2096
        offerList.add(Pair.of(1912, "359197386863386"));
2097
        offerList.add(Pair.of(1912, "359197386863543"));
2098
        offerList.add(Pair.of(1912, "359197386863667"));
2099
        offerList.add(Pair.of(1912, "359197386863683"));
2100
        offerList.add(Pair.of(1912, "359197386863709"));
2101
        offerList.add(Pair.of(1912, "359197386863949"));
2102
        offerList.add(Pair.of(1912, "359197386864145"));
2103
        offerList.add(Pair.of(1912, "359197386864186"));
2104
        offerList.add(Pair.of(1912, "359197386864608"));
2105
        offerList.add(Pair.of(1912, "359197386864681"));
2106
        offerList.add(Pair.of(1912, "359197386864822"));
2107
        offerList.add(Pair.of(1912, "359197386865142"));
2108
        offerList.add(Pair.of(1912, "359197386865365"));
2109
        offerList.add(Pair.of(1912, "359197386865704"));
2110
        offerList.add(Pair.of(1912, "359197386865746"));
2111
        offerList.add(Pair.of(1912, "359197386865829"));
2112
        offerList.add(Pair.of(1912, "359197386865886"));
2113
        offerList.add(Pair.of(1912, "359197386866181"));
2114
        offerList.add(Pair.of(1912, "359197386866223"));
2115
        offerList.add(Pair.of(1912, "359197386866405"));
2116
        offerList.add(Pair.of(1912, "359197386866546"));
2117
        offerList.add(Pair.of(1912, "359197386866603"));
2118
        offerList.add(Pair.of(1912, "359197386866868"));
2119
        offerList.add(Pair.of(1912, "359197386867049"));
2120
        offerList.add(Pair.of(1912, "359197386867346"));
2121
        offerList.add(Pair.of(1912, "359197386867387"));
2122
        offerList.add(Pair.of(1912, "359197386867460"));
2123
        offerList.add(Pair.of(1912, "359197386867825"));
2124
        offerList.add(Pair.of(1912, "359197386867908"));
2125
        offerList.add(Pair.of(1912, "359197386868047"));
2126
        offerList.add(Pair.of(1912, "359197386868161"));
2127
        offerList.add(Pair.of(1912, "359197386868484"));
2128
        offerList.add(Pair.of(1912, "359197386868567"));
2129
        offerList.add(Pair.of(1912, "359197386868906"));
2130
        offerList.add(Pair.of(1912, "359197386868963"));
2131
        offerList.add(Pair.of(1912, "359197386869482"));
2132
        offerList.add(Pair.of(1912, "359197386869524"));
2133
        offerList.add(Pair.of(1912, "359197386869565"));
2134
        offerList.add(Pair.of(1912, "359197386869649"));
2135
        offerList.add(Pair.of(1912, "359197386869821"));
2136
        offerList.add(Pair.of(1912, "359197386869987"));
2137
        offerList.add(Pair.of(1912, "359197386870068"));
2138
        offerList.add(Pair.of(1912, "359197386870142"));
2139
        offerList.add(Pair.of(1912, "359197386870381"));
2140
        offerList.add(Pair.of(1912, "359197386870449"));
2141
        offerList.add(Pair.of(1912, "359197386870647"));
2142
        offerList.add(Pair.of(1912, "359197386870829"));
2143
        offerList.add(Pair.of(1912, "359197386870902"));
2144
        offerList.add(Pair.of(1912, "359197386870944"));
2145
        offerList.add(Pair.of(1912, "359197386870985"));
2146
        offerList.add(Pair.of(1912, "359197386871264"));
2147
        offerList.add(Pair.of(1912, "359197386871363"));
2148
        offerList.add(Pair.of(1912, "359197386871546"));
2149
        offerList.add(Pair.of(1912, "359197386871629"));
2150
        offerList.add(Pair.of(1912, "359197386871868"));
2151
        offerList.add(Pair.of(1912, "359197386871983"));
2152
        offerList.add(Pair.of(1912, "359197386872064"));
2153
        offerList.add(Pair.of(1912, "359197386872080"));
2154
        offerList.add(Pair.of(1912, "359197386872304"));
2155
        offerList.add(Pair.of(1912, "359197386872569"));
2156
        offerList.add(Pair.of(1912, "359197386873542"));
2157
        offerList.add(Pair.of(1912, "359197386874268"));
2158
        offerList.add(Pair.of(1912, "359197386874367"));
2159
        offerList.add(Pair.of(1912, "359197386874383"));
2160
        offerList.add(Pair.of(1912, "359197386874847"));
2161
        offerList.add(Pair.of(1912, "359197386875166"));
2162
        offerList.add(Pair.of(1912, "359571521884491"));
2163
        offerList.add(Pair.of(1912, "359571521893773"));
2164
        offerList.add(Pair.of(1912, "359571521902756"));
2165
        offerList.add(Pair.of(1912, "359571521914256"));
2166
        offerList.add(Pair.of(1912, "359571521918091"));
2167
        offerList.add(Pair.of(1912, "359571521924214"));
2168
        offerList.add(Pair.of(1912, "359571521925732"));
2169
        offerList.add(Pair.of(1912, "359571521926334"));
2170
        offerList.add(Pair.of(1912, "359571521930716"));
2171
        offerList.add(Pair.of(1912, "359571521930955"));
2172
        offerList.add(Pair.of(1912, "359571521930971"));
2173
        offerList.add(Pair.of(1912, "359571521931516"));
2174
        offerList.add(Pair.of(1912, "359571521932118"));
2175
        offerList.add(Pair.of(1912, "359571521932951"));
2176
        offerList.add(Pair.of(1912, "359571521932993"));
2177
        offerList.add(Pair.of(1912, "359571521933652"));
2178
        offerList.add(Pair.of(1912, "359571521935392"));
2179
        offerList.add(Pair.of(1912, "359571521935616"));
2180
        offerList.add(Pair.of(1912, "359571521937158"));
2181
        offerList.add(Pair.of(1912, "359571521937513"));
2182
        offerList.add(Pair.of(1912, "359571521937570"));
2183
        offerList.add(Pair.of(1912, "359571521937778"));
2184
        offerList.add(Pair.of(1912, "359571521937851"));
2185
        offerList.add(Pair.of(1912, "359571521937919"));
2186
        offerList.add(Pair.of(1912, "359571521937950"));
2187
        offerList.add(Pair.of(1912, "359571521938032"));
2188
        offerList.add(Pair.of(1912, "359571521938057"));
2189
        offerList.add(Pair.of(1912, "359571521938198"));
2190
        offerList.add(Pair.of(1912, "359571521938214"));
2191
        offerList.add(Pair.of(1912, "359571521938354"));
2192
        offerList.add(Pair.of(1912, "359571521938651"));
2193
        offerList.add(Pair.of(1912, "359571521938719"));
2194
        offerList.add(Pair.of(1912, "359571521938818"));
2195
        offerList.add(Pair.of(1912, "359571521938917"));
2196
        offerList.add(Pair.of(1912, "359571521938958"));
2197
        offerList.add(Pair.of(1912, "359571521938974"));
2198
        offerList.add(Pair.of(1912, "359571521939139"));
2199
        offerList.add(Pair.of(1912, "359571521939212"));
2200
        offerList.add(Pair.of(1912, "359571521939576"));
2201
        offerList.add(Pair.of(1912, "359571521939691"));
2202
        offerList.add(Pair.of(1912, "359571521940012"));
2203
        offerList.add(Pair.of(1912, "359571521940277"));
2204
        offerList.add(Pair.of(1912, "359571521940376"));
2205
        offerList.add(Pair.of(1912, "359571521940970"));
2206
        offerList.add(Pair.of(1912, "359571521941119"));
2207
        offerList.add(Pair.of(1912, "359571521941937"));
2208
        offerList.add(Pair.of(1912, "359571521943495"));
2209
        offerList.add(Pair.of(1912, "359571521944279"));
2210
        offerList.add(Pair.of(1912, "359571521944691"));
2211
        offerList.add(Pair.of(1912, "359571521944873"));
2212
        offerList.add(Pair.of(1912, "359571521945052"));
2213
        offerList.add(Pair.of(1912, "359571521945177"));
2214
        offerList.add(Pair.of(1912, "359571521945276"));
2215
        offerList.add(Pair.of(1912, "359571521945631"));
2216
        offerList.add(Pair.of(1912, "359571521945797"));
2217
        offerList.add(Pair.of(1912, "359571521946217"));
2218
        offerList.add(Pair.of(1912, "359571521946415"));
2219
        offerList.add(Pair.of(1912, "359571521946670"));
2220
        offerList.add(Pair.of(1912, "359571521946837"));
2221
        offerList.add(Pair.of(1912, "359571521946910"));
2222
        offerList.add(Pair.of(1912, "359571521947199"));
2223
        offerList.add(Pair.of(1912, "359571521947355"));
2224
        offerList.add(Pair.of(1912, "359571521947371"));
2225
        offerList.add(Pair.of(1912, "359571521947751"));
2226
        offerList.add(Pair.of(1912, "359571521947819"));
2227
        offerList.add(Pair.of(1912, "359571521948171"));
2228
        offerList.add(Pair.of(1912, "359571521948692"));
2229
        offerList.add(Pair.of(1912, "359571521949195"));
2230
        offerList.add(Pair.of(1912, "359571521949815"));
2231
        offerList.add(Pair.of(1912, "359571521950433"));
2232
        offerList.add(Pair.of(1912, "359571521950896"));
2233
        offerList.add(Pair.of(1912, "359571521951274"));
2234
        offerList.add(Pair.of(1912, "359571521951555"));
2235
        offerList.add(Pair.of(1912, "359571521951837"));
2236
        offerList.add(Pair.of(1912, "359571521952694"));
2237
        offerList.add(Pair.of(1912, "359571521953056"));
2238
        offerList.add(Pair.of(1912, "359571521953197"));
2239
        offerList.add(Pair.of(1912, "359571521953270"));
2240
        offerList.add(Pair.of(1912, "359571521953619"));
2241
        offerList.add(Pair.of(1912, "359571521953676"));
2242
        offerList.add(Pair.of(1912, "359571521953692"));
2243
        offerList.add(Pair.of(1912, "359571521953858"));
2244
        offerList.add(Pair.of(1912, "359571521953890"));
2245
        offerList.add(Pair.of(1912, "359571521954294"));
2246
        offerList.add(Pair.of(1912, "359571521954419"));
2247
        offerList.add(Pair.of(1912, "359571521954492"));
2248
        offerList.add(Pair.of(1912, "359571521954799"));
2249
        offerList.add(Pair.of(1912, "359571521954815"));
2250
        offerList.add(Pair.of(1912, "359571521954831"));
2251
        offerList.add(Pair.of(1912, "359571521954856"));
2252
        offerList.add(Pair.of(1912, "359571521955119"));
2253
        offerList.add(Pair.of(1912, "359571521956695"));
2254
        offerList.add(Pair.of(1912, "359571521956950"));
2255
        offerList.add(Pair.of(1912, "359571521957057"));
2256
        offerList.add(Pair.of(1912, "359571521957339"));
2257
        offerList.add(Pair.of(1912, "359571521957834"));
2258
        offerList.add(Pair.of(1912, "359571521958113"));
2259
        offerList.add(Pair.of(1912, "359571521958394"));
2260
        offerList.add(Pair.of(1912, "359571522322517"));
2261
        offerList.add(Pair.of(1912, "359571522325734"));
2262
        offerList.add(Pair.of(1912, "359571522327375"));
2263
        offerList.add(Pair.of(1912, "359571522328811"));
2264
        offerList.add(Pair.of(1912, "359571522332292"));
2265
        offerList.add(Pair.of(1912, "359571522335055"));
2266
        offerList.add(Pair.of(1912, "359571522339115"));
2267
        offerList.add(Pair.of(1912, "359571523006655"));
2268
        offerList.add(Pair.of(1912, "359571523008396"));
2269
        offerList.add(Pair.of(1912, "359571523016936"));
2270
        offerList.add(Pair.of(1912, "359571523018536"));
2271
        offerList.add(Pair.of(1912, "359571523019211"));
2272
        offerList.add(Pair.of(1912, "359571523021217"));
2273
        offerList.add(Pair.of(1912, "359571523021274"));
2274
        offerList.add(Pair.of(1912, "359571523022538"));
2275
        offerList.add(Pair.of(1912, "359571523022553"));
2276
        offerList.add(Pair.of(1912, "359571523022751"));
2277
        offerList.add(Pair.of(1912, "359571523023478"));
2278
        offerList.add(Pair.of(1912, "359571523023817"));
2279
        offerList.add(Pair.of(1912, "359571523023916"));
2280
        offerList.add(Pair.of(1912, "359571523024195"));
2281
        offerList.add(Pair.of(1912, "359571523029533"));
2282
        offerList.add(Pair.of(1912, "359571523033311"));
2283
        offerList.add(Pair.of(1912, "359571523033337"));
2284
        offerList.add(Pair.of(1912, "359571523034814"));
2285
        offerList.add(Pair.of(1912, "359571523252531"));
2286
        offerList.add(Pair.of(1912, "359571523252754"));
2287
        offerList.add(Pair.of(1912, "359571523252838"));
2288
        offerList.add(Pair.of(1912, "359571523837190"));
2289
        offerList.add(Pair.of(1912, "359571523841952"));
2290
        offerList.add(Pair.of(1912, "359571523842018"));
2291
        offerList.add(Pair.of(1912, "359571524068316"));
2292
        offerList.add(Pair.of(1912, "359571524069553"));
2293
        offerList.add(Pair.of(1912, "359571524071450"));
2294
        offerList.add(Pair.of(1912, "359571524071799"));
2295
        offerList.add(Pair.of(1912, "359571524072599"));
2296
        offerList.add(Pair.of(1912, "359571524072730"));
2297
        offerList.add(Pair.of(1912, "359571524073076"));
2298
        offerList.add(Pair.of(1912, "359571524073571"));
2299
        offerList.add(Pair.of(1912, "359571524075873"));
2300
        offerList.add(Pair.of(1912, "359571524077614"));
2301
        offerList.add(Pair.of(1912, "359571524078810"));
2302
        offerList.add(Pair.of(1912, "359571524080550"));
2303
        offerList.add(Pair.of(1912, "359571524081970"));
2304
        offerList.add(Pair.of(1912, "359571524084412"));
2305
        offerList.add(Pair.of(1912, "359571524085153"));
2306
        offerList.add(Pair.of(1912, "359571524086656"));
2307
        offerList.add(Pair.of(1912, "359571524086797"));
2308
        offerList.add(Pair.of(1912, "359571524087431"));
2309
        offerList.add(Pair.of(1912, "359571524087837"));
2310
        offerList.add(Pair.of(1912, "359571524088199"));
2311
        offerList.add(Pair.of(1912, "359571524089593"));
2312
        offerList.add(Pair.of(1912, "359571524089973"));
2313
        offerList.add(Pair.of(1912, "359571524094791"));
2314
        offerList.add(Pair.of(1912, "359571524094833"));
2315
        offerList.add(Pair.of(1912, "359571524094874"));
2316
        offerList.add(Pair.of(1912, "359571524094957"));
2317
        offerList.add(Pair.of(1912, "359571524095053"));
2318
        offerList.add(Pair.of(1912, "359571524095335"));
2319
        offerList.add(Pair.of(1912, "359571524095772"));
2320
        offerList.add(Pair.of(1912, "359571524095871"));
2321
        offerList.add(Pair.of(1912, "359571524612097"));
2322
        offerList.add(Pair.of(1912, "359571524617898"));
2323
        offerList.add(Pair.of(1912, "359571524633390"));
2324
        offerList.add(Pair.of(1912, "359571524633879"));
2325
        offerList.add(Pair.of(1912, "359571524634414"));
2326
        offerList.add(Pair.of(1912, "359571524766190"));
2327
        offerList.add(Pair.of(1912, "359571524766216"));
2328
        offerList.add(Pair.of(1912, "359571527360694"));
2329
        Map<Integer, Set<String>> offerSerialNumbersMap = offerList.stream().collect(groupingBy(x -> x.getLeft(), mapping(x -> x.getRight(), toSet())));
2330
        List<Integer> offerIds = new ArrayList(offerSerialNumbersMap.keySet());
2331
        for (Integer offerId : offerIds) {
2332
            //if(offerId !=1912) continue;
2333
            List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllByOfferId(offerId);
2334
            Set<String> serialNumbersToReverse = offerSerialNumbersMap.get(offerId);
2335
            Map<Long, Map<String, List<OfferPayout>>> partnerOfferPayouts = offerPayouts.stream().filter(x -> x.getRejectTimestamp() == null && serialNumbersToReverse.contains(x.getSerialNumber()))
2336
                    .collect(groupingBy(OfferPayout::getFofoId, groupingBy(OfferPayout::getSerialNumber)));
2337
            for (Entry<Long, Map<String, List<OfferPayout>>> partnerPayoutEntry : partnerOfferPayouts.entrySet()) {
2338
                int fofoId = partnerPayoutEntry.getKey().intValue();
2339
                float amount = 0;
2340
                List<OfferPayout> partnerPayouts = partnerPayoutEntry.getValue().values().stream().map(list -> Collections.max(list, Comparator.comparing(OfferPayout::getAmount))).collect(toList());
2341
                for (OfferPayout offerPayout : partnerPayouts) {
2342
                    amount += offerPayout.getAmount();
2343
                    offerPayout.setStatus(SchemePayoutStatus.REJECTED);
2344
                    offerPayout.setRejectTimestamp(LocalDateTime.now());
2345
                }
2346
                walletService.rollbackAmountFromWallet(fofoId, amount, offerId,
2347
                        WalletReferenceType.ADDITIONAL_SCHEME, "Payout reversed as amount credited twice", LocalDateTime.now());
2348
 
2349
            }
2350
 
2351
        }
2352
 
2353
        //System.out.println(gstProAuthService.getAuthToken("34AACCC1596Q002"));
33638 amit.gupta 2354
        //redisFortnightlyCacheManage.getCache("gstAuthToken").evict("34AACCC1596Q002");
33464 ranu 2355
//        LocalDate startDate = LocalDate.of(2024, Month.MAY, 1);
2356
//        List<PriceDropIMEI> priceDropIMEIList = priceDropIMEIRepository.selectAllByCreditedBetween(startDate.atStartOfDay(), startDate.plusMonths(1).atTime(Utils.MAX_TIME));
2357
//        Set<Integer> inventoryItemIds = priceDropIMEIList.stream().map(x -> x.getInventoryItemId()).collect(Collectors.toSet());
2358
//        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds);
2359
//        List<String> headers = Arrays.asList("FofoId", "Serial Number", "Original DP", "DP(Inc PDs)", "PDs credited", "Fixed amount", "Discount", "Percentage Amount", "Margins Calc.", "Margins credited", "SoldOut");
2360
//
2361
//        List<List<?>> rows = new ArrayList<>();
2362
//        for (InventoryItem inventoryItem : inventoryItems) {
2363
//            InventoryPayoutModel ipm = priceCircularService.getPayouts(inventoryItem);
2364
//            ipm.getActualRolloutAmount();
2365
//                        rows.add(Arrays.asList(inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), ipm.getDp() + ipm.getPriceDropAmount(), ipm.getDp(), 0d,//PDs credited
2366
//                    ipm.getFixedAmount(), ipm.getDiscountAmount(), ipm.getPercentageAmount(), ipm.getActualRolloutAmount(), ipm.getPaidAmount(), inventoryItem.getLastScanType().equals(ScanType.SALE)));
2367
//        }
2368
//        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
2369
//        FileOutputStream fos = new FileOutputStream(new File("/Users/amit/data.csv"));
2370
//        baos.writeTo(fos);
33452 amit.gupta 2371
 
2372
 
2373
    }
2374
 
2375
    public void test4() throws Exception {
2376
        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);
2377
        for (Integer offerId : offerIds) {
2378
            Offer fromOffer = offerRepository.selectById(offerId);
2379
            CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(fromOffer);
2380
            System.out.println("Processing offer Id " + fromOffer);
2381
            offerService.processActivationtOffer(createOfferRequest);
2382
        }
33433 amit.gupta 2383
        //sdCreditService.checkLoans();
33384 amit.gupta 2384
        /*System.out.println(warehouseService.moveToBad(Arrays.asList("860374066889716",
2385
                "863587077946699",
2386
                "865883067303639",
2387
                "868116066180113",
2388
                "868116066179719")));*/
33423 amit.gupta 2389
        /*System.out.println(warehouseService.moveToGood(Arrays.asList("354814720314877",
33391 amit.gupta 2390
                "43356/c21100001116",
33423 amit.gupta 2391
                "34850/c21100054629")));*/
33355 amit.gupta 2392
        //this.test1();
33433 amit.gupta 2393
        this.processSidbiDeductions();
33316 amit.gupta 2394
        /*List<Order> orders = orderRepository.selectByInvoiceNumber("NSDL43328");
2395
        invoiceService.saveInvoice(orders);*/
33355 amit.gupta 2396
        /*for ( int fofoId : Arrays.asList(4149607,175138674,175138854,175138934,175138958,175139138,175139150,175139245,175139259,175139306,175139324,175139344,175139346,175139362,175139386,175139395,175139412,175139452,175139455,175139460,175139462,175139463,175139488,175139489,175139499,175139504,175139508,175139511,175139513,175139521,175139524,175139531,175139532,175139557,175139559,175139576,175139603,175139605,175139608,175139612,175139621,175139630,175139638,175139657,175139661,175139690,175139697,175139716,175139731)) {
33317 amit.gupta 2397
            try {
2398
                sdCreditService.fundWallet(fofoId);
2399
            } catch (ProfitMandiBusinessException pbse) {
2400
                LOGGER.info("Failed to fund wallet for - {}", fofoId);
2401
            }
33355 amit.gupta 2402
        }*/
33295 amit.gupta 2403
 
2404
        //transactionService.moveOrdersFulfimentWarehouseByBillingWarehouseId(7573);
32817 amit.gupta 2405
    }
2406
 
2407
    public void test3() throws Exception {
2408
        List<Long> payoutIds = Arrays.asList();
32795 amit.gupta 2409
        List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllByIds(payoutIds);
33452 amit.gupta 2410
        Map<Integer, List<OfferPayout>> offerPayoutMap = offerPayouts.stream().collect(groupingBy(x -> (int) x.getOfferId()));
2411
        for (Entry<Integer, List<OfferPayout>> offerPayoutEntry : offerPayoutMap.entrySet()) {
32795 amit.gupta 2412
            int offerId = offerPayoutEntry.getKey();
2413
            List<OfferPayout> offerPayoutList = offerPayoutEntry.getValue();
33452 amit.gupta 2414
            Map<Integer, List<OfferPayout>> partnerOfferPayoutMap = offerPayoutList.stream().collect(groupingBy(x -> (int) x.getFofoId()));
32795 amit.gupta 2415
            for (Entry<Integer, List<OfferPayout>> partnerOfferPayoutEntry : partnerOfferPayoutMap.entrySet()) {
2416
                int fofoId = partnerOfferPayoutEntry.getKey();
2417
                List<OfferPayout> partnerPayouts = partnerOfferPayoutEntry.getValue();
2418
                float amount = 0;
2419
                for (OfferPayout offerPayout : partnerPayouts) {
2420
                    amount += offerPayout.getAmount();
2421
                    offerPayout.setStatus(SchemePayoutStatus.REJECTED);
2422
                    offerPayout.setRejectTimestamp(LocalDateTime.now());
2423
                }
2424
                walletService.rollbackAmountFromWallet(fofoId, amount, offerId,
2425
                        WalletReferenceType.ADDITIONAL_SCHEME, "Imeis returned - " + partnerPayouts.size() + "pc(s)", LocalDateTime.now());
2426
            }
2427
        }
2428
    }
2429
 
33316 amit.gupta 2430
    public void test1() throws Exception {
32690 amit.gupta 2431
        System.out.println("Hello from test");
32724 amit.gupta 2432
        //this.calculateInterestAccured();
32690 amit.gupta 2433
        //sendMailOfHtmlFormat(javaMailSender, new String[]{"amit.gupta@smartdukaan.com"}, "hello", null, "Hello");
32698 amit.gupta 2434
        //priceDropService.rejectPriceDropsOfApprovedImeis();
32511 amit.gupta 2435
        //Create return
32600 amit.gupta 2436
        //this.updatePartnerLimit();
32607 ranu 2437
        //creditNoteService.sendCnMails(YearMonth.now().minusMonths(2));
32690 amit.gupta 2438
        //orderService.createMissingScratchOffers();
33315 amit.gupta 2439
        LocalDateTime debitNoteDate = LocalDate.of(2024, Month.APRIL, 30).atStartOfDay();
32698 amit.gupta 2440
        Map<Integer, Set<String>> fofoIdImeiReturnMap = new LinkedHashMap<>();
33355 amit.gupta 2441
        /*fofoIdImeiReturnMap.put(175139690,	new HashSet<>(Arrays.asList("862054078463472","863862077158219","866202075810858","866202077654494","866335072023651","866518078002718")));
33315 amit.gupta 2442
        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")));
2443
        fofoIdImeiReturnMap.put(175139603,	new HashSet<>(Arrays.asList("350886063151961","356412387787135","357594162824701","357594162874771","860600078193972","863862077025350","863862077875796","863967075815072","866335073794995","866335074287874","869116067546048")));
2444
        fofoIdImeiReturnMap.put(175139657,	new HashSet<>(Arrays.asList("350933415734746","354324787135850","354324788766356","354990352512960","354990352580181","358142881241184","866611064207332","869116067600464")));
2445
        fofoIdImeiReturnMap.put(175139223,	new HashSet<>(Arrays.asList("350210770983048","350210771169027","350210771179844","350210771180784","863975067090596","866611060326797","868565075758196","869452074016992","869452074609515","869452074609556","869452074976674","869452074978654")));
2446
        fofoIdImeiReturnMap.put(175139557,	new HashSet<>(Arrays.asList("861977073551795","861977073552678","861977074486819","862046062571245","862046067278226","862046067734921","862046067756866","864468070394741","864468071225506","864468071668341","864468073604740","864468074854625","866993074734475")));
2447
        fofoIdImeiReturnMap.put(175139079,	new HashSet<>(Arrays.asList("862046068861921","862282079169299","865388071283496","866335072007753","866335073946256","866518073601712","866518077425993","866518078760471","868938062675394","868938062690799","868938064895552")));
2448
        fofoIdImeiReturnMap.put(175139711,	new HashSet<>(Arrays.asList("861753065266498","861888066009099","864468073703369","866993071640154","869116062800465")));
2449
        fofoIdImeiReturnMap.put(175139488,	new HashSet<>(Arrays.asList("862054076866114","862054076866650","866335071879079","866335077875998","866335077876095","866518078758939","868938062692878")));
2450
        fofoIdImeiReturnMap.put(175138934,	new HashSet<>(Arrays.asList("862054072810231","862054072823150","862054076867674","862054078659590","863862075768456","863862077158193","863975064472490","863975064473233","865388071160033","865610079408035","866335072117370","866335073899471","866335074306153","866335075664477","868938062669876","868938062677895","868938062685997")));
2451
        fofoIdImeiReturnMap.put(4149607	 ,   new HashSet<>(Arrays.asList("864468073415741","864468075548523","864468075549927","864468079499426","866657074106022","868938062686656","868938062696978","868938062699352","868938064895198","868938066363799")));
2452
        fofoIdImeiReturnMap.put(175139138,	new HashSet<>(Arrays.asList("862286066217631","864259076533691","864468073358842","864487061610014","864487061675918","866083066080028","866518078760950","866518078768979","866657075343848","868544061108518","868544061138432","869116065510848","869116065519781","869452074116891","869452074972939")));
2453
        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")));
2454
        fofoIdImeiReturnMap.put(175139731,	new HashSet<>(Arrays.asList("860600079214413","861753063502217","861753065084172","861753065084636","863975064472094","863975064473076","863975064477218","864468074456462","865883068726994","866657074641481","866657078016946","868938062699832","868938062700754")));
2455
        fofoIdImeiReturnMap.put(175138958,	new HashSet<>(Arrays.asList("863862075766393","864179064784108","866202075811732","866202076252654","866202078005571","868544060277439")));
2456
        fofoIdImeiReturnMap.put(175139612,	new HashSet<>(Arrays.asList("864468073474946","864468073477808","864468075031082","864468075280689","864468075745723","864468079481747","864468079483123","866657074538125","866657074538141","866657074573106","867467071856465","867467071875465","867467071891223","867467071913845","867467072729125","867467072760088")));
2457
        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")));
2458
        fofoIdImeiReturnMap.put(175139245,	new HashSet<>(Arrays.asList("354324787133962","354324787569397","354324787602750","863816078139719","863816078448318","866335070534139")));
2459
        fofoIdImeiReturnMap.put(175139324,	new HashSet<>(Arrays.asList("863718060410316","863862075060755","865610074109257","866518078844457","866518079735159")));
2460
        fofoIdImeiReturnMap.put(175139576,	new HashSet<>(Arrays.asList("354324789013261","861128071288044","862736064686138","863718062236859","863816074642674","863816074646691","864259078939631","867467071870367","867467072760625","868565073047048")));
2461
        fofoIdImeiReturnMap.put(175139150,	new HashSet<>(Arrays.asList("860492060436217","861977073052257","862054073026738","862054073052056","863862077158938","866993074147710","867907071407074","868938060257450","868956064835055")));
2462
        fofoIdImeiReturnMap.put(175139463,	new HashSet<>(Arrays.asList("862181066909552","863816077757719","863816078448516","864214068977273","866335070447936","866335071699212","866335071699592","866335071700291")));
2463
        fofoIdImeiReturnMap.put(175139722,	new HashSet<>(Arrays.asList("358250293364682","358250294683627","358250295102007","861858064421273","861888066009537","864214068983198","864259078491112","864259078787733","865883068445694","866335072878930","866518078371014","868492068014968","868565072254660","868565073401468","868565073465661")));
2464
        fofoIdImeiReturnMap.put(168311083,	new HashSet<>(Arrays.asList("863718064506176","864468070873488","865883068175572","866335071204435","866335072093738","866518077064313","866657077386209","866657077862282","868938061427359")));
2465
        fofoIdImeiReturnMap.put(175139691,	new HashSet<>(Arrays.asList("863718061338714","863718061339258")));
2466
        fofoIdImeiReturnMap.put(175139395,	new HashSet<>(Arrays.asList("860492060436910","861220079009850","862054077288730","863511068660374","863718060300574","863718060617936","866335072874111","869452070894897")));
2467
        fofoIdImeiReturnMap.put(175139621,	new HashSet<>(Arrays.asList("351240553452191","351240553483527","351240553502920","354990353485570","860492062979750","860492062980998","864214068585274","864214068784398","864214068795378","864214068946534","864214068946757","864214068982075","868938061418754","868938061427391","868938062623139")));
2468
        fofoIdImeiReturnMap.put(175139638,	new HashSet<>(Arrays.asList("863862077159191","866518078780438","866518079750471","868428060238049","868938061532836","868938062619517")));
2469
        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")));
2470
        fofoIdImeiReturnMap.put(175139513,	new HashSet<>(Arrays.asList("861977073670355","863718060618439","864468075204986","868024064295935","868024065473754","868024065567811","868024065763972","868956063947893")));
2471
        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")));
2472
        fofoIdImeiReturnMap.put(175139359,	new HashSet<>(Arrays.asList("358250293060942","358250293061387","863718063044252","863862077160991","866335072536793","866335072536975","866335072537130","866335072726691","866335072726733","866335073628532","866335073925250","866335073925292","866335073926233","866335075267156")));
2473
        fofoIdImeiReturnMap.put(175139397,	new HashSet<>(Arrays.asList("861977073659010","863511069721050","864468071611101","864468074432844","864468074435284")));
2474
        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")));
2475
        fofoIdImeiReturnMap.put(175139460,	new HashSet<>(Arrays.asList("860492061918494","862054079983072","862054079983171","866335070533032","866518078995119","866518079014993","868938060095017")));
2476
        fofoIdImeiReturnMap.put(175139585,	new HashSet<>(Arrays.asList("358250293614706","358250293614904","358250294602908","358250294603120","358250295002181","861977074487718","863718061173699","863816078050254","865883068445777","866335070453439","866335070526812","866335071204351","866518078640293","869116067596803")));
2477
        fofoIdImeiReturnMap.put(175139726,	new HashSet<>(Arrays.asList("861858064489411","863718063927654","864468073702221","864468073928784","864468074193149","865883068445819","866657078378742","866657078498904","867949078179850","867949078180494","868544060023197")));
2478
        fofoIdImeiReturnMap.put(175139532,	new HashSet<>(Arrays.asList("863718060615096","863718060615617","863718060727537","863816077797897","866335073405139","868565072217287","868565072264560","868956065132510")));
2479
        fofoIdImeiReturnMap.put(175139462,	new HashSet<>(Arrays.asList("865610074119819","865610074120536","866335072878658","866335072882098","866335073617030")));
2480
        fofoIdImeiReturnMap.put(175139259,	new HashSet<>(Arrays.asList("350210771180644","355300593052348","860492061918213","861858064422651","864259078402572","864259078924310","866335070769719","866335071700556","866335071742558","866657073553208","867949078178530","867949078692472","868024065518616","868024065619091","869116067492540")));
2481
        fofoIdImeiReturnMap.put(175139344,	new HashSet<>(Arrays.asList("350115571135781","354990352587723","358250293362843","358250293363148","862736064732510","865610070849617","865610070851290","866518078899998","868938062623378","868956065234613")));
2482
        fofoIdImeiReturnMap.put(175139602,	new HashSet<>(Arrays.asList("861128070090482","868565072242160","868565072243044","868565072261004","868565073051644")));
2483
        fofoIdImeiReturnMap.put(175139605,	new HashSet<>(Arrays.asList("861515075217922","861515076369466","863816074206397","863816075080072","864259078661755","864468075627368","867467071860541","868565072177903","868565073075726","868565073401625","868938060248012","868938066709652","869452074088611","869452074609234")));
2484
        fofoIdImeiReturnMap.put(175139640,	new HashSet<>(Arrays.asList("358250293363429","358250293363684","861753065277792","863511069733998","864214068943713","864259078496574","864259078518773","864487060042870","864487060050352","865883069366170","866518079782391","867949078692639","867949078692852","868273068551617","868938066464571","869452073150115")));
2485
        fofoIdImeiReturnMap.put(175139346,	new HashSet<>(Arrays.asList("356494471614953","860600076022215","861765072074616","861977070097412","864468074885181","864468076046105","865610073263139","865883065558994","866335075002538","866657079093605","867907070983216")));
2486
        fofoIdImeiReturnMap.put(175139489,	new HashSet<>(Arrays.asList("354324789015209","354324789081797","861515075189824","861515075575501","861977070268997","864468072790144","864468072983921","864468075233225","866657077951960","869452071082492","869452071982378","869452074617070")));
2487
        fofoIdImeiReturnMap.put(175139508,	new HashSet<>(Arrays.asList("861515075367024","864468072781283","864468074453386","864468075200448","864468076050669","866083062293849")));
2488
        fofoIdImeiReturnMap.put(175139716,	new HashSet<>(Arrays.asList("350832440575209","358250295571425","860600076019492","861753063494373","861753063501151","864468073696100","864468074855689","865883065542311","865883067956030","866202075825450","866202077663297","866335073632591","866657078023769")));
2489
        fofoIdImeiReturnMap.put(175139727,	new HashSet<>(Arrays.asList("355300592353325","355300593005387","861765072344258","862046060196128","864468073908604","864468073910121","864468073911269","867437074118411","868024064300099","868024065464977","868024065468218","869116065414389")));
2490
        fofoIdImeiReturnMap.put(175139521,	new HashSet<>(Arrays.asList("860600071402594","860600071416719","861888064397496","861977073658616","864468070509587","864468073866406","866335074999056","866657077949642","866657078406964","866993072229072","867437070891698")));
2491
        fofoIdImeiReturnMap.put(175139523,	new HashSet<>(Arrays.asList("354324785409950","354324788632830","354990352587939","358250295736085","358250295805187","358311601935629","863967076359575","866657074163502","867907070986318","869452071963378","869452074611750")));
2492
        fofoIdImeiReturnMap.put(175139697,	new HashSet<>(Arrays.asList("862282078030112","862282078867117","863975067709930","863975068443810","864468072828860","864468073705786","864468075276489","864468075277685","865610073830739","866335073264577","866518079802116","866657074518903","866657077949980","868565073058664","868938060985639","869116065613949")));
2493
        fofoIdImeiReturnMap.put(175139622,	new HashSet<>(Arrays.asList("358250293381926","358250293382304","358250293382601","358250294076046","358250294078109","358250294078463","358250294602064","358250294602429","358250294603062","358250294603203")));
2494
        fofoIdImeiReturnMap.put(175139699,	new HashSet<>(Arrays.asList("863718064441317","865610074942897","866202077653173","866202077653553","866335072262671","866335073632211","866335074805519")));
2495
        fofoIdImeiReturnMap.put(175139741,	new HashSet<>(Arrays.asList("861515071386101","861515074123402","861515074124186","861977073047752","861977073658574","864468075082804","864468076049869","865883065542139","865883067957111","866518070599679","866518079800672","866657078018587","866657078270162","866657079236220")));
2496
        fofoIdImeiReturnMap.put(175139114,	new HashSet<>(Arrays.asList("861888066708856","861977074487692","866335070051217","866335070517274","866993074145631")));
2497
        fofoIdImeiReturnMap.put(175139531,	new HashSet<>(Arrays.asList("863816077976194","863816079685710","866335070997336","866335074729354","866335075514698")));
2498
        fofoIdImeiReturnMap.put(175139386,	new HashSet<>(Arrays.asList("350210771192805","358250295053846","860388068563434","863862077333374","864468075193221","864562077193757","864718076084310","866202077464092","866202077742190","866518077001513","868565079682020","868956065252516")));
2499
        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")));
2500
        fofoIdImeiReturnMap.put(175139306,	new HashSet<>(Arrays.asList("863718064547394","864718076075516","864718076083478","866202077463631","866202077470057")));
2501
        fofoIdImeiReturnMap.put(175139733,	new HashSet<>(Arrays.asList("350210771180008","861515071845668","861888067164877","866335070489094","866518076378276","868565072242269")));
2502
        fofoIdImeiReturnMap.put(175138824,	new HashSet<>(Arrays.asList("862054078573478","863862074697490","863862075442375","864468074485545","866335070216315","866657078016169","866657078449402","869116065542247")));
2503
        fofoIdImeiReturnMap.put(175139511,	new HashSet<>(Arrays.asList("862054075642557","862054075643530","862054076379357","862054077978934","863816078158016","868938062108974")));
2504
        fofoIdImeiReturnMap.put(175139701,	new HashSet<>(Arrays.asList("863862078258331","866611061131790")));
2505
        fofoIdImeiReturnMap.put(175139552,	new HashSet<>(Arrays.asList("861753065084958","866202075814439","866202075825633","866202075864194","866202076138754","866202076252811","866202077646870","866202077651094","866202077653876","866202077659956","866202077660293","866202077663339","866202078006397","866202078006611","866202078008914","866657078023280")));
2506
        fofoIdImeiReturnMap.put(175139499,	new HashSet<>(Arrays.asList("351115165467359","351115166905951","355358277809813","355358277814052","356049795822532","358250290682060","863862075504950","864468073944906","864468076048721","866657079234365")));
2507
        fofoIdImeiReturnMap.put(175139630,	new HashSet<>(Arrays.asList("357349229650288","358250290499184","358250294552947","358250294590301","860946078570556","860946078571059","861977073552215","861977073657790","861977073657832","861977073658731","861977074660850","862054075627517","862054075632756","862054075642979","862054076374879","863967071220830")));
2508
        fofoIdImeiReturnMap.put(175139720,	new HashSet<>(Arrays.asList("865388072300075","866335073071691","866335073073697","866335073390398")));
2509
        fofoIdImeiReturnMap.put(175138854,	new HashSet<>(Arrays.asList("50115570082950","351688420279827","351688420575703","354324788647382","357594162666201","359333606194530","863862075760198")));
2510
        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")));
2511
        fofoIdImeiReturnMap.put(175139610,	new HashSet<>(Arrays.asList("862736063981738","863718063044617","866335072870176","866335072870598")));
2512
        fofoIdImeiReturnMap.put(175139366,	new HashSet<>(Arrays.asList("354324783144864","354324788632608","354889661849990","354990353239423","863967070558271","864718076129396","866657077789543","866657078285368","866657078508066","869116060977828","869116061054429","869116061208546")));
2513
        fofoIdImeiReturnMap.put(175139412,	new HashSet<>(Arrays.asList("351115165488595","351115165491318","351115165491359","351115165491458","351115165492332","355358278026573","355358278081610","861888063460717","861977073052018","863816078633919","865883069477035","866335074538870","866993071639594")));
2514
        fofoIdImeiReturnMap.put(175139504,	new HashSet<>(Arrays.asList("862054072660792","862054075971873","862054076312374","862054077948630","863816075363171","863862075442334","864718075894230","868938062122017","868938065268932","869452071940632","869452073034897","869452073158233","869452073158498","869452074159735")));
2515
        fofoIdImeiReturnMap.put(175139201,	new HashSet<>(Arrays.asList("863718061956671","863862075497734","863862075596915","864718076078510","864718076134834","866335070211639","866611060437032","866611061133812")));
2516
        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 2517
        fofoIdImeiReturnMap.put(175139661,	new HashSet<>(Arrays.asList("860946077691031","861977074661155","862054073218855","866335070523694","867940069973476","868938062656477")));*/
33452 amit.gupta 2518
        fofoIdImeiReturnMap.put(175139556, new HashSet<>(Arrays.asList("863718063534013", "866335072895173", "866335073390810")));
2519
        fofoIdImeiReturnMap.put(175139721, new HashSet<>(Arrays.asList("358250294549067", "865883067508138", "866993072210619")));
33355 amit.gupta 2520
        /*fofoIdImeiReturnMap.put(175139455,	new HashSet<>(Arrays.asList("358293804087913","866518078020694","866518078021650","866518078243676","866518078571936")));
33315 amit.gupta 2521
        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")));
2522
        fofoIdImeiReturnMap.put(175139559,	new HashSet<>(Arrays.asList("863718069016890","863816078879256","864468075283881","866335073245436","866335073403571","866657074268327","868024065473853","868956065899993","869452070362895","869452074030274")));
2523
        fofoIdImeiReturnMap.put(175139575,	new HashSet<>(Arrays.asList("354324786659199","860388067452035","861220078009919","863816078878134","863862075841154","865388070857498","867907071407116")));
33355 amit.gupta 2524
        fofoIdImeiReturnMap.put(175139686,	new HashSet<>(Arrays.asList("866657078019106","866657078032869")));*/
33315 amit.gupta 2525
 
33355 amit.gupta 2526
        //this.processOrdersToRebill(fofoIdImeiReturnMap, debitNoteDate);
2527
        purchaseReturnService.fixReturns(fofoIdImeiReturnMap, debitNoteDate);
32513 amit.gupta 2528
 
32698 amit.gupta 2529
    }
2530
 
2531
 
33315 amit.gupta 2532
    private void processOrdersToRebill(Map<Integer, Set<String>> fofoIdImeiReturnMap, LocalDateTime debitNoteDate) throws Exception {
32698 amit.gupta 2533
 
2534
 
2535
        for (Entry<Integer, Set<String>> fofoIdImeiReturnEntry : fofoIdImeiReturnMap.entrySet()) {
32511 amit.gupta 2536
            int fofoId = fofoIdImeiReturnEntry.getKey();
2537
            Set<String> imeis = fofoIdImeiReturnEntry.getValue();
2538
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, imeis, true);
2539
            for (InventoryItem inventoryItem : inventoryItems) {
2540
                //inventoryItem.getId();
2541
                purchaseReturnService.returnInventoryItem(fofoId, true, inventoryItem.getId(), ReturnType.GOOD);
2542
                //Approve return
2543
                PurchaseReturnItem purchaseReturnItem = purchaseReturnItemRepository.selectByInventoryItemId(inventoryItem.getId());
2544
                purchaseReturnItem.setStatus(PurchaseReturnStatus.APPROVED);
2545
                purchaseReturnItem.setApproveTimestamp(LocalDateTime.now());
2546
            }
2547
            Map<Purchase, List<InventoryItem>> purchaseInventoryItemsMap = purchaseReturnService.getPurchaseMapForApprovedReturns(fofoId);
2548
            int walletAmount = walletService.getWalletAmount(fofoId);
2549
            List<DebitNote> debitNotes = purchaseReturnService.generateDebitNotes(purchaseInventoryItemsMap);
2550
            int walletDiff = walletAmount - walletService.getWalletAmount(fofoId);
2551
            if (walletDiff > 0) {
2552
                int reference = walletService.getManualReference(WalletReferenceType.OTHERS);
32514 amit.gupta 2553
                walletService.addAmountToWallet(fofoId, reference, WalletReferenceType.ADVANCE_AMOUNT, "Sytematically added for internal PO", (float) walletDiff + 5000, LocalDateTime.now());
32511 amit.gupta 2554
            }
32698 amit.gupta 2555
            List<CartItem> cartItems = new ArrayList<>();
32511 amit.gupta 2556
            for (DebitNote debitNote : debitNotes) {
33315 amit.gupta 2557
                debitNote.setCreateTimestamp(debitNoteDate);
32511 amit.gupta 2558
                //Try to refund amount per debit note
32698 amit.gupta 2559
                cartItems.addAll(this.refundDnAmount(debitNote));
32511 amit.gupta 2560
            }
32698 amit.gupta 2561
            //If order created
33452 amit.gupta 2562
            Map<Integer, List<CartItem>> warehouseCartItemsMap = cartItems.stream().collect(groupingBy(x -> x.getWarehouseId()));
2563
            for (Entry<Integer, List<CartItem>> warehouseCartItemsEntry : warehouseCartItemsMap.entrySet()) {
32223 amit.gupta 2564
 
32698 amit.gupta 2565
                List<CartItem> warehouseCartItems = warehouseCartItemsEntry.getValue();
2566
 
2567
                List<CartItem> mergedCartItems = warehouseCartItems.stream()
2568
                        .collect(Collectors.collectingAndThen(
33452 amit.gupta 2569
                                groupingBy(x -> x.getItemId(), Collectors.collectingAndThen(
32724 amit.gupta 2570
                                        Collectors.reducing((a, b) -> {
32698 amit.gupta 2571
                                            a.setQuantity(a.getQuantity() + b.getQuantity());
2572
                                            return a;
2573
                                        }), Optional::get)),
2574
                                m -> new ArrayList<>(m.values())));
2575
 
32724 amit.gupta 2576
                double walletTotalAmount = mergedCartItems.stream().mapToDouble(x -> x.getQuantity() * x.getSellingPrice()).sum();
32698 amit.gupta 2577
 
2578
                com.spice.profitmandi.dao.entity.user.User user = userRepository.selectById(fofoId);
2579
                cartService.clearCart(user.getActiveCartId());
2580
                cartService.addItemsToCart(user.getActiveCartId(), mergedCartItems);
2581
 
2582
                UserCart userCart = new UserCart();
2583
                userCart.setCartId(user.getActiveCartId());
2584
                userCart.setUserId(user.getId());
2585
 
2586
                int transactionId = transactionService.createTransactionInternally(userCart, walletTotalAmount, warehouseCartItemsEntry.getKey());
2587
                commonPaymentService.payThroughWallet(transactionId);
2588
                transactionService.processTransaction(transactionId);
2589
            }
2590
        }
31697 amit.gupta 2591
    }
32048 tejbeer 2592
 
32384 amit.gupta 2593
    @Autowired
32511 amit.gupta 2594
    CartService cartService;
2595
    @Autowired
2596
    UserRepository userRepository;
2597
 
2598
    @Autowired
2599
    WarehouseScanRepository warehouseScanRepository;
2600
 
2601
    @Autowired
2602
    WarehouseInventoryService warehouseInventoryService;
2603
 
2604
    @Autowired
2605
    CommonPaymentService commonPaymentService;
2606
 
32533 amit.gupta 2607
    @Autowired
2608
    LineItemImeisRepository lineItemImeisRepository;
2609
 
32698 amit.gupta 2610
 
32511 amit.gupta 2611
    //Also create order
32698 amit.gupta 2612
    private List<CartItem> refundDnAmount(DebitNote debitNote) throws ProfitMandiBusinessException {
32511 amit.gupta 2613
        List<Integer> inventoryItemIds = purchaseReturnItemRepository.selectAllByDebitNoteId(debitNote.getId()).stream().map(x -> x.getInventoryItemId()).collect(Collectors.toList());
33452 amit.gupta 2614
        Map<Integer, Long> inventoryItemCountMap = inventoryItemIds.stream().collect(groupingBy(x -> x, Collectors.counting()));
32511 amit.gupta 2615
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(new ArrayList<>(inventoryItemCountMap.keySet()));
2616
        Purchase purchase = purchaseRepository.selectById(inventoryItems.get(0).getPurchaseId());
2617
        String invoice = purchase.getPurchaseReference();
2618
        List<Order> orders = orderRepository.selectByInvoiceNumber(invoice);
2619
        Set<Integer> orderIds = orders.stream().map(x -> x.getId()).collect(Collectors.toSet());
2620
        Order order = orders.get(0);
2621
        float totalAmount = 0;
2622
        int totalQty = 0;
2623
        Map<Integer, CartItem> itemIdCartItemMap = new HashMap<>();
2624
 
2625
        List<CartItem> cartItems = new ArrayList<>();
2626
        for (InventoryItem inventoryItem : inventoryItems) {
2627
            TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
2628
            long quantity = inventoryItemCountMap.get(inventoryItem.getId());
2629
            totalAmount += inventoryItem.getUnitPrice() * quantity;
2630
            totalQty += quantity;
2631
            if (!itemIdCartItemMap.containsKey(inventoryItem.getItemId())) {
2632
                CartItem cartItem = new CartItem();
2633
                cartItem.setItemId(inventoryItem.getItemId());
2634
                cartItem.setSellingPrice(tagListing.getSellingPrice());
32698 amit.gupta 2635
                cartItem.setWarehouseId(order.getWarehouseId());
32511 amit.gupta 2636
                cartItems.add(cartItem);
2637
                itemIdCartItemMap.put(inventoryItem.getItemId(), cartItem);
2638
            }
2639
            CartItem cartItem = itemIdCartItemMap.get(inventoryItem.getItemId());
2640
            cartItem.setQuantity((int) quantity + cartItem.getQuantity());
2641
        }
2642
        String rollbackDescription = String.format("Refunded against DN %s, %d pc(s)", debitNote.getDebitNoteNumber(), totalQty);
2643
        walletService.addAmountToWallet(debitNote.getFofoId(), order.getTransactionId(), WalletReferenceType.PURCHASE, rollbackDescription, totalAmount, LocalDateTime.now());
2644
        //Before creating order lets try to in the stock
2645
 
2646
        //All scans pertaining to specific Invoices
2647
        List<WarehouseScan> warehouseScans = warehouseScanRepository.selectAllByOrderIds(new ArrayList<>(orderIds));
32698 amit.gupta 2648
        Map<Integer, Integer> inventoryItemIdOrderIdMap = new HashMap<>();
2649
        try {
2650
            inventoryItemIdOrderIdMap = warehouseScans.stream().collect(Collectors.toMap(x -> x.getInventoryItemId(), x -> x.getQuantity()));
32724 amit.gupta 2651
        } catch (Exception e) {
32698 amit.gupta 2652
            LOGGER.info("Could not process for fofoId - {}, {}", debitNote.getFofoId(), warehouseScans);
2653
        }
32511 amit.gupta 2654
        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)))
2655
                .map(x -> x.getInventoryItemId()).collect(Collectors.toList());
2656
        List<WarehouseInventoryItem> warehouseInventoryItems = warehouseInventoryItemRepository.selectAllByIds(warehouseInventoryItemIds);
2657
 
2658
        Map<String, WarehouseInventoryItem> serialNumberWarehouseInventoryItemMap = warehouseInventoryItems.stream().filter(x -> StringUtils.isNotBlank(x.getSerialNumber())).collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
2659
 
2660
        for (InventoryItem inventoryItem : inventoryItems) {
2661
            if (StringUtils.isBlank(inventoryItem.getSerialNumber())) {
2662
                //As of now this should be happening as  dn are specifically for serialized devices
2663
                /*int returnQty = inventoryItemCountMap.get(inventoryItem.getId()).intValue();
2664
                List<WarehouseInventoryItem> warehouseInventoryItemList = itemIdWarehouseInventoryItemsMap.get(inventoryItem.getItemId());
2665
                warehouseInventoryService.returnNonSerializedQty(warehouseInventoryItem)*/
2666
            } else if (StringUtils.isNotBlank(inventoryItem.getSerialNumber())) {
2667
                String serialNumber = inventoryItem.getSerialNumber();
2668
                WarehouseInventoryItem warehouseInventoryItem = serialNumberWarehouseInventoryItemMap.get(serialNumber);
2669
                warehouseInventoryItem.setLastScanType(in.shop2020.warehouse.ScanType.SALE_RET);
2670
                warehouseInventoryService.addQuantity(warehouseInventoryItem.getId(), 1);
2671
                WarehouseScan warehouseScan = new WarehouseScan();
2672
                warehouseScan.setInventoryItemId(warehouseInventoryItem.getId());
2673
                warehouseScan.setQuantity(1);
2674
                warehouseScan.setOrderId(inventoryItemIdOrderIdMap.get(warehouseInventoryItem.getItemId()));
2675
                warehouseScan.setScannedAt(LocalDateTime.now());
2676
                warehouseScan.setType(in.shop2020.warehouse.ScanType.SALE_RET);
2677
                warehouseScanRepository.persist(warehouseScan);
2678
 
2679
            }
2680
        }
2681
 
2682
        //Create Order as well
32724 amit.gupta 2683
        return cartItems;
32698 amit.gupta 2684
    }
32511 amit.gupta 2685
 
32698 amit.gupta 2686
    void addToCartAndCreateOrder() {
32511 amit.gupta 2687
 
2688
    }
2689
 
2690
    @Autowired
32384 amit.gupta 2691
    WarehouseDebitNoteRepository warehouseDebitNoteRepository;
2692
    @Autowired
2693
    WarehouseDebitNoteLineRepository warehouseDebitNoteLineRepository;
2694
 
2695
    @Autowired
2696
    WarehouseInvoiceItemRepository warehouseInvoiceItemRepository;
2697
    @Autowired
2698
    WarehouseSupplierInvoiceRepository warehouseSupplierInvoiceRepository;
2699
 
2700
    @Autowired
2701
    PurchaseOrderService purchaseOrderService;
2702
 
32482 amit.gupta 2703
    @Autowired
2704
    VendorCatalogPricingLogRepository vendorCatalogPricingLogRepository;
32384 amit.gupta 2705
 
32214 jai.hind 2706
//    private void checkItelImeiActivationNew(LocalDate now, int i) {
2707
//    }
2708
 
32169 amit.gupta 2709
    @Autowired
2710
    SessionFactory sessionFactory;
2711
 
2712
    private void checkAllPayoutsDuplicate() throws Exception {
2713
        final Session session = sessionFactory.getCurrentSession();
32439 tejbeer 2714
        final NativeQuery<Object[]> nativeQuery = session.createNativeQuery("select sio.inventory_item_id, sio.scheme_id, sio.status, count(*) c\n" + "from fofo.scheme_in_out sio\n" + "         join catalog.scheme s on s.id = sio.scheme_id\n" + "where (sio.status = 'CREDITED'\n" + "    or sio.status = 'PENDING')\n" + "  and s.type != 'INVESTMENT'\n" + " and sio.create_timestamp >= '2023-01-01' " + "group by sio.inventory_item_id, sio.scheme_id, sio.status\n" + "having c > 1");
32169 amit.gupta 2715
        List<Object[]> resultList = nativeQuery.getResultList();
2716
        for (Object[] tuple : resultList) {
2717
            LOGGER.info("RESULT -- {}, {}, {}", tuple[0], tuple[1], tuple[2]);
2718
            int inventoryItemId = (Integer) tuple[0];
2719
            int schemeId = (Integer) tuple[1];
2720
            SchemePayoutStatus schemePayoutStatus = SchemePayoutStatus.valueOf((String) tuple[2]);
2721
            List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(schemeId, inventoryItemId);
2722
            List<SchemeInOut> statusSpecificSchemeInOuts = schemeInOuts.stream().filter(x -> x.getStatus().equals(schemePayoutStatus)).collect(Collectors.toList());
2723
            if (statusSpecificSchemeInOuts.size() > 0) {
2724
                InventoryItem inventoryItem = inventoryItemRepository.selectById(inventoryItemId);
2725
                Scheme scheme = schemeRepository.selectById(schemeId);
2726
                List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItemId);
2727
                if (scheme.getType().equals(SchemeType.IN)) {
2728
                    LOGGER.info("Skipping -- {}", inventoryItem.getSerialNumber());
2729
                } else {
2730
                    int fofoOrderId = scanRecords.stream().filter(x -> x.getOrderId() != 0).max(Comparator.comparing(x -> x.getOrderId())).get().getOrderId();
2731
                    WalletReferenceType walletReferenceType = SchemeType.ACTIVATION.equals(scheme.getType()) ? WalletReferenceType.ACTIVATION_SCHEME : SchemeType.SPECIAL_SUPPORT.equals(scheme.getType()) ? WalletReferenceType.SPECIAL_SUPPORT : WalletReferenceType.SCHEME_OUT;
2732
                    List<UserWalletHistory> userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrderId, walletReferenceType).stream().filter(x -> x.getAmount() == Math.round(statusSpecificSchemeInOuts.get(0).getAmount())).collect(Collectors.toList());
2733
                    LOGGER.info("UserwalletHistory Entry --> {}, Sios --> {}", userWalletHistoryList.size(), statusSpecificSchemeInOuts.size());
2734
                    if (userWalletHistoryList.size() != statusSpecificSchemeInOuts.size()) {
2735
                        //Skipping them in first run as it is the special casw of upgrade where mismatch has happend.
2736
                        LOGGER.info("problem with {}, sio status - {}, inventoryItem id {}, schemeID {} ", fofoOrderId, statusSpecificSchemeInOuts.stream().map(x -> x.getStatus()).collect(Collectors.toList()), inventoryItemId, schemeId);
2737
                        //Primarily multiple pending cases
2738
                        statusSpecificSchemeInOuts.stream().skip(1).forEach(schemeInOut -> {
2739
                            schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
2740
                            schemeInOut.setStatusDescription("Rejected as entry is duplicate");
2741
                        });
2742
                    } else {
2743
                        userWalletHistoryList.stream().skip(1).forEach(userWalletHistory -> {
2744
                            try {
2745
                                walletService.rollbackAmountFromWallet(inventoryItem.getFofoId(), userWalletHistory.getAmount(), userWalletHistory.getReference(), userWalletHistory.getReferenceType(), "Reversal as multiple entries created", userWalletHistory.getBusinessTimestamp());
2746
                            } catch (ProfitMandiBusinessException e) {
2747
                                throw new RuntimeException(e);
2748
                            }
2749
                        });
2750
 
2751
                        statusSpecificSchemeInOuts.stream().skip(1).forEach(schemeInOut -> {
2752
                            schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
2753
                            if (schemePayoutStatus.equals(SchemePayoutStatus.CREDITED)) {
2754
                                schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
2755
                                schemeInOut.setStatusDescription("Rolled back as entry is duplicate");
2756
                            } else {
2757
                                LOGGER.info("This seems higly unreachable should not come here");
2758
                                schemeInOut.setStatusDescription("Rejected as entry is duplicate");
2759
                            }
2760
                        });
2761
                    }
2762
                }
2763
            }
2764
        }
2765
    }
2766
 
32795 amit.gupta 2767
    public void test2() throws Exception {
32009 amit.gupta 2768
        System.out.println("Starting test");
32048 tejbeer 2769
        processScheme(LocalDate.of(2023, 05, 06).atStartOfDay(), LocalDate.of(2023, 05, 9).atStartOfDay(), false);
32009 amit.gupta 2770
        /*partnerTypeChangeService.getTypeOnDate(175139287, LocalDate.of(2023,02, 01));
2771
        partnerTypeChangeService.getTypeOnDate(175139287, LocalDate.of(2023,03, 01));
2772
        partnerTypeChangeService.getTypeOnDate(175139287, LocalDate.of(2023,04, 01));
2773
        FofoStore fs = fofoStoreRepository.selectByRetailerId(175139287);
2774
        this.rolloutMarginForStoreOnMonth(fs, LocalDate.of(2023, 2, 1));
2775
        this.rolloutMarginForStoreOnMonth(fs, LocalDate.of(2023, 3, 1));*/
2776
        //this.sendMailForSamsungRebilling();
2777
        /*List<PurchaseReturnItem> purchaseReturnItems = purchaseReturnItemRepository.selectPurchaseReturnByStatuses(Arrays.asList(PurchaseReturnStatus.DEBIT_NOTE_CREATED));
2778
        Map<Integer, List<PurchaseReturnItem>> inventoryItemsMap = purchaseReturnItems.stream().collect(Collectors.groupingBy(x -> x.getDebitNoteId()));
2779
        for (Map.Entry<Integer, List<PurchaseReturnItem>> debitNotePurcahseReturnMap : inventoryItemsMap.entrySet()) {
2780
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(debitNotePurcahseReturnMap.getValue().stream().map(x -> x.getInventoryItemId()).collect(Collectors.toList()));
2781
            offerService.reverseAdditionalSelloutSchemes(debitNotePurcahseReturnMap.getValue().get(0).getFofoId(), inventoryItems);
2782
        }*/
2783
        //this.sendMailForAgeingAlert();
2784
        //this.sendMailForAgeingAlert();
2785
        //System.out.println(brandRegionMappingRepository.getAvailabilityToVendorWarehouse(Arrays.asList(33353), 7720));
2786
 
2787
    }
2788
 
31697 amit.gupta 2789
    public void sendMailForSamsungRebilling() throws Exception {
2790
        List<BilledImeiModel> samsungModels = warehouseInventoryItemRepository.findByBillingDateBrand(LocalDate.now(), "Samsung");
2791
        LOGGER.info("SamsungModels {}", samsungModels);
2792
        samsungModels = samsungModels.stream().sorted(Comparator.comparing(x -> x.getPcmDate() == null ? -1 : 1)).collect(Collectors.toList());
2793
        if (samsungModels.size() > 0) {
2794
            List<String> headers = Arrays.asList("Partner Id", "Code", "Name", "City", "Brand", "Model Name", "Model Number", "Color", "Serial Number", "Remarks");
2795
            List<List<?>> rows = new ArrayList<>();
2796
            for (BilledImeiModel billedImeiModel : samsungModels) {
31886 tejbeer 2797
                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 2798
                rows.add(row);
2799
            }
2800
            ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
2801
            String[] sendToArray = new String[]{"kamini.sharma@smartdukaan.com", "praveen.sharma@smartdukaan.com"};
2802
            String fileName = "Imeis need Rebilling -" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
31886 tejbeer 2803
            Utils.sendMailWithAttachment(googleMailSender, sendToArray, new String[]{"tarun.verma@smartdukaan.com"}, "Samsung Rebilling IMEI Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 2804
        }
2805
    }
24002 amit.gupta 2806
 
31697 amit.gupta 2807
    public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
2808
        LocalDate yesterDay = LocalDate.now().minusDays(1);
2809
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
31886 tejbeer 2810
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25312 amit.gupta 2811
 
32169 amit.gupta 2812
        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 2813
        List<List<?>> rows = new ArrayList<>();
2814
        Map<Integer, List<?>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 2815
 
31697 amit.gupta 2816
        Map<Integer, FofoReportingModel> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25312 amit.gupta 2817
 
31886 tejbeer 2818
        Map<Integer, Integer> shortDaysMap = partnerDailyInvestmentRepository.selectAll(LocalDate.now().withDayOfMonth(1), LocalDate.now()).stream().collect(groupingBy(
2819
                x -> x.getFofoId(), Collectors.summingInt(x -> x.getShortPercentage() > 10 ? 1 : 0)));
24271 amit.gupta 2820
 
31697 amit.gupta 2821
        for (FofoStore fofoStore : fofoStores) {
2822
            LOGGER.info("Fofo Store {},  {}", fofoStore.getId(), fofoStore.getCode());
2823
            int fofoId = fofoStore.getId();
2824
            PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 1);
2825
            partnerDailyInvestment.setDate(yesterDay);
24177 govind 2826
 
31697 amit.gupta 2827
            try {
2828
                partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
31886 tejbeer 2829
                shortDaysMap.put(fofoId, shortDaysMap.get(fofoId) + (partnerDailyInvestment.getShortPercentage() > 10 ? 1 : 0));
31697 amit.gupta 2830
            } catch (Exception e) {
2831
                // ignore the exceptions during persist
2832
            }
25598 amit.gupta 2833
 
31697 amit.gupta 2834
            CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
2835
            if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
2836
                LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
2837
                continue;
2838
            }
2839
            FofoReportingModel reportingModel = partnerIdSalesHeaderMap.get(fofoStore.getId());
2840
            List<Serializable> row = new ArrayList<>();
31886 tejbeer 2841
            row.addAll(Arrays.asList(reportingModel.getCode(), reportingModel.getBusinessName(), reportingModel.getRegionalManager(), reportingModel.getTerritoryManager()));
31697 amit.gupta 2842
            row.addAll(
31886 tejbeer 2843
                    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 2844
            partnerRowsMap.put(fofoStore.getId(), row);
2845
            rows.add(row);
25837 amit.gupta 2846
 
31697 amit.gupta 2847
        }
25837 amit.gupta 2848
 
31697 amit.gupta 2849
        String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25837 amit.gupta 2850
 
31697 amit.gupta 2851
        if (sendTo == null) {
33452 amit.gupta 2852
            for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
31886 tejbeer 2853
                List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
31697 amit.gupta 2854
                ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
2855
                String[] sendToArray = new String[]{storeGuyEntry.getKey()};
31886 tejbeer 2856
                Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 2857
            }
31886 tejbeer 2858
            sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com", "amit.gupta@shop2020.in", "manish.gupta@smartdukaan.com", "niranjan.kala@smartdukaan.com");
31697 amit.gupta 2859
        }
25837 amit.gupta 2860
 
31697 amit.gupta 2861
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
2862
        String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
31886 tejbeer 2863
        Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
25837 amit.gupta 2864
 
31697 amit.gupta 2865
    }
25598 amit.gupta 2866
 
33256 amit.gupta 2867
    private Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() throws ProfitMandiBusinessException {
31697 amit.gupta 2868
        Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
2869
        Map<String, SaleRoles> partnerEmailRBMMap = new HashMap<>();
24271 amit.gupta 2870
 
31886 tejbeer 2871
        List<Position> positions = positionRepository.selectPositionByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_RBM));
2872
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31697 amit.gupta 2873
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
2874
        for (Position position : positions) {
2875
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
2876
            if (crList == null)
2877
                continue;
2878
            if (position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES) {
2879
                for (CustomRetailer cr : crList) {
2880
                    if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
2881
                        partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
2882
                    }
2883
                    SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
2884
                    AuthUser authUser = authUsersMap.get(position.getAuthUserId());
2885
                    if (authUser == null) {
2886
                        continue;
2887
                    }
2888
                    String name = authUser.getFirstName() + " " + authUser.getLastName();
2889
                    if (position.getEscalationType().equals(EscalationType.L1)) {
2890
                        saleRoles.getL1().add(name);
2891
                    } else if (position.getEscalationType().equals(EscalationType.L2)) {
2892
                        saleRoles.getL2().add(name);
2893
                    }
2894
                }
2895
            }
2896
            if (position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM) {
2897
                for (CustomRetailer cr : crList) {
2898
                    if (!partnerEmailRBMMap.containsKey(cr.getEmail())) {
2899
                        partnerEmailRBMMap.put(cr.getEmail(), new SaleRoles());
2900
                    }
2901
                    SaleRoles saleRoles = partnerEmailRBMMap.get(cr.getEmail());
2902
                    AuthUser authUser = authUsersMap.get(position.getAuthUserId());
2903
                    if (authUser == null) {
2904
                        continue;
2905
                    }
2906
                    String name = authUser.getFirstName() + " " + authUser.getLastName();
2907
                    if (position.getEscalationType().equals(EscalationType.L1) || position.getEscalationType().equals(EscalationType.L1)) {
2908
                        saleRoles.getL1().add(name);
2909
                    }
2910
                    /*else if (position.getEscalationType().equals(EscalationType.L2)) {
2911
                        saleRoles.getL2().add(name);
2912
                    }*/
2913
                }
2914
            }
24692 amit.gupta 2915
 
31697 amit.gupta 2916
        }
25418 amit.gupta 2917
 
31697 amit.gupta 2918
        Set<CustomRetailer> allCrList = new HashSet<>();
2919
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
2920
            allCrList.addAll(cr);
2921
        }
25609 amit.gupta 2922
 
31886 tejbeer 2923
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
25503 amit.gupta 2924
 
31697 amit.gupta 2925
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
25503 amit.gupta 2926
 
31697 amit.gupta 2927
        for (CustomRetailer cr : allCrList) {
2928
            FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
2929
            if (fofoStore == null) {
2930
                LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
2931
                continue;
2932
            }
2933
            String code = fofoStore.getCode();
2934
            // String storeName = "SmartDukaan-" +
2935
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
2936
            String businessName = cr.getBusinessName();
2937
            try {
2938
                String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
2939
                String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
2940
                String bdm = StringUtils.join(partnerEmailRBMMap.get(cr.getEmail()).getL1(), ", ");
2941
                FofoReportingModel reportingModel = new FofoReportingModel();
2942
                reportingModel.setBusinessName(businessName);
2943
                reportingModel.setCode(code);
2944
                reportingModel.setFofoId(fofoStore.getId());
2945
                reportingModel.setRegionalManager(stateManager);
2946
                reportingModel.setTerritoryManager(territoryManager);
2947
                reportingModel.setBusinessManager(bdm);
2948
                partnerIdSalesHeadersMap.put(fofoStore.getId(), reportingModel);
2949
            } catch (Exception e) {
2950
                LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
2951
            }
2952
        }
2953
        return partnerIdSalesHeadersMap;
24533 govind 2954
 
31697 amit.gupta 2955
    }
28709 amit.gupta 2956
 
31697 amit.gupta 2957
    public void sendPartnerInvestmentDetails() throws Exception {
2958
        this.sendPartnerInvestmentDetails(null);
2959
    }
28709 amit.gupta 2960
 
31697 amit.gupta 2961
    public void sendAgeingReport(String... sendTo) throws Exception {
28790 amit.gupta 2962
 
31886 tejbeer 2963
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW, "itemstockageing.xml");
2964
        InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "ItemwiseOverallPendingIndent.xml");
31697 amit.gupta 2965
        Attachment attachment = new Attachment(
2966
                "ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
2967
        Attachment attachment1 = new Attachment(
2968
                "pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
28790 amit.gupta 2969
 
31886 tejbeer 2970
        Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA", attachment);
2971
        Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null, "Itemwise Pending indent", "PFA", attachment1);
28790 amit.gupta 2972
 
31697 amit.gupta 2973
        // Reports to be sent to mapped partners
2974
        Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
28790 amit.gupta 2975
 
33452 amit.gupta 2976
        for (Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
31697 amit.gupta 2977
            Map<String, String> params = new HashMap<>();
2978
            if (storeGuyEntry.getValue().size() == 0)
2979
                continue;
2980
            params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
31886 tejbeer 2981
            InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "focostockreport.xml", params);
31697 amit.gupta 2982
            Attachment attache = new Attachment(
2983
                    "Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
2984
            System.out.println(storeGuyEntry.getValue());
31886 tejbeer 2985
            Utils.sendMailWithAttachments(googleMailSender, new String[]{storeGuyEntry.getKey()}, null, "Franchise Stock Report", "PFA", attache);
31697 amit.gupta 2986
        }
28839 tejbeer 2987
 
31697 amit.gupta 2988
    }
28839 tejbeer 2989
 
31697 amit.gupta 2990
    public void sendIndentTertiary() throws Exception {
28790 amit.gupta 2991
 
31886 tejbeer 2992
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "indentandtertiary.xml");
31697 amit.gupta 2993
        Attachment attachment = new Attachment(
2994
                "indentandtertiary-report-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr);
31886 tejbeer 2995
        Utils.sendMailWithAttachments(googleMailSender, INDENT_TERTIARY_MAIL_LIST, null, "Indent Tertiary Report", "PFA", attachment);
28790 amit.gupta 2996
 
31697 amit.gupta 2997
    }
28790 amit.gupta 2998
 
31697 amit.gupta 2999
    public void sendAttendanceMorningAlert() throws Exception {
3000
        LocalDateTime moriningTime = LocalDate.now().atTime(10, 31);
3001
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
31886 tejbeer 3002
        Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28775 amit.gupta 3003
 
31697 amit.gupta 3004
        List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
3005
        Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28790 amit.gupta 3006
 
31886 tejbeer 3007
        List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now());
28784 amit.gupta 3008
 
31886 tejbeer 3009
        Map<Integer, Optional<EmployeeAttendance>> employeeMorningAttendance = employeeAttendances.stream().collect(groupingBy(EmployeeAttendance::getUserId, Collectors.minBy(Comparator.comparing(EmployeeAttendance::getCreateTimestamp))));
31697 amit.gupta 3010
        for (AuthUser authUser : authUsers) {
3011
            User user = userMap.get(authUser.getEmailId());
3012
            Optional<EmployeeAttendance> employeeAttendanceOptional = employeeMorningAttendance.get(user.getId());
3013
            LOGGER.info("AuthUser - {}, employeeAttendanceOptional {}", authUser.getName(), employeeAttendanceOptional);
3014
            if (employeeAttendanceOptional != null) {
3015
                LOGGER.info("employeeAttendanceOptional.orElse {}", employeeAttendanceOptional.orElse(null));
3016
                if (employeeAttendanceOptional.orElse(null) != null) {
31886 tejbeer 3017
                    LOGGER.info("employeeAttendanceOptional.get().getCreateTimestamp() {}", employeeAttendanceOptional.get().getCreateTimestamp());
31697 amit.gupta 3018
                }
3019
            }
31886 tejbeer 3020
            if (employeeAttendanceOptional == null || employeeAttendanceOptional.orElse(null) == null || employeeAttendanceOptional.get().getCreateTimestamp().isAfter(moriningTime)) {
31697 amit.gupta 3021
                LOGGER.info("Will Send Email to {}", authUser.getFullName());
3022
                String body = String.format(
31886 tejbeer 3023
                        "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 3024
 
31886 tejbeer 3025
                Utils.sendMailWithAttachments(googleMailSender, new String[]{authUser.getEmailId()}, new String[]{"kangan.monga@smartdukaan.com"}, "Attendance Alert", body);
28790 amit.gupta 3026
 
31697 amit.gupta 3027
            }
3028
        }
28790 amit.gupta 3029
 
31697 amit.gupta 3030
    }
28790 amit.gupta 3031
 
31697 amit.gupta 3032
    public void sendAttendanceEveningAlert() throws Exception {
3033
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
31886 tejbeer 3034
        Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28709 amit.gupta 3035
 
31697 amit.gupta 3036
        List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
3037
        Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28709 amit.gupta 3038
 
31886 tejbeer 3039
        Map<Integer, List<EmployeeAttendance>> employeeAttendancesMap = employeeAttendanceRepository.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now()).stream().collect(groupingBy(x -> x.getUserId()));
28709 amit.gupta 3040
 
31697 amit.gupta 3041
        for (AuthUser authUser : authUsers) {
3042
            User user = userMap.get(authUser.getEmailId());
3043
            String body = null;
3044
            List<EmployeeAttendance> employeeAttendances = employeeAttendancesMap.get(user.getId());
3045
            if (employeeAttendances == null) {
3046
                body = String.format(
31886 tejbeer 3047
                        "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 3048
            } else {
31886 tejbeer 3049
                List<LocalDateTime> punchTimes = employeeAttendances.stream().sorted(Comparator.comparing(EmployeeAttendance::getCreateTimestamp)).map(x -> x.getCreateTimestamp()).collect(Collectors.toList());
31697 amit.gupta 3050
                if (punchTimes.size() == 1) {
3051
                    // body = String.format("Dear %s,\n Pls note that you haven't punched out yet.
3052
                    // You have been marked absent for half the day. You may contact your manager
3053
                    // and get it regularise.\n\nRegards\nHR Team", authUser.getFullName());
3054
                } else {
3055
                    LocalDateTime firstPunch = punchTimes.get(0);
3056
                    LocalDateTime lastPunch = punchTimes.get(punchTimes.size() - 1);
3057
                    Duration duration = Duration.between(firstPunch, lastPunch);
3058
                    boolean hoursCompleted = lastPunch.isAfter(firstPunch.plusHours(8).plusMinutes(30));
3059
                    if (!hoursCompleted) {
3060
                        body = String.format(
31886 tejbeer 3061
                                "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 3062
                    }
3063
                }
28709 amit.gupta 3064
 
31697 amit.gupta 3065
            }
3066
            if (body != null) {
31886 tejbeer 3067
                Utils.sendMailWithAttachments(googleMailSender, new String[]{authUser.getEmailId()}, new String[]{"kangan.monga@smartdukaan.com"}, "Attendance Alert", body);
31697 amit.gupta 3068
            }
3069
        }
28709 amit.gupta 3070
 
31697 amit.gupta 3071
        this.sendMailToHR();
28709 amit.gupta 3072
 
31697 amit.gupta 3073
    }
28709 amit.gupta 3074
 
31697 amit.gupta 3075
    private void sendMailToHR() throws Exception {
3076
        Map<String, String> map = new HashMap<>();
3077
        String reporticoDate = FormattingUtils.formatReporitcoDate(LocalDateTime.now());
3078
        map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
3079
        map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
31886 tejbeer 3080
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "employeeattendance.xml");
3081
        Attachment attachment = new Attachment("attendance-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr);
3082
        Utils.sendMailWithAttachments(googleMailSender, EMPLOYEE_ATTENDANCE_MAIL_LIST, null, "Attendance - " + FormattingUtils.formatDate(LocalDateTime.now()), "PFA Attendance", attachment);
31697 amit.gupta 3083
    }
28709 amit.gupta 3084
 
31697 amit.gupta 3085
    public void checkPartnerActiveStore() throws Exception {
24697 amit.gupta 3086
 
31697 amit.gupta 3087
        List<FofoStore> fofoStores = fofoStoreRepository.selectByStatus(true);
23929 amit.gupta 3088
 
31697 amit.gupta 3089
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
3090
        if (!fofoStores.isEmpty()) {
3091
            for (FofoStore fofoStore : fofoStores) {
24551 amit.gupta 3092
 
31697 amit.gupta 3093
                if (currentDate.isBefore(fofoStore.getActiveTimeStamp())) {
24542 amit.gupta 3094
 
31697 amit.gupta 3095
                    fofoStore.setActive(true);
3096
                    fofoStoreRepository.persist(fofoStore);
3097
                    LOGGER.info("inserted into InActiveFofoStore successfully");
29160 amit.gupta 3098
 
31697 amit.gupta 3099
                } else {
3100
                    fofoStore.setActive(false);
3101
                    fofoStore.setActiveTimeStamp(null);
3102
                    fofoStoreRepository.persist(fofoStore);
3103
                    LOGGER.info("inserted into InActiveFofoStore successfully");
3104
                }
24542 amit.gupta 3105
 
31697 amit.gupta 3106
            }
3107
        }
24542 amit.gupta 3108
 
31697 amit.gupta 3109
    }
24548 amit.gupta 3110
 
31697 amit.gupta 3111
    public void sendAgeingReport() throws Exception {
31886 tejbeer 3112
        sendAgeingReport("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "niranjan.kala@smartdukaan.com", "manish.gupta@smartdukaan.com", "kuldeep.kumar@smartdukaan.com");
31697 amit.gupta 3113
    }
24542 amit.gupta 3114
 
31697 amit.gupta 3115
    public void moveImeisToPriceDropImeis() throws Exception {
3116
        List<PriceDrop> priceDrops = priceDropRepository.selectAll();
3117
        for (PriceDrop priceDrop : priceDrops) {
3118
            priceDropService.priceDropStatus(priceDrop.getId());
3119
        }
3120
    }
29160 amit.gupta 3121
 
31697 amit.gupta 3122
    public void walletmismatch() throws Exception {
3123
        LocalDate curDate = LocalDate.now();
3124
        List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
3125
        System.out.println(pdis.size());
3126
        for (PartnerDailyInvestment pdi : pdis) {
3127
            int fofoId = pdi.getFofoId();
31886 tejbeer 3128
            for (PartnerDailyInvestment investment : Lists.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
3129
                float statementAmount = walletService.getOpeningTill(fofoId, investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
31697 amit.gupta 3130
                CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
31886 tejbeer 3131
                LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(), investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
29160 amit.gupta 3132
 
31697 amit.gupta 3133
            }
3134
        }
29160 amit.gupta 3135
 
31697 amit.gupta 3136
    }
29160 amit.gupta 3137
 
31697 amit.gupta 3138
    @Autowired
3139
    StateRepository stateRepository;
29160 amit.gupta 3140
 
31697 amit.gupta 3141
    public void gst() throws Exception {
31886 tejbeer 3142
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2021, 8, 16).atStartOfDay(), LocalDateTime.now());
31697 amit.gupta 3143
        for (FofoOrder fofoOrder : fofoOrders) {
31886 tejbeer 3144
            int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24548 amit.gupta 3145
 
31697 amit.gupta 3146
            Address retailerAddress = addressRepository.selectById(retailerAddressId);
3147
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
3148
            Integer stateId = null;
3149
            if (customerAddress.getState().equals(retailerAddress.getState())) {
3150
                try {
3151
                    stateId = stateRepository.selectByName(customerAddress.getState()).getId();
3152
                } catch (Exception e) {
3153
                    LOGGER.error("Cannot found state named {}", customerAddress.getState());
3154
                    continue;
3155
                }
3156
            }
3157
            Map<Integer, GstRate> itemIdStateTaxRateMap = null;
24542 amit.gupta 3158
 
31697 amit.gupta 3159
            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3160
            List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
3161
            if (stateId != null) {
3162
                itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
3163
            } else {
32145 tejbeer 3164
                itemIdStateTaxRateMap = stateGstRateRepository.getIgstTaxRate(itemIds);
31697 amit.gupta 3165
            }
24580 amit.gupta 3166
 
31697 amit.gupta 3167
            for (FofoOrderItem foi : fofoOrderItems) {
3168
                float sgstRate = foi.getSgstRate();
3169
                float cgstRate = foi.getCgstRate();
3170
                float igstRate = foi.getIgstRate();
32145 tejbeer 3171
                foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
3172
                foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
3173
                foi.setIgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
24587 amit.gupta 3174
 
32145 tejbeer 3175
                LOGGER.info("Invoice {}, Date {}", fofoOrder.getInvoiceNumber(), fofoOrder.getCreateTimestamp());
3176
                LOGGER.info("customerAddress.getState() {}, retailerAddress.getState() {}", customerAddress.getState(), retailerAddress.getState());
3177
                LOGGER.info("Rates getIgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
3178
                LOGGER.info("Rates getCgstRate() {}, getSgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate(), itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
24587 amit.gupta 3179
 
3180
 
31697 amit.gupta 3181
            }
3182
        }
26092 amit.gupta 3183
 
31697 amit.gupta 3184
    }
24590 amit.gupta 3185
 
33256 amit.gupta 3186
    public void schemewalletmismatch() throws ProfitMandiBusinessException {
31697 amit.gupta 3187
        LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
3188
        while (dateToReconcile.isBefore(LocalDate.now())) {
3189
            reconcileSchemes(dateToReconcile);
3190
            // reconcileOrders(dateTime);
3191
            // reconcileRecharges(dateTime);
3192
            dateToReconcile = dateToReconcile.plusDays(1);
3193
        }
3194
    }
24587 amit.gupta 3195
 
33256 amit.gupta 3196
    private void reconcileSchemes(LocalDate date) throws ProfitMandiBusinessException {
31697 amit.gupta 3197
        LocalDateTime startDate = date.atStartOfDay();
3198
        LocalDateTime endDate = startDate.plusDays(1);
3199
        List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
3200
        List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
3201
        double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
3202
        double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
3203
        double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
31886 tejbeer 3204
        List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT);
3205
        List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate, walletReferenceTypes);
31697 amit.gupta 3206
        double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
3207
        if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
3208
            LOGGER.info("Scheme Amount mismatched for Date {}", date);
24590 amit.gupta 3209
 
31724 amit.gupta 3210
            Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
24635 amit.gupta 3211
 
31886 tejbeer 3212
            Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet()).stream().collect(groupingBy(x -> x.getFofoId(), Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
24635 amit.gupta 3213
 
31724 amit.gupta 3214
            Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
24635 amit.gupta 3215
 
31886 tejbeer 3216
            Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream().collect(groupingBy(x -> x.getFofoId(), Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
24635 amit.gupta 3217
 
31697 amit.gupta 3218
            Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
24635 amit.gupta 3219
 
33452 amit.gupta 3220
            for (Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
31697 amit.gupta 3221
                if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
3222
                    finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
3223
                } else {
31886 tejbeer 3224
                    finalUserSchemeAmountMap.put(schemeAmount.getKey(), finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
31697 amit.gupta 3225
                }
3226
            }
31886 tejbeer 3227
            Map<Integer, Integer> userWalletMap = userWalletRepository.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24635 amit.gupta 3228
 
31724 amit.gupta 3229
            Map<Integer, Double> walletAmountMap = history.stream().collect(groupingBy(
31697 amit.gupta 3230
                    UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
33452 amit.gupta 3231
            for (Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
31697 amit.gupta 3232
                double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
3233
                if (diff > 5) {
3234
                    LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
3235
                }
3236
            }
3237
        }
24635 amit.gupta 3238
 
31697 amit.gupta 3239
    }
24635 amit.gupta 3240
 
31697 amit.gupta 3241
    public void dryRunSchemeReco() throws Exception {
31886 tejbeer 3242
        Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24635 amit.gupta 3243
 
31697 amit.gupta 3244
        List<UserWalletHistory> userWalletHistory = new ArrayList<>();
3245
        List<SchemeInOut> rolledbackSios = new ArrayList<>();
31886 tejbeer 3246
        Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream().collect(Collectors.toMap(Scheme::getId, Scheme::getType));
31697 amit.gupta 3247
        Set<String> serialNumbersConsidered = new HashSet<>();
24631 amit.gupta 3248
 
31697 amit.gupta 3249
        LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
3250
        LocalDateTime endDate = LocalDate.now().atStartOfDay();
3251
        List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
24598 amit.gupta 3252
 
31697 amit.gupta 3253
        Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
33256 amit.gupta 3254
        for (Purchase purchase : purchases) {
31697 amit.gupta 3255
            float amountToRollback = 0;
31886 tejbeer 3256
            String description = "Adjustment of Duplicate Scheme for Purchase Invoice " + purchase.getPurchaseReference();
3257
            Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId()).stream().filter(ii -> ii.getSerialNumber() != null).collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
31697 amit.gupta 3258
            if (inventorySerialNumberMap.size() > 0) {
33256 amit.gupta 3259
                for (Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
31697 amit.gupta 3260
                    String serialNumber = inventorySerialNumberEntry.getValue();
3261
                    int inventoryItemId = inventorySerialNumberEntry.getKey();
3262
                    if (serialNumbersConsidered.contains(serialNumber)) {
3263
                        // This will rollback scheme for differenct orders for same serial
31886 tejbeer 3264
                        List<SchemeInOut> sios = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream().filter(x -> x.getRolledBackTimestamp() == null && schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN)).collect(Collectors.toList());
31697 amit.gupta 3265
                        Collections.reverse(sios);
3266
                        for (SchemeInOut sio : sios) {
3267
                            sio.setRolledBackTimestamp(LocalDateTime.now());
3268
                            amountToRollback += sio.getAmount();
3269
                            // sio.setSchemeType(SchemeType.OUT);
3270
                            sio.setSerialNumber(serialNumber);
3271
                            rolledbackSios.add(sio);
3272
                        }
3273
                        description = description.concat(" " + serialNumber + " ");
3274
                    } else {
3275
                        serialNumbersConsidered.add(serialNumber);
3276
                        List<Integer> schemesConsidered = new ArrayList<>();
31886 tejbeer 3277
                        List<SchemeInOut> sios = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream().filter(x -> x.getRolledBackTimestamp() == null && schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN)).collect(Collectors.toList());
31697 amit.gupta 3278
                        Collections.reverse(sios);
3279
                        for (SchemeInOut sio : sios) {
3280
                            if (!schemesConsidered.contains(sio.getSchemeId())) {
3281
                                schemesConsidered.add(sio.getSchemeId());
3282
                                continue;
3283
                            }
3284
                            sio.setRolledBackTimestamp(LocalDateTime.now());
3285
                            amountToRollback += sio.getAmount();
3286
                            // sio.setSchemeType(SchemeType.OUT);
3287
                            sio.setSerialNumber(serialNumber);
3288
                            sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
3289
                            sio.setReference(purchase.getId());
3290
                            rolledbackSios.add(sio);
3291
                        }
3292
                    }
24592 amit.gupta 3293
 
31697 amit.gupta 3294
                }
3295
            }
3296
            if (amountToRollback > 0) {
3297
                // Address address =
3298
                // addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
3299
                UserWalletHistory uwh = new UserWalletHistory();
3300
                uwh.setAmount(Math.round(amountToRollback));
3301
                uwh.setDescription(description);
3302
                uwh.setTimestamp(LocalDateTime.now());
3303
                uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
3304
                uwh.setReference(purchase.getId());
3305
                uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
3306
                uwh.setFofoId(purchase.getFofoId());
3307
                uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
3308
                userWalletHistory.add(uwh);
3309
            }
33256 amit.gupta 3310
        }
31697 amit.gupta 3311
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
31886 tejbeer 3312
                Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description", "Timestamp"), userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(), x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp())).collect(Collectors.toList()));
24592 amit.gupta 3313
 
31697 amit.gupta 3314
        ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
31886 tejbeer 3315
                Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount", "Created", "Rolledback"), rolledbackSios.stream().map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(), x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp())).collect(Collectors.toList()));
24631 amit.gupta 3316
 
31886 tejbeer 3317
        Utils.sendMailWithAttachments(googleMailSender, new String[]{"amit.gupta@shop2020.in"}, null, "Partner Excess Amount Scheme In", "PFA", new Attachment[]{new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())), new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray()))});
24615 amit.gupta 3318
 
31697 amit.gupta 3319
        throw new Exception();
24615 amit.gupta 3320
 
31697 amit.gupta 3321
    }
24615 amit.gupta 3322
 
31697 amit.gupta 3323
    public void dryRunOutSchemeReco() throws Exception {
3324
        List<UserWalletHistory> userWalletHistory = new ArrayList<>();
3325
        List<SchemeInOut> rolledbackSios = new ArrayList<>();
31886 tejbeer 3326
        Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
3327
        Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream().collect(Collectors.toMap(Scheme::getId, Scheme::getType));
31697 amit.gupta 3328
        LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
3329
        LocalDateTime endDate = LocalDate.now().atStartOfDay();
3330
        List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
3331
        // Collections.reverse(allOrders);
3332
        // List<FofoOrder> allOrders =
3333
        // List<FofoOrder> allOrders =
3334
        // Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
3335
        Set<String> serialNumbersConsidered = new HashSet<>();
33256 amit.gupta 3336
        for (FofoOrder fofoOrder : allOrders) {
31697 amit.gupta 3337
            String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
3338
            Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
3339
            float amountToRollback = 0;
3340
            List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3341
            orderItems.forEach(x -> {
31886 tejbeer 3342
                inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null).collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
31697 amit.gupta 3343
            });
3344
            if (inventorySerialNumberMap.size() > 0) {
33256 amit.gupta 3345
                for (Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
31697 amit.gupta 3346
                    String serialNumber = inventorySerialNumberEntry.getValue();
3347
                    int inventoryItemId = inventorySerialNumberEntry.getKey();
3348
                    if (serialNumbersConsidered.contains(serialNumber)) {
3349
                        // This will rollback scheme for differenct orders for same serial
33256 amit.gupta 3350
                        List<SchemeInOut> sios = new ArrayList<>();
3351
                        for (SchemeInOut schemeInOut : schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId)))) {
3352
                            if (schemeInOut.getRolledBackTimestamp() == null && schemeTypeMap.get(schemeInOut.getSchemeId()).equals(SchemeType.OUT)) {
3353
                                sios.add(schemeInOut);
3354
                            }
3355
                        }
31697 amit.gupta 3356
                        Collections.reverse(sios);
3357
                        for (SchemeInOut sio : sios) {
3358
                            sio.setRolledBackTimestamp(LocalDateTime.now());
3359
                            amountToRollback += sio.getAmount();
3360
                            // sio.setSchemeType(SchemeType.OUT);
3361
                            sio.setSerialNumber(serialNumber);
3362
                            sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
3363
                            sio.setReference(fofoOrder.getId());
3364
                            rolledbackSios.add(sio);
3365
                        }
3366
                        description = description.concat(" " + serialNumber + " ");
3367
                    } else {
3368
                        serialNumbersConsidered.add(serialNumber);
3369
                        List<Integer> schemesConsidered = new ArrayList<>();
31886 tejbeer 3370
                        List<SchemeInOut> sios = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream().filter(x -> x.getRolledBackTimestamp() == null && schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT)).collect(Collectors.toList());
31697 amit.gupta 3371
                        Collections.reverse(sios);
3372
                        for (SchemeInOut sio : sios) {
3373
                            if (!schemesConsidered.contains(sio.getSchemeId())) {
3374
                                schemesConsidered.add(sio.getSchemeId());
3375
                                continue;
3376
                            }
3377
                            sio.setRolledBackTimestamp(LocalDateTime.now());
3378
                            amountToRollback += sio.getAmount();
3379
                            // sio.setSchemeType(SchemeType.OUT);
3380
                            sio.setReference(fofoOrder.getId());
3381
                            sio.setSerialNumber(serialNumber);
3382
                            sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
3383
                            rolledbackSios.add(sio);
3384
                        }
3385
                    }
24615 amit.gupta 3386
 
31697 amit.gupta 3387
                }
3388
            }
3389
            if (amountToRollback > 0) {
3390
                UserWalletHistory uwh = new UserWalletHistory();
3391
                uwh.setAmount(Math.round(amountToRollback));
3392
                uwh.setDescription(description);
3393
                uwh.setTimestamp(LocalDateTime.now());
3394
                uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
3395
                uwh.setReference(fofoOrder.getId());
3396
                uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
3397
                uwh.setFofoId(fofoOrder.getFofoId());
3398
                uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
3399
                userWalletHistory.add(uwh);
3400
            }
33256 amit.gupta 3401
        }
24615 amit.gupta 3402
 
31697 amit.gupta 3403
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
31886 tejbeer 3404
                Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description", "Timestamp"), userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(), x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp())).collect(Collectors.toList()));
24615 amit.gupta 3405
 
31697 amit.gupta 3406
        ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
31886 tejbeer 3407
                Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created", "Rolledback"), rolledbackSios.stream().map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(), x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp())).collect(Collectors.toList()));
24631 amit.gupta 3408
 
31886 tejbeer 3409
        Utils.sendMailWithAttachments(googleMailSender, new String[]{"amit.gupta@shop2020.in"}, null, "Partner Excess Amount Scheme Out", "PFA", new Attachment[]{new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())), new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray()))});
24615 amit.gupta 3410
 
31697 amit.gupta 3411
        throw new Exception();
3412
    }
24615 amit.gupta 3413
 
31697 amit.gupta 3414
    public void dryRunSchemeOutReco1() throws Exception {
3415
        List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
3416
        List<UserWalletHistory> userWalletHistory = new ArrayList<>();
3417
        List<SchemeInOut> rolledbackSios = new ArrayList<>();
31886 tejbeer 3418
        Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
3419
        Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream().collect(Collectors.toMap(Scheme::getId, Scheme::getType));
33256 amit.gupta 3420
        for (Integer reference : references) {
31697 amit.gupta 3421
            FofoOrder fofoOrder = null;
3422
            try {
3423
                fofoOrder = fofoOrderRepository.selectByOrderId(reference);
3424
            } catch (Exception e) {
25927 amit.gupta 3425
 
31697 amit.gupta 3426
            }
3427
            String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
3428
            Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
3429
            float amountToRollback = 0;
3430
            List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3431
            orderItems.forEach(x -> {
31886 tejbeer 3432
                inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null).collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
31697 amit.gupta 3433
            });
3434
            if (inventorySerialNumberMap.size() > 0) {
31886 tejbeer 3435
                List<SchemeInOut> sios = schemeInOutRepository.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream().filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT)).collect(Collectors.toList());
31697 amit.gupta 3436
                LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
3437
                UserWalletHistory uwh = new UserWalletHistory();
31886 tejbeer 3438
                Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream().collect(groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
33256 amit.gupta 3439
                for (Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
31697 amit.gupta 3440
                    List<SchemeInOut> outList = inventorySioEntry.getValue();
3441
                    if (outList.size() > 1) {
24683 amit.gupta 3442
 
31697 amit.gupta 3443
                    }
3444
                }
3445
                uwh.setAmount(Math.round(amountToRollback));
3446
                uwh.setDescription(description);
3447
                uwh.setTimestamp(LocalDateTime.now());
3448
                uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
3449
                uwh.setReference(fofoOrder.getId());
3450
                uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
3451
                uwh.setFofoId(fofoOrder.getFofoId());
3452
                uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
3453
                userWalletHistory.add(uwh);
3454
            }
33256 amit.gupta 3455
        }
26945 amit.gupta 3456
 
31697 amit.gupta 3457
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
31886 tejbeer 3458
                Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"), userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(), x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp())).collect(Collectors.toList()));
26945 amit.gupta 3459
 
31697 amit.gupta 3460
        ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
31886 tejbeer 3461
                Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created", "Rolledback"), rolledbackSios.stream().map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(), x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp())).collect(Collectors.toList()));
26941 amit.gupta 3462
 
31886 tejbeer 3463
        Utils.sendMailWithAttachments(googleMailSender, new String[]{"amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com"}, null, "Partner Excess Amount", "PFA", new Attachment[]{new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())), new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray()))});
26945 amit.gupta 3464
 
31697 amit.gupta 3465
        throw new Exception();
25880 amit.gupta 3466
 
31697 amit.gupta 3467
    }
30982 tejbeer 3468
 
31697 amit.gupta 3469
    public void sendDailySalesNotificationToPartner(Integer fofoIdInt) throws Exception {
30982 tejbeer 3470
 
31697 amit.gupta 3471
        LocalDateTime now = LocalDateTime.now();
3472
        LocalDateTime from = now.with(LocalTime.MIN);
3473
        String timeString = "Today %s";
3474
        // Send yesterday's report
3475
        /*
3476
         * if (now.getHour() < 13) { timeString = "Yesterday %s"; from =
3477
         * now.minusDays(1).; now = from.with(LocalTime.MAX);
3478
         *
3479
         * }
3480
         */
30982 tejbeer 3481
 
31697 amit.gupta 3482
        List<Integer> fofoIds = null;
31886 tejbeer 3483
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getId(), x -> x));
30982 tejbeer 3484
 
24653 govind 3485
 
31697 amit.gupta 3486
        if (fofoIdInt == null) {
3487
            fofoIds = new ArrayList<>(fofoStoreMap.keySet());
3488
        } else {
3489
            fofoIds = Arrays.asList(fofoIdInt);
3490
        }
3491
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
28368 tejbeer 3492
 
31886 tejbeer 3493
        Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now, null);
31697 amit.gupta 3494
        Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
28368 tejbeer 3495
 
31886 tejbeer 3496
        Map<Integer, Double> spPartnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0, true);
28377 tejbeer 3497
 
31886 tejbeer 3498
        Map<Integer, Double> spPartner3DaysOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from.minusDays(3), now, 0, true);
31697 amit.gupta 3499
        Map<Integer, Long> spPartnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
28368 tejbeer 3500
 
31886 tejbeer 3501
        Map<Integer, Double> partnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0, false);
31697 amit.gupta 3502
        Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, false);
28377 tejbeer 3503
 
31697 amit.gupta 3504
        //4 days + current day running
3505
        Map<Integer, Double> partnerBilledValueMap = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(from.minusDays(4), now);
28377 tejbeer 3506
 
31697 amit.gupta 3507
        Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
3508
        for (int fofoId : fofoIds) {
3509
            SaleTargetReportModel model = new SaleTargetReportModel();
3510
            model.setInsuranceSale(
3511
                    partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
3512
            model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
3513
            model.setSecondary(partnerBilledValueMap.containsKey(fofoId) ? partnerBilledValueMap.get(fofoId) : 0);
3514
            model.setSmartphoneSale(spPartnerOrderValMap.containsKey(fofoId) ? spPartnerOrderValMap.get(fofoId) : 0);
3515
            model.setSmartphoneQty(spPartnerOrderQtyMap.containsKey(fofoId) ? spPartnerOrderQtyMap.get(fofoId) : 0);
3516
            model.setTotalSale(partnerOrderValMap.containsKey(fofoId) ? partnerOrderValMap.get(fofoId) : 0);
3517
            model.setTotalQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
3518
            model.setPast3daysSale(
3519
                    spPartner3DaysOrderValMap.containsKey(fofoId) ? spPartner3DaysOrderValMap.get(fofoId) : 0);
3520
            model.setFofoId(fofoId);
3521
            model.setCode(fofoStoreMap.get(fofoId).getCode());
31724 amit.gupta 3522
            model.setActivationType(fofoStoreMap.get(fofoId).getActivationType());
31697 amit.gupta 3523
            saleTargetReportModelMap.put(fofoId, model);
3524
        }
28377 tejbeer 3525
 
31697 amit.gupta 3526
        Map<Integer, FofoReportingModel> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
3527
        for (Integer fofoId : fofoIds) {
3528
            SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
28368 tejbeer 3529
 
31697 amit.gupta 3530
            // com.spice.profitmandi.dao.entity.user.User user =
3531
            // userUserRepository.selectById(fofoId);
28377 tejbeer 3532
 
31697 amit.gupta 3533
            // Address address = addressRepository.selectById(user.getAddressId());
28377 tejbeer 3534
 
31697 amit.gupta 3535
            String title = "Sale Update";
31886 tejbeer 3536
            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 3537
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
3538
            sendNotificationModel.setCampaignName("Sales update alert");
3539
            sendNotificationModel.setTitle(title);
3540
            sendNotificationModel.setMessage(messageTemplate);
3541
            sendNotificationModel.setType("url");
3542
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
3543
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
3544
            sendNotificationModel.setMessageType(MessageType.notification);
3545
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
3546
            sendNotificationModel.setUserIds(Arrays.asList(userId));
3547
            notificationService.sendNotification(sendNotificationModel);
3548
            String whatsappMessageTemplate = String.format(
31886 tejbeer 3549
                    "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 3550
            // notificationService.sendWhatsappMessage(whatsappMessageTemplate, title,
3551
            // address.getPhoneNumber());
28377 tejbeer 3552
 
31697 amit.gupta 3553
        }
3554
        // String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap,
3555
        // saleTargetReportModelMap);
3556
        this.getStateWiseSales(saleTargetReportModelMap, partnerSalesHeadersMap);
3557
    }
28377 tejbeer 3558
 
31697 amit.gupta 3559
    public void checkRazorPayPaymentStatus() throws Exception {
31886 tejbeer 3560
        List<PendingOrder> pendingOrder = pendingOrderRepository.selectAllByStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PENDING);
28377 tejbeer 3561
 
31697 amit.gupta 3562
        for (PendingOrder po : pendingOrder) {
3563
            RazorPay razorPay = razorPayRepository.selectByOrdeId(po.getId());
3564
            List<PendingOrderItem> poItems = pendingOrderItemRepository.selectByOrderId(po.getId());
28369 tejbeer 3565
 
31697 amit.gupta 3566
            LOGGER.info("razorPay" + razorPay);
3567
            if (razorPay != null) {
3568
                List<Payment> payments = razorPaymentService.fetchOrderForPayment(razorPay.getRazorOrderId());
28368 tejbeer 3569
 
31697 amit.gupta 3570
                if (!payments.isEmpty()) {
3571
                    List<String> statusList = new ArrayList<>();
3572
                    for (Payment payment : payments) {
25880 amit.gupta 3573
 
31697 amit.gupta 3574
                        JSONObject jsonObj = new JSONObject(payment.toString());
25880 amit.gupta 3575
 
31697 amit.gupta 3576
                        String status = jsonObj.getString("status");
25880 amit.gupta 3577
 
31697 amit.gupta 3578
                        statusList.add(status);
25865 amit.gupta 3579
 
31697 amit.gupta 3580
                    }
3581
                    LOGGER.info("statusList" + statusList);
26941 amit.gupta 3582
 
31697 amit.gupta 3583
                    if (statusList.contains("authorized") || statusList.contains("captured")) {
3584
                        po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
3585
                        po.setPaidAmount(po.getTotalAmount());
3586
                        for (PendingOrderItem poi : poItems) {
3587
                            poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
3588
                        }
3589
                        Map<String, Object> emailModel = pendingOrderService.sendCreateOrderMail(po);
26941 amit.gupta 3590
 
31697 amit.gupta 3591
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(po.getFofoId());
3592
                        Customer customer = customerRepository.selectById(po.getCustomerId());
3593
                        String[] customerEmail = null;
3594
                        if (customer.getEmailId() != null) {
3595
                            customerEmail = new String[]{customer.getEmailId()};
3596
                        }
31886 tejbeer 3597
                        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 3598
                        List<String> authUserEmails = csService.getAuthUserByPartnerId(customRetailer.getPartnerId());
3599
                        if (authUserEmails != null) {
3600
                            authUserEmails = new ArrayList<>();
3601
                        }
3602
                        authUserEmails.addAll(bccTo);
26945 amit.gupta 3603
 
31697 amit.gupta 3604
                        // emailService.sendMailWithAttachments("Order Created with SmartDukaan",
3605
                        // "order-confirm.vm",
3606
                        // emailModel, customerEmail, null, authUserEmails.toArray(new String[0]));
26945 amit.gupta 3607
 
31697 amit.gupta 3608
                    } else if (statusList.contains("refunded") || statusList.contains("failed")) {
3609
                        for (PendingOrderItem poi : poItems) {
3610
                            poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
3611
                        }
25865 amit.gupta 3612
 
31697 amit.gupta 3613
                        po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
3614
                    }
25865 amit.gupta 3615
 
31697 amit.gupta 3616
                }
3617
                // LOGGER.info("payment" + payments);
25865 amit.gupta 3618
 
31697 amit.gupta 3619
            }
3620
        }
3621
    }
25865 amit.gupta 3622
 
31697 amit.gupta 3623
    public static class SaleTargetReportModel {
3624
        private double totalSale;
3625
        private long totalQty;
3626
        private double past3daysSale;
3627
        private int fofoId;
3628
        private String code;
31724 amit.gupta 3629
        private ActivationType activationType;
25865 amit.gupta 3630
 
31724 amit.gupta 3631
 
3632
        @Override
3633
        public boolean equals(Object o) {
3634
            if (this == o) return true;
3635
            if (o == null || getClass() != o.getClass()) return false;
3636
            SaleTargetReportModel that = (SaleTargetReportModel) o;
3637
            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;
3638
        }
3639
 
3640
        @Override
3641
        public int hashCode() {
3642
            return Objects.hash(totalSale, totalQty, past3daysSale, fofoId, code, activationType, secondary, smartphoneSale, smartphoneQty, insuranceSale, insruanceQty);
3643
        }
3644
 
3645
        public ActivationType getActivationType() {
3646
            return activationType;
3647
        }
3648
 
3649
        public void setActivationType(ActivationType activationType) {
3650
            this.activationType = activationType;
3651
        }
3652
 
31697 amit.gupta 3653
        public double getSecondary() {
3654
            return secondary;
3655
        }
25865 amit.gupta 3656
 
31697 amit.gupta 3657
        public void setSecondary(double secondary) {
3658
            this.secondary = secondary;
3659
        }
25865 amit.gupta 3660
 
31697 amit.gupta 3661
        private double secondary;
25865 amit.gupta 3662
 
31697 amit.gupta 3663
        public int getFofoId() {
3664
            return fofoId;
3665
        }
25865 amit.gupta 3666
 
31697 amit.gupta 3667
        @Override
3668
        public String toString() {
31886 tejbeer 3669
            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 3670
        }
25865 amit.gupta 3671
 
31697 amit.gupta 3672
        public String getCode() {
3673
            return code;
3674
        }
25865 amit.gupta 3675
 
31697 amit.gupta 3676
        public void setCode(String code) {
3677
            this.code = code;
3678
        }
25865 amit.gupta 3679
 
31697 amit.gupta 3680
        public void setFofoId(int fofoId) {
3681
            this.fofoId = fofoId;
3682
        }
25872 tejbeer 3683
 
31697 amit.gupta 3684
        private double smartphoneSale;
3685
        private long smartphoneQty;
3686
        private double insuranceSale;
3687
        private long insruanceQty;
26945 amit.gupta 3688
 
31697 amit.gupta 3689
        public long getTotalQty() {
3690
            return totalQty;
3691
        }
30765 tejbeer 3692
 
31697 amit.gupta 3693
        public void setTotalQty(long totalQty) {
3694
            this.totalQty = totalQty;
3695
        }
3696
 
3697
        public double getPast3daysSale() {
3698
            return past3daysSale;
3699
        }
3700
 
3701
        public void setPast3daysSale(double past3daysSale) {
3702
            this.past3daysSale = past3daysSale;
3703
        }
3704
 
3705
        public double getTotalSale() {
3706
            return totalSale;
3707
        }
3708
 
3709
        public void setTotalSale(double totalSale) {
3710
            this.totalSale = totalSale;
3711
        }
3712
 
3713
        public double getSmartphoneSale() {
3714
            return smartphoneSale;
3715
        }
3716
 
3717
        public void setSmartphoneSale(double smartphoneSale) {
3718
            this.smartphoneSale = smartphoneSale;
3719
        }
3720
 
3721
        public long getSmartphoneQty() {
3722
            return smartphoneQty;
3723
        }
3724
 
3725
        public void setSmartphoneQty(long smartphoneQty) {
3726
            this.smartphoneQty = smartphoneQty;
3727
        }
3728
 
3729
        public double getInsuranceSale() {
3730
            return insuranceSale;
3731
        }
3732
 
3733
        public void setInsuranceSale(double insuranceSale) {
3734
            this.insuranceSale = insuranceSale;
3735
        }
3736
 
3737
        public long getInsruanceQty() {
3738
            return insruanceQty;
3739
        }
3740
 
3741
        public void setInsruanceQty(long insruanceQty) {
3742
            this.insruanceQty = insruanceQty;
3743
        }
3744
 
3745
    }
3746
 
32482 amit.gupta 3747
    private void getStateWiseSales
3748
            (Map<Integer, SaleTargetReportModel> saleTargetReportModelMap, Map<Integer, FofoReportingModel> partnerSalesHeadersMap) throws
3749
            Exception {
31697 amit.gupta 3750
        String timeString = "Today %s";
3751
        LocalDateTime now = LocalDateTime.now();
3752
 
3753
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
31886 tejbeer 3754
        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_MARKETING, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT, ProfitMandiConstants.TICKET_CATEGORY_TECHNOLOGY);
31697 amit.gupta 3755
 
3756
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false);
3757
 
31746 amit.gupta 3758
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
3759
            String email = storeGuyEntry.getKey();
3760
            Set<Integer> fofoIds = storeGuyEntry.getValue();
3761
            LOGGER.info("fofoIds {}", fofoIds);
24683 amit.gupta 3762
 
31746 amit.gupta 3763
            if (!fofoIds.isEmpty()) {
31886 tejbeer 3764
                List<FofoStore> stores = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds));
26945 amit.gupta 3765
 
31724 amit.gupta 3766
                Map<String, List<Integer>> stateMap = stores.stream().collect(groupingBy(
3767
                        x -> x.getCode().substring(0, 2), mapping(x -> x.getId(), Collectors.toList())));
31697 amit.gupta 3768
                List<List<Serializable>> stateWiseSales = new ArrayList<>();
33452 amit.gupta 3769
                for (Entry<String, List<Integer>> stateMapEntry : stateMap.entrySet()) {
31886 tejbeer 3770
                    long totalQty = stateMapEntry.getValue().stream().collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getTotalQty()));
3771
                    double totalSale = stateMapEntry.getValue().stream().collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getTotalSale()));
3772
                    long smartPhoneQty = stateMapEntry.getValue().stream().collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getSmartphoneQty()));
31697 amit.gupta 3773
                    double smartPhoneSale = stateMapEntry.getValue().stream().collect(
3774
                            Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getSmartphoneSale()));
3775
                    stateWiseSales.add(
3776
                            Arrays.asList(stateMapEntry.getKey(), smartPhoneQty, smartPhoneSale, totalQty, totalSale));
3777
                }
3778
                StringBuilder sb = new StringBuilder();
3779
                sb.append("<html><body>");
3780
                sb.append("<p>Statewise Sale Report:</p><br/><table style=\"border-collapse: collapse;\">");
31886 tejbeer 3781
                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 3782
                for (List<Serializable> stateSale : stateWiseSales) {
3783
                    sb.append("<tr>");
3784
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(0) + "</td>");
3785
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(1) + "</td>");
3786
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(2) + "</td>");
3787
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(3) + "</td>");
3788
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(4) + "</td>");
3789
                    sb.append("</tr>");
3790
                }
3791
                sb.append("</tbody></table><br><br>");
26945 amit.gupta 3792
 
31697 amit.gupta 3793
                sb.append("<p>Partnerwise Report:</p><br/><table style=\"border-collapse: collapse;\">");
31886 tejbeer 3794
                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 3795
 
3796
 
31886 tejbeer 3797
                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 3798
 
31697 amit.gupta 3799
                String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
31169 tejbeer 3800
 
31886 tejbeer 3801
                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 3802
                List<List<?>> rows = new ArrayList<>();
3803
                for (Integer fofoId : sortedSaleTargetReport) {
3804
                    FofoReportingModel fofoReportingModel = partnerSalesHeadersMap.get(fofoId);
31886 tejbeer 3805
                    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 3806
                    ));
31169 tejbeer 3807
 
31724 amit.gupta 3808
                    //Now try to populate html rows
3809
                    if (!saleTargetReportModelMap.get(fofoId).getActivationType().equals(ActivationType.ACTIVE)) {
31697 amit.gupta 3810
                        continue;
3811
                    }
3812
                    if (saleTargetReportModelMap.get(fofoId).getSecondary() == 0) {
3813
                        sb.append("<tr style='background-color:#D21F3C;color:white'>");
3814
                    } else {
3815
                        sb.append("<tr>");
3816
                    }
31886 tejbeer 3817
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getCode() + "</td>");
3818
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getBusinessName() + "</td>");
3819
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getBusinessManager() + "</td>");
3820
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getRegionalManager() + "</td>");
3821
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getTerritoryManager() + "</td>");
3822
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSecondary() + "</td>");
3823
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
3824
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
3825
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
31697 amit.gupta 3826
                    sb.append("</tr>");
24841 govind 3827
 
25300 tejbeer 3828
 
31697 amit.gupta 3829
                }
3830
                sb.append("</tr>");
3831
                sb.append("</body></html>");
3832
                String statewiseSaleReport = sb.toString();
25300 tejbeer 3833
 
3834
 
31697 amit.gupta 3835
                ByteArrayOutputStream baos = null;
3836
                try {
3837
                    baos = FileUtil.getCSVByteStream(headers, rows);
3838
                } catch (Exception e2) {
3839
                    e2.printStackTrace();
3840
                }
3841
                Attachment attachment = new Attachment("PartnerSalePerformance.csv", new ByteArrayResource(baos.toByteArray()));
3842
                Utils.sendHtmlMailWithAttachments(googleMailSender, new String[]{email}, null, "Statewise " + subject, statewiseSaleReport, attachment);
3843
            }
3844
        }
3845
    }
29668 tejbeer 3846
 
32350 amit.gupta 3847
 
32482 amit.gupta 3848
    private void sendMailOfHtmlFormat(JavaMailSender sender, String[] email, String body, String cc[], String subject) throws
3849
            MessagingException, ProfitMandiBusinessException, IOException {
32350 amit.gupta 3850
        MimeMessage message = sender.createMimeMessage();
31697 amit.gupta 3851
        MimeMessageHelper helper = new MimeMessageHelper(message);
3852
        helper.setSubject(subject);
3853
        helper.setText(body, true);
3854
        helper.setTo(email);
3855
        if (cc != null) {
3856
            helper.setCc(cc);
3857
        }
3858
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
3859
        helper.setFrom(senderAddress);
3860
        mailSender.send(message);
3861
    }
25694 amit.gupta 3862
 
31697 amit.gupta 3863
    public void sendNotification() throws Exception {
32610 amit.gupta 3864
        List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllPendingNotifications();
31697 amit.gupta 3865
        if (!pushNotifications.isEmpty()) {
3866
            for (PushNotifications pushNotification : pushNotifications) {
3867
                Device device = deviceRepository.selectById(pushNotification.getDeviceId());
31886 tejbeer 3868
                NotificationCampaign notificationCampaign = notificationCampaignRepository.selectById(pushNotification.getNotificationCampaignid());
3869
                SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(), SimpleCampaignParams.class);
31697 amit.gupta 3870
                Campaign campaign = new SimpleCampaign(scp);
3871
                String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
3872
                JSONObject json = new JSONObject();
3873
                json.put("to", device.getFcmId());
3874
                JSONObject jsonObj = new JSONObject();
3875
                jsonObj.put("message", campaign.getMessage());
3876
                jsonObj.put("title", campaign.getTitle());
3877
                jsonObj.put("type", campaign.getType());
3878
                jsonObj.put("url", result_url);
3879
                jsonObj.put("time_to_live", campaign.getExpireTimestamp());
3880
                jsonObj.put("image", campaign.getImageUrl());
3881
                jsonObj.put("largeIcon", "large_icon");
3882
                jsonObj.put("smallIcon", "small_icon");
3883
                jsonObj.put("vibrate", 1);
3884
                jsonObj.put("pid", pushNotification.getId());
3885
                jsonObj.put("sound", 1);
3886
                jsonObj.put("priority", "high");
3887
                json.put("data", jsonObj);
3888
                try {
3889
                    CloseableHttpClient client = HttpClients.createDefault();
3890
                    HttpPost httpPost = new HttpPost(FCM_URL);
25694 amit.gupta 3891
 
31697 amit.gupta 3892
                    httpPost.setHeader("Content-Type", "application/json; utf-8");
3893
                    httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
3894
                    StringEntity entity = new StringEntity(json.toString());
3895
                    httpPost.setEntity(entity);
3896
                    CloseableHttpResponse response = client.execute(httpPost);
30858 amit.gupta 3897
 
31697 amit.gupta 3898
                    if (response.getStatusLine().getStatusCode() == 200) {
3899
                        pushNotification.setSentTimestamp(LocalDateTime.now());
3900
                    } else {
3901
                        pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
3902
                        LOGGER.info("message" + "not sent");
3903
                        response.toString();
3904
                    }
25694 amit.gupta 3905
 
31697 amit.gupta 3906
                } catch (Exception e) {
3907
                    e.printStackTrace();
3908
                    pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
3909
                    LOGGER.info("message " + "not sent " + e.getMessage());
3910
                }
3911
            }
3912
        }
3913
    }
25721 tejbeer 3914
 
31697 amit.gupta 3915
    public void grouping() throws Exception {
3916
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
3917
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
31886 tejbeer 3918
        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 3919
        Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers(false);
3920
        for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
3921
            if (priceDropIMEI.getPartnerId() == 0)
3922
                continue;
3923
            HashSet<String> imeis = new HashSet<>();
3924
            PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
3925
            imeis.add(priceDropIMEI.getImei());
31886 tejbeer 3926
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
31697 amit.gupta 3927
            if (inventoryItems.size() == 0) {
3928
                LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
3929
                continue;
3930
            }
3931
            InventoryItem inventoryItem = inventoryItems.get(0);
3932
            CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
31886 tejbeer 3933
            if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) || inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
31697 amit.gupta 3934
                // check if pricedrop has been rolled out
31886 tejbeer 3935
                List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(), priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
31697 amit.gupta 3936
                if (uwh.size() > 0) {
3937
                    Item item = itemRepository.selectById(inventoryItem.getItemId());
31886 tejbeer 3938
                    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 3939
                }
3940
            }
3941
        }
3942
    }
25721 tejbeer 3943
 
31697 amit.gupta 3944
    public void toffeeRollback() throws Exception {
3945
        toffeeService.cancelPolicyCopy("110143521986");
3946
        toffeeService.getOrderId("110143521986");
3947
    }
27212 tejbeer 3948
 
31697 amit.gupta 3949
    public void attachToffeeInvoices() throws Exception {
31886 tejbeer 3950
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(3, Optional.of(false));
31697 amit.gupta 3951
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
3952
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
3953
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
3954
            InvoicePdfModel pdfModel = orderService.getInvoicePdfModel(fofoOrder.getId());
3955
            java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
3956
            PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
31886 tejbeer 3957
            String pdfInvoiceString = "data:application/pdf;base64," + Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
3958
            boolean attached = toffeeService.attachInvoice(insurancePolicy.getPolicyNumber().split("#")[1], pdfInvoiceString);
31697 amit.gupta 3959
            if (attached) {
3960
                insurancePolicy.setPosted(true);
3961
            }
3962
        }
3963
    }
25721 tejbeer 3964
 
31697 amit.gupta 3965
    public void sendBAGPendingPolicies() throws Exception {
31886 tejbeer 3966
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(4, Optional.of(false));
31697 amit.gupta 3967
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
3968
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
3969
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
3970
            FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
3971
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
3972
            Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
3973
            BAGInsuranceModel bagInsuranceModel = new BAGInsuranceModel();
3974
            // bagInsuranceModel.setModelId();
3975
            bagInsuranceModel.setAddressLine1(customerAddress.getLine1());
3976
            bagInsuranceModel.setAddressLine2(customerAddress.getLine2());
3977
            bagInsuranceModel.setCity(customerAddress.getCity());
3978
            bagInsuranceModel.setBrandWarranty("1 Year");
3979
            Item item = itemRepository.selectById(fofoOrderItem.getId());
3980
            bagInsuranceModel.setModelName(item.getItemDescription());
3981
            bagInsuranceModel.setDateOfPurchase(fofoOrder.getFormattedDate());
3982
            bagInsuranceModel.setEmail(customer.getEmailId());
3983
            bagInsuranceModel.setImei1(insurancePolicy.getSerialNumber());
3984
            bagInsuranceModel.setFirstName(customer.getFirstName());
3985
            bagInsuranceModel.setLastName(customer.getLastName());
3986
            bagInsuranceModel.setMobileNumber(customer.getMobileNumber());
3987
            bagInsuranceModel.setPlanId("");
3988
            insurancePolicy.setPosted(true);
3989
        }
3990
    }
25721 tejbeer 3991
 
31697 amit.gupta 3992
    public void schemeRollback(List<String> schemeIds) throws Exception {
3993
        List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
31886 tejbeer 3994
        Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31697 amit.gupta 3995
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
3996
        for (SchemeInOut sio : schemeInOuts) {
3997
            Scheme scheme = schemesMap.get(sio.getSchemeId());
3998
            if (scheme.getType().equals(SchemeType.IN)) {
25721 tejbeer 3999
 
31697 amit.gupta 4000
            } else if (scheme.getType().equals(SchemeType.OUT)) {
4001
                InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
4002
                List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
31886 tejbeer 4003
                ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE)).max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
4004
                if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime()) || scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
31697 amit.gupta 4005
                    sio.setRolledBackTimestamp(LocalDateTime.now());
4006
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
31886 tejbeer 4007
                    String rollbackReason = "Scheme reversed for " + itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - " + fofoOrder.getInvoiceNumber();
4008
                    walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(), scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason, LocalDateTime.now());
4009
                    System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(), rollbackReason);
31697 amit.gupta 4010
                }
4011
            }
4012
        }
4013
        // throw new Exception();
4014
    }
25721 tejbeer 4015
 
31697 amit.gupta 4016
    public void checkfocusedModelInPartnerStock() throws Exception {
25721 tejbeer 4017
 
31886 tejbeer 4018
        List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
4019
        Map<Integer, Map<Integer, List<SaholicCIS>>> warehouseItemAvailabilityMap = saholicInventoryService.getSaholicStock();
31697 amit.gupta 4020
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
4021
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
25721 tejbeer 4022
 
31886 tejbeer 4023
        Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService.getSaholicPOItems();
31697 amit.gupta 4024
        Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
4025
        for (Integer fofoId : fofoIds) {
4026
            List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
4027
            focusedModelShortageReportMap.put(fofoId, focusedModelShortageList);
4028
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
4029
            Map<Integer, Integer> processingOrderMap = null;
4030
            Map<Integer, Integer> catalogIdAndQtyMap = null;
4031
            Map<Integer, Integer> grnPendingOrdersMap = null;
25721 tejbeer 4032
 
31886 tejbeer 4033
            Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
25721 tejbeer 4034
 
31697 amit.gupta 4035
            if (!currentInventorySnapshot.isEmpty()) {
31886 tejbeer 4036
                catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream().collect(groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
25800 tejbeer 4037
 
31697 amit.gupta 4038
            }
25800 tejbeer 4039
 
31886 tejbeer 4040
            Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream().collect(groupingBy(x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
31697 amit.gupta 4041
            if (!grnPendingOrders.isEmpty()) {
31886 tejbeer 4042
                grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream().collect(groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
25721 tejbeer 4043
 
31697 amit.gupta 4044
            }
25721 tejbeer 4045
 
31886 tejbeer 4046
            Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream().collect(groupingBy(x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
31697 amit.gupta 4047
            if (!processingOrder.isEmpty()) {
31886 tejbeer 4048
                processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream().collect(groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> processingOrder.get(x.getId()))));
25721 tejbeer 4049
 
31697 amit.gupta 4050
            }
25721 tejbeer 4051
 
31886 tejbeer 4052
            List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
28526 tejbeer 4053
 
31886 tejbeer 4054
            List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
31697 amit.gupta 4055
            LOGGER.info("regionIds" + regionIds);
4056
            if (regionIds.size() == 0) {
4057
                LOGGER.info("No region found for partner {}", fofoId);
4058
                continue;
4059
            }
31886 tejbeer 4060
            Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream().collect(groupingBy(FocusedModel::getCatalogId, mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
25721 tejbeer 4061
 
31697 amit.gupta 4062
            LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
32060 amit.gupta 4063
 
32048 tejbeer 4064
            Map<String, RetailerBlockBrands> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(fofoId).stream().collect(Collectors.toMap(x -> x.getBlockBrands(), x -> x));
31388 amit.gupta 4065
 
32048 tejbeer 4066
 
33452 amit.gupta 4067
            for (Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
31697 amit.gupta 4068
                int minQty = entry.getValue().get();
4069
                int inStockQty = 0;
4070
                int processingQty = 0;
4071
                int grnPendingQty = 0;
4072
                int allColorNetAvailability = 0;
4073
                int allColorPoAvailability = 0;
4074
                if (processingOrderMap != null) {
31886 tejbeer 4075
                    processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0 : processingOrderMap.get(entry.getKey());
31388 amit.gupta 4076
 
31697 amit.gupta 4077
                }
4078
                if (grnPendingOrdersMap != null) {
31886 tejbeer 4079
                    grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0 : grnPendingOrdersMap.get(entry.getKey());
25721 tejbeer 4080
 
31697 amit.gupta 4081
                }
4082
                if (catalogIdAndQtyMap != null) {
31886 tejbeer 4083
                    inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0 : catalogIdAndQtyMap.get(entry.getKey());
27213 tejbeer 4084
 
31697 amit.gupta 4085
                }
25721 tejbeer 4086
 
31697 amit.gupta 4087
                int grnStockQty = grnPendingQty + inStockQty;
4088
                int totalQty = processingQty + grnPendingQty + inStockQty;
27208 tejbeer 4089
 
31697 amit.gupta 4090
                int shortageQty = minQty - totalQty;
4091
                List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());
28528 tejbeer 4092
 
31697 amit.gupta 4093
                TagListing tagListing = tagListingRepository.selectByCatalogId(entry.getKey());
27208 tejbeer 4094
 
31697 amit.gupta 4095
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
25721 tejbeer 4096
 
31886 tejbeer 4097
                Map<Integer, List<SaholicCIS>> itemAvailabilityMap = warehouseItemAvailabilityMap.get(fofoStore.getWarehouseId());
27233 tejbeer 4098
 
31886 tejbeer 4099
                Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap.get(fofoStore.getWarehouseId());
29801 manish 4100
 
31697 amit.gupta 4101
                for (Item item : items) {
4102
                    List<SaholicCIS> currentAvailability = null;
4103
                    List<SaholicPOItem> poItemAvailability = null;
4104
                    if (itemAvailabilityMap != null) {
4105
                        currentAvailability = itemAvailabilityMap.get(item.getId());
4106
                    }
25721 tejbeer 4107
 
31697 amit.gupta 4108
                    if (poItemAvailabilityMap != null) {
4109
                        poItemAvailability = poItemAvailabilityMap.get(item.getId());
4110
                    }
4111
                    if (currentAvailability != null) {
31886 tejbeer 4112
                        allColorNetAvailability += currentAvailability.stream().collect(Collectors.summingInt(SaholicCIS::getNetavailability));
31697 amit.gupta 4113
                    }
25800 tejbeer 4114
 
31697 amit.gupta 4115
                    if (poItemAvailability != null) {
31886 tejbeer 4116
                        allColorPoAvailability += poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
31697 amit.gupta 4117
                    }
25800 tejbeer 4118
 
31697 amit.gupta 4119
                }
25721 tejbeer 4120
 
31697 amit.gupta 4121
                FocusedModelShortageModel fm = new FocusedModelShortageModel();
4122
                fm.setFofoId(fofoId);
4123
                fm.setStoreCode(fofoStore.getCode());
4124
                fm.setStoreName(customRetailer.getBusinessName());
4125
                fm.setBrandName(items.get(0).getBrand());
4126
                fm.setModelName(items.get(0).getModelName());
4127
                fm.setModelNumber(items.get(0).getModelNumber());
4128
                fm.setGrnStockQty(grnStockQty);
4129
                fm.setPendingIndentQty(processingQty);
4130
                fm.setShortageQty(shortageQty);
4131
                fm.setPoAvailability(allColorPoAvailability);
4132
                fm.setDp(tagListing.getSellingPrice());
4133
                fm.setWarehouseName(warehouseMap.get(customRetailer.getWarehouseId()));
4134
                fm.setStateManager(partnerIdSalesHeadersMap.get(fofoId).getRegionalManager());
4135
                fm.setTerritoryManager(partnerIdSalesHeadersMap.get(fofoId).getTerritoryManager());
4136
                fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
4137
                fm.setAvailability(allColorNetAvailability);
25721 tejbeer 4138
 
31697 amit.gupta 4139
                focusedModelShortageList.add(fm);
4140
            }
25721 tejbeer 4141
 
31697 amit.gupta 4142
        }
4143
        if (!focusedModelShortageReportMap.isEmpty()) {
4144
            String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
4145
            Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
4146
            Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 4147
 
31697 amit.gupta 4148
            focusedModelShortageReportMap.entrySet().forEach(x -> {
4149
                storeGuyMap.entrySet().forEach(y -> {
28526 tejbeer 4150
 
31697 amit.gupta 4151
                    if (y.getValue().contains(x.getKey())) {
4152
                        if (!emailRowsMap.containsKey(y.getKey())) {
4153
                            emailRowsMap.put(y.getKey(), new ArrayList<>());
4154
                        }
31886 tejbeer 4155
                        List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays.asList(r.getStoreCode(), r.getStoreName(), r.getBrandName(), r.getModelName(), r.getModelNumber(), r.getDp(), r.getWarehouseName(), r.getStateManager(), r.getTerritoryManager(), r.getPendingIndentQty(), r.getGrnStockQty(), r.getShortageQty(), r.getAvailability())).collect(Collectors.toList());
31697 amit.gupta 4156
                        emailRowsMap.get(y.getKey()).addAll(fms);
29995 tejbeer 4157
 
31697 amit.gupta 4158
                    }
29995 tejbeer 4159
 
31697 amit.gupta 4160
                });
25721 tejbeer 4161
 
31697 amit.gupta 4162
            });
25721 tejbeer 4163
 
31886 tejbeer 4164
            List<String> headers = Arrays.asList("Store Code", "Store Name", "Brand", "Model Name", "Model Number", "DP", "Warehouse Name", "State Manager", "Territory Manager", "Pending Indent", "InStock", "Shortage Qty", "Availability");
31697 amit.gupta 4165
            emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 4166
 
31697 amit.gupta 4167
                ByteArrayOutputStream baos = null;
4168
                try {
4169
                    baos = FileUtil.getCSVByteStream(headers, entry.getValue());
4170
                } catch (Exception e2) {
4171
                    e2.printStackTrace();
4172
                }
4173
                String[] sendToArray = new String[]{
25721 tejbeer 4174
 
31886 tejbeer 4175
                        entry.getKey(), "apurve.shrivastava@smartdukaan.com", "puneet.bisht@smartdukaan.com"
25721 tejbeer 4176
 
31697 amit.gupta 4177
                };
25721 tejbeer 4178
 
31886 tejbeer 4179
 
31697 amit.gupta 4180
                try {
31886 tejbeer 4181
                    Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 4182
                } catch (Exception e1) { // TODO Auto-generated catch block
4183
                    e1.printStackTrace();
4184
                }
25721 tejbeer 4185
 
31697 amit.gupta 4186
            });
4187
        }
4188
    }
25721 tejbeer 4189
 
31697 amit.gupta 4190
    private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
4191
        StringBuilder sb = new StringBuilder();
4192
        sb.append("Focused Model Shortage in Your Stock : \n");
4193
        for (FocusedModelShortageModel entry : focusedModelShortageModel) {
25721 tejbeer 4194
 
31697 amit.gupta 4195
            sb.append(entry.getItemName() + "-" + entry.getShortageQty());
4196
            sb.append(String.format("%n", ""));
4197
        }
4198
        return sb.toString();
4199
    }
25721 tejbeer 4200
 
31697 amit.gupta 4201
    private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
4202
        MimeMessage message = mailSender.createMimeMessage();
4203
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
25721 tejbeer 4204
 
31697 amit.gupta 4205
        helper.setSubject(subject);
4206
        helper.setText(messageText, true);
4207
        helper.setTo(email);
4208
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
4209
        helper.setFrom(senderAddress);
4210
        mailSender.send(message);
25721 tejbeer 4211
 
31697 amit.gupta 4212
    }
25721 tejbeer 4213
 
31697 amit.gupta 4214
    private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
4215
        StringBuilder sb = new StringBuilder();
31886 tejbeer 4216
        sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
4217
        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 4218
        for (FocusedModelShortageModel entry : focusedModelShortageModel) {
25721 tejbeer 4219
 
31697 amit.gupta 4220
            sb.append("<tr>");
4221
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
25936 amit.gupta 4222
 
31697 amit.gupta 4223
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
26790 tejbeer 4224
 
31697 amit.gupta 4225
            sb.append("</tr>");
25927 amit.gupta 4226
 
31697 amit.gupta 4227
        }
26790 tejbeer 4228
 
31697 amit.gupta 4229
        sb.append("</tbody></table></body></html>");
26945 amit.gupta 4230
 
31697 amit.gupta 4231
        return sb.toString();
4232
    }
26945 amit.gupta 4233
 
31697 amit.gupta 4234
    public void notifyLead() throws Exception {
31886 tejbeer 4235
        List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
4236
        Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
31697 amit.gupta 4237
        LOGGER.info("authUserEmailMap {}", authUserEmailMap);
31886 tejbeer 4238
        Map<String, Integer> dtrEmailMap = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25982 amit.gupta 4239
 
31697 amit.gupta 4240
        LOGGER.info("dtrEmailMap {}", dtrEmailMap);
26283 tejbeer 4241
 
31697 amit.gupta 4242
        Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26283 tejbeer 4243
 
33452 amit.gupta 4244
        for (Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
31697 amit.gupta 4245
            int authId = authUserEmail.getKey();
4246
            String email = authUserEmail.getValue();
4247
            authUserKeyMap.put(authId, dtrEmailMap.get(email));
4248
        }
4249
        LOGGER.info("authUserKeyMap", authUserKeyMap);
4250
        LOGGER.info("leadsToNotify {}", leadsToNotify);
26283 tejbeer 4251
 
31697 amit.gupta 4252
        String templateMessage = "Lead followup for %s %s, %s, %s is due by %s";
4253
        for (Lead lead : leadsToNotify) {
4254
            if (authUserKeyMap.get(lead.getAssignTo()) == null) {
4255
                LOGGER.info("Assignee no longer part of system {}", lead.getAssignTo());
4256
                continue;
4257
            }
4258
            String title = "Leads followup Reminder";
31886 tejbeer 4259
            String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(), lead.getAddress(), lead.getLeadMobile(), leadTimeFormatter.format(lead.getScheduledTimestamp()));
31697 amit.gupta 4260
            String url = "https://app.smartdukaan.com/pages/home/leadUpdate?leadId=" + lead.getId();
4261
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
4262
            sendNotificationModel.setCampaignName("Lead Reminder");
4263
            sendNotificationModel.setTitle(title);
4264
            sendNotificationModel.setMessage(notificationMessage);
4265
            sendNotificationModel.setType("url");
4266
            sendNotificationModel.setUrl(url);
4267
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
4268
            sendNotificationModel.setMessageType(MessageType.reminder);
4269
            sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAssignTo())));
4270
            System.out.println(sendNotificationModel);
4271
            notificationService.sendNotification(sendNotificationModel);
4272
        }
4273
    }
26790 tejbeer 4274
 
32350 amit.gupta 4275
    @Autowired
4276
    AuthService authService;
4277
 
4278
    public void sendUnscheduledFollowUpMail() throws Exception {
4279
        List<Lead> missedScheduleLeads = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDate.now().atStartOfDay().minusDays(30), LocalDateTime.now().toLocalDate().atStartOfDay());
4280
        List<Lead> leadsScheduledForToday = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDate.now().atStartOfDay(), LocalDate.now().atTime(LocalTime.MAX));
4281
        List<Integer> authIds = missedScheduleLeads.stream().map(x -> x.getAssignTo()).distinct().collect(Collectors.toList());
4282
        LOGGER.info(authIds.size());
4283
        Map<Integer, AuthUser> authUserMap = authRepository.selectAllAuthUserByIds(authIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
4284
        LOGGER.info(authUserMap.size());
4285
        //if(true) return;
4286
 
4287
        missedScheduleLeads = missedScheduleLeads.stream().sorted(Comparator.comparing(Lead::getState, String.CASE_INSENSITIVE_ORDER).thenComparing(Lead::getAssignTo).thenComparing(Lead::getScheduledTimestamp)).collect(Collectors.toList());
4288
        //leadsScheduledForToday
4289
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
4290
        LOGGER.info("Auth Users Size - {}", authUsers.size());
4291
        for (AuthUser authUser : authUsers) {
4292
            LOGGER.info("Auth Name - {}", authUser.getFullName());
4293
            List<Integer> reporteeAuthIds = authService.getAllReportees(authUser.getId());
4294
            reporteeAuthIds.add(authUser.getId());
4295
            StringBuilder sb = new StringBuilder();
4296
            sb.append("<html><body>");
4297
            List<Lead> authMissedScheduledLeads = missedScheduleLeads.stream().filter(x -> reporteeAuthIds.contains(x.getAssignTo())).collect(Collectors.toList());
4298
            LOGGER.info("authMissedScheduledLeads {}", authMissedScheduledLeads.size());
4299
            if (authMissedScheduledLeads.size() > 0) {
4300
                addMissedScheduledLeadsTable(sb, authMissedScheduledLeads, authUserMap);
4301
                sb.append("</body></html>");
4302
 
4303
                String subject = "Lead Updates Summary";
32421 amit.gupta 4304
                String[] email = Arrays.asList(authUser.getEmailId()).toArray(new String[1]);
4305
                //String[] email = Arrays.asList("amit.gupta@smartdukaan.com").toArray(new String[1]);
32350 amit.gupta 4306
                this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
32421 amit.gupta 4307
                //break;
32350 amit.gupta 4308
            }
4309
        }
4310
 
4311
    }
4312
 
32482 amit.gupta 4313
    private void addMissedScheduledLeadsTable(StringBuilder
4314
                                                      sb, List<Lead> missedScheduleLeads, Map<Integer, AuthUser> authUserMap) {
32350 amit.gupta 4315
        sb.append("<h3>Leads That Missed the schedule</h3>");
32439 tejbeer 4316
        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 4317
        for (Lead lead : missedScheduleLeads) {
32439 tejbeer 4318
            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(
4319
                    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 4320
        }
4321
        sb.append("</table>");
4322
    }
4323
 
31697 amit.gupta 4324
    public void notifyVisits() throws Exception {
31886 tejbeer 4325
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
4326
        Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
4327
        Map<String, Integer> dtrEmailMap = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
31697 amit.gupta 4328
        Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26790 tejbeer 4329
 
33452 amit.gupta 4330
        for (Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
31697 amit.gupta 4331
            int authId = authUserEmail.getKey();
4332
            String email = authUserEmail.getValue();
4333
            authUserKeyMap.put(authId, dtrEmailMap.get(email));
4334
        }
4335
        String visitTemplate = "Planned visit to franchisee %s is due by %s";
4336
        String followupTemplate = "Lead followup for franchisee %s is due by %s";
4337
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
4338
        for (FranchiseeVisit visit : franchiseeVisits) {
4339
            if (authUserKeyMap.containsKey(visit.getAuthId())) {
4340
                continue;
4341
            }
4342
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
4343
            String message = null;
4344
            if (visit.getFranchiseActivityId() == 0) {
31886 tejbeer 4345
                message = String.format(visitTemplate, visit.getPartnerName(), timeFormatter.format(visit.getScheduleTimestamp()));
31697 amit.gupta 4346
                sendNotificationModel.setCampaignName("Franchisee visit Reminder");
4347
            } else {
31886 tejbeer 4348
                message = String.format(followupTemplate, visit.getPartnerName(), timeFormatter.format(visit.getScheduleTimestamp()));
31697 amit.gupta 4349
                sendNotificationModel.setCampaignName("Franchisee followup Reminder");
4350
            }
4351
            sendNotificationModel.setMessage(message);
4352
            sendNotificationModel.setType("url");
4353
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
4354
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
4355
            sendNotificationModel.setMessageType(MessageType.reminder);
4356
            sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
4357
            // notificationService.sendNotification(sendNotificationModel);
4358
        }
4359
    }
26792 tejbeer 4360
 
31697 amit.gupta 4361
    public void ticketClosed() throws Exception {
26790 tejbeer 4362
 
31697 amit.gupta 4363
        List<Ticket> tickets = ticketRepository.selectAllNotClosedTicketsWithStatus(ActivityType.RESOLVED);
4364
        for (Ticket ticket : tickets) {
4365
            if (ticket.getUpdateTimestamp().toLocalDate().isBefore(LocalDate.now().minusDays(7))) {
4366
                ticket.setCloseTimestamp(LocalDateTime.now());
4367
                ticket.setLastActivity(ActivityType.RESOLVED_ACCEPTED);
4368
                ticket.setUpdateTimestamp(LocalDateTime.now());
4369
                ticketRepository.persist(ticket);
4370
            }
4371
        }
26790 tejbeer 4372
 
31697 amit.gupta 4373
    }
26790 tejbeer 4374
 
31697 amit.gupta 4375
    public void checkValidateReferral() throws Exception {
26790 tejbeer 4376
 
31697 amit.gupta 4377
        List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
4378
        LOGGER.info("referrals" + referrals);
4379
        if (!referrals.isEmpty()) {
4380
            String subject = "Referral Request";
4381
            String messageText = this.getMessageForReferral(referrals);
26790 tejbeer 4382
 
31697 amit.gupta 4383
            MimeMessage message = mailSender.createMimeMessage();
4384
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
4385
            String[] email = {"kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com"};
4386
            helper.setSubject(subject);
4387
            helper.setText(messageText, true);
4388
            helper.setTo(email);
4389
            InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
4390
            helper.setFrom(senderAddress);
4391
            mailSender.send(message);
26790 tejbeer 4392
 
31697 amit.gupta 4393
        }
4394
    }
26790 tejbeer 4395
 
31697 amit.gupta 4396
    private String getMessageForReferral(List<Refferal> referrals) {
4397
        StringBuilder sb = new StringBuilder();
31886 tejbeer 4398
        sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
4399
        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 4400
        for (Refferal entry : referrals) {
26790 tejbeer 4401
 
31697 amit.gupta 4402
            sb.append("<tr>");
4403
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
30421 tejbeer 4404
 
31697 amit.gupta 4405
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
4406
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
4407
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
4408
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
4409
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
30421 tejbeer 4410
 
31697 amit.gupta 4411
            sb.append("</tr>");
30421 tejbeer 4412
 
31697 amit.gupta 4413
        }
30421 tejbeer 4414
 
31697 amit.gupta 4415
        sb.append("</tbody></table></body></html>");
30421 tejbeer 4416
 
31697 amit.gupta 4417
        return sb.toString();
4418
    }
30421 tejbeer 4419
 
32832 amit.gupta 4420
    private String getMessageForRBMEscalatedPartners(List<PartnerCollectionRemark> pcrs) throws
32482 amit.gupta 4421
            ProfitMandiBusinessException {
31697 amit.gupta 4422
        StringBuilder sb = new StringBuilder();
32832 amit.gupta 4423
        sb.append("<html><body><p>Alert</p><p>Escalated by RBM-L1:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
4424
        sb.append("<tbody>" +
4425
                "<tr>" +
4426
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
4427
                "<th style='border:1px solid black;padding: 5px'>Escalated Since</th>" +
4428
                "<th style='border:1px solid black;padding: 5px'>Message</th>" +
4429
                "</tr>");
30421 tejbeer 4430
 
31697 amit.gupta 4431
        for (PartnerCollectionRemark entry : pcrs) {
30421 tejbeer 4432
 
31697 amit.gupta 4433
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30421 tejbeer 4434
 
31697 amit.gupta 4435
            sb.append("<tr>");
31886 tejbeer 4436
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
4437
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
32832 amit.gupta 4438
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMessage() + "</td>");
28205 tejbeer 4439
 
31697 amit.gupta 4440
            sb.append("</tr>");
28205 tejbeer 4441
 
31697 amit.gupta 4442
        }
28205 tejbeer 4443
 
31697 amit.gupta 4444
        sb.append("</tbody></table></body></html>");
28205 tejbeer 4445
 
31697 amit.gupta 4446
        return sb.toString();
4447
    }
28208 tejbeer 4448
 
32795 amit.gupta 4449
    private String getMessageForSalesEscalatedPartners(List<PartnerCollectionRemark> pcrs) throws
4450
            ProfitMandiBusinessException {
4451
        StringBuilder sb = new StringBuilder();
4452
        sb.append("<html><body><p>Alert</p><p>Escalated to Sales Team:-</p>" + "<br/>" +
4453
                "<table style='border:1px solid black ;padding: 5px';>");
4454
        sb.append("<tbody>" +
4455
                "<tr>" +
4456
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
4457
                "<th style='border:1px solid black;padding: 5px'>Escalated Since</th>" +
4458
                "<th style='border:1px solid black;padding: 5px'>Message</th>" +
4459
                "</tr>");
4460
        for (PartnerCollectionRemark entry : pcrs) {
4461
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
4462
            sb.append("<tr>");
4463
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
4464
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
4465
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMessage() + "</td>");
4466
            sb.append("</tr>");
4467
        }
4468
 
4469
        sb.append("</tbody></table></body></html>");
4470
 
4471
        return sb.toString();
4472
    }
4473
 
33078 ranu 4474
    private String getMessageForUnauthorizedBuying(List<NonSdBuying> nsb) throws
4475
            ProfitMandiBusinessException {
4476
        StringBuilder sb = new StringBuilder();
4477
        sb.append("<html><body><p>Alert</p><p>Unauthorized Buying-</p>" + "<br/>" +
4478
                "<table style='border:1px solid black ;padding: 5px';>");
4479
        sb.append("<tbody>" +
4480
                "<tr>" +
4481
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>" +
4482
                "<th style='border:1px solid black;padding: 5px'>Brand Name</th>" +
4483
                "<th style='border:1px solid black;padding: 5px'>Brand Value</th>" +
4484
                "<th style='border:1px solid black;padding: 5px'>Created At</th>" +
4485
                "<th style='border:1px solid black;padding: 5px'>Reason</th>" +
4486
                "</tr>");
4487
        for (NonSdBuying entry : nsb) {
4488
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
4489
            List<Integer> brandIds = Collections.singletonList(entry.getBrandId());
4490
            BrandCatalog brandsDisplay = brandsRepository.selectByIds(brandIds).get(0);
4491
            sb.append("<tr>");
4492
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
4493
            sb.append("<td style='border:1px solid black;padding: 5px'>" + brandsDisplay.getName() + "</td>");
4494
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getBrandValue() + "</td>");
4495
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
4496
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getReason() + "</td>");
4497
            sb.append("</tr>");
4498
        }
4499
 
4500
        sb.append("</tbody></table></body></html>");
4501
 
4502
        return sb.toString();
4503
    }
4504
 
31697 amit.gupta 4505
    public void reverseWallet() throws Exception {
4506
        LocalDate localDate = LocalDate.of(2020, 10, 28);
31886 tejbeer 4507
        List<UserWalletHistory> uwhList = userWalletHistoryRepository.selectAllByDateType(localDate.atStartOfDay(), localDate.plusDays(1).atStartOfDay(), Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
31697 amit.gupta 4508
        for (UserWalletHistory uwh : uwhList) {
4509
            if (uwh.getBusinessTimestamp().getMonth().equals(Month.SEPTEMBER)) {
4510
                UserWallet uw = userWalletRepository.selectById(uwh.getWalletId());
4511
                // LOGGER.info("UWH - {}", uwh);
4512
                // amount += uwh.getAmount();
4513
                // System.out.println("Amount is - " + amount);
4514
                // walletService.rollbackAmountFromWallet(uw.getUserId(), uwh.getAmount(),
4515
                // uwh.getReference(), uwh.getReferenceType(), "Margin reversal for error prone
4516
                // run", uwh.getBusinessTimestamp());
4517
                int orderId = uwh.getReference();
4518
                FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
4519
                int inventoryItemId = 0;
4520
                // fofoOrderRepository.delete(fofoOrder);
4521
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
4522
                /*
4523
                 * List<PaymentOptionTransaction> paymentOptionTransactions =
4524
                 * paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId
4525
                 * (), PaymentOptionReferenceType.ORDER); for(PaymentOptionTransaction
4526
                 * paymentOptionTransaction : paymentOptionTransactions) {
4527
                 * //paymentOptionTransactionRepository.delete(paymentOptionTransaction); }
4528
                 */
4529
                for (FofoOrderItem foi : fofoOrderItems) {
4530
                    // fofoOrderItemRepository.delete(foi);
4531
                    List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
4532
                    for (FofoLineItem fli : flis) {
4533
                        // fofoLineItemRepository.delete(fli);
4534
                        inventoryItemId = fli.getInventoryItemId();
4535
                    }
4536
                }
4537
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(
33452 amit.gupta 4538
                        Stream.of(inventoryItemId).collect(Collectors.toSet()));
31697 amit.gupta 4539
                for (SchemeInOut sio : schemeInOuts) {
4540
                    if (sio.getCreateTimestamp().toLocalDate().equals(localDate)) {
4541
                        LOGGER.info("SIO - {}", sio);
4542
                        sio.setRolledBackTimestamp(LocalDateTime.now());
4543
                    }
4544
                }
28208 tejbeer 4545
 
31697 amit.gupta 4546
            }
4547
        }
28208 tejbeer 4548
 
31697 amit.gupta 4549
    }
28208 tejbeer 4550
 
31697 amit.gupta 4551
    public void partnerProblemAlert() throws Exception {
4552
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
4553
        Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
4554
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
31886 tejbeer 4555
        Map<Integer, Double> mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), 0, false);
4556
        Map<Integer, PartnerDailyInvestment> pdi = partnerDailyInvestmentRepository.selectAll(LocalDate.now()).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 4557
 
31697 amit.gupta 4558
        for (Entry<Integer, Double> ls : lmtdSale.entrySet()) {
28208 tejbeer 4559
 
31697 amit.gupta 4560
            double lmtdTwentyPercentSale = ls.getValue() * 0.2;
28208 tejbeer 4561
 
31697 amit.gupta 4562
            LOGGER.info("lmtdTwentyPercentSale" + lmtdTwentyPercentSale);
28208 tejbeer 4563
 
31697 amit.gupta 4564
            double mtdSale = mtdSales.get(ls.getKey()) == null ? 0 : mtdSales.get(ls.getKey());
28205 tejbeer 4565
 
31697 amit.gupta 4566
            LOGGER.info("mtdSale" + mtdSale);
28205 tejbeer 4567
 
31886 tejbeer 4568
            double totalSixtyPercentInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getTotalInvestment() * 0.6;
28205 tejbeer 4569
 
31697 amit.gupta 4570
            LOGGER.info("totalSixtyPercentInvestment" + totalSixtyPercentInvestment);
28205 tejbeer 4571
 
31697 amit.gupta 4572
            double stockInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getInStockAmount();
28205 tejbeer 4573
 
31697 amit.gupta 4574
            LOGGER.info("stockInvestment" + stockInvestment);
28205 tejbeer 4575
 
31697 amit.gupta 4576
            boolean Investmentvalue = partnerInvestmentService.isInvestmentBelow(ls.getKey(), 25);
28205 tejbeer 4577
 
31697 amit.gupta 4578
            PartnerProblem partnerProblem = partnerProblemRepository.selectByFofoId(ls.getKey());
28205 tejbeer 4579
 
31697 amit.gupta 4580
            if (partnerProblem == null) {
4581
                partnerProblem = new PartnerProblem();
4582
                partnerProblem.setFofoId(ls.getKey());
4583
                if (mtdSale < lmtdTwentyPercentSale) {
4584
                    partnerProblem.setMtd(1);
4585
                }
4586
                if (Investmentvalue) {
4587
                    partnerProblem.setInvestment(1);
4588
                }
28205 tejbeer 4589
 
31697 amit.gupta 4590
                if (stockInvestment < totalSixtyPercentInvestment) {
4591
                    partnerProblem.setInvestment(1);
4592
                }
28205 tejbeer 4593
 
31697 amit.gupta 4594
                partnerProblemRepository.persist(partnerProblem);
4595
            } else {
4596
                if (mtdSale < lmtdTwentyPercentSale) {
4597
                    partnerProblem.setMtd(partnerProblem.getMtd() + 1);
28213 tejbeer 4598
 
31697 amit.gupta 4599
                } else {
4600
                    partnerProblem.setMtd(0);
28227 tejbeer 4601
 
31697 amit.gupta 4602
                }
4603
                if (Investmentvalue) {
4604
                    partnerProblem.setInvestment(partnerProblem.getInvestment() + 1);
4605
                } else {
4606
                    partnerProblem.setInvestment(0);
28227 tejbeer 4607
 
31697 amit.gupta 4608
                }
4609
                if (stockInvestment < totalSixtyPercentInvestment) {
4610
                    partnerProblem.setStockInvestment(partnerProblem.getStockInvestment() + 1);
4611
                } else {
4612
                    partnerProblem.setStockInvestment(0);
4613
                }
28213 tejbeer 4614
 
31697 amit.gupta 4615
            }
28213 tejbeer 4616
 
31697 amit.gupta 4617
        }
28213 tejbeer 4618
 
31886 tejbeer 4619
        List<PartnerProblem> partnerProblems = partnerProblemRepository.selectAll().stream().filter(x -> x.getMtd() + x.getInvestment() + x.getStockInvestment() > 0).collect(Collectors.toList());
28205 tejbeer 4620
 
31697 amit.gupta 4621
        partnerProblems = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 4622
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 4623
        }).collect(Collectors.toList());
28205 tejbeer 4624
 
31697 amit.gupta 4625
        Map<Integer, PartnerProblem> partnerProblemMap = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 4626
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 4627
        }).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 4628
 
31697 amit.gupta 4629
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
28205 tejbeer 4630
 
31697 amit.gupta 4631
        List<Integer> assignTo = Arrays.asList(15, 9, 54, 53);
28205 tejbeer 4632
 
31886 tejbeer 4633
        Map<Integer, AuthUser> assignAuthUserMap = authRepository.selectAllAuthUserByIds(assignTo).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
28222 tejbeer 4634
 
31886 tejbeer 4635
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "sm@smartdukaan.com");
31697 amit.gupta 4636
        LOGGER.info("partnerProblem" + partnerProblems);
4637
        StringBuilder sb = new StringBuilder();
4638
        sb.append("<htl><body>");
4639
        sb.append(
4640
                "<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 4641
        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 4642
 
31697 amit.gupta 4643
                + "	    				</tr>");
28218 tejbeer 4644
 
31697 amit.gupta 4645
        for (PartnerProblem pp : partnerProblems) {
4646
            int value = pp.getFofoId() % 4;
28218 tejbeer 4647
 
31697 amit.gupta 4648
            Map<EscalationType, AuthUser> authUserMap = csService.getAuthUserAndEsclationByPartnerId(pp.getFofoId());
4649
            LOGGER.info("authUserMap" + authUserMap);
4650
            sb.append("<tr>");
31886 tejbeer 4651
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
4652
            sb.append("<td style='border:1px solid black;padding: 5px'>" + assignAuthUserMap.get(assignTo.get(value)).getName() + "</td>");
31697 amit.gupta 4653
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
4654
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
4655
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
31886 tejbeer 4656
            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 4657
 
31697 amit.gupta 4658
            sb.append("</tr>");
4659
        }
4660
        sb.append("</tbody></table><br><br>");
4661
        String subject = "Partner Problem Alert!";
4662
        String[] email = sendTo.toArray(new String[sendTo.size()]);
28227 tejbeer 4663
 
32350 amit.gupta 4664
        this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
28227 tejbeer 4665
 
31697 amit.gupta 4666
        Map<Integer, List<Integer>> authUserPartnerMapping = csService.getAuthUserIdPartnerIdMapping();
28224 tejbeer 4667
 
31697 amit.gupta 4668
        for (Entry<Integer, List<Integer>> authUserPartner : authUserPartnerMapping.entrySet()) {
4669
            AuthUser authUser = authRepository.selectById(authUserPartner.getKey());
4670
            for (Integer patnerId : authUserPartner.getValue()) {
4671
                if (partnerProblemMap.get(patnerId) != null) {
28230 tejbeer 4672
 
31697 amit.gupta 4673
                    StringBuilder sbbuilder = new StringBuilder();
4674
                    sbbuilder.append("<hml><body>");
4675
                    sb.append(
4676
                            "<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 4677
                    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 4678
 
31697 amit.gupta 4679
                            + "	    				</tr>");
28205 tejbeer 4680
 
31697 amit.gupta 4681
                    for (Integer partnerId : authUserPartner.getValue()) {
4682
                        if (partnerProblemMap.get(partnerId) != null) {
4683
                            PartnerProblem pp = partnerProblemMap.get(partnerId);
4684
                            sbbuilder.append("<tr>");
31886 tejbeer 4685
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
4686
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
31697 amit.gupta 4687
                            sbbuilder.append(
4688
                                    "<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
31886 tejbeer 4689
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
28790 amit.gupta 4690
 
31697 amit.gupta 4691
                            sbbuilder.append("</tr>");
4692
                        }
28790 amit.gupta 4693
 
31697 amit.gupta 4694
                    }
4695
                    sbbuilder.append("</tbody></table><br><br>");
29488 manish 4696
 
32350 amit.gupta 4697
                    this.sendMailOfHtmlFormat(googleMailSender, new String[]{authUser.getEmailId()}, sbbuilder.toString(), null, subject);
31697 amit.gupta 4698
                }
29488 manish 4699
 
31697 amit.gupta 4700
            }
4701
        }
4702
    }
28775 amit.gupta 4703
 
31697 amit.gupta 4704
    @Autowired
4705
    WarehouseRepository warehouseRepository;
29488 manish 4706
 
33256 amit.gupta 4707
    public void getVendorWarehouses(int warehouseId) throws ProfitMandiBusinessException {
31697 amit.gupta 4708
        LOGGER.info("Warehouses - {}", warehouseRepository.getVendorWarehouses().get(warehouseId));
29488 manish 4709
 
31697 amit.gupta 4710
    }
29488 manish 4711
 
31697 amit.gupta 4712
    public void checkImeiActivation() {
29801 manish 4713
 
31697 amit.gupta 4714
        try {
4715
            vivoImeiActivationService.checkImeiActivation();
4716
        } catch (ProfitMandiBusinessException e) {
4717
            // TODO Auto-generated catch block
4718
            e.printStackTrace();
4719
        } catch (IOException e) {
4720
            // TODO Auto-generated catch block
4721
            e.printStackTrace();
4722
        } catch (Exception e) {
4723
            // TODO Auto-generated catch block
4724
            e.printStackTrace();
4725
        }
29807 manish 4726
 
31697 amit.gupta 4727
    }
29801 manish 4728
 
31697 amit.gupta 4729
    public void checkItelImeiActivation(LocalDate date, Integer day) {
4730
        LOGGER.info("Hello - {}", "hhh");
29488 manish 4731
 
31697 amit.gupta 4732
        try {
4733
            itelImeiActivationService.checkItelImeiActivation(date, day);
4734
        } catch (ProfitMandiBusinessException e) {
4735
            // TODO Auto-generated catch block
4736
            e.printStackTrace();
4737
        } catch (IOException e) {
4738
            // TODO Auto-generated catch block
4739
            e.printStackTrace();
4740
        } catch (Exception e) {
4741
            // TODO Auto-generated catch block
4742
            e.printStackTrace();
4743
        }
29488 manish 4744
 
31697 amit.gupta 4745
    }
29488 manish 4746
 
32482 amit.gupta 4747
    public void selectFinServiceFollowUpDateByCurrDate(LocalDate currentDate) throws
4748
            MessagingException, ProfitMandiBusinessException, IOException {
31697 amit.gupta 4749
        LOGGER.info("selectfinServiceFollow - {}", "selectfinServiceFollowUpDateByCurrDate");
29308 tejbeer 4750
 
31697 amit.gupta 4751
        serviceConfigService.selectFinServicePartnerfollowUpDateByCurrentDate(currentDate);
29252 amit.gupta 4752
 
31697 amit.gupta 4753
    }
29451 manish 4754
 
31697 amit.gupta 4755
    public void checkTecnoImeiActivation(LocalDate date, Integer day) {
4756
        LOGGER.info("Hello - {}", "hhh");
29308 tejbeer 4757
 
31697 amit.gupta 4758
        try {
4759
            tecnoImeiActivation.checkTecnoImeiActivation(date, day);
4760
        } catch (ProfitMandiBusinessException e) {
4761
            // TODO Auto-generated catch block
4762
            e.printStackTrace();
4763
        } catch (IOException e) {
4764
            // TODO Auto-generated catch block
4765
            e.printStackTrace();
4766
        } catch (Exception e) {
4767
            // TODO Auto-generated catch block
4768
            e.printStackTrace();
4769
        }
29308 tejbeer 4770
 
31697 amit.gupta 4771
    }
29441 tejbeer 4772
 
31697 amit.gupta 4773
    public void checkCancellationMargin() throws Exception {
4774
        LocalDateTime startDate = LocalDate.of(2021, 4, 1).atStartOfDay();
4775
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectCancelledBetweenSaleDate(startDate, LocalDateTime.now());
4776
        LOGGER.info("Total Orders =  {}", fofoOrders.size());
4777
        for (FofoOrder fofoOrder : fofoOrders) {
31886 tejbeer 4778
            List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
4779
            history.addAll(userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.ACTIVATION_SCHEME));
31697 amit.gupta 4780
            int walletSum = history.stream().mapToInt(x -> x.getAmount()).sum();
4781
            if (Math.abs(walletSum) > 1) {
4782
                // LOGGER.info("Cancelled invoice {}, Order Id = {}, = havent rolledback, Value
4783
                // = {}", fofoOrder.getInvoiceNumber(), fofoOrder.getId(), walletSum);
4784
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
4785
                List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(fofoOrderItems.get(0).getId());
4786
                FofoLineItem fli = flis.get(0);
4787
                if (StringUtils.isEmpty(fli.getSerialNumber()))
4788
                    continue;
31886 tejbeer 4789
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(fli.getInventoryItemId())));
31697 amit.gupta 4790
                InventoryItem inventoryItem = inventoryItemRepository.selectById(fli.getInventoryItemId());
31886 tejbeer 4791
                double schemeSum = schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).mapToDouble(x -> x.getAmount()).sum();
31697 amit.gupta 4792
                /*
4793
                 * if(inventoryItem.getGoodQuantity()==1) {
4794
                 * LOGGER.info("GoodQty, Serial Number {}, InventoryItem = {}, Billed on {}",
4795
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
4796
                 * inventoryItem.getUpdateTimestamp()); } else
4797
                 * if(inventoryItem.getBadQuantity()==1){
4798
                 * LOGGER.info("Bad Qty, Serial Number {}, InventoryItem = {}, Billed on {}",
4799
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
4800
                 * inventoryItem.getUpdateTimestamp()); } else if
4801
                 * (inventoryItem.getLastScanType().equals(ScanType.SALE)) { LOGGER.
4802
                 * info("Problem Sold, Serial Number {}, InventoryItem = {}, Billed on {}",
4803
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
4804
                 * inventoryItem.getUpdateTimestamp()); }
4805
                 */
31886 tejbeer 4806
                if (inventoryItem.getLastScanType().equals(ScanType.SALE) || inventoryItem.getLastScanType().equals(ScanType.SALE_RET)) {
4807
                    Map<String, Double> map = schemeInOuts.stream().collect(
4808
                            groupingBy(
4809
                                    x -> DateTimeFormatter.ofPattern("yyyyMMddHH").format(x.getCreateTimestamp()) + "- " + x.getSchemeId(), Collectors.summingDouble(x -> x.getAmount())));
33452 amit.gupta 4810
                    for (Entry<String, Double> entry : map.entrySet()) {
31697 amit.gupta 4811
                        LOGGER.info("{} = {}", entry.getKey(), entry.getValue());
4812
                    }
31886 tejbeer 4813
                    LOGGER.info("id- {}, imei- {}, lastScan = {}, Scheme sum - {}", inventoryItem.getId(), inventoryItem.getSerialNumber(), inventoryItem.getLastScanType(), schemeSum);
31697 amit.gupta 4814
                }
4815
            }
4816
        }
29441 tejbeer 4817
 
31697 amit.gupta 4818
    }
29308 tejbeer 4819
 
31697 amit.gupta 4820
    public static String readFileAsString(String file) throws Exception {
4821
        String data = "";
4822
        data = new String(Files.readAllBytes(Paths.get(file)));
4823
        return data;
4824
    }
29308 tejbeer 4825
 
4826
 
31697 amit.gupta 4827
    public void partnerWiseCreditAccount() throws Exception {
29814 tejbeer 4828
 
31697 amit.gupta 4829
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
29814 tejbeer 4830
 
31697 amit.gupta 4831
        for (FofoStore fs : fofoStores) {
29835 tejbeer 4832
 
31697 amit.gupta 4833
            if (fs.getPan() != null) {
4834
                AccountStatusResponseOut accountStatusResponseOut = mandiiService.getStatus(fs.getPan());
29835 tejbeer 4835
 
31697 amit.gupta 4836
                LOGGER.info("accountStatusResponseOut" + accountStatusResponseOut);
31886 tejbeer 4837
                CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fs.getId(), Gateway.MANDII);
29817 tejbeer 4838
 
31697 amit.gupta 4839
                if (creditAccount == null) {
29835 tejbeer 4840
 
31697 amit.gupta 4841
                    creditAccount = new CreditAccount();
29835 tejbeer 4842
 
31697 amit.gupta 4843
                    creditAccount.setFofoId(fs.getId());
4844
                    creditAccount.setGateway(Gateway.MANDII);
29817 tejbeer 4845
 
31697 amit.gupta 4846
                }
29814 tejbeer 4847
 
31697 amit.gupta 4848
                if (accountStatusResponseOut == null) {
4849
                    creditAccount.setCreditStatus(CreditStatus.UNKNOWN);
4850
                    creditAccount.setDescription("User company not found");
30421 tejbeer 4851
 
31697 amit.gupta 4852
                } else {
4853
                    if (accountStatusResponseOut.getSanctionLimit() != null) {
4854
                        creditAccount.setSanctionedAmount(accountStatusResponseOut.getSanctionLimit().floatValue());
4855
                    } else {
4856
                        creditAccount.setSanctionedAmount(0);
4857
                    }
30421 tejbeer 4858
 
31697 amit.gupta 4859
                    creditAccount.setInterestRate(accountStatusResponseOut.getRateOfInterest());
4860
                    if (accountStatusResponseOut.getBalanceAmount() != null) {
4861
                        creditAccount.setAvailableAmount(accountStatusResponseOut.getBalanceAmount().floatValue());
4862
                    } else {
4863
                        creditAccount.setAvailableAmount(0);
4864
                    }
30421 tejbeer 4865
 
31697 amit.gupta 4866
                    if (accountStatusResponseOut.getCurrentStage() != null) {
4867
                        creditAccount.setDescription(accountStatusResponseOut.getCurrentStage().toString());
4868
                    }
4869
                    if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.SANCTION_AVAILABLE)) {
4870
                        creditAccount.setCreditStatus(CreditStatus.SANCTIONED);
4871
                    } else if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.IN_ELIGIBLE)) {
4872
                        creditAccount.setCreditStatus(CreditStatus.INELIGIBLE);
4873
                    } else {
30421 tejbeer 4874
 
31697 amit.gupta 4875
                        creditAccount.setCreditStatus(CreditStatus.TO_BE_EVALUATED);
4876
                    }
4877
                }
30421 tejbeer 4878
 
31697 amit.gupta 4879
                creditAccount.setUpdatedOn(LocalDateTime.now());
4880
                creditAccountRepository.persist(creditAccount);
4881
            }
4882
        }
4883
    }
30421 tejbeer 4884
 
31697 amit.gupta 4885
    @Autowired
4886
    private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
30421 tejbeer 4887
 
32832 amit.gupta 4888
    //RBM L2 Escalations
32482 amit.gupta 4889
    public void reviewUncontactablePartner() throws
4890
            ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
30421 tejbeer 4891
 
31697 amit.gupta 4892
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
30421 tejbeer 4893
 
32832 amit.gupta 4894
        List<Integer> partnerLastCollectionRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(customRetailerMap.keySet()));
30859 tejbeer 4895
 
32832 amit.gupta 4896
        if (!partnerLastCollectionRemarkIds.isEmpty()) {
4897
            List<PartnerCollectionRemark> partnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(partnerLastCollectionRemarkIds);
30421 tejbeer 4898
 
33064 ranu 4899
            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 4900
            Map<Integer, PartnerCollectionRemark> salesEscalatedRemarksMap = partnerCollectionRemarks.stream().filter(x -> x.getRemark().equals(CollectionRemark.SALES_ESCALATION)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30859 tejbeer 4901
 
32832 amit.gupta 4902
 
4903
            if (!rbmEscalatedRemarksMap.isEmpty()) {
4904
                //
33452 amit.gupta 4905
                for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM), true).entrySet()) {
32832 amit.gupta 4906
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
4907
                            .map(x -> rbmEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
4908
                    String subject = "Partners escalated to RBM-L2";
4909
                    String messageText = this.getMessageForRBMEscalatedPartners(filteredRows);
4910
 
31697 amit.gupta 4911
                    MimeMessage message = mailSender.createMimeMessage();
4912
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
4913
                    String[] email = new String[]{storeGuyEntry.getKey()};
30859 tejbeer 4914
 
31697 amit.gupta 4915
                    helper.setSubject(subject);
4916
                    helper.setText(messageText, true);
4917
                    helper.setTo(email);
31886 tejbeer 4918
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
31697 amit.gupta 4919
                    helper.setFrom(senderAddress);
4920
                    mailSender.send(message);
30859 tejbeer 4921
 
31697 amit.gupta 4922
                    LOGGER.info("filteredRows {}", filteredRows);
30859 tejbeer 4923
 
31697 amit.gupta 4924
                }
4925
            }
32832 amit.gupta 4926
            if (!salesEscalatedRemarksMap.isEmpty()) {
4927
                //
33452 amit.gupta 4928
                for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_RBM), true).entrySet()) {
32832 amit.gupta 4929
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
4930
                            .map(x -> salesEscalatedRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
4931
                    String subject = "Partners escalated to Sales";
4932
                    String messageText = this.getMessageForSalesEscalatedPartners(filteredRows);
30936 tejbeer 4933
 
32832 amit.gupta 4934
                    MimeMessage message = mailSender.createMimeMessage();
4935
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
4936
                    String[] email = new String[]{storeGuyEntry.getKey()};
4937
 
4938
                    helper.setSubject(subject);
4939
                    helper.setText(messageText, true);
4940
                    helper.setTo(email);
4941
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
4942
                    helper.setFrom(senderAddress);
4943
                    mailSender.send(message);
4944
 
4945
                    LOGGER.info("filteredRows {}", filteredRows);
4946
 
4947
                }
4948
            }
4949
 
31697 amit.gupta 4950
        }
4951
    }
30936 tejbeer 4952
 
33078 ranu 4953
 
31697 amit.gupta 4954
    @Autowired
33078 ranu 4955
    private NonSdBuyingRepository nonSdBuyingRepository;
4956
 
4957
    //Non Sd Buying
4958
    public void reviewNonSdBuyingBrand() throws
4959
            ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
4960
        List<NonSdBuying> nonSdByuingActiveList = nonSdBuyingRepository.selectAllActiveNonSDBuyingList(true);
4961
        Map<Integer, NonSdBuying> unAuthorizedBuyingMap = nonSdByuingActiveList.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
4962
 
4963
        if (!unAuthorizedBuyingMap.isEmpty()) {
33452 amit.gupta 4964
            for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES), true).entrySet()) {
33078 ranu 4965
                List<NonSdBuying> unAuthorizedfilteredRows = storeGuyEntry.getValue().stream()
4966
                        .map(x -> unAuthorizedBuyingMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
33112 amit.gupta 4967
                if (!unAuthorizedfilteredRows.isEmpty()) {
33078 ranu 4968
                    String subject = "Unauthorized Buying";
4969
                    String messageText = this.getMessageForUnauthorizedBuying(unAuthorizedfilteredRows);
4970
 
4971
                    MimeMessage message = mailSender.createMimeMessage();
4972
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
4973
                    String[] email = new String[]{storeGuyEntry.getKey()};
33112 amit.gupta 4974
                    // String[] email = {"ranu.rajput@smartdukaan.com"};
33078 ranu 4975
 
4976
                    helper.setSubject(subject);
4977
                    helper.setText(messageText, true);
4978
                    helper.setTo(email);
4979
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
4980
                    helper.setFrom(senderAddress);
4981
                    mailSender.send(message);
4982
                    LOGGER.info("unAuthorizedfilteredRows {}", unAuthorizedfilteredRows);
4983
                }
4984
 
4985
 
4986
            }
4987
 
4988
        }
4989
    }
4990
 
4991
    @Autowired
31697 amit.gupta 4992
    private LoanRepository loanRepository;
31020 tejbeer 4993
 
31697 amit.gupta 4994
    @Autowired
4995
    private LoanStatementRepository loanStatementRepository;
30859 tejbeer 4996
 
31697 amit.gupta 4997
    @Autowired
4998
    private SDCreditService sdCreditService;
30859 tejbeer 4999
 
31697 amit.gupta 5000
    @Autowired
5001
    private SDCreditRequirementRepository sdCreditRequirementRepository;
30859 tejbeer 5002
 
31697 amit.gupta 5003
    @Autowired
5004
    private CurrentPartnerDailyInvestmentRepository currentPartnerDailyInvestmentRepository;
30859 tejbeer 5005
 
31697 amit.gupta 5006
    @Autowired
5007
    private TransactionRepository transactionRepository;
30859 tejbeer 5008
 
31697 amit.gupta 5009
    @Autowired
5010
    private SanctionRequestRepository sanctionRequestRepository;
30859 tejbeer 5011
 
31697 amit.gupta 5012
    public void calculateInterestAccured() throws ProfitMandiBusinessException {
5013
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30859 tejbeer 5014
 
32724 amit.gupta 5015
        for (Loan loan : loans) {
5016
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
5017
            Map<LoanReferenceType, Double> loanStatusAmount = loanStatements.stream().collect(groupingBy(
5018
                    x -> x.getLoanReferenceType(), Collectors.summingDouble(x -> x.getAmount().doubleValue())));
30936 tejbeer 5019
 
32724 amit.gupta 5020
            int freeDays = loan.getFreeDays();
30936 tejbeer 5021
 
32724 amit.gupta 5022
            LocalDateTime freeDaysLimitDate = loan.getCreatedOn().plusDays(freeDays);
30936 tejbeer 5023
 
32724 amit.gupta 5024
            LOGGER.info("freeDaysLimitDate {}", freeDaysLimitDate);
5025
            if (LocalDateTime.now().isAfter(freeDaysLimitDate)) {
5026
                int loanStatementId = loanStatementRepository.selectLatestLoanSatement(loan.getFofoId(), loan.getId());
5027
                LOGGER.info("loanStatementId {}", loanStatementId);
5028
                if (loanStatementId != 0) {
5029
                    this.calculateInterest(loan, loanStatusAmount, loanStatementId);
31697 amit.gupta 5030
                } else {
32724 amit.gupta 5031
                    sdCreditService.addInterest(freeDaysLimitDate.toLocalDate(), LocalDate.now(), loan, loanStatusAmount);
31697 amit.gupta 5032
                }
32724 amit.gupta 5033
            }
31518 amit.gupta 5034
 
31697 amit.gupta 5035
        }
30936 tejbeer 5036
 
32724 amit.gupta 5037
 
31697 amit.gupta 5038
    }
30936 tejbeer 5039
 
31697 amit.gupta 5040
    @Autowired
5041
    FofoPaymentRepository fofoPaymentRepository;
30936 tejbeer 5042
 
31697 amit.gupta 5043
    @Autowired
5044
    CCAvenuePaymentService ccAvenuePaymentService;
30936 tejbeer 5045
 
31697 amit.gupta 5046
    public void settleCCAvePayments() throws Exception {
31886 tejbeer 5047
        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 5048
        for (FofoPayment fofoPayment : fofoPayments) {
5049
            ccAvenuePaymentService.updatePayment(fofoPayment);
5050
        }
5051
    }
30859 tejbeer 5052
 
31697 amit.gupta 5053
    /*
5054
     * public void getCCAvenuePendingOrderStatus(int pendingOrderId) { PendingOrder
5055
     * pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
5056
     * ccAvenuePaymentService.getPaymentStatusMap(pendingOrder); }
5057
     */
30859 tejbeer 5058
 
32482 amit.gupta 5059
    private void calculateInterest(Loan loan, Map<LoanReferenceType, Double> loanStatusAmount,
5060
                                   int loanStatementId) throws ProfitMandiBusinessException {
31697 amit.gupta 5061
        LoanStatement loanStatement = loanStatementRepository.selectById(loanStatementId);
30859 tejbeer 5062
 
31697 amit.gupta 5063
        if (loanStatement.getLoanId() == loan.getId()) {
30859 tejbeer 5064
 
31886 tejbeer 5065
            sdCreditService.addInterest(loanStatement.getCreatedAt().toLocalDate(), LocalDate.now(), loan, loanStatusAmount);
30859 tejbeer 5066
 
31697 amit.gupta 5067
        } else {
5068
            throw new ProfitMandiBusinessException("loanstament", loanStatement.getLoanId(), "Invalid LoanId");
5069
        }
5070
    }
31175 tejbeer 5071
 
31697 amit.gupta 5072
    public void loanSettlement() throws Exception {
33664 amit.gupta 5073
        List<Loan> blockedLoans = loanRepository.selectAllActiveLoan().stream().filter(x -> x.getFreeDays() >= 365).collect(toList());
5074
        List<Loan> loans = loanRepository.selectAllActiveLoan().stream().filter(x -> x.getFreeDays() < 365).collect(toList());
5075
        //Settle blocked loans only when normal loans are settled
5076
        loans.addAll(blockedLoans);
30859 tejbeer 5077
 
31697 amit.gupta 5078
        if (!loans.isEmpty()) {
30859 tejbeer 5079
 
31697 amit.gupta 5080
            for (Loan loan : loans) {
33664 amit.gupta 5081
                double settledAmount = sdCreditService.settleLoan(loan);
31020 tejbeer 5082
 
33664 amit.gupta 5083
                List<SanctionRequest> sanctionRequests = sanctionRequestRepository.selectHoldSanctionByFofoId(loan.getFofoId());
5084
                for (SanctionRequest sanctionRequest : sanctionRequests) {
30859 tejbeer 5085
 
33664 amit.gupta 5086
                    List<Order> orders = orderRepository.selectAllByTransactionId(sanctionRequest.getTransactionId());
5087
                    if (orders.size() == 0) {
5088
                        LOGGER.info("Could not find orders - for Sanction Request {}", sanctionRequest);
5089
                        continue;
5090
                    }
31175 tejbeer 5091
 
33664 amit.gupta 5092
                    if (settledAmount >= sanctionRequest.getPendingAmount().doubleValue()) {
5093
                        settledAmount -= sanctionRequest.getPendingAmount().doubleValue();
5094
                        sanctionRequest.setPendingAmount(BigDecimal.valueOf(0));
5095
                        this.sendUnholdEmail(orders);
31697 amit.gupta 5096
                    } else {
33664 amit.gupta 5097
                        double pendinAmount = sanctionRequest.getPendingAmount().doubleValue() - settledAmount;
5098
                        sanctionRequest.setPendingAmount(BigDecimal.valueOf(pendinAmount));
5099
                        break;
30999 tejbeer 5100
 
31697 amit.gupta 5101
                    }
31020 tejbeer 5102
 
32439 tejbeer 5103
                }
5104
            }
31020 tejbeer 5105
 
32439 tejbeer 5106
        }
31020 tejbeer 5107
 
33664 amit.gupta 5108
 
32439 tejbeer 5109
    }
31020 tejbeer 5110
 
5111
 
32439 tejbeer 5112
    private void sendUnholdEmail(List<Order> orders) throws Exception {
30859 tejbeer 5113
 
5114
 
32439 tejbeer 5115
        orders.forEach(x -> x.setShipmentHold(false));
33452 amit.gupta 5116
        orders = orders.stream().filter(x -> x.getRefundTimestamp() != null).collect(Collectors.toList());
33506 amit.gupta 5117
        if (orders.size() > 0) {
33427 amit.gupta 5118
 
33664 amit.gupta 5119
            double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));
30859 tejbeer 5120
 
33506 amit.gupta 5121
            List<String> authUserEmail = csService.getAuthUserIdByPartnerId(orders.get(0).getRetailerId()).stream().map(x -> x.getEmailId()).collect(Collectors.toList());
5122
            authUserEmail.add("vinay.p@smartdukaan.com");
5123
            authUserEmail.add("shivam.gupta@smartdukaan.com");
30859 tejbeer 5124
 
33506 amit.gupta 5125
            String[] emailTo = authUserEmail.toArray(new String[authUserEmail.size()]);
30859 tejbeer 5126
 
33506 amit.gupta 5127
            String[] ccTo = {"tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com"};
30859 tejbeer 5128
 
33664 amit.gupta 5129
            String subject = "Dispatch held orders of - " + (orders.get(0).getRetailerName());
5130
            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.");
5131
            Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
33506 amit.gupta 5132
        }
30859 tejbeer 5133
 
32439 tejbeer 5134
 
31697 amit.gupta 5135
    }
30859 tejbeer 5136
 
32307 amit.gupta 5137
    public void dailyLoanAlert() throws Exception {
31697 amit.gupta 5138
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30859 tejbeer 5139
 
31697 amit.gupta 5140
        Map<Integer, Double> partnerLoanAmount = new HashMap<>();
30859 tejbeer 5141
 
31697 amit.gupta 5142
        if (!loans.isEmpty()) {
30859 tejbeer 5143
 
31697 amit.gupta 5144
            for (Loan loan : loans) {
30859 tejbeer 5145
 
31697 amit.gupta 5146
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30859 tejbeer 5147
 
31886 tejbeer 5148
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31697 amit.gupta 5149
                if (partnerLoanAmount.get(loan.getFofoId()) != null) {
5150
                    amount += partnerLoanAmount.get(loan.getFofoId());
5151
                    partnerLoanAmount.put(loan.getFofoId(), amount);
5152
                } else {
5153
                    partnerLoanAmount.put(loan.getFofoId(), amount);
5154
                }
30965 tejbeer 5155
 
31697 amit.gupta 5156
            }
30965 tejbeer 5157
 
31697 amit.gupta 5158
        }
30859 tejbeer 5159
 
31697 amit.gupta 5160
        if (!partnerLoanAmount.isEmpty()) {
30965 tejbeer 5161
 
31697 amit.gupta 5162
            for (Entry<Integer, Double> partnerLoanAmountEnrty : partnerLoanAmount.entrySet()) {
30859 tejbeer 5163
 
31697 amit.gupta 5164
                int fofoId = partnerLoanAmountEnrty.getKey();
30859 tejbeer 5165
 
31697 amit.gupta 5166
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
30859 tejbeer 5167
 
31697 amit.gupta 5168
                Address address = addressRepository.selectById(user.getAddressId());
30896 amit.gupta 5169
 
31697 amit.gupta 5170
                String title = "Alert Credit Outstanding!";
5171
                String url = "http://app.smartdukaan.com/pages/home/credit";
31886 tejbeer 5172
                String message = "Your total pending Loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(partnerLoanAmountEnrty.getValue())) + ".";
31697 amit.gupta 5173
                notificationService.sendNotification(fofoId, title, MessageType.notification, title, message, url);
30913 tejbeer 5174
 
32841 amit.gupta 5175
                //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30913 tejbeer 5176
 
31697 amit.gupta 5177
            }
30917 tejbeer 5178
 
31697 amit.gupta 5179
        }
30917 tejbeer 5180
 
31697 amit.gupta 5181
    }
30920 tejbeer 5182
 
31697 amit.gupta 5183
    public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
5184
        schemeService.processActivatedImeisForSchemes();
5185
    }
30920 tejbeer 5186
 
33112 amit.gupta 5187
    @Autowired
33355 amit.gupta 5188
    SidbiService sidbiService;
33112 amit.gupta 5189
 
33364 amit.gupta 5190
    public void processSidbiDeductions() throws ProfitMandiBusinessException {
33434 amit.gupta 5191
        //sidbiService.migrateSanctions();
33355 amit.gupta 5192
        sidbiService.processDeductions();
5193
    }
5194
 
31697 amit.gupta 5195
    public void updatePartnerLimit() throws ProfitMandiBusinessException {
5196
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
33355 amit.gupta 5197
        Map<Integer, BigDecimal> fofoSidbiLimitMap = sidbiService.getSuggestedLimitMap();
31886 tejbeer 5198
        Map<Integer, SDCreditRequirement> sdCreditRequirementMap = sdCreditRequirementRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
33159 amit.gupta 5199
        Map<Integer, CreditAccount> creditAccountMap = creditAccountRepository.selectAllByGateways(Arrays.asList(Gateway.SIDBI, Gateway.SDDIRECT))
33112 amit.gupta 5200
                .stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31886 tejbeer 5201
        Map<Integer, CurrentPartnerDailyInvestment> currentPartnerDailyInvestmentMap = currentPartnerDailyInvestmentRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31697 amit.gupta 5202
        for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
5203
            int fofoId = customRetailerEntry.getKey();
5204
            LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
33287 amit.gupta 5205
 
33112 amit.gupta 5206
            CreditAccount creditAccount = creditAccountMap.get(fofoId);
5207
 
31697 amit.gupta 5208
            CurrentPartnerDailyInvestment currentPartnerDailyInvestment = currentPartnerDailyInvestmentMap.get(fofoId);
33355 amit.gupta 5209
            BigDecimal suggestedAmount = this.getSuggestedAmount(creditAccount, currentPartnerDailyInvestment, fofoSidbiLimitMap.get(fofoId));
33112 amit.gupta 5210
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementMap.get(fofoId);
30929 tejbeer 5211
 
31697 amit.gupta 5212
            LOGGER.info("suggestedAmount {} ", suggestedAmount);
30913 tejbeer 5213
 
31697 amit.gupta 5214
            if (sdCreditRequirement == null) {
5215
                sdCreditRequirement = new SDCreditRequirement();
5216
                sdCreditRequirement.setFofoId(fofoId);
5217
                sdCreditRequirement.setCreditDays(15);
33452 amit.gupta 5218
                sdCreditRequirement.setInterestRate(ProfitMandiConstants.NEW_INTEREST_RATE);
31697 amit.gupta 5219
                sdCreditRequirement.setRisk(CreditRisk.HIGH_RISK);
5220
                sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
5221
                sdCreditRequirement.setCreateTimestamp(LocalDateTime.now());
5222
                sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
5223
                sdCreditRequirementRepository.persist(sdCreditRequirement);
5224
            }
30913 tejbeer 5225
 
31697 amit.gupta 5226
            CreditRisk creditRisk = sdCreditService.getCurrentRisk(sdCreditRequirement, firstBillingDate);
30913 tejbeer 5227
 
31697 amit.gupta 5228
            sdCreditRequirement.setRisk(creditRisk);
30913 tejbeer 5229
 
31697 amit.gupta 5230
            sdCreditRequirement.setSuggestedLimit(suggestedAmount);
5231
            sdCreditRequirement.setLimit(suggestedAmount);
5232
            BigDecimal utilizedLimit = new BigDecimal(sdCreditService.getUtilizationAmount(fofoId));
30934 tejbeer 5233
 
31697 amit.gupta 5234
            BigDecimal availableLimit = sdCreditRequirement.getLimit().subtract(utilizedLimit);
30934 tejbeer 5235
 
31697 amit.gupta 5236
            LOGGER.info("utilizedLimit {} ", utilizedLimit);
30913 tejbeer 5237
 
31697 amit.gupta 5238
            LOGGER.info("availableLimit {} ", availableLimit);
30913 tejbeer 5239
 
31697 amit.gupta 5240
            sdCreditRequirement.setUtilizedAmount(utilizedLimit);
30929 tejbeer 5241
 
31697 amit.gupta 5242
            sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
30929 tejbeer 5243
 
31697 amit.gupta 5244
            if (creditAccount != null) {
30929 tejbeer 5245
 
31697 amit.gupta 5246
                creditAccount.setInterestRate(sdCreditRequirement.getInterestRate().floatValue());
5247
                creditAccount.setSanctionedAmount(sdCreditRequirement.getLimit().floatValue());
5248
                creditAccount.setAvailableAmount(availableLimit.floatValue());
5249
                creditAccount.setFreeDays(sdCreditRequirement.getFreeDays());
5250
                creditAccount.setUpdatedOn(LocalDateTime.now());
5251
            }
30929 tejbeer 5252
 
31697 amit.gupta 5253
        }
31177 tejbeer 5254
 
31697 amit.gupta 5255
    }
30929 tejbeer 5256
 
33355 amit.gupta 5257
    private BigDecimal getSuggestedAmount(CreditAccount creditAccount, CurrentPartnerDailyInvestment currentPartnerDailyInvestment, BigDecimal sidbiLimit) {
33112 amit.gupta 5258
        BigDecimal suggestedAmount = BigDecimal.ZERO;
5259
        //1 LAC
5260
        double limitValue = 100000;
33295 amit.gupta 5261
        if (creditAccount == null || creditAccount.getGateway().equals(Gateway.SDDIRECT)) {
33112 amit.gupta 5262
 
5263
            if (currentPartnerDailyInvestment != null) {
5264
                suggestedAmount = BigDecimal.valueOf(Math.min(currentPartnerDailyInvestment.getTotalInvestment() * 0.1, limitValue));
5265
            }
5266
            if (suggestedAmount.doubleValue() < 0) {
5267
                suggestedAmount = BigDecimal.ZERO;
5268
            }
33355 amit.gupta 5269
        } else if (creditAccount.getGateway().equals(Gateway.SIDBI) && sidbiLimit != null) {
33112 amit.gupta 5270
            //Left
33355 amit.gupta 5271
            suggestedAmount = sidbiLimit;
33112 amit.gupta 5272
        }
5273
        return suggestedAmount;
5274
    }
5275
 
31697 amit.gupta 5276
    public void notifyDefaultLoans() throws ProfitMandiBusinessException, MessagingException, IOException {
30929 tejbeer 5277
 
31697 amit.gupta 5278
        sdCreditService.updateRisk();
5279
        List<Loan> defaultLoans = sdCreditService.getDefaultLoan();
5280
        if (!defaultLoans.isEmpty()) {
5281
            this.sendDefaultLoanAlert(defaultLoans);
5282
        }
30929 tejbeer 5283
 
31697 amit.gupta 5284
    }
30929 tejbeer 5285
 
32482 amit.gupta 5286
    public void sendDefaultLoanAlert(List<Loan> defaultLoans) throws
5287
            ProfitMandiBusinessException, MessagingException, IOException {
31697 amit.gupta 5288
        String subject = "Default Partners";
30931 tejbeer 5289
 
31886 tejbeer 5290
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
30929 tejbeer 5291
 
33452 amit.gupta 5292
        for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
31697 amit.gupta 5293
            List<Loan> filteredRows = new ArrayList<>();
5294
            for (Loan loan : defaultLoans) {
30929 tejbeer 5295
 
31697 amit.gupta 5296
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30929 tejbeer 5297
 
31697 amit.gupta 5298
                    filteredRows.add(loan);
5299
                }
5300
            }
5301
            if (!filteredRows.isEmpty()) {
33628 tejus.loha 5302
                String[] email = new String[]{storeGuyEntry.getKey()};
31697 amit.gupta 5303
                String messageText = this.getMessageForDueDateExtend(filteredRows);
32350 amit.gupta 5304
                this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, subject);
30982 tejbeer 5305
 
31697 amit.gupta 5306
            }
30936 tejbeer 5307
 
31697 amit.gupta 5308
        }
33628 tejus.loha 5309
        String messageText = this.getMessageForDueDateExtend(defaultLoans);
5310
        this.sendMailOfHtmlFormat(googleMailSender, new String[]{"puneet.wahi@smartdukaan.com"}, messageText, null, subject);
30982 tejbeer 5311
 
31697 amit.gupta 5312
        for (Loan defaultLoan : defaultLoans) {
5313
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
30929 tejbeer 5314
 
31886 tejbeer 5315
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 5316
 
31697 amit.gupta 5317
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
30936 tejbeer 5318
 
31697 amit.gupta 5319
            Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 5320
 
31697 amit.gupta 5321
            String title = "Loan Amount Overdue!";
5322
            String url = "http://app.smartdukaan.com/pages/home/credit";
31886 tejbeer 5323
            String message = "Your loan due date " + defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + " has been exceeded. Additional penal interest of " + defaultLoan.getInterestRate().setScale(2, RoundingMode.HALF_UP) + "%  and Rs.100 shall be levied on daily basis." + " Your total pending Loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + ". !!Pay Now!!";
5324
            notificationService.sendNotification(defaultLoan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 5325
 
31697 amit.gupta 5326
            // notificationService.sendWhatsappMessage(message, title,
5327
            // address.getPhoneNumber());
30929 tejbeer 5328
 
31697 amit.gupta 5329
        }
5330
    }
30929 tejbeer 5331
 
31697 amit.gupta 5332
    private String getMessageForDueDateExtend(List<Loan> loans) throws ProfitMandiBusinessException {
33553 ranu 5333
        Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
5334
        Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
5335
        List<AST> asts = astRepository.selectAll();
5336
        Map<Integer, AST> astMap = asts.stream()
5337
                .collect(Collectors.toMap(AST::getId, ast -> ast));
31697 amit.gupta 5338
        StringBuilder sb = new StringBuilder();
5339
        sb.append(
33553 ranu 5340
                "<html><body><p>Alert</p><p>Default Partners :-</p>" + "<br/><p>EveryDay Rs.100 charged as Penalty</p>" + "<br/>" +
5341
                        "<table style='border:1px solid black ;padding: 5px';>");
5342
        sb.append("<tbody>\n" +
5343
                "<tr>\n" +
5344
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" +
33555 ranu 5345
                "<th style='border:1px solid black;padding: 5px'>State Name</th>\n" +
5346
                "<th style='border:1px solid black;padding: 5px'>Area</th>\n" +
5347
                "<th style='border:1px solid black;padding: 5px'>Territory</th>\n" +
33553 ranu 5348
                "<th style='border:1px solid black;padding: 5px'>due date</th>\n" +
5349
                "<th style='border:1px solid black;padding: 5px'>Days</th>\n" +
33664 amit.gupta 5350
                "<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n" +
33553 ranu 5351
                "<th style='border:1px solid black;padding: 5px'>RBM L1</th>\n" +
5352
                "<th style='border:1px solid black;padding: 5px'>RBM L2</th>\n" +
5353
                "<th style='border:1px solid black;padding: 5px'>Sales L1</th>\n" +
5354
                "<th style='border:1px solid black;padding: 5px'>Sales L2</th>\n" +
5355
                "</tr>");
31697 amit.gupta 5356
        for (Loan entry : loans) {
30929 tejbeer 5357
 
31697 amit.gupta 5358
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
30929 tejbeer 5359
 
31886 tejbeer 5360
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 5361
 
31697 amit.gupta 5362
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
30929 tejbeer 5363
 
31697 amit.gupta 5364
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30929 tejbeer 5365
 
31697 amit.gupta 5366
            sb.append("<tr>");
31886 tejbeer 5367
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
33555 ranu 5368
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getAddress().getState() + "</td>");
5369
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getArea() + "</td>");
5370
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getTerritory() + "</td>");
31886 tejbeer 5371
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 5372
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 5373
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
33553 ranu 5374
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager() + "</td>");
5375
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager() + "</td>");
5376
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager() + "</td>");
5377
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager() + "</td>");
31397 tejbeer 5378
 
33555 ranu 5379
 
31697 amit.gupta 5380
            sb.append("</tr>");
31397 tejbeer 5381
 
31697 amit.gupta 5382
        }
31397 tejbeer 5383
 
31697 amit.gupta 5384
        sb.append("</tbody></table></body></html>");
31397 tejbeer 5385
 
31697 amit.gupta 5386
        return sb.toString();
5387
    }
31397 tejbeer 5388
 
31697 amit.gupta 5389
    private String getMessageForDueDateCross(List<Loan> loans) throws ProfitMandiBusinessException {
33161 ranu 5390
        Map<Integer, com.spice.profitmandi.dao.model.FofoReportingModel> fofoReportingModelMap = csService.getPartnerIdSalesHeaders();
33452 amit.gupta 5391
        Map<Integer, FofoRBMReportingModel> fofoRbmReportingModelMap = csService.getPartnerIdRBMHeaders();
33553 ranu 5392
        List<AST> asts = astRepository.selectAll();
5393
        Map<Integer, AST> astMap = asts.stream()
5394
                .collect(Collectors.toMap(AST::getId, ast -> ast));
5395
 
31697 amit.gupta 5396
        StringBuilder sb = new StringBuilder();
33161 ranu 5397
        sb.append("<html><body><p>Alert</p><p>Due Date Cross Partners :-</p>" + "<br/><p>Additional penal interest of  shall be levied on daily basis.</p>" + "<br/>" +
5398
                "<table style='border:1px solid black ;padding: 5px';>");
5399
        sb.append("<tbody>\n" + "<tr>\n" +
33256 amit.gupta 5400
                "<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" +
5401
                "<th style='border:1px solid black;padding: 5px'>State Name</th>\n" +
33555 ranu 5402
                "<th style='border:1px solid black;padding: 5px'>Area</th>\n" +
33553 ranu 5403
                "<th style='border:1px solid black;padding: 5px'>Territory</th>\n" +
33256 amit.gupta 5404
                "<th style='border:1px solid black;padding: 5px'>due date</th>\n" +
5405
                "<th style='border:1px solid black;padding: 5px'>Days</th>\n" +
5406
                "<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n" +
5407
                "<th style='border:1px solid black;padding: 5px'>RBM L1</th>\n" +
5408
                "<th style='border:1px solid black;padding: 5px'>RBM L2</th>\n" +
5409
                "<th style='border:1px solid black;padding: 5px'>Sales L1</th>\n" +
5410
                "<th style='border:1px solid black;padding: 5px'>Sales L2</th>\n" +
33161 ranu 5411
                "</tr>");
31397 tejbeer 5412
 
31697 amit.gupta 5413
        for (Loan entry : loans) {
31397 tejbeer 5414
 
31697 amit.gupta 5415
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
31397 tejbeer 5416
 
31886 tejbeer 5417
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31397 tejbeer 5418
 
31697 amit.gupta 5419
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
31397 tejbeer 5420
 
31697 amit.gupta 5421
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
31397 tejbeer 5422
 
31697 amit.gupta 5423
            sb.append("<tr>");
31886 tejbeer 5424
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
33162 ranu 5425
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getAddress().getState() + "</td>");
33553 ranu 5426
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getArea() + "</td>");
5427
            sb.append("<td style='border:1px solid black;padding: 5px'>" + astMap.get(customRetailer.getAstId()).getTerritory() + "</td>");
30936 tejbeer 5428
 
31886 tejbeer 5429
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 5430
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 5431
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
33161 ranu 5432
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL1Manager() + "</td>");
5433
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoRbmReportingModelMap.get(entry.getFofoId()).getL2Manager() + "</td>");
5434
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getTerritoryManager() + "</td>");
5435
            sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoReportingModelMap.get(entry.getFofoId()).getRegionalManager() + "</td>");
31697 amit.gupta 5436
            sb.append("</tr>");
5437
        }
31397 tejbeer 5438
 
31697 amit.gupta 5439
        sb.append("</tbody></table></body></html>");
31397 tejbeer 5440
 
31697 amit.gupta 5441
        return sb.toString();
5442
    }
31397 tejbeer 5443
 
32307 amit.gupta 5444
    public void notifyLoanDueDateCross() throws Exception {
31397 tejbeer 5445
 
31697 amit.gupta 5446
        List<Loan> dueDateCrossLoans = sdCreditService.getDueDateCrossLoan();
5447
        if (!dueDateCrossLoans.isEmpty()) {
5448
            this.sendDueDateCrossLoanAlert(dueDateCrossLoans);
5449
        }
31397 tejbeer 5450
 
31697 amit.gupta 5451
    }
31397 tejbeer 5452
 
32307 amit.gupta 5453
    private void sendDueDateCrossLoanAlert(List<Loan> dueDateCrossLoans) throws Exception {
31886 tejbeer 5454
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
31397 tejbeer 5455
 
33452 amit.gupta 5456
        for (Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
33631 tejus.loha 5457
            List<Loan> filteredRows = new ArrayList<>();
31697 amit.gupta 5458
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 5459
 
31697 amit.gupta 5460
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30982 tejbeer 5461
 
31697 amit.gupta 5462
                    filteredRows.add(loan);
5463
                }
5464
            }
5465
            if (!filteredRows.isEmpty()) {
5466
                String messageText = this.getMessageForDueDateCross(filteredRows);
33628 tejus.loha 5467
                String[] email = new String[]{storeGuyEntry.getKey()};
30982 tejbeer 5468
 
32350 amit.gupta 5469
                this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, "Due Date Cross");
30936 tejbeer 5470
 
31697 amit.gupta 5471
            }
30936 tejbeer 5472
 
31697 amit.gupta 5473
        }
33631 tejus.loha 5474
        String messageText = this.getMessageForDueDateCross(dueDateCrossLoans);
33628 tejus.loha 5475
        this.sendMailOfHtmlFormat(googleMailSender, new String[]{"puneet.wahi@smartdukaan.com"}, messageText, null, "Due Date Cross");
5476
 
5477
 
31697 amit.gupta 5478
        if (!dueDateCrossLoans.isEmpty()) {
5479
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 5480
 
31697 amit.gupta 5481
                long noOfdaysBetween = ChronoUnit.DAYS.between(loan.getDueDate().toLocalDate(), LocalDate.now());
30989 tejbeer 5482
 
31697 amit.gupta 5483
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30989 tejbeer 5484
 
31697 amit.gupta 5485
                Address address = addressRepository.selectById(user.getAddressId());
30982 tejbeer 5486
 
31697 amit.gupta 5487
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 5488
 
31697 amit.gupta 5489
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30936 tejbeer 5490
 
31886 tejbeer 5491
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 5492
 
31697 amit.gupta 5493
                String url = "http://app.smartdukaan.com/pages/home/credit";
30936 tejbeer 5494
 
31697 amit.gupta 5495
                String title = "Alert!";
31886 tejbeer 5496
                String message = "Your loan 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 5497
 
31886 tejbeer 5498
                notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 5499
 
32841 amit.gupta 5500
                //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 5501
 
31697 amit.gupta 5502
            }
5503
        }
30982 tejbeer 5504
 
31697 amit.gupta 5505
    }
30936 tejbeer 5506
 
32307 amit.gupta 5507
    public void alertForDueDate() throws Exception {
30936 tejbeer 5508
 
31697 amit.gupta 5509
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30936 tejbeer 5510
 
31697 amit.gupta 5511
        if (!loans.isEmpty()) {
5512
            for (Loan loan : loans) {
30936 tejbeer 5513
 
31697 amit.gupta 5514
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30936 tejbeer 5515
 
31697 amit.gupta 5516
                Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 5517
 
31697 amit.gupta 5518
                long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), loan.getDueDate().toLocalDate());
30936 tejbeer 5519
 
31697 amit.gupta 5520
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 5521
 
31697 amit.gupta 5522
                if (noOfdaysBetween <= 4 && noOfdaysBetween >= 0) {
5523
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
31886 tejbeer 5524
                    double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 5525
 
31697 amit.gupta 5526
                    String title = "Alert!";
5527
                    String url = "http://app.smartdukaan.com/pages/home/credit";
5528
                    String message = null;
5529
                    if (noOfdaysBetween == 0) {
30936 tejbeer 5530
 
31886 tejbeer 5531
                        message = "Your total pending Loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + " is due for Today, Pay Now!!";
30982 tejbeer 5532
 
31697 amit.gupta 5533
                    } else {
30982 tejbeer 5534
 
31886 tejbeer 5535
                        message = "Your total pending Loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + " is due by " + loan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + " , Pay Now!!";
30982 tejbeer 5536
 
31697 amit.gupta 5537
                    }
31886 tejbeer 5538
                    notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
32841 amit.gupta 5539
                    //notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 5540
 
31697 amit.gupta 5541
                }
5542
            }
5543
        }
30984 tejbeer 5544
 
31697 amit.gupta 5545
    }
30982 tejbeer 5546
 
32307 amit.gupta 5547
    public void userMobileNumberOptIn() throws Exception {
30982 tejbeer 5548
 
31697 amit.gupta 5549
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
30982 tejbeer 5550
 
31886 tejbeer 5551
        List<com.spice.profitmandi.dao.entity.user.User> users = userUserRepository.selectByIds(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
30982 tejbeer 5552
 
31886 tejbeer 5553
        List<Address> addresses = addressRepository.selectByIds(users.stream().map(x -> x.getAddressId()).collect(Collectors.toList()));
30982 tejbeer 5554
 
31697 amit.gupta 5555
        LOGGER.info("addresses" + addresses);
30984 tejbeer 5556
 
31697 amit.gupta 5557
        for (Address address : addresses) {
32307 amit.gupta 5558
            notificationService.optIn(address.getPhoneNumber());
30982 tejbeer 5559
 
31697 amit.gupta 5560
        }
30982 tejbeer 5561
 
31697 amit.gupta 5562
    }
30982 tejbeer 5563
 
31697 amit.gupta 5564
    public void authUserMobileNumberOptIn() throws HttpHostConnectException, ProfitMandiBusinessException {
31206 tejbeer 5565
 
31697 amit.gupta 5566
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
5567
        LOGGER.info("authUsers" + authUsers);
31206 tejbeer 5568
 
31697 amit.gupta 5569
        for (AuthUser authUser : authUsers) {
5570
            Map<String, String> requestheaders = new HashMap<>();
5571
            requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
5572
            Map<String, String> requestParams = new HashMap<>();
5573
            requestParams.put("userid", String.valueOf(2000215976));
5574
            requestParams.put("password", "MFRd!BBL");
5575
            requestParams.put("phone_number", authUser.getMobileNumber());
5576
            requestParams.put("auth_scheme", "plain");
5577
            requestParams.put("v", "1.1");
5578
            requestParams.put("format", "json");
31206 tejbeer 5579
 
31697 amit.gupta 5580
            requestParams.put("method", "OPT_IN");
31206 tejbeer 5581
 
31697 amit.gupta 5582
            requestParams.put("channel", "WHATSAPP");
31886 tejbeer 5583
            String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
31697 amit.gupta 5584
            LOGGER.info("response" + response);
5585
        }
31206 tejbeer 5586
 
31697 amit.gupta 5587
    }
31206 tejbeer 5588
 
31697 amit.gupta 5589
    @Autowired
5590
    private HygieneDataRepository hygieneDataRepository;
31209 tejbeer 5591
 
31697 amit.gupta 5592
    public void hygineAlertForPartner() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 5593
 
31697 amit.gupta 5594
        List<String> remarks = new ArrayList<>();
5595
        remarks.add("Out of Service");
5596
        remarks.add("Duplicate number");
5597
        remarks.add("Partner number");
31886 tejbeer 5598
        List<HygieneData> hygieneData = hygieneDataRepository.selectAllByDisposedDateAndRemark(LocalDate.now(), remarks);
31206 tejbeer 5599
 
31697 amit.gupta 5600
        if (!hygieneData.isEmpty()) {
31206 tejbeer 5601
 
31886 tejbeer 5602
            Map<Integer, List<HygieneData>> partnerHygieneDataMap = hygieneData.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 5603
 
31697 amit.gupta 5604
            for (Entry<Integer, List<HygieneData>> partnerHygieneDataMapEntry : partnerHygieneDataMap.entrySet()) {
31206 tejbeer 5605
 
31697 amit.gupta 5606
                CustomRetailer customRetailer = retailerService.getFofoRetailer(partnerHygieneDataMapEntry.getKey());
31206 tejbeer 5607
 
31697 amit.gupta 5608
                StringBuilder sb = new StringBuilder();
31886 tejbeer 5609
                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 5610
 
31886 tejbeer 5611
                        + " </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 5612
 
31697 amit.gupta 5613
                        + "<br/><table style='border:1px solid black ;padding: 5px';>");
5614
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
5615
                sb.append("<th style='border:1px solid black;padding: 5px'>Invoice Number</th>\n");
5616
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Name</th>\n");
5617
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Number</th>\n");
5618
                sb.append("</tr>\n");
31206 tejbeer 5619
 
31697 amit.gupta 5620
                List<HygieneData> hygienes = partnerHygieneDataMapEntry.getValue();
31206 tejbeer 5621
 
31697 amit.gupta 5622
                List<Integer> orderIds = hygienes.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
31206 tejbeer 5623
 
31697 amit.gupta 5624
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectAllByOrderIds(orderIds);
31206 tejbeer 5625
 
31697 amit.gupta 5626
                for (FofoOrder fofoOrder : fofoOrders) {
5627
                    Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
5628
                    sb.append("<tr>");
31886 tejbeer 5629
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoOrder.getInvoiceNumber() + "</td>\n");
5630
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getFirstName() + "" + customer.getLastName() + "</td>\n");
5631
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getMobileNumber() + "</td>\n");
31206 tejbeer 5632
 
31697 amit.gupta 5633
                    sb.append("</tr>\n");
5634
                }
31206 tejbeer 5635
 
31697 amit.gupta 5636
                sb.append("</tbody></table></body></html>");
5637
                String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 5638
 
32350 amit.gupta 5639
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31206 tejbeer 5640
 
31697 amit.gupta 5641
            }
31206 tejbeer 5642
 
31697 amit.gupta 5643
        }
31206 tejbeer 5644
 
31697 amit.gupta 5645
    }
31206 tejbeer 5646
 
33046 amit.gupta 5647
    //
5648
    public void setInventoryItemIdToPriceDropImei() {
5649
        List<PriceDropIMEI> priceDropIMEIList = priceDropIMEIRepository.selectAllMissingInventoryItemIds();
5650
        LOGGER.info("Problems with - {} entries", priceDropIMEIList.size());
5651
        //priceDropIMEIList.stream().collect(C)
5652
        for (PriceDropIMEI priceDropIMEI : priceDropIMEIList) {
5653
            System.out.println(priceDropIMEI.getImei());
5654
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllBySerialNumberFofoId(priceDropIMEI.getImei(), priceDropIMEI.getPartnerId());
33051 amit.gupta 5655
            if (inventoryItems.size() == 0) {
33046 amit.gupta 5656
                LOGGER.info("Could not find Grn - FofoID {} , Imei {} ", priceDropIMEI);
33051 amit.gupta 5657
            } else if (inventoryItems.size() > 1) {
33046 amit.gupta 5658
                LOGGER.info("Found 2 such instance for - FofoID {} , Imei {} ", priceDropIMEI.getImei(), priceDropIMEI.getPartnerId());
5659
            } else {
5660
                priceDropIMEI.setInventoryItemId(inventoryItems.get(0).getId());
5661
            }
5662
 
5663
        }
5664
    }
5665
 
33051 amit.gupta 5666
    @Autowired
5667
    SaholicReservationSnapshotRepository saholicReservationSnapshotRepository;
5668
 
33256 amit.gupta 5669
    public void removePartialBillingForTransaction(int transactionId) throws ProfitMandiBusinessException {
33051 amit.gupta 5670
        List<Order> orderList = orderRepository.selectAllByTransactionId(transactionId);
5671
        Map<Integer, Order> orderMap = orderList.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
5672
        //Delete scanRecords
5673
        List<WarehouseScan> warehouseScans = warehouseScanRepository.selectAllByOrderIds(new ArrayList<>(orderMap.keySet()));
5674
        for (WarehouseScan warehouseScan : warehouseScans) {
5675
            warehouseScanRepository.delete(warehouseScan);
5676
            WarehouseInventoryItem warehouseInventoryItem = warehouseInventoryItemRepository.selectById(warehouseScan.getInventoryItemId());
5677
            warehouseInventoryItem.setLastScanType(in.shop2020.warehouse.ScanType.PURCHASE);
5678
            warehouseInventoryItem.setCurrentQuantity(warehouseInventoryItem.getCurrentQuantity() + warehouseScan.getQuantity());
5679
        }
5680
 
5681
        for (Order order : orderList) {
33078 ranu 5682
            if (order.getBillingTimestamp() != null) {
33056 amit.gupta 5683
                order.setStatus(OrderStatus.ACCEPTED);
5684
                order.setStatusDescription("Submitted for Processing");
5685
                order.setBillingTimestamp(null);
5686
                order.setBilledBy(null);
33057 amit.gupta 5687
                order.setSerialNumber(null);
33056 amit.gupta 5688
                order.setJacketNumber(null);
33060 amit.gupta 5689
                order.getLineItem().setSerialNumber(null);
33056 amit.gupta 5690
                List<LineItemImei> lineItemImeis = lineItemImeisRepository.selectByLineItemId(order.getLineItem().getId());
5691
                for (LineItemImei lineItemImei : lineItemImeis) {
5692
                    lineItemImeisRepository.delete(lineItemImei);
5693
                }
5694
                SaholicReservationSnapshot saholicReservationSnapshot = saholicReservationSnapshotRepository
5695
                        .selectByOrderId(order.getId());
5696
                if (saholicReservationSnapshot == null) {
5697
                    saholicInventoryService.addReservationCount(order.getLineItem().getItemId(),
5698
                            order.getFulfilmentWarehouseId(), order.getLineItem().getQuantity(), order.getId());
5699
                }
33055 amit.gupta 5700
            }
33051 amit.gupta 5701
        }
5702
    }
5703
 
31697 amit.gupta 5704
    public void hygineAlertForInternalTeam() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 5705
 
31697 amit.gupta 5706
        List<String> remarks = new ArrayList<>();
5707
        remarks.add("Out of Service");
5708
        remarks.add("Duplicate number");
5709
        remarks.add("Partner number");
31886 tejbeer 5710
        List<HygieneData> hygieneDataLastThreeMonth = hygieneDataRepository.selectDisposedDateAndRemarks(
5711
                LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay(), LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX), remarks);
31206 tejbeer 5712
 
31886 tejbeer 5713
        List<HygieneData> hygieneDataRecentMonth = hygieneDataRepository.selectDisposedDateAndRemarks(LocalDate.now().withDayOfMonth(1), remarks);
31697 amit.gupta 5714
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
5715
        Map<Integer, List<HygieneData>> partnerHygieneLastThreeMonthMap = null;
31206 tejbeer 5716
 
31697 amit.gupta 5717
        Map<Integer, List<HygieneData>> partnerHygieneDataRecentMonth = null;
31206 tejbeer 5718
 
31697 amit.gupta 5719
        if (!hygieneDataLastThreeMonth.isEmpty()) {
31886 tejbeer 5720
            partnerHygieneLastThreeMonthMap = hygieneDataLastThreeMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 5721
 
31697 amit.gupta 5722
        }
31206 tejbeer 5723
 
31697 amit.gupta 5724
        if (!hygieneDataRecentMonth.isEmpty()) {
31886 tejbeer 5725
            partnerHygieneDataRecentMonth = hygieneDataRecentMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31697 amit.gupta 5726
        }
31206 tejbeer 5727
 
31697 amit.gupta 5728
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31206 tejbeer 5729
 
31697 amit.gupta 5730
            String email = storeGuyEntry.getKey();
31206 tejbeer 5731
 
31697 amit.gupta 5732
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
31206 tejbeer 5733
 
31697 amit.gupta 5734
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData = new HashMap<>();
5735
            Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData = new HashMap<>();
5736
            for (Integer fofoId : fofoIds) {
31206 tejbeer 5737
 
31697 amit.gupta 5738
                partnerYearMonthData.put(fofoId, null);
5739
                partnerDateWiseData.put(fofoId, null);
5740
                if (!partnerHygieneLastThreeMonthMap.isEmpty()) {
5741
                    List<HygieneData> hygienes = partnerHygieneLastThreeMonthMap.get(fofoId);
31206 tejbeer 5742
 
31697 amit.gupta 5743
                    if (hygienes != null) {
31886 tejbeer 5744
                        Map<YearMonth, List<HygieneData>> yearMonthData = hygienes.stream().collect(groupingBy(x -> YearMonth.from(x.getDisposedTimestamp())));
31206 tejbeer 5745
 
31697 amit.gupta 5746
                        partnerYearMonthData.put(fofoId, yearMonthData);
31206 tejbeer 5747
 
31697 amit.gupta 5748
                    }
5749
                    List<HygieneData> dateWiseHygienes = partnerHygieneDataRecentMonth.get(fofoId);
31206 tejbeer 5750
 
31697 amit.gupta 5751
                    if (dateWiseHygienes != null) {
31206 tejbeer 5752
 
31886 tejbeer 5753
                        Map<LocalDate, List<HygieneData>> dateWiseData = hygienes.stream().collect(groupingBy(x -> (x.getDisposedTimestamp()).toLocalDate()));
31206 tejbeer 5754
 
31697 amit.gupta 5755
                        partnerDateWiseData.put(fofoId, dateWiseData);
31206 tejbeer 5756
 
31697 amit.gupta 5757
                    }
31206 tejbeer 5758
 
31697 amit.gupta 5759
                }
31206 tejbeer 5760
 
31697 amit.gupta 5761
            }
31206 tejbeer 5762
 
31697 amit.gupta 5763
            String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 5764
 
31697 amit.gupta 5765
            LOGGER.info("hygieneData {}", partnerDateWiseData.values());
31206 tejbeer 5766
 
31697 amit.gupta 5767
            boolean partnerDateWise = partnerDateWiseData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 5768
 
31697 amit.gupta 5769
            boolean partnerYearMonth = partnerYearMonthData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 5770
 
31697 amit.gupta 5771
            if (!partnerDateWise && !partnerYearMonth) {
5772
                String sb = this.getMessageHygieneAlertForPartner(partnerYearMonthData, partnerDateWiseData);
32350 amit.gupta 5773
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb, null, subject);
31697 amit.gupta 5774
            }
31206 tejbeer 5775
 
31697 amit.gupta 5776
        }
31206 tejbeer 5777
 
31697 amit.gupta 5778
    }
31206 tejbeer 5779
 
31697 amit.gupta 5780
    private String getMessageHygieneAlertForPartner(
33256 amit.gupta 5781
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData, Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData)
5782
            throws ProfitMandiBusinessException {
31206 tejbeer 5783
 
31697 amit.gupta 5784
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31206 tejbeer 5785
 
31697 amit.gupta 5786
        LocalDateTime startDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
5787
        LocalDateTime endDate = LocalDateTime.now();
31206 tejbeer 5788
 
31697 amit.gupta 5789
        LocalDateTime startYearMonth = LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay();
31886 tejbeer 5790
        LocalDateTime endYearMonth = LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX);
31206 tejbeer 5791
 
31697 amit.gupta 5792
        DateTimeFormatter dateYearMonthFormatter = DateTimeFormatter.ofPattern("MMM''uu");
31206 tejbeer 5793
 
31697 amit.gupta 5794
        List<YearMonth> yearMonthRange = new ArrayList<>();
5795
        yearMonthRange.add(YearMonth.from(startYearMonth));
31206 tejbeer 5796
 
31697 amit.gupta 5797
        yearMonthRange.add(YearMonth.from(startYearMonth.plusMonths(1)));
31206 tejbeer 5798
 
31697 amit.gupta 5799
        yearMonthRange.add(YearMonth.from(endYearMonth));
31206 tejbeer 5800
 
31697 amit.gupta 5801
        long noOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate.plusDays(1));
31206 tejbeer 5802
 
31886 tejbeer 5803
        List<LocalDate> dateRange = Stream.iterate(startDate.toLocalDate(), date -> date.plusDays(1)).limit(noOfDaysBetween).collect(Collectors.toList());
31206 tejbeer 5804
 
31697 amit.gupta 5805
        StringBuilder sb = new StringBuilder();
31886 tejbeer 5806
        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 5807
 
31697 amit.gupta 5808
                + "<table style='border:1px solid black ;padding: 5px';>");
5809
        sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
5810
        sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31206 tejbeer 5811
 
31697 amit.gupta 5812
        for (YearMonth yearMonth : yearMonthRange) {
31886 tejbeer 5813
            sb.append("<th style='border:1px solid black;padding: 5px'>" + yearMonth.format(dateYearMonthFormatter) + "</th>\n");
31697 amit.gupta 5814
        }
31206 tejbeer 5815
 
31697 amit.gupta 5816
        for (LocalDate localDate : dateRange) {
5817
            sb.append("<th style='border:1px solid black;padding: 5px'>" + localDate + "</th>\n");
5818
        }
31206 tejbeer 5819
 
31697 amit.gupta 5820
        sb.append("</tr>\n");
31206 tejbeer 5821
 
31886 tejbeer 5822
        for (Entry<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthEntry : partnerYearMonthData.entrySet()) {
31206 tejbeer 5823
 
31697 amit.gupta 5824
            int fofoId = partnerYearMonthEntry.getKey();
31206 tejbeer 5825
 
31697 amit.gupta 5826
            Map<YearMonth, List<HygieneData>> yearMonthData = partnerYearMonthEntry.getValue();
31206 tejbeer 5827
 
31697 amit.gupta 5828
            Map<LocalDate, List<HygieneData>> dateWiseData = partnerDateWiseData.get(fofoId);
31206 tejbeer 5829
 
31697 amit.gupta 5830
            if (yearMonthData == null && dateWiseData == null) {
5831
                continue;
5832
            }
31206 tejbeer 5833
 
31697 amit.gupta 5834
            sb.append("<tr>");
31886 tejbeer 5835
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31697 amit.gupta 5836
            for (YearMonth yearMonth : yearMonthRange) {
31206 tejbeer 5837
 
31697 amit.gupta 5838
                if (yearMonthData == null) {
5839
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 5840
 
31697 amit.gupta 5841
                } else {
5842
                    List<HygieneData> hygieneList = yearMonthData.get(yearMonth);
31206 tejbeer 5843
 
31697 amit.gupta 5844
                    if (hygieneList != null) {
5845
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31206 tejbeer 5846
 
31697 amit.gupta 5847
                    } else {
5848
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 5849
 
31697 amit.gupta 5850
                    }
5851
                }
5852
            }
31206 tejbeer 5853
 
31697 amit.gupta 5854
            for (LocalDate localDate : dateRange) {
31206 tejbeer 5855
 
31697 amit.gupta 5856
                if (dateWiseData == null) {
5857
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 5858
 
31697 amit.gupta 5859
                } else {
5860
                    List<HygieneData> hygieneList = dateWiseData.get(localDate);
31206 tejbeer 5861
 
31697 amit.gupta 5862
                    if (hygieneList != null) {
5863
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31218 tejbeer 5864
 
31697 amit.gupta 5865
                    } else {
5866
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31218 tejbeer 5867
 
31697 amit.gupta 5868
                    }
5869
                }
5870
            }
5871
            sb.append("</tr>");
31218 tejbeer 5872
 
31697 amit.gupta 5873
        }
31218 tejbeer 5874
 
31697 amit.gupta 5875
        sb.append("</tbody></table></body></html>");
31218 tejbeer 5876
 
31697 amit.gupta 5877
        return sb.toString();
5878
    }
31218 tejbeer 5879
 
31697 amit.gupta 5880
    @Autowired
5881
    private MonthlyTargetRepository monthlyTargetRepository;
31218 tejbeer 5882
 
31697 amit.gupta 5883
    public void monthlyTargetForPartner() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 5884
 
31697 amit.gupta 5885
        LocalDateTime curDate = LocalDateTime.now();
5886
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 5887
 
31886 tejbeer 5888
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 5889
 
31886 tejbeer 5890
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
5891
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 5892
 
31697 amit.gupta 5893
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 5894
 
31697 amit.gupta 5895
        for (Entry<Integer, MonthlyTarget> partnerMonthlyTargetEntry : partnersMonthlyTarget.entrySet()) {
31249 tejbeer 5896
 
31697 amit.gupta 5897
            int fofoId = partnerMonthlyTargetEntry.getKey();
31249 tejbeer 5898
 
31697 amit.gupta 5899
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
31249 tejbeer 5900
 
31697 amit.gupta 5901
            Double purchaseTarget = partnerMonthlyTargetEntry.getValue().getPurchaseTarget();
31218 tejbeer 5902
 
31697 amit.gupta 5903
            Double saleTarget = partnerMonthlyTargetEntry.getValue().getSaleTarget();
31218 tejbeer 5904
 
31697 amit.gupta 5905
            if (purchaseTarget > 0) {
5906
                Double purchase = secondaryMtd.get(fofoId);
31249 tejbeer 5907
 
31697 amit.gupta 5908
                if (purchase == null) {
5909
                    purchase = 0.0;
5910
                }
31218 tejbeer 5911
 
31697 amit.gupta 5912
                Double balanceTarget = purchaseTarget - purchase;
31218 tejbeer 5913
 
31697 amit.gupta 5914
                if (balanceTarget <= 0) {
5915
                    balanceTarget = 0.0;
5916
                }
31651 tejbeer 5917
 
31697 amit.gupta 5918
                StringBuilder sb = new StringBuilder();
5919
                sb.append("<html><body><p>Dear Partner,\n");
31886 tejbeer 5920
                sb.append("<p>Pls note your agreed monthly target is Rs." + purchaseTarget + " and your achievement till date is Rs." + purchase + "</p>");
31697 amit.gupta 5921
                sb.append("<p>Pls note that your balance target is Rs." + balanceTarget + "</p>\n");
5922
                sb.append(
32350 amit.gupta 5923
                        "<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 5924
 
32350 amit.gupta 5925
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31697 amit.gupta 5926
            }
31218 tejbeer 5927
 
31697 amit.gupta 5928
        }
31218 tejbeer 5929
 
31697 amit.gupta 5930
    }
31218 tejbeer 5931
 
33444 ranu 5932
 
5933
    public void findAllLiveDemoBrandItemsByBillingDate() throws MessagingException, ProfitMandiBusinessException, IOException {
5934
        LocalDateTime endDate = LocalDate.now().atStartOfDay().minusDays(8);
5935
 
5936
        List<LiveDemoOrderLineItemModel> liveDemoOrderLineItemModels = orderRepository.findAllLiveDemoBrandItemsByBillingDate(endDate.minusDays(60), endDate);
5937
        LOGGER.info("liveDemoOrderLineItemModels {}", liveDemoOrderLineItemModels);
5938
        String subject = "Billed Live Demo Model";
5939
        StringBuilder sb = new StringBuilder();
5940
 
5941
        sb.append("<html><body><p>Hi,\n");
5942
        sb.append("<p>Please check live demo billed order :</p>\n" + " <table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
5943
 
5944
        sb.append("<th style='border:1px solid black;padding: 5px'>Item Id</th>\n");
5945
        sb.append("<th style='border:1px solid black;padding: 5px'>Invoice Number</th>\n");
5946
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5947
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5948
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5949
        sb.append("<th style='border:1px solid black;padding: 5px'>Serial Number</th>\n");
5950
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer Name</th>\n");
5951
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer City</th>\n");
5952
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer Pincode</th>\n");
5953
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer State</th>\n");
5954
        sb.append("<th style='border:1px solid black;padding: 5px'>Billing Date</th>\n");
5955
        sb.append("</tr>\n");
5956
        for (LiveDemoOrderLineItemModel liveDemoModel : liveDemoOrderLineItemModels) {
5957
            sb.append("<tr>");
5958
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getItemId() + "</td>\n");
5959
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getInvoiceNumber() + "</td>\n");
5960
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getBrand() + "</td>\n");
5961
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getModelNumber() + "</td>\n");
5962
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getModelName() + "</td>\n");
5963
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getSerialNumber() + "</td>\n");
5964
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerName() + "</td>\n");
5965
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerCity() + "</td>\n");
5966
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getRetailerPincode() + "</td>\n");
5967
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getState() + "</td>\n");
5968
            sb.append("<td style='border:1px solid black;padding: 5px'>" + liveDemoModel.getFormattedBillingDate() + "</td>\n");
5969
 
5970
            sb.append("</tr>\n");
5971
 
33506 amit.gupta 5972
        }
33444 ranu 5973
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "niranjan.kala@smartdukaan.com",
33506 amit.gupta 5974
                "mohit.gulati@smartdukaan.com", "vinay.p@smartdukaan.com", "shivam.gupta@smartdukaan.com");
33444 ranu 5975
 
5976
 
5977
        String[] email = sendTo.toArray(new String[sendTo.size()]);
5978
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
5979
 
5980
    }
5981
 
33464 ranu 5982
    public void findTodayPocoBillingItems() throws MessagingException, ProfitMandiBusinessException, IOException {
5983
        LocalDateTime endDate = LocalDate.now().atStartOfDay().plusDays(1);
5984
        LocalDateTime startDate = LocalDate.now().atStartOfDay().minusDays(1);
33444 ranu 5985
 
33464 ranu 5986
        List<LiveDemoOrderLineItemModel> pocoBillingOrderLineItemModels = orderRepository.findTodayPocoBillingItems(startDate, endDate);
5987
        LOGGER.info("pocoBillingOrderLineItemModels {}", pocoBillingOrderLineItemModels);
5988
        String subject = "Poco Billing";
5989
        StringBuilder sb = new StringBuilder();
5990
 
5991
        sb.append("<html><body><p>Hi,\n");
5992
        sb.append("<p>Please check poco billed order :</p>\n" + " <table style='border:1px solid black ;padding: 5px; border-collapse: collapse;'>");
5993
 
5994
        sb.append("<th style='border:1px solid black;padding: 5px'>Brand</th>\n");
5995
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Number</th>\n");
5996
        sb.append("<th style='border:1px solid black;padding: 5px'>Model Name</th>\n");
5997
        sb.append("<th style='border:1px solid black;padding: 5px'>Serial Number</th>\n");
5998
        sb.append("<th style='border:1px solid black;padding: 5px'>Retailer State</th>\n");
5999
        sb.append("<th style='border:1px solid black;padding: 5px'>Billing Date</th>\n");
6000
        sb.append("</tr>\n");
6001
        for (LiveDemoOrderLineItemModel pocoModel : pocoBillingOrderLineItemModels) {
6002
            sb.append("<tr>");
6003
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getBrand() + "</td>\n");
6004
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getModelNumber() + "</td>\n");
6005
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getModelName() + "</td>\n");
6006
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getSerialNumber() + "</td>\n");
6007
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getState() + "</td>\n");
6008
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pocoModel.getFormattedBillingDate() + "</td>\n");
6009
 
6010
            sb.append("</tr>\n");
6011
 
33506 amit.gupta 6012
        }
33664 amit.gupta 6013
        List<String> sendTo = Arrays.asList("uday.singh@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "nishant.ohri@smartdukaan.com", "ritesh.chauhan1@smartdukaan.com");
33464 ranu 6014
 
6015
        String[] email = sendTo.toArray(new String[sendTo.size()]);
6016
        this.sendMailOfHtmlFormat(mailSender, email, sb.toString(), null, subject);
6017
 
6018
    }
6019
 
6020
 
31697 amit.gupta 6021
    public void monthlyTargetForInternalTeam() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 6022
 
31697 amit.gupta 6023
        LocalDateTime curDate = LocalDateTime.now();
31218 tejbeer 6024
 
31886 tejbeer 6025
        List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, ProfitMandiConstants.TICKET_CATEGORY_RBM, ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_MARKETING, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS, ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
31218 tejbeer 6026
 
31697 amit.gupta 6027
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false);
31218 tejbeer 6028
 
31697 amit.gupta 6029
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 6030
 
31697 amit.gupta 6031
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31218 tejbeer 6032
 
31886 tejbeer 6033
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 6034
 
31886 tejbeer 6035
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
6036
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 6037
 
31697 amit.gupta 6038
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 6039
 
31697 amit.gupta 6040
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31218 tejbeer 6041
 
31697 amit.gupta 6042
            String email = storeGuyEntry.getKey();
31218 tejbeer 6043
 
31697 amit.gupta 6044
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
6045
            Map<Integer, MonthlyTarget> monthlyTargetAchievement = new HashMap<>();
6046
            for (Integer fofoId : fofoIds) {
31218 tejbeer 6047
 
31697 amit.gupta 6048
                MonthlyTarget monthlyTarget = partnersMonthlyTarget.get(fofoId);
6049
                if (monthlyTarget != null) {
6050
                    Double purchaseTarget = monthlyTarget.getPurchaseTarget();
31218 tejbeer 6051
 
31697 amit.gupta 6052
                    Double saleTarget = monthlyTarget.getSaleTarget();
31218 tejbeer 6053
 
31697 amit.gupta 6054
                    if (purchaseTarget != null && purchaseTarget > 0) {
6055
                        Double purchase = secondaryMtd.get(fofoId);
6056
                        if (purchase == null) {
6057
                            purchase = 0.0;
6058
                        }
6059
                        monthlyTarget.setPurchaseAchievement(purchase);
6060
                        monthlyTargetAchievement.put(fofoId, monthlyTarget);
31218 tejbeer 6061
 
31697 amit.gupta 6062
                    }
6063
                }
6064
            }
31218 tejbeer 6065
 
31697 amit.gupta 6066
            if (!monthlyTargetAchievement.isEmpty()) {
31218 tejbeer 6067
 
31697 amit.gupta 6068
                StringBuilder sb = new StringBuilder();
31218 tejbeer 6069
 
31697 amit.gupta 6070
                sb.append("<html><body><p>Hi,\n");
31886 tejbeer 6071
                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 6072
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
6073
                sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31218 tejbeer 6074
 
31697 amit.gupta 6075
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Target</th>\n");
31218 tejbeer 6076
 
31697 amit.gupta 6077
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Achievement</th>\n");
6078
                sb.append("</tr>\n");
31218 tejbeer 6079
 
31886 tejbeer 6080
                for (Entry<Integer, MonthlyTarget> monthlyTargetAchievementEntry : monthlyTargetAchievement.entrySet()) {
31697 amit.gupta 6081
                    sb.append("<tr>");
6082
                    int fofoId = monthlyTargetAchievementEntry.getKey();
31218 tejbeer 6083
 
31697 amit.gupta 6084
                    MonthlyTarget monthlyTarget = monthlyTargetAchievementEntry.getValue();
31886 tejbeer 6085
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31218 tejbeer 6086
 
31886 tejbeer 6087
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseTarget() + "</td>\n");
31218 tejbeer 6088
 
31886 tejbeer 6089
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseAchievement() + "</td>\n");
31218 tejbeer 6090
 
31697 amit.gupta 6091
                    sb.append("</tr>\n");
31218 tejbeer 6092
 
31697 amit.gupta 6093
                }
31218 tejbeer 6094
 
32350 amit.gupta 6095
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb.toString(), null, subject);
31697 amit.gupta 6096
                // this.sendMailOfHtmlFormat("tejbeer.kaur@smartdukaan.com", sb.toString(),
6097
                // null, subject);
31218 tejbeer 6098
 
31697 amit.gupta 6099
            }
31604 tejbeer 6100
 
31697 amit.gupta 6101
        }
31604 tejbeer 6102
 
31697 amit.gupta 6103
    }
31604 tejbeer 6104
 
32061 amit.gupta 6105
    @Autowired
6106
    private PerformanceService performanceService;
6107
 
6108
 
6109
    public void sendFilteredRetailerPerformance() throws Exception {
6110
        RetailerFilterModel retailerFilterModel = performanceService.getRetailerFilterModel();
6111
 
6112
        Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(true);
6113
 
6114
 
6115
        List<RetailerPeformanceFilterModel> partnersPerformance = performanceService.getPerformance(retailerFilterModel, customRetailers);
6116
 
6117
        Map<Integer, RetailerPeformanceFilterModel> partnersPerformanceMap = new HashMap<>();
6118
 
6119
        if (!partnersPerformance.isEmpty()) {
6120
            partnersPerformanceMap = partnersPerformance.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
6121
            performanceService.sendPartnerPerformanceEmail(partnersPerformanceMap, retailerFilterModel, customRetailers);
6122
 
6123
        }
6124
 
6125
 
6126
    }
6127
 
32081 tejbeer 6128
    @Autowired
6129
    private VendorItemPricingRepository vendorItemPricingRepository;
32061 amit.gupta 6130
 
32081 tejbeer 6131
 
6132
    @Autowired
6133
    private VendorCatalogPricingService vendorCatalogPricingService;
6134
 
6135
 
33256 amit.gupta 6136
    public void migrateVendorItemPricing() throws ProfitMandiBusinessException {
32081 tejbeer 6137
 
6138
        List<VendorItemPricing> vendorItemPricings = vendorItemPricingRepository.selectAll();
32350 amit.gupta 6139
        LOGGER.info("At migrate VendorItemPricing");
32092 tejbeer 6140
        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 6141
        for (VendorItemPricing vendorItemPricing : vendorItemPricings) {
6142
            Item item = null;
32092 tejbeer 6143
            if (items.get(vendorItemPricing.getItemId()) != null) {
6144
                item = items.get(vendorItemPricing.getItemId());
6145
            } else {
32084 tejbeer 6146
                continue;
32081 tejbeer 6147
            }
32092 tejbeer 6148
 
32081 tejbeer 6149
            VendorCatalogPricingModel vendorCatalogPricingModel = new VendorCatalogPricingModel();
6150
            vendorCatalogPricingModel.setCatalogId(item.getCatalogItemId());
6151
            vendorCatalogPricingModel.setAuthId(13);
32088 tejbeer 6152
            vendorCatalogPricingModel.setDp(vendorItemPricing.getDp());
32081 tejbeer 6153
 
6154
            vendorCatalogPricingModel.setTp(vendorItemPricing.getTp());
6155
            vendorCatalogPricingModel.setMop(vendorItemPricing.getMop());
32384 amit.gupta 6156
            vendorCatalogPricingModel.setEffectedOn(LocalDate.of(2023, 8, 22));
32081 tejbeer 6157
            vendorCatalogPricingModel.setVendorId(vendorItemPricing.getVendorId());
6158
 
6159
 
6160
            try {
6161
                vendorCatalogPricingService.createVendorCatalogPricingLog(vendorCatalogPricingModel);
6162
            } catch (ProfitMandiBusinessException e) {
6163
                continue;
6164
            }
6165
 
6166
        }
6167
 
6168
    }
6169
 
6170
    public void approveVendorCatalogPricing() {
6171
        List<VendorCatalogPricingLog> vendorCatalogPricingLogs = vendorCatalogPricingLogRepository.selectByStatus(VendorCatalogPricingStatus.PENDING);
6172
 
32084 tejbeer 6173
 
32081 tejbeer 6174
        for (VendorCatalogPricingLog vendorCatalogPricingLog : vendorCatalogPricingLogs) {
32107 tejbeer 6175
            vendorCatalogPricingLog.setStatus(VendorCatalogPricingStatus.APPROVED);
6176
            vendorCatalogPricingLog.setUpdatedTimestamp(LocalDateTime.now());
6177
            vendorCatalogPricingLog.setApprovedBy(13);
6178
            vendorCatalogPricingLog.setApprovedTimestamp(LocalDateTime.now());
32114 tejbeer 6179
            vendorCatalogPricingService.createVendorCatalogPricing(vendorCatalogPricingLog);
6180
        }
32081 tejbeer 6181
 
32114 tejbeer 6182
    }
32108 tejbeer 6183
 
32822 ranu 6184
    public void sendMailWhatsAppAfterLoanDueDate() throws Exception {
6185
        sdCreditService.updateRisk();
6186
        List<Loan> defaultLoans = sdCreditService.getLoanALert();
6187
        if (!defaultLoans.isEmpty()) {
6188
            this.sendLoanAlert(defaultLoans);
6189
        }
32108 tejbeer 6190
 
32822 ranu 6191
 
6192
    }
6193
 
6194
    public void sendLoanAlert(List<Loan> defaultLoans) throws
6195
            Exception {
6196
 
6197
        List<Integer> categoryIds = Arrays.asList(
6198
                ProfitMandiConstants.TICKET_CATEGORY_CATEGORY,
6199
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
6200
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
6201
                ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS,
6202
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT);
6203
 
6204
        /*for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
6205
            List<Loan> filteredRows = defaultLoans.stream()
6206
                    .filter(loan -> storeGuyEntry.getValue().contains(loan.getFofoId()))
6207
                    .collect(Collectors.toList());
6208
 
6209
            if (!filteredRows.isEmpty()) {
6210
                for (Loan defaultLoan : filteredRows) {
6211
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
6212
                    double amount = loanStatements.stream().map(LoanStatement::getAmount).collect(Collectors.summingDouble(BigDecimal::doubleValue));
6213
                    String messageText = getMessageForDueDateExtend(defaultLoan,amount);
6214
                   // String[] email = new String[]{storeGuyEntry.getKey()};
6215
                    String[] email = {"ranu.rajput@smartdukaan.com"};
6216
                    sendMailOfHtmlFormat(mailSender, email, messageText, null, subject);
6217
 
6218
                }
6219
            }
6220
        }*/
32842 amit.gupta 6221
        //Send single whatsapp to tv
6222
        String title = "SD Credit Alert!";
32850 amit.gupta 6223
        boolean notYetSent = true;
32822 ranu 6224
        for (Loan defaultLoan : defaultLoans) {
6225
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
6226
 
6227
            double amount = loanStatements.stream().map(LoanStatement::getAmount).collect(Collectors.summingDouble(BigDecimal::doubleValue));
6228
 
6229
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
6230
 
6231
            Address address = addressRepository.selectById(user.getAddressId());
6232
 
32842 amit.gupta 6233
            //String url = "http://app.smartdukaan.com/pages/home/credit";
32822 ranu 6234
 
32842 amit.gupta 6235
            String message = getMessageForDueDateExtend(defaultLoan, amount);
6236
            String whatsAppMessage = getWhatsAppMessageForDueDateExtend(defaultLoan, amount);
32948 amit.gupta 6237
            if (whatsAppMessage != null) {
32850 amit.gupta 6238
                notificationService.sendWhatsappMessage(whatsAppMessage, title, address.getPhoneNumber());
32948 amit.gupta 6239
                if (notYetSent) {
32850 amit.gupta 6240
                    notificationService.sendWhatsappMessage(whatsAppMessage, title, "9911565032");
6241
                    notYetSent = false;
6242
                }
6243
            }
6244
 
32822 ranu 6245
            String[] email = {user.getEmailId()};
6246
            sendMailOfHtmlFormat(mailSender, email, message, null, "Loan Alert - SmartDukaan");
6247
        }
6248
    }
6249
 
6250
    private String getMessageForDueDateExtend(Loan defaultLoan, double amount) throws ProfitMandiBusinessException {
6251
 
6252
        double absoluteAmount = Math.abs(amount);
6253
        long roundedAmount = Math.round(absoluteAmount);
6254
        String formattedAmount = (amount < 0) ? "" + roundedAmount : "" + roundedAmount;
6255
 
6256
        LocalDate dueDate = defaultLoan.getDueDate().toLocalDate();
6257
        LocalDate defaultDate = defaultLoan.getDueDate().toLocalDate().plusDays(15);
6258
 
6259
        // Retrieve the name of the user associated with the loan
6260
        String name = userUserRepository.selectById(defaultLoan.getFofoId()).getName();
6261
 
6262
        // Initialize a StringBuilder to construct the HTML message
6263
        StringBuilder sb = new StringBuilder();
6264
 
32842 amit.gupta 6265
        if (LocalDate.now().isBefore(dueDate)) {
6266
            long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), defaultLoan.getDueDate().toLocalDate());
32822 ranu 6267
            String payDate = defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
6268
            // 5 Days Before Due Date - daily
6269
            if (noOfdaysBetween <= 5) {
6270
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
6271
                sb.append("<p>This is a friendly reminder that your loan payment is due in " + noOfdaysBetween + "days, on " +
6272
                        payDate +
6273
                        ". Please ensure that the payment is made on time to avoid any late fees or penalties.</p>");
6274
                sb.append("<p>As per the terms of your loan agreement, the total amount due is Rs. " + formattedAmount + ". " +
6275
                        "You can make the payment by adding money to your wallet. If you have any questions or need assistance, " +
6276
                        "our customer service team is available to help you.</p>");
6277
                sb.append("<p>Thank you for your cooperation and prompt attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
6278
            }
32842 amit.gupta 6279
        } else if (LocalDate.now().isBefore(defaultDate)) {
32822 ranu 6280
            long noOfdaysBetween = ChronoUnit.DAYS.between(defaultDate, LocalDate.now());
6281
 
6282
            // After Due Date – Alternate days
6283
            if ((noOfdaysBetween % 2 == 0) && (noOfdaysBetween > 5)) {
6284
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
6285
                sb.append("<p>We would like to remind you that your payment for the outstanding balance on your account is now overdue. " +
6286
                        "As per our terms and conditions, a higher interest rate will be levied on the overdue amount Rs. " + formattedAmount + ".</p>");
6287
                sb.append("<p>To avoid further charges and any negative impact on your CIBIL score, we kindly request that you settle the " +
6288
                        "outstanding balance as soon as possible.</p>");
6289
                sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
6290
            }
6291
            // 5 Days before default - daily
32842 amit.gupta 6292
            if (noOfdaysBetween <= 5) {
32822 ranu 6293
                sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br>");
6294
                sb.append("<p>Attention: High Alert</p>");
6295
                sb.append("<p>Dear " + name + "</p>");
6296
                sb.append("<p>This is to inform you that the due date for your payment of Rs. " + formattedAmount + " has been crossed, " +
6297
                        "and you are approaching the default date on " + defaultDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + ". " +
6298
                        "Please be aware that this will have a significant impact on your CIBIL score and may result in substantial penalties as well.</p>");
6299
                sb.append("<p>To rectify this situation, it is imperative that you take immediate action. " +
6300
                        "Please make the necessary payment immediately to avoid further consequences.</p>");
6301
                sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
6302
            }
32842 amit.gupta 6303
        } else {
32822 ranu 6304
            // Post Default - Daily
32842 amit.gupta 6305
            sb.append("<html><body><p><b>Loan Repayment Alert !</b></p></br><p>Dear " + name + "</p>");
6306
            sb.append("<p>We regret to inform you that you are currently in loan default. As a result, " +
6307
                    "higher penalties are being charged, which is also negatively impacting your CIBIL score. " +
6308
                    "It is imperative that you make an immediate payment to rectify this situation.</p>");
6309
            sb.append("<p>Please note that failing to make the payment promptly will result in further consequences, " +
6310
                    "including potential legal action and additional financial penalties. " +
6311
                    "We strongly urge you to take this matter seriously and settle the outstanding amount as soon as possible.</p>");
6312
            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>");
6313
            sb.append("<p>Thank you for your attention to this matter.</p></br><p> Smart Dukaan Team !!</p>");
32822 ranu 6314
 
6315
        }
6316
 
6317
        // Return the constructed HTML message
6318
        sb.append("</body></html>");
6319
        return sb.toString();
6320
    }
6321
 
6322
    private String getWhatsAppMessageForDueDateExtend(Loan defaultLoan, double amount) throws ProfitMandiBusinessException {
6323
 
6324
        double absoluteAmount = Math.abs(amount);
6325
        long roundedAmount = Math.round(absoluteAmount);
6326
        String formattedAmount = (amount < 0) ? "" + roundedAmount : "" + roundedAmount;
6327
 
6328
        LocalDate dueDate = defaultLoan.getDueDate().toLocalDate();
6329
        LocalDate defaultDate = defaultLoan.getDueDate().toLocalDate().plusDays(15);
6330
 
6331
        // Retrieve the name of the user associated with the loan
6332
        String name = userUserRepository.selectById(defaultLoan.getFofoId()).getName();
6333
 
6334
        // Initialize a StringBuilder to construct the HTML message
6335
        String message = null;
6336
 
32842 amit.gupta 6337
        if (LocalDate.now().isBefore(dueDate)) {
32822 ranu 6338
            long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), defaultLoan.getDueDate().toLocalDate());
6339
            String payDate = defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
6340
            // 5 Days Before Due Date - daily
6341
            if (noOfdaysBetween <= 5) {
6342
 
6343
                message = "Dear %s, This is a friendly reminder that your loan payment is due in %d days, on %s.\n" +
6344
                        "\n" +
6345
                        "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" +
6346
                        "\n" +
6347
                        "If you have any questions or need assistance, our customer service team is available to help you.\n" +
6348
                        "Thank you for your cooperation and prompt attention to this matter.\n" +
6349
                        "\n" +
6350
                        "Team SmartDukaan";
32842 amit.gupta 6351
                message = String.format(message, name, noOfdaysBetween, payDate, formattedAmount);
6352
            }
6353
        } else if (LocalDate.now().isBefore(defaultDate)) {
32822 ranu 6354
            long noOfdaysBetween = ChronoUnit.DAYS.between(defaultDate, LocalDate.now());
6355
            // After Due Date – Alternate days
6356
            if ((noOfdaysBetween % 2 == 0) && (noOfdaysBetween > 5)) {
6357
                message = "Dear %s, We would like to remind you that your payment for the outstanding balance on your account is now overdue. \n" +
6358
                        "As per our terms and conditions, a higher interest rate will be levied on the overdue amount Rs.%s.\n" +
6359
                        "To avoid further charges and any negative impact on your CIBIL score, we kindly request that you settle the outstanding balance as soon as possible.\n" +
6360
                        "Thank you for your attention to this matter. \n" +
6361
                        "\n" +
6362
                        "Team SmartDukaan";
6363
                message = String.format(message, name, formattedAmount);
6364
            }
6365
            // 5 Days before default - daily
32842 amit.gupta 6366
            if (noOfdaysBetween <= 5) {
32822 ranu 6367
                String defaultPayDate = defaultDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
6368
                message = "Attention: High Alert!! Dear %s, \n" +
6369
                        "\n" +
6370
                        "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" +
6371
                        "Please be aware that this will have a significant impact on your CIBIL score and may result in substantial penalties as well. To rectify this situation, it is imperative that you take immediate action.\n" +
6372
                        "\n" +
6373
                        "Please make the necessary payment immediately to avoid further consequences. Thank you for your attention to this matter.\n" +
6374
                        "\n" +
6375
                        "Team SmartDukaan";
6376
                message = String.format(message, name, formattedAmount, defaultPayDate);
6377
            }
32842 amit.gupta 6378
        } else {
32822 ranu 6379
            // Post Default - Daily
6380
            message = "Dear %s, We regret to inform you that you are currently in loan default. As a result, higher penalties are being charged, which is also negatively impacting your CIBIL score. \n" +
6381
                    "\n" +
6382
                    "It is imperative that you make an immediate payment to rectify this situation. \n" +
6383
                    "\n" +
6384
                    "Please note that failing to make the payment promptly will result in further consequences, including potential legal action and additional financial penalties. \n" +
6385
                    "\n" +
6386
                    "We strongly urge you to take this matter seriously and settle the outstanding amount as soon as possible. \n" +
6387
                    "\n" +
6388
                    "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" +
6389
                    "\n" +
6390
                    "Team SmartDukaan";
6391
            message = String.format(message, name, formattedAmount);
6392
 
6393
        }
6394
        // Return the constructed HTML message
6395
        return message;
6396
    }
6397
 
32210 jai.hind 6398
}
33664 amit.gupta 6399
// 2284"