Subversion Repositories SmartDukaan

Rev

Rev 31118 | Rev 31123 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
28217 tejbeer 1
package com.smartdukaan.cron.scheduled;
23723 amit.gupta 2
 
31020 tejbeer 3
import java.io.FileOutputStream;
4
import java.io.IOException;
5
import java.io.ObjectOutputStream;
6
import java.io.Serializable;
7
import java.io.UnsupportedEncodingException;
8
import java.math.BigDecimal;
9
import java.math.RoundingMode;
10
import java.nio.file.Files;
11
import java.nio.file.Paths;
12
import java.sql.Timestamp;
13
import java.text.DecimalFormat;
14
import java.time.Duration;
15
import java.time.LocalDate;
16
import java.time.LocalDateTime;
17
import java.time.LocalTime;
18
import java.time.Month;
19
import java.time.YearMonth;
20
import java.time.format.DateTimeFormatter;
21
import java.time.temporal.ChronoField;
22
import java.time.temporal.ChronoUnit;
23
import java.util.ArrayList;
24
import java.util.Arrays;
25
import java.util.Base64;
26
import java.util.Collections;
27
import java.util.Comparator;
28
import java.util.HashMap;
29
import java.util.HashSet;
30
import java.util.LinkedHashMap;
31
import java.util.List;
32
import java.util.Map;
33
import java.util.Map.Entry;
34
import java.util.Optional;
35
import java.util.Set;
36
import java.util.stream.Collectors;
37
 
38
import javax.mail.MessagingException;
39
import javax.mail.internet.InternetAddress;
40
import javax.mail.internet.MimeMessage;
41
 
42
import org.apache.commons.io.output.ByteArrayOutputStream;
43
import org.apache.commons.lang.StringUtils;
44
import org.apache.http.client.methods.CloseableHttpResponse;
45
import org.apache.http.client.methods.HttpPost;
46
import org.apache.http.conn.HttpHostConnectException;
47
import org.apache.http.entity.StringEntity;
48
import org.apache.http.impl.client.CloseableHttpClient;
49
import org.apache.http.impl.client.HttpClients;
50
import org.apache.logging.log4j.LogManager;
51
import org.apache.logging.log4j.Logger;
52
import org.json.JSONArray;
53
import org.json.JSONObject;
31117 tejbeer 54
import org.json.XML;
31020 tejbeer 55
import org.springframework.beans.factory.annotation.Autowired;
56
import org.springframework.beans.factory.annotation.Qualifier;
57
import org.springframework.beans.factory.annotation.Value;
58
import org.springframework.core.io.ByteArrayResource;
59
import org.springframework.core.io.InputStreamSource;
60
import org.springframework.mail.javamail.JavaMailSender;
61
import org.springframework.mail.javamail.MimeMessageHelper;
62
import org.springframework.stereotype.Component;
63
import org.springframework.transaction.annotation.Transactional;
64
 
24542 amit.gupta 65
import com.google.common.collect.Lists;
25300 tejbeer 66
import com.google.gson.Gson;
29488 manish 67
import com.razorpay.Payment;
68
import com.smartdukaan.cron.itelImeiActivation.ItelImeiActivationService;
69
import com.smartdukaan.cron.itelImeiActivation.TecnoImeiActivation;
25721 tejbeer 70
import com.spice.profitmandi.common.enumuration.MessageType;
23724 amit.gupta 71
import com.spice.profitmandi.common.enumuration.RechargeStatus;
24681 amit.gupta 72
import com.spice.profitmandi.common.enumuration.ReporticoProject;
24121 govind 73
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
31020 tejbeer 74
import com.spice.profitmandi.common.model.CustomRetailer;
75
import com.spice.profitmandi.common.model.FocusedModelShortageModel;
76
import com.spice.profitmandi.common.model.GstRate;
77
import com.spice.profitmandi.common.model.InvoicePdfModel;
78
import com.spice.profitmandi.common.model.ProfitMandiConstants;
79
import com.spice.profitmandi.common.model.RechargeCredential;
80
import com.spice.profitmandi.common.model.SendNotificationModel;
24681 amit.gupta 81
import com.spice.profitmandi.common.services.ReporticoService;
29814 tejbeer 82
import com.spice.profitmandi.common.services.mandii.AccountStatusResponseOut;
83
import com.spice.profitmandi.common.services.mandii.EligibilityStatusEnum;
84
import com.spice.profitmandi.common.services.mandii.MandiiService;
24002 amit.gupta 85
import com.spice.profitmandi.common.util.FileUtil;
23929 amit.gupta 86
import com.spice.profitmandi.common.util.FormattingUtils;
27678 amit.gupta 87
import com.spice.profitmandi.common.util.PdfUtils;
23929 amit.gupta 88
import com.spice.profitmandi.common.util.Utils;
24592 amit.gupta 89
import com.spice.profitmandi.common.util.Utils.Attachment;
29308 tejbeer 90
import com.spice.profitmandi.common.web.client.RestClient;
25300 tejbeer 91
import com.spice.profitmandi.dao.Interface.Campaign;
25590 amit.gupta 92
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30421 tejbeer 93
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionRemark;
25800 tejbeer 94
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
25609 amit.gupta 95
import com.spice.profitmandi.dao.entity.catalog.Item;
24590 amit.gupta 96
import com.spice.profitmandi.dao.entity.catalog.Scheme;
25590 amit.gupta 97
import com.spice.profitmandi.dao.entity.cs.Position;
26283 tejbeer 98
import com.spice.profitmandi.dao.entity.cs.Ticket;
31020 tejbeer 99
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
100
import com.spice.profitmandi.dao.entity.dtr.CreditStatus;
101
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
102
import com.spice.profitmandi.dao.entity.dtr.EmployeeAttendance;
103
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
104
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
105
import com.spice.profitmandi.dao.entity.dtr.PushNotifications;
106
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
107
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
108
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
28769 amit.gupta 109
import com.spice.profitmandi.dao.entity.dtr.User;
31020 tejbeer 110
import com.spice.profitmandi.dao.entity.fofo.ActivityType;
111
import com.spice.profitmandi.dao.entity.fofo.CurrentPartnerDailyInvestment;
112
import com.spice.profitmandi.dao.entity.fofo.Customer;
113
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
114
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
115
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
116
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
117
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
118
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
119
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
120
import com.spice.profitmandi.dao.entity.fofo.PartnerProblem;
121
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
122
import com.spice.profitmandi.dao.entity.fofo.PendingOrder;
123
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
124
import com.spice.profitmandi.dao.entity.fofo.Purchase;
125
import com.spice.profitmandi.dao.entity.fofo.RazorPay;
126
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
127
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
30390 amit.gupta 128
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
27208 tejbeer 129
import com.spice.profitmandi.dao.entity.inventory.SaholicCIS;
130
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
31020 tejbeer 131
import com.spice.profitmandi.dao.entity.transaction.Loan;
132
import com.spice.profitmandi.dao.entity.transaction.LoanStatement;
133
import com.spice.profitmandi.dao.entity.transaction.Order;
134
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
135
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
136
import com.spice.profitmandi.dao.entity.transaction.SDCreditRequirement;
137
import com.spice.profitmandi.dao.entity.transaction.SanctionRequest;
138
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
139
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
140
import com.spice.profitmandi.dao.entity.user.Address;
141
import com.spice.profitmandi.dao.entity.user.Device;
142
import com.spice.profitmandi.dao.entity.user.FranchiseeVisit;
143
import com.spice.profitmandi.dao.entity.user.Lead;
144
import com.spice.profitmandi.dao.entity.user.Refferal;
30421 tejbeer 145
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
24250 amit.gupta 146
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25598 amit.gupta 147
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26790 tejbeer 148
import com.spice.profitmandi.dao.enumuration.dtr.RefferalStatus;
29814 tejbeer 149
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
24242 amit.gupta 150
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
30913 tejbeer 151
import com.spice.profitmandi.dao.enumuration.transaction.CreditRisk;
30859 tejbeer 152
import com.spice.profitmandi.dao.enumuration.transaction.LoanReferenceType;
25609 amit.gupta 153
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
30390 amit.gupta 154
import com.spice.profitmandi.dao.model.PartnerDetailModel;
25300 tejbeer 155
import com.spice.profitmandi.dao.model.SimpleCampaign;
156
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
25590 amit.gupta 157
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
30421 tejbeer 158
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionRemarkRepository;
31020 tejbeer 159
import com.spice.profitmandi.dao.repository.catalog.DeviceRepository;
160
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
161
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
162
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
163
import com.spice.profitmandi.dao.repository.catalog.StateGstRateRepository;
164
import com.spice.profitmandi.dao.repository.cs.CsService;
165
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
166
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
167
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
168
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
169
import com.spice.profitmandi.dao.repository.dtr.CreditAccountRepository;
170
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
171
import com.spice.profitmandi.dao.repository.dtr.EmployeeAttendanceRepository;
172
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
173
import com.spice.profitmandi.dao.repository.dtr.FranchiseeActivityRepository;
174
import com.spice.profitmandi.dao.repository.dtr.FranchiseeVisitRepository;
175
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
176
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
177
import com.spice.profitmandi.dao.repository.dtr.Mongo;
178
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
179
import com.spice.profitmandi.dao.repository.dtr.PartnerProblemRepository;
180
import com.spice.profitmandi.dao.repository.dtr.PushNotificationRepository;
181
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
182
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
183
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
184
import com.spice.profitmandi.dao.repository.dtr.RefferalRepository;
185
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
186
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
187
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
188
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
189
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
190
import com.spice.profitmandi.dao.repository.fofo.CurrentPartnerDailyInvestmentRepository;
191
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
192
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
193
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
194
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
195
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
196
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
197
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
198
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
199
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
200
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
201
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
202
import com.spice.profitmandi.dao.repository.fofo.PendingOrderRepository;
203
import com.spice.profitmandi.dao.repository.fofo.PendingOrderService;
204
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
205
import com.spice.profitmandi.dao.repository.fofo.RazorPayRepository;
206
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
207
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
208
import com.spice.profitmandi.dao.repository.fofo.ServiceConfigRepository;
30390 amit.gupta 209
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
28990 amit.gupta 210
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
28775 amit.gupta 211
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
31020 tejbeer 212
import com.spice.profitmandi.dao.repository.transaction.HdfcPaymentRepository;
213
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
214
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
215
import com.spice.profitmandi.dao.repository.transaction.LoanStatementRepository;
216
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
217
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
218
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
219
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
220
import com.spice.profitmandi.dao.repository.transaction.SanctionRequestRepository;
221
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
222
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
223
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
24542 amit.gupta 224
import com.spice.profitmandi.dao.repository.user.AddressRepository;
25721 tejbeer 225
import com.spice.profitmandi.dao.repository.user.UserRepository;
25854 amit.gupta 226
import com.spice.profitmandi.service.NotificationService;
24337 amit.gupta 227
import com.spice.profitmandi.service.PartnerInvestmentService;
30390 amit.gupta 228
import com.spice.profitmandi.service.PartnerStatsService;
28368 tejbeer 229
import com.spice.profitmandi.service.integrations.RazorpayPaymentService;
30858 amit.gupta 230
import com.spice.profitmandi.service.integrations.bharti.model.BAGInsuranceModel;
25694 amit.gupta 231
import com.spice.profitmandi.service.integrations.toffee.ToffeeService;
23929 amit.gupta 232
import com.spice.profitmandi.service.inventory.InventoryService;
27208 tejbeer 233
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
25335 amit.gupta 234
import com.spice.profitmandi.service.order.OrderService;
24431 amit.gupta 235
import com.spice.profitmandi.service.pricing.PriceDropService;
23724 amit.gupta 236
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
237
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
238
import com.spice.profitmandi.service.scheme.SchemeService;
29668 tejbeer 239
import com.spice.profitmandi.service.serviceConfig.ServiceConfigService;
31008 amit.gupta 240
import com.spice.profitmandi.service.transaction.CreditNoteService;
30859 tejbeer 241
import com.spice.profitmandi.service.transaction.SDCreditService;
23929 amit.gupta 242
import com.spice.profitmandi.service.transaction.TransactionService;
243
import com.spice.profitmandi.service.user.RetailerService;
23739 amit.gupta 244
import com.spice.profitmandi.service.wallet.WalletService;
31020 tejbeer 245
 
25721 tejbeer 246
import in.shop2020.model.v1.order.OrderStatus;
29308 tejbeer 247
import in.shop2020.model.v1.order.WalletReferenceType;
248
import okhttp3.OkHttpClient;
249
import okhttp3.Request;
30119 amit.gupta 250
import okhttp3.Response;
23739 amit.gupta 251
 
23723 amit.gupta 252
@Component
23724 amit.gupta 253
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 254
public class ScheduledTasks {
255
 
23724 amit.gupta 256
	@Value("${oxigen.recharge.transaction.url}")
257
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 258
 
23724 amit.gupta 259
	@Value("${oxigen.recharge.enquiry.url}")
260
	private String oxigenRechargeEnquiryUrl;
24533 govind 261
 
24431 amit.gupta 262
	@Autowired
27088 tejbeer 263
	private RegionRepository regionRepository;
29668 tejbeer 264
 
29488 manish 265
	@Autowired
29801 manish 266
	private ServiceConfigService serviceConfigService;
267
 
268
	@Autowired
29488 manish 269
	private TecnoImeiActivation tecnoImeiActivation;
28205 tejbeer 270
 
27795 amit.gupta 271
	private static final DateTimeFormatter leadTimeFormatter = DateTimeFormatter.ofPattern("d LLL, hh:mm a");
27088 tejbeer 272
 
273
	@Autowired
274
	private PartnerRegionRepository partnerRegionRepository;
28790 amit.gupta 275
 
28769 amit.gupta 276
	@Autowired
277
	private EmployeeAttendanceRepository employeeAttendanceRepository;
27088 tejbeer 278
 
279
	@Autowired
29451 manish 280
	VivoImeiActivationService vivoImeiActivationService;
29488 manish 281
 
29451 manish 282
	@Autowired
29488 manish 283
	ItelImeiActivationService itelImeiActivationService;
284
 
285
	@Autowired
25503 amit.gupta 286
	private PartnerTypeChangeService partnerTypeChangeService;
25598 amit.gupta 287
 
25590 amit.gupta 288
	@Autowired
26408 amit.gupta 289
	private ActivatedImeiRepository activatedImeiRepository;
290
 
291
	@Autowired
29451 manish 292
	private LineItemRepository lineItemRepository;
293
 
294
	@Autowired
25910 amit.gupta 295
	private LeadRepository leadRepository;
25927 amit.gupta 296
 
25910 amit.gupta 297
	@Autowired
25590 amit.gupta 298
	private AuthRepository authRepository;
25503 amit.gupta 299
 
300
	@Autowired
24431 amit.gupta 301
	private PriceDropService priceDropService;
26283 tejbeer 302
 
25590 amit.gupta 303
	@Autowired
25927 amit.gupta 304
	private FranchiseeVisitRepository franchiseeVisitRepository;
26790 tejbeer 305
 
25927 amit.gupta 306
	@Autowired
307
	private FranchiseeActivityRepository franchiseeActivityRepository;
26790 tejbeer 308
 
25927 amit.gupta 309
	@Autowired
25982 amit.gupta 310
	private HdfcPaymentRepository hdfcPaymentRepository;
26790 tejbeer 311
 
25982 amit.gupta 312
	@Autowired
25590 amit.gupta 313
	private CsService csService;
25846 amit.gupta 314
 
25837 amit.gupta 315
	@Autowired
27208 tejbeer 316
	private SaholicInventoryService saholicInventoryService;
317
 
318
	@Autowired
25837 amit.gupta 319
	private InsurancePolicyRepository insurancePolicyRepository;
23723 amit.gupta 320
 
25694 amit.gupta 321
	@Autowired
322
	private ToffeeService toffeeService;
323
 
23724 amit.gupta 324
	@Value("${oxigen.recharge.auth.key}")
325
	private String oxigenRechargeAuthKey;
326
 
327
	@Value("${oxigen.recharge.validation.url}")
328
	private String oxigenRechargeValidationUrl;
329
 
330
	@Value("${oxigen.recharge.validation.auth.key}")
331
	private String oxigenRechargeValidationAuthKey;
332
 
333
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
334
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
335
 
336
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
337
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
338
 
339
	@Value("${think.walnut.digital.recharge.enquiry.url}")
340
	private String thinkWalnutDigitalRechargeEnquiryUrl;
341
 
342
	@Value("${think.walnut.digital.recharge.balance.url}")
343
	private String thinkWalnutDigitalRechargeBalanceUrl;
344
 
345
	@Value("${think.walnut.digital.recharge.username}")
346
	private String thinkWalnutDigitalRechargeUserName;
347
 
348
	@Value("${think.walnut.digital.recharge.password}")
349
	private String thinkWalnutDigitalRechargePassword;
350
 
351
	@Value("${think.walnut.digital.recharge.auth.key}")
352
	private String thinkWalnutDigitalRechargeAuthKey;
353
 
23723 amit.gupta 354
	@Autowired
23724 amit.gupta 355
	private PurchaseRepository purchaseRepository;
356
 
357
	@Autowired
25609 amit.gupta 358
	private PriceDropIMEIRepository priceDropIMEIRepository;
359
 
360
	@Autowired
361
	PriceDropRepository priceDropRepository;
362
 
363
	@Autowired
27086 tejbeer 364
	private PartnerTypeChangeRepository partnerTypeChangeRepository;
28368 tejbeer 365
 
27086 tejbeer 366
	@Autowired
23724 amit.gupta 367
	private SchemeService schemeService;
24683 amit.gupta 368
 
29668 tejbeer 369
	@Autowired
370
	private ServiceConfigRepository serviceConfigRepository;
371
 
29308 tejbeer 372
	@Value("${delhivery.tracking.token}")
373
	private String token;
374
 
30752 tejbeer 375
	private static final String[] STOCK_AGEING_MAIL_LIST = new String[] { "uday.singh@smartudkaan.com",
29160 amit.gupta 376
			"mohinder.mutreja@smartdukaan.com", "ankit.bhatia@smartdukaan.com", "tarun.verma@smartdukaan.com",
30752 tejbeer 377
			"kuldeep.kumar@smartdukaan.com", "manish.gupta@smartdukaan.com" };
25609 amit.gupta 378
 
30752 tejbeer 379
	private static final String[] ITEMWISE_PENDING_INDENT_MAIL_LIST = new String[] { "kamini.sharma@smartdukaan.com",
28205 tejbeer 380
			"tarun.verma@smartdukaan.com", "uday.singh@smartdukaan.com", "kuldeep.kumar@smartdukaan.com",
30752 tejbeer 381
			"niranjan.kala@smartdukaan.com" };
25609 amit.gupta 382
 
30752 tejbeer 383
	private static final String[] INDENT_TERTIARY_MAIL_LIST = new String[] { "uday.singh@smartdukaan.com",
384
			"kuldeep.kumar@smartdukaan.com" };
28709 amit.gupta 385
 
30752 tejbeer 386
	private static final String[] EMPLOYEE_ATTENDANCE_MAIL_LIST = new String[] { "sm@smartdukaan.com",
387
			"sm@smartdukaan.com" };
28790 amit.gupta 388
 
25721 tejbeer 389
	private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING);
390
 
24681 amit.gupta 391
	@Autowired
392
	private ReporticoService reporticoService;
23724 amit.gupta 393
 
394
	@Autowired
24337 amit.gupta 395
	private PartnerInvestmentService partnerInvestmentService;
25598 amit.gupta 396
 
25590 amit.gupta 397
	@Autowired
398
	private PositionRepository positionRepository;
24337 amit.gupta 399
 
400
	@Autowired
24542 amit.gupta 401
	private FofoOrderItemRepository fofoOrderItemRepository;
25865 amit.gupta 402
 
25854 amit.gupta 403
	@Autowired
404
	private NotificationService notificationService;
24542 amit.gupta 405
 
406
	@Autowired
24277 amit.gupta 407
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
408
 
409
	@Autowired
24241 amit.gupta 410
	private SchemeInOutRepository schemeInOutRepository;
411
 
412
	@Autowired
23724 amit.gupta 413
	private RechargeTransactionRepository rechargeTransactionRepository;
414
 
415
	@Autowired
24542 amit.gupta 416
	private CustomerAddressRepository customerAddressRepository;
417
 
418
	@Autowired
23724 amit.gupta 419
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
420
 
421
	@Autowired
24590 amit.gupta 422
	private FofoLineItemRepository fofoLineItemRepository;
423
 
424
	@Autowired
23724 amit.gupta 425
	private FofoOrderRepository fofoOrderRepository;
24587 amit.gupta 426
 
24580 amit.gupta 427
	@Autowired
428
	private UserWalletHistoryRepository userWalletHistoryRepository;
24250 amit.gupta 429
 
24249 amit.gupta 430
	@Autowired
24587 amit.gupta 431
	private UserWalletRepository userWalletRepository;
432
 
433
	@Autowired
24249 amit.gupta 434
	private InventoryItemRepository inventoryItemRepository;
23929 amit.gupta 435
 
23739 amit.gupta 436
	@Autowired
437
	private WalletService walletService;
23724 amit.gupta 438
 
439
	@Autowired
440
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
441
 
442
	@Autowired
443
	private OxigenRechargeProviderService oxigenRechargeProviderService;
444
 
445
	@Autowired
446
	private RechargeProviderRepository rechargeProviderRepository;
447
 
448
	@Autowired
24242 amit.gupta 449
	private ScanRecordRepository scanRecordRepository;
450
 
451
	@Autowired
23724 amit.gupta 452
	private DailyRechargeRepository dailyRechargeRepository;
453
 
23929 amit.gupta 454
	@Autowired
455
	private FofoStoreRepository fofoStoreRepository;
24177 govind 456
 
23724 amit.gupta 457
	@Value("${prod}")
458
	private boolean prod;
26945 amit.gupta 459
 
26929 amit.gupta 460
	@Autowired
461
	private StateGstRateRepository stateGstRateRepository;
23724 amit.gupta 462
 
23929 amit.gupta 463
	@Autowired
464
	private RetailerService retailerService;
465
 
466
	@Autowired
467
	private TransactionService transactionService;
24250 amit.gupta 468
 
24249 amit.gupta 469
	@Autowired
470
	private ItemRepository itemRepository;
23929 amit.gupta 471
 
472
	@Autowired
473
	private OrderRepository orderRepository;
25351 tejbeer 474
 
25335 amit.gupta 475
	@Autowired
476
	private OrderService orderService;
23929 amit.gupta 477
 
478
	@Autowired
24241 amit.gupta 479
	private SchemeRepository schemeRepository;
480
 
481
	@Autowired
23929 amit.gupta 482
	private JavaMailSender mailSender;
24177 govind 483
 
24174 govind 484
	@Autowired
485
	private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 486
 
487
	@Autowired
488
	@Qualifier(value = "googleMailSender")
23932 amit.gupta 489
	private JavaMailSender googleMailSender;
23929 amit.gupta 490
 
491
	@Autowired
492
	private InventoryService inventoryService;
493
 
24533 govind 494
	@Autowired
24542 amit.gupta 495
	private AddressRepository addressRepository;
496
 
497
	@Autowired
498
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
499
 
24653 govind 500
	@Autowired
501
	private Mongo mongoClient;
24683 amit.gupta 502
 
24669 govind 503
	@Autowired
25300 tejbeer 504
	private DeviceRepository deviceRepository;
505
 
506
	@Autowired
507
	private PushNotificationRepository pushNotificationRepository;
508
 
509
	@Autowired
510
	private NotificationCampaignRepository notificationCampaignRepository;
511
 
512
	@Autowired
25721 tejbeer 513
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
514
 
515
	@Autowired
516
	private FocusedModelRepository focusedModelRepository;
517
 
518
	@Autowired
24669 govind 519
	private UserAccountRepository userAccountRepository;
24653 govind 520
 
25721 tejbeer 521
	@Autowired
25927 amit.gupta 522
	private UserRepository userUserRepository;
25721 tejbeer 523
 
524
	@Autowired
25927 amit.gupta 525
	private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
526
 
527
	@Autowired
25721 tejbeer 528
	private UserCampaignRepository userCampaignRepository;
529
 
530
	@Autowired
531
	private Gson gson;
532
 
26283 tejbeer 533
	@Autowired
534
	private TicketRepository ticketRepository;
535
 
26790 tejbeer 536
	@Autowired
537
	private RefferalRepository refferalRepository;
538
 
28205 tejbeer 539
	@Autowired
540
	private PartnerProblemRepository partnerProblemRepository;
541
 
28368 tejbeer 542
	@Autowired
543
	private PendingOrderRepository pendingOrderRepository;
544
 
545
	@Autowired
546
	private PendingOrderItemRepository pendingOrderItemRepository;
547
 
548
	@Value("${razorpay.account.keyId}")
549
	private String keyId;
550
 
551
	@Value("${razorpay.account.keySecret}")
552
	private String keySecret;
553
 
28369 tejbeer 554
	@Autowired
555
	private RazorpayPaymentService razorPaymentService;
556
 
557
	@Autowired
558
	private RazorPayRepository razorPayRepository;
559
 
28377 tejbeer 560
	@Autowired
561
	private PendingOrderService pendingOrderService;
562
 
563
	@Autowired
564
	private CustomerRepository customerRepository;
565
 
29308 tejbeer 566
	@Autowired
567
	private RestClient restClient;
568
 
29814 tejbeer 569
	@Autowired
570
	private MandiiService mandiiService;
571
 
572
	@Autowired
573
	CreditAccountRepository creditAccountRepository;
23755 amit.gupta 574
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 575
 
25300 tejbeer 576
	private String FCM_URL = "https://fcm.googleapis.com/fcm/send";
