Subversion Repositories SmartDukaan

Rev

Rev 26122 | Rev 26283 | 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",
26265 amit.gupta 703
				"Wallet Amount", "In Stock Amount", "Activated Stock", "Return In Transit Stock", "Unbilled Amount", "Grn Pending Amount",
25598 amit.gupta 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(),
26265 amit.gupta 728
							partnerDailyInvestment.getActivatedStockAmount() == 0 ? "-":"("+partnerDailyInvestment.getActivatedStockAmount()+")",
25927 amit.gupta 729
							0, partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(),
730
							partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(),
731
							partnerDailyInvestment.getShortInvestment(), partnerDailyInvestment.getUnbilledQty()));
25837 amit.gupta 732
			partnerRowsMap.put(fofoStore.getId(), row);
24002 amit.gupta 733
			rows.add(row);
734
 
23929 amit.gupta 735
		}
25312 amit.gupta 736
 
24271 amit.gupta 737
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25598 amit.gupta 738
 
25927 amit.gupta 739
		if (sendTo == null) {
25895 amit.gupta 740
			for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
741
				List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x))
742
						.filter(x -> x != null).collect(Collectors.toList());
743
				ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
744
				String[] sendToArray = new String[] { storeGuyEntry.getKey() };
745
				Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
746
						fileName, new ByteArrayResource(baos.toByteArray()));
747
			}
748
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
749
					"prakash.rai@smartdukaan.com", "amit.gupta@shop2020.in", "amod.sen@smartdukaan.com");
25341 amit.gupta 750
		}
25312 amit.gupta 751
 
25604 amit.gupta 752
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
753
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
25609 amit.gupta 754
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
755
				fileName, new ByteArrayResource(baos.toByteArray()));
24271 amit.gupta 756
 
23929 amit.gupta 757
	}
24177 govind 758
 
25837 amit.gupta 759
	private Map<Integer, List<Serializable>> getPartnerIdSalesHeaders() {
25598 amit.gupta 760
		Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
761
 
762
		List<Position> positions = positionRepository
763
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
764
		Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream()
765
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
766
		Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
767
		for (Position position : positions) {
768
			List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
25609 amit.gupta 769
			if (crList == null)
770
				continue;
25598 amit.gupta 771
			for (CustomRetailer cr : crList) {
772
				if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
773
					partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
774
				}
775
				SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
776
				AuthUser authUser = authUsersMap.get(position.getAuthUserId());
26059 amit.gupta 777
				if(authUser==null) {
778
					continue;
779
				}
25598 amit.gupta 780
				String name = authUser.getFirstName() + " " + authUser.getLastName();
781
				if (position.getEscalationType().equals(EscalationType.L1)) {
782
					saleRoles.getL1().add(name);
783
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
784
					saleRoles.getL2().add(name);
785
				}
786
			}
787
		}
25837 amit.gupta 788
 
789
		Set<CustomRetailer> allCrList = new HashSet<>();
790
		for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
791
			allCrList.addAll(cr);
792
		}
793
 
794
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
795
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
796
 
797
		Map<Integer, List<Serializable>> partnerIdSalesHeadersMap = new HashMap<>();
798
 
799
		for (CustomRetailer cr : allCrList) {
800
			FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
25927 amit.gupta 801
			if (fofoStore == null) {
25870 amit.gupta 802
				LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
803
				continue;
804
			}
25865 amit.gupta 805
			String code = fofoStore.getCode() + "";
25837 amit.gupta 806
			String storeName = "SmartDukaan-" + fofoStore.getCode().replaceAll("[a-zA-Z]", "");
807
			String businessName = cr.getBusinessName();
808
			try {
809
				String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
810
				String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
811
				List<Serializable> row = new ArrayList<>(
812
						Arrays.asList(code, businessName, storeName, stateManager, territoryManager));
813
				partnerIdSalesHeadersMap.put(cr.getPartnerId(), row);
814
 
815
			} catch (Exception e) {
816
				LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
817
			}
818
		}
819
		return partnerIdSalesHeadersMap;
820
 
25598 amit.gupta 821
	}
822
 
24271 amit.gupta 823
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 824
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 825
	}
826
 
25312 amit.gupta 827
	public void sendTargetVsSalesReport(List<String> sendTo) throws Exception {
24177 govind 828
 
25312 amit.gupta 829
		if (sendTo == null) {
25827 amit.gupta 830
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
831
					"amit.gupta@shop2020.in", "amod.sen@smartdukaan.com", "prakash.rai@smartdukaan.com");
25312 amit.gupta 832
		}
25837 amit.gupta 833
		Map<Integer, List<Serializable>> partnerSalesTargetRowsMap = targetService.getDailySaleReportVsTarget();
25315 amit.gupta 834
 
25837 amit.gupta 835
		Map<Integer, List<Serializable>> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
24177 govind 836
 
25837 amit.gupta 837
		List<String> headers = Arrays.asList("Code", "Firm Name", "Store Name", "State Manager", "Teritory Manager",
838
				"Current Category", "Target Value", "Target Achieved", "Achived Percentage", "Remaining Target",
839
				"Today's Target", "Today's achievement");
25609 amit.gupta 840
 
25837 amit.gupta 841
		List<List<?>> rows = new ArrayList<>();
842
		Map<Integer, List<? extends Serializable>> partnerRowMap = new HashMap<>();
843
		for (Map.Entry<Integer, List<Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap.entrySet()) {
844
			List<Serializable> row = partnerIdSalesHeadersMap.get(partnerSalesTargetRowEntry.getKey());
845
			if (row == null) {
846
				LOGGER.warn("Could not find headers for partner ID - {}", partnerSalesTargetRowEntry.getKey());
25315 amit.gupta 847
			}
25837 amit.gupta 848
			row.addAll(partnerSalesTargetRowEntry.getValue());
849
			partnerRowMap.put(partnerSalesTargetRowEntry.getKey(), row);
850
			rows.add(row);
24177 govind 851
		}
25503 amit.gupta 852
 
25318 amit.gupta 853
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25894 amit.gupta 854
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
855
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25827 amit.gupta 856
			if (storeGuyEntry.getValue().size() == 0)
857
				continue;
25927 amit.gupta 858
			List<List<?>> storeGuyRows = storeGuyEntry.getValue().stream().filter(x -> partnerRowMap.containsKey(x))
859
					.map(x -> partnerRowMap.get(x)).collect(Collectors.toList());
25827 amit.gupta 860
			ByteArrayOutputStream authUserStream = FileUtil.getCSVByteStream(headers, storeGuyRows);
861
			Attachment attache = new Attachment(fileName, new ByteArrayResource(authUserStream.toByteArray()));
