Subversion Repositories SmartDukaan

Rev

Rev 32726 | Rev 32781 | 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;
25800 tejbeer 27
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
25609 amit.gupta 28
import com.spice.profitmandi.dao.entity.catalog.Item;
24590 amit.gupta 29
import com.spice.profitmandi.dao.entity.catalog.Scheme;
31388 amit.gupta 30
import com.spice.profitmandi.dao.entity.catalog.TagListing;
25590 amit.gupta 31
import com.spice.profitmandi.dao.entity.cs.Position;
26283 tejbeer 32
import com.spice.profitmandi.dao.entity.cs.Ticket;
28769 amit.gupta 33
import com.spice.profitmandi.dao.entity.dtr.User;
32421 amit.gupta 34
import com.spice.profitmandi.dao.entity.dtr.*;
35
import com.spice.profitmandi.dao.entity.fofo.*;
36
import com.spice.profitmandi.dao.entity.inventory.*;
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.*;
25590 amit.gupta 55
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
30421 tejbeer 56
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionRemarkRepository;
32421 amit.gupta 57
import com.spice.profitmandi.dao.repository.catalog.*;
58
import com.spice.profitmandi.dao.repository.cs.*;
59
import com.spice.profitmandi.dao.repository.dtr.*;
60
import com.spice.profitmandi.dao.repository.fofo.*;
61
import com.spice.profitmandi.dao.repository.inventory.*;
62
import com.spice.profitmandi.dao.repository.transaction.*;
24542 amit.gupta 63
import com.spice.profitmandi.dao.repository.user.AddressRepository;
25721 tejbeer 64
import com.spice.profitmandi.dao.repository.user.UserRepository;
32421 amit.gupta 65
import com.spice.profitmandi.dao.repository.warehouse.*;
31604 tejbeer 66
import com.spice.profitmandi.dao.service.solr.FofoSolr;
32421 amit.gupta 67
import com.spice.profitmandi.service.*;
31332 amit.gupta 68
import com.spice.profitmandi.service.integrations.CCAvenuePaymentService;
28368 tejbeer 69
import com.spice.profitmandi.service.integrations.RazorpayPaymentService;
30858 amit.gupta 70
import com.spice.profitmandi.service.integrations.bharti.model.BAGInsuranceModel;
25694 amit.gupta 71
import com.spice.profitmandi.service.integrations.toffee.ToffeeService;
32421 amit.gupta 72
import com.spice.profitmandi.service.inventory.*;
31746 amit.gupta 73
import com.spice.profitmandi.service.offers.OfferService;
25335 amit.gupta 74
import com.spice.profitmandi.service.order.OrderService;
24431 amit.gupta 75
import com.spice.profitmandi.service.pricing.PriceDropService;
23724 amit.gupta 76
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
77
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
78
import com.spice.profitmandi.service.scheme.SchemeService;
29668 tejbeer 79
import com.spice.profitmandi.service.serviceConfig.ServiceConfigService;
31008 amit.gupta 80
import com.spice.profitmandi.service.transaction.CreditNoteService;
30859 tejbeer 81
import com.spice.profitmandi.service.transaction.SDCreditService;
23929 amit.gupta 82
import com.spice.profitmandi.service.transaction.TransactionService;
83
import com.spice.profitmandi.service.user.RetailerService;
32511 amit.gupta 84
import com.spice.profitmandi.service.wallet.CommonPaymentService;
23739 amit.gupta 85
import com.spice.profitmandi.service.wallet.WalletService;
32421 amit.gupta 86
import com.spice.profitmandi.service.warehouse.PurchaseOrderService;
32511 amit.gupta 87
import com.spice.profitmandi.service.warehouse.WarehouseInventoryService;
25721 tejbeer 88
import in.shop2020.model.v1.order.OrderStatus;
29308 tejbeer 89
import in.shop2020.model.v1.order.WalletReferenceType;
32698 amit.gupta 90
import jdk.nashorn.api.scripting.ScriptObjectMirror;
29308 tejbeer 91
import okhttp3.OkHttpClient;
92
import okhttp3.Request;
30119 amit.gupta 93
import okhttp3.Response;
32421 amit.gupta 94
import org.apache.commons.io.output.ByteArrayOutputStream;
95
import org.apache.commons.lang.StringUtils;
96
import org.apache.http.client.methods.CloseableHttpResponse;
97
import org.apache.http.client.methods.HttpPost;
98
import org.apache.http.conn.HttpHostConnectException;
99
import org.apache.http.entity.StringEntity;
100
import org.apache.http.impl.client.CloseableHttpClient;
101
import org.apache.http.impl.client.HttpClients;
102
import org.apache.logging.log4j.LogManager;
103
import org.apache.logging.log4j.Logger;
104
import org.hibernate.Session;
105
import org.hibernate.SessionFactory;
106
import org.hibernate.query.NativeQuery;
107
import org.json.JSONArray;
108
import org.json.JSONObject;
109
import org.json.XML;
110
import org.springframework.beans.factory.annotation.Autowired;
111
import org.springframework.beans.factory.annotation.Qualifier;
112
import org.springframework.beans.factory.annotation.Value;
113
import org.springframework.core.io.ByteArrayResource;
114
import org.springframework.core.io.InputStreamSource;
115
import org.springframework.mail.javamail.JavaMailSender;
116
import org.springframework.mail.javamail.MimeMessageHelper;
117
import org.springframework.stereotype.Component;
118
import org.springframework.transaction.annotation.Transactional;
31640 tejbeer 119
 
32421 amit.gupta 120
import javax.mail.MessagingException;
121
import javax.mail.internet.InternetAddress;
122
import javax.mail.internet.MimeMessage;
123
import java.io.*;
124
import java.math.BigDecimal;
125
import java.math.RoundingMode;
126
import java.nio.file.Files;
127
import java.nio.file.Paths;
128
import java.sql.Timestamp;
129
import java.text.DecimalFormat;
130
import java.time.*;
131
import java.time.format.DateTimeFormatter;
132
import java.time.temporal.ChronoField;
133
import java.time.temporal.ChronoUnit;
134
import java.util.*;
135
import java.util.Map.Entry;
136
import java.util.stream.Collectors;
137
import java.util.stream.Stream;
32060 amit.gupta 138
 
32439 tejbeer 139
 
32421 amit.gupta 140
import static java.util.stream.Collectors.groupingBy;
141
import static java.util.stream.Collectors.mapping;
142
 
143
 
23723 amit.gupta 144
@Component
23724 amit.gupta 145
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 146
public class ScheduledTasks {
147
 
31697 amit.gupta 148
    @Value("${oxigen.recharge.transaction.url}")
149
    private String oxigenRechargeTransactionUrl;
23723 amit.gupta 150
 
31697 amit.gupta 151
    @Value("${oxigen.recharge.enquiry.url}")
152
    private String oxigenRechargeEnquiryUrl;
24533 govind 153
 
31697 amit.gupta 154
    @Autowired
32482 amit.gupta 155
    PurchaseMigration purchaseMigration;
156
 
157
    @Autowired
31697 amit.gupta 158
    private RegionRepository regionRepository;
29668 tejbeer 159
 
31697 amit.gupta 160
    @Autowired
161
    private ServiceConfigService serviceConfigService;
29801 manish 162
 
31697 amit.gupta 163
    @Autowired
164
    private TecnoImeiActivation tecnoImeiActivation;
28205 tejbeer 165
 
31697 amit.gupta 166
    private static final DateTimeFormatter leadTimeFormatter = DateTimeFormatter.ofPattern("d LLL, hh:mm a");
27088 tejbeer 167
 
31697 amit.gupta 168
    @Autowired
169
    private PartnerRegionRepository partnerRegionRepository;
28790 amit.gupta 170
 
31697 amit.gupta 171
    @Autowired
172
    private EmployeeAttendanceRepository employeeAttendanceRepository;
27088 tejbeer 173
 
31697 amit.gupta 174
    @Autowired
175
    VivoImeiActivationService vivoImeiActivationService;
29488 manish 176
 
31697 amit.gupta 177
    @Autowired
178
    ItelImeiActivationService itelImeiActivationService;
29488 manish 179
 
31697 amit.gupta 180
    @Autowired
181
    private PartnerTypeChangeService partnerTypeChangeService;
25598 amit.gupta 182
 
31697 amit.gupta 183
    @Autowired
184
    private ActivatedImeiRepository activatedImeiRepository;
26408 amit.gupta 185
 
31697 amit.gupta 186
    @Autowired
187
    private LineItemRepository lineItemRepository;
29451 manish 188
 
31697 amit.gupta 189
    @Autowired
190
    private LeadRepository leadRepository;
25927 amit.gupta 191
 
31697 amit.gupta 192
    @Autowired
193
    private AuthRepository authRepository;
25503 amit.gupta 194
 
31697 amit.gupta 195
    @Autowired
196
    private PriceDropService priceDropService;
26283 tejbeer 197
 
31697 amit.gupta 198
    @Autowired
199
    private FranchiseeVisitRepository franchiseeVisitRepository;
26790 tejbeer 200
 
31697 amit.gupta 201
    @Autowired
202
    private FranchiseeActivityRepository franchiseeActivityRepository;
26790 tejbeer 203
 
31697 amit.gupta 204
    @Autowired
205
    private HdfcPaymentRepository hdfcPaymentRepository;
26790 tejbeer 206
 
31697 amit.gupta 207
    @Autowired
208
    private CsService csService;
25846 amit.gupta 209
 
31697 amit.gupta 210
    @Autowired
211
    private SaholicInventoryService saholicInventoryService;
27208 tejbeer 212
 
31697 amit.gupta 213
    @Autowired
214
    private InsurancePolicyRepository insurancePolicyRepository;
23723 amit.gupta 215
 
31697 amit.gupta 216
    @Autowired
217
    private ToffeeService toffeeService;
25694 amit.gupta 218
 
31697 amit.gupta 219
    @Value("${oxigen.recharge.auth.key}")
220
    private String oxigenRechargeAuthKey;
23724 amit.gupta 221
 
31697 amit.gupta 222
    @Value("${oxigen.recharge.validation.url}")
223
    private String oxigenRechargeValidationUrl;
23724 amit.gupta 224
 
31697 amit.gupta 225
    @Value("${oxigen.recharge.validation.auth.key}")
226
    private String oxigenRechargeValidationAuthKey;
23724 amit.gupta 227
 
31697 amit.gupta 228
    @Value("${think.walnut.digital.recharge.transaction.mobile.url}")
229
    private String thinkWalnutDigitalRechargeTransactionMobileUrl;
23724 amit.gupta 230
 
31697 amit.gupta 231
    @Value("${think.walnut.digital.recharge.transaction.dth.url}")
232
    private String thinkWalnutDigitalRechargeTransactionDthUrl;
23724 amit.gupta 233
 
31697 amit.gupta 234
    @Value("${think.walnut.digital.recharge.enquiry.url}")
235
    private String thinkWalnutDigitalRechargeEnquiryUrl;
23724 amit.gupta 236
 
31697 amit.gupta 237
    @Value("${think.walnut.digital.recharge.balance.url}")
238
    private String thinkWalnutDigitalRechargeBalanceUrl;
23724 amit.gupta 239
 
31697 amit.gupta 240
    @Value("${think.walnut.digital.recharge.username}")
241
    private String thinkWalnutDigitalRechargeUserName;
23724 amit.gupta 242
 
31697 amit.gupta 243
    @Value("${think.walnut.digital.recharge.password}")
244
    private String thinkWalnutDigitalRechargePassword;
23724 amit.gupta 245
 
31697 amit.gupta 246
    @Value("${think.walnut.digital.recharge.auth.key}")
247
    private String thinkWalnutDigitalRechargeAuthKey;
23724 amit.gupta 248
 
31697 amit.gupta 249
    @Autowired
250
    private PurchaseRepository purchaseRepository;
23724 amit.gupta 251
 
31697 amit.gupta 252
    @Autowired
253
    private PriceDropIMEIRepository priceDropIMEIRepository;
25609 amit.gupta 254
 
31697 amit.gupta 255
    @Autowired
256
    PriceDropRepository priceDropRepository;
25609 amit.gupta 257
 
31697 amit.gupta 258
    @Autowired
259
    private PartnerTypeChangeRepository partnerTypeChangeRepository;
28368 tejbeer 260
 
31697 amit.gupta 261
    @Autowired
262
    private SchemeService schemeService;
24683 amit.gupta 263
 
31697 amit.gupta 264
    @Autowired
265
    private ServiceConfigRepository serviceConfigRepository;
29668 tejbeer 266
 
32061 amit.gupta 267
    @Autowired
268
    private RetailerBlockBrandsRepository retailerBlockBrandsRepository;
269
 
31697 amit.gupta 270
    @Value("${delhivery.tracking.token}")
271
    private String token;
29308 tejbeer 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
 
32580 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"};
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
359
    private TransactionService transactionService;
24250 amit.gupta 360
 
31697 amit.gupta 361
    @Autowired
362
    private ItemRepository itemRepository;
23929 amit.gupta 363
 
31697 amit.gupta 364
    @Autowired
365
    private OrderRepository orderRepository;
25351 tejbeer 366
 
31697 amit.gupta 367
    @Autowired
368
    private OrderService orderService;
23929 amit.gupta 369
 
31697 amit.gupta 370
    @Autowired
371
    private SchemeRepository schemeRepository;
24241 amit.gupta 372
 
31697 amit.gupta 373
    @Autowired
374
    private SchemeItemRepository schemeItemRepository;
31612 tejbeer 375
 
31697 amit.gupta 376
    @Autowired
377
    private JavaMailSender mailSender;
24177 govind 378
 
31697 amit.gupta 379
    @Autowired
380
    private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 381
 
31697 amit.gupta 382
    @Autowired
383
    @Qualifier(value = "googleMailSender")
384
    private JavaMailSender googleMailSender;
23929 amit.gupta 385
 
31697 amit.gupta 386
    @Autowired
387
    private InventoryService inventoryService;
23929 amit.gupta 388
 
31697 amit.gupta 389
    @Autowired
390
    private AddressRepository addressRepository;
24542 amit.gupta 391
 
31697 amit.gupta 392
    @Autowired
393
    private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
24542 amit.gupta 394
 
31697 amit.gupta 395
    @Autowired
396
    private Mongo mongoClient;
24683 amit.gupta 397
 
31697 amit.gupta 398
    @Autowired
399
    private DeviceRepository deviceRepository;
25300 tejbeer 400
 
31697 amit.gupta 401
    @Autowired
402
    private PushNotificationRepository pushNotificationRepository;
25300 tejbeer 403
 
31697 amit.gupta 404
    @Autowired
405
    private NotificationCampaignRepository notificationCampaignRepository;
25300 tejbeer 406
 
31697 amit.gupta 407
    @Autowired
408
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
25721 tejbeer 409
 
31697 amit.gupta 410
    @Autowired
411
    private FocusedModelRepository focusedModelRepository;
25721 tejbeer 412
 
31697 amit.gupta 413
    @Autowired
414
    private UserAccountRepository userAccountRepository;
24653 govind 415
 
31697 amit.gupta 416
    @Autowired
417
    private UserRepository userUserRepository;
25721 tejbeer 418
 
31697 amit.gupta 419
    @Autowired
420
    private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
25927 amit.gupta 421
 
31697 amit.gupta 422
    @Autowired
423
    private UserCampaignRepository userCampaignRepository;
25721 tejbeer 424
 
31697 amit.gupta 425
    @Autowired
426
    private Gson gson;
25721 tejbeer 427
 
31697 amit.gupta 428
    @Autowired
429
    private TicketRepository ticketRepository;
26283 tejbeer 430
 
31697 amit.gupta 431
    @Autowired
432
    private RefferalRepository refferalRepository;
26790 tejbeer 433
 
31697 amit.gupta 434
    @Autowired
435
    private PartnerProblemRepository partnerProblemRepository;
28205 tejbeer 436
 
31697 amit.gupta 437
    @Autowired
438
    private PendingOrderRepository pendingOrderRepository;
28368 tejbeer 439
 
31697 amit.gupta 440
    @Autowired
441
    private PendingOrderItemRepository pendingOrderItemRepository;
28368 tejbeer 442
 
31697 amit.gupta 443
    @Value("${razorpay.account.keyId}")
444
    private String keyId;
28368 tejbeer 445
 
31697 amit.gupta 446
    @Value("${razorpay.account.keySecret}")
447
    private String keySecret;
28368 tejbeer 448
 
31697 amit.gupta 449
    @Autowired
450
    private RazorpayPaymentService razorPaymentService;
28369 tejbeer 451
 
31697 amit.gupta 452
    @Autowired
453
    private RazorPayRepository razorPayRepository;
28369 tejbeer 454
 
31697 amit.gupta 455
    @Autowired
456
    private PendingOrderService pendingOrderService;
28377 tejbeer 457
 
31697 amit.gupta 458
    @Autowired
459
    private CustomerRepository customerRepository;
28377 tejbeer 460
 
31697 amit.gupta 461
    @Autowired
462
    private RestClient restClient;
29308 tejbeer 463
 
31697 amit.gupta 464
    @Autowired
465
    private MandiiService mandiiService;
29814 tejbeer 466
 
31697 amit.gupta 467
    @Autowired
468
    CreditAccountRepository creditAccountRepository;
31604 tejbeer 469
 
31697 amit.gupta 470
    @Autowired
471
    CustomerOfferRepository customerOfferRepository;
31612 tejbeer 472
 
31697 amit.gupta 473
    @Autowired
474
    CustomerOfferItemRepository customerOfferItemRepository;
475
    @Autowired
476
    private FofoSolr fofoSolr;
23724 amit.gupta 477
 
25300 tejbeer 478
 
31697 amit.gupta 479
    private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
31388 amit.gupta 480
 
31697 amit.gupta 481
    private String FCM_URL = "https://fcm.googleapis.com/fcm/send";
482
    private String FCM_API_KEY = "AAAASAjNcn4:APA91bG6fWRIgYJI0L9gCjP5ynaXz2hJHYKtD9dfH7Depdv31Nd9APJwhx-OPkAJ1WSz4BGNYG8lHThLFSjDGFxIwUZv241YcAJEGDLgt86mxq9FXJe-yBRu-S0_ZwHqmX-QaVKl5F_A";
23724 amit.gupta 483
 
31697 amit.gupta 484
    @Autowired
485
    private TagListingRepository tagListingRepository;
23724 amit.gupta 486
 
31697 amit.gupta 487
    public void generateDailyRecharge() {
31886 tejbeer 488
        List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository.selectAll(0, 2000);
31697 amit.gupta 489
        List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
490
        rechargeProviders.stream().forEach(x -> x.setAmount(0));
23724 amit.gupta 491
 
31697 amit.gupta 492
        rechargeProviders.stream().forEach(x -> {
31886 tejbeer 493
            Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory.stream().filter(z -> z.getProviderId() == x.getId()).collect(groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
23724 amit.gupta 494
 
31697 amit.gupta 495
            LOGGER.info("dateWiseProviderCreditsMap -{}", dateWiseProviderCreditsMap);
496
            LocalDate endDate = LocalDate.now().plusDays(1);
497
            float previousDayClosing = 0;
498
            LocalDate date = LocalDate.of(2018, 4, 6);
499
            while (date.isBefore(endDate)) {
31886 tejbeer 500
                List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(), date.plusDays(1).atStartOfDay());
23724 amit.gupta 501
 
31886 tejbeer 502
                List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream().filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
23724 amit.gupta 503
 
31697 amit.gupta 504
                float dailyAmount = 0;
505
                float totalCommission = 0;
506
                for (RechargeTransaction rechargeTransaction : successfulTransactions) {
507
                    if (rechargeTransaction.getProviderId() == x.getId()) {
508
                        dailyAmount += rechargeTransaction.getAmount();
509
                        totalCommission += rechargeTransaction.getCommission();
510
                    }
511
                }
28205 tejbeer 512
 
31697 amit.gupta 513
                List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
514
                float dailyWalletRecharge = 0;
515
                if (rechargeHistoryList != null) {
516
                    for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
517
                        if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
518
                            dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
519
                        }
520
                    }
521
                }
522
                if (dailyAmount > 0 || dailyWalletRecharge > 0) {
523
                    DailyRecharge dailyRecharge = null;
524
                    try {
525
                        dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
526
                    } catch (Exception e) {
527
                        LOGGER.info("Could not find Recharge entry");
528
                    }
529
                    if (dailyRecharge == null) {
530
                        dailyRecharge = new DailyRecharge();
531
                        dailyRecharge.setCreateDate(date);
532
                    }
533
                    dailyRecharge.setOpeningBalance(previousDayClosing);
534
                    dailyRecharge.setProviderId(x.getId());
535
                    dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
536
                    dailyRecharge.setTotalAmount(dailyAmount);
537
                    dailyRecharge.setTotalCommission(totalCommission);
538
                    float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
539
                    dailyRecharge.setClosingBalance(closingBalance);
540
                    dailyRechargeRepository.persist(dailyRecharge);
541
                    x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
542
                    previousDayClosing = dailyRecharge.getClosingBalance();
543
                }
544
                date = date.plusDays(1);
545
            }
546
            rechargeProviderRepository.persist(x);
547
        });
548
        LOGGER.info("finished generating daily recharge");
549
    }
24240 amit.gupta 550
 
31697 amit.gupta 551
    public void reconcileRecharge() throws Exception {
552
        LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
553
        LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
554
        List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
555
        LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
556
        nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
557
        nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
558
        RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
559
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
560
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
561
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
562
        thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
563
        Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
31886 tejbeer 564
        List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
31697 amit.gupta 565
        for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
566
            try {
567
                int providerId = rechargeTransaction.getProviderId();
568
                if (providerId == 1) {
31886 tejbeer 569
                    oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey, rechargeTransaction);
31697 amit.gupta 570
                } else if (providerId == 2) {
31886 tejbeer 571
                    thinkWalnutDigitalRechargeProviderService.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
31697 amit.gupta 572
                }
31886 tejbeer 573
                if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS) || rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
574
                    requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(), rechargeTransaction.getStatus());
31697 amit.gupta 575
                }
576
            } catch (Exception e) {
577
                LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
578
            }
579
        }
580
        LOGGER.info("Reconcile recharge ran successfully");
581
    }
24241 amit.gupta 582
 
31697 amit.gupta 583
    public void processActivation() throws Exception {
584
        schemeService.processActivation();
585
    }
24241 amit.gupta 586
 
31697 amit.gupta 587
    // TemporaryMethod
588
    public void migrateInvoice() {
589
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
590
        Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
31886 tejbeer 591
        partnerOrdersMap = fofoOrders.stream().collect(groupingBy(FofoOrder::getFofoId, Collectors.toList()));
31697 amit.gupta 592
        for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
593
            int sequence = 0;
594
            String prefix = "";
31886 tejbeer 595
            List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId()).collect(Collectors.toList());
31697 amit.gupta 596
            for (FofoOrder order : sortedList) {
23724 amit.gupta 597
 
31697 amit.gupta 598
                LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
599
                if (!order.getInvoiceNumber().contains("SEC")) {
600
                    sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
601
                    prefix = order.getInvoiceNumber().split("/")[0];
602
                } else {
603
                    sequence += 1;
604
                    String invoiceNumber = prefix + "/" + sequence;
605
                    order.setInvoiceNumber(invoiceNumber);
606
                    fofoOrderRepository.persist(order);
607
                }
608
            }
24252 amit.gupta 609
 
31697 amit.gupta 610
        }
611
    }
28205 tejbeer 612
 
31697 amit.gupta 613
    @Autowired
614
    private ReporticoCacheTableRepository reporticoCacheTableRepository;
28205 tejbeer 615
 
31697 amit.gupta 616
    public void processScheme(int offset, boolean dryRun) throws Exception {
617
        LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
618
        LocalDateTime endDate = startDate.plusDays(30);
619
        processScheme(startDate, endDate, dryRun);
620
    }
24533 govind 621
 
31697 amit.gupta 622
    public void processSchemeOut(List<String> invoiceNumbers) throws Exception {
623
        for (String invoiceNumber : invoiceNumbers) {
624
            System.out.println("Invoice Number - " + invoiceNumber);
625
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
32147 amit.gupta 626
            //orderService.reverseScheme(fofoOrder);
31697 amit.gupta 627
            schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
628
        }
629
    }
24271 amit.gupta 630
 
31697 amit.gupta 631
    public void processSchemeIn(List<String> invoiceNumbers) throws Exception {
632
        for (String invoiceNumber : invoiceNumbers) {
633
            System.out.println("Invoice Number - " + invoiceNumber);
634
            Purchase purchase = purchaseRepository.selectByPurchaseReference(invoiceNumber);
635
            schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
636
        }
637
    }
24271 amit.gupta 638
 
31697 amit.gupta 639
    public void processScheme(int offset, int durationDays, boolean dryRun) throws Exception {
640
        LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
641
        LocalDateTime endDate = startDate.plusDays(durationDays);
642
        processScheme(startDate, endDate, dryRun);
643
    }
24271 amit.gupta 644
 
31697 amit.gupta 645
    public void processScheme(boolean dryRun) throws Exception {
646
        LocalDateTime fromDate = LocalDateTime.now().minusDays(30);
647
        processScheme(fromDate, LocalDateTime.now(), dryRun);
648
    }
23929 amit.gupta 649
 
31697 amit.gupta 650
    public void processScheme(LocalDateTime startDate, LocalDateTime endDate, boolean dryRun) throws Exception {
651
        LOGGER.info("Started execution at {}", LocalDateTime.now());
652
        System.out.println(
653
                "InventoryId\tSerialNumber\tItem Id\tScheme Id\tScheme Name\tScheme Type\tAmount Type\tDP\tTaxable\tScheme Amount\tAmount Paid");
654
        try {
655
            List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
656
            for (Purchase purchase : purchases) {
657
                schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
658
            }
29160 amit.gupta 659
 
31697 amit.gupta 660
            List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
661
            for (FofoOrder fofoOrder : fofoOrders) {
662
                schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
663
            }
664
        } catch (Exception e) {
665
            e.printStackTrace();
666
            throw e;
667
        }
31886 tejbeer 668
        List<UserWalletHistory> uwhs = userWalletHistoryRepository.selectAllByDateType(LocalDate.now().atStartOfDay(), endDate, Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
31697 amit.gupta 669
        System.out.println("Amount\tReference\tReferenceType\tTimestamp\tDescription");
670
        for (UserWalletHistory uwh : uwhs) {
31886 tejbeer 671
            System.out.println(String.format("%d\t%d\t%s\t%s\t%s", uwh.getAmount(), uwh.getReference(), uwh.getReferenceType(), uwh.getTimestamp().toString(), uwh.getDescription()));
31697 amit.gupta 672
        }
673
        LOGGER.info("Schemes processed successfully.");
674
        if (dryRun) {
675
            throw new Exception();
676
        }
677
    }
29160 amit.gupta 678
 
31697 amit.gupta 679
    public void processRechargeCashback() throws Throwable {
680
        LocalDateTime cashbackTime = LocalDateTime.now();
681
        int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
31886 tejbeer 682
        List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository.getPendingCashBackRehargeTransactions();
31697 amit.gupta 683
        Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
31724 amit.gupta 684
                groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
31697 amit.gupta 685
        for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
686
            int retailerId = (Integer) totalRetailerCashback.getKey();
687
            float amount = totalRetailerCashback.getValue().floatValue();
688
            if (Math.round(amount) > 0) {
31886 tejbeer 689
                walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK, "Recharge Cashback", Math.round(amount), LocalDateTime.now());
31697 amit.gupta 690
            }
691
        }
692
        for (RechargeTransaction rt : pendingTransactions) {
693
            rt.setCashbackTimestamp(cashbackTime);
694
            rt.setCashbackReference(referenceId);
695
            rechargeTransactionRepository.persist(rt);
696
        }
697
        LOGGER.info("Cashbacks for Recharge processed Successfully");
698
    }
29160 amit.gupta 699
 
31697 amit.gupta 700
    public void rollOutUpgardedMarginsNextMonth() throws Exception {
701
        LocalDate startOfPreviousMonth = LocalDate.now().with(ChronoField.DAY_OF_MONTH, 1).minusMonths(1);
29160 amit.gupta 702
 
31697 amit.gupta 703
        List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
704
        for (FofoStore store : stores) {
32003 amit.gupta 705
            this.rolloutMarginForStoreOnMonth(store, startOfPreviousMonth);
706
        }
707
    }
29252 amit.gupta 708
 
32003 amit.gupta 709
    public void rolloutMarginForStoreOnMonth(FofoStore store, LocalDate startOfMonth) throws ProfitMandiBusinessException {
710
        int fofoId = store.getId();
29252 amit.gupta 711
 
32003 amit.gupta 712
        PartnerType startOfPreviousMonthPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth);
713
        PartnerType todayPartnerType = partnerTypeChangeService.getTypeOnMonth(fofoId, YearMonth.from(startOfMonth.atStartOfDay()));
714
        if (!startOfPreviousMonthPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
715
            return;
716
        }
717
        if (!startOfPreviousMonthPartnerType.equals(todayPartnerType)) {
718
            LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(), startOfPreviousMonthPartnerType, todayPartnerType);
719
            List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startOfMonth.atStartOfDay(), startOfMonth.plusMonths(1).atStartOfDay(), 0, 0);
720
            for (FofoOrder fofoOrder : fofoOrders) {
721
                schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
31697 amit.gupta 722
            }
723
        }
724
    }
29252 amit.gupta 725
 
32003 amit.gupta 726
 
31697 amit.gupta 727
    public void rollOutUpgardedMargins() throws Exception {
728
        LocalDate today = LocalDate.now();
729
        LocalDate yesterday = today.minusDays(1);
730
        int upgradedCount = 0;
731
        List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
732
        StringBuilder sb = new StringBuilder();
733
        for (FofoStore store : stores) {
734
            int fofoId = store.getId();
23724 amit.gupta 735
 
31697 amit.gupta 736
            PartnerType yesterdayPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, yesterday);
737
            PartnerType todayPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, today);
738
            if (!yesterdayPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
739
                continue;
740
            }
741
            if (!yesterdayPartnerType.equals(todayPartnerType)) {
742
                upgradedCount++;
31886 tejbeer 743
                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 744
                sb.append("<br>");
31886 tejbeer 745
                LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(), yesterdayPartnerType, todayPartnerType);
746
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, yesterday.withDayOfMonth(1).atStartOfDay(), yesterday.atStartOfDay(), 0, 0);
31697 amit.gupta 747
                for (FofoOrder fofoOrder : fofoOrders) {
748
                    schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
749
                }
30390 amit.gupta 750
 
31697 amit.gupta 751
            }
752
        }
753
        if (upgradedCount > 0) {
32439 tejbeer 754
            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 755
        } else {
32439 tejbeer 756
            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 757
        }
758
    }
30393 amit.gupta 759
 
31697 amit.gupta 760
    @Autowired
761
    private PartnerStatsService partnerStatsService;
30393 amit.gupta 762
 
31697 amit.gupta 763
    // Temporary Method
764
    public void evaluateExcessSchemeOut() throws Exception {
765
        Map<Integer, String> userNameMap = retailerService.getAllFofoRetailerIdNameMap();
766
        Map<Integer, Float> userAmountMap = new HashMap<>();
30393 amit.gupta 767
 
31697 amit.gupta 768
        List<List<?>> rows = new ArrayList<>();
31886 tejbeer 769
        List<String> headers = Arrays.asList("Scheme", "Item", "Partner", "Amount", "Credited On", "Invoice Number", "Sale On", "Scheme Start", "Scheme End", "Active On", "Expired On");
31697 amit.gupta 770
        schemeRepository.selectAll().stream().forEach(x -> {
771
            if (x.getType().equals(SchemeType.OUT)) {
31886 tejbeer 772
                List<SchemeInOut> sioList = schemeInOutRepository.selectBySchemeIds(new HashSet<>(Arrays.asList(x.getId())));
31697 amit.gupta 773
                if (x.getActiveTimestamp() != null) {
774
                    LocalDateTime endDateTime = x.getEndDateTime();
775
                    if (x.getExpireTimestamp() != null && x.getExpireTimestamp().isBefore(x.getEndDateTime())) {
776
                        endDateTime = x.getExpireTimestamp();
777
                    }
778
                    for (SchemeInOut sio : sioList) {
779
                        InventoryItem inventoryItem = null;
780
                        inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
781
                        FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndSerialNumber(
782
                                inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), null, null, 0, 1).get(0);
31886 tejbeer 783
                        Optional<ScanRecord> record = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId()).stream().filter(y -> y.getType().equals(ScanType.SALE)).findFirst();
31697 amit.gupta 784
                        if (record.isPresent()) {
785
                            int fofoId = record.get().getFofoId();
31886 tejbeer 786
                            if (record.get().getCreateTimestamp().isAfter(endDateTime) || record.get().getCreateTimestamp().isBefore(x.getStartDateTime())) {
31697 amit.gupta 787
                                if (!userAmountMap.containsKey(fofoId)) {
788
                                    userAmountMap.put(fofoId, 0f);
789
                                }
790
                                userAmountMap.put(fofoId, sio.getAmount() + userAmountMap.get(fofoId));
791
                                try {
31886 tejbeer 792
                                    rows.add(Arrays.asList(x.getDescription(), itemRepository.selectById(inventoryItem.getItemId()).getItemDescription(), userNameMap.get(fofoId), sio.getAmount(), FormattingUtils.formatDate(sio.getCreateTimestamp()), fofoOrder.getInvoiceNumber(), FormattingUtils.formatDate(record.get().getCreateTimestamp()), FormattingUtils.formatDate(x.getStartDateTime()), FormattingUtils.formatDate(x.getEndDateTime()), FormattingUtils.formatDate(x.getActiveTimestamp()), FormattingUtils.formatDate(x.getExpireTimestamp())));
31697 amit.gupta 793
                                } catch (Exception e) {
794
                                    e.printStackTrace();
795
                                }
796
                            }
797
                        }
798
                    }
799
                }
800
            }
801
        });
31886 tejbeer 802
        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 803
 
31697 amit.gupta 804
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
31886 tejbeer 805
        Utils.sendMailWithAttachment(googleMailSender, new String[]{"amit.gupta@shop2020.in"}, null, "Partner Excess Amount", "PFA", "ListofSchemes.csv", new ByteArrayResource(baos.toByteArray()));
30390 amit.gupta 806
 
31697 amit.gupta 807
    }
30390 amit.gupta 808
 
31697 amit.gupta 809
    public void fetchParnterStats() throws Exception {
810
        Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
811
        ObjectOutputStream oos = null;
812
        FileOutputStream fout = null;
813
        try {
814
            fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
815
            oos = new ObjectOutputStream(fout);
816
            oos.writeObject(partnerStats);
30637 amit.gupta 817
 
31697 amit.gupta 818
        } catch (Exception ex) {
819
            ex.printStackTrace();
820
        } finally {
821
            if (oos != null) {
822
                oos.close();
823
            }
824
        }
32421 amit.gupta 825
        ReporticoCacheTable reporticoCacheTable = reporticoCacheTableRepository.selectByTableName("partnerStat");
826
        if (reporticoCacheTable == null) {
827
            reporticoCacheTable = new ReporticoCacheTable();
828
            reporticoCacheTable.setTableName("partnerStat");
829
            reporticoCacheTable.setLastCreatedTimestamp(LocalDateTime.now());
830
            reporticoCacheTableRepository.persist(reporticoCacheTable);
31697 amit.gupta 831
        } else {
32421 amit.gupta 832
            reporticoCacheTable.setLastCreatedTimestamp(LocalDateTime.now());
31697 amit.gupta 833
        }
834
    }
31008 amit.gupta 835
 
31697 amit.gupta 836
    public void processPriceDrop() throws Exception {
31886 tejbeer 837
        List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetween(LocalDateTime.now(), LocalDateTime.now().minusYears(1));
31697 amit.gupta 838
        for (PriceDrop priceDrop : priceDrops) {
839
            if (priceDrop.getDropAmount() > 0) {
840
                priceDropService.processPriceDrop(priceDrop.getId(), true);
841
            }
842
        }
843
    }
31008 amit.gupta 844
 
31697 amit.gupta 845
    @Autowired
846
    CreditNoteService creditNoteService;
25598 amit.gupta 847
 
31697 amit.gupta 848
    public void sendCreditNote(YearMonth yearMonth) throws Exception {
849
        creditNoteService.issueMonthlyMarginsCN(yearMonth);
850
    }
25598 amit.gupta 851
 
31918 amit.gupta 852
    @Autowired
853
    BrandAgeingLimitRepository brandAgeingLimitRepository;
854
 
855
    @Autowired
856
    AgeingService ageingService;
857
 
858
    public void sendMailForAgeingAlert() throws Exception {
859
        //brandAgeingLimitRepository.selectAll();
860
        Map<String, AgeingModel> ageingModelMap = ageingService.getAllAgeingForSecondary();
861
 
862
        System.out.println(ageingModelMap.size());
863
        List<PartnerAgeingModel> partnerAgeingModels = ageingService.getAllAgeingForTertiary();
864
 
865
 
32084 tejbeer 866
        org.apache.commons.io.output.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 867
 
32084 tejbeer 868
        org.apache.commons.io.output.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()));
31918 amit.gupta 869
        Utils.Attachment attachment1 = new Utils.Attachment("secondary-alert.csv", new ByteArrayResource(byteArrayOutputStream.toByteArray()));
870
        Utils.Attachment attachment2 = new Utils.Attachment("tertiary-alert.csv", new ByteArrayResource(byteArrayOutputStream2.toByteArray()));
871
 
872
        String mailSubject = "Stock ageing Alert";
873
        Utils.sendMailWithAttachments(mailSender, new String[]{"deena.nath@smartdukaan.com"}, null, mailSubject, "PFA", attachment1, attachment2);
874
    }
875
 
32724 amit.gupta 876
    public void rejectPriceDropsOfApprovedImeis() throws ProfitMandiBusinessException {
32690 amit.gupta 877
        priceDropService.rejectPriceDropsOfApprovedImeis();
878
    }
879
 
31697 amit.gupta 880
    private class SaleRoles {
25598 amit.gupta 881
 
31697 amit.gupta 882
        private List<String> l1;
883
        private List<String> l2;
25598 amit.gupta 884
 
31697 amit.gupta 885
        public SaleRoles() {
886
            l1 = new ArrayList<>();
887
            l2 = new ArrayList<>();
888
        }
25598 amit.gupta 889
 
31697 amit.gupta 890
        public List<String> getL1() {
891
            return l1;
892
        }
25598 amit.gupta 893
 
31697 amit.gupta 894
        public List<String> getL2() {
895
            return l2;
896
        }
26945 amit.gupta 897
 
31697 amit.gupta 898
    }
