Subversion Repositories SmartDukaan

Rev

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