Subversion Repositories SmartDukaan

Rev

Rev 26862 | Rev 26940 | 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, Double> salesByFofoIdMap = new HashMap<>();
1384
		Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1385
				null);
1386
		Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
1387
		Map<Integer, Double> partnerOrderAmountMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now,
1388
				0, true);
1389
		Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
1390
		Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
1391
		for (int fofoId : fofoIds) {
1392
			SaleTargetReportModel model = new SaleTargetReportModel();
25927 amit.gupta 1393
			model.setInsuranceSale(
1394
					partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
25865 amit.gupta 1395
			model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
1396
			model.setSmartphoneSale(partnerOrderAmountMap.containsKey(fofoId) ? partnerOrderAmountMap.get(fofoId) : 0);
1397
			model.setSmartphoneQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
1398
			model.setTotalSale(salesByFofoIdMap.containsKey(fofoId) ? salesByFofoIdMap.get(fofoId) : 0);
25880 amit.gupta 1399
			model.setFofoId(fofoId);
25865 amit.gupta 1400
			saleTargetReportModelMap.put(fofoId, model);
1401
		}
25880 amit.gupta 1402
 
25865 amit.gupta 1403
		Map<Integer, List<Serializable>> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
24653 govind 1404
		for (Integer fofoId : fofoIds) {
25865 amit.gupta 1405
			SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
25821 amit.gupta 1406
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1407
			sendNotificationModel.setCampaignName("Sales update alert");
25884 tejbeer 1408
			sendNotificationModel.setTitle("Sale Update");
25927 amit.gupta 1409
			sendNotificationModel
1410
					.setMessage(String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1411
							model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1412
							String.format(timeString, now.format(timeFormatter))));
25821 amit.gupta 1413
			sendNotificationModel.setType("url");
26564 amit.gupta 1414
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25821 amit.gupta 1415
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1416
			sendNotificationModel.setMessageType(MessageType.notification);
25872 tejbeer 1417
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1418
			sendNotificationModel.setUserIds(Arrays.asList(userId));
25854 amit.gupta 1419
			notificationService.sendNotification(sendNotificationModel);
24653 govind 1420
		}
25865 amit.gupta 1421
		String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap, saleTargetReportModelMap);
24653 govind 1422
		LOGGER.info(saleReport);
25837 amit.gupta 1423
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com",
25846 amit.gupta 1424
				"chaitnaya.vats@smartdukaan.com" };
25837 amit.gupta 1425
 
25912 amit.gupta 1426
		String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
25821 amit.gupta 1427
		this.sendMailOfHtmlFomat("amit.gupta@shop2020.in", saleReport, cc, subject);
24653 govind 1428
	}
1429
 