577
	private String FCM_API_KEY = "AAAASAjNcn4:APA91bG6fWRIgYJI0L9gCjP5ynaXz2hJHYKtD9dfH7Depdv31Nd9APJwhx-OPkAJ1WSz4BGNYG8lHThLFSjDGFxIwUZv241YcAJEGDLgt86mxq9FXJe-yBRu-S0_ZwHqmX-QaVKl5F_A";
578
 
23724 amit.gupta 579
	public void generateDailyRecharge() {
580
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
581
				.selectAll(0, 2000);
582
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
583
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
584
 
585
		rechargeProviders.stream().forEach(x -> {
586
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
587
					.stream().filter(z -> z.getProviderId() == x.getId())
588
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
589
 
29252 amit.gupta 590
			LOGGER.info("dateWiseProviderCreditsMap -{}", dateWiseProviderCreditsMap);
23724 amit.gupta 591
			LocalDate endDate = LocalDate.now().plusDays(1);
592
			float previousDayClosing = 0;
593
			LocalDate date = LocalDate.of(2018, 4, 6);
594
			while (date.isBefore(endDate)) {
595
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
596
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
597
								date.plusDays(1).atStartOfDay());
598
 
599
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
600
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
601
 
602
				float dailyAmount = 0;
603
				float totalCommission = 0;
604
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
605
					if (rechargeTransaction.getProviderId() == x.getId()) {
606
						dailyAmount += rechargeTransaction.getAmount();
607
						totalCommission += rechargeTransaction.getCommission();
608
					}
609
				}
610
 
611
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
612
				float dailyWalletRecharge = 0;
613
				if (rechargeHistoryList != null) {
614
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
615
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
616
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
617
						}
618
					}
619
				}
620
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
621
					DailyRecharge dailyRecharge = null;
622
					try {
623
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
624
					} catch (Exception e) {
625
						LOGGER.info("Could not find Recharge entry");
626
					}
627
					if (dailyRecharge == null) {
628
						dailyRecharge = new DailyRecharge();
629
						dailyRecharge.setCreateDate(date);
630
					}
631
					dailyRecharge.setOpeningBalance(previousDayClosing);
632
					dailyRecharge.setProviderId(x.getId());
633
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
634
					dailyRecharge.setTotalAmount(dailyAmount);
635
					dailyRecharge.setTotalCommission(totalCommission);
636
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
637
					dailyRecharge.setClosingBalance(closingBalance);
638
					dailyRechargeRepository.persist(dailyRecharge);
639
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
640
					previousDayClosing = dailyRecharge.getClosingBalance();
641
				}
642
				date = date.plusDays(1);
643
			}
644
			rechargeProviderRepository.persist(x);
645
		});
23761 amit.gupta 646
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 647
	}
648
 
23738 amit.gupta 649
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 650
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
651
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
652
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
653
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
654
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
655
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
656
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
657
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
658
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
659
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
660
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
661
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
662
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
663
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
664
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
665
			try {
666
				int providerId = rechargeTransaction.getProviderId();
667
				if (providerId == 1) {
668
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
669
							rechargeTransaction);
670
				} else if (providerId == 2) {
671
					thinkWalnutDigitalRechargeProviderService
672
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
673
				}
674
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
675
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
676
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
677
							rechargeTransaction.getStatus());
678
				}
679
			} catch (Exception e) {
680
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
681
			}
682
		}
23738 amit.gupta 683
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 684
	}
28205 tejbeer 685
 
27438 amit.gupta 686
	public void processActivation() throws Exception {
687
		schemeService.processActivation();
688
	}
24240 amit.gupta 689
 
690
	// TemporaryMethod
24237 amit.gupta 691
	public void migrateInvoice() {
692
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
693
		Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
24241 amit.gupta 694
		partnerOrdersMap = fofoOrders.stream()
695
				.collect(Collectors.groupingBy(FofoOrder::getFofoId, Collectors.toList()));
24237 amit.gupta 696
		for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
24240 amit.gupta 697
			int sequence = 0;
698
			String prefix = "";
24241 amit.gupta 699
			List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId())
700
					.collect(Collectors.toList());
701
			for (FofoOrder order : sortedList) {
702
 
24240 amit.gupta 703
				LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
24241 amit.gupta 704
				if (!order.getInvoiceNumber().contains("SEC")) {
24240 amit.gupta 705
					sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
706
					prefix = order.getInvoiceNumber().split("/")[0];
707
				} else {
708
					sequence += 1;
24241 amit.gupta 709
					String invoiceNumber = prefix + "/" + sequence;
24240 amit.gupta 710
					order.setInvoiceNumber(invoiceNumber);
711
					fofoOrderRepository.persist(order);
712
				}
713
			}
24241 amit.gupta 714
 
24237 amit.gupta 715
		}
716
	}
23724 amit.gupta 717
 
30393 amit.gupta 718
	@Autowired
719
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
24252 amit.gupta 720
 
25584 amit.gupta 721
	public void processScheme(int offset, boolean dryRun) throws Exception {
24462 amit.gupta 722
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24259 amit.gupta 723
		LocalDateTime endDate = startDate.plusDays(30);
25584 amit.gupta 724
		processScheme(startDate, endDate, dryRun);
24256 amit.gupta 725
	}
28205 tejbeer 726
 
27892 amit.gupta 727
	public void processSchemeOut(List<String> invoiceNumbers) throws Exception {
28205 tejbeer 728
		for (String invoiceNumber : invoiceNumbers) {
729
			System.out.println("Invoice Number - " + invoiceNumber);
27892 amit.gupta 730
			FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
30972 amit.gupta 731
			orderService.reverseScheme(fofoOrder);
27892 amit.gupta 732
			schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
733
		}
734
	}
28205 tejbeer 735
 
27987 amit.gupta 736
	public void processSchemeIn(List<String> invoiceNumbers) throws Exception {
28205 tejbeer 737
		for (String invoiceNumber : invoiceNumbers) {
738
			System.out.println("Invoice Number - " + invoiceNumber);
27987 amit.gupta 739
			Purchase purchase = purchaseRepository.selectByPurchaseReference(invoiceNumber);
740
			schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
741
		}
742
	}
24533 govind 743
 
25584 amit.gupta 744
	public void processScheme(int offset, int durationDays, boolean dryRun) throws Exception {
24462 amit.gupta 745
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24461 amit.gupta 746
		LocalDateTime endDate = startDate.plusDays(durationDays);
25584 amit.gupta 747
		processScheme(startDate, endDate, dryRun);
24461 amit.gupta 748
	}
24271 amit.gupta 749
 
25584 amit.gupta 750
	public void processScheme(boolean dryRun) throws Exception {
24256 amit.gupta 751
		LocalDateTime fromDate = LocalDateTime.now().minusDays(30);
25584 amit.gupta 752
		processScheme(fromDate, LocalDateTime.now(), dryRun);
24256 amit.gupta 753
	}
24271 amit.gupta 754
 
25584 amit.gupta 755
	public void processScheme(LocalDateTime startDate, LocalDateTime endDate, boolean dryRun) throws Exception {
23724 amit.gupta 756
		LOGGER.info("Started execution at {}", LocalDateTime.now());
25312 amit.gupta 757
		System.out.println(
758
				"InventoryId\tSerialNumber\tItem Id\tScheme Id\tScheme Name\tScheme Type\tAmount Type\tDP\tTaxable\tScheme Amount\tAmount Paid");
24561 amit.gupta 759
		try {
24587 amit.gupta 760
			List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
761
			for (Purchase purchase : purchases) {
762
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
763
			}
24271 amit.gupta 764
 
24587 amit.gupta 765
			List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
766
			for (FofoOrder fofoOrder : fofoOrders) {
767
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
768
			}
769
		} catch (Exception e) {
24561 amit.gupta 770
			e.printStackTrace();
24565 amit.gupta 771
			throw e;
24561 amit.gupta 772
		}
28205 tejbeer 773
		List<UserWalletHistory> uwhs = userWalletHistoryRepository.selectAllByDateType(LocalDate.now().atStartOfDay(),
774
				endDate, Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
25043 amit.gupta 775
		System.out.println("Amount\tReference\tReferenceType\tTimestamp\tDescription");
25312 amit.gupta 776
		for (UserWalletHistory uwh : uwhs) {
777
			System.out.println(String.format("%d\t%d\t%s\t%s\t%s", uwh.getAmount(), uwh.getReference(),
778
					uwh.getReferenceType(), uwh.getTimestamp().toString(), uwh.getDescription()));
25043 amit.gupta 779
		}
30644 amit.gupta 780
		LOGGER.info("Schemes processed successfully.");
25598 amit.gupta 781
		if (dryRun) {
25584 amit.gupta 782
			throw new Exception();
783
		}
23724 amit.gupta 784
	}
23929 amit.gupta 785
 
23739 amit.gupta 786
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 787
		LocalDateTime cashbackTime = LocalDateTime.now();
23929 amit.gupta 788
		int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
789
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository
790
				.getPendingCashBackRehargeTransactions();
791
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
792
				Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
793
		for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
794
			int retailerId = (Integer) totalRetailerCashback.getKey();
23739 amit.gupta 795
			float amount = totalRetailerCashback.getValue().floatValue();
23929 amit.gupta 796
			if (Math.round(amount) > 0) {
797
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK,
26565 amit.gupta 798
						"Recharge Cashback", Math.round(amount), LocalDateTime.now());
23762 amit.gupta 799
			}
23739 amit.gupta 800
		}
23929 amit.gupta 801
		for (RechargeTransaction rt : pendingTransactions) {
23761 amit.gupta 802
			rt.setCashbackTimestamp(cashbackTime);
803
			rt.setCashbackReference(referenceId);
804
			rechargeTransactionRepository.persist(rt);
805
		}
23739 amit.gupta 806
		LOGGER.info("Cashbacks for Recharge processed Successfully");
807
	}
29160 amit.gupta 808
 
809
	public void rollOutUpgardedMarginsNextMonth() throws Exception {
29107 amit.gupta 810
		LocalDate startOfPreviousMonth = LocalDate.now().with(ChronoField.DAY_OF_MONTH, 1).minusMonths(1);
29160 amit.gupta 811
 
28971 amit.gupta 812
		List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
29160 amit.gupta 813
		for (FofoStore store : stores) {
814
			int fofoId = store.getId();
815
 
30752 tejbeer 816
			PartnerType startOfPreviousMonthPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId,
817
					startOfPreviousMonth);
29160 amit.gupta 818
			PartnerType todayPartnerType = partnerTypeChangeService.getTypeOnMonth(fofoId,
819
					YearMonth.from(startOfPreviousMonth.atStartOfDay()));
30119 amit.gupta 820
			if (!startOfPreviousMonthPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
29160 amit.gupta 821
				continue;
822
			}
30119 amit.gupta 823
			if (!startOfPreviousMonthPartnerType.equals(todayPartnerType)) {
29160 amit.gupta 824
				LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(),
30119 amit.gupta 825
						startOfPreviousMonthPartnerType, todayPartnerType);
29160 amit.gupta 826
				List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId,
827
						startOfPreviousMonth.atStartOfDay(), startOfPreviousMonth.plusMonths(1).atStartOfDay(), 0, 0);
828
				for (FofoOrder fofoOrder : fofoOrders) {
829
					schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
28974 amit.gupta 830
				}
29160 amit.gupta 831
 
832
			}
28971 amit.gupta 833
		}
834
	}
29252 amit.gupta 835
 
29160 amit.gupta 836
	public void rollOutUpgardedMargins() throws Exception {
837
		LocalDate today = LocalDate.now();
838
		LocalDate yesterday = today.minusDays(1);
839
		int upgradedCount = 0;
840
		List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
841
		StringBuilder sb = new StringBuilder();
842
		for (FofoStore store : stores) {
843
			int fofoId = store.getId();
29252 amit.gupta 844
 
30215 amit.gupta 845
			PartnerType yesterdayPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, yesterday);
846
			PartnerType todayPartnerType = partnerTypeChangeService.getTypeOnDate(fofoId, today);
29160 amit.gupta 847
			if (!yesterdayPartnerType.nextPartnerTypes().contains(todayPartnerType)) {
848
				continue;
849
			}
850
			if (!yesterdayPartnerType.equals(todayPartnerType)) {
851
				upgradedCount++;
29252 amit.gupta 852
				sb.append(String.format("Partner Type has been changed for code %s from %s to %s", store.getCode(),
853
						yesterdayPartnerType.toString(), todayPartnerType.toString()));
29160 amit.gupta 854
				sb.append("<br>");
855
				LOGGER.info("Partner Type has been changed for code {} from {} to {}", store.getCode(),
856
						yesterdayPartnerType, todayPartnerType);
857
				List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoId(fofoId,
858
						yesterday.withDayOfMonth(1).atStartOfDay(), yesterday.atStartOfDay(), 0, 0);
859
				for (FofoOrder fofoOrder : fofoOrders) {
860
					schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
861
				}
29252 amit.gupta 862
 
29160 amit.gupta 863
			}
864
		}
29252 amit.gupta 865
		if (upgradedCount > 0) {
866
			sendMailHtmlFormat(
30752 tejbeer 867
					new String[] { "amit.gupta@smartdukaan.com", "tarun.verma@smartdukaan.com",
868
							"neeraj.gupta@smartdukaan.com" },
29252 amit.gupta 869
					sb.toString(), null, "Few Partners Category have been Upgraded");
29160 amit.gupta 870
		} else {
29252 amit.gupta 871
			sendMailHtmlFormat(
30752 tejbeer 872
					new String[] { "amit.gupta@smartdukaan.com", "tarun.verma@smartdukaan.com",
873
							"neeraj.gupta@smartdukaan.com" },
29252 amit.gupta 874
					sb.toString(), null, "No partners Category have been upgraded today");
29160 amit.gupta 875
		}
876
	}
23724 amit.gupta 877
 
30390 amit.gupta 878
	@Autowired
879
	private PartnerStatsService partnerStatsService;
880
 
30393 amit.gupta 881
	// Temporary Method
882
	public void evaluateExcessSchemeOut() throws Exception {
883
		Map<Integer, String> userNameMap = retailerService.getAllFofoRetailerIdNameMap();
884
		Map<Integer, Float> userAmountMap = new HashMap<>();
885
 
886
		List<List<?>> rows = new ArrayList<>();
887
		List<String> headers = Arrays.asList("Scheme", "Item", "Partner", "Amount", "Credited On", "Invoice Number",
888
				"Sale On", "Scheme Start", "Scheme End", "Active On", "Expired On");
889
		schemeRepository.selectAll().stream().forEach(x -> {
890
			if (x.getType().equals(SchemeType.OUT)) {
891
				List<SchemeInOut> sioList = schemeInOutRepository
892
						.selectBySchemeIds(new HashSet<>(Arrays.asList(x.getId())));
893
				if (x.getActiveTimestamp() != null) {
894
					LocalDateTime endDateTime = x.getEndDateTime();
895
					if (x.getExpireTimestamp() != null && x.getExpireTimestamp().isBefore(x.getEndDateTime())) {
896
						endDateTime = x.getExpireTimestamp();
897
					}
898
					for (SchemeInOut sio : sioList) {
899
						InventoryItem inventoryItem = null;
900
						inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
901
						FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndSerialNumber(
902
								inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), null, null, 0, 1).get(0);
903
						Optional<ScanRecord> record = scanRecordRepository
904
								.selectByInventoryItemId(sio.getInventoryItemId()).stream()
905
								.filter(y -> y.getType().equals(ScanType.SALE)).findFirst();
906
						if (record.isPresent()) {
907
							int fofoId = record.get().getFofoId();
908
							if (record.get().getCreateTimestamp().isAfter(endDateTime)
909
									|| record.get().getCreateTimestamp().isBefore(x.getStartDateTime())) {
910
								if (!userAmountMap.containsKey(fofoId)) {
911
									userAmountMap.put(fofoId, 0f);
912
								}
913
								userAmountMap.put(fofoId, sio.getAmount() + userAmountMap.get(fofoId));
914
								try {
915
									rows.add(Arrays.asList(x.getDescription(),
916
											itemRepository.selectById(inventoryItem.getItemId()).getItemDescription(),
917
											userNameMap.get(fofoId), sio.getAmount(),
918
											FormattingUtils.formatDate(sio.getCreateTimestamp()),
919
											fofoOrder.getInvoiceNumber(),
920
											FormattingUtils.formatDate(record.get().getCreateTimestamp()),
921
											FormattingUtils.formatDate(x.getStartDateTime()),
922
											FormattingUtils.formatDate(x.getEndDateTime()),
923
											FormattingUtils.formatDate(x.getActiveTimestamp()),
924
											FormattingUtils.formatDate(x.getExpireTimestamp())));
925
								} catch (Exception e) {
926
									e.printStackTrace();
927
								}
928
							}
929
						}
930
					}
931
				}
932
			}
933
		});
934
		userAmountMap.entrySet().stream()
935
				.forEach(x -> LOGGER.info("{} to be deducted from {}({}) for wrongly disbursed due to technical error.",
936
						x.getValue(), userNameMap.get(x.getKey())));
937
 
938
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
939
		Utils.sendMailWithAttachment(googleMailSender,
30752 tejbeer 940
				new String[] { "amit.gupta@shop2020.in", "adeel.yazdani@smartdukaan.com" }, null,
30393 amit.gupta 941
				"Partner Excess Amount", "PFA", "ListofSchemes.csv", new ByteArrayResource(baos.toByteArray()));
942
 
943
	}
944
 
30390 amit.gupta 945
	public void fetchParnterStats() throws Exception {
946
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
947
		ObjectOutputStream oos = null;
948
		FileOutputStream fout = null;
949
		try {
950
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
951
			oos = new ObjectOutputStream(fout);
952
			oos.writeObject(partnerStats);
953
 
954
		} catch (Exception ex) {
955
			ex.printStackTrace();
956
		} finally {
957
			if (oos != null) {
958
				oos.close();
959
			}
960
		}
961
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
962
		if (rct == null) {
963
			rct = new ReporticoCacheTable();
964
			rct.setTableName("partnerStat");
30393 amit.gupta 965
			rct.setLastCreatedTimestamp(LocalDateTime.now());
966
			reporticoCacheTableRepository.persist(rct);
967
		} else {
968
			rct.setLastCreatedTimestamp(LocalDateTime.now());
30390 amit.gupta 969
		}
970
	}
971
 
30637 amit.gupta 972
	public void processPriceDrop() throws Exception {
30752 tejbeer 973
		List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetween(LocalDateTime.now(),
974
				LocalDateTime.now().minusYears(1));
30637 amit.gupta 975
		for (PriceDrop priceDrop : priceDrops) {
976
			if (priceDrop.getDropAmount() > 0) {
977
				priceDropService.processPriceDrop(priceDrop.getId(), true);
978
			}
979
		}
980
	}
981
 
31008 amit.gupta 982
	@Autowired
983
	CreditNoteService creditNoteService;
984
 
985
	public void sendCreditNote(YearMonth yearMonth) throws Exception {
986
		creditNoteService.issueMonthlyMarginsCN(yearMonth);
987
	}
988
 
25598 amit.gupta 989
	private class SaleRoles {
990
 
991
		private List<String> l1;
992
		private List<String> l2;
993
 
994
		public SaleRoles() {
995
			l1 = new ArrayList<>();
996
			l2 = new ArrayList<>();
997
		}
998
 
999
		public List<String> getL1() {
1000
			return l1;
1001
		}
1002
 
1003
		public List<String> getL2() {
1004
			return l2;
1005
		}
1006
 
1007
	}
1008
 
26945 amit.gupta 1009
	private class FofoReportingModel {
1010
		private String code;
1011
		private int fofoId;
1012
		private String businessName;
1013
		private String territoryManager;
1014
		private String regionalManager;
1015
 
1016
		@Override
1017
		public String toString() {
1018
			return "FofoReportingModel [code=" + code + ", fofoId=" + fofoId + ", businessName=" + businessName
1019
					+ ", territoryManager=" + territoryManager + ", regionalManager=" + regionalManager + "]";
1020
		}
1021
 
1022
		public String getCode() {
1023
			return code;
1024
		}
1025
 
1026
		public void setCode(String code) {
1027
			this.code = code;
1028
		}
1029
 
1030
		public String getBusinessName() {
1031
			return businessName;
1032
		}
1033
 
1034
		public void setBusinessName(String businessName) {
1035
			this.businessName = businessName;
1036
		}
1037
 
1038
		public String getTerritoryManager() {
1039
			return territoryManager;
1040
		}
1041
 
1042
		public void setTerritoryManager(String territoryManager) {
1043
			this.territoryManager = territoryManager;
1044
		}
1045
 
1046
		public String getRegionalManager() {
1047
			return regionalManager;
1048
		}
1049
 
1050
		public void setRegionalManager(String regionalManager) {
1051
			this.regionalManager = regionalManager;
1052
		}
1053
 
1054
		private ScheduledTasks getOuterType() {
1055
			return ScheduledTasks.this;
1056
		}
1057
 
1058
		@Override
1059
		public int hashCode() {
1060
			final int prime = 31;
1061
			int result = 1;
1062
			result = prime * result + getOuterType().hashCode();
1063
			result = prime * result + ((businessName == null) ? 0 : businessName.hashCode());
1064
			result = prime * result + ((code == null) ? 0 : code.hashCode());
1065
			result = prime * result + fofoId;
1066
			result = prime * result + ((regionalManager == null) ? 0 : regionalManager.hashCode());
1067
			result = prime * result + ((territoryManager == null) ? 0 : territoryManager.hashCode());
1068
			return result;
1069
		}
1070
 
1071
		@Override
1072
		public boolean equals(Object obj) {
1073
			if (this == obj)
1074
				return true;
1075
			if (obj == null)
1076
				return false;
1077
			if (getClass() != obj.getClass())
1078
				return false;
1079
			FofoReportingModel other = (FofoReportingModel) obj;
1080
			if (!getOuterType().equals(other.getOuterType()))
1081
				return false;
1082
			if (businessName == null) {
1083
				if (other.businessName != null)
1084
					return false;
1085
			} else if (!businessName.equals(other.businessName))
1086
				return false;
1087
			if (code == null) {
1088
				if (other.code != null)
1089
					return false;
1090
			} else if (!code.equals(other.code))
1091
				return false;
1092
			if (fofoId != other.fofoId)
1093
				return false;
1094
			if (regionalManager == null) {
1095
				if (other.regionalManager != null)
1096
					return false;
1097
			} else if (!regionalManager.equals(other.regionalManager))
1098
				return false;
1099
			if (territoryManager == null) {
1100
				if (other.territoryManager != null)
1101
					return false;
1102
			} else if (!territoryManager.equals(other.territoryManager))
1103
				return false;
1104
			return true;
1105
		}
1106
 
1107
		public int getFofoId() {
1108
			return fofoId;
1109
		}
1110
 
1111
		public void setFofoId(int fofoId) {
1112
			this.fofoId = fofoId;
1113
		}
1114
 
1115
	}
1116
 
24271 amit.gupta 1117
	public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
24277 amit.gupta 1118
		LocalDate yesterDay = LocalDate.now().minusDays(1);
25267 amit.gupta 1119
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
23929 amit.gupta 1120
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
1121
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
25351 tejbeer 1122
 
26957 amit.gupta 1123
		List<String> headers = Arrays.asList("Code", "Outlet name", "State Manager", "Teritory/Team Lead",
26945 amit.gupta 1124
				"Wallet Amount", "In Stock Amount", "Activated Stock", "Return In Transit Stock", "Unbilled Amount",
1125
				"Grn Pending Amount", "Min Investment", "Investment Amount", "Investment Short", "Unbilled Qty",
1126
				"Short Days");
25837 amit.gupta 1127
		List<List<?>> rows = new ArrayList<>();
25895 amit.gupta 1128
		Map<Integer, List<?>> partnerRowsMap = new HashMap<>();
25598 amit.gupta 1129
 
26945 amit.gupta 1130
		Map<Integer, FofoReportingModel> partnerIdSalesHeaderMap = this.getPartnerIdSalesHeaders();
25598 amit.gupta 1131
 
26945 amit.gupta 1132
		Map<Integer, Integer> shortDaysMap = partnerDailyInvestmentRepository
1133
				.selectAll(LocalDate.now().withDayOfMonth(1), LocalDate.now()).stream().collect(Collectors.groupingBy(
1134
						x -> x.getFofoId(), Collectors.summingInt(x -> x.getShortPercentage() > 10 ? 1 : 0)));
1135
 
24002 amit.gupta 1136
		for (FofoStore fofoStore : fofoStores) {
27750 amit.gupta 1137
			LOGGER.info("Fofo Store {},  {}", fofoStore.getId(), fofoStore.getCode());
26376 amit.gupta 1138
			int fofoId = fofoStore.getId();
26945 amit.gupta 1139
			PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoId, 1);
25598 amit.gupta 1140
			partnerDailyInvestment.setDate(yesterDay);
26945 amit.gupta 1141
 
25598 amit.gupta 1142
			try {
1143
				partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
26945 amit.gupta 1144
				shortDaysMap.put(fofoId,
1145
						shortDaysMap.get(fofoId) + (partnerDailyInvestment.getShortPercentage() > 10 ? 1 : 0));
25598 amit.gupta 1146
			} catch (Exception e) {
1147
				// ignore the exceptions during persist
1148
			}
1149
 
24002 amit.gupta 1150
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
25837 amit.gupta 1151
			if (retailer == null || partnerIdSalesHeaderMap.get(fofoStore.getId()) == null) {
24002 amit.gupta 1152
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
1153
				continue;
1154
			}
26945 amit.gupta 1155
			FofoReportingModel reportingModel = partnerIdSalesHeaderMap.get(fofoStore.getId());
1156
			List<Serializable> row = new ArrayList<>();
1157
			row.addAll(Arrays.asList(reportingModel.getCode(), reportingModel.getBusinessName(),
1158
					reportingModel.getRegionalManager(), reportingModel.getTerritoryManager()));
