Subversion Repositories SmartDukaan

Rev

Rev 26957 | Rev 26988 | 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
 
758
		private ScheduledTasks getOuterType() {
759
			return ScheduledTasks.this;
760
		}
761
 
762
		@Override
763
		public int hashCode() {
764
			final int prime = 31;
765
			int result = 1;
766
			result = prime * result + getOuterType().hashCode();
767
			result = prime * result + ((businessName == null) ? 0 : businessName.hashCode());
768
			result = prime * result + ((code == null) ? 0 : code.hashCode());
769
			result = prime * result + fofoId;
770
			result = prime * result + ((regionalManager == null) ? 0 : regionalManager.hashCode());
771
			result = prime * result + ((territoryManager == null) ? 0 : territoryManager.hashCode());
772
			return result;
773
		}
774
 
775
		@Override
776
		public boolean equals(Object obj) {
777
			if (this == obj)
778
				return true;
779
			if (obj == null)
780
				return false;
781
			if (getClass() != obj.getClass())
782
				return false;
783
			FofoReportingModel other = (FofoReportingModel) obj;
784
			if (!getOuterType().equals(other.getOuterType()))
785
				return false;
786
			if (businessName == null) {
787
				if (other.businessName != null)
788
					return false;
789
			} else if (!businessName.equals(other.businessName))
790
				return false;
791
			if (code == null) {
792
				if (other.code != null)
793
					return false;
794
			} else if (!code.equals(other.code))
795
				return false;
796
			if (fofoId != other.fofoId)
797
				return false;
798
			if (regionalManager == null) {
799
				if (other.regionalManager != null)
800
					return false;
801
			} else if (!regionalManager.equals(other.regionalManager))
802
				return false;
803
			if (territoryManager == null) {
804
				if (other.territoryManager != null)
805
					return false;
806
			} else if (!territoryManager.equals(other.territoryManager))
807
				return false;
808
			return true;
809
		}
810
 
811
		public int getFofoId() {
812
			return fofoId;
813
		}
814
 
815
		public void setFofoId(int fofoId) {
816
			this.fofoId = fofoId;
817
		}
818
 
819
	}
820
 
24271 amit.gupta 821
	public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
24277 amit.gupta 822
		LocalDate yesterDay = LocalDate.now().minusDays(1);
25267 amit.gupta 823
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
23929 amit.gupta 824
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
825
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25351 tejbeer 826
 
26957 amit.gupta 827
		List<String> headers = Arrays.asList("Code", "Outlet name", "State Manager", "Teritory/Team Lead",
26945 amit.gupta 828
				"Wallet Amount", "In Stock Amount", "Activated Stock", "Return In Transit Stock", "Unbilled Amount",
829
				"Grn Pending Amount", "Min Investment", "Investment Amount", "Investment Short", "Unbilled Qty",
830
				"Short Days");
25837 amit.gupta 831
		List<List<?>> rows = new ArrayList<>();
25895 amit.gupta 832
		Map<Integer, List<?>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 833
 
26945 amit.gupta 834
		Map<Integer, FofoReportingModel> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25598 amit.gupta 835
 
26945 amit.gupta 836
		Map<Integer, Integer> shortDaysMap = partnerDailyInvestmentRepository
837
				.selectAll(LocalDate.now().withDayOfMonth(1), LocalDate.now()).stream().collect(Collectors.groupingBy(
838
						x -> x.getFofoId(), Collectors.summingInt(x -> x.getShortPercentage() > 10 ? 1 : 0)));
839
 
24002 amit.gupta 840
		for (FofoStore fofoStore : fofoStores) {
26376 amit.gupta 841
			int fofoId = fofoStore.getId();
26945 amit.gupta 842
			PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 1);
25598 amit.gupta 843
			partnerDailyInvestment.setDate(yesterDay);
26945 amit.gupta 844
 
25598 amit.gupta 845
			try {
846
				partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
26945 amit.gupta 847
				shortDaysMap.put(fofoId,
848
						shortDaysMap.get(fofoId) + (partnerDailyInvestment.getShortPercentage() > 10 ? 1 : 0));
25598 amit.gupta 849
			} catch (Exception e) {
850
				// ignore the exceptions during persist
851
			}
852
 
24002 amit.gupta 853
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
25837 amit.gupta 854
			if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
24002 amit.gupta 855
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
856
				continue;
857
			}
26945 amit.gupta 858
			FofoReportingModel reportingModel = partnerIdSalesHeaderMap.get(fofoStore.getId());
859
			List<Serializable> row = new ArrayList<>();
860
			row.addAll(Arrays.asList(reportingModel.getCode(), reportingModel.getBusinessName(),
861
					reportingModel.getRegionalManager(), reportingModel.getTerritoryManager()));
25927 amit.gupta 862
			row.addAll(
863
					Arrays.asList(partnerDailyInvestment.getWalletAmount(), partnerDailyInvestment.getInStockAmount(),
26945 amit.gupta 864
							partnerDailyInvestment.getActivatedStockAmount() == 0 ? "-"
865
									: "(" + partnerDailyInvestment.getActivatedStockAmount() + ")",
25927 amit.gupta 866
							0, partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(),
867
							partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(),
26945 amit.gupta 868
							partnerDailyInvestment.getShortInvestment(), partnerDailyInvestment.getUnbilledQty(),
869
							shortDaysMap.get(fofoId)));
25837 amit.gupta 870
			partnerRowsMap.put(fofoStore.getId(), row);
24002 amit.gupta 871
			rows.add(row);
872
 
23929 amit.gupta 873
		}
25312 amit.gupta 874
 
24271 amit.gupta 875
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25598 amit.gupta 876
 
25927 amit.gupta 877
		if (sendTo == null) {
25895 amit.gupta 878
			for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
879
				List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x))
880
						.filter(x -> x != null).collect(Collectors.toList());
881
				ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
882
				String[] sendToArray = new String[] { storeGuyEntry.getKey() };
883
				Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
884
						fileName, new ByteArrayResource(baos.toByteArray()));
885
			}
886
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
26376 amit.gupta 887
					"prakash.rai@smartdukaan.com", "amit.gupta@shop2020.in");
25341 amit.gupta 888
		}
25312 amit.gupta 889
 
25604 amit.gupta 890
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
891
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
25609 amit.gupta 892
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
893
				fileName, new ByteArrayResource(baos.toByteArray()));
24271 amit.gupta 894
 
23929 amit.gupta 895
	}
24177 govind 896
 
26945 amit.gupta 897
	private Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() {
25598 amit.gupta 898
		Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
899
 
900
		List<Position> positions = positionRepository
901
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
902
		Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream()
903
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
904
		Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
905
		for (Position position : positions) {
906
			List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
25609 amit.gupta 907
			if (crList == null)
908
				continue;
25598 amit.gupta 909
			for (CustomRetailer cr : crList) {
910
				if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
911
					partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
912
				}
913
				SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
914
				AuthUser authUser = authUsersMap.get(position.getAuthUserId());
26945 amit.gupta 915
				if (authUser == null) {
26059 amit.gupta 916
					continue;
917
				}
25598 amit.gupta 918
				String name = authUser.getFirstName() + " " + authUser.getLastName();
919
				if (position.getEscalationType().equals(EscalationType.L1)) {
920
					saleRoles.getL1().add(name);
921
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
922
					saleRoles.getL2().add(name);
923
				}
924
			}
925
		}
25837 amit.gupta 926
 
927
		Set<CustomRetailer> allCrList = new HashSet<>();
928
		for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
929
			allCrList.addAll(cr);
930
		}
931
 
932
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
933
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
934
 
26945 amit.gupta 935
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
25837 amit.gupta 936
 
