Subversion Repositories SmartDukaan

Rev

Rev 26032 | Rev 26092 | 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());
26059 amit.gupta 775
				if(authUser==null) {
776
					continue;
777
				}
25598 amit.gupta 778
				String name = authUser.getFirstName() + " " + authUser.getLastName();
779
				if (position.getEscalationType().equals(EscalationType.L1)) {
780
					saleRoles.getL1().add(name);
781
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
782
					saleRoles.getL2().add(name);
783
				}
784
			}
785
		}
25837 amit.gupta 786
 
787
		Set<CustomRetailer> allCrList = new HashSet<>();
788
		for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
789
			allCrList.addAll(cr);
790
		}
791
 
792
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
793
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
794
 
795
		Map<Integer, List<Serializable>> partnerIdSalesHeadersMap = new HashMap<>();
796
 
797
		for (CustomRetailer cr : allCrList) {
798
			FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
25927 amit.gupta 799
			if (fofoStore == null) {
25870 amit.gupta 800
				LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
801
				continue;
802
			}
25865 amit.gupta 803
			String code = fofoStore.getCode() + "";
25837 amit.gupta 804
			String storeName = "SmartDukaan-" + fofoStore.getCode().replaceAll("[a-zA-Z]", "");
805
			String businessName = cr.getBusinessName();
806
			try {
807
				String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
808
				String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
809
				List<Serializable> row = new ArrayList<>(
810
						Arrays.asList(code, businessName, storeName, stateManager, territoryManager));
811
				partnerIdSalesHeadersMap.put(cr.getPartnerId(), row);
812
 
813
			} catch (Exception e) {
814
				LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
815
			}
816
		}
817
		return partnerIdSalesHeadersMap;
818
 
25598 amit.gupta 819
	}
820
 
24271 amit.gupta 821
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 822
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 823
	}
824
 
25312 amit.gupta 825
	public void sendTargetVsSalesReport(List<String> sendTo) throws Exception {
24177 govind 826
 
25312 amit.gupta 827
		if (sendTo == null) {
25827 amit.gupta 828
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
829
					"amit.gupta@shop2020.in", "amod.sen@smartdukaan.com", "prakash.rai@smartdukaan.com");
25312 amit.gupta 830
		}
25837 amit.gupta 831
		Map<Integer, List<Serializable>> partnerSalesTargetRowsMap = targetService.getDailySaleReportVsTarget();
25315 amit.gupta 832
 
25837 amit.gupta 833
		Map<Integer, List<Serializable>> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
24177 govind 834
 
25837 amit.gupta 835
		List<String> headers = Arrays.asList("Code", "Firm Name", "Store Name", "State Manager", "Teritory Manager",
836
				"Current Category", "Target Value", "Target Achieved", "Achived Percentage", "Remaining Target",
837
				"Today's Target", "Today's achievement");
25609 amit.gupta 838
 
25837 amit.gupta 839
		List<List<?>> rows = new ArrayList<>();
840
		Map<Integer, List<? extends Serializable>> partnerRowMap = new HashMap<>();
841
		for (Map.Entry<Integer, List<Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap.entrySet()) {
842
			List<Serializable> row = partnerIdSalesHeadersMap.get(partnerSalesTargetRowEntry.getKey());
843
			if (row == null) {
844
				LOGGER.warn("Could not find headers for partner ID - {}", partnerSalesTargetRowEntry.getKey());
25315 amit.gupta 845
			}
25837 amit.gupta 846
			row.addAll(partnerSalesTargetRowEntry.getValue());
847
			partnerRowMap.put(partnerSalesTargetRowEntry.getKey(), row);
848
			rows.add(row);
24177 govind 849
		}
25503 amit.gupta 850
 
25318 amit.gupta 851
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25894 amit.gupta 852
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
853
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25827 amit.gupta 854
			if (storeGuyEntry.getValue().size() == 0)
855
				continue;
25927 amit.gupta 856
			List<List<?>> storeGuyRows = storeGuyEntry.getValue().stream().filter(x -> partnerRowMap.containsKey(x))
857
					.map(x -> partnerRowMap.get(x)).collect(Collectors.toList());
25827 amit.gupta 858
			ByteArrayOutputStream authUserStream = FileUtil.getCSVByteStream(headers, storeGuyRows);
859
			Attachment attache = new Attachment(fileName, new ByteArrayResource(authUserStream.toByteArray()));
860
			System.out.println(storeGuyEntry.getValue());
861
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
862
					"Franchise Stock Report", "PFA", attache);
863
		}
24240 amit.gupta 864
 
25312 amit.gupta 865
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
866
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
867
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
868
				new ByteArrayResource(baos.toByteArray()));
24174 govind 869
	}
24683 amit.gupta 870
 
24697 amit.gupta 871
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 872
 
873
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
874
				"itemstockageing.xml");
24708 amit.gupta 875
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 876
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 877
		Attachment attachment = new Attachment(
25445 amit.gupta 878
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 879
		Attachment attachment1 = new Attachment(
25445 amit.gupta 880
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 881
 
25609 amit.gupta 882
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
883
				attachment);
884
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
885
				"Itemwise Pending indent", "PFA", attachment1);
886
 
25598 amit.gupta 887
		// Reports to be sent to mapped partners
25597 amit.gupta 888
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 889
 
890
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 891
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 892
			if (storeGuyEntry.getValue().size() == 0)
893
				continue;
25418 amit.gupta 894
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
895
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
896
					"focostockreport.xml", params);
897
			Attachment attache = new Attachment(
25609 amit.gupta 898
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 899
			System.out.println(storeGuyEntry.getValue());
25609 amit.gupta 900
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
901
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 902
		}
25503 amit.gupta 903
 
24681 amit.gupta 904
	}
24533 govind 905
 
24697 amit.gupta 906
	public void sendAgeingReport() throws Exception {
25807 amit.gupta 907
		sendAgeingReport("kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com", "tarun.verma@smartdukaan.com",
25609 amit.gupta 908
				"chaitnaya.vats@smartdukaan.com");
24697 amit.gupta 909
	}
910
 
24533 govind 911
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 912
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 913
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 914
			priceDropService.priceDropStatus(priceDrop.getId());
915
		}
916
	}
23929 amit.gupta 917
 