862
			System.out.println(storeGuyEntry.getValue());
863
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
864
					"Franchise Stock Report", "PFA", attache);
865
		}
24240 amit.gupta 866
 
25312 amit.gupta 867
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
868
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
869
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
870
				new ByteArrayResource(baos.toByteArray()));
24174 govind 871
	}
24683 amit.gupta 872
 
24697 amit.gupta 873
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 874
 
875
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
876
				"itemstockageing.xml");
24708 amit.gupta 877
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 878
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 879
		Attachment attachment = new Attachment(
25445 amit.gupta 880
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 881
		Attachment attachment1 = new Attachment(
25445 amit.gupta 882
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 883
 
25609 amit.gupta 884
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
885
				attachment);
886
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
887
				"Itemwise Pending indent", "PFA", attachment1);
888
 
25598 amit.gupta 889
		// Reports to be sent to mapped partners
25597 amit.gupta 890
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 891
 
892
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 893
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 894
			if (storeGuyEntry.getValue().size() == 0)
895
				continue;
25418 amit.gupta 896
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
897
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
898
					"focostockreport.xml", params);
899
			Attachment attache = new Attachment(
25609 amit.gupta 900
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 901
			System.out.println(storeGuyEntry.getValue());
25609 amit.gupta 902
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
903
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 904
		}
25503 amit.gupta 905
 
24681 amit.gupta 906
	}
24533 govind 907
 
24697 amit.gupta 908
	public void sendAgeingReport() throws Exception {
25807 amit.gupta 909
		sendAgeingReport("kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com",
25609 amit.gupta 910
				"chaitnaya.vats@smartdukaan.com");
24697 amit.gupta 911
	}
912
 
24533 govind 913
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 914
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 915
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 916
			priceDropService.priceDropStatus(priceDrop.getId());
917
		}
918
	}
23929 amit.gupta 919
 
24542 amit.gupta 920
	public void walletmismatch() throws Exception {
921
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 922
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 923
		System.out.println(pdis.size());
24542 amit.gupta 924
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 925
			int fofoId = pdi.getFofoId();
24542 amit.gupta 926
			for (PartnerDailyInvestment investment : Lists
927
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 928
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 929
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 930
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 931
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
932
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 933
 
24542 amit.gupta 934
			}
24549 amit.gupta 935
		}
24542 amit.gupta 936
 
937
	}
938
 
939
	public void gst() throws Exception {
24548 amit.gupta 940
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
941
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
942
		for (FofoOrder fofoOrder : fofoOrders) {
943
			int retailerAddressId = retailerRegisteredAddressRepository
944
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 945
 
946
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
947
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
948
			Integer stateId = null;
949
			if (customerAddress.getState().equals(retailerAddress.getState())) {
950
				try {
951
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
952
				} catch (Exception e) {
953
					LOGGER.error("Unable to get state rates");
954
				}
955
			}
956
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
957
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 958
 
959
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
960
			Set<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
24542 amit.gupta 961
			if (stateId != null) {
962
				itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemIds), stateId);
963
			} else {
964
				itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemIds));
965
			}
966
 
24548 amit.gupta 967
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 968
				if (stateId == null) {
969
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
970
				} else {
971
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
972
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
973
				}
974
				fofoOrderItemRepository.persist(foi);
975
			}
976
		}
24548 amit.gupta 977
 
24542 amit.gupta 978
	}
979
 
24580 amit.gupta 980
	public void schemewalletmismatch() {
981
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 982
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 983
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 984
			// reconcileOrders(dateTime);
985
			// reconcileRecharges(dateTime);
24580 amit.gupta 986
			dateToReconcile = dateToReconcile.plusDays(1);
987
		}
988
	}
989
 
990
	private void reconcileSchemes(LocalDate date) {
991
		LocalDateTime startDate = date.atStartOfDay();
992
		LocalDateTime endDate = startDate.plusDays(1);
993
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
994
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 995
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
996
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 997
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 998
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
999
				WalletReferenceType.SCHEME_OUT);
1000
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
1001
				walletReferenceTypes);
1002
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
1003
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 1004
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 1005
 
1006
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
1007
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1008
 
1009
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
1010
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1011
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
1012
 
1013
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
1014
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1015
 
1016
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
1017
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
1018
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
1019
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
1020
 
1021
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
26092 amit.gupta 1022
 
24587 amit.gupta 1023
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
1024
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
1025
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
1026
				} else {
1027
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
1028
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
1029
				}
1030
			}
24590 amit.gupta 1031
			Map<Integer, Integer> userWalletMap = userWalletRepository
1032
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
1033
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1034
 
24587 amit.gupta 1035
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
1036
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
1037
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
1038
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1039
				if (diff > 5) {
1040
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1041
				}
1042
			}
24580 amit.gupta 1043
		}
24587 amit.gupta 1044
 
24580 amit.gupta 1045
	}
24590 amit.gupta 1046
 
24592 amit.gupta 1047
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1048
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1049
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1050
 
24592 amit.gupta 1051
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1052
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1053
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1054
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1055
		Set<String> serialNumbersConsidered = new HashSet<>();
1056
 
25096 amit.gupta 1057
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1058
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1059
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1060
 
24683 amit.gupta 1061
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1062
		purchases.stream().forEach(purchase -> {
1063
			float amountToRollback = 0;
1064
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1065
					+ purchase.getPurchaseReference();
1066
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1067
					.stream().filter(ii -> ii.getSerialNumber() != null)
1068
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1069
			if (inventorySerialNumberMap.size() > 0) {
1070
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1071
					String serialNumber = inventorySerialNumberEntry.getValue();
1072
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1073
					if (serialNumbersConsidered.contains(serialNumber)) {
1074
						// This will rollback scheme for differenct orders for same serial
1075
						List<SchemeInOut> sios = schemeInOutRepository
1076
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1077
								.filter(x -> x.getRolledBackTimestamp() == null
1078
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1079
								.collect(Collectors.toList());
1080
						Collections.reverse(sios);
1081
						for (SchemeInOut sio : sios) {
1082
							sio.setRolledBackTimestamp(LocalDateTime.now());
1083
							amountToRollback += sio.getAmount();
1084
							// sio.setSchemeType(SchemeType.OUT);
1085
							sio.setSerialNumber(serialNumber);
1086
							rolledbackSios.add(sio);
1087
						}
1088
						description = description.concat(" " + serialNumber + " ");
1089
					} else {
1090
						serialNumbersConsidered.add(serialNumber);
1091
						List<Integer> schemesConsidered = new ArrayList<>();
1092
						List<SchemeInOut> sios = schemeInOutRepository
1093
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1094
								.filter(x -> x.getRolledBackTimestamp() == null
1095
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1096
								.collect(Collectors.toList());
1097
						Collections.reverse(sios);
1098
						for (SchemeInOut sio : sios) {
1099
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1100
								schemesConsidered.add(sio.getSchemeId());
1101
								continue;
1102
							}
1103
							sio.setRolledBackTimestamp(LocalDateTime.now());
1104
							amountToRollback += sio.getAmount();
1105
							// sio.setSchemeType(SchemeType.OUT);
1106
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1107
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1108
							sio.setReference(purchase.getId());
24635 amit.gupta 1109
							rolledbackSios.add(sio);
1110
						}
1111
					}
1112
 
1113
				}
1114
			}
1115
			if (amountToRollback > 0) {
24683 amit.gupta 1116
				// Address address =
1117
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1118
				UserWalletHistory uwh = new UserWalletHistory();
1119
				uwh.setAmount(Math.round(amountToRollback));
1120
				uwh.setDescription(description);
1121
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1122
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1123
				uwh.setReference(purchase.getId());
1124
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1125
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1126
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1127
				userWalletHistory.add(uwh);
1128
			}
1129
		});
