Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23724 amit.gupta 1
package com.smartdukaan.cron.scheduled;
23723 amit.gupta 2
 
24121 govind 3
import java.io.IOException;
24807 amit.gupta 4
import java.io.Serializable;
23739 amit.gupta 5
import java.sql.Timestamp;
23724 amit.gupta 6
import java.time.LocalDate;
7
import java.time.LocalDateTime;
24256 amit.gupta 8
import java.time.LocalTime;
24653 govind 9
import java.time.format.DateTimeFormatter;
23724 amit.gupta 10
import java.time.temporal.ChronoUnit;
11
import java.util.ArrayList;
12
import java.util.Arrays;
24627 amit.gupta 13
import java.util.Collections;
26945 amit.gupta 14
import java.util.Comparator;
23723 amit.gupta 15
import java.util.HashMap;
24241 amit.gupta 16
import java.util.HashSet;
23724 amit.gupta 17
import java.util.List;
23723 amit.gupta 18
import java.util.Map;
24242 amit.gupta 19
import java.util.Optional;
24542 amit.gupta 20
import java.util.Set;
23724 amit.gupta 21
import java.util.stream.Collectors;
23723 amit.gupta 22
 
24121 govind 23
import javax.mail.MessagingException;
24
import javax.mail.internet.InternetAddress;
25
import javax.mail.internet.MimeMessage;
26
 
23929 amit.gupta 27
import org.apache.commons.io.output.ByteArrayOutputStream;
25598 amit.gupta 28
import org.apache.commons.lang.StringUtils;
25300 tejbeer 29
import org.apache.http.client.methods.CloseableHttpResponse;
30
import org.apache.http.client.methods.HttpPost;
31
import org.apache.http.entity.StringEntity;
32
import org.apache.http.impl.client.CloseableHttpClient;
33
import org.apache.http.impl.client.HttpClients;
23755 amit.gupta 34
import org.apache.logging.log4j.LogManager;
35
import org.apache.logging.log4j.Logger;
25300 tejbeer 36
import org.json.JSONObject;
23723 amit.gupta 37
import org.springframework.beans.factory.annotation.Autowired;
23933 amit.gupta 38
import org.springframework.beans.factory.annotation.Qualifier;
23724 amit.gupta 39
import org.springframework.beans.factory.annotation.Value;
23929 amit.gupta 40
import org.springframework.core.io.ByteArrayResource;
24692 amit.gupta 41
import org.springframework.core.io.InputStreamSource;
23929 amit.gupta 42
import org.springframework.mail.javamail.JavaMailSender;
24121 govind 43
import org.springframework.mail.javamail.MimeMessageHelper;
23723 amit.gupta 44
import org.springframework.stereotype.Component;
23724 amit.gupta 45
import org.springframework.transaction.annotation.Transactional;
23723 amit.gupta 46
 
24542 amit.gupta 47
import com.google.common.collect.Lists;
25300 tejbeer 48
import com.google.gson.Gson;
49
import com.google.gson.GsonBuilder;
25721 tejbeer 50
import com.spice.profitmandi.common.enumuration.MessageType;
23724 amit.gupta 51
import com.spice.profitmandi.common.enumuration.RechargeStatus;
24681 amit.gupta 52
import com.spice.profitmandi.common.enumuration.ReporticoProject;
24121 govind 53
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23929 amit.gupta 54
import com.spice.profitmandi.common.model.CustomRetailer;
25721 tejbeer 55
import com.spice.profitmandi.common.model.FocusedModelShortageModel;
24542 amit.gupta 56
import com.spice.profitmandi.common.model.GstRate;
25590 amit.gupta 57
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23724 amit.gupta 58
import com.spice.profitmandi.common.model.RechargeCredential;
25821 amit.gupta 59
import com.spice.profitmandi.common.model.SendNotificationModel;
24681 amit.gupta 60
import com.spice.profitmandi.common.services.ReporticoService;
24002 amit.gupta 61
import com.spice.profitmandi.common.util.FileUtil;
23929 amit.gupta 62
import com.spice.profitmandi.common.util.FormattingUtils;
63
import com.spice.profitmandi.common.util.Utils;
24592 amit.gupta 64
import com.spice.profitmandi.common.util.Utils.Attachment;
25300 tejbeer 65
import com.spice.profitmandi.dao.Interface.Campaign;
66
import com.spice.profitmandi.dao.convertor.LocalDateTimeJsonConverter;
25590 amit.gupta 67
import com.spice.profitmandi.dao.entity.auth.AuthUser;
25800 tejbeer 68
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
25609 amit.gupta 69
import com.spice.profitmandi.dao.entity.catalog.Item;
24590 amit.gupta 70
import com.spice.profitmandi.dao.entity.catalog.Scheme;
25590 amit.gupta 71
import com.spice.profitmandi.dao.entity.cs.Position;
26283 tejbeer 72
import com.spice.profitmandi.dao.entity.cs.Ticket;
23724 amit.gupta 73
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
25300 tejbeer 74
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
75
import com.spice.profitmandi.dao.entity.dtr.PushNotifications;
23724 amit.gupta 76
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
77
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
78
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
26283 tejbeer 79
import com.spice.profitmandi.dao.entity.fofo.ActivityType;
24542 amit.gupta 80
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
24590 amit.gupta 81
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
23724 amit.gupta 82
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
24542 amit.gupta 83
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23929 amit.gupta 84
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24249 amit.gupta 85
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24277 amit.gupta 86
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
23724 amit.gupta 87
import com.spice.profitmandi.dao.entity.fofo.Purchase;
24242 amit.gupta 88
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
24241 amit.gupta 89
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
24431 amit.gupta 90
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
25609 amit.gupta 91
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
24587 amit.gupta 92
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
24580 amit.gupta 93
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
24542 amit.gupta 94
import com.spice.profitmandi.dao.entity.user.Address;
25300 tejbeer 95
import com.spice.profitmandi.dao.entity.user.Device;
25927 amit.gupta 96
import com.spice.profitmandi.dao.entity.user.FranchiseeVisit;
25910 amit.gupta 97
import com.spice.profitmandi.dao.entity.user.Lead;
26790 tejbeer 98
import com.spice.profitmandi.dao.entity.user.Refferal;
24250 amit.gupta 99
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25598 amit.gupta 100
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26790 tejbeer 101
import com.spice.profitmandi.dao.enumuration.dtr.RefferalStatus;
24242 amit.gupta 102
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
25609 amit.gupta 103
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
25300 tejbeer 104
import com.spice.profitmandi.dao.model.SimpleCampaign;
105
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
25590 amit.gupta 106
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25300 tejbeer 107
import com.spice.profitmandi.dao.repository.catalog.DeviceRepository;
25721 tejbeer 108
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
24249 amit.gupta 109
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
24241 amit.gupta 110
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
26929 amit.gupta 111
import com.spice.profitmandi.dao.repository.catalog.StateGstRateRepository;
25590 amit.gupta 112
import com.spice.profitmandi.dao.repository.cs.CsService;
113
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
26283 tejbeer 114
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
23724 amit.gupta 115
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
23929 amit.gupta 116
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25927 amit.gupta 117
import com.spice.profitmandi.dao.repository.dtr.FranchiseeActivityRepository;
118
import com.spice.profitmandi.dao.repository.dtr.FranchiseeVisitRepository;
25837 amit.gupta 119
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
25910 amit.gupta 120
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
24653 govind 121
import com.spice.profitmandi.dao.repository.dtr.Mongo;
25300 tejbeer 122
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
123
import com.spice.profitmandi.dao.repository.dtr.PushNotificationRepository;
23724 amit.gupta 124
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
125
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
126
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
26790 tejbeer 127
import com.spice.profitmandi.dao.repository.dtr.RefferalRepository;
24542 amit.gupta 128
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
24669 govind 129
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
25721 tejbeer 130
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
26408 amit.gupta 131
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
25721 tejbeer 132
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24542 amit.gupta 133
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
24590 amit.gupta 134
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
24542 amit.gupta 135
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
23724 amit.gupta 136
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
24249 amit.gupta 137
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24277 amit.gupta 138
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
24174 govind 139
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
25503 amit.gupta 140
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
23724 amit.gupta 141
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
24242 amit.gupta 142
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
24241 amit.gupta 143
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
25982 amit.gupta 144
import com.spice.profitmandi.dao.repository.transaction.HdfcPaymentRepository;
23929 amit.gupta 145
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
25609 amit.gupta 146
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
24431 amit.gupta 147
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
24580 amit.gupta 148
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
24587 amit.gupta 149
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
24542 amit.gupta 150
import com.spice.profitmandi.dao.repository.user.AddressRepository;
25721 tejbeer 151
import com.spice.profitmandi.dao.repository.user.UserRepository;
25854 amit.gupta 152
import com.spice.profitmandi.service.NotificationService;
24337 amit.gupta 153
import com.spice.profitmandi.service.PartnerInvestmentService;
25694 amit.gupta 154
import com.spice.profitmandi.service.integrations.toffee.ToffeeService;
23929 amit.gupta 155
import com.spice.profitmandi.service.inventory.InventoryService;
25335 amit.gupta 156
import com.spice.profitmandi.service.order.OrderService;
24431 amit.gupta 157
import com.spice.profitmandi.service.pricing.PriceDropService;
23724 amit.gupta 158
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
159
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
160
import com.spice.profitmandi.service.scheme.SchemeService;
24121 govind 161
import com.spice.profitmandi.service.slab.TargetSlabService;
23929 amit.gupta 162
import com.spice.profitmandi.service.transaction.TransactionService;
163
import com.spice.profitmandi.service.user.RetailerService;
23739 amit.gupta 164
import com.spice.profitmandi.service.wallet.WalletService;
23723 amit.gupta 165
 
25721 tejbeer 166
import in.shop2020.model.v1.order.OrderStatus;
25982 amit.gupta 167
import in.shop2020.model.v1.order.WalletReferenceType;;
23739 amit.gupta 168
 
