Subversion Repositories SmartDukaan

Rev

Rev 27132 | Rev 27206 | 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",
27132 amit.gupta 270
			"rajat.gupta@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "amit.babu@smartdukaan.com", 
271
			"manish.gupta@smartdukaan.com"};
25609 amit.gupta 272
 
273
	private static final String[] ITEMWISE_PENDING_INDENT_MAIL_LIST = new String[] { "kamini.sharma@smartdukaan.com",
27131 amit.gupta 274
			"amit.babu@smartdukaan.com", "tarun.verma@smartdukaan.com", "uday.singh@smartdukaan.com",
275
			"kuldeep.kumar@smartdukaan.com", "niranjan.kala@smartdukaan.com" };
25609 amit.gupta 276
 
25721 tejbeer 277
	private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING);
278
 
24681 amit.gupta 279
	@Autowired
280
	private ReporticoService reporticoService;
23724 amit.gupta 281
 
282
	@Autowired
24337 amit.gupta 283
	private PartnerInvestmentService partnerInvestmentService;
25598 amit.gupta 284
 
25590 amit.gupta 285
	@Autowired
286
	private PositionRepository positionRepository;
24337 amit.gupta 287
 
288
	@Autowired
24542 amit.gupta 289
	private FofoOrderItemRepository fofoOrderItemRepository;
25865 amit.gupta 290
 
25854 amit.gupta 291
	@Autowired
292
	private NotificationService notificationService;
24542 amit.gupta 293
 
294
	@Autowired
24277 amit.gupta 295
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
296
 
297
	@Autowired
24241 amit.gupta 298
	private SchemeInOutRepository schemeInOutRepository;
299
 
300
	@Autowired
23724 amit.gupta 301
	private RechargeTransactionRepository rechargeTransactionRepository;
302
 
303
	@Autowired
24542 amit.gupta 304
	private CustomerAddressRepository customerAddressRepository;
305
 
306
	@Autowired
23724 amit.gupta 307
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
308
 
309
	@Autowired
24590 amit.gupta 310
	private FofoLineItemRepository fofoLineItemRepository;
311
 
312
	@Autowired
23724 amit.gupta 313
	private FofoOrderRepository fofoOrderRepository;
24587 amit.gupta 314
 
24580 amit.gupta 315
	@Autowired
316
	private UserWalletHistoryRepository userWalletHistoryRepository;
24250 amit.gupta 317
 
24249 amit.gupta 318
	@Autowired
24587 amit.gupta 319
	private UserWalletRepository userWalletRepository;
320
 
321
	@Autowired
24249 amit.gupta 322
	private InventoryItemRepository inventoryItemRepository;
23929 amit.gupta 323
 
23739 amit.gupta 324
	@Autowired
325
	private WalletService walletService;
23724 amit.gupta 326
 
327
	@Autowired
328
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
329
 
330
	@Autowired
331
	private OxigenRechargeProviderService oxigenRechargeProviderService;
332
 
333
	@Autowired
334
	private RechargeProviderRepository rechargeProviderRepository;
335
 
336
	@Autowired
24242 amit.gupta 337
	private ScanRecordRepository scanRecordRepository;
338
 
339
	@Autowired
23724 amit.gupta 340
	private DailyRechargeRepository dailyRechargeRepository;
341
 
23929 amit.gupta 342
	@Autowired
343
	private FofoStoreRepository fofoStoreRepository;
24177 govind 344
 
24121 govind 345
	@Autowired
346
	private TargetSlabService targetService;
23929 amit.gupta 347
 
23724 amit.gupta 348
	@Value("${prod}")
349
	private boolean prod;
26945 amit.gupta 350
 
26929 amit.gupta 351
	@Autowired
352
	private StateGstRateRepository stateGstRateRepository;
23724 amit.gupta 353
 
23929 amit.gupta 354
	@Autowired
355
	private RetailerService retailerService;
356
 
357
	@Autowired
358
	private TransactionService transactionService;
24250 amit.gupta 359
 
24249 amit.gupta 360
	@Autowired
361
	private ItemRepository itemRepository;
23929 amit.gupta 362
 
363
	@Autowired
364
	private OrderRepository orderRepository;
25351 tejbeer 365
 
25335 amit.gupta 366
	@Autowired
367
	private OrderService orderService;
23929 amit.gupta 368
 
369
	@Autowired
24241 amit.gupta 370
	private SchemeRepository schemeRepository;
371
 
372
	@Autowired
23929 amit.gupta 373
	private JavaMailSender mailSender;
24177 govind 374
 
24174 govind 375
	@Autowired
376
	private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 377
 
378
	@Autowired
379
	@Qualifier(value = "googleMailSender")
23932 amit.gupta 380
	private JavaMailSender googleMailSender;
23929 amit.gupta 381
 
382
	@Autowired
383
	private InventoryService inventoryService;
384
 
24533 govind 385
	@Autowired
24542 amit.gupta 386
	private AddressRepository addressRepository;
387
 
388
	@Autowired
389
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
390
 
24653 govind 391
	@Autowired
392
	private Mongo mongoClient;
24683 amit.gupta 393
 
24669 govind 394
	@Autowired
25300 tejbeer 395
	private DeviceRepository deviceRepository;
396
 
397
	@Autowired
398
	private PushNotificationRepository pushNotificationRepository;
399
 
400
	@Autowired
401
	private NotificationCampaignRepository notificationCampaignRepository;
402
 
403
	@Autowired
25721 tejbeer 404
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
405
 
406
	@Autowired
407
	private FocusedModelRepository focusedModelRepository;
408
 
409
	@Autowired
24669 govind 410
	private UserAccountRepository userAccountRepository;
24653 govind 411
 
25721 tejbeer 412
	@Autowired
25927 amit.gupta 413
	private UserRepository userUserRepository;
25721 tejbeer 414
 
415
	@Autowired
25927 amit.gupta 416
	private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
417
 
418
	@Autowired
25721 tejbeer 419
	private UserCampaignRepository userCampaignRepository;
420
 
421
	@Autowired
422
	private Gson gson;
423
 
26283 tejbeer 424
	@Autowired
425
	private TicketRepository ticketRepository;
426
 
26790 tejbeer 427
	@Autowired
428
	private RefferalRepository refferalRepository;
429
 
23755 amit.gupta 430
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 431
 
25300 tejbeer 432
	private String FCM_URL = "https://fcm.googleapis.com/fcm/send";
433
	private String FCM_API_KEY = "AAAASAjNcn4:APA91bG6fWRIgYJI0L9gCjP5ynaXz2hJHYKtD9dfH7Depdv31Nd9APJwhx-OPkAJ1WSz4BGNYG8lHThLFSjDGFxIwUZv241YcAJEGDLgt86mxq9FXJe-yBRu-S0_ZwHqmX-QaVKl5F_A";
434
 
23724 amit.gupta 435
	public void generateDailyRecharge() {
436
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
437
				.selectAll(0, 2000);
438
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
439
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
440
 
441
		rechargeProviders.stream().forEach(x -> {
442
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
443
					.stream().filter(z -> z.getProviderId() == x.getId())
444
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
445
 
446
			LOGGER.info("dateWiseProviderCreditsMap -- {}", dateWiseProviderCreditsMap);
447
			LocalDate endDate = LocalDate.now().plusDays(1);
448
			float previousDayClosing = 0;
449
			LocalDate date = LocalDate.of(2018, 4, 6);
450
			while (date.isBefore(endDate)) {
451
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
452
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
453
								date.plusDays(1).atStartOfDay());
454
 
455
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
456
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
457
 
458
				float dailyAmount = 0;
459
				float totalCommission = 0;
460
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
461
					if (rechargeTransaction.getProviderId() == x.getId()) {
462
						dailyAmount += rechargeTransaction.getAmount();
463
						totalCommission += rechargeTransaction.getCommission();
464
					}
465
				}
466
 
467
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
468
				float dailyWalletRecharge = 0;
469
				if (rechargeHistoryList != null) {
470
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
471
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
472
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
473
						}
474
					}
475
				}
476
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
477
					DailyRecharge dailyRecharge = null;