1130
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1131
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1132
						"Timestamp"),
1133
				userWalletHistory.stream()
1134
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1135
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1136
						.collect(Collectors.toList()));
1137
 
1138
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1139
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1140
						"Created", "Rolledback"),
24635 amit.gupta 1141
				rolledbackSios.stream()
24681 amit.gupta 1142
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1143
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1144
						.collect(Collectors.toList()));
1145
 
25043 amit.gupta 1146
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1147
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1148
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1149
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1150
 
25096 amit.gupta 1151
		throw new Exception();
24635 amit.gupta 1152
 
1153
	}
1154
 
1155
	public void dryRunOutSchemeReco() throws Exception {
1156
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1157
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1158
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1159
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1160
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1161
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1162
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1163
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1164
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1165
		// Collections.reverse(allOrders);
1166
		// List<FofoOrder> allOrders =
24653 govind 1167
		// List<FofoOrder> allOrders =
24631 amit.gupta 1168
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1169
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1170
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1171
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1172
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1173
			float amountToRollback = 0;
24590 amit.gupta 1174
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1175
			orderItems.forEach(x -> {
24606 amit.gupta 1176
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1177
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1178
			});
24606 amit.gupta 1179
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1180
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1181
					String serialNumber = inventorySerialNumberEntry.getValue();
1182
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1183
					if (serialNumbersConsidered.contains(serialNumber)) {
1184
						// This will rollback scheme for differenct orders for same serial
1185
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1186
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1187
								.filter(x -> x.getRolledBackTimestamp() == null
1188
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1189
								.collect(Collectors.toList());
1190
						Collections.reverse(sios);
1191
						for (SchemeInOut sio : sios) {
1192
							sio.setRolledBackTimestamp(LocalDateTime.now());
1193
							amountToRollback += sio.getAmount();
1194
							// sio.setSchemeType(SchemeType.OUT);
1195
							sio.setSerialNumber(serialNumber);
1196
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1197
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1198
							rolledbackSios.add(sio);
24623 amit.gupta 1199
						}
24635 amit.gupta 1200
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1201
					} else {
1202
						serialNumbersConsidered.add(serialNumber);
1203
						List<Integer> schemesConsidered = new ArrayList<>();
1204
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1205
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1206
								.filter(x -> x.getRolledBackTimestamp() == null
1207
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1208
								.collect(Collectors.toList());
1209
						Collections.reverse(sios);
1210
						for (SchemeInOut sio : sios) {
1211
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1212
								schemesConsidered.add(sio.getSchemeId());
1213
								continue;
1214
							}
1215
							sio.setRolledBackTimestamp(LocalDateTime.now());
1216
							amountToRollback += sio.getAmount();
1217
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1218
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1219
							sio.setSerialNumber(serialNumber);
1220
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1221
							rolledbackSios.add(sio);
1222
						}
24615 amit.gupta 1223
					}
24631 amit.gupta 1224
 
24604 amit.gupta 1225
				}
24590 amit.gupta 1226
			}
24631 amit.gupta 1227
			if (amountToRollback > 0) {
1228
				UserWalletHistory uwh = new UserWalletHistory();
1229
				uwh.setAmount(Math.round(amountToRollback));
1230
				uwh.setDescription(description);
1231
				uwh.setTimestamp(LocalDateTime.now());
1232
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1233
				uwh.setReference(fofoOrder.getId());
1234
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1235
				uwh.setFofoId(fofoOrder.getFofoId());
1236
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1237
				userWalletHistory.add(uwh);
1238
			}
24590 amit.gupta 1239
		});
24598 amit.gupta 1240
 
24592 amit.gupta 1241
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1242
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1243
						"Timestamp"),
1244
				userWalletHistory.stream()
1245
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1246
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1247
						.collect(Collectors.toList()));
1248
 
1249
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1250
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1251
						"Rolledback"),
1252
				rolledbackSios.stream()
1253
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1254
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1255
						.collect(Collectors.toList()));
1256
 
25043 amit.gupta 1257
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1258
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1259
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1260
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1261
 
25267 amit.gupta 1262
		throw new Exception();
24590 amit.gupta 1263
	}
24615 amit.gupta 1264
 
24611 amit.gupta 1265
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1266
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1267
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1268
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1269
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1270
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1271
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1272
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1273
		references.stream().forEach(reference -> {
1274
			FofoOrder fofoOrder = null;
1275
			try {
1276
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1277
			} catch (Exception e) {
1278
 
24611 amit.gupta 1279
			}
1280
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1281
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1282
			float amountToRollback = 0;
1283
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1284
			orderItems.forEach(x -> {
1285
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1286
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1287
			});
1288
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1289
				List<SchemeInOut> sios = schemeInOutRepository
1290
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1291
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1292
						.collect(Collectors.toList());
1293
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1294
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1295
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1296
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1297
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1298
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1299
					if (outList.size() > 1) {
1300
 
24611 amit.gupta 1301
					}
1302
				}
1303
				uwh.setAmount(Math.round(amountToRollback));
1304
				uwh.setDescription(description);
1305
				uwh.setTimestamp(LocalDateTime.now());
1306
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1307
				uwh.setReference(fofoOrder.getId());
1308
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1309
				uwh.setFofoId(fofoOrder.getFofoId());
1310
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1311
				userWalletHistory.add(uwh);
1312
			}
1313
		});
24615 amit.gupta 1314
 
24611 amit.gupta 1315
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1316
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1317
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1318
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1319
						.collect(Collectors.toList()));
