Subversion Repositories SmartDukaan

Rev

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