23723 amit.gupta 169
@Component
23724 amit.gupta 170
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 171
public class ScheduledTasks {
172
 
23724 amit.gupta 173
	@Value("${oxigen.recharge.transaction.url}")
174
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 175
 
23724 amit.gupta 176
	@Value("${oxigen.recharge.enquiry.url}")
177
	private String oxigenRechargeEnquiryUrl;
24533 govind 178
 
24431 amit.gupta 179
	@Autowired
25503 amit.gupta 180
	private PartnerTypeChangeService partnerTypeChangeService;
25598 amit.gupta 181
 
25590 amit.gupta 182
	@Autowired
26408 amit.gupta 183
	private ActivatedImeiRepository activatedImeiRepository;
184
 
185
	@Autowired
25910 amit.gupta 186
	private LeadRepository leadRepository;
25927 amit.gupta 187
 
25910 amit.gupta 188
	@Autowired
25590 amit.gupta 189
	private AuthRepository authRepository;
25503 amit.gupta 190
 
191
	@Autowired
24431 amit.gupta 192
	private PriceDropService priceDropService;
26283 tejbeer 193
 
25590 amit.gupta 194
	@Autowired
25927 amit.gupta 195
	private FranchiseeVisitRepository franchiseeVisitRepository;
26790 tejbeer 196
 
25927 amit.gupta 197
	@Autowired
198
	private FranchiseeActivityRepository franchiseeActivityRepository;
26790 tejbeer 199
 
25927 amit.gupta 200
	@Autowired
25982 amit.gupta 201
	private HdfcPaymentRepository hdfcPaymentRepository;
26790 tejbeer 202
 
25982 amit.gupta 203
	@Autowired
25590 amit.gupta 204
	private CsService csService;
25846 amit.gupta 205
 
25837 amit.gupta 206
	@Autowired
207
	private InsurancePolicyRepository insurancePolicyRepository;
23723 amit.gupta 208
 
25694 amit.gupta 209
	@Autowired
210
	private ToffeeService toffeeService;
211
 
23724 amit.gupta 212
	@Value("${oxigen.recharge.auth.key}")
213
	private String oxigenRechargeAuthKey;
214
 
215
	@Value("${oxigen.recharge.validation.url}")
216
	private String oxigenRechargeValidationUrl;
217
 
218
	@Value("${oxigen.recharge.validation.auth.key}")
219
	private String oxigenRechargeValidationAuthKey;
220
 
221
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
222
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
223
 
224
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
225
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
226
 
227
	@Value("${think.walnut.digital.recharge.enquiry.url}")
228
	private String thinkWalnutDigitalRechargeEnquiryUrl;
229
 
230
	@Value("${think.walnut.digital.recharge.balance.url}")
231
	private String thinkWalnutDigitalRechargeBalanceUrl;
232
 
233
	@Value("${think.walnut.digital.recharge.username}")
234
	private String thinkWalnutDigitalRechargeUserName;
235
 
236
	@Value("${think.walnut.digital.recharge.password}")
237
	private String thinkWalnutDigitalRechargePassword;
238
 
239
	@Value("${think.walnut.digital.recharge.auth.key}")
240
	private String thinkWalnutDigitalRechargeAuthKey;
241
 
23723 amit.gupta 242
	@Autowired
23724 amit.gupta 243
	private PurchaseRepository purchaseRepository;
244
 
245
	@Autowired
25609 amit.gupta 246
	private PriceDropIMEIRepository priceDropIMEIRepository;
247
 
248
	@Autowired
249
	PriceDropRepository priceDropRepository;
250
 
251
	@Autowired
23724 amit.gupta 252
	private SchemeService schemeService;
24683 amit.gupta 253
 
26945 amit.gupta 254
	private static final String[] STOCK_AGEING_MAIL_LIST = new String[] { "uday.singh@smartudkaan.com",
25609 amit.gupta 255
			"adeel.yazdani@smartdukaan.com", "manoj.singh@smartdukaan.com", "kamini.sharma@smartdukaan.com",
26862 amit.gupta 256
			"mohinder.mutreja@smartdukaan.com", "ankit.bhatia@smartdukaan.com", "tarun.verma@smartdukaan.com",
26945 amit.gupta 257
			"hemant.kaura@smartdukaan.com", "rajat.gupta@smartdukaan.com", "kuldeep.kumar@smartdukaan.com",
258
			"prakash.rai@smartdukaan.com" };
25609 amit.gupta 259
 
260
	private static final String[] ITEMWISE_PENDING_INDENT_MAIL_LIST = new String[] { "kamini.sharma@smartdukaan.com",
26862 amit.gupta 261
			"prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com", "uday.singh@smartdukaan.com",
25821 amit.gupta 262
			"kuldeep.kumar@smartdukaan.com" };
25609 amit.gupta 263
 
25721 tejbeer 264
	private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING);
265
 
24681 amit.gupta 266
	@Autowired
267
	private ReporticoService reporticoService;
23724 amit.gupta 268
 
269
	@Autowired
24337 amit.gupta 270
	private PartnerInvestmentService partnerInvestmentService;
25598 amit.gupta 271
 
25590 amit.gupta 272
	@Autowired
273
	private PositionRepository positionRepository;
24337 amit.gupta 274
 
275
	@Autowired
24542 amit.gupta 276
	private FofoOrderItemRepository fofoOrderItemRepository;
25865 amit.gupta 277
 
25854 amit.gupta 278
	@Autowired
279
	private NotificationService notificationService;
24542 amit.gupta 280
 
281
	@Autowired
24277 amit.gupta 282
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
283
 
284
	@Autowired
24241 amit.gupta 285
	private SchemeInOutRepository schemeInOutRepository;
286
 
287
	@Autowired
23724 amit.gupta 288
	private RechargeTransactionRepository rechargeTransactionRepository;
289
 
290
	@Autowired
24542 amit.gupta 291
	private CustomerAddressRepository customerAddressRepository;
292
 
293
	@Autowired
23724 amit.gupta 294
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
295
 
296
	@Autowired
24590 amit.gupta 297
	private FofoLineItemRepository fofoLineItemRepository;
298
 
299
	@Autowired
23724 amit.gupta 300
	private FofoOrderRepository fofoOrderRepository;
24587 amit.gupta 301
 
24580 amit.gupta 302
	@Autowired
303
	private UserWalletHistoryRepository userWalletHistoryRepository;
24250 amit.gupta 304
 
24249 amit.gupta 305
	@Autowired
24587 amit.gupta 306
	private UserWalletRepository userWalletRepository;
307
 
308
	@Autowired
24249 amit.gupta 309
	private InventoryItemRepository inventoryItemRepository;
23929 amit.gupta 310
 
23739 amit.gupta 311
	@Autowired
312
	private WalletService walletService;
23724 amit.gupta 313
 
314
	@Autowired
315
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
316
 
317
	@Autowired
318
	private OxigenRechargeProviderService oxigenRechargeProviderService;
319
 
320
	@Autowired
321
	private RechargeProviderRepository rechargeProviderRepository;
322
 
323
	@Autowired
24242 amit.gupta 324
	private ScanRecordRepository scanRecordRepository;
325
 
326
	@Autowired
23724 amit.gupta 327
	private DailyRechargeRepository dailyRechargeRepository;
328
 
23929 amit.gupta 329
	@Autowired
330
	private FofoStoreRepository fofoStoreRepository;
24177 govind 331
 
24121 govind 332
	@Autowired
333
	private TargetSlabService targetService;
23929 amit.gupta 334
 
23724 amit.gupta 335
	@Value("${prod}")
336
	private boolean prod;
26945 amit.gupta 337
 
26929 amit.gupta 338
	@Autowired
339
	private StateGstRateRepository stateGstRateRepository;
23724 amit.gupta 340
 
23929 amit.gupta 341
	@Autowired
342
	private RetailerService retailerService;
343
 
344
	@Autowired
345
	private TransactionService transactionService;
24250 amit.gupta 346
 
24249 amit.gupta 347
	@Autowired
348
	private ItemRepository itemRepository;
23929 amit.gupta 349
 
350
	@Autowired
351
	private OrderRepository orderRepository;
25351 tejbeer 352
 
25335 amit.gupta 353
	@Autowired
354
	private OrderService orderService;
23929 amit.gupta 355
 
356
	@Autowired
24241 amit.gupta 357
	private SchemeRepository schemeRepository;
358
 
359
	@Autowired
23929 amit.gupta 360
	private JavaMailSender mailSender;
24177 govind 361
 
24174 govind 362
	@Autowired
363
	private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 364
 
365
	@Autowired
366
	@Qualifier(value = "googleMailSender")
23932 amit.gupta 367
	private JavaMailSender googleMailSender;
23929 amit.gupta 368
 
369
	@Autowired
370
	private InventoryService inventoryService;
371
 
24533 govind 372
	@Autowired
24542 amit.gupta 373
	private AddressRepository addressRepository;
374
 
375
	@Autowired
376
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
377
 
24653 govind 378
	@Autowired
379
	private Mongo mongoClient;
24683 amit.gupta 380
 
24669 govind 381
	@Autowired
25300 tejbeer 382
	private DeviceRepository deviceRepository;
383
 
384
	@Autowired
385
	private PushNotificationRepository pushNotificationRepository;
386
 
387
	@Autowired
388
	private NotificationCampaignRepository notificationCampaignRepository;
389
 
390
	@Autowired
25721 tejbeer 391
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
392
 
393
	@Autowired
394
	private FocusedModelRepository focusedModelRepository;
395
 
396
	@Autowired
24669 govind 397
	private UserAccountRepository userAccountRepository;
24653 govind 398
 
25721 tejbeer 399
	@Autowired
25927 amit.gupta 400
	private UserRepository userUserRepository;
25721 tejbeer 401
 
402
	@Autowired
25927 amit.gupta 403
	private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
404
 
405
	@Autowired
25721 tejbeer 406
	private UserCampaignRepository userCampaignRepository;
407
 
408
	@Autowired
409
	private Gson gson;
410
 
26283 tejbeer 411
	@Autowired
412
	private TicketRepository ticketRepository;
413
 
26790 tejbeer 414
	@Autowired
415
	private RefferalRepository refferalRepository;
416
 
23755 amit.gupta 417
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 418
 
25300 tejbeer 419
	private String FCM_URL = "https://fcm.googleapis.com/fcm/send";
420
	private String FCM_API_KEY = "AAAASAjNcn4:APA91bG6fWRIgYJI0L9gCjP5ynaXz2hJHYKtD9dfH7Depdv31Nd9APJwhx-OPkAJ1WSz4BGNYG8lHThLFSjDGFxIwUZv241YcAJEGDLgt86mxq9FXJe-yBRu-S0_ZwHqmX-QaVKl5F_A";
421
 
23724 amit.gupta 422
	public void generateDailyRecharge() {
423
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
424
				.selectAll(0, 2000);
425
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
426
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
427
 
428
		rechargeProviders.stream().forEach(x -> {
429
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
430
					.stream().filter(z -> z.getProviderId() == x.getId())
431
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
432
 
433
			LOGGER.info("dateWiseProviderCreditsMap -- {}", dateWiseProviderCreditsMap);
434
			LocalDate endDate = LocalDate.now().plusDays(1);
435
			float previousDayClosing = 0;
436
			LocalDate date = LocalDate.of(2018, 4, 6);
437
			while (date.isBefore(endDate)) {
438
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
439
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
440
								date.plusDays(1).atStartOfDay());
441
 
442
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
443
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
444
 
445
				float dailyAmount = 0;
446
				float totalCommission = 0;
447
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
448
					if (rechargeTransaction.getProviderId() == x.getId()) {
449
						dailyAmount += rechargeTransaction.getAmount();
450
						totalCommission += rechargeTransaction.getCommission();
451
					}
452
				}
453
 
454
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
455
				float dailyWalletRecharge = 0;
456
				if (rechargeHistoryList != null) {
457
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
458
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
459
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
460
						}
461
					}
462
				}
463
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
464
					DailyRecharge dailyRecharge = null;
465
					try {
466
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
467
					} catch (Exception e) {
468
						LOGGER.info("Could not find Recharge entry");
469
					}
470
					if (dailyRecharge == null) {
471
						dailyRecharge = new DailyRecharge();
472
						dailyRecharge.setCreateDate(date);
473
					}
474
					dailyRecharge.setOpeningBalance(previousDayClosing);
475
					dailyRecharge.setProviderId(x.getId());
476
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
477
					dailyRecharge.setTotalAmount(dailyAmount);
478
					dailyRecharge.setTotalCommission(totalCommission);
479
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
480
					dailyRecharge.setClosingBalance(closingBalance);
481
					dailyRechargeRepository.persist(dailyRecharge);
482
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
483
					previousDayClosing = dailyRecharge.getClosingBalance();
484
				}
485
				date = date.plusDays(1);
486
			}
487
			rechargeProviderRepository.persist(x);
488
		});
23761 amit.gupta 489
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 490
	}
491
 
23738 amit.gupta 492
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 493
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
494
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
495
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
496
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
497
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
498
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
499
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
500
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
501
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
502
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
503
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
504
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
505
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
506
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
507
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
508
			try {
509
				int providerId = rechargeTransaction.getProviderId();
510
				if (providerId == 1) {
511
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
512
							rechargeTransaction);
513
				} else if (providerId == 2) {
514
					thinkWalnutDigitalRechargeProviderService
515
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
516
				}
517
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
518
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
519
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
520
							rechargeTransaction.getStatus());
521
				}
522
			} catch (Exception e) {
523
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
524
			}
525
		}
23738 amit.gupta 526
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 527
	}
24240 amit.gupta 528
 
529
	// TemporaryMethod
24237 amit.gupta 530
	public void migrateInvoice() {
531
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
532
		Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
24241 amit.gupta 533
		partnerOrdersMap = fofoOrders.stream()
534
				.collect(Collectors.groupingBy(FofoOrder::getFofoId, Collectors.toList()));
24237 amit.gupta 535
		for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
24240 amit.gupta 536
			int sequence = 0;
537
			String prefix = "";
24241 amit.gupta 538
			List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId())
539
					.collect(Collectors.toList());
540
			for (FofoOrder order : sortedList) {
541
 
24240 amit.gupta 542
				LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
24241 amit.gupta 543
				if (!order.getInvoiceNumber().contains("SEC")) {
24240 amit.gupta 544
					sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
545
					prefix = order.getInvoiceNumber().split("/")[0];
546
				} else {
547
					sequence += 1;
24241 amit.gupta 548
					String invoiceNumber = prefix + "/" + sequence;
24240 amit.gupta 549
					order.setInvoiceNumber(invoiceNumber);
550
					fofoOrderRepository.persist(order);
551
				}
552
			}
