Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23724 amit.gupta 1
package com.smartdukaan.cron.scheduled;
23723 amit.gupta 2
 
24121 govind 3
import java.io.IOException;
24807 amit.gupta 4
import java.io.Serializable;
23739 amit.gupta 5
import java.sql.Timestamp;
23724 amit.gupta 6
import java.time.LocalDate;
7
import java.time.LocalDateTime;
24256 amit.gupta 8
import java.time.LocalTime;
24653 govind 9
import java.time.format.DateTimeFormatter;
23724 amit.gupta 10
import java.time.temporal.ChronoUnit;
11
import java.util.ArrayList;
12
import java.util.Arrays;
24627 amit.gupta 13
import java.util.Collections;
23723 amit.gupta 14
import java.util.HashMap;
24241 amit.gupta 15
import java.util.HashSet;
23724 amit.gupta 16
import java.util.List;
23723 amit.gupta 17
import java.util.Map;
24242 amit.gupta 18
import java.util.Optional;
24542 amit.gupta 19
import java.util.Set;
23724 amit.gupta 20
import java.util.stream.Collectors;
23723 amit.gupta 21
 
24121 govind 22
import javax.mail.MessagingException;
23
import javax.mail.internet.InternetAddress;
24
import javax.mail.internet.MimeMessage;
25
 
23929 amit.gupta 26
import org.apache.commons.io.output.ByteArrayOutputStream;
25598 amit.gupta 27
import org.apache.commons.lang.StringUtils;
25300 tejbeer 28
import org.apache.http.client.methods.CloseableHttpResponse;
29
import org.apache.http.client.methods.HttpPost;
30
import org.apache.http.entity.StringEntity;
31
import org.apache.http.impl.client.CloseableHttpClient;
32
import org.apache.http.impl.client.HttpClients;
23755 amit.gupta 33
import org.apache.logging.log4j.LogManager;
34
import org.apache.logging.log4j.Logger;
25300 tejbeer 35
import org.json.JSONObject;
23723 amit.gupta 36
import org.springframework.beans.factory.annotation.Autowired;
23933 amit.gupta 37
import org.springframework.beans.factory.annotation.Qualifier;
23724 amit.gupta 38
import org.springframework.beans.factory.annotation.Value;
23929 amit.gupta 39
import org.springframework.core.io.ByteArrayResource;
24692 amit.gupta 40
import org.springframework.core.io.InputStreamSource;
23929 amit.gupta 41
import org.springframework.mail.javamail.JavaMailSender;
24121 govind 42
import org.springframework.mail.javamail.MimeMessageHelper;
23723 amit.gupta 43
import org.springframework.stereotype.Component;
23724 amit.gupta 44
import org.springframework.transaction.annotation.Transactional;
23723 amit.gupta 45
 
24542 amit.gupta 46
import com.google.common.collect.Lists;
25300 tejbeer 47
import com.google.gson.Gson;
48
import com.google.gson.GsonBuilder;
25721 tejbeer 49
import com.spice.profitmandi.common.enumuration.MessageType;
23724 amit.gupta 50
import com.spice.profitmandi.common.enumuration.RechargeStatus;
24681 amit.gupta 51
import com.spice.profitmandi.common.enumuration.ReporticoProject;
24121 govind 52
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23929 amit.gupta 53
import com.spice.profitmandi.common.model.CustomRetailer;
25721 tejbeer 54
import com.spice.profitmandi.common.model.FocusedModelShortageModel;
24542 amit.gupta 55
import com.spice.profitmandi.common.model.GstRate;
25590 amit.gupta 56
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23724 amit.gupta 57
import com.spice.profitmandi.common.model.RechargeCredential;
25821 amit.gupta 58
import com.spice.profitmandi.common.model.SendNotificationModel;
24681 amit.gupta 59
import com.spice.profitmandi.common.services.ReporticoService;
24002 amit.gupta 60
import com.spice.profitmandi.common.util.FileUtil;
23929 amit.gupta 61
import com.spice.profitmandi.common.util.FormattingUtils;
62
import com.spice.profitmandi.common.util.Utils;
24592 amit.gupta 63
import com.spice.profitmandi.common.util.Utils.Attachment;
25300 tejbeer 64
import com.spice.profitmandi.dao.Interface.Campaign;
65
import com.spice.profitmandi.dao.convertor.LocalDateTimeJsonConverter;
25590 amit.gupta 66
import com.spice.profitmandi.dao.entity.auth.AuthUser;
25800 tejbeer 67
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
25609 amit.gupta 68
import com.spice.profitmandi.dao.entity.catalog.Item;
24590 amit.gupta 69
import com.spice.profitmandi.dao.entity.catalog.Scheme;
25590 amit.gupta 70
import com.spice.profitmandi.dao.entity.cs.Position;
23724 amit.gupta 71
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
25300 tejbeer 72
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
73
import com.spice.profitmandi.dao.entity.dtr.PushNotifications;
23724 amit.gupta 74
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
75
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
76
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
25721 tejbeer 77
import com.spice.profitmandi.dao.entity.dtr.UserCampaign;
24542 amit.gupta 78
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
24590 amit.gupta 79
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
23724 amit.gupta 80
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
24542 amit.gupta 81
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23929 amit.gupta 82
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24249 amit.gupta 83
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24277 amit.gupta 84
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
23724 amit.gupta 85
import com.spice.profitmandi.dao.entity.fofo.Purchase;
24242 amit.gupta 86
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
24241 amit.gupta 87
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
24431 amit.gupta 88
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
25609 amit.gupta 89
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
24587 amit.gupta 90
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
24580 amit.gupta 91
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
24542 amit.gupta 92
import com.spice.profitmandi.dao.entity.user.Address;
25300 tejbeer 93
import com.spice.profitmandi.dao.entity.user.Device;
24250 amit.gupta 94
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25598 amit.gupta 95
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
24242 amit.gupta 96
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
25609 amit.gupta 97
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
25300 tejbeer 98
import com.spice.profitmandi.dao.model.SimpleCampaign;
99
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
25590 amit.gupta 100
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25300 tejbeer 101
import com.spice.profitmandi.dao.repository.catalog.DeviceRepository;
25721 tejbeer 102
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
24249 amit.gupta 103
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
24241 amit.gupta 104
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
25590 amit.gupta 105
import com.spice.profitmandi.dao.repository.cs.CsService;
106
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
23724 amit.gupta 107
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
23929 amit.gupta 108
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25837 amit.gupta 109
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
24653 govind 110
import com.spice.profitmandi.dao.repository.dtr.Mongo;
25300 tejbeer 111
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
112
import com.spice.profitmandi.dao.repository.dtr.PushNotificationRepository;
23724 amit.gupta 113
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
114
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
115
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
24542 amit.gupta 116
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
24669 govind 117
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
25721 tejbeer 118
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
119
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24542 amit.gupta 120
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
24590 amit.gupta 121
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
24542 amit.gupta 122
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
23724 amit.gupta 123
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
24249 amit.gupta 124
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24277 amit.gupta 125
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
24174 govind 126
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
25503 amit.gupta 127
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
23724 amit.gupta 128
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
24242 amit.gupta 129
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
24241 amit.gupta 130
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
23929 amit.gupta 131
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
25609 amit.gupta 132
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
24431 amit.gupta 133
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
24580 amit.gupta 134
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
24587 amit.gupta 135
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
24542 amit.gupta 136
import com.spice.profitmandi.dao.repository.user.AddressRepository;
25721 tejbeer 137
import com.spice.profitmandi.dao.repository.user.UserRepository;
24337 amit.gupta 138
import com.spice.profitmandi.service.PartnerInvestmentService;
25694 amit.gupta 139
import com.spice.profitmandi.service.integrations.toffee.ToffeeService;
23929 amit.gupta 140
import com.spice.profitmandi.service.inventory.InventoryService;
25335 amit.gupta 141
import com.spice.profitmandi.service.order.OrderService;
24431 amit.gupta 142
import com.spice.profitmandi.service.pricing.PriceDropService;
23724 amit.gupta 143
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
144
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
145
import com.spice.profitmandi.service.scheme.SchemeService;
24121 govind 146
import com.spice.profitmandi.service.slab.TargetSlabService;
23929 amit.gupta 147
import com.spice.profitmandi.service.transaction.TransactionService;
148
import com.spice.profitmandi.service.user.RetailerService;
23739 amit.gupta 149
import com.spice.profitmandi.service.wallet.WalletService;
23723 amit.gupta 150
 