937
		for (CustomRetailer cr : allCrList) {
938
			FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
25927 amit.gupta 939
			if (fofoStore == null) {
25870 amit.gupta 940
				LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
941
				continue;
942
			}
26945 amit.gupta 943
			String code = fofoStore.getCode();
944
			// String storeName = "SmartDukaan-" +
945
			// fofoStore.getCode().replaceAll("[a-zA-Z]", "");
25837 amit.gupta 946
			String businessName = cr.getBusinessName();
947
			try {
948
				String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
949
				String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
26945 amit.gupta 950
				FofoReportingModel reportingModel = new FofoReportingModel();
951
				reportingModel.setBusinessName(businessName);
952
				reportingModel.setCode(code);
953
				reportingModel.setFofoId(fofoStore.getId());
954
				reportingModel.setRegionalManager(stateManager);
955
				reportingModel.setTerritoryManager(territoryManager);
956
				partnerIdSalesHeadersMap.put(fofoStore.getId(), reportingModel);
25837 amit.gupta 957
			} catch (Exception e) {
958
				LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
959
			}
960
		}
961
		return partnerIdSalesHeadersMap;
962
 
25598 amit.gupta 963
	}
964
 
24271 amit.gupta 965
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 966
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 967
	}
968
 
25312 amit.gupta 969
	public void sendTargetVsSalesReport(List<String> sendTo) throws Exception {
24177 govind 970
 
25312 amit.gupta 971
		if (sendTo == null) {
25827 amit.gupta 972
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
973
					"amit.gupta@shop2020.in", "amod.sen@smartdukaan.com", "prakash.rai@smartdukaan.com");
25312 amit.gupta 974
		}
25837 amit.gupta 975
		Map<Integer, List<Serializable>> partnerSalesTargetRowsMap = targetService.getDailySaleReportVsTarget();
25315 amit.gupta 976
 
26945 amit.gupta 977
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
24177 govind 978
 
26945 amit.gupta 979
		List<String> headers = Arrays.asList("Code", "Firm Name", "State Manager", "Teritory Manager",
25837 amit.gupta 980
				"Current Category", "Target Value", "Target Achieved", "Achived Percentage", "Remaining Target",
981
				"Today's Target", "Today's achievement");
25609 amit.gupta 982
 
25837 amit.gupta 983
		List<List<?>> rows = new ArrayList<>();
984
		Map<Integer, List<? extends Serializable>> partnerRowMap = new HashMap<>();
985
		for (Map.Entry<Integer, List<Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap.entrySet()) {
26945 amit.gupta 986
			FofoReportingModel fofoReportingModel = partnerIdSalesHeadersMap.get(partnerSalesTargetRowEntry.getKey());
987
			if (fofoReportingModel == null) {
25837 amit.gupta 988
				LOGGER.warn("Could not find headers for partner ID - {}", partnerSalesTargetRowEntry.getKey());
26945 amit.gupta 989
				continue;
25315 amit.gupta 990
			}
26945 amit.gupta 991
			List<Serializable> row = Arrays.asList(fofoReportingModel.getCode(), fofoReportingModel.getBusinessName(),
992
					fofoReportingModel.getRegionalManager(), fofoReportingModel.getTerritoryManager());
25837 amit.gupta 993
			row.addAll(partnerSalesTargetRowEntry.getValue());
994
			partnerRowMap.put(partnerSalesTargetRowEntry.getKey(), row);
995
			rows.add(row);
24177 govind 996
		}
25503 amit.gupta 997
 
25318 amit.gupta 998
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25894 amit.gupta 999
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
1000
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25827 amit.gupta 1001
			if (storeGuyEntry.getValue().size() == 0)
1002
				continue;
25927 amit.gupta 1003
			List<List<?>> storeGuyRows = storeGuyEntry.getValue().stream().filter(x -> partnerRowMap.containsKey(x))
1004
					.map(x -> partnerRowMap.get(x)).collect(Collectors.toList());
25827 amit.gupta 1005
			ByteArrayOutputStream authUserStream = FileUtil.getCSVByteStream(headers, storeGuyRows);
1006
			Attachment attache = new Attachment(fileName, new ByteArrayResource(authUserStream.toByteArray()));
1007
			System.out.println(storeGuyEntry.getValue());
1008
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
1009
					"Franchise Stock Report", "PFA", attache);
1010
		}
24240 amit.gupta 1011
 
25312 amit.gupta 1012
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1013
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
1014
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
1015
				new ByteArrayResource(baos.toByteArray()));
24174 govind 1016
	}
24683 amit.gupta 1017
 
24697 amit.gupta 1018
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 1019
 
1020
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
1021
				"itemstockageing.xml");
24708 amit.gupta 1022
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 1023
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 1024
		Attachment attachment = new Attachment(
25445 amit.gupta 1025
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 1026
		Attachment attachment1 = new Attachment(
25445 amit.gupta 1027
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 1028
 
25609 amit.gupta 1029
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
1030
				attachment);
1031
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
1032
				"Itemwise Pending indent", "PFA", attachment1);
1033
 
25598 amit.gupta 1034
		// Reports to be sent to mapped partners
25597 amit.gupta 1035
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 1036
 
1037
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 1038
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 1039
			if (storeGuyEntry.getValue().size() == 0)
1040
				continue;
25418 amit.gupta 1041
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
1042
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
1043
					"focostockreport.xml", params);
1044
			Attachment attache = new Attachment(
25609 amit.gupta 1045
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 1046
			System.out.println(storeGuyEntry.getValue());
25609 amit.gupta 1047
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
1048
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 1049
		}
25503 amit.gupta 1050
 
24681 amit.gupta 1051
	}
24533 govind 1052
 
24697 amit.gupta 1053
	public void sendAgeingReport() throws Exception {
25807 amit.gupta 1054
		sendAgeingReport("kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com",
26862 amit.gupta 1055
				"hemant.kaura@smartdukaan.com");
24697 amit.gupta 1056
	}
1057
 
24533 govind 1058
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 1059
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 1060
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 1061
			priceDropService.priceDropStatus(priceDrop.getId());
1062
		}
1063
	}
23929 amit.gupta 1064
 
24542 amit.gupta 1065
	public void walletmismatch() throws Exception {
1066
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 1067
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 1068
		System.out.println(pdis.size());
24542 amit.gupta 1069
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 1070
			int fofoId = pdi.getFofoId();
24542 amit.gupta 1071
			for (PartnerDailyInvestment investment : Lists
1072
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 1073
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 1074
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 1075
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 1076
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
1077
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 1078
 
24542 amit.gupta 1079
			}
24549 amit.gupta 1080
		}
24542 amit.gupta 1081
 
1082
	}
1083
 
1084
	public void gst() throws Exception {
24548 amit.gupta 1085
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
1086
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
1087
		for (FofoOrder fofoOrder : fofoOrders) {
1088
			int retailerAddressId = retailerRegisteredAddressRepository
1089
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 1090
 
1091
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
1092
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1093
			Integer stateId = null;
1094
			if (customerAddress.getState().equals(retailerAddress.getState())) {
1095
				try {
1096
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
1097
				} catch (Exception e) {
1098
					LOGGER.error("Unable to get state rates");
1099
				}
1100
			}
1101
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1102
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 1103
 
1104
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
26929 amit.gupta 1105
			List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
24542 amit.gupta 1106
			if (stateId != null) {
26929 amit.gupta 1107
				itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
24542 amit.gupta 1108
			} else {
26929 amit.gupta 1109
				itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(itemIds);
24542 amit.gupta 1110
			}
1111
 
24548 amit.gupta 1112
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 1113
				if (stateId == null) {
1114
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
1115
				} else {
1116
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
1117
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
1118
				}
1119
				fofoOrderItemRepository.persist(foi);
1120
			}
1121
		}
24548 amit.gupta 1122
 
24542 amit.gupta 1123
	}
1124
 
24580 amit.gupta 1125
	public void schemewalletmismatch() {
1126
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 1127
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 1128
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 1129
			// reconcileOrders(dateTime);
1130
			// reconcileRecharges(dateTime);
24580 amit.gupta 1131
			dateToReconcile = dateToReconcile.plusDays(1);
1132
		}
1133
	}
1134
 