25865 amit.gupta 1430
	public static class SaleTargetReportModel {
1431
		private double totalSale;
25880 amit.gupta 1432
		private int fofoId;
1433
 
1434
		public int getFofoId() {
1435
			return fofoId;
1436
		}
1437
 
1438
		public void setFofoId(int fofoId) {
1439
			this.fofoId = fofoId;
1440
		}
1441
 
25865 amit.gupta 1442
		private double smartphoneSale;
1443
		private long smartphoneQty;
1444
		private double insuranceSale;
1445
		private long insruanceQty;
1446
 
1447
		@Override
1448
		public int hashCode() {
1449
			final int prime = 31;
1450
			int result = 1;
25880 amit.gupta 1451
			result = prime * result + fofoId;
25865 amit.gupta 1452
			result = prime * result + (int) (insruanceQty ^ (insruanceQty >>> 32));
1453
			long temp;
1454
			temp = Double.doubleToLongBits(insuranceSale);
1455
			result = prime * result + (int) (temp ^ (temp >>> 32));
1456
			result = prime * result + (int) (smartphoneQty ^ (smartphoneQty >>> 32));
1457
			temp = Double.doubleToLongBits(smartphoneSale);
1458
			result = prime * result + (int) (temp ^ (temp >>> 32));
1459
			temp = Double.doubleToLongBits(totalSale);
1460
			result = prime * result + (int) (temp ^ (temp >>> 32));
1461
			return result;
1462
		}
1463
 
1464
		@Override
1465
		public boolean equals(Object obj) {
1466
			if (this == obj)
1467
				return true;
1468
			if (obj == null)
1469
				return false;
1470
			if (getClass() != obj.getClass())
1471
				return false;
1472
			SaleTargetReportModel other = (SaleTargetReportModel) obj;
25880 amit.gupta 1473
			if (fofoId != other.fofoId)
1474
				return false;
25865 amit.gupta 1475
			if (insruanceQty != other.insruanceQty)
1476
				return false;
1477
			if (Double.doubleToLongBits(insuranceSale) != Double.doubleToLongBits(other.insuranceSale))
1478
				return false;
1479
			if (smartphoneQty != other.smartphoneQty)
1480
				return false;
1481
			if (Double.doubleToLongBits(smartphoneSale) != Double.doubleToLongBits(other.smartphoneSale))
1482
				return false;
1483
			if (Double.doubleToLongBits(totalSale) != Double.doubleToLongBits(other.totalSale))
1484
				return false;
1485
			return true;
1486
		}
1487
 
1488
		public double getTotalSale() {
1489
			return totalSale;
1490
		}
1491
 
1492
		public void setTotalSale(double totalSale) {
1493
			this.totalSale = totalSale;
1494
		}
1495
 
1496
		public double getSmartphoneSale() {
1497
			return smartphoneSale;
1498
		}
1499
 
1500
		public void setSmartphoneSale(double smartphoneSale) {
1501
			this.smartphoneSale = smartphoneSale;
1502
		}
1503
 
1504
		public long getSmartphoneQty() {
1505
			return smartphoneQty;
1506
		}
1507
 
1508
		public void setSmartphoneQty(long smartphoneQty) {
1509
			this.smartphoneQty = smartphoneQty;
1510
		}
1511
 
1512
		public double getInsuranceSale() {
1513
			return insuranceSale;
1514
		}
1515
 
1516
		public void setInsuranceSale(double insuranceSale) {
1517
			this.insuranceSale = insuranceSale;
1518
		}
1519
 
1520
		public long getInsruanceQty() {
1521
			return insruanceQty;
1522
		}
1523
 
1524
		public void setInsruanceQty(long insruanceQty) {
1525
			this.insruanceQty = insruanceQty;
1526
		}
1527
 
1528
		@Override
1529
		public String toString() {
25880 amit.gupta 1530
			return "SaleTargetReportModel [totalSale=" + totalSale + ", fofoId=" + fofoId + ", smartphoneSale="
1531
					+ smartphoneSale + ", smartphoneQty=" + smartphoneQty + ", insuranceSale=" + insuranceSale
1532
					+ ", insruanceQty=" + insruanceQty + "]";
25865 amit.gupta 1533
		}
1534
 
1535
	}
1536
 
1537
	private String getDailySalesReportHtml(Map<Integer, List<Serializable>> partnerSalesHeadersMap,
25872 tejbeer 1538
			Map<Integer, SaleTargetReportModel> saleReportTargetMap) throws ProfitMandiBusinessException {
24653 govind 1539
		StringBuilder sb = new StringBuilder();
25872 tejbeer 1540
 
25832 amit.gupta 1541
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 1542
		sb.append("<tbody>\n" + "	    				<tr>\n"
25865 amit.gupta 1543
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1544
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1545
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1546
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1547
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
24653 govind 1548
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
25865 amit.gupta 1549
				+ "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>\n"
1550
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>\n"
1551
				+ "	    					<th style='border:1px solid black;padding: 5px'>Insurance Sale</th>\n"
1552
				+ "	    					<th style='border:1px solid black;padding: 5px'>Insurance Qty</th>\n"
24653 govind 1553
				+ "	    				</tr>");
25880 amit.gupta 1554
		List<Integer> sortedPartnerSalesHeaders = partnerSalesHeadersMap.entrySet().stream()
1555
				.sorted((x, y) -> ((String) (x.getValue().get(3))).compareTo((String) (y.getValue().get(3))))
25927 amit.gupta 1556
				.map(x -> x.getKey()).collect(Collectors.toList());
1557
		for (Integer fofoId : sortedPartnerSalesHeaders) {
25865 amit.gupta 1558
			sb.append("<tr>");
25880 amit.gupta 1559
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(0)
1560
					+ "</td>");
1561
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(1)
1562
					+ "</td>");
