Subversion Repositories SmartDukaan

Rev

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