1135
	private void reconcileSchemes(LocalDate date) {
1136
		LocalDateTime startDate = date.atStartOfDay();
1137
		LocalDateTime endDate = startDate.plusDays(1);
1138
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
1139
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 1140
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
1141
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 1142
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 1143
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
1144
				WalletReferenceType.SCHEME_OUT);
1145
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
1146
				walletReferenceTypes);
1147
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
1148
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 1149
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 1150
 
1151
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
1152
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1153
 
1154
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
1155
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1156
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
1157
 
1158
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
1159
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1160
 
1161
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
1162
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
1163
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
1164
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
1165
 
1166
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
26092 amit.gupta 1167
 
24587 amit.gupta 1168
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
1169
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
1170
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
1171
				} else {
1172
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
1173
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
1174
				}
1175
			}
24590 amit.gupta 1176
			Map<Integer, Integer> userWalletMap = userWalletRepository
1177
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
1178
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1179
 
24587 amit.gupta 1180
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
1181
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
1182
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
1183
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1184
				if (diff > 5) {
1185
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1186
				}
1187
			}
24580 amit.gupta 1188
		}
24587 amit.gupta 1189
 
24580 amit.gupta 1190
	}
24590 amit.gupta 1191
 
24592 amit.gupta 1192
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1193
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1194
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1195
 
24592 amit.gupta 1196
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1197
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1198
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1199
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1200
		Set<String> serialNumbersConsidered = new HashSet<>();
1201
 
25096 amit.gupta 1202
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1203
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1204
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1205
 
24683 amit.gupta 1206
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1207
		purchases.stream().forEach(purchase -> {
1208
			float amountToRollback = 0;
1209
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1210
					+ purchase.getPurchaseReference();
1211
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1212
					.stream().filter(ii -> ii.getSerialNumber() != null)
1213
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1214
			if (inventorySerialNumberMap.size() > 0) {
1215
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1216
					String serialNumber = inventorySerialNumberEntry.getValue();
1217
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1218
					if (serialNumbersConsidered.contains(serialNumber)) {
1219
						// This will rollback scheme for differenct orders for same serial
1220
						List<SchemeInOut> sios = schemeInOutRepository
1221
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1222
								.filter(x -> x.getRolledBackTimestamp() == null
1223
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1224
								.collect(Collectors.toList());
1225
						Collections.reverse(sios);
1226
						for (SchemeInOut sio : sios) {
1227
							sio.setRolledBackTimestamp(LocalDateTime.now());
1228
							amountToRollback += sio.getAmount();
1229
							// sio.setSchemeType(SchemeType.OUT);
1230
							sio.setSerialNumber(serialNumber);
1231
							rolledbackSios.add(sio);
1232
						}
1233
						description = description.concat(" " + serialNumber + " ");
1234
					} else {
1235
						serialNumbersConsidered.add(serialNumber);
1236
						List<Integer> schemesConsidered = new ArrayList<>();
1237
						List<SchemeInOut> sios = schemeInOutRepository
1238
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1239
								.filter(x -> x.getRolledBackTimestamp() == null
1240
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1241
								.collect(Collectors.toList());
1242
						Collections.reverse(sios);
1243
						for (SchemeInOut sio : sios) {
1244
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1245
								schemesConsidered.add(sio.getSchemeId());
1246
								continue;
1247
							}
1248
							sio.setRolledBackTimestamp(LocalDateTime.now());
1249
							amountToRollback += sio.getAmount();
1250
							// sio.setSchemeType(SchemeType.OUT);
1251
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1252
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1253
							sio.setReference(purchase.getId());
24635 amit.gupta 1254
							rolledbackSios.add(sio);
1255
						}
1256
					}
1257
 
1258
				}
1259
			}
1260
			if (amountToRollback > 0) {
24683 amit.gupta 1261
				// Address address =
1262
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1263
				UserWalletHistory uwh = new UserWalletHistory();
1264
				uwh.setAmount(Math.round(amountToRollback));
1265
				uwh.setDescription(description);
1266
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1267
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1268
				uwh.setReference(purchase.getId());
1269
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1270
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1271
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1272
				userWalletHistory.add(uwh);
1273
			}
1274
		});
1275
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1276
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1277
						"Timestamp"),
1278
				userWalletHistory.stream()
1279
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1280
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1281
						.collect(Collectors.toList()));
1282
 
1283
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1284
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1285
						"Created", "Rolledback"),
24635 amit.gupta 1286
				rolledbackSios.stream()
24681 amit.gupta 1287
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1288
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1289
						.collect(Collectors.toList()));
1290
 
25043 amit.gupta 1291
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1292
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1293
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1294
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1295
 
25096 amit.gupta 1296
		throw new Exception();
24635 amit.gupta 1297
 
1298
	}
1299
 
1300
	public void dryRunOutSchemeReco() throws Exception {
1301
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1302
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1303
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1304
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1305
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1306
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1307
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1308
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1309
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1310
		// Collections.reverse(allOrders);
1311
		// List<FofoOrder> allOrders =
24653 govind 1312
		// List<FofoOrder> allOrders =
24631 amit.gupta 1313
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1314
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1315
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1316
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1317
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1318
			float amountToRollback = 0;
24590 amit.gupta 1319
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1320
			orderItems.forEach(x -> {
24606 amit.gupta 1321
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1322
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1323
			});
24606 amit.gupta 1324
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1325
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1326
					String serialNumber = inventorySerialNumberEntry.getValue();
1327
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1328
					if (serialNumbersConsidered.contains(serialNumber)) {
1329
						// This will rollback scheme for differenct orders for same serial
1330
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1331
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1332
								.filter(x -> x.getRolledBackTimestamp() == null
1333
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1334
								.collect(Collectors.toList());
1335
						Collections.reverse(sios);
1336
						for (SchemeInOut sio : sios) {
1337
							sio.setRolledBackTimestamp(LocalDateTime.now());
1338
							amountToRollback += sio.getAmount();
1339
							// sio.setSchemeType(SchemeType.OUT);
1340
							sio.setSerialNumber(serialNumber);
1341
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1342
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1343
							rolledbackSios.add(sio);
24623 amit.gupta 1344
						}
24635 amit.gupta 1345
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1346
					} else {
1347
						serialNumbersConsidered.add(serialNumber);
1348
						List<Integer> schemesConsidered = new ArrayList<>();
1349
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1350
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1351
								.filter(x -> x.getRolledBackTimestamp() == null
1352
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1353
								.collect(Collectors.toList());
1354
						Collections.reverse(sios);
1355
						for (SchemeInOut sio : sios) {
1356
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1357
								schemesConsidered.add(sio.getSchemeId());
1358
								continue;
1359
							}
1360
							sio.setRolledBackTimestamp(LocalDateTime.now());
1361
							amountToRollback += sio.getAmount();
1362
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1363
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1364
							sio.setSerialNumber(serialNumber);
1365
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1366
							rolledbackSios.add(sio);
1367
						}
24615 amit.gupta 1368
					}
24631 amit.gupta 1369
 
24604 amit.gupta 1370
				}
24590 amit.gupta 1371
			}
24631 amit.gupta 1372
			if (amountToRollback > 0) {
1373
				UserWalletHistory uwh = new UserWalletHistory();
1374
				uwh.setAmount(Math.round(amountToRollback));
1375
				uwh.setDescription(description);
1376
				uwh.setTimestamp(LocalDateTime.now());
1377
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1378
				uwh.setReference(fofoOrder.getId());
1379
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1380
				uwh.setFofoId(fofoOrder.getFofoId());
1381
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1382
				userWalletHistory.add(uwh);
1383
			}
24590 amit.gupta 1384
		});
24598 amit.gupta 1385
 
24592 amit.gupta 1386
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1387
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1388
						"Timestamp"),
1389
				userWalletHistory.stream()
1390
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1391
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1392
						.collect(Collectors.toList()));
1393
 
1394
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1395
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1396
						"Rolledback"),
1397
				rolledbackSios.stream()
1398
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1399
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1400
						.collect(Collectors.toList()));