26945 amit.gupta 899
 
31697 amit.gupta 900
    private class FofoReportingModel {
901
        private String code;
902
        private int fofoId;
903
        private String businessName;
904
        private String territoryManager;
905
        private String regionalManager;
906
        private String businessManager;
26945 amit.gupta 907
 
31697 amit.gupta 908
        public String getCode() {
909
            return code;
910
        }
26945 amit.gupta 911
 
31697 amit.gupta 912
        public void setCode(String code) {
913
            this.code = code;
914
        }
26945 amit.gupta 915
 
31697 amit.gupta 916
        public String getBusinessName() {
917
            return businessName;
918
        }
26945 amit.gupta 919
 
31697 amit.gupta 920
        public void setBusinessName(String businessName) {
921
            this.businessName = businessName;
922
        }
26945 amit.gupta 923
 
31697 amit.gupta 924
        public String getTerritoryManager() {
925
            return territoryManager;
926
        }
26945 amit.gupta 927
 
31697 amit.gupta 928
        public void setTerritoryManager(String territoryManager) {
929
            this.territoryManager = territoryManager;
930
        }
26945 amit.gupta 931
 
31697 amit.gupta 932
        public String getRegionalManager() {
933
            return regionalManager;
934
        }
26945 amit.gupta 935
 
31697 amit.gupta 936
        public void setRegionalManager(String regionalManager) {
937
            this.regionalManager = regionalManager;
938
        }
26945 amit.gupta 939
 
31697 amit.gupta 940
        private ScheduledTasks getOuterType() {
941
            return ScheduledTasks.this;
942
        }
26945 amit.gupta 943
 
31697 amit.gupta 944
        @Override
945
        public String toString() {
31886 tejbeer 946
            return "FofoReportingModel{" + "code='" + code + '\'' + ", fofoId=" + fofoId + ", businessName='" + businessName + '\'' + ", territoryManager='" + territoryManager + '\'' + ", regionalManager='" + regionalManager + '\'' + ", businessManager='" + businessManager + '\'' + '}';
31697 amit.gupta 947
        }
26945 amit.gupta 948
 
31697 amit.gupta 949
        @Override
950
        public boolean equals(Object o) {
951
            if (this == o) return true;
952
            if (o == null || getClass() != o.getClass()) return false;
953
            FofoReportingModel that = (FofoReportingModel) o;
954
            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);
955
        }
26945 amit.gupta 956
 
31697 amit.gupta 957
        @Override
958
        public int hashCode() {
959
            return Objects.hash(code, fofoId, businessName, territoryManager, regionalManager, businessManager);
960
        }
26945 amit.gupta 961
 
31697 amit.gupta 962
        public String getBusinessManager() {
963
            return businessManager;
964
        }
26945 amit.gupta 965
 
31697 amit.gupta 966
        public void setBusinessManager(String businessManager) {
967
            this.businessManager = businessManager;
968
        }
25351 tejbeer 969
 
31697 amit.gupta 970
        public int getFofoId() {
971
            return fofoId;
972
        }
25598 amit.gupta 973
 
31697 amit.gupta 974
        public void setFofoId(int fofoId) {
975
            this.fofoId = fofoId;
976
        }
25598 amit.gupta 977
 
31697 amit.gupta 978
    }
26945 amit.gupta 979
 
31697 amit.gupta 980
    @Autowired
981
    WarehouseInventoryItemRepository warehouseInventoryItemRepository;
26945 amit.gupta 982
 
31746 amit.gupta 983
    @Autowired
984
    OfferService offerService;
985
 
986
    @Autowired
987
    PurchaseReturnItemRepository purchaseReturnItemRepository;
988
 
31918 amit.gupta 989
    @Autowired
990
    BrandRegionMappingRepository brandRegionMappingRepository;
991
 
32161 tejbeer 992
    @Autowired
993
    StandAlone standAlone;
32214 jai.hind 994
    @Autowired
995
    ItelImeiActivationNewService itelImeiActivationNewService;
32350 amit.gupta 996
 
997
    public void checkItelImeiActivationNew(LocalDate date, Integer day) throws Exception {
32063 amit.gupta 998
        try {
32223 amit.gupta 999
            itelImeiActivationNewService.checkItelImeiActivationNew(date, day);
32063 amit.gupta 1000
        } catch (Throwable e) {
1001
            throw new Exception(e);
1002
        }
32223 amit.gupta 1003
    }
32062 amit.gupta 1004
 
32511 amit.gupta 1005
    @Autowired
1006
    PurchaseReturnService purchaseReturnService;
1007
 
32682 amit.gupta 1008
    @Autowired
1009
    JavaMailSender javaMailSender;
1010
 
