Subversion Repositories SmartDukaan

Rev

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

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