Untitled

mail@pastecode.io avatar
unknown
plain_text
4 months ago
18 kB
3
Indexable
package com.byteplustech.arstatement.statement.controller.v1.api;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.byteplustech.arstatement.excel.builder.ExcelBuilder;
import com.byteplustech.arstatement.excel.builder.ExcelBuilderFactory;
import com.byteplustech.arstatement.excel.builder.StatementByStatusReportExcelBuilder;
import com.byteplustech.arstatement.excel.sheet.StatementByStatusReportModel;
import com.byteplustech.arstatement.excel.sheet.StatementByStatusReportSheet;
import com.byteplustech.arstatement.statement.controller.v1.request.StatementByStatusReportRequest;
import com.byteplustech.arstatement.statement.controller.v1.request.StatementReportRequest;
import com.byteplustech.arstatement.statement.repository.CustomStatementHeaderImplRepository;
import com.byteplustech.arstatement.statement.service.*;
import com.byteplustech.arstatement.utils.AuthUtils;
import com.byteplustech.arstatement.utils.DateUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.logging.log4j.util.Strings;
import org.jooq.tools.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.byteplustech.arstatement.dto.Response;
import com.byteplustech.arstatement.statement.controller.v1.request.AdvanceReceiptExcelRequest;
import com.byteplustech.arstatement.statement.controller.v1.request.CompleteReceiptSearchrequest;

import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;

import javax.xml.bind.ValidationException;

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@Log4j2
@RequestMapping("/api/v1/report")
@Api(value = "report-application")
public class ReportController {

    private final IPendingRefundReportService pendingRefundReportService;
    private final IPendingMatchReportService pendingMatchReportService;
    private final IAdvanceReceiptReportExcelService advanceReceiptReportExcelService;
    private final IOutstandingReportService outstandingReportService;
    private final IReportForKBankService reportForKBankService;
    private final IReportService reportService;
    private final IReceiptReportService receiptReportService;
//    private final IStatementExcelReportService statementExcelReportService;
    private final OtherReportServiceImpl otherReportService;
    private final ReceiptReportServiceImpl receiptReportServiceImpl;
    private final CustomStatementHeaderImplRepository customStatementHeaderImplRepository;

    public ReportController(IPendingRefundReportService pendingRefundReportService,
                            IPendingMatchReportService pendingMatchReportService,
                            IAdvanceReceiptReportExcelService advanceReceiptReportExcelService,
                            IOutstandingReportService outstandingReportService,
                            IReportForKBankService reportForKBankService,
                            IReportService reportService,
                            IReceiptReportService receiptReportService,
//            , IStatementExcelReportService statementExcelReportService
                            OtherReportServiceImpl otherReportService, ReceiptReportServiceImpl receiptReportServiceImpl, CustomStatementHeaderImplRepository customStatementHeaderImplRepository) {
        this.pendingRefundReportService = pendingRefundReportService;
        this.pendingMatchReportService = pendingMatchReportService;
        this.advanceReceiptReportExcelService = advanceReceiptReportExcelService;
        this.outstandingReportService = outstandingReportService;
        this.reportForKBankService = reportForKBankService;
        this.reportService = reportService;
        this.receiptReportService = receiptReportService;
//        this.statementExcelReportService = statementExcelReportService;
        this.otherReportService = otherReportService;
        this.receiptReportServiceImpl = receiptReportServiceImpl;
        this.customStatementHeaderImplRepository = customStatementHeaderImplRepository;
    }

    @GetMapping(value = "in069")
    public ResponseEntity in069(@RequestParam("buId") BigDecimal buId) {
        try {
            return pendingRefundReportService.genXlsx(buId);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return new ResponseEntity(null, HttpStatus.NOT_FOUND);
        }
    }

//    @GetMapping(value = "in035")
//    public ResponseEntity in035(StatementSearchRequest request) throws Exception {
//        return pendingMatchReportService.genXlsx(request);
//    }

//    @GetMapping(value = "in048")
//    public ResponseEntity in048(AdvanceReceiptExcelRequest request) throws Exception {
//        return advanceReceiptReportExcelService.genXlsx(request);
//    }

    @PostMapping(value = "in035")
    public Response in035(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody StatementReportRequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(pendingMatchReportService.genJobPendingMatchReportExcel(request, userLogin));
    }
    @PostMapping(value = "in048")
    public Response in048(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody AdvanceReceiptExcelRequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(advanceReceiptReportExcelService.genJobReportAdvanceReceiptExcel(request, userLogin));
    }

