Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
22551 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
30859 tejbeer 3
import com.spice.profitmandi.common.enumuration.MessageType;
22551 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23936 tejbeer 5
import com.spice.profitmandi.common.model.CustomRetailer;
34527 tejus.loha 6
import com.spice.profitmandi.common.model.HdfcPaymentModel;
22551 ashik.ali 7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
24089 tejbeer 8
import com.spice.profitmandi.common.model.UnsettledPaymentModel;
31238 amit.gupta 9
import com.spice.profitmandi.common.util.*;
29811 tejbeer 10
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
31238 amit.gupta 11
import com.spice.profitmandi.dao.entity.transaction.*;
35971 aman 12
import com.spice.profitmandi.dao.entity.user.FullStockPayment;
32727 shampa 13
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
35971 aman 14
import com.spice.profitmandi.dao.enumuration.onBorading.onBoardingFormEnums.FullStockPaymentStatus;
23936 tejbeer 15
import com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus;
24876 tejbeer 16
import com.spice.profitmandi.dao.enumuration.transaction.TransactionType;
33420 amit.gupta 17
import com.spice.profitmandi.dao.model.DateRangeModel;
33861 tejus.loha 18
import com.spice.profitmandi.dao.model.StoreTimelineModel;
23936 tejbeer 19
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
24876 tejbeer 20
import com.spice.profitmandi.dao.repository.catalog.ManualPaymentRequestRepository;
24089 tejbeer 21
import com.spice.profitmandi.dao.repository.catalog.UnsettledPaymentsRepository;
29811 tejbeer 22
import com.spice.profitmandi.dao.repository.dtr.CreditAccountRepository;
24876 tejbeer 23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33861 tejus.loha 24
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
23985 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
32490 jai.hind 26
import com.spice.profitmandi.dao.repository.transaction.*;
35971 aman 27
import com.spice.profitmandi.dao.repository.user.FullStockPaymentRepository;
33861 tejus.loha 28
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
33359 amit.gupta 29
import com.spice.profitmandi.dao.service.SidbiService;
30859 tejbeer 30
import com.spice.profitmandi.service.NotificationService;
24523 amit.gupta 31
import com.spice.profitmandi.service.authentication.RoleManager;
29070 amit.gupta 32
import com.spice.profitmandi.service.transaction.TransactionService;
23936 tejbeer 33
import com.spice.profitmandi.service.user.RetailerService;
33861 tejus.loha 34
import com.spice.profitmandi.service.user.StoreTimelineTatService;
22551 ashik.ali 35
import com.spice.profitmandi.service.wallet.WalletService;
36
import com.spice.profitmandi.web.model.LoginDetails;
37
import com.spice.profitmandi.web.util.CookiesProcessor;
23936 tejbeer 38
import com.spice.profitmandi.web.util.MVCResponseSender;
39
import in.shop2020.model.v1.order.WalletReferenceType;
31238 amit.gupta 40
import org.apache.logging.log4j.LogManager;
41
import org.apache.logging.log4j.Logger;
42
import org.apache.poi.ss.usermodel.Cell;
43
import org.apache.poi.ss.usermodel.CellStyle;
44
import org.apache.poi.ss.usermodel.CreationHelper;
45
import org.apache.poi.ss.usermodel.Sheet;
46
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
47
import org.springframework.beans.factory.annotation.Autowired;
48
import org.springframework.core.io.InputStreamResource;
49
import org.springframework.http.HttpHeaders;
50
import org.springframework.http.HttpStatus;
51
import org.springframework.http.ResponseEntity;
52
import org.springframework.mail.javamail.JavaMailSender;
53
import org.springframework.mail.javamail.MimeMessageHelper;
54
import org.springframework.stereotype.Controller;
35971 aman 55
import org.springframework.transaction.annotation.Transactional;
31238 amit.gupta 56
import org.springframework.ui.Model;
57
import org.springframework.web.bind.annotation.*;
58
import org.springframework.web.multipart.MultipartFile;
23936 tejbeer 59
 
31238 amit.gupta 60
import javax.mail.internet.InternetAddress;
61
import javax.mail.internet.MimeMessage;
62
import javax.servlet.http.HttpServletRequest;
63
import javax.swing.*;
64
import java.io.ByteArrayInputStream;
65
import java.io.ByteArrayOutputStream;
66
import java.io.InputStream;
32490 jai.hind 67
import java.math.BigDecimal;
31238 amit.gupta 68
import java.text.MessageFormat;
33420 amit.gupta 69
import java.time.*;
31238 amit.gupta 70
import java.util.*;
71
import java.util.stream.Collectors;
72
 
34096 aman.kumar 73
import static com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus.approved;
74
 
22551 ashik.ali 75
@Controller
35458 amit 76
@Transactional(rollbackFor = Throwable.class)
22551 ashik.ali 77
public class WalletController {
78
 
32491 jai.hind 79
    private static final int IDX_PERIOD = 1;
80
    private static final int OPENING_BALANCE = 2;
81
    private static final int ACTIVATION_SCHEME = 4;
82
    private static final int ADVANCE_AMOUNT = 5;
83
    private static final int AUTOMATED_ADVANCE = 6;
84
    private static final int BRAND_PAYOUT = 7;
85
    private static final int INVESTMENT_PAYOUT = 8;
86
    private static final int OTHERS = 9;
87
    private static final int PREBOOKING_ORDER = 10;
88
    private static final int PRICE_DROP = 11;
89
    private static final int PURCHASE = 12;
90
    private static final int PURCHASE_BILLED = 13;
91
    private static final int PURCHASE_PENDING_BILLING = 14;
92
    private static final int PURCHASE_CANCELLED = 15;
93
    private static final int RECHARGE = 16;
94
    private static final int REFUND = 17;
95
    private static final int SCHEME_IN = 18;
96
    private static final int SCHEME_OUT = 19;
97
    private static final Map<WalletReferenceType, Integer> walletReferenceMap = new HashMap<>();
32494 amit.gupta 98
    private static final int GRAND_TOTAL = 20;
99
    private static final int CLOSING_BALANCE = 22;
100
    private static final int PENDING_GRN = 23;
101
    private static final int ACTIVATED_IMEIS = 24;
102
    private static final Logger LOGGER = LogManager.getLogger(WalletController.class);
32490 jai.hind 103
 
32491 jai.hind 104
    static {
105
        walletReferenceMap.put(WalletReferenceType.ACTIVATION_SCHEME, ACTIVATION_SCHEME);
106
        walletReferenceMap.put(WalletReferenceType.ADVANCE_AMOUNT, ADVANCE_AMOUNT);
107
        walletReferenceMap.put(WalletReferenceType.AUTOMATED_ADVANCE, AUTOMATED_ADVANCE);
108
        walletReferenceMap.put(WalletReferenceType.BRAND_PAYOUT, BRAND_PAYOUT);
109
        walletReferenceMap.put(WalletReferenceType.INVESTMENT_PAYOUT, INVESTMENT_PAYOUT);
110
        walletReferenceMap.put(WalletReferenceType.OTHERS, OTHERS);
111
        walletReferenceMap.put(WalletReferenceType.PREBOOKING_ORDER, PREBOOKING_ORDER);
112
        walletReferenceMap.put(WalletReferenceType.PRICE_DROP, PRICE_DROP);
113
        walletReferenceMap.put(WalletReferenceType.PURCHASE, PURCHASE);
114
        walletReferenceMap.put(WalletReferenceType.RECHARGE, RECHARGE);
115
        walletReferenceMap.put(WalletReferenceType.REFUND, REFUND);
116
        walletReferenceMap.put(WalletReferenceType.SCHEME_IN, SCHEME_IN);
117
        walletReferenceMap.put(WalletReferenceType.SCHEME_OUT, SCHEME_OUT);
28515 amit.gupta 118
 
32491 jai.hind 119
    }
32490 jai.hind 120
 
32491 jai.hind 121
    @Autowired
36401 amit 122
    JavaMailSender gmailRelaySender;
32494 amit.gupta 123
    @Autowired
35811 amit 124
    com.spice.profitmandi.service.transaction.SDCreditService sdCreditService;
125
    @Autowired
32494 amit.gupta 126
    AddWalletRequestRepository addWalletRequestRepository;
127
    @Autowired
128
    TransactionService transactionService;
129
    @Autowired
32491 jai.hind 130
    private CookiesProcessor cookiesProcessor;
131
    @Autowired
132
    private WalletService walletService;
133
    @Autowired
134
    private UserWalletRepository userWalletRepository;
135
    @Autowired
136
    private UserWalletHistoryRepository userWalletHistoryRepository;
137
    @Autowired
138
    private MVCResponseSender mvcResponseSender;
139
    @Autowired
140
    private UserAccountRepository userAccountRepository;
141
    @Autowired
142
    private OrderRepository orderRepository;
143
    @Autowired
144
    private UnsettledPaymentsRepository unsettledPaymentsRepository;
145
    @Autowired
146
    private RetailerService retailerService;
147
    @Autowired
148
    private RoleManager roleManager;
149
    @Autowired
150
    private FofoStoreRepository fofoStoreRepository;
151
    @Autowired
152
    private ManualPaymentRequestRepository manualPaymentRequestRepository;
153
    @Autowired
154
    private CreditAccountRepository creditAccountRepository;
30859 tejbeer 155
 
32491 jai.hind 156
    @Autowired
157
    private NotificationService notificationService;
158
    @Autowired
159
    LoanRepository loanRepository;
160
    @Autowired
161
    private LoanStatementRepository loanStatementRepository;
162
    @Autowired
36754 amit 163
    private ReturnOrderInfoRepository returnOrderInfoRepository;
164
    @Autowired
32491 jai.hind 165
    SDCreditRequirementRepository sdCreditRequirementRepository;
33861 tejus.loha 166
    @Autowired
167
    LoiFormRepository loiFormRepository;
168
    @Autowired
169
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
170
    @Autowired
171
    StoreTimelineTatService storeTimelineTatService;
28515 amit.gupta 172
 
35971 aman 173
    @Autowired
174
    FullStockPaymentRepository fullStockPaymentRepository;
175
    @Autowired
176
    com.spice.profitmandi.dao.repository.auth.AuthRepository authRepository;
177
    @Autowired
178
    com.spice.profitmandi.dao.repository.cs.PositionRepository positionRepository;
33205 amit.gupta 179
 
35971 aman 180
 
32491 jai.hind 181
    @PostMapping(value = "/wallet/upload")
32495 amit.gupta 182
    public String uploadWalletBulk(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model) throws Exception {
32491 jai.hind 183
        List<WalletHistoryModel> walletHistoryModelList = ExcelUtils.parseWalletBulkCredit(file.getInputStream());
184
        for (WalletHistoryModel walletHistoryModel : walletHistoryModelList) {
185
            if (walletHistoryModel.getReference() == 0) {
32495 amit.gupta 186
                ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(walletHistoryModel.getWalletReferenceType());
32491 jai.hind 187
                if (paymentType == null) {
188
                    paymentType = new ManualPaymentType();
189
                    paymentType.setReferenceType(walletHistoryModel.getWalletReferenceType());
190
                    manualPaymentRequestRepository.persist(paymentType);
191
                }
192
                paymentType.setCounter(paymentType.getCounter() + 1);
193
                int reference = paymentType.getCounter();
32495 amit.gupta 194
                walletService.addAmountToWallet(walletHistoryModel.getFofoId(), reference, walletHistoryModel.getWalletReferenceType(), walletHistoryModel.getDescription(), (float) walletHistoryModel.getAmount(), walletHistoryModel.getBusinessDate());
32491 jai.hind 195
            } else {
32495 amit.gupta 196
                walletService.addAmountToWallet(walletHistoryModel.getFofoId(), walletHistoryModel.getReference(), walletHistoryModel.getWalletReferenceType(), walletHistoryModel.getDescription(), (float) walletHistoryModel.getAmount(), walletHistoryModel.getBusinessDate());
32491 jai.hind 197
            }
198
        }
23993 tejbeer 199
 
32491 jai.hind 200
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
201
        return "response";
202
    }
27067 amit.gupta 203
 
32491 jai.hind 204
    @RequestMapping(value = "/walletDetails", method = RequestMethod.GET)
32495 amit.gupta 205
    public String dashboard(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "100") int limit, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 206
        /*
207
         * boolean underMaintainance = true; if(underMaintainance) { throw new
208
         * ProfitMandiBusinessException("Wallet", "Wallet",
209
         * "Wallet is under Maintenance"); }
210
         */
211
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
212
        int fofoId = fofoDetails.getFofoId();
213
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
214
        UserWallet userWallet = walletService.getUserWallet(fofoId);
23993 tejbeer 215
 
32491 jai.hind 216
        LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
217
        LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
23993 tejbeer 218
 
32491 jai.hind 219
        List<UserWalletHistory> userWalletHistories = new ArrayList<>();
220
        try {
32495 amit.gupta 221
            userWalletHistories = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDateTime, endDateTime, offset, limit);
32491 jai.hind 222
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
223
            LOGGER.error("UserWallet History not found : ", profitMandiBusinessException);
224
        }
