Subversion Repositories SmartDukaan

Rev

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