BackOfficeSalesController

mail@pastecode.io avatar
unknown
java
2 years ago
35 kB
1
Indexable
Never
package com.oto11.controller;

import com.google.gson.Gson;
import com.oto11.dto.PageData;
import com.oto11.dto.garage.CampaignAndAdditionalServiceDTO;
import com.oto11.dto.sales.SalesDTO;
import com.oto11.dto.settlement.SettlementExcelReportAsTableDTO;
import com.oto11.dto.settlement.SettlementLogDTO;
import com.oto11.dto.settlement.SettlementPaymentDTO;
import com.oto11.dto.settlement.SettlementSalesDTO;
import com.oto11.dto.settlement.ws.*;
import com.oto11.enums.OrderStatusEnums;
import com.oto11.enums.SapTransactionTypeEnums;
import com.oto11.enums.UserTypeEnums;
import com.oto11.exception.InvalidRequestException;
import com.oto11.exception.NotFoundException;
import com.oto11.exception.UnAuthorizedException;
import com.oto11.service.ExcelHelper;
import com.oto11.service.GarageService;
import com.oto11.service.SalesService;
import com.oto11.service.SettlementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/garaj11/api/sales")
@RequiredArgsConstructor
@Log4j2
public class SalesController {

    @Value("${backoffice.offline-transfer-no}")
    private String offlineTransferNo;

    @Value("${backoffice.sap-account-no}")
    private String sapAccountNo;

    private final SalesService salesService;

    private final GarageService garageService;

    private final SettlementService settlementService;

    @CrossOrigin
    @GetMapping(value = "/find-sales-list")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesListing','read')")
    public ResponseEntity<PageData<List<SalesDTO>>> findSalesList(@RequestHeader(value = "Authorization") String token,
                                                                  @RequestParam(value = "orderId", required = false) Long orderId,
                                                                  @RequestParam(value = "buyerId", required = false) String buyerId,
                                                                  @RequestParam(value = "buyerName", required = false) String buyerName,
                                                                  @RequestParam(value = "buyerSurname", required = false) String buyerSurname,
                                                                  @RequestParam(value = "sellerId", required = false) String sellerId,
                                                                  @RequestParam(value = "sellerName", required = false) String sellerName,
                                                                  @RequestParam(value = "plate", required = false) String plate,
                                                                  @RequestParam(required = false) String garageId,
                                                                  @RequestParam(value = "title", required = false) String vehicleTitle,
                                                                  @RequestParam(value = "beginDate") String beginDate,
                                                                  @RequestParam(value = "endDate") String endDate,
                                                                  @RequestParam(value = "salesType", required = false) String salesType,
                                                                  @RequestParam(value = "pageNo") Integer pageNo,
                                                                  @RequestParam(value = "pageSize") Integer pageSize,
                                                                  @RequestParam(value = "sortBy") String sortBy,
                                                                  @RequestParam(value = "campaign",required = false) String campaign,
                                                                  @RequestParam(value = "sortType") String sortType) {
        return new ResponseEntity<>(salesService.findSalesList(orderId, buyerId, buyerName, buyerSurname, sellerId, sellerName, plate, garageId, vehicleTitle, beginDate, endDate, salesType, pageNo, pageSize, sortBy, sortType,campaign), HttpStatus.OK);
    }

    @CrossOrigin
    @GetMapping(value = "/get-sales")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesListing','read','/sales/SalesDetail','read')")
    public ResponseEntity<SalesDTO> getSales(@RequestHeader(value = "Authorization") String token, @RequestParam(value = "id") String carId, @RequestParam(value = "orderId") Long orderId) {
        return new ResponseEntity<>(salesService.getSales(carId, orderId), HttpStatus.OK);
    }

    @CrossOrigin
    @PostMapping(value = "/update-sales")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesDetail','write')")
    public ResponseEntity<String> updateSales(@RequestHeader(value = "Authorization") String token, @RequestBody SalesDTO sales) {
        return new ResponseEntity<>(salesService.updateSales(sales), HttpStatus.OK);
    }