1320
 
24611 amit.gupta 1321
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1322
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1323
						"Rolledback"),
1324
				rolledbackSios.stream()
24615 amit.gupta 1325
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1326
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1327
						.collect(Collectors.toList()));
1328
 
24623 amit.gupta 1329
		Utils.sendMailWithAttachments(googleMailSender,
1330
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1331
				"Partner Excess Amount", "PFA",
1332
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1333
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1334
 
24628 amit.gupta 1335
		throw new Exception();
24615 amit.gupta 1336
 
24611 amit.gupta 1337
	}
24615 amit.gupta 1338
 
25837 amit.gupta 1339
	public void sendDailySalesNotificationToPartner(Integer fofoIdInt)
24653 govind 1340
			throws ProfitMandiBusinessException, MessagingException, IOException {
25927 amit.gupta 1341
 
24653 govind 1342
		LocalDateTime now = LocalDateTime.now();
25837 amit.gupta 1343
		LocalDateTime from = now.with(LocalTime.MIN);
25925 amit.gupta 1344
		String timeString = "Today %s";
25927 amit.gupta 1345
		// Send yesterday's report
1346
		if (now.getHour() < 13) {
25925 amit.gupta 1347
			timeString = "Yesterday %s";
25910 amit.gupta 1348
			from = now.minusDays(1);
1349
			now = from.with(LocalTime.MAX);
25927 amit.gupta 1350
 
25910 amit.gupta 1351
		}
24855 amit.gupta 1352
		List<Integer> fofoIds = null;
25043 amit.gupta 1353
		if (fofoIdInt == null) {
1354
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1355
					.collect(Collectors.toList());
24856 amit.gupta 1356
		} else {
24855 amit.gupta 1357
			fofoIds = Arrays.asList(fofoIdInt);
1358
		}
25912 amit.gupta 1359
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
24683 amit.gupta 1360
 
25865 amit.gupta 1361
		Map<Integer, Double> salesByFofoIdMap = new HashMap<>();
1362
		Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1363
				null);
1364
		Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
1365
		Map<Integer, Double> partnerOrderAmountMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now,
1366
				0, true);
1367
		Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
1368
		Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
1369
		for (int fofoId : fofoIds) {
1370
			SaleTargetReportModel model = new SaleTargetReportModel();
25927 amit.gupta 1371
			model.setInsuranceSale(
1372
					partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
25865 amit.gupta 1373
			model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
1374
			model.setSmartphoneSale(partnerOrderAmountMap.containsKey(fofoId) ? partnerOrderAmountMap.get(fofoId) : 0);
1375
			model.setSmartphoneQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
1376
			model.setTotalSale(salesByFofoIdMap.containsKey(fofoId) ? salesByFofoIdMap.get(fofoId) : 0);
25880 amit.gupta 1377
			model.setFofoId(fofoId);
25865 amit.gupta 1378
			saleTargetReportModelMap.put(fofoId, model);
1379
		}
25880 amit.gupta 1380
 
25865 amit.gupta 1381
		Map<Integer, List<Serializable>> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
24653 govind 1382
		for (Integer fofoId : fofoIds) {
25865 amit.gupta 1383
			SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
25821 amit.gupta 1384
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1385
			sendNotificationModel.setCampaignName("Sales update alert");
25884 tejbeer 1386
			sendNotificationModel.setTitle("Sale Update");
25927 amit.gupta 1387
			sendNotificationModel
1388
					.setMessage(String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1389
							model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1390
							String.format(timeString, now.format(timeFormatter))));
25821 amit.gupta 1391
			sendNotificationModel.setType("url");
1392
			sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
1393
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1394
			sendNotificationModel.setMessageType(MessageType.notification);
25872 tejbeer 1395
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1396
			sendNotificationModel.setUserIds(Arrays.asList(userId));
25854 amit.gupta 1397
			notificationService.sendNotification(sendNotificationModel);
24653 govind 1398
		}
25865 amit.gupta 1399
		String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap, saleTargetReportModelMap);
24653 govind 1400
		LOGGER.info(saleReport);
25837 amit.gupta 1401
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com",
25846 amit.gupta 1402
				"chaitnaya.vats@smartdukaan.com" };
25837 amit.gupta 1403
 
25912 amit.gupta 1404
		String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
25821 amit.gupta 1405
		this.sendMailOfHtmlFomat("amit.gupta@shop2020.in", saleReport, cc, subject);
24653 govind 1406
	}
1407
 
25865 amit.gupta 1408
	public static class SaleTargetReportModel {
1409
		private double totalSale;
25880 amit.gupta 1410
		private int fofoId;
1411
 
1412
		public int getFofoId() {
1413
			return fofoId;
1414
		}
1415
 
1416
		public void setFofoId(int fofoId) {
1417
			this.fofoId = fofoId;
1418
		}
1419
 
25865 amit.gupta 1420
		private double smartphoneSale;
1421
		private long smartphoneQty;
1422
		private double insuranceSale;
1423
		private long insruanceQty;
1424
 
1425
		@Override
1426
		public int hashCode() {
1427
			final int prime = 31;
1428
			int result = 1;
25880 amit.gupta 1429
			result = prime * result + fofoId;
25865 amit.gupta 1430
			result = prime * result + (int) (insruanceQty ^ (insruanceQty >>> 32));
1431
			long temp;
1432
			temp = Double.doubleToLongBits(insuranceSale);
1433
			result = prime * result + (int) (temp ^ (temp >>> 32));
1434
			result = prime * result + (int) (smartphoneQty ^ (smartphoneQty >>> 32));
1435
			temp = Double.doubleToLongBits(smartphoneSale);
1436
			result = prime * result + (int) (temp ^ (temp >>> 32));
1437
			temp = Double.doubleToLongBits(totalSale);
1438
			result = prime * result + (int) (temp ^ (temp >>> 32));
1439
			return result;
1440
		}
1441
 
1442
		@Override
1443
		public boolean equals(Object obj) {
1444
			if (this == obj)
1445
				return true;
1446
			if (obj == null)
1447
				return false;
1448
			if (getClass() != obj.getClass())
1449
				return false;
1450
			SaleTargetReportModel other = (SaleTargetReportModel) obj;
25880 amit.gupta 1451
			if (fofoId != other.fofoId)
1452
				return false;
25865 amit.gupta 1453
			if (insruanceQty != other.insruanceQty)
1454
				return false;
1455
			if (Double.doubleToLongBits(insuranceSale) != Double.doubleToLongBits(other.insuranceSale))
1456
				return false;
1457
			if (smartphoneQty != other.smartphoneQty)
1458
				return false;
1459
			if (Double.doubleToLongBits(smartphoneSale) != Double.doubleToLongBits(other.smartphoneSale))
1460
				return false;
1461
			if (Double.doubleToLongBits(totalSale) != Double.doubleToLongBits(other.totalSale))
1462
				return false;
1463
			return true;
1464
		}
1465
 
1466
		public double getTotalSale() {
1467
			return totalSale;
1468
		}
1469
 
1470
		public void setTotalSale(double totalSale) {
1471
			this.totalSale = totalSale;
1472
		}
1473
 
1474
		public double getSmartphoneSale() {
1475
			return smartphoneSale;
1476
		}
1477
 
1478
		public void setSmartphoneSale(double smartphoneSale) {
1479
			this.smartphoneSale = smartphoneSale;
1480
		}
1481
 
1482
		public long getSmartphoneQty() {
1483
			return smartphoneQty;
1484
		}
1485
 
1486
		public void setSmartphoneQty(long smartphoneQty) {
1487
			this.smartphoneQty = smartphoneQty;
1488
		}
1489
 
1490
		public double getInsuranceSale() {
1491
			return insuranceSale;
1492
		}
1493
 
1494
		public void setInsuranceSale(double insuranceSale) {
1495
			this.insuranceSale = insuranceSale;
1496
		}
1497
 
1498
		public long getInsruanceQty() {
1499
			return insruanceQty;
1500
		}
1501
 
1502
		public void setInsruanceQty(long insruanceQty) {
1503
			this.insruanceQty = insruanceQty;
1504
		}
1505
 
1506
		@Override
1507
		public String toString() {
25880 amit.gupta 1508
			return "SaleTargetReportModel [totalSale=" + totalSale + ", fofoId=" + fofoId + ", smartphoneSale="
1509
					+ smartphoneSale + ", smartphoneQty=" + smartphoneQty + ", insuranceSale=" + insuranceSale
1510
					+ ", insruanceQty=" + insruanceQty + "]";
25865 amit.gupta 1511
		}
1512
 
1513
	}