23993 tejbeer 225
 
32491 jai.hind 226
        long countItems = 0;
227
        try {
228
            countItems = walletService.getSizeByRetailerId(fofoDetails.getFofoId(), startDateTime, endDateTime);
229
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
230
            LOGGER.error("UserWallet not found : ", profitMandiBusinessException);
231
        }
36746 amit 232
        com.spice.profitmandi.dao.model.CreditSummary creditSummary = sdCreditService.getCreditSummary(fofoId);
32491 jai.hind 233
        model.addAttribute("userWallet", userWallet);
234
        model.addAttribute("walletHistories", userWalletHistories);
36242 aman 235
        model.addAttribute("walletAttachmentMap", buildWalletHistoryAttachmentMap(userWalletHistories));
32491 jai.hind 236
        model.addAttribute("start", offset + 1);
237
        model.addAttribute("size", countItems);
238
        model.addAttribute("isAdmin", isAdmin);
36746 amit 239
        model.addAttribute("totalDue", creditSummary.getTotalDue());
240
        model.addAttribute("utilization", creditSummary.getUtilization());
32491 jai.hind 241
        model.addAttribute(ProfitMandiConstants.START_TIME, startTimeString);
242
        model.addAttribute(ProfitMandiConstants.END_TIME, endTimeString);
23993 tejbeer 243
 
32491 jai.hind 244
        if (userWalletHistories.size() < limit) {
245
            model.addAttribute("end", offset + userWalletHistories.size());
246
        } else {
247
            model.addAttribute("end", offset + limit);
248
        }
249
        return "wallet-details";
250
    }
23993 tejbeer 251
 
32491 jai.hind 252
    @RequestMapping(value = "/getPaginatedWalletHistory")
32495 amit.gupta 253
    public String getSaleHistoryPaginated(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 254
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22551 ashik.ali 255
 
32491 jai.hind 256
        LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
257
        LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
23993 tejbeer 258
 
32491 jai.hind 259
        List<UserWalletHistory> userWalletHistories = new ArrayList<>();
260
        try {
32495 amit.gupta 261
            userWalletHistories = walletService.getPaginatedUserWalletHistoryByRetailerId(loginDetails.getFofoId(), startDateTime, endDateTime, offset, limit);
32491 jai.hind 262
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
263
            LOGGER.error("UserWallet History not found : ", profitMandiBusinessException);
264
        }
23993 tejbeer 265
 
32491 jai.hind 266
        model.addAttribute("walletHistories", userWalletHistories);
36242 aman 267
        model.addAttribute("walletAttachmentMap", buildWalletHistoryAttachmentMap(userWalletHistories));
32491 jai.hind 268
        return "wallet-history-paginated";
269
    }
23936 tejbeer 270
 
32491 jai.hind 271
    @RequestMapping(value = "/getAddWalletRequest", method = RequestMethod.GET)
36500 ranu 272
    public String getAddwalletRequest(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "100") int limit, Model model) throws Exception {
32491 jai.hind 273
        List<AddWalletRequest> walletRequest = null;
274
        long size = 0;
275
        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.pending);
276
        LOGGER.info("walletRequest" + walletRequest);
277
        size = addWalletRequestRepository.selectCountByStatus(AddWalletRequestStatus.pending);
278
        if (!walletRequest.isEmpty()) {
279
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
30426 tejbeer 280
 
32491 jai.hind 281
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 282
 
32495 amit.gupta 283
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 284
 
32491 jai.hind 285
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
286
            model.addAttribute("walletRequest", walletRequest);
36242 aman 287
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 288
            model.addAttribute("rStatus", "pending");
289
            model.addAttribute("start", offset + 1);
290
            model.addAttribute("size", size);
291
            model.addAttribute("url", "/getPaginatedWalletRequest");
23993 tejbeer 292
 
32491 jai.hind 293
            if (walletRequest.size() < limit) {
294
                model.addAttribute("end", offset + walletRequest.size());
295
            } else {
296
                model.addAttribute("end", offset + limit);
297
            }
23993 tejbeer 298
 
32491 jai.hind 299
        } else {
23993 tejbeer 300
 
32491 jai.hind 301
            model.addAttribute("walletRequest", walletRequest);
302
            model.addAttribute("size", size);
23936 tejbeer 303
 
32491 jai.hind 304
        }
305
        return "add-wallet-request";
306
    }
23936 tejbeer 307
 
32491 jai.hind 308
    @RequestMapping(value = "/getPaginatedWalletRequest", method = RequestMethod.GET)
32495 amit.gupta 309
    public String getPaginatedWalletRequest(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws Exception {
32491 jai.hind 310
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
311
        List<AddWalletRequest> walletRequest = null;
312
        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.pending);
313
        LOGGER.info("walletRequest" + walletRequest);
314
        if (!walletRequest.isEmpty()) {
315
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
316
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 317
 
32495 amit.gupta 318
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 319
 
32491 jai.hind 320
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
321
            model.addAttribute("walletRequest", walletRequest);
36242 aman 322
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 323
            model.addAttribute("rStatus", "pending");
324
            model.addAttribute("url", "/getPaginatedWalletRequest");
23993 tejbeer 325
 
32491 jai.hind 326
        } else {
327
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 328
 
32491 jai.hind 329
        }
23993 tejbeer 330
 
32491 jai.hind 331
        return "add-wallet-request-paginated";
332
    }
23993 tejbeer 333
 
32491 jai.hind 334
    @RequestMapping(value = "/getAddWalletApproved", method = RequestMethod.GET)
34096 aman.kumar 335
    public String walletAddnAccept(HttpServletRequest request, Model model) throws Exception {
336
 
337
        return "add-wallet-req";
338
    }
339
 
340
    @RequestMapping(value = "/getAddWalletApprovedByDate", method = RequestMethod.GET)
341
    public String getAddwalletRequestApproved(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
342
                                              @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
343
        LOGGER.info("requested startDate=[{}], EndDate = [{}]", startDate, endDate);
32491 jai.hind 344
        List<AddWalletRequest> walletRequest = null;
345
        long size = 0;
34096 aman.kumar 346
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.approved);
347
//        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, approved);
348
        size = addWalletRequestRepository.selectCountByStatus(approved);
32491 jai.hind 349
        if (!walletRequest.isEmpty()) {
350
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
351
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 352
 
32495 amit.gupta 353
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 354
 
32491 jai.hind 355
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
356
            model.addAttribute("walletRequest", walletRequest);
36242 aman 357
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 358
            model.addAttribute("start", offset + 1);
359
            model.addAttribute("size", size);
360
            model.addAttribute("url", "/getPaginatedWalletApproved");
23993 tejbeer 361
 
32491 jai.hind 362
            if (walletRequest.size() < limit) {
363
                model.addAttribute("end", offset + walletRequest.size());
364
            } else {
365
                model.addAttribute("end", offset + limit);
366
            }
367
        } else {
23993 tejbeer 368
 
32491 jai.hind 369
            model.addAttribute("walletRequest", walletRequest);
370
            model.addAttribute("size", size);
23936 tejbeer 371
 
32491 jai.hind 372
        }
34096 aman.kumar 373
        return "add-wallet-request-paginated";
32491 jai.hind 374
    }
23936 tejbeer 375
 
32491 jai.hind 376
    @RequestMapping(value = "/getPaginatedWalletApproved", method = RequestMethod.GET)
34096 aman.kumar 377
    public String getPaginatedWalletApproved(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
378
                                             @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 379
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
380
        List<AddWalletRequest> walletRequest = null;
34096 aman.kumar 381
        long size = 0;
382
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.approved);
383
 
384
//        walletRequest = addWalletRequestRepository.selectAllByStatus(offset, limit, AddWalletRequestStatus.approved);
32491 jai.hind 385
        LOGGER.info("walletRequest" + walletRequest);
386
        if (!walletRequest.isEmpty()) {
387
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
388
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 389
 
32495 amit.gupta 390
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 391
 
32491 jai.hind 392
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
393
            model.addAttribute("walletRequest", walletRequest);
36242 aman 394
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 395
            model.addAttribute("url", "/getPaginatedWalletApproved");
396
        } else {
397
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 398
 
32491 jai.hind 399
        }
400
        return "add-wallet-request-paginated";
401
    }
23993 tejbeer 402
 
32491 jai.hind 403
    @RequestMapping(value = "/getAddWalletRequestRejected", method = RequestMethod.GET)
34096 aman.kumar 404
    public String walletAddnReject(HttpServletRequest request, Model model) throws Exception {
405
 
406
        return "add-wallet-rejected";
407
    }
408
 
409
    @RequestMapping(value = "/getAddWalletRequestRejectedByDate", method = RequestMethod.GET)
410
    public String getAddwalletRequestRejected(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
411
                                              @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 412
        List<AddWalletRequest> walletRequest = null;
23985 tejbeer 413
 
32491 jai.hind 414
        long size = 0;
34096 aman.kumar 415
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.rejected);
32491 jai.hind 416
        size = addWalletRequestRepository.selectCountByStatus(AddWalletRequestStatus.rejected);
417
        LOGGER.info("walletRequest" + walletRequest);
418
        if (!walletRequest.isEmpty()) {
419
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
420
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30426 tejbeer 421
 
32495 amit.gupta 422
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
23993 tejbeer 423
 
32491 jai.hind 424
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
425
            model.addAttribute("walletRequest", walletRequest);
36242 aman 426
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 427
            model.addAttribute("start", offset + 1);
428
            model.addAttribute("size", size);
429
            model.addAttribute("url", "/getPaginatedWalletRequestRejected");
23985 tejbeer 430
 
32491 jai.hind 431
            if (walletRequest.size() < limit) {
432
                model.addAttribute("end", offset + walletRequest.size());
433
            } else {
434
                model.addAttribute("end", offset + limit);
435
            }
436
        } else {
437
            model.addAttribute("walletRequest", walletRequest);
438
            model.addAttribute("size", size);
439
        }
23993 tejbeer 440
 
34096 aman.kumar 441
        return "add-wallet-request-paginated";
32491 jai.hind 442
    }
23985 tejbeer 443
 
