Subversion Repositories SmartDukaan

Rev

Rev 25821 | Rev 25827 | 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) {
25822 amit.gupta 774
			/*
775
			 * sendTo = Arrays.asList("tarun.verma@smartdukaan.com",
776
			 * "kamini.sharma@smartdukaan.com", "amit.gupta@shop2020.in",
777
			 * "amod.sen@smartdukaan.com", "prakash.rai@smartdukaan.com");
778
			 */
779
			sendTo = Arrays.asList("amit.gupta@shop2020.in");
25312 amit.gupta 780
		}
781
		Map<String, List<? extends Serializable>> partnerSalesTargetRowsMap = new HashMap<>();
25822 amit.gupta 782
		partnerSalesTargetRowsMap = targetService.getDailySaleReportVsTarget();
25315 amit.gupta 783
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
784
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
785
 
25312 amit.gupta 786
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
25315 amit.gupta 787
				.getFofoRetailers(new ArrayList<>(fofoStoresMap.keySet()));
24177 govind 788
 
25315 amit.gupta 789
		Map<String, CustomRetailer> customRetailerEmailMap = customRetailerMap.values().stream()
790
				.collect(Collectors.toMap(x -> x.getEmail(), x -> x));
25609 amit.gupta 791
 
25598 amit.gupta 792
		Map<String, SaleRoles> partnerEmailSalesMap = this.getPartnerEmailSalesMap();
25315 amit.gupta 793
 
25598 amit.gupta 794
		List<String> headers = Arrays.asList("Code", "Firm Name", "Store Name", "Current Category", "State Manager",
795
				"Teritory Manager", "Team Leader", "Targeted Category", "Targeted Value", "Target Achieved",
796
				"Achived Percentage", "Remaining Target", "Today's Target", "Today's achievement");
24177 govind 797
 
25312 amit.gupta 798
		List<List<? extends Serializable>> rows = new ArrayList<>();
799
		Map<String, List<Serializable>> partnerRowMap = new HashMap<>();
25315 amit.gupta 800
		for (Map.Entry<String, List<? extends Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap
801
				.entrySet()) {
802
			CustomRetailer retailer = customRetailerEmailMap.get(partnerSalesTargetRowEntry.getKey());
803
			FofoStore fofoStore = fofoStoresMap.get(retailer.getPartnerId());
25312 amit.gupta 804
			Serializable code = fofoStore.getCode();
25345 amit.gupta 805
			Serializable storeName = "SmartDukaan-" + fofoStore.getCode().replaceAll("[a-zA-Z]", "");
25314 amit.gupta 806
			Serializable businessName = retailer.getBusinessName();
25317 amit.gupta 807
			try {
25609 amit.gupta 808
				Serializable stateManager = StringUtils.join(partnerEmailSalesMap.get(retailer.getEmail()).getL2(),
809
						", ");
810
				Serializable territoryManager = StringUtils.join(partnerEmailSalesMap.get(retailer.getEmail()).getL1(),
811
						", ");
25317 amit.gupta 812
				List<Serializable> row = new ArrayList<>(
25598 amit.gupta 813
						Arrays.asList(code, businessName, storeName, stateManager, territoryManager));
25317 amit.gupta 814
				if (partnerSalesTargetRowsMap.get(retailer.getEmail()) != null) {
25323 amit.gupta 815
					row.addAll(partnerSalesTargetRowsMap.get(retailer.getEmail()));
25317 amit.gupta 816
					partnerRowMap.put(retailer.getEmail(), row);
817
					rows.add(row);
818
				}
25351 tejbeer 819
			} catch (Exception e) {
25317 amit.gupta 820
				LOGGER.warn("Could not find partner with email - {}", retailer.getEmail());
25315 amit.gupta 821
			}
25312 amit.gupta 822
 
24177 govind 823
		}
25503 amit.gupta 824
 
25318 amit.gupta 825
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
24240 amit.gupta 826
 
25312 amit.gupta 827
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
828
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
829
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
830
				new ByteArrayResource(baos.toByteArray()));
24174 govind 831
	}
24683 amit.gupta 832
 
24697 amit.gupta 833
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 834
 
835
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
836
				"itemstockageing.xml");
24708 amit.gupta 837
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 838
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 839
		Attachment attachment = new Attachment(
25445 amit.gupta 840
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 841
		Attachment attachment1 = new Attachment(
25445 amit.gupta 842
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 843
 
25609 amit.gupta 844
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
845
				attachment);
846
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
847
				"Itemwise Pending indent", "PFA", attachment1);
848
 
25598 amit.gupta 849
		// Reports to be sent to mapped partners
25597 amit.gupta 850
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 851
 
852
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 853
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 854
			if (storeGuyEntry.getValue().size() == 0)
855
				continue;
25418 amit.gupta 856
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
857
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
858
					"focostockreport.xml", params);
859
			Attachment attache = new Attachment(
25609 amit.gupta 860
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 861
			System.out.println(storeGuyEntry.getValue());
25609 amit.gupta 862
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
863
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 864
		}
25503 amit.gupta 865
 
24681 amit.gupta 866
	}
24533 govind 867
 