32223 amit.gupta 1011
    public void test() throws Exception {
32690 amit.gupta 1012
        System.out.println("Hello from test");
32724 amit.gupta 1013
        //this.calculateInterestAccured();
32690 amit.gupta 1014
        //sendMailOfHtmlFormat(javaMailSender, new String[]{"amit.gupta@smartdukaan.com"}, "hello", null, "Hello");
32698 amit.gupta 1015
        //priceDropService.rejectPriceDropsOfApprovedImeis();
32511 amit.gupta 1016
        //Create return
32600 amit.gupta 1017
        //this.updatePartnerLimit();
32607 ranu 1018
        //creditNoteService.sendCnMails(YearMonth.now().minusMonths(2));
32690 amit.gupta 1019
        //orderService.createMissingScratchOffers();
32728 amit.gupta 1020
        LocalDateTime debitNoteDate = LocalDate.of(2023, Month.SEPTEMBER, 30).atStartOfDay();
32698 amit.gupta 1021
        Map<Integer, Set<String>> fofoIdImeiReturnMap = new LinkedHashMap<>();
32728 amit.gupta 1022
        fofoIdImeiReturnMap.put(167996137,new HashSet<>(Arrays.asList("357415663618188","357415663627767","866399066670844","866399066672022","866399066715284","866399066718205","866399066721126","866399066725069","869350065039538","869350065061318","869350065067596","869350065068016","869350065068974","869350065086794","869350065090317","869350065094558","869350065098435","869350065136177","869350065155391")));
1023
        fofoIdImeiReturnMap.put(175135227,new HashSet<>(Arrays.asList("356612600793998","356612600803870","359691642134905","359691642145604","862628060221475","863879060089334","864985065856988","865210064246753","865753067332328","865753069773248","866399065879826","866399066626606","866399066664540","866399066734129","866807068958710","867158063179137","868905064220974","868905065216294","869350065013970","869350065182791")));
1024
        fofoIdImeiReturnMap.put(175138674,new HashSet<>(Arrays.asList("861831062447822","864920066684790","865753067320703","865753069672200","866807064015176","868905064555858","869916067520178","869916067520632")));
1025
        fofoIdImeiReturnMap.put(175138823,new HashSet<>(Arrays.asList("861530062830587","861530063587103","861530063599348","861679065410440","864985066215804","864985066876621","865210065762170")));
1026
        fofoIdImeiReturnMap.put(175138863,new HashSet<>(Arrays.asList("356393508712964","356393508722468","356393508722823","356393508723342","356393508723383","356393508724720","356393508728820","356393508744124","356393508745527","356393508747341","356393508748760","356393508759668","356393508762829","356393508775607","356393508793485","356393509343983","356393509344924","356393509345723","356393509351200","356393509352489","356612600709275","356612600709317","356612600712238","356612600713210","356612600716791","356612600719654","356612600720215","356612600720694","356612600721353","356612600721734","356612600722690","356612600722815","356612600724753","356612600725511","356612600725792","356612600726378","356612600726899","356612600727673","356612600727996","356612600730719","356612600733291","356612600733770","356612600733952","356612600737532","356612600738217","356612600738530","356612600740395","356612600747192","356612600748778","356612600749438","356612600750154","356612600752218","356612600752739","356612600756011","356612600757738","356612600758256","356612600758470","356612600758850","356612600758876","356612600761573","356612600804555","356612600812210","356612600817938","356612600824231","356612600826178","356612600827010","356612600827135","356612600827234","356612600827713","356612600829511","356612600829974","356612600830816","356612600830873","356612600831517","356612600833158","356612600834651","356612600836094","356612600837555","356612600928594","356612600930459","356612600942892","356612600959219","356612600965877","356612600966974","356612600967378","356612600969135","356612600973194","356612600974192","356612600974739","356612600975017","356612600975553","356612600977435","356612600980751","356612600980876","356612600981411","356612600981932","356612600981973","356612604433070","356612604454373","356612604455479","356612604455750","356612605269556","356612605278318","356612605280736","356612605281130","356612605286410","356612605289455","356612605289679","356612605290438","356612605290933","356612605291394","356612605292152","356612605293697","356612605294091","356612605294455","356612605294554","356612605295254","356612605296559","356612605296575","356612605296633","356612605297110","356612605710179","356612605715095","356612605716911","356612605717919","356612605718412","356612605718495","356612605718636","356612605718651","356612605718776","356612605718818","356612605718834","356612605718859","356612605718891","356612605718917","356612605718933","356612605718990","356612605719139","356612605719212","356612605719253","356612605719410","357014953177490","357014953186731","357014953187713","357014953187754","357014953188810","357014953189099","357014953189412","357014953189917","357014953190071","357014953191392","357014953191871","357014953191897","357014953191913","357014953191970","357014953192291","357014953192556","357014953193018","357014953193091","357014953193174","357014953193356","358382747351997","358382747523579","358382747523975","358382747555217","358382747557916","358382747572691","358382747573152","358382747575231","358382747575579","358382747575652","358382747576395","358382747576510","358382747576619","358382747576692","358382747576759","358382747576791","358382747576973","358382747576999","358382747577138","358382747577377","358382747577690","358382747577856","358382747578276","358382747578292","358382747584373","358382747584514","359197382621184","359197382647106","359197382647387","359197382648427","359197382648443")));
1027
        fofoIdImeiReturnMap.put(175138870,new HashSet<>(Arrays.asList("350923627169328","350923627198863","350923627875049","351336673336049","351336673340546","355724848495830","355724848499154","356455410153452","356455410159277","356612605719956","356612605720194","359508181975748","359508182024801","359691642145406","861831062564667","861831062599507","861831062599762","865753069263646","865753069651063","865821064720405","865821064760781","865821065335666","866399065697467","866399065730789","866399065732082","869350061853536","869350061926514","869350062669832","869350062681233","869350062681373","869350062684294")));
1028
        fofoIdImeiReturnMap.put(175138942,new HashSet<>(Arrays.asList("350031479190473","350250293972177","350250293974942","353140544973073","353397823400224","353397824106911","353397824214244","359118661998473")));
1029
        fofoIdImeiReturnMap.put(175139107,new HashSet<>(Arrays.asList("351733712184093","351733712368928","353140545077080","353140545590280")));
1030
        fofoIdImeiReturnMap.put(175139176,new HashSet<>(Arrays.asList("359691642003241","359691642003506","359691642010907","359691642019742","359691642061785","359691642068624","359691642076148","359691642083284","359691642115706","359691642115888","359691642134921","359691642137346","359691642137882","359691642138443","359691642141561","359691642141660","359691642141868","359691642142288","359691642144508","359691642144904","359691642146545","359691642147725","359691642151404","359691642151727","359691642152808","359691642179207","359691642179629","866807067510173","866807067519232","869296069014474","869296069015158","869296069020299","869296069020596","869296069021271")));
1031
        fofoIdImeiReturnMap.put(175139180,new HashSet<>(Arrays.asList("865279060303819","865279060948159","866399065674821","866399065696840","866399065701541","866559062503097","866807064663835","866807064664536","866807064664577","866807064683379","866807065123896","869236065764458","869236065883670")));
1032
        fofoIdImeiReturnMap.put(175139187,new HashSet<>(Arrays.asList("351166973169331","351166973171592","356393509346663","356393509355805","356612604544991","356612604545691","357014954899233","357014954901153","357014954934873","357014954935672","357014954937231","357014954937678","357014954938890","359197382629682","359197382647866","359197382647882","359691642142205","862628068228175","863879068173957","864985065825629","866399066067009","866399066075705","866641067104095","867158061549711","867492061861176")));
1033
        fofoIdImeiReturnMap.put(175139223,new HashSet<>(Arrays.asList("350250293971054","353140545612282","863879062572436","864920063982718","864987060011015")));
1034
        fofoIdImeiReturnMap.put(175139242,new HashSet<>(Arrays.asList("862628066855359","862628068472815","863879060436170","863879061140474","864690068767337","864920067190219")));
1035
        fofoIdImeiReturnMap.put(175139261,new HashSet<>(Arrays.asList("865037063916197","865037063921239","866807066673311")));
1036
        fofoIdImeiReturnMap.put(175139295,new HashSet<>(Arrays.asList("353305256516622","353305256517703","354849877296808","354849877299240","359691642157203","359691642159746","359691642167608","860374069783197","861530062947282","864985066061448","866399062765986","866399065001280","866399066743625","866726066870570","866807064443717","866807064654396")));
1037
        fofoIdImeiReturnMap.put(175139328,new HashSet<>(Arrays.asList("861784060313035","862628068090153","862628068262117","863879062228856","863879062320554","864985062056681","864985062215402","865210064597296","865210065180431","866132066506233")));
1038
        fofoIdImeiReturnMap.put(175139329,new HashSet<>(Arrays.asList("351733714004521","359118663635321","865279064602331","866399062751085","866399062758882")));
1039
        fofoIdImeiReturnMap.put(175139333,new HashSet<>(Arrays.asList("864985062090243","864985065791169","864985065840040","864985065844984","866399065642240","866399066060848","866399066707505","866399066753624","869350061832191","869350061851415","869350062255178","869350062608657")));
1040
        fofoIdImeiReturnMap.put(175139364,new HashSet<>(Arrays.asList("353305256533601","353305256536968","359691642106465","359691642139300","359749531615929","862628066855631","863653060019751","863653060270255","863879060439919","865279066559992","865821063929064","865821064323424","866807065289937","867158060809637","868666068787083","868905064544076")));
1041
        fofoIdImeiReturnMap.put(175139372,new HashSet<>(Arrays.asList("351166972285419","351166975524178","351166976059059","351166976064158","351166976067094","357014952943934","357014952944353","357014952945574","357014952949154","357014952949196","357014952950657","357014952951937","357014952952950","357014952953214","357014952953750","357014952953990","357014952954550","357014953188570","357014953189578","357014953190576","357014953191152","357014953191236","357014953192572","357014953192796","357014953193836","864985061925787","864985061993587")));
1042
        fofoIdImeiReturnMap.put(175139386,new HashSet<>(Arrays.asList("350250292546261","350250293896210","350386305533381","352450543770565","353397822543180","357014953173978","359749531155942","863879068182354","865037067599551","867492060235059","869350061949755")));
1043
        fofoIdImeiReturnMap.put(175139390,new HashSet<>(Arrays.asList("350339951003118","352450548485607","353397824198728","353397824258225","354849877087843","354849877105843","354849877151664","354849877296162","860607069060599","863879062659092","864848067855947","865037065956555","865865062255872","866807066486896","866807068958298","868701069311433","868905064220750","869076064654809","869350062196075","869350062666473")));
1044
        fofoIdImeiReturnMap.put(175139392,new HashSet<>(Arrays.asList("354301731104828","354301731181784","860398069424833","861784061894090","864480066119602","864480066130047","866399065988924","866399066060061","866807064683999","867158060809975","867492060235752")));
1045
        fofoIdImeiReturnMap.put(175139396,new HashSet<>(Arrays.asList("350339951029758","864848067933108","864848067965860","865279060304411","865753067321909","865753068700747","866399066669069","866399066721365","869076064651763","869350061904495","869350062192991")));
1046
        fofoIdImeiReturnMap.put(175139404,new HashSet<>(Arrays.asList("352450544013585","352450544013940","352450544014344","352450547322587","352450547322744","358142883505941","359749531269867","868905065214570")));
1047
        fofoIdImeiReturnMap.put(175139410,new HashSet<>(Arrays.asList("350923626587702","350923626677503","350923626689383","350923627241283","350923627259541","351336673333228","351336673334580","351336673344449","352450544501886","352450545460561","352450545826068","353305256494044","353305256519709","356393509343744","356393509347224","357983840349969","357983840350322","357983840350546","357983840351486","357983840352344","357983840352823","357983840352864","357983840353144","357983840357582","357983840359067","359691642108461","359691642174968","863653061135671","863653061177012","863653062654993","863653062669439","864288064103175","864985065813260","865279063733434","865753069777728","866399065698101","866399065717323","866399065719949","866399065726944")));
1048
        fofoIdImeiReturnMap.put(175139422,new HashSet<>(Arrays.asList("351166975963533","351166975976295","354849877717662","354849877719742","354849877726705","354849877729444","354849877729642","354849877730046","354849877730665","354849877731903","354849877734063","354849877743221","355724848410193","355724848412058","355724848423378","355724848425316","355724848425357","355724848426454","355724848426595","355724848426736","355724848426777","355724848428617","356393508695383","356393508713046","356393508722385","356393508722542","356393508727806","356393508733424","356393508736880","356393508737680","356393508738902","356393508768206","356393508768560","356393508773263","356393508796926","356612600716692","356612600735577","356612600736195","356612600736997","356612600740155","356612600742854","356612600743613","356612600746616","356612600747051","356612600748455","356612600926655","356612600928131","356612600928230","356612600929675","356612600934873","356612600936019","356612600943858","356612600945135","356612600947453","356612600949996","356612600951455","356612600951810","356612600953758","356612600956934","356612600962254","356612600963393","356612600963419","356612600981551","356612600983375","356612600983912","359691642043445","359691642047909","359691642049368","359691642051380","359691642089901","359691642114766","359691642135084","359691642135241","359691642141223","359691642144565","359691642145109","359691642152600","359691642153160","359691642155645","359691642156841","861530062172105","861530062174382","864985065768787","864985065792944","866807064663710")));
1049
        fofoIdImeiReturnMap.put(175139425,new HashSet<>(Arrays.asList("350386305671629","350386306043125","863653060563873","863653060564970","865037065022895","865037065094795","868905065657356","868905066089856")));
1050
        fofoIdImeiReturnMap.put(175139426,new HashSet<>(Arrays.asList("359197382598762","359197382619329","359197382623701","359197382629302","359197382630680","359197382637305","359197382641943","359197382645480","359197382647304","359197382647528","860374069742052","861530063115582","862628068090534","862628068266092","863653061146876","863653061150217","866807064452577","867158060215595")));
1051
        fofoIdImeiReturnMap.put(175139429,new HashSet<>(Arrays.asList("352094722900948","352094722908982","353305256468261","353305256536604","355724848504375","356612605716879","358382747569358","358382747580439","359197382650704","359197382651967","359691642166485","359691642172160","861530063122463","864848067843141","864848067935947","864985066066827","866132060383811","866399062773725","866399065623760","868666065635608","868666065730581","868666067425545","868666067819143")));
1052
        fofoIdImeiReturnMap.put(175139431,new HashSet<>(Arrays.asList("860374069332672","862892060190615","863879063992419","864985061894884","865210064232472","865821063930708","865821065112404","866807067509712","867212063822897","867212068439556")));
1053
        fofoIdImeiReturnMap.put(175139440,new HashSet<>(Arrays.asList("354849877295602","354849877296600","861663069285230","864985066226280","864985066330744","866399065940081","866399066065086","866807064443857","866807067122359","867212068441537","867212068443053","869350065159799","869350065160276","869916067368859")));
1054
        fofoIdImeiReturnMap.put(175139442,new HashSet<>(Arrays.asList("861530062218262","861530062870823","861530062965466","866559062488851","866559062489834","866559062491699")));
1055
        fofoIdImeiReturnMap.put(175139449,new HashSet<>(Arrays.asList("359749531470226","359749531473402","359749531625381","359749531637501","359749531767209","861784061890593","865279065935557","865279066560370","866399064536229","866399065066721","866399065302282","866399065699125","866399065717349","866399065734161")));
1056
        fofoIdImeiReturnMap.put(175139451,new HashSet<>(Arrays.asList("352450547378647","862628068576730","865865067474338","866132066698774","867492062851556","868666065861022")));
1057
        fofoIdImeiReturnMap.put(175139452,new HashSet<>(Arrays.asList("350031479647969","350191506027955","350655759940262","351733714485035","353140544946657","353397823356202","353397823400539","355724848507774","864848068287108","864985065787142","864985065837145","868701061018192","869106063245851","869106065767977")));
1058
        fofoIdImeiReturnMap.put(175139457,new HashSet<>(Arrays.asList("357014950300871","861530062195841","863653061134492","863653061138915","864848068172664","864985065981687","866399062770705","866399065110404","868701063248771")));
1059
        fofoIdImeiReturnMap.put(175139459,new HashSet<>(Arrays.asList("352450543885389","352450544527246","354301731188268","359680163322346","866641067145718","868701063374437","869076063987929","869076064359821")));
1060
        fofoIdImeiReturnMap.put(175139463,new HashSet<>(Arrays.asList("350923626635949","350923626636269","350923626690902","861784060309637","864848068046108","864848068051546","866807064687750","869916067368297")));
1061
        fofoIdImeiReturnMap.put(175139465,new HashSet<>(Arrays.asList("351613386249440","351613387095180","861663068329336","861663069069253","861784060309918","864985065810969","865753067325041","865753067353860","866807064687131","867212067917156","867212068434714","869350061950019","869350062195671","869350062386452","869916067369071")));
1062
        fofoIdImeiReturnMap.put(175139466,new HashSet<>(Arrays.asList("359749531534823","359749531619442","861663069053398","861663069069857","863879062138451","866399065107301","866399065212788","866807067493537","866807067515230","867212063830312","867212068447013","869916067366572")));
1063
        fofoIdImeiReturnMap.put(175139467,new HashSet<>(Arrays.asList("350250294009631","350250294416570","351613386626407","351613386634724","351613386881341","351613386881721","866807063687975","866807064692651","867212063830239","867212067915812","867212068434896","867212068443756","867212068445470")));
1064
        fofoIdImeiReturnMap.put(175139468,new HashSet<>(Arrays.asList("863653065382279","864690068728354","864690068728412","865279066339650","866132063736916","866132064179710")));
1065
        fofoIdImeiReturnMap.put(175139472,new HashSet<>(Arrays.asList("351613386632884","351613386906387","357415663628286","860374069457230","863879063994217","863879063996659","864848068065868","865037066313699","866399066697367","866807064662399","867212067916190","867212068443236","868905065660756","869236068140771","869350062605497")));
1066
        fofoIdImeiReturnMap.put(175139477,new HashSet<>(Arrays.asList("861663068335796","861663069050774","861663069051590","863879061279330","863879062320612","864288064231455","864647061805472","866807063530852","866807063565775","867212063825619","867212068442154")));
1067
        fofoIdImeiReturnMap.put(175139489,new HashSet<>(Arrays.asList("350031476683801","350031477646419","863653067155012","865037065748796","865037068846316","865210063382351","865279065239570","866399066070789","866559062481237","866641067273452","867492061243532","868652062503601","868666065959727","868666067777804","868701062941111","868701069479172")));
1068
        fofoIdImeiReturnMap.put(175139490,new HashSet<>(Arrays.asList("350031477636618","351733715724002","352120260187174","352953554051643","355724848426439","357014954930939","863653061893972","865821060228742","866399066062984","866399066069989","868652062617484","868666065958901","868905064290456","868905064825012","869076064649502")));
1069
        fofoIdImeiReturnMap.put(175139493,new HashSet<>(Arrays.asList("350250294029969","350250294131203","350339951594819","351733715279890","351733715611290","356612605730052","358382747584456","358382747584910","860695063377770","862628066338554","862628067568811","863879066397897","864920064911971","868701063410017","868701067287973")));
1070
        fofoIdImeiReturnMap.put(175139496,new HashSet<>(Arrays.asList("350386305879537","860695063378810","863879062651750","864920069103590","865037066073517","865210064600017","865279067176432","865865062952171","866807068662916","866807069402130","867158063179178","867492063171996","868905065232135")));
1071
        fofoIdImeiReturnMap.put(175139505,new HashSet<>(Arrays.asList("352450547876988","353305256493285","354301731180687","862628066338018","863653064984612","865037066073772","865210064252231","865210064255556","865279066156054","866399065988643","867158063267031","867492063304399","869076064640725","869236066123035")));
1072
        //orderService.createMissingScratchOffers();
1073
        /*LocalDateTime debitNoteDate = LocalDate.of(2023, Month.NOVEMBER, 30).atStartOfDay();
1074
        fofoIdImeiReturnMap.put(175138983, new HashSet<>(Arrays.asList("353350901603805", "353823611691989", "862869067816608", "862869067931803", "862869067934302", "867022067784724", "867022067840922")));
32725 amit.gupta 1075
        fofoIdImeiReturnMap.put(175139377, new HashSet<>(Arrays.asList("350048273593173", "351063314519862", "352950861869717", "352950861876696", "866399064994105", "864480065905886", "864480065906900")));
32724 amit.gupta 1076
        fofoIdImeiReturnMap.put(175139404, new HashSet<>(Arrays.asList("867022067841961", "352450547322587", "355056447721856", "355056447740690", "355056447741177", "860605068562631", "863511060840651", "863511060841378", "863511060914118", "863511060961879", "863511061221752", "866755064176375")));
1077
        fofoIdImeiReturnMap.put(175139414, new HashSet<>(Arrays.asList("350145991734970", "350339953960984", "350339953963632", "351733718884472", "351733718929012", "352950861872059", "352950861872075", "352950861874030", "354198344830744", "354198345065548", "862286069518415", "862529064459378", "866151068236995", "866151068247919", "869922063380898", "869922063381656", "869947077546051")));
1078
        fofoIdImeiReturnMap.put(175139603, new HashSet<>(Arrays.asList("350339953953468", "350339953958186", "350386308377042", "352838657138621", "353370808836100", "355622834350540", "357594161087250", "861220070279031", "861220073282339", "861628061583296", "862286066718497", "862286066867179", "862869068956981", "862869069415946")));
32726 amit.gupta 1079
        fofoIdImeiReturnMap.put(175139223, new HashSet<>(Arrays.asList("862637062003476", "868666065959545", "869106065845393", "869106065847233", "869947077513630", "869947077540930", "869947077542910", "869947077543298")));
32724 amit.gupta 1080
        fofoIdImeiReturnMap.put(175139285, new HashSet<>(Arrays.asList("353370808735872", "355622834359251", "860374064583139", "860400067776667", "860492069299517", "860929064759078", "862637066562378", "862637066563079", "862637066745130", "862637066775251", "862637066777992", "862892065489715", "862892066355055", "864179060269989", "865037060047731")));
1081
        fofoIdImeiReturnMap.put(175139553, new HashSet<>(Arrays.asList("351733718537047", "353370808666192")));
1082
        fofoIdImeiReturnMap.put(175139557, new HashSet<>(Arrays.asList("860374064569815", "860374067374874", "860492067749570", "860492069303830", "860492069537536", "862498065298617", "862498066046817", "862498066754519", "862835068019914", "862835068021639", "864179060272900", "864179063089665", "865458067432835", "865458067439095")));
1083
        fofoIdImeiReturnMap.put(175139079, new HashSet<>(Arrays.asList("863055065444598", "867791061938714")));
1084
        fofoIdImeiReturnMap.put(175139236, new HashSet<>(Arrays.asList("350339952958062", "860929062956296", "862637063125294", "862965069308196", "863405066565836", "864179060270185", "864179060273361", "864214065436596", "864712067373451", "864712067398953", "865458066638077", "865458067514095")));
1085
        fofoIdImeiReturnMap.put(175139403, new HashSet<>(Arrays.asList("860929063010333", "861628060810898", "863405068051579", "864712067990494")));
32700 amit.gupta 1086
        fofoIdImeiReturnMap.put(175138929, new HashSet<>(Arrays.asList("867791060999618")));
32724 amit.gupta 1087
        fofoIdImeiReturnMap.put(175139488, new HashSet<>(Arrays.asList("862637062917352", "862892065474915", "862892066509412", "863055065684995", "863055067139550", "864214063273074", "864214065450571", "864214065450654", "864987061051317")));
1088
        fofoIdImeiReturnMap.put(175138864, new HashSet<>(Arrays.asList("355358274454290", "355358274454555", "355358274455453", "355358274455537", "355358274456097", "355358275888132", "355358275901851", "355358276874396", "355358276879973", "355358277017854", "355358277808930", "355358277810118", "355358277810373", "355358277811058", "355358277811397", "355358277811876", "355358277812353", "355358277813955", "355358277815695", "355358277815737", "355480685141892", "355480686958674", "359197384540861", "359197384543501", "860374067465995", "860929063012297", "863405066559979", "867791060998032", "351336672377002", "351336672383703", "352764973036382", "352764973045169", "352764977689004", "352764977691141", "352764977695621", "352764977696447", "351166972268175", "351166972279990", "351166972285336", "351166972287894", "353305256496304", "353305256507605", "353305256518040", "353305256518982", "354849877079600", "354849877295065", "354849877296287", "354849877297202", "354849877299026", "355724848508657", "356393509334321", "356393509337605", "356393509345384", "356393509345442", "356393509355409", "351166974789038", "351166974794053", "351166974797676", "351166974797890", "351166974798070", "351166974798450", "351166974798492", "351166974798633", "351166974800736", "351166974801676", "351336670217747", "351336670445504", "351336670446304", "351336670456642", "352067619066411", "352067619070694", "352067619098356", "352067619099693", "352067619100335", "352067619101150", "352067619101473", "352067619101556", "353305255445005", "355724849671033", "355724849691692", "355724849693011", "355724849693375", "355724849695057", "355724849697194", "355724849697350", "355724849697756", "355724849698416", "355724849698598", "355724849698978", "355724849699174", "355724849699299", "355724849699935", "355724849700097", "355724849700295", "355724849700394", "355724849700733", "355724849700832", "355724849700899", "356393509097142", "357014950050815", "357014950065359", "357014950066217", "357014950066258", "357014950066639", "358382744463993", "358382744464470", "358382744473174", "358382744473596", "358382744474677", "358382744474750", "358382744475518", "358382744476110", "358382744476193", "358382745346619", "359197380403395", "359197381846709", "359197381851303", "359903979713619")));
1089
        fofoIdImeiReturnMap.put(175138934, new HashSet<>(Arrays.asList("860929064688251", "862637062015272", "862637062837857", "862637062921099", "862637062921271", "862637063124958", "862637063137752", "863055067139956", "864179060220503", "864179060221048", "864179060273742", "864214065707814", "864288064845395")));
1090
        fofoIdImeiReturnMap.put(175139149, new HashSet<>(Arrays.asList("860374063780793", "862637063282814", "862637063713057", "863055067131870", "864214062184710")));
1091
        fofoIdImeiReturnMap.put(175139283, new HashSet<>(Arrays.asList("860374064569799", "860374064582479", "860929063010473", "862637062915190", "862637062918673", "862637063718551", "863055067133553", "864214065415053", "864214065718316", "865037060045230", "865037060048192")));
1092
        fofoIdImeiReturnMap.put(175139355, new HashSet<>(Arrays.asList("350339952649414", "350896232452968", "350896232580032", "351733718515506", "351733718596589", "351733718905673", "352838656953343", "861628060809619", "861628060813553", "861628060819675", "862869068954929", "862869068968804", "862869069166424", "862869069366123", "862869069369481")));
1093
        fofoIdImeiReturnMap.put(175138859, new HashSet<>(Arrays.asList("357594161083416", "860374067399236", "860929064759391", "864179060270029", "864179060604904", "864712067991435", "864712068260038", "865458066748793", "865626062874116", "867791061987539", "868905064256499", "860398068747853", "869236069342236", "351336670452302", "351336670454068", "355724849685355", "355724849688599", "358382744467630", "864987064817755", "867492068859553")));
1094
        fofoIdImeiReturnMap.put(175138897, new HashSet<>(Arrays.asList("860400066397846", "863405066558450", "863405068130498", "864214065454896", "864214065769475", "865458066767496", "869106063548577", "869947077514075", "869947077543975", "352764977690309", "860188066517709", "864480062533202", "865821064849964", "862628061687633", "863653066318595", "867492066969974", "867492068898411", "868828062170514", "868828065147139")));
1095
        fofoIdImeiReturnMap.put(175139138, new HashSet<>(Arrays.asList("861220070263134", "861220070283132", "861628061572554", "862286069523852", "862286069528133", "862286069528414", "862637062836339", "862637062915596", "862637062916438", "862637063712356", "862637063715193", "862892065489814", "862892065489855", "863055065683773", "865753068715786", "865753068819083", "869947079470136")));
1096
        fofoIdImeiReturnMap.put(175139500, new HashSet<>(Arrays.asList("860929062955959", "861220072589031", "862637062836099", "863055065443897", "865458066641816")));
1097
        fofoIdImeiReturnMap.put(175139608, new HashSet<>(Arrays.asList("352950861864965", "860400066395949", "860400068551127", "861763060427045", "862286062845872", "862286066868839", "862637062836214", "862637062838392", "862637062920877", "862637063716092", "862902068546492", "864480069195443")));
1098
        fofoIdImeiReturnMap.put(175138958, new HashSet<>(Arrays.asList("860929064141491", "860929064285330", "352450549703503", "861784062194011", "863653061349314", "863879062658219", "350339950517142", "862628062300293", "352094721864624", "864690067111651")));
1099
        fofoIdImeiReturnMap.put(175139570, new HashSet<>(Arrays.asList("352336422235137", "352691624423463")));
1100
        fofoIdImeiReturnMap.put(175135227, new HashSet<>(Arrays.asList("350592162345575", "350592162354759", "350592162355210", "350592162418356", "352450549335363", "355358274467359", "355358276990416", "359197384541380", "359197384542842", "359571521176492", "359571521187713", "860374063778995", "863055065444556", "864179060274104", "864179060604987", "864214065708275", "864712067373816", "865626063758532", "868905060763019", "868905062586178", "350571688017090", "350923626878721", "351336672360040", "351336672380824", "351336672420406")));
1101
        fofoIdImeiReturnMap.put(175138833, new HashSet<>(Arrays.asList("863405068052353", "864712067372511", "864712067373675", "865037060048937", "867791062003252")));
1102
        fofoIdImeiReturnMap.put(175130896, new HashSet<>(Arrays.asList("351613388352143", "351613388352762", "351733719029002", "355358274140857", "355358274146177", "355358274159295", "355358278067650", "355358278085918", "355358278089779", "355358278091130", "355480686960431", "355480686968012", "359571521218096", "359571521226172", "860400066394421", "860400068543843", "860400068544643", "862286066866031", "862637061999336", "864712067376710", "864712067992110", "868666065959784", "868666065972340")));
1103
        fofoIdImeiReturnMap.put(175139320, new HashSet<>(Arrays.asList("350592162342796", "350592162363552", "350592162366274", "350592162378451", "350592162381836", "350592162398053", "350592162400396", "350592162401279", "350592162402574", "350592162402632", "350592162403374", "350592162403911", "350592162404992", "350592162405270", "350592162405395", "350592162405510", "350592162405619", "350592162405775", "350592162405833", "350592162405973", "350592162406013", "350592162406096", "350592162406153", "350592162406195", "350592162406211", "350592162406237", "350592162406476", "350592162406518", "350592162406898", "350592162406997", "350592162407177", "350592162407458", "350592162407615", "350592162407839", "350592162407896", "350592162407953", "350592162408191", "350592162408290", "350592162408639", "350592162408753", "350592162408993", "350592162409074", "350592162409157", "350592162409199", "350592162409314", "350592162409496", "350592162409793", "350592162409876", "350592162409934", "350592162410031", "350592162410296", "350592162410338", "350592162410494", "350592162410619", "350592162410759", "350592162410957", "350592162410973", "350592162411195", "350592162411435", "350592162411674", "350592162411815", "350592162412235", "350592162412813", "350592162412870", "350592162413092", "350592162413357", "350592162413613", "350592162413811", "350592162414017", "350592162414132", "350592162414298", "350592162414678", "350592162414710", "350592162414793", "350592162415352", "350592162415857", "350592162416012", "350592162416053", "350592162417218", "350592162417572", "350592162417754", "350592162417994", "359571521162757", "359571521164159", "359571521164258", "359571521176757", "359571521178050", "359571521179314", "359571521179652", "359571521179736", "359571521180296", "359571521180379", "359571521180973", "359571521181153", "359571521181237", "359571521181518", "359571521181534", "359571521181617", "359571521181633", "359571521181716", "359571521181757", "359571521182011", "359571521182094", "359571521182573", "359571521183076", "359571521183530", "359571521183597", "359571521183852", "359571521184637", "359571521184819", "359571521185758", "359571521186038", "359571521186392", "359571521186715", "359571521186798", "359571521187952", "359571521188299", "359571521188570", "359571521188596", "359571521188612", "359571521188794", "359571521188877", "359571521188992", "359571521189891", "359571521189974", "359571521190113", "359571521190238", "359571521190550", "359571521192671", "359571521193893", "359571521194156", "359571521194511", "359571521194636", "359571521194859", "359571521194974", "359571521195377", "359571521195435", "359571521196490", "359571521196656", "359571521196672", "359571521197019", "359571521197779", "359571521200979", "359571521201993", "359571521202397", "359571521203858", "359571521204815", "359571521211174", "359571521216793", "359571521217411", "359571521218195", "359571521219011", "359571521219193", "359571521220472", "359571521221595", "359571521221876", "359571521222130", "359571521222510", "359571521222692", "359571521223336", "359571521223773", "359571521224136")));
1104
        fofoIdImeiReturnMap.put(175138834, new HashSet<>(Arrays.asList("350592162395158", "350592162397873", "350592162398699", "350592162401352", "350592162402194", "350592162402251", "350592162402319", "350592162403150", "350592162403317", "350592162403416", "350592162404034", "350592162404372", "350592162404430", "350592162404810", "350592162405577", "350592162405635", "350592162405916", "350592162406138", "350592162406534", "350592162407417", "350592162407631", "350592162407698", "350592162407755", "350592162407813", "350592162408118", "350592162408274", "350592162408373", "350592162408415", "350592162408654", "350592162408738", "350592162408878", "350592162408894", "350592162408910", "350592162408951", "350592162409090", "350592162409231", "350592162409355", "350592162409512", "350592162409579", "350592162409819", "350592162410510", "350592162410635", "350592162410650", "350592162411112", "350592162411278", "350592162411351", "350592162413134", "350592162413191", "350592162413274", "350592162413316", "350592162413415", "350592162413514", "350592162413555", "350592162413670", "350592162414355", "350592162414892", "350592162415154", "350592162415212", "350592162415238", "350592162415451", "350592162415634", "350592162415790", "350592162415873", "350592162415998", "350592162416095", "350592162416194", "350592162416475", "350592162416871", "350592162416939", "350592162417010", "350592162417531", "350592162417556", "350592162417655", "350592162417978", "350592162418133", "350592162418430", "350592162418596", "350592162418653", "350592162418711", "359571521153673", "359571521154259", "359571521156379", "359571521158136", "359571521170073", "359571521170974", "359571521171394", "359571521171634", "359571521171998", "359571521172137", "359571521173317", "359571521173572", "359571521174075", "359571521174299", "359571521174372", "359571521174430", "359571521174455", "359571521174471", "359571521174596", "359571521174653", "359571521174679", "359571521174711", "359571521174893", "359571521175072", "359571521175130", "359571521175791", "359571521175890", "359571521176112", "359571521177052", "359571521177557", "359571521177938", "359571521178332", "359571521178555", "359571521178597", "359571521179611", "359571521179710", "359571521179892", "359571521179918", "359571521180056", "359571521180072", "359571521180338", "359571521180411", "359571521180510", "359571521180676", "359571521180791", "359571521180833", "359571521180874", "359571521181179", "359571521181195", "359571521181336", "359571521181377", "359571521181419", "359571521181559", "359571521181591", "359571521181856", "359571521182078", "359571521182136", "359571521182631", "359571521182813", "359571521182938", "359571521183050", "359571521183134", "359571521183159", "359571521183779", "359571521183894", "359571521184058", "359571521184090", "359571521184215", "359571521184355", "359571521184371", "359571521184397", "359571521184512", "359571521184538", "359571521184652", "359571521184694", "359571521184710", "359571521184934", "359571521185097", "359571521185337", "359571521185394", "359571521185493", "359571521185618", "359571521185691", "359571521185717", "359571521185790", "359571521185873", "359571521186012", "359571521186095", "359571521186178", "359571521186251", "359571521186335", "359571521186350", "359571521186475", "359571521186517", "359571521186533", "359571521186590", "359571521186699", "359571521187119", "359571521187630", "359571521187655", "359571521187739", "359571521188232", "359571521188455", "359571521188695", "359571521188711", "359571521188919", "359571521188976", "359571521189156", "359571521189636", "359571521189719", "359571521189735", "359571521189818", "359571521189875", "359571521190170", "359571521190311", "359571521190394", "359571521190717", "359571521190758", "359571521190873", "359571521191079", "359571521191095", "359571521191111", "359571521191251", "359571521191293", "359571521191319", "359571521191434", "359571521191459", "359571521191491", "359571521191574", "359571521191590", "359571521191715", "359571521191830", "359571521191897", "359571521191939", "359571521191954", "359571521191996", "359571521192218", "359571521192416", "359571521192531", "359571521192614", "359571521192655", "359571521192713", "359571521192739", "359571521192754", "359571521192770", "359571521192796", "359571521192853", "359571521192911", "359571521192978", "359571521193018", "359571521193075", "359571521193158", "359571521193174", "359571521193232", "359571521193455", "359571521193471", "359571521193570", "359571521193612", "359571521193711", "359571521193752", "359571521193794", "359571521193836", "359571521194495", "359571521194693", "359571521194750", "359571521195070", "359571521195138", "359571521195195", "359571521195716", "359571521196052", "359571521196771", "359571521196813", "359571521197357", "359571521197373", "359571521197712", "359571521197852", "359571521197993", "359571521206430", "359571521208154", "359571521210119", "359571521219938", "359571521220910", "359571521221058", "359571521221116", "359571521221439", "359571521221850", "359571521222353", "359571521223419", "359571521223591", "359571521223831", "359571521223971", "359571521224375", "359571521224730", "359571521225034", "359571521225554", "350592162331757", "350592162332052", "350592162349452", "350592162354650", "350592162354999", "350592162358396", "350592162377891", "350592162380077", "350592162380614", "350592162384012", "350592162392395", "350592162393559")));
1105
        fofoIdImeiReturnMap.put(175139245, new HashSet<>(Arrays.asList("862965067920497", "862965069412519", "863405065773894", "865458068206733", "865458068211816")));
1106
        fofoIdImeiReturnMap.put(175139295, new HashSet<>(Arrays.asList("860929062051270", "863405064356154", "864712067983036", "864712067983937")));
1107
        fofoIdImeiReturnMap.put(175139324, new HashSet<>(Arrays.asList("860374061467773", "860929062030514", "860929062141832", "862965067920356", "862965069014133", "863405063891516", "863405066198893")));
1108
        fofoIdImeiReturnMap.put(175139150, new HashSet<>(Arrays.asList("350386307518406", "355622834384101", "860492067081677", "860492067110872", "860679067766410", "860929061693353", "860929066402735", "862637061235558", "862892066180453", "863405068226171", "865458068125859", "865458069600991", "867791061341935", "868905066076515", "868905066087017")));
1109
        fofoIdImeiReturnMap.put(175139181, new HashSet<>(Arrays.asList("350339953281456", "860929062051593", "862637061519498", "862892066288231", "862965069524594", "863405066204238")));
1110
        fofoIdImeiReturnMap.put(175139463, new HashSet<>(Arrays.asList("860374064979311", "864816061592196", "865458067327258", "865458067415376", "866807063524236", "869947079468130")));
1111
        fofoIdImeiReturnMap.put(175139466, new HashSet<>(Arrays.asList("351613386940568", "351613387291086", "351613387490100", "359680168664528", "862637061234858", "863055065310591", "863405066195576", "865458067699912", "866807063677356", "869947078039296", "869947078056977", "869947078057298")));
32700 amit.gupta 1112
        fofoIdImeiReturnMap.put(175139526, new HashSet<>(Arrays.asList("860929062026256")));
32724 amit.gupta 1113
        fofoIdImeiReturnMap.put(175139441, new HashSet<>(Arrays.asList("863405066709772", "863405066710333", "865458067328991", "865458067415095", "865458069598096", "867212065870852")));
1114
        fofoIdImeiReturnMap.put(175139395, new HashSet<>(Arrays.asList("351613386910066", "351613387705648", "352450549335421", "352450549356682", "352450549356740", "860374064974171", "860679067766451", "865458067699433", "865458068211774", "868905060836559", "869947079614436")));
1115
        fofoIdImeiReturnMap.put(175139467, new HashSet<>(Arrays.asList("350923626866742", "350923626874902", "350923628430620", "350923628431727", "350923628433764", "350923628433889", "350923628434366", "350923628434549", "350923628435769", "350923628435868", "350923628436601", "350923628437286", "350923628438383", "350923628438409", "350923628445404", "350923628458365", "350923628458449", "350923628458803", "350923628467804", "350923628521543", "351613386910009", "351613386910249", "351613386910546", "351613387498186", "860929065915711", "860929066398396", "865458067722292", "865458069593873", "865458069594392", "867212065990155", "867791061346397")));
1116
        fofoIdImeiReturnMap.put(175139129, new HashSet<>(Arrays.asList("350339952951992", "355358274116659", "355358274158776", "355358274173494", "355358274173734", "355358274174195", "355358274177099", "355358277455872", "355358278085413", "355358278087252", "355358278490134", "860400066384620", "860400066388324", "861628060791270", "863055064988132", "863405064770552", "866151069820235", "867791061344392")));
1117
        fofoIdImeiReturnMap.put(175139233, new HashSet<>(Arrays.asList("350250294368201", "351733718941439", "357594161173308", "359680168437826", "862892066180594", "862892066288595", "863055063673990", "863405065656552", "864214066139470", "865458067277636", "865458068211014", "868905060992436")));
1118
        fofoIdImeiReturnMap.put(175139328, new HashSet<>(Arrays.asList("359680168664924", "860929061660196", "860929062346936", "864712066918272", "864712066918413", "866807063560198")));
1119
        fofoIdImeiReturnMap.put(175138989, new HashSet<>(Arrays.asList("865458067293013", "866726063923190", "867212065990577", "867791061366353", "869947076684838", "869947076797275", "869947076314659", "350933414128064", "351613386881549", "352450543500467", "359749531361441", "863653062670031", "869076063985766")));
1120
        fofoIdImeiReturnMap.put(175138996, new HashSet<>(Arrays.asList("860400066171621", "860400066183584", "864712067822911", "866726063560976", "869947078049659")));
1121
        fofoIdImeiReturnMap.put(175139006, new HashSet<>(Arrays.asList("350923628433665", "350923628434507", "350923628436981", "350923628437245", "350923628458282", "356393508778908", "356393509652300", "356393509660568", "356393509671565", "356393509771647", "862965069404151", "865458067690796", "865458068210677", "866726063559390", "866726063867694", "867791061350159")));
1122
        fofoIdImeiReturnMap.put(175139013, new HashSet<>(Arrays.asList("860929063610413", "860929065364837", "860929065917071", "860929066118653", "862965069524495", "865458068207475", "865458068874795", "867212065862578", "867212065871355", "868905060174191", "868905060174514", "868905066080830", "868905066083016")));
1123
        fofoIdImeiReturnMap.put(175139329, new HashSet<>(Arrays.asList("357594161174371", "357594161264107", "865626063745117", "868905060180693", "350145991758821", "351733716292389", "352950861878429", "860093065821245", "865753061852362", "866042060910069", "869271068198487")));
1124
        fofoIdImeiReturnMap.put(175139359, new HashSet<>(Arrays.asList("860929065365099", "860929065917436", "867212063830916", "867212063844834", "869350065110032", "863653065044275", "863653065062772", "863653065063671", "863653065064257", "867492061495298")));
1125
        fofoIdImeiReturnMap.put(175139501, new HashSet<>(Arrays.asList("353140546831717", "860492067082154")));
1126
        fofoIdImeiReturnMap.put(175139082, new HashSet<>(Arrays.asList("351712243346637", "351733718918734", "357594161974283", "359680168838767", "359680168838866", "860929062648752", "864712067824578", "868905060828036")));
1127
        fofoIdImeiReturnMap.put(175139435, new HashSet<>(Arrays.asList("350933415820586", "351733718596837", "357594161339032", "861784067381274", "862965069521731", "864712066796090", "865753067326700", "869947079626778")));
1128
        fofoIdImeiReturnMap.put(175139439, new HashSet<>(Arrays.asList("860929061118690", "862637061214355", "862892066288298", "863055063524151", "863055065303331", "863405064772533", "864214065758395", "864214065759815", "864214065759831", "865458067313993", "865458068126592", "866726063720612")));
1129
        fofoIdImeiReturnMap.put(175139532, new HashSet<>(Arrays.asList("352937907229105", "860929062652192", "860929062652374", "860929062918056", "867791062627779")));
1130
        fofoIdImeiReturnMap.put(175139393, new HashSet<>(Arrays.asList("860679067766493", "860679067766634", "863055065304339")));
1131
        fofoIdImeiReturnMap.put(175139465, new HashSet<>(Arrays.asList("860492067081370", "860492067084234", "860929062648216", "860929066397414", "862892064921718", "863055063676951", "865458066931092", "865458067278253", "865458067592133", "866807063562533")));
1132
        fofoIdImeiReturnMap.put(175139477, new HashSet<>(Arrays.asList("860929063335599", "863405065650654", "864816060350414")));
1133
        fofoIdImeiReturnMap.put(175139519, new HashSet<>(Arrays.asList("865626063101253", "865626063746776", "352450547843467")));
1134
        fofoIdImeiReturnMap.put(175139415, new HashSet<>(Arrays.asList("350339952008843", "356228329486432", "864816061592410", "869947076324930")));
1135
        fofoIdImeiReturnMap.put(175139591, new HashSet<>(Arrays.asList("860679067765750", "860679069287191", "860929063899958", "862286061149391", "862286061149573", "865037064907674", "865037064909894", "865037064910371", "865037064910637", "865037064910991", "865458064830999", "865458064831492", "865458065220570", "865458066736319", "866807063452974", "867212063280690", "867212064536132", "867212064536777", "867791068373030", "868905064952279", "868905066118119", "869947079512556", "869947079612950")));
1136
        fofoIdImeiReturnMap.put(175139438, new HashSet<>(Arrays.asList("352450549339746", "860929066617332", "862902063054310", "868666065957960", "869106065836236", "352450549421320", "866807069189299", "869076064303761")));
1137
        fofoIdImeiReturnMap.put(175139227, new HashSet<>(Arrays.asList("350134240859796", "357594161343901", "357718897884892", "358142884109800", "860374067385375", "860929062044291", "860929063898299", "865279060942053", "865458065221156")));
1138
        fofoIdImeiReturnMap.put(175139459, new HashSet<>(Arrays.asList("862869068949887", "863922060313021", "866151068236011", "866151068247554", "869076064661002")));
1139
        fofoIdImeiReturnMap.put(175139489, new HashSet<>(Arrays.asList("350134240895642", "860400066368029", "860400066398323", "860679069610699", "861628061563470", "862869069371925", "868666065893165")));
1140
        fofoIdImeiReturnMap.put(175139498, new HashSet<>(Arrays.asList("353370808661870", "860679067692590")));
1141
        fofoIdImeiReturnMap.put(175139521, new HashSet<>(Arrays.asList("355358277803394", "355358277809730", "355358277809995", "355358277822915", "355358277824176", "355358277825314", "358177964771772", "358177964772739", "358177964773711", "358177964774396", "860679067691873", "860679067692111", "860679069532174", "860929063900178", "860929064134512", "862286066207491", "864720068978830", "864816061153254", "865458066734777", "866151069979536", "866807063462635", "867791066205390", "868666065722729", "868666065962341", "869106062608877", "869106065838117", "869944068548360", "869947076402298")));
1142
        fofoIdImeiReturnMap.put(175139523, new HashSet<>(Arrays.asList("350386305169137", "351733715495298", "860374065898536", "860929063897515", "862807061160599", "863653061286656", "863653061637437", "864816061588731", "865626066322898", "866807063635156", "868905062139911")));
1143
        fofoIdImeiReturnMap.put(175139558, new HashSet<>(Arrays.asList("353140546901403", "861220073281612", "861220073283519", "869947076396631")));
1144
        fofoIdImeiReturnMap.put(175139561, new HashSet<>(Arrays.asList("353140546896462", "357718897547911", "860400066294100", "860400068543983", "860929064457830", "861628060812258", "862902063054278", "869657061778830")));
1145
        fofoIdImeiReturnMap.put(175139416, new HashSet<>(Arrays.asList("860929066509810", "861522060511319", "861940060496036", "864816061589259", "864816061590752", "866151069979478", "866807067353590", "866807067539370", "869947079626273", "352764975205043", "352764975205209", "352764975210985", "352764975224341", "352764975224747", "352764975225165", "352764975225603", "352764975225686", "352764975226700", "352764975226908", "352764975227047", "352764975227088", "352764975227443", "352764975227682", "352764975228581", "352764975228920", "352764975229126", "352764975229340", "352764975229381", "352764975229746", "356612600717757", "356612600718235", "356612600723250", "356612600738613", "356612606361493", "356612606363911", "356612606369199", "356612606372474", "358382747354918", "358382747577799", "358382747578615", "358382747578797", "359749531766805", "860398063576976", "861530062225465", "867492066819955", "868828060668196")));
1146
        fofoIdImeiReturnMap.put(175139495, new HashSet<>(Arrays.asList("350145991713164", "350339952736831", "352950861872083", "355622834484562", "357594161974622")));
1147
        fofoIdImeiReturnMap.put(175139025, new HashSet<>(Arrays.asList("860400066390809", "860400068552141", "860929061672258", "860929062841738", "862965068501072", "863405065502194")));
1148
        fofoIdImeiReturnMap.put(175139429, new HashSet<>(Arrays.asList("862166069971733", "862902067784771", "862902067784839", "864816060350398", "864816060350513", "864816061582650", "868492067979880", "868492067980581", "868492067982066", "868492067987149", "868492067996165", "868492067999706", "868492068028604", "868492068029149")));
1149
        fofoIdImeiReturnMap.put(175139182, new HashSet<>(Arrays.asList("863055068371152", "864647065162276")));
1150
        fofoIdImeiReturnMap.put(175139386, new HashSet<>(Arrays.asList("350339954046601", "351733718529275", "353140546973642", "354301731446682", "355358278075570", "355358278088896", "359691642050143", "359691642177540", "869947076332651", "350191506095275", "350386305533381", "350191505946916")));
1151
        fofoIdImeiReturnMap.put(175138840, new HashSet<>(Arrays.asList("860492068962016", "860492069986071", "860929065241571", "863405066405553", "865626063001594", "867791060562697", "868905063514054", "863653060261296", "865037065347490", "865279060955972", "868905064552731")));
1152
        fofoIdImeiReturnMap.put(175139419, new HashSet<>(Arrays.asList("860400068554600", "861763060404861", "864480067707728", "350923627837643", "350923627844581", "351166971901131", "351166971902717", "353305256519600", "355480684023596", "355480684024255", "355480684066793", "356455410227041", "356455410229864", "357014951844232", "357014951856095", "357014951856251", "357014951859255", "357983840357707", "358177964142370", "358177964143238", "358177964771855", "358177964772994", "358382747571370", "358382747582492", "359197382649227", "359691642138625", "359691642138724", "864987061358274", "350031477755442", "350031477831177", "351733710803645", "354198343595918", "354198343607879", "354198343631291", "356163219371941", "864372068983210", "864920062212695", "864920063177053", "866151063027910", "866151063028975", "866151063030377", "866151063030492", "866194068822257", "868655061017259")));
1153
        fofoIdImeiReturnMap.put(175139420, new HashSet<>(Arrays.asList("352764977334460", "355358277019199", "355358277036490", "355358278067775", "355358278083616", "359197384183621", "863055065850737", "863055065884595", "863405066400653", "352764977342265", "352764977343941", "352764977687065", "352764978149966", "351166972212231", "353305256511045", "353305256516507", "353305256516705", "356612604455339", "356612604455990", "358177964238111", "861784061447378", "866399062591127", "351336670342081", "351367492366073", "351367492373277", "351367492375397", "352067618177532", "352450540634368", "355724841512698", "358378399556222", "864848067902889", "868666062666481")));
1154
        fofoIdImeiReturnMap.put(175139506, new HashSet<>(Arrays.asList("860607066506495", "860607066507337", "862166069971915", "862637062115890", "863055067772574", "863055067773473", "864214065036594", "864214066594914", "864816060360439", "865626063008433", "866726063702271", "866726064092110", "869947077535898", "869947077539916")));
1155
        fofoIdImeiReturnMap.put(175139475, new HashSet<>(Arrays.asList("861522060512739", "864816061591297")));
1156
        fofoIdImeiReturnMap.put(175138863, new HashSet<>(Arrays.asList("355358273779135", "355358274119513", "355358274146318", "355358274153793", "355358274154577", "355358274154593", "355358274155293", "355358274155491", "355358274156515", "355358274158370", "355358274158479", "355358274171670", "355358274172397", "355358274174930", "355358274177552", "355358274180911", "355358274181836", "355358274182354", "355358274183519", "355358274184657", "355358274188278", "355358274190373", "355358274190597", "355358274190696", "355358274190811", "355358274191231", "355358274191751", "355358274192270", "355358274192437", "355358274192452", "355358274193070", "355358274193138", "355358274193658", "355358274194078", "355358274194334", "355358274194490", "355358274196032", "355358274477473", "355358274477614", "355358274479354", "355358275452632", "355358275453473", "355358275455494", "355358275455833", "355358275455890", "355358275456559", "355358275458019", "355358275458472", "355358275459272", "355358275459330", "355358275459496", "355358275459819", "355358275459835", "355358275459918", "355358275460270", "355358275460759", "355358275460791", "355358275460833", "355358275461195", "355358275461815", "355358275462516", "355358275462813", "355358275765553", "355358275774191", "355358275877952", "355358275883430", "355358275883737", "355358275887472", "355358275888033", "355358275888173", "355358275896879", "355358275899311", "355358275899576", "355358275901935", "355358275903410", "355358275905019", "355358275908559", "355358275908856", "355358276758839", "355358276870279", "355358276870832", "355358276877159", "355358276879692", "355358276881573", "355358276881631", "355358276883751", "355358276886895", "355358276887752", "355358276888412", "355358276888859", "355358276889071", "355358276889816", "355358276894014", "355358276894071", "355358276894410", "355358278081511", "355358278082378", "355358278083194", "355358278083277", "355358278083632", "355358278084432", "355358278085470", "355358278085710", "355358278086270", "355358278086353", "355358278086452", "355358278086536", "355358278086619", "355358278086650", "355358278087716", "355358278087831", "355358278087898", "355358278088755", "355358278089993", "355358278090595", "355480686729091", "355480686729471", "355480686729778", "355480686733119", "355480686956710", "355480686957536", "355480686957676", "355480686957759", "355480686958070", "355480686958435", "355480686959433", "355480686960316", "355480686960639", "355480686960852", "355480686961611", "355480686964771", "355480686965836", "355480686966677", "355480686968210", "355480686968434", "359197384179025", "359197384180825", "359197384181443", "359197384181708", "359197384183662", "359571522563599", "359571522563672", "359571522564175", "359571522577417", "359571522580239", "359571522580593", "359571522585857", "359571522585956", "359571522586699", "359571522588190", "359571522588471", "359571522588554", "359571522589016", "359571522592176", "359571524914493", "359571524914535", "359571524914675", "359571524915516", "359571524915714", "359571524915839", "359571524916290", "359571524920979", "359571524921456", "359571524924617", "359571524924799", "359571524924898", "359571524925119", "359571524925978", "359571524928352", "359571524928659")));
1157
        fofoIdImeiReturnMap.put(175139089, new HashSet<>(Arrays.asList("862637064584754", "862909069350832", "865865068870195", "866132066418538", "866807067278698", "866807067280199", "868386060580978", "352067619060034", "352067619060273", "352067619065033", "352067619065272", "352067619069217", "352067619075677", "352067619075735", "352067619076295", "352067619077475", "352067619099271", "352094722782064", "352094723001381", "352094723070121", "357415663619863", "357415663657186", "357415663785086", "860695062934019", "862628064902492", "862628064906295", "865037067597951", "865037068421136", "867492063916135", "867492064274831")));
1158
        fofoIdImeiReturnMap.put(175139452, new HashSet<>(Arrays.asList("350339954047195", "353140546950814", "355358274453672", "355358274462814", "355358277811033", "359197384182367", "862166069972012", "863055068360239")));
1159
        fofoIdImeiReturnMap.put(175139449, new HashSet<>(Arrays.asList("863055060224250", "864816061789610", "864816061791251")));
1160
        fofoIdImeiReturnMap.put(175139542, new HashSet<>(Arrays.asList("358142884065143", "860400065403140", "860400066392227", "860400068211144", "860492067291490", "865821064835161", "869947078219476")));
1161
        fofoIdImeiReturnMap.put(175138824, new HashSet<>(Arrays.asList("860400068194803", "860400068201129", "860400068211169", "860400068218263", "861628060806235", "862869067811948", "864816060360470", "864816060360512", "867022067183927", "869106063548478", "869947077539692", "869947077540112")));
1162
        fofoIdImeiReturnMap.put(175139029, new HashSet<>(Arrays.asList("863405066054831", "865303062635935", "865303063979175")));
1163
        fofoIdImeiReturnMap.put(175139396, new HashSet<>(Arrays.asList("353075420188125", "863055062233812", "869947077535815")));
1164
        fofoIdImeiReturnMap.put(175139581, new HashSet<>(Arrays.asList("860929063644313", "860929064489478", "861628060818891", "861784066921419", "862637060053978", "862637062859679", "862869068943120", "862869069371826", "862892065807452", "863405065495373", "864179061757867", "864179062028268", "864214063816039", "864214066139751", "864647064652178", "865458066152392", "865458066153218", "865458066153432", "865753068701422", "865753068733888", "869106063530534")));
1165
        fofoIdImeiReturnMap.put(175139569, new HashSet<>(Arrays.asList("351613386911460", "351613386940584", "351613386940824", "351613387478709", "351613387654622", "352450549313501", "358142884003664", "358142884005008", "860400068128108", "860492068962677", "860607066506834", "862637060052533", "862637060053853", "862909069429255", "862909069429297", "864179060695282", "864179060873608", "864179061750722", "866726064092136", "868905063515457", "869947076316571", "869947076354077", "869947076388455", "869947076709239", "869947076712712")));
1166
        fofoIdImeiReturnMap.put(175139610, new HashSet<>(Arrays.asList("860492067291532", "860492067294379", "860492067547735", "860492067550770", "862637062839499", "862637062841479", "862637063539296", "862892065802834", "862892068433512", "862892068433637", "862892068433876", "862892068433918", "862892068433991", "863055064965015", "863055064965650", "863055064965734", "863405064249318", "864179061803364", "864179061804602", "864179062838047", "864214066732175", "864214067673931", "864214067793093", "864214067795239", "864214067795437")));
1167
        fofoIdImeiReturnMap.put(175139364, new HashSet<>(Arrays.asList("350933415706660", "358142884005545", "860374063635237", "860607066506917", "861784068326336", "862637062853573", "862909069428638", "864179062838245", "864179063753161", "864179063753989", "864214063822730", "869947077539114")));
1168
        fofoIdImeiReturnMap.put(175139549, new HashSet<>(Arrays.asList("860929064495236", "862965069219872", "863405065200351")));
1169
        fofoIdImeiReturnMap.put(175139564, new HashSet<>(Arrays.asList("351613386987106", "351613386987767", "351613386988088", "351613386988302", "351613386993609", "351613386994185", "351613386994243", "351613386994284", "351613386994342", "351613387255644", "351613387258085", "351613387300903", "351613387300960", "864816060355694", "864816060621590", "864816061791095")));
1170
        fofoIdImeiReturnMap.put(175139366, new HashSet<>(Arrays.asList("351733718596951", "863405064939694", "867791061376097", "350031475892213", "351733717084934", "353140545607183")));
1171
        fofoIdImeiReturnMap.put(175139412, new HashSet<>(Arrays.asList("356049795800439", "356049795802997", "356049795810958", "356049795811675", "356049795811733", "359571521186897", "359571521188372", "359571521189131", "359571521190097", "359571521190915", "861433065523251", "861433065916158", "864179061688823", "359197382648922", "359197382652189", "355724843104536", "355724843127313", "355724843128196", "355724843129533", "355724843130754", "867158066644897")));
1172
        fofoIdImeiReturnMap.put(175139437, new HashSet<>(Arrays.asList("350592162405452", "350592162405494", "350592162406419", "350592162406955", "350592162407292", "355480686729836", "355480686730537", "355480686963070", "359571521181351", "359571521194230", "359571521194735", "359571521195534", "359571521195757", "860492068958915", "864816060350315", "864816061582817", "867158060809975", "867212066345094", "867791061076093", "868905063046578", "868905063482310", "869947076332693", "869947079621811")));
1173
        fofoIdImeiReturnMap.put(175139481, new HashSet<>(Arrays.asList("354301732198340", "359749532131280", "359749532132726", "860929061673439", "862286062845617", "862286062845971", "862637066462330", "862637066610458", "864179061805021", "865458068514870", "866151068234099", "869947074812092")));
1174
        fofoIdImeiReturnMap.put(175139504, new HashSet<>(Arrays.asList("860400067865767", "860400068541482", "862166069970917", "863055067773655")));
1175
        fofoIdImeiReturnMap.put(175139201, new HashSet<>(Arrays.asList("860679069532133", "862902068546997", "864816061582338", "868652061264429")));
1176
        fofoIdImeiReturnMap.put(175139392, new HashSet<>(Arrays.asList("860400066384687", "860400067318247", "860400068127100", "860929065048034", "860929066454470", "863405064939918", "863405065628130", "863405066055374", "864214065420673", "867791060557333")));
1177
        fofoIdImeiReturnMap.put(175139494, new HashSet<>(Arrays.asList("358142884051762", "862637063207274", "862902068532898", "862965069428358", "864214062904992", "864214065380257", "864647061811199", "864816061592279", "866726063977451")));
1178
        fofoIdImeiReturnMap.put(175139547, new HashSet<>(Arrays.asList("860400066372302", "862637065107373", "862902067784516", "864816061583773", "865303064283734", "867212065247598", "869947074813850")));
1179
        fofoIdImeiReturnMap.put(175139551, new HashSet<>(Arrays.asList("350031479973589", "350145991758995", "351733712444455", "351733712857292", "353140546952372", "354198344836071", "357962509324265", "860679067692814", "863055066719618")));
1180
        fofoIdImeiReturnMap.put(175139421, new HashSet<>(Arrays.asList("352691627610546", "860929062843072", "861433066782070", "861628061571150", "863405065200070", "863405066062859", "867791060567753")));
1181
        fofoIdImeiReturnMap.put(175139556, new HashSet<>(Arrays.asList("860400067777228", "860400068196162", "862902067784599", "863405064597336")));
1182
        fofoIdImeiReturnMap.put(175138827, new HashSet<>(Arrays.asList("860929062965917", "862965067738139", "863405063802513", "863405065032754", "864179062561425", "864179062561649", "864179063752163", "864179063753021", "866726063411337", "866726063672698", "866726064093274")));
1183
        fofoIdImeiReturnMap.put(175138982, new HashSet<>(Arrays.asList("860374063694531", "860400067679820", "860400068210021", "860492067540359", "860929062841415", "861522060512432", "862892065807635", "862902068533755", "864179063237447", "864179063237785", "864214066727498", "864214066732571", "864816060350612", "865458068516313", "866151068237910", "866151068239114", "866726063975216", "866726064092433", "868666065892183", "869947076332297", "869947078052679")));
1184
        fofoIdImeiReturnMap.put(175139411, new HashSet<>(Arrays.asList("860679067692939", "860679069287290", "862965069783638", "864816061143016", "864816061145235", "864816061147272", "867791060567415")));
1185
        fofoIdImeiReturnMap.put(175139422, new HashSet<>(Arrays.asList("860374063228215", "860400068451583", "861220073284210", "864647061776335", "864816060621939", "865303064616891", "866726063672250")));
1186
        fofoIdImeiReturnMap.put(175139455, new HashSet<>(Arrays.asList("862637064588656", "862637065106250", "862892064250811", "862892065881416", "863055067771618", "864214065359699", "865303064283619")));
1187
        fofoIdImeiReturnMap.put(175138674, new HashSet<>(Arrays.asList("351613387108900", "351613387973527", "862628067280276", "862637062834094", "862637062854894", "862892065806751", "864214066308711", "864214066707011")));
32700 amit.gupta 1188
        fofoIdImeiReturnMap.put(175139108, new HashSet<>(Arrays.asList("350112335652631")));
32724 amit.gupta 1189
        fofoIdImeiReturnMap.put(175139507, new HashSet<>(Arrays.asList("350134240797954", "350134240866676", "350191505940471", "351712242099047", "352153270447718", "352153270448591", "353140545862978", "353140546123792")));
1190
        fofoIdImeiReturnMap.put(175139107, new HashSet<>(Arrays.asList("350386305998881", "351733715694635", "353140545077080", "353140545590280", "352153270036701", "352153270443519")));
32700 amit.gupta 1191
        fofoIdImeiReturnMap.put(175138906, new HashSet<>(Arrays.asList("350992324682206")));
32724 amit.gupta 1192
        fofoIdImeiReturnMap.put(175139210, new HashSet<>(Arrays.asList("351613387050524", "352450549158609", "352450549227222")));
1193
        fofoIdImeiReturnMap.put(175139219, new HashSet<>(Arrays.asList("352764974779261", "352764974790342", "352764974790904", "352764974791225", "352764974792223", "352764974794989", "352764974795986", "352764974799780", "352764975904744", "352764975906301", "352764975906665", "352764976848205", "352764976857404", "352764976870969", "352764976872965", "352764976875166", "352764976877642", "352764976878947", "352764976886007", "352764976886122", "352764976886486", "352764976887567", "352764976894167", "352764976913645", "352764976914940", "352764976915681", "352764976916101", "352764976917620", "352764976917869", "352764976918362", "352764976918966", "352764976919287", "352764976919402", "352764976919428", "352764976919584", "352764976919642", "352764976919964", "352764976920186", "352764976920327", "352764976920343", "352764976920624", "352764976920640", "352764976920848", "352764976921069", "352764976921143", "352764976921267", "352764976921325", "352764976921929", "352764976921986", "352764976922109", "352764976922307", "352764976922729", "352764976923305", "352764976923586", "352764976923842", "352764976924022", "352764976924360", "352764976924386", "352764976924881", "352764976925029", "352764977286405", "352764977288526", "352764977289201", "352764977289607", "352764977290241", "352764977290829", "352764977291207", "352764977292122", "352764977292346", "352764977293146", "352764977296727", "352764977296867", "352764977296941", "352764977296982", "352764977297824", "352764977298046", "352764977298285", "352764977298400", "352764977298442", "352764977298723", "352764977299028", "352764977306203", "352764977306682", "352764977307185", "352764977309082", "352764977310544", "352764977310908", "352764977311104", "352764977311443", "352764977312607", "352764977312888", "352764977312920", "352764977313423", "352764977313548", "352764977313829", "352764977313928", "352764977313985", "352764977413702", "352764977460604", "352764977462824", "352764977687008", "352764977695860", "352764977916969", "352764977927925", "860398068740270", "860398068747770")));
1194
        fofoIdImeiReturnMap.put(175139073, new HashSet<>(Arrays.asList("350339951344884", "350339951611928", "352350272411755", "352772521510097", "356163219380496", "356393508230405", "356393508238283", "356393508238721", "860398069096730")));
1195
        fofoIdImeiReturnMap.put(175139345, new HashSet<>(Arrays.asList("351733712445734", "355002360088808")));
1196
        fofoIdImeiReturnMap.put(175139497, new HashSet<>(Arrays.asList("355724848403537", "355724848419491", "355724848421810", "355724848500753", "355724848502478", "357014954932315", "357014954933131", "357014954933172", "357014954933859", "357014954933891", "868701069478778")));
1197
        fofoIdImeiReturnMap.put(175139436, new HashSet<>(Arrays.asList("861530062182203", "861530062182906", "866399065946385", "866399065954140", "866399065999723", "866399066070722")));
1198
        fofoIdImeiReturnMap.put(175139511, new HashSet<>(Arrays.asList("862628068754618", "863879068172157", "864647062004554", "867492060213171", "868905067771759", "869076064644586", "869076064644701", "869236065766750", "869663063223817")));
32728 amit.gupta 1199
        fofoIdImeiReturnMap.put(175139454, new HashSet<>(Arrays.asList("863879063211455", "863879064916334", "868655068568650", "868905064553937")));*/
32724 amit.gupta 1200
        purchaseReturnService.processReturn(fofoIdImeiReturnMap, debitNoteDate);
32513 amit.gupta 1201
 
32698 amit.gupta 1202
    }
1203
 
1204
 
1205
    private void processRebilling(Map<Integer, Set<String>> fofoIdImeiReturnMap) throws Exception {
1206
 
1207
 
1208
        for (Entry<Integer, Set<String>> fofoIdImeiReturnEntry : fofoIdImeiReturnMap.entrySet()) {
32511 amit.gupta 1209
            int fofoId = fofoIdImeiReturnEntry.getKey();
1210
            Set<String> imeis = fofoIdImeiReturnEntry.getValue();
1211
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, imeis, true);
1212
            for (InventoryItem inventoryItem : inventoryItems) {
1213
                //inventoryItem.getId();
1214
                purchaseReturnService.returnInventoryItem(fofoId, true, inventoryItem.getId(), ReturnType.GOOD);
1215
                //Approve return
1216
                PurchaseReturnItem purchaseReturnItem = purchaseReturnItemRepository.selectByInventoryItemId(inventoryItem.getId());
1217
                purchaseReturnItem.setStatus(PurchaseReturnStatus.APPROVED);
1218
                purchaseReturnItem.setApproveTimestamp(LocalDateTime.now());
1219
            }
1220
            Map<Purchase, List<InventoryItem>> purchaseInventoryItemsMap = purchaseReturnService.getPurchaseMapForApprovedReturns(fofoId);
1221
            int walletAmount = walletService.getWalletAmount(fofoId);
1222
            List<DebitNote> debitNotes = purchaseReturnService.generateDebitNotes(purchaseInventoryItemsMap);
1223
            int walletDiff = walletAmount - walletService.getWalletAmount(fofoId);
1224
            if (walletDiff > 0) {
1225
                int reference = walletService.getManualReference(WalletReferenceType.OTHERS);
32514 amit.gupta 1226
                walletService.addAmountToWallet(fofoId, reference, WalletReferenceType.ADVANCE_AMOUNT, "Sytematically added for internal PO", (float) walletDiff + 5000, LocalDateTime.now());
32511 amit.gupta 1227
            }
32698 amit.gupta 1228
            List<CartItem> cartItems = new ArrayList<>();
32511 amit.gupta 1229
            for (DebitNote debitNote : debitNotes) {
32698 amit.gupta 1230
                debitNote.setCreateTimestamp(LocalDate.of(2023, Month.NOVEMBER, 30).atStartOfDay());
32511 amit.gupta 1231
                //Try to refund amount per debit note
32698 amit.gupta 1232
                cartItems.addAll(this.refundDnAmount(debitNote));
32511 amit.gupta 1233
            }
32698 amit.gupta 1234
            //If order created
32724 amit.gupta 1235
            Map<Integer, List<CartItem>> warehouseCartItemsMap = cartItems.stream().collect(Collectors.groupingBy(x -> x.getWarehouseId()));
1236
            for (Map.Entry<Integer, List<CartItem>> warehouseCartItemsEntry : warehouseCartItemsMap.entrySet()) {
32223 amit.gupta 1237
 
32698 amit.gupta 1238
                List<CartItem> warehouseCartItems = warehouseCartItemsEntry.getValue();
1239
 
1240
                List<CartItem> mergedCartItems = warehouseCartItems.stream()
1241
                        .collect(Collectors.collectingAndThen(
32724 amit.gupta 1242
                                Collectors.groupingBy(x -> x.getItemId(), Collectors.collectingAndThen(
1243
                                        Collectors.reducing((a, b) -> {
32698 amit.gupta 1244
                                            a.setQuantity(a.getQuantity() + b.getQuantity());
1245
                                            return a;
1246
                                        }), Optional::get)),
1247
                                m -> new ArrayList<>(m.values())));
1248
 
32724 amit.gupta 1249
                double walletTotalAmount = mergedCartItems.stream().mapToDouble(x -> x.getQuantity() * x.getSellingPrice()).sum();
32698 amit.gupta 1250
 
1251
                com.spice.profitmandi.dao.entity.user.User user = userRepository.selectById(fofoId);
1252
                cartService.clearCart(user.getActiveCartId());
1253
                cartService.addItemsToCart(user.getActiveCartId(), mergedCartItems);
1254
 
1255
                UserCart userCart = new UserCart();
1256
                userCart.setCartId(user.getActiveCartId());
1257
                userCart.setUserId(user.getId());
1258
 
1259
                int transactionId = transactionService.createTransactionInternally(userCart, walletTotalAmount, warehouseCartItemsEntry.getKey());
1260
                commonPaymentService.payThroughWallet(transactionId);
1261
                transactionService.processTransaction(transactionId);
1262
            }
1263
        }