1563
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(2)
1564
					+ "</td>");
1565
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(3)
1566
					+ "</td>");
1567
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(4)
1568
					+ "</td>");
1569
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1570
					+ saleReportTargetMap.get(fofoId).getTotalSale() + "</td>");
1571
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1572
					+ saleReportTargetMap.get(fofoId).getSmartphoneSale() + "</td>");
1573
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1574
					+ saleReportTargetMap.get(fofoId).getSmartphoneQty() + "</td>");
1575
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1576
					+ saleReportTargetMap.get(fofoId).getInsuranceSale() + "</td>");
1577
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1578
					+ saleReportTargetMap.get(fofoId).getInsruanceQty() + "</td>");
25865 amit.gupta 1579
			sb.append("</tr>");
24653 govind 1580
 
1581
		}
24683 amit.gupta 1582
 
24653 govind 1583
		sb.append("</tbody></table></body></html>");
25865 amit.gupta 1584
		return String.format(sb.toString(), REPORT_HEADERS);
24653 govind 1585
	}
24841 govind 1586
 
1587
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1588
			throws MessagingException, ProfitMandiBusinessException, IOException {
1589
		MimeMessage message = mailSender.createMimeMessage();
1590
		MimeMessageHelper helper = new MimeMessageHelper(message);
1591
		helper.setSubject(subject);
1592
		helper.setText(body, true);
1593
		helper.setTo(email);
1594
		if (cc != null) {
1595
			helper.setCc(cc);
1596
		}
1597
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1598
		helper.setFrom(senderAddress);
1599
		mailSender.send(message);
1600
	}
25300 tejbeer 1601
 
25351 tejbeer 1602
	public void sendNotification() throws Exception {
25300 tejbeer 1603
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1604
		if (!pushNotifications.isEmpty()) {
1605
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1606
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1607
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1608
						.selectById(pushNotification.getNotificationCampaignid());
1609
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1610
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1611
 
1612
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1613
						SimpleCampaignParams.class);
1614
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1615
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1616
				JSONObject json = new JSONObject();
25351 tejbeer 1617
				json.put("to", device.getFcmId());
25300 tejbeer 1618
				JSONObject jsonObj = new JSONObject();
1619
				jsonObj.put("message", campaign.getMessage());
1620
				jsonObj.put("title", campaign.getTitle());
1621
				jsonObj.put("type", campaign.getType());
1622
				jsonObj.put("url", result_url);
1623
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1624
				jsonObj.put("image", campaign.getImageUrl());
1625
				jsonObj.put("largeIcon", "large_icon");
1626
				jsonObj.put("smallIcon", "small_icon");
1627
				jsonObj.put("vibrate", 1);
1628
				jsonObj.put("pid", pushNotification.getId());
1629
				jsonObj.put("sound", 1);
1630
				jsonObj.put("priority", "high");
1631
				json.put("data", jsonObj);
25351 tejbeer 1632
				try {
1633
					CloseableHttpClient client = HttpClients.createDefault();
1634
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1635
 
25351 tejbeer 1636
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1637
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1638
					StringEntity entity = new StringEntity(json.toString());
1639
					httpPost.setEntity(entity);
1640
					CloseableHttpResponse response = client.execute(httpPost);
1641
					LOGGER.info("response" + response);
25300 tejbeer 1642
 
25351 tejbeer 1643
					if (response.getStatusLine().getStatusCode() == 200) {
1644
						pushNotification.setSentTimestamp(LocalDateTime.now());
1645
					} else {
25356 tejbeer 1646
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 1647
						LOGGER.info("message" + "not sent");
25351 tejbeer 1648
					}
25300 tejbeer 1649
 
25351 tejbeer 1650
				} catch (Exception e) {
1651
					e.printStackTrace();
26443 amit.gupta 1652
					pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
26436 amit.gupta 1653
					LOGGER.info("message " + "not sent " + e.getMessage());
25300 tejbeer 1654
				}
1655
			}
