Subversion Repositories SmartDukaan

Rev

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