    @CrossOrigin
    @GetMapping(value = "/download-excel")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesListing','read')")
    public ResponseEntity<String> downloadApprovalDataAsExcel(@RequestHeader(value = "Authorization") String token,
                                                              @RequestParam(value = "orderId", required = false) Long orderId,
                                                              @RequestParam(value = "buyerId", required = false) String buyerId,
                                                              @RequestParam(value = "buyerName", required = false) String buyerName,
                                                              @RequestParam(value = "buyerSurname", required = false) String buyerSurname,
                                                              @RequestParam(value = "sellerId", required = false) String sellerId,
                                                              @RequestParam(value = "sellerName", required = false) String sellerName,
                                                              @RequestParam(value = "plate", required = false) String plate,
                                                              @RequestParam(required = false) String garageId,
                                                              @RequestParam(value = "title", required = false) String vehicleTitle,
                                                              @RequestParam(value = "beginDate") String beginDate,
                                                              @RequestParam(value = "endDate") String endDate,
                                                              @RequestParam(value = "salesType", required = false) String salesType) throws ParseException, NotFoundException, UnAuthorizedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'");

        Timestamp beginDateT = null;
        Timestamp endDateT = null;

        if (beginDate != null) {
            Date beginDateO = sdf.parse(beginDate);
            beginDateT = new Timestamp(beginDateO.getTime());
        }
        if (beginDate != null) {
            Date endDateO = sdf.parse(endDate);
            endDateT = new Timestamp(endDateO.getTime());
        }
        SimpleDateFormat date = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat time = new SimpleDateFormat("HH:mm:SS");
        SimpleDateFormat dateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:SS");

        List<SalesDTO> result = salesService.findAllSalesList(orderId, buyerId, buyerName, buyerSurname, sellerId, sellerName, plate, garageId, vehicleTitle, beginDateT, endDateT, salesType).getBody();
        int index = 0;
        int size = result.size() + 1;
        Object[][] data = new Object[size][35];
        data[index++] = new Object[]{"Satıcı ID", "Satıcı İsim", "Satıcı Soyisim", "Satıcı Email", "Satıcı Tipi", //
                "Alıcı ID", "Alıcı İsim", "Alıcı Soyisim", "Alıcı Email", "Alıcı Tipi", //
                "Araç ID", "Araç Başlığı", "Yıl", "Marka", "Model", "Kasa Tipi", "Vites", "Yakıt", "Versiyon", "Kilometre", "Renk", "Plaka", "Şasi No", "Motor No", "Şehir", //
                "Ödeme ID", "İlan ID", "Ödeme Kanalı", "Durumu", "Ödeme Tipi","Ödeme Banka Adı", "Komisyon Tutarı", "Komisyon Oranı(%)", "Komisyon Tutarı (Net Tutar)", "Satış Tutarı", "Kredi Miktarı", "Devir Tarihi", "Ödeme Tarihi","Ödeme Saati", "Ek Hizmetler"};

        while (index < size) {
            SalesDTO row = result.get(index - 1);
            data[index++] = new Object[]{
                    row.getSellerId(),
                    row.getSellerName(),
                    row.getSellerSurname(),
                    row.getSellerEmail(),
                    row.getSellerType() == null ? "" : (UserTypeEnums.INDIVIDUAL.name().equals(row.getSellerType()) ? "Bireysel" : "Kurumsal"),
                    row.getBuyerId(),
                    row.getBuyerName(),
                    row.getBuyerSurname(),
                    row.getBuyerEmail(),
                    row.getBuyerType() == null ? "" : (UserTypeEnums.INDIVIDUAL.name().equals(row.getBuyerType()) ? "Bireysel" : "Kurumsal"),
                    row.getCarId(),
                    row.getVehicleTitle(),
                    row.getVehicleYear(),
                    row.getVehicleBrand(),
                    row.getVehicleModel(),
                    row.getVehicleBodyStyle(),
                    row.getVehicleTransmissionType(),
                    row.getVehicleFuelType(),
                    row.getVehicleVersion(),
                    row.getVehicleKilometers(),
                    row.getVehicleColor(),
                    row.getPlateNumber(),
                    row.getChassisNumber(),
                    row.getEngineNo(),
                    row.getCity(),
                    row.getOrderId() == null ? "" : String.valueOf(row.getOrderId()),
                    row.getGarageId() == null ? "" : String.valueOf(row.getGarageId()),
                    row.getOrderChannel(),
                    row.getOrderStatus() == null ? "" : (OrderStatusEnums.PAYMENT_SUCCEEDED.name().equals(row.getOrderStatus()) ? "Ödeme Başarılı" : row.getOrderStatus()),
                    row.getPaymentType(),
                    row.getPaymentName(),
                    row.getCommissionAmount(),
                    row.getCommissionPercent(),
                    row.getCommissionAmountExcVat(),
                    row.getAmount(),
                    row.getCreditAmount(),
                    row.getDeliveredDate() == null ? "" : date.format(row.getDeliveredDate()),
                    row.getCreatedDate() == null ? "" : date.format(row.getCreatedDate()),
                    row.getCreatedDate() == null ? "" : time.format(row.getCreatedDate()),
                    garageService.getAdditionalServices(row.getGarageId()) == null || garageService.getAdditionalServices(row.getGarageId()).isEmpty() ? "" : garageService.getAdditionalServices(row.getGarageId()).toString(),
            };
        }