1401
 
25043 amit.gupta 1402
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1403
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1404
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1405
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1406
 
25267 amit.gupta 1407
		throw new Exception();
24590 amit.gupta 1408
	}
24615 amit.gupta 1409
 
24611 amit.gupta 1410
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1411
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1412
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1413
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1414
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1415
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1416
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1417
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1418
		references.stream().forEach(reference -> {
1419
			FofoOrder fofoOrder = null;
1420
			try {
1421
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1422
			} catch (Exception e) {
1423
 
24611 amit.gupta 1424
			}
1425
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1426
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1427
			float amountToRollback = 0;
1428
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1429
			orderItems.forEach(x -> {
1430
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1431
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1432
			});
1433
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1434
				List<SchemeInOut> sios = schemeInOutRepository
1435
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1436
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1437
						.collect(Collectors.toList());
1438
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1439
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1440
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1441
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1442
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1443
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1444
					if (outList.size() > 1) {
1445
 
24611 amit.gupta 1446
					}
1447
				}
1448
				uwh.setAmount(Math.round(amountToRollback));
1449
				uwh.setDescription(description);
1450
				uwh.setTimestamp(LocalDateTime.now());
1451
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1452
				uwh.setReference(fofoOrder.getId());
1453
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1454
				uwh.setFofoId(fofoOrder.getFofoId());
1455
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1456
				userWalletHistory.add(uwh);
1457
			}
1458
		});
24615 amit.gupta 1459
 
24611 amit.gupta 1460
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1461
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1462
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1463
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1464
						.collect(Collectors.toList()));
1465
 
24611 amit.gupta 1466
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1467
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1468
						"Rolledback"),
1469
				rolledbackSios.stream()
24615 amit.gupta 1470
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1471
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1472
						.collect(Collectors.toList()));
1473
 
24623 amit.gupta 1474
		Utils.sendMailWithAttachments(googleMailSender,
1475
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1476
				"Partner Excess Amount", "PFA",
1477
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1478
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1479
 
24628 amit.gupta 1480
		throw new Exception();
24615 amit.gupta 1481
 
24611 amit.gupta 1482
	}
24615 amit.gupta 1483
 
26945 amit.gupta 1484
	public void sendDailySalesNotificationToPartner(Integer fofoIdInt) throws Exception {
25927 amit.gupta 1485
 
24653 govind 1486
		LocalDateTime now = LocalDateTime.now();
25837 amit.gupta 1487
		LocalDateTime from = now.with(LocalTime.MIN);
25925 amit.gupta 1488
		String timeString = "Today %s";
25927 amit.gupta 1489
		// Send yesterday's report
1490
		if (now.getHour() < 13) {
25925 amit.gupta 1491
			timeString = "Yesterday %s";
25910 amit.gupta 1492
			from = now.minusDays(1);
1493
			now = from.with(LocalTime.MAX);
25927 amit.gupta 1494
 
25910 amit.gupta 1495
		}
24855 amit.gupta 1496
		List<Integer> fofoIds = null;
25043 amit.gupta 1497
		if (fofoIdInt == null) {
1498
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1499
					.collect(Collectors.toList());
24856 amit.gupta 1500
		} else {
24855 amit.gupta 1501
			fofoIds = Arrays.asList(fofoIdInt);
1502
		}
25912 amit.gupta 1503
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
24683 amit.gupta 1504
 
25865 amit.gupta 1505
		Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1506
				null);
1507
		Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
26945 amit.gupta 1508
 
1509
		Map<Integer, Double> spPartnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1510
				true);
1511
 
1512
		Map<Integer, Double> spPartner3DaysOrderValMap = fofoOrderItemRepository
1513
				.selectSumAmountGroupByRetailer(from.minusDays(3), now, 0, true);
26941 amit.gupta 1514
		Map<Integer, Long> spPartnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
1515
 
26945 amit.gupta 1516
		Map<Integer, Double> partnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1517
				false);
26941 amit.gupta 1518
		Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, false);
26945 amit.gupta 1519
 
25865 amit.gupta 1520
		Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
1521
		for (int fofoId : fofoIds) {
1522
			SaleTargetReportModel model = new SaleTargetReportModel();
25927 amit.gupta 1523
			model.setInsuranceSale(
1524
					partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
25865 amit.gupta 1525
			model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
26941 amit.gupta 1526
			model.setSmartphoneSale(spPartnerOrderValMap.containsKey(fofoId) ? spPartnerOrderValMap.get(fofoId) : 0);
1527
			model.setSmartphoneQty(spPartnerOrderQtyMap.containsKey(fofoId) ? spPartnerOrderQtyMap.get(fofoId) : 0);
1528
			model.setTotalSale(partnerOrderValMap.containsKey(fofoId) ? partnerOrderValMap.get(fofoId) : 0);
1529
			model.setTotalQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
26945 amit.gupta 1530
			model.setPast3daysSale(
1531
					spPartner3DaysOrderValMap.containsKey(fofoId) ? spPartner3DaysOrderValMap.get(fofoId) : 0);
25880 amit.gupta 1532
			model.setFofoId(fofoId);
25865 amit.gupta 1533
			saleTargetReportModelMap.put(fofoId, model);
1534
		}
25880 amit.gupta 1535
 
26945 amit.gupta 1536
		Map<Integer, FofoReportingModel> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
24653 govind 1537
		for (Integer fofoId : fofoIds) {
25865 amit.gupta 1538
			SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
25821 amit.gupta 1539
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1540
			sendNotificationModel.setCampaignName("Sales update alert");
25884 tejbeer 1541
			sendNotificationModel.setTitle("Sale Update");
25927 amit.gupta 1542
			sendNotificationModel
1543
					.setMessage(String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1544
							model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1545
							String.format(timeString, now.format(timeFormatter))));
25821 amit.gupta 1546
			sendNotificationModel.setType("url");
26564 amit.gupta 1547
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25821 amit.gupta 1548
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1549
			sendNotificationModel.setMessageType(MessageType.notification);
25872 tejbeer 1550
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1551
			sendNotificationModel.setUserIds(Arrays.asList(userId));
25854 amit.gupta 1552
			notificationService.sendNotification(sendNotificationModel);
24653 govind 1553
		}
26945 amit.gupta 1554
		// String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap,
1555
		// saleTargetReportModelMap);
1556
		String statewiseSaleReport = this.getStateWiseSales(saleTargetReportModelMap, partnerSalesHeadersMap);
25837 amit.gupta 1557
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com",
26945 amit.gupta 1558
				"niranjan.kala@smartdukaan.com", "up.singh@smartdukaan.com", "sm@smartdukaan.com" };
25837 amit.gupta 1559
 
25912 amit.gupta 1560
		String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
26945 amit.gupta 1561
		// this.sendMailOfHtmlFomat("amit.gupta@smartukaan.com", saleReport, cc,
1562
		// subject);
1563
		this.sendMailOfHtmlFormat("amit.gupta@smartdukaan.com", statewiseSaleReport, cc, "Statewise" + subject);
24653 govind 1564
	}
1565
 
