Subversion Repositories SmartDukaan

Rev

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