478
					try {
479
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
480
					} catch (Exception e) {
481
						LOGGER.info("Could not find Recharge entry");
482
					}
483
					if (dailyRecharge == null) {
484
						dailyRecharge = new DailyRecharge();
485
						dailyRecharge.setCreateDate(date);
486
					}
487
					dailyRecharge.setOpeningBalance(previousDayClosing);
488
					dailyRecharge.setProviderId(x.getId());
489
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
490
					dailyRecharge.setTotalAmount(dailyAmount);
491
					dailyRecharge.setTotalCommission(totalCommission);
492
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
493
					dailyRecharge.setClosingBalance(closingBalance);
494
					dailyRechargeRepository.persist(dailyRecharge);
495
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
496
					previousDayClosing = dailyRecharge.getClosingBalance();
497
				}
498
				date = date.plusDays(1);
499
			}
500
			rechargeProviderRepository.persist(x);
501
		});
23761 amit.gupta 502
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 503
	}
504
 
23738 amit.gupta 505
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 506
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
507
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
508
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
509
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
510
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
511
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
512
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
513
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
514
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
515
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
516
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
517
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
518
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
519
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
520
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
521
			try {
522
				int providerId = rechargeTransaction.getProviderId();
523
				if (providerId == 1) {
524
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
525
							rechargeTransaction);
526
				} else if (providerId == 2) {
527
					thinkWalnutDigitalRechargeProviderService
528
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
529
				}
530
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
531
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
532
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
533
							rechargeTransaction.getStatus());
534
				}
535
			} catch (Exception e) {
536
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
537
			}
538
		}
23738 amit.gupta 539
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 540
	}
24240 amit.gupta 541
 
542
	// TemporaryMethod
24237 amit.gupta 543
	public void migrateInvoice() {
544
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
545
		Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
24241 amit.gupta 546
		partnerOrdersMap = fofoOrders.stream()
547
				.collect(Collectors.groupingBy(FofoOrder::getFofoId, Collectors.toList()));
24237 amit.gupta 548
		for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
24240 amit.gupta 549
			int sequence = 0;
550
			String prefix = "";
24241 amit.gupta 551
			List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId())
552
					.collect(Collectors.toList());
553
			for (FofoOrder order : sortedList) {
554
 
24240 amit.gupta 555
				LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
24241 amit.gupta 556
				if (!order.getInvoiceNumber().contains("SEC")) {
24240 amit.gupta 557
					sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
558
					prefix = order.getInvoiceNumber().split("/")[0];
559
				} else {
560
					sequence += 1;
24241 amit.gupta 561
					String invoiceNumber = prefix + "/" + sequence;
24240 amit.gupta 562
					order.setInvoiceNumber(invoiceNumber);
563
					fofoOrderRepository.persist(order);
564
				}
565
			}
24241 amit.gupta 566
 
24237 amit.gupta 567
		}
568
	}
23724 amit.gupta 569
 
24241 amit.gupta 570
	// Temporary Method
24252 amit.gupta 571
	public void evaluateExcessSchemeOut() throws Exception {
24244 amit.gupta 572
		Map<Integer, String> userNameMap = retailerService.getAllFofoRetailerIdNameMap();
573
		Map<Integer, Float> userAmountMap = new HashMap<>();
24252 amit.gupta 574
 
25837 amit.gupta 575
		List<List<?>> rows = new ArrayList<>();
24271 amit.gupta 576
		List<String> headers = Arrays.asList("Scheme", "Item", "Partner", "Amount", "Credited On", "Invoice Number",
577
				"Sale On", "Scheme Start", "Scheme End", "Active On", "Expired On");
24241 amit.gupta 578
		schemeRepository.selectAll().stream().forEach(x -> {
24250 amit.gupta 579
			if (x.getType().equals(SchemeType.OUT)) {
580
				List<SchemeInOut> sioList = schemeInOutRepository
581
						.selectBySchemeIds(new HashSet<>(Arrays.asList(x.getId())));
582
				if (x.getActiveTimestamp() != null) {
583
					LocalDateTime endDateTime = x.getEndDateTime();
584
					if (x.getExpireTimestamp() != null && x.getExpireTimestamp().isBefore(x.getEndDateTime())) {
585
						endDateTime = x.getExpireTimestamp();
24249 amit.gupta 586
					}
24250 amit.gupta 587
					for (SchemeInOut sio : sioList) {
588
						InventoryItem inventoryItem = null;
24266 amit.gupta 589
						inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
24271 amit.gupta 590
						FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndSerialNumber(
591
								inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), null, null, 0, 1).get(0);
24250 amit.gupta 592
						Optional<ScanRecord> record = scanRecordRepository
593
								.selectByInventoryItemId(sio.getInventoryItemId()).stream()
594
								.filter(y -> y.getType().equals(ScanType.SALE)).findFirst();
595
						if (record.isPresent()) {
596
							int fofoId = record.get().getFofoId();
597
							if (record.get().getCreateTimestamp().isAfter(endDateTime)
598
									|| record.get().getCreateTimestamp().isBefore(x.getStartDateTime())) {
599
								if (!userAmountMap.containsKey(fofoId)) {
600
									userAmountMap.put(fofoId, 0f);
601
								}
602
								userAmountMap.put(fofoId, sio.getAmount() + userAmountMap.get(fofoId));
603
								try {
24252 amit.gupta 604
									rows.add(Arrays.asList(x.getDescription(),
24250 amit.gupta 605
											itemRepository.selectById(inventoryItem.getItemId()).getItemDescription(),
24252 amit.gupta 606
											userNameMap.get(fofoId), sio.getAmount(),
24253 amit.gupta 607
											FormattingUtils.formatDate(sio.getCreateTimestamp()),
608
											fofoOrder.getInvoiceNumber(),
609
											FormattingUtils.formatDate(record.get().getCreateTimestamp()),
610
											FormattingUtils.formatDate(x.getStartDateTime()),
611
											FormattingUtils.formatDate(x.getEndDateTime()),
612
											FormattingUtils.formatDate(x.getActiveTimestamp()),
613
											FormattingUtils.formatDate(x.getExpireTimestamp())));
24250 amit.gupta 614
								} catch (Exception e) {
615
									e.printStackTrace();
616
								}
24242 amit.gupta 617
							}
24241 amit.gupta 618
						}
619
					}
620
				}
621
			}
622
		});
24246 amit.gupta 623
		userAmountMap.entrySet().stream()
624
				.forEach(x -> LOGGER.info("{} to be deducted from {}({}) for wrongly disbursed due to technical error.",
625
						x.getValue(), userNameMap.get(x.getKey())));
24241 amit.gupta 626
 
24252 amit.gupta 627
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
24271 amit.gupta 628
		Utils.sendMailWithAttachment(googleMailSender,
629
				new String[] { "amit.gupta@shop2020.in", "adeel.yazdani@smartdukaan.com" }, null,
630
				"Partner Excess Amount", "PFA", "ListofSchemes.csv", new ByteArrayResource(baos.toByteArray()));
24252 amit.gupta 631
 
24241 amit.gupta 632
	}
24271 amit.gupta 633
 
25584 amit.gupta 634
	public void processScheme(int offset, boolean dryRun) throws Exception {
24462 amit.gupta 635
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24259 amit.gupta 636
		LocalDateTime endDate = startDate.plusDays(30);
25584 amit.gupta 637
		processScheme(startDate, endDate, dryRun);
24256 amit.gupta 638
	}
24533 govind 639
 
25584 amit.gupta 640
	public void processScheme(int offset, int durationDays, boolean dryRun) throws Exception {
24462 amit.gupta 641
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24461 amit.gupta 642
		LocalDateTime endDate = startDate.plusDays(durationDays);
25584 amit.gupta 643
		processScheme(startDate, endDate, dryRun);
24461 amit.gupta 644
	}
24271 amit.gupta 645
 
25584 amit.gupta 646
	public void processScheme(boolean dryRun) throws Exception {
24256 amit.gupta 647
		LocalDateTime fromDate = LocalDateTime.now().minusDays(30);
25584 amit.gupta 648
		processScheme(fromDate, LocalDateTime.now(), dryRun);
24256 amit.gupta 649
	}