25865 amit.gupta 1566
	public static class SaleTargetReportModel {
1567
		private double totalSale;
26941 amit.gupta 1568
		private long totalQty;
26945 amit.gupta 1569
		private double past3daysSale;
25880 amit.gupta 1570
		private int fofoId;
1571
 
1572
		public int getFofoId() {
1573
			return fofoId;
1574
		}
1575
 
1576
		public void setFofoId(int fofoId) {
1577
			this.fofoId = fofoId;
1578
		}
1579
 
25865 amit.gupta 1580
		private double smartphoneSale;
1581
		private long smartphoneQty;
1582
		private double insuranceSale;
1583
		private long insruanceQty;
1584
 
26941 amit.gupta 1585
		public long getTotalQty() {
1586
			return totalQty;
1587
		}
1588
 
1589
		public void setTotalQty(long totalQty) {
1590
			this.totalQty = totalQty;
1591
		}
1592
 
26945 amit.gupta 1593
		public double getPast3daysSale() {
1594
			return past3daysSale;
1595
		}
1596
 
1597
		public void setPast3daysSale(double past3daysSale) {
1598
			this.past3daysSale = past3daysSale;
1599
		}
1600
 
25865 amit.gupta 1601
		@Override
1602
		public int hashCode() {
1603
			final int prime = 31;
1604
			int result = 1;
25880 amit.gupta 1605
			result = prime * result + fofoId;
25865 amit.gupta 1606
			result = prime * result + (int) (insruanceQty ^ (insruanceQty >>> 32));
1607
			long temp;
1608
			temp = Double.doubleToLongBits(insuranceSale);
1609
			result = prime * result + (int) (temp ^ (temp >>> 32));
1610
			result = prime * result + (int) (smartphoneQty ^ (smartphoneQty >>> 32));
1611
			temp = Double.doubleToLongBits(smartphoneSale);
1612
			result = prime * result + (int) (temp ^ (temp >>> 32));
26941 amit.gupta 1613
			result = prime * result + (int) (totalQty ^ (totalQty >>> 32));
25865 amit.gupta 1614
			temp = Double.doubleToLongBits(totalSale);
1615
			result = prime * result + (int) (temp ^ (temp >>> 32));
1616
			return result;
1617
		}
1618
 
1619
		@Override
1620
		public boolean equals(Object obj) {
1621
			if (this == obj)
1622
				return true;
1623
			if (obj == null)
1624
				return false;
1625
			if (getClass() != obj.getClass())
1626
				return false;
1627
			SaleTargetReportModel other = (SaleTargetReportModel) obj;
25880 amit.gupta 1628
			if (fofoId != other.fofoId)
1629
				return false;
25865 amit.gupta 1630
			if (insruanceQty != other.insruanceQty)
1631
				return false;
1632
			if (Double.doubleToLongBits(insuranceSale) != Double.doubleToLongBits(other.insuranceSale))
1633
				return false;
1634
			if (smartphoneQty != other.smartphoneQty)
1635
				return false;
1636
			if (Double.doubleToLongBits(smartphoneSale) != Double.doubleToLongBits(other.smartphoneSale))
1637
				return false;
26941 amit.gupta 1638
			if (totalQty != other.totalQty)
1639
				return false;
25865 amit.gupta 1640
			if (Double.doubleToLongBits(totalSale) != Double.doubleToLongBits(other.totalSale))
1641
				return false;
1642
			return true;
1643
		}
1644
 
1645
		public double getTotalSale() {
1646
			return totalSale;
1647
		}
1648
 
1649
		public void setTotalSale(double totalSale) {
1650
			this.totalSale = totalSale;
1651
		}
1652
 
1653
		public double getSmartphoneSale() {
1654
			return smartphoneSale;
1655
		}
1656
 
1657
		public void setSmartphoneSale(double smartphoneSale) {
1658
			this.smartphoneSale = smartphoneSale;
1659
		}
1660
 
1661
		public long getSmartphoneQty() {
1662
			return smartphoneQty;
1663
		}
1664
 
1665
		public void setSmartphoneQty(long smartphoneQty) {
1666
			this.smartphoneQty = smartphoneQty;
1667
		}
1668
 
1669
		public double getInsuranceSale() {
1670
			return insuranceSale;
1671
		}
1672
 
1673
		public void setInsuranceSale(double insuranceSale) {
1674
			this.insuranceSale = insuranceSale;
1675
		}
1676
 
1677
		public long getInsruanceQty() {
1678
			return insruanceQty;
1679
		}
1680
 
1681
		public void setInsruanceQty(long insruanceQty) {
1682
			this.insruanceQty = insruanceQty;
1683
		}
1684
 
1685
		@Override
1686
		public String toString() {
26945 amit.gupta 1687
			return "SaleTargetReportModel [totalSale=" + totalSale + ", totalQty=" + totalQty + ", past3daysSale="
1688
					+ past3daysSale + ", fofoId=" + fofoId + ", smartphoneSale=" + smartphoneSale + ", smartphoneQty="
1689
					+ smartphoneQty + ", insuranceSale=" + insuranceSale + ", insruanceQty=" + insruanceQty + "]";
25865 amit.gupta 1690
		}
1691
 
1692
	}
1693
 
26945 amit.gupta 1694
	private String getStateWiseSales(Map<Integer, SaleTargetReportModel> saleTargetReportModelMap,
1695
			Map<Integer, FofoReportingModel> partnerSalesHeadersMap) throws Exception {
26940 amit.gupta 1696
		List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
26945 amit.gupta 1697
		Map<String, List<Integer>> stateMap = stores.stream().collect(Collectors
1698
				.groupingBy(x -> x.getCode().substring(0, 2), Collectors.mapping(x -> x.getId(), Collectors.toList())));
26940 amit.gupta 1699
		List<List<Serializable>> stateWiseSales = new ArrayList<>();
1700
		for (Map.Entry<String, List<Integer>> stateMapEntry : stateMap.entrySet()) {
26945 amit.gupta 1701
			long totalQty = stateMapEntry.getValue().stream()
1702
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getTotalQty()));
1703
			double totalSale = stateMapEntry.getValue().stream()
1704
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getTotalSale()));
1705
			long smartPhoneQty = stateMapEntry.getValue().stream()
1706
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getSmartphoneQty()));
1707
			double smartPhoneSale = stateMapEntry.getValue().stream()
1708
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getSmartphoneSale()));
1709
			stateWiseSales
1710
					.add(Arrays.asList(stateMapEntry.getKey(), smartPhoneQty, smartPhoneSale, totalQty, totalSale));
26940 amit.gupta 1711
		}
1712
		StringBuilder sb = new StringBuilder();
26945 amit.gupta 1713
		sb.append("<html><body>");
1714
		sb.append("<p>Statewise Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
26940 amit.gupta 1715
		sb.append("<tbody>\n" + "	    <tr>"
1716
				+ "	    					<th style='border:1px solid black;padding: 5px'>State</th>"
26941 amit.gupta 1717
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
1718
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Value</th>"
1719
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Qty</th>"
1720
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Value</th>"
26940 amit.gupta 1721
				+ "	    				</tr>");
1722
		for (List<Serializable> stateSale : stateWiseSales) {
1723
			sb.append("<tr>");
1724
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(0) + "</td>");
1725
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(1) + "</td>");
1726
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(2) + "</td>");
26941 amit.gupta 1727
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(3) + "</td>");
1728
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(4) + "</td>");
26940 amit.gupta 1729
			sb.append("</tr>");
1730
		}
26945 amit.gupta 1731
		sb.append("</tbody></table><br><br>");
25872 tejbeer 1732
 
26945 amit.gupta 1733
		sb.append("<p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 1734
		sb.append("<tbody>\n" + "	    				<tr>\n"
26945 amit.gupta 1735
				+ "	    					<th style='border:1px solid black;padding: 5px'>Code</th>"
1736
				+ "	    					<th style='border:1px solid black;padding: 5px'>Business Name</th>"
1737
				+ "	    					<th style='border:1px solid black;padding: 5px'>Regional Manager</th>"
1738
				+ "	    					<th style='border:1px solid black;padding: 5px'>Territory Manager</th>"
1739
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>"
1740
				+ "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>"
1741
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
24653 govind 1742
				+ "	    				</tr>");
26945 amit.gupta 1743
 
1744
		List<Integer> sortedPartnerSalesHeaders = partnerSalesHeadersMap.values().stream()
26947 amit.gupta 1745
				.sorted(Comparator.comparing(FofoReportingModel::getCode)
1746
						.thenComparing(FofoReportingModel::getRegionalManager)
26948 amit.gupta 1747
						.thenComparing(FofoReportingModel::getTerritoryManager))
26945 amit.gupta 1748
				.map(FofoReportingModel::getFofoId).collect(Collectors.toList());
25927 amit.gupta 1749
		for (Integer fofoId : sortedPartnerSalesHeaders) {
26945 amit.gupta 1750
			if(saleTargetReportModelMap.get(fofoId).getPast3daysSale()==0) {
26947 amit.gupta 1751
				sb.append("<tr style='background-color:red'>");
1752
			} else {
26945 amit.gupta 1753
				sb.append("<tr>");
1754
			}
1755
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getCode()
25880 amit.gupta 1756
					+ "</td>");
26945 amit.gupta 1757
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getBusinessName()
25880 amit.gupta 1758
					+ "</td>");
