Subversion Repositories SmartDukaan

Rev

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