24271 amit.gupta 650
 
25584 amit.gupta 651
	public void processScheme(LocalDateTime startDate, LocalDateTime endDate, boolean dryRun) throws Exception {
23724 amit.gupta 652
		LOGGER.info("Started execution at {}", LocalDateTime.now());
25312 amit.gupta 653
		System.out.println(
654
				"InventoryId\tSerialNumber\tItem Id\tScheme Id\tScheme Name\tScheme Type\tAmount Type\tDP\tTaxable\tScheme Amount\tAmount Paid");
24561 amit.gupta 655
		try {
24587 amit.gupta 656
			List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
657
			for (Purchase purchase : purchases) {
658
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
659
			}
24271 amit.gupta 660
 
24587 amit.gupta 661
			List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
662
			for (FofoOrder fofoOrder : fofoOrders) {
663
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
664
			}
665
		} catch (Exception e) {
24561 amit.gupta 666
			e.printStackTrace();
24565 amit.gupta 667
			throw e;
24561 amit.gupta 668
		}
25312 amit.gupta 669
		List<UserWalletHistory> uwhs = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
670
				Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
25043 amit.gupta 671
		System.out.println("Amount\tReference\tReferenceType\tTimestamp\tDescription");
25312 amit.gupta 672
		for (UserWalletHistory uwh : uwhs) {
673
			System.out.println(String.format("%d\t%d\t%s\t%s\t%s", uwh.getAmount(), uwh.getReference(),
674
					uwh.getReferenceType(), uwh.getTimestamp().toString(), uwh.getDescription()));
25043 amit.gupta 675
		}
23724 amit.gupta 676
		LOGGER.info("Schemes process successfully.");
25598 amit.gupta 677
		if (dryRun) {
25584 amit.gupta 678
			throw new Exception();
679
		}
23724 amit.gupta 680
	}
23929 amit.gupta 681
 
23739 amit.gupta 682
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 683
		LocalDateTime cashbackTime = LocalDateTime.now();
23929 amit.gupta 684
		int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
685
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository
686
				.getPendingCashBackRehargeTransactions();
687
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
688
				Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
689
		for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
690
			int retailerId = (Integer) totalRetailerCashback.getKey();
23739 amit.gupta 691
			float amount = totalRetailerCashback.getValue().floatValue();
23929 amit.gupta 692
			if (Math.round(amount) > 0) {
693
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK,
26565 amit.gupta 694
						"Recharge Cashback", Math.round(amount), LocalDateTime.now());
23762 amit.gupta 695
			}
23739 amit.gupta 696
		}
23929 amit.gupta 697
		for (RechargeTransaction rt : pendingTransactions) {
23761 amit.gupta 698
			rt.setCashbackTimestamp(cashbackTime);
699
			rt.setCashbackReference(referenceId);
700
			rechargeTransactionRepository.persist(rt);
701
		}
23739 amit.gupta 702
		LOGGER.info("Cashbacks for Recharge processed Successfully");
703
	}
23724 amit.gupta 704
 
25598 amit.gupta 705
	private class SaleRoles {
706
 
707
		private List<String> l1;
708
		private List<String> l2;
709
 
710
		public SaleRoles() {
711
			l1 = new ArrayList<>();
712
			l2 = new ArrayList<>();
713
		}
714
 
715
		public List<String> getL1() {
716
			return l1;
717
		}
718
 
719
		public List<String> getL2() {
720
			return l2;
721
		}
722
 
723
	}
724
 
26945 amit.gupta 725
	private class FofoReportingModel {
726
		private String code;
727
		private int fofoId;
728
		private String businessName;
729
		private String territoryManager;
730
		private String regionalManager;
731
 
732
		@Override
733
		public String toString() {
734
			return "FofoReportingModel [code=" + code + ", fofoId=" + fofoId + ", businessName=" + businessName
735
					+ ", territoryManager=" + territoryManager + ", regionalManager=" + regionalManager + "]";
736
		}
737
 
738
		public String getCode() {
739
			return code;
740
		}
741
 
742
		public void setCode(String code) {
743
			this.code = code;
744
		}
745
 
746
		public String getBusinessName() {
747
			return businessName;
748
		}
749
 
750
		public void setBusinessName(String businessName) {
751
			this.businessName = businessName;
752
		}
753
 
754
		public String getTerritoryManager() {
755
			return territoryManager;
756
		}
757
 
758
		public void setTerritoryManager(String territoryManager) {
759
			this.territoryManager = territoryManager;
760
		}
761
 
762
		public String getRegionalManager() {
763
			return regionalManager;
764
		}
765
 
766
		public void setRegionalManager(String regionalManager) {
767
			this.regionalManager = regionalManager;
768
		}
769
 
770
		private ScheduledTasks getOuterType() {
771
			return ScheduledTasks.this;
772
		}
773
 
774
		@Override
775
		public int hashCode() {
776
			final int prime = 31;
777
			int result = 1;
778
			result = prime * result + getOuterType().hashCode();
779
			result = prime * result + ((businessName == null) ? 0 : businessName.hashCode());
780
			result = prime * result + ((code == null) ? 0 : code.hashCode());
781
			result = prime * result + fofoId;
782
			result = prime * result + ((regionalManager == null) ? 0 : regionalManager.hashCode());
783
			result = prime * result + ((territoryManager == null) ? 0 : territoryManager.hashCode());
784
			return result;
785
		}
786
 
787
		@Override
788
		public boolean equals(Object obj) {
789
			if (this == obj)
790
				return true;
791
			if (obj == null)
792
				return false;
793
			if (getClass() != obj.getClass())
794
				return false;
795
			FofoReportingModel other = (FofoReportingModel) obj;
796
			if (!getOuterType().equals(other.getOuterType()))
797
				return false;
798
			if (businessName == null) {
799
				if (other.businessName != null)
800
					return false;
801
			} else if (!businessName.equals(other.businessName))
802
				return false;
803
			if (code == null) {
804
				if (other.code != null)
805
					return false;
806
			} else if (!code.equals(other.code))
807
				return false;
808
			if (fofoId != other.fofoId)
809
				return false;
810
			if (regionalManager == null) {
811
				if (other.regionalManager != null)
812
					return false;
813
			} else if (!regionalManager.equals(other.regionalManager))
814
				return false;
815
			if (territoryManager == null) {
816
				if (other.territoryManager != null)
817
					return false;
818
			} else if (!territoryManager.equals(other.territoryManager))
819
				return false;
820
			return true;
821
		}
822
 
823
		public int getFofoId() {
824
			return fofoId;
825
		}
826
 
827
		public void setFofoId(int fofoId) {
828
			this.fofoId = fofoId;
829
		}
830
 
831
	}
832
 
24271 amit.gupta 833
	public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
24277 amit.gupta 834
		LocalDate yesterDay = LocalDate.now().minusDays(1);
25267 amit.gupta 835
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
23929 amit.gupta 836
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
837
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25351 tejbeer 838
 
26957 amit.gupta 839
		List<String> headers = Arrays.asList("Code", "Outlet name", "State Manager", "Teritory/Team Lead",
26945 amit.gupta 840
				"Wallet Amount", "In Stock Amount", "Activated Stock", "Return In Transit Stock", "Unbilled Amount",
841
				"Grn Pending Amount", "Min Investment", "Investment Amount", "Investment Short", "Unbilled Qty",
842
				"Short Days");
25837 amit.gupta 843
		List<List<?>> rows = new ArrayList<>();
25895 amit.gupta 844
		Map<Integer, List<?>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 845
 
26945 amit.gupta 846
		Map<Integer, FofoReportingModel> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25598 amit.gupta 847
 
26945 amit.gupta 848
		Map<Integer, Integer> shortDaysMap = partnerDailyInvestmentRepository
849
				.selectAll(LocalDate.now().withDayOfMonth(1), LocalDate.now()).stream().collect(Collectors.groupingBy(
850
						x -> x.getFofoId(), Collectors.summingInt(x -> x.getShortPercentage() > 10 ? 1 : 0)));