24697 amit.gupta 868
	public void sendAgeingReport() throws Exception {
25807 amit.gupta 869
		sendAgeingReport("kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com",
25609 amit.gupta 870
				"chaitnaya.vats@smartdukaan.com");
24697 amit.gupta 871
	}
872
 
24533 govind 873
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 874
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 875
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 876
			priceDropService.priceDropStatus(priceDrop.getId());
877
		}
878
	}
23929 amit.gupta 879
 
24542 amit.gupta 880
	public void walletmismatch() throws Exception {
881
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 882
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 883
		System.out.println(pdis.size());
24542 amit.gupta 884
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 885
			int fofoId = pdi.getFofoId();
24542 amit.gupta 886
			for (PartnerDailyInvestment investment : Lists
887
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 888
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 889
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 890
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 891
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
892
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 893
 
24542 amit.gupta 894
			}
24549 amit.gupta 895
		}
24542 amit.gupta 896
 
897
	}
898
 
899
	public void gst() throws Exception {
24548 amit.gupta 900
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
901
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
902
		for (FofoOrder fofoOrder : fofoOrders) {
903
			int retailerAddressId = retailerRegisteredAddressRepository
904
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 905
 
906
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
907
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
908
			Integer stateId = null;
909
			if (customerAddress.getState().equals(retailerAddress.getState())) {
910
				try {
911
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
912
				} catch (Exception e) {
913
					LOGGER.error("Unable to get state rates");
914
				}
915
			}
916
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
917
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 918
 
919
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
920
			Set<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
24542 amit.gupta 921
			if (stateId != null) {
922
				itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemIds), stateId);
923
			} else {
924
				itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemIds));
925
			}
926
 
24548 amit.gupta 927
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 928
				if (stateId == null) {
929
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
930
				} else {
931
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
932
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
933
				}
934
				fofoOrderItemRepository.persist(foi);
935
			}
936
		}
24548 amit.gupta 937
 
24542 amit.gupta 938
	}
939
 
24580 amit.gupta 940
	public void schemewalletmismatch() {
941
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 942
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 943
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 944
			// reconcileOrders(dateTime);
945
			// reconcileRecharges(dateTime);
24580 amit.gupta 946
			dateToReconcile = dateToReconcile.plusDays(1);
947
		}
948
	}
949
 
950
	private void reconcileSchemes(LocalDate date) {
951
		LocalDateTime startDate = date.atStartOfDay();
952
		LocalDateTime endDate = startDate.plusDays(1);
953
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
954
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 955
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
956
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 957
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 958
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
959
				WalletReferenceType.SCHEME_OUT);
960
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
961
				walletReferenceTypes);
962
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
963
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 964
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 965
 
966
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
967
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
968
 
969
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
970
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
971
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
972
 
973
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
974
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
975
 
976
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
977
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
978
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
979
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
980
 
981
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
982
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeMap.entrySet()) {
983
			}
984
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
985
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
986
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
987
				} else {
988
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
989
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
990
				}
991
			}
24590 amit.gupta 992
			Map<Integer, Integer> userWalletMap = userWalletRepository
993
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
994
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
995
 
24587 amit.gupta 996
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
997
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
998
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
999
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1000
				if (diff > 5) {
1001
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1002
				}
1003
			}
24580 amit.gupta 1004
		}
24587 amit.gupta 1005
 
24580 amit.gupta 1006
	}
24590 amit.gupta 1007
 
24592 amit.gupta 1008
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1009
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1010
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1011
 
24592 amit.gupta 1012
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1013
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1014
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1015
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1016
		Set<String> serialNumbersConsidered = new HashSet<>();
1017
 
25096 amit.gupta 1018
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1019
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1020
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1021
 
24683 amit.gupta 1022
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1023
		purchases.stream().forEach(purchase -> {
1024
			float amountToRollback = 0;
1025
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1026
					+ purchase.getPurchaseReference();
1027
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1028
					.stream().filter(ii -> ii.getSerialNumber() != null)
1029
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1030
			if (inventorySerialNumberMap.size() > 0) {
1031
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1032
					String serialNumber = inventorySerialNumberEntry.getValue();
1033
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1034
					if (serialNumbersConsidered.contains(serialNumber)) {
1035
						// This will rollback scheme for differenct orders for same serial
1036
						List<SchemeInOut> sios = schemeInOutRepository
1037
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1038
								.filter(x -> x.getRolledBackTimestamp() == null
1039
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1040
								.collect(Collectors.toList());
1041
						Collections.reverse(sios);
1042
						for (SchemeInOut sio : sios) {
1043
							sio.setRolledBackTimestamp(LocalDateTime.now());
1044
							amountToRollback += sio.getAmount();
1045
							// sio.setSchemeType(SchemeType.OUT);
1046
							sio.setSerialNumber(serialNumber);
1047
							rolledbackSios.add(sio);
1048
						}
1049
						description = description.concat(" " + serialNumber + " ");
1050
					} else {
1051
						serialNumbersConsidered.add(serialNumber);
1052
						List<Integer> schemesConsidered = new ArrayList<>();
1053
						List<SchemeInOut> sios = schemeInOutRepository
1054
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1055
								.filter(x -> x.getRolledBackTimestamp() == null
1056
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1057
								.collect(Collectors.toList());
1058
						Collections.reverse(sios);
1059
						for (SchemeInOut sio : sios) {
1060
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1061
								schemesConsidered.add(sio.getSchemeId());
1062
								continue;
1063
							}
1064
							sio.setRolledBackTimestamp(LocalDateTime.now());
1065
							amountToRollback += sio.getAmount();
1066
							// sio.setSchemeType(SchemeType.OUT);
1067
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1068
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1069
							sio.setReference(purchase.getId());
24635 amit.gupta 1070
							rolledbackSios.add(sio);
1071
						}
1072
					}
1073
 
1074
				}
1075
			}
1076
			if (amountToRollback > 0) {
24683 amit.gupta 1077
				// Address address =
1078
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1079
				UserWalletHistory uwh = new UserWalletHistory();
1080
				uwh.setAmount(Math.round(amountToRollback));
1081
				uwh.setDescription(description);
1082
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1083
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1084
				uwh.setReference(purchase.getId());
1085
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1086
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1087
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1088
				userWalletHistory.add(uwh);
1089
			}
1090
		});