24542 amit.gupta 918
	public void walletmismatch() throws Exception {
919
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 920
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 921
		System.out.println(pdis.size());
24542 amit.gupta 922
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 923
			int fofoId = pdi.getFofoId();
24542 amit.gupta 924
			for (PartnerDailyInvestment investment : Lists
925
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 926
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 927
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 928
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 929
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
930
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 931
 
24542 amit.gupta 932
			}
24549 amit.gupta 933
		}
24542 amit.gupta 934
 
935
	}
936
 
937
	public void gst() throws Exception {
24548 amit.gupta 938
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
939
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
940
		for (FofoOrder fofoOrder : fofoOrders) {
941
			int retailerAddressId = retailerRegisteredAddressRepository
942
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 943
 
944
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
945
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
946
			Integer stateId = null;
947
			if (customerAddress.getState().equals(retailerAddress.getState())) {
948
				try {
949
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
950
				} catch (Exception e) {
951
					LOGGER.error("Unable to get state rates");
952
				}
953
			}
954
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
955
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 956
 
957
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
958
			Set<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
24542 amit.gupta 959
			if (stateId != null) {
960
				itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemIds), stateId);
961
			} else {
962
				itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemIds));
963
			}
964
 
24548 amit.gupta 965
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 966
				if (stateId == null) {
967
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
968
				} else {
969
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
970
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
971
				}
972
				fofoOrderItemRepository.persist(foi);
973
			}
974
		}
24548 amit.gupta 975
 
24542 amit.gupta 976
	}
977
 
24580 amit.gupta 978
	public void schemewalletmismatch() {
979
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 980
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 981
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 982
			// reconcileOrders(dateTime);
983
			// reconcileRecharges(dateTime);
24580 amit.gupta 984
			dateToReconcile = dateToReconcile.plusDays(1);
985
		}
986
	}
987
 
988
	private void reconcileSchemes(LocalDate date) {
989
		LocalDateTime startDate = date.atStartOfDay();
990
		LocalDateTime endDate = startDate.plusDays(1);
991
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
992
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 993
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
994
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 995
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 996
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
997
				WalletReferenceType.SCHEME_OUT);
998
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
999
				walletReferenceTypes);
1000
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
1001
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 1002
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 1003
 
1004
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
1005
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1006
 
1007
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
1008
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1009
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
1010
 
1011
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
1012
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1013
 
1014
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
1015
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
1016
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
1017
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
1018
 
1019
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
1020
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeMap.entrySet()) {
1021
			}
1022
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
1023
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
1024
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
1025
				} else {
1026
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
1027
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
1028
				}
1029
			}
24590 amit.gupta 1030
			Map<Integer, Integer> userWalletMap = userWalletRepository
1031
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
1032
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1033
 
24587 amit.gupta 1034
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
1035
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
1036
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
1037
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1038
				if (diff > 5) {
1039
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1040
				}
1041
			}
24580 amit.gupta 1042
		}
24587 amit.gupta 1043
 
24580 amit.gupta 1044
	}
24590 amit.gupta 1045
 
24592 amit.gupta 1046
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1047
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1048
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1049
 
24592 amit.gupta 1050
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1051
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1052
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1053
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1054
		Set<String> serialNumbersConsidered = new HashSet<>();
1055
 
25096 amit.gupta 1056
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1057
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1058
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1059
 
24683 amit.gupta 1060
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1061
		purchases.stream().forEach(purchase -> {
1062
			float amountToRollback = 0;
1063
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1064
					+ purchase.getPurchaseReference();
1065
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1066
					.stream().filter(ii -> ii.getSerialNumber() != null)
1067
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1068
			if (inventorySerialNumberMap.size() > 0) {
1069
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1070
					String serialNumber = inventorySerialNumberEntry.getValue();
1071
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1072
					if (serialNumbersConsidered.contains(serialNumber)) {
1073
						// This will rollback scheme for differenct orders for same serial
1074
						List<SchemeInOut> sios = schemeInOutRepository
1075
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1076
								.filter(x -> x.getRolledBackTimestamp() == null
1077
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1078
								.collect(Collectors.toList());
1079
						Collections.reverse(sios);
1080
						for (SchemeInOut sio : sios) {
1081
							sio.setRolledBackTimestamp(LocalDateTime.now());
1082
							amountToRollback += sio.getAmount();
1083
							// sio.setSchemeType(SchemeType.OUT);
1084
							sio.setSerialNumber(serialNumber);
1085
							rolledbackSios.add(sio);
1086
						}
1087
						description = description.concat(" " + serialNumber + " ");
1088
					} else {
1089
						serialNumbersConsidered.add(serialNumber);
1090
						List<Integer> schemesConsidered = new ArrayList<>();
1091
						List<SchemeInOut> sios = schemeInOutRepository
1092
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1093
								.filter(x -> x.getRolledBackTimestamp() == null
1094
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1095
								.collect(Collectors.toList());
1096
						Collections.reverse(sios);
1097
						for (SchemeInOut sio : sios) {
1098
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1099
								schemesConsidered.add(sio.getSchemeId());
1100
								continue;
1101
							}
1102
							sio.setRolledBackTimestamp(LocalDateTime.now());
1103
							amountToRollback += sio.getAmount();
1104
							// sio.setSchemeType(SchemeType.OUT);
1105
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1106
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1107
							sio.setReference(purchase.getId());
24635 amit.gupta 1108
							rolledbackSios.add(sio);
1109
						}
1110
					}
1111
 
1112
				}
1113
			}
1114
			if (amountToRollback > 0) {
24683 amit.gupta 1115
				// Address address =
1116
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1117
				UserWalletHistory uwh = new UserWalletHistory();
1118
				uwh.setAmount(Math.round(amountToRollback));
1119
				uwh.setDescription(description);
1120
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1121
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1122
				uwh.setReference(purchase.getId());
1123
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1124
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1125
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1126
				userWalletHistory.add(uwh);
1127
			}
1128
		});
1129
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1130
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1131
						"Timestamp"),
1132
				userWalletHistory.stream()
1133
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1134
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1135
						.collect(Collectors.toList()));
1136
 
1137
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1138
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1139
						"Created", "Rolledback"),
24635 amit.gupta 1140
				rolledbackSios.stream()
24681 amit.gupta 1141
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1142
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1143
						.collect(Collectors.toList()));
1144
 
25043 amit.gupta 1145
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1146
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1147
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1148
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1149
 
25096 amit.gupta 1150
		throw new Exception();
24635 amit.gupta 1151
 
1152
	}
1153
 
