Subversion Repositories SmartDukaan

Rev

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