    @PostMapping(value = "in024")
    public Response in024(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody StatementReportRequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(outstandingReportService.genJobReportOutstanding(request, userLogin));
    }

    @PostMapping(value = "receiptReport")
    public Response receiptReport(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody StatementReportRequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(receiptReportService.genJobReceiptReport(request, userLogin));
    }

    @PostMapping(value = "statementReportExcel")
    public Response statementReportExcel(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody StatementReportRequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(receiptReportService.genJobExcelNew(request, userLogin));
    }

    @PostMapping(value = "sentStatementViaEmailReportExcel")
    public Response sentStatementViaEmailReportExcel(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody Map<String, Object> request) {
        String userLogin = AuthUtils.getUserLogin(principal);

        return Response.ok().setPayload(receiptReportService.genJobSentStatementViaEmailReport(request, userLogin));
    }

    @PostMapping(value = "statementByStatusReport")
    public Response statementByStatusReport(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody Map<String, Object> request) {
        String userLogin = AuthUtils.getUserLogin(principal);

        String businessUnit = MapUtils.getString(request, "businessUnit");
        String createDateStartStr = MapUtils.getString(request, "createDateStart");
        String createDateEndStr = MapUtils.getString(request, "createDateEnd");

        if (StringUtils.isBlank(businessUnit)) {
            return Response.badRequest().setPayload("businessUnit cannot be empty.");
        }

        if (StringUtils.isBlank(createDateStartStr) || StringUtils.isBlank(createDateEndStr)) {
            return Response.badRequest().setPayload("createDateStart and createDateEnd cannot be empty.");
        }

        LocalDateTime createDateStart = LocalDateTime.parse(createDateStartStr, DateTimeFormatter.ISO_DATE_TIME);
        LocalDateTime createDateEnd = LocalDateTime.parse(createDateEndStr, DateTimeFormatter.ISO_DATE_TIME);
        if (ChronoUnit.MONTHS.between(createDateStart, createDateEnd) > 6) {
            return Response.badRequest().setPayload("createDateStart and createDateEnd must not exceed 6 months apart.");
        }

        return Response.ok().setPayload(receiptReportService.genJobStatementByStatusReport(request, userLogin));
    }
    
    @PostMapping(value = "completeReceiptReport")
    public Response completeReceiptReportExcel(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody CompleteReceiptSearchrequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(receiptReportService.genJobExcelCompleteReceipt(request, userLogin));
    }

    @PostMapping(value = "errReceiptReport")
    public Response errReceiptReport(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody CompleteReceiptSearchrequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(receiptReportService.genJobExcelErrReceiptReport(request, userLogin));
    }

    @PostMapping(value = "completeMonitoringReport")
    public Response completeMonitoringReport(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody StatementReportRequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(otherReportService.startXlsxReportCompleteMonitoring(request, userLogin));
    }

