fix(creditcall): preserve detailed SDK failure diagnostics
This commit is contained in:
@@ -33,7 +33,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
buildVersion = "v2.2.2"
|
buildVersion = "v2.2.3"
|
||||||
serviceName = "hardlink"
|
serviceName = "hardlink"
|
||||||
pollingFrequency = 8 * time.Second
|
pollingFrequency = 8 * time.Second
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// creditCallDiagnostic carries allowlisted observations, never financial evidence.
|
||||||
|
type creditCallDiagnostic struct {
|
||||||
|
reason string
|
||||||
|
cause string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (diagnostic creditCallDiagnostic) apply(final *paymentapi.Result) {
|
||||||
|
if diagnostic.reason == "" || final.Reason != "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch final.Outcome {
|
||||||
|
case "unknown":
|
||||||
|
final.Message = "Payment outcome uncertain: " + diagnostic.cause + "; contact reception"
|
||||||
|
case "declined":
|
||||||
|
final.Message = "Transaction declined: " + diagnostic.cause
|
||||||
|
case "cancelled":
|
||||||
|
final.Message = "Transaction cancelled: " + diagnostic.cause
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
final.Reason = diagnostic.reason
|
||||||
|
}
|
||||||
|
|
||||||
|
func creditCallInitialDiagnostic(result creditcall.TransactionResultXML) creditCallDiagnostic {
|
||||||
|
transactionResult, sdkError := creditCallDiagnosticFieldsFromEntries(result.Entries)
|
||||||
|
switch strings.ToLower(transactionResult) {
|
||||||
|
case types.ResultApproved:
|
||||||
|
return creditCallDiagnostic{}
|
||||||
|
case "timeout":
|
||||||
|
return creditCallDiagnostic{reason: "cli_timeout", cause: "CLI wait expired"}
|
||||||
|
}
|
||||||
|
if recognizedCreditCallSDKError(sdkError) {
|
||||||
|
return creditCallDiagnostic{reason: "sdk_" + sdkError, cause: sdkError}
|
||||||
|
}
|
||||||
|
return creditCallDiagnostic{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func creditCallConfirmationErrorDiagnostic(err error) creditCallDiagnostic {
|
||||||
|
var networkError net.Error
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &networkError) && networkError.Timeout()) {
|
||||||
|
return creditCallDiagnostic{reason: "confirmation_timeout", cause: "ConfirmTransaction timed out"}
|
||||||
|
}
|
||||||
|
var requestError *url.Error
|
||||||
|
if errors.As(err, &requestError) {
|
||||||
|
return creditCallDiagnostic{reason: "confirmation_request_error", cause: "ConfirmTransaction request failed"}
|
||||||
|
}
|
||||||
|
return creditCallDiagnostic{reason: "confirmation_response_read_error", cause: "ConfirmTransaction response could not be read"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func creditCallConfirmationResultDiagnostic(entries []creditcall.EntryXML, invalidXML bool) creditCallDiagnostic {
|
||||||
|
if invalidXML {
|
||||||
|
return creditCallDiagnostic{reason: "confirmation_invalid_response", cause: "ConfirmTransaction response is invalid"}
|
||||||
|
}
|
||||||
|
transactionResult, sdkError := creditCallDiagnosticFieldsFromEntries(entries)
|
||||||
|
if recognizedCreditCallSDKError(sdkError) {
|
||||||
|
return creditCallDiagnostic{reason: "confirmation_sdk_" + sdkError, cause: "ConfirmTransaction: " + sdkError}
|
||||||
|
}
|
||||||
|
result := strings.ToLower(transactionResult)
|
||||||
|
if result == types.ResultError && strings.HasPrefix(sdkError, "ConfirmTransaction failed:") {
|
||||||
|
return creditCallDiagnostic{reason: "confirmation_cli_error", cause: "ConfirmTransaction CLI failed"}
|
||||||
|
}
|
||||||
|
switch result {
|
||||||
|
case "canceled", "cancelled":
|
||||||
|
result = "cancelled"
|
||||||
|
case types.ResultDeclined, types.ResultError, "timeout":
|
||||||
|
default:
|
||||||
|
result = "unknown"
|
||||||
|
}
|
||||||
|
return creditCallDiagnostic{reason: "confirmation_result_" + result, cause: "ConfirmTransaction result " + result}
|
||||||
|
}
|
||||||
|
|
||||||
|
func creditCallDiagnosticFieldsFromEntries(entries []creditcall.EntryXML) (transactionResult, sdkError string) {
|
||||||
|
for _, entry := range entries {
|
||||||
|
switch entry.Key {
|
||||||
|
case types.TransactionResult:
|
||||||
|
transactionResult = entry.Value
|
||||||
|
case types.Errors:
|
||||||
|
sdkError = entry.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return transactionResult, sdkError
|
||||||
|
}
|
||||||
|
|
||||||
|
// recognizedCreditCallSDKError matches exact symbolic names from the bundled
|
||||||
|
// ChipDNA SDK 3.17 transaction error types. Descriptions and numeric/compound
|
||||||
|
// errors are deliberately excluded; numeric values overlap between SDK types.
|
||||||
|
func recognizedCreditCallSDKError(code string) bool {
|
||||||
|
switch code {
|
||||||
|
case "ChipCardRemoved", "ClientNotConnectedToServer", "NoPinPadsAvailable", "AmountTooLarge", "AmountTooSmall",
|
||||||
|
"NoPinPadsConfigured", "PaymentDeviceUnavailable", "PaymentDeviceNotInitialized", "PinpadConnectionClosed",
|
||||||
|
"PinPadTransactionTerminated", "EposTransactionTerminated", "TransactionProcessingError", "TransactionInProgress",
|
||||||
|
"TransactionAlreadyInProgressError", "TransactionNotStarted", "MissingParameter", "InvalidParameter", "InvalidValue",
|
||||||
|
"UnexpectedParameters", "AmountZeroNotAllowed", "AmountInvalid", "AmountMissing",
|
||||||
|
"ReferenceAlreadyExistsForApprovedTransaction", "PinPadAmountInvalid", "PinpadAmountTooLarge",
|
||||||
|
"TransactionReferenceMissing", "TransactionReferenceEmpty", "TransactionForConfirmVoidNotFound", "TransactionNotFound",
|
||||||
|
"TransactionAlreadyConfirmed", "TransactionOriginallyDeclined", "TransactionNotCommitted", "ConfirmRequestFailed",
|
||||||
|
"ConfirmAccountVerificationNotAllowed", "ConfirmLinkedRefundNotAllowed", "RemoteServerAccessFailed",
|
||||||
|
"ServerCommunicationError", "ServerRequestError", "ServerResponseError", "NoResponseFromServer", "TemporarilyUnavailable",
|
||||||
|
"ChipCardBlocked", "ChipReadFailure", "SwipeReadFailure", "ExpiredCard", "BadCard", "CardSchemeNotSupported", "CardUsageExceeded",
|
||||||
|
"PinPadUserCancelled", "CardHolderActionTimedOut":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,502 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This contract list is independent of the production allowlist.
|
||||||
|
var creditCallDiagnosticSDKFixtures = []string{
|
||||||
|
"ChipCardRemoved", "ClientNotConnectedToServer", "NoPinPadsAvailable", "AmountTooLarge", "AmountTooSmall",
|
||||||
|
"NoPinPadsConfigured", "PaymentDeviceUnavailable", "PaymentDeviceNotInitialized", "PinpadConnectionClosed",
|
||||||
|
"PinPadTransactionTerminated", "EposTransactionTerminated", "TransactionProcessingError", "TransactionInProgress",
|
||||||
|
"TransactionAlreadyInProgressError", "TransactionNotStarted", "MissingParameter", "InvalidParameter", "InvalidValue",
|
||||||
|
"UnexpectedParameters", "AmountZeroNotAllowed", "AmountInvalid", "AmountMissing",
|
||||||
|
"ReferenceAlreadyExistsForApprovedTransaction", "PinPadAmountInvalid", "PinpadAmountTooLarge",
|
||||||
|
"TransactionReferenceMissing", "TransactionReferenceEmpty", "TransactionForConfirmVoidNotFound", "TransactionNotFound",
|
||||||
|
"TransactionAlreadyConfirmed", "TransactionOriginallyDeclined", "TransactionNotCommitted", "ConfirmRequestFailed",
|
||||||
|
"ConfirmAccountVerificationNotAllowed", "ConfirmLinkedRefundNotAllowed", "RemoteServerAccessFailed",
|
||||||
|
"ServerCommunicationError", "ServerRequestError", "ServerResponseError", "NoResponseFromServer", "TemporarilyUnavailable",
|
||||||
|
"ChipCardBlocked", "ChipReadFailure", "SwipeReadFailure", "ExpiredCard", "BadCard", "CardSchemeNotSupported", "CardUsageExceeded",
|
||||||
|
"PinPadUserCancelled", "CardHolderActionTimedOut",
|
||||||
|
}
|
||||||
|
|
||||||
|
type creditCallDiagnosticFixture struct {
|
||||||
|
name, operation string
|
||||||
|
initial, confirmation map[string]string
|
||||||
|
startFailure, confirmFailure string
|
||||||
|
confirmationXML string
|
||||||
|
recoverConfirmation bool
|
||||||
|
zero bool
|
||||||
|
reason, message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func creditCallDiagnosticFields(result, sdkError string) map[string]string {
|
||||||
|
return map[string]string{
|
||||||
|
types.TransactionResult: result, types.Errors: sdkError, types.TransactionType: "SALE",
|
||||||
|
types.Reference: "SYNTH-STAGE2", types.TotalAmount: "1234", types.ReceiptDataCardholder: "synthetic initial receipt",
|
||||||
|
types.CardType: "Visa", types.PanMasked: "************1133", types.ExpiryDate: "1230",
|
||||||
|
types.CardHash: "synthetic-hash", types.CardReference: "synthetic-card-reference",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func creditCallDiagnosticFixtures() []creditCallDiagnosticFixture {
|
||||||
|
var fixtures []creditCallDiagnosticFixture
|
||||||
|
for _, operation := range []string{"sale", "preauth"} {
|
||||||
|
for _, result := range []string{"ERROR", "DECLINED", "UNKNOWN", "CANCELLED", "TIMEOUT", "", "APPROVED"} {
|
||||||
|
for _, code := range creditCallDiagnosticSDKFixtures {
|
||||||
|
fixture := creditCallDiagnosticFixture{
|
||||||
|
name: operation + "/initial_" + result + "/" + code, operation: operation,
|
||||||
|
initial: creditCallDiagnosticFields(result, code), reason: "sdk_" + code,
|
||||||
|
message: "Payment outcome uncertain: " + code + "; contact reception",
|
||||||
|
}
|
||||||
|
switch result {
|
||||||
|
case "APPROVED":
|
||||||
|
fixture.reason, fixture.message = "", "Payment approved"
|
||||||
|
case "TIMEOUT":
|
||||||
|
fixture.reason, fixture.message = "cli_timeout", "Payment outcome uncertain: CLI wait expired; contact reception"
|
||||||
|
case "DECLINED":
|
||||||
|
fixture.message = "Transaction declined: " + code
|
||||||
|
case "CANCELLED":
|
||||||
|
fixture.message = "Transaction cancelled: " + code
|
||||||
|
}
|
||||||
|
if result == "" || result == "ERROR" || result == "DECLINED" {
|
||||||
|
if code == "PinPadUserCancelled" {
|
||||||
|
fixture.reason, fixture.message = "user_cancelled", "Transaction cancelled"
|
||||||
|
}
|
||||||
|
if code == "CardHolderActionTimedOut" {
|
||||||
|
fixture.reason, fixture.message = "cardholder_timeout", "Cardholder action timed out"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fixtures = append(fixtures, fixture)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, result := range []string{"ERROR", "DECLINED", "UNKNOWN", "CANCELLED", "TIMEOUT", ""} {
|
||||||
|
for _, unknown := range []struct{ name, code string }{
|
||||||
|
{"absent", ""}, {"unrecognized", "DeviceUnavailable"}, {"issuer", "InsufficientFunds"}, {"numeric", "500005"},
|
||||||
|
{"compound", "ChipCardRemoved,AmountTooSmall"}, {"whitespace", " ChipCardRemoved"},
|
||||||
|
{"case", "chipcardremoved"}, {"secret", "token=SYNTHETIC-SECRET; PAN=4111111111111111"},
|
||||||
|
} {
|
||||||
|
fixture := creditCallDiagnosticFixture{name: operation + "/fallback_" + result + "/" + unknown.name,
|
||||||
|
operation: operation, initial: creditCallDiagnosticFields(result, unknown.code),
|
||||||
|
message: "Payment outcome uncertain; contact reception"}
|
||||||
|
fixture.initial[types.ErrorDescription] = "ChipCardRemoved SYNTHETIC-SECRET"
|
||||||
|
switch result {
|
||||||
|
case "DECLINED":
|
||||||
|
fixture.message = "Transaction declined"
|
||||||
|
case "CANCELLED":
|
||||||
|
fixture.message = "Transaction cancelled"
|
||||||
|
case "TIMEOUT":
|
||||||
|
fixture.reason, fixture.message = "cli_timeout", "Payment outcome uncertain: CLI wait expired; contact reception"
|
||||||
|
}
|
||||||
|
fixtures = append(fixtures, fixture)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, failure := range []string{"transport", "incomplete", "malformed", "error_frame", "unknown_frame"} {
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: operation + "/start/" + failure, operation: operation,
|
||||||
|
initial: creditCallDiagnosticFields("ERROR", "ChipCardRemoved"), startFailure: failure,
|
||||||
|
message: "Payment outcome uncertain; contact reception"})
|
||||||
|
}
|
||||||
|
missing := creditCallDiagnosticFields("ERROR", "AmountTooSmall")
|
||||||
|
delete(missing, types.TransactionResult)
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: operation + "/missing_result", operation: operation, initial: missing,
|
||||||
|
reason: "sdk_AmountTooSmall", message: "Payment outcome uncertain: AmountTooSmall; contact reception"})
|
||||||
|
}
|
||||||
|
for _, code := range creditCallDiagnosticSDKFixtures {
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_sdk/" + code, operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", "AmountTooLarge"),
|
||||||
|
confirmation: map[string]string{types.TransactionResult: "ERROR", types.Errors: code, types.ReceiptDataCardholder: "synthetic confirmation receipt"},
|
||||||
|
reason: "confirmation_sdk_" + code, message: "Payment outcome uncertain: ConfirmTransaction: " + code + "; contact reception"})
|
||||||
|
}
|
||||||
|
for _, result := range []string{"DECLINED", "CANCELLED", "CANCELED", "ERROR", "TIMEOUT", "UNKNOWN", ""} {
|
||||||
|
suffix := strings.ToLower(result)
|
||||||
|
if suffix == "canceled" {
|
||||||
|
suffix = "cancelled"
|
||||||
|
}
|
||||||
|
if suffix == "" || suffix == "unknown" {
|
||||||
|
suffix = "unknown"
|
||||||
|
}
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_result/" + result, operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", "ChipCardRemoved"),
|
||||||
|
confirmation: map[string]string{types.TransactionResult: result}, reason: "confirmation_result_" + suffix,
|
||||||
|
message: "Payment outcome uncertain: ConfirmTransaction result " + suffix + "; contact reception"})
|
||||||
|
}
|
||||||
|
for _, failure := range []struct{ name, reason, cause string }{
|
||||||
|
{"deadline", "confirmation_timeout", "ConfirmTransaction timed out"},
|
||||||
|
{"timeout", "confirmation_timeout", "ConfirmTransaction timed out"},
|
||||||
|
{"request", "confirmation_request_error", "ConfirmTransaction request failed"},
|
||||||
|
{"read", "confirmation_response_read_error", "ConfirmTransaction response could not be read"},
|
||||||
|
} {
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_failure/" + failure.name, operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", ""), confirmFailure: failure.name,
|
||||||
|
reason: failure.reason, message: "Payment outcome uncertain: " + failure.cause + "; contact reception"})
|
||||||
|
}
|
||||||
|
for _, failure := range []string{"request", "read"} {
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_recovers/" + failure, operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", ""), confirmFailure: failure, recoverConfirmation: true, message: "Payment approved"})
|
||||||
|
}
|
||||||
|
for _, response := range []struct{ name, xml, reason, cause string }{
|
||||||
|
{"omitted", "<TransactionResult/>", "", ""},
|
||||||
|
{"malformed_retains_approval", "<TransactionResult><Entry>", "", ""},
|
||||||
|
{"malformed_after_error", "<TransactionResult><Entry><Key>TRANSACTION_RESULT</Key><Value>ERROR</Value></Entry><Entry>",
|
||||||
|
"confirmation_invalid_response", "ConfirmTransaction response is invalid"},
|
||||||
|
} {
|
||||||
|
message := "Payment approved"
|
||||||
|
if response.reason != "" {
|
||||||
|
message = "Payment outcome uncertain: " + response.cause + "; contact reception"
|
||||||
|
}
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_xml/" + response.name, operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", "ChipCardRemoved"), confirmationXML: response.xml, reason: response.reason, message: message})
|
||||||
|
}
|
||||||
|
for _, code := range []string{"ConfirmTransaction failed: SYNTHETIC-SECRET PAN=4111111111111111", "ChipCardRemoved,SYNTHETIC-SECRET", "500005", "chipcardremoved"} {
|
||||||
|
reason, cause := "confirmation_result_error", "ConfirmTransaction result error"
|
||||||
|
name := "fallback_" + code
|
||||||
|
if strings.HasPrefix(code, "ConfirmTransaction failed:") {
|
||||||
|
reason, cause, name = "confirmation_cli_error", "ConfirmTransaction CLI failed", "cli_exception"
|
||||||
|
}
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/" + name, operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", ""), confirmation: map[string]string{types.TransactionResult: "ERROR", types.Errors: code},
|
||||||
|
reason: reason, message: "Payment outcome uncertain: " + cause + "; contact reception"})
|
||||||
|
}
|
||||||
|
for _, result := range []string{"APPROVED", "ERROR"} {
|
||||||
|
fields := creditCallDiagnosticFields(result, "ChipCardRemoved")
|
||||||
|
fields[types.TransactionType], fields[types.TotalAmount] = "ACCOUNT VERIFICATION", ""
|
||||||
|
reason, message := "sdk_ChipCardRemoved", "Payment outcome uncertain: ChipCardRemoved; contact reception"
|
||||||
|
if result == "APPROVED" {
|
||||||
|
reason, message = "", "Payment approved"
|
||||||
|
}
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "preauth/verification/" + result, operation: "preauth",
|
||||||
|
initial: fields, zero: true, reason: reason, message: message})
|
||||||
|
}
|
||||||
|
fields := creditCallDiagnosticFields("APPROVED", "ChipCardRemoved")
|
||||||
|
fields[types.TransactionType] = "Refund"
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "preauth/unrecognized_approved_type", operation: "preauth", initial: fields,
|
||||||
|
message: "Payment outcome uncertain; contact reception"})
|
||||||
|
for _, operation := range []string{"sale", "preauth"} {
|
||||||
|
fields := creditCallDiagnosticFields("APPROVED", "ChipCardRemoved")
|
||||||
|
fields[types.TotalAmount], fields[types.TransactionType] = "invalid", "ACCOUNT VERIFICATION"
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: operation + "/amount_unverified", operation: operation, initial: fields,
|
||||||
|
reason: "amount_unverified", message: "Payment amount uncertain; contact reception"})
|
||||||
|
}
|
||||||
|
return fixtures
|
||||||
|
}
|
||||||
|
|
||||||
|
type creditCallDiagnosticRequest struct {
|
||||||
|
Method, Path, Body string
|
||||||
|
FreshCallDeadline bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type creditCallDiagnosticObservation struct {
|
||||||
|
HTTPStatus int
|
||||||
|
Final *paymentapi.Result `json:",omitempty"`
|
||||||
|
Legacy *cmstypes.ResponseRec `json:",omitempty"`
|
||||||
|
Progress []string
|
||||||
|
Requests []creditCallDiagnosticRequest
|
||||||
|
Receipts []string
|
||||||
|
Persistence map[string]any
|
||||||
|
PersistenceCount int32
|
||||||
|
PersistenceTimeValid bool
|
||||||
|
BodiesClosed []bool
|
||||||
|
RetryDelayKept bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type creditCallDiagnosticBody struct {
|
||||||
|
io.Reader
|
||||||
|
err error
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *creditCallDiagnosticBody) Read(p []byte) (int, error) {
|
||||||
|
if b.err != nil {
|
||||||
|
return 0, b.err
|
||||||
|
}
|
||||||
|
return b.Reader.Read(p)
|
||||||
|
}
|
||||||
|
func (b *creditCallDiagnosticBody) Close() error { b.closed = true; return nil }
|
||||||
|
|
||||||
|
type creditCallDiagnosticTimeout struct{}
|
||||||
|
|
||||||
|
func (creditCallDiagnosticTimeout) Error() string { return "SYNTHETIC-SECRET timeout" }
|
||||||
|
func (creditCallDiagnosticTimeout) Timeout() bool { return true }
|
||||||
|
func (creditCallDiagnosticTimeout) Temporary() bool { return true }
|
||||||
|
|
||||||
|
func captureCreditCallDiagnostic(t *testing.T, fixture creditCallDiagnosticFixture, legacy bool) creditCallDiagnosticObservation {
|
||||||
|
t.Helper()
|
||||||
|
started := time.Now()
|
||||||
|
observation := creditCallDiagnosticObservation{RetryDelayKept: true}
|
||||||
|
app := &App{isPayment: true, cfg: &config.ConfigRec{TimeoutSeconds: 1}, creditCallReceipt: func(receipt string) {
|
||||||
|
observation.Receipts = append(observation.Receipts, receipt)
|
||||||
|
}}
|
||||||
|
database := preauthTestDatabase(t, app)
|
||||||
|
var bodies []*creditCallDiagnosticBody
|
||||||
|
var confirmations []time.Time
|
||||||
|
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
payload, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("read synthetic %s request: %v", fixture.name, err)
|
||||||
|
}
|
||||||
|
deadline, ok := r.Context().Deadline()
|
||||||
|
observation.Requests = append(observation.Requests, creditCallDiagnosticRequest{r.Method, r.URL.Path, string(payload), ok && time.Until(deadline) > 299*time.Second})
|
||||||
|
body := &creditCallDiagnosticBody{}
|
||||||
|
if r.URL.Path == "/confirm-transaction/" {
|
||||||
|
confirmations = append(confirmations, time.Now())
|
||||||
|
failure := fixture.confirmFailure
|
||||||
|
if fixture.recoverConfirmation && len(confirmations) > 1 {
|
||||||
|
failure = ""
|
||||||
|
}
|
||||||
|
switch failure {
|
||||||
|
case "deadline":
|
||||||
|
return nil, context.DeadlineExceeded
|
||||||
|
case "timeout":
|
||||||
|
return nil, creditCallDiagnosticTimeout{}
|
||||||
|
case "request":
|
||||||
|
return nil, errors.New("SYNTHETIC-SECRET request failure")
|
||||||
|
case "read":
|
||||||
|
body.err = errors.New("SYNTHETIC-SECRET body failure")
|
||||||
|
}
|
||||||
|
fields := fixture.confirmation
|
||||||
|
if fields == nil {
|
||||||
|
fields = map[string]string{types.TransactionResult: "APPROVED", types.ReceiptDataCardholder: "synthetic confirmation receipt"}
|
||||||
|
}
|
||||||
|
xmlBody := fixture.confirmationXML
|
||||||
|
if xmlBody == "" {
|
||||||
|
xmlBody = chipDNAFixture(t, fields)
|
||||||
|
}
|
||||||
|
body.Reader = strings.NewReader(xmlBody)
|
||||||
|
} else {
|
||||||
|
if fixture.startFailure == "transport" {
|
||||||
|
return nil, errors.New("SYNTHETIC-SECRET start failure")
|
||||||
|
}
|
||||||
|
if legacy {
|
||||||
|
body.Reader = strings.NewReader(chipDNAFixture(t, fixture.initial))
|
||||||
|
} else {
|
||||||
|
frame, err := json.Marshal(map[string]any{"type": "result", "result": fixture.initial})
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("marshal synthetic %s frame: %v", fixture.name, err)
|
||||||
|
}
|
||||||
|
wire := string(frame) + "\n"
|
||||||
|
switch fixture.startFailure {
|
||||||
|
case "incomplete":
|
||||||
|
wire = string(frame)
|
||||||
|
case "malformed":
|
||||||
|
wire = "{SYNTHETIC-SECRET\n"
|
||||||
|
case "error_frame":
|
||||||
|
wire = "{\"type\":\"error\",\"message\":\"SYNTHETIC-SECRET\"}\n"
|
||||||
|
case "unknown_frame":
|
||||||
|
wire = "{\"type\":\"SYNTHETIC-SECRET\"}\n"
|
||||||
|
}
|
||||||
|
body.Reader = strings.NewReader("{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"CardRequested\"}\n" + wire)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bodies = append(bodies, body)
|
||||||
|
// Confirmation HTTP status remains ignored when its body is readable.
|
||||||
|
status := http.StatusOK
|
||||||
|
if r.URL.Path == "/confirm-transaction/" {
|
||||||
|
status = http.StatusServiceUnavailable
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: status, Body: body, Header: make(http.Header)}, nil
|
||||||
|
})
|
||||||
|
app.EnableCreditCallStreaming()
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
amount := "1234"
|
||||||
|
if fixture.zero {
|
||||||
|
amount = "0"
|
||||||
|
}
|
||||||
|
if legacy {
|
||||||
|
if fixture.operation == "preauth" {
|
||||||
|
app.takePreauthorization(recorder, preauthLegacyRequest(amount, "Sale", "2030-01-02 00:00:00 +0000"))
|
||||||
|
} else {
|
||||||
|
app.takePayment(recorder, saleRequest(false))
|
||||||
|
}
|
||||||
|
observation.Legacy = &cmstypes.ResponseRec{}
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), observation.Legacy); err != nil {
|
||||||
|
t.Fatalf("decode %s legacy result: %v", fixture.name, err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/api/payment/"+fixture.operation,
|
||||||
|
strings.NewReader(`{"reference":"SYNTH-STAGE2","amount":`+amount+`,"currency":"GBP","checkoutDate":"2030-01-02 00:00:00 +0000"}`))
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
app.streamPayment(recorder, request, fixture.operation == "preauth")
|
||||||
|
for _, frame := range decodePaymentStream(t, recorder.Body) {
|
||||||
|
if frame.Result != nil {
|
||||||
|
if observation.Final != nil {
|
||||||
|
t.Errorf("%s emitted multiple final results", fixture.name)
|
||||||
|
}
|
||||||
|
observation.Final = frame.Result
|
||||||
|
} else {
|
||||||
|
observation.Progress = append(observation.Progress, frame.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if observation.Final == nil {
|
||||||
|
t.Fatalf("%s emitted no final result", fixture.name)
|
||||||
|
}
|
||||||
|
for _, secret := range []string{"SYNTHETIC-SECRET", "4111111111111111", "<TransactionResult", "synthetic initial receipt"} {
|
||||||
|
if strings.Contains(recorder.Body.String(), secret) {
|
||||||
|
t.Errorf("%s exposed synthetic private marker %q in API response", fixture.name, secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
observation.HTTPStatus = recorder.Code
|
||||||
|
if fixture.operation == "preauth" && fixture.startFailure == "" && fixture.initial[types.TransactionResult] == "APPROVED" && fixture.initial[types.TransactionType] == "SALE" {
|
||||||
|
observation.Persistence = waitPreauthInsert(t, database)
|
||||||
|
timestamp, ok := observation.Persistence["TxnDateTime"].(time.Time)
|
||||||
|
observation.PersistenceTimeValid = ok && timestamp.Location() == time.UTC && !timestamp.Before(started) && !timestamp.After(time.Now())
|
||||||
|
if !observation.PersistenceTimeValid {
|
||||||
|
t.Errorf("%s persisted TxnDateTime=%v, want current UTC time within this run", fixture.name, observation.Persistence["TxnDateTime"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
observation.PersistenceCount = database.count.Load()
|
||||||
|
for _, body := range bodies {
|
||||||
|
observation.BodiesClosed = append(observation.BodiesClosed, body.closed)
|
||||||
|
if !body.closed {
|
||||||
|
t.Errorf("%s left a response body open", fixture.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(confirmations) > 1 {
|
||||||
|
observation.RetryDelayKept = confirmations[1].Sub(confirmations[0]) >= 2*time.Second
|
||||||
|
}
|
||||||
|
if !observation.RetryDelayKept {
|
||||||
|
t.Errorf("%s confirmation retry delay was shorter than two seconds", fixture.name)
|
||||||
|
}
|
||||||
|
return observation
|
||||||
|
}
|
||||||
|
|
||||||
|
// This test uses only pre-existing interfaces, so the same fixtures run against
|
||||||
|
// the captured unmodified production source and the diagnostic implementation.
|
||||||
|
func TestCreditCallDiagnosticParityCapture(t *testing.T) {
|
||||||
|
observations := map[string]creditCallDiagnosticObservation{}
|
||||||
|
for _, fixture := range creditCallDiagnosticFixtures() {
|
||||||
|
t.Run(fixture.name, func(t *testing.T) {
|
||||||
|
observations[fixture.name] = captureCreditCallDiagnostic(t, fixture, false)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Legacy responses and side effects must remain exactly unchanged too.
|
||||||
|
for _, fixture := range creditCallDiagnosticFixtures() {
|
||||||
|
if fixture.startFailure != "" || fixture.zero || fixture.confirmFailure != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
t.Run("legacy/"+fixture.name, func(t *testing.T) {
|
||||||
|
observations["legacy/"+fixture.name] = captureCreditCallDiagnostic(t, fixture, true)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if baseline := os.Getenv("HARDLINK_CREDITCALL_DIAGNOSTIC_BASELINE"); baseline != "" {
|
||||||
|
data, err := os.ReadFile(baseline)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var before map[string]creditCallDiagnosticObservation
|
||||||
|
if err := json.Unmarshal(data, &before); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Round-trip current observations to match interface-valued SQL argument types.
|
||||||
|
data, err = json.Marshal(observations)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var after map[string]creditCallDiagnosticObservation
|
||||||
|
if err := json.Unmarshal(data, &after); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(before) != len(after) {
|
||||||
|
t.Errorf("capture cases=%d, want baseline %d", len(after), len(before))
|
||||||
|
}
|
||||||
|
for name, want := range before {
|
||||||
|
got, ok := after[name]
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("missing baseline fixture %q", name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if want.Final != nil && got.Final != nil {
|
||||||
|
want.Final.Reason, want.Final.Message = "", ""
|
||||||
|
got.Final.Reason, got.Final.Message = "", ""
|
||||||
|
}
|
||||||
|
// SQL generates the transaction timestamp during each run. Its type,
|
||||||
|
// UTC location and range are asserted above; retain raw values in captures.
|
||||||
|
if want.Persistence != nil && got.Persistence != nil {
|
||||||
|
want.Persistence["TxnDateTime"], got.Persistence["TxnDateTime"] = "validated current UTC time", "validated current UTC time"
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("%s changed beyond diagnostic fields: got %+v, want %+v", name, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if destination := os.Getenv("HARDLINK_CREDITCALL_DIAGNOSTIC_CAPTURE"); destination != "" {
|
||||||
|
data, err := json.MarshalIndent(observations, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(destination, data, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallDiagnosticReasons(t *testing.T) {
|
||||||
|
for _, fixture := range creditCallDiagnosticFixtures() {
|
||||||
|
t.Run(fixture.name, func(t *testing.T) {
|
||||||
|
got := captureCreditCallDiagnostic(t, fixture, false).Final
|
||||||
|
if got.Reason != fixture.reason || got.Message != fixture.message {
|
||||||
|
t.Errorf("%s Reason/Message=%q/%q, want %q/%q", fixture.name, got.Reason, got.Message, fixture.reason, fixture.message)
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(got.Reason, "confirmation_") && (got.Outcome != "unknown" || got.Retryable) {
|
||||||
|
t.Errorf("%s final=%+v, want nonretryable confirmation uncertainty", fixture.name, got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallDiagnosticEntryOrderAndOwnership(t *testing.T) {
|
||||||
|
for _, fixture := range []struct {
|
||||||
|
name string
|
||||||
|
entries []creditcall.EntryXML
|
||||||
|
want creditCallDiagnostic
|
||||||
|
}{
|
||||||
|
{name: "last error unrecognized", entries: []creditcall.EntryXML{
|
||||||
|
{Key: types.Errors, Value: "ChipCardRemoved"}, {Key: types.Errors, Value: "DeviceUnavailable"},
|
||||||
|
}},
|
||||||
|
{name: "last error recognized", entries: []creditcall.EntryXML{
|
||||||
|
{Key: types.Errors, Value: "DeviceUnavailable"}, {Key: types.Errors, Value: "ChipCardRemoved"},
|
||||||
|
}, want: creditCallDiagnostic{reason: "sdk_ChipCardRemoved", cause: "ChipCardRemoved"}},
|
||||||
|
{name: "last result approved", entries: []creditcall.EntryXML{
|
||||||
|
{Key: types.TransactionResult, Value: "ERROR"}, {Key: types.Errors, Value: "ChipCardRemoved"}, {Key: types.TransactionResult, Value: "APPROVED"},
|
||||||
|
}},
|
||||||
|
} {
|
||||||
|
t.Run(fixture.name, func(t *testing.T) {
|
||||||
|
before := append([]creditcall.EntryXML(nil), fixture.entries...)
|
||||||
|
got := creditCallInitialDiagnostic(creditcall.TransactionResultXML{Entries: fixture.entries})
|
||||||
|
if got != fixture.want {
|
||||||
|
t.Errorf("creditCallInitialDiagnostic(%+v)=%+v, want %+v", fixture.entries, got, fixture.want)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(fixture.entries, before) {
|
||||||
|
t.Errorf("creditCallInitialDiagnostic changed entries: got %+v, want %+v", fixture.entries, before)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallConfirmationSDKErrorWithoutResultKeepsLegacyApproval(t *testing.T) {
|
||||||
|
fixture := creditCallDiagnosticFixture{name: "sale/confirmation_sdk_without_result", operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", ""), confirmation: map[string]string{types.Errors: "TransactionNotFound"}}
|
||||||
|
got := captureCreditCallDiagnostic(t, fixture, false)
|
||||||
|
if got.Final.Outcome != "approved" || got.Final.Reason != "" || got.Final.TransactionReference != "SYNTH-STAGE2" || got.Final.AmountMinor != 1234 {
|
||||||
|
t.Errorf("confirmation SDK error without TRANSACTION_RESULT final=%+v, want unchanged inherited approval and metadata", got.Final)
|
||||||
|
}
|
||||||
|
if len(got.Requests) != 2 || !reflect.DeepEqual(got.Receipts, []string{"synthetic initial receipt"}) {
|
||||||
|
t.Errorf("confirmation SDK error without TRANSACTION_RESULT requests/receipts=%v/%v, want one start, one confirmation and inherited receipt", got.Requests, got.Receipts)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,7 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
|
|||||||
transaction.TransactionType = "AccountVerification"
|
transaction.TransactionType = "AccountVerification"
|
||||||
}
|
}
|
||||||
var initial creditCallInitialResult
|
var initial creditCallInitialResult
|
||||||
|
var diagnostic creditCallDiagnostic
|
||||||
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
result, err := callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) {
|
result, err := callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) {
|
||||||
if status != nil {
|
if status != nil {
|
||||||
@@ -59,6 +60,7 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
|
|||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
initial = classifyCreditCallInitialResult(result)
|
initial = classifyCreditCallInitialResult(result)
|
||||||
|
diagnostic = creditCallInitialDiagnostic(result)
|
||||||
}
|
}
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
@@ -84,6 +86,10 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if outcome.confirmationDiagnostic.reason != "" {
|
||||||
|
diagnostic = outcome.confirmationDiagnostic
|
||||||
|
}
|
||||||
|
diagnostic.apply(&final)
|
||||||
return &paymentsvc.Result{Terminal: final}, nil
|
return &paymentsvc.Result{Terminal: final}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ type creditCallSaleOutcome struct {
|
|||||||
Approved bool
|
Approved bool
|
||||||
FailureType string
|
FailureType string
|
||||||
FailureDescription string
|
FailureDescription string
|
||||||
|
|
||||||
|
confirmationDiagnostic creditCallDiagnostic
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) creditCallClient() *http.Client {
|
func (app *App) creditCallClient() *http.Client {
|
||||||
@@ -84,13 +86,16 @@ func (app *App) executeCreditCallSale(
|
|||||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error())
|
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error())
|
||||||
outcome.FailureType = types.ResultError
|
outcome.FailureType = types.ResultError
|
||||||
outcome.FailureDescription = "ConfirmTransactionError"
|
outcome.FailureDescription = "ConfirmTransactionError"
|
||||||
|
outcome.confirmationDiagnostic = creditCallConfirmationErrorDiagnostic(err)
|
||||||
return outcome
|
return outcome
|
||||||
}
|
}
|
||||||
|
|
||||||
// Intentionally reuse both records: XML appends confirmation entries, and
|
// Intentionally reuse both records: XML appends confirmation entries, and
|
||||||
// missing confirmation fields/receipts retain their existing legacy behavior.
|
// missing confirmation fields/receipts retain their existing legacy behavior.
|
||||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
initialEntryCount := len(trResult.Entries)
|
||||||
logging.Error(types.ServiceName, err.Error(), "Parse confirm result error", string(op), "", "", 0)
|
parseErr := trResult.ParseTransactionResult(body)
|
||||||
|
if parseErr != nil {
|
||||||
|
logging.Error(types.ServiceName, parseErr.Error(), "Parse confirm result error", string(op), "", "", 0)
|
||||||
}
|
}
|
||||||
result.FillFromTransactionResult(trResult)
|
result.FillFromTransactionResult(trResult)
|
||||||
res = result.Fields[types.TransactionResult]
|
res = result.Fields[types.TransactionResult]
|
||||||
@@ -107,6 +112,7 @@ func (app *App) executeCreditCallSale(
|
|||||||
outcome.Payment = result
|
outcome.Payment = result
|
||||||
outcome.FailureType = res
|
outcome.FailureType = res
|
||||||
outcome.FailureDescription = result.Fields[types.Errors]
|
outcome.FailureDescription = result.Fields[types.Errors]
|
||||||
|
outcome.confirmationDiagnostic = creditCallConfirmationResultDiagnostic(trResult.Entries[initialEntryCount:], parseErr != nil)
|
||||||
return outcome
|
return outcome
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
`buildVersion` is a const in `cmd/hardlink/main.go`.
|
`buildVersion` is a const in `cmd/hardlink/main.go`.
|
||||||
|
|
||||||
|
#### v2.2.3 - 05 November 2026
|
||||||
|
fix(creditcall): preserve detailed SDK failure diagnostics
|
||||||
|
|
||||||
#### v2.2.2 - 05 November 2026
|
#### v2.2.2 - 05 November 2026
|
||||||
fix(creditcall): restore SDK timeout and cancellation classification
|
fix(creditcall): restore SDK timeout and cancellation classification
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user