25927 amit.gupta 1159
			row.addAll(
1160
					Arrays.asList(partnerDailyInvestment.getWalletAmount(), partnerDailyInvestment.getInStockAmount(),
26945 amit.gupta 1161
							partnerDailyInvestment.getActivatedStockAmount() == 0 ? "-"
1162
									: "(" + partnerDailyInvestment.getActivatedStockAmount() + ")",
25927 amit.gupta 1163
							0, partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(),
1164
							partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(),
26945 amit.gupta 1165
							partnerDailyInvestment.getShortInvestment(), partnerDailyInvestment.getUnbilledQty(),
1166
							shortDaysMap.get(fofoId)));
25837 amit.gupta 1167
			partnerRowsMap.put(fofoStore.getId(), row);
24002 amit.gupta 1168
			rows.add(row);
1169
 
23929 amit.gupta 1170
		}
25312 amit.gupta 1171
 
24271 amit.gupta 1172
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25598 amit.gupta 1173
 
25927 amit.gupta 1174
		if (sendTo == null) {
30215 amit.gupta 1175
			for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
25895 amit.gupta 1176
				List<List<?>> filteredRows = storeGuyEntry.getValue().stream().map(x -> partnerRowsMap.get(x))
1177
						.filter(x -> x != null).collect(Collectors.toList());
1178
				ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
30752 tejbeer 1179
				String[] sendToArray = new String[] { storeGuyEntry.getKey() };
25895 amit.gupta 1180
				Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
1181
						fileName, new ByteArrayResource(baos.toByteArray()));
1182
			}
27210 tejbeer 1183
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
28467 tejbeer 1184
					"neeraj.gupta@smartdukaan.com", "amit.gupta@shop2020.in", "manish.gupta@smartdukaan.com",
1185
					"niranjan.kala@smartdukaan.com");
25341 amit.gupta 1186
		}
25312 amit.gupta 1187
 
25604 amit.gupta 1188
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1189
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
25609 amit.gupta 1190
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Franchise Investment Summary", "PFA",
1191
				fileName, new ByteArrayResource(baos.toByteArray()));
24271 amit.gupta 1192
 
23929 amit.gupta 1193
	}
24177 govind 1194
 
26945 amit.gupta 1195
	private Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() {
25598 amit.gupta 1196
		Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
1197
 
1198
		List<Position> positions = positionRepository
1199
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
1200
		Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream()
1201
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1202
		Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
1203
		for (Position position : positions) {
1204
			List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
25609 amit.gupta 1205
			if (crList == null)
1206
				continue;
25598 amit.gupta 1207
			for (CustomRetailer cr : crList) {
1208
				if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
1209
					partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
1210
				}
1211
				SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
1212
				AuthUser authUser = authUsersMap.get(position.getAuthUserId());
26945 amit.gupta 1213
				if (authUser == null) {
26059 amit.gupta 1214
					continue;
1215
				}
25598 amit.gupta 1216
				String name = authUser.getFirstName() + " " + authUser.getLastName();
1217
				if (position.getEscalationType().equals(EscalationType.L1)) {
1218
					saleRoles.getL1().add(name);
1219
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
1220
					saleRoles.getL2().add(name);
1221
				}
1222
			}
1223
		}
25837 amit.gupta 1224
 
1225
		Set<CustomRetailer> allCrList = new HashSet<>();
1226
		for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1227
			allCrList.addAll(cr);
1228
		}
1229
 
1230
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
1231
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1232
 
26945 amit.gupta 1233
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
25837 amit.gupta 1234
 
1235
		for (CustomRetailer cr : allCrList) {
1236
			FofoStore fofoStore = fofoStoresMap.get(cr.getPartnerId());
25927 amit.gupta 1237
			if (fofoStore == null) {
25870 amit.gupta 1238
				LOGGER.info("Could not find Store {} in active Store", cr.getBusinessName());
1239
				continue;
1240
			}
26945 amit.gupta 1241
			String code = fofoStore.getCode();
1242
			// String storeName = "SmartDukaan-" +
1243
			// fofoStore.getCode().replaceAll("[a-zA-Z]", "");
25837 amit.gupta 1244
			String businessName = cr.getBusinessName();
1245
			try {
1246
				String stateManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL2(), ", ");
1247
				String territoryManager = StringUtils.join(partnerEmailSalesMap.get(cr.getEmail()).getL1(), ", ");
26945 amit.gupta 1248
				FofoReportingModel reportingModel = new FofoReportingModel();
1249
				reportingModel.setBusinessName(businessName);
1250
				reportingModel.setCode(code);
1251
				reportingModel.setFofoId(fofoStore.getId());
1252
				reportingModel.setRegionalManager(stateManager);
1253
				reportingModel.setTerritoryManager(territoryManager);
1254
				partnerIdSalesHeadersMap.put(fofoStore.getId(), reportingModel);
25837 amit.gupta 1255
			} catch (Exception e) {
1256
				LOGGER.warn("Could not find partner with email - {}", cr.getEmail());
1257
			}
1258
		}
1259
		return partnerIdSalesHeadersMap;
1260
 
25598 amit.gupta 1261
	}
1262
 
24271 amit.gupta 1263
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 1264
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 1265
	}
1266
 
24697 amit.gupta 1267
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 1268
 
1269
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
1270
				"itemstockageing.xml");
24708 amit.gupta 1271
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 1272
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 1273
		Attachment attachment = new Attachment(
25445 amit.gupta 1274
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 1275
		Attachment attachment1 = new Attachment(
25445 amit.gupta 1276
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
25418 amit.gupta 1277
 
25609 amit.gupta 1278
		Utils.sendMailWithAttachments(googleMailSender, STOCK_AGEING_MAIL_LIST, null, "Stock Ageing Report", "PFA",
1279
				attachment);
1280
		Utils.sendMailWithAttachments(googleMailSender, ITEMWISE_PENDING_INDENT_MAIL_LIST, null,
1281
				"Itemwise Pending indent", "PFA", attachment1);
1282
 
25598 amit.gupta 1283
		// Reports to be sent to mapped partners
25597 amit.gupta 1284
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 1285
 
1286
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 1287
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 1288
			if (storeGuyEntry.getValue().size() == 0)
1289
				continue;
25418 amit.gupta 1290
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
1291
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
1292
					"focostockreport.xml", params);
1293
			Attachment attache = new Attachment(
25609 amit.gupta 1294
					"Franchise-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 1295
			System.out.println(storeGuyEntry.getValue());
30752 tejbeer 1296
			Utils.sendMailWithAttachments(googleMailSender, new String[] { storeGuyEntry.getKey() }, null,
25609 amit.gupta 1297
					"Franchise Stock Report", "PFA", attache);
25418 amit.gupta 1298
		}
25503 amit.gupta 1299
 
24681 amit.gupta 1300
	}
24533 govind 1301
 
28632 amit.gupta 1302
	public void sendIndentTertiary() throws Exception {
28709 amit.gupta 1303
 
28632 amit.gupta 1304
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
1305
				"indentandtertiary.xml");
1306
		Attachment attachment = new Attachment(
28839 tejbeer 1307
				"indentandtertiary-report-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr);
28709 amit.gupta 1308
		Utils.sendMailWithAttachments(googleMailSender, INDENT_TERTIARY_MAIL_LIST, null, "Indent Tertiary Report",
1309
				"PFA", attachment);
1310
 
28632 amit.gupta 1311
	}
28790 amit.gupta 1312
 
28769 amit.gupta 1313
	public void sendAttendanceMorningAlert() throws Exception {
28793 amit.gupta 1314
		LocalDateTime moriningTime = LocalDate.now().atTime(10, 31);
28775 amit.gupta 1315
		List<AuthUser> authUsers = authRepository.selectAllActiveUser();
28790 amit.gupta 1316
		Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive())
1317
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
1318
 
28769 amit.gupta 1319
		List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
28790 amit.gupta 1320
		Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
1321
 
1322
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository
1323
				.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now());
1324
 
1325
		Map<Integer, Optional<EmployeeAttendance>> employeeMorningAttendance = employeeAttendances.stream()
1326
				.collect(Collectors.groupingBy(EmployeeAttendance::getUserId,
1327
						Collectors.minBy(Comparator.comparing(EmployeeAttendance::getCreateTimestamp))));
1328
		for (AuthUser authUser : authUsers) {
28769 amit.gupta 1329
			User user = userMap.get(authUser.getEmailId());
1330
			Optional<EmployeeAttendance> employeeAttendanceOptional = employeeMorningAttendance.get(user.getId());
28817 amit.gupta 1331
			LOGGER.info("AuthUser - {}, employeeAttendanceOptional {}", authUser.getName(), employeeAttendanceOptional);
28839 tejbeer 1332
			if (employeeAttendanceOptional != null) {
28818 amit.gupta 1333
				LOGGER.info("employeeAttendanceOptional.orElse {}", employeeAttendanceOptional.orElse(null));
28839 tejbeer 1334
				if (employeeAttendanceOptional.orElse(null) != null) {
1335
					LOGGER.info("employeeAttendanceOptional.get().getCreateTimestamp() {}",
1336
							employeeAttendanceOptional.get().getCreateTimestamp());
28818 amit.gupta 1337
				}
1338
			}
28790 amit.gupta 1339
			if (employeeAttendanceOptional == null || employeeAttendanceOptional.orElse(null) == null
28769 amit.gupta 1340
					|| employeeAttendanceOptional.get().getCreateTimestamp().isAfter(moriningTime)) {
28819 amit.gupta 1341
				LOGGER.info("Will Send Email to {}", authUser.getFullName());
28790 amit.gupta 1342
				String body = String.format(
28806 amit.gupta 1343
						"Dear %s,\n Pls note that you haven't punched your attendance by 10:30am%s. You have been marked absent for half the day.\n\nRegards\nHR Team",
28839 tejbeer 1344
						authUser.getFullName(),
1345
						(employeeAttendanceOptional == null || employeeAttendanceOptional.orElse(null) == null) ? ""
1346
								: "(Punched at "
30752 tejbeer 1347
										+ FormattingUtils.format(employeeAttendanceOptional.get().getCreateTimestamp())
1348
										+ ")");
28839 tejbeer 1349
 
30752 tejbeer 1350
				Utils.sendMailWithAttachments(googleMailSender, new String[] { authUser.getEmailId() },
31120 tejbeer 1351
						new String[] { "kangan.monga@smartdukaan.com" }, "Attendance Alert", body);
28839 tejbeer 1352
 
28769 amit.gupta 1353
			}
1354
		}
28790 amit.gupta 1355
 
28769 amit.gupta 1356
	}
28790 amit.gupta 1357
 
28775 amit.gupta 1358
	public void sendAttendanceEveningAlert() throws Exception {
1359
		List<AuthUser> authUsers = authRepository.selectAllActiveUser();
28790 amit.gupta 1360
		Map<String, AuthUser> authUserEmailMap = authUsers.stream().filter(x -> x.isActive())
1361
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
1362
 
28775 amit.gupta 1363
		List<User> users = dtrUserRepository.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.keySet()));
28790 amit.gupta 1364
		Map<String, User> userMap = users.stream().collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
28775 amit.gupta 1365
 
28790 amit.gupta 1366
		Map<Integer, List<EmployeeAttendance>> employeeAttendancesMap = employeeAttendanceRepository
1367
				.selectAllByDatesBetween(LocalDate.now().atStartOfDay(), LocalDateTime.now()).stream()
1368
				.collect(Collectors.groupingBy(x -> x.getUserId()));
1369
 
1370
		for (AuthUser authUser : authUsers) {
28775 amit.gupta 1371
			User user = userMap.get(authUser.getEmailId());
28784 amit.gupta 1372
			String body = null;
1373
			List<EmployeeAttendance> employeeAttendances = employeeAttendancesMap.get(user.getId());
28790 amit.gupta 1374
			if (employeeAttendances == null) {
1375
				body = String.format(
28806 amit.gupta 1376
						"Dear %s,\n No attendance has been registered by you today. You have been marked absent for the day.\n\nRegards\nHR Team",
28790 amit.gupta 1377
						authUser.getFullName());
28784 amit.gupta 1378
			} else {
28790 amit.gupta 1379
				List<LocalDateTime> punchTimes = employeeAttendances.stream()
1380
						.sorted(Comparator.comparing(EmployeeAttendance::getCreateTimestamp))
1381
						.map(x -> x.getCreateTimestamp()).collect(Collectors.toList());
1382
				if (punchTimes.size() == 1) {
1383
					// body = String.format("Dear %s,\n Pls note that you haven't punched out yet.
1384
					// You have been marked absent for half the day. You may contact your manager
1385
					// and get it regularise.\n\nRegards\nHR Team", authUser.getFullName());
28784 amit.gupta 1386
				} else {
1387
					LocalDateTime firstPunch = punchTimes.get(0);
28790 amit.gupta 1388
					LocalDateTime lastPunch = punchTimes.get(punchTimes.size() - 1);
28805 amit.gupta 1389
					Duration duration = Duration.between(firstPunch, lastPunch);
28784 amit.gupta 1390
					boolean hoursCompleted = lastPunch.isAfter(firstPunch.plusHours(8).plusMinutes(30));
28790 amit.gupta 1391
					if (!hoursCompleted) {
1392
						body = String.format(
28806 amit.gupta 1393
								"Dear %s,\n Pls note that you haven't completed 8.30 Hrs (%d.%d Hrs). You have been marked absent for half the day.\n\nRegards\nHR Team",
28839 tejbeer 1394
								authUser.getFullName(), duration.toHours(),
1395
								duration.toMinutes() - duration.toHours() * 60);
28784 amit.gupta 1396
					}
1397
				}
1398
 
1399
			}
28790 amit.gupta 1400
			if (body != null) {
30752 tejbeer 1401
				Utils.sendMailWithAttachments(googleMailSender, new String[] { authUser.getEmailId() },
31120 tejbeer 1402
						new String[] { "kangan.monga@smartdukaan.com" }, "Attendance Alert", body);
28775 amit.gupta 1403
			}
1404
		}
28790 amit.gupta 1405
 
1406
		this.sendMailToHR();
1407
 
28775 amit.gupta 1408
	}
28790 amit.gupta 1409
 
1410
	private void sendMailToHR() throws Exception {
1411
		Map<String, String> map = new HashMap<>();
1412
		String reporticoDate = FormattingUtils.formatReporitcoDate(LocalDateTime.now());
1413
		map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
1414
		map.put("MANUAL_datesBetween_FROMDATE", reporticoDate);
1415
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
1416
				"employeeattendance.xml");
1417
		Attachment attachment = new Attachment("attendance-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv",
1418
				isr);
1419
		Utils.sendMailWithAttachments(googleMailSender, EMPLOYEE_ATTENDANCE_MAIL_LIST, null,
1420
				"Attendance - " + FormattingUtils.formatDate(LocalDateTime.now()), "PFA Attendance", attachment);
1421
	}
1422
 
28709 amit.gupta 1423
	public void checkPartnerActiveStore() throws Exception {
1424
 
1425
		List<FofoStore> fofoStores = fofoStoreRepository.selectByStatus(true);
1426
 
1427
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
28712 amit.gupta 1428
		if (!fofoStores.isEmpty()) {
1429
			for (FofoStore fofoStore : fofoStores) {
28709 amit.gupta 1430
 
28712 amit.gupta 1431
				if (currentDate.isBefore(fofoStore.getActiveTimeStamp())) {
28709 amit.gupta 1432
 
28712 amit.gupta 1433
					fofoStore.setActive(true);
1434
					fofoStoreRepository.persist(fofoStore);
1435
					LOGGER.info("inserted into InActiveFofoStore successfully");
28709 amit.gupta 1436
 
30393 amit.gupta 1437
				} else {
28712 amit.gupta 1438
					fofoStore.setActive(false);
1439
					fofoStore.setActiveTimeStamp(null);
1440
					fofoStoreRepository.persist(fofoStore);
1441
					LOGGER.info("inserted into InActiveFofoStore successfully");
1442
				}
28709 amit.gupta 1443
 
1444
			}
1445
		}
1446
 
1447
	}
1448
 
24697 amit.gupta 1449
	public void sendAgeingReport() throws Exception {
30593 amit.gupta 1450
		sendAgeingReport("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com",
28467 tejbeer 1451
				"niranjan.kala@smartdukaan.com", "manish.gupta@smartdukaan.com", "kuldeep.kumar@smartdukaan.com");
24697 amit.gupta 1452
	}
1453
 
24533 govind 1454
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 1455
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 1456
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 1457
			priceDropService.priceDropStatus(priceDrop.getId());
1458
		}
1459
	}
23929 amit.gupta 1460
 
24542 amit.gupta 1461
	public void walletmismatch() throws Exception {
1462
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 1463
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 1464
		System.out.println(pdis.size());
24542 amit.gupta 1465
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 1466
			int fofoId = pdi.getFofoId();
24542 amit.gupta 1467
			for (PartnerDailyInvestment investment : Lists
1468
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 1469
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 1470
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 1471
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 1472
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
1473
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 1474
 
24542 amit.gupta 1475
			}
24549 amit.gupta 1476
		}
24542 amit.gupta 1477
 
1478
	}
29160 amit.gupta 1479
 
28990 amit.gupta 1480
	@Autowired
1481
	StateRepository stateRepository;
24542 amit.gupta 1482
 
1483
	public void gst() throws Exception {
28995 amit.gupta 1484
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2021, 8, 16).atStartOfDay(),
28990 amit.gupta 1485
				LocalDateTime.now());
24548 amit.gupta 1486
		for (FofoOrder fofoOrder : fofoOrders) {
1487
			int retailerAddressId = retailerRegisteredAddressRepository
1488
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 1489
 
1490
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
1491
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1492
			Integer stateId = null;
1493
			if (customerAddress.getState().equals(retailerAddress.getState())) {
1494
				try {
28990 amit.gupta 1495
					stateId = stateRepository.selectByName(customerAddress.getState()).getId();
24542 amit.gupta 1496
				} catch (Exception e) {
28990 amit.gupta 1497
					LOGGER.error("Cannot found state named {}", customerAddress.getState());
1498
					continue;
24542 amit.gupta 1499
				}
1500
			}
1501
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1502
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 1503
 
1504
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
26929 amit.gupta 1505
			List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
24542 amit.gupta 1506
			if (stateId != null) {
26929 amit.gupta 1507
				itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
24542 amit.gupta 1508
			} else {
26929 amit.gupta 1509
				itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(itemIds);
24542 amit.gupta 1510
			}
1511
 
24548 amit.gupta 1512
			for (FofoOrderItem foi : fofoOrderItems) {
28990 amit.gupta 1513
				float sgstRate = foi.getSgstRate();
1514
				float cgstRate = foi.getCgstRate();
1515
				float igstRate = foi.getIgstRate();
29160 amit.gupta 1516
				if (stateId == null && igstRate == 0) {
1517
 
1518
					foi.setSgstRate(0);
1519
					foi.setCgstRate(0);
1520
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
1521
 
28993 amit.gupta 1522
					LOGGER.info("Invoice {}, Date {}", fofoOrder.getInvoiceNumber(), fofoOrder.getCreateTimestamp());
29160 amit.gupta 1523
					LOGGER.info("customerAddress.getState() {}, retailerAddress.getState() {}",
1524
							customerAddress.getState(), retailerAddress.getState());
28990 amit.gupta 1525
					LOGGER.info("Rates getIgstRate() {}", itemIdIgstTaxRateMap.get(foi.getItemId()));
29160 amit.gupta 1526
 
1527
				} else if (stateId != null && sgstRate == 0 && cgstRate == 0) {
1528
 
1529
					foi.setIgstRate(0);
1530
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
1531
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
1532
 
28993 amit.gupta 1533
					LOGGER.info("Invoice {}, Date {}", fofoOrder.getInvoiceNumber(), fofoOrder.getCreateTimestamp());
29160 amit.gupta 1534
					LOGGER.info("customerAddress.getState() {}, retailerAddress.getState() {}",
1535
							customerAddress.getState(), retailerAddress.getState());
1536
					LOGGER.info("Rates getCgstRate() {}, getSgstRate() {}",
1537
							itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate(),
1538
							itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
24542 amit.gupta 1539
				}
1540
			}
1541
		}
24548 amit.gupta 1542
 
24542 amit.gupta 1543
	}
1544
 
24580 amit.gupta 1545
	public void schemewalletmismatch() {
1546
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 1547
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 1548
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 1549
			// reconcileOrders(dateTime);
1550
			// reconcileRecharges(dateTime);
24580 amit.gupta 1551
			dateToReconcile = dateToReconcile.plusDays(1);
1552
		}
1553
	}
1554
 
1555
	private void reconcileSchemes(LocalDate date) {
1556
		LocalDateTime startDate = date.atStartOfDay();
1557
		LocalDateTime endDate = startDate.plusDays(1);
1558
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
1559
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 1560
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
1561
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 1562
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 1563
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
1564
				WalletReferenceType.SCHEME_OUT);
1565
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
1566
				walletReferenceTypes);
1567
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
1568
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 1569
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 1570
 
1571
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
1572
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1573
 
1574
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
1575
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1576
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
1577
 
1578
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
1579
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
1580
 
1581
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
1582
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
1583
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
1584
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
1585
 
1586
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
26092 amit.gupta 1587
 
24587 amit.gupta 1588
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
1589
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
1590
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
1591
				} else {
1592
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
1593
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
1594
				}
1595
			}
24590 amit.gupta 1596
			Map<Integer, Integer> userWalletMap = userWalletRepository
1597
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
1598
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1599
 
24587 amit.gupta 1600
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
1601
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
1602
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
1603
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
1604
				if (diff > 5) {
1605
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
1606
				}
1607
			}
24580 amit.gupta 1608
		}
24587 amit.gupta 1609
 
24580 amit.gupta 1610
	}
24590 amit.gupta 1611
 
24592 amit.gupta 1612
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 1613
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1614
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1615
 
24592 amit.gupta 1616
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1617
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 1618
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1619
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1620
		Set<String> serialNumbersConsidered = new HashSet<>();
1621
 
25096 amit.gupta 1622
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 1623
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
1624
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
1625
 
24683 amit.gupta 1626
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 1627
		purchases.stream().forEach(purchase -> {
1628
			float amountToRollback = 0;
1629
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
1630
					+ purchase.getPurchaseReference();
1631
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1632
					.stream().filter(ii -> ii.getSerialNumber() != null)
1633
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1634
			if (inventorySerialNumberMap.size() > 0) {
1635
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1636
					String serialNumber = inventorySerialNumberEntry.getValue();
1637
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1638
					if (serialNumbersConsidered.contains(serialNumber)) {
1639
						// This will rollback scheme for differenct orders for same serial
1640
						List<SchemeInOut> sios = schemeInOutRepository
1641
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1642
								.filter(x -> x.getRolledBackTimestamp() == null
1643
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1644
								.collect(Collectors.toList());
1645
						Collections.reverse(sios);
1646
						for (SchemeInOut sio : sios) {
1647
							sio.setRolledBackTimestamp(LocalDateTime.now());
1648
							amountToRollback += sio.getAmount();
1649
							// sio.setSchemeType(SchemeType.OUT);
1650
							sio.setSerialNumber(serialNumber);
1651
							rolledbackSios.add(sio);
1652
						}
1653
						description = description.concat(" " + serialNumber + " ");
1654
					} else {
1655
						serialNumbersConsidered.add(serialNumber);
1656
						List<Integer> schemesConsidered = new ArrayList<>();
1657
						List<SchemeInOut> sios = schemeInOutRepository
1658
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1659
								.filter(x -> x.getRolledBackTimestamp() == null
1660
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1661
								.collect(Collectors.toList());
1662
						Collections.reverse(sios);
1663
						for (SchemeInOut sio : sios) {
1664
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1665
								schemesConsidered.add(sio.getSchemeId());
1666
								continue;
1667
							}
1668
							sio.setRolledBackTimestamp(LocalDateTime.now());
1669
							amountToRollback += sio.getAmount();
1670
							// sio.setSchemeType(SchemeType.OUT);
1671
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1672
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1673
							sio.setReference(purchase.getId());
24635 amit.gupta 1674
							rolledbackSios.add(sio);
1675
						}
1676
					}
1677
 
1678
				}
1679
			}
1680
			if (amountToRollback > 0) {
24683 amit.gupta 1681
				// Address address =
1682
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1683
				UserWalletHistory uwh = new UserWalletHistory();
1684
				uwh.setAmount(Math.round(amountToRollback));
1685
				uwh.setDescription(description);
1686
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1687
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1688
				uwh.setReference(purchase.getId());
1689
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1690
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1691
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1692
				userWalletHistory.add(uwh);
1693
			}
1694
		});
1695
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1696
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1697
						"Timestamp"),
1698
				userWalletHistory.stream()
1699
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1700
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1701
						.collect(Collectors.toList()));
1702
 
1703
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1704
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1705
						"Created", "Rolledback"),
24635 amit.gupta 1706
				rolledbackSios.stream()
24681 amit.gupta 1707
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1708
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1709
						.collect(Collectors.toList()));
1710
 
30752 tejbeer 1711
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1712
				"Partner Excess Amount Scheme In", "PFA",
30752 tejbeer 1713
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1714
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1715
 
25096 amit.gupta 1716
		throw new Exception();
24635 amit.gupta 1717
 
1718
	}
1719
 