31697 amit.gupta 1264
    }
32048 tejbeer 1265
 
32384 amit.gupta 1266
    @Autowired
32511 amit.gupta 1267
    CartService cartService;
1268
    @Autowired
1269
    UserRepository userRepository;
1270
 
1271
    @Autowired
1272
    WarehouseScanRepository warehouseScanRepository;
1273
 
1274
    @Autowired
1275
    WarehouseInventoryService warehouseInventoryService;
1276
 
1277
    @Autowired
1278
    CommonPaymentService commonPaymentService;
1279
 
32533 amit.gupta 1280
    @Autowired
1281
    LineItemImeisRepository lineItemImeisRepository;
1282
 
32698 amit.gupta 1283
 
32511 amit.gupta 1284
    //Also create order
32698 amit.gupta 1285
    private List<CartItem> refundDnAmount(DebitNote debitNote) throws ProfitMandiBusinessException {
32511 amit.gupta 1286
        List<Integer> inventoryItemIds = purchaseReturnItemRepository.selectAllByDebitNoteId(debitNote.getId()).stream().map(x -> x.getInventoryItemId()).collect(Collectors.toList());
1287
        Map<Integer, Long> inventoryItemCountMap = inventoryItemIds.stream().collect(Collectors.groupingBy(x -> x, Collectors.counting()));
1288
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(new ArrayList<>(inventoryItemCountMap.keySet()));
1289
        Purchase purchase = purchaseRepository.selectById(inventoryItems.get(0).getPurchaseId());
1290
        String invoice = purchase.getPurchaseReference();
1291
        List<Order> orders = orderRepository.selectByInvoiceNumber(invoice);
1292
        Set<Integer> orderIds = orders.stream().map(x -> x.getId()).collect(Collectors.toSet());
1293
        Order order = orders.get(0);
1294
        float totalAmount = 0;
1295
        int totalQty = 0;
1296
        Map<Integer, CartItem> itemIdCartItemMap = new HashMap<>();
1297
 
1298
        List<CartItem> cartItems = new ArrayList<>();
1299
        for (InventoryItem inventoryItem : inventoryItems) {
1300
            TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1301
            long quantity = inventoryItemCountMap.get(inventoryItem.getId());
1302
            totalAmount += inventoryItem.getUnitPrice() * quantity;
1303
            totalQty += quantity;
1304
            if (!itemIdCartItemMap.containsKey(inventoryItem.getItemId())) {
1305
                CartItem cartItem = new CartItem();
1306
                cartItem.setItemId(inventoryItem.getItemId());
1307
                cartItem.setSellingPrice(tagListing.getSellingPrice());
32698 amit.gupta 1308
                cartItem.setWarehouseId(order.getWarehouseId());
32511 amit.gupta 1309
                cartItems.add(cartItem);
1310
                itemIdCartItemMap.put(inventoryItem.getItemId(), cartItem);
1311
            }
1312
            CartItem cartItem = itemIdCartItemMap.get(inventoryItem.getItemId());
1313
            cartItem.setQuantity((int) quantity + cartItem.getQuantity());
1314
        }
1315
        String rollbackDescription = String.format("Refunded against DN %s, %d pc(s)", debitNote.getDebitNoteNumber(), totalQty);
1316
        walletService.addAmountToWallet(debitNote.getFofoId(), order.getTransactionId(), WalletReferenceType.PURCHASE, rollbackDescription, totalAmount, LocalDateTime.now());
1317
        //Before creating order lets try to in the stock
1318
 
1319
        //All scans pertaining to specific Invoices
1320
        List<WarehouseScan> warehouseScans = warehouseScanRepository.selectAllByOrderIds(new ArrayList<>(orderIds));
32698 amit.gupta 1321
        Map<Integer, Integer> inventoryItemIdOrderIdMap = new HashMap<>();
1322
        try {
1323
            inventoryItemIdOrderIdMap = warehouseScans.stream().collect(Collectors.toMap(x -> x.getInventoryItemId(), x -> x.getQuantity()));
32724 amit.gupta 1324
        } catch (Exception e) {
32698 amit.gupta 1325
            LOGGER.info("Could not process for fofoId - {}, {}", debitNote.getFofoId(), warehouseScans);
1326
        }
32511 amit.gupta 1327
        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)))
1328
                .map(x -> x.getInventoryItemId()).collect(Collectors.toList());
1329
        List<WarehouseInventoryItem> warehouseInventoryItems = warehouseInventoryItemRepository.selectAllByIds(warehouseInventoryItemIds);
1330
 
1331
        Map<String, WarehouseInventoryItem> serialNumberWarehouseInventoryItemMap = warehouseInventoryItems.stream().filter(x -> StringUtils.isNotBlank(x.getSerialNumber())).collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
1332
 
1333
        for (InventoryItem inventoryItem : inventoryItems) {
1334
            if (StringUtils.isBlank(inventoryItem.getSerialNumber())) {
1335
                //As of now this should be happening as  dn are specifically for serialized devices
1336
                /*int returnQty = inventoryItemCountMap.get(inventoryItem.getId()).intValue();
1337
                List<WarehouseInventoryItem> warehouseInventoryItemList = itemIdWarehouseInventoryItemsMap.get(inventoryItem.getItemId());
1338
                warehouseInventoryService.returnNonSerializedQty(warehouseInventoryItem)*/
1339
            } else if (StringUtils.isNotBlank(inventoryItem.getSerialNumber())) {
1340
                String serialNumber = inventoryItem.getSerialNumber();
1341
                WarehouseInventoryItem warehouseInventoryItem = serialNumberWarehouseInventoryItemMap.get(serialNumber);
1342
                warehouseInventoryItem.setLastScanType(in.shop2020.warehouse.ScanType.SALE_RET);
1343
                warehouseInventoryService.addQuantity(warehouseInventoryItem.getId(), 1);
1344
                WarehouseScan warehouseScan = new WarehouseScan();
1345
                warehouseScan.setInventoryItemId(warehouseInventoryItem.getId());
1346
                warehouseScan.setQuantity(1);
1347
                warehouseScan.setOrderId(inventoryItemIdOrderIdMap.get(warehouseInventoryItem.getItemId()));
1348
                warehouseScan.setScannedAt(LocalDateTime.now());
1349
                warehouseScan.setType(in.shop2020.warehouse.ScanType.SALE_RET);
1350
                warehouseScanRepository.persist(warehouseScan);
1351
 
1352
            }
1353
        }
1354
 
1355
        //Create Order as well
32724 amit.gupta 1356
        return cartItems;
32698 amit.gupta 1357
    }
32511 amit.gupta 1358
 
32698 amit.gupta 1359
    void addToCartAndCreateOrder() {
32511 amit.gupta 1360
 
1361
    }
1362
 
1363
    @Autowired
32384 amit.gupta 1364
    WarehouseDebitNoteRepository warehouseDebitNoteRepository;
1365
    @Autowired
1366
    WarehouseDebitNoteLineRepository warehouseDebitNoteLineRepository;
1367
 
1368
    @Autowired
1369
    WarehouseInvoiceItemRepository warehouseInvoiceItemRepository;
1370
    @Autowired
1371
    WarehouseSupplierInvoiceRepository warehouseSupplierInvoiceRepository;
1372
 
1373
    @Autowired
1374
    PurchaseOrderService purchaseOrderService;
1375
 
32482 amit.gupta 1376
    @Autowired
1377
    VendorCatalogPricingLogRepository vendorCatalogPricingLogRepository;
32384 amit.gupta 1378
 
32214 jai.hind 1379
//    private void checkItelImeiActivationNew(LocalDate now, int i) {
1380
//    }
1381
 
32169 amit.gupta 1382
    @Autowired
1383
    SessionFactory sessionFactory;
1384
 
1385
    private void checkAllPayoutsDuplicate() throws Exception {
1386
        final Session session = sessionFactory.getCurrentSession();
32439 tejbeer 1387
        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 1388
        List<Object[]> resultList = nativeQuery.getResultList();
1389
        for (Object[] tuple : resultList) {
1390
            LOGGER.info("RESULT -- {}, {}, {}", tuple[0], tuple[1], tuple[2]);
1391
            int inventoryItemId = (Integer) tuple[0];
1392
            int schemeId = (Integer) tuple[1];
1393
            SchemePayoutStatus schemePayoutStatus = SchemePayoutStatus.valueOf((String) tuple[2]);
1394
            List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(schemeId, inventoryItemId);
1395
            List<SchemeInOut> statusSpecificSchemeInOuts = schemeInOuts.stream().filter(x -> x.getStatus().equals(schemePayoutStatus)).collect(Collectors.toList());
1396
            if (statusSpecificSchemeInOuts.size() > 0) {
1397
                InventoryItem inventoryItem = inventoryItemRepository.selectById(inventoryItemId);
1398
                Scheme scheme = schemeRepository.selectById(schemeId);
1399
                List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItemId);
1400
                if (scheme.getType().equals(SchemeType.IN)) {
1401
                    LOGGER.info("Skipping -- {}", inventoryItem.getSerialNumber());
1402
                } else {
1403
                    int fofoOrderId = scanRecords.stream().filter(x -> x.getOrderId() != 0).max(Comparator.comparing(x -> x.getOrderId())).get().getOrderId();
1404
                    WalletReferenceType walletReferenceType = SchemeType.ACTIVATION.equals(scheme.getType()) ? WalletReferenceType.ACTIVATION_SCHEME : SchemeType.SPECIAL_SUPPORT.equals(scheme.getType()) ? WalletReferenceType.SPECIAL_SUPPORT : WalletReferenceType.SCHEME_OUT;
1405
                    List<UserWalletHistory> userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrderId, walletReferenceType).stream().filter(x -> x.getAmount() == Math.round(statusSpecificSchemeInOuts.get(0).getAmount())).collect(Collectors.toList());
1406
                    LOGGER.info("UserwalletHistory Entry --> {}, Sios --> {}", userWalletHistoryList.size(), statusSpecificSchemeInOuts.size());
1407
                    if (userWalletHistoryList.size() != statusSpecificSchemeInOuts.size()) {
1408
                        //Skipping them in first run as it is the special casw of upgrade where mismatch has happend.
1409
                        LOGGER.info("problem with {}, sio status - {}, inventoryItem id {}, schemeID {} ", fofoOrderId, statusSpecificSchemeInOuts.stream().map(x -> x.getStatus()).collect(Collectors.toList()), inventoryItemId, schemeId);
1410
                        //Primarily multiple pending cases
1411
                        statusSpecificSchemeInOuts.stream().skip(1).forEach(schemeInOut -> {
1412
                            schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
1413
                            schemeInOut.setStatusDescription("Rejected as entry is duplicate");
1414
                        });
1415
                    } else {
1416
                        userWalletHistoryList.stream().skip(1).forEach(userWalletHistory -> {
1417
                            try {
1418
                                walletService.rollbackAmountFromWallet(inventoryItem.getFofoId(), userWalletHistory.getAmount(), userWalletHistory.getReference(), userWalletHistory.getReferenceType(), "Reversal as multiple entries created", userWalletHistory.getBusinessTimestamp());
1419
                            } catch (ProfitMandiBusinessException e) {
1420
                                throw new RuntimeException(e);
1421
                            }
1422
                        });
1423
 
1424
                        statusSpecificSchemeInOuts.stream().skip(1).forEach(schemeInOut -> {
1425
                            schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
1426
                            if (schemePayoutStatus.equals(SchemePayoutStatus.CREDITED)) {
1427
                                schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
1428
                                schemeInOut.setStatusDescription("Rolled back as entry is duplicate");
1429
                            } else {
1430
                                LOGGER.info("This seems higly unreachable should not come here");
1431
                                schemeInOut.setStatusDescription("Rejected as entry is duplicate");
1432
                            }
1433
                        });
1434
                    }
1435
                }
1436
            }
1437
        }
1438
    }
1439
 
32009 amit.gupta 1440
    public void test1() throws Exception {
1441
        System.out.println("Starting test");
32048 tejbeer 1442
        processScheme(LocalDate.of(2023, 05, 06).atStartOfDay(), LocalDate.of(2023, 05, 9).atStartOfDay(), false);
32009 amit.gupta 1443
        /*partnerTypeChangeService.getTypeOnDate(175139287, LocalDate.of(2023,02, 01));
1444
        partnerTypeChangeService.getTypeOnDate(175139287, LocalDate.of(2023,03, 01));
1445
        partnerTypeChangeService.getTypeOnDate(175139287, LocalDate.of(2023,04, 01));
1446
        FofoStore fs = fofoStoreRepository.selectByRetailerId(175139287);
1447
        this.rolloutMarginForStoreOnMonth(fs, LocalDate.of(2023, 2, 1));
1448
        this.rolloutMarginForStoreOnMonth(fs, LocalDate.of(2023, 3, 1));*/
25598 amit.gupta 1449
 
32009 amit.gupta 1450
        //this.sendMailForSamsungRebilling();
1451
        /*List<PurchaseReturnItem> purchaseReturnItems = purchaseReturnItemRepository.selectPurchaseReturnByStatuses(Arrays.asList(PurchaseReturnStatus.DEBIT_NOTE_CREATED));
1452
        Map<Integer, List<PurchaseReturnItem>> inventoryItemsMap = purchaseReturnItems.stream().collect(Collectors.groupingBy(x -> x.getDebitNoteId()));
1453
        for (Map.Entry<Integer, List<PurchaseReturnItem>> debitNotePurcahseReturnMap : inventoryItemsMap.entrySet()) {
1454
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(debitNotePurcahseReturnMap.getValue().stream().map(x -> x.getInventoryItemId()).collect(Collectors.toList()));
1455
            offerService.reverseAdditionalSelloutSchemes(debitNotePurcahseReturnMap.getValue().get(0).getFofoId(), inventoryItems);
1456
        }*/
1457
        //this.sendMailForAgeingAlert();
1458
        //this.sendMailForAgeingAlert();
1459
        //System.out.println(brandRegionMappingRepository.getAvailabilityToVendorWarehouse(Arrays.asList(33353), 7720));
1460
 
1461
    }
1462
 
31697 amit.gupta 1463
    public void sendMailForSamsungRebilling() throws Exception {
1464
        List<BilledImeiModel> samsungModels = warehouseInventoryItemRepository.findByBillingDateBrand(LocalDate.now(), "Samsung");
1465
        LOGGER.info("SamsungModels {}", samsungModels);
1466
        samsungModels = samsungModels.stream().sorted(Comparator.comparing(x -> x.getPcmDate() == null ? -1 : 1)).collect(Collectors.toList());
1467
        if (samsungModels.size() > 0) {
1468
            List<String> headers = Arrays.asList("Partner Id", "Code", "Name", "City", "Brand", "Model Name", "Model Number", "Color", "Serial Number", "Remarks");
1469
            List<List<?>> rows = new ArrayList<>();
1470
            for (BilledImeiModel billedImeiModel : samsungModels) {
31886 tejbeer 1471
                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 1472
                rows.add(row);
1473
            }
1474
            ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1475
            String[] sendToArray = new String[]{"kamini.sharma@smartdukaan.com", "praveen.sharma@smartdukaan.com"};
1476
            String fileName = "Imeis need Rebilling -" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
31886 tejbeer 1477
            Utils.sendMailWithAttachment(googleMailSender, sendToArray, new String[]{"tarun.verma@smartdukaan.com"}, "Samsung Rebilling IMEI Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 1478
        }
1479
    }
24002 amit.gupta 1480
 
31697 amit.gupta 1481
    public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
1482
        LocalDate yesterDay = LocalDate.now().minusDays(1);
1483
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
31886 tejbeer 1484
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25312 amit.gupta 1485
 
32169 amit.gupta 1486
        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 1487
        List<List<?>> rows = new ArrayList<>();
1488
        Map<Integer, List<?>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 1489
 
31697 amit.gupta 1490
        Map<Integer, FofoReportingModel> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25312 amit.gupta 1491
 
31886 tejbeer 1492
        Map<Integer, Integer> shortDaysMap = partnerDailyInvestmentRepository.selectAll(LocalDate.now().withDayOfMonth(1), LocalDate.now()).stream().collect(groupingBy(
1493
                x -> x.getFofoId(), Collectors.summingInt(x -> x.getShortPercentage() > 10 ? 1 : 0)));
24271 amit.gupta 1494
 
31697 amit.gupta 1495
        for (FofoStore fofoStore : fofoStores) {
1496
            LOGGER.info("Fofo Store {},  {}", fofoStore.getId(), fofoStore.getCode());
1497
            int fofoId = fofoStore.getId();
1498
            PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 1);
1499
            partnerDailyInvestment.setDate(yesterDay);
24177 govind 1500
 
31697 amit.gupta 1501
            try {
1502
                partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
31886 tejbeer 1503
                shortDaysMap.put(fofoId, shortDaysMap.get(fofoId) + (partnerDailyInvestment.getShortPercentage() > 10 ? 1 : 0));
31697 amit.gupta 1504
            } catch (Exception e) {
1505
                // ignore the exceptions during persist
1506
            }
25598 amit.gupta 1507
 
31697 amit.gupta 1508
            CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
1509
            if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
1510
                LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
1511
                continue;
1512
            }
1513
            FofoReportingModel reportingModel = partnerIdSalesHeaderMap.get(fofoStore.getId());
1514
            List<Serializable> row = new ArrayList<>();
31886 tejbeer 1515
            row.addAll(Arrays.asList(reportingModel.getCode(), reportingModel.getBusinessName(), reportingModel.getRegionalManager(), reportingModel.getTerritoryManager()));
31697 amit.gupta 1516
            row.addAll(
31886 tejbeer 1517
                    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 1518
            partnerRowsMap.put(fofoStore.getId(), row);
1519
            rows.add(row);
25837 amit.gupta 1520
 
31697 amit.gupta 1521
        }
25837 amit.gupta 1522
 
31697 amit.gupta 1523
        String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25837 amit.gupta 1524
 
31697 amit.gupta 1525
        if (sendTo == null) {
1526
            for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
31886 tejbeer 1527
                List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
31697 amit.gupta 1528
                ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
1529
                String[] sendToArray = new String[]{storeGuyEntry.getKey()};
31886 tejbeer 1530
                Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 1531
            }
31886 tejbeer 1532
            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 1533
        }
25837 amit.gupta 1534
 
31697 amit.gupta 1535
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1536
        String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
31886 tejbeer 1537
        Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
25837 amit.gupta 1538
 
31697 amit.gupta 1539
    }
25598 amit.gupta 1540
 
31697 amit.gupta 1541
    private Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() {
1542
        Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
1543
        Map<String, SaleRoles> partnerEmailRBMMap = new HashMap<>();
24271 amit.gupta 1544
 
31886 tejbeer 1545
        List<Position> positions = positionRepository.selectPositionByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_RBM));
1546
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31697 amit.gupta 1547
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
1548
        for (Position position : positions) {
1549
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1550
            if (crList == null)
1551
                continue;
1552
            if (position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES) {
1553
                for (CustomRetailer cr : crList) {
1554
                    if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
1555
                        partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
1556
                    }
1557
                    SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
1558
                    AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1559
                    if (authUser == null) {
1560
                        continue;
1561
                    }
1562
                    String name = authUser.getFirstName() + " " + authUser.getLastName();
1563
                    if (position.getEscalationType().equals(EscalationType.L1)) {
1564
                        saleRoles.getL1().add(name);
1565
                    } else if (position.getEscalationType().equals(EscalationType.L2)) {
1566
                        saleRoles.getL2().add(name);
1567
                    }
1568
                }
1569
            }
1570
            if (position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM) {
1571
                for (CustomRetailer cr : crList) {
1572
                    if (!partnerEmailRBMMap.containsKey(cr.getEmail())) {
1573
                        partnerEmailRBMMap.put(cr.getEmail(), new SaleRoles());
1574
                    }
1575
                    SaleRoles saleRoles = partnerEmailRBMMap.get(cr.getEmail());
1576
                    AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1577
                    if (authUser == null) {
1578
                        continue;
1579
                    }
1580
                    String name = authUser.getFirstName() + " " + authUser.getLastName();
1581
                    if (position.getEscalationType().equals(EscalationType.L1) || position.getEscalationType().equals(EscalationType.L1)) {
1582
                        saleRoles.getL1().add(name);
1583
                    }
1584
                    /*else if (position.getEscalationType().equals(EscalationType.L2)) {
1585
                        saleRoles.getL2().add(name);
1586
                    }*/
1587
                }
1588
            }
24692 amit.gupta 1589
 
31697 amit.gupta 1590
        }
25418 amit.gupta 1591
 
31697 amit.gupta 1592
        Set<CustomRetailer> allCrList = new HashSet<>();
1593
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1594
            allCrList.addAll(cr);
1595
        }
25609 amit.gupta 1596
 
31886 tejbeer 1597
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
25503 amit.gupta 1598
 
31697 amit.gupta 1599
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
25503 amit.gupta 1600
 
31697 amit.gupta 1601
        for (CustomRetailer cr : allCrList) {
1602
            FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
1603
            if (fofoStore == null) {
1604
                LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
1605
                continue;
1606
            }
1607
            String code = fofoStore.getCode();
1608
            // String storeName = "SmartDukaan-" +
1609
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
1610
            String businessName = cr.getBusinessName();
1611
            try {
1612
                String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
1613
                String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
1614
                String bdm = StringUtils.join(partnerEmailRBMMap.get(cr.getEmail()).getL1(), ", ");
1615
                FofoReportingModel reportingModel = new FofoReportingModel();
1616
                reportingModel.setBusinessName(businessName);
1617
                reportingModel.setCode(code);
1618
                reportingModel.setFofoId(fofoStore.getId());
1619
                reportingModel.setRegionalManager(stateManager);
1620
                reportingModel.setTerritoryManager(territoryManager);
1621
                reportingModel.setBusinessManager(bdm);
1622
                partnerIdSalesHeadersMap.put(fofoStore.getId(), reportingModel);
1623
            } catch (Exception e) {
1624
                LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
1625
            }
1626
        }
1627
        return partnerIdSalesHeadersMap;
24533 govind 1628
 
31697 amit.gupta 1629
    }
28709 amit.gupta 1630
 
31697 amit.gupta 1631
    public void sendPartnerInvestmentDetails() throws Exception {
1632
        this.sendPartnerInvestmentDetails(null);
1633
    }
28709 amit.gupta 1634
 
31697 amit.gupta 1635
    public void sendAgeingReport(String... sendTo) throws Exception {
28790 amit.gupta 1636
 
31886 tejbeer 1637
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW, "itemstockageing.xml");
1638
        InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "ItemwiseOverallPendingIndent.xml");
31697 amit.gupta 1639
        Attachment attachment = new Attachment(
1640
                "ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
1641
        Attachment attachment1 = new Attachment(
1642
                "pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
28790 amit.gupta 1643
 
31886 tejbeer 1644
        Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA", attachment);
1645
        Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null, "Itemwise Pending indent", "PFA", attachment1);
28790 amit.gupta 1646
 
31697 amit.gupta 1647
        // Reports to be sent to mapped partners
1648
        Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
28790 amit.gupta 1649
 
31697 amit.gupta 1650
        for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
1651
            Map<String, String> params = new HashMap<>();
1652
            if (storeGuyEntry.getValue().size() == 0)
1653
                continue;
1654
            params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
31886 tejbeer 1655
            InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "focostockreport.xml", params);
31697 amit.gupta 1656
            Attachment attache = new Attachment(
1657
                    "Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
1658
            System.out.println(storeGuyEntry.getValue());
31886 tejbeer 1659
            Utils.sendMailWithAttachments(googleMailSender, new String[]{storeGuyEntry.getKey()}, null, "Franchise Stock Report", "PFA", attache);
31697 amit.gupta 1660
        }
28839 tejbeer 1661
 
31697 amit.gupta 1662
    }
28839 tejbeer 1663
 
31697 amit.gupta 1664
    public void sendIndentTertiary() throws Exception {
28790 amit.gupta 1665
 
31886 tejbeer 1666
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "indentandtertiary.xml");
31697 amit.gupta 1667
        Attachment attachment = new Attachment(
1668
                "indentandtertiary-report-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr);
31886 tejbeer 1669
        Utils.sendMailWithAttachments(googleMailSender, INDENT_TERTIARY_MAIL_LIST, null, "Indent Tertiary Report", "PFA", attachment);
28790 amit.gupta 1670
 
31697 amit.gupta 1671
    }
28790 amit.gupta 1672
 
31697 amit.gupta 1673
    public void sendAttendanceMorningAlert() throws Exception {
1674
        LocalDateTime moriningTime = LocalDate.now().atTime(10, 31);
1675
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
31886 tejbeer 1676
        Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28775 amit.gupta 1677
 
31697 amit.gupta 1678
        List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
1679
        Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28790 amit.gupta 1680
 
31886 tejbeer 1681
        List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now());
28784 amit.gupta 1682
 
31886 tejbeer 1683
        Map<Integer, Optional<EmployeeAttendance>> employeeMorningAttendance = employeeAttendances.stream().collect(groupingBy(EmployeeAttendance::getUserId, Collectors.minBy(Comparator.comparing(EmployeeAttendance::getCreateTimestamp))));
31697 amit.gupta 1684
        for (AuthUser authUser : authUsers) {
1685
            User user = userMap.get(authUser.getEmailId());
1686
            Optional<EmployeeAttendance> employeeAttendanceOptional = employeeMorningAttendance.get(user.getId());
1687
            LOGGER.info("AuthUser - {}, employeeAttendanceOptional {}", authUser.getName(), employeeAttendanceOptional);
1688
            if (employeeAttendanceOptional != null) {
1689
                LOGGER.info("employeeAttendanceOptional.orElse {}", employeeAttendanceOptional.orElse(null));
1690
                if (employeeAttendanceOptional.orElse(null) != null) {
31886 tejbeer 1691
                    LOGGER.info("employeeAttendanceOptional.get().getCreateTimestamp() {}", employeeAttendanceOptional.get().getCreateTimestamp());
31697 amit.gupta 1692
                }
1693
            }
31886 tejbeer 1694
            if (employeeAttendanceOptional == null || employeeAttendanceOptional.orElse(null) == null || employeeAttendanceOptional.get().getCreateTimestamp().isAfter(moriningTime)) {
31697 amit.gupta 1695
                LOGGER.info("Will Send Email to {}", authUser.getFullName());
1696
                String body = String.format(
31886 tejbeer 1697
                        "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 1698
 
31886 tejbeer 1699
                Utils.sendMailWithAttachments(googleMailSender, new String[]{authUser.getEmailId()}, new String[]{"kangan.monga@smartdukaan.com"}, "Attendance Alert", body);
28790 amit.gupta 1700
 
31697 amit.gupta 1701
            }
1702
        }
28790 amit.gupta 1703
 
31697 amit.gupta 1704
    }
28790 amit.gupta 1705
 
31697 amit.gupta 1706
    public void sendAttendanceEveningAlert() throws Exception {
1707
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
31886 tejbeer 1708
        Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28709 amit.gupta 1709
 
31697 amit.gupta 1710
        List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
1711
        Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28709 amit.gupta 1712
 
31886 tejbeer 1713
        Map<Integer, List<EmployeeAttendance>> employeeAttendancesMap = employeeAttendanceRepository.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now()).stream().collect(groupingBy(x -> x.getUserId()));
28709 amit.gupta 1714
 
31697 amit.gupta 1715
        for (AuthUser authUser : authUsers) {
1716
            User user = userMap.get(authUser.getEmailId());
1717
            String body = null;
1718
            List<EmployeeAttendance> employeeAttendances = employeeAttendancesMap.get(user.getId());
1719
            if (employeeAttendances == null) {
1720
                body = String.format(
31886 tejbeer 1721
                        "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 1722
            } else {
31886 tejbeer 1723
                List<LocalDateTime> punchTimes = employeeAttendances.stream().sorted(Comparator.comparing(EmployeeAttendance::getCreateTimestamp)).map(x -> x.getCreateTimestamp()).collect(Collectors.toList());
31697 amit.gupta 1724
                if (punchTimes.size() == 1) {
1725
                    // body = String.format("Dear %s,\n Pls note that you haven't punched out yet.
1726
                    // You have been marked absent for half the day. You may contact your manager
1727
                    // and get it regularise.\n\nRegards\nHR Team", authUser.getFullName());
1728
                } else {
1729
                    LocalDateTime firstPunch = punchTimes.get(0);
1730
                    LocalDateTime lastPunch = punchTimes.get(punchTimes.size() - 1);
1731
                    Duration duration = Duration.between(firstPunch, lastPunch);
1732
                    boolean hoursCompleted = lastPunch.isAfter(firstPunch.plusHours(8).plusMinutes(30));
1733
                    if (!hoursCompleted) {
1734
                        body = String.format(
31886 tejbeer 1735
                                "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 1736
                    }
1737
                }
28709 amit.gupta 1738
 
31697 amit.gupta 1739
            }
1740
            if (body != null) {
31886 tejbeer 1741
                Utils.sendMailWithAttachments(googleMailSender, new String[]{authUser.getEmailId()}, new String[]{"kangan.monga@smartdukaan.com"}, "Attendance Alert", body);
31697 amit.gupta 1742
            }
1743
        }
28709 amit.gupta 1744
 
31697 amit.gupta 1745
        this.sendMailToHR();
28709 amit.gupta 1746
 
31697 amit.gupta 1747
    }
28709 amit.gupta 1748
 
31697 amit.gupta 1749
    private void sendMailToHR() throws Exception {
1750
        Map<String, String> map = new HashMap<>();
1751
        String reporticoDate = FormattingUtils.formatReporitcoDate(LocalDateTime.now());
1752
        map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
1753
        map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
31886 tejbeer 1754
        InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO, "employeeattendance.xml");
1755
        Attachment attachment = new Attachment("attendance-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr);
1756
        Utils.sendMailWithAttachments(googleMailSender, EMPLOYEE_ATTENDANCE_MAIL_LIST, null, "Attendance - " + FormattingUtils.formatDate(LocalDateTime.now()), "PFA Attendance", attachment);
31697 amit.gupta 1757
    }
28709 amit.gupta 1758
 
31697 amit.gupta 1759
    public void checkPartnerActiveStore() throws Exception {
24697 amit.gupta 1760
 
31697 amit.gupta 1761
        List<FofoStore> fofoStores = fofoStoreRepository.selectByStatus(true);
23929 amit.gupta 1762
 
31697 amit.gupta 1763
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1764
        if (!fofoStores.isEmpty()) {
1765
            for (FofoStore fofoStore : fofoStores) {
24551 amit.gupta 1766
 
31697 amit.gupta 1767
                if (currentDate.isBefore(fofoStore.getActiveTimeStamp())) {
24542 amit.gupta 1768
 
31697 amit.gupta 1769
                    fofoStore.setActive(true);
1770
                    fofoStoreRepository.persist(fofoStore);
1771
                    LOGGER.info("inserted into InActiveFofoStore successfully");
29160 amit.gupta 1772
 
31697 amit.gupta 1773
                } else {
1774
                    fofoStore.setActive(false);
1775
                    fofoStore.setActiveTimeStamp(null);
1776
                    fofoStoreRepository.persist(fofoStore);
1777
                    LOGGER.info("inserted into InActiveFofoStore successfully");
1778
                }
24542 amit.gupta 1779
 
31697 amit.gupta 1780
            }
1781
        }
24542 amit.gupta 1782
 
31697 amit.gupta 1783
    }
24548 amit.gupta 1784
 
31697 amit.gupta 1785
    public void sendAgeingReport() throws Exception {
31886 tejbeer 1786
        sendAgeingReport("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "niranjan.kala@smartdukaan.com", "manish.gupta@smartdukaan.com", "kuldeep.kumar@smartdukaan.com");
31697 amit.gupta 1787
    }
24542 amit.gupta 1788
 
31697 amit.gupta 1789
    public void moveImeisToPriceDropImeis() throws Exception {
1790
        List<PriceDrop> priceDrops = priceDropRepository.selectAll();
1791
        for (PriceDrop priceDrop : priceDrops) {
1792
            priceDropService.priceDropStatus(priceDrop.getId());
1793
        }
1794
    }
29160 amit.gupta 1795
 
31697 amit.gupta 1796
    public void walletmismatch() throws Exception {
1797
        LocalDate curDate = LocalDate.now();
1798
        List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
1799
        System.out.println(pdis.size());
1800
        for (PartnerDailyInvestment pdi : pdis) {
1801
            int fofoId = pdi.getFofoId();
31886 tejbeer 1802
            for (PartnerDailyInvestment investment : Lists.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
1803
                float statementAmount = walletService.getOpeningTill(fofoId, investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
31697 amit.gupta 1804
                CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
31886 tejbeer 1805
                LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(), investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
29160 amit.gupta 1806
 
31697 amit.gupta 1807
            }
1808
        }
29160 amit.gupta 1809
 
31697 amit.gupta 1810
    }
29160 amit.gupta 1811
 
31697 amit.gupta 1812
    @Autowired
1813
    StateRepository stateRepository;
29160 amit.gupta 1814
 
31697 amit.gupta 1815
    public void gst() throws Exception {
31886 tejbeer 1816
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2021, 8, 16).atStartOfDay(), LocalDateTime.now());
31697 amit.gupta 1817
        for (FofoOrder fofoOrder : fofoOrders) {
31886 tejbeer 1818
            int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24548 amit.gupta 1819
 
31697 amit.gupta 1820
            Address retailerAddress = addressRepository.selectById(retailerAddressId);
1821
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1822
            Integer stateId = null;
1823
            if (customerAddress.getState().equals(retailerAddress.getState())) {
1824
                try {
1825
                    stateId = stateRepository.selectByName(customerAddress.getState()).getId();
1826
                } catch (Exception e) {
1827
                    LOGGER.error("Cannot found state named {}", customerAddress.getState());
1828
                    continue;
1829
                }
1830
            }
1831
            Map<Integer, GstRate> itemIdStateTaxRateMap = null;
24542 amit.gupta 1832
 
31697 amit.gupta 1833
            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1834
            List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
1835
            if (stateId != null) {
1836
                itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
1837
            } else {
32145 tejbeer 1838
                itemIdStateTaxRateMap = stateGstRateRepository.getIgstTaxRate(itemIds);
31697 amit.gupta 1839
            }
24580 amit.gupta 1840
 
31697 amit.gupta 1841
            for (FofoOrderItem foi : fofoOrderItems) {
1842
                float sgstRate = foi.getSgstRate();
1843
                float cgstRate = foi.getCgstRate();
1844
                float igstRate = foi.getIgstRate();
32145 tejbeer 1845
                foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
1846
                foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
1847
                foi.setIgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
24587 amit.gupta 1848
 
32145 tejbeer 1849
                LOGGER.info("Invoice {}, Date {}", fofoOrder.getInvoiceNumber(), fofoOrder.getCreateTimestamp());
1850
                LOGGER.info("customerAddress.getState() {}, retailerAddress.getState() {}", customerAddress.getState(), retailerAddress.getState());
1851
                LOGGER.info("Rates getIgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getIgstRate());
1852
                LOGGER.info("Rates getCgstRate() {}, getSgstRate() {}", itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate(), itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
24587 amit.gupta 1853
 
1854
 
31697 amit.gupta 1855
            }
1856
        }
26092 amit.gupta 1857
 
31697 amit.gupta 1858
    }
24590 amit.gupta 1859
 
31697 amit.gupta 1860
    public void schemewalletmismatch() {
1861
        LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
1862
        while (dateToReconcile.isBefore(LocalDate.now())) {
1863
            reconcileSchemes(dateToReconcile);
1864
            // reconcileOrders(dateTime);
1865
            // reconcileRecharges(dateTime);
1866
            dateToReconcile = dateToReconcile.plusDays(1);
1867
        }
1868
    }
24587 amit.gupta 1869
 
31697 amit.gupta 1870
    private void reconcileSchemes(LocalDate date) {
1871
        LocalDateTime startDate = date.atStartOfDay();
1872
        LocalDateTime endDate = startDate.plusDays(1);
1873
        List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
1874
        List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
1875
        double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
1876
        double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
1877
        double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
31886 tejbeer 1878
        List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT);
1879
        List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate, walletReferenceTypes);
31697 amit.gupta 1880
        double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
1881
        if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
1882
            LOGGER.info("Scheme Amount mismatched for Date {}", date);
24590 amit.gupta 1883
 
31724 amit.gupta 1884
            Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
24635 amit.gupta 1885
 
31886 tejbeer 1886
            Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet()).stream().collect(groupingBy(x -> x.getFofoId(), Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
24635 amit.gupta 1887
 
31724 amit.gupta 1888
            Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
24635 amit.gupta 1889
 
31886 tejbeer 1890
            Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream().collect(groupingBy(x -> x.getFofoId(), Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
24635 amit.gupta 1891
 
31697 amit.gupta 1892
            Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
24635 amit.gupta 1893
 
31697 amit.gupta 1894
            for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
1895
                if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
1896
                    finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
1897
                } else {
31886 tejbeer 1898
                    finalUserSchemeAmountMap.put(schemeAmount.getKey(), finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
31697 amit.gupta 1899
                }
1900
            }
31886 tejbeer 1901
            Map<Integer, Integer> userWalletMap = userWalletRepository.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24635 amit.gupta 1902
 
31724 amit.gupta 1903
            Map<Integer, Double> walletAmountMap = history.stream().collect(groupingBy(
31697 amit.gupta 1904
                    UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
1905
            for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
1906
                double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1907
                if (diff > 5) {
1908
                    LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1909
                }
1910
            }
1911
        }
24635 amit.gupta 1912
 
31697 amit.gupta 1913
    }
24635 amit.gupta 1914
 
31697 amit.gupta 1915
    public void dryRunSchemeReco() throws Exception {
31886 tejbeer 1916
        Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24635 amit.gupta 1917
 
31697 amit.gupta 1918
        List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1919
        List<SchemeInOut> rolledbackSios = new ArrayList<>();
31886 tejbeer 1920
        Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream().collect(Collectors.toMap(Scheme::getId, Scheme::getType));
31697 amit.gupta 1921
        Set<String> serialNumbersConsidered = new HashSet<>();
24631 amit.gupta 1922
 
31697 amit.gupta 1923
        LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
1924
        LocalDateTime endDate = LocalDate.now().atStartOfDay();
1925
        List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
24598 amit.gupta 1926
 
31697 amit.gupta 1927
        Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
1928
        purchases.stream().forEach(purchase -> {
1929
            float amountToRollback = 0;
31886 tejbeer 1930
            String description = "Adjustment of Duplicate Scheme for Purchase Invoice " + purchase.getPurchaseReference();
1931
            Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId()).stream().filter(ii -> ii.getSerialNumber() != null).collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
31697 amit.gupta 1932
            if (inventorySerialNumberMap.size() > 0) {
1933
                for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1934
                    String serialNumber = inventorySerialNumberEntry.getValue();
1935
                    int inventoryItemId = inventorySerialNumberEntry.getKey();
1936
                    if (serialNumbersConsidered.contains(serialNumber)) {
1937
                        // This will rollback scheme for differenct orders for same serial
31886 tejbeer 1938
                        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 1939
                        Collections.reverse(sios);
1940
                        for (SchemeInOut sio : sios) {
1941
                            sio.setRolledBackTimestamp(LocalDateTime.now());
1942
                            amountToRollback += sio.getAmount();
1943
                            // sio.setSchemeType(SchemeType.OUT);
1944
                            sio.setSerialNumber(serialNumber);
1945
                            rolledbackSios.add(sio);
1946
                        }
1947
                        description = description.concat(" " + serialNumber + " ");
1948
                    } else {
1949
                        serialNumbersConsidered.add(serialNumber);
1950
                        List<Integer> schemesConsidered = new ArrayList<>();
31886 tejbeer 1951
                        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 1952
                        Collections.reverse(sios);
1953
                        for (SchemeInOut sio : sios) {
1954
                            if (!schemesConsidered.contains(sio.getSchemeId())) {
1955
                                schemesConsidered.add(sio.getSchemeId());
1956
                                continue;
1957
                            }
1958
                            sio.setRolledBackTimestamp(LocalDateTime.now());
1959
                            amountToRollback += sio.getAmount();
1960
                            // sio.setSchemeType(SchemeType.OUT);
1961
                            sio.setSerialNumber(serialNumber);
1962
                            sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1963
                            sio.setReference(purchase.getId());
1964
                            rolledbackSios.add(sio);
1965
                        }
1966
                    }
24592 amit.gupta 1967
 
31697 amit.gupta 1968
                }
1969
            }
1970
            if (amountToRollback > 0) {
1971
                // Address address =
1972
                // addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
1973
                UserWalletHistory uwh = new UserWalletHistory();
1974
                uwh.setAmount(Math.round(amountToRollback));
1975
                uwh.setDescription(description);
1976
                uwh.setTimestamp(LocalDateTime.now());
1977
                uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
1978
                uwh.setReference(purchase.getId());
1979
                uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1980
                uwh.setFofoId(purchase.getFofoId());
1981
                uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1982
                userWalletHistory.add(uwh);
1983
            }
1984
        });
1985
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
31886 tejbeer 1986
                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 1987
 
31697 amit.gupta 1988
        ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
31886 tejbeer 1989
                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 1990
 
31886 tejbeer 1991
        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 1992
 
31697 amit.gupta 1993
        throw new Exception();
24615 amit.gupta 1994
 
31697 amit.gupta 1995
    }
24615 amit.gupta 1996
 
31697 amit.gupta 1997
    public void dryRunOutSchemeReco() throws Exception {
1998
        List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1999
        List<SchemeInOut> rolledbackSios = new ArrayList<>();
31886 tejbeer 2000
        Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
2001
        Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream().collect(Collectors.toMap(Scheme::getId, Scheme::getType));
31697 amit.gupta 2002
        LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
2003
        LocalDateTime endDate = LocalDate.now().atStartOfDay();
2004
        List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
2005
        // Collections.reverse(allOrders);
2006
        // List<FofoOrder> allOrders =
2007
        // List<FofoOrder> allOrders =
2008
        // Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
2009
        Set<String> serialNumbersConsidered = new HashSet<>();
2010
        allOrders.stream().forEach(fofoOrder -> {
2011
            String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
2012
            Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
2013
            float amountToRollback = 0;
2014
            List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
2015
            orderItems.forEach(x -> {
31886 tejbeer 2016
                inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null).collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
31697 amit.gupta 2017
            });
2018
            if (inventorySerialNumberMap.size() > 0) {
2019
                for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
2020
                    String serialNumber = inventorySerialNumberEntry.getValue();
2021
                    int inventoryItemId = inventorySerialNumberEntry.getKey();
2022
                    if (serialNumbersConsidered.contains(serialNumber)) {
2023
                        // This will rollback scheme for differenct orders for same serial
31886 tejbeer 2024
                        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 2025
                        Collections.reverse(sios);
2026
                        for (SchemeInOut sio : sios) {
2027
                            sio.setRolledBackTimestamp(LocalDateTime.now());
2028
                            amountToRollback += sio.getAmount();
2029
                            // sio.setSchemeType(SchemeType.OUT);
2030
                            sio.setSerialNumber(serialNumber);
2031
                            sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
2032
                            sio.setReference(fofoOrder.getId());
2033
                            rolledbackSios.add(sio);
2034
                        }
2035
                        description = description.concat(" " + serialNumber + " ");
2036
                    } else {
2037
                        serialNumbersConsidered.add(serialNumber);
2038
                        List<Integer> schemesConsidered = new ArrayList<>();
31886 tejbeer 2039
                        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 2040
                        Collections.reverse(sios);
2041
                        for (SchemeInOut sio : sios) {
2042
                            if (!schemesConsidered.contains(sio.getSchemeId())) {
2043
                                schemesConsidered.add(sio.getSchemeId());
2044
                                continue;
2045
                            }
2046
                            sio.setRolledBackTimestamp(LocalDateTime.now());
2047
                            amountToRollback += sio.getAmount();
2048
                            // sio.setSchemeType(SchemeType.OUT);
2049
                            sio.setReference(fofoOrder.getId());
2050
                            sio.setSerialNumber(serialNumber);
2051
                            sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
2052
                            rolledbackSios.add(sio);
2053
                        }
2054
                    }
24615 amit.gupta 2055
 
31697 amit.gupta 2056
                }
2057
            }
2058
            if (amountToRollback > 0) {
2059
                UserWalletHistory uwh = new UserWalletHistory();
2060
                uwh.setAmount(Math.round(amountToRollback));
2061
                uwh.setDescription(description);
2062
                uwh.setTimestamp(LocalDateTime.now());
2063
                uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
2064
                uwh.setReference(fofoOrder.getId());
2065
                uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
2066
                uwh.setFofoId(fofoOrder.getFofoId());
2067
                uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
2068
                userWalletHistory.add(uwh);
2069
            }
2070
        });