1514
 
1515
	private String getDailySalesReportHtml(Map<Integer, List<Serializable>> partnerSalesHeadersMap,
25872 tejbeer 1516
			Map<Integer, SaleTargetReportModel> saleReportTargetMap) throws ProfitMandiBusinessException {
24653 govind 1517
		StringBuilder sb = new StringBuilder();
25872 tejbeer 1518
 
25832 amit.gupta 1519
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 1520
		sb.append("<tbody>\n" + "	    				<tr>\n"
25865 amit.gupta 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"
1525
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
24653 govind 1526
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
25865 amit.gupta 1527
				+ "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>\n"
1528
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>\n"
1529
				+ "	    					<th style='border:1px solid black;padding: 5px'>Insurance Sale</th>\n"
1530
				+ "	    					<th style='border:1px solid black;padding: 5px'>Insurance Qty</th>\n"
24653 govind 1531
				+ "	    				</tr>");
25880 amit.gupta 1532
		List<Integer> sortedPartnerSalesHeaders = partnerSalesHeadersMap.entrySet().stream()
1533
				.sorted((x, y) -> ((String) (x.getValue().get(3))).compareTo((String) (y.getValue().get(3))))
25927 amit.gupta 1534
				.map(x -> x.getKey()).collect(Collectors.toList());
1535
		for (Integer fofoId : sortedPartnerSalesHeaders) {
25865 amit.gupta 1536
			sb.append("<tr>");
25880 amit.gupta 1537
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(0)
1538
					+ "</td>");
1539
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(1)
1540
					+ "</td>");
1541
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(2)
1542
					+ "</td>");
1543
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(3)
1544
					+ "</td>");
1545
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(4)
1546
					+ "</td>");
1547
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1548
					+ saleReportTargetMap.get(fofoId).getTotalSale() + "</td>");
1549
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1550
					+ saleReportTargetMap.get(fofoId).getSmartphoneSale() + "</td>");
1551
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1552
					+ saleReportTargetMap.get(fofoId).getSmartphoneQty() + "</td>");
1553
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1554
					+ saleReportTargetMap.get(fofoId).getInsuranceSale() + "</td>");
1555
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1556
					+ saleReportTargetMap.get(fofoId).getInsruanceQty() + "</td>");
25865 amit.gupta 1557
			sb.append("</tr>");
24653 govind 1558
 
1559
		}
24683 amit.gupta 1560
 
24653 govind 1561
		sb.append("</tbody></table></body></html>");
25865 amit.gupta 1562
		return String.format(sb.toString(), REPORT_HEADERS);
24653 govind 1563
	}
24841 govind 1564
 
1565
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1566
			throws MessagingException, ProfitMandiBusinessException, IOException {
1567
		MimeMessage message = mailSender.createMimeMessage();
1568
		MimeMessageHelper helper = new MimeMessageHelper(message);
1569
		helper.setSubject(subject);
1570
		helper.setText(body, true);
1571
		helper.setTo(email);
1572
		if (cc != null) {
1573
			helper.setCc(cc);
1574
		}
1575
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1576
		helper.setFrom(senderAddress);
1577
		mailSender.send(message);
1578
	}
25300 tejbeer 1579
 
25351 tejbeer 1580
	public void sendNotification() throws Exception {
25300 tejbeer 1581
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1582
		if (!pushNotifications.isEmpty()) {
1583
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1584
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1585
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1586
						.selectById(pushNotification.getNotificationCampaignid());
1587
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1588
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1589
 
1590
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1591
						SimpleCampaignParams.class);
1592
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1593
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1594
				JSONObject json = new JSONObject();
25351 tejbeer 1595
				json.put("to", device.getFcmId());
25300 tejbeer 1596
				JSONObject jsonObj = new JSONObject();
1597
				jsonObj.put("message", campaign.getMessage());
1598
				jsonObj.put("title", campaign.getTitle());
1599
				jsonObj.put("type", campaign.getType());
1600
				jsonObj.put("url", result_url);
1601
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1602
				jsonObj.put("image", campaign.getImageUrl());
1603
				jsonObj.put("largeIcon", "large_icon");
1604
				jsonObj.put("smallIcon", "small_icon");
1605
				jsonObj.put("vibrate", 1);
1606
				jsonObj.put("pid", pushNotification.getId());
1607
				jsonObj.put("sound", 1);
1608
				jsonObj.put("priority", "high");
1609
				json.put("data", jsonObj);
25351 tejbeer 1610
				try {
1611
					CloseableHttpClient client = HttpClients.createDefault();
1612
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1613
 
25351 tejbeer 1614
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1615
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1616
					StringEntity entity = new StringEntity(json.toString());
1617
					httpPost.setEntity(entity);
1618
					CloseableHttpResponse response = client.execute(httpPost);
1619
					LOGGER.info("response" + response);
25300 tejbeer 1620
 
25351 tejbeer 1621
					if (response.getStatusLine().getStatusCode() == 200) {
1622
						pushNotification.setSentTimestamp(LocalDateTime.now());
1623
					} else {
25356 tejbeer 1624
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 1625
						LOGGER.info("message" + "not sent");
25351 tejbeer 1626
					}
25300 tejbeer 1627
 
25351 tejbeer 1628
				} catch (Exception e) {
1629
					e.printStackTrace();
25300 tejbeer 1630
					LOGGER.info("message" + "not sent");
1631
				}
1632
			}