        String fileString = ExcelHelper.downloadDataAsBase64ExcelFile(data);
        return new ResponseEntity<>(fileString, HttpStatus.OK);
    }

    @CrossOrigin
    @GetMapping(value = "/set-delivered-date")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesDetail','write')")
    public ResponseEntity<Boolean> setDeliveredDate(@RequestHeader(value = "Authorization") String token, @RequestParam(value = "id") String carId, @RequestParam(value = "deliveredDate") String deliveryDateStr, @RequestParam(value = "salesId") Long salesId) throws ParseException, NotFoundException, InvalidRequestException {

        Timestamp deliveredDate = null;
        if (deliveryDateStr != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(deliveryDateStr));
            deliveredDate = new Timestamp(c.getTime().getTime());
        } else {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }

        Boolean isSet = salesService.setDeliveredDate(carId, deliveredDate);
        transferToSap(token,salesId);
        return new ResponseEntity<>(isSet, HttpStatus.OK);
    }

    @CrossOrigin
    @GetMapping(value = "/download-sap-sales-excel")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesListing','read')")
    public ResponseEntity<String> downloadSapSalesExcel(@RequestHeader(value = "Authorization") String token, @RequestParam(value = "id") Long salesId) throws NotFoundException, InvalidRequestException, ParseException {
        List<String> sortList = new ArrayList<>();
        HashMap<String, Object[][]> excelData = new HashMap<>();

        List<SettlementExcelReportAsTableDTO> resultData = getResultData(salesId);

        for (SettlementExcelReportAsTableDTO sheet : resultData) {
            sortList.add(sheet.getName());
            excelData.put(sheet.getName(), sheet.getData());
        }

        return new ResponseEntity<>(ExcelHelper.downloadDataAsBase64ExcelFileMultipleSheet(excelData, sortList), HttpStatus.OK);
    }

    @CrossOrigin
    @GetMapping(value = "/get-sap-excel-as-table")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesListing','read')")
    public ResponseEntity<List<SettlementExcelReportAsTableDTO>> getSapExcelAsTable(@RequestHeader(value = "Authorization") String token, @RequestParam(value = "id") Long salesId) throws NotFoundException, InvalidRequestException, ParseException {
        List<SettlementExcelReportAsTableDTO> resultData = getResultData(salesId);
        return new ResponseEntity<>(resultData, HttpStatus.OK);
    }

    private List<SettlementExcelReportAsTableDTO> getResultData(Long salesId) throws NotFoundException, InvalidRequestException, ParseException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

        SettlementSalesDTO sales = salesService.findSales(salesId);
        if (sales == null) {
            throw new NotFoundException();
        }
        SettlementPaymentDTO payment = salesService.findPaymentByOrderId(sales.getOrderId());
        if (payment == null) {
            throw new NotFoundException();
        }
        Timestamp deliveredDate = garageService.getDeliveredDate(sales.getCarId()).getBody();
        Boolean isPaymentCancellation = sales.getSettlementStatus() != null && sales.getSettlementStatus().equals(0) ? true : false;

        if (!isPaymentCancellation && deliveredDate == null && SapTransactionTypeEnums.T.name().equals(payment.getSapTransactionType())) {
            throw new InvalidRequestException();
        } else {
            deliveredDate = new Timestamp(new Date().getTime());
        }

        log.info("Settlement Status : " + sales.getSettlementStatus() + " isPaymentCancellation : " + isPaymentCancellation);

        Gson gson = new Gson();
        SettlementLogDTO settlementLogDTOCommission = settlementService.findByOrderIdAndWstype(sales.getOrderId(), "COMMISSION");
        SettlementLogDTO settlementLogDTOPayment = settlementService.findByOrderIdAndWstype(sales.getOrderId(), "PAYMENT");

        String commissionDate = sdf.format(deliveredDate);
        String paymentDate = sdf.format(new Date());

        if (!StringUtils.isEmpty(settlementLogDTOCommission) && !StringUtils.isEmpty(settlementLogDTOCommission.getWsRequestData())){
            JSONObject jo = new JSONObject(settlementLogDTOCommission.getWsRequestData());
            if (jo.has("tamamlanma_TARIHI") && !StringUtils.isEmpty(jo.getString("tamamlanma_TARIHI"))){
                commissionDate = sdf.format(sdf1.parse(jo.getString("tamamlanma_TARIHI")));
            }
        }

        if (!StringUtils.isEmpty(settlementLogDTOPayment) && !StringUtils.isEmpty(settlementLogDTOPayment.getWsRequestData())){
            JSONObject jo = new JSONObject(settlementLogDTOPayment.getWsRequestData());
            if (jo.has("islem_TARIHI") && !StringUtils.isEmpty(jo.getString("islem_TARIHI"))){
                paymentDate = sdf.format(sdf1.parse(jo.getString("islem_TARIHI")));
            }
        }

        String transactionType = payment.getSapTransactionType();
        String commissionTransactionType = SapTransactionTypeEnums.R.name();
        if (isPaymentCancellation) {
            transactionType = SapTransactionTypeEnums.T.name().equals(payment.getSapTransactionType()) ? SapTransactionTypeEnums.TI.name() : SapTransactionTypeEnums.RI.name();
            commissionTransactionType = SapTransactionTypeEnums.RI.name();
        }

        String sapBankCollection = null;
        String sellerId = null;
        String buyerId = null;
        String sellerId02 = null;
        String buyerId02 = null;
        String transactionType03 = null;
        BigDecimal commissionAmount = null;
        String sapCollectionType = null;
        if (SapTransactionTypeEnums.T.name().equals(payment.getSapTransactionType())) {
            sapBankCollection = "OFFLINE_TRANSFER".equals(payment.getSapCollectionBankAccount()) ? offlineTransferNo : payment.getSapCollectionBankAccount();
            sellerId = sales.getSellerId();
            buyerId = "";
            sellerId02 = isPaymentCancellation ? "" : sales.getSellerId();
            buyerId02 = sales.getBuyerId();
            commissionAmount = sales.getCommissionAmount();
            transactionType03 = isPaymentCancellation ? SapTransactionTypeEnums.SI.name() : SapTransactionTypeEnums.S.name();
            sapCollectionType = "0".concat(payment.getSapCollectionType());
        } else if (SapTransactionTypeEnums.R.name().equals(payment.getSapTransactionType())) {
            sapBankCollection = sapAccountNo;
            sellerId = "";
            buyerId = sales.getBuyerId();
            sellerId02 = "";
            buyerId02 = sales.getBuyerId();
            commissionAmount = sales.getAmount();
            transactionType03 = commissionTransactionType;
            sapCollectionType = "0".concat(payment.getSapCollectionType());
            ;
        } else {
            sapBankCollection = "";
            sellerId = "";
            buyerId = "";
            sellerId02 = "";
            buyerId02 = "";
            commissionAmount = new BigDecimal(0);
            transactionType03 = "";
            sapCollectionType = "";
        }

        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, 1);
        Date dt = c.getTime();

        String salesCreateDate = sales.getCreatedDate() != null ? sdf.format(new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(sales.getCreatedDate())) : "";
        HashMap<String, Object[][]> excelData = new HashMap<>();
        Object[][] data1 = new Object[2][7];
        data1[0] = new Object[]{"ORDER_NUMBER", "TRANSACTION_TYPE", "IADE_KALEMI", "TAHSILAT_TIPI", "ISLEM_TARIHI", "TAHSILAT_HESAP_NUMARASI", "TUTAR"};
        data1[1] = new Object[]{
                sales.getOrderId().toString(),
                transactionType,
                payment.getRefundId(),
                sapCollectionType,
                salesCreateDate,
                sapBankCollection,
                sales.getAmount()
        };
        String sheetName1 = "ZFI_GRJ11_01 (TAHSILAT1)";
        excelData.put(sheetName1, data1);

        Object[][] data2 = new Object[2][9];
        data2[0] = new Object[]{"ORDER_NUMBER", "ORDER_ITEM_ID", "TRANSACTION_TYPE", "IADE_KALEMI", "ISLEM_TARIHI", "SATICI_ID", "TUTAR", "ALICI_ID", "KAPORA_TUTAR"};
        data2[1] = new Object[]{
                sales.getOrderId().toString(),
                payment.getOrderItemId(),
                transactionType,
                payment.getRefundId(),
                salesCreateDate,
                sellerId02,
                sales.getAmount(),
                buyerId02,
                ""
        };
        String sheetName2 = "ZFI_GRJ11_02 (TAHSILAT2)";
        excelData.put(sheetName2, data2);

        Object[][] data3 = new Object[2][8];
        data3[0] = new Object[]{"ORDER_NUMBER", "ORDER_ITEM_ID", "TRANSACTION_TYPE", "IADE_KALEM_ID", "TAMAMLANMA_TARIHI", "SATICI_ID", "ALICI_ID", "TUTAR"};
        data3[1] = new Object[]{
                sales.getOrderId().toString(),
                payment.getOrderItemId(),
                transactionType03,
                payment.getRefundId(),
                commissionDate,
                sellerId,
                buyerId,
                commissionAmount,
        };
        String sheetName3 = "ZFI_GRJ11_03 (Komisyon)";
        excelData.put(sheetName3, data3);

        Object[][] data4 = new Object[2][8];
        data4[0] = new Object[]{"ORDER_NUMBER", "ORDER_ITEM_ID", "IZAHAT_NUMARASI", "ISLEM_TARIHI", "SATICI_ID", "ODENMESI_GEREKEN_TUTAR", "BLOKE_TUTAR", "ODENECEK_TUTAR"};
        data4[1] = new Object[]{
                sales.getOrderId().toString(),
                payment.getOrderItemId(),
                payment.getSapExplanationNo(),
                paymentDate,
                sales.getSellerId(),
                sales.getSellerClaimAmount(),
                "",
                sales.getSellerClaimAmount(),
        };
        String sheetName4 = "ZFI_GRJ11_04 (Ödeme)";
        excelData.put(sheetName4, data4);

        List<String> sortList = Arrays.asList(sheetName1, sheetName2, sheetName3, sheetName4);

        List<SettlementExcelReportAsTableDTO> resultData = new ArrayList<>();

        for (String name : sortList) {
            SettlementExcelReportAsTableDTO sheetData = SettlementExcelReportAsTableDTO.builder().name(name).data(excelData.get(name)).build();
            if ((SapTransactionTypeEnums.R.name().equals(transactionType) || isPaymentCancellation) && name.equals("ZFI_GRJ11_04 (Ödeme)"))
                continue;
            resultData.add(sheetData);
        }
        return resultData;
    }

    @CrossOrigin
    @GetMapping(value = "/transfer-to-sap")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesDetail','write')")
    public ResponseEntity<String> transferToSap(@RequestHeader(value = "Authorization") String token, @RequestParam(value = "id") Long salesId) throws ParseException, NotFoundException, InvalidRequestException {

        SettlementSalesDTO sales = salesService.findSales(salesId);
        if (sales == null) {
            throw new NotFoundException("transfer-to-sap Sales not found : " + salesId);
        }
        SettlementPaymentDTO payment = salesService.findPaymentByOrderId(sales.getOrderId());
        if (payment == null) {
            throw new NotFoundException("transfer-to-sap payment not found for orderId : " + sales.getOrderId());
        }
        Timestamp deliveredDate = garageService.getDeliveredDate(sales.getCarId()).getBody();

        if (deliveredDate == null && SapTransactionTypeEnums.T.name().equals(payment.getSapTransactionType())) {
            throw new InvalidRequestException("transfer-to-sap invalid parameter - deliveredDate : " + deliveredDate + " / SapTransactionType : payment.getSapTransactionType()");
        } else {
            deliveredDate = new Timestamp(new Date().getTime());
        }

        JSONObject jo = sendSapWS(sales, payment, deliveredDate, false);

        return new ResponseEntity<>(jo.toString(), HttpStatus.OK);
    }

    @CrossOrigin
    @GetMapping(value = "/cancel-payment-to-sap")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesDetail','write')")
    public ResponseEntity<String> cancelPaymentToSAP(@RequestHeader(value = "Authorization") String token, @RequestParam(value = "id") Long salesId) throws ParseException, NotFoundException, InvalidRequestException {

        SettlementSalesDTO sales = salesService.findSales(salesId);
        if (sales == null) {
            throw new NotFoundException("cancel-payment-to-sap Sales not found : " + salesId);
        }
        SettlementPaymentDTO payment = salesService.findPaymentByOrderId(sales.getOrderId());
        if (payment == null) {
            throw new NotFoundException("cancel-payment-to-sap payment not found for orderId : " + sales.getOrderId());
        }
        Timestamp deliveredDate = garageService.getDeliveredDate(sales.getCarId()).getBody();

        if (deliveredDate == null) {
            deliveredDate = new Timestamp(new Date().getTime());
        }

        JSONObject jo = sendSapWS(sales, payment, deliveredDate, true);

        return new ResponseEntity<>(jo.toString(), HttpStatus.OK);
    }

    private JSONObject sendSapWS(SettlementSalesDTO sales, SettlementPaymentDTO payment, Timestamp deliveredDate, Boolean isPaymentCancellation) throws ParseException {
        JSONObject jo = new JSONObject();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String salesCreateDate = sales.getCreatedDate() != null ? sdf.format(new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(sales.getCreatedDate())) : "";
        String transactionType = payment.getSapTransactionType();
        String commissionTransactionType = SapTransactionTypeEnums.R.name();
        if (isPaymentCancellation) {
            transactionType = SapTransactionTypeEnums.T.name().equals(payment.getSapTransactionType()) ? SapTransactionTypeEnums.TI.name() : SapTransactionTypeEnums.RI.name();
            commissionTransactionType = SapTransactionTypeEnums.RI.name();
        }
        String sapBankCollection = null;
        String sellerId = null;
        String buyerId = null;
        String sellerId02 = null;
        String buyerId02 = null;
        String transactionType03 = null;
        BigDecimal commissionAmount = null;
        String sapCollectionType = null;
        if (SapTransactionTypeEnums.T.name().equals(payment.getSapTransactionType())) {
            sapBankCollection = "OFFLINE_TRANSFER".equals(payment.getSapCollectionBankAccount()) ? offlineTransferNo : payment.getSapCollectionBankAccount();
            sellerId = sales.getSellerId();
            buyerId = "";
            sellerId02 = isPaymentCancellation ? "" : sales.getSellerId();
            buyerId02 = sales.getBuyerId();
            commissionAmount = sales.getCommissionAmount();
            transactionType03 = isPaymentCancellation ? SapTransactionTypeEnums.SI.name() : SapTransactionTypeEnums.S.name();
            sapCollectionType = "0".concat(payment.getSapCollectionType());
        } else if (SapTransactionTypeEnums.R.name().equals(payment.getSapTransactionType())) {
            sapBankCollection = sapAccountNo;
            sellerId = "";
            buyerId = sales.getBuyerId();
            sellerId02 = "";
            buyerId02 = sales.getBuyerId();
            commissionAmount = sales.getAmount();
            transactionType03 = commissionTransactionType;
            sapCollectionType = "0".concat(payment.getSapCollectionType());
        } else {
            sapBankCollection = "";
            sellerId = "";
            buyerId = "";
            sellerId02 = "";
            buyerId02 = "";
            commissionAmount = new BigDecimal(0);
            transactionType03 = "";
            sapCollectionType = "";
        }
        //*******************************************************************//
        SettlementLogDTO receiptOfPayment1 = settlementService.findByOrderIdAndWstype(sales.getOrderId(), "RECEIPTOFPAYMENT1");
        SettlementLogDTO receiptOfPayment2 = settlementService.findByOrderIdAndWstype(sales.getOrderId(), "RECEIPTOFPAYMENT2");
        if( receiptOfPayment1 == null || !"SUCCESS".equals(receiptOfPayment1.getStatus())
                || receiptOfPayment2 == null || !"SUCCESS".equals(receiptOfPayment2.getStatus()) ) {
            ZFI_GRJ11_S_001 zfi_grj11_s_001 = new ZFI_GRJ11_S_001();

            zfi_grj11_s_001.setORDER_NUMBER(sales.getOrderId().toString());
            zfi_grj11_s_001.setTRANSACTION_TYPE(transactionType);
            zfi_grj11_s_001.setIADE_KALEMI(payment.getRefundId());
            zfi_grj11_s_001.setTAHSILAT_TIPI(sapCollectionType);
            zfi_grj11_s_001.setISLEM_TARIHI(salesCreateDate);
            zfi_grj11_s_001.setTAHSILAT_HESAP_NUMARASI(sapBankCollection);
            zfi_grj11_s_001.setTUTAR(sales.getAmount());

            log.info("zfi_grj11_s_001 Table Info : " + zfi_grj11_s_001.toString());

            ZFI_GRJ11_S_002 zfi_grj11_s_002 = new ZFI_GRJ11_S_002();

            zfi_grj11_s_002.setORDER_NUMBER(sales.getOrderId().toString());
            zfi_grj11_s_002.setORDER_ITEM_ID(payment.getOrderItemId());
            zfi_grj11_s_002.setTRANSACTION_TYPE(transactionType);
            zfi_grj11_s_002.setIADE_KALEMI(payment.getRefundId());
            zfi_grj11_s_002.setISLEM_TARIHI(salesCreateDate);
            zfi_grj11_s_002.setALICI_ID(buyerId02);
            zfi_grj11_s_002.setSATICI_ID(sellerId02);
            zfi_grj11_s_002.setTUTAR(sales.getAmount());
            zfi_grj11_s_002.setKAPORA_TUTAR(new BigDecimal("0"));

            log.info("zfi_grj11_s_002 Table Info : " + zfi_grj11_s_002.toString());

            BAPIRET2 receiptOfPayment = salesService.sendReceiptOfPayment(zfi_grj11_s_001, zfi_grj11_s_002);
            JSONObject ropJson = new JSONObject();
            ropJson.put("key", receiptOfPayment.getTYPE());
            ropJson.put("status", receiptOfPayment.getMESSAGE_V1());
            ropJson.put("message", receiptOfPayment.getMESSAGE());
            jo.put("receiptOfPayment", ropJson);

            log.info("zfi_grj11_s_001 and zfi_grj11_s_002 Response Info : " + ropJson.toString());
        }
        //*******************************************************************//
        ZFI_GRJ11_S_003 zfi_grj11_s_003 = new ZFI_GRJ11_S_003();

        zfi_grj11_s_003.setORDER_NUMBER(sales.getOrderId().toString());
        zfi_grj11_s_003.setORDER_ITEM_ID(payment.getOrderItemId());
        zfi_grj11_s_003.setIADE_KALEM_ID(payment.getRefundId());
        zfi_grj11_s_003.setTAMAMLANMA_TARIHI(deliveredDate != null ? sdf.format(deliveredDate) : "");
        zfi_grj11_s_003.setALICI_ID(sales.getBuyerId());
        zfi_grj11_s_003.setTUTAR(commissionAmount);
        zfi_grj11_s_003.setALICI_ID(buyerId);
        zfi_grj11_s_003.setSATICI_ID(sellerId);
        zfi_grj11_s_003.setTRANSACTION_TYPE(transactionType03);

        log.info("zfi_grj11_s_003 Table Info : " + zfi_grj11_s_003.toString());

        BAPIRET2 commission = salesService.sendCommission(zfi_grj11_s_003);
        JSONObject cJson = new JSONObject();
        cJson.put("key", commission.getTYPE());
        cJson.put("status", commission.getMESSAGE_V1());
        cJson.put("message", commission.getMESSAGE());
        jo.put("commission", cJson);

        log.info("zfi_grj11_s_003 Response Info : " + cJson.toString());
        Integer settlementStatus = null;
        //*******************************************************************//
        if (!isPaymentCancellation && !SapTransactionTypeEnums.R.name().equals(transactionType)) {

            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
//            c.add(Calendar.DATE, 1);
            Date dt = c.getTime();

            ZFI_GRJ11_S_004 zfi_grj11_s_004 = new ZFI_GRJ11_S_004();

            zfi_grj11_s_004.setORDER_NUMBER(sales.getOrderId().toString());
            zfi_grj11_s_004.setORDER_ITEM_ID(payment.getOrderItemId());
            zfi_grj11_s_004.setIZAHAT_NUMARASI(payment.getSapExplanationNo());
            zfi_grj11_s_004.setISLEM_TARIHI(sdf.format(dt));
            zfi_grj11_s_004.setSATICI_ID(sales.getSellerId());
            zfi_grj11_s_004.setODENMESI_GEREKEN_TUTAR(sales.getSellerClaimAmount());
            zfi_grj11_s_004.setBLOKE_TUTAR(new BigDecimal("0"));
            zfi_grj11_s_004.setODENECEK_TUTAR(sales.getSellerClaimAmount());

            log.info("zfi_grj11_s_004 Table Info : " + zfi_grj11_s_004.toString());

            BAPIRET2 payment04 = salesService.sendPayment(zfi_grj11_s_004);
            JSONObject pJson = new JSONObject();
            pJson.put("key", payment04.getTYPE());
            pJson.put("status", payment04.getMESSAGE_V1());
            pJson.put("message", payment04.getMESSAGE());
            jo.put("payment", pJson);

            log.info("zfi_grj11_s_004 Response Info : " + pJson.toString());

            if ("S".contains(commission.getTYPE()) && "S".contains(payment04.getTYPE())) {

                Boolean isUpdated = salesService.setSettlementStatus(sales.getOrderId(), 1);
                if (isUpdated) {
                    settlementStatus = 1;
                }
            }
        } else if (!isPaymentCancellation && SapTransactionTypeEnums.R.name().equals(transactionType)) {
            if ("S".contains(commission.getTYPE())) {
                Boolean isUpdated = salesService.setSettlementStatus(sales.getOrderId(), 1);
                if (isUpdated) {
                    settlementStatus = 1;
                }
            }
        } else if (isPaymentCancellation) {
            if ("S".contains(commission.getTYPE())) {
                Boolean isUpdated = salesService.setSettlementStatus(sales.getOrderId(), 0);
                if (isUpdated) {
                    settlementStatus = 0;
                }
            }
        }

        jo.put("settlementStatus", settlementStatus);
        //*******************************************************************//

        return jo;
    }

    @CrossOrigin
    @GetMapping(value = "/campaign-and-addtional-services")
    @PreAuthorize("@securityService.hasAccess(#token,'/sales/SalesListing','read','/sales/SalesDetail','read')")
    public ResponseEntity<CampaignAndAdditionalServiceDTO> findCampaignAndAdditionalServices(@RequestHeader(value = "Authorization") String token, @RequestParam(value = "carId") String carId) throws NotFoundException, UnAuthorizedException {
        return new ResponseEntity<>(garageService.findCampaignAndAdditionalServices(carId), HttpStatus.OK);
    }
}