851
 
24002 amit.gupta 852
		for (FofoStore fofoStore : fofoStores) {
26376 amit.gupta 853
			int fofoId = fofoStore.getId();
26945 amit.gupta 854
			PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 1);
25598 amit.gupta 855
			partnerDailyInvestment.setDate(yesterDay);
26945 amit.gupta 856
 
25598 amit.gupta 857
			try {
858
				partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
26945 amit.gupta 859
				shortDaysMap.put(fofoId,
860
						shortDaysMap.get(fofoId) + (partnerDailyInvestment.getShortPercentage() > 10 ? 1 : 0));
25598 amit.gupta 861
			} catch (Exception e) {
862
				// ignore the exceptions during persist
863
			}
864
 
24002 amit.gupta 865
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
25837 amit.gupta 866
			if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
24002 amit.gupta 867
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
868
				continue;
869
			}
26945 amit.gupta 870
			FofoReportingModel reportingModel = partnerIdSalesHeaderMap.get(fofoStore.getId());
871
			List<Serializable> row = new ArrayList<>();
872
			row.addAll(Arrays.asList(reportingModel.getCode(), reportingModel.getBusinessName(),
873
					reportingModel.getRegionalManager(), reportingModel.getTerritoryManager()));
25927 amit.gupta 874
			row.addAll(
875
					Arrays.asList(partnerDailyInvestment.getWalletAmount(), partnerDailyInvestment.getInStockAmount(),
26945 amit.gupta 876
							partnerDailyInvestment.getActivatedStockAmount() == 0 ? "-"
877
									: "(" + partnerDailyInvestment.getActivatedStockAmount() + ")",
25927 amit.gupta 878
							0, partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(),
879
							partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(),
26945 amit.gupta 880
							partnerDailyInvestment.getShortInvestment(), partnerDailyInvestment.getUnbilledQty(),
881
							shortDaysMap.get(fofoId)));
25837 amit.gupta 882
			partnerRowsMap.put(fofoStore.getId(), row);
24002 amit.gupta 883
			rows.add(row);
884
 
23929 amit.gupta 885
		}
25312 amit.gupta 886
 
24271 amit.gupta 887
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25598 amit.gupta 888
 
25927 amit.gupta 889
		if (sendTo == null) {
25895 amit.gupta 890
			for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
891
				List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x))
892
						.filter(x -> x != null).collect(Collectors.toList());
893
				ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
894
				String[] sendToArray = new String[] { storeGuyEntry.getKey() };
895
				Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
896
						fileName, new ByteArrayResource(baos.toByteArray()));
897
			}
27131 amit.gupta 898
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "hemant.kaura@smartdukaan.com",
27116 amit.gupta 899
					"amit.babu@smartdukaan.com", "amit.gupta@shop2020.in", "manish.gupta@smartdukaan.com", "niranjan.kala@smartdukaan.com");
25341 amit.gupta 900
		}
25312 amit.gupta 901
 
25604 amit.gupta 902
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
903
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
25609 amit.gupta 904
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
905
				fileName, new ByteArrayResource(baos.toByteArray()));
24271 amit.gupta 906
 
23929 amit.gupta 907
	}
24177 govind 908
 
26945 amit.gupta 909
	private Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() {
25598 amit.gupta 910
		Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
911
 
912
		List<Position> positions = positionRepository
913
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
914
		Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream()
915
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
916
		Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
917
		for (Position position : positions) {
918
			List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
25609 amit.gupta 919
			if (crList == null)
920
				continue;
25598 amit.gupta 921
			for (CustomRetailer cr : crList) {
922
				if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
923
					partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
924
				}
925
				SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
926
				AuthUser authUser = authUsersMap.get(position.getAuthUserId());
26945 amit.gupta 927
				if (authUser == null) {
26059 amit.gupta 928
					continue;
929
				}
25598 amit.gupta 930
				String name = authUser.getFirstName() + " " + authUser.getLastName();
931
				if (position.getEscalationType().equals(EscalationType.L1)) {
932
					saleRoles.getL1().add(name);
933
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
934
					saleRoles.getL2().add(name);
935
				}
936
			}
937
		}
25837 amit.gupta 938
 
939
		Set<CustomRetailer> allCrList = new HashSet<>();
940
		for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
941
			allCrList.addAll(cr);
942
		}
943
 
944
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
945
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
946
 
26945 amit.gupta 947
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
25837 amit.gupta 948
 
949
		for (CustomRetailer cr : allCrList) {
950
			FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
25927 amit.gupta 951
			if (fofoStore == null) {
25870 amit.gupta 952
				LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
953
				continue;
954
			}
26945 amit.gupta 955
			String code = fofoStore.getCode();
956
			// String storeName = "SmartDukaan-" +
957
			// fofoStore.getCode().replaceAll("[a-zA-Z]", "");
25837 amit.gupta 958
			String businessName = cr.getBusinessName();
959
			try {
960
				String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
961
				String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
26945 amit.gupta 962
				FofoReportingModel reportingModel = new FofoReportingModel();
963
				reportingModel.setBusinessName(businessName);
964
				reportingModel.setCode(code);
965
				reportingModel.setFofoId(fofoStore.getId());
966
				reportingModel.setRegionalManager(stateManager);
967
				reportingModel.setTerritoryManager(territoryManager);
968
				partnerIdSalesHeadersMap.put(fofoStore.getId(), reportingModel);
25837 amit.gupta 969
			} catch (Exception e) {
970
				LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
971
			}
972
		}
973
		return partnerIdSalesHeadersMap;
974
 
25598 amit.gupta 975
	}
976
 
24271 amit.gupta 977
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 978
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 979
	}
980
 
25312 amit.gupta 981
	public void sendTargetVsSalesReport(List<String> sendTo) throws Exception {
24177 govind 982
 
25312 amit.gupta 983
		if (sendTo == null) {
25827 amit.gupta 984
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
27131 amit.gupta 985
					"amit.gupta@shop2020.in", "hemant.kaura@smartdukaan.com", "amit.babu@smartdukaan.com", "manish.gupta@smartdukaan.com");
25312 amit.gupta 986
		}
25837 amit.gupta 987
		Map<Integer, List<Serializable>> partnerSalesTargetRowsMap = targetService.getDailySaleReportVsTarget();
25315 amit.gupta 988
 
26945 amit.gupta 989
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
24177 govind 990
 
26945 amit.gupta 991
		List<String> headers = Arrays.asList("Code", "Firm Name", "State Manager", "Teritory Manager",
25837 amit.gupta 992
				"Current Category", "Target Value", "Target Achieved", "Achived Percentage", "Remaining Target",
993
				"Today's Target", "Today's achievement");
25609 amit.gupta 994
 
25837 amit.gupta 995
		List<List<?>> rows = new ArrayList<>();
996
		Map<Integer, List<? extends Serializable>> partnerRowMap = new HashMap<>();
997
		for (Map.Entry<Integer, List<Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap.entrySet()) {
26945 amit.gupta 998
			FofoReportingModel fofoReportingModel = partnerIdSalesHeadersMap.get(partnerSalesTargetRowEntry.getKey());
999
			if (fofoReportingModel == null) {
25837 amit.gupta 1000
				LOGGER.warn("Could not find headers for partner ID - {}", partnerSalesTargetRowEntry.getKey());
26945 amit.gupta 1001
				continue;
25315 amit.gupta 1002
			}
26945 amit.gupta 1003
			List<Serializable> row = Arrays.asList(fofoReportingModel.getCode(), fofoReportingModel.getBusinessName(),
1004
					fofoReportingModel.getRegionalManager(), fofoReportingModel.getTerritoryManager());
25837 amit.gupta 1005
			row.addAll(partnerSalesTargetRowEntry.getValue());
1006
			partnerRowMap.put(partnerSalesTargetRowEntry.getKey(), row);
1007
			rows.add(row);
24177 govind 1008
		}
25503 amit.gupta 1009
 
25318 amit.gupta 1010
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25894 amit.gupta 1011
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
1012
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25827 amit.gupta 1013
			if (storeGuyEntry.getValue().size() == 0)