1633
		}
1634
	}
1635
 
25553 amit.gupta 1636
	public void grouping() throws Exception {
25609 amit.gupta 1637
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
1638
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
1639
		System.out.println(String.join("\t",
1640
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 1641
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
25609 amit.gupta 1642
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers();
1643
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 1644
			if (priceDropIMEI.getPartnerId() == 0)
1645
				continue;
25609 amit.gupta 1646
			HashSet<String> imeis = new HashSet<>();
1647
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
1648
			imeis.add(priceDropIMEI.getImei());
1649
			List<InventoryItem> inventoryItems = inventoryItemRepository
1650
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 1651
			if (inventoryItems.size() == 0) {
1652
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 1653
				continue;
25612 amit.gupta 1654
			}
25609 amit.gupta 1655
			InventoryItem inventoryItem = inventoryItems.get(0);
1656
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
1657
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
1658
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
1659
				// check if pricedrop has been rolled out
1660
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
1661
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
1662
				if (uwh.size() > 0) {
25615 amit.gupta 1663
					Item item = itemRepository.selectById(inventoryItem.getItemId());
25609 amit.gupta 1664
					System.out.println(String.join("\t",
1665
							Arrays.asList(priceDropIMEI.getImei(), inventoryItem.getItemId() + "", item.getBrand(),
1666
									item.getModelName(), item.getModelNumber(), inventoryItem.getFofoId() + "",
1667
									customRetailer.getBusinessName(), inventoryItem.getCreateTimestamp().format(dtf),
1668
									priceDrop.getAffectedOn().format(dtf),
1669
									priceDropIMEI.getUpdateTimestamp().format(dtf),
25694 amit.gupta 1670
									inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getPartnerPayout() + "",
25609 amit.gupta 1671
									inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
1672
				}
1673
			}
1674
		}
25503 amit.gupta 1675
	}
25694 amit.gupta 1676
 
1677
	public void testToffee() throws Exception {
25846 amit.gupta 1678
		LOGGER.info("Insurance Sum Summary --- {}",
1679
				insurancePolicyRepository.selectAmountSumGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
1680
		LOGGER.info("Insurance Qty Summary --- {}",
1681
				insurancePolicyRepository.selectQtyGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
25854 amit.gupta 1682
		LOGGER.info("SmartPhone Amount Summary --- {}",
25856 amit.gupta 1683
				fofoOrderItemRepository.selectSumAmountGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25854 amit.gupta 1684
		LOGGER.info("Smartphone Qty Summary --- {}",
1685
				fofoOrderItemRepository.selectQtyGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25800 tejbeer 1686
		// LOGGER.info("{}", toffeeService.getAuthToken());
25846 amit.gupta 1687
		/*
1688
		 * LOGGER.info("{}", toffeeService.getProducts()); // LOGGER.info("{}",
1689
		 * toffeeService.getPincodes("36103000PR")); PremiumCalculationRequestModel pcrm
1690
		 * = new PremiumCalculationRequestModel(); pcrm.setProductDetails("36103000PR");
1691
		 * // pcrm.setProductDetails("36103000PR");
1692
		 * pcrm.setDurations(Arrays.asList("3 Months", "6 Months", "1 Year"));
1693
		 * pcrm.setSumInsured("15000");
1694
		 * System.out.println(toffeeService.getPremiumCalculation(pcrm));
1695
		 */
25694 amit.gupta 1696
	}
1697
 
1698
	public void schemeRollback(List<String> schemeIds) throws Exception {
1699
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 1700
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 1701
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1702
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
1703
		for (SchemeInOut sio : schemeInOuts) {
1704
			Scheme scheme = schemesMap.get(sio.getSchemeId());
1705
			if (scheme.getType().equals(SchemeType.IN)) {
1706
 
1707
			} else if (scheme.getType().equals(SchemeType.OUT)) {
1708
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
1709
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
1710
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
1711
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
1712
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
1713
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
1714
					sio.setRolledBackTimestamp(LocalDateTime.now());
1715
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 1716
					String rollbackReason = "Scheme reversed for "
1717
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 1718
							+ fofoOrder.getInvoiceNumber();
1719
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
1720
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason);
1721
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
1722
							rollbackReason);
1723
				}
1724
			}
1725
		}
25721 tejbeer 1726
		// throw new Exception();
25694 amit.gupta 1727
	}
25721 tejbeer 1728
 
1729
	public void checkfocusedModelInPartnerStock() throws Exception {
1730
 
1731
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1732
				.collect(Collectors.toList());
1733
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
1734
		for (Integer fofoId : fofoIds) {
1735
			if (!focusedModelShortageReportMap.containsKey(fofoId)) {
1736
				focusedModelShortageReportMap.put(fofoId, new ArrayList<>());
1737
			}
1738
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1739
			Map<Integer, Integer> processingOrderMap = null;
1740
			Map<Integer, Integer> catalogIdAndQtyMap = null;
1741
			Map<Integer, Integer> grnPendingOrdersMap = null;
1742
 
1743
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1744
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1745
 
1746
			if (!currentInventorySnapshot.isEmpty()) {
1747
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1748
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1749
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1750
 
1751
			}
1752
 
1753
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1754
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1755
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1756
			if (!grnPendingOrders.isEmpty()) {
1757
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1758
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1759
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1760
 
1761
			}
1762
 
1763
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1764
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1765
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1766
			if (!processingOrder.isEmpty()) {
1767
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1768
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1769
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1770
 
1771
			}
1772
 
25800 tejbeer 1773
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1774
					.collect(Collectors.toList());
1775
 
1776
			List<Integer> focusedModelCatalogId = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
1777
					.collect(Collectors.toList());
1778
			Map<String, Object> equalsMap = new HashMap<>();
1779
			equalsMap.put("categoryId", 10006);
1780
			equalsMap.put("brand", brands);
1781
 
1782
			Map<String, List<?>> notEqualsMap = new HashMap<>();
1783
 
1784
			Map<String, Object> equalsJoinMap = new HashMap<>();
1785
			equalsJoinMap.put("catalogId", focusedModelCatalogId);
1786
 
1787
			Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1788
 
1789
			List<Integer> catalogIds = itemRepository
1790
					.selectItems(FocusedModel.class, "catalogItemId", "catalogId", equalsMap, notEqualsMap,
1791
							equalsJoinMap, notEqualsJoinMap, "minimumQty")
1792
					.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
1793
 
1794
			Map<Integer, Integer> focusedCatalogIdAndQtyMap = focusedModelRepository.selectByCatalogIdsl(catalogIds)
1795
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getMinimumQty()));
1796
 
1797
			/*
1798
			 * Map<Integer, Integer> focusedCatalogIdAndQtyMap =
1799
			 * focusedModelRepository.selectAll().stream() .collect(Collectors.toMap(x ->
1800
			 * x.getCatalogId(), x -> x.getMinimumQty()));
1801
			 */
1802
 
25721 tejbeer 1803
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
1804
 
1805
			for (Map.Entry<Integer, Integer> entry : focusedCatalogIdAndQtyMap.entrySet()) {
1806
				int inStockQty = 0;
1807
				int processingQty = 0;
1808
				int grnPendingQty = 0;
1809
				if (processingOrderMap != null) {
1810
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
1811
							: processingOrderMap.get(entry.getKey());
1812
 
1813
				}
1814
				if (grnPendingOrdersMap != null) {
1815
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
1816
							: grnPendingOrdersMap.get(entry.getKey());
1817
 
1818
				}
1819
				if (catalogIdAndQtyMap != null) {
1820
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
1821
							: catalogIdAndQtyMap.get(entry.getKey());
1822
 
1823
				}
1824
				int totalQty = processingQty + grnPendingQty + inStockQty;
1825
 
1826
				if (totalQty < entry.getValue()) {
1827
 
1828
					int shortageQty = entry.getValue() - totalQty;
1829
					List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
1830
 
1831
					FocusedModelShortageModel fm = new FocusedModelShortageModel();
1832
					fm.setFofoId(fofoId);
1833
					fm.setStoreName(customRetailer.getBusinessName());
1834
 
1835
					fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
1836
					fm.setShortageQty(shortageQty);
1837
 
1838
					focusedModelShortageReportMap.get(fofoId).add(fm);
1839
				}
1840
 
1841
			}
1842
			List<FocusedModelShortageModel> focusedModelShortageModel = focusedModelShortageReportMap.get(fofoId);
1843
 
1844
			if (!focusedModelShortageModel.isEmpty()) {
1845
				String subject = "Stock Alert";
1846
				String messageText = this.getMessage(focusedModelShortageModel);
1847
 
25732 tejbeer 1848
				this.sendMailWithAttachments(subject, messageText, customRetailer.getEmail());
25721 tejbeer 1849
				String notificationMessage = this.getNotificationMessage(focusedModelShortageModel);
1850
 
1851
				LOGGER.info("notificationMessage" + notificationMessage);
1852
 
25872 tejbeer 1853
				SendNotificationModel sendNotificationModel = new SendNotificationModel();
1854
				sendNotificationModel.setCampaignName("Stock Alert");
1855
				sendNotificationModel.setTitle("Alert");
1856
				sendNotificationModel.setMessage(notificationMessage);
1857
				sendNotificationModel.setType("url");
1858
				sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
1859
				sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1860
				sendNotificationModel.setMessageType(MessageType.notification);
25732 tejbeer 1861
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
25872 tejbeer 1862
				sendNotificationModel.setUserIds(Arrays.asList(userId));
1863
				notificationService.sendNotification(sendNotificationModel);
25721 tejbeer 1864
 
1865
			}
25732 tejbeer 1866
 
25721 tejbeer 1867
		}
25800 tejbeer 1868
		if (!focusedModelShortageReportMap.isEmpty())
25721 tejbeer 1869
 
25800 tejbeer 1870
		{
1871
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
1872
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
25837 amit.gupta 1873
			Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 1874
 
25800 tejbeer 1875
			focusedModelShortageReportMap.entrySet().forEach(x -> {
1876
				storeGuyMap.entrySet().forEach(y -> {
1877
 
1878
					if (y.getValue().contains(x.getKey())) {
1879
						if (!emailRowsMap.containsKey(y.getKey())) {
1880
							emailRowsMap.put(y.getKey(), new ArrayList<>());
1881
						}
1882
						List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays
1883
								.asList(r.getFofoId(), r.getStoreName(), r.getItemName(), r.getShortageQty()))
1884
								.collect(Collectors.toList());
1885
						emailRowsMap.get(y.getKey()).addAll(fms);
1886
 
25721 tejbeer 1887
					}
1888
 
25800 tejbeer 1889
				});
25721 tejbeer 1890
 
1891
			});
1892
 
25800 tejbeer 1893
			List<String> headers = Arrays.asList("Partner Id", "Partner Name", "Model Name", "Shortage Qty");
25837 amit.gupta 1894
			emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 1895
 
25800 tejbeer 1896
				ByteArrayOutputStream baos = null;
1897
				try {
25837 amit.gupta 1898
					baos = FileUtil.getCSVByteStream(headers, entry.getValue());
25800 tejbeer 1899
				} catch (Exception e2) {
1900
					e2.printStackTrace();
1901
				}
25837 amit.gupta 1902
				String[] sendToArray = new String[] { entry.getKey() };
25800 tejbeer 1903
				try {
1904
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
1905
							new ByteArrayResource(baos.toByteArray()));
1906
				} catch (Exception e1) { // TODO Auto-generated catch block
1907
					e1.printStackTrace();
1908
				}
25721 tejbeer 1909
 
25800 tejbeer 1910
			});