1154
	public void dryRunOutSchemeReco() throws Exception {
1155
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1156
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1157
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1158
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1159
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1160
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1161
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1162
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1163
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1164
		// Collections.reverse(allOrders);
1165
		// List<FofoOrder> allOrders =
24653 govind 1166
		// List<FofoOrder> allOrders =
24631 amit.gupta 1167
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1168
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1169
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1170
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1171
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1172
			float amountToRollback = 0;
24590 amit.gupta 1173
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1174
			orderItems.forEach(x -> {
24606 amit.gupta 1175
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1176
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1177
			});
24606 amit.gupta 1178
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1179
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1180
					String serialNumber = inventorySerialNumberEntry.getValue();
1181
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1182
					if (serialNumbersConsidered.contains(serialNumber)) {
1183
						// This will rollback scheme for differenct orders for same serial
1184
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1185
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1186
								.filter(x -> x.getRolledBackTimestamp() == null
1187
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1188
								.collect(Collectors.toList());
1189
						Collections.reverse(sios);
1190
						for (SchemeInOut sio : sios) {
1191
							sio.setRolledBackTimestamp(LocalDateTime.now());
1192
							amountToRollback += sio.getAmount();
1193
							// sio.setSchemeType(SchemeType.OUT);
1194
							sio.setSerialNumber(serialNumber);
1195
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1196
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1197
							rolledbackSios.add(sio);
24623 amit.gupta 1198
						}
24635 amit.gupta 1199
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1200
					} else {
1201
						serialNumbersConsidered.add(serialNumber);
1202
						List<Integer> schemesConsidered = new ArrayList<>();
1203
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1204
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1205
								.filter(x -> x.getRolledBackTimestamp() == null
1206
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1207
								.collect(Collectors.toList());
1208
						Collections.reverse(sios);
1209
						for (SchemeInOut sio : sios) {
1210
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1211
								schemesConsidered.add(sio.getSchemeId());
1212
								continue;
1213
							}
1214
							sio.setRolledBackTimestamp(LocalDateTime.now());
1215
							amountToRollback += sio.getAmount();
1216
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1217
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1218
							sio.setSerialNumber(serialNumber);
1219
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1220
							rolledbackSios.add(sio);
1221
						}
24615 amit.gupta 1222
					}
24631 amit.gupta 1223
 
24604 amit.gupta 1224
				}
24590 amit.gupta 1225
			}
24631 amit.gupta 1226
			if (amountToRollback > 0) {
1227
				UserWalletHistory uwh = new UserWalletHistory();
1228
				uwh.setAmount(Math.round(amountToRollback));
1229
				uwh.setDescription(description);
1230
				uwh.setTimestamp(LocalDateTime.now());
1231
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1232
				uwh.setReference(fofoOrder.getId());
1233
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1234
				uwh.setFofoId(fofoOrder.getFofoId());
1235
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1236
				userWalletHistory.add(uwh);
1237
			}
24590 amit.gupta 1238
		});
24598 amit.gupta 1239
 
24592 amit.gupta 1240
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1241
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1242
						"Timestamp"),
1243
				userWalletHistory.stream()
1244
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1245
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1246
						.collect(Collectors.toList()));
1247
 
1248
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1249
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1250
						"Rolledback"),
1251
				rolledbackSios.stream()
1252
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1253
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1254
						.collect(Collectors.toList()));
1255
 
25043 amit.gupta 1256
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1257
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1258
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1259
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1260
 
25267 amit.gupta 1261
		throw new Exception();
24590 amit.gupta 1262
	}
24615 amit.gupta 1263
 
24611 amit.gupta 1264
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1265
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1266
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1267
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1268
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1269
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1270
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1271
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1272
		references.stream().forEach(reference -> {
1273
			FofoOrder fofoOrder = null;
1274
			try {
1275
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1276
			} catch (Exception e) {
1277
 
24611 amit.gupta 1278
			}
1279
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1280
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1281
			float amountToRollback = 0;
1282
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1283
			orderItems.forEach(x -> {
1284
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1285
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1286
			});
1287
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1288
				List<SchemeInOut> sios = schemeInOutRepository
1289
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1290
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1291
						.collect(Collectors.toList());
1292
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1293
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1294
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1295
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1296
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1297
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1298
					if (outList.size() > 1) {
1299
 
24611 amit.gupta 1300
					}
1301
				}
1302
				uwh.setAmount(Math.round(amountToRollback));
1303
				uwh.setDescription(description);
1304
				uwh.setTimestamp(LocalDateTime.now());
1305
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1306
				uwh.setReference(fofoOrder.getId());
1307
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1308
				uwh.setFofoId(fofoOrder.getFofoId());
1309
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1310
				userWalletHistory.add(uwh);
1311
			}
1312
		});
24615 amit.gupta 1313
 
24611 amit.gupta 1314
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1315
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1316
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1317
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1318
						.collect(Collectors.toList()));
1319
 
24611 amit.gupta 1320
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1321
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1322
						"Rolledback"),
1323
				rolledbackSios.stream()
24615 amit.gupta 1324
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1325
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1326
						.collect(Collectors.toList()));
1327
 
24623 amit.gupta 1328
		Utils.sendMailWithAttachments(googleMailSender,
1329
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1330
				"Partner Excess Amount", "PFA",
1331
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1332
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1333
 
24628 amit.gupta 1334
		throw new Exception();
24615 amit.gupta 1335
 
24611 amit.gupta 1336
	}
24615 amit.gupta 1337
 
25837 amit.gupta 1338
	public void sendDailySalesNotificationToPartner(Integer fofoIdInt)
24653 govind 1339
			throws ProfitMandiBusinessException, MessagingException, IOException {
25927 amit.gupta 1340
 
24653 govind 1341
		LocalDateTime now = LocalDateTime.now();
25837 amit.gupta 1342
		LocalDateTime from = now.with(LocalTime.MIN);
25925 amit.gupta 1343
		String timeString = "Today %s";
25927 amit.gupta 1344
		// Send yesterday's report
1345
		if (now.getHour() < 13) {
25925 amit.gupta 1346
			timeString = "Yesterday %s";
25910 amit.gupta 1347
			from = now.minusDays(1);
1348
			now = from.with(LocalTime.MAX);
25927 amit.gupta 1349
 
25910 amit.gupta 1350
		}
24855 amit.gupta 1351
		List<Integer> fofoIds = null;
25043 amit.gupta 1352
		if (fofoIdInt == null) {
1353
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1354
					.collect(Collectors.toList());
24856 amit.gupta 1355
		} else {
24855 amit.gupta 1356
			fofoIds = Arrays.asList(fofoIdInt);
1357
		}
25912 amit.gupta 1358
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
24683 amit.gupta 1359
 
25865 amit.gupta 1360
		Map<Integer, Double> salesByFofoIdMap = new HashMap<>();
1361
		Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1362
				null);