25721 tejbeer 151
import in.shop2020.model.v1.order.OrderStatus;
25778 amit.gupta 152
import in.shop2020.model.v1.order.WalletReferenceType;;
23739 amit.gupta 153
 
23723 amit.gupta 154
@Component
23724 amit.gupta 155
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 156
public class ScheduledTasks {
157
 
23724 amit.gupta 158
	@Value("${oxigen.recharge.transaction.url}")
159
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 160
 
23724 amit.gupta 161
	@Value("${oxigen.recharge.enquiry.url}")
162
	private String oxigenRechargeEnquiryUrl;
24533 govind 163
 
24431 amit.gupta 164
	@Autowired
25503 amit.gupta 165
	private PartnerTypeChangeService partnerTypeChangeService;
25598 amit.gupta 166
 
25590 amit.gupta 167
	@Autowired
168
	private AuthRepository authRepository;
25503 amit.gupta 169
 
170
	@Autowired
24431 amit.gupta 171
	private PriceDropService priceDropService;
25598 amit.gupta 172
 
25590 amit.gupta 173
	@Autowired
174
	private CsService csService;
25846 amit.gupta 175
 
25837 amit.gupta 176
	@Autowired
177
	private InsurancePolicyRepository insurancePolicyRepository;
23723 amit.gupta 178
 
25694 amit.gupta 179
	@Autowired
180
	private ToffeeService toffeeService;
181
 
23724 amit.gupta 182
	@Value("${oxigen.recharge.auth.key}")
183
	private String oxigenRechargeAuthKey;
184
 
185
	@Value("${oxigen.recharge.validation.url}")
186
	private String oxigenRechargeValidationUrl;
187
 
188
	@Value("${oxigen.recharge.validation.auth.key}")
189
	private String oxigenRechargeValidationAuthKey;
190
 
191
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
192
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
193
 
194
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
195
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
196
 
197
	@Value("${think.walnut.digital.recharge.enquiry.url}")
198
	private String thinkWalnutDigitalRechargeEnquiryUrl;
199
 
200
	@Value("${think.walnut.digital.recharge.balance.url}")
201
	private String thinkWalnutDigitalRechargeBalanceUrl;
202
 
203
	@Value("${think.walnut.digital.recharge.username}")
204
	private String thinkWalnutDigitalRechargeUserName;
205
 
206
	@Value("${think.walnut.digital.recharge.password}")
207
	private String thinkWalnutDigitalRechargePassword;
208
 
209
	@Value("${think.walnut.digital.recharge.auth.key}")
210
	private String thinkWalnutDigitalRechargeAuthKey;
211
 
23723 amit.gupta 212
	@Autowired
23724 amit.gupta 213
	private PurchaseRepository purchaseRepository;
214
 
215
	@Autowired
25609 amit.gupta 216
	private PriceDropIMEIRepository priceDropIMEIRepository;
217
 
218
	@Autowired
219
	PriceDropRepository priceDropRepository;
220
 
221
	@Autowired
23724 amit.gupta 222
	private SchemeService schemeService;
24683 amit.gupta 223
 
25609 amit.gupta 224
	private static final String[] STOCK_AGEING_MAIL_LIST = new String[] { "amod.sen@smartdukaan.com",
225
			"adeel.yazdani@smartdukaan.com", "manoj.singh@smartdukaan.com", "kamini.sharma@smartdukaan.com",
226
			"mohinder.mutreja@smartdukaan.com", "	ankit.bhatia@smartdukaan.com", "tarun.verma@smartdukaan.com",
25821 amit.gupta 227
			"chaitnaya.vats@smartdukaan.com", "kuldeep.kumar@smartdukaan.com", "prakash.rai@smartdukaan.com" };
25609 amit.gupta 228
 
229
	private static final String[] ITEMWISE_PENDING_INDENT_MAIL_LIST = new String[] { "kamini.sharma@smartdukaan.com",
25821 amit.gupta 230
			"prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com", "chaitnaya.vats@smartdukaan.com",
231
			"kuldeep.kumar@smartdukaan.com" };
25609 amit.gupta 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
 
25837 amit.gupta 516
		List<List<?>> 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 List<String> getL2() {
661
			return l2;
662
		}
663
 
664
	}
665
 
24271 amit.gupta 666
	public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
25312 amit.gupta 667
		if (sendTo == null) {
25821 amit.gupta 668
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
669
					"prakash.rai@smartdukaan.com", "amit.gupta@shop2020.in", "amod.sen@smartdukaan.com");
25312 amit.gupta 670
		}
24277 amit.gupta 671
		LocalDate yesterDay = LocalDate.now().minusDays(1);
25267 amit.gupta 672
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
23929 amit.gupta 673
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
674
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25351 tejbeer 675
 
25598 amit.gupta 676
		List<String> headers = Arrays.asList("Code", "Firm Name", "Store Name", "State Manager", "Teritory/Team Lead",
677
				"Wallet Amount", "In Stock Amount", "Return In Transit Stock", "Unbilled Amount", "Grn Pending Amount",
678
				"Min Investment", "Investment Amount", "Investment Short", "Unbilled Qty");
25837 amit.gupta 679
		List<List<?>> rows = new ArrayList<>();
680
		Map<Integer, List<? extends Serializable>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 681
 