1720
	public void dryRunOutSchemeReco() throws Exception {
1721
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1722
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1723
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1724
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1725
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1726
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1727
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1728
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1729
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1730
		// Collections.reverse(allOrders);
1731
		// List<FofoOrder> allOrders =
24653 govind 1732
		// List<FofoOrder> allOrders =
24631 amit.gupta 1733
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1734
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1735
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1736
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1737
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1738
			float amountToRollback = 0;
24590 amit.gupta 1739
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1740
			orderItems.forEach(x -> {
24606 amit.gupta 1741
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1742
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1743
			});
24606 amit.gupta 1744
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1745
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1746
					String serialNumber = inventorySerialNumberEntry.getValue();
1747
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1748
					if (serialNumbersConsidered.contains(serialNumber)) {
1749
						// This will rollback scheme for differenct orders for same serial
1750
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1751
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1752
								.filter(x -> x.getRolledBackTimestamp() == null
1753
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1754
								.collect(Collectors.toList());
1755
						Collections.reverse(sios);
1756
						for (SchemeInOut sio : sios) {
1757
							sio.setRolledBackTimestamp(LocalDateTime.now());
1758
							amountToRollback += sio.getAmount();
1759
							// sio.setSchemeType(SchemeType.OUT);
1760
							sio.setSerialNumber(serialNumber);
1761
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1762
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1763
							rolledbackSios.add(sio);
24623 amit.gupta 1764
						}
24635 amit.gupta 1765
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1766
					} else {
1767
						serialNumbersConsidered.add(serialNumber);
1768
						List<Integer> schemesConsidered = new ArrayList<>();
1769
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1770
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1771
								.filter(x -> x.getRolledBackTimestamp() == null
1772
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1773
								.collect(Collectors.toList());
1774
						Collections.reverse(sios);
1775
						for (SchemeInOut sio : sios) {
1776
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1777
								schemesConsidered.add(sio.getSchemeId());
1778
								continue;
1779
							}
1780
							sio.setRolledBackTimestamp(LocalDateTime.now());
1781
							amountToRollback += sio.getAmount();
1782
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1783
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1784
							sio.setSerialNumber(serialNumber);
1785
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1786
							rolledbackSios.add(sio);
1787
						}
24615 amit.gupta 1788
					}
24631 amit.gupta 1789
 
24604 amit.gupta 1790
				}
24590 amit.gupta 1791
			}
24631 amit.gupta 1792
			if (amountToRollback > 0) {
1793
				UserWalletHistory uwh = new UserWalletHistory();
1794
				uwh.setAmount(Math.round(amountToRollback));
1795
				uwh.setDescription(description);
1796
				uwh.setTimestamp(LocalDateTime.now());
1797
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1798
				uwh.setReference(fofoOrder.getId());
1799
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1800
				uwh.setFofoId(fofoOrder.getFofoId());
1801
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1802
				userWalletHistory.add(uwh);
1803
			}
24590 amit.gupta 1804
		});
24598 amit.gupta 1805
 
24592 amit.gupta 1806
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1807
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1808
						"Timestamp"),
1809
				userWalletHistory.stream()
1810
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1811
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1812
						.collect(Collectors.toList()));
1813
 
1814
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1815
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1816
						"Rolledback"),
1817
				rolledbackSios.stream()
1818
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1819
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1820
						.collect(Collectors.toList()));
1821
 
30752 tejbeer 1822
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1823
				"Partner Excess Amount Scheme Out", "PFA",
30752 tejbeer 1824
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1825
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1826
 
25267 amit.gupta 1827
		throw new Exception();
24590 amit.gupta 1828
	}
24615 amit.gupta 1829
 
24611 amit.gupta 1830
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1831
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1832
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1833
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1834
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1835
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1836
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1837
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1838
		references.stream().forEach(reference -> {
1839
			FofoOrder fofoOrder = null;
1840
			try {
1841
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1842
			} catch (Exception e) {
1843
 
24611 amit.gupta 1844
			}
1845
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1846
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1847
			float amountToRollback = 0;
1848
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1849
			orderItems.forEach(x -> {
1850
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1851
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1852
			});
1853
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1854
				List<SchemeInOut> sios = schemeInOutRepository
1855
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1856
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1857
						.collect(Collectors.toList());
1858
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1859
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1860
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1861
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1862
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1863
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1864
					if (outList.size() > 1) {
1865
 
24611 amit.gupta 1866
					}
1867
				}
1868
				uwh.setAmount(Math.round(amountToRollback));
1869
				uwh.setDescription(description);
1870
				uwh.setTimestamp(LocalDateTime.now());
1871
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1872
				uwh.setReference(fofoOrder.getId());
1873
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1874
				uwh.setFofoId(fofoOrder.getFofoId());
1875
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1876
				userWalletHistory.add(uwh);
1877
			}
1878
		});
24615 amit.gupta 1879
 
24611 amit.gupta 1880
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1881
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1882
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
30752 tejbeer 1883
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1884
						.collect(Collectors.toList()));
1885
 
24611 amit.gupta 1886
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1887
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1888
						"Rolledback"),
1889
				rolledbackSios.stream()
24615 amit.gupta 1890
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1891
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1892
						.collect(Collectors.toList()));
1893
 
24623 amit.gupta 1894
		Utils.sendMailWithAttachments(googleMailSender,
30752 tejbeer 1895
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1896
				"Partner Excess Amount", "PFA",
30752 tejbeer 1897
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1898
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1899
 
24628 amit.gupta 1900
		throw new Exception();
24615 amit.gupta 1901
 
24611 amit.gupta 1902
	}
24615 amit.gupta 1903
 
26945 amit.gupta 1904
	public void sendDailySalesNotificationToPartner(Integer fofoIdInt) throws Exception {
25927 amit.gupta 1905
 
24653 govind 1906
		LocalDateTime now = LocalDateTime.now();
25837 amit.gupta 1907
		LocalDateTime from = now.with(LocalTime.MIN);
25925 amit.gupta 1908
		String timeString = "Today %s";
25927 amit.gupta 1909
		// Send yesterday's report
27007 amit.gupta 1910
		/*
1911
		 * if (now.getHour() < 13) { timeString = "Yesterday %s"; from =
1912
		 * now.minusDays(1).; now = from.with(LocalTime.MAX);
30393 amit.gupta 1913
		 *
27007 amit.gupta 1914
		 * }
1915
		 */
24855 amit.gupta 1916
		List<Integer> fofoIds = null;
25043 amit.gupta 1917
		if (fofoIdInt == null) {
1918
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1919
					.collect(Collectors.toList());
24856 amit.gupta 1920
		} else {
24855 amit.gupta 1921
			fofoIds = Arrays.asList(fofoIdInt);
1922
		}
25912 amit.gupta 1923
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
24683 amit.gupta 1924
 
25865 amit.gupta 1925
		Map<Integer, Float> partnerPolicyAmountMap = insurancePolicyRepository.selectAmountSumGroupByRetailerId(now,
1926
				null);
1927
		Map<Integer, Long> partnerPolicyQtyMap = insurancePolicyRepository.selectQtyGroupByRetailerId(now, null);
26945 amit.gupta 1928
 
1929
		Map<Integer, Double> spPartnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1930
				true);
1931
 
1932
		Map<Integer, Double> spPartner3DaysOrderValMap = fofoOrderItemRepository
1933
				.selectSumAmountGroupByRetailer(from.minusDays(3), now, 0, true);
26941 amit.gupta 1934
		Map<Integer, Long> spPartnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, true);
1935
 
26945 amit.gupta 1936
		Map<Integer, Double> partnerOrderValMap = fofoOrderItemRepository.selectSumAmountGroupByRetailer(from, now, 0,
1937
				false);
26941 amit.gupta 1938
		Map<Integer, Long> partnerOrderQtyMap = fofoOrderItemRepository.selectQtyGroupByRetailer(from, now, 0, false);
26945 amit.gupta 1939
 
25865 amit.gupta 1940
		Map<Integer, SaleTargetReportModel> saleTargetReportModelMap = new HashMap<>();
1941
		for (int fofoId : fofoIds) {
1942
			SaleTargetReportModel model = new SaleTargetReportModel();
25927 amit.gupta 1943
			model.setInsuranceSale(
1944
					partnerPolicyAmountMap.containsKey(fofoId) ? partnerPolicyAmountMap.get(fofoId).doubleValue() : 0);
25865 amit.gupta 1945
			model.setInsruanceQty(partnerPolicyQtyMap.containsKey(fofoId) ? partnerPolicyQtyMap.get(fofoId) : 0);
26941 amit.gupta 1946
			model.setSmartphoneSale(spPartnerOrderValMap.containsKey(fofoId) ? spPartnerOrderValMap.get(fofoId) : 0);
1947
			model.setSmartphoneQty(spPartnerOrderQtyMap.containsKey(fofoId) ? spPartnerOrderQtyMap.get(fofoId) : 0);
1948
			model.setTotalSale(partnerOrderValMap.containsKey(fofoId) ? partnerOrderValMap.get(fofoId) : 0);
1949
			model.setTotalQty(partnerOrderQtyMap.containsKey(fofoId) ? partnerOrderQtyMap.get(fofoId) : 0);
26945 amit.gupta 1950
			model.setPast3daysSale(
1951
					spPartner3DaysOrderValMap.containsKey(fofoId) ? spPartner3DaysOrderValMap.get(fofoId) : 0);
25880 amit.gupta 1952
			model.setFofoId(fofoId);
25865 amit.gupta 1953
			saleTargetReportModelMap.put(fofoId, model);
1954
		}
25880 amit.gupta 1955
 
26945 amit.gupta 1956
		Map<Integer, FofoReportingModel> partnerSalesHeadersMap = this.getPartnerIdSalesHeaders();
24653 govind 1957
		for (Integer fofoId : fofoIds) {
25865 amit.gupta 1958
			SaleTargetReportModel model = saleTargetReportModelMap.get(fofoId);
30982 tejbeer 1959
 
1960
			com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
1961
 
1962
			Address address = addressRepository.selectById(user.getAddressId());
1963
 
1964
			String title = "Sale Update";
1965
			String messageTemplate = String.format("Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1966
					model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1967
					String.format(timeString, now.format(timeFormatter)));
25821 amit.gupta 1968
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
1969
			sendNotificationModel.setCampaignName("Sales update alert");
30982 tejbeer 1970
			sendNotificationModel.setTitle(title);
1971
			sendNotificationModel.setMessage(messageTemplate);
25821 amit.gupta 1972
			sendNotificationModel.setType("url");
27206 tejbeer 1973
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
25821 amit.gupta 1974
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1975
			sendNotificationModel.setMessageType(MessageType.notification);
25872 tejbeer 1976
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1977
			sendNotificationModel.setUserIds(Arrays.asList(userId));
25854 amit.gupta 1978
			notificationService.sendNotification(sendNotificationModel);
30999 tejbeer 1979
			String whatsappMessageTemplate = String.format(
1980
					"Dear Partner, Your sale update is Smartphones Rs.%.0f, Insurance Rs.%.0f, Total Rs.%.0f till %s.",
1981
					model.getSmartphoneSale(), model.getInsuranceSale(), model.getTotalSale(),
1982
					String.format(timeString, now.format(timeFormatter)));
1983
			notificationService.sendWhatsappMessage(whatsappMessageTemplate, title, address.getPhoneNumber());
30982 tejbeer 1984
 
24653 govind 1985
		}
26945 amit.gupta 1986
		// String saleReport = this.getDailySalesReportHtml(partnerSalesHeadersMap,
1987
		// saleTargetReportModelMap);
1988
		String statewiseSaleReport = this.getStateWiseSales(saleTargetReportModelMap, partnerSalesHeadersMap);
30752 tejbeer 1989
		String cc[] = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "niranjan.kala@smartdukaan.com",
1990
				"sm@smartdukaan.com" };
25837 amit.gupta 1991
 
25912 amit.gupta 1992
		String subject = String.format("Sale till %s", String.format(timeString, now.format(timeFormatter)));
26945 amit.gupta 1993
		// this.sendMailOfHtmlFomat("amit.gupta@smartukaan.com", saleReport, cc,
1994
		// subject);
1995
		this.sendMailOfHtmlFormat("amit.gupta@smartdukaan.com", statewiseSaleReport, cc, "Statewise" + subject);
24653 govind 1996
	}
1997
 
28377 tejbeer 1998
	public void checkRazorPayPaymentStatus() throws Exception {
28368 tejbeer 1999
		List<PendingOrder> pendingOrder = pendingOrderRepository
2000
				.selectAllByStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PENDING);
2001
 
2002
		for (PendingOrder po : pendingOrder) {
2003
			RazorPay razorPay = razorPayRepository.selectByOrdeId(po.getId());
28377 tejbeer 2004
			List<PendingOrderItem> poItems = pendingOrderItemRepository.selectByOrderId(po.getId());
28368 tejbeer 2005
 
28369 tejbeer 2006
			LOGGER.info("razorPay" + razorPay);
2007
			if (razorPay != null) {
2008
				List<Payment> payments = razorPaymentService.fetchOrderForPayment(razorPay.getRazorOrderId());
28377 tejbeer 2009
 
28369 tejbeer 2010
				if (!payments.isEmpty()) {
28377 tejbeer 2011
					List<String> statusList = new ArrayList<>();
28369 tejbeer 2012
					for (Payment payment : payments) {
28368 tejbeer 2013
 
28377 tejbeer 2014
						JSONObject jsonObj = new JSONObject(payment.toString());
2015
 
2016
						String status = jsonObj.getString("status");
2017
 
2018
						statusList.add(status);
2019
 
28369 tejbeer 2020
					}
28377 tejbeer 2021
					LOGGER.info("statusList" + statusList);
28368 tejbeer 2022
 
28377 tejbeer 2023
					if (statusList.contains("authorized") || statusList.contains("captured")) {
2024
						po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
2025
						po.setPaidAmount(po.getTotalAmount());
2026
						for (PendingOrderItem poi : poItems) {
2027
							poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.PROCESSING);
2028
						}
2029
						Map<String, Object> emailModel = pendingOrderService.sendCreateOrderMail(po);
2030
 
2031
						CustomRetailer customRetailer = retailerService.getFofoRetailer(po.getFofoId());
2032
						Customer customer = customerRepository.selectById(po.getCustomerId());
2033
						String[] customerEmail = null;
2034
						if (customer.getEmailId() != null) {
30752 tejbeer 2035
							customerEmail = new String[] { customer.getEmailId() };
28377 tejbeer 2036
						}
2037
						List<String> bccTo = Arrays.asList("kamini.sharma@smartdukaan.com",
28467 tejbeer 2038
								"tarun.verma@smartdukaan.com", "niranjan.kala@smartdukaan.com", "sm@smartdukaan.com",
2039
								"tejbeer.kaur@shop2020.in", customRetailer.getEmail());
28377 tejbeer 2040
						List<String> authUserEmails = csService.getAuthUserByPartnerId(customRetailer.getPartnerId());
2041
						if (authUserEmails != null) {
2042
							authUserEmails = new ArrayList<>();
2043
						}
2044
						authUserEmails.addAll(bccTo);
2045
 
28382 tejbeer 2046
						// emailService.sendMailWithAttachments("Order Created with SmartDukaan",
2047
						// "order-confirm.vm",
2048
						// emailModel, customerEmail, null, authUserEmails.toArray(new String[0]));
28377 tejbeer 2049
 
2050
					} else if (statusList.contains("refunded") || statusList.contains("failed")) {
2051
						for (PendingOrderItem poi : poItems) {
2052
							poi.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
2053
						}
2054
 
2055
						po.setStatus(com.spice.profitmandi.dao.enumuration.transaction.OrderStatus.FAILED);
2056
					}
2057
 
28369 tejbeer 2058
				}
28377 tejbeer 2059
				// LOGGER.info("payment" + payments);
28369 tejbeer 2060
 
2061
			}
28368 tejbeer 2062
		}
2063
	}
2064
 
25865 amit.gupta 2065
	public static class SaleTargetReportModel {
2066
		private double totalSale;
26941 amit.gupta 2067
		private long totalQty;
26945 amit.gupta 2068
		private double past3daysSale;
25880 amit.gupta 2069
		private int fofoId;
2070
 
2071
		public int getFofoId() {
2072
			return fofoId;
2073
		}
2074
 
2075
		public void setFofoId(int fofoId) {
2076
			this.fofoId = fofoId;
2077
		}
2078
 
25865 amit.gupta 2079
		private double smartphoneSale;
2080
		private long smartphoneQty;
2081
		private double insuranceSale;
2082
		private long insruanceQty;
2083
 
26941 amit.gupta 2084
		public long getTotalQty() {
2085
			return totalQty;
2086
		}
2087
 
2088
		public void setTotalQty(long totalQty) {
2089
			this.totalQty = totalQty;
2090
		}
2091
 
26945 amit.gupta 2092
		public double getPast3daysSale() {
2093
			return past3daysSale;
2094
		}
2095
 
2096
		public void setPast3daysSale(double past3daysSale) {
2097
			this.past3daysSale = past3daysSale;
2098
		}
2099
 
25865 amit.gupta 2100
		@Override
2101
		public int hashCode() {
2102
			final int prime = 31;
2103
			int result = 1;
25880 amit.gupta 2104
			result = prime * result + fofoId;
25865 amit.gupta 2105
			result = prime * result + (int) (insruanceQty ^ (insruanceQty >>> 32));
2106
			long temp;
2107
			temp = Double.doubleToLongBits(insuranceSale);
2108
			result = prime * result + (int) (temp ^ (temp >>> 32));
2109
			result = prime * result + (int) (smartphoneQty ^ (smartphoneQty >>> 32));
2110
			temp = Double.doubleToLongBits(smartphoneSale);
2111
			result = prime * result + (int) (temp ^ (temp >>> 32));
26941 amit.gupta 2112
			result = prime * result + (int) (totalQty ^ (totalQty >>> 32));
25865 amit.gupta 2113
			temp = Double.doubleToLongBits(totalSale);
2114
			result = prime * result + (int) (temp ^ (temp >>> 32));
2115
			return result;
2116
		}
2117
 
2118
		@Override
2119
		public boolean equals(Object obj) {
2120
			if (this == obj)
2121
				return true;
2122
			if (obj == null)
2123
				return false;
2124
			if (getClass() != obj.getClass())
2125
				return false;
2126
			SaleTargetReportModel other = (SaleTargetReportModel) obj;
25880 amit.gupta 2127
			if (fofoId != other.fofoId)
2128
				return false;
25865 amit.gupta 2129
			if (insruanceQty != other.insruanceQty)
2130
				return false;
2131
			if (Double.doubleToLongBits(insuranceSale) != Double.doubleToLongBits(other.insuranceSale))
2132
				return false;
2133
			if (smartphoneQty != other.smartphoneQty)
2134
				return false;
2135
			if (Double.doubleToLongBits(smartphoneSale) != Double.doubleToLongBits(other.smartphoneSale))
2136
				return false;
26941 amit.gupta 2137
			if (totalQty != other.totalQty)
2138
				return false;
25865 amit.gupta 2139
			if (Double.doubleToLongBits(totalSale) != Double.doubleToLongBits(other.totalSale))
2140
				return false;
2141
			return true;
2142
		}
2143
 
2144
		public double getTotalSale() {
2145
			return totalSale;
2146
		}
2147
 
2148
		public void setTotalSale(double totalSale) {
2149
			this.totalSale = totalSale;
2150
		}
2151
 
2152
		public double getSmartphoneSale() {
2153
			return smartphoneSale;
2154
		}
2155
 
2156
		public void setSmartphoneSale(double smartphoneSale) {
2157
			this.smartphoneSale = smartphoneSale;
2158
		}
2159
 
2160
		public long getSmartphoneQty() {
2161
			return smartphoneQty;
2162
		}
2163
 
2164
		public void setSmartphoneQty(long smartphoneQty) {
2165
			this.smartphoneQty = smartphoneQty;
2166
		}
2167
 
2168
		public double getInsuranceSale() {
2169
			return insuranceSale;
2170
		}
2171
 
2172
		public void setInsuranceSale(double insuranceSale) {
2173
			this.insuranceSale = insuranceSale;
2174
		}
2175
 
2176
		public long getInsruanceQty() {
2177
			return insruanceQty;
2178
		}
2179
 
2180
		public void setInsruanceQty(long insruanceQty) {
2181
			this.insruanceQty = insruanceQty;
2182
		}
2183
 
2184
		@Override
2185
		public String toString() {
26945 amit.gupta 2186
			return "SaleTargetReportModel [totalSale=" + totalSale + ", totalQty=" + totalQty + ", past3daysSale="
2187
					+ past3daysSale + ", fofoId=" + fofoId + ", smartphoneSale=" + smartphoneSale + ", smartphoneQty="
2188
					+ smartphoneQty + ", insuranceSale=" + insuranceSale + ", insruanceQty=" + insruanceQty + "]";
25865 amit.gupta 2189
		}
2190
 
2191
	}
2192
 
26945 amit.gupta 2193
	private String getStateWiseSales(Map<Integer, SaleTargetReportModel> saleTargetReportModelMap,
30752 tejbeer 2194
			Map<Integer, FofoReportingModel> partnerSalesHeadersMap) throws Exception {
26940 amit.gupta 2195
		List<FofoStore> stores = fofoStoreRepository.selectActiveStores();
26945 amit.gupta 2196
		Map<String, List<Integer>> stateMap = stores.stream().collect(Collectors
2197
				.groupingBy(x -> x.getCode().substring(0, 2), Collectors.mapping(x -> x.getId(), Collectors.toList())));
26940 amit.gupta 2198
		List<List<Serializable>> stateWiseSales = new ArrayList<>();
2199
		for (Map.Entry<String, List<Integer>> stateMapEntry : stateMap.entrySet()) {
26945 amit.gupta 2200
			long totalQty = stateMapEntry.getValue().stream()
2201
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getTotalQty()));
2202
			double totalSale = stateMapEntry.getValue().stream()
2203
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getTotalSale()));
2204
			long smartPhoneQty = stateMapEntry.getValue().stream()
2205
					.collect(Collectors.summingLong(x -> saleTargetReportModelMap.get(x).getSmartphoneQty()));
2206
			double smartPhoneSale = stateMapEntry.getValue().stream()
2207
					.collect(Collectors.summingDouble(x -> saleTargetReportModelMap.get(x).getSmartphoneSale()));
2208
			stateWiseSales
2209
					.add(Arrays.asList(stateMapEntry.getKey(), smartPhoneQty, smartPhoneSale, totalQty, totalSale));
26940 amit.gupta 2210
		}
2211
		StringBuilder sb = new StringBuilder();
26945 amit.gupta 2212
		sb.append("<html><body>");
2213
		sb.append("<p>Statewise Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
26940 amit.gupta 2214
		sb.append("<tbody>\n" + "	    <tr>"
2215
				+ "	    					<th style='border:1px solid black;padding: 5px'>State</th>"
26941 amit.gupta 2216
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
2217
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Value</th>"
2218
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Qty</th>"
2219
				+ "	    					<th style='border:1px solid black;padding: 5px'>Total Value</th>"
26940 amit.gupta 2220
				+ "	    				</tr>");
2221
		for (List<Serializable> stateSale : stateWiseSales) {
2222
			sb.append("<tr>");
2223
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(0) + "</td>");
2224
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(1) + "</td>");
2225
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(2) + "</td>");
26941 amit.gupta 2226
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(3) + "</td>");
2227
			sb.append("<td style='border:1px solid black;padding: 5px'>" + stateSale.get(4) + "</td>");
26940 amit.gupta 2228
			sb.append("</tr>");
2229
		}
26945 amit.gupta 2230
		sb.append("</tbody></table><br><br>");
25872 tejbeer 2231
 
26945 amit.gupta 2232
		sb.append("<p>Sale Report:</p><br/><table style='border:1px solid black';cellspacing=0>");
24653 govind 2233
		sb.append("<tbody>\n" + "	    				<tr>\n"
26945 amit.gupta 2234
				+ "	    					<th style='border:1px solid black;padding: 5px'>Code</th>"
2235
				+ "	    					<th style='border:1px solid black;padding: 5px'>Business Name</th>"
2236
				+ "	    					<th style='border:1px solid black;padding: 5px'>Regional Manager</th>"
2237
				+ "	    					<th style='border:1px solid black;padding: 5px'>Territory Manager</th>"
2238
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>"
2239
				+ "	    					<th style='border:1px solid black;padding: 5px'>Smartphone Sale</th>"
2240
				+ "	    					<th style='border:1px solid black;padding: 5px'>SmartPhone Qty</th>"
24653 govind 2241
				+ "	    				</tr>");
26945 amit.gupta 2242
 
30765 tejbeer 2243
		/*
2244
		 * List<Integer> sortedPartnerSalesHeaders =
2245
		 * partnerSalesHeadersMap.values().stream()
2246
		 * .sorted(Comparator.comparing(FofoReportingModel::getCode)
2247
		 * .thenComparing(FofoReportingModel::getRegionalManager)
2248
		 * .thenComparing(FofoReportingModel::getTerritoryManager))
2249
		 * .map(FofoReportingModel::getFofoId).collect(Collectors.toList());
2250
		 */
2251
 
2252
		List<Integer> sortedSaleTargetReport = saleTargetReportModelMap.values().stream()
2253
				.sorted(Comparator.comparing(SaleTargetReportModel::getTotalSale)).map(SaleTargetReportModel::getFofoId)
2254
				.collect(Collectors.toList());
2255
		for (Integer fofoId : sortedSaleTargetReport) {
27007 amit.gupta 2256
			if (saleTargetReportModelMap.get(fofoId).getPast3daysSale() == 0) {
26947 amit.gupta 2257
				sb.append("<tr style='background-color:red'>");
2258
			} else {
26945 amit.gupta 2259
				sb.append("<tr>");
2260
			}
2261
			sb.append("<td style='border:1px solid black;padding: 5px'>" + partnerSalesHeadersMap.get(fofoId).getCode()
25880 amit.gupta 2262
					+ "</td>");
2263
			sb.append("<td style='border:1px solid black;padding: 5px'>"
27007 amit.gupta 2264
					+ partnerSalesHeadersMap.get(fofoId).getBusinessName() + "</td>");
2265
			sb.append("<td style='border:1px solid black;padding: 5px'>"
2266
					+ partnerSalesHeadersMap.get(fofoId).getRegionalManager() + "</td>");
2267
			sb.append("<td style='border:1px solid black;padding: 5px'>"
2268
					+ partnerSalesHeadersMap.get(fofoId).getTerritoryManager() + "</td>");
2269
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 2270
					+ saleTargetReportModelMap.get(fofoId).getTotalSale() + "</td>");