1363
		Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
1364
		Map<Integer, Double> partnerOrderAmountMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now,
1365
				0, true);
1366
		Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
1367
		Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
1368
		for (int fofoId : fofoIds) {
1369
			SaleTargetReportModel model = new SaleTargetReportModel();
25927 amit.gupta 1370
			model.setInsuranceSale(
1371
					partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
25865 amit.gupta 1372
			model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
1373
			model.setSmartphoneSale(partnerOrderAmountMap.containsKey(fofoId) ? partnerOrderAmountMap.get(fofoId) : 0);
1374
			model.setSmartphoneQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
1375
			model.setTotalSale(salesByFofoIdMap.containsKey(fofoId) ? salesByFofoIdMap.get(fofoId) : 0);
25880 amit.gupta 1376
			model.setFofoId(fofoId);
25865 amit.gupta 1377
			saleTargetReportModelMap.put(fofoId, model);
1378
		}
25880 amit.gupta 1379
 
25865 amit.gupta 1380
		Map<Integer, List<Serializable>> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
24653 govind 1381
		for (Integer fofoId : fofoIds) {
25865 amit.gupta 1382
			SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
25821 amit.gupta 1383
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1384
			sendNotificationModel.setCampaignName("Sales update alert");
25884 tejbeer 1385
			sendNotificationModel.setTitle("Sale Update");
25927 amit.gupta 1386
			sendNotificationModel
1387
					.setMessage(String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1388
							model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1389
							String.format(timeString, now.format(timeFormatter))));
25821 amit.gupta 1390
			sendNotificationModel.setType("url");
1391
			sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
1392
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1393
			sendNotificationModel.setMessageType(MessageType.notification);
25872 tejbeer 1394
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1395
			sendNotificationModel.setUserIds(Arrays.asList(userId));
25854 amit.gupta 1396
			notificationService.sendNotification(sendNotificationModel);
24653 govind 1397
		}
25865 amit.gupta 1398
		String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap, saleTargetReportModelMap);
24653 govind 1399
		LOGGER.info(saleReport);
25837 amit.gupta 1400
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "prakash.rai@smartdukaan.com",
25846 amit.gupta 1401
				"chaitnaya.vats@smartdukaan.com" };
25837 amit.gupta 1402
 
25912 amit.gupta 1403
		String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
25821 amit.gupta 1404
		this.sendMailOfHtmlFomat("amit.gupta@shop2020.in", saleReport, cc, subject);
24653 govind 1405
	}
1406
 
25865 amit.gupta 1407
	public static class SaleTargetReportModel {
1408
		private double totalSale;
25880 amit.gupta 1409
		private int fofoId;
1410
 
1411
		public int getFofoId() {
1412
			return fofoId;
1413
		}
1414
 
1415
		public void setFofoId(int fofoId) {
1416
			this.fofoId = fofoId;
1417
		}
1418
 
25865 amit.gupta 1419
		private double smartphoneSale;
1420
		private long smartphoneQty;
1421
		private double insuranceSale;
1422
		private long insruanceQty;
1423
 
1424
		@Override
1425
		public int hashCode() {
1426
			final int prime = 31;
1427
			int result = 1;
25880 amit.gupta 1428
			result = prime * result + fofoId;
25865 amit.gupta 1429
			result = prime * result + (int) (insruanceQty ^ (insruanceQty >>> 32));
1430
			long temp;
1431
			temp = Double.doubleToLongBits(insuranceSale);
1432
			result = prime * result + (int) (temp ^ (temp >>> 32));
1433
			result = prime * result + (int) (smartphoneQty ^ (smartphoneQty >>> 32));
1434
			temp = Double.doubleToLongBits(smartphoneSale);
1435
			result = prime * result + (int) (temp ^ (temp >>> 32));
1436
			temp = Double.doubleToLongBits(totalSale);
1437
			result = prime * result + (int) (temp ^ (temp >>> 32));
1438
			return result;
1439
		}
1440
 
1441
		@Override
1442
		public boolean equals(Object obj) {
1443
			if (this == obj)
1444
				return true;
1445
			if (obj == null)
1446
				return false;
1447
			if (getClass() != obj.getClass())
1448
				return false;
1449
			SaleTargetReportModel other = (SaleTargetReportModel) obj;
25880 amit.gupta 1450
			if (fofoId != other.fofoId)
1451
				return false;
25865 amit.gupta 1452
			if (insruanceQty != other.insruanceQty)
1453
				return false;
1454
			if (Double.doubleToLongBits(insuranceSale) != Double.doubleToLongBits(other.insuranceSale))
1455
				return false;
1456
			if (smartphoneQty != other.smartphoneQty)
1457
				return false;
1458
			if (Double.doubleToLongBits(smartphoneSale) != Double.doubleToLongBits(other.smartphoneSale))
1459
				return false;
1460
			if (Double.doubleToLongBits(totalSale) != Double.doubleToLongBits(other.totalSale))
1461
				return false;
1462
			return true;
1463
		}
1464
 
1465
		public double getTotalSale() {
1466
			return totalSale;
1467
		}
1468
 
1469
		public void setTotalSale(double totalSale) {
1470
			this.totalSale = totalSale;
1471
		}
1472
 
1473
		public double getSmartphoneSale() {
1474
			return smartphoneSale;
1475
		}
1476
 
1477
		public void setSmartphoneSale(double smartphoneSale) {
1478
			this.smartphoneSale = smartphoneSale;
1479
		}
1480
 
1481
		public long getSmartphoneQty() {
1482
			return smartphoneQty;
1483
		}
1484
 
1485
		public void setSmartphoneQty(long smartphoneQty) {
1486
			this.smartphoneQty = smartphoneQty;
1487
		}
1488
 
1489
		public double getInsuranceSale() {
1490
			return insuranceSale;
1491
		}
1492
 
1493
		public void setInsuranceSale(double insuranceSale) {
1494
			this.insuranceSale = insuranceSale;
1495
		}
1496
 
1497
		public long getInsruanceQty() {
1498
			return insruanceQty;
1499
		}
1500
 
1501
		public void setInsruanceQty(long insruanceQty) {
1502
			this.insruanceQty = insruanceQty;
1503
		}
1504
 
1505
		@Override
1506
		public String toString() {
25880 amit.gupta 1507
			return "SaleTargetReportModel [totalSale=" + totalSale + ", fofoId=" + fofoId + ", smartphoneSale="
1508
					+ smartphoneSale + ", smartphoneQty=" + smartphoneQty + ", insuranceSale=" + insuranceSale
1509
					+ ", insruanceQty=" + insruanceQty + "]";
25865 amit.gupta 1510
		}
1511
 
1512
	}