25837 amit.gupta 682
		Map<Integer, List<Serializable>> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25598 amit.gupta 683
 
24002 amit.gupta 684
		for (FofoStore fofoStore : fofoStores) {
25598 amit.gupta 685
			PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoStore.getId(),
686
					1);
687
			partnerDailyInvestment.setDate(yesterDay);
688
			try {
689
				partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
690
			} catch (Exception e) {
691
				// ignore the exceptions during persist
692
			}
693
 
24002 amit.gupta 694
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
25837 amit.gupta 695
			if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
24002 amit.gupta 696
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
697
				continue;
698
			}
25837 amit.gupta 699
			List<Serializable> row = partnerIdSalesHeaderMap.get(fofoStore.getId());
700
			partnerRowsMap.put(fofoStore.getId(), row);
24002 amit.gupta 701
			rows.add(row);
702
 
23929 amit.gupta 703
		}
25312 amit.gupta 704
 
24271 amit.gupta 705
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25598 amit.gupta 706
 
25837 amit.gupta 707
		for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
708
			List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x))
709
					.filter(x -> x != null).collect(Collectors.toList());
25312 amit.gupta 710
			ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
25609 amit.gupta 711
			String[] sendToArray = new String[] { storeGuyEntry.getKey() };
712
			Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
25604 amit.gupta 713
					fileName, new ByteArrayResource(baos.toByteArray()));
25341 amit.gupta 714
		}
25312 amit.gupta 715
 
25604 amit.gupta 716
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
717
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
25609 amit.gupta 718
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
719
				fileName, new ByteArrayResource(baos.toByteArray()));
24271 amit.gupta 720
 
23929 amit.gupta 721
	}
24177 govind 722
 
25837 amit.gupta 723
	private Map<Integer, List<Serializable>> getPartnerIdSalesHeaders() {
25598 amit.gupta 724
		Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
725
 
726
		List<Position> positions = positionRepository
727
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
728
		Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream()
729
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
730
		Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
731
		for (Position position : positions) {
732
			List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
25609 amit.gupta 733
			if (crList == null)
734
				continue;
25598 amit.gupta 735
			for (CustomRetailer cr : crList) {
736
				if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
737
					partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
738
				}
739
				SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
740
				AuthUser authUser = authUsersMap.get(position.getAuthUserId());
741
				String name = authUser.getFirstName() + " " + authUser.getLastName();
742
				if (position.getEscalationType().equals(EscalationType.L1)) {
743
					saleRoles.getL1().add(name);
744
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
745
					saleRoles.getL2().add(name);
746
				}
747
			}
748
		}
25837 amit.gupta 749
 
750
		Set<CustomRetailer> allCrList = new HashSet<>();
751
		for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
752
			allCrList.addAll(cr);
753
		}
754
 
755
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
756
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
757
 
758
		Map<Integer, List<Serializable>> partnerIdSalesHeadersMap = new HashMap<>();
759
 
760
		for (CustomRetailer cr : allCrList) {
761
			FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
762
			String code = fofoStore.getCode();
763
			String storeName = "SmartDukaan-" + fofoStore.getCode().replaceAll("[a-zA-Z]", "");
764
			String businessName = cr.getBusinessName();
765
			try {
766
				String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
767
				String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
768
				List<Serializable> row = new ArrayList<>(
769
						Arrays.asList(code, businessName, storeName, stateManager, territoryManager));
770
				partnerIdSalesHeadersMap.put(cr.getPartnerId(), row);
771
 
772
			} catch (Exception e) {
773
				LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
774
			}
775
		}
776
		return partnerIdSalesHeadersMap;
777
 
25598 amit.gupta 778
	}
779
 
24271 amit.gupta 780
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 781
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 782
	}
783
 
25312 amit.gupta 784
	public void sendTargetVsSalesReport(List<String> sendTo) throws Exception {
24177 govind 785
 
25312 amit.gupta 786
		if (sendTo == null) {
25827 amit.gupta 787
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
788
					"amit.gupta@shop2020.in", "amod.sen@smartdukaan.com", "prakash.rai@smartdukaan.com");
25312 amit.gupta 789
		}
25837 amit.gupta 790
		Map<Integer, List<Serializable>> partnerSalesTargetRowsMap = targetService.getDailySaleReportVsTarget();
25315 amit.gupta 791
 
25837 amit.gupta 792
		Map<Integer, List<Serializable>> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
24177 govind 793
 
25837 amit.gupta 794
		List<String> headers = Arrays.asList("Code", "Firm Name", "Store Name", "State Manager", "Teritory Manager",
795
				"Current Category", "Target Value", "Target Achieved", "Achived Percentage", "Remaining Target",
796
				"Today's Target", "Today's achievement");
25609 amit.gupta 797
 
25837 amit.gupta 798
		List<List<?>> rows = new ArrayList<>();
799
		Map<Integer, List<? extends Serializable>> partnerRowMap = new HashMap<>();
800
		for (Map.Entry<Integer, List<Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap.entrySet()) {
801
			List<Serializable> row = partnerIdSalesHeadersMap.get(partnerSalesTargetRowEntry.getKey());
802
			if (row == null) {
803
				LOGGER.warn("Could not find headers for partner ID - {}", partnerSalesTargetRowEntry.getKey());
25315 amit.gupta 804
			}
25837 amit.gupta 805
			row.addAll(partnerSalesTargetRowEntry.getValue());
806
			partnerRowMap.put(partnerSalesTargetRowEntry.getKey(), row);
807
			rows.add(row);
24177 govind 808
		}
25503 amit.gupta 809
 
25318 amit.gupta 810
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25827 amit.gupta 811
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
812
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
813
			if (storeGuyEntry.getValue().size() == 0)
814
				continue;
25837 amit.gupta 815
			List<List<?>> storeGuyRows = storeGuyEntry.getValue().stream().map(x -> partnerRowMap.get(x))
816
					.collect(Collectors.toList());
25827 amit.gupta 817
			ByteArrayOutputStream authUserStream = FileUtil.getCSVByteStream(headers, storeGuyRows);
818
			Attachment attache = new Attachment(fileName, new ByteArrayResource(authUserStream.toByteArray()));
819
			System.out.println(storeGuyEntry.getValue());
820
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
821
					"Franchise Stock Report", "PFA", attache);
822
		}
24240 amit.gupta 823
 
25312 amit.gupta 824
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
825
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
826
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
827
				new ByteArrayResource(baos.toByteArray()));
24174 govind 828
	}
24683 amit.gupta 829
 
24697 amit.gupta 830
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 831
 
832
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
833
				"itemstockageing.xml");
24708 amit.gupta 834
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 835
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 836
		Attachment attachment = new Attachment(
25445 amit.gupta 837
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 838
		Attachment attachment1 = new Attachment(
25445 amit.gupta 839
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 840
 
25609 amit.gupta 841
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
842
				attachment);
843
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
844
				"Itemwise Pending indent", "PFA", attachment1);