32491 jai.hind 444
    @RequestMapping(value = "/getPaginatedWalletRequestRejected", method = RequestMethod.GET)
34096 aman.kumar 445
    public String getPaginatedWalletRequestRejected(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "startDate") LocalDateTime startDate,
446
                                                    @RequestParam(name = "endDate") LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
32491 jai.hind 447
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
448
        List<AddWalletRequest> walletRequest = null;
34096 aman.kumar 449
        walletRequest = addWalletRequestRepository.selectAllRetailerIdByDateAndStatus(startDate, endDate, AddWalletRequestStatus.rejected);
32491 jai.hind 450
        LOGGER.info("walletRequest" + walletRequest);
451
        if (!walletRequest.isEmpty()) {
452
            List<Integer> fofoIds = this.getFofoIdsFromWalletRequest(walletRequest);
453
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
23993 tejbeer 454
 
32495 amit.gupta 455
            Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
32491 jai.hind 456
            model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
457
            model.addAttribute("walletRequest", walletRequest);
36242 aman 458
            model.addAttribute("fspAttachmentMap", buildFspAttachmentMap(walletRequest));
32491 jai.hind 459
            model.addAttribute("url", "/getPaginatedWalletRequestRejected");
460
        } else {
461
            model.addAttribute("walletRequest", walletRequest);
23993 tejbeer 462
 
32491 jai.hind 463
        }
23993 tejbeer 464
 
32491 jai.hind 465
        return "add-wallet-request-paginated";
466
    }
23993 tejbeer 467
 
35197 amit 468
    @Autowired
469
    HdfcPaymentRepository hdfcPaymentRepository;
470
 
32491 jai.hind 471
    @RequestMapping(value = "/addAmountToWallet", method = RequestMethod.PUT)
32495 amit.gupta 472
    public String addAmountToWallet(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, @RequestParam(name = "walletRequestid", defaultValue = "0") int walletRequestid, Model model) throws Exception {
23993 tejbeer 473
 
32491 jai.hind 474
        AddWalletRequest addWalletRequest = addWalletRequestRepository.selectById(walletRequestid);
35197 amit 475
        List<AddWalletRequest> requests = addWalletRequestRepository.selectAllByTransactionReference(addWalletRequest.getTransaction_reference());
476
        if (requests.stream().filter(x -> x.getId() != addWalletRequest.getId()).filter(x -> x.getStatus().equals(approved)).count() != 1) {
477
            HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(addWalletRequest.getTransaction_reference());
478
            if (hdfcPayment != null) {
479
                String rejectReason = "Payment for UTR Already added via Auto Update";
480
                throw new ProfitMandiBusinessException(rejectReason, rejectReason, rejectReason);
481
            }
482
        } else {
483
            String rejectReason = "Entry already Approved Please reject";
484
            throw new ProfitMandiBusinessException(rejectReason, rejectReason, rejectReason);
485
        }
35971 aman 486
        // FSP wallet addons can only be approved by Account team L3
487
        if (addWalletRequest.getFspId() > 0) {
488
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
489
            String approverEmail = loginDetails.getEmailId();
490
            com.spice.profitmandi.dao.entity.auth.AuthUser approverUser = authRepository.selectByEmailOrMobile(approverEmail);
491
            boolean isAccountL3 = false;
492
            if (approverUser != null) {
493
                List<com.spice.profitmandi.dao.entity.cs.Position> positions = positionRepository.selectPositionByAuthId(approverUser.getId());
494
                for (com.spice.profitmandi.dao.entity.cs.Position position : positions) {
495
                    if (position.getEscalationType().equals(com.spice.profitmandi.dao.enumuration.cs.EscalationType.L3)
496
                            && position.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS) {
497
                        isAccountL3 = true;
498
                        break;
499
                    }
500
                }
501
            }
502
            if (!isAccountL3) {
503
                throw new ProfitMandiBusinessException(
504
                        "Only Account team L3 can approve Full Stock Payment entries",
505
                        approverEmail,
506
                        "You are not authorized to approve FSP wallet requests");
507
            }
508
        }
509
 
32491 jai.hind 510
        if (addWalletRequest.getStatus().equals(AddWalletRequestStatus.pending)) {
32495 amit.gupta 511
            walletService.addAmountToWallet(addWalletRequest.getRetailerId(), walletRequestid, WalletReferenceType.ADVANCE_AMOUNT, "ntfs/rgfs", addWalletRequest.getAmount(), addWalletRequest.getCreateTimestamp());
32491 jai.hind 512
            addWalletRequest.setStatus(AddWalletRequestStatus.approved);
513
            addWalletRequest.setUpdateTimestamp(LocalDateTime.now());
514
            unsettledPaymentsRepository.deleteById(id);
33861 tejus.loha 515
 
516
            // check full stock payment if partner comes from Loi process
517
            String code = fofoStoreRepository.selectByRetailerId(addWalletRequest.getRetailerId()).getCode();
518
            StoreTimelineModel storeTimelineModel = partnerOnBoardingPanelRepository.selectStoreTimeLine(code);
519
            if (storeTimelineModel != null && storeTimelineModel.getFullStockTimestamp() == null) {
520
                UserWallet userWallet = userWalletRepository.selectByRetailerId(addWalletRequest.getRetailerId());
521
                List<UserWalletHistory> userWalletHistories = userWalletHistoryRepository.selectByWalletIdAndReferenceType(userWallet.getId(), WalletReferenceType.ADVANCE_AMOUNT);
522
                long totalAdvanceAmount = userWalletHistories.stream().mapToLong(x -> x.getAmount()).sum();
523
                LOGGER.info("totalAdvanceAmount - " + totalAdvanceAmount);
35971 aman 524
                if (totalAdvanceAmount >= ProfitMandiConstants.FSP_DIRECT_WALLET_THRESHOLD) {
33861 tejus.loha 525
                    storeTimelineTatService.onFullPaymentReceived(storeTimelineModel.getOnboardingId());
526
                }
35971 aman 527
 
528
                // Mark linked FullStockPayment record as APPROVED via fspId
529
                if (addWalletRequest.getFspId() > 0) {
530
                    FullStockPayment fsp = fullStockPaymentRepository.selectById(addWalletRequest.getFspId());
531
                    if (fsp != null && fsp.getPaymentStatus() == FullStockPaymentStatus.PENDING) {
532
                        fsp.setPaymentStatus(FullStockPaymentStatus.APPROVED);
533
                        fsp.setApproveTimestamp(LocalDateTime.now());
534
                        fullStockPaymentRepository.persist(fsp);
535
                        LOGGER.info("Marked FSP id={} as APPROVED via wallet addon approval, onboardingId={}", fsp.getId(), storeTimelineModel.getOnboardingId());
536
                    }
537
                }
538
 
539
                // Auto-mark FULL_STOCK_PAYMENT in timeline when total approved FSP amount >= 7 lakh
540
                double totalApprovedFsp = fullStockPaymentRepository.selectByOnboardingId(storeTimelineModel.getOnboardingId())
541
                        .stream()
542
                        .filter(p -> p.getPaymentStatus() == FullStockPaymentStatus.APPROVED)
543
                        .mapToDouble(FullStockPayment::getCollectedAmount)
544
                        .sum();
545
                LOGGER.info("totalApprovedFsp={} for onboardingId={}", totalApprovedFsp, storeTimelineModel.getOnboardingId());
546
                if (totalApprovedFsp >= ProfitMandiConstants.FSP_DIRECT_WALLET_THRESHOLD) {
547
                    storeTimelineTatService.onFullPaymentReceived(storeTimelineModel.getOnboardingId());
548
                    LOGGER.info("Auto-marked FULL_STOCK_PAYMENT done for onboardingId={}, totalApprovedFsp={}", storeTimelineModel.getOnboardingId(), totalApprovedFsp);
36064 aman 549
                    try {
550
                        storeTimelineTatService.sendFullStockPaymentPOEmail(storeTimelineModel.getOnboardingId());
551
                    } catch (Exception ex) {
552
                        LOGGER.error("Failed to send FSP PO email after approved FSP >= 7L for onboardingId=" + storeTimelineModel.getOnboardingId(), ex);
553
                    }
35971 aman 554
                }
33861 tejus.loha 555
            }
556
 
32491 jai.hind 557
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
558
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 559
            String subject = "Request Approved for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
560
            String messageText = MessageFormat.format("User Id - {0}\n Name -{1}\n Email -{2}\n mobile -{3}\n Reference - {4}\n Amount - Rs.{5}", new Integer(addWalletRequest.getRetailerId()), customRetailer.getBusinessName(), customRetailer.getEmail(), customRetailer.getMobileNumber(), addWalletRequest.getTransaction_reference(), new Float(addWalletRequest.getAmount()));
23993 tejbeer 561
 
32491 jai.hind 562
            //	this.sendMailWithAttachments(subject, messageText);
563
            return "response";
564
        } else {
565
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
566
            return "response";
567
        }
568
    }
23993 tejbeer 569
 
32491 jai.hind 570
    @RequestMapping(value = "/addAmountToWalletRequestRejected", method = RequestMethod.PUT)
32495 amit.gupta 571
    public String addAmountToWalletRequestRejected(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
23993 tejbeer 572
 
32491 jai.hind 573
        AddWalletRequest addWalletRequest = addWalletRequestRepository.selectById(id);
574
        if (addWalletRequest.getStatus().equals(AddWalletRequestStatus.pending)) {
575
            addWalletRequest.setStatus(AddWalletRequestStatus.rejected);
576
            addWalletRequest.setUpdateTimestamp(LocalDateTime.now());
577
            addWalletRequestRepository.persist(addWalletRequest);
35971 aman 578
 
579
            // Mark linked FSP as REJECTED via fspId
580
            if (addWalletRequest.getFspId() > 0) {
581
                try {
582
                    FullStockPayment fsp = fullStockPaymentRepository.selectById(addWalletRequest.getFspId());
583
                    if (fsp != null && fsp.getPaymentStatus() == FullStockPaymentStatus.PENDING) {
584
                        fsp.setPaymentStatus(FullStockPaymentStatus.REJECTED);
585
                        fsp.setDescription("Wallet addon request rejected");
586
                        fsp.setApproveTimestamp(LocalDateTime.now());
587
                        fullStockPaymentRepository.persist(fsp);
588
                        LOGGER.info("Marked FSP id={} as REJECTED via wallet addon rejection", fsp.getId());
589
                    }
590
                } catch (Exception e) {
591
                    LOGGER.error("Error marking FSP as REJECTED on wallet addon rejection", e);
592
                }
593
            }
594
 
32491 jai.hind 595
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
596
            CustomRetailer customRetailer = retailerService.getFofoRetailer(addWalletRequest.getRetailerId());
32495 amit.gupta 597
            String subject = "Request Rejected for " + customRetailer.getBusinessName() + " of Rs." + addWalletRequest.getAmount();
598
            String messageText = MessageFormat.format("User Id - {0}\n Name -{1}\n Email -{2}\n mobile -{3}\n Reference - {4}\n Amount - Rs.{5}", new Integer(addWalletRequest.getRetailerId()), customRetailer.getBusinessName(), customRetailer.getEmail(), customRetailer.getMobileNumber(), addWalletRequest.getTransaction_reference(), new Float(addWalletRequest.getAmount()));
23993 tejbeer 599
 
32491 jai.hind 600
            //this.sendMailWithAttachments(subject, messageText);
601
            return "response";
602
        } else {
603
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
604
            return "response";
605
        }
606
    }
23985 tejbeer 607
 