    @PostMapping(value = "statementInterfacingReport")
    public Response statementInterfacingReport(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody CompleteReceiptSearchrequest request) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(otherReportService.startXlsxReportStatementInterfacing(request, userLogin));
    }

    @PostMapping("kbank/{flagReport}")
    public Response createReportForKBank(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal, @RequestBody StatementReportRequest request, @PathVariable("flagReport") String flagReport) {
        String userLogin = "admin";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(reportForKBankService.createJobReportForKbank(request, flagReport, userLogin));
    }

    @GetMapping("/download")
    public ResponseEntity downloadAllFiles(@RequestParam("requestId") Long requestId,@RequestParam("reportName") String reportName) {
        return reportService.getFile(requestId, reportName);
    }

    @GetMapping("logs")
    public Response getLogs(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal,
            @RequestParam(defaultValue = "0") int offset,
            @RequestParam(defaultValue = "100") int limit,
            @RequestParam(defaultValue = "reportJobInfoId") String orderBy,
            @RequestParam String reportName) {
        String userLogin = "";
        if (principal != null) userLogin = principal.getAttribute("sub");

        return Response.ok().setPayload(reportService.getLogSchedule(offset, limit, orderBy, reportName, userLogin));
    }

    // TODO por test
    @PostMapping(value = "portest")
    public ResponseEntity<byte[]> completeReceiptReportExcel(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal,
                                                             @RequestBody StatementByStatusReportRequest request) throws Exception {


        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=completeReceiptReport.xlsx");

        List<Map<String, Object>> reportDataMaps = customStatementHeaderImplRepository.getStatementByStatusReport(request);
        if (CollectionUtils.isEmpty(reportDataMaps)) {
            return null;
        }
        Set<String> uniqueStatementNumbers = new HashSet<>();
        AtomicInteger sequence = new AtomicInteger(1);

        List<StatementByStatusReportModel> reportData = reportDataMaps.stream()
                .filter(o -> uniqueStatementNumbers.add(MapUtils.getString(o, "STATEMENT_NUMBER", Strings.EMPTY)))
                .map(o -> {
                    String rawOthersApplyDate = MapUtils.getString(o, "RECEIPT_DATE", StringUtils.EMPTY);
                    Date rawOthersApplyDateObj = DateUtils.timestampOracleDbToDate(rawOthersApplyDate);
                    String othersApplyDate = Objects.nonNull(rawOthersApplyDateObj) ? DateUtils.sdfddMMyyyy.format(rawOthersApplyDateObj) : Strings.EMPTY;

                    String rawStatementDate = MapUtils.getString(o, "STATEMENT_DATE", StringUtils.EMPTY);
                    Date rawStatementDateObj = DateUtils.timestampOracleDbToDate(rawStatementDate);
                    String statementDate = Objects.nonNull(rawStatementDateObj) ? DateUtils.sdfddMMyyyy.format(rawStatementDateObj) : Strings.EMPTY;

                    Double premium = MapUtils.getDoubleValue(o, "PREMIUM_AMOUNT");
                    Double stamp = MapUtils.getDoubleValue(o, "PREMIUM_STAMP_AMOUNT");
                    Double outputVat = MapUtils.getDoubleValue(o, "PREMIUM_OUTPUT_VAT_AMOUNT");
                    Double totalPremium = premium + stamp + outputVat;

                    return StatementByStatusReportModel.builder()
                            .sequence(sequence.getAndIncrement())
                            .othersApplyDate(othersApplyDate)
                            .statementDate(statementDate)
                            .statementNumber(MapUtils.getString(o, "STATEMENT_NUMBER", Strings.EMPTY))
                            .customerName(MapUtils.getString(o, "CUSTOMER_NAME", Strings.EMPTY))
                            .siteNumber(MapUtils.getString(o, "SITE_NUMBER", Strings.EMPTY))
                            .dChanel(MapUtils.getString(o, "D_CHANNEL", Strings.EMPTY))
                            .branch(MapUtils.getString(o, "BRANCH", Strings.EMPTY))
                            .premium(premium)
                            .stamp(stamp)
                            .outputVat(outputVat)
                            .totprm(totalPremium)
                            .wht1Percent(MapUtils.getDouble(o, "PREMIUM_WHT_PERCENT_AMOUNT"))
                            .commission(MapUtils.getDouble(o, "COMMISSION_AMOUNT"))
                            .inputVatAmount7Percent(MapUtils.getDouble(o, "COMMISSION_INPUT_VAT_AMOUNT"))
                            .whtCommission3Percent(MapUtils.getDouble(o, "COMMISSION_WHT_AMOUNT"))
                            .statementAmount(MapUtils.getDouble(o, "STATEMENT_AMOUNT"))
                            .statementStatus(MapUtils.getString(o, "STATEMENT_STATUS", Strings.EMPTY))
                            .othersReceiptNumber(MapUtils.getString(o, "RECEIPT_NUMBER", Strings.EMPTY))
                            .othersRemark(MapUtils.getString(o, "REMARK", Strings.EMPTY))
                            .createBy(MapUtils.getString(o, "CREATE_BY", Strings.EMPTY))
                            .build();
                })
                .collect(Collectors.toList());

        ExcelBuilder excelBuilder = ExcelBuilderFactory.get(StatementByStatusReportExcelBuilder.class);
        StatementByStatusReportSheet statementByStatusReportSheet = new StatementByStatusReportSheet(reportData);
        excelBuilder.addSheet(statementByStatusReportSheet);

        byte[] bytes = excelBuilder.generate();

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(bytes.length)
                .contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM)
                .body(bytes);
    }


}
Leave a Comment