24241 amit.gupta 553
 
24237 amit.gupta 554
		}
555
	}
23724 amit.gupta 556
 
24241 amit.gupta 557
	// Temporary Method
24252 amit.gupta 558
	public void evaluateExcessSchemeOut() throws Exception {
24244 amit.gupta 559
		Map<Integer, String> userNameMap = retailerService.getAllFofoRetailerIdNameMap();
560
		Map<Integer, Float> userAmountMap = new HashMap<>();
24252 amit.gupta 561
 
25837 amit.gupta 562
		List<List<?>> rows = new ArrayList<>();
24271 amit.gupta 563
		List<String> headers = Arrays.asList("Scheme", "Item", "Partner", "Amount", "Credited On", "Invoice Number",
564
				"Sale On", "Scheme Start", "Scheme End", "Active On", "Expired On");
24241 amit.gupta 565
		schemeRepository.selectAll().stream().forEach(x -> {
24250 amit.gupta 566
			if (x.getType().equals(SchemeType.OUT)) {
567
				List<SchemeInOut> sioList = schemeInOutRepository
568
						.selectBySchemeIds(new HashSet<>(Arrays.asList(x.getId())));
569
				if (x.getActiveTimestamp() != null) {
570
					LocalDateTime endDateTime = x.getEndDateTime();
571
					if (x.getExpireTimestamp() != null && x.getExpireTimestamp().isBefore(x.getEndDateTime())) {
572
						endDateTime = x.getExpireTimestamp();
24249 amit.gupta 573
					}
24250 amit.gupta 574
					for (SchemeInOut sio : sioList) {
575
						InventoryItem inventoryItem = null;
24266 amit.gupta 576
						inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
24271 amit.gupta 577
						FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndSerialNumber(
578
								inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), null, null, 0, 1).get(0);
24250 amit.gupta 579
						Optional<ScanRecord> record = scanRecordRepository
580
								.selectByInventoryItemId(sio.getInventoryItemId()).stream()
581
								.filter(y -> y.getType().equals(ScanType.SALE)).findFirst();
582
						if (record.isPresent()) {
583
							int fofoId = record.get().getFofoId();
584
							if (record.get().getCreateTimestamp().isAfter(endDateTime)
585
									|| record.get().getCreateTimestamp().isBefore(x.getStartDateTime())) {
586
								if (!userAmountMap.containsKey(fofoId)) {
587
									userAmountMap.put(fofoId, 0f);
588
								}
589
								userAmountMap.put(fofoId, sio.getAmount() + userAmountMap.get(fofoId));
590
								try {
24252 amit.gupta 591
									rows.add(Arrays.asList(x.getDescription(),
24250 amit.gupta 592
											itemRepository.selectById(inventoryItem.getItemId()).getItemDescription(),
24252 amit.gupta 593
											userNameMap.get(fofoId), sio.getAmount(),
24253 amit.gupta 594
											FormattingUtils.formatDate(sio.getCreateTimestamp()),
595
											fofoOrder.getInvoiceNumber(),
596
											FormattingUtils.formatDate(record.get().getCreateTimestamp()),
597
											FormattingUtils.formatDate(x.getStartDateTime()),
598
											FormattingUtils.formatDate(x.getEndDateTime()),
599
											FormattingUtils.formatDate(x.getActiveTimestamp()),
600
											FormattingUtils.formatDate(x.getExpireTimestamp())));
24250 amit.gupta 601
								} catch (Exception e) {
602
									e.printStackTrace();
603
								}
24242 amit.gupta 604
							}
24241 amit.gupta 605
						}
606
					}
607
				}
608
			}
609
		});
24246 amit.gupta 610
		userAmountMap.entrySet().stream()
611
				.forEach(x -> LOGGER.info("{} to be deducted from {}({}) for wrongly disbursed due to technical error.",
612
						x.getValue(), userNameMap.get(x.getKey())));
24241 amit.gupta 613
 
24252 amit.gupta 614
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
24271 amit.gupta 615
		Utils.sendMailWithAttachment(googleMailSender,
616
				new String[] { "amit.gupta@shop2020.in", "adeel.yazdani@smartdukaan.com" }, null,
617
				"Partner Excess Amount", "PFA", "ListofSchemes.csv", new ByteArrayResource(baos.toByteArray()));
24252 amit.gupta 618
 
24241 amit.gupta 619
	}
24271 amit.gupta 620
 
25584 amit.gupta 621
	public void processScheme(int offset, boolean dryRun) throws Exception {
24462 amit.gupta 622
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24259 amit.gupta 623
		LocalDateTime endDate = startDate.plusDays(30);
25584 amit.gupta 624
		processScheme(startDate, endDate, dryRun);
24256 amit.gupta 625
	}
24533 govind 626
 
25584 amit.gupta 627
	public void processScheme(int offset, int durationDays, boolean dryRun) throws Exception {
24462 amit.gupta 628
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24461 amit.gupta 629
		LocalDateTime endDate = startDate.plusDays(durationDays);
25584 amit.gupta 630
		processScheme(startDate, endDate, dryRun);
24461 amit.gupta 631
	}
24271 amit.gupta 632
 
25584 amit.gupta 633
	public void processScheme(boolean dryRun) throws Exception {
24256 amit.gupta 634
		LocalDateTime fromDate = LocalDateTime.now().minusDays(30);
25584 amit.gupta 635
		processScheme(fromDate, LocalDateTime.now(), dryRun);
24256 amit.gupta 636
	}
24271 amit.gupta 637
 
25584 amit.gupta 638
	public void processScheme(LocalDateTime startDate, LocalDateTime endDate, boolean dryRun) throws Exception {
23724 amit.gupta 639
		LOGGER.info("Started execution at {}", LocalDateTime.now());
25312 amit.gupta 640
		System.out.println(
641
				"InventoryId\tSerialNumber\tItem Id\tScheme Id\tScheme Name\tScheme Type\tAmount Type\tDP\tTaxable\tScheme Amount\tAmount Paid");
24561 amit.gupta 642
		try {
24587 amit.gupta 643
			List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
644
			for (Purchase purchase : purchases) {
645
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
646
			}
24271 amit.gupta 647
 
24587 amit.gupta 648
			List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
649
			for (FofoOrder fofoOrder : fofoOrders) {
650
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
651
			}
652
		} catch (Exception e) {
24561 amit.gupta 653
			e.printStackTrace();
24565 amit.gupta 654
			throw e;
24561 amit.gupta 655
		}
25312 amit.gupta 656
		List<UserWalletHistory> uwhs = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
657
				Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
25043 amit.gupta 658
		System.out.println("Amount\tReference\tReferenceType\tTimestamp\tDescription");
25312 amit.gupta 659
		for (UserWalletHistory uwh : uwhs) {
660
			System.out.println(String.format("%d\t%d\t%s\t%s\t%s", uwh.getAmount(), uwh.getReference(),
661
					uwh.getReferenceType(), uwh.getTimestamp().toString(), uwh.getDescription()));
25043 amit.gupta 662
		}
23724 amit.gupta 663
		LOGGER.info("Schemes process successfully.");
25598 amit.gupta 664
		if (dryRun) {
25584 amit.gupta 665
			throw new Exception();
666
		}
23724 amit.gupta 667
	}
23929 amit.gupta 668
 
23739 amit.gupta 669
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 670
		LocalDateTime cashbackTime = LocalDateTime.now();
23929 amit.gupta 671
		int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
672
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository
673
				.getPendingCashBackRehargeTransactions();
674
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
675
				Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
676
		for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
677
			int retailerId = (Integer) totalRetailerCashback.getKey();
23739 amit.gupta 678
			float amount = totalRetailerCashback.getValue().floatValue();
23929 amit.gupta 679
			if (Math.round(amount) > 0) {
680
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK,
26565 amit.gupta 681
						"Recharge Cashback", Math.round(amount), LocalDateTime.now());
23762 amit.gupta 682
			}
23739 amit.gupta 683
		}
23929 amit.gupta 684
		for (RechargeTransaction rt : pendingTransactions) {
23761 amit.gupta 685
			rt.setCashbackTimestamp(cashbackTime);
686
			rt.setCashbackReference(referenceId);
687
			rechargeTransactionRepository.persist(rt);
688
		}
23739 amit.gupta 689
		LOGGER.info("Cashbacks for Recharge processed Successfully");
690
	}
23724 amit.gupta 691
 
25598 amit.gupta 692
	private class SaleRoles {
693
 
694
		private List<String> l1;
695
		private List<String> l2;
696
 
697
		public SaleRoles() {
698
			l1 = new ArrayList<>();
699
			l2 = new ArrayList<>();
700
		}
701
 
702
		public List<String> getL1() {
703
			return l1;
704
		}
705
 
706
		public List<String> getL2() {
707
			return l2;
708
		}
709
 
710
	}
711
 
26945 amit.gupta 712
	private class FofoReportingModel {
713
		private String code;
714
		private int fofoId;
715
		private String businessName;
716
		private String territoryManager;
717
		private String regionalManager;
718
 
719
		@Override
720
		public String toString() {
721
			return "FofoReportingModel [code=" + code + ", fofoId=" + fofoId + ", businessName=" + businessName
722
					+ ", territoryManager=" + territoryManager + ", regionalManager=" + regionalManager + "]";
723
		}
724
 
725
		public String getCode() {
726
			return code;
727
		}
728
 
729
		public void setCode(String code) {
730
			this.code = code;
731
		}
732
 
733
		public String getBusinessName() {
734
			return businessName;
735
		}
736
 
737
		public void setBusinessName(String businessName) {
738
			this.businessName = businessName;
739
		}
740
 
741
		public String getTerritoryManager() {
742
			return territoryManager;
743
		}
744
 
745
		public void setTerritoryManager(String territoryManager) {
746
			this.territoryManager = territoryManager;
747
		}
748
 
749
		public String getRegionalManager() {
750
			return regionalManager;
751
		}
752
 
753
		public void setRegionalManager(String regionalManager) {
754
			this.regionalManager = regionalManager;
755
		}
756
 
757
		private ScheduledTasks getOuterType() {
758
			return ScheduledTasks.this;
759
		}
760
 
761
		@Override
762
		public int hashCode() {
763
			final int prime = 31;
764
			int result = 1;
765
			result = prime * result + getOuterType().hashCode();
766
			result = prime * result + ((businessName == null) ? 0 : businessName.hashCode());
767
			result = prime * result + ((code == null) ? 0 : code.hashCode());
768
			result = prime * result + fofoId;
769
			result = prime * result + ((regionalManager == null) ? 0 : regionalManager.hashCode());
770
			result = prime * result + ((territoryManager == null) ? 0 : territoryManager.hashCode());
771
			return result;
772
		}
773
 
774
		@Override
775
		public boolean equals(Object obj) {
776
			if (this == obj)
777
				return true;
778
			if (obj == null)
779
				return false;
780
			if (getClass() != obj.getClass())
781
				return false;
782
			FofoReportingModel other = (FofoReportingModel) obj;
783
			if (!getOuterType().equals(other.getOuterType()))
784
				return false;
785
			if (businessName == null) {
786
				if (other.businessName != null)
787
					return false;
788
			} else if (!businessName.equals(other.businessName))
789
				return false;
790
			if (code == null) {
791
				if (other.code != null)
792
					return false;
793
			} else if (!code.equals(other.code))
794
				return false;
795
			if (fofoId != other.fofoId)
796
				return false;
797
			if (regionalManager == null) {
798
				if (other.regionalManager != null)
799
					return false;
800
			} else if (!regionalManager.equals(other.regionalManager))
801
				return false;
802
			if (territoryManager == null) {
803
				if (other.territoryManager != null)
804
					return false;
805
			} else if (!territoryManager.equals(other.territoryManager))
806
				return false;
807
			return true;
808
		}
809
 
810
		public int getFofoId() {
811
			return fofoId;
812
		}
813
 
814
		public void setFofoId(int fofoId) {
815
			this.fofoId = fofoId;
816
		}
817
 
818
	}
819
 