32491 jai.hind 608
    private void sendMailWithAttachments(String subject, String messageText) throws Exception {
36401 amit 609
        MimeMessage message = gmailRelaySender.createMimeMessage();
32491 jai.hind 610
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
32495 amit.gupta 611
        String[] email = {"neerajgupta2021@gmail.com", "adeel.yazdani@smartdukaan.com", "kamini.sharma@smartdukaan.com", "care@smartdukaan.com", "mohinder.mutreja@smartdukaan.com"};
32491 jai.hind 612
        helper.setSubject(subject);
613
        helper.setText(messageText);
614
        helper.setTo(email);
615
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
616
        helper.setFrom(senderAddress);
36401 amit 617
        gmailRelaySender.send(message);
23993 tejbeer 618
 
32491 jai.hind 619
    }
23936 tejbeer 620
 
32491 jai.hind 621
    private List<Integer> getFofoIdsFromWalletRequest(List<AddWalletRequest> walletRequest) {
622
        return walletRequest.stream().map(x -> x.getRetailerId()).distinct().collect(Collectors.toList());
623
    }
24089 tejbeer 624
 
36242 aman 625
    /**
626
     * Builds a map of AddWalletRequest.id -> FullStockPayment.attachment for requests linked to FSP.
627
     */
628
    private Map<Integer, Integer> buildFspAttachmentMap(List<AddWalletRequest> walletRequests) {
629
        Map<Integer, Integer> attachmentMap = new HashMap<>();
630
        List<Integer> fspIds = walletRequests.stream()
631
                .filter(r -> r.getFspId() > 0)
632
                .map(AddWalletRequest::getFspId)
633
                .distinct()
634
                .collect(Collectors.toList());
635
        if (fspIds.isEmpty()) {
636
            return attachmentMap;
637
        }
638
        List<FullStockPayment> fspList = fullStockPaymentRepository.selectByIds(fspIds);
639
        Map<Integer, Integer> fspIdToAttachment = fspList.stream()
640
                .filter(f -> f.getAttachment() > 0)
641
                .collect(Collectors.toMap(FullStockPayment::getId, FullStockPayment::getAttachment));
642
        for (AddWalletRequest r : walletRequests) {
643
            if (r.getFspId() > 0 && fspIdToAttachment.containsKey(r.getFspId())) {
644
                attachmentMap.put(r.getId(), fspIdToAttachment.get(r.getFspId()));
645
            }
646
        }
647
        return attachmentMap;
648
    }
649
 
650
    /**
651
     * Builds a map of UserWalletHistory.id -> FullStockPayment.attachment for ADVANCE_AMOUNT entries linked to FSP.
652
     */
653
    private Map<Integer, Integer> buildWalletHistoryAttachmentMap(List<UserWalletHistory> histories) {
654
        Map<Integer, Integer> attachmentMap = new HashMap<>();
655
        List<Integer> awrIds = histories.stream()
656
                .filter(h -> h.getReferenceType() == WalletReferenceType.ADVANCE_AMOUNT && h.getReference() > 0)
657
                .map(UserWalletHistory::getReference)
658
                .distinct()
659
                .collect(Collectors.toList());
660
        if (awrIds.isEmpty()) {
661
            return attachmentMap;
662
        }
663
        List<AddWalletRequest> awrList = addWalletRequestRepository.selectByIds(awrIds);
664
        Map<Integer, Integer> awrIdToFspId = awrList.stream()
665
                .filter(r -> r.getFspId() > 0)
666
                .collect(Collectors.toMap(AddWalletRequest::getId, AddWalletRequest::getFspId));
667
        List<Integer> fspIds = awrIdToFspId.values().stream().distinct().collect(Collectors.toList());
668
        if (fspIds.isEmpty()) {
669
            return attachmentMap;
670
        }
671
        List<FullStockPayment> fspList = fullStockPaymentRepository.selectByIds(fspIds);
672
        Map<Integer, Integer> fspIdToAttachment = fspList.stream()
673
                .filter(f -> f.getAttachment() > 0)
674
                .collect(Collectors.toMap(FullStockPayment::getId, FullStockPayment::getAttachment));
675
        for (UserWalletHistory h : histories) {
676
            if (h.getReferenceType() == WalletReferenceType.ADVANCE_AMOUNT && h.getReference() > 0) {
677
                Integer fspId = awrIdToFspId.get(h.getReference());
678
                if (fspId != null && fspIdToAttachment.containsKey(fspId)) {
679
                    attachmentMap.put(h.getId(), fspIdToAttachment.get(fspId));
680
                }
681
            }
682
        }
683
        return attachmentMap;
684
    }
685
 
32491 jai.hind 686
    @RequestMapping(value = "/getcreateUnsettledPayments", method = RequestMethod.GET)
32495 amit.gupta 687
    public String getcreateUnsettledPayment(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "15") int limit, Model model) throws Exception {
32491 jai.hind 688
        List<UnsettledPayment> up = null;
24089 tejbeer 689
 
32491 jai.hind 690
        long size = 0;
691
        up = unsettledPaymentsRepository.selectAllById(offset, limit);
24089 tejbeer 692
 
32491 jai.hind 693
        size = unsettledPaymentsRepository.selectAllCount();
694
        if (!up.isEmpty()) {
695
            model.addAttribute("unsettledPayment", up);
696
            model.addAttribute("start", offset + 1);
697
            model.addAttribute("size", size);
698
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 699
 
32491 jai.hind 700
            if (up.size() < limit) {
701
                model.addAttribute("end", offset + up.size());
702
            } else {
703
                model.addAttribute("end", offset + limit);
704
            }
705
        } else {
706
            model.addAttribute("unsettledPayment", up);
707
            model.addAttribute("size", size);
708
        }
24089 tejbeer 709
 
32491 jai.hind 710
        LOGGER.info("unsettledPaymentList" + up);
711
        return "unsettled-payments";
712
    }
24089 tejbeer 713
 
32491 jai.hind 714
    @RequestMapping(value = "/getUnsettledPaymentsByAmount", method = RequestMethod.GET)
32495 amit.gupta 715
    public String getUnsettledPaymentByAmount(HttpServletRequest request, @RequestParam(name = "amount", defaultValue = "0") float amount, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws Exception {
32491 jai.hind 716
        List<UnsettledPayment> up = null;
24089 tejbeer 717
 
32491 jai.hind 718
        long size = 0;
719
        up = unsettledPaymentsRepository.selectAllByAmount(amount, offset, limit);
24089 tejbeer 720
 
32491 jai.hind 721
        size = unsettledPaymentsRepository.selectAllCount();
722
        if (!up.isEmpty()) {
723
            model.addAttribute("unsettledPayment", up);
724
            model.addAttribute("start", offset + 1);
725
            model.addAttribute("size", size);
726
            model.addAttribute("url", "/getPaginatedUnsettledPayments");
24089 tejbeer 727
 
32491 jai.hind 728
            if (up.size() < limit) {
729
                model.addAttribute("end", offset + up.size());
730
            } else {
731
                model.addAttribute("end", offset + limit);
732
            }
733
            return "unsettle-payment-modal";
734
        } else {
735
            model.addAttribute("unsettledPayment", up);
736
            model.addAttribute("size", size);
737
        }
24089 tejbeer 738
 
32491 jai.hind 739
        return "unsettle-payment-modal";
740
    }
24089 tejbeer 741
 
32491 jai.hind 742
    @RequestMapping(value = "/createUnsettledPaymentsEntries", method = RequestMethod.POST)
32495 amit.gupta 743
    public String createUnsettledPaymentsEntries(HttpServletRequest request, @RequestBody UnsettledPaymentModel unsettledPaymentModel, Model model) throws Exception {
24089 tejbeer 744
 
32491 jai.hind 745
        UnsettledPayment up = new UnsettledPayment();
746
        up.setTransaction_reference(unsettledPaymentModel.getTransactionReference());
747
        up.setAmount(unsettledPaymentModel.getAmount());
748
        up.setDescription(unsettledPaymentModel.getDescription());
749
        up.setReference_date(unsettledPaymentModel.getReferenceDate());
750
        LOGGER.info("uppaynments" + up);
751
        unsettledPaymentsRepository.persist(up);
752
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
753
        return "response";
754
    }
24089 tejbeer 755
 
32491 jai.hind 756
    @RequestMapping(value = "/removeUnsettledPaymentsEntries", method = RequestMethod.DELETE)
32495 amit.gupta 757
    public String removeUnsettledPaymentsEntries(HttpServletRequest request, @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
24089 tejbeer 758
 
32491 jai.hind 759
        unsettledPaymentsRepository.deleteById(id);
24089 tejbeer 760
 
32491 jai.hind 761
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
762
        return "response";
763
    }
24509 amit.gupta 764
 
32491 jai.hind 765
    @RequestMapping(value = "/wallet/statement", method = RequestMethod.GET)
32495 amit.gupta 766
    public String getWalletStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
32491 jai.hind 767
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
34441 tejus.loha 768
        if (!isAdmin) {
769
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
770
        }
32491 jai.hind 771
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
772
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32495 amit.gupta 773
        List<UserWalletHistory> uwhList = walletService.getPaginatedUserWalletHistoryByRetailerId(fofoId, startDate, endDate, 0, 0);
32491 jai.hind 774
        Collections.reverse(uwhList);
775
        model.addAttribute("opening", openingBalance);
776
        model.addAttribute("closing", closingBalance);
777
        model.addAttribute("history", uwhList);
778
        model.addAttribute("startDate", startDate);
779
        model.addAttribute("endDate", endDate);
780
        return "walletStatement";
781
    }
29811 tejbeer 782
 
32491 jai.hind 783
    @RequestMapping(value = "/account/reco", method = RequestMethod.GET)
32495 amit.gupta 784
    public ResponseEntity<?> accountReco(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 785
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
786
        if (!isAdmin) {
787
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
788
        }
33207 amit.gupta 789
        LocalDateTime closingDateTime = closingDate.plusDays(1).atStartOfDay();
32491 jai.hind 790
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
791
        Set<Integer> retailersSet = customRetailerMap.keySet();
29070 amit.gupta 792
 
32491 jai.hind 793
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 794
 
32491 jai.hind 795
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 796
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 797
 
32491 jai.hind 798
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 799
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
32491 jai.hind 800
        Map<Integer, Float> closingWalletMap = userWalletHistoryRepository.getSumTillDate(closingDateTime, walletSet);
33212 amit.gupta 801
        Map<Integer, Float> peindingIndentMap = transactionService.getPendingIndentValueMap(closingDateTime, Optional.empty());
29811 tejbeer 802
 
32491 jai.hind 803
        List<List<?>> rows = new ArrayList<>();
804
        for (Map.Entry<Integer, Float> closingBalance : closingBalanceMap.entrySet()) {
805
            int walletId = closingBalance.getKey();
806
            int retailerId = walletRetailerMap.get(walletId);
29811 tejbeer 807
 
32491 jai.hind 808
            float accountClosing = 0f;
809
            if (!closingPurchaseMap.containsKey(retailerId)) {
810
                accountClosing = closingBalance.getValue();
811
            } else {
812
                accountClosing = closingBalance.getValue() - closingPurchaseMap.get(retailerId);
813
            }
29070 amit.gupta 814
 
32491 jai.hind 815
            CustomRetailer cr = customRetailerMap.get(retailerId);
29070 amit.gupta 816
 
32495 amit.gupta 817
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), accountClosing, closingWalletMap.get(walletId), peindingIndentMap.get(retailerId)));
32491 jai.hind 818
        }
29070 amit.gupta 819
 
32495 amit.gupta 820
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance", "Closing Wallet", "In Transit"), rows);
32491 jai.hind 821
        final HttpHeaders headers = new HttpHeaders();