24615 amit.gupta 2071
 
31697 amit.gupta 2072
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
31886 tejbeer 2073
                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 2074
 
31697 amit.gupta 2075
        ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
31886 tejbeer 2076
                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 2077
 
31886 tejbeer 2078
        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 2079
 
31697 amit.gupta 2080
        throw new Exception();
2081
    }
24615 amit.gupta 2082
 
31697 amit.gupta 2083
    public void dryRunSchemeOutReco1() throws Exception {
2084
        List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
2085
        List<UserWalletHistory> userWalletHistory = new ArrayList<>();
2086
        List<SchemeInOut> rolledbackSios = new ArrayList<>();
31886 tejbeer 2087
        Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream().collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
2088
        Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream().collect(Collectors.toMap(Scheme::getId, Scheme::getType));
31697 amit.gupta 2089
        references.stream().forEach(reference -> {
2090
            FofoOrder fofoOrder = null;
2091
            try {
2092
                fofoOrder = fofoOrderRepository.selectByOrderId(reference);
2093
            } catch (Exception e) {
25927 amit.gupta 2094
 
31697 amit.gupta 2095
            }
2096
            String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
2097
            Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
2098
            float amountToRollback = 0;
2099
            List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
2100
            orderItems.forEach(x -> {
31886 tejbeer 2101
                inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null).collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
31697 amit.gupta 2102
            });
2103
            if (inventorySerialNumberMap.size() > 0) {
31886 tejbeer 2104
                List<SchemeInOut> sios = schemeInOutRepository.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream().filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT)).collect(Collectors.toList());
31697 amit.gupta 2105
                LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
2106
                UserWalletHistory uwh = new UserWalletHistory();
31886 tejbeer 2107
                Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream().collect(groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
31697 amit.gupta 2108
                for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
2109
                    List<SchemeInOut> outList = inventorySioEntry.getValue();
2110
                    if (outList.size() > 1) {
24683 amit.gupta 2111
 
31697 amit.gupta 2112
                    }
2113
                }
2114
                uwh.setAmount(Math.round(amountToRollback));
2115
                uwh.setDescription(description);
2116
                uwh.setTimestamp(LocalDateTime.now());
2117
                uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
2118
                uwh.setReference(fofoOrder.getId());
2119
                uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
2120
                uwh.setFofoId(fofoOrder.getFofoId());
2121
                uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
2122
                userWalletHistory.add(uwh);
2123
            }
2124
        });
26945 amit.gupta 2125
 
31697 amit.gupta 2126
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
31886 tejbeer 2127
                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 2128
 
31697 amit.gupta 2129
        ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
31886 tejbeer 2130
                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 2131
 
31886 tejbeer 2132
        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 2133
 
31697 amit.gupta 2134
        throw new Exception();
25880 amit.gupta 2135
 
31697 amit.gupta 2136
    }
30982 tejbeer 2137
 
31697 amit.gupta 2138
    public void sendDailySalesNotificationToPartner(Integer fofoIdInt) throws Exception {
30982 tejbeer 2139
 
31697 amit.gupta 2140
        LocalDateTime now = LocalDateTime.now();
2141
        LocalDateTime from = now.with(LocalTime.MIN);
2142
        String timeString = "Today %s";
2143
        // Send yesterday's report
2144
        /*
2145
         * if (now.getHour() < 13) { timeString = "Yesterday %s"; from =
2146
         * now.minusDays(1).; now = from.with(LocalTime.MAX);
2147
         *
2148
         * }
2149
         */
30982 tejbeer 2150
 
31697 amit.gupta 2151
        List<Integer> fofoIds = null;
31886 tejbeer 2152
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toMap(x -> x.getId(), x -> x));
30982 tejbeer 2153
 
24653 govind 2154
 
31697 amit.gupta 2155
        if (fofoIdInt == null) {
2156
            fofoIds = new ArrayList<>(fofoStoreMap.keySet());
2157
        } else {
2158
            fofoIds = Arrays.asList(fofoIdInt);
2159
        }
2160
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
28368 tejbeer 2161
 
31886 tejbeer 2162
        Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now, null);
31697 amit.gupta 2163
        Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
28368 tejbeer 2164
 
31886 tejbeer 2165
        Map<Integer, Double> spPartnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0, true);
28377 tejbeer 2166
 
31886 tejbeer 2167
        Map<Integer, Double> spPartner3DaysOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from.minusDays(3), now, 0, true);
31697 amit.gupta 2168
        Map<Integer, Long> spPartnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
28368 tejbeer 2169
 
31886 tejbeer 2170
        Map<Integer, Double> partnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0, false);
31697 amit.gupta 2171
        Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, false);
28377 tejbeer 2172
 
31697 amit.gupta 2173
        //4 days + current day running
2174
        Map<Integer, Double> partnerBilledValueMap = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(from.minusDays(4), now);
28377 tejbeer 2175
 
31697 amit.gupta 2176
        Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
2177
        for (int fofoId : fofoIds) {
2178
            SaleTargetReportModel model = new SaleTargetReportModel();
2179
            model.setInsuranceSale(
2180
                    partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
2181
            model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
2182
            model.setSecondary(partnerBilledValueMap.containsKey(fofoId) ? partnerBilledValueMap.get(fofoId) : 0);
2183
            model.setSmartphoneSale(spPartnerOrderValMap.containsKey(fofoId) ? spPartnerOrderValMap.get(fofoId) : 0);
2184
            model.setSmartphoneQty(spPartnerOrderQtyMap.containsKey(fofoId) ? spPartnerOrderQtyMap.get(fofoId) : 0);
2185
            model.setTotalSale(partnerOrderValMap.containsKey(fofoId) ? partnerOrderValMap.get(fofoId) : 0);
2186
            model.setTotalQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
2187
            model.setPast3daysSale(
2188
                    spPartner3DaysOrderValMap.containsKey(fofoId) ? spPartner3DaysOrderValMap.get(fofoId) : 0);
2189
            model.setFofoId(fofoId);
2190
            model.setCode(fofoStoreMap.get(fofoId).getCode());
31724 amit.gupta 2191
            model.setActivationType(fofoStoreMap.get(fofoId).getActivationType());
31697 amit.gupta 2192
            saleTargetReportModelMap.put(fofoId, model);
2193
        }
28377 tejbeer 2194
 
31697 amit.gupta 2195
        Map<Integer, FofoReportingModel> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
2196
        for (Integer fofoId : fofoIds) {
2197
            SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
28368 tejbeer 2198
 
31697 amit.gupta 2199
            // com.spice.profitmandi.dao.entity.user.User user =
2200
            // userUserRepository.selectById(fofoId);
28377 tejbeer 2201
 
31697 amit.gupta 2202
            // Address address = addressRepository.selectById(user.getAddressId());
28377 tejbeer 2203
 
31697 amit.gupta 2204
            String title = "Sale Update";
31886 tejbeer 2205
            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 2206
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
2207
            sendNotificationModel.setCampaignName("Sales update alert");
2208
            sendNotificationModel.setTitle(title);
2209
            sendNotificationModel.setMessage(messageTemplate);
2210
            sendNotificationModel.setType("url");
2211
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
2212
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2213
            sendNotificationModel.setMessageType(MessageType.notification);
2214
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
2215
            sendNotificationModel.setUserIds(Arrays.asList(userId));
2216
            notificationService.sendNotification(sendNotificationModel);
2217
            String whatsappMessageTemplate = String.format(
31886 tejbeer 2218
                    "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 2219
            // notificationService.sendWhatsappMessage(whatsappMessageTemplate, title,
2220
            // address.getPhoneNumber());
28377 tejbeer 2221
 
31697 amit.gupta 2222
        }
2223
        // String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap,
2224
        // saleTargetReportModelMap);
2225
        this.getStateWiseSales(saleTargetReportModelMap, partnerSalesHeadersMap);
2226
    }
28377 tejbeer 2227
 
31697 amit.gupta 2228
    public void checkRazorPayPaymentStatus() throws Exception {
31886 tejbeer 2229
        List<PendingOrder> pendingOrder = pendingOrderRepository.selectAllByStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PENDING);
28377 tejbeer 2230
 
31697 amit.gupta 2231
        for (PendingOrder po : pendingOrder) {
2232
            RazorPay razorPay = razorPayRepository.selectByOrdeId(po.getId());
2233
            List<PendingOrderItem> poItems = pendingOrderItemRepository.selectByOrderId(po.getId());
28369 tejbeer 2234
 
31697 amit.gupta 2235
            LOGGER.info("razorPay" + razorPay);
2236
            if (razorPay != null) {
2237
                List<Payment> payments = razorPaymentService.fetchOrderForPayment(razorPay.getRazorOrderId());
28368 tejbeer 2238
 
31697 amit.gupta 2239
                if (!payments.isEmpty()) {
2240
                    List<String> statusList = new ArrayList<>();
2241
                    for (Payment payment : payments) {
25880 amit.gupta 2242
 
31697 amit.gupta 2243
                        JSONObject jsonObj = new JSONObject(payment.toString());
25880 amit.gupta 2244
 
31697 amit.gupta 2245
                        String status = jsonObj.getString("status");
25880 amit.gupta 2246
 
31697 amit.gupta 2247
                        statusList.add(status);
25865 amit.gupta 2248
 
31697 amit.gupta 2249
                    }
2250
                    LOGGER.info("statusList" + statusList);
26941 amit.gupta 2251
 
31697 amit.gupta 2252
                    if (statusList.contains("authorized") || statusList.contains("captured")) {
2253
                        po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
2254
                        po.setPaidAmount(po.getTotalAmount());
2255
                        for (PendingOrderItem poi : poItems) {
2256
                            poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
2257
                        }
2258
                        Map<String, Object> emailModel = pendingOrderService.sendCreateOrderMail(po);
26941 amit.gupta 2259
 
31697 amit.gupta 2260
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(po.getFofoId());
2261
                        Customer customer = customerRepository.selectById(po.getCustomerId());
2262
                        String[] customerEmail = null;
2263
                        if (customer.getEmailId() != null) {
2264
                            customerEmail = new String[]{customer.getEmailId()};
2265
                        }
31886 tejbeer 2266
                        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 2267
                        List<String> authUserEmails = csService.getAuthUserByPartnerId(customRetailer.getPartnerId());
2268
                        if (authUserEmails != null) {
2269
                            authUserEmails = new ArrayList<>();
2270
                        }
2271
                        authUserEmails.addAll(bccTo);
26945 amit.gupta 2272
 
31697 amit.gupta 2273
                        // emailService.sendMailWithAttachments("Order Created with SmartDukaan",
2274
                        // "order-confirm.vm",
2275
                        // emailModel, customerEmail, null, authUserEmails.toArray(new String[0]));
26945 amit.gupta 2276
 
31697 amit.gupta 2277
                    } else if (statusList.contains("refunded") || statusList.contains("failed")) {
2278
                        for (PendingOrderItem poi : poItems) {
2279
                            poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
2280
                        }
25865 amit.gupta 2281
 
31697 amit.gupta 2282
                        po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
2283
                    }
25865 amit.gupta 2284
 
31697 amit.gupta 2285
                }
2286
                // LOGGER.info("payment" + payments);
25865 amit.gupta 2287
 
31697 amit.gupta 2288
            }
2289
        }
2290
    }
25865 amit.gupta 2291
 
31697 amit.gupta 2292
    public static class SaleTargetReportModel {
2293
        private double totalSale;
2294
        private long totalQty;
2295
        private double past3daysSale;
2296
        private int fofoId;
2297
        private String code;
31724 amit.gupta 2298
        private ActivationType activationType;
25865 amit.gupta 2299
 
31724 amit.gupta 2300
 
2301
        @Override
2302
        public boolean equals(Object o) {
2303
            if (this == o) return true;
2304
            if (o == null || getClass() != o.getClass()) return false;
2305
            SaleTargetReportModel that = (SaleTargetReportModel) o;
2306
            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;
2307
        }
2308
 
2309
        @Override
2310
        public int hashCode() {
2311
            return Objects.hash(totalSale, totalQty, past3daysSale, fofoId, code, activationType, secondary, smartphoneSale, smartphoneQty, insuranceSale, insruanceQty);
2312
        }
2313
 
2314
        public ActivationType getActivationType() {
2315
            return activationType;
2316
        }
2317
 
2318
        public void setActivationType(ActivationType activationType) {
2319
            this.activationType = activationType;
2320
        }
2321
 
31697 amit.gupta 2322
        public double getSecondary() {
2323
            return secondary;
2324
        }
25865 amit.gupta 2325
 
31697 amit.gupta 2326
        public void setSecondary(double secondary) {
2327
            this.secondary = secondary;
2328
        }
25865 amit.gupta 2329
 
31697 amit.gupta 2330
        private double secondary;
25865 amit.gupta 2331
 
31697 amit.gupta 2332
        public int getFofoId() {
2333
            return fofoId;
2334
        }
25865 amit.gupta 2335
 
31697 amit.gupta 2336
        @Override
2337
        public String toString() {
31886 tejbeer 2338
            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 2339
        }
25865 amit.gupta 2340
 
31697 amit.gupta 2341
        public String getCode() {
2342
            return code;
2343
        }
25865 amit.gupta 2344
 
31697 amit.gupta 2345
        public void setCode(String code) {
2346
            this.code = code;
2347
        }
25865 amit.gupta 2348
 
31697 amit.gupta 2349
        public void setFofoId(int fofoId) {
2350
            this.fofoId = fofoId;
2351
        }
25872 tejbeer 2352
 
31697 amit.gupta 2353
        private double smartphoneSale;
2354
        private long smartphoneQty;
2355
        private double insuranceSale;
2356
        private long insruanceQty;
26945 amit.gupta 2357
 
31697 amit.gupta 2358
        public long getTotalQty() {
2359
            return totalQty;
2360
        }
30765 tejbeer 2361
 
31697 amit.gupta 2362
        public void setTotalQty(long totalQty) {
2363
            this.totalQty = totalQty;
2364
        }
2365
 
2366
        public double getPast3daysSale() {
2367
            return past3daysSale;
2368
        }
2369
 
2370
        public void setPast3daysSale(double past3daysSale) {
2371
            this.past3daysSale = past3daysSale;
2372
        }
2373
 
2374
        public double getTotalSale() {
2375
            return totalSale;
2376
        }
2377
 
2378
        public void setTotalSale(double totalSale) {
2379
            this.totalSale = totalSale;
2380
        }
2381
 
2382
        public double getSmartphoneSale() {
2383
            return smartphoneSale;
2384
        }
2385
 
2386
        public void setSmartphoneSale(double smartphoneSale) {
2387
            this.smartphoneSale = smartphoneSale;
2388
        }
2389
 
2390
        public long getSmartphoneQty() {
2391
            return smartphoneQty;
2392
        }
2393
 
2394
        public void setSmartphoneQty(long smartphoneQty) {
2395
            this.smartphoneQty = smartphoneQty;
2396
        }
2397
 
2398
        public double getInsuranceSale() {
2399
            return insuranceSale;
2400
        }
2401
 
2402
        public void setInsuranceSale(double insuranceSale) {
2403
            this.insuranceSale = insuranceSale;
2404
        }
2405
 
2406
        public long getInsruanceQty() {
2407
            return insruanceQty;
2408
        }
2409
 
2410
        public void setInsruanceQty(long insruanceQty) {
2411
            this.insruanceQty = insruanceQty;
2412
        }
2413
 
2414
    }
2415
 
32482 amit.gupta 2416
    private void getStateWiseSales
2417
            (Map<Integer, SaleTargetReportModel> saleTargetReportModelMap, Map<Integer, FofoReportingModel> partnerSalesHeadersMap) throws
2418
            Exception {
31697 amit.gupta 2419
        String timeString = "Today %s";
2420
        LocalDateTime now = LocalDateTime.now();
2421
 
2422
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
31886 tejbeer 2423
        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 2424
 
2425
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false);
2426
 
31746 amit.gupta 2427
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
2428
            String email = storeGuyEntry.getKey();
2429
            Set<Integer> fofoIds = storeGuyEntry.getValue();
2430
            LOGGER.info("fofoIds {}", fofoIds);
24683 amit.gupta 2431
 
31746 amit.gupta 2432
            if (!fofoIds.isEmpty()) {
31886 tejbeer 2433
                List<FofoStore> stores = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds));
26945 amit.gupta 2434
 
31724 amit.gupta 2435
                Map<String, List<Integer>> stateMap = stores.stream().collect(groupingBy(
2436
                        x -> x.getCode().substring(0, 2), mapping(x -> x.getId(), Collectors.toList())));
31697 amit.gupta 2437
                List<List<Serializable>> stateWiseSales = new ArrayList<>();
2438
                for (Map.Entry<String, List<Integer>> stateMapEntry : stateMap.entrySet()) {
31886 tejbeer 2439
                    long totalQty = stateMapEntry.getValue().stream().collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getTotalQty()));
2440
                    double totalSale = stateMapEntry.getValue().stream().collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getTotalSale()));
2441
                    long smartPhoneQty = stateMapEntry.getValue().stream().collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getSmartphoneQty()));
31697 amit.gupta 2442
                    double smartPhoneSale = stateMapEntry.getValue().stream().collect(
2443
                            Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getSmartphoneSale()));
2444
                    stateWiseSales.add(
2445
                            Arrays.asList(stateMapEntry.getKey(), smartPhoneQty, smartPhoneSale, totalQty, totalSale));
2446
                }
2447
                StringBuilder sb = new StringBuilder();
2448
                sb.append("<html><body>");
2449
                sb.append("<p>Statewise Sale Report:</p><br/><table style=\"border-collapse: collapse;\">");
31886 tejbeer 2450
                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 2451
                for (List<Serializable> stateSale : stateWiseSales) {
2452
                    sb.append("<tr>");
2453
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(0) + "</td>");
2454
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(1) + "</td>");
2455
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(2) + "</td>");
2456
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(3) + "</td>");
2457
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(4) + "</td>");
2458
                    sb.append("</tr>");
2459
                }
2460
                sb.append("</tbody></table><br><br>");
26945 amit.gupta 2461
 
31697 amit.gupta 2462
                sb.append("<p>Partnerwise Report:</p><br/><table style=\"border-collapse: collapse;\">");
31886 tejbeer 2463
                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 2464
 
2465
 
31886 tejbeer 2466
                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 2467
 
31697 amit.gupta 2468
                String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
31169 tejbeer 2469
 
31886 tejbeer 2470
                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 2471
                List<List<?>> rows = new ArrayList<>();
2472
                for (Integer fofoId : sortedSaleTargetReport) {
2473
                    FofoReportingModel fofoReportingModel = partnerSalesHeadersMap.get(fofoId);
31886 tejbeer 2474
                    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 2475
                    ));
31169 tejbeer 2476
 
31724 amit.gupta 2477
                    //Now try to populate html rows
2478
                    if (!saleTargetReportModelMap.get(fofoId).getActivationType().equals(ActivationType.ACTIVE)) {
31697 amit.gupta 2479
                        continue;
2480
                    }
2481
                    if (saleTargetReportModelMap.get(fofoId).getSecondary() == 0) {
2482
                        sb.append("<tr style='background-color:#D21F3C;color:white'>");
2483
                    } else {
2484
                        sb.append("<tr>");
2485
                    }
31886 tejbeer 2486
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getCode() + "</td>");
2487
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getBusinessName() + "</td>");
2488
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getBusinessManager() + "</td>");
2489
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getRegionalManager() + "</td>");
2490
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getTerritoryManager() + "</td>");
2491
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSecondary() + "</td>");
2492
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
2493
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
2494
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
31697 amit.gupta 2495
                    sb.append("</tr>");
24841 govind 2496
 
25300 tejbeer 2497
 
31697 amit.gupta 2498
                }
2499
                sb.append("</tr>");
2500
                sb.append("</body></html>");
2501
                String statewiseSaleReport = sb.toString();
25300 tejbeer 2502
 
2503
 
31697 amit.gupta 2504
                ByteArrayOutputStream baos = null;
2505
                try {
2506
                    baos = FileUtil.getCSVByteStream(headers, rows);
2507
                } catch (Exception e2) {
2508
                    e2.printStackTrace();
2509
                }
2510
                Attachment attachment = new Attachment("PartnerSalePerformance.csv", new ByteArrayResource(baos.toByteArray()));
2511
                Utils.sendHtmlMailWithAttachments(googleMailSender, new String[]{email}, null, "Statewise " + subject, statewiseSaleReport, attachment);
2512
            }
2513
        }
2514
    }
29668 tejbeer 2515
 
32350 amit.gupta 2516
 
32482 amit.gupta 2517
    private void sendMailOfHtmlFormat(JavaMailSender sender, String[] email, String body, String cc[], String subject) throws
2518
            MessagingException, ProfitMandiBusinessException, IOException {
32350 amit.gupta 2519
        MimeMessage message = sender.createMimeMessage();
31697 amit.gupta 2520
        MimeMessageHelper helper = new MimeMessageHelper(message);
2521
        helper.setSubject(subject);
2522
        helper.setText(body, true);
2523
        helper.setTo(email);
2524
        if (cc != null) {
2525
            helper.setCc(cc);
2526
        }
2527
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
2528
        helper.setFrom(senderAddress);
2529
        mailSender.send(message);
2530
    }
25694 amit.gupta 2531
 
31697 amit.gupta 2532
    public void sendNotification() throws Exception {
32610 amit.gupta 2533
        List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllPendingNotifications();
31697 amit.gupta 2534
        if (!pushNotifications.isEmpty()) {
2535
            for (PushNotifications pushNotification : pushNotifications) {
2536
                Device device = deviceRepository.selectById(pushNotification.getDeviceId());
31886 tejbeer 2537
                NotificationCampaign notificationCampaign = notificationCampaignRepository.selectById(pushNotification.getNotificationCampaignid());
2538
                SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(), SimpleCampaignParams.class);
31697 amit.gupta 2539
                Campaign campaign = new SimpleCampaign(scp);
2540
                String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
2541
                JSONObject json = new JSONObject();
2542
                json.put("to", device.getFcmId());
2543
                JSONObject jsonObj = new JSONObject();
2544
                jsonObj.put("message", campaign.getMessage());
2545
                jsonObj.put("title", campaign.getTitle());
2546
                jsonObj.put("type", campaign.getType());
2547
                jsonObj.put("url", result_url);
2548
                jsonObj.put("time_to_live", campaign.getExpireTimestamp());
2549
                jsonObj.put("image", campaign.getImageUrl());
2550
                jsonObj.put("largeIcon", "large_icon");
2551
                jsonObj.put("smallIcon", "small_icon");
2552
                jsonObj.put("vibrate", 1);
2553
                jsonObj.put("pid", pushNotification.getId());
2554
                jsonObj.put("sound", 1);
2555
                jsonObj.put("priority", "high");
2556
                json.put("data", jsonObj);
2557
                try {
2558
                    CloseableHttpClient client = HttpClients.createDefault();
2559
                    HttpPost httpPost = new HttpPost(FCM_URL);
25694 amit.gupta 2560
 
31697 amit.gupta 2561
                    httpPost.setHeader("Content-Type", "application/json; utf-8");
2562
                    httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
2563
                    StringEntity entity = new StringEntity(json.toString());
2564
                    httpPost.setEntity(entity);
2565
                    CloseableHttpResponse response = client.execute(httpPost);
30858 amit.gupta 2566
 
31697 amit.gupta 2567
                    if (response.getStatusLine().getStatusCode() == 200) {
2568
                        pushNotification.setSentTimestamp(LocalDateTime.now());
2569
                    } else {
2570
                        pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
2571
                        LOGGER.info("message" + "not sent");
2572
                        response.toString();
2573
                    }
25694 amit.gupta 2574
 
31697 amit.gupta 2575
                } catch (Exception e) {
2576
                    e.printStackTrace();
2577
                    pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
2578
                    LOGGER.info("message " + "not sent " + e.getMessage());
2579
                }
2580
            }
2581
        }
2582
    }
25721 tejbeer 2583
 
31697 amit.gupta 2584
    public void grouping() throws Exception {
2585
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
2586
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
31886 tejbeer 2587
        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 2588
        Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers(false);
2589
        for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
2590
            if (priceDropIMEI.getPartnerId() == 0)
2591
                continue;
2592
            HashSet<String> imeis = new HashSet<>();
2593
            PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
2594
            imeis.add(priceDropIMEI.getImei());
31886 tejbeer 2595
            List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
31697 amit.gupta 2596
            if (inventoryItems.size() == 0) {
2597
                LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
2598
                continue;
2599
            }
2600
            InventoryItem inventoryItem = inventoryItems.get(0);
2601
            CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
31886 tejbeer 2602
            if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) || inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
31697 amit.gupta 2603
                // check if pricedrop has been rolled out
31886 tejbeer 2604
                List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(), priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
31697 amit.gupta 2605
                if (uwh.size() > 0) {
2606
                    Item item = itemRepository.selectById(inventoryItem.getItemId());
31886 tejbeer 2607
                    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 2608
                }
2609
            }
2610
        }
2611
    }
25721 tejbeer 2612
 
31697 amit.gupta 2613
    public void toffeeRollback() throws Exception {
2614
        toffeeService.cancelPolicyCopy("110143521986");
2615
        toffeeService.getOrderId("110143521986");
2616
    }
27212 tejbeer 2617
 
31697 amit.gupta 2618
    public void attachToffeeInvoices() throws Exception {
31886 tejbeer 2619
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(3, Optional.of(false));
31697 amit.gupta 2620
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
2621
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
2622
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
2623
            InvoicePdfModel pdfModel = orderService.getInvoicePdfModel(fofoOrder.getId());
2624
            java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
2625
            PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
31886 tejbeer 2626
            String pdfInvoiceString = "data:application/pdf;base64," + Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
2627
            boolean attached = toffeeService.attachInvoice(insurancePolicy.getPolicyNumber().split("#")[1], pdfInvoiceString);
31697 amit.gupta 2628
            if (attached) {
2629
                insurancePolicy.setPosted(true);
2630
            }
2631
        }
2632
    }
25721 tejbeer 2633
 
31697 amit.gupta 2634
    public void sendBAGPendingPolicies() throws Exception {
31886 tejbeer 2635
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(4, Optional.of(false));
31697 amit.gupta 2636
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
2637
            String invoiceNumber = insurancePolicy.getInvoiceNumber();
2638
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
2639
            FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
2640
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
2641
            Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
2642
            BAGInsuranceModel bagInsuranceModel = new BAGInsuranceModel();
2643
            // bagInsuranceModel.setModelId();
2644
            bagInsuranceModel.setAddressLine1(customerAddress.getLine1());
2645
            bagInsuranceModel.setAddressLine2(customerAddress.getLine2());
2646
            bagInsuranceModel.setCity(customerAddress.getCity());
2647
            bagInsuranceModel.setBrandWarranty("1 Year");
2648
            Item item = itemRepository.selectById(fofoOrderItem.getId());
2649
            bagInsuranceModel.setModelName(item.getItemDescription());
2650
            bagInsuranceModel.setDateOfPurchase(fofoOrder.getFormattedDate());
2651
            bagInsuranceModel.setEmail(customer.getEmailId());
2652
            bagInsuranceModel.setImei1(insurancePolicy.getSerialNumber());
2653
            bagInsuranceModel.setFirstName(customer.getFirstName());
2654
            bagInsuranceModel.setLastName(customer.getLastName());
2655
            bagInsuranceModel.setMobileNumber(customer.getMobileNumber());
2656
            bagInsuranceModel.setPlanId("");
2657
            insurancePolicy.setPosted(true);
2658
        }
2659
    }
25721 tejbeer 2660
 
31697 amit.gupta 2661
    public void schemeRollback(List<String> schemeIds) throws Exception {
2662
        List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
31886 tejbeer 2663
        Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31697 amit.gupta 2664
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
2665
        for (SchemeInOut sio : schemeInOuts) {
2666
            Scheme scheme = schemesMap.get(sio.getSchemeId());
2667
            if (scheme.getType().equals(SchemeType.IN)) {
25721 tejbeer 2668
 
31697 amit.gupta 2669
            } else if (scheme.getType().equals(SchemeType.OUT)) {
2670
                InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
2671
                List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
31886 tejbeer 2672
                ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE)).max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
2673
                if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime()) || scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
31697 amit.gupta 2674
                    sio.setRolledBackTimestamp(LocalDateTime.now());
2675
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
31886 tejbeer 2676
                    String rollbackReason = "Scheme reversed for " + itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - " + fofoOrder.getInvoiceNumber();
2677
                    walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(), scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason, LocalDateTime.now());
2678
                    System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(), rollbackReason);
31697 amit.gupta 2679
                }
2680
            }
2681
        }
2682
        // throw new Exception();
2683
    }
25721 tejbeer 2684
 