24271 amit.gupta 820
	public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
24277 amit.gupta 821
		LocalDate yesterDay = LocalDate.now().minusDays(1);
25267 amit.gupta 822
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
23929 amit.gupta 823
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
824
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25351 tejbeer 825
 
26957 amit.gupta 826
		List<String> headers = Arrays.asList("Code", "Outlet name", "State Manager", "Teritory/Team Lead",
26945 amit.gupta 827
				"Wallet Amount", "In Stock Amount", "Activated Stock", "Return In Transit Stock", "Unbilled Amount",
828
				"Grn Pending Amount", "Min Investment", "Investment Amount", "Investment Short", "Unbilled Qty",
829
				"Short Days");
25837 amit.gupta 830
		List<List<?>> rows = new ArrayList<>();
25895 amit.gupta 831
		Map<Integer, List<?>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 832
 
26945 amit.gupta 833
		Map<Integer, FofoReportingModel> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25598 amit.gupta 834
 
26945 amit.gupta 835
		Map<Integer, Integer> shortDaysMap = partnerDailyInvestmentRepository
836
				.selectAll(LocalDate.now().withDayOfMonth(1), LocalDate.now()).stream().collect(Collectors.groupingBy(
837
						x -> x.getFofoId(), Collectors.summingInt(x -> x.getShortPercentage() > 10 ? 1 : 0)));
838
 
24002 amit.gupta 839
		for (FofoStore fofoStore : fofoStores) {
26376 amit.gupta 840
			int fofoId = fofoStore.getId();
26945 amit.gupta 841
			PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 1);
25598 amit.gupta 842
			partnerDailyInvestment.setDate(yesterDay);
26945 amit.gupta 843
 
25598 amit.gupta 844
			try {
845
				partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
26945 amit.gupta 846
				shortDaysMap.put(fofoId,
847
						shortDaysMap.get(fofoId) + (partnerDailyInvestment.getShortPercentage() > 10 ? 1 : 0));
25598 amit.gupta 848
			} catch (Exception e) {
849
				// ignore the exceptions during persist
850
			}
851
 
24002 amit.gupta 852
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
25837 amit.gupta 853
			if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
24002 amit.gupta 854
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
855
				continue;
856
			}
26945 amit.gupta 857
			FofoReportingModel reportingModel = partnerIdSalesHeaderMap.get(fofoStore.getId());
858
			List<Serializable> row = new ArrayList<>();
859
			row.addAll(Arrays.asList(reportingModel.getCode(), reportingModel.getBusinessName(),
860
					reportingModel.getRegionalManager(), reportingModel.getTerritoryManager()));
25927 amit.gupta 861
			row.addAll(
862
					Arrays.asList(partnerDailyInvestment.getWalletAmount(), partnerDailyInvestment.getInStockAmount(),
26945 amit.gupta 863
							partnerDailyInvestment.getActivatedStockAmount() == 0 ? "-"
864
									: "(" + partnerDailyInvestment.getActivatedStockAmount() + ")",
25927 amit.gupta 865
							0, partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(),
866
							partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(),
26945 amit.gupta 867
							partnerDailyInvestment.getShortInvestment(), partnerDailyInvestment.getUnbilledQty(),
868
							shortDaysMap.get(fofoId)));
25837 amit.gupta 869
			partnerRowsMap.put(fofoStore.getId(), row);
24002 amit.gupta 870
			rows.add(row);
871
 
23929 amit.gupta 872
		}
25312 amit.gupta 873
 
24271 amit.gupta 874
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25598 amit.gupta 875
 
25927 amit.gupta 876
		if (sendTo == null) {
25895 amit.gupta 877
			for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
878
				List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x))
879
						.filter(x -> x != null).collect(Collectors.toList());
880
				ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
881
				String[] sendToArray = new String[] { storeGuyEntry.getKey() };
882
				Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
883
						fileName, new ByteArrayResource(baos.toByteArray()));
884
			}
885
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
26376 amit.gupta 886
					"prakash.rai@smartdukaan.com", "amit.gupta@shop2020.in");
25341 amit.gupta 887
		}
25312 amit.gupta 888
 
25604 amit.gupta 889
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
890
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
25609 amit.gupta 891
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
892
				fileName, new ByteArrayResource(baos.toByteArray()));
24271 amit.gupta 893
 
23929 amit.gupta 894
	}
24177 govind 895
 
26945 amit.gupta 896
	private Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() {
25598 amit.gupta 897
		Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
898
 
899
		List<Position> positions = positionRepository
900
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
901
		Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream()
902
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
903
		Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
904
		for (Position position : positions) {
905
			List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
25609 amit.gupta 906
			if (crList == null)
907
				continue;
25598 amit.gupta 908
			for (CustomRetailer cr : crList) {
909
				if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
910
					partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
911
				}
912
				SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
913
				AuthUser authUser = authUsersMap.get(position.getAuthUserId());
26945 amit.gupta 914
				if (authUser == null) {
26059 amit.gupta 915
					continue;
916
				}
25598 amit.gupta 917
				String name = authUser.getFirstName() + " " + authUser.getLastName();
918
				if (position.getEscalationType().equals(EscalationType.L1)) {
919
					saleRoles.getL1().add(name);
920
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
921
					saleRoles.getL2().add(name);
922
				}
923
			}
924
		}
25837 amit.gupta 925
 
926
		Set<CustomRetailer> allCrList = new HashSet<>();
927
		for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
928
			allCrList.addAll(cr);
929
		}
930
 
931
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
932
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
933
 
26945 amit.gupta 934
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
25837 amit.gupta 935
 
936
		for (CustomRetailer cr : allCrList) {
937
			FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
25927 amit.gupta 938
			if (fofoStore == null) {
25870 amit.gupta 939
				LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
940
				continue;
941
			}
26945 amit.gupta 942
			String code = fofoStore.getCode();
943
			// String storeName = "SmartDukaan-" +
944
			// fofoStore.getCode().replaceAll("[a-zA-Z]", "");
25837 amit.gupta 945
			String businessName = cr.getBusinessName();
946
			try {
947
				String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
948
				String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
26945 amit.gupta 949
				FofoReportingModel reportingModel = new FofoReportingModel();
950
				reportingModel.setBusinessName(businessName);
951
				reportingModel.setCode(code);
952
				reportingModel.setFofoId(fofoStore.getId());
953
				reportingModel.setRegionalManager(stateManager);
954
				reportingModel.setTerritoryManager(territoryManager);
955
				partnerIdSalesHeadersMap.put(fofoStore.getId(), reportingModel);
25837 amit.gupta 956
			} catch (Exception e) {
957
				LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
958
			}
959
		}
960
		return partnerIdSalesHeadersMap;
961
 
25598 amit.gupta 962
	}
963
 
24271 amit.gupta 964
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 965
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 966
	}
967
 
25312 amit.gupta 968
	public void sendTargetVsSalesReport(List<String> sendTo) throws Exception {
24177 govind 969
 
25312 amit.gupta 970
		if (sendTo == null) {
25827 amit.gupta 971
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
972
					"amit.gupta@shop2020.in", "amod.sen@smartdukaan.com", "prakash.rai@smartdukaan.com");
25312 amit.gupta 973
		}
25837 amit.gupta 974
		Map<Integer, List<Serializable>> partnerSalesTargetRowsMap = targetService.getDailySaleReportVsTarget();
25315 amit.gupta 975
 
26945 amit.gupta 976
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
24177 govind 977
 
26945 amit.gupta 978
		List<String> headers = Arrays.asList("Code", "Firm Name", "State Manager", "Teritory Manager",
25837 amit.gupta 979
				"Current Category", "Target Value", "Target Achieved", "Achived Percentage", "Remaining Target",
980
				"Today's Target", "Today's achievement");
25609 amit.gupta 981
 
25837 amit.gupta 982
		List<List<?>> rows = new ArrayList<>();
983
		Map<Integer, List<? extends Serializable>> partnerRowMap = new HashMap<>();
984
		for (Map.Entry<Integer, List<Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap.entrySet()) {
26945 amit.gupta 985
			FofoReportingModel fofoReportingModel = partnerIdSalesHeadersMap.get(partnerSalesTargetRowEntry.getKey());
986
			if (fofoReportingModel == null) {
25837 amit.gupta 987
				LOGGER.warn("Could not find headers for partner ID - {}", partnerSalesTargetRowEntry.getKey());
26945 amit.gupta 988
				continue;
25315 amit.gupta 989
			}
26945 amit.gupta 990
			List<Serializable> row = Arrays.asList(fofoReportingModel.getCode(), fofoReportingModel.getBusinessName(),
991
					fofoReportingModel.getRegionalManager(), fofoReportingModel.getTerritoryManager());
25837 amit.gupta 992
			row.addAll(partnerSalesTargetRowEntry.getValue());
993
			partnerRowMap.put(partnerSalesTargetRowEntry.getKey(), row);
994
			rows.add(row);
24177 govind 995
		}
25503 amit.gupta 996
 
25318 amit.gupta 997
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25894 amit.gupta 998
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
999
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25827 amit.gupta 1000
			if (storeGuyEntry.getValue().size() == 0)
1001
				continue;
25927 amit.gupta 1002
			List<List<?>> storeGuyRows = storeGuyEntry.getValue().stream().filter(x -> partnerRowMap.containsKey(x))
1003
					.map(x -> partnerRowMap.get(x)).collect(Collectors.toList());
25827 amit.gupta 1004
			ByteArrayOutputStream authUserStream = FileUtil.getCSVByteStream(headers, storeGuyRows);
1005
			Attachment attache = new Attachment(fileName, new ByteArrayResource(authUserStream.toByteArray()));
1006
			System.out.println(storeGuyEntry.getValue());
1007
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
1008
					"Franchise Stock Report", "PFA", attache);
1009
		}
24240 amit.gupta 1010
 
25312 amit.gupta 1011
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1012
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
1013
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
1014
				new ByteArrayResource(baos.toByteArray()));
24174 govind 1015
	}
24683 amit.gupta 1016
 
24697 amit.gupta 1017
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 1018
 
1019
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
1020
				"itemstockageing.xml");
24708 amit.gupta 1021
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 1022
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 1023
		Attachment attachment = new Attachment(
25445 amit.gupta 1024
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 1025
		Attachment attachment1 = new Attachment(
25445 amit.gupta 1026
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 1027
 
25609 amit.gupta 1028
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
1029
				attachment);
1030
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
1031
				"Itemwise Pending indent", "PFA", attachment1);
1032
 
25598 amit.gupta 1033
		// Reports to be sent to mapped partners
25597 amit.gupta 1034
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 1035
 
1036
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 1037
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 1038
			if (storeGuyEntry.getValue().size() == 0)
1039
				continue;
25418 amit.gupta 1040
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
1041
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
1042
					"focostockreport.xml", params);
1043
			Attachment attache = new Attachment(
25609 amit.gupta 1044
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 1045
			System.out.println(storeGuyEntry.getValue());
25609 amit.gupta 1046
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
1047
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 1048
		}
25503 amit.gupta 1049
 
24681 amit.gupta 1050
	}
24533 govind 1051
 
24697 amit.gupta 1052
	public void sendAgeingReport() throws Exception {
25807 amit.gupta 1053
		sendAgeingReport("kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com",
26862 amit.gupta 1054
				"hemant.kaura@smartdukaan.com");
24697 amit.gupta 1055
	}
1056
 
24533 govind 1057
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 1058
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 1059
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 1060
			priceDropService.priceDropStatus(priceDrop.getId());
1061
		}
1062
	}
23929 amit.gupta 1063
 
24542 amit.gupta 1064
	public void walletmismatch() throws Exception {
1065
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 1066
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 1067
		System.out.println(pdis.size());
24542 amit.gupta 1068
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 1069
			int fofoId = pdi.getFofoId();
24542 amit.gupta 1070
			for (PartnerDailyInvestment investment : Lists
1071
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 1072
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 1073
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 1074
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 1075
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
1076
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 1077
 
24542 amit.gupta 1078
			}
24549 amit.gupta 1079
		}
24542 amit.gupta 1080
 
1081
	}
1082
 
