Subversion Repositories SmartDukaan

Rev

Rev 25822 | Rev 25829 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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