feat(hardlink): unify kiosk payments and finalize legacy cleanup

This commit is contained in:
2026-11-04 17:43:10 +00:00
parent 568adc034b
commit 814d87768d
57 changed files with 3624 additions and 1762 deletions
+116
View File
@@ -0,0 +1,116 @@
package paymentapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
// Execute sends exactly one request. Missing, malformed or interrupted results are
// uncertain; this client never retries a financial request.
func Execute(ctx context.Context, client *http.Client, baseURL, operation string, request Request, onStatus func(string)) (Result, error) {
var path string
switch operation {
case Sale:
path = SalePath
if request.Amount <= 0 {
return Result{}, errors.New("sale amount must be positive")
}
case Preauth:
path = PreauthPath
if request.Amount < 0 {
return Result{}, errors.New("preauth amount must not be negative")
}
default:
return Result{}, errors.New("invalid terminal operation")
}
if client == nil || strings.TrimSpace(baseURL) == "" {
return Result{}, errors.New("terminal client is not configured")
}
body, err := json.Marshal(request)
if err != nil {
return Result{}, fmt.Errorf("encode terminal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(baseURL, `/\`)+path, bytes.NewReader(body))
if err != nil {
return Result{}, errors.New("invalid terminal endpoint")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/x-ndjson")
response, err := client.Do(req)
if err != nil {
if ctx.Err() != nil {
return Result{}, fmt.Errorf("terminal request interrupted: %w", ctx.Err())
}
if errors.Is(err, context.DeadlineExceeded) {
return Result{}, fmt.Errorf("terminal request interrupted: %w", context.DeadlineExceeded)
}
if errors.Is(err, context.Canceled) {
return Result{}, fmt.Errorf("terminal request interrupted: %w", context.Canceled)
}
// Do not expose a transport error that may contain a URL or raw payload.
return Result{}, errors.New("terminal request failed; outcome is uncertain")
}
defer response.Body.Close()
if !strings.HasPrefix(response.Header.Get("Content-Type"), "application/x-ndjson") {
return Result{}, fmt.Errorf("terminal returned an invalid response contract (HTTP %d)", response.StatusCode)
}
decoder := json.NewDecoder(response.Body)
for {
var frame struct {
Frame
Legacy json.RawMessage `json:"response"`
}
if err := decoder.Decode(&frame); err != nil {
if ctx.Err() != nil {
return Result{}, fmt.Errorf("terminal stream interrupted: %w", ctx.Err())
}
if errors.Is(err, io.EOF) {
return Result{}, errors.New("terminal stream ended before a final result")
}
return Result{}, errors.New("terminal stream is invalid; outcome is uncertain")
}
if len(frame.Legacy) != 0 {
return Result{}, errors.New("terminal returned a legacy result contract")
}
switch frame.Type {
case "status":
if frame.Code == "" || frame.Result != nil {
return Result{}, errors.New("invalid terminal status frame")
}
if onStatus != nil {
onStatus(frame.Code)
}
case "result":
if frame.Result == nil || frame.Code != "" {
return Result{}, errors.New("invalid terminal result frame")
}
result := *frame.Result
switch result.Outcome {
case "approved", "declined", "cancelled", "timeout", "error", "unknown":
default:
return Result{}, errors.New("invalid terminal outcome")
}
if result.HTTPStatus < 100 || result.HTTPStatus > 599 {
return Result{}, errors.New("invalid terminal operation status")
}
if result.Outcome == "approved" && (result.HTTPStatus < 200 || result.HTTPStatus >= 300 || response.StatusCode < 200 || response.StatusCode >= 300 || result.Retryable) {
return Result{}, errors.New("contradictory terminal approval")
}
if result.Outcome == "unknown" && result.Retryable {
return Result{}, errors.New("uncertain terminal result cannot permit retry")
}
if response.StatusCode < 200 || response.StatusCode >= 300 || result.HTTPStatus < 200 || result.HTTPStatus >= 300 {
return result, fmt.Errorf("terminal operation failed (HTTP %d, operation %d)", response.StatusCode, result.HTTPStatus)
}
return result, nil
default:
return Result{}, errors.New("invalid terminal frame type")
}
}
}
+146
View File
@@ -0,0 +1,146 @@
package paymentapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
)
func TestExecuteUsesOneContractForSaleAndPreauth(t *testing.T) {
for _, operation := range []string{Sale, Preauth} {
t.Run(operation, func(t *testing.T) {
input := Request{Reference: "SYNTH-BOOK", Amount: 2500, Currency: "GBP", CheckoutDate: "12 Oct 2030"}
if operation == Sale {
input.RequiredPreauth = &PreauthRequirement{Amount: 5000, CheckoutDate: "12 Oct 2030"}
}
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.Method != http.MethodPost || r.URL.Path != "/api/payment/"+operation {
t.Errorf("Execute(%q) sent %s %s, want POST modern operation", operation, r.Method, r.URL.Path)
}
var got Request
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
t.Error(err)
return
}
if !reflect.DeepEqual(got, input) {
t.Errorf("Execute(%q) request=%+v, want %+v", operation, got, input)
}
if r.Header.Get("Accept") != "application/x-ndjson" || r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Execute(%q) headers=%v, want JSON request/NDJSON response", operation, r.Header)
}
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
encoder := json.NewEncoder(w)
for _, frame := range []Frame{{Type: "status", Code: "PAYMENT_PROCESSING"}, {Type: "status", Code: "FUTURE_OBSERVATIONAL_CODE"}, {Type: "result", Result: &Result{Outcome: "approved", HTTPStatus: 200, Provider: "FutureProcessor", AmountMinor: 2500, TransactionReference: "SYNTH-REFERENCE", CardType: "Visa"}}} {
if err := encoder.Encode(frame); err != nil {
t.Error(err)
return
}
}
}))
t.Cleanup(server.Close)
var progress []string
got, err := Execute(context.Background(), server.Client(), server.URL, operation, input, func(code string) { progress = append(progress, code) })
if err != nil || got.Outcome != "approved" || got.TransactionReference != "SYNTH-REFERENCE" || calls != 1 {
t.Fatalf("Execute(%q)=%+v/%v calls=%d, want one approved request", operation, got, err, calls)
}
if !reflect.DeepEqual(progress, []string{"PAYMENT_PROCESSING", "FUTURE_OBSERVATIONAL_CODE"}) {
t.Errorf("Execute(%q) progress=%v, want observed codes in order", operation, progress)
}
})
}
}
type testTransport func(*http.Request) (*http.Response, error)
func (f testTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
type trackedBody struct {
io.Reader
closed bool
}
func (b *trackedBody) Close() error { b.closed = true; return nil }
func TestExecuteRejectsIncompleteOrContradictoryResultsAndClosesBodies(t *testing.T) {
tests := []struct {
name, body string
status int
}{
{"eof", `{"type":"status","code":"PAYMENT_APPROVED"}`, 200},
{"malformed", `{"type":`, 200},
{"legacy", `{"type":"result","response":{"status":{"code":200},"data":"/successful"}}`, 200},
{"mixed", `{"type":"result","result":{"outcome":"approved","httpStatus":200},"response":{}}`, 200},
{"empty_status", `{"type":"status","code":""}`, 200},
{"status_result", `{"type":"status","code":"X","result":{"outcome":"approved","httpStatus":200}}`, 200},
{"unknown_frame", `{"type":"other"}`, 200},
{"unknown_outcome", `{"type":"result","result":{"outcome":"maybe","httpStatus":200}}`, 200},
{"invalid_status", `{"type":"result","result":{"outcome":"approved","httpStatus":0}}`, 200},
{"http_approval_conflict", `{"type":"result","result":{"outcome":"approved","httpStatus":200}}`, 502},
{"operation_approval_conflict", `{"type":"result","result":{"outcome":"approved","httpStatus":502}}`, 200},
{"retryable_approval", `{"type":"result","result":{"outcome":"approved","httpStatus":200,"retryable":true}}`, 200},
{"retryable_unknown", `{"type":"result","result":{"outcome":"unknown","httpStatus":200,"retryable":true}}`, 200},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
body := &trackedBody{Reader: strings.NewReader(test.body)}
calls := 0
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: test.status, Header: http.Header{"Content-Type": []string{"application/x-ndjson"}}, Body: body}, nil
})}
_, err := Execute(context.Background(), client, "http://synthetic.invalid", Sale, Request{Amount: 100}, nil)
if err == nil || !body.closed || calls != 1 {
t.Errorf("Execute(%s) error=%v closed=%t calls=%d, want error/closed/one request", test.name, err, body.closed, calls)
}
})
}
}
func TestExecuteProgressCannotApproveOrRetryUnknown(t *testing.T) {
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/x-ndjson"}}, Body: io.NopCloser(strings.NewReader("{\"type\":\"status\",\"code\":\"PAYMENT_APPROVED\"}\n{\"type\":\"result\",\"result\":{\"outcome\":\"unknown\",\"httpStatus\":200}}"))}, nil
})}
got, err := Execute(context.Background(), client, "http://synthetic.invalid", Sale, Request{Amount: 100}, nil)
if err != nil || got.Outcome != "unknown" || got.Retryable {
t.Errorf("Execute(progress approved then unknown)=%+v/%v, want nonretryable unknown", got, err)
}
}
func TestExecutePreservesCancellationWithoutLeakingTransportDiagnostics(t *testing.T) {
for _, cause := range []error{context.Canceled, context.DeadlineExceeded} {
t.Run(cause.Error(), func(t *testing.T) {
calls := 0
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) {
calls++
return nil, fmt.Errorf("synthetic-private-payload: %w", cause)
})}
_, err := Execute(context.Background(), client, "http://synthetic.invalid", Sale, Request{Amount: 100}, nil)
if !errors.Is(err, cause) || strings.Contains(err.Error(), "synthetic-private-payload") || calls != 1 {
t.Errorf("Execute(transport %v)=%v calls=%d, want sanitized wrapped cause and one attempt", cause, err, calls)
}
})
}
}
func TestExecuteRejectsInvalidRequestsWithoutDispatch(t *testing.T) {
for _, test := range []struct {
operation string
amount int64
}{{Sale, 0}, {Sale, -1}, {Preauth, -1}, {"refund", 1}} {
calls := 0
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) { calls++; return nil, errors.New("must not dispatch") })}
_, err := Execute(context.Background(), client, "http://synthetic.invalid", test.operation, Request{Amount: test.amount}, nil)
if err == nil || calls != 0 {
t.Errorf("Execute(%q,%d) error=%v calls=%d, want validation error without dispatch", test.operation, test.amount, err, calls)
}
}
}
+55
View File
@@ -0,0 +1,55 @@
// Package paymentapi defines the modern Hardlink terminal contract and its HTTP client.
// It contains no provider selection, PMS posting or guest-journey logic.
package paymentapi
const (
Sale = "sale"
Preauth = "preauth"
SalePath = "/api/payment/sale"
PreauthPath = "/api/payment/preauth"
)
// PreauthRequirement describes a later required hold; validating it never executes it.
type PreauthRequirement struct {
Amount int64 `json:"amount"`
CheckoutDate string `json:"checkoutDate,omitempty"`
}
// Request uses integer minor units and currency supplied by CMS.
type Request struct {
Reference string `json:"reference,omitempty"`
Amount int64 `json:"amount"`
Currency string `json:"currency,omitempty"`
CheckoutDate string `json:"checkoutDate,omitempty"`
RequiredPreauth *PreauthRequirement `json:"requiredPreauth,omitempty"`
}
// Result is authoritative terminal outcome and metadata, never a PMS description.
// CurrencyCode is configured bookkeeping currency, not settlement-currency evidence.
type Result struct {
Outcome string `json:"outcome"`
HTTPStatus int `json:"httpStatus"`
Reason string `json:"reason,omitempty"`
Retryable bool `json:"retryable"`
Message string `json:"message,omitempty"`
Provider string `json:"provider,omitempty"`
AmountMinor int64 `json:"amountMinor"`
CurrencyCode string `json:"currencyCode,omitempty"`
TransactionReference string `json:"transactionReference,omitempty"`
CardType string `json:"cardType,omitempty"`
MaskedCardNumber string `json:"maskedCardNumber,omitempty"`
ExpiryDate string `json:"expiryDate,omitempty"`
CardHash string `json:"cardHash,omitempty"`
CardReference string `json:"cardReference,omitempty"`
ReceiptNumber string `json:"receiptNumber,omitempty"`
SequenceNumber string `json:"sequenceNumber,omitempty"`
AuthorizationCode string `json:"authorizationCode,omitempty"`
LastFour string `json:"lastFour,omitempty"`
}
// Frame carries observational progress or one final result.
type Frame struct {
Type string `json:"type"`
Code string `json:"code,omitempty"`
Result *Result `json:"result,omitempty"`
}