1656
		}
1657
	}
1658
 
25553 amit.gupta 1659
	public void grouping() throws Exception {
25609 amit.gupta 1660
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
1661
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
1662
		System.out.println(String.join("\t",
1663
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 1664
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
25609 amit.gupta 1665
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers();
1666
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 1667
			if (priceDropIMEI.getPartnerId() == 0)
1668
				continue;
25609 amit.gupta 1669
			HashSet<String> imeis = new HashSet<>();
1670
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
1671
			imeis.add(priceDropIMEI.getImei());
1672
			List<InventoryItem> inventoryItems = inventoryItemRepository
1673
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 1674
			if (inventoryItems.size() == 0) {
1675
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 1676
				continue;
25612 amit.gupta 1677
			}
25609 amit.gupta 1678
			InventoryItem inventoryItem = inventoryItems.get(0);
1679
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
1680
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
1681
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
1682
				// check if pricedrop has been rolled out
1683
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
1684
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
1685
				if (uwh.size() > 0) {
25615 amit.gupta 1686
					Item item = itemRepository.selectById(inventoryItem.getItemId());
26862 amit.gupta 1687
					System.out.println(String.join("\t",
1688
							Arrays.asList(priceDropIMEI.getImei(), inventoryItem.getItemId() + "", item.getBrand(),
1689
									item.getModelName(), item.getModelNumber(), inventoryItem.getFofoId() + "",
1690
									customRetailer.getBusinessName(), inventoryItem.getCreateTimestamp().format(dtf),
1691
									priceDrop.getAffectedOn().format(dtf),
1692
									priceDropIMEI.getUpdateTimestamp().format(dtf),
1693
									inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getAutoPartnerPayout() + "",
1694
									inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
25609 amit.gupta 1695
				}
1696
			}
1697
		}
25503 amit.gupta 1698
	}
25694 amit.gupta 1699
 
1700
	public void testToffee() throws Exception {
25846 amit.gupta 1701
		LOGGER.info("Insurance Sum Summary --- {}",
1702
				insurancePolicyRepository.selectAmountSumGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
1703
		LOGGER.info("Insurance Qty Summary --- {}",
1704
				insurancePolicyRepository.selectQtyGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
25854 amit.gupta 1705
		LOGGER.info("SmartPhone Amount Summary --- {}",
25856 amit.gupta 1706
				fofoOrderItemRepository.selectSumAmountGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25854 amit.gupta 1707
		LOGGER.info("Smartphone Qty Summary --- {}",
1708
				fofoOrderItemRepository.selectQtyGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25800 tejbeer 1709
		// LOGGER.info("{}", toffeeService.getAuthToken());
25846 amit.gupta 1710
		/*
1711
		 * LOGGER.info("{}", toffeeService.getProducts()); // LOGGER.info("{}",
1712
		 * toffeeService.getPincodes("36103000PR")); PremiumCalculationRequestModel pcrm
1713
		 * = new PremiumCalculationRequestModel(); pcrm.setProductDetails("36103000PR");
1714
		 * // pcrm.setProductDetails("36103000PR");
1715
		 * pcrm.setDurations(Arrays.asList("3 Months", "6 Months", "1 Year"));
1716
		 * pcrm.setSumInsured("15000");
1717
		 * System.out.println(toffeeService.getPremiumCalculation(pcrm));
1718
		 */
25694 amit.gupta 1719
	}
1720
 
1721
	public void schemeRollback(List<String> schemeIds) throws Exception {
1722
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 1723
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 1724
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1725
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
1726
		for (SchemeInOut sio : schemeInOuts) {
1727
			Scheme scheme = schemesMap.get(sio.getSchemeId());
1728
			if (scheme.getType().equals(SchemeType.IN)) {
1729
 
1730
			} else if (scheme.getType().equals(SchemeType.OUT)) {
1731
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
1732
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
1733
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
1734
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
1735
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
1736
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
1737
					sio.setRolledBackTimestamp(LocalDateTime.now());
1738
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 1739
					String rollbackReason = "Scheme reversed for "
1740
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 1741
							+ fofoOrder.getInvoiceNumber();
1742
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
26862 amit.gupta 1743
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason, LocalDateTime.now());
25694 amit.gupta 1744
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
1745
							rollbackReason);
1746
				}
1747
			}
1748
		}
25721 tejbeer 1749
		// throw new Exception();
25694 amit.gupta 1750
	}
25721 tejbeer 1751
 
1752
	public void checkfocusedModelInPartnerStock() throws Exception {
1753
 
1754
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1755
				.collect(Collectors.toList());
1756
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
1757
		for (Integer fofoId : fofoIds) {
1758
			if (!focusedModelShortageReportMap.containsKey(fofoId)) {
1759
				focusedModelShortageReportMap.put(fofoId, new ArrayList<>());
1760
			}
1761
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1762
			Map<Integer, Integer> processingOrderMap = null;
1763
			Map<Integer, Integer> catalogIdAndQtyMap = null;
1764
			Map<Integer, Integer> grnPendingOrdersMap = null;
1765
 
1766
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1767
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1768
 
1769
			if (!currentInventorySnapshot.isEmpty()) {
1770
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1771
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1772
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1773
 
1774
			}
1775
 
1776
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1777
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1778
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1779
			if (!grnPendingOrders.isEmpty()) {
1780
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1781
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1782
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1783
 
1784
			}
1785
 
1786
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1787
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1788
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1789
			if (!processingOrder.isEmpty()) {
1790
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1791
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1792
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1793
 
1794
			}
1795
 
25800 tejbeer 1796
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1797
					.collect(Collectors.toList());
1798
 
1799
			List<Integer> focusedModelCatalogId = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
1800
					.collect(Collectors.toList());
1801
			Map<String, Object> equalsMap = new HashMap<>();
1802
			equalsMap.put("categoryId", 10006);
1803
			equalsMap.put("brand", brands);
1804
 
1805
			Map<String, List<?>> notEqualsMap = new HashMap<>();
1806
 
1807
			Map<String, Object> equalsJoinMap = new HashMap<>();
1808
			equalsJoinMap.put("catalogId", focusedModelCatalogId);
1809
 
1810
			Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1811
 
1812
			List<Integer> catalogIds = itemRepository
1813
					.selectItems(FocusedModel.class, "catalogItemId", "catalogId", equalsMap, notEqualsMap,
1814
							equalsJoinMap, notEqualsJoinMap, "minimumQty")
1815
					.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
1816
 
1817
			Map<Integer, Integer> focusedCatalogIdAndQtyMap = focusedModelRepository.selectByCatalogIdsl(catalogIds)
1818
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getMinimumQty()));
1819
 
1820
			/*
1821
			 * Map<Integer, Integer> focusedCatalogIdAndQtyMap =
1822
			 * focusedModelRepository.selectAll().stream() .collect(Collectors.toMap(x ->
1823
			 * x.getCatalogId(), x -> x.getMinimumQty()));
1824
			 */
1825
 
25721 tejbeer 1826
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
1827
 
1828
			for (Map.Entry<Integer, Integer> entry : focusedCatalogIdAndQtyMap.entrySet()) {
1829
				int inStockQty = 0;
1830
				int processingQty = 0;
1831
				int grnPendingQty = 0;
1832
				if (processingOrderMap != null) {
1833
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
1834
							: processingOrderMap.get(entry.getKey());
1835
 
1836
				}
1837
				if (grnPendingOrdersMap != null) {
1838
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
1839
							: grnPendingOrdersMap.get(entry.getKey());
1840
 
1841
				}
1842
				if (catalogIdAndQtyMap != null) {
1843
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
1844
							: catalogIdAndQtyMap.get(entry.getKey());
1845
 
1846
				}
1847
				int totalQty = processingQty + grnPendingQty + inStockQty;
1848
 
1849
				if (totalQty < entry.getValue()) {
1850
 
1851
					int shortageQty = entry.getValue() - totalQty;
1852
					List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
1853
 
1854
					FocusedModelShortageModel fm = new FocusedModelShortageModel();
1855
					fm.setFofoId(fofoId);
1856
					fm.setStoreName(customRetailer.getBusinessName());
1857
 
1858
					fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
1859
					fm.setShortageQty(shortageQty);
1860
 
1861
					focusedModelShortageReportMap.get(fofoId).add(fm);
1862
				}
1863
 
1864
			}
1865
			List<FocusedModelShortageModel> focusedModelShortageModel = focusedModelShortageReportMap.get(fofoId);
1866
 
1867
			if (!focusedModelShortageModel.isEmpty()) {
1868
				String subject = "Stock Alert";
1869
				String messageText = this.getMessage(focusedModelShortageModel);
1870
 
25732 tejbeer 1871
				this.sendMailWithAttachments(subject, messageText, customRetailer.getEmail());
25721 tejbeer 1872
				String notificationMessage = this.getNotificationMessage(focusedModelShortageModel);
1873
 
1874
				LOGGER.info("notificationMessage" + notificationMessage);
1875
 
25872 tejbeer 1876
				SendNotificationModel sendNotificationModel = new SendNotificationModel();
1877
				sendNotificationModel.setCampaignName("Stock Alert");
1878
				sendNotificationModel.setTitle("Alert");
1879
				sendNotificationModel.setMessage(notificationMessage);
1880
				sendNotificationModel.setType("url");
26564 amit.gupta 1881
				sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25872 tejbeer 1882
				sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1883
				sendNotificationModel.setMessageType(MessageType.notification);
25732 tejbeer 1884
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
25872 tejbeer 1885
				sendNotificationModel.setUserIds(Arrays.asList(userId));
1886
				notificationService.sendNotification(sendNotificationModel);
25721 tejbeer 1887
 
1888
			}
25732 tejbeer 1889
 
25721 tejbeer 1890
		}
25800 tejbeer 1891
		if (!focusedModelShortageReportMap.isEmpty())
25721 tejbeer 1892
 
25800 tejbeer 1893
		{
1894
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
1895
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
25837 amit.gupta 1896
			Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 1897
 
25800 tejbeer 1898
			focusedModelShortageReportMap.entrySet().forEach(x -> {
1899
				storeGuyMap.entrySet().forEach(y -> {
1900
 
1901
					if (y.getValue().contains(x.getKey())) {
1902
						if (!emailRowsMap.containsKey(y.getKey())) {
1903
							emailRowsMap.put(y.getKey(), new ArrayList<>());
1904
						}
1905
						List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays
1906
								.asList(r.getFofoId(), r.getStoreName(), r.getItemName(), r.getShortageQty()))
1907
								.collect(Collectors.toList());
1908
						emailRowsMap.get(y.getKey()).addAll(fms);
1909
 
25721 tejbeer 1910
					}
1911
 
25800 tejbeer 1912
				});
25721 tejbeer 1913
 
1914
			});
1915
 
25800 tejbeer 1916
			List<String> headers = Arrays.asList("Partner Id", "Partner Name", "Model Name", "Shortage Qty");
25837 amit.gupta 1917
			emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 1918
 
25800 tejbeer 1919
				ByteArrayOutputStream baos = null;
1920
				try {
25837 amit.gupta 1921
					baos = FileUtil.getCSVByteStream(headers, entry.getValue());
25800 tejbeer 1922
				} catch (Exception e2) {
1923
					e2.printStackTrace();
1924
				}
25837 amit.gupta 1925
				String[] sendToArray = new String[] { entry.getKey() };
25800 tejbeer 1926
				try {
1927
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
1928
							new ByteArrayResource(baos.toByteArray()));
1929
				} catch (Exception e1) { // TODO Auto-generated catch block
1930
					e1.printStackTrace();
1931
				}
25721 tejbeer 1932
 
25800 tejbeer 1933
			});
