Subversion Repositories SmartDukaan

Rev

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