845
 
25598 amit.gupta 846
		// Reports to be sent to mapped partners
25597 amit.gupta 847
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 848
 
849
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 850
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 851
			if (storeGuyEntry.getValue().size() == 0)
852
				continue;
25418 amit.gupta 853
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
854
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
855
					"focostockreport.xml", params);
856
			Attachment attache = new Attachment(
25609 amit.gupta 857
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 858
			System.out.println(storeGuyEntry.getValue());
25609 amit.gupta 859
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
860
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 861
		}
25503 amit.gupta 862
 
24681 amit.gupta 863
	}
24533 govind 864
 
24697 amit.gupta 865
	public void sendAgeingReport() throws Exception {
25807 amit.gupta 866
		sendAgeingReport("kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com",
25609 amit.gupta 867
				"chaitnaya.vats@smartdukaan.com");
24697 amit.gupta 868
	}
869
 
24533 govind 870
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 871
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 872
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 873
			priceDropService.priceDropStatus(priceDrop.getId());
874
		}
875
	}
23929 amit.gupta 876
 
24542 amit.gupta 877
	public void walletmismatch() throws Exception {
878
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 879
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 880
		System.out.println(pdis.size());
24542 amit.gupta 881
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 882
			int fofoId = pdi.getFofoId();
24542 amit.gupta 883
			for (PartnerDailyInvestment investment : Lists
884
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 885
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 886
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 887
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 888
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
889
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 890
 
24542 amit.gupta 891
			}
24549 amit.gupta 892
		}
24542 amit.gupta 893
 
894
	}
895
 
896
	public void gst() throws Exception {
24548 amit.gupta 897
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
898
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
899
		for (FofoOrder fofoOrder : fofoOrders) {
900
			int retailerAddressId = retailerRegisteredAddressRepository
901
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 902
 
903
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
904
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
905
			Integer stateId = null;
906
			if (customerAddress.getState().equals(retailerAddress.getState())) {
907
				try {
908
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
909
				} catch (Exception e) {
910
					LOGGER.error("Unable to get state rates");
911
				}
912
			}
913
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
914
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 915
 
916
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
917
			Set<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
24542 amit.gupta 918
			if (stateId != null) {
919
				itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemIds), stateId);
920
			} else {
921
				itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemIds));
922
			}
923
 
24548 amit.gupta 924
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 925
				if (stateId == null) {
926
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
927
				} else {
928
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
929
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
930
				}
931
				fofoOrderItemRepository.persist(foi);
932
			}
933
		}
24548 amit.gupta 934
 
24542 amit.gupta 935
	}
936
 
24580 amit.gupta 937
	public void schemewalletmismatch() {
938
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 939
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 940
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 941
			// reconcileOrders(dateTime);
942
			// reconcileRecharges(dateTime);
24580 amit.gupta 943
			dateToReconcile = dateToReconcile.plusDays(1);
944
		}
945
	}
946
 
947
	private void reconcileSchemes(LocalDate date) {
948
		LocalDateTime startDate = date.atStartOfDay();
949
		LocalDateTime endDate = startDate.plusDays(1);
950
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
951
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 952
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
953
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 954
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 955
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
956
				WalletReferenceType.SCHEME_OUT);
957
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
958
				walletReferenceTypes);
959
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
960
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 961
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 962
 
963
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
964
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
965
 
966
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
967
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
968
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
969
 
970
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
971
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
972
 
973
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
974
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
975
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
976
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
977
 
978
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
979
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeMap.entrySet()) {
980
			}
981
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
982
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
983
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
984
				} else {
985
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
986
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
987
				}
988
			}
24590 amit.gupta 989
			Map<Integer, Integer> userWalletMap = userWalletRepository
990
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
991
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
992
 
24587 amit.gupta 993
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
994
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
995
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
996
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
997
				if (diff > 5) {
998
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
999
				}
1000
			}
24580 amit.gupta 1001
		}
24587 amit.gupta 1002
 
24580 amit.gupta 1003
	}
24590 amit.gupta 1004
 
24592 amit.gupta 1005
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1006
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1007
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1008
 
24592 amit.gupta 1009
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1010
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1011
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1012
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1013
		Set<String> serialNumbersConsidered = new HashSet<>();
1014
 
25096 amit.gupta 1015
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1016
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1017
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1018
 
24683 amit.gupta 1019
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1020
		purchases.stream().forEach(purchase -> {
1021
			float amountToRollback = 0;
1022
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1023
					+ purchase.getPurchaseReference();
1024
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1025
					.stream().filter(ii -> ii.getSerialNumber() != null)
1026
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1027
			if (inventorySerialNumberMap.size() > 0) {
1028
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1029
					String serialNumber = inventorySerialNumberEntry.getValue();
1030
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1031
					if (serialNumbersConsidered.contains(serialNumber)) {
1032
						// This will rollback scheme for differenct orders for same serial
1033
						List<SchemeInOut> sios = schemeInOutRepository
1034
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1035
								.filter(x -> x.getRolledBackTimestamp() == null
1036
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1037
								.collect(Collectors.toList());
1038
						Collections.reverse(sios);
1039
						for (SchemeInOut sio : sios) {
1040
							sio.setRolledBackTimestamp(LocalDateTime.now());
1041
							amountToRollback += sio.getAmount();
1042
							// sio.setSchemeType(SchemeType.OUT);
1043
							sio.setSerialNumber(serialNumber);
1044
							rolledbackSios.add(sio);
1045
						}
1046
						description = description.concat(" " + serialNumber + " ");
1047
					} else {
1048
						serialNumbersConsidered.add(serialNumber);
1049
						List<Integer> schemesConsidered = new ArrayList<>();
1050
						List<SchemeInOut> sios = schemeInOutRepository
1051
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1052
								.filter(x -> x.getRolledBackTimestamp() == null
1053
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1054
								.collect(Collectors.toList());
1055
						Collections.reverse(sios);
1056
						for (SchemeInOut sio : sios) {
1057
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1058
								schemesConsidered.add(sio.getSchemeId());
1059
								continue;
1060
							}
1061
							sio.setRolledBackTimestamp(LocalDateTime.now());
1062
							amountToRollback += sio.getAmount();
1063
							// sio.setSchemeType(SchemeType.OUT);
1064
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1065
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1066
							sio.setReference(purchase.getId());
24635 amit.gupta 1067
							rolledbackSios.add(sio);
1068
						}
1069
					}
1070
 
1071
				}
1072
			}
1073
			if (amountToRollback > 0) {
24683 amit.gupta 1074
				// Address address =
1075
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1076
				UserWalletHistory uwh = new UserWalletHistory();
1077
				uwh.setAmount(Math.round(amountToRollback));
1078
				uwh.setDescription(description);
1079
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1080
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1081
				uwh.setReference(purchase.getId());
1082
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1083
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1084
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1085
				userWalletHistory.add(uwh);
1086
			}
1087
		});
