github.com/companieshouse/lfp-pay-api@v0.0.0-20230203133422-0ca455cd79f9/handlers/penalties.go (about)

     1  package handlers
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/companieshouse/chs.go/log"
    10  	"github.com/companieshouse/lfp-pay-api-core/models"
    11  	"github.com/companieshouse/lfp-pay-api/service"
    12  	"github.com/companieshouse/lfp-pay-api/utils"
    13  	"github.com/gorilla/mux"
    14  )
    15  
    16  // HandleGetPenalties retrieves the penalty details for the supplied company number from e5
    17  func HandleGetPenalties(w http.ResponseWriter, req *http.Request) {
    18  	log.InfoR(req, "start GET penalties request from e5")
    19  
    20  	// Check for a company number in request
    21  	vars := mux.Vars(req)
    22  	companyNumber, err := utils.GetCompanyNumberFromVars(vars)
    23  	if err != nil {
    24  		log.ErrorR(req, err)
    25  		m := models.NewMessageResponse("company number is not in request context")
    26  		utils.WriteJSONWithStatus(w, req, m, http.StatusBadRequest)
    27  		return
    28  	}
    29  
    30  	companyNumber = strings.ToUpper(companyNumber)
    31  
    32  	// Call service layer to handle request to E5
    33  	transactionListResponse, responseType, err := service.GetPenalties(companyNumber)
    34  	if err != nil {
    35  		log.ErrorR(req, fmt.Errorf("error calling e5 to get transactions: %v", err))
    36  		switch responseType {
    37  		case service.InvalidData:
    38  			m := models.NewMessageResponse("failed to read finance transactions")
    39  			utils.WriteJSONWithStatus(w, req, m, http.StatusBadRequest)
    40  			return
    41  		case service.Error:
    42  		default:
    43  			m := models.NewMessageResponse("there was a problem communicating with the finance backend")
    44  			utils.WriteJSONWithStatus(w, req, m, http.StatusInternalServerError)
    45  			return
    46  		}
    47  	}
    48  
    49  	// response body contains fully decorated REST model
    50  	w.Header().Set("Content-Type", "application/json")
    51  	w.WriteHeader(http.StatusOK)
    52  
    53  	err = json.NewEncoder(w).Encode(transactionListResponse)
    54  	if err != nil {
    55  		log.ErrorR(req, fmt.Errorf("error writing response: %v", err))
    56  		return
    57  	}
    58  
    59  	log.InfoR(req, "Successfully GET penalties from e5", log.Data{"company_number": companyNumber})
    60  }