25880 amit.gupta 2271
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 2272
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneSale() + "</td>");
25880 amit.gupta 2273
			sb.append("<td style='border:1px solid black;padding: 5px'>"
26945 amit.gupta 2274
					+ saleTargetReportModelMap.get(fofoId).getSmartphoneQty() + "</td>");
25865 amit.gupta 2275
			sb.append("</tr>");
24653 govind 2276
		}
24683 amit.gupta 2277
 
26945 amit.gupta 2278
		sb.append("</tr>");
2279
 
2280
		sb.append("</body></html>");
2281
 
2282
		return sb.toString();
24653 govind 2283
	}
24841 govind 2284
 
26945 amit.gupta 2285
	private void sendMailOfHtmlFormat(String email, String body, String cc[], String subject)
24841 govind 2286
			throws MessagingException, ProfitMandiBusinessException, IOException {
2287
		MimeMessage message = mailSender.createMimeMessage();
2288
		MimeMessageHelper helper = new MimeMessageHelper(message);
2289
		helper.setSubject(subject);
2290
		helper.setText(body, true);
2291
		helper.setTo(email);
2292
		if (cc != null) {
2293
			helper.setCc(cc);
2294
		}
2295
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
2296
		helper.setFrom(senderAddress);
2297
		mailSender.send(message);
2298
	}
25300 tejbeer 2299
 
25351 tejbeer 2300
	public void sendNotification() throws Exception {
25300 tejbeer 2301
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
2302
		if (!pushNotifications.isEmpty()) {
2303
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 2304
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 2305
				NotificationCampaign notificationCampaign = notificationCampaignRepository
2306
						.selectById(pushNotification.getNotificationCampaignid());
2307
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
2308
						SimpleCampaignParams.class);
2309
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 2310
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 2311
				JSONObject json = new JSONObject();
25351 tejbeer 2312
				json.put("to", device.getFcmId());
25300 tejbeer 2313
				JSONObject jsonObj = new JSONObject();
2314
				jsonObj.put("message", campaign.getMessage());
2315
				jsonObj.put("title", campaign.getTitle());
2316
				jsonObj.put("type", campaign.getType());
2317
				jsonObj.put("url", result_url);
2318
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
2319
				jsonObj.put("image", campaign.getImageUrl());
2320
				jsonObj.put("largeIcon", "large_icon");
2321
				jsonObj.put("smallIcon", "small_icon");
2322
				jsonObj.put("vibrate", 1);
2323
				jsonObj.put("pid", pushNotification.getId());
2324
				jsonObj.put("sound", 1);
2325
				jsonObj.put("priority", "high");
2326
				json.put("data", jsonObj);
25351 tejbeer 2327
				try {
2328
					CloseableHttpClient client = HttpClients.createDefault();
2329
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 2330
 
25351 tejbeer 2331
					httpPost.setHeader("Content-Type", "application/json; utf-8");
2332
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
2333
					StringEntity entity = new StringEntity(json.toString());
2334
					httpPost.setEntity(entity);
2335
					CloseableHttpResponse response = client.execute(httpPost);
25300 tejbeer 2336
 
25351 tejbeer 2337
					if (response.getStatusLine().getStatusCode() == 200) {
2338
						pushNotification.setSentTimestamp(LocalDateTime.now());
2339
					} else {
25356 tejbeer 2340
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25778 amit.gupta 2341
						LOGGER.info("message" + "not sent");
26945 amit.gupta 2342
						response.toString();
25351 tejbeer 2343
					}
25300 tejbeer 2344
 
25351 tejbeer 2345
				} catch (Exception e) {
2346
					e.printStackTrace();
26443 amit.gupta 2347
					pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
26436 amit.gupta 2348
					LOGGER.info("message " + "not sent " + e.getMessage());
25300 tejbeer 2349
				}
2350
			}
2351
		}
2352
	}
2353
 
25553 amit.gupta 2354
	public void grouping() throws Exception {
25609 amit.gupta 2355
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm");
2356
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByStatus(PriceDropImeiStatus.APPROVED);
2357
		System.out.println(String.join("\t",
2358
				Arrays.asList("IMEI", "ItemId", "Brand", "Model Name", "Model Number", "Franchise Id", "Franchise Name",
25694 amit.gupta 2359
						"Grn On", "Price Dropped On", "Approved On", "Returned On", "Price Drop Paid", "Is Doa")));
26963 amit.gupta 2360
		Map<Integer, CustomRetailer> retailersMap = retailerService.getFofoRetailers(false);
25609 amit.gupta 2361
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
25694 amit.gupta 2362
			if (priceDropIMEI.getPartnerId() == 0)
2363
				continue;
25609 amit.gupta 2364
			HashSet<String> imeis = new HashSet<>();
2365
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropIMEI.getPriceDropId());
2366
			imeis.add(priceDropIMEI.getImei());
2367
			List<InventoryItem> inventoryItems = inventoryItemRepository
2368
					.selectByFofoIdSerialNumbers(priceDropIMEI.getPartnerId(), imeis, false);
25694 amit.gupta 2369
			if (inventoryItems.size() == 0) {
2370
				LOGGER.info("Need to investigate partnerId - {} imeis - {}", priceDropIMEI.getPartnerId(), imeis);
25613 amit.gupta 2371
				continue;
25612 amit.gupta 2372
			}
25609 amit.gupta 2373
			InventoryItem inventoryItem = inventoryItems.get(0);
2374
			CustomRetailer customRetailer = retailersMap.get(inventoryItem.getFofoId());
2375
			if (inventoryItem.getLastScanType().equals(ScanType.DOA_OUT)
2376
					|| inventoryItem.getLastScanType().equals(ScanType.PURCHASE_RET)) {
2377
				// check if pricedrop has been rolled out
2378
				List<UserWalletHistory> uwh = walletService.getAllByReference(inventoryItem.getFofoId(),
2379
						priceDropIMEI.getPriceDropId(), WalletReferenceType.PRICE_DROP);
2380
				if (uwh.size() > 0) {
25615 amit.gupta 2381
					Item item = itemRepository.selectById(inventoryItem.getItemId());
30965 tejbeer 2382
					System.out.println(String.join("\t",
2383
							Arrays.asList(priceDropIMEI.getImei(), inventoryItem.getItemId() + "", item.getBrand(),
2384
									item.getModelName(), item.getModelNumber(), inventoryItem.getFofoId() + "",
2385
									customRetailer.getBusinessName(), inventoryItem.getCreateTimestamp().format(dtf),
2386
									priceDrop.getAffectedOn().format(dtf),
2387
									priceDropIMEI.getUpdateTimestamp().format(dtf),
2388
									inventoryItem.getUpdateTimestamp().format(dtf),
2389
									priceDrop.getAutoPartnerPayout(inventoryItem.getUpdateTimestamp()) + "",
2390
									inventoryItem.getLastScanType().equals(ScanType.DOA_OUT) + "")));
25609 amit.gupta 2391
				}
2392
			}
2393
		}
25503 amit.gupta 2394
	}
29668 tejbeer 2395
 
29566 amit.gupta 2396
	public void toffeeRollback() throws Exception {
2397
		toffeeService.cancelPolicyCopy("110143521986");
2398
		toffeeService.getOrderId("110143521986");
2399
	}
25694 amit.gupta 2400
 
27686 amit.gupta 2401
	public void attachToffeeInvoices() throws Exception {
28205 tejbeer 2402
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(3,
2403
				Optional.of(false));
2404
		for (InsurancePolicy insurancePolicy : insurancePolicies) {
27678 amit.gupta 2405
			String invoiceNumber = insurancePolicy.getInvoiceNumber();
2406
			FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
30321 amit.gupta 2407
			InvoicePdfModel pdfModel = orderService.getInvoicePdfModel(fofoOrder.getId());
27678 amit.gupta 2408
			java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
2409
			PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
28205 tejbeer 2410
			String pdfInvoiceString = "data:application/pdf;base64,"
2411
					+ Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
2412
			boolean attached = toffeeService.attachInvoice(insurancePolicy.getPolicyNumber().split("#")[1],
2413
					pdfInvoiceString);
2414
			if (attached) {
27678 amit.gupta 2415
				insurancePolicy.setPosted(true);
2416
			}
2417
		}
25694 amit.gupta 2418
	}
2419
 
30858 amit.gupta 2420
	public void sendBAGPendingPolicies() throws Exception {
2421
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectAllByProviderId(4,
2422
				Optional.of(false));
2423
		for (InsurancePolicy insurancePolicy : insurancePolicies) {
2424
			String invoiceNumber = insurancePolicy.getInvoiceNumber();
2425
			FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
2426
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId()).get(0);
2427
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
2428
			Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
2429
			BAGInsuranceModel bagInsuranceModel = new BAGInsuranceModel();
30913 tejbeer 2430
			// bagInsuranceModel.setModelId();
30858 amit.gupta 2431
			bagInsuranceModel.setAddressLine1(customerAddress.getLine1());
2432
			bagInsuranceModel.setAddressLine2(customerAddress.getLine2());
2433
			bagInsuranceModel.setCity(customerAddress.getCity());
2434
			bagInsuranceModel.setBrandWarranty("1 Year");
2435
			Item item = itemRepository.selectById(fofoOrderItem.getId());
2436
			bagInsuranceModel.setModelName(item.getItemDescription());
2437
			bagInsuranceModel.setDateOfPurchase(fofoOrder.getFormattedDate());
2438
			bagInsuranceModel.setEmail(customer.getEmailId());
2439
			bagInsuranceModel.setImei1(insurancePolicy.getSerialNumber());
2440
			bagInsuranceModel.setFirstName(customer.getFirstName());
2441
			bagInsuranceModel.setLastName(customer.getLastName());
2442
			bagInsuranceModel.setMobileNumber(customer.getMobileNumber());
2443
			bagInsuranceModel.setPlanId("");
2444
			insurancePolicy.setPosted(true);
2445
		}
2446
	}
2447
 
25694 amit.gupta 2448
	public void schemeRollback(List<String> schemeIds) throws Exception {
2449
		List<Integer> schemeIdsInt = schemeIds.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
25708 amit.gupta 2450
		Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIdsInt, 0, schemeIds.size()).stream()
25694 amit.gupta 2451
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
2452
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIdsInt));
2453
		for (SchemeInOut sio : schemeInOuts) {
2454
			Scheme scheme = schemesMap.get(sio.getSchemeId());
2455
			if (scheme.getType().equals(SchemeType.IN)) {
2456
 
2457
			} else if (scheme.getType().equals(SchemeType.OUT)) {
2458
				InventoryItem inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
2459
				List<ScanRecord> sr = scanRecordRepository.selectByInventoryItemId(sio.getInventoryItemId());
2460
				ScanRecord scanRecord = sr.stream().filter(x -> x.getType().equals(ScanType.SALE))
2461
						.max((x1, x2) -> x1.getCreateTimestamp().compareTo(x2.getCreateTimestamp())).get();
2462
				if (scanRecord.getCreateTimestamp().isAfter(scheme.getEndDateTime())
2463
						|| scanRecord.getCreateTimestamp().isBefore(scheme.getStartDateTime())) {
2464
					sio.setRolledBackTimestamp(LocalDateTime.now());
2465
					FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.getOrderId());
25709 amit.gupta 2466
					String rollbackReason = "Scheme reversed for "
2467
							+ itemRepository.selectById(inventoryItem.getItemId()).getItemDescription() + "/Inv - "
25694 amit.gupta 2468
							+ fofoOrder.getInvoiceNumber();
2469
					walletService.rollbackAmountFromWallet(scanRecord.getFofoId(), sio.getAmount(),
26945 amit.gupta 2470
							scanRecord.getOrderId(), WalletReferenceType.SCHEME_OUT, rollbackReason,
2471
							LocalDateTime.now());
25694 amit.gupta 2472
					System.out.printf("Amount %f,SchemeId %d,Reason %s\n", sio.getAmount(), sio.getSchemeId(),
2473
							rollbackReason);
2474
				}
2475
			}
2476
		}
25721 tejbeer 2477
		// throw new Exception();
25694 amit.gupta 2478
	}
25721 tejbeer 2479
 
2480
	public void checkfocusedModelInPartnerStock() throws Exception {
2481
 
2482
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
2483
				.collect(Collectors.toList());
27212 tejbeer 2484
		Map<Integer, Map<Integer, List<SaholicCIS>>> warehouseItemAvailabilityMap = saholicInventoryService
2485
				.getSaholicStock();
27213 tejbeer 2486
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2487
		Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = this.getPartnerIdSalesHeaders();
27212 tejbeer 2488
 
2489
		Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService
2490
				.getSaholicPOItems();
25721 tejbeer 2491
		Map<Integer, List<FocusedModelShortageModel>> focusedModelShortageReportMap = new HashMap<>();
2492
		for (Integer fofoId : fofoIds) {
27102 amit.gupta 2493
			List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
2494
			focusedModelShortageReportMap.put(fofoId, focusedModelShortageList);
25721 tejbeer 2495
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2496
			Map<Integer, Integer> processingOrderMap = null;
2497
			Map<Integer, Integer> catalogIdAndQtyMap = null;
2498
			Map<Integer, Integer> grnPendingOrdersMap = null;
2499
 
2500
			Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
2501
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
2502
 
2503
			if (!currentInventorySnapshot.isEmpty()) {
2504
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
2505
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2506
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
2507
 
2508
			}
2509
 
2510
			Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
2511
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2512
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2513
			if (!grnPendingOrders.isEmpty()) {
2514
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
2515
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2516
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
2517
 
2518
			}
2519
 
2520
			Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
2521
					.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2522
							Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2523
			if (!processingOrder.isEmpty()) {
2524
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
2525
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2526
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
2527
 
2528
			}
2529
 
25800 tejbeer 2530
			List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
2531
					.collect(Collectors.toList());
2532
 
27088 tejbeer 2533
			List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
2534
					.collect(Collectors.toList());
27095 tejbeer 2535
			LOGGER.info("regionIds" + regionIds);
27102 amit.gupta 2536
			if (regionIds.size() == 0) {
2537
				LOGGER.info("No region found for partner {}", fofoId);
2538
				continue;
2539
			}
27100 amit.gupta 2540
			Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository
27102 amit.gupta 2541
					.selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,
29668 tejbeer 2542
							Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
25800 tejbeer 2543
 
25721 tejbeer 2544
			LOGGER.info("focusedCatalogIdAndQtyMap" + focusedCatalogIdAndQtyMap);
2545
 
27100 amit.gupta 2546
			for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
2547
				int minQty = entry.getValue().get();
25721 tejbeer 2548
				int inStockQty = 0;
2549
				int processingQty = 0;
2550
				int grnPendingQty = 0;
27208 tejbeer 2551
				int allColorNetAvailability = 0;
27253 tejbeer 2552
				int allColorPoAvailability = 0;
25721 tejbeer 2553
				if (processingOrderMap != null) {
2554
					processingQty = (processingOrderMap.get(entry.getKey()) == null) ? 0
2555
							: processingOrderMap.get(entry.getKey());
2556
 
2557
				}
2558
				if (grnPendingOrdersMap != null) {
2559
					grnPendingQty = (grnPendingOrdersMap.get(entry.getKey()) == null) ? 0
2560
							: grnPendingOrdersMap.get(entry.getKey());
2561
 
2562
				}
2563
				if (catalogIdAndQtyMap != null) {
2564
					inStockQty = (catalogIdAndQtyMap.get(entry.getKey()) == null) ? 0
2565
							: catalogIdAndQtyMap.get(entry.getKey());
2566
 
2567
				}
28526 tejbeer 2568
 
2569
				int grnStockQty = grnPendingQty + inStockQty;
25721 tejbeer 2570
				int totalQty = processingQty + grnPendingQty + inStockQty;
2571
 
29801 manish 2572
				int shortageQty = minQty - totalQty;
2573
				List<Item> item = itemRepository.selectAllByCatalogItemId(entry.getKey());
2574
				FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
25721 tejbeer 2575
 
29801 manish 2576
				Map<Integer, List<SaholicCIS>> itemAvailabilityMap = warehouseItemAvailabilityMap
2577
						.get(fofoStore.getWarehouseId());
27213 tejbeer 2578
 
29801 manish 2579
				Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap
2580
						.get(fofoStore.getWarehouseId());
25721 tejbeer 2581
 
29801 manish 2582
				for (Item it : item) {
2583
					List<SaholicCIS> currentAvailability = null;
2584
					List<SaholicPOItem> poItemAvailability = null;
2585
					if (itemAvailabilityMap != null) {
2586
						currentAvailability = itemAvailabilityMap.get(it.getId());
2587
					}
27208 tejbeer 2588
 
29801 manish 2589
					if (poItemAvailabilityMap != null) {
2590
						poItemAvailability = poItemAvailabilityMap.get(it.getId());
2591
					}
2592
					if (currentAvailability != null) {
2593
						allColorNetAvailability += currentAvailability.stream()
2594
								.collect(Collectors.summingInt(SaholicCIS::getNetavailability));
2595
					}
28528 tejbeer 2596
 
29801 manish 2597
					if (poItemAvailability != null) {
2598
						allColorPoAvailability += poItemAvailability.stream()
2599
								.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
27208 tejbeer 2600
					}
2601
 
25721 tejbeer 2602
				}
2603
 
29801 manish 2604
				FocusedModelShortageModel fm = new FocusedModelShortageModel();
2605
				fm.setFofoId(fofoId);
2606
				fm.setStoreCode(fofoStore.getCode());
2607
				fm.setStoreName(customRetailer.getBusinessName());
2608
				fm.setBrandName(item.get(0).getBrand());
2609
				fm.setModelName(item.get(0).getModelName());
2610
				fm.setModelNumber(item.get(0).getModelNumber());
2611
				fm.setGrnStockQty(grnStockQty);
2612
				fm.setPendingIndentQty(processingQty);
2613
				fm.setShortageQty(shortageQty);
2614
				fm.setPoAvailabitiy(allColorPoAvailability);
2615
				fm.setWarehouseName(warehouseMap.get(customRetailer.getWarehouseId()));
2616
				fm.setStateManager(partnerIdSalesHeadersMap.get(fofoId).getRegionalManager());
2617
				fm.setTerritoryManager(partnerIdSalesHeadersMap.get(fofoId).getTerritoryManager());
2618
				fm.setItemName(item.get(0).getBrand() + item.get(0).getModelNumber() + item.get(0).getModelName());
2619
				fm.setAvailabitiy(allColorNetAvailability);
27233 tejbeer 2620
 
29801 manish 2621
				focusedModelShortageList.add(fm);
2622
			}
2623
 
29668 tejbeer 2624
			/*
2625
			 * if (!focusedModelShortageList.isEmpty()) { String subject = "Stock Alert";
2626
			 * String messageText = this.getMessage(focusedModelShortageList);
30393 amit.gupta 2627
			 *
29668 tejbeer 2628
			 * this.sendMailWithAttachments(subject, messageText,
2629
			 * customRetailer.getEmail()); String notificationMessage =
2630
			 * this.getNotificationMessage(focusedModelShortageList);
30393 amit.gupta 2631
			 *
29668 tejbeer 2632
			 * LOGGER.info("notificationMessage" + notificationMessage);
30393 amit.gupta 2633
			 *
29668 tejbeer 2634
			 * SendNotificationModel sendNotificationModel = new SendNotificationModel();
2635
			 * sendNotificationModel.setCampaignName("Stock Alert");
2636
			 * sendNotificationModel.setTitle("Alert");
2637
			 * sendNotificationModel.setMessage(notificationMessage);
2638
			 * sendNotificationModel.setType("url"); sendNotificationModel.setUrl(
2639
			 * "https://app.smartdukaan.com/pages/home/notifications");
2640
			 * sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2641
			 * sendNotificationModel.setMessageType(MessageType.notification); int userId =
2642
			 * userAccountRepository.selectUserIdByRetailerId(fofoId);
2643
			 * sendNotificationModel.setUserIds(Arrays.asList(userId));
2644
			 * notificationService.sendNotification(sendNotificationModel);
30393 amit.gupta 2645
			 *
29668 tejbeer 2646
			 * }
2647
			 */
27233 tejbeer 2648
 
25721 tejbeer 2649
		}
27102 amit.gupta 2650
		if (!focusedModelShortageReportMap.isEmpty()) {
25800 tejbeer 2651
			String fileName = "Stock Alert-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
30215 amit.gupta 2652
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
25837 amit.gupta 2653
			Map<String, List<List<?>>> emailRowsMap = new HashMap<>();
25721 tejbeer 2654
 
25800 tejbeer 2655
			focusedModelShortageReportMap.entrySet().forEach(x -> {
2656
				storeGuyMap.entrySet().forEach(y -> {
2657
 
2658
					if (y.getValue().contains(x.getKey())) {
2659
						if (!emailRowsMap.containsKey(y.getKey())) {
2660
							emailRowsMap.put(y.getKey(), new ArrayList<>());
2661
						}
27208 tejbeer 2662
						List<List<? extends Serializable>> fms = x.getValue().stream()
2663
								.map(r -> Arrays.asList(r.getStoreCode(), r.getStoreName(), r.getBrandName(),
27213 tejbeer 2664
										r.getModelName(), r.getModelNumber(), r.getWarehouseName(), r.getStateManager(),
28526 tejbeer 2665
										r.getTerritoryManager(), r.getPendingIndentQty(), r.getGrnStockQty(),
2666
										r.getShortageQty(), r.getAvailabitiy()))
25800 tejbeer 2667
								.collect(Collectors.toList());
2668
						emailRowsMap.get(y.getKey()).addAll(fms);
2669
 
25721 tejbeer 2670
					}
2671
 
25800 tejbeer 2672
				});
25721 tejbeer 2673
 
2674
			});
2675
 
27212 tejbeer 2676
			List<String> headers = Arrays.asList("Store Code", "Store Name", "Brand", "Model Name", "Model Number",
28526 tejbeer 2677
					"Warehouse Name", "State Manager", "Territory Manager", "Pending Indent", "InStock", "Shortage Qty",
2678
					"Availability");
25837 amit.gupta 2679
			emailRowsMap.entrySet().forEach(entry -> {
25721 tejbeer 2680
 
25800 tejbeer 2681
				ByteArrayOutputStream baos = null;
2682
				try {
25837 amit.gupta 2683
					baos = FileUtil.getCSVByteStream(headers, entry.getValue());
25800 tejbeer 2684
				} catch (Exception e2) {
2685
					e2.printStackTrace();
2686
				}
30752 tejbeer 2687
				String[] sendToArray = new String[] {
28526 tejbeer 2688
 
29996 tejbeer 2689
						entry.getKey()
29995 tejbeer 2690
 
2691
				};
2692
 
25800 tejbeer 2693
				try {
2694
					Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Stock Alert", "PFA", fileName,
2695
							new ByteArrayResource(baos.toByteArray()));
2696
				} catch (Exception e1) { // TODO Auto-generated catch block
2697
					e1.printStackTrace();
2698
				}
25721 tejbeer 2699
 
25800 tejbeer 2700
			});
2701
		}
25721 tejbeer 2702
	}
2703
 
2704
	private String getNotificationMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2705
		StringBuilder sb = new StringBuilder();
2706
		sb.append("Focused Model Shortage in Your Stock : \n");
2707
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
2708
 
2709
			sb.append(entry.getItemName() + "-" + entry.getShortageQty());
2710
			sb.append(String.format("%n", ""));
2711
		}
2712
		return sb.toString();
2713
	}
2714
 
2715
	private void sendMailWithAttachments(String subject, String messageText, String email) throws Exception {
2716
		MimeMessage message = mailSender.createMimeMessage();
2717
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
2718
 
2719
		helper.setSubject(subject);
2720
		helper.setText(messageText, true);
2721
		helper.setTo(email);
27116 amit.gupta 2722
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
25721 tejbeer 2723
		helper.setFrom(senderAddress);
2724
		mailSender.send(message);
2725
 
2726
	}
2727
 
2728
	private String getMessage(List<FocusedModelShortageModel> focusedModelShortageModel) {
2729
		StringBuilder sb = new StringBuilder();
2730
		sb.append("<html><body><p>Alert</p><p>Focused Model Shortage in Your Stock:-</p>"
2731
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2732
		sb.append("<tbody>\n" + "	    				<tr>\n"
2733
				+ "	    					<th style='border:1px solid black;padding: 5px'>Item</th>\n"
2734
				+ "	    					<th style='border:1px solid black;padding: 5px'>Shortage Qty</th>\n"
2735
				+ "	    				</tr>");
2736
		for (FocusedModelShortageModel entry : focusedModelShortageModel) {
2737
 
2738
			sb.append("<tr>");
2739
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getItemName() + "</td>");
2740
 
2741
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getShortageQty() + "</td>");
2742
 
2743
			sb.append("</tr>");
2744
 
2745
		}
2746
 
2747
		sb.append("</tbody></table></body></html>");
2748
 
2749
		return sb.toString();
2750
	}
2751
 