1091
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1092
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1093
						"Timestamp"),
1094
				userWalletHistory.stream()
1095
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1096
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1097
						.collect(Collectors.toList()));
1098
 
1099
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1100
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1101
						"Created", "Rolledback"),
24635 amit.gupta 1102
				rolledbackSios.stream()
24681 amit.gupta 1103
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1104
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1105
						.collect(Collectors.toList()));
1106
 
25043 amit.gupta 1107
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1108
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1109
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1110
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1111
 
25096 amit.gupta 1112
		throw new Exception();
24635 amit.gupta 1113
 
1114
	}
1115
 
1116
	public void dryRunOutSchemeReco() throws Exception {
1117
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1118
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1119
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1120
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1121
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1122
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1123
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1124
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1125
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1126
		// Collections.reverse(allOrders);
1127
		// List<FofoOrder> allOrders =
24653 govind 1128
		// List<FofoOrder> allOrders =
24631 amit.gupta 1129
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1130
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1131
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1132
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1133
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1134
			float amountToRollback = 0;
24590 amit.gupta 1135
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1136
			orderItems.forEach(x -> {
24606 amit.gupta 1137
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1138
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1139
			});
24606 amit.gupta 1140
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1141
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1142
					String serialNumber = inventorySerialNumberEntry.getValue();
1143
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1144
					if (serialNumbersConsidered.contains(serialNumber)) {
1145
						// This will rollback scheme for differenct orders for same serial
1146
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1147
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1148
								.filter(x -> x.getRolledBackTimestamp() == null
1149
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1150
								.collect(Collectors.toList());
1151
						Collections.reverse(sios);
1152
						for (SchemeInOut sio : sios) {
1153
							sio.setRolledBackTimestamp(LocalDateTime.now());
1154
							amountToRollback += sio.getAmount();
1155
							// sio.setSchemeType(SchemeType.OUT);
1156
							sio.setSerialNumber(serialNumber);
1157
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1158
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1159
							rolledbackSios.add(sio);
24623 amit.gupta 1160
						}
24635 amit.gupta 1161
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1162
					} else {
1163
						serialNumbersConsidered.add(serialNumber);
1164
						List<Integer> schemesConsidered = new ArrayList<>();
1165
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1166
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1167
								.filter(x -> x.getRolledBackTimestamp() == null
1168
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1169
								.collect(Collectors.toList());
1170
						Collections.reverse(sios);
1171
						for (SchemeInOut sio : sios) {
1172
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1173
								schemesConsidered.add(sio.getSchemeId());
1174
								continue;
1175
							}
1176
							sio.setRolledBackTimestamp(LocalDateTime.now());
1177
							amountToRollback += sio.getAmount();
1178
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1179
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1180
							sio.setSerialNumber(serialNumber);
1181
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1182
							rolledbackSios.add(sio);
1183
						}
24615 amit.gupta 1184
					}
24631 amit.gupta 1185
 
24604 amit.gupta 1186
				}
24590 amit.gupta 1187
			}
24631 amit.gupta 1188
			if (amountToRollback > 0) {
1189
				UserWalletHistory uwh = new UserWalletHistory();
1190
				uwh.setAmount(Math.round(amountToRollback));
1191
				uwh.setDescription(description);
1192
				uwh.setTimestamp(LocalDateTime.now());
1193
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1194
				uwh.setReference(fofoOrder.getId());
1195
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1196
				uwh.setFofoId(fofoOrder.getFofoId());
1197
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1198
				userWalletHistory.add(uwh);
1199
			}
24590 amit.gupta 1200
		});
24598 amit.gupta 1201
 
24592 amit.gupta 1202
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1203
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1204
						"Timestamp"),
1205
				userWalletHistory.stream()
1206
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1207
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1208
						.collect(Collectors.toList()));
1209
 
1210
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1211
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1212
						"Rolledback"),
1213
				rolledbackSios.stream()
1214
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1215
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1216
						.collect(Collectors.toList()));
1217
 
25043 amit.gupta 1218
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1219
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1220
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1221
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1222
 
25267 amit.gupta 1223
		throw new Exception();
24590 amit.gupta 1224
	}
24615 amit.gupta 1225
 