1083
	public void gst() throws Exception {
24548 amit.gupta 1084
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
1085
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
1086
		for (FofoOrder fofoOrder : fofoOrders) {
1087
			int retailerAddressId = retailerRegisteredAddressRepository
1088
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 1089
 
1090
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
1091
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1092
			Integer stateId = null;
1093
			if (customerAddress.getState().equals(retailerAddress.getState())) {
1094
				try {
1095
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
1096
				} catch (Exception e) {
1097
					LOGGER.error("Unable to get state rates");
1098
				}
1099
			}
1100
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1101
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 1102
 
1103
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
26929 amit.gupta 1104
			List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
24542 amit.gupta 1105
			if (stateId != null) {
26929 amit.gupta 1106
				itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
24542 amit.gupta 1107
			} else {
26929 amit.gupta 1108
				itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(itemIds);
24542 amit.gupta 1109
			}
1110
 
24548 amit.gupta 1111
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 1112
				if (stateId == null) {
1113
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
1114
				} else {
1115
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
1116
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
1117
				}
1118
				fofoOrderItemRepository.persist(foi);
1119
			}
1120
		}
24548 amit.gupta 1121
 
24542 amit.gupta 1122
	}
1123
 
24580 amit.gupta 1124
	public void schemewalletmismatch() {
1125
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 1126
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 1127
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 1128
			// reconcileOrders(dateTime);
1129
			// reconcileRecharges(dateTime);
24580 amit.gupta 1130
			dateToReconcile = dateToReconcile.plusDays(1);
1131
		}
1132
	}
1133
 
1134
	private void reconcileSchemes(LocalDate date) {
1135
		LocalDateTime startDate = date.atStartOfDay();
1136
		LocalDateTime endDate = startDate.plusDays(1);
1137
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
1138
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 1139
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
1140
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 1141
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 1142
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
1143
				WalletReferenceType.SCHEME_OUT);
1144
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
1145
				walletReferenceTypes);
1146
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
1147
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 1148
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 1149
 
1150
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
1151
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1152
 
1153
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
1154
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1155
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
1156
 
1157
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
1158
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1159
 
1160
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
1161
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
1162
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
1163
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
1164
 
1165
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
26092 amit.gupta 1166
 
24587 amit.gupta 1167
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
1168
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
1169
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
1170
				} else {
1171
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
1172
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
1173
				}
1174
			}
24590 amit.gupta 1175
			Map<Integer, Integer> userWalletMap = userWalletRepository
1176
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
1177
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1178
 
24587 amit.gupta 1179
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
1180
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
1181
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
1182
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1183
				if (diff > 5) {
1184
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1185
				}
1186
			}
24580 amit.gupta 1187
		}
24587 amit.gupta 1188
 
24580 amit.gupta 1189
	}
24590 amit.gupta 1190
 
24592 amit.gupta 1191
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1192
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1193
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1194
 
24592 amit.gupta 1195
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1196
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1197
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1198
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1199
		Set<String> serialNumbersConsidered = new HashSet<>();
1200
 
25096 amit.gupta 1201
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1202
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1203
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1204
 
24683 amit.gupta 1205
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1206
		purchases.stream().forEach(purchase -> {
1207
			float amountToRollback = 0;
1208
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1209
					+ purchase.getPurchaseReference();
1210
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1211
					.stream().filter(ii -> ii.getSerialNumber() != null)
1212
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1213
			if (inventorySerialNumberMap.size() > 0) {
1214
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1215
					String serialNumber = inventorySerialNumberEntry.getValue();
1216
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1217
					if (serialNumbersConsidered.contains(serialNumber)) {
1218
						// This will rollback scheme for differenct orders for same serial
1219
						List<SchemeInOut> sios = schemeInOutRepository
1220
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1221
								.filter(x -> x.getRolledBackTimestamp() == null
1222
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1223
								.collect(Collectors.toList());
1224
						Collections.reverse(sios);
1225
						for (SchemeInOut sio : sios) {
1226
							sio.setRolledBackTimestamp(LocalDateTime.now());
1227
							amountToRollback += sio.getAmount();
1228
							// sio.setSchemeType(SchemeType.OUT);
1229
							sio.setSerialNumber(serialNumber);
1230
							rolledbackSios.add(sio);
1231
						}
1232
						description = description.concat(" " + serialNumber + " ");
1233
					} else {
1234
						serialNumbersConsidered.add(serialNumber);
1235
						List<Integer> schemesConsidered = new ArrayList<>();
1236
						List<SchemeInOut> sios = schemeInOutRepository
1237
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1238
								.filter(x -> x.getRolledBackTimestamp() == null
1239
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1240
								.collect(Collectors.toList());
1241
						Collections.reverse(sios);
1242
						for (SchemeInOut sio : sios) {
1243
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1244
								schemesConsidered.add(sio.getSchemeId());
1245
								continue;
1246
							}
1247
							sio.setRolledBackTimestamp(LocalDateTime.now());
1248
							amountToRollback += sio.getAmount();
1249
							// sio.setSchemeType(SchemeType.OUT);
1250
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1251
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1252
							sio.setReference(purchase.getId());
24635 amit.gupta 1253
							rolledbackSios.add(sio);
1254
						}
1255
					}
1256
 
1257
				}
1258
			}
1259
			if (amountToRollback > 0) {
24683 amit.gupta 1260
				// Address address =
1261
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1262
				UserWalletHistory uwh = new UserWalletHistory();
1263
				uwh.setAmount(Math.round(amountToRollback));
1264
				uwh.setDescription(description);
1265
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1266
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1267
				uwh.setReference(purchase.getId());
1268
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1269
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1270
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1271
				userWalletHistory.add(uwh);
1272
			}
1273
		});
1274
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1275
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1276
						"Timestamp"),
1277
				userWalletHistory.stream()
1278
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1279
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1280
						.collect(Collectors.toList()));
1281
 
1282
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1283
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1284
						"Created", "Rolledback"),
24635 amit.gupta 1285
				rolledbackSios.stream()
24681 amit.gupta 1286
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1287
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1288
						.collect(Collectors.toList()));
1289
 
25043 amit.gupta 1290
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1291
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1292
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1293
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1294
 
25096 amit.gupta 1295
		throw new Exception();
24635 amit.gupta 1296
 
1297
	}
1298
 
1299
	public void dryRunOutSchemeReco() throws Exception {
1300
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1301
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1302
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1303
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1304
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1305
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1306
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1307
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1308
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1309
		// Collections.reverse(allOrders);
1310
		// List<FofoOrder> allOrders =
24653 govind 1311
		// List<FofoOrder> allOrders =
24631 amit.gupta 1312
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1313
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1314
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1315
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1316
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1317
			float amountToRollback = 0;
24590 amit.gupta 1318
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1319
			orderItems.forEach(x -> {
24606 amit.gupta 1320
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1321
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1322
			});
24606 amit.gupta 1323
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1324
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1325
					String serialNumber = inventorySerialNumberEntry.getValue();
1326
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1327
					if (serialNumbersConsidered.contains(serialNumber)) {
1328
						// This will rollback scheme for differenct orders for same serial
1329
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1330
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1331
								.filter(x -> x.getRolledBackTimestamp() == null
1332
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1333
								.collect(Collectors.toList());
1334
						Collections.reverse(sios);
1335
						for (SchemeInOut sio : sios) {
1336
							sio.setRolledBackTimestamp(LocalDateTime.now());
1337
							amountToRollback += sio.getAmount();
1338
							// sio.setSchemeType(SchemeType.OUT);
1339
							sio.setSerialNumber(serialNumber);
1340
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1341
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1342
							rolledbackSios.add(sio);
24623 amit.gupta 1343
						}
24635 amit.gupta 1344
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1345
					} else {
1346
						serialNumbersConsidered.add(serialNumber);
1347
						List<Integer> schemesConsidered = new ArrayList<>();
1348
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1349
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1350
								.filter(x -> x.getRolledBackTimestamp() == null
1351
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1352
								.collect(Collectors.toList());
1353
						Collections.reverse(sios);
1354
						for (SchemeInOut sio : sios) {
1355
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1356
								schemesConsidered.add(sio.getSchemeId());
1357
								continue;
1358
							}
1359
							sio.setRolledBackTimestamp(LocalDateTime.now());
1360
							amountToRollback += sio.getAmount();
1361
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1362
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1363
							sio.setSerialNumber(serialNumber);
1364
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1365
							rolledbackSios.add(sio);
1366
						}
24615 amit.gupta 1367
					}
24631 amit.gupta 1368
 
24604 amit.gupta 1369
				}
24590 amit.gupta 1370
			}
24631 amit.gupta 1371
			if (amountToRollback > 0) {
1372
				UserWalletHistory uwh = new UserWalletHistory();
1373
				uwh.setAmount(Math.round(amountToRollback));
1374
				uwh.setDescription(description);
1375
				uwh.setTimestamp(LocalDateTime.now());
1376
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1377
				uwh.setReference(fofoOrder.getId());
1378
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1379
				uwh.setFofoId(fofoOrder.getFofoId());
1380
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1381
				userWalletHistory.add(uwh);
1382
			}
24590 amit.gupta 1383
		});
24598 amit.gupta 1384
 
24592 amit.gupta 1385
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1386
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1387
						"Timestamp"),
1388
				userWalletHistory.stream()
1389
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1390
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1391
						.collect(Collectors.toList()));
1392
 
1393
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1394
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1395
						"Rolledback"),
1396
				rolledbackSios.stream()
1397
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1398
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1399
						.collect(Collectors.toList()));
1400
 
25043 amit.gupta 1401
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1402
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1403
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1404
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1405
 
25267 amit.gupta 1406
		throw new Exception();
24590 amit.gupta 1407
	}
24615 amit.gupta 1408
 
24611 amit.gupta 1409
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1410
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1411
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1412
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1413
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1414
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1415
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1416
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1417
		references.stream().forEach(reference -> {
1418
			FofoOrder fofoOrder = null;
1419
			try {
1420
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1421
			} catch (Exception e) {
1422
 
24611 amit.gupta 1423
			}
1424
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1425
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1426
			float amountToRollback = 0;
1427
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1428
			orderItems.forEach(x -> {
1429
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1430
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1431
			});
1432
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1433
				List<SchemeInOut> sios = schemeInOutRepository
1434
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1435
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1436
						.collect(Collectors.toList());
1437
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1438
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1439
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1440
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1441
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1442
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1443
					if (outList.size() > 1) {
1444
 
24611 amit.gupta 1445
					}
1446
				}
1447
				uwh.setAmount(Math.round(amountToRollback));
1448
				uwh.setDescription(description);
1449
				uwh.setTimestamp(LocalDateTime.now());
1450
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1451
				uwh.setReference(fofoOrder.getId());
1452
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1453
				uwh.setFofoId(fofoOrder.getFofoId());
1454
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1455
				userWalletHistory.add(uwh);
1456
			}
1457
		});
24615 amit.gupta 1458
 
24611 amit.gupta 1459
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1460
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1461
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1462
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1463
						.collect(Collectors.toList()));
1464
 
24611 amit.gupta 1465
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1466
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1467
						"Rolledback"),
1468
				rolledbackSios.stream()
24615 amit.gupta 1469
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1470
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1471
						.collect(Collectors.toList()));
1472
 
24623 amit.gupta 1473
		Utils.sendMailWithAttachments(googleMailSender,
1474
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1475
				"Partner Excess Amount", "PFA",
1476
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1477
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1478
 
24628 amit.gupta 1479
		throw new Exception();
24615 amit.gupta 1480
 
24611 amit.gupta 1481
	}
24615 amit.gupta 1482
 
26945 amit.gupta 1483
	public void sendDailySalesNotificationToPartner(Integer fofoIdInt) throws Exception {
25927 amit.gupta 1484
 
24653 govind 1485
		LocalDateTime now = LocalDateTime.now();
25837 amit.gupta 1486
		LocalDateTime from = now.with(LocalTime.MIN);
25925 amit.gupta 1487
		String timeString = "Today %s";
25927 amit.gupta 1488
		// Send yesterday's report
27007 amit.gupta 1489
		/*
1490
		 * if (now.getHour() < 13) { timeString = "Yesterday %s"; from =
1491
		 * now.minusDays(1).; now = from.with(LocalTime.MAX);
1492
		 * 
1493
		 * }
1494
		 */
24855 amit.gupta 1495
		List<Integer> fofoIds = null;
25043 amit.gupta 1496
		if (fofoIdInt == null) {
1497
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1498
					.collect(Collectors.toList());
24856 amit.gupta 1499
		} else {
24855 amit.gupta 1500
			fofoIds = Arrays.asList(fofoIdInt);
1501
		}
25912 amit.gupta 1502
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
24683 amit.gupta 1503
 
25865 amit.gupta 1504
		Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1505
				null);
