Subversion Repositories SmartDukaan

Rev

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