Subversion Repositories SmartDukaan

Rev

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