822
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 823
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 824
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
29070 amit.gupta 825
 
32491 jai.hind 826
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
827
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
828
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
829
    }
29811 tejbeer 830
 
32491 jai.hind 831
    @RequestMapping(value = "/account/closing-statements", method = RequestMethod.GET)
32495 amit.gupta 832
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDate closingDate, Model model) throws Exception {
32491 jai.hind 833
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
834
        if (!isAdmin) {
835
            throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
836
        }
837
        LocalDateTime closingDateTime = closingDate.atStartOfDay().plusDays(1);
28597 amit.gupta 838
 
32491 jai.hind 839
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
840
        Set<Integer> retailersSet = customRetailerMap.keySet();
28597 amit.gupta 841
 
32491 jai.hind 842
        Map<Integer, Float> closingPurchaseMap = orderRepository.selectOpeningAmount(closingDateTime, retailersSet);
29811 tejbeer 843
 
32491 jai.hind 844
        Map<Integer, UserWallet> retailerWalletMap = walletService.getRetailerIdUserWalletMap(retailersSet);
32495 amit.gupta 845
        Map<Integer, Integer> walletRetailerMap = retailerWalletMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getKey()));
29811 tejbeer 846
 
32491 jai.hind 847
        Set<Integer> walletSet = walletRetailerMap.keySet();
32495 amit.gupta 848
        Map<Integer, Float> closingBalanceMap = userWalletHistoryRepository.getSumTillDateExcludingPurchase(closingDateTime, walletSet);
28597 amit.gupta 849
 
32491 jai.hind 850
        List<List<?>> rows = new ArrayList<>();
851
        for (Map.Entry<Integer, Float> closingWalletBalance : closingBalanceMap.entrySet()) {
852
            int walletId = closingWalletBalance.getKey();
853
            int retailerId = walletRetailerMap.get(walletId);
854
            if (!closingPurchaseMap.containsKey(retailerId)) {
855
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue());
856
            } else {
32495 amit.gupta 857
                closingPurchaseMap.put(retailerId, closingWalletBalance.getValue() - closingPurchaseMap.get(retailerId));
32491 jai.hind 858
            }
859
            float closingValue = closingPurchaseMap.get(retailerId);
860
            CustomRetailer cr = customRetailerMap.get(retailerId);
28597 amit.gupta 861
 
32495 amit.gupta 862
            rows.add(Arrays.asList(retailerId, cr.getBusinessName(), cr.getAddress().getCity(), cr.getAddress().getState(), closingValue));
32491 jai.hind 863
        }
28597 amit.gupta 864
 
32495 amit.gupta 865
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil.getCSVByteStream(Arrays.asList("Id", "Partner Name", "City", "State", "Closing Balance"), rows);
32491 jai.hind 866
        final HttpHeaders headers = new HttpHeaders();
867
        headers.set("Content-Type", "text/csv");
32495 amit.gupta 868
        headers.set("Content-disposition", "inline; filename=account-statement-closing-." + StringUtils.toHyphenatedString(closingDate) + ".csv");
32491 jai.hind 869
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28597 amit.gupta 870
 
32491 jai.hind 871
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
872
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28597 amit.gupta 873
 
32491 jai.hind 874
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28597 amit.gupta 875
 
32491 jai.hind 876
    }
28515 amit.gupta 877
 
32491 jai.hind 878
    @RequestMapping(value = "/account/statement", method = RequestMethod.GET)
32495 amit.gupta 879
    public ResponseEntity<?> getAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
34440 amit.gupta 880
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
881
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
882
        if (!isAdmin) {
883
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
884
        }
33212 amit.gupta 885
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
886
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
32491 jai.hind 887
        UserWallet uw = walletService.getUserWallet(fofoId);
33220 amit.gupta 888
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
32495 amit.gupta 889
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
33220 amit.gupta 890
        //LOGGER.info("Data - {}", history.stream().filter(x -> x.getReferenceType().equals(WalletReferenceType.OTHERS)).collect(Collectors.groupingBy(x -> x.getBusinessTimestamp().toLocalDate())));
36754 amit 891
        // Body shows genuine money movements. Exclude: PURCHASE (rebuilt via billing); the loan cash legs
892
        // CREDIT_LIMIT/CREDIT_UTILIZED (represented by the Interest Accrued line + opening/closing loan); and the
893
        // scheme set CN_WALLET_REFERENCES (shown instead as the month-end MARGINS credit-note line).
33205 amit.gupta 894
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
36754 amit 895
                .filter(x -> !x.getReferenceType().equals(WalletReferenceType.CREDIT_LIMIT))
896
                .filter(x -> !x.getReferenceType().equals(WalletReferenceType.CREDIT_UTILIZED))
897
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType()))
898
                .sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
33205 amit.gupta 899
 
32491 jai.hind 900
        InputStream is = getClass().getClassLoader().getResourceAsStream("account-statement.xlsx");
33205 amit.gupta 901
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
33225 amit.gupta 902
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
36754 amit 903
        List<StatementDetailModel> returnDetails = returnOrderInfoRepository.selectReturnsBetween(fofoId, startDate, endDate);
33212 amit.gupta 904
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
905
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
28515 amit.gupta 906
 
33212 amit.gupta 907
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
908
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
36754 amit 909
        float openingLoan = loanStatementRepository.getLoanPrincipalAtDate(fofoId, startDate) + loanStatementRepository.getLoanInterestAtDate(fofoId, startDate);
910
        float closingLoan = loanStatementRepository.getLoanPrincipalAtDate(fofoId, endDate) + loanStatementRepository.getLoanInterestAtDate(fofoId, endDate);
911
        float interestAccruedCost = loanStatementRepository.getInterestAccruedBetween(fofoId, startDate, endDate);
912
        LOGGER.info("OpeningPI - {}, ClosingPI - {}, OpeningLoan - {}, ClosingLoan - {}, InterestAccrued - {}", openingPendingAmount, closingPendingAmount, openingLoan, closingLoan, interestAccruedCost);
913
        ByteArrayOutputStream byteArrayOutputStream = this.populateData(is, openingBalance + openingPendingAmount - openingLoan, closingBalance + closingPendingAmount - closingLoan,
914
                customRetailer, history, startDate, endDate, billedStatementDetails, returnDetails, interestAccruedCost);
33212 amit.gupta 915
 
32491 jai.hind 916
        final HttpHeaders headers = new HttpHeaders();
917
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
32495 amit.gupta 918
        headers.set("Content-disposition", "inline; filename=account-statement." + StringUtils.toHyphenatedString(startDate.toLocalDate()) + "-" + StringUtils.toHyphenatedString(endDate.toLocalDate()) + ".xlsx");
32491 jai.hind 919
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
28515 amit.gupta 920
 
32491 jai.hind 921
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
922
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28515 amit.gupta 923
 
32491 jai.hind 924
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28515 amit.gupta 925
 
32491 jai.hind 926
    }
28597 amit.gupta 927
 
33205 amit.gupta 928
    @Autowired
929
    CreditNoteRepository creditNoteRepository;
930
    @Autowired
931
    CreditNoteLineRepository creditNoteLineRepository;
932
 
36754 amit 933
    // Friendly category for a statement line, keyed on the wallet reference-type or billing sub-type string.
934
    private String statementCategory(String type) {
935
        if (type == null) return "Other";
936
        switch (type) {
937
            case "ADVANCE_AMOUNT": case "AUTOMATED_ADVANCE": return "Advance / Payment";
938
            case "PAYMENT_GATEWAY": case "RECHARGE": return "Payment";
939
            case "SCHEME_IN": case "SCHEME_OUT": case "ADDITIONAL_SCHEME": case "ACTIVATION_SCHEME": return "Scheme / Margin";
940
            case "CREDIT_LIMIT": case "CREDIT_UTILIZED": return "SD Credit (Loan)";
941
            case "PURCHASE": return "Purchase / Order Refund";
942
            case "REFUND": return "Refund";
943
            case "PRICE_DROP": return "Price Drop";
944
            case "BRAND_PAYOUT": case "INVESTMENT_PAYOUT": return "Payout";
945
            case "SPECIAL_SUPPORT": return "Special Support";
946
            case "DAMAGE_PROTECTION": return "Damage Protection";
947
            case "PREBOOKING_ORDER": return "Prebooking Order";
948
            // billing sub-types from selectDetailsBetween
949
            case "BILLED": return "Billing / Invoice";
950
            case "RTO": return "Cancellation (RTO)";
951
            case "RETURNED": return "Return";
952
            case "INVOICE_CANCELLED": return "Invoice Cancelled";
953
            case "RETURNS_CN": return "Return (Credit Note)";
954
            default: return "Other";
955
        }
956
    }
957
 