31697 amit.gupta 2685
    public void checkfocusedModelInPartnerStock() throws Exception {
25721 tejbeer 2686
 
31886 tejbeer 2687
        List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
2688
        Map<Integer, Map<Integer, List<SaholicCIS>>> warehouseItemAvailabilityMap = saholicInventoryService.getSaholicStock();
31697 amit.gupta 2689
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2690
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
25721 tejbeer 2691
 
31886 tejbeer 2692
        Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService.getSaholicPOItems();
31697 amit.gupta 2693
        Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
2694
        for (Integer fofoId : fofoIds) {
2695
            List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
2696
            focusedModelShortageReportMap.put(fofoId, focusedModelShortageList);
2697
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2698
            Map<Integer, Integer> processingOrderMap = null;
2699
            Map<Integer, Integer> catalogIdAndQtyMap = null;
2700
            Map<Integer, Integer> grnPendingOrdersMap = null;
25721 tejbeer 2701
 
31886 tejbeer 2702
            Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
25721 tejbeer 2703
 
31697 amit.gupta 2704
            if (!currentInventorySnapshot.isEmpty()) {
31886 tejbeer 2705
                catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream().collect(groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
25800 tejbeer 2706
 
31697 amit.gupta 2707
            }
25800 tejbeer 2708
 
31886 tejbeer 2709
            Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream().collect(groupingBy(x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
31697 amit.gupta 2710
            if (!grnPendingOrders.isEmpty()) {
31886 tejbeer 2711
                grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream().collect(groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
25721 tejbeer 2712
 
31697 amit.gupta 2713
            }
25721 tejbeer 2714
 
31886 tejbeer 2715
            Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream().collect(groupingBy(x -> x.getLineItem().getItemId(), Collectors.summingInt(x -> x.getLineItem().getQuantity())));
31697 amit.gupta 2716
            if (!processingOrder.isEmpty()) {
31886 tejbeer 2717
                processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream().collect(groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> processingOrder.get(x.getId()))));
25721 tejbeer 2718
 
31697 amit.gupta 2719
            }
25721 tejbeer 2720
 
31886 tejbeer 2721
            List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
28526 tejbeer 2722
 
31886 tejbeer 2723
            List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
31697 amit.gupta 2724
            LOGGER.info("regionIds" + regionIds);
2725
            if (regionIds.size() == 0) {
2726
                LOGGER.info("No region found for partner {}", fofoId);
2727
                continue;
2728
            }
31886 tejbeer 2729
            Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream().collect(groupingBy(FocusedModel::getCatalogId, mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
25721 tejbeer 2730
 
31697 amit.gupta 2731
            LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
32060 amit.gupta 2732
 
32048 tejbeer 2733
            Map<String, RetailerBlockBrands> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(fofoId).stream().collect(Collectors.toMap(x -> x.getBlockBrands(), x -> x));
31388 amit.gupta 2734
 
32048 tejbeer 2735
 
31697 amit.gupta 2736
            for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
2737
                int minQty = entry.getValue().get();
2738
                int inStockQty = 0;
2739
                int processingQty = 0;
2740
                int grnPendingQty = 0;
2741
                int allColorNetAvailability = 0;
2742
                int allColorPoAvailability = 0;
2743
                if (processingOrderMap != null) {
31886 tejbeer 2744
                    processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0 : processingOrderMap.get(entry.getKey());
31388 amit.gupta 2745
 
31697 amit.gupta 2746
                }
2747
                if (grnPendingOrdersMap != null) {
31886 tejbeer 2748
                    grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0 : grnPendingOrdersMap.get(entry.getKey());
25721 tejbeer 2749
 
31697 amit.gupta 2750
                }
2751
                if (catalogIdAndQtyMap != null) {
31886 tejbeer 2752
                    inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0 : catalogIdAndQtyMap.get(entry.getKey());
27213 tejbeer 2753
 
31697 amit.gupta 2754
                }
25721 tejbeer 2755
 
31697 amit.gupta 2756
                int grnStockQty = grnPendingQty + inStockQty;
2757
                int totalQty = processingQty + grnPendingQty + inStockQty;
27208 tejbeer 2758
 
31697 amit.gupta 2759
                int shortageQty = minQty - totalQty;
2760
                List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());
28528 tejbeer 2761
 
31697 amit.gupta 2762
                TagListing tagListing = tagListingRepository.selectByCatalogId(entry.getKey());
27208 tejbeer 2763
 
31697 amit.gupta 2764
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
25721 tejbeer 2765
 
31886 tejbeer 2766
                Map<Integer, List<SaholicCIS>> itemAvailabilityMap = warehouseItemAvailabilityMap.get(fofoStore.getWarehouseId());
27233 tejbeer 2767
 
31886 tejbeer 2768
                Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap.get(fofoStore.getWarehouseId());
29801 manish 2769
 
31697 amit.gupta 2770
                for (Item item : items) {
2771
                    List<SaholicCIS> currentAvailability = null;
2772
                    List<SaholicPOItem> poItemAvailability = null;
2773
                    if (itemAvailabilityMap != null) {
2774
                        currentAvailability = itemAvailabilityMap.get(item.getId());
2775
                    }
25721 tejbeer 2776
 
31697 amit.gupta 2777
                    if (poItemAvailabilityMap != null) {
2778
                        poItemAvailability = poItemAvailabilityMap.get(item.getId());
2779
                    }
2780
                    if (currentAvailability != null) {
31886 tejbeer 2781
                        allColorNetAvailability += currentAvailability.stream().collect(Collectors.summingInt(SaholicCIS::getNetavailability));
31697 amit.gupta 2782
                    }
25800 tejbeer 2783
 
31697 amit.gupta 2784
                    if (poItemAvailability != null) {
31886 tejbeer 2785
                        allColorPoAvailability += poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
31697 amit.gupta 2786
                    }
25800 tejbeer 2787
 
31697 amit.gupta 2788
                }
25721 tejbeer 2789
 
31697 amit.gupta 2790
                FocusedModelShortageModel fm = new FocusedModelShortageModel();
2791
                fm.setFofoId(fofoId);
2792
                fm.setStoreCode(fofoStore.getCode());
2793
                fm.setStoreName(customRetailer.getBusinessName());
2794
                fm.setBrandName(items.get(0).getBrand());
2795
                fm.setModelName(items.get(0).getModelName());
2796
                fm.setModelNumber(items.get(0).getModelNumber());
2797
                fm.setGrnStockQty(grnStockQty);
2798
                fm.setPendingIndentQty(processingQty);
2799
                fm.setShortageQty(shortageQty);
2800
                fm.setPoAvailability(allColorPoAvailability);
2801
                fm.setDp(tagListing.getSellingPrice());
2802
                fm.setWarehouseName(warehouseMap.get(customRetailer.getWarehouseId()));
2803
                fm.setStateManager(partnerIdSalesHeadersMap.get(fofoId).getRegionalManager());
2804
                fm.setTerritoryManager(partnerIdSalesHeadersMap.get(fofoId).getTerritoryManager());
2805
                fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
2806
                fm.setAvailability(allColorNetAvailability);
25721 tejbeer 2807
 
31697 amit.gupta 2808
                focusedModelShortageList.add(fm);
2809
            }
25721 tejbeer 2810
 
31697 amit.gupta 2811
        }
2812
        if (!focusedModelShortageReportMap.isEmpty()) {
2813
            String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
2814
            Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2815
            Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 2816
 
31697 amit.gupta 2817
            focusedModelShortageReportMap.entrySet().forEach(x -> {
2818
                storeGuyMap.entrySet().forEach(y -> {
28526 tejbeer 2819
 
31697 amit.gupta 2820
                    if (y.getValue().contains(x.getKey())) {
2821
                        if (!emailRowsMap.containsKey(y.getKey())) {
2822
                            emailRowsMap.put(y.getKey(), new ArrayList<>());
2823
                        }
31886 tejbeer 2824
                        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 2825
                        emailRowsMap.get(y.getKey()).addAll(fms);
29995 tejbeer 2826
 
31697 amit.gupta 2827
                    }
29995 tejbeer 2828
 
31697 amit.gupta 2829
                });
25721 tejbeer 2830
 
31697 amit.gupta 2831
            });
25721 tejbeer 2832
 
31886 tejbeer 2833
            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 2834
            emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 2835
 
31697 amit.gupta 2836
                ByteArrayOutputStream baos = null;
2837
                try {
2838
                    baos = FileUtil.getCSVByteStream(headers, entry.getValue());
2839
                } catch (Exception e2) {
2840
                    e2.printStackTrace();
2841
                }
2842
                String[] sendToArray = new String[]{
25721 tejbeer 2843
 
31886 tejbeer 2844
                        entry.getKey(), "apurve.shrivastava@smartdukaan.com", "puneet.bisht@smartdukaan.com"
25721 tejbeer 2845
 
31697 amit.gupta 2846
                };
25721 tejbeer 2847
 
31886 tejbeer 2848
 
31697 amit.gupta 2849
                try {
31886 tejbeer 2850
                    Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
31697 amit.gupta 2851
                } catch (Exception e1) { // TODO Auto-generated catch block
2852
                    e1.printStackTrace();
2853
                }
25721 tejbeer 2854
 
31697 amit.gupta 2855
            });
2856
        }
2857
    }
25721 tejbeer 2858
 
31697 amit.gupta 2859
    private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2860
        StringBuilder sb = new StringBuilder();
2861
        sb.append("Focused Model Shortage in Your Stock : \n");
2862
        for (FocusedModelShortageModel entry : focusedModelShortageModel) {
25721 tejbeer 2863
 
31697 amit.gupta 2864
            sb.append(entry.getItemName() + "-" + entry.getShortageQty());
2865
            sb.append(String.format("%n", ""));
2866
        }
2867
        return sb.toString();
2868
    }
25721 tejbeer 2869
 
31697 amit.gupta 2870
    private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
2871
        MimeMessage message = mailSender.createMimeMessage();
2872
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
25721 tejbeer 2873
 
31697 amit.gupta 2874
        helper.setSubject(subject);
2875
        helper.setText(messageText, true);
2876
        helper.setTo(email);
2877
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
2878
        helper.setFrom(senderAddress);
2879
        mailSender.send(message);
25721 tejbeer 2880
 
31697 amit.gupta 2881
    }
25721 tejbeer 2882
 
31697 amit.gupta 2883
    private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2884
        StringBuilder sb = new StringBuilder();
31886 tejbeer 2885
        sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
2886
        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 2887
        for (FocusedModelShortageModel entry : focusedModelShortageModel) {
25721 tejbeer 2888
 
31697 amit.gupta 2889
            sb.append("<tr>");
2890
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
25936 amit.gupta 2891
 
31697 amit.gupta 2892
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
26790 tejbeer 2893
 
31697 amit.gupta 2894
            sb.append("</tr>");
25927 amit.gupta 2895
 
31697 amit.gupta 2896
        }
26790 tejbeer 2897
 
31697 amit.gupta 2898
        sb.append("</tbody></table></body></html>");
26945 amit.gupta 2899
 
31697 amit.gupta 2900
        return sb.toString();
2901
    }
26945 amit.gupta 2902
 
31697 amit.gupta 2903
    public void notifyLead() throws Exception {
31886 tejbeer 2904
        List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
2905
        Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
31697 amit.gupta 2906
        LOGGER.info("authUserEmailMap {}", authUserEmailMap);
31886 tejbeer 2907
        Map<String, Integer> dtrEmailMap = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25982 amit.gupta 2908
 
31697 amit.gupta 2909
        LOGGER.info("dtrEmailMap {}", dtrEmailMap);
26283 tejbeer 2910
 
31697 amit.gupta 2911
        Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26283 tejbeer 2912
 
31697 amit.gupta 2913
        for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2914
            int authId = authUserEmail.getKey();
2915
            String email = authUserEmail.getValue();
2916
            authUserKeyMap.put(authId, dtrEmailMap.get(email));
2917
        }
2918
        LOGGER.info("authUserKeyMap", authUserKeyMap);
2919
        LOGGER.info("leadsToNotify {}", leadsToNotify);
26283 tejbeer 2920
 
31697 amit.gupta 2921
        String templateMessage = "Lead followup for %s %s, %s, %s is due by %s";
2922
        for (Lead lead : leadsToNotify) {
2923
            if (authUserKeyMap.get(lead.getAssignTo()) == null) {
2924
                LOGGER.info("Assignee no longer part of system {}", lead.getAssignTo());
2925
                continue;
2926
            }
2927
            String title = "Leads followup Reminder";
31886 tejbeer 2928
            String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(), lead.getAddress(), lead.getLeadMobile(), leadTimeFormatter.format(lead.getScheduledTimestamp()));
31697 amit.gupta 2929
            String url = "https://app.smartdukaan.com/pages/home/leadUpdate?leadId=" + lead.getId();
2930
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
2931
            sendNotificationModel.setCampaignName("Lead Reminder");
2932
            sendNotificationModel.setTitle(title);
2933
            sendNotificationModel.setMessage(notificationMessage);
2934
            sendNotificationModel.setType("url");
2935
            sendNotificationModel.setUrl(url);
2936
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2937
            sendNotificationModel.setMessageType(MessageType.reminder);
2938
            sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAssignTo())));
2939
            System.out.println(sendNotificationModel);
2940
            notificationService.sendNotification(sendNotificationModel);
2941
        }
2942
    }
26790 tejbeer 2943
 
32350 amit.gupta 2944
    @Autowired
2945
    AuthService authService;
2946
 
2947
    public void sendUnscheduledFollowUpMail() throws Exception {
2948
        List<Lead> missedScheduleLeads = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDate.now().atStartOfDay().minusDays(30), LocalDateTime.now().toLocalDate().atStartOfDay());
2949
        List<Lead> leadsScheduledForToday = leadRepository.selectLeadsScheduledBetweenDate(null, LocalDate.now().atStartOfDay(), LocalDate.now().atTime(LocalTime.MAX));
2950
        List<Integer> authIds = missedScheduleLeads.stream().map(x -> x.getAssignTo()).distinct().collect(Collectors.toList());
2951
        LOGGER.info(authIds.size());
2952
        Map<Integer, AuthUser> authUserMap = authRepository.selectAllAuthUserByIds(authIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
2953
        LOGGER.info(authUserMap.size());
2954
        //if(true) return;
2955
 
2956
        missedScheduleLeads = missedScheduleLeads.stream().sorted(Comparator.comparing(Lead::getState, String.CASE_INSENSITIVE_ORDER).thenComparing(Lead::getAssignTo).thenComparing(Lead::getScheduledTimestamp)).collect(Collectors.toList());
2957
        //leadsScheduledForToday
2958
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
2959
        LOGGER.info("Auth Users Size - {}", authUsers.size());
2960
        for (AuthUser authUser : authUsers) {
2961
            LOGGER.info("Auth Name - {}", authUser.getFullName());
2962
            List<Integer> reporteeAuthIds = authService.getAllReportees(authUser.getId());
2963
            reporteeAuthIds.add(authUser.getId());
2964
            StringBuilder sb = new StringBuilder();
2965
            sb.append("<html><body>");
2966
            List<Lead> authMissedScheduledLeads = missedScheduleLeads.stream().filter(x -> reporteeAuthIds.contains(x.getAssignTo())).collect(Collectors.toList());
2967
            LOGGER.info("authMissedScheduledLeads {}", authMissedScheduledLeads.size());
2968
            if (authMissedScheduledLeads.size() > 0) {
2969
                addMissedScheduledLeadsTable(sb, authMissedScheduledLeads, authUserMap);
2970
                sb.append("</body></html>");
2971
 
2972
                String subject = "Lead Updates Summary";
32421 amit.gupta 2973
                String[] email = Arrays.asList(authUser.getEmailId()).toArray(new String[1]);
2974
                //String[] email = Arrays.asList("amit.gupta@smartdukaan.com").toArray(new String[1]);
32350 amit.gupta 2975
                this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
32421 amit.gupta 2976
                //break;
32350 amit.gupta 2977
            }
2978
        }
2979
 
2980
    }
2981
 
32482 amit.gupta 2982
    private void addMissedScheduledLeadsTable(StringBuilder
2983
                                                      sb, List<Lead> missedScheduleLeads, Map<Integer, AuthUser> authUserMap) {
32350 amit.gupta 2984
        sb.append("<h3>Leads That Missed the schedule</h3>");
32439 tejbeer 2985
        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 2986
        for (Lead lead : missedScheduleLeads) {
32439 tejbeer 2987
            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(
2988
                    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 2989
        }
2990
        sb.append("</table>");
2991
    }
2992
 
31697 amit.gupta 2993
    public void notifyVisits() throws Exception {
31886 tejbeer 2994
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
2995
        Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
2996
        Map<String, Integer> dtrEmailMap = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
31697 amit.gupta 2997
        Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26790 tejbeer 2998
 
31697 amit.gupta 2999
        for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
3000
            int authId = authUserEmail.getKey();
3001
            String email = authUserEmail.getValue();
3002
            authUserKeyMap.put(authId, dtrEmailMap.get(email));
3003
        }
3004
        String visitTemplate = "Planned visit to franchisee %s is due by %s";
3005
        String followupTemplate = "Lead followup for franchisee %s is due by %s";
3006
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
3007
        for (FranchiseeVisit visit : franchiseeVisits) {
3008
            if (authUserKeyMap.containsKey(visit.getAuthId())) {
3009
                continue;
3010
            }
3011
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
3012
            String message = null;
3013
            if (visit.getFranchiseActivityId() == 0) {
31886 tejbeer 3014
                message = String.format(visitTemplate, visit.getPartnerName(), timeFormatter.format(visit.getScheduleTimestamp()));
31697 amit.gupta 3015
                sendNotificationModel.setCampaignName("Franchisee visit Reminder");
3016
            } else {
31886 tejbeer 3017
                message = String.format(followupTemplate, visit.getPartnerName(), timeFormatter.format(visit.getScheduleTimestamp()));
31697 amit.gupta 3018
                sendNotificationModel.setCampaignName("Franchisee followup Reminder");
3019
            }
3020
            sendNotificationModel.setMessage(message);
3021
            sendNotificationModel.setType("url");
3022
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
3023
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
3024
            sendNotificationModel.setMessageType(MessageType.reminder);
3025
            sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
3026
            // notificationService.sendNotification(sendNotificationModel);
3027
        }
3028
    }
26792 tejbeer 3029
 
31697 amit.gupta 3030
    public void ticketClosed() throws Exception {
26790 tejbeer 3031
 
31697 amit.gupta 3032
        List<Ticket> tickets = ticketRepository.selectAllNotClosedTicketsWithStatus(ActivityType.RESOLVED);
3033
        for (Ticket ticket : tickets) {
3034
            if (ticket.getUpdateTimestamp().toLocalDate().isBefore(LocalDate.now().minusDays(7))) {
3035
                ticket.setCloseTimestamp(LocalDateTime.now());
3036
                ticket.setLastActivity(ActivityType.RESOLVED_ACCEPTED);
3037
                ticket.setUpdateTimestamp(LocalDateTime.now());
3038
                ticketRepository.persist(ticket);
3039
            }
3040
        }
26790 tejbeer 3041
 
31697 amit.gupta 3042
    }
26790 tejbeer 3043
 
31697 amit.gupta 3044
    public void checkValidateReferral() throws Exception {
26790 tejbeer 3045
 
31697 amit.gupta 3046
        List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
3047
        LOGGER.info("referrals" + referrals);
3048
        if (!referrals.isEmpty()) {
3049
            String subject = "Referral Request";
3050
            String messageText = this.getMessageForReferral(referrals);
26790 tejbeer 3051
 
31697 amit.gupta 3052
            MimeMessage message = mailSender.createMimeMessage();
3053
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
3054
            String[] email = {"kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com"};
3055
            helper.setSubject(subject);
3056
            helper.setText(messageText, true);
3057
            helper.setTo(email);
3058
            InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
3059
            helper.setFrom(senderAddress);
3060
            mailSender.send(message);
26790 tejbeer 3061
 
31697 amit.gupta 3062
        }
3063
    }
26790 tejbeer 3064
 
31697 amit.gupta 3065
    private String getMessageForReferral(List<Refferal> referrals) {
3066
        StringBuilder sb = new StringBuilder();
31886 tejbeer 3067
        sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
3068
        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 3069
        for (Refferal entry : referrals) {
26790 tejbeer 3070
 
31697 amit.gupta 3071
            sb.append("<tr>");
3072
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
30421 tejbeer 3073
 
31697 amit.gupta 3074
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
3075
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
3076
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
3077
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
3078
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
30421 tejbeer 3079
 
31697 amit.gupta 3080
            sb.append("</tr>");
30421 tejbeer 3081
 
31697 amit.gupta 3082
        }
30421 tejbeer 3083
 
31697 amit.gupta 3084
        sb.append("</tbody></table></body></html>");
30421 tejbeer 3085
 
31697 amit.gupta 3086
        return sb.toString();
3087
    }
30421 tejbeer 3088
 
32482 amit.gupta 3089
    private String getMessageForUncontacblePartner(List<PartnerCollectionRemark> pcrs) throws
3090
            ProfitMandiBusinessException {
31697 amit.gupta 3091
        StringBuilder sb = new StringBuilder();
31886 tejbeer 3092
        sb.append("<html><body><p>Alert</p><p>Not Responding Partner:-</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
3093
        sb.append("<tbody>\n" + "	    				<tr>\n" + "	    					<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>from</th>\n"
30421 tejbeer 3094
 
31697 amit.gupta 3095
                + "	    				</tr>");
3096
        for (PartnerCollectionRemark entry : pcrs) {
30421 tejbeer 3097
 
31697 amit.gupta 3098
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30421 tejbeer 3099
 
31697 amit.gupta 3100
            sb.append("<tr>");
31886 tejbeer 3101
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
28205 tejbeer 3102
 
31886 tejbeer 3103
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
28205 tejbeer 3104
 
31697 amit.gupta 3105
            sb.append("</tr>");
28205 tejbeer 3106
 
31697 amit.gupta 3107
        }
28205 tejbeer 3108
 
31697 amit.gupta 3109
        sb.append("</tbody></table></body></html>");
28205 tejbeer 3110
 
31697 amit.gupta 3111
        return sb.toString();
3112
    }
28208 tejbeer 3113
 
31697 amit.gupta 3114
    public void reverseWallet() throws Exception {
3115
        LocalDate localDate = LocalDate.of(2020, 10, 28);
31886 tejbeer 3116
        List<UserWalletHistory> uwhList = userWalletHistoryRepository.selectAllByDateType(localDate.atStartOfDay(), localDate.plusDays(1).atStartOfDay(), Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
31697 amit.gupta 3117
        for (UserWalletHistory uwh : uwhList) {
3118
            if (uwh.getBusinessTimestamp().getMonth().equals(Month.SEPTEMBER)) {
3119
                UserWallet uw = userWalletRepository.selectById(uwh.getWalletId());
3120
                // LOGGER.info("UWH - {}", uwh);
3121
                // amount += uwh.getAmount();
3122
                // System.out.println("Amount is - " + amount);
3123
                // walletService.rollbackAmountFromWallet(uw.getUserId(), uwh.getAmount(),
3124
                // uwh.getReference(), uwh.getReferenceType(), "Margin reversal for error prone
3125
                // run", uwh.getBusinessTimestamp());
3126
                int orderId = uwh.getReference();
3127
                FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
3128
                int inventoryItemId = 0;
3129
                // fofoOrderRepository.delete(fofoOrder);
3130
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3131
                /*
3132
                 * List<PaymentOptionTransaction> paymentOptionTransactions =
3133
                 * paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId
3134
                 * (), PaymentOptionReferenceType.ORDER); for(PaymentOptionTransaction
3135
                 * paymentOptionTransaction : paymentOptionTransactions) {
3136
                 * //paymentOptionTransactionRepository.delete(paymentOptionTransaction); }
3137
                 */
3138
                for (FofoOrderItem foi : fofoOrderItems) {
3139
                    // fofoOrderItemRepository.delete(foi);
3140
                    List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
3141
                    for (FofoLineItem fli : flis) {
3142
                        // fofoLineItemRepository.delete(fli);
3143
                        inventoryItemId = fli.getInventoryItemId();
3144
                    }
3145
                }
3146
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(
3147
                        java.util.stream.Stream.of(inventoryItemId).collect(Collectors.toSet()));
3148
                for (SchemeInOut sio : schemeInOuts) {
3149
                    if (sio.getCreateTimestamp().toLocalDate().equals(localDate)) {
3150
                        LOGGER.info("SIO - {}", sio);
3151
                        sio.setRolledBackTimestamp(LocalDateTime.now());
3152
                    }
3153
                }
28208 tejbeer 3154
 
31697 amit.gupta 3155
            }
3156
        }
28208 tejbeer 3157
 
31697 amit.gupta 3158
    }
28208 tejbeer 3159
 
31697 amit.gupta 3160
    public void partnerProblemAlert() throws Exception {
3161
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
3162
        Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
3163
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
31886 tejbeer 3164
        Map<Integer, Double> mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), 0, false);
3165
        Map<Integer, PartnerDailyInvestment> pdi = partnerDailyInvestmentRepository.selectAll(LocalDate.now()).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 3166
 
31697 amit.gupta 3167
        for (Entry<Integer, Double> ls : lmtdSale.entrySet()) {
28208 tejbeer 3168
 
31697 amit.gupta 3169
            double lmtdTwentyPercentSale = ls.getValue() * 0.2;
28208 tejbeer 3170
 
31697 amit.gupta 3171
            LOGGER.info("lmtdTwentyPercentSale" + lmtdTwentyPercentSale);
28208 tejbeer 3172
 
31697 amit.gupta 3173
            double mtdSale = mtdSales.get(ls.getKey()) == null ? 0 : mtdSales.get(ls.getKey());
28205 tejbeer 3174
 
31697 amit.gupta 3175
            LOGGER.info("mtdSale" + mtdSale);
28205 tejbeer 3176
 
31886 tejbeer 3177
            double totalSixtyPercentInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getTotalInvestment() * 0.6;
28205 tejbeer 3178
 
31697 amit.gupta 3179
            LOGGER.info("totalSixtyPercentInvestment" + totalSixtyPercentInvestment);
28205 tejbeer 3180
 
31697 amit.gupta 3181
            double stockInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getInStockAmount();
28205 tejbeer 3182
 
31697 amit.gupta 3183
            LOGGER.info("stockInvestment" + stockInvestment);
28205 tejbeer 3184
 
31697 amit.gupta 3185
            boolean Investmentvalue = partnerInvestmentService.isInvestmentBelow(ls.getKey(), 25);
28205 tejbeer 3186
 
31697 amit.gupta 3187
            PartnerProblem partnerProblem = partnerProblemRepository.selectByFofoId(ls.getKey());
28205 tejbeer 3188
 
31697 amit.gupta 3189
            if (partnerProblem == null) {
3190
                partnerProblem = new PartnerProblem();
3191
                partnerProblem.setFofoId(ls.getKey());
3192
                if (mtdSale < lmtdTwentyPercentSale) {
3193
                    partnerProblem.setMtd(1);
3194
                }
3195
                if (Investmentvalue) {
3196
                    partnerProblem.setInvestment(1);
3197
                }
28205 tejbeer 3198
 
31697 amit.gupta 3199
                if (stockInvestment < totalSixtyPercentInvestment) {
3200
                    partnerProblem.setInvestment(1);
3201
                }
28205 tejbeer 3202
 
31697 amit.gupta 3203
                partnerProblemRepository.persist(partnerProblem);
3204
            } else {
3205
                if (mtdSale < lmtdTwentyPercentSale) {
3206
                    partnerProblem.setMtd(partnerProblem.getMtd() + 1);
28213 tejbeer 3207
 
31697 amit.gupta 3208
                } else {
3209
                    partnerProblem.setMtd(0);
28227 tejbeer 3210
 
31697 amit.gupta 3211
                }
3212
                if (Investmentvalue) {
3213
                    partnerProblem.setInvestment(partnerProblem.getInvestment() + 1);
3214
                } else {
3215
                    partnerProblem.setInvestment(0);
28227 tejbeer 3216
 
31697 amit.gupta 3217
                }
3218
                if (stockInvestment < totalSixtyPercentInvestment) {
3219
                    partnerProblem.setStockInvestment(partnerProblem.getStockInvestment() + 1);
3220
                } else {
3221
                    partnerProblem.setStockInvestment(0);
3222
                }
28213 tejbeer 3223
 
31697 amit.gupta 3224
            }
28213 tejbeer 3225
 
31697 amit.gupta 3226
        }
28213 tejbeer 3227
 
31886 tejbeer 3228
        List<PartnerProblem> partnerProblems = partnerProblemRepository.selectAll().stream().filter(x -> x.getMtd() + x.getInvestment() + x.getStockInvestment() > 0).collect(Collectors.toList());
28205 tejbeer 3229
 
31697 amit.gupta 3230
        partnerProblems = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 3231
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 3232
        }).collect(Collectors.toList());
28205 tejbeer 3233
 
31697 amit.gupta 3234
        Map<Integer, PartnerProblem> partnerProblemMap = partnerProblems.stream().sorted((x1, x2) -> {
31886 tejbeer 3235
            return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment() + x2.getStockInvestment() ? 1 : -1;
31697 amit.gupta 3236
        }).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
28205 tejbeer 3237
 
31697 amit.gupta 3238
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
28205 tejbeer 3239
 
31697 amit.gupta 3240
        List<Integer> assignTo = Arrays.asList(15, 9, 54, 53);
28205 tejbeer 3241
 
31886 tejbeer 3242
        Map<Integer, AuthUser> assignAuthUserMap = authRepository.selectAllAuthUserByIds(assignTo).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
28222 tejbeer 3243
 
31886 tejbeer 3244
        List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com", "sm@smartdukaan.com");
31697 amit.gupta 3245
        LOGGER.info("partnerProblem" + partnerProblems);
3246
        StringBuilder sb = new StringBuilder();
3247
        sb.append("<htl><body>");
3248
        sb.append(
3249
                "<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 3250
        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 3251
 
31697 amit.gupta 3252
                + "	    				</tr>");
28218 tejbeer 3253
 
31697 amit.gupta 3254
        for (PartnerProblem pp : partnerProblems) {
3255
            int value = pp.getFofoId() % 4;
28218 tejbeer 3256
 
31697 amit.gupta 3257
            Map<EscalationType, AuthUser> authUserMap = csService.getAuthUserAndEsclationByPartnerId(pp.getFofoId());
3258
            LOGGER.info("authUserMap" + authUserMap);
3259
            sb.append("<tr>");
31886 tejbeer 3260
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
3261
            sb.append("<td style='border:1px solid black;padding: 5px'>" + assignAuthUserMap.get(assignTo.get(value)).getName() + "</td>");
31697 amit.gupta 3262
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
3263
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
3264
            sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
31886 tejbeer 3265
            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 3266
 
31697 amit.gupta 3267
            sb.append("</tr>");
3268
        }
3269
        sb.append("</tbody></table><br><br>");
3270
        String subject = "Partner Problem Alert!";
3271
        String[] email = sendTo.toArray(new String[sendTo.size()]);
28227 tejbeer 3272
 
32350 amit.gupta 3273
        this.sendMailOfHtmlFormat(googleMailSender, email, sb.toString(), null, subject);
28227 tejbeer 3274
 
31697 amit.gupta 3275
        Map<Integer, List<Integer>> authUserPartnerMapping = csService.getAuthUserIdPartnerIdMapping();
28224 tejbeer 3276
 
31697 amit.gupta 3277
        for (Entry<Integer, List<Integer>> authUserPartner : authUserPartnerMapping.entrySet()) {
3278
            AuthUser authUser = authRepository.selectById(authUserPartner.getKey());
3279
            for (Integer patnerId : authUserPartner.getValue()) {
3280
                if (partnerProblemMap.get(patnerId) != null) {
28230 tejbeer 3281
 
31697 amit.gupta 3282
                    StringBuilder sbbuilder = new StringBuilder();
3283
                    sbbuilder.append("<hml><body>");
3284
                    sb.append(
3285
                            "<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 3286
                    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 3287
 
31697 amit.gupta 3288
                            + "	    				</tr>");
28205 tejbeer 3289
 
31697 amit.gupta 3290
                    for (Integer partnerId : authUserPartner.getValue()) {
3291
                        if (partnerProblemMap.get(partnerId) != null) {
3292
                            PartnerProblem pp = partnerProblemMap.get(partnerId);
3293
                            sbbuilder.append("<tr>");
31886 tejbeer 3294
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
3295
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
31697 amit.gupta 3296
                            sbbuilder.append(
3297
                                    "<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
31886 tejbeer 3298
                            sbbuilder.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
28790 amit.gupta 3299
 
31697 amit.gupta 3300
                            sbbuilder.append("</tr>");
3301
                        }
28790 amit.gupta 3302
 
31697 amit.gupta 3303
                    }
3304
                    sbbuilder.append("</tbody></table><br><br>");
29488 manish 3305
 
32350 amit.gupta 3306
                    this.sendMailOfHtmlFormat(googleMailSender, new String[]{authUser.getEmailId()}, sbbuilder.toString(), null, subject);
31697 amit.gupta 3307
                }
29488 manish 3308
 
31697 amit.gupta 3309
            }
3310
        }
3311
    }
28775 amit.gupta 3312
 
31697 amit.gupta 3313
    @Autowired
3314
    WarehouseRepository warehouseRepository;
29488 manish 3315
 
31697 amit.gupta 3316
    public void getVendorWarehouses(int warehouseId) {
3317
        LOGGER.info("Warehouses - {}", warehouseRepository.getVendorWarehouses().get(warehouseId));
29488 manish 3318
 
31697 amit.gupta 3319
    }
29488 manish 3320
 
31697 amit.gupta 3321
    public void checkImeiActivation() {
29801 manish 3322
 
31697 amit.gupta 3323
        try {
3324
            vivoImeiActivationService.checkImeiActivation();
3325
        } catch (ProfitMandiBusinessException e) {
3326
            // TODO Auto-generated catch block
3327
            e.printStackTrace();
3328
        } catch (IOException e) {
3329
            // TODO Auto-generated catch block
3330
            e.printStackTrace();
3331
        } catch (Exception e) {
3332
            // TODO Auto-generated catch block
3333
            e.printStackTrace();
3334
        }
29807 manish 3335
 
31697 amit.gupta 3336
    }
29801 manish 3337
 
31697 amit.gupta 3338
    public void checkItelImeiActivation(LocalDate date, Integer day) {
3339
        LOGGER.info("Hello - {}", "hhh");
29488 manish 3340
 
31697 amit.gupta 3341
        try {
3342
            itelImeiActivationService.checkItelImeiActivation(date, day);
3343
        } catch (ProfitMandiBusinessException e) {
3344
            // TODO Auto-generated catch block
3345
            e.printStackTrace();
3346
        } catch (IOException e) {
3347
            // TODO Auto-generated catch block
3348
            e.printStackTrace();
3349
        } catch (Exception e) {
3350
            // TODO Auto-generated catch block
3351
            e.printStackTrace();
3352
        }
29488 manish 3353
 
31697 amit.gupta 3354
    }
29488 manish 3355
 
32482 amit.gupta 3356
    public void selectFinServiceFollowUpDateByCurrDate(LocalDate currentDate) throws
3357
            MessagingException, ProfitMandiBusinessException, IOException {
31697 amit.gupta 3358
        LOGGER.info("selectfinServiceFollow - {}", "selectfinServiceFollowUpDateByCurrDate");
29308 tejbeer 3359
 
31697 amit.gupta 3360
        serviceConfigService.selectFinServicePartnerfollowUpDateByCurrentDate(currentDate);
29252 amit.gupta 3361
 
31697 amit.gupta 3362
    }
29451 manish 3363
 
31697 amit.gupta 3364
    public void checkTecnoImeiActivation(LocalDate date, Integer day) {
3365
        LOGGER.info("Hello - {}", "hhh");
29308 tejbeer 3366
 
31697 amit.gupta 3367
        try {
3368
            tecnoImeiActivation.checkTecnoImeiActivation(date, day);
3369
        } catch (ProfitMandiBusinessException e) {
3370
            // TODO Auto-generated catch block
3371
            e.printStackTrace();
3372
        } catch (IOException e) {
3373
            // TODO Auto-generated catch block
3374
            e.printStackTrace();
3375
        } catch (Exception e) {
3376
            // TODO Auto-generated catch block
3377
            e.printStackTrace();
3378
        }
29308 tejbeer 3379
 
31697 amit.gupta 3380
    }
29441 tejbeer 3381
 
31697 amit.gupta 3382
    public void checkCancellationMargin() throws Exception {
3383
        LocalDateTime startDate = LocalDate.of(2021, 4, 1).atStartOfDay();
3384
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectCancelledBetweenSaleDate(startDate, LocalDateTime.now());
3385
        LOGGER.info("Total Orders =  {}", fofoOrders.size());
3386
        for (FofoOrder fofoOrder : fofoOrders) {
31886 tejbeer 3387
            List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
3388
            history.addAll(userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.ACTIVATION_SCHEME));
31697 amit.gupta 3389
            int walletSum = history.stream().mapToInt(x -> x.getAmount()).sum();
3390
            if (Math.abs(walletSum) > 1) {
3391
                // LOGGER.info("Cancelled invoice {}, Order Id = {}, = havent rolledback, Value
3392
                // = {}", fofoOrder.getInvoiceNumber(), fofoOrder.getId(), walletSum);
3393
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3394
                List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(fofoOrderItems.get(0).getId());
3395
                FofoLineItem fli = flis.get(0);
3396
                if (StringUtils.isEmpty(fli.getSerialNumber()))
3397
                    continue;
31886 tejbeer 3398
                List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(fli.getInventoryItemId())));
31697 amit.gupta 3399
                InventoryItem inventoryItem = inventoryItemRepository.selectById(fli.getInventoryItemId());
31886 tejbeer 3400
                double schemeSum = schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).mapToDouble(x -> x.getAmount()).sum();
31697 amit.gupta 3401
                /*
3402
                 * if(inventoryItem.getGoodQuantity()==1) {
3403
                 * LOGGER.info("GoodQty, Serial Number {}, InventoryItem = {}, Billed on {}",
3404
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3405
                 * inventoryItem.getUpdateTimestamp()); } else
3406
                 * if(inventoryItem.getBadQuantity()==1){
3407
                 * LOGGER.info("Bad Qty, Serial Number {}, InventoryItem = {}, Billed on {}",
3408
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3409
                 * inventoryItem.getUpdateTimestamp()); } else if
3410
                 * (inventoryItem.getLastScanType().equals(ScanType.SALE)) { LOGGER.
3411
                 * info("Problem Sold, Serial Number {}, InventoryItem = {}, Billed on {}",
3412
                 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3413
                 * inventoryItem.getUpdateTimestamp()); }
3414
                 */
31886 tejbeer 3415
                if (inventoryItem.getLastScanType().equals(ScanType.SALE) || inventoryItem.getLastScanType().equals(ScanType.SALE_RET)) {
3416
                    Map<String, Double> map = schemeInOuts.stream().collect(
3417
                            groupingBy(
3418
                                    x -> DateTimeFormatter.ofPattern("yyyyMMddHH").format(x.getCreateTimestamp()) + "- " + x.getSchemeId(), Collectors.summingDouble(x -> x.getAmount())));
31697 amit.gupta 3419
                    for (Map.Entry<String, Double> entry : map.entrySet()) {
3420
                        LOGGER.info("{} = {}", entry.getKey(), entry.getValue());
3421
                    }
31886 tejbeer 3422
                    LOGGER.info("id- {}, imei- {}, lastScan = {}, Scheme sum - {}", inventoryItem.getId(), inventoryItem.getSerialNumber(), inventoryItem.getLastScanType(), schemeSum);
31697 amit.gupta 3423
                }
3424
            }
3425
        }
29441 tejbeer 3426
 
31697 amit.gupta 3427
    }
29308 tejbeer 3428
 
31697 amit.gupta 3429
    public static String readFileAsString(String file) throws Exception {
3430
        String data = "";
3431
        data = new String(Files.readAllBytes(Paths.get(file)));
3432
        return data;
3433
    }
29308 tejbeer 3434
 
