Subversion Repositories SmartDukaan

Rev

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