33205 amit.gupta 958
    private ByteArrayOutputStream populateData(InputStream is, float openingBalance, float closingBalance, CustomRetailer customRetailer, List<UserWalletHistory> history,
36754 amit 959
                                               LocalDateTime startLocalDateTime, LocalDateTime endLocalDateTime, List<StatementDetailModel> invoiceDetails,
960
                                               List<StatementDetailModel> returnDetails, float interestAccruedCost) throws Exception {
33205 amit.gupta 961
        Map<LocalDate, List<StatementDetailModel>> dateInvoiceMap = invoiceDetails.stream().collect(Collectors.groupingBy(x -> x.getOnDate().toLocalDate()));
36754 amit 962
        Map<LocalDate, List<StatementDetailModel>> dateReturnMap = returnDetails == null ? new HashMap<>()
963
                : returnDetails.stream().collect(Collectors.groupingBy(x -> x.getOnDate().toLocalDate()));
33220 amit.gupta 964
        //LOGGER.info("dateInvoiceMap - {}", dateInvoiceMap);
965
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
32491 jai.hind 966
        XSSFWorkbook workbook = new XSSFWorkbook(is);
967
        CreationHelper creationHelper = workbook.getCreationHelper();
33226 amit.gupta 968
        CellStyle dateStyle = workbook.createCellStyle();
969
        dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dd/mm/yyyy"));
28597 amit.gupta 970
 
32491 jai.hind 971
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
972
        Sheet sheet = workbook.getSheetAt(0);
33205 amit.gupta 973
        sheet.getRow(0).getCell(0).setCellValue(customRetailer.getBusinessName());
974
        sheet.getRow(1).getCell(1).setCellValue(new Date(startLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
975
        sheet.getRow(1).getCell(2).setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
32491 jai.hind 976
        sheet.getRow(2).getCell(2).setCellValue(openingBalance);
977
        long grandTotalDebit = 0l;
978
        long grandTotalCredit = 0l;
979
        int row = 4;
33212 amit.gupta 980
        LocalDate startDate = startLocalDateTime.toLocalDate();
33205 amit.gupta 981
        LocalDate endDate = endLocalDateTime.toLocalDate();
33220 amit.gupta 982
        LOGGER.info(" startDate - {}", startDate);
983
        LOGGER.info(" endDate - {}", endDate);
33226 amit.gupta 984
        double currentOpening = openingBalance;
33212 amit.gupta 985
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
986
            List<UserWalletHistory> datewiseWalletHistory = dateWalletMap.get(date);
33220 amit.gupta 987
            LOGGER.info("date - {}, datewiseWalletHistory - {}", date, datewiseWalletHistory);
33212 amit.gupta 988
            if (datewiseWalletHistory != null) {
989
                for (UserWalletHistory walletEntry : datewiseWalletHistory) {
990
                    Cell dateCell = sheet.createRow(row).createCell(0);
33226 amit.gupta 991
                    //Date
33212 amit.gupta 992
                    dateCell.setCellValue(new Date(walletEntry.getTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 993
                    dateCell.setCellStyle(dateStyle);
994
                    //TransactType
33212 amit.gupta 995
                    sheet.getRow(row).createCell(1).setCellValue(walletEntry.getReferenceType().toString());
33226 amit.gupta 996
                    //Reference Id
33227 amit.gupta 997
                    sheet.getRow(row).createCell(2).setCellValue(walletEntry.getReference());
33212 amit.gupta 998
                    if (walletEntry.getAmount() > 0) {
33226 amit.gupta 999
                        //Debit
33227 amit.gupta 1000
                        sheet.getRow(row).createCell(3).setCellValue(0);
33226 amit.gupta 1001
                        //Credit
33227 amit.gupta 1002
                        sheet.getRow(row).createCell(4).setCellValue(walletEntry.getAmount());
33212 amit.gupta 1003
                        grandTotalCredit += walletEntry.getAmount();
1004
                    } else {
33227 amit.gupta 1005
                        sheet.getRow(row).createCell(3).setCellValue(-walletEntry.getAmount());
1006
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 1007
                        grandTotalDebit -= walletEntry.getAmount();
1008
                    }
33226 amit.gupta 1009
                    //Running balance
1010
                    currentOpening += walletEntry.getAmount();
33227 amit.gupta 1011
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
36754 amit 1012
                    //Category + Description
1013
                    String wCategory = statementCategory(walletEntry.getReferenceType().toString());
1014
                    String wDesc = walletEntry.getDescription();
1015
                    sheet.getRow(row).createCell(6).setCellValue(wDesc == null || wDesc.isEmpty() ? wCategory : wCategory + " — " + wDesc);
33212 amit.gupta 1016
                    row++;
1017
                }
1018
            }
1019
            List<StatementDetailModel> statementDetailModels = dateInvoiceMap.get(date);
1020
            LOGGER.info("statementDetailModels - {}", statementDetailModels);
1021
            if (statementDetailModels != null) {
1022
                for (StatementDetailModel statementDetailModel : statementDetailModels) {
36754 amit 1023
                    // Returns are shown individually from returnorderinfo below; skip the billing query's aggregated
1024
                    // RETURNED and the RETURNS_CN (returns are not taken from credit notes).
1025
                    if ("RETURNED".equals(statementDetailModel.getReferenceType())
1026
                            || "RETURNS_CN".equals(statementDetailModel.getReferenceType())) {
1027
                        continue;
1028
                    }
33212 amit.gupta 1029
                    Cell dateCell = sheet.createRow(row).createCell(0);
1030
                    dateCell.setCellValue(statementDetailModel.getOnDate());
33226 amit.gupta 1031
                    dateCell.setCellStyle(dateStyle);
1032
                    //Transact Type
33212 amit.gupta 1033
                    sheet.getRow(row).createCell(1).setCellValue("BILLING");
33226 amit.gupta 1034
                    //Transact Reference
33227 amit.gupta 1035
                    sheet.getRow(row).createCell(2).setCellValue(statementDetailModel.getInvoiceNumber());
33212 amit.gupta 1036
                    if (statementDetailModel.getAmount() > 0) {
33227 amit.gupta 1037
                        sheet.getRow(row).createCell(3).setCellValue(statementDetailModel.getAmount());
1038
                        sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 1039
                        grandTotalDebit += statementDetailModel.getAmount();
1040
                    } else {
33227 amit.gupta 1041
                        sheet.getRow(row).createCell(3).setCellValue(0);
1042
                        sheet.getRow(row).createCell(4).setCellValue(-statementDetailModel.getAmount());
33212 amit.gupta 1043
                        grandTotalCredit += -statementDetailModel.getAmount();
1044
                    }
33226 amit.gupta 1045
                    //Running Balance
33229 amit.gupta 1046
                    currentOpening -= statementDetailModel.getAmount();
33228 amit.gupta 1047
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
33212 amit.gupta 1048
 
33226 amit.gupta 1049
 
36754 amit 1050
                    //Category (Narration)
1051
                    sheet.getRow(row).createCell(6).setCellValue(statementCategory(statementDetailModel.getReferenceType()) + " (" + statementDetailModel.getReferenceType() + ")");
33212 amit.gupta 1052
 
1053
                    row += 1;
1054
                }
1055
            }
36754 amit 1056
            // Individual returns (returnorderinfo): one credit line per return, against its invoice, on refundedAt.
1057
            List<StatementDetailModel> dateReturns = dateReturnMap.get(date);
1058
            if (dateReturns != null) {
1059
                for (StatementDetailModel ret : dateReturns) {
1060
                    Cell dateCell = sheet.createRow(row).createCell(0);
1061
                    dateCell.setCellValue(ret.getOnDate());
1062
                    dateCell.setCellStyle(dateStyle);
1063
                    sheet.getRow(row).createCell(1).setCellValue("RETURN");
1064
                    sheet.getRow(row).createCell(2).setCellValue(ret.getInvoiceNumber());
1065
                    sheet.getRow(row).createCell(3).setCellValue(0);
1066
                    sheet.getRow(row).createCell(4).setCellValue(ret.getAmount());
1067
                    grandTotalCredit += ret.getAmount();
1068
                    currentOpening += ret.getAmount();
1069
                    sheet.getRow(row).createCell(5).setCellValue(currentOpening);
1070
                    sheet.getRow(row).createCell(6).setCellValue("Return (Against Invoice " + ret.getInvoiceNumber() + ")");
1071
                    row += 1;
1072
                }
1073
            }
1074
            // Month-end credit notes (shown before the interest line): all CN types EXCEPT RETURNS (returns come from
1075
            // returnorderinfo via the billing query). MARGINS = scheme/margin credit; CN_CANCELLATION = debit (reverses a
1076
            // MARGINS CN). Any CN→raw-scheme or cross-period timing difference lands in the reconciling diff line below.
33212 amit.gupta 1077
            if (YearMonth.from(date).atEndOfMonth().equals(date)) {
1078
                List<CreditNote> creditNotes = creditNoteRepository.selectAll(customRetailer.getPartnerId(), YearMonth.from(date));
1079
                if (creditNotes != null) {
1080
                    for (CreditNote creditNote : creditNotes) {
36754 amit 1081
                        // RETURNS are sourced from returnorderinfo (billing query), not from the CN; skip them here.
1082
                        if (creditNote.getType() == CreditNoteType.RETURNS) {
1083
                            continue;
1084
                        }
33212 amit.gupta 1085
                        double cnAmount = creditNoteLineRepository.selectAllByCreditNote(creditNote.getId()).stream().collect(Collectors.summingDouble(x -> x.getAmount()));
36754 amit 1086
                        // CN_CANCELLATION reverses a previously-issued MARGINS credit note; line amount is stored positive but must debit.
1087
                        if (creditNote.getType() == CreditNoteType.CN_CANCELLATION) {
1088
                            cnAmount = -cnAmount;
1089
                        }
33205 amit.gupta 1090
                        Cell dateCell = sheet.createRow(row).createCell(0);
33212 amit.gupta 1091
                        dateCell.setCellValue(new Date(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
33226 amit.gupta 1092
                        dateCell.setCellStyle(dateStyle);
36754 amit 1093
                        // Net -ve (e.g. negative net margin, or a cancellation) is a debit note.
1094
                        sheet.getRow(row).createCell(1).setCellValue(cnAmount >= 0 ? "CREDIT NOTE" : "DEBIT NOTE");
33227 amit.gupta 1095
                        sheet.getRow(row).createCell(2).setCellValue(creditNote.getCreditNoteNumber());
33212 amit.gupta 1096
                        if (cnAmount > 0) {
33227 amit.gupta 1097
                            sheet.getRow(row).createCell(3).setCellValue(0);
1098
                            sheet.getRow(row).createCell(4).setCellValue(cnAmount);
33212 amit.gupta 1099
                            grandTotalCredit += cnAmount;
1100
                        } else {
33227 amit.gupta 1101
                            sheet.getRow(row).createCell(3).setCellValue(-cnAmount);
1102
                            sheet.getRow(row).createCell(4).setCellValue(0);
33212 amit.gupta 1103
                            grandTotalDebit += -cnAmount;
33205 amit.gupta 1104
                        }
33226 amit.gupta 1105
                        currentOpening += cnAmount;
33227 amit.gupta 1106
                        sheet.getRow(row).createCell(5).setCellValue(currentOpening);
36754 amit 1107
                        sheet.getRow(row).createCell(6).setCellValue(creditNote.getType() == CreditNoteType.CN_CANCELLATION
1108
                                ? "Margin Cancellation" : "Scheme / Margin");
33205 amit.gupta 1109
                        row += 1;
1110
                    }
1111
                }
1112
            }
32491 jai.hind 1113
        }
33205 amit.gupta 1114
 
36754 amit 1115
        // --- Reconciling lines at period end ---
1116
        // Interest accrued (charged, non-cash) is the only standing-moving loan piece. Principal movement and interest
1117
        // PAID are funded by wallet cash (the excluded CREDIT_LIMIT/CREDIT_UTILIZED legs) and net to ~0, so they are not
1118
        // shown as balance lines. Accrued interest is a debit (the partner's liability grows).
1119
        if (Math.abs(interestAccruedCost) > 0.01f) {
1120
            Cell dateCell = sheet.createRow(row).createCell(0);
1121
            dateCell.setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
1122
            dateCell.setCellStyle(dateStyle);
1123
            sheet.getRow(row).createCell(1).setCellValue("INTEREST ACCRUED");
1124
            sheet.getRow(row).createCell(2).setCellValue("");
1125
            sheet.getRow(row).createCell(3).setCellValue(interestAccruedCost);
1126
            sheet.getRow(row).createCell(4).setCellValue(0);
1127
            grandTotalDebit += (long) interestAccruedCost;
1128
            currentOpening -= interestAccruedCost;
1129
            sheet.getRow(row).createCell(5).setCellValue(currentOpening);
1130
            sheet.getRow(row).createCell(6).setCellValue("SD Credit — Interest accrued (financing cost)");
1131
            row++;
1132
        }
36755 amit 1133
        // Float-difference line: lands the running balance exactly on the formula closing. With clean data this is only
1134
        // a few rupees of rounding/float; a large value signals a data issue (e.g. MARGINS CN not yet rolled out) and is
1135
        // surfaced by the reconciliation warning below rather than being a real ledger movement.
1136
        double floatDiff = closingBalance - currentOpening;
1137
        if (Math.abs(floatDiff) > 0.01) {
36754 amit 1138
            Cell dateCell = sheet.createRow(row).createCell(0);
1139
            dateCell.setCellValue(new Date(endLocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
1140
            dateCell.setCellStyle(dateStyle);
36755 amit 1141
            sheet.getRow(row).createCell(1).setCellValue("FLOAT DIFF");
36754 amit 1142
            sheet.getRow(row).createCell(2).setCellValue("");
36755 amit 1143
            if (floatDiff > 0) {
36754 amit 1144
                sheet.getRow(row).createCell(3).setCellValue(0);
36755 amit 1145
                sheet.getRow(row).createCell(4).setCellValue(floatDiff);
1146
                grandTotalCredit += (long) floatDiff;
36754 amit 1147
            } else {
36755 amit 1148
                sheet.getRow(row).createCell(3).setCellValue(-floatDiff);
36754 amit 1149
                sheet.getRow(row).createCell(4).setCellValue(0);
36755 amit 1150
                grandTotalDebit += (long) -floatDiff;
36754 amit 1151
            }
36755 amit 1152
            currentOpening += floatDiff;
36754 amit 1153
            sheet.getRow(row).createCell(5).setCellValue(currentOpening);
36755 amit 1154
            sheet.getRow(row).createCell(6).setCellValue("Rounding / float difference");
36754 amit 1155
            row++;
1156
        }
1157
 
33238 amit.gupta 1158
        sheet.createRow(row).createCell(2).setCellValue("Grand Total");
1159
        sheet.getRow(row).createCell(3).setCellValue(grandTotalDebit);
1160
        sheet.getRow(row).createCell(4).setCellValue(grandTotalCredit);
36754 amit 1161
        row += 2;
32491 jai.hind 1162
        sheet.createRow(row).createCell(0).setCellValue("Closing Balance");
36754 amit 1163
        sheet.getRow(row).createCell(5).setCellValue(closingBalance);
32491 jai.hind 1164
        row++;
36754 amit 1165
        double diff = Math.abs(currentOpening - closingBalance);
1166
        if (diff > 1) {
1167
            LOGGER.warn("Account statement reconciliation mismatch for {}: computed={}, expected={}, diff={}",
1168
                    customRetailer.getPartnerId(), currentOpening, closingBalance, diff);
1169
        }
32491 jai.hind 1170
        try {
1171
            workbook.write(bos);
1172
        } finally {
1173
            workbook.close();
1174
            bos.close();
1175
        }
28515 amit.gupta 1176
 
32491 jai.hind 1177
        return bos;
1178
    }
24876 tejbeer 1179
 
32491 jai.hind 1180
    @RequestMapping(value = "/manualPayment", method = RequestMethod.GET)
1181
    public String ManualPayment(HttpServletRequest request, Model model) throws Exception {
1182
        model.addAttribute("referenceTypes", WalletReferenceType.referenceType);
1183
        model.addAttribute("transactionTypes", TransactionType.values());
1184
        return "wallet-edit";
24876 tejbeer 1185
 
32491 jai.hind 1186
    }
24876 tejbeer 1187
 
32491 jai.hind 1188
    @RequestMapping(value = "/getWalletHistory", method = RequestMethod.GET)
32495 amit.gupta 1189
    public String getWalletHistory(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
25018 tejbeer 1190
 
32491 jai.hind 1191
        LOGGER.info("type" + referenceType);
32495 amit.gupta 1192
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
25018 tejbeer 1193
 
32491 jai.hind 1194
        if (userWalletHistory.isEmpty()) {
1195
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1196
        }
25018 tejbeer 1197
 
32491 jai.hind 1198
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
25018 tejbeer 1199
 
32491 jai.hind 1200
        LOGGER.info("userWallet" + userWallet);
1201
        CustomRetailer customretailer = retailerService.getFofoRetailer(userWallet.getUserId());
25018 tejbeer 1202
 
32491 jai.hind 1203
        model.addAttribute("userWallet", userWallet);
1204
        model.addAttribute("customretailer", customretailer);
24876 tejbeer 1205
 
32491 jai.hind 1206
        model.addAttribute("wallethistory", userWalletHistory);
1207
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1208
        return "wallet-history";
25018 tejbeer 1209
 
32491 jai.hind 1210
    }
25018 tejbeer 1211
 
32491 jai.hind 1212
    @RequestMapping(value = "/getWalletHistoryByPartner", method = RequestMethod.GET)
32512 amit.gupta 1213
    public String getWalletHistoryByPartner(HttpServletRequest request, int fofoId, @RequestParam(name = "referenceType", required = false) WalletReferenceType referenceType, @RequestParam(name = "offset", required = false, defaultValue = "0") int offset, @RequestParam(name = "limit", required = false, defaultValue = "100") int limit, Model model) throws Exception {
25018 tejbeer 1214
 
32491 jai.hind 1215
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
32495 amit.gupta 1216
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectPaginatedByWalletIdReferenceType(userWallet.getId(), referenceType, SortOrder.DESCENDING, offset, limit);
25018 tejbeer 1217
 
32491 jai.hind 1218
        CustomRetailer customretailer = retailerService.getFofoRetailer(fofoId);
25018 tejbeer 1219
 
32491 jai.hind 1220
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
32597 amit.gupta 1221
 
1222
        List<Loan> loans = null;
1223
        BigDecimal totalDue = BigDecimal.ZERO;
1224
        BigDecimal availableLimit = BigDecimal.ZERO;
1225
        BigDecimal creditlimit = BigDecimal.ZERO;
32598 amit.gupta 1226
        if (sdCreditRequirement != null) {
32597 amit.gupta 1227
            loans = loanRepository.selectActiveLoan(fofoId);
1228
            availableLimit = sdCreditRequirement.getAvailableLimit();
1229
            creditlimit = sdCreditRequirement.getLimit();
1230
            for (Loan loan : loans) {
1231
                BigDecimal pendingAmount = loan.getPendingAmount();
1232
                BigDecimal interestAccrued = loan.getInterestAccrued();
1233
                BigDecimal interestPaid = loan.getInterestPaid();
1234
                totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));
1235
                availableLimit = creditlimit.subtract(totalDue);
1236
            }
32491 jai.hind 1237
        }
1238
        model.addAttribute("userWallet", userWallet);
1239
        model.addAttribute("customretailer", customretailer);
1240
        model.addAttribute("wallethistory", userWalletHistory);
1241
        model.addAttribute("loans", loans);
1242
        model.addAttribute("totalDue", totalDue);
1243
        model.addAttribute("availableLimit", availableLimit);
1244
        model.addAttribute("creditlimit", creditlimit);
1245
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1246
        return "wallet-history";
1247
    }
30426 tejbeer 1248
 
24876 tejbeer 1249
 
32491 jai.hind 1250
    @RequestMapping(value = "/getPartnerName", method = RequestMethod.GET)
32495 amit.gupta 1251
    public String getPartnerName(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam WalletReferenceType referenceType, Model model) throws Exception {
24905 amit.gupta 1252
 
32495 amit.gupta 1253
        List<UserWalletHistory> userWalletHistory = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1254
        if (userWalletHistory.isEmpty()) {
1255
            throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id not found");
1256
        }
1257
        UserWallet userWallet = userWalletRepository.selectById(userWalletHistory.get(0).getWalletId());
24905 amit.gupta 1258
 
32491 jai.hind 1259
        CustomRetailer retailer = retailerService.getFofoRetailer(userWallet.getUserId());
24905 amit.gupta 1260
 
32491 jai.hind 1261
        model.addAttribute("response1", mvcResponseSender.createResponseString(retailer));
24876 tejbeer 1262
 
32491 jai.hind 1263
        return "response";
24876 tejbeer 1264
 
32491 jai.hind 1265
    }
30677 amit.gupta 1266
 
32491 jai.hind 1267
    @RequestMapping(value = "/reset-wallet/9990381", method = RequestMethod.GET)
1268
    public String walletUpdate(Model model) throws Exception {
1269
        walletService.resetWallet();
1270
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1271
        return "response";
1272
    }
24876 tejbeer 1273
 
32491 jai.hind 1274
    @RequestMapping(value = "/walletUpdate", method = RequestMethod.POST)
32495 amit.gupta 1275
    public String walletUpdate(HttpServletRequest request, @RequestParam(name = "reference", defaultValue = "0") int reference, @RequestParam int referenceTypeValue, @RequestParam TransactionType transactiontype, @RequestParam int amount, @RequestParam String description, @RequestParam int retailerId, Model model, @RequestParam LocalDateTime businessTimestamp) throws Exception {
32491 jai.hind 1276
        WalletReferenceType referenceType = WalletReferenceType.findByValue(referenceTypeValue);
1277
        if (reference == 0 && referenceType.getValue() >= WalletReferenceType.INCENTIVES.getValue()) {
1278
            LOGGER.error("referenceType: " + referenceType);
1279
            ManualPaymentType paymentType = manualPaymentRequestRepository.selectByReferenceType(referenceType);
28515 amit.gupta 1280
 
32491 jai.hind 1281
            if (paymentType == null) {
1282
                paymentType = new ManualPaymentType();
1283
                paymentType.setReferenceType(referenceType);
1284
            }
1285
            paymentType.setCounter(paymentType.getCounter() + 1);
1286
            manualPaymentRequestRepository.persist(paymentType);
1287
            reference = paymentType.getCounter();
28515 amit.gupta 1288
 
32491 jai.hind 1289
        } else if (reference == 0) {
32495 amit.gupta 1290
            throw new ProfitMandiBusinessException("RefrenceId", reference, "System specific reference type cant be used manually");
32491 jai.hind 1291
        }
24876 tejbeer 1292
 
32495 amit.gupta 1293
        List<UserWalletHistory> userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reference, referenceType);
32491 jai.hind 1294
        UserWallet userWallet = userWalletRepository.selectByRetailerId(retailerId);
1295
        int walletId = userWallet.getId();
1296
        int walletAmount = walletService.getWalletAmount(retailerId);
24876 tejbeer 1297
 
32491 jai.hind 1298
        int returnReference = 0;
1299
        UserWalletHistory newUserWalletHistory = new UserWalletHistory();
28515 amit.gupta 1300
 
32491 jai.hind 1301
        if (!userWalletHistoryList.isEmpty()) {
1302
            long validRetailerEntries = userWalletHistoryList.stream().filter(x -> x.getWalletId() == walletId).count();
1303
            if (validRetailerEntries == 0) {
32495 amit.gupta 1304
                throw new ProfitMandiBusinessException("RefrenceId", reference, "Reference Id assign to Other  partner");
32491 jai.hind 1305
            }
1306
        }
28515 amit.gupta 1307
 
32491 jai.hind 1308
        if (TransactionType.DEBIT.equals(transactiontype)) {
1309
            amount = -amount;
1310
        }
26485 amit.gupta 1311
 
32491 jai.hind 1312
        userWallet.setAmount(walletAmount + amount);
1313
        newUserWalletHistory.setAmount(amount);
1314
        newUserWalletHistory.setBusinessTimestamp(businessTimestamp);
1315
        newUserWalletHistory.setDescription(description);
1316
        newUserWalletHistory.setReference(reference);
1317
        newUserWalletHistory.setWalletId(userWallet.getId());
1318
        newUserWalletHistory.setReferenceType(referenceType);
1319
        newUserWalletHistory.setTimestamp(LocalDateTime.now());
36513 amit 1320
        newUserWalletHistory.setRunningBalance(userWallet.getAmount());
32491 jai.hind 1321
        userWalletHistoryRepository.persist(newUserWalletHistory);
24876 tejbeer 1322
 
32491 jai.hind 1323
        model.addAttribute("response1", mvcResponseSender.createResponseString(reference));
1324
        return "response";
25018 tejbeer 1325
 
32491 jai.hind 1326
    }
25018 tejbeer 1327
 
32491 jai.hind 1328
    @RequestMapping(value = "/addMoney", method = RequestMethod.POST)
32495 amit.gupta 1329
    public String addMoney(HttpServletRequest request, @RequestParam float amount, @RequestParam String transactionReference, @RequestParam LocalDateTime referenceTime, @RequestParam String bankName, @RequestParam int fofoId, Model model) throws Exception {
33175 amit.gupta 1330
        transactionReference = transactionReference.toUpperCase().trim();
1331
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectByReference(transactionReference);
34096 aman.kumar 1332
        addWalletRequests = addWalletRequests.stream().filter(x -> Arrays.asList(approved, AddWalletRequestStatus.pending).contains(x.getStatus())).collect(Collectors.toList());
33175 amit.gupta 1333
        if (addWalletRequests.size() > 0) {
1334
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1335
        }
1336
        HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(transactionReference);
33205 amit.gupta 1337
        if (hdfcPayment != null) {
33175 amit.gupta 1338
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
1339
        }
32491 jai.hind 1340
        AddWalletRequest addWalletRequest = new AddWalletRequest();
1341
        addWalletRequest.setRetailerId(fofoId);
1342
        addWalletRequest.setAmount(amount);
33175 amit.gupta 1343
        addWalletRequest.setTransaction_reference(transactionReference.toUpperCase());
32491 jai.hind 1344
        addWalletRequest.setCreateTimestamp(LocalDateTime.now());
1345
        addWalletRequest.setBank_name(bankName);
1346
        addWalletRequest.setReference_date(referenceTime.toLocalDate());
1347
        addWalletRequest.setStatus(AddWalletRequestStatus.pending);
25018 tejbeer 1348
 
32491 jai.hind 1349
        LOGGER.info("info" + addWalletRequest);
29811 tejbeer 1350
 
32491 jai.hind 1351
        addWalletRequestRepository.persist(addWalletRequest);
1352
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1353
        return "response";
1354
    }
29811 tejbeer 1355
 
33045 amit.gupta 1356
    List<Gateway> directGateways = Arrays.asList(Gateway.SDDIRECT, Gateway.SIDBI);
1357
 
1358
    @Autowired
1359
    FofoSidbiSanctionRepository fofoSidbiSanctionRepository;
33175 amit.gupta 1360
 
32491 jai.hind 1361
    @RequestMapping(value = "/getCreditDetail", method = RequestMethod.GET)
1362
    public String getCreditDetail(HttpServletRequest request, Model model) throws Exception {
33175 amit.gupta 1363
        List<CreditAccount> creditAccounts = creditAccountRepository.selectAll().stream().filter(x -> directGateways.contains(x.getGateway())).collect(Collectors.toList());
32491 jai.hind 1364
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29962 tejbeer 1365
 
33420 amit.gupta 1366
        List<Integer> fofoIds = creditAccounts.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
33045 amit.gupta 1367
        //Need to maintain valid upto
33175 amit.gupta 1368
        Map<Integer, FofoSidbiSanction> fofoSidbiPendingSanctionsMap = fofoSidbiSanctionRepository.selectAll(Optional.of(false)).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
29811 tejbeer 1369
 
33420 amit.gupta 1370
        Map<Integer, Integer> partnerAverageCreditDaysMap = new HashMap<>();
33045 amit.gupta 1371
 
33420 amit.gupta 1372
        List<Loan> loans = loanRepository.selectAllLoans(fofoIds, DateRangeModel.withStartDate(LocalDate.now().atStartOfDay().minusYears(2)));
1373
        Map<Integer, List<Loan>> partnerClosedLoansMap = loans.stream().filter(x -> x.getPendingAmount().compareTo(BigDecimal.ZERO) == 0)
1374
                .collect(Collectors.groupingBy(x -> x.getFofoId()));
1375
        for (Integer fofoId : fofoIds) {
1376
            List<Loan> closedLoans = partnerClosedLoansMap.get(fofoId);
1377
 
1378
            if (closedLoans != null) {
1379
                long averageCreditDays = Math.round(closedLoans.stream().mapToLong(x -> Duration.between(x.getCreatedOn(),
1380
                        x.getSettledOn() == null ? x.getCreatedOn().plusDays(10) : x.getSettledOn()).toDays() + 1).average().orElse(0.0));
1381
                partnerAverageCreditDaysMap.put(fofoId, (int) averageCreditDays);
1382
            }
1383
        }
1384
 
1385
 
32491 jai.hind 1386
        model.addAttribute("creditAccounts", creditAccounts);
33045 amit.gupta 1387
        model.addAttribute("fofoSidbiPendingSanctionsMap", fofoSidbiPendingSanctionsMap);
1388
        model.addAttribute("directGateways", directGateways);
32491 jai.hind 1389
        model.addAttribute("customRetailers", customRetailers);
33420 amit.gupta 1390
        model.addAttribute("partnerAverageCreditDaysMap", partnerAverageCreditDaysMap);
32491 jai.hind 1391
        return "partner-credit-detail";
1392
    }
29811 tejbeer 1393
 
33045 amit.gupta 1394
 
33359 amit.gupta 1395
    @Autowired
1396
    SidbiService sidbiService;
33363 amit.gupta 1397
 
32491 jai.hind 1398
    @RequestMapping(value = "/activateKred", method = RequestMethod.POST)
33045 amit.gupta 1399
    public String activateKred(HttpServletRequest request, @RequestParam int id, Model model, @RequestParam Gateway gateway) throws Exception {
32491 jai.hind 1400
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
33359 amit.gupta 1401
        if (creditAccount.getGateway().equals(gateway)) {
1402
            creditAccount.setActive(true);
1403
        } else {
33363 amit.gupta 1404
            SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(creditAccount.getFofoId());
33360 amit.gupta 1405
 
33363 amit.gupta 1406
            if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) != 0) {
33360 amit.gupta 1407
                LOGGER.info("sdCreditRequirement - {}", sdCreditRequirement);
33363 amit.gupta 1408
                throw new ProfitMandiBusinessException("Could not change to " + gateway + " unless previous loans are settled", "", "");
33205 amit.gupta 1409
            }
33359 amit.gupta 1410
            if (gateway.equals(Gateway.SIDBI)) {
1411
                //TODO - Issuance pending
1412
                FofoSidbiSanction fofoSidbiSanction = fofoSidbiSanctionRepository.selectByFofoId(creditAccount.getFofoId());
1413
                sidbiService.issueLimit(fofoSidbiSanction);
33363 amit.gupta 1414
                sdCreditRequirement.setLimit(BigDecimal.valueOf(fofoSidbiSanction.getLoanAmount()));
1415
                sdCreditRequirement.setSuggestedLimit(sdCreditRequirement.getLimit());
33359 amit.gupta 1416
                if (sdCreditRequirement.getUtilizedAmount().compareTo(BigDecimal.ZERO) > 0) {
1417
                    throw new ProfitMandiBusinessException("Loans are not closed", "Loans are not closed", "Loans are not closed");
1418
                }
33363 amit.gupta 1419
                creditAccount.setSanctionedAmount((float) fofoSidbiSanction.getLoanAmount());
33359 amit.gupta 1420
            }
33363 amit.gupta 1421
            creditAccount.setAvailableAmount(creditAccount.getSanctionedAmount());
1422
            sdCreditRequirement.setUtilizedAmount(BigDecimal.ZERO);
1423
            creditAccount.setActive(true);
1424
            creditAccount.setGateway(gateway);
33045 amit.gupta 1425
        }
29811 tejbeer 1426
 
32491 jai.hind 1427
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
30859 tejbeer 1428
 
34712 amit.gupta 1429
        String title = "Credit Limit Approved";
32491 jai.hind 1430
        String url = "http://app.smartdukaan.com/pages/home/credit";
32495 amit.gupta 1431
        String message = "Congratulations! Your Credit Limit is approved for Rs." + FormattingUtils.formatDecimal(creditAccount.getSanctionedAmount());
1432
        notificationService.sendNotification(creditAccount.getFofoId(), "Loan", MessageType.notification, title, message, url);
29811 tejbeer 1433
 
32491 jai.hind 1434
        model.addAttribute("creditAccount", creditAccount);
1435
        model.addAttribute("customRetailers", customRetailers);
1436
        return "partner-credit-detail-row";
1437
    }
29811 tejbeer 1438
 
32491 jai.hind 1439
    @RequestMapping(value = "/deactivateKred", method = RequestMethod.POST)
1440
    public String deactivateKred(HttpServletRequest request, @RequestParam int id, Model model) throws Exception {
1441
        CreditAccount creditAccount = creditAccountRepository.selectById(id);
29811 tejbeer 1442
 
32491 jai.hind 1443
        creditAccount.setActive(false);
29811 tejbeer 1444
 
32491 jai.hind 1445
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
29811 tejbeer 1446
 
32491 jai.hind 1447
        model.addAttribute("creditAccount", creditAccount);
1448
        model.addAttribute("customRetailers", customRetailers);
1449
        return "partner-credit-detail-row";
1450
    }
1451
 
34261 tejus.loha 1452
    @RequestMapping(value = "/downloadAddWalletRequestReport", method = RequestMethod.GET)
34527 tejus.loha 1453
    public ResponseEntity<?> addWalletRequestPendingReport(@RequestParam LocalDate startDate, @RequestParam LocalDate endDate, @RequestParam AddWalletRequestStatus status, Model model) throws Exception {
1454
        if (endDate == null) {
1455
            endDate = LocalDate.now();
34261 tejus.loha 1456
        }
1457
        LocalDateTime form = startDate.atStartOfDay();
1458
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1459
        return walletService.createAddWalletRequestReport(form, to, status);
1460
    }
1461
 
34527 tejus.loha 1462
    @GetMapping(value = "/getHdfcPaymentsReport")
1463
    public String upiPaymentReport(HttpServletRequest request, @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate,@RequestParam(defaultValue = "OTH") String transferMode, Model model) throws Exception {
34261 tejus.loha 1464
 
34527 tejus.loha 1465
        if (startDate == null) {
1466
            startDate = LocalDate.now().minusDays(7);
1467
        }
1468
        if (endDate == null) {
1469
            endDate = LocalDate.now();
1470
        }
1471
        LocalDateTime form = startDate.atStartOfDay();
1472
        LocalDateTime to = endDate.atStartOfDay().plusDays(1);
1473
        List<HdfcPayment> hdfcPayments = hdfcPaymentRepository.selectAllByTransferModeAndDataRange(transferMode, form, to);
1474
        Map<Integer, CustomRetailer> allFofoRetailers = retailerService.getAllFofoRetailers();
1475
        List<HdfcPaymentModel> hdfcPaymentModelList = new ArrayList<>();
1476
        if (hdfcPayments != null && hdfcPayments.size() > 0) {
1477
            for (HdfcPayment upiPayment : hdfcPayments) {
1478
                HdfcPaymentModel hdfcPaymentModel = new HdfcPaymentModel();
1479
                // remove prifix to get fofoId = "nwspic" from virtual account "nwspicFOFOID" eg "nwspic175140063" to "175140063"
1480
                String partnerIdString = upiPayment.getVirtualAccount().substring(6);
1481
                CustomRetailer customRetailer = allFofoRetailers.get(Integer.parseInt(partnerIdString));
1482
                hdfcPaymentModel.setAmount(upiPayment.getAmount());
1483
                hdfcPaymentModel.setName(customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")");
1484
                hdfcPaymentModel.setUtr(upiPayment.getUtr());
1485
                hdfcPaymentModel.setCreateTimestamp(upiPayment.getCreateTimestamp());
1486
                hdfcPaymentModel.setCreditTimestamp(upiPayment.getCreditTimestamp());
1487
                hdfcPaymentModel.setTransactionId(upiPayment.getTransactionId());
1488
                hdfcPaymentModel.setTransferMode(upiPayment.getTransferMode());
1489
                hdfcPaymentModelList.add(hdfcPaymentModel);
1490
            }
1491
        }
1492
 
1493
        List<String> transferModeList = Arrays.asList("OTH","FUND TRANS","IMPS","NEFT","RTGS");
1494
        model.addAttribute("hdfcPaymentModels", hdfcPaymentModelList);
1495
        model.addAttribute("startDate", startDate);
1496
        model.addAttribute("endDate", endDate);
1497
        model.addAttribute("mode", transferMode);
1498
        model.addAttribute("transferModeList", transferModeList);
1499
        return "upi-payments-report-panel";
1500
    }
1501
 
1502
 
22551 ashik.ali 1503
}