1506
		Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
26945 amit.gupta 1507
 
1508
		Map<Integer, Double> spPartnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1509
				true);
1510
 
1511
		Map<Integer, Double> spPartner3DaysOrderValMap = fofoOrderItemRepository
1512
				.selectSumAmountGroupByRetailer(from.minusDays(3), now, 0, true);
26941 amit.gupta 1513
		Map<Integer, Long> spPartnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
1514
 
26945 amit.gupta 1515
		Map<Integer, Double> partnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1516
				false);
26941 amit.gupta 1517
		Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, false);
26945 amit.gupta 1518
 
25865 amit.gupta 1519
		Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
1520
		for (int fofoId : fofoIds) {
1521
			SaleTargetReportModel model = new SaleTargetReportModel();
25927 amit.gupta 1522
			model.setInsuranceSale(
1523
					partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
25865 amit.gupta 1524
			model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
26941 amit.gupta 1525
			model.setSmartphoneSale(spPartnerOrderValMap.containsKey(fofoId) ? spPartnerOrderValMap.get(fofoId) : 0);
1526
			model.setSmartphoneQty(spPartnerOrderQtyMap.containsKey(fofoId) ? spPartnerOrderQtyMap.get(fofoId) : 0);
1527
			model.setTotalSale(partnerOrderValMap.containsKey(fofoId) ? partnerOrderValMap.get(fofoId) : 0);
1528
			model.setTotalQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
26945 amit.gupta 1529
			model.setPast3daysSale(
1530
					spPartner3DaysOrderValMap.containsKey(fofoId) ? spPartner3DaysOrderValMap.get(fofoId) : 0);
25880 amit.gupta 1531
			model.setFofoId(fofoId);
25865 amit.gupta 1532
			saleTargetReportModelMap.put(fofoId, model);
1533
		}
25880 amit.gupta 1534
 
26945 amit.gupta 1535
		Map<Integer, FofoReportingModel> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
24653 govind 1536
		for (Integer fofoId : fofoIds) {
25865 amit.gupta 1537
			SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
25821 amit.gupta 1538
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1539
			sendNotificationModel.setCampaignName("Sales update alert");
25884 tejbeer 1540
			sendNotificationModel.setTitle("Sale Update");
25927 amit.gupta 1541
			sendNotificationModel
1542
					.setMessage(String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1543
							model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1544
							String.format(timeString, now.format(timeFormatter))));
25821 amit.gupta 1545
			sendNotificationModel.setType("url");
26564 amit.gupta 1546
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25821 amit.gupta 1547
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1548
			sendNotificationModel.setMessageType(MessageType.notification);
25872 tejbeer 1549
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1550
			sendNotificationModel.setUserIds(Arrays.asList(userId));
25854 amit.gupta 1551
			notificationService.sendNotification(sendNotificationModel);
24653 govind 1552
		}
26945 amit.gupta 1553
		// String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap,
1554
		// saleTargetReportModelMap);
1555
		String statewiseSaleReport = this.getStateWiseSales(saleTargetReportModelMap, partnerSalesHeadersMap);
25837 amit.gupta 1556
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com",
26945 amit.gupta 1557
				"niranjan.kala@smartdukaan.com", "up.singh@smartdukaan.com", "sm@smartdukaan.com" };
25837 amit.gupta 1558
 
25912 amit.gupta 1559
		String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
26945 amit.gupta 1560
		// this.sendMailOfHtmlFomat("amit.gupta@smartukaan.com", saleReport, cc,
1561
		// subject);
1562
		this.sendMailOfHtmlFormat("amit.gupta@smartdukaan.com", statewiseSaleReport, cc, "Statewise" + subject);
24653 govind 1563
	}
1564
 
25865 amit.gupta 1565
	public static class SaleTargetReportModel {
1566
		private double totalSale;
26941 amit.gupta 1567
		private long totalQty;
26945 amit.gupta 1568
		private double past3daysSale;
25880 amit.gupta 1569
		private int fofoId;
1570
 
1571
		public int getFofoId() {
1572
			return fofoId;
1573
		}
1574
 
1575
		public void setFofoId(int fofoId) {
1576
			this.fofoId = fofoId;
1577
		}
1578
 
25865 amit.gupta 1579
		private double smartphoneSale;
1580
		private long smartphoneQty;
1581
		private double insuranceSale;
1582
		private long insruanceQty;
1583
 
26941 amit.gupta 1584
		public long getTotalQty() {
1585
			return totalQty;
1586
		}
1587
 
1588
		public void setTotalQty(long totalQty) {
1589
			this.totalQty = totalQty;
1590
		}
1591
 
26945 amit.gupta 1592
		public double getPast3daysSale() {
1593
			return past3daysSale;
1594
		}
1595
 
1596
		public void setPast3daysSale(double past3daysSale) {
1597
			this.past3daysSale = past3daysSale;
1598
		}
1599
 
25865 amit.gupta 1600
		@Override
1601
		public int hashCode() {
1602
			final int prime = 31;
1603
			int result = 1;
25880 amit.gupta 1604
			result = prime * result + fofoId;
25865 amit.gupta 1605
			result = prime * result + (int) (insruanceQty ^ (insruanceQty >>> 32));
1606
			long temp;
1607
			temp = Double.doubleToLongBits(insuranceSale);
1608
			result = prime * result + (int) (temp ^ (temp >>> 32));
1609
			result = prime * result + (int) (smartphoneQty ^ (smartphoneQty >>> 32));
1610
			temp = Double.doubleToLongBits(smartphoneSale);
1611
			result = prime * result + (int) (temp ^ (temp >>> 32));
26941 amit.gupta 1612
			result = prime * result + (int) (totalQty ^ (totalQty >>> 32));
25865 amit.gupta 1613
			temp = Double.doubleToLongBits(totalSale);
1614
			result = prime * result + (int) (temp ^ (temp >>> 32));
1615
			return result;
1616
		}
1617
 
1618
		@Override
1619
		public boolean equals(Object obj) {
1620
			if (this == obj)
1621
				return true;
1622
			if (obj == null)
1623
				return false;
1624
			if (getClass() != obj.getClass())
1625
				return false;
1626
			SaleTargetReportModel other = (SaleTargetReportModel) obj;
25880 amit.gupta 1627
			if (fofoId != other.fofoId)
1628
				return false;
25865 amit.gupta 1629
			if (insruanceQty != other.insruanceQty)
1630
				return false;
1631
			if (Double.doubleToLongBits(insuranceSale) != Double.doubleToLongBits(other.insuranceSale))
1632
				return false;
1633
			if (smartphoneQty != other.smartphoneQty)
1634
				return false;
1635
			if (Double.doubleToLongBits(smartphoneSale) != Double.doubleToLongBits(other.smartphoneSale))
1636
				return false;
26941 amit.gupta 1637
			if (totalQty != other.totalQty)
1638
				return false;
25865 amit.gupta 1639
			if (Double.doubleToLongBits(totalSale) != Double.doubleToLongBits(other.totalSale))
1640
				return false;
1641
			return true;
1642
		}
1643
 
1644
		public double getTotalSale() {
1645
			return totalSale;
1646
		}
1647
 
1648
		public void setTotalSale(double totalSale) {
1649
			this.totalSale = totalSale;
1650
		}
1651
 
1652
		public double getSmartphoneSale() {
1653
			return smartphoneSale;
1654
		}
1655
 
1656
		public void setSmartphoneSale(double smartphoneSale) {
1657
			this.smartphoneSale = smartphoneSale;
1658
		}
1659
 
1660
		public long getSmartphoneQty() {
1661
			return smartphoneQty;
1662
		}
1663
 
1664
		public void setSmartphoneQty(long smartphoneQty) {
1665
			this.smartphoneQty = smartphoneQty;
1666
		}
1667
 
1668
		public double getInsuranceSale() {
1669
			return insuranceSale;
1670
		}
1671
 
1672
		public void setInsuranceSale(double insuranceSale) {
1673
			this.insuranceSale = insuranceSale;
1674
		}
1675
 
1676
		public long getInsruanceQty() {
1677
			return insruanceQty;
1678
		}
1679
 
1680
		public void setInsruanceQty(long insruanceQty) {
1681
			this.insruanceQty = insruanceQty;
1682
		}
1683
 
1684
		@Override
1685
		public String toString() {
26945 amit.gupta 1686
			return "SaleTargetReportModel [totalSale=" + totalSale + ", totalQty=" + totalQty + ", past3daysSale="
1687
					+ past3daysSale + ", fofoId=" + fofoId + ", smartphoneSale=" + smartphoneSale + ", smartphoneQty="
1688
					+ smartphoneQty + ", insuranceSale=" + insuranceSale + ", insruanceQty=" + insruanceQty + "]";
25865 amit.gupta 1689
		}
1690
 
1691
	}
1692
 
26945 amit.gupta 1693
	private String getStateWiseSales(Map<Integer, SaleTargetReportModel> saleTargetReportModelMap,
1694
			Map<Integer, FofoReportingModel> partnerSalesHeadersMap) throws Exception {
26940 amit.gupta 1695
		List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
26945 amit.gupta 1696
		Map<String, List<Integer>> stateMap = stores.stream().collect(Collectors
1697
				.groupingBy(x -> x.getCode().substring(0, 2), Collectors.mapping(x -> x.getId(), Collectors.toList())));
26940 amit.gupta 1698
		List<List<Serializable>> stateWiseSales = new ArrayList<>();
1699
		for (Map.Entry<String, List<Integer>> stateMapEntry : stateMap.entrySet()) {
26945 amit.gupta 1700
			long totalQty = stateMapEntry.getValue().stream()
1701
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getTotalQty()));
1702
			double totalSale = stateMapEntry.getValue().stream()
1703
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getTotalSale()));
1704
			long smartPhoneQty = stateMapEntry.getValue().stream()
1705
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getSmartphoneQty()));
1706
			double smartPhoneSale = stateMapEntry.getValue().stream()
1707
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getSmartphoneSale()));
1708
			stateWiseSales
1709
					.add(Arrays.asList(stateMapEntry.getKey(), smartPhoneQty, smartPhoneSale, totalQty, totalSale));
26940 amit.gupta 1710
		}
1711
		StringBuilder sb = new StringBuilder();
26945 amit.gupta 1712
		sb.append("<html><body>");
1713
		sb.append("<p>Statewise Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
26940 amit.gupta 1714
		sb.append("<tbody>\n" + "	    <tr>"
1715
				+ "	    					<th style='border:1px solid black;padding: 5px'>State</th>"
26941 amit.gupta 1716
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
1717
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Value</th>"
1718
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Qty</th>"
1719
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Value</th>"
26940 amit.gupta 1720
				+ "	    				</tr>");
1721
		for (List<Serializable> stateSale : stateWiseSales) {
1722
			sb.append("<tr>");
1723
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(0) + "</td>");
1724
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(1) + "</td>");
1725
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(2) + "</td>");
26941 amit.gupta 1726
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(3) + "</td>");
1727
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(4) + "</td>");
26940 amit.gupta 1728
			sb.append("</tr>");
1729
		}
26945 amit.gupta 1730
		sb.append("</tbody></table><br><br>");
25872 tejbeer 1731
 