1934
		}
25721 tejbeer 1935
	}
1936
 
1937
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1938
		StringBuilder sb = new StringBuilder();
1939
		sb.append("Focused Model Shortage in Your Stock : \n");
1940
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1941
 
1942
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
1943
			sb.append(String.format("%n", ""));
1944
		}
1945
		return sb.toString();
1946
	}
1947
 
1948
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
1949
		MimeMessage message = mailSender.createMimeMessage();
1950
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
1951
 
1952
		helper.setSubject(subject);
1953
		helper.setText(messageText, true);
1954
		helper.setTo(email);
26032 amit.gupta 1955
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smatdukaan Alerts");
25721 tejbeer 1956
		helper.setFrom(senderAddress);
1957
		mailSender.send(message);
1958
 
1959
	}
1960
 
1961
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1962
		StringBuilder sb = new StringBuilder();
1963
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
1964
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
1965
		sb.append("<tbody>\n" + "	    				<tr>\n"
1966
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
1967
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
1968
				+ "	    				</tr>");
1969
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1970
 
1971
			sb.append("<tr>");
1972
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
1973
 
1974
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
1975
 
1976
			sb.append("</tr>");
1977
 
1978
		}
1979
 
1980
		sb.append("</tbody></table></body></html>");
1981
 
1982
		return sb.toString();
