Subversion Repositories SmartDukaan

Rev

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

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