Subversion Repositories SmartDukaan

Rev

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

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