25927 amit.gupta 2752
	public void notifyLead() throws Exception {
29488 manish 2753
		List<Lead> leadsToNotify = leadRepository.selectLeadsScheduledBetweenDate(null,
2754
				LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
25927 amit.gupta 2755
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2756
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
27477 amit.gupta 2757
		LOGGER.info("authUserEmailMap {}", authUserEmailMap);
25927 amit.gupta 2758
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2759
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2760
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
25936 amit.gupta 2761
 
27477 amit.gupta 2762
		LOGGER.info("dtrEmailMap {}", dtrEmailMap);
26790 tejbeer 2763
 
25927 amit.gupta 2764
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
2765
 
2766
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2767
			int authId = authUserEmail.getKey();
2768
			String email = authUserEmail.getValue();
2769
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2770
		}
27477 amit.gupta 2771
		LOGGER.info("authUserKeyMap", authUserKeyMap);
2772
		LOGGER.info("leadsToNotify {}", leadsToNotify);
26790 tejbeer 2773
 
29308 tejbeer 2774
		String templateMessage = "Lead followup for %s %s, %s, %s is due by %s";
25927 amit.gupta 2775
		for (Lead lead : leadsToNotify) {
27217 amit.gupta 2776
			if (authUserKeyMap.get(lead.getAssignTo()) == null) {
2777
				LOGGER.info("Assignee no longer part of system {}", lead.getAssignTo());
25927 amit.gupta 2778
				continue;
2779
			}
30982 tejbeer 2780
			String title = "Leads followup Reminder";
25927 amit.gupta 2781
			String notificationMessage = String.format(templateMessage, lead.getFirstName(), lead.getLastName(),
29308 tejbeer 2782
					lead.getAddress(), lead.getLeadMobile(), leadTimeFormatter.format(lead.getScheduledTimestamp()));
30982 tejbeer 2783
			String url = "https://app.smartdukaan.com/pages/home/leadUpdate?leadId=" + lead.getId();
25927 amit.gupta 2784
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2785
			sendNotificationModel.setCampaignName("Lead Reminder");
30982 tejbeer 2786
			sendNotificationModel.setTitle(title);
25927 amit.gupta 2787
			sendNotificationModel.setMessage(notificationMessage);
2788
			sendNotificationModel.setType("url");
30982 tejbeer 2789
			sendNotificationModel.setUrl(url);
25927 amit.gupta 2790
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2791
			sendNotificationModel.setMessageType(MessageType.reminder);
26320 tejbeer 2792
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(lead.getAssignTo())));
25929 amit.gupta 2793
			System.out.println(sendNotificationModel);
25927 amit.gupta 2794
			notificationService.sendNotification(sendNotificationModel);
30982 tejbeer 2795
			AuthUser authUser = authRepository.selectById(lead.getAssignTo());
30991 tejbeer 2796
			// notificationService.sendWhatsappMessage(notificationMessage, title,
2797
			// authUser.getMobileNumber());
25927 amit.gupta 2798
		}
2799
	}
26945 amit.gupta 2800
 
25927 amit.gupta 2801
	public void notifyVisits() throws Exception {
26945 amit.gupta 2802
		List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository
2803
				.selectVisitsScheduledBetweenDate(LocalDateTime.now().minusDays(15), LocalDateTime.now().plusHours(4));
25927 amit.gupta 2804
		Map<Integer, String> authUserEmailMap = authRepository.selectAllActiveUser().stream()
2805
				.collect(Collectors.toMap(x -> x.getId(), x -> x.getEmailId()));
2806
		Map<String, Integer> dtrEmailMap = dtrUserRepository
2807
				.selectAllByEmailIds(new ArrayList<>(authUserEmailMap.values())).stream()
2808
				.collect(Collectors.toMap(x -> x.getEmailId(), x -> x.getId()));
2809
		Map<Integer, Integer> authUserKeyMap = new HashMap<>();
26945 amit.gupta 2810
 
25927 amit.gupta 2811
		for (Map.Entry<Integer, String> authUserEmail : authUserEmailMap.entrySet()) {
2812
			int authId = authUserEmail.getKey();
2813
			String email = authUserEmail.getValue();
2814
			authUserKeyMap.put(authId, dtrEmailMap.get(email));
2815
		}
2816
		String visitTemplate = "Planned visit to franchisee %s is due by %s";
2817
		String followupTemplate = "Lead followup for franchisee %s is due by %s";
2818
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("MMM 7, EEEE h:m a");
2819
		for (FranchiseeVisit visit : franchiseeVisits) {
2820
			if (authUserKeyMap.containsKey(visit.getAuthId())) {
2821
				continue;
2822
			}
2823
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2824
			String message = null;
26945 amit.gupta 2825
			if (visit.getFranchiseActivityId() == 0) {
2826
				message = String.format(visitTemplate, visit.getPartnerName(),
30574 amit.gupta 2827
						timeFormatter.format(visit.getScheduleTimestamp()));
26945 amit.gupta 2828
				sendNotificationModel.setCampaignName("Franchisee visit Reminder");
25927 amit.gupta 2829
			} else {
26945 amit.gupta 2830
				message = String.format(followupTemplate, visit.getPartnerName(),
30574 amit.gupta 2831
						timeFormatter.format(visit.getScheduleTimestamp()));
25927 amit.gupta 2832
				sendNotificationModel.setCampaignName("Franchisee followup Reminder");
2833
			}
2834
			sendNotificationModel.setMessage(message);
2835
			sendNotificationModel.setType("url");
26482 tejbeer 2836
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
25927 amit.gupta 2837
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2838
			sendNotificationModel.setMessageType(MessageType.reminder);
2839
			sendNotificationModel.setUserIds(Arrays.asList(authUserKeyMap.get(visit.getAuthId())));
30991 tejbeer 2840
			// notificationService.sendNotification(sendNotificationModel);
25927 amit.gupta 2841
		}
25910 amit.gupta 2842
	}
25982 amit.gupta 2843
 
26283 tejbeer 2844
	public void ticketClosed() throws Exception {
2845
 
2846
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTicketsWithStatus(ActivityType.RESOLVED);
2847
		for (Ticket ticket : tickets) {
2848
			if (ticket.getUpdateTimestamp().toLocalDate().isBefore(LocalDate.now().minusDays(7))) {
2849
				ticket.setCloseTimestamp(LocalDateTime.now());
2850
				ticket.setLastActivity(ActivityType.RESOLVED_ACCEPTED);
2851
				ticket.setUpdateTimestamp(LocalDateTime.now());
2852
				ticketRepository.persist(ticket);
2853
			}
2854
		}
2855
 
2856
	}
2857
 
26790 tejbeer 2858
	public void checkValidateReferral() throws Exception {
2859
 
2860
		List<Refferal> referrals = refferalRepository.selectByStatus(RefferalStatus.pending);
26791 tejbeer 2861
		LOGGER.info("referrals" + referrals);
26790 tejbeer 2862
		if (!referrals.isEmpty()) {
2863
			String subject = "Referral Request";
2864
			String messageText = this.getMessageForReferral(referrals);
2865
 
26792 tejbeer 2866
			MimeMessage message = mailSender.createMimeMessage();
2867
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
30752 tejbeer 2868
			String[] email = { "kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com" };
26792 tejbeer 2869
			helper.setSubject(subject);
2870
			helper.setText(messageText, true);
2871
			helper.setTo(email);
2872
			InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
2873
			helper.setFrom(senderAddress);
2874
			mailSender.send(message);
2875
 
26790 tejbeer 2876
		}
2877
	}
2878
 
2879
	private String getMessageForReferral(List<Refferal> referrals) {
2880
		StringBuilder sb = new StringBuilder();
2881
		sb.append("<html><body><p>Alert</p><p>Pending Referrals:-</p>"
2882
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2883
		sb.append("<tbody>\n" + "	    				<tr>\n"
2884
				+ "	    					<th style='border:1px solid black;padding: 5px'>RefereeName</th>\n"
2885
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referee Email</th>\n"
2886
				+ "	    					<th style='border:1px solid black;padding: 5px'>Referral Name</th>\n"
2887
				+ "	    					<th style='border:1px solid black;padding: 5px'>Refferal Mobile</th>\n"
2888
				+ "	    					<th style='border:1px solid black;padding: 5px'>city</th>\n"
2889
				+ "	    					<th style='border:1px solid black;padding: 5px'>state</th>\n"
2890
				+ "	    				</tr>");
2891
		for (Refferal entry : referrals) {
2892
 
2893
			sb.append("<tr>");
2894
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeName() + "</td>");
2895
 
2896
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getRefereeEmail() + "</td>");
2897
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getFirstName() + "</td>");
2898
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getMobile() + "</td>");
2899
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getCity() + "</td>");
2900
			sb.append("<td style='border:1px solid black;padding: 5px'>" + entry.getState() + "</td>");
2901
 
2902
			sb.append("</tr>");
2903
 
2904
		}
2905
 
2906
		sb.append("</tbody></table></body></html>");
2907
 
2908
		return sb.toString();
2909
	}
2910
 
30421 tejbeer 2911
	private String getMessageForUncontacblePartner(List<PartnerCollectionRemark> pcrs)
2912
			throws ProfitMandiBusinessException {
2913
		StringBuilder sb = new StringBuilder();
2914
		sb.append("<html><body><p>Alert</p><p>Not Responding Partner:-</p>"
2915
				+ "<br/><table style='border:1px solid black ;padding: 5px';>");
2916
		sb.append("<tbody>\n" + "	    				<tr>\n"
2917
				+ "	    					<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n"
2918
				+ "	    					<th style='border:1px solid black;padding: 5px'>from</th>\n"
2919
 
2920
				+ "	    				</tr>");
2921
		for (PartnerCollectionRemark entry : pcrs) {
2922
 
2923
			CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
2924
 
2925
			sb.append("<tr>");
2926
			sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "("
2927
					+ customRetailer.getCode() + ")" + "</td>");
2928
 
2929
			sb.append("<td style='border:1px solid black;padding: 5px'>"
2930
					+ entry.getCreateTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
2931
 
2932
			sb.append("</tr>");
2933
 
2934
		}
2935
 
2936
		sb.append("</tbody></table></body></html>");
2937
 
2938
		return sb.toString();
2939
	}
2940
 
27271 amit.gupta 2941
	public void reverseWallet() throws Exception {
2942
		LocalDate localDate = LocalDate.of(2020, 10, 28);
28205 tejbeer 2943
		List<UserWalletHistory> uwhList = userWalletHistoryRepository.selectAllByDateType(localDate.atStartOfDay(),
2944
				localDate.plusDays(1).atStartOfDay(),
27271 amit.gupta 2945
				Arrays.asList(WalletReferenceType.SCHEME_IN, WalletReferenceType.SCHEME_OUT));
2946
		for (UserWalletHistory uwh : uwhList) {
28205 tejbeer 2947
			if (uwh.getBusinessTimestamp().getMonth().equals(Month.SEPTEMBER)) {
27275 amit.gupta 2948
				UserWallet uw = userWalletRepository.selectById(uwh.getWalletId());
28205 tejbeer 2949
				// LOGGER.info("UWH - {}", uwh);
2950
				// amount += uwh.getAmount();
2951
				// System.out.println("Amount is - " + amount);
2952
				// walletService.rollbackAmountFromWallet(uw.getUserId(), uwh.getAmount(),
2953
				// uwh.getReference(), uwh.getReferenceType(), "Margin reversal for error prone
2954
				// run", uwh.getBusinessTimestamp());
27313 amit.gupta 2955
				int orderId = uwh.getReference();
2956
				FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
2957
				int inventoryItemId = 0;
28205 tejbeer 2958
				// fofoOrderRepository.delete(fofoOrder);
27313 amit.gupta 2959
				List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
28205 tejbeer 2960
				/*
2961
				 * List<PaymentOptionTransaction> paymentOptionTransactions =
2962
				 * paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId
2963
				 * (), PaymentOptionReferenceType.ORDER); for(PaymentOptionTransaction
2964
				 * paymentOptionTransaction : paymentOptionTransactions) {
2965
				 * //paymentOptionTransactionRepository.delete(paymentOptionTransaction); }
2966
				 */
2967
				for (FofoOrderItem foi : fofoOrderItems) {
2968
					// fofoOrderItemRepository.delete(foi);
27313 amit.gupta 2969
					List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(foi.getId());
28205 tejbeer 2970
					for (FofoLineItem fli : flis) {
2971
						// fofoLineItemRepository.delete(fli);
27313 amit.gupta 2972
						inventoryItemId = fli.getInventoryItemId();
2973
					}
2974
				}
28205 tejbeer 2975
				List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(
2976
						java.util.stream.Stream.of(inventoryItemId).collect(Collectors.toSet()));
2977
				for (SchemeInOut sio : schemeInOuts) {
2978
					if (sio.getCreateTimestamp().toLocalDate().equals(localDate)) {
27314 amit.gupta 2979
						LOGGER.info("SIO - {}", sio);
27315 amit.gupta 2980
						sio.setRolledBackTimestamp(LocalDateTime.now());
27313 amit.gupta 2981
					}
2982
				}
28205 tejbeer 2983
 
27271 amit.gupta 2984
			}
2985
		}
28205 tejbeer 2986
 
27271 amit.gupta 2987
	}
28205 tejbeer 2988
 
2989
	public void partnerProblemAlert() throws Exception {
2990
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2991
		Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
2992
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
2993
		Map<Integer, Double> mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1),
2994
				curDate.with(LocalTime.MAX), 0, false);
2995
		Map<Integer, PartnerDailyInvestment> pdi = partnerDailyInvestmentRepository.selectAll(LocalDate.now()).stream()
2996
				.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
2997
 
2998
		for (Entry<Integer, Double> ls : lmtdSale.entrySet()) {
2999
 
3000
			double lmtdTwentyPercentSale = ls.getValue() * 0.2;
28208 tejbeer 3001
 
3002
			LOGGER.info("lmtdTwentyPercentSale" + lmtdTwentyPercentSale);
3003
 
28211 tejbeer 3004
			double mtdSale = mtdSales.get(ls.getKey()) == null ? 0 : mtdSales.get(ls.getKey());
28208 tejbeer 3005
 
3006
			LOGGER.info("mtdSale" + mtdSale);
3007
 
28209 tejbeer 3008
			double totalSixtyPercentInvestment = pdi.get(ls.getKey()) == null ? 0
3009
					: pdi.get(ls.getKey()).getTotalInvestment() * 0.6;
28205 tejbeer 3010
 
28208 tejbeer 3011
			LOGGER.info("totalSixtyPercentInvestment" + totalSixtyPercentInvestment);
3012
 
28209 tejbeer 3013
			double stockInvestment = pdi.get(ls.getKey()) == null ? 0 : pdi.get(ls.getKey()).getInStockAmount();
28208 tejbeer 3014
 
3015
			LOGGER.info("stockInvestment" + stockInvestment);
3016
 
28205 tejbeer 3017
			boolean Investmentvalue = partnerInvestmentService.isInvestmentBelow(ls.getKey(), 25);
3018
 
3019
			PartnerProblem partnerProblem = partnerProblemRepository.selectByFofoId(ls.getKey());
3020
 
28210 tejbeer 3021
			if (partnerProblem == null) {
28205 tejbeer 3022
				partnerProblem = new PartnerProblem();
3023
				partnerProblem.setFofoId(ls.getKey());
3024
				if (mtdSale < lmtdTwentyPercentSale) {
3025
					partnerProblem.setMtd(1);
3026
				}
3027
				if (Investmentvalue) {
3028
					partnerProblem.setInvestment(1);
3029
				}
3030
 
3031
				if (stockInvestment < totalSixtyPercentInvestment) {
3032
					partnerProblem.setInvestment(1);
3033
				}
3034
 
3035
				partnerProblemRepository.persist(partnerProblem);
3036
			} else {
3037
				if (mtdSale < lmtdTwentyPercentSale) {
3038
					partnerProblem.setMtd(partnerProblem.getMtd() + 1);
3039
 
3040
				} else {
3041
					partnerProblem.setMtd(0);
3042
 
3043
				}
3044
				if (Investmentvalue) {
3045
					partnerProblem.setInvestment(partnerProblem.getInvestment() + 1);
3046
				} else {
3047
					partnerProblem.setInvestment(0);
3048
 
3049
				}
3050
				if (stockInvestment < totalSixtyPercentInvestment) {
3051
					partnerProblem.setStockInvestment(partnerProblem.getStockInvestment() + 1);
3052
				} else {
3053
					partnerProblem.setStockInvestment(0);
3054
				}
3055
 
3056
			}
3057
 
3058
		}
3059
 
28213 tejbeer 3060
		List<PartnerProblem> partnerProblems = partnerProblemRepository.selectAll().stream()
3061
				.filter(x -> x.getMtd() + x.getInvestment() + x.getStockInvestment() > 0).collect(Collectors.toList());
3062
 
28223 tejbeer 3063
		partnerProblems = partnerProblems.stream().sorted((x1, x2) -> {
28224 tejbeer 3064
			return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment()
28223 tejbeer 3065
					+ x2.getStockInvestment() ? 1 : -1;
3066
		}).collect(Collectors.toList());
28227 tejbeer 3067
 
3068
		Map<Integer, PartnerProblem> partnerProblemMap = partnerProblems.stream().sorted((x1, x2) -> {
3069
			return x1.getMtd() + x1.getInvestment() + x1.getStockInvestment() < x2.getMtd() + x2.getInvestment()
3070
					+ x2.getStockInvestment() ? 1 : -1;
3071
		}).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3072
 
28212 tejbeer 3073
		Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
28213 tejbeer 3074
 
28467 tejbeer 3075
		List<Integer> assignTo = Arrays.asList(15, 9, 54, 53);
28213 tejbeer 3076
 
3077
		Map<Integer, AuthUser> assignAuthUserMap = authRepository.selectAllAuthUserByIds(assignTo).stream()
3078
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
3079
 
28286 tejbeer 3080
		List<String> sendTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com",
30765 tejbeer 3081
				"niranjan.kala@smartdukaan.com", "sm@smartdukaan.com");
28208 tejbeer 3082
		LOGGER.info("partnerProblem" + partnerProblems);
28205 tejbeer 3083
		StringBuilder sb = new StringBuilder();
28218 tejbeer 3084
		sb.append("<htl><body>");
28222 tejbeer 3085
		sb.append(
3086
				"<p>Number against MTD or Investment are the count of days the MTD is low VS LMTD OR Investment is below 75%.</p><br/><p>These partners needs immediate attention.</p><br/><table style='border:1px solid black';cellspacing=0>");
28205 tejbeer 3087
		sb.append("<tbody>\n" + "	    <tr>"
3088
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner Name</th>"
3089
				+ "                         <th style='border:1px solid black;padding: 5px'>Assign TO</th>"
3090
				+ "	    					<th style='border:1px solid black;padding: 5px'>Mtd</th>"
3091
				+ "	    					<th style='border:1px solid black;padding: 5px'>Investment</th>"
3092
				+ "	    					<th style='border:1px solid black;padding: 5px'>Stock</th>"
3093
				+ "	    					<th style='border:1px solid black;padding: 5px'>Manager</th>"
3094
 
3095
				+ "	    				</tr>");
3096
 
3097
		for (PartnerProblem pp : partnerProblems) {
28467 tejbeer 3098
			int value = pp.getFofoId() % 4;
28205 tejbeer 3099
 
3100
			Map<EscalationType, AuthUser> authUserMap = csService.getAuthUserAndEsclationByPartnerId(pp.getFofoId());
28217 tejbeer 3101
			LOGGER.info("authUserMap" + authUserMap);
28205 tejbeer 3102
			sb.append("<tr>");
3103
			sb.append("<td style='border:1px solid black;padding: 5px'>"
3104
					+ customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
28213 tejbeer 3105
			sb.append("<td style='border:1px solid black;padding: 5px'>"
3106
					+ assignAuthUserMap.get(assignTo.get(value)).getName() + "</td>");
28205 tejbeer 3107
			sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
3108
			sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
3109
			sb.append("<td style='border:1px solid black;padding: 5px'>" + pp.getStockInvestment() + "</td>");
28216 tejbeer 3110
			sb.append("<td style='border:1px solid black;padding: 5px'>"
28224 tejbeer 3111
					+ (authUserMap.get(EscalationType.L1) == null ? "N/A"
30752 tejbeer 3112
							: authUserMap.get(EscalationType.L1).getFirstName())
28224 tejbeer 3113
					+ " ," + (authUserMap.get(EscalationType.L2) == null ? "N/A"
30752 tejbeer 3114
							: authUserMap.get(EscalationType.L2).getFirstName())
28216 tejbeer 3115
					+ "</td>");
28205 tejbeer 3116
 
3117
			sb.append("</tr>");
3118
		}
3119
		sb.append("</tbody></table><br><br>");
3120
		String subject = "Partner Problem Alert!";
3121
		String[] email = sendTo.toArray(new String[sendTo.size()]);
3122
 
28222 tejbeer 3123
		this.sendMailHtmlFormat(email, sb.toString(), null, subject);
3124
 
28218 tejbeer 3125
		Map<Integer, List<Integer>> authUserPartnerMapping = csService.getAuthUserIdPartnerIdMapping();
3126
 
3127
		for (Entry<Integer, List<Integer>> authUserPartner : authUserPartnerMapping.entrySet()) {
28222 tejbeer 3128
			AuthUser authUser = authRepository.selectById(authUserPartner.getKey());
28227 tejbeer 3129
			for (Integer patnerId : authUserPartner.getValue()) {
3130
				if (partnerProblemMap.get(patnerId) != null) {
28218 tejbeer 3131
 
28227 tejbeer 3132
					StringBuilder sbbuilder = new StringBuilder();
3133
					sbbuilder.append("<hml><body>");
3134
					sb.append(
3135
							"<p>Number against MTD or Investment are the count of days the MTD is low VS LMTD OR Investment is below 75%.</p><br/><p>These partners needs immediate attention.</p><br/><table style='border:1px solid black';cellspacing=0>");
3136
					sbbuilder.append("<tbody>\n" + "	    <tr>"
3137
							+ "	    					<th style='border:1px solid black;padding: 5px'>Partner Name</th>"
3138
							+ "	    					<th style='border:1px solid black;padding: 5px'>Mtd</th>"
3139
							+ "	    					<th style='border:1px solid black;padding: 5px'>Investment</th>"
3140
							+ "	    					<th style='border:1px solid black;padding: 5px'>Stock</th>"
28218 tejbeer 3141
 
28227 tejbeer 3142
							+ "	    				</tr>");
28218 tejbeer 3143
 
28227 tejbeer 3144
					for (Integer partnerId : authUserPartner.getValue()) {
3145
						if (partnerProblemMap.get(partnerId) != null) {
3146
							PartnerProblem pp = partnerProblemMap.get(partnerId);
3147
							sbbuilder.append("<tr>");
3148
							sbbuilder.append("<td style='border:1px solid black;padding: 5px'>"
3149
									+ customRetailers.get(pp.getFofoId()).getBusinessName() + "</td>");
3150
							sbbuilder
3151
									.append("<td style='border:1px solid black;padding: 5px'>" + pp.getMtd() + "</td>");
3152
							sbbuilder.append(
3153
									"<td style='border:1px solid black;padding: 5px'>" + pp.getInvestment() + "</td>");
3154
							sbbuilder.append("<td style='border:1px solid black;padding: 5px'>"
3155
									+ pp.getStockInvestment() + "</td>");
3156
 
3157
							sbbuilder.append("</tr>");
3158
						}
3159
 
28224 tejbeer 3160
					}
28227 tejbeer 3161
					sbbuilder.append("</tbody></table><br><br>");
28224 tejbeer 3162
 
28286 tejbeer 3163
					this.sendMailOfHtmlFormat(authUser.getEmailId(), sbbuilder.toString(), null, subject);
28230 tejbeer 3164
					break;
28218 tejbeer 3165
				}
28230 tejbeer 3166
 
28223 tejbeer 3167
			}
28222 tejbeer 3168
		}
3169
	}
28218 tejbeer 3170
 
28222 tejbeer 3171
	private void sendMailHtmlFormat(String email[], String body, String cc[], String subject)
3172
			throws MessagingException, ProfitMandiBusinessException, IOException {
3173
		MimeMessage message = mailSender.createMimeMessage();
3174
		MimeMessageHelper helper = new MimeMessageHelper(message);
3175
		helper.setSubject(subject);
3176
		helper.setText(body, true);
3177
		helper.setTo(email);
3178
		if (cc != null) {
3179
			helper.setCc(cc);
28218 tejbeer 3180
		}
28222 tejbeer 3181
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
3182
		helper.setFrom(senderAddress);
3183
		mailSender.send(message);
28205 tejbeer 3184
	}
3185
 
28775 amit.gupta 3186
	@Autowired
3187
	WarehouseRepository warehouseRepository;
28790 amit.gupta 3188
 
28775 amit.gupta 3189
	public void getVendorWarehouses(int warehouseId) {
28778 amit.gupta 3190
		LOGGER.info("Warehouses - {}", warehouseRepository.getVendorWarehouses().get(warehouseId));
28790 amit.gupta 3191
 
28775 amit.gupta 3192
	}
29488 manish 3193
 
29451 manish 3194
	public void checkImeiActivation() {
29488 manish 3195
 
29451 manish 3196
		try {
3197
			vivoImeiActivationService.checkImeiActivation();
3198
		} catch (ProfitMandiBusinessException e) {
3199
			// TODO Auto-generated catch block
3200
			e.printStackTrace();
3201
		} catch (IOException e) {
3202
			// TODO Auto-generated catch block
3203
			e.printStackTrace();
3204
		} catch (Exception e) {
3205
			// TODO Auto-generated catch block
3206
			e.printStackTrace();
3207
		}
28775 amit.gupta 3208
 
29451 manish 3209
	}
3210
 
29668 tejbeer 3211
	public void checkItelImeiActivation(LocalDate date, Integer day) {
29488 manish 3212
		LOGGER.info("Hello - {}", "hhh");
3213
 
3214
		try {
29668 tejbeer 3215
			itelImeiActivationService.checkItelImeiActivation(date, day);
29488 manish 3216
		} catch (ProfitMandiBusinessException e) {
3217
			// TODO Auto-generated catch block
3218
			e.printStackTrace();
3219
		} catch (IOException e) {
3220
			// TODO Auto-generated catch block
3221
			e.printStackTrace();
3222
		} catch (Exception e) {
3223
			// TODO Auto-generated catch block
3224
			e.printStackTrace();
3225
		}
3226
 
3227
	}
3228
 
29807 manish 3229
	public void selectFinServiceFollowUpDateByCurrDate(LocalDate currentDate)
