Subversion Repositories SmartDukaan

Rev

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