1513
 
1514
	private String getDailySalesReportHtml(Map<Integer, List<Serializable>> partnerSalesHeadersMap,
25872 tejbeer 1515
			Map<Integer, SaleTargetReportModel> saleReportTargetMap) throws ProfitMandiBusinessException {
24653 govind 1516
		StringBuilder sb = new StringBuilder();
25872 tejbeer 1517
 
25832 amit.gupta 1518
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 1519
		sb.append("<tbody>\n" + "	    				<tr>\n"
25865 amit.gupta 1520
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1521
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1522
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1523
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
1524
				+ "	    					<th style='border:1px solid black;padding: 5px'>%s</th>\n"
24653 govind 1525
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
25865 amit.gupta 1526
				+ "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>\n"
1527
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>\n"
1528
				+ "	    					<th style='border:1px solid black;padding: 5px'>Insurance Sale</th>\n"
1529
				+ "	    					<th style='border:1px solid black;padding: 5px'>Insurance Qty</th>\n"
24653 govind 1530
				+ "	    				</tr>");
25880 amit.gupta 1531
		List<Integer> sortedPartnerSalesHeaders = partnerSalesHeadersMap.entrySet().stream()
1532
				.sorted((x, y) -> ((String) (x.getValue().get(3))).compareTo((String) (y.getValue().get(3))))
25927 amit.gupta 1533
				.map(x -> x.getKey()).collect(Collectors.toList());
1534
		for (Integer fofoId : sortedPartnerSalesHeaders) {
25865 amit.gupta 1535
			sb.append("<tr>");
25880 amit.gupta 1536
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(0)
1537
					+ "</td>");
1538
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(1)
1539
					+ "</td>");
1540
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(2)
1541
					+ "</td>");
1542
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(3)
1543
					+ "</td>");
1544
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).get(4)
1545
					+ "</td>");
1546
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1547
					+ saleReportTargetMap.get(fofoId).getTotalSale() + "</td>");
1548
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1549
					+ saleReportTargetMap.get(fofoId).getSmartphoneSale() + "</td>");
1550
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1551
					+ saleReportTargetMap.get(fofoId).getSmartphoneQty() + "</td>");
1552
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1553
					+ saleReportTargetMap.get(fofoId).getInsuranceSale() + "</td>");
1554
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1555
					+ saleReportTargetMap.get(fofoId).getInsruanceQty() + "</td>");
25865 amit.gupta 1556
			sb.append("</tr>");
24653 govind 1557
 
1558
		}
24683 amit.gupta 1559
 
24653 govind 1560
		sb.append("</tbody></table></body></html>");
25865 amit.gupta 1561
		return String.format(sb.toString(), REPORT_HEADERS);
24653 govind 1562
	}
24841 govind 1563
 
1564
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1565
			throws MessagingException, ProfitMandiBusinessException, IOException {
1566
		MimeMessage message = mailSender.createMimeMessage();
1567
		MimeMessageHelper helper = new MimeMessageHelper(message);
1568
		helper.setSubject(subject);
1569
		helper.setText(body, true);
1570
		helper.setTo(email);
1571
		if (cc != null) {
1572
			helper.setCc(cc);
1573
		}
1574
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1575
		helper.setFrom(senderAddress);
1576
		mailSender.send(message);
1577
	}
25300 tejbeer 1578
 
25351 tejbeer 1579
	public void sendNotification() throws Exception {
25300 tejbeer 1580
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1581
		if (!pushNotifications.isEmpty()) {
1582
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1583
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1584
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1585
						.selectById(pushNotification.getNotificationCampaignid());
1586
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1587
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1588
 
1589
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1590
						SimpleCampaignParams.class);
1591
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1592
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1593
				JSONObject json = new JSONObject();
25351 tejbeer 1594
				json.put("to", device.getFcmId());
25300 tejbeer 1595
				JSONObject jsonObj = new JSONObject();
1596
				jsonObj.put("message", campaign.getMessage());
1597
				jsonObj.put("title", campaign.getTitle());
1598
				jsonObj.put("type", campaign.getType());
1599
				jsonObj.put("url", result_url);
1600
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1601
				jsonObj.put("image", campaign.getImageUrl());
1602
				jsonObj.put("largeIcon", "large_icon");
1603
				jsonObj.put("smallIcon", "small_icon");
1604
				jsonObj.put("vibrate", 1);
1605
				jsonObj.put("pid", pushNotification.getId());
1606
				jsonObj.put("sound", 1);
1607
				jsonObj.put("priority", "high");
1608
				json.put("data", jsonObj);
25351 tejbeer 1609
				try {
1610
					CloseableHttpClient client = HttpClients.createDefault();
1611
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1612
 
25351 tejbeer 1613
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1614
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1615
					StringEntity entity = new StringEntity(json.toString());
1616
					httpPost.setEntity(entity);
1617
					CloseableHttpResponse response = client.execute(httpPost);
1618
					LOGGER.info("response" + response);
25300 tejbeer 1619
 
25351 tejbeer 1620
					if (response.getStatusLine().getStatusCode() == 200) {
1621
						pushNotification.setSentTimestamp(LocalDateTime.now());
1622
					} else {
25356 tejbeer 1623
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 1624
						LOGGER.info("message" + "not sent");
25351 tejbeer 1625
					}
25300 tejbeer 1626
 
25351 tejbeer 1627
				} catch (Exception e) {
1628
					e.printStackTrace();
25300 tejbeer 1629
					LOGGER.info("message" + "not sent");
1630
				}
1631
			}
1632
		}
1633
	}
1634
 