26945 amit.gupta 1759
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getRegionalManager()
25880 amit.gupta 1760
					+ "</td>");
26945 amit.gupta 1761
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getTerritoryManager()
25880 amit.gupta 1762
					+ "</td>");
1763
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1764
					+ saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
25880 amit.gupta 1765
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1766
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
25880 amit.gupta 1767
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1768
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
25865 amit.gupta 1769
			sb.append("</tr>");
24653 govind 1770
		}
24683 amit.gupta 1771
 
26945 amit.gupta 1772
		sb.append("</tr>");
1773
 
1774
		sb.append("</body></html>");
1775
 
1776
		return sb.toString();
24653 govind 1777
	}
24841 govind 1778
 
26945 amit.gupta 1779
	private void sendMailOfHtmlFormat(String email, String body, String cc[], String subject)
24841 govind 1780
			throws MessagingException, ProfitMandiBusinessException, IOException {
1781
		MimeMessage message = mailSender.createMimeMessage();
1782
		MimeMessageHelper helper = new MimeMessageHelper(message);
1783
		helper.setSubject(subject);
1784
		helper.setText(body, true);
1785
		helper.setTo(email);
1786
		if (cc != null) {
1787
			helper.setCc(cc);
1788
		}
1789
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1790
		helper.setFrom(senderAddress);
1791
		mailSender.send(message);
1792
	}
25300 tejbeer 1793
 
25351 tejbeer 1794
	public void sendNotification() throws Exception {
25300 tejbeer 1795
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1796
		if (!pushNotifications.isEmpty()) {
1797
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1798
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1799
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1800
						.selectById(pushNotification.getNotificationCampaignid());
1801
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1802
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1803
 
1804
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1805
						SimpleCampaignParams.class);
1806
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1807
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1808
				JSONObject json = new JSONObject();
25351 tejbeer 1809
				json.put("to", device.getFcmId());
25300 tejbeer 1810
				JSONObject jsonObj = new JSONObject();
1811
				jsonObj.put("message", campaign.getMessage());
1812
				jsonObj.put("title", campaign.getTitle());
1813
				jsonObj.put("type", campaign.getType());
1814
				jsonObj.put("url", result_url);
1815
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1816
				jsonObj.put("image", campaign.getImageUrl());
1817
				jsonObj.put("largeIcon", "large_icon");
1818
				jsonObj.put("smallIcon", "small_icon");
1819
				jsonObj.put("vibrate", 1);
1820
				jsonObj.put("pid", pushNotification.getId());
1821
				jsonObj.put("sound", 1);
1822
				jsonObj.put("priority", "high");
1823
				json.put("data", jsonObj);
26957 amit.gupta 1824
				LOGGER.info("request {}",json);
25351 tejbeer 1825
				try {
1826
					CloseableHttpClient client = HttpClients.createDefault();
1827
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1828
 
25351 tejbeer 1829
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1830
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1831
					StringEntity entity = new StringEntity(json.toString());
1832
					httpPost.setEntity(entity);
1833
					CloseableHttpResponse response = client.execute(httpPost);
1834
					LOGGER.info("response" + response);
25300 tejbeer 1835
 
25351 tejbeer 1836
					if (response.getStatusLine().getStatusCode() == 200) {
1837
						pushNotification.setSentTimestamp(LocalDateTime.now());
1838
					} else {
25356 tejbeer 1839
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 1840
						LOGGER.info("message" + "not sent");
26945 amit.gupta 1841
						response.toString();
25351 tejbeer 1842
					}
25300 tejbeer 1843
 
25351 tejbeer 1844
				} catch (Exception e) {
1845
					e.printStackTrace();
26443 amit.gupta 1846
					pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
26436 amit.gupta 1847
					LOGGER.info("message " + "not sent " + e.getMessage());
25300 tejbeer 1848
				}
1849
			}
1850
		}
1851
	}
1852
 
