Subversion Repositories SmartDukaan

Rev

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