1014
				continue;
25927 amit.gupta 1015
			List<List<?>> storeGuyRows = storeGuyEntry.getValue().stream().filter(x -> partnerRowMap.containsKey(x))
1016
					.map(x -> partnerRowMap.get(x)).collect(Collectors.toList());
25827 amit.gupta 1017
			ByteArrayOutputStream authUserStream = FileUtil.getCSVByteStream(headers, storeGuyRows);
1018
			Attachment attache = new Attachment(fileName, new ByteArrayResource(authUserStream.toByteArray()));
1019
			System.out.println(storeGuyEntry.getValue());
1020
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
1021
					"Franchise Stock Report", "PFA", attache);
1022
		}
24240 amit.gupta 1023
 
25312 amit.gupta 1024
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1025
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
1026
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
1027
				new ByteArrayResource(baos.toByteArray()));
24174 govind 1028
	}
24683 amit.gupta 1029
 
24697 amit.gupta 1030
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 1031
 
1032
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
1033
				"itemstockageing.xml");
24708 amit.gupta 1034
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 1035
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 1036
		Attachment attachment = new Attachment(
25445 amit.gupta 1037
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 1038
		Attachment attachment1 = new Attachment(
25445 amit.gupta 1039
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 1040
 
25609 amit.gupta 1041
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
1042
				attachment);
1043
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
1044
				"Itemwise Pending indent", "PFA", attachment1);
1045
 
25598 amit.gupta 1046
		// Reports to be sent to mapped partners
25597 amit.gupta 1047
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 1048
 
1049
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 1050
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 1051
			if (storeGuyEntry.getValue().size() == 0)
1052
				continue;
25418 amit.gupta 1053
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
1054
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
1055
					"focostockreport.xml", params);
1056
			Attachment attache = new Attachment(
25609 amit.gupta 1057
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 1058
			System.out.println(storeGuyEntry.getValue());
25609 amit.gupta 1059
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
1060
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 1061
		}
25503 amit.gupta 1062
 
24681 amit.gupta 1063
	}
24533 govind 1064
 
24697 amit.gupta 1065
	public void sendAgeingReport() throws Exception {
27131 amit.gupta 1066
		sendAgeingReport("kamini.sharma@smartdukaan.com", "amit.babu@smartdukaan.com", "tarun.verma@smartdukaan.com", 
1067
				"niranjan.kala@smartdukaan.com", "manish.gupta@smartdukaan.com", "kuldeep.kumar@smartdukaan.com",
26862 amit.gupta 1068
				"hemant.kaura@smartdukaan.com");
24697 amit.gupta 1069
	}
1070
 
24533 govind 1071
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 1072
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 1073
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 1074
			priceDropService.priceDropStatus(priceDrop.getId());
1075
		}
1076
	}
23929 amit.gupta 1077
 
24542 amit.gupta 1078
	public void walletmismatch() throws Exception {
1079
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 1080
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 1081
		System.out.println(pdis.size());
24542 amit.gupta 1082
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 1083
			int fofoId = pdi.getFofoId();
24542 amit.gupta 1084
			for (PartnerDailyInvestment investment : Lists
1085
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 1086
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 1087
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 1088
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 1089
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
1090
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 1091
 
24542 amit.gupta 1092
			}
24549 amit.gupta 1093
		}
24542 amit.gupta 1094
 
1095
	}
1096
 
1097
	public void gst() throws Exception {
24548 amit.gupta 1098
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
1099
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
1100
		for (FofoOrder fofoOrder : fofoOrders) {
1101
			int retailerAddressId = retailerRegisteredAddressRepository
1102
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 1103
 
1104
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
1105
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1106
			Integer stateId = null;
1107
			if (customerAddress.getState().equals(retailerAddress.getState())) {
1108
				try {
1109
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
1110
				} catch (Exception e) {
1111
					LOGGER.error("Unable to get state rates");
1112
				}
1113
			}
1114
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1115
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 1116
 
1117
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
26929 amit.gupta 1118
			List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
24542 amit.gupta 1119
			if (stateId != null) {
26929 amit.gupta 1120
				itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
24542 amit.gupta 1121
			} else {
26929 amit.gupta 1122
				itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(itemIds);
24542 amit.gupta 1123
			}
1124
 
24548 amit.gupta 1125
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 1126
				if (stateId == null) {
1127
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
1128
				} else {
1129
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
1130
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
1131
				}
1132
				fofoOrderItemRepository.persist(foi);
1133
			}
1134
		}
24548 amit.gupta 1135
 
24542 amit.gupta 1136
	}
1137
 
24580 amit.gupta 1138
	public void schemewalletmismatch() {
1139
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 1140
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 1141
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 1142
			// reconcileOrders(dateTime);
1143
			// reconcileRecharges(dateTime);
24580 amit.gupta 1144
			dateToReconcile = dateToReconcile.plusDays(1);
1145
		}
1146
	}
1147
 
1148
	private void reconcileSchemes(LocalDate date) {
1149
		LocalDateTime startDate = date.atStartOfDay();
1150
		LocalDateTime endDate = startDate.plusDays(1);
1151
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
1152
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 1153
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
1154
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 1155
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 1156
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
1157
				WalletReferenceType.SCHEME_OUT);
1158
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
1159
				walletReferenceTypes);
1160
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
1161
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 1162
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 1163
 
1164
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
1165
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1166
 
1167
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
1168
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1169
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
1170
 
1171
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
1172
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1173
 
1174
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
1175
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
1176
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
1177
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
1178
 
1179
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
26092 amit.gupta 1180
 
24587 amit.gupta 1181
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
1182
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
1183
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
1184
				} else {
1185
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
1186
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
1187
				}
1188
			}
24590 amit.gupta 1189
			Map<Integer, Integer> userWalletMap = userWalletRepository
1190
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
1191
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1192
 
24587 amit.gupta 1193
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
1194
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
1195
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
1196
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1197
				if (diff > 5) {
1198
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1199
				}
1200
			}
24580 amit.gupta 1201
		}
24587 amit.gupta 1202
 
24580 amit.gupta 1203
	}
24590 amit.gupta 1204
 
24592 amit.gupta 1205
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1206
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1207
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1208
 
24592 amit.gupta 1209
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1210
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1211
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1212
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1213
		Set<String> serialNumbersConsidered = new HashSet<>();
1214
 
25096 amit.gupta 1215
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1216
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1217
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1218
 
24683 amit.gupta 1219
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1220
		purchases.stream().forEach(purchase -> {
1221
			float amountToRollback = 0;
1222
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1223
					+ purchase.getPurchaseReference();
1224
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1225
					.stream().filter(ii -> ii.getSerialNumber() != null)
1226
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1227
			if (inventorySerialNumberMap.size() > 0) {
1228
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1229
					String serialNumber = inventorySerialNumberEntry.getValue();
1230
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1231
					if (serialNumbersConsidered.contains(serialNumber)) {
1232
						// This will rollback scheme for differenct orders for same serial
1233
						List<SchemeInOut> sios = schemeInOutRepository
1234
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1235
								.filter(x -> x.getRolledBackTimestamp() == null
1236
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1237
								.collect(Collectors.toList());
1238
						Collections.reverse(sios);
1239
						for (SchemeInOut sio : sios) {
1240
							sio.setRolledBackTimestamp(LocalDateTime.now());
1241
							amountToRollback += sio.getAmount();
1242
							// sio.setSchemeType(SchemeType.OUT);
1243
							sio.setSerialNumber(serialNumber);
1244
							rolledbackSios.add(sio);
1245
						}
1246
						description = description.concat(" " + serialNumber + " ");
1247
					} else {
1248
						serialNumbersConsidered.add(serialNumber);
1249
						List<Integer> schemesConsidered = new ArrayList<>();
1250
						List<SchemeInOut> sios = schemeInOutRepository
1251
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1252
								.filter(x -> x.getRolledBackTimestamp() == null
1253
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1254
								.collect(Collectors.toList());
1255
						Collections.reverse(sios);
1256
						for (SchemeInOut sio : sios) {
1257
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1258
								schemesConsidered.add(sio.getSchemeId());
1259
								continue;
1260
							}
1261
							sio.setRolledBackTimestamp(LocalDateTime.now());
1262
							amountToRollback += sio.getAmount();
1263
							// sio.setSchemeType(SchemeType.OUT);
1264
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1265
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1266
							sio.setReference(purchase.getId());
24635 amit.gupta 1267
							rolledbackSios.add(sio);
1268
						}
1269
					}
1270
 
1271
				}
1272
			}
1273
			if (amountToRollback > 0) {
24683 amit.gupta 1274
				// Address address =
1275
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1276
				UserWalletHistory uwh = new UserWalletHistory();
1277
				uwh.setAmount(Math.round(amountToRollback));
1278
				uwh.setDescription(description);
1279
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1280
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1281
				uwh.setReference(purchase.getId());
1282
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1283
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1284
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1285
				userWalletHistory.add(uwh);
1286
			}
1287
		});