32307 amit.gupta 3435
    public void markDelhiveryOrderDelivered() throws Exception {
31886 tejbeer 3436
        List<Order> orders = orderRepository.selectOrderByProviderIdAndStatus(ProfitMandiConstants.DELHIVERY_PROVIDERID, OrderStatus.SHIPPED_FROM_WH);
29308 tejbeer 3437
 
31697 amit.gupta 3438
        if (!orders.isEmpty()) {
3439
            Set<String> airwayBill = orders.stream().map(x -> x.getAirwayBillNumber()).collect(Collectors.toSet());
29308 tejbeer 3440
 
31697 amit.gupta 3441
            int arraylength = airwayBill.size();
29308 tejbeer 3442
 
31697 amit.gupta 3443
            if (arraylength >= 75) {
29308 tejbeer 3444
 
31697 amit.gupta 3445
                airwayBill = airwayBill.stream().limit(74).collect(Collectors.toSet());
3446
            }
3447
            LOGGER.info("airwayBill" + airwayBill);
3448
            String url = "https://track.delhivery.com/api/v1/packages/json/";
29308 tejbeer 3449
 
31697 amit.gupta 3450
            OkHttpClient client = new OkHttpClient();
29308 tejbeer 3451
 
31886 tejbeer 3452
            Request request1 = new Request.Builder().url(url + "?waybill=" + String.join(",", airwayBill) + "&token=" + token).get().build();
29308 tejbeer 3453
 
31697 amit.gupta 3454
            LOGGER.info("request1" + request1);
29308 tejbeer 3455
 
31697 amit.gupta 3456
            Response response = client.newCall(request1).execute();
29308 tejbeer 3457
 
31697 amit.gupta 3458
            LOGGER.info("jsonbj" + response.body());
29308 tejbeer 3459
 
31697 amit.gupta 3460
            JSONObject jsonObj = new JSONObject(response.body().string());
29308 tejbeer 3461
 
31697 amit.gupta 3462
            LOGGER.info("jsonObj" + jsonObj);
29308 tejbeer 3463
 
31697 amit.gupta 3464
            JSONArray shipmentData = jsonObj.getJSONArray("ShipmentData");
3465
            Set<String> airwaybillStatus = new HashSet<>();
3466
            for (int i = 0; i < shipmentData.length(); i++) {
3467
                JSONObject jsonObject = shipmentData.getJSONObject(i);
3468
                JSONObject shipment = jsonObject.getJSONObject("Shipment");
30982 tejbeer 3469
 
31697 amit.gupta 3470
                LOGGER.info("shipment" + shipment);
3471
                JSONObject statusDescription = shipment.getJSONObject("Status");
3472
                String awb = shipment.getString("AWB");
30982 tejbeer 3473
 
31697 amit.gupta 3474
                String status = statusDescription.getString("Status");
3475
                LOGGER.info("status" + status);
30982 tejbeer 3476
 
31697 amit.gupta 3477
                LOGGER.info("awb" + awb);
3478
                if (status.equals("Delivered")) {
3479
                    airwaybillStatus.add(awb);
3480
                }
30982 tejbeer 3481
 
31697 amit.gupta 3482
            }
3483
            markOrderDelivered(airwaybillStatus);
3484
        }
3485
    }
29308 tejbeer 3486
 
32307 amit.gupta 3487
    public void markBlueDartOrderDelivered() throws Exception {
30982 tejbeer 3488
 
31697 amit.gupta 3489
        String loginId = "DEL81122";
31117 tejbeer 3490
 
31697 amit.gupta 3491
        String licencekey = "uhfhlg2jpmnqfhfrlsgzfr1nhu1qfvel";
31117 tejbeer 3492
 
31886 tejbeer 3493
        List<Order> orders = orderRepository.selectOrderByProviderIdAndStatus(ProfitMandiConstants.BLUEDART_PROVIDERID, OrderStatus.SHIPPED_FROM_WH);
31117 tejbeer 3494
 
31697 amit.gupta 3495
        if (!orders.isEmpty()) {
31117 tejbeer 3496
 
31697 amit.gupta 3497
            Set<String> airwayBillNo = orders.stream().map(x -> x.getAirwayBillNumber()).collect(Collectors.toSet());
31117 tejbeer 3498
 
31697 amit.gupta 3499
            LOGGER.info("airwayBill" + airwayBillNo);
3500
            String url = "https://api.bluedart.com/servlet/RoutingServlet?handler=tnt&action=custawbquery";
31117 tejbeer 3501
 
31886 tejbeer 3502
            String response = restClient.get(url + "&loginid=" + loginId + "&awb=awb&numbers=" + String.join(",", airwayBillNo) + "&format=xml&lickey=" + licencekey + "&verno=1.3&scan=1", null, null);
31117 tejbeer 3503
 
31697 amit.gupta 3504
            JSONObject updateJson = XML.toJSONObject(response);
31117 tejbeer 3505
 
31697 amit.gupta 3506
            JSONObject shipmentData = updateJson.getJSONObject("ShipmentData");
3507
            Object shipmentObject = shipmentData.get("Shipment");
31117 tejbeer 3508
 
31697 amit.gupta 3509
            Set<String> airwaybillStatus = new HashSet<>();
29308 tejbeer 3510
 
31697 amit.gupta 3511
            if (shipmentObject instanceof JSONArray) {
3512
                JSONArray shipments = (JSONArray) shipmentObject;
3513
                for (int i = 0; i < shipments.length(); i++) {
3514
                    JSONObject jsonObject = shipments.getJSONObject(i);
31117 tejbeer 3515
 
31697 amit.gupta 3516
                    Number awb = jsonObject.getNumber("WaybillNo");
3517
                    String status = jsonObject.getString("Status");
31117 tejbeer 3518
 
31697 amit.gupta 3519
                    if (status.equals("SHIPMENT DELIVERED")) {
3520
                        airwaybillStatus.add(awb.toString());
3521
                    }
29308 tejbeer 3522
 
31697 amit.gupta 3523
                }
3524
            } else {
3525
                JSONObject jsonObject = (JSONObject) shipmentObject;
3526
                Number awb = jsonObject.getNumber("WaybillNo");
3527
                String status = jsonObject.getString("Status");
31117 tejbeer 3528
 
31697 amit.gupta 3529
                if (status.equals("SHIPMENT DELIVERED")) {
3530
                    airwaybillStatus.add(awb.toString());
3531
                }
31117 tejbeer 3532
 
31697 amit.gupta 3533
            }
31117 tejbeer 3534
 
31697 amit.gupta 3535
            LOGGER.info("airwaybillStatus" + airwaybillStatus);
31117 tejbeer 3536
 
31697 amit.gupta 3537
            markOrderDelivered(airwaybillStatus);
3538
        }
31117 tejbeer 3539
 
31697 amit.gupta 3540
    }
31117 tejbeer 3541
 
32307 amit.gupta 3542
    private void markOrderDelivered(Set<String> airwaybillStatus) throws Exception {
31697 amit.gupta 3543
        if (!airwaybillStatus.isEmpty()) {
3544
            for (String aws : airwaybillStatus) {
31117 tejbeer 3545
 
31697 amit.gupta 3546
                List<Order> deliverdOrders = orderRepository.selectByAirwayBillNumber(aws);
31117 tejbeer 3547
 
31697 amit.gupta 3548
                int fofoId = deliverdOrders.get(0).getRetailerId();
3549
                for (Order dlo : deliverdOrders) {
3550
                    dlo.setStatus(OrderStatus.DELIVERY_SUCCESS);
3551
                    dlo.setStatusDescription("Order Delivered");
3552
                    dlo.setDeliveryTimestamp(LocalDateTime.now());
3553
                }
31117 tejbeer 3554
 
31697 amit.gupta 3555
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
31117 tejbeer 3556
 
31697 amit.gupta 3557
                Address address = addressRepository.selectById(user.getAddressId());
29814 tejbeer 3558
 
31697 amit.gupta 3559
                String title = "Order Delivered";
29814 tejbeer 3560
 
31886 tejbeer 3561
                String message = String.format("Dear partner, Your SmartDukaan Order " + aws + " has been delivered to you in a safe sealed bag.");
29814 tejbeer 3562
 
31697 amit.gupta 3563
                SendNotificationModel sendNotificationModel = new SendNotificationModel();
3564
                sendNotificationModel.setCampaignName("Order Delivered");
3565
                sendNotificationModel.setTitle(title);
3566
                sendNotificationModel.setMessage(message);
3567
                sendNotificationModel.setType("url");
3568
                sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
3569
                sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
3570
                sendNotificationModel.setMessageType(MessageType.notification);
3571
                int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
3572
                sendNotificationModel.setUserIds(Arrays.asList(userId));
3573
                notificationService.sendNotification(sendNotificationModel);
29815 tejbeer 3574
 
31697 amit.gupta 3575
                notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
29814 tejbeer 3576
 
31697 amit.gupta 3577
            }
3578
        }
3579
    }
29814 tejbeer 3580
 
31697 amit.gupta 3581
    public void partnerWiseCreditAccount() throws Exception {
29814 tejbeer 3582
 
31697 amit.gupta 3583
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
29814 tejbeer 3584
 
31697 amit.gupta 3585
        for (FofoStore fs : fofoStores) {
29835 tejbeer 3586
 
31697 amit.gupta 3587
            if (fs.getPan() != null) {
3588
                AccountStatusResponseOut accountStatusResponseOut = mandiiService.getStatus(fs.getPan());
29835 tejbeer 3589
 
31697 amit.gupta 3590
                LOGGER.info("accountStatusResponseOut" + accountStatusResponseOut);
31886 tejbeer 3591
                CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fs.getId(), Gateway.MANDII);
29817 tejbeer 3592
 
31697 amit.gupta 3593
                if (creditAccount == null) {
29835 tejbeer 3594
 
31697 amit.gupta 3595
                    creditAccount = new CreditAccount();
29835 tejbeer 3596
 
31697 amit.gupta 3597
                    creditAccount.setFofoId(fs.getId());
3598
                    creditAccount.setGateway(Gateway.MANDII);
29817 tejbeer 3599
 
31697 amit.gupta 3600
                }
29814 tejbeer 3601
 
31697 amit.gupta 3602
                if (accountStatusResponseOut == null) {
3603
                    creditAccount.setCreditStatus(CreditStatus.UNKNOWN);
3604
                    creditAccount.setDescription("User company not found");
30421 tejbeer 3605
 
31697 amit.gupta 3606
                } else {
3607
                    if (accountStatusResponseOut.getSanctionLimit() != null) {
3608
                        creditAccount.setSanctionedAmount(accountStatusResponseOut.getSanctionLimit().floatValue());
3609
                    } else {
3610
                        creditAccount.setSanctionedAmount(0);
3611
                    }
30421 tejbeer 3612
 
31697 amit.gupta 3613
                    creditAccount.setInterestRate(accountStatusResponseOut.getRateOfInterest());
3614
                    if (accountStatusResponseOut.getBalanceAmount() != null) {
3615
                        creditAccount.setAvailableAmount(accountStatusResponseOut.getBalanceAmount().floatValue());
3616
                    } else {
3617
                        creditAccount.setAvailableAmount(0);
3618
                    }
30421 tejbeer 3619
 
31697 amit.gupta 3620
                    if (accountStatusResponseOut.getCurrentStage() != null) {
3621
                        creditAccount.setDescription(accountStatusResponseOut.getCurrentStage().toString());
3622
                    }
3623
                    if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.SANCTION_AVAILABLE)) {
3624
                        creditAccount.setCreditStatus(CreditStatus.SANCTIONED);
3625
                    } else if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.IN_ELIGIBLE)) {
3626
                        creditAccount.setCreditStatus(CreditStatus.INELIGIBLE);
3627
                    } else {
30421 tejbeer 3628
 
31697 amit.gupta 3629
                        creditAccount.setCreditStatus(CreditStatus.TO_BE_EVALUATED);
3630
                    }
3631
                }
30421 tejbeer 3632
 
31697 amit.gupta 3633
                creditAccount.setUpdatedOn(LocalDateTime.now());
3634
                creditAccountRepository.persist(creditAccount);
3635
            }
3636
        }
3637
    }
30421 tejbeer 3638
 
31697 amit.gupta 3639
    @Autowired
3640
    private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
30421 tejbeer 3641
 
32482 amit.gupta 3642
    public void reviewUncontactablePartner() throws
3643
            ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
30421 tejbeer 3644
 
31697 amit.gupta 3645
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
30421 tejbeer 3646
 
31886 tejbeer 3647
        List<Integer> pcrms = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(customRetailerMap.keySet()));
30859 tejbeer 3648
 
31697 amit.gupta 3649
        if (!pcrms.isEmpty()) {
31886 tejbeer 3650
            Map<Integer, PartnerCollectionRemark> partnerCollectionRemarksMap = partnerCollectionRemarkRepository.selectByIds(pcrms).stream().filter(x -> x.getRemark().equals(CollectionRemark.NOT_RESPONDING)).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30421 tejbeer 3651
 
31697 amit.gupta 3652
            if (!partnerCollectionRemarksMap.isEmpty()) {
31886 tejbeer 3653
                for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
3654
                    List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerCollectionRemarksMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
31697 amit.gupta 3655
                    String subject = "UNCONTACTABLE PARTNERS";
3656
                    String messageText = this.getMessageForUncontacblePartner(filteredRows);
30859 tejbeer 3657
 
31697 amit.gupta 3658
                    MimeMessage message = mailSender.createMimeMessage();
3659
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
3660
                    String[] email = new String[]{storeGuyEntry.getKey()};
30859 tejbeer 3661
 
31697 amit.gupta 3662
                    helper.setSubject(subject);
3663
                    helper.setText(messageText, true);
3664
                    helper.setTo(email);
31886 tejbeer 3665
                    InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
31697 amit.gupta 3666
                    helper.setFrom(senderAddress);
3667
                    mailSender.send(message);
30859 tejbeer 3668
 
31697 amit.gupta 3669
                    LOGGER.info("filteredRows {}", filteredRows);
30859 tejbeer 3670
 
31697 amit.gupta 3671
                }
3672
            }
30936 tejbeer 3673
 
31697 amit.gupta 3674
        }
3675
    }
30936 tejbeer 3676
 
31697 amit.gupta 3677
    @Autowired
3678
    private LoanRepository loanRepository;
31020 tejbeer 3679
 
31697 amit.gupta 3680
    @Autowired
3681
    private LoanStatementRepository loanStatementRepository;
30859 tejbeer 3682
 
31697 amit.gupta 3683
    @Autowired
3684
    private SDCreditService sdCreditService;
30859 tejbeer 3685
 
31697 amit.gupta 3686
    @Autowired
3687
    private SDCreditRequirementRepository sdCreditRequirementRepository;
30859 tejbeer 3688
 
31697 amit.gupta 3689
    @Autowired
3690
    private CurrentPartnerDailyInvestmentRepository currentPartnerDailyInvestmentRepository;
30859 tejbeer 3691
 
31697 amit.gupta 3692
    @Autowired
3693
    private TransactionRepository transactionRepository;
30859 tejbeer 3694
 
31697 amit.gupta 3695
    @Autowired
3696
    private SanctionRequestRepository sanctionRequestRepository;
30859 tejbeer 3697
 
31697 amit.gupta 3698
    public void calculateInterestAccured() throws ProfitMandiBusinessException {
3699
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30859 tejbeer 3700
 
32724 amit.gupta 3701
        for (Loan loan : loans) {
3702
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
3703
            Map<LoanReferenceType, Double> loanStatusAmount = loanStatements.stream().collect(groupingBy(
3704
                    x -> x.getLoanReferenceType(), Collectors.summingDouble(x -> x.getAmount().doubleValue())));
30936 tejbeer 3705
 
32724 amit.gupta 3706
            int freeDays = loan.getFreeDays();
30936 tejbeer 3707
 
32724 amit.gupta 3708
            LocalDateTime freeDaysLimitDate = loan.getCreatedOn().plusDays(freeDays);
30936 tejbeer 3709
 
32724 amit.gupta 3710
            LOGGER.info("freeDaysLimitDate {}", freeDaysLimitDate);
3711
            if (LocalDateTime.now().isAfter(freeDaysLimitDate)) {
3712
                int loanStatementId = loanStatementRepository.selectLatestLoanSatement(loan.getFofoId(), loan.getId());
3713
                LOGGER.info("loanStatementId {}", loanStatementId);
3714
                if (loanStatementId != 0) {
3715
                    this.calculateInterest(loan, loanStatusAmount, loanStatementId);
31697 amit.gupta 3716
                } else {
32724 amit.gupta 3717
                    sdCreditService.addInterest(freeDaysLimitDate.toLocalDate(), LocalDate.now(), loan, loanStatusAmount);
31697 amit.gupta 3718
                }
32724 amit.gupta 3719
            }
31518 amit.gupta 3720
 
31697 amit.gupta 3721
        }
30936 tejbeer 3722
 
32724 amit.gupta 3723
 
31697 amit.gupta 3724
    }
30936 tejbeer 3725
 
31697 amit.gupta 3726
    @Autowired
3727
    FofoPaymentRepository fofoPaymentRepository;
30936 tejbeer 3728
 
31697 amit.gupta 3729
    @Autowired
3730
    CCAvenuePaymentService ccAvenuePaymentService;
30936 tejbeer 3731
 
31697 amit.gupta 3732
    public void settleCCAvePayments() throws Exception {
31886 tejbeer 3733
        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 3734
        for (FofoPayment fofoPayment : fofoPayments) {
3735
            ccAvenuePaymentService.updatePayment(fofoPayment);
3736
        }
3737
    }
30859 tejbeer 3738
 
31697 amit.gupta 3739
    /*
3740
     * public void getCCAvenuePendingOrderStatus(int pendingOrderId) { PendingOrder
3741
     * pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
3742
     * ccAvenuePaymentService.getPaymentStatusMap(pendingOrder); }
3743
     */
30859 tejbeer 3744
 
32482 amit.gupta 3745
    private void calculateInterest(Loan loan, Map<LoanReferenceType, Double> loanStatusAmount,
3746
                                   int loanStatementId) throws ProfitMandiBusinessException {
31697 amit.gupta 3747
        LoanStatement loanStatement = loanStatementRepository.selectById(loanStatementId);
30859 tejbeer 3748
 
31697 amit.gupta 3749
        if (loanStatement.getLoanId() == loan.getId()) {
30859 tejbeer 3750
 
31886 tejbeer 3751
            sdCreditService.addInterest(loanStatement.getCreatedAt().toLocalDate(), LocalDate.now(), loan, loanStatusAmount);
30859 tejbeer 3752
 
31697 amit.gupta 3753
        } else {
3754
            throw new ProfitMandiBusinessException("loanstament", loanStatement.getLoanId(), "Invalid LoanId");
3755
        }
3756
    }
31175 tejbeer 3757
 
31697 amit.gupta 3758
    public void loanSettlement() throws Exception {
3759
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30859 tejbeer 3760
 
31697 amit.gupta 3761
        if (!loans.isEmpty()) {
30859 tejbeer 3762
 
31697 amit.gupta 3763
            for (Loan loan : loans) {
31020 tejbeer 3764
 
31697 amit.gupta 3765
                UserWallet userWallet = userWalletRepository.selectByRetailerId(loan.getFofoId());
31886 tejbeer 3766
                SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(loan.getFofoId());
30859 tejbeer 3767
 
31697 amit.gupta 3768
                if (userWallet.getAmount() >= 100) {
3769
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
31175 tejbeer 3770
 
31697 amit.gupta 3771
                    LOGGER.info("loanStatements {}", loanStatements);
30859 tejbeer 3772
 
31886 tejbeer 3773
                    Map<LoanReferenceType, Double> loanStatusAmount = loanStatements.stream().collect(groupingBy(x -> x.getLoanReferenceType(), Collectors.summingDouble(x -> FormattingUtils.serialize(x.getAmount()))));
30859 tejbeer 3774
 
31697 amit.gupta 3775
                    LOGGER.info("loanStatusAmount {}", loanStatusAmount);
3776
                    Double interestAmount = loanStatusAmount.get(LoanReferenceType.INTEREST);
30859 tejbeer 3777
 
31697 amit.gupta 3778
                    if (interestAmount == null) {
3779
                        interestAmount = (double) 0;
3780
                    }
30859 tejbeer 3781
 
31697 amit.gupta 3782
                    double principalAmount = loanStatusAmount.get(LoanReferenceType.PRINCIPAL);
3783
                    double paidAmount = 0;
3784
                    if (userWallet.getAmount() > Math.abs(interestAmount)) {
30859 tejbeer 3785
 
31697 amit.gupta 3786
                        LOGGER.info("interestAmount b {}", interestAmount);
30859 tejbeer 3787
 
31697 amit.gupta 3788
                        if (interestAmount < 0) {
3789
                            LOGGER.info("interestAmount a {}", interestAmount);
30859 tejbeer 3790
 
31886 tejbeer 3791
                            settledLoanStatement(LoanReferenceType.INTEREST, BigDecimal.valueOf(interestAmount), loan.getFofoId(), loan.getId(), "Amount adjusted against loan", LocalDateTime.now());
31697 amit.gupta 3792
                            loan.setInterestPaid(loan.getInterestPaid().add(BigDecimal.valueOf(interestAmount).abs()));
30859 tejbeer 3793
 
31697 amit.gupta 3794
                            paidAmount += Math.abs(interestAmount);
3795
                        }
31020 tejbeer 3796
 
31697 amit.gupta 3797
                        double userWalletAmount = userWallet.getAmount() - Math.abs(interestAmount);
31110 tejbeer 3798
 
31697 amit.gupta 3799
                        if (userWalletAmount > Math.abs(principalAmount) && principalAmount < 0) {
31110 tejbeer 3800
 
31886 tejbeer 3801
                            settledLoanStatement(LoanReferenceType.PRINCIPAL, BigDecimal.valueOf(principalAmount), loan.getFofoId(), loan.getId(), "Amount adjusted against loan", LocalDateTime.now());
31697 amit.gupta 3802
                            double amount = userWalletAmount - Math.abs(principalAmount);
31110 tejbeer 3803
 
31697 amit.gupta 3804
                            paidAmount += Math.abs(principalAmount);
30859 tejbeer 3805
 
32145 tejbeer 3806
                            // userWallet.setAmount((int) amount);
30859 tejbeer 3807
 
31886 tejbeer 3808
                            BigDecimal utilizationAmount = sdCreditRequirement.getUtilizedAmount().subtract(BigDecimal.valueOf(principalAmount).abs());
30859 tejbeer 3809
 
31697 amit.gupta 3810
                            sdCreditRequirement.setUtilizedAmount(utilizationAmount);
30859 tejbeer 3811
 
31886 tejbeer 3812
                            CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(loan.getFofoId(), Gateway.SDDIRECT);
31020 tejbeer 3813
 
31697 amit.gupta 3814
                            creditAccount.setAvailableAmount(sdCreditRequirement.getAvailableLimit().floatValue());
3815
                            creditAccount.setUpdatedOn(LocalDateTime.now());
31020 tejbeer 3816
 
31697 amit.gupta 3817
                            loan.setPendingAmount(BigDecimal.ZERO);
32682 amit.gupta 3818
                            loan.setSettledOn(LocalDateTime.now());
31020 tejbeer 3819
 
31697 amit.gupta 3820
                        } else if (principalAmount < 0) {
31110 tejbeer 3821
 
31886 tejbeer 3822
                            settledLoanStatement(LoanReferenceType.PRINCIPAL, BigDecimal.valueOf(userWalletAmount), loan.getFofoId(), loan.getId(), "Amount adjusted against loan", LocalDateTime.now());
30859 tejbeer 3823
 
31697 amit.gupta 3824
                            paidAmount += Math.abs(userWalletAmount);
30859 tejbeer 3825
 
31886 tejbeer 3826
                            BigDecimal availableLimit = sdCreditRequirement.getAvailableLimit().add(BigDecimal.valueOf(userWalletAmount)).abs();
30859 tejbeer 3827
 
31886 tejbeer 3828
                            BigDecimal utilizationAmount = sdCreditRequirement.getUtilizedAmount().subtract(BigDecimal.valueOf(userWalletAmount)).abs();
30859 tejbeer 3829
 
31697 amit.gupta 3830
                            sdCreditRequirement.setUtilizedAmount(utilizationAmount);
30859 tejbeer 3831
 
31886 tejbeer 3832
                            CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(loan.getFofoId(), Gateway.SDDIRECT);
30859 tejbeer 3833
 
31697 amit.gupta 3834
                            creditAccount.setAvailableAmount(sdCreditRequirement.getAvailableLimit().floatValue());
3835
                            creditAccount.setUpdatedOn(LocalDateTime.now());
32117 tejbeer 3836
                            //userWallet.setAmount(0);
30859 tejbeer 3837
 
31697 amit.gupta 3838
                            loan.setPendingAmount(
3839
                                    loan.getPendingAmount().subtract(BigDecimal.valueOf(userWalletAmount)));
30859 tejbeer 3840
 
31697 amit.gupta 3841
                        }
30859 tejbeer 3842
 
32117 tejbeer 3843
                        walletService.consumeAmountFromWallet(userWallet.getUserId(), loan.getId(), WalletReferenceType.LOAN_REPAYMENT, "Amount adjusted against loan", (float) Math.abs(paidAmount), LocalDateTime.now());
30859 tejbeer 3844
 
32145 tejbeer 3845
                        // createUserWalletHistory(userWallet.getId(), userWallet.getUserId(), WalletReferenceType.LOAN_REPAYMENT, loan.getId(), Math.abs(paidAmount));
32117 tejbeer 3846
 
31697 amit.gupta 3847
                    } else {
30999 tejbeer 3848
 
31886 tejbeer 3849
                        settledLoanStatement(LoanReferenceType.INTEREST, BigDecimal.valueOf(userWallet.getAmount()), loan.getFofoId(), loan.getId(), "Amount adjusted against loan", LocalDateTime.now());
31020 tejbeer 3850
 
31697 amit.gupta 3851
                        paidAmount += Math.abs(userWallet.getAmount());
31020 tejbeer 3852
 
31697 amit.gupta 3853
                        loan.setInterestPaid(
3854
                                loan.getInterestPaid().add(BigDecimal.valueOf(userWallet.getAmount()).abs()));
31020 tejbeer 3855
 
32117 tejbeer 3856
                        //  createUserWalletHistory(userWallet.getId(), userWallet.getUserId(), WalletReferenceType.LOAN_REPAYMENT, loan.getId(), Math.abs(paidAmount));
3857
 
3858
                        walletService.consumeAmountFromWallet(userWallet.getUserId(), loan.getId(), WalletReferenceType.LOAN_REPAYMENT, "Amount adjusted against loan", (float) Math.abs(paidAmount), LocalDateTime.now());
3859
 
3860
 
3861
                        // userWallet.setAmount(0);
31697 amit.gupta 3862
                    }
31020 tejbeer 3863
 
3864
 
32439 tejbeer 3865
                    List<SanctionRequest> sanctionRequests = sanctionRequestRepository.selectHoldSanctionByFofoId(loan.getFofoId());
31020 tejbeer 3866
 
32439 tejbeer 3867
                    double settledAmount = paidAmount;
3868
                    for (SanctionRequest sanctionRequest : sanctionRequests) {
31020 tejbeer 3869
 
32439 tejbeer 3870
                        List<Order> orders = orderRepository.selectAllByTransactionId(sanctionRequest.getTransactionId());
31020 tejbeer 3871
 
3872
 
32439 tejbeer 3873
                        if (settledAmount >= sanctionRequest.getPendingAmount().doubleValue()) {
3874
                            settledAmount = settledAmount - sanctionRequest.getPendingAmount().doubleValue();
31020 tejbeer 3875
 
32439 tejbeer 3876
                            sanctionRequest.setPendingAmount(BigDecimal.valueOf(0));
3877
                            this.sendUnholdEmail(orders);
3878
                        } else {
31020 tejbeer 3879
 
32439 tejbeer 3880
                            settledAmount = sanctionRequest.getPendingAmount().doubleValue() - settledAmount;
31020 tejbeer 3881
 
32439 tejbeer 3882
                            sanctionRequest.setPendingAmount(BigDecimal.valueOf(settledAmount));
31020 tejbeer 3883
 
32439 tejbeer 3884
                            break;
31020 tejbeer 3885
 
32439 tejbeer 3886
                        }
31020 tejbeer 3887
 
32439 tejbeer 3888
                    }
3889
                }
31020 tejbeer 3890
 
32439 tejbeer 3891
            }
31020 tejbeer 3892
 
3893
 
32439 tejbeer 3894
        }
31020 tejbeer 3895
 
32439 tejbeer 3896
    }
31020 tejbeer 3897
 
3898
 
32439 tejbeer 3899
    private void sendUnholdEmail(List<Order> orders) throws Exception {
30859 tejbeer 3900
 
3901
 
32439 tejbeer 3902
        orders.forEach(x -> x.setShipmentHold(false));
3903
        double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));
30859 tejbeer 3904
 
32439 tejbeer 3905
        List<String> authUserEmail = csService.getAuthUserIdByPartnerId(orders.get(0).getRetailerId()).stream().map(x -> x.getEmailId()).collect(Collectors.toList());
3906
        authUserEmail.add("vinay.p@smartdukaan.com");
3907
        authUserEmail.add("shivam.gupta@smartdukaan.com");
30859 tejbeer 3908
 
32439 tejbeer 3909
        String[] emailTo = authUserEmail.toArray(new String[authUserEmail.size()]);
30859 tejbeer 3910
 
32439 tejbeer 3911
        String[] ccTo = {"tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com"};
30859 tejbeer 3912
 
32439 tejbeer 3913
        String subject = "Dispatched " + (orders.get(0).getRetailerName());
3914
        String message = String.format("Dear Team, \n" + "kindly note the material for the " + orders.get(0).getRetailerName() + "of Rs." + totalAmount + "is dispatched.");
3915
        Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
30859 tejbeer 3916
 
32439 tejbeer 3917
 
31697 amit.gupta 3918
    }
30859 tejbeer 3919
 
32482 amit.gupta 3920
    private void settledLoanStatement(LoanReferenceType loanReferneceType, BigDecimal amount, int fofoId,
3921
                                      int loanId, String description, LocalDateTime now) {
30859 tejbeer 3922
 
31886 tejbeer 3923
        sdCreditService.createLoanStatement(loanReferneceType, amount.abs(), fofoId, loanId, description, LocalDateTime.now());
30859 tejbeer 3924
 
31697 amit.gupta 3925
    }
30859 tejbeer 3926
 
32482 amit.gupta 3927
    private void createUserWalletHistory(int walletId, int userId, WalletReferenceType referenceType, int loanId,
3928
                                         double interestAmount) {
31697 amit.gupta 3929
        UserWalletHistory uwh = new UserWalletHistory();
3930
        uwh.setWalletId(walletId);
3931
        uwh.setFofoId(userId);
3932
        uwh.setBusinessTimestamp(LocalDateTime.now());
3933
        uwh.setReferenceType(referenceType);
3934
        uwh.setReference(loanId);
3935
        uwh.setTimestamp(LocalDateTime.now());
3936
        uwh.setAmount((int) -(interestAmount));
3937
        uwh.setDescription("Amount adjusted against loan");
3938
        userWalletHistoryRepository.persist(uwh);
30859 tejbeer 3939
 
31697 amit.gupta 3940
    }
30859 tejbeer 3941
 
32307 amit.gupta 3942
    public void dailyLoanAlert() throws Exception {
31697 amit.gupta 3943
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30859 tejbeer 3944
 
31697 amit.gupta 3945
        Map<Integer, Double> partnerLoanAmount = new HashMap<>();
30859 tejbeer 3946
 
31697 amit.gupta 3947
        if (!loans.isEmpty()) {
30859 tejbeer 3948
 
31697 amit.gupta 3949
            for (Loan loan : loans) {
30859 tejbeer 3950
 
31697 amit.gupta 3951
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30859 tejbeer 3952
 
31886 tejbeer 3953
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31697 amit.gupta 3954
                if (partnerLoanAmount.get(loan.getFofoId()) != null) {
3955
                    amount += partnerLoanAmount.get(loan.getFofoId());
3956
                    partnerLoanAmount.put(loan.getFofoId(), amount);
3957
                } else {
3958
                    partnerLoanAmount.put(loan.getFofoId(), amount);
3959
                }
30965 tejbeer 3960
 
31697 amit.gupta 3961
            }
30965 tejbeer 3962
 
31697 amit.gupta 3963
        }
30859 tejbeer 3964
 
31697 amit.gupta 3965
        if (!partnerLoanAmount.isEmpty()) {
30965 tejbeer 3966
 
31697 amit.gupta 3967
            for (Entry<Integer, Double> partnerLoanAmountEnrty : partnerLoanAmount.entrySet()) {
30859 tejbeer 3968
 
31697 amit.gupta 3969
                int fofoId = partnerLoanAmountEnrty.getKey();
30859 tejbeer 3970
 
31697 amit.gupta 3971
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
30859 tejbeer 3972
 
31697 amit.gupta 3973
                Address address = addressRepository.selectById(user.getAddressId());
30896 amit.gupta 3974
 
31697 amit.gupta 3975
                String title = "Alert Credit Outstanding!";
3976
                String url = "http://app.smartdukaan.com/pages/home/credit";
31886 tejbeer 3977
                String message = "Your total pending Loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(partnerLoanAmountEnrty.getValue())) + ".";
31697 amit.gupta 3978
                notificationService.sendNotification(fofoId, title, MessageType.notification, title, message, url);
30913 tejbeer 3979
 
31697 amit.gupta 3980
                notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30913 tejbeer 3981
 
31697 amit.gupta 3982
            }
30917 tejbeer 3983
 
31697 amit.gupta 3984
        }
30917 tejbeer 3985
 
31697 amit.gupta 3986
    }
30920 tejbeer 3987
 
31697 amit.gupta 3988
    public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
3989
        schemeService.processActivatedImeisForSchemes();
3990
    }
30920 tejbeer 3991
 
31697 amit.gupta 3992
    public void updatePartnerLimit() throws ProfitMandiBusinessException {
3993
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
30913 tejbeer 3994
 
31886 tejbeer 3995
        Map<Integer, SDCreditRequirement> sdCreditRequirementMap = sdCreditRequirementRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3996
        Map<Integer, CurrentPartnerDailyInvestment> currentPartnerDailyInvestmentMap = currentPartnerDailyInvestmentRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31697 amit.gupta 3997
        double limitValue = 100000;
3998
        for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
3999
            int fofoId = customRetailerEntry.getKey();
4000
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementMap.get(customRetailerEntry.getKey());
4001
            LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
4002
            CurrentPartnerDailyInvestment currentPartnerDailyInvestment = currentPartnerDailyInvestmentMap.get(fofoId);
4003
            BigDecimal suggestedAmount = BigDecimal.ZERO;
4004
            if (currentPartnerDailyInvestment != null) {
4005
                suggestedAmount = BigDecimal.valueOf(currentPartnerDailyInvestment.getTotalInvestment() * 0.1);
4006
            }
30929 tejbeer 4007
 
31697 amit.gupta 4008
            if (suggestedAmount.doubleValue() > limitValue) {
30929 tejbeer 4009
 
31697 amit.gupta 4010
                suggestedAmount = BigDecimal.valueOf(limitValue);
30929 tejbeer 4011
 
31697 amit.gupta 4012
            }
30913 tejbeer 4013
 
31697 amit.gupta 4014
            if (suggestedAmount.doubleValue() < 0) {
4015
                suggestedAmount = BigDecimal.ZERO;
4016
            }
30913 tejbeer 4017
 
31697 amit.gupta 4018
            LOGGER.info("suggestedAmount {} ", suggestedAmount);
30913 tejbeer 4019
 
31697 amit.gupta 4020
            if (sdCreditRequirement == null) {
4021
                sdCreditRequirement = new SDCreditRequirement();
4022
                sdCreditRequirement.setFofoId(fofoId);
4023
                sdCreditRequirement.setCreditDays(15);
4024
                sdCreditRequirement.setInterestRate(BigDecimal.valueOf(0.05));
4025
                sdCreditRequirement.setSuggestedLimit(suggestedAmount);
4026
                sdCreditRequirement.setRisk(CreditRisk.HIGH_RISK);
4027
                sdCreditRequirement.setLimit(suggestedAmount);
4028
                sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
4029
                sdCreditRequirement.setCreateTimestamp(LocalDateTime.now());
4030
                sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
4031
                sdCreditRequirementRepository.persist(sdCreditRequirement);
4032
            }
30913 tejbeer 4033
 
31697 amit.gupta 4034
            CreditRisk creditRisk = sdCreditService.getCurrentRisk(sdCreditRequirement, firstBillingDate);
30913 tejbeer 4035
 
31697 amit.gupta 4036
            sdCreditRequirement.setRisk(creditRisk);
30913 tejbeer 4037
 
31697 amit.gupta 4038
            sdCreditRequirement.setSuggestedLimit(suggestedAmount);
4039
            sdCreditRequirement.setLimit(suggestedAmount);
4040
            BigDecimal utilizedLimit = new BigDecimal(sdCreditService.getUtilizationAmount(fofoId));
30934 tejbeer 4041
 
31697 amit.gupta 4042
            BigDecimal availableLimit = sdCreditRequirement.getLimit().subtract(utilizedLimit);
30934 tejbeer 4043
 
31697 amit.gupta 4044
            LOGGER.info("utilizedLimit {} ", utilizedLimit);
30913 tejbeer 4045
 
31697 amit.gupta 4046
            LOGGER.info("availableLimit {} ", availableLimit);
30913 tejbeer 4047
 
31697 amit.gupta 4048
            sdCreditRequirement.setUtilizedAmount(utilizedLimit);
30929 tejbeer 4049
 
31697 amit.gupta 4050
            sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
30929 tejbeer 4051
 
31886 tejbeer 4052
            CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(sdCreditRequirement.getFofoId(), Gateway.SDDIRECT);
31697 amit.gupta 4053
            if (creditAccount != null) {
30929 tejbeer 4054
 
31697 amit.gupta 4055
                creditAccount.setInterestRate(sdCreditRequirement.getInterestRate().floatValue());
4056
                creditAccount.setSanctionedAmount(sdCreditRequirement.getLimit().floatValue());
4057
                creditAccount.setAvailableAmount(availableLimit.floatValue());
4058
                creditAccount.setFreeDays(sdCreditRequirement.getFreeDays());
4059
                creditAccount.setUpdatedOn(LocalDateTime.now());
4060
            }
30929 tejbeer 4061
 
31697 amit.gupta 4062
        }
31177 tejbeer 4063
 
31697 amit.gupta 4064
    }
30929 tejbeer 4065
 