25553 amit.gupta 1853
	public void grouping() throws Exception {
25609 amit.gupta 1854
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
1855
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
1856
		System.out.println(String.join("\t",
1857
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 1858
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
26963 amit.gupta 1859
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers(false);
25609 amit.gupta 1860
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 1861
			if (priceDropIMEI.getPartnerId() == 0)
1862
				continue;
25609 amit.gupta 1863
			HashSet<String> imeis = new HashSet<>();
1864
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
1865
			imeis.add(priceDropIMEI.getImei());
1866
			List<InventoryItem> inventoryItems = inventoryItemRepository
1867
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 1868
			if (inventoryItems.size() == 0) {
1869
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 1870
				continue;
25612 amit.gupta 1871
			}
25609 amit.gupta 1872
			InventoryItem inventoryItem = inventoryItems.get(0);
1873
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
1874
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
1875
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
1876
				// check if pricedrop has been rolled out
1877
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
1878
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
1879
				if (uwh.size() > 0) {
25615 amit.gupta 1880
					Item item = itemRepository.selectById(inventoryItem.getItemId());
26945 amit.gupta 1881
					System.out.println(String.join("\t", Arrays.asList(priceDropIMEI.getImei(),
1882
							inventoryItem.getItemId() + "", item.getBrand(), item.getModelName(), item.getModelNumber(),
1883
							inventoryItem.getFofoId() + "", customRetailer.getBusinessName(),
1884
							inventoryItem.getCreateTimestamp().format(dtf), priceDrop.getAffectedOn().format(dtf),
1885
							priceDropIMEI.getUpdateTimestamp().format(dtf),
1886
							inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getAutoPartnerPayout() + "",
1887
							inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
25609 amit.gupta 1888
				}
1889
			}
1890
		}
25503 amit.gupta 1891
	}
25694 amit.gupta 1892
 
1893
	public void testToffee() throws Exception {
25846 amit.gupta 1894
		LOGGER.info("Insurance Sum Summary --- {}",
1895
				insurancePolicyRepository.selectAmountSumGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
1896
		LOGGER.info("Insurance Qty Summary --- {}",
1897
				insurancePolicyRepository.selectQtyGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
25854 amit.gupta 1898
		LOGGER.info("SmartPhone Amount Summary --- {}",
25856 amit.gupta 1899
				fofoOrderItemRepository.selectSumAmountGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25854 amit.gupta 1900
		LOGGER.info("Smartphone Qty Summary --- {}",
1901
				fofoOrderItemRepository.selectQtyGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25800 tejbeer 1902
		// LOGGER.info("{}", toffeeService.getAuthToken());
25846 amit.gupta 1903
		/*
1904
		 * LOGGER.info("{}", toffeeService.getProducts()); // LOGGER.info("{}",
1905
		 * toffeeService.getPincodes("36103000PR")); PremiumCalculationRequestModel pcrm
1906
		 * = new PremiumCalculationRequestModel(); pcrm.setProductDetails("36103000PR");
1907
		 * // pcrm.setProductDetails("36103000PR");
1908
		 * pcrm.setDurations(Arrays.asList("3 Months", "6 Months", "1 Year"));
1909
		 * pcrm.setSumInsured("15000");
1910
		 * System.out.println(toffeeService.getPremiumCalculation(pcrm));
1911
		 */
25694 amit.gupta 1912
	}
1913
 
1914
	public void schemeRollback(List<String> schemeIds) throws Exception {
1915
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 1916
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 1917
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1918
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
1919
		for (SchemeInOut sio : schemeInOuts) {
1920
			Scheme scheme = schemesMap.get(sio.getSchemeId());
1921
			if (scheme.getType().equals(SchemeType.IN)) {
1922
 
1923
			} else if (scheme.getType().equals(SchemeType.OUT)) {
1924
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
1925
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
1926
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
1927
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
1928
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
1929
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
1930
					sio.setRolledBackTimestamp(LocalDateTime.now());
1931
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 1932
					String rollbackReason = "Scheme reversed for "
1933
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 1934
							+ fofoOrder.getInvoiceNumber();
1935
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
26945 amit.gupta 1936
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason,
1937
							LocalDateTime.now());
25694 amit.gupta 1938
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
1939
							rollbackReason);
1940
				}
1941
			}
1942
		}
25721 tejbeer 1943
		// throw new Exception();
25694 amit.gupta 1944
	}
25721 tejbeer 1945
 
1946
	public void checkfocusedModelInPartnerStock() throws Exception {
1947
 
1948
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1949
				.collect(Collectors.toList());
1950
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
1951
		for (Integer fofoId : fofoIds) {
1952
			if (!focusedModelShortageReportMap.containsKey(fofoId)) {
1953
				focusedModelShortageReportMap.put(fofoId, new ArrayList<>());
1954
			}
1955
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1956
			Map<Integer, Integer> processingOrderMap = null;
1957
			Map<Integer, Integer> catalogIdAndQtyMap = null;
1958
			Map<Integer, Integer> grnPendingOrdersMap = null;
1959
 
1960
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1961
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1962
 
1963
			if (!currentInventorySnapshot.isEmpty()) {
1964
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1965
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1966
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1967
 
1968
			}
1969
 
1970
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1971
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1972
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1973
			if (!grnPendingOrders.isEmpty()) {
1974
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1975
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1976
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1977
 
1978
			}
1979
 
1980
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1981
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1982
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1983
			if (!processingOrder.isEmpty()) {
1984
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1985
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1986
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1987
 
1988
			}
1989
 
25800 tejbeer 1990
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1991
					.collect(Collectors.toList());
1992
 
1993
			List<Integer> focusedModelCatalogId = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
1994
					.collect(Collectors.toList());
1995
			Map<String, Object> equalsMap = new HashMap<>();
1996
			equalsMap.put("categoryId", 10006);
1997
			equalsMap.put("brand", brands);
1998
 
1999
			Map<String, List<?>> notEqualsMap = new HashMap<>();
2000
 
2001
			Map<String, Object> equalsJoinMap = new HashMap<>();
2002
			equalsJoinMap.put("catalogId", focusedModelCatalogId);
2003
 
2004
			Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
2005
 
2006
			List<Integer> catalogIds = itemRepository
2007
					.selectItems(FocusedModel.class, "catalogItemId", "catalogId", equalsMap, notEqualsMap,
2008
							equalsJoinMap, notEqualsJoinMap, "minimumQty")
2009
					.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
2010
 
2011
			Map<Integer, Integer> focusedCatalogIdAndQtyMap = focusedModelRepository.selectByCatalogIdsl(catalogIds)
2012
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getMinimumQty()));
2013
 
2014
			/*
2015
			 * Map<Integer, Integer> focusedCatalogIdAndQtyMap =
2016
			 * focusedModelRepository.selectAll().stream() .collect(Collectors.toMap(x ->
2017
			 * x.getCatalogId(), x -> x.getMinimumQty()));
2018
			 */
2019
 
25721 tejbeer 2020
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
2021
 
2022
			for (Map.Entry<Integer, Integer> entry : focusedCatalogIdAndQtyMap.entrySet()) {
2023
				int inStockQty = 0;
2024
				int processingQty = 0;
2025
				int grnPendingQty = 0;
2026
				if (processingOrderMap != null) {
2027
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
2028
							: processingOrderMap.get(entry.getKey());
2029
 
2030
				}
2031
				if (grnPendingOrdersMap != null) {
2032
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
2033
							: grnPendingOrdersMap.get(entry.getKey());
2034
 
2035
				}
2036
				if (catalogIdAndQtyMap != null) {
2037
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
2038
							: catalogIdAndQtyMap.get(entry.getKey());
2039
 
2040
				}
2041
				int totalQty = processingQty + grnPendingQty + inStockQty;
2042
 
2043
				if (totalQty < entry.getValue()) {
2044
 
2045
					int shortageQty = entry.getValue() - totalQty;
2046
					List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
2047
 
2048
					FocusedModelShortageModel fm = new FocusedModelShortageModel();
2049
					fm.setFofoId(fofoId);
2050
					fm.setStoreName(customRetailer.getBusinessName());
2051
 
2052
					fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
2053
					fm.setShortageQty(shortageQty);
2054
 
2055
					focusedModelShortageReportMap.get(fofoId).add(fm);
2056
				}
2057
 
2058
			}
2059
			List<FocusedModelShortageModel> focusedModelShortageModel = focusedModelShortageReportMap.get(fofoId);
2060
 
2061
			if (!focusedModelShortageModel.isEmpty()) {
2062
				String subject = "Stock Alert";
2063
				String messageText = this.getMessage(focusedModelShortageModel);
2064
 
25732 tejbeer 2065
				this.sendMailWithAttachments(subject, messageText, customRetailer.getEmail());
25721 tejbeer 2066
				String notificationMessage = this.getNotificationMessage(focusedModelShortageModel);
2067
 
2068
				LOGGER.info("notificationMessage" + notificationMessage);
2069
 
25872 tejbeer 2070
				SendNotificationModel sendNotificationModel = new SendNotificationModel();
2071
				sendNotificationModel.setCampaignName("Stock Alert");
2072
				sendNotificationModel.setTitle("Alert");
2073
				sendNotificationModel.setMessage(notificationMessage);
2074
				sendNotificationModel.setType("url");
26564 amit.gupta 2075
				sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25872 tejbeer 2076
				sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2077
				sendNotificationModel.setMessageType(MessageType.notification);
25732 tejbeer 2078
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
25872 tejbeer 2079
				sendNotificationModel.setUserIds(Arrays.asList(userId));
2080
				notificationService.sendNotification(sendNotificationModel);
25721 tejbeer 2081
 
2082
			}
25732 tejbeer 2083
 
25721 tejbeer 2084
		}
25800 tejbeer 2085
		if (!focusedModelShortageReportMap.isEmpty())
25721 tejbeer 2086
 
25800 tejbeer 2087
		{
2088
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
2089
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
25837 amit.gupta 2090
			Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 2091
 
25800 tejbeer 2092
			focusedModelShortageReportMap.entrySet().forEach(x -> {
2093
				storeGuyMap.entrySet().forEach(y -> {
2094
 
2095
					if (y.getValue().contains(x.getKey())) {
2096
						if (!emailRowsMap.containsKey(y.getKey())) {
2097
							emailRowsMap.put(y.getKey(), new ArrayList<>());
2098
						}
2099
						List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays
2100
								.asList(r.getFofoId(), r.getStoreName(), r.getItemName(), r.getShortageQty()))
2101
								.collect(Collectors.toList());
2102
						emailRowsMap.get(y.getKey()).addAll(fms);
2103
 
25721 tejbeer 2104
					}
2105
 
25800 tejbeer 2106
				});
25721 tejbeer 2107
 
2108
			});
2109
 
25800 tejbeer 2110
			List<String> headers = Arrays.asList("Partner Id", "Partner Name", "Model Name", "Shortage Qty");
25837 amit.gupta 2111
			emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 2112
 
25800 tejbeer 2113
				ByteArrayOutputStream baos = null;
2114
				try {
25837 amit.gupta 2115
					baos = FileUtil.getCSVByteStream(headers, entry.getValue());
25800 tejbeer 2116
				} catch (Exception e2) {
2117
					e2.printStackTrace();
2118
				}
25837 amit.gupta 2119
				String[] sendToArray = new String[] { entry.getKey() };
25800 tejbeer 2120
				try {
2121
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
2122
							new ByteArrayResource(baos.toByteArray()));
2123
				} catch (Exception e1) { // TODO Auto-generated catch block
2124
					e1.printStackTrace();
2125
				}
25721 tejbeer 2126
 
25800 tejbeer 2127
			});