25553 amit.gupta 1635
	public void grouping() throws Exception {
25609 amit.gupta 1636
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
1637
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
1638
		System.out.println(String.join("\t",
1639
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 1640
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
25609 amit.gupta 1641
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers();
1642
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 1643
			if (priceDropIMEI.getPartnerId() == 0)
1644
				continue;
25609 amit.gupta 1645
			HashSet<String> imeis = new HashSet<>();
1646
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
1647
			imeis.add(priceDropIMEI.getImei());
1648
			List<InventoryItem> inventoryItems = inventoryItemRepository
1649
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 1650
			if (inventoryItems.size() == 0) {
1651
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 1652
				continue;
25612 amit.gupta 1653
			}
25609 amit.gupta 1654
			InventoryItem inventoryItem = inventoryItems.get(0);
1655
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
1656
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
1657
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
1658
				// check if pricedrop has been rolled out
1659
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
1660
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
1661
				if (uwh.size() > 0) {
25615 amit.gupta 1662
					Item item = itemRepository.selectById(inventoryItem.getItemId());
25609 amit.gupta 1663
					System.out.println(String.join("\t",
1664
							Arrays.asList(priceDropIMEI.getImei(), inventoryItem.getItemId() + "", item.getBrand(),
1665
									item.getModelName(), item.getModelNumber(), inventoryItem.getFofoId() + "",
1666
									customRetailer.getBusinessName(), inventoryItem.getCreateTimestamp().format(dtf),
1667
									priceDrop.getAffectedOn().format(dtf),
1668
									priceDropIMEI.getUpdateTimestamp().format(dtf),
25694 amit.gupta 1669
									inventoryItem.getUpdateTimestamp().format(dtf), priceDrop.getPartnerPayout() + "",
25609 amit.gupta 1670
									inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
1671
				}
1672
			}
1673
		}
25503 amit.gupta 1674
	}
25694 amit.gupta 1675
 
1676
	public void testToffee() throws Exception {
25846 amit.gupta 1677
		LOGGER.info("Insurance Sum Summary --- {}",
1678
				insurancePolicyRepository.selectAmountSumGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
1679
		LOGGER.info("Insurance Qty Summary --- {}",
1680
				insurancePolicyRepository.selectQtyGroupByRetailerId(LocalDateTime.MIN, LocalDateTime.MAX));
25854 amit.gupta 1681
		LOGGER.info("SmartPhone Amount Summary --- {}",
25856 amit.gupta 1682
				fofoOrderItemRepository.selectSumAmountGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25854 amit.gupta 1683
		LOGGER.info("Smartphone Qty Summary --- {}",
1684
				fofoOrderItemRepository.selectQtyGroupByRetailer(LocalDateTime.MIN, LocalDateTime.MAX, 0, true));
25800 tejbeer 1685
		// LOGGER.info("{}", toffeeService.getAuthToken());
25846 amit.gupta 1686
		/*
1687
		 * LOGGER.info("{}", toffeeService.getProducts()); // LOGGER.info("{}",
1688
		 * toffeeService.getPincodes("36103000PR")); PremiumCalculationRequestModel pcrm
1689
		 * = new PremiumCalculationRequestModel(); pcrm.setProductDetails("36103000PR");
1690
		 * // pcrm.setProductDetails("36103000PR");
1691
		 * pcrm.setDurations(Arrays.asList("3 Months", "6 Months", "1 Year"));
1692
		 * pcrm.setSumInsured("15000");
1693
		 * System.out.println(toffeeService.getPremiumCalculation(pcrm));
1694
		 */
25694 amit.gupta 1695
	}
1696
 
1697
	public void schemeRollback(List<String> schemeIds) throws Exception {
1698
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 1699
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 1700
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1701
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
1702
		for (SchemeInOut sio : schemeInOuts) {
1703
			Scheme scheme = schemesMap.get(sio.getSchemeId());
1704
			if (scheme.getType().equals(SchemeType.IN)) {
1705
 
1706
			} else if (scheme.getType().equals(SchemeType.OUT)) {
1707
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
1708
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
1709
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
1710
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
1711
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
1712
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
1713
					sio.setRolledBackTimestamp(LocalDateTime.now());
1714
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 1715
					String rollbackReason = "Scheme reversed for "
1716
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 1717
							+ fofoOrder.getInvoiceNumber();
1718
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
1719
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason);
1720
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
1721
							rollbackReason);
1722
				}
1723
			}
1724
		}
25721 tejbeer 1725
		// throw new Exception();
25694 amit.gupta 1726
	}
25721 tejbeer 1727
 
1728
	public void checkfocusedModelInPartnerStock() throws Exception {
1729
 
1730
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1731
				.collect(Collectors.toList());
1732
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
1733
		for (Integer fofoId : fofoIds) {
1734
			if (!focusedModelShortageReportMap.containsKey(fofoId)) {
1735
				focusedModelShortageReportMap.put(fofoId, new ArrayList<>());
1736
			}
1737
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1738
			Map<Integer, Integer> processingOrderMap = null;
1739
			Map<Integer, Integer> catalogIdAndQtyMap = null;
1740
			Map<Integer, Integer> grnPendingOrdersMap = null;
1741
 
1742
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1743
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1744
 
1745
			if (!currentInventorySnapshot.isEmpty()) {
1746
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1747
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1748
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1749
 
1750
			}
1751
 
1752
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1753
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1754
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1755
			if (!grnPendingOrders.isEmpty()) {
1756
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1757
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1758
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1759
 
1760
			}
1761
 
1762
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1763
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1764
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1765
			if (!processingOrder.isEmpty()) {
1766
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1767
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1768
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1769
 
1770
			}
1771
 
25800 tejbeer 1772
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1773
					.collect(Collectors.toList());
1774
 
1775
			List<Integer> focusedModelCatalogId = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
1776
					.collect(Collectors.toList());
1777
			Map<String, Object> equalsMap = new HashMap<>();
1778
			equalsMap.put("categoryId", 10006);
1779
			equalsMap.put("brand", brands);
1780
 
1781
			Map<String, List<?>> notEqualsMap = new HashMap<>();
1782
 
1783
			Map<String, Object> equalsJoinMap = new HashMap<>();
1784
			equalsJoinMap.put("catalogId", focusedModelCatalogId);
1785
 
1786
			Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1787
 
1788
			List<Integer> catalogIds = itemRepository
1789
					.selectItems(FocusedModel.class, "catalogItemId", "catalogId", equalsMap, notEqualsMap,
1790
							equalsJoinMap, notEqualsJoinMap, "minimumQty")
1791
					.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
1792
 
1793
			Map<Integer, Integer> focusedCatalogIdAndQtyMap = focusedModelRepository.selectByCatalogIdsl(catalogIds)
1794
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getMinimumQty()));
1795
 
1796
			/*
1797
			 * Map<Integer, Integer> focusedCatalogIdAndQtyMap =
1798
			 * focusedModelRepository.selectAll().stream() .collect(Collectors.toMap(x ->
1799
			 * x.getCatalogId(), x -> x.getMinimumQty()));
1800
			 */
1801
 
25721 tejbeer 1802
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
1803
 
1804
			for (Map.Entry<Integer, Integer> entry : focusedCatalogIdAndQtyMap.entrySet()) {
1805
				int inStockQty = 0;
1806
				int processingQty = 0;
1807
				int grnPendingQty = 0;
1808
				if (processingOrderMap != null) {
1809
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
1810
							: processingOrderMap.get(entry.getKey());
1811
 
1812
				}
1813
				if (grnPendingOrdersMap != null) {
1814
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
1815
							: grnPendingOrdersMap.get(entry.getKey());
1816
 
1817
				}
1818
				if (catalogIdAndQtyMap != null) {
1819
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
1820
							: catalogIdAndQtyMap.get(entry.getKey());
1821
 
1822
				}
1823
				int totalQty = processingQty + grnPendingQty + inStockQty;
1824
 
1825
				if (totalQty < entry.getValue()) {
1826
 
1827
					int shortageQty = entry.getValue() - totalQty;
1828
					List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
1829
 
1830
					FocusedModelShortageModel fm = new FocusedModelShortageModel();
1831
					fm.setFofoId(fofoId);
1832
					fm.setStoreName(customRetailer.getBusinessName());
1833
 
1834
					fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
1835
					fm.setShortageQty(shortageQty);
1836
 
1837
					focusedModelShortageReportMap.get(fofoId).add(fm);
1838
				}
1839
 
1840
			}
1841
			List<FocusedModelShortageModel> focusedModelShortageModel = focusedModelShortageReportMap.get(fofoId);
1842
 
1843
			if (!focusedModelShortageModel.isEmpty()) {
1844
				String subject = "Stock Alert";
1845
				String messageText = this.getMessage(focusedModelShortageModel);
1846
 
25732 tejbeer 1847
				this.sendMailWithAttachments(subject, messageText, customRetailer.getEmail());
25721 tejbeer 1848
				String notificationMessage = this.getNotificationMessage(focusedModelShortageModel);
1849
 
1850
				LOGGER.info("notificationMessage" + notificationMessage);
1851
 
25872 tejbeer 1852
				SendNotificationModel sendNotificationModel = new SendNotificationModel();
1853
				sendNotificationModel.setCampaignName("Stock Alert");
1854
				sendNotificationModel.setTitle("Alert");
1855
				sendNotificationModel.setMessage(notificationMessage);
1856
				sendNotificationModel.setType("url");
1857
				sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
1858
				sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1859
				sendNotificationModel.setMessageType(MessageType.notification);
25732 tejbeer 1860
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
25872 tejbeer 1861
				sendNotificationModel.setUserIds(Arrays.asList(userId));
1862
				notificationService.sendNotification(sendNotificationModel);
25721 tejbeer 1863
 
1864
			}
25732 tejbeer 1865
 
25721 tejbeer 1866
		}
25800 tejbeer 1867
		if (!focusedModelShortageReportMap.isEmpty())
25721 tejbeer 1868
 
25800 tejbeer 1869
		{
1870
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
1871
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
25837 amit.gupta 1872
			Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 1873
 
25800 tejbeer 1874
			focusedModelShortageReportMap.entrySet().forEach(x -> {
1875
				storeGuyMap.entrySet().forEach(y -> {
1876
 
1877
					if (y.getValue().contains(x.getKey())) {
1878
						if (!emailRowsMap.containsKey(y.getKey())) {
1879
							emailRowsMap.put(y.getKey(), new ArrayList<>());
1880
						}
1881
						List<List<? extends Serializable>> fms = x.getValue().stream().map(r -> Arrays
1882
								.asList(r.getFofoId(), r.getStoreName(), r.getItemName(), r.getShortageQty()))
1883
								.collect(Collectors.toList());
1884
						emailRowsMap.get(y.getKey()).addAll(fms);
1885
 
25721 tejbeer 1886
					}
1887
 
25800 tejbeer 1888
				});
25721 tejbeer 1889
 
1890
			});
1891
 
25800 tejbeer 1892
			List<String> headers = Arrays.asList("Partner Id", "Partner Name", "Model Name", "Shortage Qty");
25837 amit.gupta 1893
			emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 1894
 
25800 tejbeer 1895
				ByteArrayOutputStream baos = null;
1896
				try {
25837 amit.gupta 1897
					baos = FileUtil.getCSVByteStream(headers, entry.getValue());
25800 tejbeer 1898
				} catch (Exception e2) {
1899
					e2.printStackTrace();
1900
				}
25837 amit.gupta 1901
				String[] sendToArray = new String[] { entry.getKey() };
25800 tejbeer 1902
				try {
1903
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
1904
							new ByteArrayResource(baos.toByteArray()));
1905
				} catch (Exception e1) { // TODO Auto-generated catch block
1906
					e1.printStackTrace();
1907
				}
25721 tejbeer 1908
 
25800 tejbeer 1909
			});
