Subversion Repositories SmartDukaan

Rev

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