1983
	}
1984
 
25927 amit.gupta 1985
	public void notifyLead() throws Exception {
1986
		List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(LocalDateTime.now().minusDays(15),
1987
				LocalDateTime.now().plusHours(4));
1988
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
1989
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
25936 amit.gupta 1990
		System.out.printf("authUserEmailMap - %s", authUserEmailMap);
25927 amit.gupta 1991
		Map<String, Integer> dtrEmailMap = dtrUserRepository
1992
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
1993
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25936 amit.gupta 1994
 
1995
		System.out.printf("dtrEmailMap - %s", dtrEmailMap);
26790 tejbeer 1996
 
25927 amit.gupta 1997
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
1998
 
1999
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2000
			int authId = authUserEmail.getKey();
2001
			String email = authUserEmail.getValue();
2002
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2003
		}
25929 amit.gupta 2004
		System.out.println(authUserKeyMap);
2005
		System.out.println(leadsToNotify);
26790 tejbeer 2006
 
25927 amit.gupta 2007
		String templateMessage = "Lead followup for %s %s, %s is due by %s";
2008
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
2009
		for (Lead lead : leadsToNotify) {
2010
			if (authUserKeyMap.get(lead.getAuthId()) == null) {
2011
				continue;
2012
			}
2013
			String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(),
25941 amit.gupta 2014
					lead.getAddress(), timeFormatter.format(lead.getLeadActivity().getSchelduleTimestamp()));