24611 amit.gupta 1226
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1227
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1228
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1229
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1230
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1231
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1232
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1233
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1234
		references.stream().forEach(reference -> {
1235
			FofoOrder fofoOrder = null;
1236
			try {
1237
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1238
			} catch (Exception e) {
1239
 
24611 amit.gupta 1240
			}
1241
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1242
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1243
			float amountToRollback = 0;
1244
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1245
			orderItems.forEach(x -> {
1246
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1247
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1248
			});
1249
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1250
				List<SchemeInOut> sios = schemeInOutRepository
1251
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1252
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1253
						.collect(Collectors.toList());
1254
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1255
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1256
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1257
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1258
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1259
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1260
					if (outList.size() > 1) {
1261
 
24611 amit.gupta 1262
					}
1263
				}
1264
				uwh.setAmount(Math.round(amountToRollback));
1265
				uwh.setDescription(description);
1266
				uwh.setTimestamp(LocalDateTime.now());
1267
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1268
				uwh.setReference(fofoOrder.getId());
1269
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1270
				uwh.setFofoId(fofoOrder.getFofoId());
1271
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1272
				userWalletHistory.add(uwh);
1273
			}
1274
		});
24615 amit.gupta 1275
 
24611 amit.gupta 1276
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1277
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1278
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1279
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1280
						.collect(Collectors.toList()));
1281
 
24611 amit.gupta 1282
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1283
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1284
						"Rolledback"),
1285
				rolledbackSios.stream()
24615 amit.gupta 1286
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1287
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1288
						.collect(Collectors.toList()));
1289
 
24623 amit.gupta 1290
		Utils.sendMailWithAttachments(googleMailSender,
1291
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1292
				"Partner Excess Amount", "PFA",
1293
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1294
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1295
 
24628 amit.gupta 1296
		throw new Exception();
24615 amit.gupta 1297
 
24611 amit.gupta 1298
	}
24615 amit.gupta 1299
 
24855 amit.gupta 1300
	public void sendDailySalesReportNotificationToPartner(Integer fofoIdInt)
24653 govind 1301
			throws ProfitMandiBusinessException, MessagingException, IOException {
1302
		LocalDateTime now = LocalDateTime.now();
1303
		LocalDateTime from = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 00, 00);
1304
		Map<Integer, Double> salesByFofoIdMap = new HashMap<>();
24855 amit.gupta 1305
		List<Integer> fofoIds = null;
25043 amit.gupta 1306
		if (fofoIdInt == null) {
1307
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1308
					.collect(Collectors.toList());
24856 amit.gupta 1309
		} else {
24855 amit.gupta 1310
			fofoIds = Arrays.asList(fofoIdInt);
1311
		}
24653 govind 1312
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
1313
				.selectAllGeEqAndLeEqStartDateAndEndDate(now);
24683 amit.gupta 1314
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h a");
1315
 
1316
		Map<Integer, Float> dailyTarget = new HashMap<>();
24653 govind 1317
		for (Integer fofoId : fofoIds) {
24683 amit.gupta 1318
			Map<Integer, Float> dailyAverageSale = null;
24653 govind 1319
			double sale = fofoOrderRepository.selectTotalSaleSumByFofoIdBrtweenDate(fofoId, from, now);
1320
			for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
1321
				Map<Integer, Float> targetValues = targetService.getTargetValueByFofoIdAndTargetId(fofoId,
1322
						partnerTargetDetail.getId());
1323
				if (targetValues.size() == 0) {
1324
					continue;
1325
				} else {
1326
					List<Integer> partnerIds = new ArrayList<>();
1327
					partnerIds.add(fofoId);
1328
					dailyAverageSale = targetService.getDailyAverageSaleForCurrentForSingleFofoIdAndBrand(partnerIds,
1329
							targetValues, partnerTargetDetail.getStartDate(), partnerTargetDetail.getEndDate(),
1330
							partnerTargetDetail.getBrandName());
1331
					dailyTarget.put(fofoId, dailyAverageSale.get(fofoId));
1332
					break;
1333
				}
1334
			}
25821 amit.gupta 1335
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1336
			sendNotificationModel.setCampaignName("Sales update alert");
24683 amit.gupta 1337
			if (dailyAverageSale != null && dailyAverageSale.get(fofoId) != null) {
25821 amit.gupta 1338
				sendNotificationModel.setMessage(String.format("Rs.%.0f till %s. Today's Target is Rs.%.0f", sale,
24847 amit.gupta 1339
						now.format(timeFormatter), dailyAverageSale.get(fofoId)));
24683 amit.gupta 1340
			} else {
25821 amit.gupta 1341
				sendNotificationModel.setMessage(String.format("Rs.%.0f till %s", sale, now.format(timeFormatter)));
24653 govind 1342
			}
25821 amit.gupta 1343
			sendNotificationModel.setType("url");
1344
			sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
1345
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1346
			sendNotificationModel.setMessageType(MessageType.notification);
24653 govind 1347
			salesByFofoIdMap.put(fofoId, sale);
1348
			LOGGER.info(sale);
1349
		}
24683 amit.gupta 1350
		String saleReport = this.getDailySalesReportByPartnerId(salesByFofoIdMap, dailyTarget);