1911
		}
25721 tejbeer 1912
	}
1913
 
1914
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1915
		StringBuilder sb = new StringBuilder();
1916
		sb.append("Focused Model Shortage in Your Stock : \n");
1917
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1918
 
1919
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
1920
			sb.append(String.format("%n", ""));
1921
		}
1922
		return sb.toString();
1923
	}
1924
 
1925
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
1926
		MimeMessage message = mailSender.createMimeMessage();
1927
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
1928
 
1929
		helper.setSubject(subject);
1930
		helper.setText(messageText, true);
1931
		helper.setTo(email);
26032 amit.gupta 1932
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smatdukaan Alerts");
25721 tejbeer 1933
		helper.setFrom(senderAddress);
1934
		mailSender.send(message);
1935
 
1936
	}
1937
 
1938
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1939
		StringBuilder sb = new StringBuilder();
1940
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
1941
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
1942
		sb.append("<tbody>\n" + "	    				<tr>\n"
1943
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
1944
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
1945
				+ "	    				</tr>");
1946
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1947
 
1948
			sb.append("<tr>");
1949
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
1950
 
1951
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
1952
 
1953
			sb.append("</tr>");
1954
 
1955
		}
1956
 
1957
		sb.append("</tbody></table></body></html>");
1958
 
1959
		return sb.toString();