26945 amit.gupta 1732
		sb.append("<p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 1733
		sb.append("<tbody>\n" + "	    				<tr>\n"
26945 amit.gupta 1734
				+ "	    					<th style='border:1px solid black;padding: 5px'>Code</th>"
1735
				+ "	    					<th style='border:1px solid black;padding: 5px'>Business Name</th>"
1736
				+ "	    					<th style='border:1px solid black;padding: 5px'>Regional Manager</th>"
1737
				+ "	    					<th style='border:1px solid black;padding: 5px'>Territory Manager</th>"
1738
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>"
1739
				+ "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>"
1740
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
24653 govind 1741
				+ "	    				</tr>");
26945 amit.gupta 1742
 
1743
		List<Integer> sortedPartnerSalesHeaders = partnerSalesHeadersMap.values().stream()
26947 amit.gupta 1744
				.sorted(Comparator.comparing(FofoReportingModel::getCode)
1745
						.thenComparing(FofoReportingModel::getRegionalManager)
26948 amit.gupta 1746
						.thenComparing(FofoReportingModel::getTerritoryManager))
26945 amit.gupta 1747
				.map(FofoReportingModel::getFofoId).collect(Collectors.toList());
25927 amit.gupta 1748
		for (Integer fofoId : sortedPartnerSalesHeaders) {
27007 amit.gupta 1749
			if (saleTargetReportModelMap.get(fofoId).getPast3daysSale() == 0) {
26947 amit.gupta 1750
				sb.append("<tr style='background-color:red'>");
1751
			} else {
26945 amit.gupta 1752
				sb.append("<tr>");
1753
			}
1754
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getCode()
25880 amit.gupta 1755
					+ "</td>");
1756
			sb.append("<td style='border:1px solid black;padding: 5px'>"
27007 amit.gupta 1757
					+ partnerSalesHeadersMap.get(fofoId).getBusinessName() + "</td>");
1758
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1759
					+ partnerSalesHeadersMap.get(fofoId).getRegionalManager() + "</td>");
1760
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1761
					+ partnerSalesHeadersMap.get(fofoId).getTerritoryManager() + "</td>");
1762
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1763
					+ saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
25880 amit.gupta 1764
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1765
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
25880 amit.gupta 1766
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1767
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
25865 amit.gupta 1768
			sb.append("</tr>");
24653 govind 1769
		}
24683 amit.gupta 1770
 
26945 amit.gupta 1771
		sb.append("</tr>");
1772
 
1773
		sb.append("</body></html>");
1774
 
1775
		return sb.toString();
24653 govind 1776
	}
24841 govind 1777
 
26945 amit.gupta 1778
	private void sendMailOfHtmlFormat(String email, String body, String cc[], String subject)
24841 govind 1779
			throws MessagingException, ProfitMandiBusinessException, IOException {
1780
		MimeMessage message = mailSender.createMimeMessage();
1781
		MimeMessageHelper helper = new MimeMessageHelper(message);
1782
		helper.setSubject(subject);
1783
		helper.setText(body, true);
1784
		helper.setTo(email);
1785
		if (cc != null) {
1786
			helper.setCc(cc);
1787
		}
1788
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1789
		helper.setFrom(senderAddress);
1790
		mailSender.send(message);
1791
	}
25300 tejbeer 1792
 
25351 tejbeer 1793
	public void sendNotification() throws Exception {
25300 tejbeer 1794
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1795
		if (!pushNotifications.isEmpty()) {
1796
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1797
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1798
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1799
						.selectById(pushNotification.getNotificationCampaignid());
1800
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1801
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1802
 
1803
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1804
						SimpleCampaignParams.class);
1805
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1806
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1807
				JSONObject json = new JSONObject();
25351 tejbeer 1808
				json.put("to", device.getFcmId());
25300 tejbeer 1809
				JSONObject jsonObj = new JSONObject();
1810
				jsonObj.put("message", campaign.getMessage());
1811
				jsonObj.put("title", campaign.getTitle());
1812
				jsonObj.put("type", campaign.getType());
1813
				jsonObj.put("url", result_url);
1814
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1815
				jsonObj.put("image", campaign.getImageUrl());
1816
				jsonObj.put("largeIcon", "large_icon");
1817
				jsonObj.put("smallIcon", "small_icon");
1818
				jsonObj.put("vibrate", 1);
1819
				jsonObj.put("pid", pushNotification.getId());
1820
				jsonObj.put("sound", 1);
1821
				jsonObj.put("priority", "high");
1822
				json.put("data", jsonObj);
27007 amit.gupta 1823
				LOGGER.info("request {}", json);
25351 tejbeer 1824
				try {
1825
					CloseableHttpClient client = HttpClients.createDefault();
1826
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1827
 
25351 tejbeer 1828
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1829
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1830
					StringEntity entity = new StringEntity(json.toString());
1831
					httpPost.setEntity(entity);
1832
					CloseableHttpResponse response = client.execute(httpPost);
1833
					LOGGER.info("response" + response);
25300 tejbeer 1834
 
25351 tejbeer 1835
					if (response.getStatusLine().getStatusCode() == 200) {
1836
						pushNotification.setSentTimestamp(LocalDateTime.now());
1837
					} else {
25356 tejbeer 1838
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 1839
						LOGGER.info("message" + "not sent");
26945 amit.gupta 1840
						response.toString();
25351 tejbeer 1841
					}
25300 tejbeer 1842
 
25351 tejbeer 1843
				} catch (Exception e) {
1844
					e.printStackTrace();
26443 amit.gupta 1845
					pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
26436 amit.gupta 1846
					LOGGER.info("message " + "not sent " + e.getMessage());
25300 tejbeer 1847
				}
1848
			}
1849
		}
1850
	}
1851
 
25553 amit.gupta 1852
	public void grouping() throws Exception {
25609 amit.gupta 1853
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
1854
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
1855
		System.out.println(String.join("\t",
1856
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 1857
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
26963 amit.gupta 1858
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers(false);
25609 amit.gupta 1859
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 1860
			if (priceDropIMEI.getPartnerId() == 0)
1861
				continue;
25609 amit.gupta 1862
			HashSet<String> imeis = new HashSet<>();
1863
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
1864
			imeis.add(priceDropIMEI.getImei());
1865
			List<InventoryItem> inventoryItems = inventoryItemRepository
1866
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 1867
			if (inventoryItems.size() == 0) {
1868
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 1869
				continue;
25612 amit.gupta 1870
			}
25609 amit.gupta 1871
			InventoryItem inventoryItem = inventoryItems.get(0);
1872
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
1873
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
1874
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
1875
				// check if pricedrop has been rolled out
1876
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
1877
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
1878
				if (uwh.size() > 0) {
25615 amit.gupta 1879
					Item item = itemRepository.selectById(inventoryItem.getItemId());
26945 amit.gupta 1880
					System.out.println(String.join("\t", Arrays.asList(priceDropIMEI.getImei(),
1881
							inventoryItem.getItemId() + "", item.getBrand(), item.getModelName(), item.getModelNumber(),
1882
							inventoryItem.getFofoId() + "", customRetailer.getBusinessName(),
1883
							inventoryItem.getCreateTimestamp().format(dtf), priceDrop.getAffectedOn().format(dtf),
1884
							priceDropIMEI.getUpdateTimestamp().format(dtf),
1885
							inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getAutoPartnerPayout() + "",
1886
							inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
25609 amit.gupta 1887
				}
1888
			}
1889
		}
25503 amit.gupta 1890
	}
25694 amit.gupta 1891
 
1892
	public void testToffee() throws Exception {
25846 amit.gupta 1893
		LOGGER.info("Insurance Sum Summary --- {}",
1894
				insurancePolicyRepository.selectAmountSumGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
1895
		LOGGER.info("Insurance Qty Summary --- {}",
1896
				insurancePolicyRepository.selectQtyGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
25854 amit.gupta 1897
		LOGGER.info("SmartPhone Amount Summary --- {}",
25856 amit.gupta 1898
				fofoOrderItemRepository.selectSumAmountGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25854 amit.gupta 1899
		LOGGER.info("Smartphone Qty Summary --- {}",
1900
				fofoOrderItemRepository.selectQtyGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25800 tejbeer 1901
		// LOGGER.info("{}", toffeeService.getAuthToken());
25846 amit.gupta 1902
		/*
1903
		 * LOGGER.info("{}", toffeeService.getProducts()); // LOGGER.info("{}",
1904
		 * toffeeService.getPincodes("36103000PR")); PremiumCalculationRequestModel pcrm
1905
		 * = new PremiumCalculationRequestModel(); pcrm.setProductDetails("36103000PR");
1906
		 * // pcrm.setProductDetails("36103000PR");
1907
		 * pcrm.setDurations(Arrays.asList("3 Months", "6 Months", "1 Year"));
1908
		 * pcrm.setSumInsured("15000");
1909
		 * System.out.println(toffeeService.getPremiumCalculation(pcrm));
1910
		 */
25694 amit.gupta 1911
	}
1912
 
1913
	public void schemeRollback(List<String> schemeIds) throws Exception {
1914
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 1915
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 1916
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1917
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
1918
		for (SchemeInOut sio : schemeInOuts) {
1919
			Scheme scheme = schemesMap.get(sio.getSchemeId());
1920
			if (scheme.getType().equals(SchemeType.IN)) {
1921
 
1922
			} else if (scheme.getType().equals(SchemeType.OUT)) {
1923
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
1924
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
1925
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
1926
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
1927
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
1928
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
1929
					sio.setRolledBackTimestamp(LocalDateTime.now());
1930
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 1931
					String rollbackReason = "Scheme reversed for "
1932
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 1933
							+ fofoOrder.getInvoiceNumber();
1934
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
26945 amit.gupta 1935
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason,
1936
							LocalDateTime.now());
25694 amit.gupta 1937
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
1938
							rollbackReason);
1939
				}
1940
			}
1941
		}
25721 tejbeer 1942
		// throw new Exception();
25694 amit.gupta 1943
	}
25721 tejbeer 1944
 
1945
	public void checkfocusedModelInPartnerStock() throws Exception {
1946
 
1947
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1948
				.collect(Collectors.toList());
1949
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
1950
		for (Integer fofoId : fofoIds) {
1951
			if (!focusedModelShortageReportMap.containsKey(fofoId)) {
1952
				focusedModelShortageReportMap.put(fofoId, new ArrayList<>());
1953
			}
1954
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1955
			Map<Integer, Integer> processingOrderMap = null;
1956
			Map<Integer, Integer> catalogIdAndQtyMap = null;
1957
			Map<Integer, Integer> grnPendingOrdersMap = null;
1958
 
1959
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1960
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1961
 
1962
			if (!currentInventorySnapshot.isEmpty()) {
1963
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1964
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1965
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1966
 
1967
			}
1968
 
1969
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1970
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1971
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1972
			if (!grnPendingOrders.isEmpty()) {
1973
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1974
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1975
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1976
 
1977
			}
1978
 
1979
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1980
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1981
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1982
			if (!processingOrder.isEmpty()) {
1983
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1984
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1985
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1986
 
1987
			}
1988
 
25800 tejbeer 1989
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1990
					.collect(Collectors.toList());
1991
 
1992
			List<Integer> focusedModelCatalogId = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
1993
					.collect(Collectors.toList());
1994
			Map<String, Object> equalsMap = new HashMap<>();
1995
			equalsMap.put("categoryId", 10006);
1996
			equalsMap.put("brand", brands);
1997
 
1998
			Map<String, List<?>> notEqualsMap = new HashMap<>();
1999
 
2000
			Map<String, Object> equalsJoinMap = new HashMap<>();
2001
			equalsJoinMap.put("catalogId", focusedModelCatalogId);
2002
 
2003
			Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
2004
 
2005
			List<Integer> catalogIds = itemRepository
2006
					.selectItems(FocusedModel.class, "catalogItemId", "catalogId", equalsMap, notEqualsMap,
2007
							equalsJoinMap, notEqualsJoinMap, "minimumQty")
2008
					.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
2009
 
2010
			Map<Integer, Integer> focusedCatalogIdAndQtyMap = focusedModelRepository.selectByCatalogIdsl(catalogIds)
2011
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getMinimumQty()));
2012
 
2013
			/*
2014
			 * Map<Integer, Integer> focusedCatalogIdAndQtyMap =
2015
			 * focusedModelRepository.selectAll().stream() .collect(Collectors.toMap(x ->
2016
			 * x.getCatalogId(), x -> x.getMinimumQty()));
2017
			 */
2018
 
25721 tejbeer 2019
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
2020
 
2021
			for (Map.Entry<Integer, Integer> entry : focusedCatalogIdAndQtyMap.entrySet()) {
2022
				int inStockQty = 0;
2023
				int processingQty = 0;
2024
				int grnPendingQty = 0;
2025
				if (processingOrderMap != null) {
2026
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
2027
							: processingOrderMap.get(entry.getKey());
2028
 
2029
				}
2030
				if (grnPendingOrdersMap != null) {
2031
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
2032
							: grnPendingOrdersMap.get(entry.getKey());
2033
 
2034
				}
2035
				if (catalogIdAndQtyMap != null) {
2036
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
2037
							: catalogIdAndQtyMap.get(entry.getKey());
2038
 
2039
				}
2040
				int totalQty = processingQty + grnPendingQty + inStockQty;
2041
 
2042
				if (totalQty < entry.getValue()) {
2043
 
2044
					int shortageQty = entry.getValue() - totalQty;
2045
					List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
2046
 
2047
					FocusedModelShortageModel fm = new FocusedModelShortageModel();
2048
					fm.setFofoId(fofoId);
2049
					fm.setStoreName(customRetailer.getBusinessName());
2050
 
2051
					fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
2052
					fm.setShortageQty(shortageQty);
2053
 
2054
					focusedModelShortageReportMap.get(fofoId).add(fm);
2055
				}
2056
 
2057
			}
2058
			List<FocusedModelShortageModel> focusedModelShortageModel = focusedModelShortageReportMap.get(fofoId);
2059
 
2060
			if (!focusedModelShortageModel.isEmpty()) {
2061
				String subject = "Stock Alert";
2062
				String messageText = this.getMessage(focusedModelShortageModel);
2063
 
25732 tejbeer 2064
				this.sendMailWithAttachments(subject, messageText, customRetailer.getEmail());
25721 tejbeer 2065
				String notificationMessage = this.getNotificationMessage(focusedModelShortageModel);
2066
 
2067
				LOGGER.info("notificationMessage" + notificationMessage);
2068
 
25872 tejbeer 2069
				SendNotificationModel sendNotificationModel = new SendNotificationModel();
2070
				sendNotificationModel.setCampaignName("Stock Alert");
2071
				sendNotificationModel.setTitle("Alert");
2072
				sendNotificationModel.setMessage(notificationMessage);
2073
				sendNotificationModel.setType("url");
26564 amit.gupta 2074
				sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25872 tejbeer 2075
				sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2076
				sendNotificationModel.setMessageType(MessageType.notification);
25732 tejbeer 2077
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
25872 tejbeer 2078
				sendNotificationModel.setUserIds(Arrays.asList(userId));
2079
				notificationService.sendNotification(sendNotificationModel);
25721 tejbeer 2080
 
2081
			}
25732 tejbeer 2082
 
25721 tejbeer 2083
		}
25800 tejbeer 2084
		if (!focusedModelShortageReportMap.isEmpty())
25721 tejbeer 2085
 
25800 tejbeer 2086
		{
2087
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
2088
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
25837 amit.gupta 2089
			Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 2090
 
25800 tejbeer 2091
			focusedModelShortageReportMap.entrySet().forEach(x -> {
2092
				storeGuyMap.entrySet().forEach(y -> {
2093
 
2094
					if (y.getValue().contains(x.getKey())) {
2095
						if (!emailRowsMap.containsKey(y.getKey())) {
2096
							emailRowsMap.put(y.getKey(), new ArrayList<>());
2097
						}
2098
						List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays
2099
								.asList(r.getFofoId(), r.getStoreName(), r.getItemName(), r.getShortageQty()))
2100
								.collect(Collectors.toList());
2101
						emailRowsMap.get(y.getKey()).addAll(fms);
2102
 
25721 tejbeer 2103
					}
2104
 
25800 tejbeer 2105
				});
25721 tejbeer 2106
 
2107
			});
2108
 
25800 tejbeer 2109
			List<String> headers = Arrays.asList("Partner Id", "Partner Name", "Model Name", "Shortage Qty");
25837 amit.gupta 2110
			emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 2111
 
25800 tejbeer 2112
				ByteArrayOutputStream baos = null;
2113
				try {
25837 amit.gupta 2114
					baos = FileUtil.getCSVByteStream(headers, entry.getValue());
25800 tejbeer 2115
				} catch (Exception e2) {
2116
					e2.printStackTrace();
2117
				}
25837 amit.gupta 2118
				String[] sendToArray = new String[] { entry.getKey() };
25800 tejbeer 2119
				try {
2120
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
2121
							new ByteArrayResource(baos.toByteArray()));
2122
				} catch (Exception e1) { // TODO Auto-generated catch block
2123
					e1.printStackTrace();
2124
				}
25721 tejbeer 2125
 
25800 tejbeer 2126
			});