24653 govind 1351
		LOGGER.info(saleReport);
25822 amit.gupta 1352
		String cc[] = {};/*
1353
							 * { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
1354
							 * "prakash.rai@smartdukaan.com", "chaitnaya.vats@smartdukaan.com",
1355
							 * "adeel.yazdani@smartdukaan.com", "mohinder.mutreja@smartdukaan.com" };
1356
							 */
24653 govind 1357
		String subject = "sale report till" + " " + now.format(timeFormatter);
25821 amit.gupta 1358
		this.sendMailOfHtmlFomat("amit.gupta@shop2020.in", saleReport, cc, subject);
25822 amit.gupta 1359
		// this.sendMailOfHtmlFomat("amod.sen@smartdukaan.com", saleReport, cc,
1360
		// subject);
24653 govind 1361
	}
1362
 
24683 amit.gupta 1363
	public String getDailySalesReportByPartnerId(Map<Integer, Double> salesByFofoIdMap, Map<Integer, Float> dailyTarget)
24653 govind 1364
			throws ProfitMandiBusinessException {
1365
		StringBuilder sb = new StringBuilder();
1366
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black ;padding: 5px';>");
1367
		sb.append("<tbody>\n" + "	    				<tr>\n"
1368
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner</th>\n"
1369
				+ "	    					<th style='border:1px solid black;padding: 5px'>Daily Target</th>\n"
1370
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
1371
				+ "	    				</tr>");
1372
		for (Integer fofoId : salesByFofoIdMap.keySet()) {
25043 amit.gupta 1373
			try {
1374
				String PartnerName = retailerService.getFofoRetailer(fofoId).getBusinessName();
1375
				sb.append("<tr>");
1376
				sb.append("<td style='border:1px solid black;padding: 5px'>" + PartnerName + "</td>");
1377
				if (dailyTarget != null && dailyTarget.get(fofoId) != null) {
1378
					sb.append("<td style='border:1px solid black;padding: 5px'>" + dailyTarget.get(fofoId) + "</td>");
1379
				} else {
1380
					sb.append("<td style='border:1px solid black;padding: 5px'>" + 0.0 + "</td>");
1381
				}
1382
				sb.append("<td style='border:1px solid black;padding: 5px'>" + salesByFofoIdMap.get(fofoId) + "</td>");
24653 govind 1383
 
25043 amit.gupta 1384
				sb.append("</tr>");
1385
			} catch (Exception e) {
24842 govind 1386
				e.printStackTrace();
1387
			}
25043 amit.gupta 1388
 
24653 govind 1389
		}
24683 amit.gupta 1390
 
24653 govind 1391
		sb.append("</tbody></table></body></html>");
1392
		return sb.toString();
1393
	}
24841 govind 1394
 
1395
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1396
			throws MessagingException, ProfitMandiBusinessException, IOException {
1397
		MimeMessage message = mailSender.createMimeMessage();
1398
		MimeMessageHelper helper = new MimeMessageHelper(message);
1399
		helper.setSubject(subject);
1400
		helper.setText(body, true);
1401
		helper.setTo(email);
1402
		if (cc != null) {
1403
			helper.setCc(cc);
1404
		}
1405
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1406
		helper.setFrom(senderAddress);
1407
		mailSender.send(message);
1408
	}
25300 tejbeer 1409
 
25351 tejbeer 1410
	public void sendNotification() throws Exception {
25300 tejbeer 1411
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1412
		if (!pushNotifications.isEmpty()) {
1413
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1414
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1415
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1416
						.selectById(pushNotification.getNotificationCampaignid());
1417
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1418
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1419
 
1420
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1421
						SimpleCampaignParams.class);
1422
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1423
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1424
				JSONObject json = new JSONObject();
25351 tejbeer 1425
				json.put("to", device.getFcmId());
25300 tejbeer 1426
				JSONObject jsonObj = new JSONObject();
1427
				jsonObj.put("message", campaign.getMessage());
1428
				jsonObj.put("title", campaign.getTitle());
1429
				jsonObj.put("type", campaign.getType());
1430
				jsonObj.put("url", result_url);
1431
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1432
				jsonObj.put("image", campaign.getImageUrl());
1433
				jsonObj.put("largeIcon", "large_icon");
1434
				jsonObj.put("smallIcon", "small_icon");
1435
				jsonObj.put("vibrate", 1);
1436
				jsonObj.put("pid", pushNotification.getId());
1437
				jsonObj.put("sound", 1);
1438
				jsonObj.put("priority", "high");
1439
				json.put("data", jsonObj);
25351 tejbeer 1440
				try {
1441
					CloseableHttpClient client = HttpClients.createDefault();
1442
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1443
 
25351 tejbeer 1444
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1445
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1446
					StringEntity entity = new StringEntity(json.toString());
1447
					httpPost.setEntity(entity);
1448
					CloseableHttpResponse response = client.execute(httpPost);
1449
					LOGGER.info("response" + response);
25300 tejbeer 1450
 
25351 tejbeer 1451
					if (response.getStatusLine().getStatusCode() == 200) {
1452
						pushNotification.setSentTimestamp(LocalDateTime.now());
1453
					} else {
25356 tejbeer 1454
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 1455
						LOGGER.info("message" + "not sent");
25351 tejbeer 1456
					}
25300 tejbeer 1457
 
25351 tejbeer 1458
				} catch (Exception e) {
1459
					e.printStackTrace();
25300 tejbeer 1460
					LOGGER.info("message" + "not sent");
1461
				}
1462
			}