1910
		}
25721 tejbeer 1911
	}
1912
 
1913
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1914
		StringBuilder sb = new StringBuilder();
1915
		sb.append("Focused Model Shortage in Your Stock : \n");
1916
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1917
 
1918
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
1919
			sb.append(String.format("%n", ""));
1920
		}
1921
		return sb.toString();
1922
	}
1923
 
1924
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
1925
		MimeMessage message = mailSender.createMimeMessage();
1926
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
1927
 
1928
		helper.setSubject(subject);
1929
		helper.setText(messageText, true);
1930
		helper.setTo(email);
26032 amit.gupta 1931
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smatdukaan Alerts");
25721 tejbeer 1932
		helper.setFrom(senderAddress);
1933
		mailSender.send(message);
1934
 
1935
	}
1936
 
1937
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
1938
		StringBuilder sb = new StringBuilder();
1939
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
1940
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
1941
		sb.append("<tbody>\n" + "	    				<tr>\n"
1942
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
1943
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
1944
				+ "	    				</tr>");
1945
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
1946
 
1947
			sb.append("<tr>");
1948
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
1949
 
1950
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
1951
 
1952
			sb.append("</tr>");
1953
 
1954
		}
1955
 
1956
		sb.append("</tbody></table></body></html>");
1957
 