1088
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1089
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1090
						"Timestamp"),
1091
				userWalletHistory.stream()
1092
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1093
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1094
						.collect(Collectors.toList()));
1095
 
1096
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1097
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1098
						"Created", "Rolledback"),
24635 amit.gupta 1099
				rolledbackSios.stream()
24681 amit.gupta 1100
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1101
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1102
						.collect(Collectors.toList()));
1103
 
25043 amit.gupta 1104
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1105
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1106
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1107
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1108
 
25096 amit.gupta 1109
		throw new Exception();
24635 amit.gupta 1110
 
1111
	}
1112
 
1113
	public void dryRunOutSchemeReco() throws Exception {
1114
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1115
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1116
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1117
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1118
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1119
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1120
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1121
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1122
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1123
		// Collections.reverse(allOrders);
1124
		// List<FofoOrder> allOrders =
24653 govind 1125
		// List<FofoOrder> allOrders =
24631 amit.gupta 1126
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1127
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1128
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1129
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1130
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1131
			float amountToRollback = 0;
24590 amit.gupta 1132
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1133
			orderItems.forEach(x -> {
24606 amit.gupta 1134
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1135
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1136
			});
24606 amit.gupta 1137
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1138
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1139
					String serialNumber = inventorySerialNumberEntry.getValue();
1140
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1141
					if (serialNumbersConsidered.contains(serialNumber)) {
1142
						// This will rollback scheme for differenct orders for same serial
1143
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1144
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1145
								.filter(x -> x.getRolledBackTimestamp() == null
1146
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1147
								.collect(Collectors.toList());
1148
						Collections.reverse(sios);
1149
						for (SchemeInOut sio : sios) {
1150
							sio.setRolledBackTimestamp(LocalDateTime.now());
1151
							amountToRollback += sio.getAmount();
1152
							// sio.setSchemeType(SchemeType.OUT);
1153
							sio.setSerialNumber(serialNumber);
1154
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1155
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1156
							rolledbackSios.add(sio);
24623 amit.gupta 1157
						}
24635 amit.gupta 1158
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1159
					} else {
1160
						serialNumbersConsidered.add(serialNumber);
1161
						List<Integer> schemesConsidered = new ArrayList<>();
1162
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1163
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1164
								.filter(x -> x.getRolledBackTimestamp() == null
1165
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1166
								.collect(Collectors.toList());
1167
						Collections.reverse(sios);
1168
						for (SchemeInOut sio : sios) {
1169
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1170
								schemesConsidered.add(sio.getSchemeId());
1171
								continue;
1172
							}
1173
							sio.setRolledBackTimestamp(LocalDateTime.now());
1174
							amountToRollback += sio.getAmount();
1175
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1176
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1177
							sio.setSerialNumber(serialNumber);
1178
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1179
							rolledbackSios.add(sio);
1180
						}
24615 amit.gupta 1181
					}
24631 amit.gupta 1182
 
24604 amit.gupta 1183
				}
24590 amit.gupta 1184
			}
24631 amit.gupta 1185
			if (amountToRollback > 0) {
1186
				UserWalletHistory uwh = new UserWalletHistory();
1187
				uwh.setAmount(Math.round(amountToRollback));
1188
				uwh.setDescription(description);
1189
				uwh.setTimestamp(LocalDateTime.now());
1190
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1191
				uwh.setReference(fofoOrder.getId());
1192
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1193
				uwh.setFofoId(fofoOrder.getFofoId());
1194
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1195
				userWalletHistory.add(uwh);
1196
			}
24590 amit.gupta 1197
		});
24598 amit.gupta 1198
 
24592 amit.gupta 1199
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1200
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1201
						"Timestamp"),
1202
				userWalletHistory.stream()
1203
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1204
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1205
						.collect(Collectors.toList()));
1206
 
1207
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1208
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1209
						"Rolledback"),
1210
				rolledbackSios.stream()
1211
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1212
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1213
						.collect(Collectors.toList()));
1214
 
25043 amit.gupta 1215
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1216
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1217
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1218
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1219
 
25267 amit.gupta 1220
		throw new Exception();
24590 amit.gupta 1221
	}
24615 amit.gupta 1222
 
24611 amit.gupta 1223
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1224
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1225
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1226
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1227
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1228
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1229
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1230
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1231
		references.stream().forEach(reference -> {
1232
			FofoOrder fofoOrder = null;
1233
			try {
1234
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1235
			} catch (Exception e) {
1236
 
24611 amit.gupta 1237
			}
1238
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1239
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1240
			float amountToRollback = 0;
1241
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1242
			orderItems.forEach(x -> {
1243
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1244
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1245
			});
1246
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1247
				List<SchemeInOut> sios = schemeInOutRepository
1248
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1249
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1250
						.collect(Collectors.toList());
1251
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1252
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1253
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1254
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1255
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1256
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1257
					if (outList.size() > 1) {
1258
 
24611 amit.gupta 1259
					}
1260
				}
1261
				uwh.setAmount(Math.round(amountToRollback));
1262
				uwh.setDescription(description);
1263
				uwh.setTimestamp(LocalDateTime.now());
1264
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1265
				uwh.setReference(fofoOrder.getId());
1266
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1267
				uwh.setFofoId(fofoOrder.getFofoId());
1268
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1269
				userWalletHistory.add(uwh);
1270
			}
1271
		});
24615 amit.gupta 1272
 
24611 amit.gupta 1273
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1274
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1275
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1276
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1277
						.collect(Collectors.toList()));
1278
 
24611 amit.gupta 1279
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1280
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1281
						"Rolledback"),
1282
				rolledbackSios.stream()
24615 amit.gupta 1283
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1284
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1285
						.collect(Collectors.toList()));
1286
 
24623 amit.gupta 1287
		Utils.sendMailWithAttachments(googleMailSender,
1288
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1289
				"Partner Excess Amount", "PFA",
1290
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1291
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1292
 
24628 amit.gupta 1293
		throw new Exception();
24615 amit.gupta 1294
 
24611 amit.gupta 1295
	}
24615 amit.gupta 1296
 
25837 amit.gupta 1297
	public void sendDailySalesNotificationToPartner(Integer fofoIdInt)