1463
		}
1464
	}
1465
 
25553 amit.gupta 1466
	public void grouping() throws Exception {
25609 amit.gupta 1467
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
1468
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
1469
		System.out.println(String.join("\t",
1470
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 1471
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
25609 amit.gupta 1472
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers();
1473
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 1474
			if (priceDropIMEI.getPartnerId() == 0)
1475
				continue;
25609 amit.gupta 1476
			HashSet<String> imeis = new HashSet<>();
1477
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
1478
			imeis.add(priceDropIMEI.getImei());
1479
			List<InventoryItem> inventoryItems = inventoryItemRepository
1480
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 1481
			if (inventoryItems.size() == 0) {
1482
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 1483
				continue;
25612 amit.gupta 1484
			}
25609 amit.gupta 1485
			InventoryItem inventoryItem = inventoryItems.get(0);
1486
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
1487
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
1488
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
1489
				// check if pricedrop has been rolled out
1490
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
1491
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
1492
				if (uwh.size() > 0) {
25615 amit.gupta 1493
					Item item = itemRepository.selectById(inventoryItem.getItemId());
25609 amit.gupta 1494
					System.out.println(String.join("\t",
1495
							Arrays.asList(priceDropIMEI.getImei(), inventoryItem.getItemId() + "", item.getBrand(),
1496
									item.getModelName(), item.getModelNumber(), inventoryItem.getFofoId() + "",
1497
									customRetailer.getBusinessName(), inventoryItem.getCreateTimestamp().format(dtf),
1498
									priceDrop.getAffectedOn().format(dtf),
1499
									priceDropIMEI.getUpdateTimestamp().format(dtf),
25694 amit.gupta 1500
									inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getPartnerPayout() + "",
25609 amit.gupta 1501
									inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
1502
				}
1503
			}
1504
		}
25598 amit.gupta 1505
		/*
1506
		 * for (FofoStore fofoStore : fofoStoreRepository.selectAll()) {
1507
		 * LOGGER.info("{}, {}", fofoStore.getId(),
1508
		 * partnerTypeChangeService.getTypeOnDate(fofoStore.getId(),
1509
		 * LocalDate.now().plusDays(1))); UserWallet userWallet =
1510
		 * userWalletRepository.selectByRetailerId(fofoStore.getId());
1511
		 * if(userWallet==null) continue;
1512
		 * System.out.printf("Store Code %s, Wallet amount %d, Sum amount %f%n",
1513
		 * fofoStore.getCode(), userWallet.getAmount(),
1514
		 * walletService.getWalletAmount(fofoStore.getId())); }
1515
		 */
25609 amit.gupta 1516
 
1517
		/*
1518
		 * for (Map.Entry<String, Set<String>> storeGuyEntry :
1519
		 * csService.getAuthUserPartnerEmailMapping().entrySet()) {
1520
		 * System.out.println(storeGuyEntry.getKey() + " = " +
1521
		 * storeGuyEntry.getValue()); }
1522
		 */
25503 amit.gupta 1523
	}
25694 amit.gupta 1524
 
1525
	public void testToffee() throws Exception {
25800 tejbeer 1526
		// LOGGER.info("{}", toffeeService.getAuthToken());
25694 amit.gupta 1527
		LOGGER.info("{}", toffeeService.getProducts());
25800 tejbeer 1528
		// LOGGER.info("{}", toffeeService.getPincodes("36103000PR"));
25778 amit.gupta 1529
		PremiumCalculationRequestModel pcrm = new PremiumCalculationRequestModel();
1530
		pcrm.setProductDetails("36103000PR");
25800 tejbeer 1531
		// pcrm.setProductDetails("36103000PR");
25778 amit.gupta 1532
		pcrm.setDurations(Arrays.asList("3 Months", "6 Months", "1 Year"));
1533
		pcrm.setSumInsured("15000");
1534
		System.out.println(toffeeService.getPremiumCalculation(pcrm));
25694 amit.gupta 1535
	}
1536
 
1537
	public void schemeRollback(List<String> schemeIds) throws Exception {
1538
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 1539
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 1540
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1541
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
1542
		for (SchemeInOut sio : schemeInOuts) {
1543
			Scheme scheme = schemesMap.get(sio.getSchemeId());
1544
			if (scheme.getType().equals(SchemeType.IN)) {
1545
 
1546
			} else if (scheme.getType().equals(SchemeType.OUT)) {
1547
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
1548
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
1549
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
1550
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
1551
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
1552
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
1553
					sio.setRolledBackTimestamp(LocalDateTime.now());
1554
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 1555
					String rollbackReason = "Scheme reversed for "
1556
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 1557
							+ fofoOrder.getInvoiceNumber();
1558
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
1559
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason);
1560
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
1561
							rollbackReason);
1562
				}
1563
			}
1564
		}
25721 tejbeer 1565
		// throw new Exception();
25694 amit.gupta 1566
	}