1288
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1289
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1290
						"Timestamp"),
1291
				userWalletHistory.stream()
1292
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1293
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1294
						.collect(Collectors.toList()));
1295
 
1296
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1297
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1298
						"Created", "Rolledback"),
24635 amit.gupta 1299
				rolledbackSios.stream()
24681 amit.gupta 1300
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1301
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1302
						.collect(Collectors.toList()));
1303
 
25043 amit.gupta 1304
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1305
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1306
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1307
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1308
 
25096 amit.gupta 1309
		throw new Exception();
24635 amit.gupta 1310
 
1311
	}
1312
 
1313
	public void dryRunOutSchemeReco() throws Exception {
1314
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1315
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1316
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1317
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1318
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1319
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1320
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1321
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1322
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1323
		// Collections.reverse(allOrders);
1324
		// List<FofoOrder> allOrders =
24653 govind 1325
		// List<FofoOrder> allOrders =
24631 amit.gupta 1326
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1327
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1328
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1329
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1330
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1331
			float amountToRollback = 0;
24590 amit.gupta 1332
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1333
			orderItems.forEach(x -> {
24606 amit.gupta 1334
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1335
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1336
			});
24606 amit.gupta 1337
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1338
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1339
					String serialNumber = inventorySerialNumberEntry.getValue();
1340
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1341
					if (serialNumbersConsidered.contains(serialNumber)) {
1342
						// This will rollback scheme for differenct orders for same serial
1343
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1344
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1345
								.filter(x -> x.getRolledBackTimestamp() == null
1346
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1347
								.collect(Collectors.toList());
1348
						Collections.reverse(sios);
1349
						for (SchemeInOut sio : sios) {
1350
							sio.setRolledBackTimestamp(LocalDateTime.now());
1351
							amountToRollback += sio.getAmount();
1352
							// sio.setSchemeType(SchemeType.OUT);
1353
							sio.setSerialNumber(serialNumber);
1354
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1355
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1356
							rolledbackSios.add(sio);
24623 amit.gupta 1357
						}
24635 amit.gupta 1358
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1359
					} else {
1360
						serialNumbersConsidered.add(serialNumber);
1361
						List<Integer> schemesConsidered = new ArrayList<>();
1362
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1363
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1364
								.filter(x -> x.getRolledBackTimestamp() == null
1365
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1366
								.collect(Collectors.toList());
1367
						Collections.reverse(sios);
1368
						for (SchemeInOut sio : sios) {
1369
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1370
								schemesConsidered.add(sio.getSchemeId());
1371
								continue;
1372
							}
1373
							sio.setRolledBackTimestamp(LocalDateTime.now());
1374
							amountToRollback += sio.getAmount();
1375
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1376
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1377
							sio.setSerialNumber(serialNumber);
1378
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1379
							rolledbackSios.add(sio);
1380
						}
24615 amit.gupta 1381
					}
24631 amit.gupta 1382
 
24604 amit.gupta 1383
				}
24590 amit.gupta 1384
			}
24631 amit.gupta 1385
			if (amountToRollback > 0) {
1386
				UserWalletHistory uwh = new UserWalletHistory();
1387
				uwh.setAmount(Math.round(amountToRollback));
1388
				uwh.setDescription(description);
1389
				uwh.setTimestamp(LocalDateTime.now());
1390
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1391
				uwh.setReference(fofoOrder.getId());
1392
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1393
				uwh.setFofoId(fofoOrder.getFofoId());
1394
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1395
				userWalletHistory.add(uwh);
1396
			}
24590 amit.gupta 1397
		});
24598 amit.gupta 1398
 
24592 amit.gupta 1399
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1400
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1401
						"Timestamp"),
1402
				userWalletHistory.stream()
1403
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1404
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1405
						.collect(Collectors.toList()));
1406
 
1407
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1408
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1409
						"Rolledback"),
1410
				rolledbackSios.stream()
1411
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1412
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1413
						.collect(Collectors.toList()));
1414
 
25043 amit.gupta 1415
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1416
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1417
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1418
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1419
 
25267 amit.gupta 1420
		throw new Exception();
24590 amit.gupta 1421
	}
24615 amit.gupta 1422
 
24611 amit.gupta 1423
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1424
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1425
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1426
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1427
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1428
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1429
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1430
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1431
		references.stream().forEach(reference -> {
1432
			FofoOrder fofoOrder = null;
1433
			try {
1434
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1435
			} catch (Exception e) {
1436
 
24611 amit.gupta 1437
			}
1438
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1439
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1440
			float amountToRollback = 0;
1441
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1442
			orderItems.forEach(x -> {
1443
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1444
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1445
			});
1446
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1447
				List<SchemeInOut> sios = schemeInOutRepository
1448
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1449
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1450
						.collect(Collectors.toList());
1451
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1452
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1453
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1454
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1455
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1456
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1457
					if (outList.size() > 1) {
1458
 
24611 amit.gupta 1459
					}
1460
				}
1461
				uwh.setAmount(Math.round(amountToRollback));
1462
				uwh.setDescription(description);
1463
				uwh.setTimestamp(LocalDateTime.now());
1464
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1465
				uwh.setReference(fofoOrder.getId());
1466
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1467
				uwh.setFofoId(fofoOrder.getFofoId());
1468
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1469
				userWalletHistory.add(uwh);
1470
			}
1471
		});
24615 amit.gupta 1472
 
24611 amit.gupta 1473
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1474
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1475
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1476
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1477
						.collect(Collectors.toList()));
1478
 
24611 amit.gupta 1479
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1480
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1481
						"Rolledback"),
1482
				rolledbackSios.stream()
24615 amit.gupta 1483
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1484
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1485
						.collect(Collectors.toList()));
1486
 
24623 amit.gupta 1487
		Utils.sendMailWithAttachments(googleMailSender,
1488
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1489
				"Partner Excess Amount", "PFA",
1490
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1491
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1492
 
24628 amit.gupta 1493
		throw new Exception();
24615 amit.gupta 1494
 
24611 amit.gupta 1495
	}
24615 amit.gupta 1496
 
26945 amit.gupta 1497
	public void sendDailySalesNotificationToPartner(Integer fofoIdInt) throws Exception {
25927 amit.gupta 1498
 
24653 govind 1499
		LocalDateTime now = LocalDateTime.now();
25837 amit.gupta 1500
		LocalDateTime from = now.with(LocalTime.MIN);
25925 amit.gupta 1501
		String timeString = "Today %s";
25927 amit.gupta 1502
		// Send yesterday's report
27007 amit.gupta 1503
		/*
1504
		 * if (now.getHour() < 13) { timeString = "Yesterday %s"; from =
1505
		 * now.minusDays(1).; now = from.with(LocalTime.MAX);
1506
		 * 
1507
		 * }
1508
		 */
24855 amit.gupta 1509
		List<Integer> fofoIds = null;
25043 amit.gupta 1510
		if (fofoIdInt == null) {
1511
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1512
					.collect(Collectors.toList());
24856 amit.gupta 1513
		} else {
24855 amit.gupta 1514
			fofoIds = Arrays.asList(fofoIdInt);
1515
		}
25912 amit.gupta 1516
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
24683 amit.gupta 1517
 
25865 amit.gupta 1518
		Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1519
				null);