3230
			throws MessagingException, ProfitMandiBusinessException, IOException {
29801 manish 3231
		LOGGER.info("selectfinServiceFollow - {}", "selectfinServiceFollowUpDateByCurrDate");
3232
 
29807 manish 3233
		serviceConfigService.selectFinServicePartnerfollowUpDateByCurrentDate(currentDate);
3234
 
29801 manish 3235
	}
3236
 
29668 tejbeer 3237
	public void checkTecnoImeiActivation(LocalDate date, Integer day) {
29488 manish 3238
		LOGGER.info("Hello - {}", "hhh");
3239
 
3240
		try {
29668 tejbeer 3241
			tecnoImeiActivation.checkTecnoImeiActivation(date, day);
29488 manish 3242
		} catch (ProfitMandiBusinessException e) {
3243
			// TODO Auto-generated catch block
3244
			e.printStackTrace();
3245
		} catch (IOException e) {
3246
			// TODO Auto-generated catch block
3247
			e.printStackTrace();
3248
		} catch (Exception e) {
3249
			// TODO Auto-generated catch block
3250
			e.printStackTrace();
3251
		}
3252
 
3253
	}
3254
 
29252 amit.gupta 3255
	public void checkCancellationMargin() throws Exception {
3256
		LocalDateTime startDate = LocalDate.of(2021, 4, 1).atStartOfDay();
3257
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectCancelledBetweenSaleDate(startDate, LocalDateTime.now());
3258
		LOGGER.info("Total Orders =  {}", fofoOrders.size());
29308 tejbeer 3259
		for (FofoOrder fofoOrder : fofoOrders) {
3260
			List<UserWalletHistory> history = userWalletHistoryRepository
3261
					.selectAllByreferenceIdandreferenceType(fofoOrder.getId(), WalletReferenceType.SCHEME_OUT);
3262
			history.addAll(userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(fofoOrder.getId(),
3263
					WalletReferenceType.ACTIVATION_SCHEME));
3264
			int walletSum = history.stream().mapToInt(x -> x.getAmount()).sum();
3265
			if (Math.abs(walletSum) > 1) {
3266
				// LOGGER.info("Cancelled invoice {}, Order Id = {}, = havent rolledback, Value
3267
				// = {}", fofoOrder.getInvoiceNumber(), fofoOrder.getId(), walletSum);
29252 amit.gupta 3268
				List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
3269
				List<FofoLineItem> flis = fofoLineItemRepository.selectByFofoOrderItemId(fofoOrderItems.get(0).getId());
3270
				FofoLineItem fli = flis.get(0);
29308 tejbeer 3271
				if (StringUtils.isEmpty(fli.getSerialNumber()))
3272
					continue;
3273
				List<SchemeInOut> schemeInOuts = schemeInOutRepository
3274
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(fli.getInventoryItemId())));
29252 amit.gupta 3275
				InventoryItem inventoryItem = inventoryItemRepository.selectById(fli.getInventoryItemId());
29308 tejbeer 3276
				double schemeSum = schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null)
3277
						.mapToDouble(x -> x.getAmount()).sum();
3278
				/*
3279
				 * if(inventoryItem.getGoodQuantity()==1) {
3280
				 * LOGGER.info("GoodQty, Serial Number {}, InventoryItem = {}, Billed on {}",
3281
				 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3282
				 * inventoryItem.getUpdateTimestamp()); } else
3283
				 * if(inventoryItem.getBadQuantity()==1){
3284
				 * LOGGER.info("Bad Qty, Serial Number {}, InventoryItem = {}, Billed on {}",
3285
				 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3286
				 * inventoryItem.getUpdateTimestamp()); } else if
3287
				 * (inventoryItem.getLastScanType().equals(ScanType.SALE)) { LOGGER.
3288
				 * info("Problem Sold, Serial Number {}, InventoryItem = {}, Billed on {}",
3289
				 * inventoryItem.getSerialNumber(), inventoryItem.getId(),
3290
				 * inventoryItem.getUpdateTimestamp()); }
3291
				 */
3292
				if (inventoryItem.getLastScanType().equals(ScanType.SALE)
3293
						|| inventoryItem.getLastScanType().equals(ScanType.SALE_RET)) {
3294
					Map<String, Double> map = schemeInOuts.stream()
3295
							.collect(
3296
									Collectors.groupingBy(
3297
											x -> DateTimeFormatter.ofPattern("yyyyMMddHH")
3298
													.format(x.getCreateTimestamp()) + "- " + x.getSchemeId(),
3299
											Collectors.summingDouble(x -> x.getAmount())));
3300
					for (Map.Entry<String, Double> entry : map.entrySet()) {
3301
						LOGGER.info("{} = {}", entry.getKey(), entry.getValue());
29252 amit.gupta 3302
					}
29308 tejbeer 3303
					LOGGER.info("id- {}, imei- {}, lastScan = {}, Scheme sum - {}", inventoryItem.getId(),
3304
							inventoryItem.getSerialNumber(), inventoryItem.getLastScanType(), schemeSum);
29252 amit.gupta 3305
				}
3306
			}
3307
		}
29308 tejbeer 3308
 
29252 amit.gupta 3309
	}
3310
 
29488 manish 3311
	public static String readFileAsString(String file) throws Exception {
3312
		String data = "";
3313
		data = new String(Files.readAllBytes(Paths.get(file)));
3314
		return data;
3315
	}
29451 manish 3316
 
29308 tejbeer 3317
	public void markDelhiveryOrderDelivered() throws ProfitMandiBusinessException, IOException {
3318
		List<Order> orders = orderRepository.selectOrderByProviderIdAndStatus(ProfitMandiConstants.DELHIVERY_PROVIDERID,
3319
				OrderStatus.SHIPPED_FROM_WH);
3320
 
3321
		if (!orders.isEmpty()) {
29441 tejbeer 3322
			Set<String> airwayBill = orders.stream().map(x -> x.getAirwayBillNumber()).collect(Collectors.toSet());
29308 tejbeer 3323
 
29441 tejbeer 3324
			int arraylength = airwayBill.size();
3325
 
3326
			if (arraylength >= 75) {
3327
 
3328
				airwayBill = airwayBill.stream().limit(74).collect(Collectors.toSet());
3329
			}
29308 tejbeer 3330
			LOGGER.info("airwayBill" + airwayBill);
3331
			String url = "https://track.delhivery.com/api/v1/packages/json/";
3332
 
3333
			OkHttpClient client = new OkHttpClient();
3334
 
3335
			Request request1 = new Request.Builder()
3336
					.url(url + "?waybill=" + String.join(",", airwayBill) + "&token=" + token).get().build();
3337
 
3338
			LOGGER.info("request1" + request1);
3339
 
3340
			Response response = client.newCall(request1).execute();
3341
 
3342
			LOGGER.info("jsonbj" + response.body());
3343
 
3344
			JSONObject jsonObj = new JSONObject(response.body().string());
3345
 
3346
			LOGGER.info("jsonObj" + jsonObj);
3347
 
29403 tejbeer 3348
			JSONArray shipmentData = jsonObj.getJSONArray("ShipmentData");
29308 tejbeer 3349
			Set<String> airwaybillStatus = new HashSet<>();
29403 tejbeer 3350
			for (int i = 0; i < shipmentData.length(); i++) {
3351
				JSONObject jsonObject = shipmentData.getJSONObject(i);
29308 tejbeer 3352
				JSONObject shipment = jsonObject.getJSONObject("Shipment");
3353
 
3354
				LOGGER.info("shipment" + shipment);
3355
				JSONObject statusDescription = shipment.getJSONObject("Status");
3356
				String awb = shipment.getString("AWB");
3357
 
3358
				String status = statusDescription.getString("Status");
3359
				LOGGER.info("status" + status);
3360
 
3361
				LOGGER.info("awb" + awb);
3362
				if (status.equals("Delivered")) {
3363
					airwaybillStatus.add(awb);
3364
				}
3365
 
3366
			}
31117 tejbeer 3367
			markOrderDelivered(airwaybillStatus);
3368
		}
3369
	}
29308 tejbeer 3370
 
31117 tejbeer 3371
	public void markBlueDartOrderDelivered() throws ProfitMandiBusinessException, IOException {
29308 tejbeer 3372
 
31117 tejbeer 3373
		String loginId = "DEL81122";
30982 tejbeer 3374
 
31117 tejbeer 3375
		String licencekey = "uhfhlg2jpmnqfhfrlsgzfr1nhu1qfvel";
30982 tejbeer 3376
 
31117 tejbeer 3377
		List<Order> orders = orderRepository.selectOrderByProviderIdAndStatus(ProfitMandiConstants.BLUEDART_PROVIDERID,
3378
				OrderStatus.SHIPPED_FROM_WH);
30982 tejbeer 3379
 
31117 tejbeer 3380
		if (!orders.isEmpty()) {
30982 tejbeer 3381
 
31118 tejbeer 3382
			Set<String> airwayBillNo = orders.stream().map(x -> x.getAirwayBillNumber()).collect(Collectors.toSet());
29308 tejbeer 3383
 
31117 tejbeer 3384
			LOGGER.info("airwayBill" + airwayBillNo);
3385
			String url = "https://api.bluedart.com/servlet/RoutingServlet?handler=tnt&action=custawbquery";
30982 tejbeer 3386
 
31117 tejbeer 3387
			String response = restClient.get(url + "&loginid=" + loginId + "&awb=awb&numbers="
3388
					+ String.join(",", airwayBillNo) + "&format=xml&lickey=" + licencekey + "&verno=1.3&scan=1", null,
3389
					null);
3390
 
3391
			JSONObject updateJson = XML.toJSONObject(response);
3392
 
3393
			JSONObject shipmentData = updateJson.getJSONObject("ShipmentData");
3394
			Object shipmentObject = shipmentData.get("Shipment");
3395
 
3396
			Set<String> airwaybillStatus = new HashSet<>();
3397
 
3398
			if (shipmentObject instanceof JSONArray) {
3399
				JSONArray shipments = (JSONArray) shipmentObject;
3400
				for (int i = 0; i < shipments.length(); i++) {
3401
					JSONObject jsonObject = shipments.getJSONObject(i);
3402
 
3403
					Number awb = jsonObject.getNumber("WaybillNo");
3404
					String status = jsonObject.getString("Status");
3405
 
3406
					if (status.equals("SHIPMENT DELIVERED")) {
3407
						airwaybillStatus.add(awb.toString());
3408
					}
3409
 
29308 tejbeer 3410
				}
31117 tejbeer 3411
			} else {
3412
				JSONObject jsonObject = (JSONObject) shipmentObject;
3413
				Number awb = jsonObject.getNumber("WaybillNo");
3414
				String status = jsonObject.getString("Status");
3415
 
3416
				if (status.equals("SHIPMENT DELIVERED")) {
3417
					airwaybillStatus.add(awb.toString());
3418
				}
3419
 
29308 tejbeer 3420
			}
3421
 
31117 tejbeer 3422
			LOGGER.info("airwaybillStatus" + airwaybillStatus);
3423
 
31118 tejbeer 3424
			markOrderDelivered(airwaybillStatus);
29308 tejbeer 3425
		}
31117 tejbeer 3426
 
29308 tejbeer 3427
	}
3428
 
31117 tejbeer 3429
	private void markOrderDelivered(Set<String> airwaybillStatus)
3430
			throws ProfitMandiBusinessException, HttpHostConnectException {
3431
		if (!airwaybillStatus.isEmpty()) {
3432
			for (String aws : airwaybillStatus) {
3433
 
3434
				List<Order> deliverdOrders = orderRepository.selectByAirwayBillNumber(aws);
3435
 
3436
				int fofoId = deliverdOrders.get(0).getRetailerId();
3437
				for (Order dlo : deliverdOrders) {
3438
					dlo.setStatus(OrderStatus.DELIVERY_SUCCESS);
3439
					dlo.setStatusDescription("Order Delivered");
3440
					dlo.setDeliveryTimestamp(LocalDateTime.now());
3441
				}
3442
 
3443
				com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
3444
 
3445
				Address address = addressRepository.selectById(user.getAddressId());
3446
 
3447
				String title = "Order Delivered";
3448
 
3449
				String message = String.format("Dear partner, Your SmartDukaan Order " + aws
3450
						+ " has been delivered to you in a safe sealed bag.");
3451
 
3452
				SendNotificationModel sendNotificationModel = new SendNotificationModel();
3453
				sendNotificationModel.setCampaignName("Order Delivered");
3454
				sendNotificationModel.setTitle(title);
3455
				sendNotificationModel.setMessage(message);
3456
				sendNotificationModel.setType("url");
3457
				sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
3458
				sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
3459
				sendNotificationModel.setMessageType(MessageType.notification);
3460
				int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
3461
				sendNotificationModel.setUserIds(Arrays.asList(userId));
3462
				notificationService.sendNotification(sendNotificationModel);
3463
 
3464
				notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
3465
 
3466
			}
3467
		}
3468
	}
3469
 
29814 tejbeer 3470
	public void partnerWiseCreditAccount() throws Exception {
3471
 
3472
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
3473
 
3474
		for (FofoStore fs : fofoStores) {
3475
 
3476
			if (fs.getPan() != null) {
3477
				AccountStatusResponseOut accountStatusResponseOut = mandiiService.getStatus(fs.getPan());
29815 tejbeer 3478
 
3479
				LOGGER.info("accountStatusResponseOut" + accountStatusResponseOut);
29814 tejbeer 3480
				CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(fs.getId(),
3481
						Gateway.MANDII);
3482
 
3483
				if (creditAccount == null) {
3484
 
3485
					creditAccount = new CreditAccount();
3486
 
3487
					creditAccount.setFofoId(fs.getId());
3488
					creditAccount.setGateway(Gateway.MANDII);
3489
 
3490
				}
29835 tejbeer 3491
 
3492
				if (accountStatusResponseOut == null) {
3493
					creditAccount.setCreditStatus(CreditStatus.UNKNOWN);
3494
					creditAccount.setDescription("User company not found");
3495
 
29817 tejbeer 3496
				} else {
29835 tejbeer 3497
					if (accountStatusResponseOut.getSanctionLimit() != null) {
3498
						creditAccount.setSanctionedAmount(accountStatusResponseOut.getSanctionLimit().floatValue());
3499
					} else {
3500
						creditAccount.setSanctionedAmount(0);
3501
					}
29817 tejbeer 3502
 
29835 tejbeer 3503
					creditAccount.setInterestRate(accountStatusResponseOut.getRateOfInterest());
3504
					if (accountStatusResponseOut.getBalanceAmount() != null) {
3505
						creditAccount.setAvailableAmount(accountStatusResponseOut.getBalanceAmount().floatValue());
3506
					} else {
3507
						creditAccount.setAvailableAmount(0);
3508
					}
3509
 
3510
					if (accountStatusResponseOut.getCurrentStage() != null) {
3511
						creditAccount.setDescription(accountStatusResponseOut.getCurrentStage().toString());
3512
					}
3513
					if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.SANCTION_AVAILABLE)) {
3514
						creditAccount.setCreditStatus(CreditStatus.SANCTIONED);
3515
					} else if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.IN_ELIGIBLE)) {
3516
						creditAccount.setCreditStatus(CreditStatus.INELIGIBLE);
3517
					} else {
3518
 
3519
						creditAccount.setCreditStatus(CreditStatus.TO_BE_EVALUATED);
3520
					}
29817 tejbeer 3521
				}
3522
 
29814 tejbeer 3523
				creditAccount.setUpdatedOn(LocalDateTime.now());
3524
				creditAccountRepository.persist(creditAccount);
3525
			}
3526
		}
3527
	}
3528
 
30421 tejbeer 3529
	@Autowired
3530
	private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
3531
 
3532
	public void reviewUncontactablePartner()
3533
			throws ProfitMandiBusinessException, MessagingException, UnsupportedEncodingException {
3534
 
3535
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
3536
 
3537
		List<Integer> pcrms = partnerCollectionRemarkRepository
3538
				.selectMaxRemarkId(new ArrayList<>(customRetailerMap.keySet()));
3539
 
3540
		if (!pcrms.isEmpty()) {
3541
			Map<Integer, PartnerCollectionRemark> partnerCollectionRemarksMap = partnerCollectionRemarkRepository
3542
					.selectByIds(pcrms).stream().filter(x -> x.getRemark().equals(CollectionRemark.NOT_RESPONDING))
3543
					.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3544
 
3545
			if (!partnerCollectionRemarksMap.isEmpty()) {
3546
				for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping()
3547
						.entrySet()) {
3548
					List<PartnerCollectionRemark> filteredRows = storeGuyEntry.getValue().stream()
3549
							.map(x -> partnerCollectionRemarksMap.get(x)).filter(x -> x != null)
3550
							.collect(Collectors.toList());
30752 tejbeer 3551
					String subject = "UNCONTACTABLE PARTNERS";
30421 tejbeer 3552
					String messageText = this.getMessageForUncontacblePartner(filteredRows);
3553
 
3554
					MimeMessage message = mailSender.createMimeMessage();
3555
					MimeMessageHelper helper = new MimeMessageHelper(message, true);
30752 tejbeer 3556
					String[] email = new String[] { storeGuyEntry.getKey() };
30421 tejbeer 3557
 
3558
					helper.setSubject(subject);
3559
					helper.setText(messageText, true);
3560
					helper.setTo(email);
3561
					InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com",
3562
							"Smartdukaan Alerts");
3563
					helper.setFrom(senderAddress);
3564
					mailSender.send(message);
3565
 
3566
					LOGGER.info("filteredRows {}", filteredRows);
3567
 
3568
				}
3569
			}
30859 tejbeer 3570
 
30421 tejbeer 3571
		}
3572
	}
3573
 
30859 tejbeer 3574
	@Autowired
3575
	private LoanRepository loanRepository;
3576
 
3577
	@Autowired
3578
	private LoanStatementRepository loanStatementRepository;
3579
 
3580
	@Autowired
3581
	private SDCreditService sdCreditService;
3582
 
3583
	@Autowired
3584
	private SDCreditRequirementRepository sdCreditRequirementRepository;
3585
 
30936 tejbeer 3586
	@Autowired
3587
	private CurrentPartnerDailyInvestmentRepository currentPartnerDailyInvestmentRepository;
3588
 
3589
	@Autowired
3590
	private TransactionRepository transactionRepository;
3591
 
3592
	@Autowired
3593
	private CreditAccountRepository crediRepository;
3594
 
31020 tejbeer 3595
	@Autowired
3596
	private SanctionRequestRepository sanctionRequestRepository;
3597
 
30859 tejbeer 3598
	public void calculateInterestAccured() throws ProfitMandiBusinessException {
3599
 
3600
		List<Loan> loans = loanRepository.selectAllActiveLoan();
3601
 
3602
		if (!loans.isEmpty()) {
3603
 
3604
			for (Loan loan : loans) {
3605
 
3606
				List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
3607
 
3608
				Map<LoanReferenceType, Double> loanStatusAmount = loanStatements.stream().collect(Collectors.groupingBy(
3609
						x -> x.getLoanReferenceType(), Collectors.summingDouble(x -> x.getAmount().doubleValue())));
3610
 
3611
				if (loan.getFreeDays() > 0) {
3612
					LocalDateTime freeDaysLimitDate = loan.getCreatedOn().plusDays(loan.getFreeDays() - 1);
30936 tejbeer 3613
 
3614
					LOGGER.info("freeDaysLimitDate {}", freeDaysLimitDate);
30859 tejbeer 3615
					if (LocalDateTime.now().isAfter(freeDaysLimitDate)) {
30936 tejbeer 3616
						int loanStatementId = loanStatementRepository.selectLatestLoanSatement(loan.getFofoId(),
3617
								loan.getId());
3618
						LOGGER.info("loanStatementId {}", loanStatementId);
30859 tejbeer 3619
 
30936 tejbeer 3620
						if (loanStatementId != 0) {
3621
 
3622
							this.calculateInterest(loan, loanStatusAmount, loanStatementId);
3623
 
3624
						} else {
3625
							sdCreditService.addInterest(freeDaysLimitDate.toLocalDate(), LocalDate.now(), loan,
3626
									loanStatusAmount);
3627
						}
3628
 
30859 tejbeer 3629
					}
3630
				} else {
3631
 
3632
					int loanStatementId = loanStatementRepository.selectLatestLoanSatement(loan.getFofoId(),
3633
							loan.getId());
30936 tejbeer 3634
					LOGGER.info("loanStatementId2 {}", loanStatementId);
30859 tejbeer 3635
 
30936 tejbeer 3636
					this.calculateInterest(loan, loanStatusAmount, loanStatementId);
30859 tejbeer 3637
 
3638
				}
3639
 
3640
			}
3641
		}
3642
 
3643
	}
3644
 
30936 tejbeer 3645
	private void calculateInterest(Loan loan, Map<LoanReferenceType, Double> loanStatusAmount, int loanStatementId)
3646
			throws ProfitMandiBusinessException {
3647
		LoanStatement loanStatement = loanStatementRepository.selectById(loanStatementId);
3648
 
3649
		if (loanStatement.getLoanId() == loan.getId()) {
3650
 
3651
			sdCreditService.addInterest(loanStatement.getCreatedAt().toLocalDate(), LocalDate.now(), loan,
3652
					loanStatusAmount);
3653
 
3654
		} else {
3655
			throw new ProfitMandiBusinessException("loanstament", loanStatement.getLoanId(), "Invalid LoanId");
3656
		}
3657
	}
3658
 
31020 tejbeer 3659
	public void loanSettlement() throws Exception {
30859 tejbeer 3660
		List<Loan> loans = loanRepository.selectAllActiveLoan();
3661
 
3662
		if (!loans.isEmpty()) {
3663
 
3664
			for (Loan loan : loans) {
3665
 
3666
				UserWallet userWallet = userWalletRepository.selectByRetailerId(loan.getFofoId());
3667
				SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository
3668
						.selectByFofoId(loan.getFofoId());
3669
 
3670
				if (userWallet.getAmount() >= 100) {
3671
					List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
3672
 
3673
					Map<LoanReferenceType, Double> loanStatusAmount = loanStatements.stream()
3674
							.collect(Collectors.groupingBy(x -> x.getLoanReferenceType(),
3675
									Collectors.summingDouble(x -> x.getAmount().doubleValue())));
3676
 
3677
					LOGGER.info("loanStatusAmount {}", loanStatusAmount);
31020 tejbeer 3678
					Double interestAmount = loanStatusAmount.get(LoanReferenceType.INTEREST);
30859 tejbeer 3679
 
31020 tejbeer 3680
					if (interestAmount == null) {
3681
						interestAmount = (double) 0;
3682
					}
3683
 
30859 tejbeer 3684
					double principalAmount = loanStatusAmount.get(LoanReferenceType.PRINCIPAL);
3685
					double paidAmount = 0;
3686
					if (userWallet.getAmount() > Math.abs(interestAmount)) {
3687
 
3688
						if (interestAmount != 0) {
3689
 
3690
							settledLoanStatement(LoanReferenceType.INTEREST, BigDecimal.valueOf(interestAmount),
3691
									loan.getFofoId(), loan.getId(), "Amount adjusted against loan",
3692
									LocalDateTime.now());
3693
							loan.setInterestPaid(loan.getInterestPaid().add(BigDecimal.valueOf(interestAmount).abs()));
3694
 
3695
							paidAmount += Math.abs(interestAmount);
3696
						}
3697
 
3698
						double userWalletAmount = userWallet.getAmount() - Math.abs(interestAmount);
3699
 
3700
						if (userWalletAmount > Math.abs(principalAmount) && principalAmount != 0) {
3701
 
3702
							settledLoanStatement(LoanReferenceType.PRINCIPAL, BigDecimal.valueOf(principalAmount),
3703
									loan.getFofoId(), loan.getId(), "Amount adjusted against loan",
3704
									LocalDateTime.now());
3705
							double amount = userWalletAmount - Math.abs(principalAmount);
3706
 
3707
							paidAmount += Math.abs(principalAmount);
3708
 
3709
							userWallet.setAmount((int) amount);
3710
 
31020 tejbeer 3711
							BigDecimal utilizationAmount = sdCreditRequirement.getUtilizedAmount()
3712
									.subtract(BigDecimal.valueOf(principalAmount).abs());
3713
 
31110 tejbeer 3714
							sdCreditRequirement.setUtilizedAmount(utilizationAmount);
3715
 
3716
							CreditAccount creditAccount = creditAccountRepository
3717
									.selectByFofoIdAndGateway(loan.getFofoId(), Gateway.SDDIRECT);
3718
 
3719
							creditAccount.setAvailableAmount(sdCreditRequirement.getAvailableLimit().floatValue());
3720
							creditAccount.setUpdatedOn(LocalDateTime.now());
3721
 
30859 tejbeer 3722
							loan.setPendingAmount(BigDecimal.ZERO);
3723
 
3724
						} else if (principalAmount != 0) {
3725
 
3726
							settledLoanStatement(LoanReferenceType.PRINCIPAL, BigDecimal.valueOf(userWalletAmount),
3727
									loan.getFofoId(), loan.getId(), "Amount adjusted against loan",
3728
									LocalDateTime.now());
3729
 
3730
							paidAmount += Math.abs(userWalletAmount);
3731
 
31020 tejbeer 3732
							BigDecimal availableLimit = sdCreditRequirement.getAvailableLimit()
3733
									.add(BigDecimal.valueOf(userWalletAmount)).abs();
3734
 
3735
							BigDecimal utilizationAmount = sdCreditRequirement.getUtilizedAmount()
3736
									.subtract(BigDecimal.valueOf(userWalletAmount)).abs();
3737
 
31110 tejbeer 3738
							sdCreditRequirement.setUtilizedAmount(utilizationAmount);
31020 tejbeer 3739
 
31110 tejbeer 3740
							CreditAccount creditAccount = creditAccountRepository
3741
									.selectByFofoIdAndGateway(loan.getFofoId(), Gateway.SDDIRECT);
3742
 
3743
							creditAccount.setAvailableAmount(sdCreditRequirement.getAvailableLimit().floatValue());
3744
							creditAccount.setUpdatedOn(LocalDateTime.now());
30859 tejbeer 3745
							userWallet.setAmount(0);
3746
 
3747
							loan.setPendingAmount(
3748
									loan.getPendingAmount().subtract(BigDecimal.valueOf(userWalletAmount)));
3749
 
3750
						}
3751
 
3752
						createUserWalletHistory(userWallet.getId(), userWallet.getUserId(),
3753
								WalletReferenceType.LOAN_REPAYMENT, loan.getId(), Math.abs(paidAmount));
3754
 
3755
					} else {
3756
 
3757
						settledLoanStatement(LoanReferenceType.INTEREST, BigDecimal.valueOf(userWallet.getAmount()),
3758
								loan.getFofoId(), loan.getId(), "Amount adjusted against loan", LocalDateTime.now());
3759
 
3760
						paidAmount += Math.abs(userWallet.getAmount());
3761
 
3762
						createUserWalletHistory(userWallet.getId(), userWallet.getUserId(),
3763
								WalletReferenceType.LOAN_REPAYMENT, loan.getId(), Math.abs(paidAmount));
3764
 
3765
						loan.setInterestPaid(
3766
								loan.getInterestPaid().add(BigDecimal.valueOf(userWallet.getAmount()).abs()));
3767
 
3768
						userWallet.setAmount(0);
3769
					}
3770
 
3771
				}
3772
			}
30999 tejbeer 3773
 
31020 tejbeer 3774
			List<Order> allOrders = orderRepository.selectHoldOrder();
3775
 
3776
			LOGGER.info("allOrders {}", allOrders);
3777
 
3778
			if (!allOrders.isEmpty()) {
3779
				Map<Integer, List<Order>> transactionOrdersMap = allOrders.stream()
3780
						.collect(Collectors.groupingBy(Order::getTransactionId, Collectors.toList()));
3781
				LinkedHashMap<Integer, List<Order>> sortedTransactionOrdersMap = new LinkedHashMap<>();
3782
				transactionOrdersMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
3783
						.forEachOrdered(x -> sortedTransactionOrdersMap.put(x.getKey(), x.getValue()));
3784
				LOGGER.info("sortedTransactionOrdersMap {}", sortedTransactionOrdersMap);
3785
 
3786
				for (Entry<Integer, List<Order>> transactionOrdersEntry : sortedTransactionOrdersMap.entrySet()) {
3787
 
3788
					List<Order> orders = transactionOrdersEntry.getValue();
3789
 
3790
					double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));
3791
 
3792
					LocalDateTime createDate = orders.get(0).getCreateTimestamp();
3793
 
3794
					int fofoId = orders.get(0).getRetailerId();
3795
 
3796
					int transactionId = transactionOrdersEntry.getKey();
3797
 
3798
					SanctionRequest sanctionRequest = sanctionRequestRepository.selectByTransactionId(transactionId);
3799
 
3800
					double loanSettleAmount = loanStatementRepository.selectByDateAndFofoId(createDate, fofoId).stream()
3801
							.filter(x -> x.getAmount().doubleValue() > 0)
3802
							.collect(Collectors.summingDouble(x -> x.getAmount().doubleValue()));
3803
 
3804
					LOGGER.info("loanSettleAmount {}", loanSettleAmount);
3805
 
3806
					LOGGER.info("totalAmount {}", totalAmount);
3807
					if (loanSettleAmount >= sanctionRequest.getUtilizationAmount().doubleValue()) {
3808
 
3809
						LOGGER.info("totalAmount {}", totalAmount);
3810
 
3811
						orders.forEach(x -> x.setShipmentHold(false));
3812
 
3813
						List<String> authUserEmail = csService.getAuthUserIdByPartnerId(orders.get(0).getRetailerId())
3814
								.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
3815
						authUserEmail.add("vinay.p@smartdukaan.com");
3816
						authUserEmail.add("shivam.gupta@smartdukaan.com");
3817
 
3818
						String[] emailTo = authUserEmail.toArray(new String[authUserEmail.size()]);
3819
 
3820
						String[] ccTo = { "tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com" };
3821
 
3822
						String subject = "Dispatched " + (orders.get(0).getRetailerName());
3823
						String message = String.format("Dear Team, \n" + "kindly note the meterial for the "
3824
								+ orders.get(0).getRetailerName() + "of Rs." + totalAmount + "is dispatched.");
3825
 
3826
						Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
3827
 
3828
					}
3829
 
3830
				}
3831
			}