25721 tejbeer 1567
 
1568
	public void checkfocusedModelInPartnerStock() throws Exception {
1569
 
1570
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1571
				.collect(Collectors.toList());
1572
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
1573
		for (Integer fofoId : fofoIds) {
1574
			if (!focusedModelShortageReportMap.containsKey(fofoId)) {
1575
				focusedModelShortageReportMap.put(fofoId, new ArrayList<>());
1576
			}
1577
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1578
			Map<Integer, Integer> processingOrderMap = null;
1579
			Map<Integer, Integer> catalogIdAndQtyMap = null;
1580
			Map<Integer, Integer> grnPendingOrdersMap = null;
1581
 
1582
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1583
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1584
 
1585
			if (!currentInventorySnapshot.isEmpty()) {
1586
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1587
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1588
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1589
 
1590
			}
1591
 
1592
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1593
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1594
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1595
			if (!grnPendingOrders.isEmpty()) {
1596
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1597
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1598
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1599
 
1600
			}
1601
 
1602
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1603
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1604
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1605
			if (!processingOrder.isEmpty()) {
1606
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1607
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1608
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1609
 
1610
			}
1611
 
25800 tejbeer 1612
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1613
					.collect(Collectors.toList());
1614
 
1615
			List<Integer> focusedModelCatalogId = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
1616
					.collect(Collectors.toList());
1617
			Map<String, Object> equalsMap = new HashMap<>();
1618
			equalsMap.put("categoryId", 10006);
1619
			equalsMap.put("brand", brands);
1620
 
1621
			Map<String, List<?>> notEqualsMap = new HashMap<>();
1622
 
1623
			Map<String, Object> equalsJoinMap = new HashMap<>();
1624
			equalsJoinMap.put("catalogId", focusedModelCatalogId);
1625
 
1626
			Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1627
 
1628
			List<Integer> catalogIds = itemRepository
1629
					.selectItems(FocusedModel.class, "catalogItemId", "catalogId", equalsMap, notEqualsMap,
1630
							equalsJoinMap, notEqualsJoinMap, "minimumQty")
1631
					.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
1632
 
1633
			Map<Integer, Integer> focusedCatalogIdAndQtyMap = focusedModelRepository.selectByCatalogIdsl(catalogIds)
1634
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getMinimumQty()));
1635
 
1636
			/*
1637
			 * Map<Integer, Integer> focusedCatalogIdAndQtyMap =
1638
			 * focusedModelRepository.selectAll().stream() .collect(Collectors.toMap(x ->
1639
			 * x.getCatalogId(), x -> x.getMinimumQty()));
1640
			 */
1641
 
25721 tejbeer 1642
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
1643
 
1644
			for (Map.Entry<Integer, Integer> entry : focusedCatalogIdAndQtyMap.entrySet()) {
1645
				int inStockQty = 0;
1646
				int processingQty = 0;
1647
				int grnPendingQty = 0;
1648
				if (processingOrderMap != null) {
1649
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
1650
							: processingOrderMap.get(entry.getKey());
1651
 
1652
				}
1653
				if (grnPendingOrdersMap != null) {
1654
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
1655
							: grnPendingOrdersMap.get(entry.getKey());
1656
 
1657
				}
1658
				if (catalogIdAndQtyMap != null) {
1659
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
1660
							: catalogIdAndQtyMap.get(entry.getKey());
1661
 
1662
				}
1663
				int totalQty = processingQty + grnPendingQty + inStockQty;
1664
 
1665
				if (totalQty < entry.getValue()) {
1666
 
1667
					int shortageQty = entry.getValue() - totalQty;
1668
					List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
1669
 
1670
					FocusedModelShortageModel fm = new FocusedModelShortageModel();
1671
					fm.setFofoId(fofoId);
1672
					fm.setStoreName(customRetailer.getBusinessName());
1673
 
1674
					fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
1675
					fm.setShortageQty(shortageQty);
1676
 
1677
					focusedModelShortageReportMap.get(fofoId).add(fm);
1678
				}
1679
 
1680
			}
1681
			List<FocusedModelShortageModel> focusedModelShortageModel = focusedModelShortageReportMap.get(fofoId);
1682
 