1520
		Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
26945 amit.gupta 1521
 
1522
		Map<Integer, Double> spPartnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1523
				true);
1524
 
1525
		Map<Integer, Double> spPartner3DaysOrderValMap = fofoOrderItemRepository
1526
				.selectSumAmountGroupByRetailer(from.minusDays(3), now, 0, true);
26941 amit.gupta 1527
		Map<Integer, Long> spPartnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
1528
 
26945 amit.gupta 1529
		Map<Integer, Double> partnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1530
				false);
26941 amit.gupta 1531
		Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, false);
26945 amit.gupta 1532
 
25865 amit.gupta 1533
		Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
1534
		for (int fofoId : fofoIds) {
1535
			SaleTargetReportModel model = new SaleTargetReportModel();
25927 amit.gupta 1536
			model.setInsuranceSale(
1537
					partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
25865 amit.gupta 1538
			model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
26941 amit.gupta 1539
			model.setSmartphoneSale(spPartnerOrderValMap.containsKey(fofoId) ? spPartnerOrderValMap.get(fofoId) : 0);
1540
			model.setSmartphoneQty(spPartnerOrderQtyMap.containsKey(fofoId) ? spPartnerOrderQtyMap.get(fofoId) : 0);
1541
			model.setTotalSale(partnerOrderValMap.containsKey(fofoId) ? partnerOrderValMap.get(fofoId) : 0);
1542
			model.setTotalQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
26945 amit.gupta 1543
			model.setPast3daysSale(
1544
					spPartner3DaysOrderValMap.containsKey(fofoId) ? spPartner3DaysOrderValMap.get(fofoId) : 0);
25880 amit.gupta 1545
			model.setFofoId(fofoId);
25865 amit.gupta 1546
			saleTargetReportModelMap.put(fofoId, model);
1547
		}
25880 amit.gupta 1548
 
26945 amit.gupta 1549
		Map<Integer, FofoReportingModel> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
24653 govind 1550
		for (Integer fofoId : fofoIds) {
25865 amit.gupta 1551
			SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
25821 amit.gupta 1552
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1553
			sendNotificationModel.setCampaignName("Sales update alert");
25884 tejbeer 1554
			sendNotificationModel.setTitle("Sale Update");
25927 amit.gupta 1555
			sendNotificationModel
1556
					.setMessage(String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1557
							model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1558
							String.format(timeString, now.format(timeFormatter))));
25821 amit.gupta 1559
			sendNotificationModel.setType("url");
26564 amit.gupta 1560
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25821 amit.gupta 1561
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1562
			sendNotificationModel.setMessageType(MessageType.notification);
25872 tejbeer 1563
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1564
			sendNotificationModel.setUserIds(Arrays.asList(userId));
25854 amit.gupta 1565
			notificationService.sendNotification(sendNotificationModel);
24653 govind 1566
		}
26945 amit.gupta 1567
		// String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap,
1568
		// saleTargetReportModelMap);
1569
		String statewiseSaleReport = this.getStateWiseSales(saleTargetReportModelMap, partnerSalesHeadersMap);
27116 amit.gupta 1570
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "amit.babu@smartdukaan.com",
26945 amit.gupta 1571
				"niranjan.kala@smartdukaan.com", "up.singh@smartdukaan.com", "sm@smartdukaan.com" };
25837 amit.gupta 1572
 
25912 amit.gupta 1573
		String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
26945 amit.gupta 1574
		// this.sendMailOfHtmlFomat("amit.gupta@smartukaan.com", saleReport, cc,
1575
		// subject);
1576
		this.sendMailOfHtmlFormat("amit.gupta@smartdukaan.com", statewiseSaleReport, cc, "Statewise" + subject);
24653 govind 1577
	}
1578
 
25865 amit.gupta 1579
	public static class SaleTargetReportModel {
1580
		private double totalSale;
26941 amit.gupta 1581
		private long totalQty;
26945 amit.gupta 1582
		private double past3daysSale;
25880 amit.gupta 1583
		private int fofoId;
1584
 
1585
		public int getFofoId() {
1586
			return fofoId;
1587
		}
1588
 
1589
		public void setFofoId(int fofoId) {
1590
			this.fofoId = fofoId;
1591
		}
1592
 
25865 amit.gupta 1593
		private double smartphoneSale;
1594
		private long smartphoneQty;
1595
		private double insuranceSale;
1596
		private long insruanceQty;
1597
 
26941 amit.gupta 1598
		public long getTotalQty() {
1599
			return totalQty;
1600
		}
1601
 
1602
		public void setTotalQty(long totalQty) {
1603
			this.totalQty = totalQty;
1604
		}
1605
 
26945 amit.gupta 1606
		public double getPast3daysSale() {
1607
			return past3daysSale;
1608
		}
1609
 
1610
		public void setPast3daysSale(double past3daysSale) {
1611
			this.past3daysSale = past3daysSale;
1612
		}
1613
 
25865 amit.gupta 1614
		@Override
1615
		public int hashCode() {
1616
			final int prime = 31;
1617
			int result = 1;
25880 amit.gupta 1618
			result = prime * result + fofoId;
25865 amit.gupta 1619
			result = prime * result + (int) (insruanceQty ^ (insruanceQty >>> 32));
1620
			long temp;
1621
			temp = Double.doubleToLongBits(insuranceSale);
1622
			result = prime * result + (int) (temp ^ (temp >>> 32));
1623
			result = prime * result + (int) (smartphoneQty ^ (smartphoneQty >>> 32));
1624
			temp = Double.doubleToLongBits(smartphoneSale);
1625
			result = prime * result + (int) (temp ^ (temp >>> 32));
26941 amit.gupta 1626
			result = prime * result + (int) (totalQty ^ (totalQty >>> 32));
25865 amit.gupta 1627
			temp = Double.doubleToLongBits(totalSale);
1628
			result = prime * result + (int) (temp ^ (temp >>> 32));
1629
			return result;
1630
		}
1631
 
1632
		@Override
1633
		public boolean equals(Object obj) {
1634
			if (this == obj)
1635
				return true;
1636
			if (obj == null)
1637
				return false;
1638
			if (getClass() != obj.getClass())
1639
				return false;
1640
			SaleTargetReportModel other = (SaleTargetReportModel) obj;
25880 amit.gupta 1641
			if (fofoId != other.fofoId)
1642
				return false;
25865 amit.gupta 1643
			if (insruanceQty != other.insruanceQty)
1644
				return false;
1645
			if (Double.doubleToLongBits(insuranceSale) != Double.doubleToLongBits(other.insuranceSale))
1646
				return false;
1647
			if (smartphoneQty != other.smartphoneQty)
1648
				return false;
1649
			if (Double.doubleToLongBits(smartphoneSale) != Double.doubleToLongBits(other.smartphoneSale))
1650
				return false;
26941 amit.gupta 1651
			if (totalQty != other.totalQty)
1652
				return false;
25865 amit.gupta 1653
			if (Double.doubleToLongBits(totalSale) != Double.doubleToLongBits(other.totalSale))
1654
				return false;
1655
			return true;
1656
		}
1657
 
1658
		public double getTotalSale() {
1659
			return totalSale;
1660
		}
1661
 
1662
		public void setTotalSale(double totalSale) {
1663
			this.totalSale = totalSale;
1664
		}
1665
 
1666
		public double getSmartphoneSale() {
1667
			return smartphoneSale;
1668
		}
1669
 
1670
		public void setSmartphoneSale(double smartphoneSale) {
1671
			this.smartphoneSale = smartphoneSale;
1672
		}
1673
 
1674
		public long getSmartphoneQty() {
1675
			return smartphoneQty;
1676
		}
1677
 
1678
		public void setSmartphoneQty(long smartphoneQty) {
1679
			this.smartphoneQty = smartphoneQty;
1680
		}
1681
 
1682
		public double getInsuranceSale() {
1683
			return insuranceSale;
1684
		}
1685
 
1686
		public void setInsuranceSale(double insuranceSale) {
1687
			this.insuranceSale = insuranceSale;
1688
		}
1689
 
1690
		public long getInsruanceQty() {
1691
			return insruanceQty;
1692
		}
1693
 
1694
		public void setInsruanceQty(long insruanceQty) {
1695
			this.insruanceQty = insruanceQty;
1696
		}
1697
 
1698
		@Override
1699
		public String toString() {
26945 amit.gupta 1700
			return "SaleTargetReportModel [totalSale=" + totalSale + ", totalQty=" + totalQty + ", past3daysSale="
1701
					+ past3daysSale + ", fofoId=" + fofoId + ", smartphoneSale=" + smartphoneSale + ", smartphoneQty="
1702
					+ smartphoneQty + ", insuranceSale=" + insuranceSale + ", insruanceQty=" + insruanceQty + "]";
25865 amit.gupta 1703
		}
1704
 
1705
	}
