Subversion Repositories SmartDukaan

Rev

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