Subversion Repositories SmartDukaan

Rev

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

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