Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2e640a720 | ||
|
|
242af6063b | ||
|
|
3aae843011 |
@@ -33,7 +33,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
buildVersion = "v2.2.1"
|
buildVersion = "v2.2.4"
|
||||||
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,563 @@
|
|||||||
|
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
|
||||||
|
emptyConfirmation bool
|
||||||
|
correctedConfirmation bool
|
||||||
|
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"})
|
||||||
|
}
|
||||||
|
const approvedEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value>APPROVED</Value></Entry>"
|
||||||
|
const declinedEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value>DECLINED</Value></Entry>"
|
||||||
|
const errorEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value>ERROR</Value></Entry>"
|
||||||
|
const emptyEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value></Value></Entry>"
|
||||||
|
for _, response := range []struct {
|
||||||
|
name, xml, reason, cause string
|
||||||
|
corrected bool
|
||||||
|
}{
|
||||||
|
{"mixed_case", "<TransactionResult><Entry><Key>TRANSACTION_RESULT</Key><Value>aPpRoVeD</Value></Entry></TransactionResult>", "", "", false},
|
||||||
|
{"omitted", "<TransactionResult/>", "confirmation_result_unknown", "ConfirmTransaction result unknown", true},
|
||||||
|
{"empty_body", "", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
|
||||||
|
{"whitespace_body", " \r\n\t", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
|
||||||
|
{"malformed_retains_approval", "<TransactionResult><Entry>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
|
||||||
|
{"malformed_after_approved", "<TransactionResult>" + approvedEntry + "<Entry>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
|
||||||
|
{"malformed_after_error", "<TransactionResult><Entry><Key>TRANSACTION_RESULT</Key><Value>ERROR</Value></Entry><Entry>",
|
||||||
|
"confirmation_invalid_response", "ConfirmTransaction response is invalid", false},
|
||||||
|
{"malformed_after_declined", "<TransactionResult>" + declinedEntry + "<Entry>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", false},
|
||||||
|
{"wrong_root", "<Unexpected/>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
|
||||||
|
{"sdk_only_disconnected", "<TransactionResult><Entry><Key>ERRORS</Key><Value>ClientNotConnectedToServer</Value></Entry></TransactionResult>",
|
||||||
|
"confirmation_sdk_ClientNotConnectedToServer", "ConfirmTransaction: ClientNotConnectedToServer", true},
|
||||||
|
{"sdk_only_not_found", "<TransactionResult><Entry><Key>ERRORS</Key><Value>TransactionNotFound</Value></Entry></TransactionResult>",
|
||||||
|
"confirmation_sdk_TransactionNotFound", "ConfirmTransaction: TransactionNotFound", true},
|
||||||
|
{"duplicate_approved_declined", "<TransactionResult>" + approvedEntry + declinedEntry + "</TransactionResult>",
|
||||||
|
"confirmation_result_declined", "ConfirmTransaction result declined", false},
|
||||||
|
{"duplicate_declined_approved", "<TransactionResult>" + declinedEntry + approvedEntry + "</TransactionResult>", "", "", false},
|
||||||
|
{"duplicate_error_approved", "<TransactionResult>" + errorEntry + approvedEntry + "</TransactionResult>", "", "", false},
|
||||||
|
{"duplicate_approved_empty", "<TransactionResult>" + approvedEntry + emptyEntry + "</TransactionResult>",
|
||||||
|
"confirmation_result_unknown", "ConfirmTransaction result unknown", false},
|
||||||
|
{"duplicate_empty_approved", "<TransactionResult>" + emptyEntry + approvedEntry + "</TransactionResult>", "", "", false},
|
||||||
|
{"duplicate_approved_error", "<TransactionResult>" + approvedEntry + errorEntry + "</TransactionResult>",
|
||||||
|
"confirmation_result_error", "ConfirmTransaction result error", false},
|
||||||
|
} {
|
||||||
|
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,
|
||||||
|
emptyConfirmation: response.xml == "", correctedConfirmation: response.corrected, reason: response.reason, message: message})
|
||||||
|
}
|
||||||
|
for _, metadata := range []string{"returned_amount", "overrides", "empty_overrides"} {
|
||||||
|
fields := creditCallDiagnosticFields("APPROVED", "")
|
||||||
|
fields[types.TotalAmount] = "3100"
|
||||||
|
confirmation := map[string]string{types.TransactionResult: "APPROVED"}
|
||||||
|
if metadata == "overrides" {
|
||||||
|
confirmation[types.Reference], confirmation[types.TotalAmount] = "SYNTH-CONFIRMATION", "2500"
|
||||||
|
confirmation[types.CardType], confirmation[types.PanMasked] = "Mastercard", "************7788"
|
||||||
|
confirmation[types.ExpiryDate], confirmation[types.CardReference] = "1231", "synthetic-confirmation-card"
|
||||||
|
confirmation[types.ReceiptDataCardholder] = "synthetic confirmation receipt"
|
||||||
|
}
|
||||||
|
if metadata == "empty_overrides" {
|
||||||
|
confirmation[types.ExpiryDate], confirmation[types.CardHash], confirmation[types.ReceiptDataCardholder] = "", "", ""
|
||||||
|
}
|
||||||
|
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_metadata/" + metadata, operation: "sale",
|
||||||
|
initial: fields, confirmation: confirmation, message: "Payment approved"})
|
||||||
|
}
|
||||||
|
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 == "" && !fixture.emptyConfirmation {
|
||||||
|
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{}
|
||||||
|
corrections := map[string]creditCallDiagnosticFixture{}
|
||||||
|
for _, fixture := range creditCallDiagnosticFixtures() {
|
||||||
|
if fixture.correctedConfirmation {
|
||||||
|
corrections[fixture.name] = fixture
|
||||||
|
corrections["legacy/"+fixture.name] = fixture
|
||||||
|
}
|
||||||
|
t.Run(fixture.name, func(t *testing.T) {
|
||||||
|
observations[fixture.name] = captureCreditCallDiagnostic(t, fixture, false)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Legacy observations use the same explicitly allowed correction cases.
|
||||||
|
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 fixture, corrected := corrections[name]; corrected {
|
||||||
|
if want.Final != nil {
|
||||||
|
if want.Final.Outcome != "approved" || want.Final.Retryable {
|
||||||
|
t.Fatalf("%s baseline=%+v, want the specifically identified false approval", name, want.Final)
|
||||||
|
}
|
||||||
|
want.Final = &paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Provider: "creditcall",
|
||||||
|
AmountMinor: 1234, CurrencyCode: "GBP", Reason: fixture.reason, Message: fixture.message}
|
||||||
|
} else {
|
||||||
|
if !strings.HasPrefix(want.Legacy.Data, "/successful?") {
|
||||||
|
t.Fatalf("%s baseline=%+v, want the specifically identified false success redirect", name, want.Legacy)
|
||||||
|
}
|
||||||
|
want.Legacy = &cmstypes.ResponseRec{Status: cmstypes.StatusRec{Code: http.StatusOK, Message: "unknown"},
|
||||||
|
Data: "/unsuccessful?Description=Transaction+unknown&MsgType=error"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 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 the exact approved correction: 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 TestCreditCallConfirmationSDKErrorWithoutResultRemainsUncertain(t *testing.T) {
|
||||||
|
fixture := creditCallDiagnosticFixture{name: "sale/confirmation_sdk_without_result", operation: "sale",
|
||||||
|
initial: creditCallDiagnosticFields("APPROVED", ""), confirmation: map[string]string{types.Errors: "ClientNotConnectedToServer"}}
|
||||||
|
got := captureCreditCallDiagnostic(t, fixture, false)
|
||||||
|
if got.Final.Outcome != "unknown" || got.Final.Retryable || got.Final.Reason != "confirmation_sdk_ClientNotConnectedToServer" || got.Final.TransactionReference != "" || got.Final.AmountMinor != 1234 {
|
||||||
|
t.Errorf("confirmation SDK error without TRANSACTION_RESULT final=%+v, want nonretryable uncertainty without approved-only 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,22 @@ import (
|
|||||||
// creditCallProcessor delegates to the unchanged legacy execution/finalization core.
|
// creditCallProcessor delegates to the unchanged legacy execution/finalization core.
|
||||||
type creditCallProcessor struct{ app *App }
|
type creditCallProcessor struct{ app *App }
|
||||||
|
|
||||||
|
type creditCallInitialKind uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
creditCallInitialUnknown creditCallInitialKind = iota
|
||||||
|
creditCallInitialApproved
|
||||||
|
creditCallInitialDeclined
|
||||||
|
creditCallInitialCancelled
|
||||||
|
creditCallInitialTimeout
|
||||||
|
)
|
||||||
|
|
||||||
|
// creditCallInitialResult describes only the completed initial SDK response.
|
||||||
|
type creditCallInitialResult struct {
|
||||||
|
kind creditCallInitialKind
|
||||||
|
reason string
|
||||||
|
}
|
||||||
|
|
||||||
func (*creditCallProcessor) ValidatePreauth(req paymentsvc.SaleRequest) error {
|
func (*creditCallProcessor) ValidatePreauth(req paymentsvc.SaleRequest) error {
|
||||||
if req.Amount < 0 {
|
if req.Amount < 0 {
|
||||||
return paymentsvc.ErrPreauthUnsupported
|
return paymentsvc.ErrPreauthUnsupported
|
||||||
@@ -34,12 +50,19 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
|
|||||||
transaction.AmountMinorUnits = ""
|
transaction.AmountMinorUnits = ""
|
||||||
transaction.TransactionType = "AccountVerification"
|
transaction.TransactionType = "AccountVerification"
|
||||||
}
|
}
|
||||||
|
var initial creditCallInitialResult
|
||||||
|
var diagnostic creditCallDiagnostic
|
||||||
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
return 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 {
|
||||||
status(paymentsvc.StatusUpdate{Code: code})
|
status(paymentsvc.StatusUpdate{Code: code})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
if err == nil {
|
||||||
|
initial = classifyCreditCallInitialResult(result)
|
||||||
|
diagnostic = creditCallInitialDiagnostic(result)
|
||||||
|
}
|
||||||
|
return result, err
|
||||||
}
|
}
|
||||||
var outcome creditCallSaleOutcome
|
var outcome creditCallSaleOutcome
|
||||||
if preauth {
|
if preauth {
|
||||||
@@ -48,7 +71,7 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
|
|||||||
} else {
|
} else {
|
||||||
outcome = p.app.executeCreditCallSale(transaction, start)
|
outcome = p.app.executeCreditCallSale(transaction, start)
|
||||||
}
|
}
|
||||||
final := outcome.streamResult()
|
final := outcome.streamResult(initial)
|
||||||
final.AmountMinor, final.CurrencyCode = req.Amount, req.Currency
|
final.AmountMinor, final.CurrencyCode = req.Amount, req.Currency
|
||||||
if outcome.Approved {
|
if outcome.Approved {
|
||||||
if raw := outcome.Payment.Fields[types.TotalAmount]; raw != "" {
|
if raw := outcome.Payment.Fields[types.TotalAmount]; raw != "" {
|
||||||
@@ -63,10 +86,44 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
func (outcome creditCallSaleOutcome) streamResult() paymentapi.Result {
|
func classifyCreditCallInitialResult(result creditcall.TransactionResultXML) creditCallInitialResult {
|
||||||
|
var transactionResult, sdkError string
|
||||||
|
for _, entry := range result.Entries {
|
||||||
|
switch entry.Key {
|
||||||
|
case types.TransactionResult:
|
||||||
|
transactionResult = entry.Value
|
||||||
|
case types.Errors:
|
||||||
|
sdkError = entry.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
transactionResult = strings.ToLower(transactionResult)
|
||||||
|
switch transactionResult {
|
||||||
|
case types.ResultApproved:
|
||||||
|
return creditCallInitialResult{kind: creditCallInitialApproved}
|
||||||
|
case "cancelled", "canceled":
|
||||||
|
return creditCallInitialResult{kind: creditCallInitialCancelled}
|
||||||
|
case "", types.ResultError, types.ResultDeclined:
|
||||||
|
switch sdkError {
|
||||||
|
case "CardHolderActionTimedOut":
|
||||||
|
return creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}
|
||||||
|
case "PinPadUserCancelled":
|
||||||
|
return creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}
|
||||||
|
}
|
||||||
|
if transactionResult == types.ResultDeclined {
|
||||||
|
return creditCallInitialResult{kind: creditCallInitialDeclined}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return creditCallInitialResult{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (outcome creditCallSaleOutcome) streamResult(initial creditCallInitialResult) paymentapi.Result {
|
||||||
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: outcome.HTTPStatus, Provider: "creditcall", Message: "Payment outcome uncertain; contact reception"}
|
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: outcome.HTTPStatus, Provider: "creditcall", Message: "Payment outcome uncertain; contact reception"}
|
||||||
if final.HTTPStatus == 0 {
|
if final.HTTPStatus == 0 {
|
||||||
final.HTTPStatus = http.StatusOK
|
final.HTTPStatus = http.StatusOK
|
||||||
@@ -79,13 +136,21 @@ func (outcome creditCallSaleOutcome) streamResult() paymentapi.Result {
|
|||||||
final.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
|
final.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
|
||||||
final.ExpiryDate = fields[types.ExpiryDate]
|
final.ExpiryDate = fields[types.ExpiryDate]
|
||||||
final.CardHash, final.CardReference = fields[types.CardHash], fields[types.CardReference]
|
final.CardHash, final.CardReference = fields[types.CardHash], fields[types.CardReference]
|
||||||
} else {
|
return final
|
||||||
switch strings.ToLower(outcome.FailureType) {
|
}
|
||||||
case "declined":
|
// Initial approval followed by unsuccessful confirmation must not permit another charge.
|
||||||
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
|
if initial.kind == creditCallInitialApproved {
|
||||||
case "cancelled", "canceled":
|
return final
|
||||||
final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled"
|
}
|
||||||
}
|
switch initial.kind {
|
||||||
|
case creditCallInitialDeclined:
|
||||||
|
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
|
||||||
|
case creditCallInitialCancelled:
|
||||||
|
final.Outcome, final.Retryable = "cancelled", true
|
||||||
|
final.Reason, final.Message = initial.reason, "Transaction cancelled"
|
||||||
|
case creditCallInitialTimeout:
|
||||||
|
final.Outcome, final.Retryable = "timeout", true
|
||||||
|
final.Reason, final.Message = initial.reason, "Cardholder action timed out"
|
||||||
}
|
}
|
||||||
return final
|
return final
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,17 +86,34 @@ 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
|
// Reuse both records to preserve metadata and receipt merging. Only fresh
|
||||||
// missing confirmation fields/receipts retain their existing legacy behavior.
|
// confirmation entries can establish completion approval.
|
||||||
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]
|
||||||
if !strings.EqualFold(res, types.ResultApproved) {
|
confirmationEntries := trResult.Entries[initialEntryCount:]
|
||||||
|
var confirmationResult string
|
||||||
|
for _, entry := range confirmationEntries {
|
||||||
|
if entry.Key == types.TransactionResult {
|
||||||
|
confirmationResult = entry.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
confirmationApproved := false
|
||||||
|
if parseErr == nil {
|
||||||
|
confirmationApproved = strings.EqualFold(confirmationResult, types.ResultApproved)
|
||||||
|
}
|
||||||
|
if !confirmationApproved {
|
||||||
|
if strings.EqualFold(res, types.ResultApproved) {
|
||||||
|
res = "unknown"
|
||||||
|
}
|
||||||
app.printCreditCallReceipt(result.CardholderReceipt)
|
app.printCreditCallReceipt(result.CardholderReceipt)
|
||||||
desc := result.Fields[types.ErrorDescription]
|
desc := result.Fields[types.ErrorDescription]
|
||||||
if desc == "" {
|
if desc == "" {
|
||||||
@@ -104,9 +123,11 @@ func (app *App) executeCreditCallSale(
|
|||||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc)
|
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc)
|
||||||
outcome.HTTPStatus = http.StatusOK
|
outcome.HTTPStatus = http.StatusOK
|
||||||
outcome.Status = result.Status
|
outcome.Status = result.Status
|
||||||
|
outcome.Status.Message = res
|
||||||
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(confirmationEntries, parseErr != nil)
|
||||||
return outcome
|
return outcome
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ func TestCreditCallStructuredFieldsExcludeRawData(t *testing.T) {
|
|||||||
result := (creditCallSaleOutcome{Approved: true, Payment: creditcall.PaymentResult{Fields: map[string]string{
|
result := (creditCallSaleOutcome{Approved: true, Payment: creditcall.PaymentResult{Fields: map[string]string{
|
||||||
types.Reference: "ref", types.PanMasked: "1234567890123456", types.CardHash: "hash", types.CardReference: "card-ref",
|
types.Reference: "ref", types.PanMasked: "1234567890123456", types.CardHash: "hash", types.CardReference: "card-ref",
|
||||||
"PAN": "pan-secret", "CVV": "cvv-secret", "PIN": "pin-secret", "TRACK_DATA": "track-secret", types.ReceiptDataCardholder: "receipt-secret",
|
"PAN": "pan-secret", "CVV": "cvv-secret", "PIN": "pin-secret", "TRACK_DATA": "track-secret", types.ReceiptDataCardholder: "receipt-secret",
|
||||||
}}}).streamResult()
|
}}}).streamResult(creditCallInitialResult{kind: creditCallInitialApproved})
|
||||||
body, err := json.Marshal(result)
|
body, err := json.Marshal(result)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -219,8 +219,8 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
|
|||||||
{"cancelled", "Cancelled", "", 0, false, "start receipt"},
|
{"cancelled", "Cancelled", "", 0, false, "start receipt"},
|
||||||
{"timeout", "TIMEOUT", "", 0, false, "start receipt"},
|
{"timeout", "TIMEOUT", "", 0, false, "start receipt"},
|
||||||
{"confirmation declined", "Approved", "Declined", 1, false, "confirm receipt"},
|
{"confirmation declined", "Approved", "Declined", 1, false, "confirm receipt"},
|
||||||
{"confirmation omissions", "Approved", "omitted", 1, true, "start receipt"},
|
{"confirmation omissions", "Approved", "omitted", 1, false, "start receipt"},
|
||||||
{"malformed confirmation", "Approved", "malformed", 1, true, "start receipt"},
|
{"malformed confirmation", "Approved", "malformed", 1, false, "start receipt"},
|
||||||
} {
|
} {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
fields := map[string]string{types.TransactionResult: test.startResult, types.Reference: "native-ref",
|
fields := map[string]string{types.TransactionResult: test.startResult, types.Reference: "native-ref",
|
||||||
@@ -314,6 +314,160 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreditCallFreshConfirmationResults(t *testing.T) {
|
||||||
|
fixtures := map[string]creditCallDiagnosticFixture{}
|
||||||
|
for _, fixture := range creditCallDiagnosticFixtures() {
|
||||||
|
fixtures[fixture.name] = fixture
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, outcome string
|
||||||
|
amount int64
|
||||||
|
}{
|
||||||
|
{"confirmation_xml/mixed_case", "approved", 1234},
|
||||||
|
{"confirmation_xml/omitted", "unknown", 1234},
|
||||||
|
{"confirmation_xml/empty_body", "unknown", 1234},
|
||||||
|
{"confirmation_xml/whitespace_body", "unknown", 1234},
|
||||||
|
{"confirmation_xml/malformed_retains_approval", "unknown", 1234},
|
||||||
|
{"confirmation_xml/malformed_after_approved", "unknown", 1234},
|
||||||
|
{"confirmation_xml/malformed_after_error", "unknown", 1234},
|
||||||
|
{"confirmation_xml/malformed_after_declined", "unknown", 1234},
|
||||||
|
{"confirmation_xml/wrong_root", "unknown", 1234},
|
||||||
|
{"confirmation_xml/sdk_only_disconnected", "unknown", 1234},
|
||||||
|
{"confirmation_xml/sdk_only_not_found", "unknown", 1234},
|
||||||
|
{"confirmation_xml/duplicate_approved_declined", "unknown", 1234},
|
||||||
|
{"confirmation_xml/duplicate_declined_approved", "approved", 1234},
|
||||||
|
{"confirmation_xml/duplicate_error_approved", "approved", 1234},
|
||||||
|
{"confirmation_xml/duplicate_approved_empty", "unknown", 1234},
|
||||||
|
{"confirmation_xml/duplicate_empty_approved", "approved", 1234},
|
||||||
|
{"confirmation_xml/duplicate_approved_error", "unknown", 1234},
|
||||||
|
{"confirmation_result/DECLINED", "unknown", 1234},
|
||||||
|
{"confirmation_result/ERROR", "unknown", 1234},
|
||||||
|
{"confirmation_result/CANCELLED", "unknown", 1234},
|
||||||
|
{"confirmation_result/CANCELED", "unknown", 1234},
|
||||||
|
{"confirmation_result/TIMEOUT", "unknown", 1234},
|
||||||
|
{"confirmation_result/UNKNOWN", "unknown", 1234},
|
||||||
|
{"confirmation_result/", "unknown", 1234},
|
||||||
|
{"confirmation_metadata/returned_amount", "approved", 3100},
|
||||||
|
{"confirmation_metadata/overrides", "approved", 2500},
|
||||||
|
{"confirmation_metadata/empty_overrides", "approved", 3100},
|
||||||
|
} {
|
||||||
|
for _, legacy := range []bool{false, true} {
|
||||||
|
mode := "modern"
|
||||||
|
if legacy {
|
||||||
|
mode = "legacy"
|
||||||
|
}
|
||||||
|
t.Run(mode+"/"+tc.name, func(t *testing.T) {
|
||||||
|
fixture, ok := fixtures["sale/"+tc.name]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("missing confirmation fixture %q", tc.name)
|
||||||
|
}
|
||||||
|
got := captureCreditCallDiagnostic(t, fixture, legacy)
|
||||||
|
if len(got.Requests) != 2 {
|
||||||
|
t.Fatalf("Sale(%s) requests=%+v, want one start and one confirmation", tc.name, got.Requests)
|
||||||
|
}
|
||||||
|
if got.HTTPStatus != http.StatusOK || got.Requests[1].Path != "/confirm-transaction/" {
|
||||||
|
t.Errorf("Sale(%s) HTTP/requests=%d/%+v, want HTTP 200, one start and one confirmation", tc.name, got.HTTPStatus, got.Requests)
|
||||||
|
}
|
||||||
|
for _, request := range got.Requests {
|
||||||
|
if !request.FreshCallDeadline || request.Method != http.MethodPost {
|
||||||
|
t.Errorf("Sale(%s) request=%+v, want POST with an independent 300-second timeout", tc.name, request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var confirmation creditcall.ConfirmTransactionRequest
|
||||||
|
if err := xml.Unmarshal([]byte(got.Requests[1].Body), &confirmation); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if confirmation.Amount != "1234" || confirmation.Reference != "SYNTH-STAGE2" {
|
||||||
|
t.Errorf("Sale(%s) confirmation=%+v, want the original requested amount and authorization reference", tc.name, confirmation)
|
||||||
|
}
|
||||||
|
if legacy {
|
||||||
|
if strings.HasPrefix(got.Legacy.Data, "/successful?") != (tc.outcome == "approved") {
|
||||||
|
t.Errorf("Sale(%s) legacy=%+v, want success only for fresh approval", tc.name, got.Legacy)
|
||||||
|
}
|
||||||
|
if fixture.correctedConfirmation && (got.Legacy.Status.Code != http.StatusOK || got.Legacy.Status.Message != "unknown" || got.Legacy.Data != "/unsuccessful?Description=Transaction+unknown&MsgType=error") {
|
||||||
|
t.Errorf("Sale(%s) legacy=%+v, want unchanged status code and explicit uncertainty failure response", tc.name, got.Legacy)
|
||||||
|
}
|
||||||
|
} else if got.Final.Outcome != tc.outcome || got.Final.Retryable || got.Final.HTTPStatus != http.StatusOK || got.Final.AmountMinor != tc.amount || got.Final.Reason != fixture.reason || got.Final.Message != fixture.message {
|
||||||
|
t.Errorf("Sale(%s) final=%+v, want %s/nonretryable/HTTP200/amount%d and %q/%q", tc.name, got.Final, tc.outcome, tc.amount, fixture.reason, fixture.message)
|
||||||
|
}
|
||||||
|
wantReceipt := "synthetic initial receipt"
|
||||||
|
if tc.name == "confirmation_metadata/overrides" {
|
||||||
|
wantReceipt = "synthetic confirmation receipt"
|
||||||
|
}
|
||||||
|
if tc.name == "confirmation_metadata/empty_overrides" {
|
||||||
|
wantReceipt = ""
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got.Receipts, []string{wantReceipt}) || got.PersistenceCount != 0 {
|
||||||
|
t.Errorf("Sale(%s) receipts/persistence=%v/%d, want [%q]/0", tc.name, got.Receipts, got.PersistenceCount, wantReceipt)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallSaleConfirmationPreservesMergedFields(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, rawXML, receipt string
|
||||||
|
confirmation map[string]string
|
||||||
|
approved bool
|
||||||
|
}{
|
||||||
|
{name: "minimal approval", confirmation: map[string]string{types.TransactionResult: "APPROVED"}, receipt: "synthetic initial receipt", approved: true},
|
||||||
|
{name: "confirmation overrides", confirmation: map[string]string{types.TransactionResult: "APPROVED", types.Reference: "SYNTH-CONFIRMED", types.TotalAmount: "2500", types.CardHash: "", types.ReceiptDataCardholder: "synthetic confirmation receipt"}, receipt: "synthetic confirmation receipt", approved: true},
|
||||||
|
{name: "SDK-only uncertainty", confirmation: map[string]string{types.Errors: "ClientNotConnectedToServer"}, receipt: "synthetic initial receipt"},
|
||||||
|
{name: "partial approved XML", rawXML: "<TransactionResult><Entry><Key>TRANSACTION_RESULT</Key><Value>APPROVED</Value></Entry><Entry>", receipt: "synthetic initial receipt"},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
initial := creditCallDiagnosticFields("APPROVED", "")
|
||||||
|
initial[types.TotalAmount] = "3100"
|
||||||
|
initial["AUTH_DATE_TIME"], initial["CARDEASE_REFERENCE"] = "20300101120000", "synthetic-authorization"
|
||||||
|
expected := map[string]string{}
|
||||||
|
for key, value := range initial {
|
||||||
|
if key != types.ReceiptDataCardholder {
|
||||||
|
expected[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key, value := range tc.confirmation {
|
||||||
|
if key != types.ReceiptDataCardholder {
|
||||||
|
expected[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var receipts []string
|
||||||
|
starts, confirms := 0, 0
|
||||||
|
body := &creditCallDiagnosticBody{}
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, creditCallReceipt: func(receipt string) { receipts = append(receipts, receipt) }}
|
||||||
|
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
confirms++
|
||||||
|
if r.URL.Path != "/confirm-transaction/" {
|
||||||
|
t.Errorf("unexpected confirmation path %q", r.URL.Path)
|
||||||
|
}
|
||||||
|
wire := tc.rawXML
|
||||||
|
if wire == "" {
|
||||||
|
wire = chipDNAFixture(t, tc.confirmation)
|
||||||
|
}
|
||||||
|
body.Reader = strings.NewReader(wire)
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: body}, nil
|
||||||
|
})
|
||||||
|
outcome := app.executeCreditCallSale(cmstypes.TransactionRec{AmountMinorUnits: "1234"}, func(*http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
starts++
|
||||||
|
var result creditcall.TransactionResultXML
|
||||||
|
for key, value := range initial {
|
||||||
|
result.Entries = append(result.Entries, creditcall.EntryXML{Key: key, Value: value})
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
})
|
||||||
|
if outcome.Approved != tc.approved || !reflect.DeepEqual(outcome.Payment.Fields, expected) || outcome.Payment.CardholderReceipt != tc.receipt {
|
||||||
|
t.Errorf("Sale(%s) approved/fields/receipt=%t/%v/%q, want %t/%v/%q", tc.name, outcome.Approved, outcome.Payment.Fields, outcome.Payment.CardholderReceipt, tc.approved, expected, tc.receipt)
|
||||||
|
}
|
||||||
|
if !tc.approved && (outcome.Status.Message != "unknown" || outcome.FailureType != "unknown" || outcome.Payment.Status.Message != "APPROVED") {
|
||||||
|
t.Errorf("Sale(%s) status/failure/payment status=%+v/%q/%+v, want uncertainty without mutating merged authorization evidence", tc.name, outcome.Status, outcome.FailureType, outcome.Payment.Status)
|
||||||
|
}
|
||||||
|
if starts != 1 || confirms != 1 || !body.closed || !reflect.DeepEqual(receipts, []string{tc.receipt}) {
|
||||||
|
t.Errorf("Sale(%s) starts/confirms/closed/receipts=%d/%d/%t/%v, want 1/1/true/[%q]", tc.name, starts, confirms, body.closed, receipts, tc.receipt)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
|
func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
|
||||||
for _, streaming := range []bool{false, true} {
|
for _, streaming := range []bool{false, true} {
|
||||||
var attempts int
|
var attempts int
|
||||||
|
|||||||
@@ -0,0 +1,369 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,16 @@
|
|||||||
|
|
||||||
`buildVersion` is a const in `cmd/hardlink/main.go`.
|
`buildVersion` is a const in `cmd/hardlink/main.go`.
|
||||||
|
|
||||||
#### v2.2.1 - Unreleased
|
#### v2.2.4 - 05 November 2026
|
||||||
|
fix(creditcall): require fresh confirmation approval for sale
|
||||||
|
|
||||||
|
#### v2.2.3 - 05 November 2026
|
||||||
|
fix(creditcall): preserve detailed SDK failure diagnostics
|
||||||
|
|
||||||
|
#### v2.2.2 - 05 November 2026
|
||||||
|
fix(creditcall): restore SDK timeout and cancellation classification
|
||||||
|
|
||||||
|
#### v2.2.1 - 04 November 2026
|
||||||
refactor: migrate the Go module and active imports to `gitea.futuresens.co.uk/futuresens/hardlink/v2`; include current module/build documentation.
|
refactor: migrate the Go module and active imports to `gitea.futuresens.co.uk/futuresens/hardlink/v2`; include current module/build documentation.
|
||||||
|
|
||||||
#### v2.2.0 - 02 November 2026
|
#### v2.2.0 - 02 November 2026
|
||||||
Reference in New Issue
Block a user