Skip to content

Commit

Permalink
pfs-116 changing post to a get
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicholassully committed Aug 12, 2024
1 parent 9f111f2 commit cafb428
Show file tree
Hide file tree
Showing 15 changed files with 110 additions and 89 deletions.
2 changes: 1 addition & 1 deletion adrs/0002-new-finance-back-end.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ the source of truth for payments moving to us from SOP. We are therefore replaci
## Decision

This will be a new Front End service following our established Golang FE pattern. The web pages it serves will have two
separate functions: Uploading files for processing, and downloading reports. Reportsing will be broken out into a separate
separate functions: Uploading files for processing, and downloading reports. Reporting will be broken out into a separate
microservice, as it has a defined scope and will allow us to provide resources for potentially long-running database queries
without impacting other services. The architecture for processing files will depend on the file and how coupled the data
are with existing processes.
Expand Down
28 changes: 23 additions & 5 deletions internal/api/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ func (e ClientError) Error() string {
return string(e)
}

func NewApiClient(httpClient HTTPClient, siriusUrl string) (*ApiClient, error) {
func NewApiClient(httpClient HTTPClient, siriusUrl string, backendUrl string) (*ApiClient, error) {
return &ApiClient{
http: httpClient,
siriusUrl: siriusUrl,
http: httpClient,
siriusUrl: siriusUrl,
backendUrl: backendUrl,
}, nil
}

Expand All @@ -34,8 +35,9 @@ type HTTPClient interface {
}

type ApiClient struct {
http HTTPClient
siriusUrl string
http HTTPClient
siriusUrl string
backendUrl string
}

type StatusError struct {
Expand Down Expand Up @@ -68,6 +70,22 @@ func (c *ApiClient) newSiriusRequest(ctx Context, method, path string, body io.R
return req, err
}

func (c *ApiClient) newBackendRequest(ctx Context, method, path string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx.Context, method, c.backendUrl+path, body)
if err != nil {
return nil, err
}

for _, c := range ctx.Cookies {
req.AddCookie(c)
}

req.Header.Add("OPG-Bypass-Membrane", "1")
req.Header.Add("X-XSRF-TOKEN", ctx.XSRFToken)

return req, err
}

func newStatusError(resp *http.Response) StatusError {
return StatusError{
Code: resp.StatusCode,
Expand Down
4 changes: 2 additions & 2 deletions internal/api/submit_download.go → internal/api/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"net/http"
)

func (c *ApiClient) SubmitDownload(ctx Context, reportType string, reportJournalType string, reportScheduleType string, reportAccountType string, reportDebtType string, dateField string, dateFromField string, dateToField string, emailField string) error {
func (c *ApiClient) Download(ctx Context, reportType string, reportJournalType string, reportScheduleType string, reportAccountType string, reportDebtType string, dateField string, dateFromField string, dateToField string, emailField string) error {
var body bytes.Buffer
var dateTransformed *model.Date
var toDateTransformed *model.Date
Expand Down Expand Up @@ -43,7 +43,7 @@ func (c *ApiClient) SubmitDownload(ctx Context, reportType string, reportJournal
return err
}

req, err := c.newSiriusRequest(ctx, http.MethodPost, "/downloads", &body)
req, err := c.newBackendRequest(ctx, http.MethodGet, "/downloads", &body)

if err != nil {
return err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

func TestSubmitDownload(t *testing.T) {
mockClient := SetUpTest()
client, _ := NewApiClient(mockClient, "http://localhost:3000")
client, _ := NewApiClient(mockClient, "http://localhost:3000", "")

data := `{
"reportType": "AccountsReceivable",
Expand All @@ -38,7 +38,7 @@ func TestSubmitDownload(t *testing.T) {
}, nil
}

err := client.SubmitDownload(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")
err := client.Download(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")
assert.Equal(t, nil, err)
}

Expand All @@ -48,9 +48,9 @@ func TestSubmitDownloadUnauthorised(t *testing.T) {
}))
defer svr.Close()

client, _ := NewApiClient(http.DefaultClient, svr.URL)
client, _ := NewApiClient(http.DefaultClient, svr.URL, svr.URL)

err := client.SubmitDownload(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")
err := client.Download(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")

assert.Equal(t, ErrUnauthorized.Error(), err.Error())
}
Expand All @@ -61,20 +61,20 @@ func TestSubmitDownloadReturns500Error(t *testing.T) {
}))
defer svr.Close()

client, _ := NewApiClient(http.DefaultClient, svr.URL)
client, _ := NewApiClient(http.DefaultClient, svr.URL, svr.URL)

err := client.SubmitDownload(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")
err := client.Download(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")

assert.Equal(t, StatusError{
Code: http.StatusInternalServerError,
URL: svr.URL + "/supervision-api/v1/downloads",
Method: http.MethodPost,
URL: svr.URL + "/downloads",
Method: http.MethodGet,
}, err)
}

func TestSubmitDownloadReturnsBadRequestError(t *testing.T) {
mockClient := SetUpTest()
client, _ := NewApiClient(mockClient, "http://localhost:3000")
client, _ := NewApiClient(mockClient, "http://localhost:3000", "")

json := `
{"reasons":["StartDate","EndDate"]}
Expand All @@ -89,7 +89,7 @@ func TestSubmitDownloadReturnsBadRequestError(t *testing.T) {
}, nil
}

err := client.SubmitDownload(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")
err := client.Download(getContext(nil), "AccountsReceivable", "", "", "BadDebtWriteOffReport", "", "11/05/2024", "01/04/2024", "31/03/2025", "[email protected]")

expectedError := model.ValidationError{Message: "", Errors: model.ValidationErrors{"EndDate": map[string]string{"EndDate": "EndDate"}, "StartDate": map[string]string{"StartDate": "StartDate"}}}
assert.Equal(t, expectedError, err)
Expand All @@ -111,9 +111,9 @@ func TestSubmitDownloadReturnsValidationError(t *testing.T) {
}))
defer svr.Close()

client, _ := NewApiClient(http.DefaultClient, svr.URL)
client, _ := NewApiClient(http.DefaultClient, svr.URL, svr.URL)

err := client.SubmitDownload(getContext(nil), "", "", "", "", "", "", "", "", "")
err := client.Download(getContext(nil), "", "", "", "", "", "", "", "", "")
expectedError := model.ValidationError{Message: "", Errors: model.ValidationErrors{"ReportType": map[string]string{"required": "Please select a report type"}}}
assert.Equal(t, expectedError, err.(model.ValidationError))
}
6 changes: 0 additions & 6 deletions internal/model/journal_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package model
var ReportJournalTypes = []ReportJournalType{
ReportTypeReceiptTransactions,
ReportTypeNonReceiptTransactions,
ReportTypeMOTOCardPayments,
}

type ReportJournalType int
Expand All @@ -12,7 +11,6 @@ const (
ReportTypeUnknown ReportJournalType = iota
ReportTypeReceiptTransactions
ReportTypeNonReceiptTransactions
ReportTypeMOTOCardPayments
)

func (i ReportJournalType) String() string {
Expand All @@ -25,8 +23,6 @@ func (i ReportJournalType) Translation() string {
return "Receipt Transactions"
case ReportTypeNonReceiptTransactions:
return "Non Receipt Transactions"
case ReportTypeMOTOCardPayments:
return "Accounts Receivable"
default:
return ""
}
Expand All @@ -38,8 +34,6 @@ func (i ReportJournalType) Key() string {
return "ReceiptTransactions"
case ReportTypeNonReceiptTransactions:
return "NonReceiptTransactions"
case ReportTypeMOTOCardPayments:
return "AccountsReceivable"
default:
return ""
}
Expand Down
6 changes: 6 additions & 0 deletions internal/model/schedule_type.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package model

var ReportScheduleTypes = []ReportScheduleType{
ReportTypeMOTOCardPayments,
ReportTypeOnlineCardPayments,
ReportOPGBACSTransfer,
ReportSupervisionBACSTransfer,
Expand Down Expand Up @@ -33,6 +34,7 @@ type ReportScheduleType int

const (
ReportScheduleTypeUnknown ReportScheduleType = iota
ReportTypeMOTOCardPayments
ReportTypeOnlineCardPayments
ReportOPGBACSTransfer
ReportSupervisionBACSTransfer
Expand Down Expand Up @@ -67,6 +69,8 @@ func (i ReportScheduleType) String() string {

func (i ReportScheduleType) Translation() string {
switch i {
case ReportTypeMOTOCardPayments:
return "Accounts Receivable"
case ReportTypeOnlineCardPayments:
return "Online Card Payments"
case ReportOPGBACSTransfer:
Expand Down Expand Up @@ -126,6 +130,8 @@ func (i ReportScheduleType) Translation() string {

func (i ReportScheduleType) Key() string {
switch i {
case ReportTypeMOTOCardPayments:
return "Accounts Receivable"
case ReportTypeOnlineCardPayments:
return "OnlineCardPayments"
case ReportOPGBACSTransfer:
Expand Down
50 changes: 50 additions & 0 deletions internal/server/download.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package server

import (
"errors"
"github.com/opg-sirius-finance-admin/internal/api"
"github.com/opg-sirius-finance-admin/internal/model"
"github.com/opg-sirius-finance-admin/internal/util/util"
"net/http"
)

type DownloadHandler struct {
router
}

func (h *DownloadHandler) render(v AppVars, w http.ResponseWriter, r *http.Request) error {
ctx := getContext(r)
params := r.URL.Query()

var (
reportType = params.Get("reportType")
reportJournalType = params.Get("reportJournalType")
reportScheduleType = params.Get("reportScheduleType")
reportAccountType = params.Get("reportAccountType")
reportDebtType = params.Get("reportDebtType")
dateField = params.Get("dateField")
dateFromField = params.Get("dateFromField")
dateToField = params.Get("dateToField")
emailField = params.Get("emailField")
)

err := h.Client().Download(ctx, reportType, reportJournalType, reportScheduleType, reportAccountType, reportDebtType, dateField, dateFromField, dateToField, emailField)

if err != nil {
var (
valErr model.ValidationError
stErr api.StatusError
)
if errors.As(err, &valErr) {
data := AppVars{Errors: util.RenameErrors(valErr.Errors)}
w.WriteHeader(http.StatusUnprocessableEntity)
err = h.execute(w, r, data)
} else if errors.As(err, &stErr) {
data := AppVars{Error: stErr.Error()}
w.WriteHeader(stErr.Code)
err = h.execute(w, r, data)
}
}

return err
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"testing"
)

func TestSubmitManualInvoiceSuccess(t *testing.T) {
func TestDownloadSuccess(t *testing.T) {
form := url.Values{
"reportType": {"AccountsReceivable"},
"reportJournalType": {""},
Expand All @@ -27,7 +27,7 @@ func TestSubmitManualInvoiceSuccess(t *testing.T) {
ro := &mockRoute{client: client}

w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodPost, "/download", strings.NewReader(form.Encode()))
r, _ := http.NewRequest(http.MethodGet, "/download", strings.NewReader(form.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.SetPathValue("clientId", "1")

Expand All @@ -37,14 +37,14 @@ func TestSubmitManualInvoiceSuccess(t *testing.T) {

appVars.EnvironmentVars.Prefix = "prefix"

sut := SubmitDownloadHandler{ro}
sut := DownloadHandler{ro}

err := sut.render(appVars, w, r)

assert.Nil(t, err)
}

func TestSubmitDownloadValidationErrors(t *testing.T) {
func TestDownloadValidationErrors(t *testing.T) {
assert := assert.New(t)
client := &mockApiClient{}
ro := &mockRoute{client: client}
Expand All @@ -60,15 +60,15 @@ func TestSubmitDownloadValidationErrors(t *testing.T) {
}

w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodPost, "/invoices", nil)
r, _ := http.NewRequest(http.MethodGet, "/download", nil)
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.SetPathValue("clientId", "1")

appVars := AppVars{
Path: "/add",
}

sut := SubmitDownloadHandler{ro}
sut := DownloadHandler{ro}
err := sut.render(appVars, w, r)
assert.Nil(err)
assert.Equal("422 Unprocessable Entity", w.Result().Status)
Expand Down
2 changes: 2 additions & 0 deletions internal/server/environment_vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type EnvironmentVars struct {
WebDir string
SiriusURL string
SiriusPublicURL string
BackendUrl string
Prefix string
}

Expand All @@ -19,6 +20,7 @@ func NewEnvironmentVars() EnvironmentVars {
SiriusURL: getEnv("SIRIUS_URL", "http://host.docker.internal:8080"),
SiriusPublicURL: getEnv("SIRIUS_PUBLIC_URL", ""),
Prefix: getEnv("PREFIX", ""),
BackendUrl: getEnv("BACKEND_URL", ""),
}
}

Expand Down
4 changes: 2 additions & 2 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

type ApiClient interface {
SubmitDownload(api.Context, string, string, string, string, string, string, string, string, string) error
Download(api.Context, string, string, string, string, string, string, string, string, string) error
}

type router interface {
Expand All @@ -40,7 +40,7 @@ func New(logger *slog.Logger, client ApiClient, templates map[string]*template.T
handleMux("GET /uploads", &GetUploadsHandler{&route{client: client, tmpl: templates["uploads.gotmpl"], partial: "uploads"}})
handleMux("GET /annual-invoicing-letters", &GetAnnualInvoicingLettersHandler{&route{client: client, tmpl: templates["annual_invoicing_letters.gotmpl"], partial: "annual-invoicing-letters"}})

handleMux("POST /downloads", &SubmitDownloadHandler{&route{client: client, tmpl: templates["downloads.gotmpl"], partial: "error-summary"}})
handleMux("GET /download", &DownloadHandler{&route{client: client, tmpl: templates["downloads.gotmpl"], partial: "error-summary"}})

mux.Handle("/health-check", healthCheck())

Expand Down
2 changes: 1 addition & 1 deletion internal/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ type mockApiClient struct {
error error //nolint:golint,unused
}

func (m mockApiClient) SubmitDownload(context api.Context, s string, s2 string, s3 string, s4 string, s5 string, s6 string, s7 string, s8 string, s9 string) error {
func (m mockApiClient) Download(context api.Context, s string, s2 string, s3 string, s4 string, s5 string, s6 string, s7 string, s8 string, s9 string) error {
return m.error
}
Loading

0 comments on commit cafb428

Please sign in to comment.