package handlers import ( "context" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "reflect" "strings" "sync/atomic" "testing" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types" ) func TestClassifyCreditCallInitialResult(t *testing.T) { for _, tc := range []struct { name, result, sdkError string want creditCallInitialResult }{ {name: "empty", want: creditCallInitialResult{kind: creditCallInitialUnknown}}, {name: "approval wins over cancellation error", result: "APPROVED", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialApproved}}, {name: "mixed-case approval wins over timeout", result: "Approved", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialApproved}}, {name: "ordinary decline", result: "DECLINED", sdkError: "InsufficientFunds", want: creditCallInitialResult{kind: creditCallInitialDeclined}}, {name: "declined cancellation", result: "DECLINED", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}}, {name: "declined cardholder timeout", result: "DECLINED", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}}, {name: "explicit cancellation", result: "CANCELLED", want: creditCallInitialResult{kind: creditCallInitialCancelled}}, {name: "alternate cancellation spelling", result: "Canceled", want: creditCallInitialResult{kind: creditCallInitialCancelled}}, {name: "SDK timeout", result: "ERROR", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}}, {name: "SDK cancellation", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}}, {name: "CLI wait expiry with SDK timeout", result: "TIMEOUT", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{}}, {name: "CLI wait expiry with SDK cancellation", result: "TIMEOUT", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{}}, {name: "unknown result", result: "UNKNOWN", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{}}, {name: "compound error", result: "ERROR", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: creditCallInitialResult{}}, {name: "case-sensitive SDK error", result: "ERROR", sdkError: "pinpadusercancelled", want: creditCallInitialResult{}}, } { t.Run(tc.name, func(t *testing.T) { input := creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{ {Key: types.TransactionResult, Value: tc.result}, {Key: types.Errors, Value: tc.sdkError}, }} if got := classifyCreditCallInitialResult(input); got != tc.want { t.Errorf("classifyCreditCallInitialResult(%q,%q)=%+v, want %+v", tc.result, tc.sdkError, got, tc.want) } }) } } func TestClassifyCreditCallInitialResultLastEntryWins(t *testing.T) { for _, tc := range []struct { name string entries []creditcall.EntryXML want creditCallInitialResult }{ {name: "no response fields", want: creditCallInitialResult{}}, {name: "last result is approval", entries: []creditcall.EntryXML{ {Key: types.TransactionResult, Value: "DECLINED"}, {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.TransactionResult, Value: "APPROVED"}, }, want: creditCallInitialResult{kind: creditCallInitialApproved}}, {name: "last result is declined cancellation", entries: []creditcall.EntryXML{ {Key: types.TransactionResult, Value: "APPROVED"}, {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.TransactionResult, Value: "DECLINED"}, }, want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}}, {name: "last error is unknown", entries: []creditcall.EntryXML{ {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.Errors, Value: "DeviceUnavailable"}, }, want: creditCallInitialResult{}}, {name: "last error is SDK timeout", entries: []creditcall.EntryXML{ {Key: types.Errors, Value: "DeviceUnavailable"}, {Key: types.Errors, Value: "CardHolderActionTimedOut"}, }, want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}}, {name: "description is not an SDK code", entries: []creditcall.EntryXML{ {Key: types.ErrorDescription, Value: "PinPadUserCancelled"}, }, want: creditCallInitialResult{}}, } { t.Run(tc.name, func(t *testing.T) { input := creditcall.TransactionResultXML{Entries: tc.entries} before := append([]creditcall.EntryXML(nil), input.Entries...) if got := classifyCreditCallInitialResult(input); got != tc.want { t.Errorf("classifyCreditCallInitialResult(%+v)=%+v, want %+v", input.Entries, got, tc.want) } if !reflect.DeepEqual(input.Entries, before) { t.Errorf("classifyCreditCallInitialResult mutated entries: got %+v, want %+v", input.Entries, before) } }) } } func TestCreditCallInitialSDKErrorClassification(t *testing.T) { for _, operation := range []string{"sale", "preauth"} { for _, tc := range []struct { name, result, sdkError, description, want, reason string retryable, resultPresent bool }{ {name: "missing result", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, {name: "empty result", resultPresent: true, sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, {name: "error result", result: "ERROR", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, {name: "mixed-case error result", result: "Error", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, {name: "CLI wait timeout", result: "TIMEOUT", sdkError: "Transaction timed out waiting for device response", want: "unknown"}, {name: "CLI timeout with conflicting SDK error", result: "TIMEOUT", sdkError: "CardHolderActionTimedOut", want: "unknown"}, {name: "other SDK error", result: "ERROR", sdkError: "DeviceUnavailable", want: "unknown"}, {name: "compound error", sdkError: "CardHolderActionTimedOut, DeviceUnavailable", want: "unknown"}, {name: "description only", description: "CardHolderActionTimedOut", sdkError: "DeviceUnavailable", want: "unknown"}, {name: "cardholder timeout with declined result", result: "DECLINED", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, {name: "cardholder timeout with mixed-case decline", result: "Declined", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, {name: "cancelled retains classification", result: "Cancelled", sdkError: "CardHolderActionTimedOut", want: "cancelled", retryable: true}, {name: "explicit cancellation", result: "CANCELLED", want: "cancelled", retryable: true}, {name: "alternate cancellation spelling", result: "CANCELED", want: "cancelled", retryable: true}, {name: "user cancel missing result", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, {name: "user cancel empty result", resultPresent: true, sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, {name: "user cancel error result", result: "ERROR", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, {name: "user cancel mixed-case error result", result: "Error", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, {name: "user cancel with CLI timeout", result: "TIMEOUT", sdkError: "PinPadUserCancelled", want: "unknown"}, {name: "user cancel with unknown result", result: "UNKNOWN", sdkError: "PinPadUserCancelled", want: "unknown"}, {name: "user cancel with declined result", result: "DECLINED", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, {name: "user cancel with mixed-case decline", result: "Declined", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, {name: "ordinary decline", result: "DECLINED", sdkError: "InsufficientFunds", want: "declined", retryable: true}, {name: "decline without SDK error", result: "DECLINED", want: "declined", retryable: true}, {name: "decline with compound timeout error", result: "DECLINED", sdkError: "CardHolderActionTimedOut, DeviceUnavailable", want: "declined", retryable: true}, {name: "decline with compound cancellation error", result: "DECLINED", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: "declined", retryable: true}, {name: "user cancel compound error", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: "unknown"}, {name: "user cancel description only", description: "PinPadUserCancelled", sdkError: "DeviceUnavailable", want: "unknown"}, } { t.Run(operation+"/"+tc.name, func(t *testing.T) { var starts, confirms atomic.Int32 fields := map[string]string{types.Errors: tc.sdkError, types.ReceiptDataCardholder: "synthetic initial receipt"} if tc.result != "" || tc.resultPresent { fields[types.TransactionResult] = tc.result } if tc.description != "" { fields[types.ErrorDescription] = tc.description } app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/start-transaction-stream/" { confirms.Add(1) t.Errorf("initial %s response reached unexpected path %q", operation, r.URL.Path) w.WriteHeader(http.StatusBadRequest) return } starts.Add(1) if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { t.Errorf("encode synthetic SDK result: %v", err) } }) var receipts []string app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) } recorder := httptest.NewRecorder() if operation == "preauth" { app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", "")) } else { app.salePayment(recorder, saleRequest(true)) } frames := decodePaymentStream(t, recorder.Body) if len(frames) != 1 || frames[0].Result == nil { t.Fatalf("%s(%s) frames=%+v, want one final result", operation, tc.name, frames) } final := frames[0].Result if final.Outcome != tc.want || final.Retryable != tc.retryable || final.HTTPStatus != http.StatusOK { t.Errorf("%s(%s) final=%+v, want %s retryable=%t HTTP 200", operation, tc.name, final, tc.want, tc.retryable) } if tc.want == "timeout" && (final.Reason != "cardholder_timeout" || final.Message != "Cardholder action timed out") { t.Errorf("%s(%s) reason/message=%q/%q, want sanitized cardholder timeout", operation, tc.name, final.Reason, final.Message) } if tc.reason != "" && (final.Reason != tc.reason || final.Message != "Transaction cancelled") { t.Errorf("%s(%s) reason/message=%q/%q, want %q/Transaction cancelled", operation, tc.name, final.Reason, final.Message, tc.reason) } if starts.Load() != 1 || confirms.Load() != 0 || !reflect.DeepEqual(receipts, []string{"synthetic initial receipt"}) { t.Errorf("%s(%s) starts/confirms/receipts=%d/%d/%v, want 1/0/[synthetic initial receipt]", operation, tc.name, starts.Load(), confirms.Load(), receipts) } }) } } } func TestCreditCallInitialSDKErrorRequiresCompleteResponse(t *testing.T) { for _, operation := range []string{"sale", "preauth"} { for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} { for _, failure := range []string{"transport loss", "interrupted execution", "truncated result", "error frame", "HTTP failure"} { t.Run(operation+"/"+sdkError+"/"+failure, func(t *testing.T) { app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { body := fmt.Sprintf(`{"type":"result","result":{"ERRORS":%q}}`, sdkError) switch failure { case "error frame": body = fmt.Sprintf("{\"type\":\"error\",\"error\":%q}\n", sdkError) case "HTTP failure": w.WriteHeader(http.StatusBadGateway) body += "\n" } if _, err := io.WriteString(w, body); err != nil { t.Errorf("write synthetic incomplete SDK result: %v", err) } }) transport := app.creditCallTransport var calls atomic.Int32 app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { calls.Add(1) if failure == "transport loss" { return nil, io.ErrUnexpectedEOF } if failure == "interrupted execution" { return nil, context.Canceled } return transport.RoundTrip(r) }) app.creditCallReceipt = func(string) { t.Error("incomplete SDK result printed a receipt") } recorder := httptest.NewRecorder() if operation == "preauth" { app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", "")) } else { app.salePayment(recorder, saleRequest(true)) } frames := decodePaymentStream(t, recorder.Body) if len(frames) != 1 || frames[0].Result == nil { t.Fatalf("%s(%s) frames=%+v, want one uncertain result", operation, failure, frames) } final := frames[0].Result if calls.Load() != 1 || final.Outcome != "unknown" || final.Retryable || final.HTTPStatus != http.StatusBadGateway || strings.Contains(final.Message, sdkError) { t.Errorf("%s(%s) calls/final=%d/%+v, want one dispatch and sanitized nonretryable uncertainty", operation, failure, calls.Load(), final) } }) } } } } func TestCreditCallInitialSDKErrorDuringConfirmationRemainsUncertain(t *testing.T) { for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} { for _, result := range []string{"", "ERROR", "TIMEOUT", "DECLINED", "CANCELLED", "CANCELED"} { t.Run(sdkError+"/confirmation result="+result, func(t *testing.T) { var starts, confirms atomic.Int32 app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/start-transaction-stream/" { starts.Add(1) fields := map[string]string{types.TransactionResult: "Approved", types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234"} if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { t.Errorf("encode initial approval: %v", err) } return } if r.URL.Path != "/confirm-transaction/" { t.Errorf("unexpected SDK path %q", r.URL.Path) w.WriteHeader(http.StatusBadRequest) return } confirms.Add(1) fields := map[string]string{types.TransactionResult: result, types.Errors: sdkError, types.ReceiptDataCardholder: "synthetic confirmation receipt"} if _, err := io.WriteString(w, chipDNAFixture(t, fields)); err != nil { t.Errorf("write confirmation result: %v", err) } }) var receipts []string app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) } recorder := httptest.NewRecorder() app.salePayment(recorder, saleRequest(true)) frames := decodePaymentStream(t, recorder.Body) if len(frames) != 1 || frames[0].Result == nil { t.Fatalf("confirmation(%q) frames=%+v, want one uncertain final result", result, frames) } final := frames[0].Result if final.Outcome != "unknown" || final.Retryable { t.Errorf("confirmation(%q) final=%+v, want nonretryable uncertainty after initial approval", result, final) } if starts.Load() != 1 || confirms.Load() != 1 || !reflect.DeepEqual(receipts, []string{"synthetic confirmation receipt"}) { t.Errorf("confirmation(%q) starts/confirms/receipts=%d/%d/%v, want 1/1/[synthetic confirmation receipt]", result, starts.Load(), confirms.Load(), receipts) } }) } } } func TestCreditCallInitialApprovalPreservesExecutionWithSDKError(t *testing.T) { for _, operation := range []string{"sale", "preauth"} { for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} { t.Run(operation+"/"+sdkError, func(t *testing.T) { var starts, confirms atomic.Int32 app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/start-transaction-stream/" { starts.Add(1) fields := map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "SALE", types.Errors: sdkError, types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234", types.ReceiptDataCardholder: "synthetic initial receipt"} if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { t.Errorf("encode initial approval: %v", err) } return } if r.URL.Path != "/confirm-transaction/" { t.Errorf("unexpected SDK path %q", r.URL.Path) w.WriteHeader(http.StatusBadRequest) return } confirms.Add(1) if _, err := io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: "APPROVED", types.ReceiptDataCardholder: "synthetic confirmation receipt"})); err != nil { t.Errorf("write confirmation approval: %v", err) } }) var receipts []string app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) } recorder := httptest.NewRecorder() wantConfirms, wantReceipt := int32(1), "synthetic confirmation receipt" if operation == "preauth" { database := preauthTestDatabase(t, app) app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", "2026-11-10 00:00:00 +0000")) persisted := waitPreauthInsert(t, database) if persisted["TxnReference"] != "SYNTH-APPROVED" || persisted["TotalMinorUnits"] != "1234" { t.Errorf("approved PREAUTH persisted=%v, want unchanged reference and terminal amount", persisted) } if database.count.Load() != 1 { t.Errorf("approved PREAUTH persistence calls=%d, want 1", database.count.Load()) } wantConfirms, wantReceipt = 0, "synthetic initial receipt" } else { app.salePayment(recorder, saleRequest(true)) } frames := decodePaymentStream(t, recorder.Body) if len(frames) != 1 || frames[0].Result == nil { t.Fatalf("%s approval(%s) frames=%+v, want one approved result", operation, sdkError, frames) } final := frames[0].Result if final.Outcome != "approved" || final.Retryable || final.TransactionReference != "SYNTH-APPROVED" || final.AmountMinor != 1234 { t.Errorf("%s approval(%s) final=%+v, want approved with unchanged reference and amount", operation, sdkError, final) } if starts.Load() != 1 || confirms.Load() != wantConfirms || !reflect.DeepEqual(receipts, []string{wantReceipt}) { t.Errorf("%s approval(%s) starts/confirms/receipts=%d/%d/%v, want 1/%d/[%s]", operation, sdkError, starts.Load(), confirms.Load(), receipts, wantConfirms, wantReceipt) } }) } } } func TestCreditCallInitialApprovalConfirmationReadFailureRemainsUncertain(t *testing.T) { var starts, confirms atomic.Int32 app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/start-transaction-stream/" { t.Errorf("unexpected SDK path %q", r.URL.Path) w.WriteHeader(http.StatusBadRequest) return } starts.Add(1) fields := map[string]string{types.TransactionResult: "APPROVED", types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234"} if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { t.Errorf("encode initial approval: %v", err) } }) transport := app.creditCallTransport closed := [2]bool{} app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { if r.URL.Path != "/confirm-transaction/" { return transport.RoundTrip(r) } attempt := int(confirms.Add(1)) - 1 if attempt >= len(closed) { t.Error("more than two confirmation attempts") return nil, io.ErrUnexpectedEOF } return &http.Response{StatusCode: http.StatusOK, Body: failedCreditCallBody{closed: &closed[attempt]}}, nil }) app.creditCallReceipt = func(string) { t.Error("failed confirmation printed a receipt") } recorder := httptest.NewRecorder() app.salePayment(recorder, saleRequest(true)) frames := decodePaymentStream(t, recorder.Body) if len(frames) != 1 || frames[0].Result == nil { t.Fatalf("confirmation read failure frames=%+v, want one uncertain final result", frames) } final := frames[0].Result if final.Outcome != "unknown" || final.Retryable || final.HTTPStatus != http.StatusBadGateway { t.Errorf("confirmation read failure final=%+v, want nonretryable uncertainty", final) } if starts.Load() != 1 || confirms.Load() != 2 || !closed[0] || !closed[1] { t.Errorf("starts/confirms/closed=%d/%d/%v, want one dispatch and two closed confirmation bodies", starts.Load(), confirms.Load(), closed) } }