Subversion Repositories SmartDukaan

Rev

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

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