3832
 
30859 tejbeer 3833
		}
3834
 
3835
	}
3836
 
3837
	private void settledLoanStatement(LoanReferenceType loanReferneceType, BigDecimal amount, int fofoId, int loanId,
3838
			String description, LocalDateTime now) {
3839
 
3840
		sdCreditService.createLoanStatement(loanReferneceType, amount.abs(), fofoId, loanId, description,
3841
				LocalDateTime.now());
3842
 
3843
	}
3844
 
3845
	private void createUserWalletHistory(int walletId, int userId, WalletReferenceType referenceType, int loanId,
3846
			double interestAmount) {
3847
		UserWalletHistory uwh = new UserWalletHistory();
3848
		uwh.setWalletId(walletId);
3849
		uwh.setFofoId(userId);
3850
		uwh.setBusinessTimestamp(LocalDateTime.now());
3851
		uwh.setReferenceType(referenceType);
3852
		uwh.setReference(loanId);
3853
		uwh.setTimestamp(LocalDateTime.now());
3854
		uwh.setAmount((int) -(interestAmount));
30908 tejbeer 3855
		uwh.setDescription("Amount adjusted against loan");
30859 tejbeer 3856
		userWalletHistoryRepository.persist(uwh);
3857
 
3858
	}
3859
 
30965 tejbeer 3860
	public void dailyLoanAlert()
3861
			throws ProfitMandiBusinessException, HttpHostConnectException, UnsupportedEncodingException {
30859 tejbeer 3862
		List<Loan> loans = loanRepository.selectAllActiveLoan();
3863
 
3864
		Map<Integer, Double> partnerLoanAmount = new HashMap<>();
3865
 
3866
		if (!loans.isEmpty()) {
3867
 
3868
			for (Loan loan : loans) {
3869
 
3870
				List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
3871
 
3872
				double amount = loanStatements.stream().map(x -> x.getAmount())
3873
						.collect(Collectors.summingDouble(x -> x.doubleValue()));
3874
				if (partnerLoanAmount.get(loan.getFofoId()) != null) {
3875
					amount += partnerLoanAmount.get(loan.getFofoId());
3876
					partnerLoanAmount.put(loan.getFofoId(), amount);
3877
				} else {
3878
					partnerLoanAmount.put(loan.getFofoId(), amount);
3879
				}
3880
 
3881
			}
3882
 
3883
		}
3884
 
3885
		if (!partnerLoanAmount.isEmpty()) {
3886
 
3887
			for (Entry<Integer, Double> partnerLoanAmountEnrty : partnerLoanAmount.entrySet()) {
3888
 
3889
				int fofoId = partnerLoanAmountEnrty.getKey();
3890
 
30965 tejbeer 3891
				com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
3892
 
3893
				Address address = addressRepository.selectById(user.getAddressId());
3894
 
3895
				String title = "Alert Credit Outstanding!";
30859 tejbeer 3896
				String url = "http://app.smartdukaan.com/pages/home/credit";
30989 tejbeer 3897
				String message = "Your total pending Loan amount is Rs."
3898
						+ FormattingUtils.formatDecimal(Math.abs(partnerLoanAmountEnrty.getValue())) + ".";
30859 tejbeer 3899
				notificationService.sendNotification(fofoId, title, MessageType.notification, title, message, url);
3900
 
30989 tejbeer 3901
				notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30965 tejbeer 3902
 
30859 tejbeer 3903
			}
3904
 
3905
		}
3906
 
3907
	}
3908
 
30896 amit.gupta 3909
	public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
3910
		schemeService.processActivatedImeisForSchemes();
3911
	}
3912
 
30913 tejbeer 3913
	public void updatePartnerLimit() throws ProfitMandiBusinessException {
3914
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailers(true);
3915
 
3916
		Map<Integer, SDCreditRequirement> sdCreditRequirementMap = sdCreditRequirementRepository.selectAll().stream()
3917
				.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
3918
		Map<Integer, CurrentPartnerDailyInvestment> currentPartnerDailyInvestmentMap = currentPartnerDailyInvestmentRepository
3919
				.selectAll().stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30933 tejbeer 3920
		double limitValue = 100000;
30913 tejbeer 3921
		for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
3922
			int fofoId = customRetailerEntry.getKey();
3923
			SDCreditRequirement sdCreditRequirement = sdCreditRequirementMap.get(customRetailerEntry.getKey());
30929 tejbeer 3924
			LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
30913 tejbeer 3925
			CurrentPartnerDailyInvestment currentPartnerDailyInvestment = currentPartnerDailyInvestmentMap.get(fofoId);
3926
			BigDecimal suggestedAmount = BigDecimal.ZERO;
3927
			if (currentPartnerDailyInvestment != null) {
3928
				suggestedAmount = BigDecimal.valueOf(currentPartnerDailyInvestment.getTotalInvestment() * 0.1);
3929
			}
3930
 
30933 tejbeer 3931
			if (suggestedAmount.doubleValue() > limitValue) {
30917 tejbeer 3932
 
30933 tejbeer 3933
				suggestedAmount = BigDecimal.valueOf(limitValue);
30917 tejbeer 3934
 
3935
			}
30920 tejbeer 3936
 
3937
			if (suggestedAmount.doubleValue() < 0) {
3938
				suggestedAmount = BigDecimal.ZERO;
3939
			}
3940
 
30913 tejbeer 3941
			LOGGER.info("suggestedAmount {} ", suggestedAmount);
3942
 
3943
			if (sdCreditRequirement == null) {
3944
				sdCreditRequirement = new SDCreditRequirement();
3945
				sdCreditRequirement.setFofoId(fofoId);
3946
				sdCreditRequirement.setCreditDays(15);
3947
				sdCreditRequirement.setInterestRate(BigDecimal.valueOf(0.05));
3948
				sdCreditRequirement.setSuggestedLimit(suggestedAmount);
30929 tejbeer 3949
				sdCreditRequirement.setRisk(CreditRisk.HIGH_RISK);
30913 tejbeer 3950
				sdCreditRequirement.setLimit(suggestedAmount);
3951
				sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
3952
				sdCreditRequirement.setCreateTimestamp(LocalDateTime.now());
3953
				sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3954
				sdCreditRequirementRepository.persist(sdCreditRequirement);
3955
			}
30929 tejbeer 3956
 
30936 tejbeer 3957
			CreditRisk creditRisk = sdCreditService.getCurrentRisk(sdCreditRequirement, firstBillingDate);
30929 tejbeer 3958
 
3959
			sdCreditRequirement.setRisk(creditRisk);
3960
 
30913 tejbeer 3961
			sdCreditRequirement.setSuggestedLimit(suggestedAmount);
3962
			sdCreditRequirement.setLimit(suggestedAmount);
3963
			BigDecimal utilizedLimit = new BigDecimal(sdCreditService.getUtilizationAmount(fofoId));
3964
 
3965
			BigDecimal availableLimit = sdCreditRequirement.getLimit().subtract(utilizedLimit);
3966
 
3967
			LOGGER.info("utilizedLimit {} ", utilizedLimit);
3968
 
3969
			LOGGER.info("availableLimit {} ", availableLimit);
3970
 
3971
			sdCreditRequirement.setUtilizedAmount(utilizedLimit);
3972
 
3973
			sdCreditRequirement.setUpdateTimestamp(LocalDateTime.now());
3974
 
30934 tejbeer 3975
			CreditAccount creditAccount = creditAccountRepository
3976
					.selectByFofoIdAndGateway(sdCreditRequirement.getFofoId(), Gateway.SDDIRECT);
30965 tejbeer 3977
			if (creditAccount != null) {
30934 tejbeer 3978
 
30965 tejbeer 3979
				creditAccount.setInterestRate(sdCreditRequirement.getInterestRate().floatValue());
3980
				creditAccount.setSanctionedAmount(sdCreditRequirement.getLimit().floatValue());
3981
				creditAccount.setAvailableAmount(availableLimit.floatValue());
3982
				creditAccount.setFreeDays(sdCreditRequirement.getFreeDays());
30934 tejbeer 3983
				creditAccount.setUpdatedOn(LocalDateTime.now());
3984
			}
3985
 
30913 tejbeer 3986
		}
3987
 
3988
	}
3989
 
30936 tejbeer 3990
	public void notifyDefaultLoans() throws ProfitMandiBusinessException, MessagingException, IOException {
30929 tejbeer 3991
 
30936 tejbeer 3992
		sdCreditService.updateRisk();
3993
		List<Loan> defaultLoans = sdCreditService.getDefaultLoan();
3994
		if (!defaultLoans.isEmpty()) {
3995
			this.sendDefaultLoanAlert(defaultLoans);
30929 tejbeer 3996
		}
3997
 
3998
	}
3999
 
30936 tejbeer 4000
	public void sendDefaultLoanAlert(List<Loan> defaultLoans)
4001
			throws ProfitMandiBusinessException, MessagingException, IOException {
4002
		String subject = "Default Partners";
30929 tejbeer 4003
 
30936 tejbeer 4004
		List<AuthUser> authUsers = csService
4005
				.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_FINANCIAL_SERVICES);
4006
		if (!authUsers.isEmpty()) {
4007
			List<String> financeEmails = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
4008
			String messageText = this.getMessageForDueDateExtend(defaultLoans);
30929 tejbeer 4009
 
30936 tejbeer 4010
			String[] email = financeEmails.toArray(new String[financeEmails.size()]);
30929 tejbeer 4011
 
30936 tejbeer 4012
			this.sendMailHtmlFormat(email, messageText, null, subject);
30929 tejbeer 4013
 
30936 tejbeer 4014
		}
30929 tejbeer 4015
 
30936 tejbeer 4016
		for (Map.Entry<String, Set<Integer>> storeGuyEntry : csService.getAuthUserPartnerIdMapping().entrySet()) {
4017
			List<Loan> filteredRows = new ArrayList<>();
4018
			for (Loan loan : defaultLoans) {
30929 tejbeer 4019
 
30936 tejbeer 4020
				if (storeGuyEntry.getValue().contains(loan.getFofoId())) {
30929 tejbeer 4021
 
30936 tejbeer 4022
					filteredRows.add(loan);
30929 tejbeer 4023
				}
4024
			}
30936 tejbeer 4025
			if (!filteredRows.isEmpty()) {
4026
				String messageText = this.getMessageForDueDateExtend(filteredRows);
4027
				String[] email = new String[] { storeGuyEntry.getKey() };
30929 tejbeer 4028
 
30936 tejbeer 4029
				this.sendMailHtmlFormat(email, messageText, null, subject);
30929 tejbeer 4030
 
30931 tejbeer 4031
			}
4032
 
30936 tejbeer 4033
		}
30929 tejbeer 4034
 
30936 tejbeer 4035
		for (Loan defaultLoan : defaultLoans) {
4036
			List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(defaultLoan.getId());
30929 tejbeer 4037
 
30936 tejbeer 4038
			double amount = loanStatements.stream().map(x -> x.getAmount())
4039
					.collect(Collectors.summingDouble(x -> x.doubleValue()));
30929 tejbeer 4040
 
30982 tejbeer 4041
			com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(defaultLoan.getFofoId());
4042
 
4043
			Address address = addressRepository.selectById(user.getAddressId());
4044
 
30989 tejbeer 4045
			String title = "Loan Amount Overdue!";
30936 tejbeer 4046
			String url = "http://app.smartdukaan.com/pages/home/credit";
30989 tejbeer 4047
			String message = "Your loan due date "
30936 tejbeer 4048
					+ defaultLoan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
30991 tejbeer 4049
					+ " has been exceeded. Additional penal interest of "
4050
					+ defaultLoan.getInterestRate().setScale(2, RoundingMode.HALF_UP)
30989 tejbeer 4051
					+ "%  and Rs.100 shall be levied on daily basis." + " Your total pending Loan amount is Rs."
30991 tejbeer 4052
					+ FormattingUtils.formatDecimal(Math.abs(amount)) + ". !!Pay Now!!";
30936 tejbeer 4053
			notificationService.sendNotification(defaultLoan.getFofoId(), title, MessageType.notification, title,
4054
					message, url);
4055
 
30989 tejbeer 4056
			notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4057
 
30929 tejbeer 4058
		}
4059
	}
4060
 
4061
	private String getMessageForDueDateExtend(List<Loan> loans) throws ProfitMandiBusinessException {
4062
		StringBuilder sb = new StringBuilder();
30936 tejbeer 4063
		sb.append(
4064
				"<html><body><p>Alert</p><p>Default Partners :-</p>" + "<br/><p>EveryDay Rs.100 charged as Penalty</p>"
4065
						+ "<br/><table style='border:1px solid black ;padding: 5px';>");
30929 tejbeer 4066
		sb.append("<tbody>\n" + "	    				<tr>\n"
4067
				+ "	    					<th style='border:1px solid black;padding: 5px'>PartnerName</th>\n"
4068
				+ "	    					<th style='border:1px solid black;padding: 5px'>due date</th>\n"
4069
				+ "	    					<th style='border:1px solid black;padding: 5px'>Days</th>\n"
30936 tejbeer 4070
				+ "	    					<th style='border:1px solid black;padding: 5px'>Pending Amount</th>\n"
30929 tejbeer 4071
 
4072
				+ "	    				</tr>");
4073
		for (Loan entry : loans) {
30936 tejbeer 4074
 
4075
			List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
4076
 
4077
			double amount = loanStatements.stream().map(x -> x.getAmount())
4078
					.collect(Collectors.summingDouble(x -> x.doubleValue()));
4079
 
30929 tejbeer 4080
			long noOfdaysBetween = ChronoUnit.DAYS.between(entry.getDueDate().toLocalDate(), LocalDateTime.now());
4081
 
4082
			CustomRetailer customRetailer = retailerService.getFofoRetailer(entry.getFofoId());
4083
 
4084
			sb.append("<tr>");
4085
			sb.append("<td style='border:1px solid black;padding: 5px'>" + customRetailer.getBusinessName() + "("
4086
					+ customRetailer.getCode() + ")" + "</td>");
4087
 
4088
			sb.append("<td style='border:1px solid black;padding: 5px'>"
4089
					+ entry.getDueDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>");
4090
			sb.append("<td style='border:1px solid black;padding: 5px'>" + noOfdaysBetween + "</td>");
30936 tejbeer 4091
			sb.append("<td style='border:1px solid black;padding: 5px'>"
4092
					+ new DecimalFormat("#.##").format(Math.abs(amount)) + "</td>");
30929 tejbeer 4093
 
4094
			sb.append("</tr>");
4095
 
4096
		}
4097
 
4098
		sb.append("</tbody></table></body></html>");
4099
 
4100
		return sb.toString();
4101
	}
4102
 
30936 tejbeer 4103
	public void notifyLoanDueDateCross() throws ProfitMandiBusinessException, MessagingException, IOException {
4104
 
4105
		List<Loan> loans = loanRepository.selectAllActiveLoan().stream()
4106
				.filter(x -> x.getDueDate().isBefore(LocalDateTime.now())).collect(Collectors.toList());
4107
		if (!loans.isEmpty()) {
4108
			for (Loan loan : loans) {
4109
 
4110
				long noOfdaysBetween = ChronoUnit.DAYS.between(loan.getDueDate().toLocalDate(), LocalDate.now());
4111
 
30982 tejbeer 4112
				com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
4113
 
4114
				Address address = addressRepository.selectById(user.getAddressId());
4115
 
30936 tejbeer 4116
				LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
4117
 
4118
				if (noOfdaysBetween <= 15 && noOfdaysBetween >= 0) {
4119
					List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
4120
 
4121
					double amount = loanStatements.stream().map(x -> x.getAmount())
4122
							.collect(Collectors.summingDouble(x -> x.doubleValue()));
4123
 
30989 tejbeer 4124
					String url = "http://app.smartdukaan.com/pages/home/credit";
4125
 
30982 tejbeer 4126
					String title = "Alert!";
30989 tejbeer 4127
					String message = "Your loan due date "
30936 tejbeer 4128
							+ loan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
30991 tejbeer 4129
							+ " has been exceeded. Additional penal interest of "
4130
							+ loan.getInterestRate().setScale(2, RoundingMode.HALF_UP)
30989 tejbeer 4131
							+ "% shall be levied on daily basis. Your total pending loan amount is Rs."
30936 tejbeer 4132
							+ FormattingUtils.formatDecimal(Math.abs(amount)) + ". !!Pay Now!!";
30989 tejbeer 4133
 
30936 tejbeer 4134
					notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title,
4135
							message, url);
30982 tejbeer 4136
 
30989 tejbeer 4137
					notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4138
 
30936 tejbeer 4139
				}
4140
			}
4141
		}
4142
 
4143
	}
4144
 
4145
	public void alertForDueDate() throws ProfitMandiBusinessException, MessagingException, IOException {
4146
 
4147
		List<Loan> loans = loanRepository.selectAllActiveLoan();
4148
 
4149
		if (!loans.isEmpty()) {
4150
			for (Loan loan : loans) {
4151
 
30982 tejbeer 4152
				com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(loan.getFofoId());
4153
 
4154
				Address address = addressRepository.selectById(user.getAddressId());
4155
 
30936 tejbeer 4156
				long noOfdaysBetween = ChronoUnit.DAYS.between(LocalDate.now(), loan.getDueDate().toLocalDate());
4157
 
4158
				LOGGER.info("noOfdaysBetween {} ", noOfdaysBetween);
4159
 
4160
				if (noOfdaysBetween <= 4 && noOfdaysBetween >= 0) {
4161
					List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(loan.getId());
4162
					double amount = loanStatements.stream().map(x -> x.getAmount())
4163
							.collect(Collectors.summingDouble(x -> x.doubleValue()));
4164
 
30965 tejbeer 4165
					String title = "Alert!";
30936 tejbeer 4166
					String url = "http://app.smartdukaan.com/pages/home/credit";
4167
					String message = null;
4168
					if (noOfdaysBetween == 0) {
4169
 
4170
						message = "Your total pending Loan amount is Rs."
4171
								+ FormattingUtils.formatDecimal(Math.abs(amount)) + " is due for Today, Pay Now!!";
4172
 
4173
					} else {
4174
 
4175
						message = "Your total pending Loan amount is Rs."
4176
								+ FormattingUtils.formatDecimal(Math.abs(amount)) + " is due by "
4177
								+ loan.getDueDate().toLocalDate().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
30989 tejbeer 4178
								+ " , Pay Now!!";
30936 tejbeer 4179
 
4180
					}
4181
					notificationService.sendNotification(loan.getFofoId(), title, MessageType.notification, title,
4182
							message, url);
30989 tejbeer 4183
					notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());
30982 tejbeer 4184
 
30936 tejbeer 4185
				}
4186
			}
4187
		}
4188
 
4189
	}
4190
 
30982 tejbeer 4191
	public void userMobileNumberOptIn() throws HttpHostConnectException, ProfitMandiBusinessException {
4192
 
4193
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
4194
 
4195
		List<com.spice.profitmandi.dao.entity.user.User> users = userUserRepository
4196
				.selectByIds(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
4197
 
4198
		List<Address> addresses = addressRepository
4199
				.selectByIds(users.stream().map(x -> x.getAddressId()).collect(Collectors.toList()));
4200
 
30984 tejbeer 4201
		LOGGER.info("addresses" + addresses);
4202
 
30982 tejbeer 4203
		for (Address address : addresses) {
4204
			Map<String, String> requestheaders = new HashMap<>();
4205
			requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
4206
			Map<String, String> requestParams = new HashMap<>();
4207
			requestParams.put("userid", String.valueOf(2000215976));
4208
			requestParams.put("password", "MFRd!BBL");
30983 tejbeer 4209
			requestParams.put("phone_number", address.getPhoneNumber());
30982 tejbeer 4210
			requestParams.put("auth_scheme", "plain");
4211
			requestParams.put("v", "1.1");
30983 tejbeer 4212
			requestParams.put("format", "json");
30982 tejbeer 4213
 
4214
			requestParams.put("method", "OPT_IN");
4215
 
4216
			requestParams.put("channel", "WHATSAPP");
4217
			String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams,
4218
					requestheaders);
4219
			LOGGER.info("response" + response);
4220
		}
4221
 
4222
	}
4223
 
4224
	public void authUserMobileNumberOptIn() throws HttpHostConnectException, ProfitMandiBusinessException {
4225
 
4226
		List<AuthUser> authUsers = authRepository.selectAllActiveUser();
30984 tejbeer 4227
		LOGGER.info("authUsers" + authUsers);
4228
 
30982 tejbeer 4229
		for (AuthUser authUser : authUsers) {
4230
			Map<String, String> requestheaders = new HashMap<>();
4231
			requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
4232
			Map<String, String> requestParams = new HashMap<>();
4233
			requestParams.put("userid", String.valueOf(2000215976));
4234
			requestParams.put("password", "MFRd!BBL");
30983 tejbeer 4235
			requestParams.put("phone_number", authUser.getMobileNumber());
30982 tejbeer 4236
			requestParams.put("auth_scheme", "plain");
4237
			requestParams.put("v", "1.1");
30983 tejbeer 4238
			requestParams.put("format", "json");
30982 tejbeer 4239
 
4240
			requestParams.put("method", "OPT_IN");
4241
 
4242
			requestParams.put("channel", "WHATSAPP");
4243
			String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams,
4244
					requestheaders);
4245
			LOGGER.info("response" + response);
4246
		}
4247
 
4248
	}
4249
 
26418 tejbeer 4250
}
29814 tejbeer 4251
 
27438 amit.gupta 4252
//2284