Subversion Repositories SmartDukaan

Rev

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