25927 amit.gupta 2015
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2016
			sendNotificationModel.setCampaignName("Lead Reminder");
2017
			sendNotificationModel.setTitle("Leads followup Reminder");
2018
			sendNotificationModel.setMessage(notificationMessage);
2019
			sendNotificationModel.setType("url");
26564 amit.gupta 2020
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2021
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2022
			sendNotificationModel.setMessageType(MessageType.reminder);
26320 tejbeer 2023
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAssignTo())));
25929 amit.gupta 2024
			System.out.println(sendNotificationModel);
25927 amit.gupta 2025
			notificationService.sendNotification(sendNotificationModel);
2026
		}
2027
	}
2028
	public void notifyVisits() throws Exception {
26862 amit.gupta 2029
		List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), 
2030
				LocalDateTime.now().plusHours(4));
25927 amit.gupta 2031
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2032
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
2033
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2034
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2035
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
2036
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26862 amit.gupta 2037
 
25927 amit.gupta 2038
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2039
			int authId = authUserEmail.getKey();
2040
			String email = authUserEmail.getValue();
2041
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2042
		}
2043
		String visitTemplate = "Planned visit to franchisee %s is due by %s";
2044
		String followupTemplate = "Lead followup for franchisee %s is due by %s";
2045
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
2046
		for (FranchiseeVisit visit : franchiseeVisits) {
2047
			if (authUserKeyMap.containsKey(visit.getAuthId())) {
2048
				continue;
2049
			}
2050
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2051
			String message = null;
26862 amit.gupta 2052
			if(visit.getFranchiseActivityId()==0) {
2053
				 message = String.format(visitTemplate, visit.getPartnerName(), timeFormatter.format(visit.getSchelduleTimestamp()));
2054
				 sendNotificationModel.setCampaignName("Franchisee visit Reminder");
25927 amit.gupta 2055
			} else {
26862 amit.gupta 2056
				message = String.format(followupTemplate, visit.getPartnerName(), timeFormatter.format(visit.getSchelduleTimestamp()));
25927 amit.gupta 2057
				sendNotificationModel.setCampaignName("Franchisee followup Reminder");
2058
			}
2059
			sendNotificationModel.setMessage(message);
2060
			sendNotificationModel.setType("url");
26482 tejbeer 2061
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2062
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2063
			sendNotificationModel.setMessageType(MessageType.reminder);
2064
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
2065
			notificationService.sendNotification(sendNotificationModel);
2066
		}