24653 govind 1298
			throws ProfitMandiBusinessException, MessagingException, IOException {
1299
		LocalDateTime now = LocalDateTime.now();
25837 amit.gupta 1300
		LocalDateTime from = now.with(LocalTime.MIN);
24653 govind 1301
		Map<Integer, Double> salesByFofoIdMap = new HashMap<>();
24855 amit.gupta 1302
		List<Integer> fofoIds = null;
25043 amit.gupta 1303
		if (fofoIdInt == null) {
1304
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1305
					.collect(Collectors.toList());
24856 amit.gupta 1306
		} else {
24855 amit.gupta 1307
			fofoIds = Arrays.asList(fofoIdInt);
1308
		}
24683 amit.gupta 1309
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h a");
1310
 
1311
		Map<Integer, Float> dailyTarget = new HashMap<>();
24653 govind 1312
		for (Integer fofoId : fofoIds) {
25837 amit.gupta 1313
			double sale = fofoOrderRepository.selectTotalSaleSumByFofoIdBetweenDate(fofoId, from, now);
1314
 
25821 amit.gupta 1315
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1316
			sendNotificationModel.setCampaignName("Sales update alert");
25837 amit.gupta 1317
			sendNotificationModel.setMessage(String.format(
1318
					"Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.", sale, now.format(timeFormatter)));
25821 amit.gupta 1319
			sendNotificationModel.setType("url");
1320
			sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
1321
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1322
			sendNotificationModel.setMessageType(MessageType.notification);
24653 govind 1323
			salesByFofoIdMap.put(fofoId, sale);
1324
			LOGGER.info(sale);
1325
		}
25846 amit.gupta 1326
		Map<Integer, Float> parternPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1327
				null);
25837 amit.gupta 1328
		Map<Integer, Float> parternPolicyQtyMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now, null);
24683 amit.gupta 1329
		String saleReport = this.getDailySalesReportByPartnerId(salesByFofoIdMap, dailyTarget);
24653 govind 1330
		LOGGER.info(saleReport);
25837 amit.gupta 1331
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com",
25846 amit.gupta 1332
				"chaitnaya.vats@smartdukaan.com" };
25837 amit.gupta 1333
 
25833 amit.gupta 1334
		String subject = String.format("Sale till %s", now.format(timeFormatter));
25821 amit.gupta 1335
		this.sendMailOfHtmlFomat("amit.gupta@shop2020.in", saleReport, cc, subject);
24653 govind 1336
	}
1337
 
25837 amit.gupta 1338
	private String getDailySalesReportByPartnerId(Map<Integer, Double> salesByFofoIdMap,
1339
			Map<Integer, Float> dailyTarget) throws ProfitMandiBusinessException {
24653 govind 1340
		StringBuilder sb = new StringBuilder();
25832 amit.gupta 1341
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 1342
		sb.append("<tbody>\n" + "	    				<tr>\n"
1343
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner</th>\n"
1344
				+ "	    					<th style='border:1px solid black;padding: 5px'>Daily Target</th>\n"
1345
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
1346
				+ "	    				</tr>");
1347
		for (Integer fofoId : salesByFofoIdMap.keySet()) {
25043 amit.gupta 1348
			try {
1349
				String PartnerName = retailerService.getFofoRetailer(fofoId).getBusinessName();
1350
				sb.append("<tr>");
1351
				sb.append("<td style='border:1px solid black;padding: 5px'>" + PartnerName + "</td>");
1352
				if (dailyTarget != null && dailyTarget.get(fofoId) != null) {
1353
					sb.append("<td style='border:1px solid black;padding: 5px'>" + dailyTarget.get(fofoId) + "</td>");
1354
				} else {
1355
					sb.append("<td style='border:1px solid black;padding: 5px'>" + 0.0 + "</td>");
1356
				}
1357
				sb.append("<td style='border:1px solid black;padding: 5px'>" + salesByFofoIdMap.get(fofoId) + "</td>");
24653 govind 1358
 
25043 amit.gupta 1359
				sb.append("</tr>");
1360
			} catch (Exception e) {
24842 govind 1361
				e.printStackTrace();
1362
			}
25043 amit.gupta 1363
 
24653 govind 1364
		}
24683 amit.gupta 1365
 
24653 govind 1366
		sb.append("</tbody></table></body></html>");
1367
		return sb.toString();
1368
	}
24841 govind 1369
 
1370
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1371
			throws MessagingException, ProfitMandiBusinessException, IOException {
1372
		MimeMessage message = mailSender.createMimeMessage();
1373
		MimeMessageHelper helper = new MimeMessageHelper(message);
1374
		helper.setSubject(subject);
1375
		helper.setText(body, true);
1376
		helper.setTo(email);
1377
		if (cc != null) {
1378
			helper.setCc(cc);
1379
		}
1380
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1381
		helper.setFrom(senderAddress);
1382
		mailSender.send(message);
1383
	}
25300 tejbeer 1384
 
25351 tejbeer 1385
	public void sendNotification() throws Exception {
25300 tejbeer 1386
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1387
		if (!pushNotifications.isEmpty()) {
1388
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1389
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1390
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1391
						.selectById(pushNotification.getNotificationCampaignid());
1392
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1393
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1394
 
1395
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1396
						SimpleCampaignParams.class);
1397
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1398
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1399
				JSONObject json = new JSONObject();
25351 tejbeer 1400
				json.put("to", device.getFcmId());
25300 tejbeer 1401
				JSONObject jsonObj = new JSONObject();
1402
				jsonObj.put("message", campaign.getMessage());
1403
				jsonObj.put("title", campaign.getTitle());
1404
				jsonObj.put("type", campaign.getType());
1405
				jsonObj.put("url", result_url);
1406
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1407
				jsonObj.put("image", campaign.getImageUrl());
1408
				jsonObj.put("largeIcon", "large_icon");
1409
				jsonObj.put("smallIcon", "small_icon");
1410
				jsonObj.put("vibrate", 1);
1411
				jsonObj.put("pid", pushNotification.getId());
1412
				jsonObj.put("sound", 1);
1413
				jsonObj.put("priority", "high");
1414
				json.put("data", jsonObj);
25351 tejbeer 1415
				try {
1416
					CloseableHttpClient client = HttpClients.createDefault();
1417
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1418
 
25351 tejbeer 1419
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1420
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1421
					StringEntity entity = new StringEntity(json.toString());
1422
					httpPost.setEntity(entity);
1423
					CloseableHttpResponse response = client.execute(httpPost);
1424
					LOGGER.info("response" + response);
25300 tejbeer 1425
 
25351 tejbeer 1426
					if (response.getStatusLine().getStatusCode() == 200) {
1427
						pushNotification.setSentTimestamp(LocalDateTime.now());
1428
					} else {
25356 tejbeer 1429
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 1430
						LOGGER.info("message" + "not sent");
25351 tejbeer 1431
					}
25300 tejbeer 1432
 
25351 tejbeer 1433
				} catch (Exception e) {
1434
					e.printStackTrace();
25300 tejbeer 1435
					LOGGER.info("message" + "not sent");
1436
				}
1437
			}
1438
		}
1439
	}
1440
 
