Subversion Repositories SmartDukaan

Rev

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