Subversion Repositories SmartDukaan

Rev

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