Subversion Repositories SmartDukaan

Rev

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