1960
	}
1961
 
25927 amit.gupta 1962
	public void notifyLead() throws Exception {
1963
		List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(LocalDateTime.now().minusDays(15),
1964
				LocalDateTime.now().plusHours(4));
1965
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
1966
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
25936 amit.gupta 1967
		System.out.printf("authUserEmailMap - %s", authUserEmailMap);
25927 amit.gupta 1968
		Map<String, Integer> dtrEmailMap = dtrUserRepository
1969
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
1970
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25936 amit.gupta 1971
 
1972
		System.out.printf("dtrEmailMap - %s", dtrEmailMap);
1973
 
25927 amit.gupta 1974
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
1975
 
1976
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
1977
			int authId = authUserEmail.getKey();
1978
			String email = authUserEmail.getValue();
1979
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
1980
		}
25929 amit.gupta 1981
		System.out.println(authUserKeyMap);
1982
		System.out.println(leadsToNotify);
1983
 
25927 amit.gupta 1984
		String templateMessage = "Lead followup for %s %s, %s is due by %s";
1985
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
1986
		for (Lead lead : leadsToNotify) {
1987
			if (authUserKeyMap.get(lead.getAuthId()) == null) {
1988
				continue;
1989
			}
1990
			String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(),
25941 amit.gupta 1991
					lead.getAddress(), timeFormatter.format(lead.getLeadActivity().getSchelduleTimestamp()));
25927 amit.gupta 1992
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1993
			sendNotificationModel.setCampaignName("Lead Reminder");
1994
			sendNotificationModel.setTitle("Leads followup Reminder");
1995
			sendNotificationModel.setMessage(notificationMessage);
1996
			sendNotificationModel.setType("url");
26121 amit.gupta 1997
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 1998
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1999
			sendNotificationModel.setMessageType(MessageType.reminder);
2000
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAuthId())));
25929 amit.gupta 2001
			System.out.println(sendNotificationModel);
25927 amit.gupta 2002
			notificationService.sendNotification(sendNotificationModel);
2003
		}
2004
	}
2005
	public void notifyVisits() throws Exception {
2006
		List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), 
2007
				LocalDateTime.now().plusHours(4));
2008
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2009
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
2010
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2011
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2012
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
2013
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
25910 amit.gupta 2014
 
25927 amit.gupta 2015
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2016
			int authId = authUserEmail.getKey();
2017
			String email = authUserEmail.getValue();
2018
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2019
		}
2020
		String visitTemplate = "Planned visit to franchisee %s is due by %s";
2021
		String followupTemplate = "Lead followup for franchisee %s is due by %s";
2022
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
2023
		for (FranchiseeVisit visit : franchiseeVisits) {
2024
			if (authUserKeyMap.containsKey(visit.getAuthId())) {
2025
				continue;
2026
			}
2027
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2028
			String message = null;
2029
			if(visit.getFranchiseActivityId()==0) {
2030
				 message = String.format(visitTemplate, visit.getPartnerName(), timeFormatter.format(visit.getSchelduleTimestamp()));
2031
				 sendNotificationModel.setCampaignName("Franchisee visit Reminder");
2032
			} else {
2033
				message = String.format(followupTemplate, visit.getPartnerName(), timeFormatter.format(visit.getSchelduleTimestamp()));
2034
				sendNotificationModel.setCampaignName("Franchisee followup Reminder");
2035
			}
2036
			sendNotificationModel.setMessage(message);
2037
			sendNotificationModel.setType("url");
26122 amit.gupta 2038
			sendNotificationModel.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2039
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2040
			sendNotificationModel.setMessageType(MessageType.reminder);
2041
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
2042
			notificationService.sendNotification(sendNotificationModel);
2043
		}
25910 amit.gupta 2044
	}
25927 amit.gupta 2045
 
25982 amit.gupta 2046
	public AddPaymentResponse addPayment(AddPaymentRequest addPaymentRequest) throws Exception {
2047
		HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByTransactionId(addPaymentRequest.getTransactionId());
2048
		AddPaymentResponse response = new AddPaymentResponse();
2049
		if (hdfcPayment == null) {
2050
			hdfcPayment = new HdfcPayment();
2051
			hdfcPayment.setAmount(addPaymentRequest.getAmount());
2052
			hdfcPayment.setCreateTimestamp(LocalDateTime.now());
2053
			hdfcPayment.setCreditTimestamp(addPaymentRequest.getCreditDateTime());
2054
			hdfcPayment.setFromAccountNumber(addPaymentRequest.getFromAccountNumber());
2055
			hdfcPayment.setFromBankName(addPaymentRequest.getFromBankName());
2056
			hdfcPayment.setMmid(addPaymentRequest.getMmid());
2057
			hdfcPayment.setRemitterName(addPaymentRequest.getRemitterName());
2058
			hdfcPayment.setTransactionId(addPaymentRequest.getTransactionId());
2059
			hdfcPayment.setTransferMode(addPaymentRequest.getTransferMode());
2060
			hdfcPayment.setUtr(addPaymentRequest.getUtr());
2061
			hdfcPayment.setVirtualAccount(hdfcPayment.getVirtualAccount());
2062
			hdfcPaymentRepository.persist(hdfcPayment);
2063
			String virtualAccount = hdfcPayment.getVirtualAccount();
2064
			String retailerIdString = virtualAccount.substring(6);
2065
			int retailerId = Integer.parseInt(retailerIdString);
2066
			String description = String.format("Paid through %s, Utr# %s", hdfcPayment.getTransferMode(),
2067
					hdfcPayment.getUtr());
2068
			walletService.addAmountToWallet(retailerId, hdfcPayment.getId(), WalletReferenceType.ADVANCE_AMOUNT,
2069
					description, (float) hdfcPayment.getAmount());
2070
			response.setCode("100");
2071
			response.setStatus("Success");
2072
		} else {
2073
			response.setCode("200");
2074
			response.setStatus("Duplicate");
2075
		}
2076
		response.setTransactionId("");
2077
 
2078
		return response;
2079
	}
25927 amit.gupta 2080
 
25982 amit.gupta 2081
 
25910 amit.gupta 2082
 
25721 tejbeer 2083
}