Subversion Repositories SmartDukaan

Rev

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