2127
		}
25721 tejbeer 2128
	}
2129
 
2130
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2131
		StringBuilder sb = new StringBuilder();
2132
		sb.append("Focused Model Shortage in Your Stock : \n");
2133
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
2134
 
2135
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
2136
			sb.append(String.format("%n", ""));
2137
		}
2138
		return sb.toString();
2139
	}
2140
 
2141
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
2142
		MimeMessage message = mailSender.createMimeMessage();
2143
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
2144
 
2145
		helper.setSubject(subject);
2146
		helper.setText(messageText, true);
2147
		helper.setTo(email);
26032 amit.gupta 2148
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smatdukaan Alerts");
25721 tejbeer 2149
		helper.setFrom(senderAddress);
2150
		mailSender.send(message);
2151
 
2152
	}
2153
 
2154
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2155
		StringBuilder sb = new StringBuilder();
2156
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
2157
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2158
		sb.append("<tbody>\n" + "	    				<tr>\n"
2159
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
2160
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
2161
				+ "	    				</tr>");
2162
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
2163
 
2164
			sb.append("<tr>");
2165
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
2166
 
2167
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
2168
 
2169
			sb.append("</tr>");
2170
 
2171
		}
2172
 
2173
		sb.append("</tbody></table></body></html>");
2174
 
2175
		return sb.toString();
2176
	}
2177
 
25927 amit.gupta 2178
	public void notifyLead() throws Exception {
2179
		List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(LocalDateTime.now().minusDays(15),
2180
				LocalDateTime.now().plusHours(4));
2181
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2182
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
25936 amit.gupta 2183
		System.out.printf("authUserEmailMap - %s", authUserEmailMap);
25927 amit.gupta 2184
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2185
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2186
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25936 amit.gupta 2187
 
2188
		System.out.printf("dtrEmailMap - %s", dtrEmailMap);
26790 tejbeer 2189
 
25927 amit.gupta 2190
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
2191
 
2192
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2193
			int authId = authUserEmail.getKey();
2194
			String email = authUserEmail.getValue();
2195
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2196
		}
25929 amit.gupta 2197
		System.out.println(authUserKeyMap);
2198
		System.out.println(leadsToNotify);
26790 tejbeer 2199
 
25927 amit.gupta 2200
		String templateMessage = "Lead followup for %s %s, %s is due by %s";
2201
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
2202
		for (Lead lead : leadsToNotify) {
2203
			if (authUserKeyMap.get(lead.getAuthId()) == null) {
2204
				continue;
2205
			}
2206
			String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(),
25941 amit.gupta 2207
					lead.getAddress(), timeFormatter.format(lead.getLeadActivity().getSchelduleTimestamp()));
25927 amit.gupta 2208
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2209
			sendNotificationModel.setCampaignName("Lead Reminder");
2210
			sendNotificationModel.setTitle("Leads followup Reminder");
2211
			sendNotificationModel.setMessage(notificationMessage);
2212
			sendNotificationModel.setType("url");
26564 amit.gupta 2213
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2214
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2215
			sendNotificationModel.setMessageType(MessageType.reminder);
26320 tejbeer 2216
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAssignTo())));
25929 amit.gupta 2217
			System.out.println(sendNotificationModel);
25927 amit.gupta 2218
			notificationService.sendNotification(sendNotificationModel);
2219
		}
2220
	}
26945 amit.gupta 2221
 
25927 amit.gupta 2222
	public void notifyVisits() throws Exception {
26945 amit.gupta 2223
		List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository
2224
				.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
25927 amit.gupta 2225
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2226
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
2227
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2228
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2229
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
2230
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26945 amit.gupta 2231
 
25927 amit.gupta 2232
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2233
			int authId = authUserEmail.getKey();
2234
			String email = authUserEmail.getValue();
2235
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2236
		}
2237
		String visitTemplate = "Planned visit to franchisee %s is due by %s";
2238
		String followupTemplate = "Lead followup for franchisee %s is due by %s";
2239
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
2240
		for (FranchiseeVisit visit : franchiseeVisits) {
2241
			if (authUserKeyMap.containsKey(visit.getAuthId())) {
2242
				continue;
2243
			}
2244
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2245
			String message = null;
26945 amit.gupta 2246
			if (visit.getFranchiseActivityId() == 0) {
2247
				message = String.format(visitTemplate, visit.getPartnerName(),
2248
						timeFormatter.format(visit.getSchelduleTimestamp()));
2249
				sendNotificationModel.setCampaignName("Franchisee visit Reminder");
25927 amit.gupta 2250
			} else {
26945 amit.gupta 2251
				message = String.format(followupTemplate, visit.getPartnerName(),
2252
						timeFormatter.format(visit.getSchelduleTimestamp()));
25927 amit.gupta 2253
				sendNotificationModel.setCampaignName("Franchisee followup Reminder");
2254
			}
2255
			sendNotificationModel.setMessage(message);
2256
			sendNotificationModel.setType("url");
26482 tejbeer 2257
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2258
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2259
			sendNotificationModel.setMessageType(MessageType.reminder);
2260
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
2261
			notificationService.sendNotification(sendNotificationModel);
2262
		}
25910 amit.gupta 2263
	}
25982 amit.gupta 2264
 
26283 tejbeer 2265
	public void ticketClosed() throws Exception {
2266
 
2267
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTicketsWithStatus(ActivityType.RESOLVED);
2268
		for (Ticket ticket : tickets) {
2269
			if (ticket.getUpdateTimestamp().toLocalDate().isBefore(LocalDate.now().minusDays(7))) {
2270
				ticket.setCloseTimestamp(LocalDateTime.now());
2271
				ticket.setLastActivity(ActivityType.RESOLVED_ACCEPTED);
2272
				ticket.setUpdateTimestamp(LocalDateTime.now());
2273
				ticketRepository.persist(ticket);
2274
			}
2275
		}
2276
 
2277
	}
2278
 
26790 tejbeer 2279
	public void checkValidateReferral() throws Exception {
2280
 
2281
		List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
26791 tejbeer 2282
		LOGGER.info("referrals" + referrals);
26790 tejbeer 2283
		if (!referrals.isEmpty()) {
2284
			String subject = "Referral Request";
2285
			String messageText = this.getMessageForReferral(referrals);
2286
 
26792 tejbeer 2287
			MimeMessage message = mailSender.createMimeMessage();
2288
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
2289
			String[] email = { "kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com" };
2290
			helper.setSubject(subject);
2291
			helper.setText(messageText, true);
2292
			helper.setTo(email);
2293
			InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
2294
			helper.setFrom(senderAddress);
2295
			mailSender.send(message);
2296
 
26790 tejbeer 2297
		}
2298
	}
2299
 
2300
	private String getMessageForReferral(List<Refferal> referrals) {
2301
		StringBuilder sb = new StringBuilder();
2302
		sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>"
2303
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2304
		sb.append("<tbody>\n" + "	    				<tr>\n"
2305
				+ "	    					<th style='border:1px solid black;padding: 5px'>RefereeName</th>\n"
2306
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referee Email</th>\n"
2307
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referral Name</th>\n"
2308
				+ "	    					<th style='border:1px solid black;padding: 5px'>Refferal Mobile</th>\n"
2309
				+ "	    					<th style='border:1px solid black;padding: 5px'>city</th>\n"
2310
				+ "	    					<th style='border:1px solid black;padding: 5px'>state</th>\n"
2311
				+ "	    				</tr>");
2312
		for (Refferal entry : referrals) {
2313
 
2314
			sb.append("<tr>");
2315
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
2316
 
2317
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
2318
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
2319
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
2320
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
2321
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
2322
 
2323
			sb.append("</tr>");
2324
 
2325
		}
2326
 
2327
		sb.append("</tbody></table></body></html>");
2328
 
2329
		return sb.toString();
2330
	}
2331
 
26418 tejbeer 2332
}