25553 amit.gupta 1441
	public void grouping() throws Exception {
25609 amit.gupta 1442
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
1443
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
1444
		System.out.println(String.join("\t",
1445
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 1446
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
25609 amit.gupta 1447
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers();
1448
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 1449
			if (priceDropIMEI.getPartnerId() == 0)
1450
				continue;
25609 amit.gupta 1451
			HashSet<String> imeis = new HashSet<>();
1452
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
1453
			imeis.add(priceDropIMEI.getImei());
1454
			List<InventoryItem> inventoryItems = inventoryItemRepository
1455
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 1456
			if (inventoryItems.size() == 0) {
1457
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 1458
				continue;
25612 amit.gupta 1459
			}
25609 amit.gupta 1460
			InventoryItem inventoryItem = inventoryItems.get(0);
1461
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
1462
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
1463
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
1464
				// check if pricedrop has been rolled out
1465
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
1466
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
1467
				if (uwh.size() > 0) {
25615 amit.gupta 1468
					Item item = itemRepository.selectById(inventoryItem.getItemId());
25609 amit.gupta 1469
					System.out.println(String.join("\t",
1470
							Arrays.asList(priceDropIMEI.getImei(), inventoryItem.getItemId() + "", item.getBrand(),
1471
									item.getModelName(), item.getModelNumber(), inventoryItem.getFofoId() + "",
1472
									customRetailer.getBusinessName(), inventoryItem.getCreateTimestamp().format(dtf),
1473
									priceDrop.getAffectedOn().format(dtf),
1474
									priceDropIMEI.getUpdateTimestamp().format(dtf),
25694 amit.gupta 1475
									inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getPartnerPayout() + "",
25609 amit.gupta 1476
									inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
1477
				}
1478
			}
1479
		}
25503 amit.gupta 1480
	}
25694 amit.gupta 1481
 
1482
	public void testToffee() throws Exception {
25846 amit.gupta 1483
		LOGGER.info("Insurance Sum Summary --- {}",
1484
				insurancePolicyRepository.selectAmountSumGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
1485
		LOGGER.info("Insurance Qty Summary --- {}",
1486
				insurancePolicyRepository.selectQtyGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
25800 tejbeer 1487
		// LOGGER.info("{}", toffeeService.getAuthToken());
25846 amit.gupta 1488
		/*
1489
		 * LOGGER.info("{}", toffeeService.getProducts()); // LOGGER.info("{}",
1490
		 * toffeeService.getPincodes("36103000PR")); PremiumCalculationRequestModel pcrm
1491
		 * = new PremiumCalculationRequestModel(); pcrm.setProductDetails("36103000PR");
1492
		 * // pcrm.setProductDetails("36103000PR");
1493
		 * pcrm.setDurations(Arrays.asList("3 Months", "6 Months", "1 Year"));
1494
		 * pcrm.setSumInsured("15000");
1495
		 * System.out.println(toffeeService.getPremiumCalculation(pcrm));
1496
		 */
25694 amit.gupta 1497
	}
1498
 
1499
	public void schemeRollback(List<String> schemeIds) throws Exception {
1500
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 1501
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 1502
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1503
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
1504
		for (SchemeInOut sio : schemeInOuts) {
1505
			Scheme scheme = schemesMap.get(sio.getSchemeId());
1506
			if (scheme.getType().equals(SchemeType.IN)) {
1507
 
1508
			} else if (scheme.getType().equals(SchemeType.OUT)) {
1509
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
1510
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
1511
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
1512
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
1513
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
1514
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
1515
					sio.setRolledBackTimestamp(LocalDateTime.now());
1516
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 1517
					String rollbackReason = "Scheme reversed for "
1518
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 1519
							+ fofoOrder.getInvoiceNumber();
1520
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
1521
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason);
1522
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
1523
							rollbackReason);
1524
				}
1525
			}
1526
		}
25721 tejbeer 1527
		// throw new Exception();
25694 amit.gupta 1528
	}
25721 tejbeer 1529
 
1530
	public void checkfocusedModelInPartnerStock() throws Exception {
1531
 
1532
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1533
				.collect(Collectors.toList());
1534
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
1535
		for (Integer fofoId : fofoIds) {
1536
			if (!focusedModelShortageReportMap.containsKey(fofoId)) {
1537
				focusedModelShortageReportMap.put(fofoId, new ArrayList<>());
1538
			}
1539
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1540
			Map<Integer, Integer> processingOrderMap = null;
1541
			Map<Integer, Integer> catalogIdAndQtyMap = null;
1542
			Map<Integer, Integer> grnPendingOrdersMap = null;
1543
 
1544
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1545
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1546
 
1547
			if (!currentInventorySnapshot.isEmpty()) {
1548
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1549
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1550
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1551
 
1552
			}
1553
 
1554
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1555
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1556
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1557
			if (!grnPendingOrders.isEmpty()) {
1558
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1559
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1560
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1561
 
1562
			}
1563
 
1564
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1565
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1566
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1567
			if (!processingOrder.isEmpty()) {
1568
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1569
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1570
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1571
 
1572
			}
1573
 
25800 tejbeer 1574
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1575
					.collect(Collectors.toList());
1576
 
1577
			List<Integer> focusedModelCatalogId = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
1578
					.collect(Collectors.toList());
1579
			Map<String, Object> equalsMap = new HashMap<>();
1580
			equalsMap.put("categoryId", 10006);
1581
			equalsMap.put("brand", brands);
1582
 
1583
			Map<String, List<?>> notEqualsMap = new HashMap<>();
1584
 
1585
			Map<String, Object> equalsJoinMap = new HashMap<>();
1586
			equalsJoinMap.put("catalogId", focusedModelCatalogId);
1587
 
1588
			Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1589
 
1590
			List<Integer> catalogIds = itemRepository
1591
					.selectItems(FocusedModel.class, "catalogItemId", "catalogId", equalsMap, notEqualsMap,
1592
							equalsJoinMap, notEqualsJoinMap, "minimumQty")
1593
					.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
1594
 
1595
			Map<Integer, Integer> focusedCatalogIdAndQtyMap = focusedModelRepository.selectByCatalogIdsl(catalogIds)
1596
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getMinimumQty()));
1597
 
1598
			/*
1599
			 * Map<Integer, Integer> focusedCatalogIdAndQtyMap =
1600
			 * focusedModelRepository.selectAll().stream() .collect(Collectors.toMap(x ->
1601
			 * x.getCatalogId(), x -> x.getMinimumQty()));
1602
			 */
1603
 
25721 tejbeer 1604
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
1605
 
1606
			for (Map.Entry<Integer, Integer> entry : focusedCatalogIdAndQtyMap.entrySet()) {
1607
				int inStockQty = 0;
1608
				int processingQty = 0;
1609
				int grnPendingQty = 0;
1610
				if (processingOrderMap != null) {
1611
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
1612
							: processingOrderMap.get(entry.getKey());
1613
 
1614
				}
1615
				if (grnPendingOrdersMap != null) {
1616
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
1617
							: grnPendingOrdersMap.get(entry.getKey());
1618
 
1619
				}
1620
				if (catalogIdAndQtyMap != null) {
1621
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
1622
							: catalogIdAndQtyMap.get(entry.getKey());
1623
 
1624
				}
1625
				int totalQty = processingQty + grnPendingQty + inStockQty;
1626
 
1627
				if (totalQty < entry.getValue()) {
1628
 
1629
					int shortageQty = entry.getValue() - totalQty;
1630
					List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
1631
 
1632
					FocusedModelShortageModel fm = new FocusedModelShortageModel();
1633
					fm.setFofoId(fofoId);
1634
					fm.setStoreName(customRetailer.getBusinessName());
1635
 
1636
					fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
1637
					fm.setShortageQty(shortageQty);
1638
 
1639
					focusedModelShortageReportMap.get(fofoId).add(fm);
1640
				}
1641
 
1642
			}
1643
			List<FocusedModelShortageModel> focusedModelShortageModel = focusedModelShortageReportMap.get(fofoId);
1644
 
1645
			if (!focusedModelShortageModel.isEmpty()) {
1646
				String subject = "Stock Alert";
1647
				String messageText = this.getMessage(focusedModelShortageModel);
1648
 
25732 tejbeer 1649
				this.sendMailWithAttachments(subject, messageText, customRetailer.getEmail());
25721 tejbeer 1650
				String notificationMessage = this.getNotificationMessage(focusedModelShortageModel);
1651
 
1652
				LOGGER.info("notificationMessage" + notificationMessage);
1653
				SimpleCampaignParams scp = new SimpleCampaignParams();
1654
 
1655
				scp.setTitle("Alert");
1656
				scp.setType("url");
25759 tejbeer 1657
				scp.setUrl("http://app.smartdukaan.com/pages/home/notifications");
25721 tejbeer 1658
				scp.setMessage(notificationMessage);
1659
				scp.setExpireTimestamp(LocalDateTime.now().plusDays(2));
1660
				SimpleCampaign sc = new SimpleCampaign(scp);
1661
				sc.setSimpleCampaignParams(scp);
1662
				LOGGER.info("scp" + scp);
1663
				NotificationCampaign nc = new NotificationCampaign();
1664
				nc.setName("Stock Alert");
1665
				nc.setImplementationType("SimpleCampaign");
1666
				nc.setImplementationParams(gson.toJson(scp));
1667
				nc.setCreatedTimestamp(LocalDateTime.now());
1668
				nc.setMessageType(MessageType.notification);
1669
				notificationCampaignRepository.persist(nc);
1670
				LOGGER.info("nc" + nc);
1671
				LOGGER.info("fofoID" + fofoId);
25732 tejbeer 1672
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
25721 tejbeer 1673
				LOGGER.info("userId" + userId);
1674
 
1675
				UserCampaign uc = new UserCampaign();
1676
				uc.setCampaignId(nc.getId());
1677
				uc.setUserId(userId);
1678
				uc.setPushTimestamp(LocalDateTime.now());
25800 tejbeer 1679
 
25721 tejbeer 1680
				userCampaignRepository.persist(uc);
1681
				List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(userId,
1682
						LocalDateTime.now().minusMonths(3), LocalDateTime.now());
1683
				pushNotification(nc.getId(), devices);
1684
 
1685
			}
25732 tejbeer 1686
 
25721 tejbeer 1687
		}
25800 tejbeer 1688
		if (!focusedModelShortageReportMap.isEmpty())
25721 tejbeer 1689
 
25800 tejbeer 1690
		{
1691
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
1692
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
25837 amit.gupta 1693
			Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 1694
 
25800 tejbeer 1695
			focusedModelShortageReportMap.entrySet().forEach(x -> {
1696
				storeGuyMap.entrySet().forEach(y -> {
1697
 
1698
					if (y.getValue().contains(x.getKey())) {
1699
						if (!emailRowsMap.containsKey(y.getKey())) {
1700
							emailRowsMap.put(y.getKey(), new ArrayList<>());
1701
						}
1702
						List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays
1703
								.asList(r.getFofoId(), r.getStoreName(), r.getItemName(), r.getShortageQty()))
1704
								.collect(Collectors.toList());
1705
						emailRowsMap.get(y.getKey()).addAll(fms);
1706
 
25721 tejbeer 1707
					}
1708
 
25800 tejbeer 1709
				});
25721 tejbeer 1710
 
1711
			});
1712
 
25800 tejbeer 1713
			List<String> headers = Arrays.asList("Partner Id", "Partner Name", "Model Name", "Shortage Qty");
25837 amit.gupta 1714
			emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 1715
 
25800 tejbeer 1716
				ByteArrayOutputStream baos = null;
1717
				try {
25837 amit.gupta 1718
					baos = FileUtil.getCSVByteStream(headers, entry.getValue());
25800 tejbeer 1719
				} catch (Exception e2) {
1720
					e2.printStackTrace();
1721
				}
25837 amit.gupta 1722
				String[] sendToArray = new String[] { entry.getKey() };
25800 tejbeer 1723
				try {
1724
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
1725
							new ByteArrayResource(baos.toByteArray()));
1726
				} catch (Exception e1) { // TODO Auto-generated catch block
1727
					e1.printStackTrace();
1728
				}