1958
		return sb.toString();
1959
	}
1960
 
25927 amit.gupta 1961
	public void notifyLead() throws Exception {
1962
		List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(LocalDateTime.now().minusDays(15),
1963
				LocalDateTime.now().plusHours(4));
1964
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
1965
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
25936 amit.gupta 1966
		System.out.printf("authUserEmailMap - %s", authUserEmailMap);
25927 amit.gupta 1967
		Map<String, Integer> dtrEmailMap = dtrUserRepository
1968
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
1969
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25936 amit.gupta 1970
 
1971
		System.out.printf("dtrEmailMap - %s", dtrEmailMap);
1972
 
25927 amit.gupta 1973
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
1974
 
1975
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
1976
			int authId = authUserEmail.getKey();
1977
			String email = authUserEmail.getValue();
1978
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
1979
		}
25929 amit.gupta 1980
		System.out.println(authUserKeyMap);
1981
		System.out.println(leadsToNotify);
1982
 
25927 amit.gupta 1983
		String templateMessage = "Lead followup for %s %s, %s is due by %s";
1984
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
1985
		for (Lead lead : leadsToNotify) {
1986
			if (authUserKeyMap.get(lead.getAuthId()) == null) {
1987
				continue;
1988
			}
1989
			String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(),
25941 amit.gupta 1990
					lead.getAddress(), timeFormatter.format(lead.getLeadActivity().getSchelduleTimestamp()));
25927 amit.gupta 1991
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1992
			sendNotificationModel.setCampaignName("Lead Reminder");
1993
			sendNotificationModel.setTitle("Leads followup Reminder");
1994
			sendNotificationModel.setMessage(notificationMessage);
1995
			sendNotificationModel.setType("url");
1996
			sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
1997
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1998
			sendNotificationModel.setMessageType(MessageType.reminder);
1999
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAuthId())));
25929 amit.gupta 2000
			System.out.println(sendNotificationModel);
25927 amit.gupta 2001
			notificationService.sendNotification(sendNotificationModel);
2002
		}
2003
	}
2004
	public void notifyVisits() throws Exception {
2005
		List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), 
2006
				LocalDateTime.now().plusHours(4));
2007
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2008
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
2009
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2010
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2011
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
2012
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
25910 amit.gupta 2013
 
25927 amit.gupta 2014
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2015
			int authId = authUserEmail.getKey();
2016
			String email = authUserEmail.getValue();
2017
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2018
		}
2019
		String visitTemplate = "Planned visit to franchisee %s is due by %s";
2020
		String followupTemplate = "Lead followup for franchisee %s is due by %s";
2021
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
2022
		for (FranchiseeVisit visit : franchiseeVisits) {
2023
			if (authUserKeyMap.containsKey(visit.getAuthId())) {
2024
				continue;
2025
			}
2026
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2027
			String message = null;
2028
			if(visit.getFranchiseActivityId()==0) {
2029
				 message = String.format(visitTemplate, visit.getPartnerName(), timeFormatter.format(visit.getSchelduleTimestamp()));
2030
				 sendNotificationModel.setCampaignName("Franchisee visit Reminder");
2031
			} else {
2032
				message = String.format(followupTemplate, visit.getPartnerName(), timeFormatter.format(visit.getSchelduleTimestamp()));
2033
				sendNotificationModel.setCampaignName("Franchisee followup Reminder");
2034
			}
2035
			sendNotificationModel.setMessage(message);
2036
			sendNotificationModel.setType("url");
2037
			sendNotificationModel.setUrl("http://app.profitmandi.com/pages/home/notifications");
2038
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2039
			sendNotificationModel.setMessageType(MessageType.reminder);
2040
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
2041
			notificationService.sendNotification(sendNotificationModel);
2042
		}
25910 amit.gupta 2043
	}
25927 amit.gupta 2044
 
25982 amit.gupta 2045
	public AddPaymentResponse addPayment(AddPaymentRequest addPaymentRequest) throws Exception {
2046
		HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByTransactionId(addPaymentRequest.getTransactionId());
2047
		AddPaymentResponse response = new AddPaymentResponse();
2048
		if (hdfcPayment == null) {
2049
			hdfcPayment = new HdfcPayment();
2050
			hdfcPayment.setAmount(addPaymentRequest.getAmount());
2051
			hdfcPayment.setCreateTimestamp(LocalDateTime.now());
2052
			hdfcPayment.setCreditTimestamp(addPaymentRequest.getCreditDateTime());
2053
			hdfcPayment.setFromAccountNumber(addPaymentRequest.getFromAccountNumber());
2054
			hdfcPayment.setFromBankName(addPaymentRequest.getFromBankName());
2055
			hdfcPayment.setMmid(addPaymentRequest.getMmid());
2056
			hdfcPayment.setRemitterName(addPaymentRequest.getRemitterName());
2057
			hdfcPayment.setTransactionId(addPaymentRequest.getTransactionId());
2058
			hdfcPayment.setTransferMode(addPaymentRequest.getTransferMode());
2059
			hdfcPayment.setUtr(addPaymentRequest.getUtr());
2060
			hdfcPayment.setVirtualAccount(hdfcPayment.getVirtualAccount());
2061
			hdfcPaymentRepository.persist(hdfcPayment);
2062
			String virtualAccount = hdfcPayment.getVirtualAccount();
2063
			String retailerIdString = virtualAccount.substring(6);
2064
			int retailerId = Integer.parseInt(retailerIdString);
2065
			String description = String.format("Paid through %s, Utr# %s", hdfcPayment.getTransferMode(),
2066
					hdfcPayment.getUtr());
2067
			walletService.addAmountToWallet(retailerId, hdfcPayment.getId(), WalletReferenceType.ADVANCE_AMOUNT,
2068
					description, (float) hdfcPayment.getAmount());
2069
			response.setCode("100");
2070
			response.setStatus("Success");
2071
		} else {
2072
			response.setCode("200");
2073
			response.setStatus("Duplicate");
2074
		}
2075
		response.setTransactionId("");
2076
 
2077
		return response;
2078
	}
25927 amit.gupta 2079
 
25982 amit.gupta 2080
 
25910 amit.gupta 2081
 
25721 tejbeer 2082
}