feat(hardlink): unify kiosk payments and finalize legacy cleanup
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type failedDiagnosticWriter struct{ header http.Header }
|
||||
|
||||
func (w *failedDiagnosticWriter) Header() http.Header { return w.header }
|
||||
func (*failedDiagnosticWriter) WriteHeader(int) {}
|
||||
func (*failedDiagnosticWriter) Flush() {}
|
||||
func (*failedDiagnosticWriter) Write([]byte) (int, error) {
|
||||
return 0, errors.New("https://user:WRITE_PRIVATE_MARKER@gateway.invalid/4111111111111111")
|
||||
}
|
||||
|
||||
func TestTrustReconciliationLogsPreserveIdentityAndFinancialOutcome(t *testing.T) {
|
||||
for _, preauth := range []bool{false, true} {
|
||||
for _, mode := range []string{"unknown", "unknown-transport", "unknown-write-failure", "approved-client-closed", "approved-write-failure"} {
|
||||
operation := "sale"
|
||||
if preauth {
|
||||
operation = "preauth"
|
||||
}
|
||||
t.Run(operation+"/"+mode, func(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
logger := log.StandardLogger()
|
||||
oldOutput, oldFormatter := logger.Out, logger.Formatter
|
||||
logger.SetOutput(&output)
|
||||
logger.SetFormatter(&log.JSONFormatter{})
|
||||
t.Cleanup(func() { logger.SetOutput(oldOutput); logger.SetFormatter(oldFormatter) })
|
||||
unknown := strings.HasPrefix(mode, "unknown")
|
||||
financial, lookups, prints := 0, 0, 0
|
||||
var ref string
|
||||
var tokens []string
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
client, err := trustpayments.New(trustpayments.Config{
|
||||
BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "SYNTH-SITE", Password: "PASSWORD_PRIVATE_MARKER", Terminal: "SYNTH-PED", Currency: "GBP", Timezone: "Europe/London",
|
||||
Transport: trustFixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||
var input map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tokens = append(tokens, r.Header.Get("token"))
|
||||
if strings.HasSuffix(r.URL.Path, "/status") {
|
||||
lookups++
|
||||
if input["refid"] != ref {
|
||||
t.Errorf("Status RefID=%q, want original %q", input["refid"], ref)
|
||||
}
|
||||
} else {
|
||||
financial++
|
||||
ref = input["refid"]
|
||||
if !strings.HasSuffix(r.URL.Path, "/"+operation) || input["type"] != operation {
|
||||
t.Errorf("Financial request path/type=%s/%s, want %s", r.URL.Path, input["type"], operation)
|
||||
}
|
||||
if mode == "approved-client-closed" {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
if mode == "unknown-transport" {
|
||||
return nil, errors.New("https://user:PASSWORD_PRIVATE_MARKER@gateway.invalid/4111111111111111/JWT_PRIVATE_MARKER")
|
||||
}
|
||||
body := map[string]any{"refid": ref, "siteid": "SYNTH-SITE", "terminalserialnumber": "SYNTH-PED", "type": operation, "amount": "25.00", "finalamount": "25.00", "resultcode": "Approved", "authcode": "AUTH_PRIVATE_MARKER", "cardtype": "Visa", "last4": "1133", "receipt": "PAN: 4111111111111111\nRAW_PRIVATE_MARKER"}
|
||||
if unknown {
|
||||
body["errorcode"], body["errormessage"] = 2003, "RAW_PRIVATE_MARKER JWT_PRIVATE_MARKER"
|
||||
}
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(encoded)), Header: make(http.Header)}, nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
app := &App{cfg: &config.ConfigRec{Hotel: "SYNTH-HOTEL", Kiosk: 9}, isPayment: true}
|
||||
app.SetPaymentService(paymentsvc.NewService(&trustpayments.Processor{Client: client, PrintReceipt: func(string) { prints++ }}))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/payment/"+operation, strings.NewReader(`{"reference":"SYNTH-BOOK","amount":2500,"currency":"GBP"}`)).WithContext(ctx)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
var writer http.ResponseWriter = recorder
|
||||
if strings.Contains(mode, "write-failure") {
|
||||
writer = &failedDiagnosticWriter{header: make(http.Header)}
|
||||
}
|
||||
app.streamPayment(writer, request, preauth)
|
||||
wantLookups, wantPrints, wantOutcome := 0, 1, "approved"
|
||||
if unknown {
|
||||
wantLookups, wantPrints, wantOutcome = 1, 0, "unknown"
|
||||
}
|
||||
if financial != 1 || lookups != wantLookups || prints != wantPrints || len(ref) != 32 {
|
||||
t.Fatalf("Trust(%s) financial/status/prints/ref=%d/%d/%d/%q, want 1/%d/%d and original RefID", mode, financial, lookups, prints, ref, wantLookups, wantPrints)
|
||||
}
|
||||
if unknown && !strings.Contains(mode, "write-failure") {
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if len(frames) == 0 {
|
||||
t.Fatal("Unknown payment stream is empty, want final result")
|
||||
}
|
||||
final := frames[len(frames)-1].Result
|
||||
if final == nil || final.Outcome != wantOutcome || final.Retryable || final.TransactionReference != ref {
|
||||
t.Errorf("Unknown terminal result=%+v, want unchanged nonretryable outcome and RefID %s", final, ref)
|
||||
}
|
||||
}
|
||||
var requestID string
|
||||
warnings := 0
|
||||
decoder := json.NewDecoder(strings.NewReader(output.String()))
|
||||
for {
|
||||
var entry map[string]any
|
||||
if err := decoder.Decode(&entry); err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if entry["level"] != "warning" {
|
||||
continue
|
||||
}
|
||||
warnings++
|
||||
id, _ := entry["request_id"].(string)
|
||||
if requestID == "" {
|
||||
requestID = id
|
||||
}
|
||||
if id == "" || id != requestID || entry["request_reference"] != "SYNTH-BOOK" || entry["transaction_reference"] != ref || entry["provider"] != "TrustPayments" || entry["operation"] != operation || entry["outcome"] != wantOutcome {
|
||||
t.Errorf("Reconciliation warning=%v, want same request ID, Trust RefID, provider, operation and financial outcome", entry)
|
||||
}
|
||||
}
|
||||
wantWarnings := 0
|
||||
if unknown {
|
||||
wantWarnings = 2
|
||||
}
|
||||
if strings.Contains(mode, "write-failure") || mode == "approved-client-closed" {
|
||||
wantWarnings++
|
||||
}
|
||||
if warnings != wantWarnings {
|
||||
t.Errorf("Trust(%s) reconciliation warnings=%d, want %d", mode, warnings, wantWarnings)
|
||||
}
|
||||
for _, secret := range append(tokens, "PASSWORD_PRIVATE_MARKER", "AUTH_PRIVATE_MARKER", "RAW_PRIVATE_MARKER", "JWT_PRIVATE_MARKER", "WRITE_PRIVATE_MARKER", "4111111111111111") {
|
||||
if secret != "" && strings.Contains(output.String(), secret) {
|
||||
t.Errorf("Trust(%s) diagnostics contain private fixture data", mode)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user