25721 tejbeer 1729
 
25800 tejbeer 1730
			});
1731
		}
25721 tejbeer 1732
	}
1733
 
1734
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1735
		StringBuilder sb = new StringBuilder();
1736
		sb.append("Focused Model Shortage in Your Stock : \n");
1737
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1738
 
1739
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
1740
			sb.append(String.format("%n", ""));
1741
		}
1742
		return sb.toString();
1743
	}
1744
 
1745
	public void pushNotification(int cid, List<Device> devices) {
1746
		for (Device device : devices) {
1747
			PushNotifications pn = new PushNotifications();
1748
			pn.setNotificationCampaignid(cid);
1749
			pn.setDeviceId(device.getId());
1750
			pn.setUserId(device.getUser_id());
1751
			pushNotificationRepository.persist(pn);
1752
		}
1753
 
1754
	}
1755
 
1756
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
1757
		MimeMessage message = mailSender.createMimeMessage();
1758
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
1759
 
1760
		helper.setSubject(subject);
1761
		helper.setText(messageText, true);
1762
		helper.setTo(email);
1763
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "ProfitMandi Admin");
1764
		helper.setFrom(senderAddress);
1765
		mailSender.send(message);
1766
 
1767
	}
1768
 
1769
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1770
		StringBuilder sb = new StringBuilder();
1771
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
1772
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
1773
		sb.append("<tbody>\n" + "	    				<tr>\n"
1774
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
1775
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
1776
				+ "	    				</tr>");
1777
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1778
 
1779
			sb.append("<tr>");
1780
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
1781
 
1782
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
1783
 
1784
			sb.append("</tr>");
1785
 
1786
		}
1787
 
1788
		sb.append("</tbody></table></body></html>");
1789
 
1790
		return sb.toString();
1791
	}
1792
 
1793
}