31697 amit.gupta 4066
    public void notifyDefaultLoans() throws ProfitMandiBusinessException, MessagingException, IOException {
30929 tejbeer 4067
 
31697 amit.gupta 4068
        sdCreditService.updateRisk();
4069
        List<Loan> defaultLoans = sdCreditService.getDefaultLoan();
4070
        if (!defaultLoans.isEmpty()) {
4071
            this.sendDefaultLoanAlert(defaultLoans);
4072
        }
30929 tejbeer 4073
 
31697 amit.gupta 4074
    }
30929 tejbeer 4075
 
32482 amit.gupta 4076
    public void sendDefaultLoanAlert(List<Loan> defaultLoans) throws
4077
            ProfitMandiBusinessException, MessagingException, IOException {
31697 amit.gupta 4078
        String subject = "Default Partners";
30931 tejbeer 4079
 
31886 tejbeer 4080
        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 4081
 
31886 tejbeer 4082
        for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
31697 amit.gupta 4083
            List<Loan> filteredRows = new ArrayList<>();
4084
            for (Loan loan : defaultLoans) {
30929 tejbeer 4085
 
31697 amit.gupta 4086
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30929 tejbeer 4087
 
31697 amit.gupta 4088
                    filteredRows.add(loan);
4089
                }
4090
            }
4091
            if (!filteredRows.isEmpty()) {
4092
                String messageText = this.getMessageForDueDateExtend(filteredRows);
4093
                String[] email = new String[]{storeGuyEntry.getKey()};
30982 tejbeer 4094
 
32350 amit.gupta 4095
                this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, subject);
30982 tejbeer 4096
 
31697 amit.gupta 4097
            }
30936 tejbeer 4098
 
31697 amit.gupta 4099
        }
30982 tejbeer 4100
 
31697 amit.gupta 4101
        for (Loan defaultLoan : defaultLoans) {
4102
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
30929 tejbeer 4103
 
31886 tejbeer 4104
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 4105
 
31697 amit.gupta 4106
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
30936 tejbeer 4107
 
31697 amit.gupta 4108
            Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 4109
 
31697 amit.gupta 4110
            String title = "Loan Amount Overdue!";
4111
            String url = "http://app.smartdukaan.com/pages/home/credit";
31886 tejbeer 4112
            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!!";
4113
            notificationService.sendNotification(defaultLoan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 4114
 
31697 amit.gupta 4115
            // notificationService.sendWhatsappMessage(message, title,
4116
            // address.getPhoneNumber());
30929 tejbeer 4117
 
31697 amit.gupta 4118
        }
4119
    }
30929 tejbeer 4120
 
31697 amit.gupta 4121
    private String getMessageForDueDateExtend(List<Loan> loans) throws ProfitMandiBusinessException {
4122
        StringBuilder sb = new StringBuilder();
4123
        sb.append(
31886 tejbeer 4124
                "<html><body><p>Alert</p><p>Default Partners :-</p>" + "<br/><p>EveryDay Rs.100 charged as Penalty</p>" + "<br/><table style='border:1px solid black ;padding: 5px';>");
4125
        sb.append("<tbody>\n" + "	    				<tr>\n" + "	    					<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>due date</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Days</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n"
30929 tejbeer 4126
 
31697 amit.gupta 4127
                + "	    				</tr>");
4128
        for (Loan entry : loans) {
30929 tejbeer 4129
 
31697 amit.gupta 4130
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
30929 tejbeer 4131
 
31886 tejbeer 4132
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 4133
 
31697 amit.gupta 4134
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
30929 tejbeer 4135
 
31697 amit.gupta 4136
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
30929 tejbeer 4137
 
31697 amit.gupta 4138
            sb.append("<tr>");
31886 tejbeer 4139
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
31397 tejbeer 4140
 
31886 tejbeer 4141
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 4142
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 4143
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
31397 tejbeer 4144
 
31697 amit.gupta 4145
            sb.append("</tr>");
31397 tejbeer 4146
 
31697 amit.gupta 4147
        }
31397 tejbeer 4148
 
31697 amit.gupta 4149
        sb.append("</tbody></table></body></html>");
31397 tejbeer 4150
 
31697 amit.gupta 4151
        return sb.toString();
4152
    }
31397 tejbeer 4153
 
31697 amit.gupta 4154
    private String getMessageForDueDateCross(List<Loan> loans) throws ProfitMandiBusinessException {
4155
        StringBuilder sb = new StringBuilder();
31886 tejbeer 4156
        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/><table style='border:1px solid black ;padding: 5px';>");
4157
        sb.append("<tbody>\n" + "	    				<tr>\n" + "	    					<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>due date</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Days</th>\n" + "	    					<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n"
31397 tejbeer 4158
 
31697 amit.gupta 4159
                + "	    				</tr>");
4160
        for (Loan entry : loans) {
31397 tejbeer 4161
 
31697 amit.gupta 4162
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
31397 tejbeer 4163
 
31886 tejbeer 4164
            double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
31397 tejbeer 4165
 
31697 amit.gupta 4166
            long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
31397 tejbeer 4167
 
31697 amit.gupta 4168
            CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
31397 tejbeer 4169
 
31697 amit.gupta 4170
            sb.append("<tr>");
31886 tejbeer 4171
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")" + "</td>");
30936 tejbeer 4172
 
31886 tejbeer 4173
            sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
31697 amit.gupta 4174
            sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
31886 tejbeer 4175
            sb.append("<td style='border:1px solid black;padding: 5px'>" + new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
30936 tejbeer 4176
 
31697 amit.gupta 4177
            sb.append("</tr>");
31397 tejbeer 4178
 
31697 amit.gupta 4179
        }
31397 tejbeer 4180
 
31697 amit.gupta 4181
        sb.append("</tbody></table></body></html>");
31397 tejbeer 4182
 
31697 amit.gupta 4183
        return sb.toString();
4184
    }
31397 tejbeer 4185
 
32307 amit.gupta 4186
    public void notifyLoanDueDateCross() throws Exception {
31397 tejbeer 4187
 
31697 amit.gupta 4188
        List<Loan> dueDateCrossLoans = sdCreditService.getDueDateCrossLoan();
4189
        if (!dueDateCrossLoans.isEmpty()) {
4190
            this.sendDueDateCrossLoanAlert(dueDateCrossLoans);
4191
        }
31397 tejbeer 4192
 
31697 amit.gupta 4193
    }
31397 tejbeer 4194
 
32307 amit.gupta 4195
    private void sendDueDateCrossLoanAlert(List<Loan> dueDateCrossLoans) throws Exception {
31886 tejbeer 4196
        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 4197
 
31886 tejbeer 4198
        for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false).entrySet()) {
31697 amit.gupta 4199
            List<Loan> filteredRows = new ArrayList<>();
4200
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 4201
 
31697 amit.gupta 4202
                if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30982 tejbeer 4203
 
31697 amit.gupta 4204
                    filteredRows.add(loan);
4205
                }
4206
            }
4207
            if (!filteredRows.isEmpty()) {
4208
                String messageText = this.getMessageForDueDateCross(filteredRows);
4209
                String[] email = new String[]{storeGuyEntry.getKey()};
30982 tejbeer 4210
 
32350 amit.gupta 4211
                this.sendMailOfHtmlFormat(googleMailSender, email, messageText, null, "Due Date Cross");
30936 tejbeer 4212
 
31697 amit.gupta 4213
            }
30936 tejbeer 4214
 
31697 amit.gupta 4215
        }
4216
        if (!dueDateCrossLoans.isEmpty()) {
4217
            for (Loan loan : dueDateCrossLoans) {
30936 tejbeer 4218
 
31697 amit.gupta 4219
                long noOfdaysBetween = ChronoUnit.DAYS.between(loan.getDueDate().toLocalDate(), LocalDate.now());
30989 tejbeer 4220
 
31697 amit.gupta 4221
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30989 tejbeer 4222
 
31697 amit.gupta 4223
                Address address = addressRepository.selectById(user.getAddressId());
30982 tejbeer 4224
 
31697 amit.gupta 4225
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 4226
 
31697 amit.gupta 4227
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
30936 tejbeer 4228
 
31886 tejbeer 4229
                double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 4230
 
31697 amit.gupta 4231
                String url = "http://app.smartdukaan.com/pages/home/credit";
30936 tejbeer 4232
 
31697 amit.gupta 4233
                String title = "Alert!";
31886 tejbeer 4234
                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 4235
 
31886 tejbeer 4236
                notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
30936 tejbeer 4237
 
31697 amit.gupta 4238
                notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4239
 
31697 amit.gupta 4240
            }
4241
        }
30982 tejbeer 4242
 
31697 amit.gupta 4243
    }
30936 tejbeer 4244
 
32307 amit.gupta 4245
    public void alertForDueDate() throws Exception {
30936 tejbeer 4246
 
31697 amit.gupta 4247
        List<Loan> loans = loanRepository.selectAllActiveLoan();
30936 tejbeer 4248
 
31697 amit.gupta 4249
        if (!loans.isEmpty()) {
4250
            for (Loan loan : loans) {
30936 tejbeer 4251
 
31697 amit.gupta 4252
                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
30936 tejbeer 4253
 
31697 amit.gupta 4254
                Address address = addressRepository.selectById(user.getAddressId());
30936 tejbeer 4255
 
31697 amit.gupta 4256
                long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), loan.getDueDate().toLocalDate());
30936 tejbeer 4257
 
31697 amit.gupta 4258
                LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
30982 tejbeer 4259
 
31697 amit.gupta 4260
                if (noOfdaysBetween <= 4 && noOfdaysBetween >= 0) {
4261
                    List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
31886 tejbeer 4262
                    double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
30936 tejbeer 4263
 
31697 amit.gupta 4264
                    String title = "Alert!";
4265
                    String url = "http://app.smartdukaan.com/pages/home/credit";
4266
                    String message = null;
4267
                    if (noOfdaysBetween == 0) {
30936 tejbeer 4268
 
31886 tejbeer 4269
                        message = "Your total pending Loan amount is Rs." + FormattingUtils.formatDecimal(Math.abs(amount)) + " is due for Today, Pay Now!!";
30982 tejbeer 4270
 
31697 amit.gupta 4271
                    } else {
30982 tejbeer 4272
 
31886 tejbeer 4273
                        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 4274
 
31697 amit.gupta 4275
                    }
31886 tejbeer 4276
                    notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title, message, url);
31697 amit.gupta 4277
                    notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4278
 
31697 amit.gupta 4279
                }
4280
            }
4281
        }
30984 tejbeer 4282
 
31697 amit.gupta 4283
    }
30982 tejbeer 4284
 
32307 amit.gupta 4285
    public void userMobileNumberOptIn() throws Exception {
30982 tejbeer 4286
 
31697 amit.gupta 4287
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
30982 tejbeer 4288
 
31886 tejbeer 4289
        List<com.spice.profitmandi.dao.entity.user.User> users = userUserRepository.selectByIds(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
30982 tejbeer 4290
 
31886 tejbeer 4291
        List<Address> addresses = addressRepository.selectByIds(users.stream().map(x -> x.getAddressId()).collect(Collectors.toList()));
30982 tejbeer 4292
 
31697 amit.gupta 4293
        LOGGER.info("addresses" + addresses);
30984 tejbeer 4294
 
31697 amit.gupta 4295
        for (Address address : addresses) {
32307 amit.gupta 4296
            notificationService.optIn(address.getPhoneNumber());
30982 tejbeer 4297
 
31697 amit.gupta 4298
        }
30982 tejbeer 4299
 
31697 amit.gupta 4300
    }
30982 tejbeer 4301
 
31697 amit.gupta 4302
    public void authUserMobileNumberOptIn() throws HttpHostConnectException, ProfitMandiBusinessException {
31206 tejbeer 4303
 
31697 amit.gupta 4304
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
4305
        LOGGER.info("authUsers" + authUsers);
31206 tejbeer 4306
 
31697 amit.gupta 4307
        for (AuthUser authUser : authUsers) {
4308
            Map<String, String> requestheaders = new HashMap<>();
4309
            requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
4310
            Map<String, String> requestParams = new HashMap<>();
4311
            requestParams.put("userid", String.valueOf(2000215976));
4312
            requestParams.put("password", "MFRd!BBL");
4313
            requestParams.put("phone_number", authUser.getMobileNumber());
4314
            requestParams.put("auth_scheme", "plain");
4315
            requestParams.put("v", "1.1");
4316
            requestParams.put("format", "json");
31206 tejbeer 4317
 
31697 amit.gupta 4318
            requestParams.put("method", "OPT_IN");
31206 tejbeer 4319
 
31697 amit.gupta 4320
            requestParams.put("channel", "WHATSAPP");
31886 tejbeer 4321
            String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
31697 amit.gupta 4322
            LOGGER.info("response" + response);
4323
        }
31206 tejbeer 4324
 
31697 amit.gupta 4325
    }
31206 tejbeer 4326
 
31697 amit.gupta 4327
    @Autowired
4328
    private HygieneDataRepository hygieneDataRepository;
31209 tejbeer 4329
 
31697 amit.gupta 4330
    public void hygineAlertForPartner() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 4331
 
31697 amit.gupta 4332
        List<String> remarks = new ArrayList<>();
4333
        remarks.add("Out of Service");
4334
        remarks.add("Duplicate number");
4335
        remarks.add("Partner number");
31886 tejbeer 4336
        List<HygieneData> hygieneData = hygieneDataRepository.selectAllByDisposedDateAndRemark(LocalDate.now(), remarks);
31206 tejbeer 4337
 
31697 amit.gupta 4338
        if (!hygieneData.isEmpty()) {
31206 tejbeer 4339
 
31886 tejbeer 4340
            Map<Integer, List<HygieneData>> partnerHygieneDataMap = hygieneData.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 4341
 
31697 amit.gupta 4342
            for (Entry<Integer, List<HygieneData>> partnerHygieneDataMapEntry : partnerHygieneDataMap.entrySet()) {
31206 tejbeer 4343
 
31697 amit.gupta 4344
                CustomRetailer customRetailer = retailerService.getFofoRetailer(partnerHygieneDataMapEntry.getKey());
31206 tejbeer 4345
 
31697 amit.gupta 4346
                StringBuilder sb = new StringBuilder();
31886 tejbeer 4347
                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 4348
 
31886 tejbeer 4349
                        + " </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 4350
 
31697 amit.gupta 4351
                        + "<br/><table style='border:1px solid black ;padding: 5px';>");
4352
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4353
                sb.append("<th style='border:1px solid black;padding: 5px'>Invoice Number</th>\n");
4354
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Name</th>\n");
4355
                sb.append("<th style='border:1px solid black;padding: 5px'>Customer Number</th>\n");
4356
                sb.append("</tr>\n");
31206 tejbeer 4357
 
31697 amit.gupta 4358
                List<HygieneData> hygienes = partnerHygieneDataMapEntry.getValue();
31206 tejbeer 4359
 
31697 amit.gupta 4360
                List<Integer> orderIds = hygienes.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
31206 tejbeer 4361
 
31697 amit.gupta 4362
                List<FofoOrder> fofoOrders = fofoOrderRepository.selectAllByOrderIds(orderIds);
31206 tejbeer 4363
 
31697 amit.gupta 4364
                for (FofoOrder fofoOrder : fofoOrders) {
4365
                    Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
4366
                    sb.append("<tr>");
31886 tejbeer 4367
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + fofoOrder.getInvoiceNumber() + "</td>\n");
4368
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getFirstName() + "" + customer.getLastName() + "</td>\n");
4369
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customer.getMobileNumber() + "</td>\n");
31206 tejbeer 4370
 
31697 amit.gupta 4371
                    sb.append("</tr>\n");
4372
                }
31206 tejbeer 4373
 
31697 amit.gupta 4374
                sb.append("</tbody></table></body></html>");
4375
                String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 4376
 
32350 amit.gupta 4377
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31206 tejbeer 4378
 
31697 amit.gupta 4379
            }
31206 tejbeer 4380
 
31697 amit.gupta 4381
        }
31206 tejbeer 4382
 
31697 amit.gupta 4383
    }
31206 tejbeer 4384
 
31697 amit.gupta 4385
    public void hygineAlertForInternalTeam() throws ProfitMandiBusinessException, MessagingException, IOException {
31206 tejbeer 4386
 
31697 amit.gupta 4387
        List<String> remarks = new ArrayList<>();
4388
        remarks.add("Out of Service");
4389
        remarks.add("Duplicate number");
4390
        remarks.add("Partner number");
31886 tejbeer 4391
        List<HygieneData> hygieneDataLastThreeMonth = hygieneDataRepository.selectDisposedDateAndRemarks(
4392
                LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay(), LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX), remarks);
31206 tejbeer 4393
 
31886 tejbeer 4394
        List<HygieneData> hygieneDataRecentMonth = hygieneDataRepository.selectDisposedDateAndRemarks(LocalDate.now().withDayOfMonth(1), remarks);
31697 amit.gupta 4395
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
4396
        Map<Integer, List<HygieneData>> partnerHygieneLastThreeMonthMap = null;
31206 tejbeer 4397
 
31697 amit.gupta 4398
        Map<Integer, List<HygieneData>> partnerHygieneDataRecentMonth = null;
31206 tejbeer 4399
 
31697 amit.gupta 4400
        if (!hygieneDataLastThreeMonth.isEmpty()) {
31886 tejbeer 4401
            partnerHygieneLastThreeMonthMap = hygieneDataLastThreeMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31206 tejbeer 4402
 
31697 amit.gupta 4403
        }
31206 tejbeer 4404
 
31697 amit.gupta 4405
        if (!hygieneDataRecentMonth.isEmpty()) {
31886 tejbeer 4406
            partnerHygieneDataRecentMonth = hygieneDataRecentMonth.stream().collect(groupingBy(x -> x.getFofoId()));
31697 amit.gupta 4407
        }
31206 tejbeer 4408
 
31697 amit.gupta 4409
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31206 tejbeer 4410
 
31697 amit.gupta 4411
            String email = storeGuyEntry.getKey();
31206 tejbeer 4412
 
31697 amit.gupta 4413
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
31206 tejbeer 4414
 
31697 amit.gupta 4415
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData = new HashMap<>();
4416
            Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData = new HashMap<>();
4417
            for (Integer fofoId : fofoIds) {
31206 tejbeer 4418
 
31697 amit.gupta 4419
                partnerYearMonthData.put(fofoId, null);
4420
                partnerDateWiseData.put(fofoId, null);
4421
                if (!partnerHygieneLastThreeMonthMap.isEmpty()) {
4422
                    List<HygieneData> hygienes = partnerHygieneLastThreeMonthMap.get(fofoId);
31206 tejbeer 4423
 
31697 amit.gupta 4424
                    if (hygienes != null) {
31886 tejbeer 4425
                        Map<YearMonth, List<HygieneData>> yearMonthData = hygienes.stream().collect(groupingBy(x -> YearMonth.from(x.getDisposedTimestamp())));
31206 tejbeer 4426
 
31697 amit.gupta 4427
                        partnerYearMonthData.put(fofoId, yearMonthData);
31206 tejbeer 4428
 
31697 amit.gupta 4429
                    }
4430
                    List<HygieneData> dateWiseHygienes = partnerHygieneDataRecentMonth.get(fofoId);
31206 tejbeer 4431
 
31697 amit.gupta 4432
                    if (dateWiseHygienes != null) {
31206 tejbeer 4433
 
31886 tejbeer 4434
                        Map<LocalDate, List<HygieneData>> dateWiseData = hygienes.stream().collect(groupingBy(x -> (x.getDisposedTimestamp()).toLocalDate()));
31206 tejbeer 4435
 
31697 amit.gupta 4436
                        partnerDateWiseData.put(fofoId, dateWiseData);
31206 tejbeer 4437
 
31697 amit.gupta 4438
                    }
31206 tejbeer 4439
 
31697 amit.gupta 4440
                }
31206 tejbeer 4441
 
31697 amit.gupta 4442
            }
31206 tejbeer 4443
 
31697 amit.gupta 4444
            String subject = "Customer Info - Hygiene Alert";
31206 tejbeer 4445
 
31697 amit.gupta 4446
            LOGGER.info("hygieneData {}", partnerDateWiseData.values());
31206 tejbeer 4447
 
31697 amit.gupta 4448
            boolean partnerDateWise = partnerDateWiseData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 4449
 
31697 amit.gupta 4450
            boolean partnerYearMonth = partnerYearMonthData.values().stream().allMatch(Objects::isNull);
31206 tejbeer 4451
 
31697 amit.gupta 4452
            if (!partnerDateWise && !partnerYearMonth) {
4453
                String sb = this.getMessageHygieneAlertForPartner(partnerYearMonthData, partnerDateWiseData);
32350 amit.gupta 4454
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb, null, subject);
31697 amit.gupta 4455
            }
31206 tejbeer 4456
 
31697 amit.gupta 4457
        }
31206 tejbeer 4458
 
31697 amit.gupta 4459
    }
31206 tejbeer 4460
 
31697 amit.gupta 4461
    private String getMessageHygieneAlertForPartner(
32482 amit.gupta 4462
            Map<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthData, Map<Integer, Map<LocalDate, List<HygieneData>>> partnerDateWiseData) {
31206 tejbeer 4463
 
31697 amit.gupta 4464
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31206 tejbeer 4465
 
31697 amit.gupta 4466
        LocalDateTime startDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
4467
        LocalDateTime endDate = LocalDateTime.now();
31206 tejbeer 4468
 
31697 amit.gupta 4469
        LocalDateTime startYearMonth = LocalDate.now().withDayOfMonth(1).minusMonths(3).atStartOfDay();
31886 tejbeer 4470
        LocalDateTime endYearMonth = LocalDate.now().minusMonths(1).withDayOfMonth(LocalDate.now().minusMonths(1).lengthOfMonth()).atTime(LocalTime.MAX);
31206 tejbeer 4471
 
31697 amit.gupta 4472
        DateTimeFormatter dateYearMonthFormatter = DateTimeFormatter.ofPattern("MMM''uu");
31206 tejbeer 4473
 
31697 amit.gupta 4474
        List<YearMonth> yearMonthRange = new ArrayList<>();
4475
        yearMonthRange.add(YearMonth.from(startYearMonth));
31206 tejbeer 4476
 
31697 amit.gupta 4477
        yearMonthRange.add(YearMonth.from(startYearMonth.plusMonths(1)));
31206 tejbeer 4478
 
31697 amit.gupta 4479
        yearMonthRange.add(YearMonth.from(endYearMonth));
31206 tejbeer 4480
 
31697 amit.gupta 4481
        long noOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate.plusDays(1));
31206 tejbeer 4482
 
31886 tejbeer 4483
        List<LocalDate> dateRange = Stream.iterate(startDate.toLocalDate(), date -> date.plusDays(1)).limit(noOfDaysBetween).collect(Collectors.toList());
31206 tejbeer 4484
 
31697 amit.gupta 4485
        StringBuilder sb = new StringBuilder();
31886 tejbeer 4486
        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 4487
 
31697 amit.gupta 4488
                + "<table style='border:1px solid black ;padding: 5px';>");
4489
        sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4490
        sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31206 tejbeer 4491
 
31697 amit.gupta 4492
        for (YearMonth yearMonth : yearMonthRange) {
31886 tejbeer 4493
            sb.append("<th style='border:1px solid black;padding: 5px'>" + yearMonth.format(dateYearMonthFormatter) + "</th>\n");
31697 amit.gupta 4494
        }
31206 tejbeer 4495
 
31697 amit.gupta 4496
        for (LocalDate localDate : dateRange) {
4497
            sb.append("<th style='border:1px solid black;padding: 5px'>" + localDate + "</th>\n");
4498
        }
31206 tejbeer 4499
 
31697 amit.gupta 4500
        sb.append("</tr>\n");
31206 tejbeer 4501
 
31886 tejbeer 4502
        for (Entry<Integer, Map<YearMonth, List<HygieneData>>> partnerYearMonthEntry : partnerYearMonthData.entrySet()) {
31206 tejbeer 4503
 
31697 amit.gupta 4504
            int fofoId = partnerYearMonthEntry.getKey();
31206 tejbeer 4505
 
31697 amit.gupta 4506
            Map<YearMonth, List<HygieneData>> yearMonthData = partnerYearMonthEntry.getValue();
31206 tejbeer 4507
 
31697 amit.gupta 4508
            Map<LocalDate, List<HygieneData>> dateWiseData = partnerDateWiseData.get(fofoId);
31206 tejbeer 4509
 
31697 amit.gupta 4510
            if (yearMonthData == null && dateWiseData == null) {
4511
                continue;
4512
            }
31206 tejbeer 4513
 
31697 amit.gupta 4514
            sb.append("<tr>");
31886 tejbeer 4515
            sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31697 amit.gupta 4516
            for (YearMonth yearMonth : yearMonthRange) {
31206 tejbeer 4517
 
31697 amit.gupta 4518
                if (yearMonthData == null) {
4519
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4520
 
31697 amit.gupta 4521
                } else {
4522
                    List<HygieneData> hygieneList = yearMonthData.get(yearMonth);
31206 tejbeer 4523
 
31697 amit.gupta 4524
                    if (hygieneList != null) {
4525
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31206 tejbeer 4526
 
31697 amit.gupta 4527
                    } else {
4528
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4529
 
31697 amit.gupta 4530
                    }
4531
                }
4532
            }
31206 tejbeer 4533
 
31697 amit.gupta 4534
            for (LocalDate localDate : dateRange) {
31206 tejbeer 4535
 
31697 amit.gupta 4536
                if (dateWiseData == null) {
4537
                    sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31206 tejbeer 4538
 
31697 amit.gupta 4539
                } else {
4540
                    List<HygieneData> hygieneList = dateWiseData.get(localDate);
31206 tejbeer 4541
 
31697 amit.gupta 4542
                    if (hygieneList != null) {
4543
                        sb.append("<td style='border:1px solid black;padding: 5px'>" + hygieneList.size() + "</td>\n");
31218 tejbeer 4544
 
31697 amit.gupta 4545
                    } else {
4546
                        sb.append("<td style='border:1px solid black;padding: 5px'>-</td>\n");
31218 tejbeer 4547
 
31697 amit.gupta 4548
                    }
4549
                }
4550
            }
4551
            sb.append("</tr>");
31218 tejbeer 4552
 
31697 amit.gupta 4553
        }
31218 tejbeer 4554
 
31697 amit.gupta 4555
        sb.append("</tbody></table></body></html>");
31218 tejbeer 4556
 
31697 amit.gupta 4557
        return sb.toString();
4558
    }
31218 tejbeer 4559
 
31697 amit.gupta 4560
    @Autowired
4561
    private MonthlyTargetRepository monthlyTargetRepository;
31218 tejbeer 4562
 
31697 amit.gupta 4563
    public void monthlyTargetForPartner() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 4564
 
31697 amit.gupta 4565
        LocalDateTime curDate = LocalDateTime.now();
4566
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 4567
 
31886 tejbeer 4568
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 4569
 
31886 tejbeer 4570
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
4571
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 4572
 
31697 amit.gupta 4573
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 4574
 
31697 amit.gupta 4575
        for (Entry<Integer, MonthlyTarget> partnerMonthlyTargetEntry : partnersMonthlyTarget.entrySet()) {
31249 tejbeer 4576
 
31697 amit.gupta 4577
            int fofoId = partnerMonthlyTargetEntry.getKey();
31249 tejbeer 4578
 
31697 amit.gupta 4579
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
31249 tejbeer 4580
 
31697 amit.gupta 4581
            Double purchaseTarget = partnerMonthlyTargetEntry.getValue().getPurchaseTarget();
31218 tejbeer 4582
 
31697 amit.gupta 4583
            Double saleTarget = partnerMonthlyTargetEntry.getValue().getSaleTarget();
31218 tejbeer 4584
 
31697 amit.gupta 4585
            if (purchaseTarget > 0) {
4586
                Double purchase = secondaryMtd.get(fofoId);
31249 tejbeer 4587
 
31697 amit.gupta 4588
                if (purchase == null) {
4589
                    purchase = 0.0;
4590
                }
31218 tejbeer 4591
 
31697 amit.gupta 4592
                Double balanceTarget = purchaseTarget - purchase;
31218 tejbeer 4593
 
31697 amit.gupta 4594
                if (balanceTarget <= 0) {
4595
                    balanceTarget = 0.0;
4596
                }
31651 tejbeer 4597
 
31697 amit.gupta 4598
                StringBuilder sb = new StringBuilder();
4599
                sb.append("<html><body><p>Dear Partner,\n");
31886 tejbeer 4600
                sb.append("<p>Pls note your agreed monthly target is Rs." + purchaseTarget + " and your achievement till date is Rs." + purchase + "</p>");
31697 amit.gupta 4601
                sb.append("<p>Pls note that your balance target is Rs." + balanceTarget + "</p>\n");
4602
                sb.append(
32350 amit.gupta 4603
                        "<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 4604
 
32350 amit.gupta 4605
                this.sendMailOfHtmlFormat(mailSender, new String[]{customRetailer.getEmail()}, sb.toString(), null, subject);
31697 amit.gupta 4606
            }
31218 tejbeer 4607
 
31697 amit.gupta 4608
        }
31218 tejbeer 4609
 
31697 amit.gupta 4610
    }
31218 tejbeer 4611
 
31697 amit.gupta 4612
    public void monthlyTargetForInternalTeam() throws MessagingException, ProfitMandiBusinessException, IOException {
31218 tejbeer 4613
 
31697 amit.gupta 4614
        LocalDateTime curDate = LocalDateTime.now();
31218 tejbeer 4615
 
31886 tejbeer 4616
        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 4617
 
31697 amit.gupta 4618
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(categoryIds, false);
31218 tejbeer 4619
 
31697 amit.gupta 4620
        List<MonthlyTarget> monthlyTargets = monthlyTargetRepository.selectByDate(YearMonth.now());
31218 tejbeer 4621
 
31697 amit.gupta 4622
        Map<Integer, CustomRetailer> customeRetailerMap = retailerService.getAllFofoRetailers();
31218 tejbeer 4623
 
31886 tejbeer 4624
        Map<Integer, MonthlyTarget> partnersMonthlyTarget = monthlyTargets.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31218 tejbeer 4625
 
31886 tejbeer 4626
        Map<Integer, Double> secondaryMtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
4627
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), 0, false);
31218 tejbeer 4628
 
31697 amit.gupta 4629
        String subject = "Monthly Target Vs Achievement";
31218 tejbeer 4630
 
31697 amit.gupta 4631
        for (Entry<String, Set<Integer>> storeGuyEntry : storeGuyMap.entrySet()) {
31218 tejbeer 4632
 
31697 amit.gupta 4633
            String email = storeGuyEntry.getKey();
31218 tejbeer 4634
 
31697 amit.gupta 4635
            List<Integer> fofoIds = new ArrayList<>(storeGuyEntry.getValue());
4636
            Map<Integer, MonthlyTarget> monthlyTargetAchievement = new HashMap<>();
4637
            for (Integer fofoId : fofoIds) {
31218 tejbeer 4638
 
31697 amit.gupta 4639
                MonthlyTarget monthlyTarget = partnersMonthlyTarget.get(fofoId);
4640
                if (monthlyTarget != null) {
4641
                    Double purchaseTarget = monthlyTarget.getPurchaseTarget();
31218 tejbeer 4642
 
31697 amit.gupta 4643
                    Double saleTarget = monthlyTarget.getSaleTarget();
31218 tejbeer 4644
 
31697 amit.gupta 4645
                    if (purchaseTarget != null && purchaseTarget > 0) {
4646
                        Double purchase = secondaryMtd.get(fofoId);
4647
                        if (purchase == null) {
4648
                            purchase = 0.0;
4649
                        }
4650
                        monthlyTarget.setPurchaseAchievement(purchase);
4651
                        monthlyTargetAchievement.put(fofoId, monthlyTarget);
31218 tejbeer 4652
 
31697 amit.gupta 4653
                    }
4654
                }
4655
            }
31218 tejbeer 4656
 
31697 amit.gupta 4657
            if (!monthlyTargetAchievement.isEmpty()) {
31218 tejbeer 4658
 
31697 amit.gupta 4659
                StringBuilder sb = new StringBuilder();
31218 tejbeer 4660
 
31697 amit.gupta 4661
                sb.append("<html><body><p>Hi,\n");
31886 tejbeer 4662
                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 4663
                sb.append("<tbody>\n" + "	" + "    				" + "<tr>\n");
4664
                sb.append("<th style='border:1px solid black;padding: 5px'>Partner Name</th>\n");
31218 tejbeer 4665
 
31697 amit.gupta 4666
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Target</th>\n");
31218 tejbeer 4667
 
31697 amit.gupta 4668
                sb.append("<th style='border:1px solid black;padding: 5px'>Purchase Achievement</th>\n");
4669
                sb.append("</tr>\n");
31218 tejbeer 4670
 
31886 tejbeer 4671
                for (Entry<Integer, MonthlyTarget> monthlyTargetAchievementEntry : monthlyTargetAchievement.entrySet()) {
31697 amit.gupta 4672
                    sb.append("<tr>");
4673
                    int fofoId = monthlyTargetAchievementEntry.getKey();
31218 tejbeer 4674
 
31697 amit.gupta 4675
                    MonthlyTarget monthlyTarget = monthlyTargetAchievementEntry.getValue();
31886 tejbeer 4676
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + customeRetailerMap.get(fofoId).getBusinessName() + "</td>\n");
31218 tejbeer 4677
 
31886 tejbeer 4678
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseTarget() + "</td>\n");
31218 tejbeer 4679
 
31886 tejbeer 4680
                    sb.append("<td style='border:1px solid black;padding: 5px'>" + monthlyTarget.getPurchaseAchievement() + "</td>\n");
31218 tejbeer 4681
 
31697 amit.gupta 4682
                    sb.append("</tr>\n");
31218 tejbeer 4683
 
31697 amit.gupta 4684
                }
31218 tejbeer 4685
 
32350 amit.gupta 4686
                this.sendMailOfHtmlFormat(googleMailSender, new String[]{email}, sb.toString(), null, subject);
31697 amit.gupta 4687
                // this.sendMailOfHtmlFormat("tejbeer.kaur@smartdukaan.com", sb.toString(),
4688
                // null, subject);
31218 tejbeer 4689
 
31697 amit.gupta 4690
            }
31604 tejbeer 4691
 
31697 amit.gupta 4692
        }
31604 tejbeer 4693
 
31697 amit.gupta 4694
    }
31604 tejbeer 4695
 
32061 amit.gupta 4696
    @Autowired
4697
    private PerformanceService performanceService;
4698
 
4699
 
4700
    public void sendFilteredRetailerPerformance() throws Exception {
4701
        RetailerFilterModel retailerFilterModel = performanceService.getRetailerFilterModel();
4702
 
4703
        Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(true);
4704
 
4705
 
4706
        List<RetailerPeformanceFilterModel> partnersPerformance = performanceService.getPerformance(retailerFilterModel, customRetailers);
4707
 
4708
        Map<Integer, RetailerPeformanceFilterModel> partnersPerformanceMap = new HashMap<>();
4709
 
4710
        if (!partnersPerformance.isEmpty()) {
4711
            partnersPerformanceMap = partnersPerformance.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
4712
            performanceService.sendPartnerPerformanceEmail(partnersPerformanceMap, retailerFilterModel, customRetailers);
4713
 
4714
        }
4715
 
4716
 
4717
    }
4718
 
32081 tejbeer 4719
    @Autowired
4720
    private VendorItemPricingRepository vendorItemPricingRepository;
32061 amit.gupta 4721
 
32081 tejbeer 4722
 
4723
    @Autowired
4724
    private VendorCatalogPricingService vendorCatalogPricingService;
4725
 
4726
 
4727
    public void migrateVendorItemPricing() {
4728
 
4729
        List<VendorItemPricing> vendorItemPricings = vendorItemPricingRepository.selectAll();
32350 amit.gupta 4730
        LOGGER.info("At migrate VendorItemPricing");
32092 tejbeer 4731
        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 4732
        for (VendorItemPricing vendorItemPricing : vendorItemPricings) {
4733
            Item item = null;
32092 tejbeer 4734
            if (items.get(vendorItemPricing.getItemId()) != null) {
4735
                item = items.get(vendorItemPricing.getItemId());
4736
            } else {
32084 tejbeer 4737
                continue;
32081 tejbeer 4738
            }
32092 tejbeer 4739
 
32081 tejbeer 4740
            VendorCatalogPricingModel vendorCatalogPricingModel = new VendorCatalogPricingModel();
4741
            vendorCatalogPricingModel.setCatalogId(item.getCatalogItemId());
4742
            vendorCatalogPricingModel.setAuthId(13);
32088 tejbeer 4743
            vendorCatalogPricingModel.setDp(vendorItemPricing.getDp());
32081 tejbeer 4744
 
4745
            vendorCatalogPricingModel.setTp(vendorItemPricing.getTp());
4746
            vendorCatalogPricingModel.setMop(vendorItemPricing.getMop());
32384 amit.gupta 4747
            vendorCatalogPricingModel.setEffectedOn(LocalDate.of(2023, 8, 22));
32081 tejbeer 4748
            vendorCatalogPricingModel.setVendorId(vendorItemPricing.getVendorId());
4749
 
4750
 
4751
            try {
4752
                vendorCatalogPricingService.createVendorCatalogPricingLog(vendorCatalogPricingModel);
4753
            } catch (ProfitMandiBusinessException e) {
4754
                continue;
4755
            }
4756
 
4757
        }
4758
 
4759
    }
4760
 
4761
    public void approveVendorCatalogPricing() {
4762
        List<VendorCatalogPricingLog> vendorCatalogPricingLogs = vendorCatalogPricingLogRepository.selectByStatus(VendorCatalogPricingStatus.PENDING);
4763
 
32084 tejbeer 4764
 
32081 tejbeer 4765
        for (VendorCatalogPricingLog vendorCatalogPricingLog : vendorCatalogPricingLogs) {
32107 tejbeer 4766
            vendorCatalogPricingLog.setStatus(VendorCatalogPricingStatus.APPROVED);
4767
            vendorCatalogPricingLog.setUpdatedTimestamp(LocalDateTime.now());
4768
            vendorCatalogPricingLog.setApprovedBy(13);
4769
            vendorCatalogPricingLog.setApprovedTimestamp(LocalDateTime.now());
32114 tejbeer 4770
            vendorCatalogPricingService.createVendorCatalogPricing(vendorCatalogPricingLog);
4771
        }
32081 tejbeer 4772
 
32114 tejbeer 4773
    }
32108 tejbeer 4774
 
4775
 
32210 jai.hind 4776
}
4777
// 2284'