Subversion Repositories SmartDukaan

Rev

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