2128
		}
25721 tejbeer 2129
	}
2130
 
2131
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2132
		StringBuilder sb = new StringBuilder();
2133
		sb.append("Focused Model Shortage in Your Stock : \n");
2134
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
2135
 
2136
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
2137
			sb.append(String.format("%n", ""));
2138
		}
2139
		return sb.toString();
2140
	}
2141
 
2142
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
2143
		MimeMessage message = mailSender.createMimeMessage();
2144
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
2145
 
2146
		helper.setSubject(subject);
2147
		helper.setText(messageText, true);
2148
		helper.setTo(email);
26032 amit.gupta 2149
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smatdukaan Alerts");
25721 tejbeer 2150
		helper.setFrom(senderAddress);
2151
		mailSender.send(message);
2152
 
2153
	}
2154
 
2155
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2156
		StringBuilder sb = new StringBuilder();
2157
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
2158
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2159
		sb.append("<tbody>\n" + "	    				<tr>\n"
2160
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
2161
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
2162
				+ "	    				</tr>");
2163
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
2164
 
2165
			sb.append("<tr>");
2166
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
2167
 
2168
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
2169
 
2170
			sb.append("</tr>");
2171
 
2172
		}
2173
 
2174
		sb.append("</tbody></table></body></html>");
2175
 
2176
		return sb.toString();
2177
	}
2178
 
25927 amit.gupta 2179
	public void notifyLead() throws Exception {
2180
		List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(LocalDateTime.now().minusDays(15),
2181
				LocalDateTime.now().plusHours(4));
2182
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2183
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
25936 amit.gupta 2184
		System.out.printf("authUserEmailMap - %s", authUserEmailMap);
25927 amit.gupta 2185
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2186
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2187
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25936 amit.gupta 2188
 
2189
		System.out.printf("dtrEmailMap - %s", dtrEmailMap);
26790 tejbeer 2190
 
25927 amit.gupta 2191
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
2192
 
2193
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2194
			int authId = authUserEmail.getKey();
2195
			String email = authUserEmail.getValue();
2196
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2197
		}
25929 amit.gupta 2198
		System.out.println(authUserKeyMap);
2199
		System.out.println(leadsToNotify);
26790 tejbeer 2200
 
25927 amit.gupta 2201
		String templateMessage = "Lead followup for %s %s, %s is due by %s";
2202
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
2203
		for (Lead lead : leadsToNotify) {
2204
			if (authUserKeyMap.get(lead.getAuthId()) == null) {
2205
				continue;
2206
			}
2207
			String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(),
25941 amit.gupta 2208
					lead.getAddress(), timeFormatter.format(lead.getLeadActivity().getSchelduleTimestamp()));
25927 amit.gupta 2209
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2210
			sendNotificationModel.setCampaignName("Lead Reminder");
2211
			sendNotificationModel.setTitle("Leads followup Reminder");
2212
			sendNotificationModel.setMessage(notificationMessage);
2213
			sendNotificationModel.setType("url");
26564 amit.gupta 2214
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2215
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2216
			sendNotificationModel.setMessageType(MessageType.reminder);
26320 tejbeer 2217
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAssignTo())));
25929 amit.gupta 2218
			System.out.println(sendNotificationModel);
25927 amit.gupta 2219
			notificationService.sendNotification(sendNotificationModel);
2220
		}
2221
	}
26945 amit.gupta 2222
 
25927 amit.gupta 2223
	public void notifyVisits() throws Exception {
26945 amit.gupta 2224
		List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository
2225
				.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
25927 amit.gupta 2226
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2227
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
2228
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2229
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2230
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
2231
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26945 amit.gupta 2232
 
25927 amit.gupta 2233
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2234
			int authId = authUserEmail.getKey();
2235
			String email = authUserEmail.getValue();
2236
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2237
		}
2238
		String visitTemplate = "Planned visit to franchisee %s is due by %s";
2239
		String followupTemplate = "Lead followup for franchisee %s is due by %s";
2240
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
2241
		for (FranchiseeVisit visit : franchiseeVisits) {
2242
			if (authUserKeyMap.containsKey(visit.getAuthId())) {
2243
				continue;
2244
			}
2245
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2246
			String message = null;
26945 amit.gupta 2247
			if (visit.getFranchiseActivityId() == 0) {
2248
				message = String.format(visitTemplate, visit.getPartnerName(),
2249
						timeFormatter.format(visit.getSchelduleTimestamp()));
2250
				sendNotificationModel.setCampaignName("Franchisee visit Reminder");
25927 amit.gupta 2251
			} else {
26945 amit.gupta 2252
				message = String.format(followupTemplate, visit.getPartnerName(),
2253
						timeFormatter.format(visit.getSchelduleTimestamp()));
25927 amit.gupta 2254
				sendNotificationModel.setCampaignName("Franchisee followup Reminder");
2255
			}
2256
			sendNotificationModel.setMessage(message);
2257
			sendNotificationModel.setType("url");
26482 tejbeer 2258
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2259
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2260
			sendNotificationModel.setMessageType(MessageType.reminder);
2261
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
2262
			notificationService.sendNotification(sendNotificationModel);
2263
		}
25910 amit.gupta 2264
	}
25982 amit.gupta 2265
 
26283 tejbeer 2266
	public void ticketClosed() throws Exception {
2267
 
2268
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTicketsWithStatus(ActivityType.RESOLVED);
2269
		for (Ticket ticket : tickets) {
2270
			if (ticket.getUpdateTimestamp().toLocalDate().isBefore(LocalDate.now().minusDays(7))) {
2271
				ticket.setCloseTimestamp(LocalDateTime.now());
2272
				ticket.setLastActivity(ActivityType.RESOLVED_ACCEPTED);
2273
				ticket.setUpdateTimestamp(LocalDateTime.now());
2274
				ticketRepository.persist(ticket);
2275
			}
2276
		}
2277
 
2278
	}
2279
 
26790 tejbeer 2280
	public void checkValidateReferral() throws Exception {
2281
 
2282
		List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
26791 tejbeer 2283
		LOGGER.info("referrals" + referrals);
26790 tejbeer 2284
		if (!referrals.isEmpty()) {
2285
			String subject = "Referral Request";
2286
			String messageText = this.getMessageForReferral(referrals);
2287
 
26792 tejbeer 2288
			MimeMessage message = mailSender.createMimeMessage();
2289
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
2290
			String[] email = { "kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com" };
2291
			helper.setSubject(subject);
2292
			helper.setText(messageText, true);
2293
			helper.setTo(email);
2294
			InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
2295
			helper.setFrom(senderAddress);
2296
			mailSender.send(message);
2297
 
26790 tejbeer 2298
		}
2299
	}
2300
 
2301
	private String getMessageForReferral(List<Refferal> referrals) {
2302
		StringBuilder sb = new StringBuilder();
2303
		sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>"
2304
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2305
		sb.append("<tbody>\n" + "	    				<tr>\n"
2306
				+ "	    					<th style='border:1px solid black;padding: 5px'>RefereeName</th>\n"
2307
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referee Email</th>\n"
2308
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referral Name</th>\n"
2309
				+ "	    					<th style='border:1px solid black;padding: 5px'>Refferal Mobile</th>\n"
2310
				+ "	    					<th style='border:1px solid black;padding: 5px'>city</th>\n"
2311
				+ "	    					<th style='border:1px solid black;padding: 5px'>state</th>\n"
2312
				+ "	    				</tr>");
2313
		for (Refferal entry : referrals) {
2314
 
2315
			sb.append("<tr>");
2316
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
2317
 
2318
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
2319
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
2320
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
2321
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
2322
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
2323
 
2324
			sb.append("</tr>");
2325
 
2326
		}
2327
 
2328
		sb.append("</tbody></table></body></html>");
2329
 
2330
		return sb.toString();
2331
	}
2332
 
26418 tejbeer 2333
}