1683
			if (!focusedModelShortageModel.isEmpty()) {
1684
				String subject = "Stock Alert";
1685
				String messageText = this.getMessage(focusedModelShortageModel);
1686
 
25732 tejbeer 1687
				this.sendMailWithAttachments(subject, messageText, customRetailer.getEmail());
25721 tejbeer 1688
				String notificationMessage = this.getNotificationMessage(focusedModelShortageModel);
1689
 
1690
				LOGGER.info("notificationMessage" + notificationMessage);
1691
				SimpleCampaignParams scp = new SimpleCampaignParams();
1692
 
1693
				scp.setTitle("Alert");
1694
				scp.setType("url");
25759 tejbeer 1695
				scp.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25721 tejbeer 1696
				scp.setMessage(notificationMessage);
1697
				scp.setExpireTimestamp(LocalDateTime.now().plusDays(2));
1698
				SimpleCampaign sc = new SimpleCampaign(scp);
1699
				sc.setSimpleCampaignParams(scp);
1700
				LOGGER.info("scp" + scp);
1701
				NotificationCampaign nc = new NotificationCampaign();
1702
				nc.setName("Stock Alert");
1703
				nc.setImplementationType("SimpleCampaign");
1704
				nc.setImplementationParams(gson.toJson(scp));
1705
				nc.setCreatedTimestamp(LocalDateTime.now());
1706
				nc.setMessageType(MessageType.notification);
1707
				notificationCampaignRepository.persist(nc);
1708
				LOGGER.info("nc" + nc);
1709
				LOGGER.info("fofoID" + fofoId);
25732 tejbeer 1710
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
25721 tejbeer 1711
				LOGGER.info("userId" + userId);
1712
 
1713
				UserCampaign uc = new UserCampaign();
1714
				uc.setCampaignId(nc.getId());
1715
				uc.setUserId(userId);
1716
				uc.setPushTimestamp(LocalDateTime.now());
25800 tejbeer 1717
 
25721 tejbeer 1718
				userCampaignRepository.persist(uc);
1719
				List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(userId,
1720
						LocalDateTime.now().minusMonths(3), LocalDateTime.now());
1721
				pushNotification(nc.getId(), devices);
1722
 
1723
			}
25732 tejbeer 1724
 
25721 tejbeer 1725
		}
25800 tejbeer 1726
		if (!focusedModelShortageReportMap.isEmpty())
25721 tejbeer 1727
 
25800 tejbeer 1728
		{
1729
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
1730
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1731
			Map<String, List<List<? extends Serializable>>> emailRowsMap = new HashMap<>();
25721 tejbeer 1732
 
25800 tejbeer 1733
			focusedModelShortageReportMap.entrySet().forEach(x -> {
1734
				storeGuyMap.entrySet().forEach(y -> {
1735
 
1736
					if (y.getValue().contains(x.getKey())) {
1737
						if (!emailRowsMap.containsKey(y.getKey())) {
1738
							emailRowsMap.put(y.getKey(), new ArrayList<>());
1739
						}
1740
						List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays
1741
								.asList(r.getFofoId(), r.getStoreName(), r.getItemName(), r.getShortageQty()))
1742
								.collect(Collectors.toList());
1743
						emailRowsMap.get(y.getKey()).addAll(fms);
1744
 
25721 tejbeer 1745
					}
1746
 
25800 tejbeer 1747
				});
25721 tejbeer 1748
 
1749
			});
1750
 
25800 tejbeer 1751
			List<String> headers = Arrays.asList("Partner Id", "Partner Name", "Model Name", "Shortage Qty");
1752
			emailRowsMap.entrySet().forEach(e -> {
25721 tejbeer 1753
 
25800 tejbeer 1754
				ByteArrayOutputStream baos = null;
1755
				try {
1756
					baos = FileUtil.getCSVByteStream(headers, e.getValue());
1757
				} catch (Exception e2) {
1758
					e2.printStackTrace();
1759
				}
1760
				String[] sendToArray = new String[] { e.getKey() };
1761
				try {
25721 tejbeer 1762
 
25800 tejbeer 1763
					LOGGER.info("email" + e.getKey());
1764
					LOGGER.info("list" + e.getValue());
25721 tejbeer 1765
 
25800 tejbeer 1766
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
1767
							new ByteArrayResource(baos.toByteArray()));
1768
				} catch (Exception e1) { // TODO Auto-generated catch block
1769
					e1.printStackTrace();
1770
				}
25721 tejbeer 1771
 
25800 tejbeer 1772
			});
1773
		}
25721 tejbeer 1774
	}
1775
 
1776
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1777
		StringBuilder sb = new StringBuilder();
1778
		sb.append("Focused Model Shortage in Your Stock : \n");
1779
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1780
 
1781
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
1782
			sb.append(String.format("%n", ""));
1783
		}
1784
		return sb.toString();
1785
	}
1786
 
1787
	public void pushNotification(int cid, List<Device> devices) {
1788
		for (Device device : devices) {
1789
			PushNotifications pn = new PushNotifications();
1790
			pn.setNotificationCampaignid(cid);
1791
			pn.setDeviceId(device.getId());
1792
			pn.setUserId(device.getUser_id());
1793
			pushNotificationRepository.persist(pn);
1794
		}
1795
 
1796
	}
1797
 
1798
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
1799
		MimeMessage message = mailSender.createMimeMessage();
1800
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
1801
 
1802
		helper.setSubject(subject);
1803
		helper.setText(messageText, true);
1804
		helper.setTo(email);
1805
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "ProfitMandi Admin");
1806
		helper.setFrom(senderAddress);
1807
		mailSender.send(message);
1808
 
1809
	}
1810
 
1811
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1812
		StringBuilder sb = new StringBuilder();
1813
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
1814
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
1815
		sb.append("<tbody>\n" + "	    				<tr>\n"
1816
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
1817
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
1818
				+ "	    				</tr>");
1819
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1820
 
1821
			sb.append("<tr>");
1822
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
1823
 
1824
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
1825
 
1826
			sb.append("</tr>");
1827
 
1828
		}
1829
 
1830
		sb.append("</tbody></table></body></html>");
1831
 
1832
		return sb.toString();
1833
	}
1834
 
1835
}