1706
 
26945 amit.gupta 1707
	private String getStateWiseSales(Map<Integer, SaleTargetReportModel> saleTargetReportModelMap,
1708
			Map<Integer, FofoReportingModel> partnerSalesHeadersMap) throws Exception {
26940 amit.gupta 1709
		List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
26945 amit.gupta 1710
		Map<String, List<Integer>> stateMap = stores.stream().collect(Collectors
1711
				.groupingBy(x -> x.getCode().substring(0, 2), Collectors.mapping(x -> x.getId(), Collectors.toList())));
26940 amit.gupta 1712
		List<List<Serializable>> stateWiseSales = new ArrayList<>();
1713
		for (Map.Entry<String, List<Integer>> stateMapEntry : stateMap.entrySet()) {
26945 amit.gupta 1714
			long totalQty = stateMapEntry.getValue().stream()
1715
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getTotalQty()));
1716
			double totalSale = stateMapEntry.getValue().stream()
1717
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getTotalSale()));
1718
			long smartPhoneQty = stateMapEntry.getValue().stream()
1719
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getSmartphoneQty()));
1720
			double smartPhoneSale = stateMapEntry.getValue().stream()
1721
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getSmartphoneSale()));
1722
			stateWiseSales
1723
					.add(Arrays.asList(stateMapEntry.getKey(), smartPhoneQty, smartPhoneSale, totalQty, totalSale));
26940 amit.gupta 1724
		}
1725
		StringBuilder sb = new StringBuilder();
26945 amit.gupta 1726
		sb.append("<html><body>");
1727
		sb.append("<p>Statewise Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
26940 amit.gupta 1728
		sb.append("<tbody>\n" + "	    <tr>"
1729
				+ "	    					<th style='border:1px solid black;padding: 5px'>State</th>"
26941 amit.gupta 1730
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
1731
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Value</th>"
1732
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Qty</th>"
1733
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Value</th>"
26940 amit.gupta 1734
				+ "	    				</tr>");
1735
		for (List<Serializable> stateSale : stateWiseSales) {
1736
			sb.append("<tr>");
1737
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(0) + "</td>");
1738
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(1) + "</td>");
1739
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(2) + "</td>");
26941 amit.gupta 1740
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(3) + "</td>");
1741
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(4) + "</td>");
26940 amit.gupta 1742
			sb.append("</tr>");
1743
		}
26945 amit.gupta 1744
		sb.append("</tbody></table><br><br>");
25872 tejbeer 1745
 
26945 amit.gupta 1746
		sb.append("<p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 1747
		sb.append("<tbody>\n" + "	    				<tr>\n"
26945 amit.gupta 1748
				+ "	    					<th style='border:1px solid black;padding: 5px'>Code</th>"
1749
				+ "	    					<th style='border:1px solid black;padding: 5px'>Business Name</th>"
1750
				+ "	    					<th style='border:1px solid black;padding: 5px'>Regional Manager</th>"
1751
				+ "	    					<th style='border:1px solid black;padding: 5px'>Territory Manager</th>"
1752
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>"
1753
				+ "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>"
1754
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
24653 govind 1755
				+ "	    				</tr>");
26945 amit.gupta 1756
 
1757
		List<Integer> sortedPartnerSalesHeaders = partnerSalesHeadersMap.values().stream()
26947 amit.gupta 1758
				.sorted(Comparator.comparing(FofoReportingModel::getCode)
1759
						.thenComparing(FofoReportingModel::getRegionalManager)
26948 amit.gupta 1760
						.thenComparing(FofoReportingModel::getTerritoryManager))
26945 amit.gupta 1761
				.map(FofoReportingModel::getFofoId).collect(Collectors.toList());
25927 amit.gupta 1762
		for (Integer fofoId : sortedPartnerSalesHeaders) {
27007 amit.gupta 1763
			if (saleTargetReportModelMap.get(fofoId).getPast3daysSale() == 0) {
26947 amit.gupta 1764
				sb.append("<tr style='background-color:red'>");
1765
			} else {
26945 amit.gupta 1766
				sb.append("<tr>");
1767
			}
1768
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getCode()
25880 amit.gupta 1769
					+ "</td>");
1770
			sb.append("<td style='border:1px solid black;padding: 5px'>"
27007 amit.gupta 1771
					+ partnerSalesHeadersMap.get(fofoId).getBusinessName() + "</td>");
1772
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1773
					+ partnerSalesHeadersMap.get(fofoId).getRegionalManager() + "</td>");
1774
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1775
					+ partnerSalesHeadersMap.get(fofoId).getTerritoryManager() + "</td>");
1776
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1777
					+ saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
25880 amit.gupta 1778
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1779
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
25880 amit.gupta 1780
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 1781
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
25865 amit.gupta 1782
			sb.append("</tr>");
24653 govind 1783
		}
24683 amit.gupta 1784
 
26945 amit.gupta 1785
		sb.append("</tr>");
1786
 
1787
		sb.append("</body></html>");
1788
 
1789
		return sb.toString();
24653 govind 1790
	}
24841 govind 1791
 
26945 amit.gupta 1792
	private void sendMailOfHtmlFormat(String email, String body, String cc[], String subject)
24841 govind 1793
			throws MessagingException, ProfitMandiBusinessException, IOException {
1794
		MimeMessage message = mailSender.createMimeMessage();
1795
		MimeMessageHelper helper = new MimeMessageHelper(message);
1796
		helper.setSubject(subject);
1797
		helper.setText(body, true);
1798
		helper.setTo(email);
1799
		if (cc != null) {
1800
			helper.setCc(cc);
1801
		}
1802
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1803
		helper.setFrom(senderAddress);
1804
		mailSender.send(message);
1805
	}
25300 tejbeer 1806
 
25351 tejbeer 1807
	public void sendNotification() throws Exception {
25300 tejbeer 1808
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1809
		if (!pushNotifications.isEmpty()) {
1810
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1811
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1812
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1813
						.selectById(pushNotification.getNotificationCampaignid());
1814
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1815
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1816
 
1817
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1818
						SimpleCampaignParams.class);
1819
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1820
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1821
				JSONObject json = new JSONObject();
25351 tejbeer 1822
				json.put("to", device.getFcmId());
25300 tejbeer 1823
				JSONObject jsonObj = new JSONObject();
1824
				jsonObj.put("message", campaign.getMessage());
1825
				jsonObj.put("title", campaign.getTitle());
1826
				jsonObj.put("type", campaign.getType());
1827
				jsonObj.put("url", result_url);
1828
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1829
				jsonObj.put("image", campaign.getImageUrl());
1830
				jsonObj.put("largeIcon", "large_icon");
1831
				jsonObj.put("smallIcon", "small_icon");
1832
				jsonObj.put("vibrate", 1);
1833
				jsonObj.put("pid", pushNotification.getId());
1834
				jsonObj.put("sound", 1);
1835
				jsonObj.put("priority", "high");
1836
				json.put("data", jsonObj);
25351 tejbeer 1837
				try {
1838
					CloseableHttpClient client = HttpClients.createDefault();
1839
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1840
 
25351 tejbeer 1841
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1842
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1843
					StringEntity entity = new StringEntity(json.toString());
1844
					httpPost.setEntity(entity);
1845
					CloseableHttpResponse response = client.execute(httpPost);
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
}