25910 amit.gupta 2067
	}
25982 amit.gupta 2068
 
26283 tejbeer 2069
	public void ticketClosed() throws Exception {
2070
 
2071
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTicketsWithStatus(ActivityType.RESOLVED);
2072
		for (Ticket ticket : tickets) {
2073
			if (ticket.getUpdateTimestamp().toLocalDate().isBefore(LocalDate.now().minusDays(7))) {
2074
				ticket.setCloseTimestamp(LocalDateTime.now());
2075
				ticket.setLastActivity(ActivityType.RESOLVED_ACCEPTED);
2076
				ticket.setUpdateTimestamp(LocalDateTime.now());
2077
				ticketRepository.persist(ticket);
2078
			}
2079
		}
2080
 
2081
	}
2082
 
26790 tejbeer 2083
	public void checkValidateReferral() throws Exception {
2084
 
2085
		List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
26791 tejbeer 2086
		LOGGER.info("referrals" + referrals);
26790 tejbeer 2087
		if (!referrals.isEmpty()) {
2088
			String subject = "Referral Request";
2089
			String messageText = this.getMessageForReferral(referrals);
2090
 
26792 tejbeer 2091
			MimeMessage message = mailSender.createMimeMessage();
2092
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
2093
			String[] email = { "kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com" };
2094
			helper.setSubject(subject);
2095
			helper.setText(messageText, true);
2096
			helper.setTo(email);
2097
			InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
2098
			helper.setFrom(senderAddress);
2099
			mailSender.send(message);
2100
 
26790 tejbeer 2101
		}
2102
	}
2103
 
2104
	private String getMessageForReferral(List<Refferal> referrals) {
2105
		StringBuilder sb = new StringBuilder();
2106
		sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>"
2107
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2108
		sb.append("<tbody>\n" + "	    				<tr>\n"
2109
				+ "	    					<th style='border:1px solid black;padding: 5px'>RefereeName</th>\n"
2110
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referee Email</th>\n"
2111
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referral Name</th>\n"
2112
				+ "	    					<th style='border:1px solid black;padding: 5px'>Refferal Mobile</th>\n"
2113
				+ "	    					<th style='border:1px solid black;padding: 5px'>city</th>\n"
2114
				+ "	    					<th style='border:1px solid black;padding: 5px'>state</th>\n"
2115
				+ "	    				</tr>");
2116
		for (Refferal entry : referrals) {
2117
 
2118
			sb.append("<tr>");
2119
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
2120
 
2121
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
2122
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
2123
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
2124
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
2125
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
2126
 
2127
			sb.append("</tr>");
2128
 
2129
		}
2130
 
2131
		sb.append("</tbody></table></body></html>");
2132
 
2133
		return sb.toString();
2134
	}
2135
 
26418 tejbeer 2136
}