Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1969aaa1d2 | ||
|
|
c8cbd1e7a3 | ||
|
|
afb8bb0e9e | ||
|
|
93ff67fbb1 |
@@ -0,0 +1,124 @@
|
|||||||
|
# CreditCall payment streaming
|
||||||
|
|
||||||
|
Deploy ChipDNAClientCLI, then hardlink, then Operafyne. No database or configuration
|
||||||
|
migration is needed. The existing CreditCall provider selection enables the new
|
||||||
|
SALE and PREAUTH routes; CreditCall does not implement the generic payment provider interface.
|
||||||
|
|
||||||
|
## Contracts
|
||||||
|
|
||||||
|
`POST /api/payment/sale` accepts the existing JSON sale request, for example
|
||||||
|
`{"amount":1234,"confirmNo":"BOOKING-123","currency":"GBP"}`. Amount remains in
|
||||||
|
minor units. CreditCall uses its existing SDK transaction reference generation.
|
||||||
|
|
||||||
|
`POST /api/payment/preauth` accepts string fields `amount`, `transactionType`
|
||||||
|
and `checkoutDate`. Positive preauth sends the existing `Sale` input and checkout
|
||||||
|
string; zero-value verification sends `{"amount":"","transactionType":"AccountVerification","checkoutDate":""}`.
|
||||||
|
The returned `ACCOUNT VERIFICATION` type is matched case-insensitively and succeeds
|
||||||
|
without persistence. Returned approved `SALE` schedules existing SQL persistence
|
||||||
|
using provider-returned `TOTAL_AMOUNT`, never the request amount. PREAUTH does not
|
||||||
|
confirm. Checkout remains departure-derived midnight UTC in the existing string
|
||||||
|
format; SQL's existing date conversion and 48-hour release calculation are unchanged.
|
||||||
|
|
||||||
|
For CreditCall, responses contain newline-delimited JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"type":"status","code":"PAYMENT_PRESENT_CARD"}
|
||||||
|
{"type":"result","result":{"outcome":"approved","message":"Payment approved","httpStatus":200,"status":{"code":200,"message":"Approved"},"transactionReference":"native-reference","cardType":"Visa","maskedCardNumber":"************1234","expiryDate":"1228","cardHash":"existing-hash","cardReference":"existing-card-reference"}}
|
||||||
|
```
|
||||||
|
|
||||||
|
`outcome` is `approved`, `declined`, `cancelled`, `timeout`, or `error`. Approval
|
||||||
|
is produced only by the shared CreditCall transaction/finalization core, including
|
||||||
|
SALE confirmation behavior; PREAUTH uses its existing unconfirmed-result rules. `httpStatus` preserves the equivalent legacy
|
||||||
|
operation status even after streaming commits HTTP 200. `status` preserves the
|
||||||
|
existing processor `StatusRec`. Failure `message` preserves the plain description
|
||||||
|
used by the legacy flow, including its existing interpretation quirks.
|
||||||
|
|
||||||
|
Card fields are emitted only on success. Unmasked or unexpected card-number data
|
||||||
|
is omitted; encoding is not masking. Receipts and raw SDK parameter bags are not
|
||||||
|
sent to Operafyne. The new adapter never builds a redirect URL. Dojo and PayBridge
|
||||||
|
continue using their existing `{"type":"result","response":...}` contract.
|
||||||
|
|
||||||
|
Hardlink calls `POST /start-transaction-stream/` on ChipDNAClientCLI with
|
||||||
|
`{"amount":"1234","transactionType":"Sale"}`. Its NDJSON consists of allowlisted
|
||||||
|
`status` frames (`source`, `value`), a single `result` containing allowlisted SDK
|
||||||
|
fields, or a sanitized `error`. `TRANSACTION_TYPE` and optional `TOTAL_AMOUNT`
|
||||||
|
are included only when returned by the provider. They are never synthesized and
|
||||||
|
are not added to the kiosk-facing result. AccountVerification normally omits
|
||||||
|
`TOTAL_AMOUNT`. Receipt XML may be a JSON string field needed by
|
||||||
|
hardlink's existing receipt handler; it is never a raw line in the stream.
|
||||||
|
SALE confirmation continues through the existing, separate XML endpoint.
|
||||||
|
|
||||||
|
## Lifetime and compatibility
|
||||||
|
|
||||||
|
- `/start-transaction/`, `/takepayment`, and `/takepreauth` retain their existing
|
||||||
|
external contracts. Both SALE and PREAUTH now stream to Operafyne; existing SQL
|
||||||
|
persistence/release behavior remains unchanged.
|
||||||
|
- Operafyne uses a private 120-second CreditCall client for SALE and PREAUTH.
|
||||||
|
This is only the kiosk wait boundary; Dojo/PayBridge clients are unchanged.
|
||||||
|
Timeout/cancellation is technical, not an authoritative decline or automatically
|
||||||
|
retryable result. It never triggers a second start or legacy endpoint fallback.
|
||||||
|
- Validation uses the inbound request. At financial dispatch handoff, hardlink
|
||||||
|
detaches cancellation with `context.WithoutCancel`. Inbound cancellation and
|
||||||
|
write failures control only delivery; result processing, SALE confirmation,
|
||||||
|
receipts and PREAUTH persistence scheduling continue independently.
|
||||||
|
- Start and each SALE confirmation call retain their independent 300-second timeout.
|
||||||
|
Confirmation still uses two attempts, retrying transport/read errors with the
|
||||||
|
existing two-second delay. The generic whole-operation timeout is not used.
|
||||||
|
- Kiosk cancellation or failed/blocked kiosk delivery does not cancel upstream reading,
|
||||||
|
confirmation, receipt handling, or PREAUTH persistence scheduling. Progress queues may drop hints when full;
|
||||||
|
final results have a separate slot and are delivered at most once.
|
||||||
|
- Only the response writer writes frames. Transaction execution never waits
|
||||||
|
for progress delivery. No additional delivery timer or whole-operation deadline
|
||||||
|
shortens the existing HTTP call bounds.
|
||||||
|
- Native SDK 3.17 updates use `UPDATE`; card notifications use `NOTIFICATION`,
|
||||||
|
retained as `CARD_STATUS` on the internal wire. Normal progress does not require
|
||||||
|
a reference: it is accepted only inside the existing serial transaction's active
|
||||||
|
observational window. A supplied nonempty reference must match. The window opens
|
||||||
|
immediately before the SDK start call and closes immediately at
|
||||||
|
`TransactionFinished`; finalization never waits for card removal.
|
||||||
|
- `CardRemovalRequested` and `CardRemovalEnforced` follow the same active-window
|
||||||
|
rule as other progress, including when no reference is supplied. Real Miura
|
||||||
|
insertion-recovery sequences can repeat present-card and remove-card prompts
|
||||||
|
within one transaction; these repeated prompts are not deduplicated. Outside
|
||||||
|
the active window they are discarded. `Removed` remains omitted even with a
|
||||||
|
reference, and the existing `Inserted` mapping is unchanged.
|
||||||
|
- Ownership is best-effort UI observation. SDK 3.17 does not establish that every
|
||||||
|
queued reference-less callback, including removal, has drained before another transaction
|
||||||
|
starts. Such a callback may briefly display stale progress in a later active
|
||||||
|
window. This accepted limitation must never affect success, decline, cancellation,
|
||||||
|
timeout outcomes, confirmation, retry, receipts, PMS posting, or business state.
|
||||||
|
- After timeout, an ambiguous start error, an asynchronous SDK error during an
|
||||||
|
active window, or reference reuse/overlap, progress remains suppressed for that
|
||||||
|
`Client` lifetime across SALE and PREAUTH. New transactions, elapsed time, callbacks and automatic
|
||||||
|
reconnect do not reset the guard. Payments remain enabled.
|
||||||
|
- Only the exact synchronous `ClientNotConnectedToServer` error safely clears an
|
||||||
|
unsuppressed window and releases its unused reference: SDK 3.17 `StartCommand`
|
||||||
|
returns it before `SendRequest`. Validation errors, mixed errors and all other
|
||||||
|
unproven errors suppress observation. Safe pre-dispatch rejection never clears
|
||||||
|
an existing suppression latch.
|
||||||
|
- Progress cannot approve, decline, confirm, cancel, or retry a transaction.
|
||||||
|
`OnlineAuthCompleted` means waiting; `Removed` and unknown events are omitted.
|
||||||
|
|
||||||
|
## Automated verification
|
||||||
|
|
||||||
|
In hardlink, use `go test -count=1 -skip '^Test_SendMail$' ./...` to exclude the
|
||||||
|
existing test that sends real email. Focused tests cover legacy parity, malformed
|
||||||
|
XML/NDJSON, retained confirmation fields and receipts, retries, disconnects,
|
||||||
|
backpressure, field filtering, and conservative status mapping. Race checks cover
|
||||||
|
the changed handler and mapper packages. No test proves absence of orphan holds.
|
||||||
|
|
||||||
|
In ChipDNAClientCLI, build `ChipDnaClient.sln` and `Tests/StreamingTests.csproj`
|
||||||
|
with MSBuild, then run `Tests/bin/Debug/ChipDNAClient.StreamingTests.exe`. The
|
||||||
|
test executable links the production streaming code and needs no terminal.
|
||||||
|
|
||||||
|
In Operafyne, run `go test -count=1 ./...`; the service tests cover structured
|
||||||
|
CreditCall SALE/PREAUTH, unchanged legacy requests, the 120-second UX boundary,
|
||||||
|
cancellation after dispatch, failure/retry parity, and existing
|
||||||
|
Dojo/PayBridge response handling. Run `go vet ./...`, `go build ./...`, and
|
||||||
|
`git diff --check` in both Go repositories.
|
||||||
|
|
||||||
|
Physical account-verification testing confirmed approved `ACCOUNT VERIFICATION`
|
||||||
|
with no `TOTAL_AMOUNT`. A monetary `/takepayment` test confirmed returned minor
|
||||||
|
units; positive PREAUTH through the new transport still needs physical Miura
|
||||||
|
validation. Automated tests do not replace that check. Receipt fields such as
|
||||||
|
`NoChargeDeclaration` retain the existing provider-entry rendering behavior.
|
||||||
@@ -33,7 +33,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
buildVersion = "v1.3.6"
|
buildVersion = "v2.0.1"
|
||||||
serviceName = "hardlink"
|
serviceName = "hardlink"
|
||||||
pollingFrequency = 8 * time.Second
|
pollingFrequency = 8 * time.Second
|
||||||
)
|
)
|
||||||
@@ -135,7 +135,8 @@ func main() {
|
|||||||
|
|
||||||
switch paymentProvider {
|
switch paymentProvider {
|
||||||
case cmstypes.PaySystemCreditCall:
|
case cmstypes.PaySystemCreditCall:
|
||||||
// CreditCall keeps using the existing /takepayment and /takepreauth endpoints.
|
// CreditCall streaming shares its proven legacy transaction core.
|
||||||
|
app.EnableCreditCallStreaming()
|
||||||
startChipDnaClient()
|
startChipDnaClient()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -203,7 +204,7 @@ func main() {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only PayBridge and Dojo use POST /api/payment/sale.
|
// PayBridge and Dojo use the generic payment service.
|
||||||
if provider != nil {
|
if provider != nil {
|
||||||
app.SetPaymentService(paymentsvc.NewService(provider))
|
app.SetPaymentService(paymentsvc.NewService(provider))
|
||||||
log.Infof("Payment provider enabled for POST /api/payment/sale: %s", cmstypes.PaySystemNames[paymentProvider])
|
log.Infof("Payment provider enabled for POST /api/payment/sale: %s", cmstypes.PaySystemNames[paymentProvider])
|
||||||
|
|||||||
@@ -125,6 +125,15 @@ func BuildPaymentRedirectURL(result map[string]string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
||||||
|
approved, persist := PreauthDecision(result)
|
||||||
|
if approved {
|
||||||
|
return BuildSuccessURL(result), persist
|
||||||
|
}
|
||||||
|
return BuildFailureURL(result[types.TransactionResult], result[types.Errors]), false
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreauthDecision preserves the returned-type approval and persistence rules.
|
||||||
|
func PreauthDecision(result map[string]string) (approved, persist bool) {
|
||||||
res := result[types.TransactionResult]
|
res := result[types.TransactionResult]
|
||||||
tType := result[types.TransactionType]
|
tType := result[types.TransactionType]
|
||||||
|
|
||||||
@@ -136,7 +145,7 @@ func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
|||||||
log.WithField(types.LogResult, result[types.TransactionResult]).
|
log.WithField(types.LogResult, result[types.TransactionResult]).
|
||||||
Info("Account verification approved")
|
Info("Account verification approved")
|
||||||
|
|
||||||
return BuildSuccessURL(result), false
|
return true, false
|
||||||
|
|
||||||
// Transaction type Sale?
|
// Transaction type Sale?
|
||||||
case strings.EqualFold(tType, types.SaleTransactionType):
|
case strings.EqualFold(tType, types.SaleTransactionType):
|
||||||
@@ -144,12 +153,12 @@ func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
|||||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||||
Info("Amount preauthorized successfully")
|
Info("Amount preauthorized successfully")
|
||||||
|
|
||||||
return BuildSuccessURL(result), true
|
return true, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Not approved
|
// Not approved
|
||||||
return BuildFailureURL(res, result[types.Errors]), false
|
return false, false
|
||||||
}
|
}
|
||||||
|
|
||||||
func BuildSuccessURL(result map[string]string) string {
|
func BuildSuccessURL(result map[string]string) string {
|
||||||
@@ -168,9 +177,7 @@ func BuildSuccessURL(result map[string]string) string {
|
|||||||
|
|
||||||
func BuildFailureURL(msgType, description string) string {
|
func BuildFailureURL(msgType, description string) string {
|
||||||
q := url.Values{}
|
q := url.Values{}
|
||||||
if msgType != "" {
|
description = FailureDescription(msgType, description)
|
||||||
description = fmt.Sprintf("Transaction %s", strings.ToLower(msgType))
|
|
||||||
}
|
|
||||||
if description != "" {
|
if description != "" {
|
||||||
msgType = types.ResultError
|
msgType = types.ResultError
|
||||||
}
|
}
|
||||||
@@ -185,3 +192,12 @@ func BuildFailureURL(msgType, description string) string {
|
|||||||
RawQuery: q.Encode(),
|
RawQuery: q.Encode(),
|
||||||
}).String()
|
}).String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FailureDescription preserves the description used by the legacy payment flow
|
||||||
|
// without requiring structured consumers to construct a redirect URL.
|
||||||
|
func FailureDescription(msgType, description string) string {
|
||||||
|
if msgType != "" {
|
||||||
|
return fmt.Sprintf("Transaction %s", strings.ToLower(msgType))
|
||||||
|
}
|
||||||
|
return description
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package creditcall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPreauthLegacyDecision(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, result, kind string
|
||||||
|
approved, save bool
|
||||||
|
}{
|
||||||
|
{"sale", "APPROVED", "SALE", true, true},
|
||||||
|
{"verification", "APPROVED", "ACCOUNT VERIFICATION", true, false},
|
||||||
|
{"mixed case", "Approved", "Account Verification", true, false},
|
||||||
|
{"request spelling is not result spelling", "APPROVED", "AccountVerification", false, false},
|
||||||
|
{"missing type", "APPROVED", "", false, false},
|
||||||
|
{"declined sale", "DECLINED", "SALE", false, false},
|
||||||
|
{"declined verification", "DECLINED", "ACCOUNT VERIFICATION", false, false},
|
||||||
|
{"missing result", "", "SALE", false, false},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
fields := map[string]string{types.TransactionResult: tc.result, types.TransactionType: tc.kind, types.Errors: "provider detail"}
|
||||||
|
redirect, save := BuildPreauthRedirectURL(fields)
|
||||||
|
if strings.HasPrefix(redirect, "/successful?") != tc.approved || save != tc.save {
|
||||||
|
t.Errorf("BuildPreauthRedirectURL(%v) = %q,%t, want approved=%t save=%t", fields, redirect, save, tc.approved, tc.save)
|
||||||
|
}
|
||||||
|
if _, ok := fields[types.TotalAmount]; ok {
|
||||||
|
t.Error("BuildPreauthRedirectURL fabricated TOTAL_AMOUNT")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package creditcall
|
||||||
|
|
||||||
|
import "gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
||||||
|
|
||||||
|
// ProgressStatus maps informational SDK events, never financial decisions.
|
||||||
|
func ProgressStatus(source, value string) string {
|
||||||
|
switch source {
|
||||||
|
case "UPDATE":
|
||||||
|
switch value {
|
||||||
|
case "CardRequested", "ProvideCard", "InsertOrSwipeCard", "InsertOrContactless":
|
||||||
|
return paymentstatus.PresentCard
|
||||||
|
case "InsertCard":
|
||||||
|
return paymentstatus.InsertCard
|
||||||
|
case "SwipeCard":
|
||||||
|
return paymentstatus.SwipeCard
|
||||||
|
case "CardRemovalRequested", "CardRemovalEnforced":
|
||||||
|
return paymentstatus.RemoveCard
|
||||||
|
case "PinEntryStarted", "PinEntryPrompt", "PinEntryInProgress":
|
||||||
|
return paymentstatus.EnterPIN
|
||||||
|
case "PinEntryFailed":
|
||||||
|
return paymentstatus.EnterPINAgain
|
||||||
|
case "PinEntrySuccessful", "TransactionStarted", "OnlineAuthRequested", "OnlineAuthorizeRequest":
|
||||||
|
return paymentstatus.Processing
|
||||||
|
case "OnlineAuthCompleted":
|
||||||
|
return paymentstatus.PleaseWait
|
||||||
|
}
|
||||||
|
case "CARD_STATUS":
|
||||||
|
switch value {
|
||||||
|
case "Inserted":
|
||||||
|
return paymentstatus.DoNotRemoveCard
|
||||||
|
case "Tapped", "Swiped":
|
||||||
|
return paymentstatus.Processing
|
||||||
|
}
|
||||||
|
case "SIGNATURE":
|
||||||
|
if value == "Requested" {
|
||||||
|
return paymentstatus.SignatureRequired
|
||||||
|
}
|
||||||
|
case "PAUSE":
|
||||||
|
if value == "Paused" {
|
||||||
|
return paymentstatus.PleaseWait
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// MaskedCardNumber excludes unmasked or unexpected SDK data from the new wire contract.
|
||||||
|
func MaskedCardNumber(value string) string {
|
||||||
|
digits, masks := 0, 0
|
||||||
|
for _, ch := range value {
|
||||||
|
switch {
|
||||||
|
case ch >= '0' && ch <= '9':
|
||||||
|
digits++
|
||||||
|
case ch == '*' || ch == 'x' || ch == 'X':
|
||||||
|
masks++
|
||||||
|
case ch == ' ' || ch == '-':
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if masks < 4 || digits > 10 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package creditcall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProgressStatus(t *testing.T) {
|
||||||
|
for _, test := range []struct{ source, value, want string }{
|
||||||
|
{"UPDATE", "CardRequested", paymentstatus.PresentCard},
|
||||||
|
{"UPDATE", "ProvideCard", paymentstatus.PresentCard},
|
||||||
|
{"UPDATE", "InsertOrSwipeCard", paymentstatus.PresentCard},
|
||||||
|
{"UPDATE", "InsertOrContactless", paymentstatus.PresentCard},
|
||||||
|
{"UPDATE", "InsertCard", paymentstatus.InsertCard},
|
||||||
|
{"UPDATE", "SwipeCard", paymentstatus.SwipeCard},
|
||||||
|
{"UPDATE", "CardRemovalRequested", paymentstatus.RemoveCard},
|
||||||
|
{"UPDATE", "CardRemovalEnforced", paymentstatus.RemoveCard},
|
||||||
|
{"UPDATE", "PinEntryStarted", paymentstatus.EnterPIN},
|
||||||
|
{"UPDATE", "PinEntryPrompt", paymentstatus.EnterPIN},
|
||||||
|
{"UPDATE", "PinEntryInProgress", paymentstatus.EnterPIN},
|
||||||
|
{"UPDATE", "PinEntryFailed", paymentstatus.EnterPINAgain},
|
||||||
|
{"UPDATE", "PinEntrySuccessful", paymentstatus.Processing},
|
||||||
|
{"UPDATE", "TransactionStarted", paymentstatus.Processing},
|
||||||
|
{"UPDATE", "OnlineAuthRequested", paymentstatus.Processing},
|
||||||
|
{"UPDATE", "OnlineAuthorizeRequest", paymentstatus.Processing},
|
||||||
|
{"UPDATE", "OnlineAuthCompleted", paymentstatus.PleaseWait},
|
||||||
|
{"CARD_STATUS", "Inserted", paymentstatus.DoNotRemoveCard},
|
||||||
|
{"CARD_STATUS", "Tapped", paymentstatus.Processing},
|
||||||
|
{"CARD_STATUS", "Swiped", paymentstatus.Processing},
|
||||||
|
{"CARD_STATUS", "Removed", ""},
|
||||||
|
{"SIGNATURE", "Requested", paymentstatus.SignatureRequired},
|
||||||
|
{"PAUSE", "Paused", paymentstatus.PleaseWait},
|
||||||
|
{"UPDATE", "Approved", ""}, {"UPDATE", "Declined", ""},
|
||||||
|
{"UPDATE", "unknown", ""}, {"PAN", "CardRequested", ""},
|
||||||
|
} {
|
||||||
|
if got := ProgressStatus(test.source, test.value); got != test.want {
|
||||||
|
t.Errorf("ProgressStatus(%q, %q) = %q, want %q", test.source, test.value, got, test.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMaskedCardNumber(t *testing.T) {
|
||||||
|
for _, test := range []struct{ value, want string }{
|
||||||
|
{"123456******1234", "123456******1234"}, {"************1234", "************1234"},
|
||||||
|
{"1234567890123456", ""}, {"1234567890123456****", ""}, {"3132333435363738", ""},
|
||||||
|
{"%B1234567890123456^NAME", ""}, {"", ""},
|
||||||
|
} {
|
||||||
|
if got := MaskedCardNumber(test.value); got != test.want {
|
||||||
|
t.Errorf("MaskedCardNumber(%q) = %q, want %q", test.value, got, test.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
type creditCallPreauthRequest struct {
|
||||||
|
Amount string `json:"amount"`
|
||||||
|
TransactionType string `json:"transactionType"`
|
||||||
|
CheckoutDate string `json:"checkoutDate"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (app *App) streamCreditCallPreauth(w http.ResponseWriter, r *http.Request) {
|
||||||
|
app.streamCreditCall(w, r, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// executeCreditCallPreauth finalizes the existing unconfirmed transaction.
|
||||||
|
// The outcome container and its wire projections are shared with SALE; its execution is not.
|
||||||
|
func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.TransactionRec,
|
||||||
|
start func(*http.Client) (creditcall.TransactionResultXML, error)) creditCallSaleOutcome {
|
||||||
|
const op = logging.Op("takePreauthorization")
|
||||||
|
outcome := creditCallSaleOutcome{
|
||||||
|
HTTPStatus: http.StatusBadGateway,
|
||||||
|
Status: cmstypes.StatusRec{Code: http.StatusInternalServerError, Message: "500 Internal server error"},
|
||||||
|
}
|
||||||
|
transaction, err := start(app.creditCallClient())
|
||||||
|
if err != nil {
|
||||||
|
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
||||||
|
outcome.FailureType = types.ResultError
|
||||||
|
outcome.FailureDescription = "No response from payment processor"
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
var result creditcall.PaymentResult
|
||||||
|
result.FillFromTransactionResult(transaction)
|
||||||
|
app.printCreditCallReceipt(result.CardholderReceipt)
|
||||||
|
approved, persist := creditcall.PreauthDecision(result.Fields)
|
||||||
|
outcome.HTTPStatus = http.StatusOK
|
||||||
|
outcome.Status = result.Status
|
||||||
|
outcome.Payment = result
|
||||||
|
outcome.Approved = approved
|
||||||
|
outcome.FailureType = result.Fields[types.TransactionResult]
|
||||||
|
outcome.FailureDescription = result.Fields[types.Errors]
|
||||||
|
if persist {
|
||||||
|
go app.persistPreauth(ctx, result.Fields, request.CheckoutDate)
|
||||||
|
}
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
||||||
|
)
|
||||||
|
|
||||||
|
type preauthTestConnector struct {
|
||||||
|
inserts chan []driver.NamedValue
|
||||||
|
count atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *preauthTestConnector) Connect(context.Context) (driver.Conn, error) {
|
||||||
|
return &preauthTestConn{c}, nil
|
||||||
|
}
|
||||||
|
func (c *preauthTestConnector) Driver() driver.Driver { return preauthTestDriver{c} }
|
||||||
|
|
||||||
|
type preauthTestDriver struct{ c *preauthTestConnector }
|
||||||
|
|
||||||
|
func (d preauthTestDriver) Open(string) (driver.Conn, error) { return &preauthTestConn{d.c}, nil }
|
||||||
|
|
||||||
|
type preauthTestConn struct{ c *preauthTestConnector }
|
||||||
|
|
||||||
|
func (*preauthTestConn) Prepare(string) (driver.Stmt, error) {
|
||||||
|
return nil, errors.New("unexpected prepare")
|
||||||
|
}
|
||||||
|
func (*preauthTestConn) Close() error { return nil }
|
||||||
|
func (*preauthTestConn) Begin() (driver.Tx, error) { return nil, errors.New("unexpected begin") }
|
||||||
|
func (*preauthTestConn) Ping(context.Context) error { return nil }
|
||||||
|
func (c *preauthTestConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
if !strings.Contains(query, "INSERT INTO dbo.Preauthorizations") {
|
||||||
|
return nil, errors.New("unexpected SQL")
|
||||||
|
}
|
||||||
|
c.c.count.Add(1)
|
||||||
|
c.c.inserts <- append([]driver.NamedValue(nil), args...)
|
||||||
|
return driver.RowsAffected(1), nil
|
||||||
|
}
|
||||||
|
func preauthTestDatabase(t *testing.T, app *App) *preauthTestConnector {
|
||||||
|
t.Helper()
|
||||||
|
c := &preauthTestConnector{inserts: make(chan []driver.NamedValue, 4)}
|
||||||
|
app.db = sql.OpenDB(c)
|
||||||
|
app.cfg.LogDir = t.TempDir()
|
||||||
|
t.Cleanup(func() { app.db.Close() })
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
func waitPreauthInsert(t *testing.T, c *preauthTestConnector) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
select {
|
||||||
|
case args := <-c.inserts:
|
||||||
|
result := map[string]any{}
|
||||||
|
for _, arg := range args {
|
||||||
|
result[arg.Name] = arg.Value
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("preauth persistence did not reach SQL")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func preauthLegacyRequest(amount, kind, checkout string) *http.Request {
|
||||||
|
body, _ := xml.Marshal(cmstypes.TransactionRec{AmountMinorUnits: amount, TransactionType: kind, CheckoutDate: checkout})
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/takepreauth", strings.NewReader(string(body)))
|
||||||
|
r.Header.Set("Content-Type", "text/xml")
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthLegacyCharacterization(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, amount, requestType, result, resultType, total string
|
||||||
|
save, approved bool
|
||||||
|
}{
|
||||||
|
{"positive", "12000", "Sale", "APPROVED", "SALE", "3100", true, true},
|
||||||
|
{"declined", "12000", "Sale", "DECLINED", "SALE", "", false, false},
|
||||||
|
{"verification", "", "AccountVerification", "APPROVED", "ACCOUNT VERIFICATION", "", false, true},
|
||||||
|
{"verification failure", "", "AccountVerification", "DECLINED", "ACCOUNT VERIFICATION", "", false, false},
|
||||||
|
{"unexpected type", "12000", "Sale", "APPROVED", "Refund", "", false, false},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
var starts, prints int
|
||||||
|
checkout := ""
|
||||||
|
if tc.amount != "" {
|
||||||
|
checkout = "2026-09-11 00:00:00 +0000"
|
||||||
|
}
|
||||||
|
fields := map[string]string{types.TransactionResult: tc.result, types.TransactionType: tc.resultType, types.Reference: "preauth-ref", types.PanMasked: "************1133", types.CardType: "Visa", types.ExpiryDate: "1228", types.CardHash: "card-hash", types.CardReference: "card-reference", types.ReceiptDataCardholder: "receipt"}
|
||||||
|
if tc.total != "" {
|
||||||
|
fields[types.TotalAmount] = tc.total
|
||||||
|
}
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
starts++
|
||||||
|
if r.URL.Path != "/start-transaction/" {
|
||||||
|
t.Errorf("PREAUTH upstream path=%s, want start only", r.URL.Path)
|
||||||
|
}
|
||||||
|
var input cmstypes.TransactionRec
|
||||||
|
if err := xml.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
if input.AmountMinorUnits != tc.amount || input.TransactionType != tc.requestType || input.CheckoutDate != checkout {
|
||||||
|
t.Errorf("PREAUTH input=%+v, want amount=%q type=%q checkout=%q", input, tc.amount, tc.requestType, checkout)
|
||||||
|
}
|
||||||
|
// Legacy ignores upstream HTTP status when XML contains a result.
|
||||||
|
w.WriteHeader(http.StatusBadGateway)
|
||||||
|
io.WriteString(w, chipDNAFixture(t, fields))
|
||||||
|
})
|
||||||
|
c := preauthTestDatabase(t, app)
|
||||||
|
app.creditCallReceipt = func(receipt string) {
|
||||||
|
prints++
|
||||||
|
if receipt != "receipt" {
|
||||||
|
t.Errorf("receipt=%q, want receipt", receipt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
app.takePreauthorization(recorder, preauthLegacyRequest(tc.amount, tc.requestType, checkout))
|
||||||
|
var response cmstypes.ResponseRec
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if recorder.Code != 200 || response.Status.Code != 200 || starts != 1 || prints != 1 || strings.HasPrefix(response.Data, "/successful?") != tc.approved {
|
||||||
|
t.Errorf("PREAUTH response=%+v HTTP=%d starts=%d prints=%d, want approved=%t one start/receipt", response, recorder.Code, starts, prints, tc.approved)
|
||||||
|
}
|
||||||
|
if tc.save {
|
||||||
|
got := waitPreauthInsert(t, c)
|
||||||
|
if got["TotalMinorUnits"] != "3100" || got["TxnReference"] != "preauth-ref" {
|
||||||
|
t.Errorf("persisted=%v, want provider amount/reference", got)
|
||||||
|
}
|
||||||
|
departure := time.Date(2026, 9, 11, 0, 0, 0, 0, time.Local).UTC()
|
||||||
|
if got["DepartureDate"] != departure || got["ReleaseDate"] != departure.Add(48*time.Hour) {
|
||||||
|
t.Errorf("persisted dates=%v, want existing local midnight plus 48 hours", got)
|
||||||
|
}
|
||||||
|
} else if c.count.Load() != 0 {
|
||||||
|
t.Error("non-persisting result inserted SQL")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func preauthStreamRequest(amount, kind, checkout string) *http.Request {
|
||||||
|
body, _ := json.Marshal(creditCallPreauthRequest{Amount: amount, TransactionType: kind, CheckoutDate: checkout})
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/api/payment/preauth", strings.NewReader(string(body)))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthStreamingParity(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, result, kind, total string
|
||||||
|
approved, persist bool
|
||||||
|
}{
|
||||||
|
{"monetary", "APPROVED", "SALE", "3100", true, true},
|
||||||
|
{"verification", "APPROVED", "ACCOUNT VERIFICATION", "", true, false},
|
||||||
|
{"declined", "DECLINED", "SALE", "", false, false},
|
||||||
|
{"verification failed", "DECLINED", "ACCOUNT VERIFICATION", "", false, false},
|
||||||
|
{"unknown approved type", "APPROVED", "AccountVerification", "", false, false},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
fields := map[string]string{types.TransactionResult: tc.result, types.TransactionType: tc.kind, types.Reference: "preauth-ref", types.PanMasked: "************1133", types.CardType: "Visa", types.ExpiryDate: "1228", types.CardHash: "hash", types.CardReference: "cardref", types.ReceiptDataCardholder: "receipt"}
|
||||||
|
if tc.total != "" {
|
||||||
|
fields[types.TotalAmount] = tc.total
|
||||||
|
}
|
||||||
|
amount, kind, date := "12000", "Sale", "2026-09-11 00:00:00 +0000"
|
||||||
|
if strings.Contains(tc.name, "verification") {
|
||||||
|
amount, kind, date = "", "AccountVerification", ""
|
||||||
|
}
|
||||||
|
var legacy cmstypes.ResponseRec
|
||||||
|
for _, stream := range []bool{false, true} {
|
||||||
|
calls, prints := 0, 0
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls++
|
||||||
|
if stream {
|
||||||
|
if r.URL.Path != "/start-transaction-stream/" {
|
||||||
|
t.Errorf("stream called %s, want one generic start", r.URL.Path)
|
||||||
|
}
|
||||||
|
var input creditCallPreauthRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
if input.Amount != amount || input.TransactionType != kind {
|
||||||
|
t.Errorf("upstream input=%+v, want %q/%q", input, amount, kind)
|
||||||
|
}
|
||||||
|
for _, event := range []struct{ source, value string }{{"UPDATE", "CardRequested"}, {"CARD_STATUS", "Inserted"}, {"UPDATE", "CardRemovalRequested"}, {"CARD_STATUS", "Removed"}, {"UPDATE", "CardRequested"}, {"UPDATE", "CardRemovalEnforced"}, {"UPDATE", "PinEntryStarted"}, {"UPDATE", "OnlineAuthCompleted"}} {
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "status", "source": event.source, "value": event.value})
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields})
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields})
|
||||||
|
} else {
|
||||||
|
io.WriteString(w, chipDNAFixture(t, fields))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
c := preauthTestDatabase(t, app)
|
||||||
|
app.creditCallReceipt = func(receipt string) {
|
||||||
|
prints++
|
||||||
|
if receipt != "receipt" {
|
||||||
|
t.Errorf("receipt=%q, want retained receipt", receipt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
if stream {
|
||||||
|
app.streamCreditCallPreauth(recorder, preauthStreamRequest(amount, kind, date))
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
var statuses []string
|
||||||
|
for _, frame := range frames {
|
||||||
|
if frame.Type == "status" {
|
||||||
|
statuses = append(statuses, frame.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want := []string{paymentstatus.PresentCard, paymentstatus.DoNotRemoveCard, paymentstatus.RemoveCard, paymentstatus.PresentCard, paymentstatus.RemoveCard, paymentstatus.EnterPIN, paymentstatus.PleaseWait}
|
||||||
|
if !reflect.DeepEqual(statuses, want) {
|
||||||
|
t.Errorf("preauth statuses=%v, want %v", statuses, want)
|
||||||
|
}
|
||||||
|
final := frames[len(frames)-1].Result
|
||||||
|
if final == nil {
|
||||||
|
t.Fatal("missing structured final")
|
||||||
|
}
|
||||||
|
if (final.Outcome == "approved") != tc.approved || final.Status != legacy.Status || final.HTTPStatus != 200 {
|
||||||
|
t.Errorf("stream final=%+v, legacy=%+v", final, legacy)
|
||||||
|
}
|
||||||
|
if tc.approved && (final.TransactionReference != "preauth-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1133" || final.ExpiryDate != "1228" || final.CardHash != "hash" || final.CardReference != "cardref") {
|
||||||
|
t.Errorf("preauth fields lost: %+v", final)
|
||||||
|
}
|
||||||
|
if len(frames) != len(want)+1 {
|
||||||
|
t.Errorf("frames=%d, want one final", len(frames))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
app.takePreauthorization(recorder, preauthLegacyRequest(amount, kind, date))
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &legacy); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if calls != 1 || prints != 1 {
|
||||||
|
t.Errorf("calls/prints=%d/%d, want 1/1", calls, prints)
|
||||||
|
}
|
||||||
|
if tc.persist {
|
||||||
|
got := waitPreauthInsert(t, c)
|
||||||
|
if got["TotalMinorUnits"] != tc.total {
|
||||||
|
t.Errorf("SQL amount=%v, want provider %q", got["TotalMinorUnits"], tc.total)
|
||||||
|
}
|
||||||
|
} else if c.count.Load() != 0 {
|
||||||
|
t.Error("verification/failure persisted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallInboundCancellationAfterDispatch(t *testing.T) {
|
||||||
|
for _, preauth := range []bool{false, true} {
|
||||||
|
t.Run(map[bool]string{false: "sale", true: "preauth"}[preauth], func(t *testing.T) {
|
||||||
|
dispatched := make(chan struct{})
|
||||||
|
release := make(chan struct{})
|
||||||
|
var starts, confirms, receipts atomic.Int32
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path == "/confirm-transaction/" {
|
||||||
|
confirms.Add(1)
|
||||||
|
io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: "APPROVED", types.ReceiptDataCardholder: "receipt"}))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
starts.Add(1)
|
||||||
|
close(dispatched)
|
||||||
|
<-release
|
||||||
|
if r.Context().Err() != nil {
|
||||||
|
t.Errorf("financial upstream was cancelled: %v", r.Context().Err())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "SALE", types.TotalAmount: "3100", types.Reference: "delayed-ref", types.ReceiptDataCardholder: "receipt"}})
|
||||||
|
})
|
||||||
|
c := preauthTestDatabase(t, app)
|
||||||
|
app.creditCallReceipt = func(receipt string) {
|
||||||
|
if receipt != "receipt" {
|
||||||
|
t.Errorf("receipt=%q", receipt)
|
||||||
|
}
|
||||||
|
receipts.Add(1)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
if preauth {
|
||||||
|
app.streamCreditCallPreauth(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000").WithContext(ctx))
|
||||||
|
} else {
|
||||||
|
app.streamCreditCallSale(recorder, saleRequest(true).WithContext(ctx))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-dispatched:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
close(release)
|
||||||
|
t.Fatal("no upstream dispatch")
|
||||||
|
}
|
||||||
|
cancel() // Exact acceptance boundary: upstream has observed StartTransaction.
|
||||||
|
close(release)
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("cancelled inbound request stopped finalization")
|
||||||
|
}
|
||||||
|
wantConfirms := int32(1)
|
||||||
|
if preauth {
|
||||||
|
wantConfirms = 0
|
||||||
|
got := waitPreauthInsert(t, c)
|
||||||
|
if got["TotalMinorUnits"] != "3100" {
|
||||||
|
t.Errorf("delayed persistence=%v", got)
|
||||||
|
}
|
||||||
|
if c.count.Load() != 1 {
|
||||||
|
t.Errorf("delayed persistence count=%d, want exactly one", c.count.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if starts.Load() != 1 || receipts.Load() != 1 || confirms.Load() != wantConfirms {
|
||||||
|
t.Errorf("starts/receipts/confirms=%d/%d/%d, want 1/1/%d", starts.Load(), receipts.Load(), confirms.Load(), wantConfirms)
|
||||||
|
}
|
||||||
|
if recorder.Body.Len() != 0 {
|
||||||
|
t.Errorf("cancelled delivery wrote %s", recorder.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthMissingAmountNeverSynthesized(t *testing.T) {
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "SALE", types.Reference: "missing-amount"}})
|
||||||
|
})
|
||||||
|
c := preauthTestDatabase(t, app)
|
||||||
|
app.creditCallReceipt = func(string) {}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
app.streamCreditCallPreauth(recorder, preauthStreamRequest("9999", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
if frames[0].Result.Outcome != "approved" {
|
||||||
|
t.Fatalf("missing amount changed approval: %+v", frames[0].Result)
|
||||||
|
}
|
||||||
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
|
for {
|
||||||
|
data, err := os.ReadFile(app.spoolPath())
|
||||||
|
var record preauthSpoolRecord
|
||||||
|
if err == nil && json.Unmarshal(data, &record) == nil {
|
||||||
|
if _, ok := record.Fields[types.TotalAmount]; ok {
|
||||||
|
t.Errorf("spool fabricated amount: %v", record.Fields)
|
||||||
|
}
|
||||||
|
if record.CheckoutDate != "2026-09-11 00:00:00 +0000" {
|
||||||
|
t.Errorf("spool checkout=%q", record.CheckoutDate)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("missing provider amount did not retain existing spool fallback")
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
if c.count.Load() != 0 {
|
||||||
|
t.Error("SQL inserted fabricated amount")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthStreamFailureAndCancelledBeforeDispatch(t *testing.T) {
|
||||||
|
for _, body := range []string{"", "{", "{}\n", "<xml/>\n", "{\"type\":\"result\",\"result\":{}}\n", "{\"type\":\"result\",\"result\":{\"TRANSACTION_RESULT\":\"APPROVED\"}}"} {
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, body) })
|
||||||
|
calls := 0
|
||||||
|
transport := app.creditCallTransport
|
||||||
|
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { calls++; return transport.RoundTrip(r) })
|
||||||
|
app.creditCallReceipt = func(string) { t.Error("malformed stream printed receipt") }
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
app.streamCreditCallPreauth(recorder, preauthStreamRequest("", "AccountVerification", ""))
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
if calls != 1 || len(frames) != 1 || frames[0].Result.Outcome != "error" || frames[0].Result.HTTPStatus != 502 {
|
||||||
|
t.Errorf("invalid stream %q: calls=%d frames=%+v", body, calls, frames)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
app.streamCreditCallPreauth(httptest.NewRecorder(), preauthStreamRequest("", "AccountVerification", "").WithContext(ctx))
|
||||||
|
if calls != 1 {
|
||||||
|
t.Error("already-cancelled request dispatched a transaction")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/logging"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
// creditCallSaleOutcome is the transaction outcome before either wire format is applied.
|
||||||
|
type creditCallSaleOutcome struct {
|
||||||
|
HTTPStatus int
|
||||||
|
Status cmstypes.StatusRec
|
||||||
|
Payment creditcall.PaymentResult
|
||||||
|
Approved bool
|
||||||
|
FailureType string
|
||||||
|
FailureDescription string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (app *App) creditCallClient() *http.Client {
|
||||||
|
// Each start/confirm call gets the original independent timeout. In particular,
|
||||||
|
// neither a kiosk disconnect nor a whole-sale deadline bounds confirmation.
|
||||||
|
return &http.Client{Timeout: 300 * time.Second, Transport: app.creditCallTransport}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (app *App) printCreditCallReceipt(receipt string) {
|
||||||
|
if app.creditCallReceipt != nil {
|
||||||
|
app.creditCallReceipt(receipt)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
printer.PrintReceipt(receipt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (app *App) executeCreditCallSale(
|
||||||
|
request cmstypes.TransactionRec,
|
||||||
|
start func(*http.Client) (creditcall.TransactionResultXML, error),
|
||||||
|
) creditCallSaleOutcome {
|
||||||
|
const op = logging.Op("takePayment")
|
||||||
|
outcome := creditCallSaleOutcome{
|
||||||
|
HTTPStatus: http.StatusBadGateway,
|
||||||
|
Status: cmstypes.StatusRec{Code: http.StatusInternalServerError, Message: "500 Internal server error"},
|
||||||
|
}
|
||||||
|
client := app.creditCallClient()
|
||||||
|
trResult, err := start(client)
|
||||||
|
if err != nil {
|
||||||
|
logging.Error(types.ServiceName, err.Error(), "Start transaction error", string(op), "", "", 0)
|
||||||
|
outcome.FailureType = types.ResultError
|
||||||
|
outcome.FailureDescription = "No response from payment processor"
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
var result creditcall.PaymentResult
|
||||||
|
result.FillFromTransactionResult(trResult)
|
||||||
|
res := result.Fields[types.TransactionResult]
|
||||||
|
if !strings.EqualFold(res, types.ResultApproved) {
|
||||||
|
app.printCreditCallReceipt(result.CardholderReceipt)
|
||||||
|
desc := result.Fields[types.ErrorDescription]
|
||||||
|
if desc == "" {
|
||||||
|
desc = result.Fields[types.Errors]
|
||||||
|
}
|
||||||
|
logging.Error(types.ServiceName, "Preauthorization failed", "Result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||||
|
outcome.HTTPStatus = http.StatusOK
|
||||||
|
outcome.Status = result.Status
|
||||||
|
outcome.Payment = result
|
||||||
|
outcome.FailureType = res
|
||||||
|
outcome.FailureDescription = result.Fields[types.Errors]
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
ref := result.Fields[types.Reference]
|
||||||
|
log.Printf("Preauth approved, reference: %s. Sending confirm...", ref)
|
||||||
|
body, err := confirmWithRetry(client, creditcall.ConfirmTransactionRequest{
|
||||||
|
Amount: request.AmountMinorUnits, Reference: ref,
|
||||||
|
}, 2)
|
||||||
|
if err != nil {
|
||||||
|
logging.Error(types.ServiceName, err.Error(), "Confirm transaction error", string(op), "", "", 0)
|
||||||
|
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error())
|
||||||
|
outcome.FailureType = types.ResultError
|
||||||
|
outcome.FailureDescription = "ConfirmTransactionError"
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
// Intentionally reuse both records: XML appends confirmation entries, and
|
||||||
|
// missing confirmation fields/receipts retain their existing legacy behavior.
|
||||||
|
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||||
|
logging.Error(types.ServiceName, err.Error(), "Parse confirm result error", string(op), "", "", 0)
|
||||||
|
}
|
||||||
|
result.FillFromTransactionResult(trResult)
|
||||||
|
res = result.Fields[types.TransactionResult]
|
||||||
|
if !strings.EqualFold(res, types.ResultApproved) {
|
||||||
|
app.printCreditCallReceipt(result.CardholderReceipt)
|
||||||
|
desc := result.Fields[types.ErrorDescription]
|
||||||
|
if desc == "" {
|
||||||
|
desc = result.Fields[types.Errors]
|
||||||
|
}
|
||||||
|
logging.Error(types.ServiceName, "Transaction not approved after confirm", "Confirm result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||||
|
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc)
|
||||||
|
outcome.HTTPStatus = http.StatusOK
|
||||||
|
outcome.Status = result.Status
|
||||||
|
outcome.Payment = result
|
||||||
|
outcome.FailureType = res
|
||||||
|
outcome.FailureDescription = result.Fields[types.Errors]
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
app.printCreditCallReceipt(result.CardholderReceipt)
|
||||||
|
log.Printf("Transaction approved and confirmed, reference: %s", ref)
|
||||||
|
outcome.HTTPStatus = http.StatusOK
|
||||||
|
outcome.Status = result.Status
|
||||||
|
outcome.Payment = result
|
||||||
|
outcome.Approved = true
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
func (outcome creditCallSaleOutcome) legacyResponse() cmstypes.ResponseRec {
|
||||||
|
response := cmstypes.ResponseRec{Status: outcome.Status}
|
||||||
|
if outcome.Approved {
|
||||||
|
response.Data = creditcall.BuildSuccessURL(outcome.Payment.Fields)
|
||||||
|
} else {
|
||||||
|
response.Data = creditcall.BuildFailureURL(outcome.FailureType, outcome.FailureDescription)
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
@@ -0,0 +1,480 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
||||||
|
)
|
||||||
|
|
||||||
|
type failedCreditCallBody struct{ closed *bool }
|
||||||
|
|
||||||
|
func (b failedCreditCallBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
|
||||||
|
func (b failedCreditCallBody) Close() error { *b.closed = true; return nil }
|
||||||
|
|
||||||
|
func TestCreditCallConfirmationReadFailureAndHTTPStatus(t *testing.T) {
|
||||||
|
for _, failFirstRead := range []bool{false, true} {
|
||||||
|
calls, receipts, firstClosed := 0, 0, false
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, creditCallReceipt: func(string) { receipts++ }}
|
||||||
|
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
if r.URL.Path != "/confirm-transaction/" {
|
||||||
|
t.Errorf("confirmation path=%s", r.URL.Path)
|
||||||
|
}
|
||||||
|
deadline, ok := r.Context().Deadline()
|
||||||
|
if !ok || time.Until(deadline) < 299*time.Second {
|
||||||
|
t.Errorf("confirmation call has no fresh 300-second deadline: %v", deadline)
|
||||||
|
}
|
||||||
|
var body io.ReadCloser = io.NopCloser(strings.NewReader(chipDNAFixture(t, map[string]string{types.TransactionResult: "Approved"})))
|
||||||
|
if failFirstRead && calls == 1 {
|
||||||
|
body = failedCreditCallBody{closed: &firstClosed}
|
||||||
|
}
|
||||||
|
// Legacy confirmation ignores HTTP status when the body can be read.
|
||||||
|
return &http.Response{StatusCode: http.StatusServiceUnavailable, Body: body}, nil
|
||||||
|
})
|
||||||
|
outcome := app.executeCreditCallSale(cmstypes.TransactionRec{AmountMinorUnits: "1234"}, func(*http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
return creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{{Key: types.TransactionResult, Value: "Approved"}, {Key: types.Reference, Value: "ref"}}}, nil
|
||||||
|
})
|
||||||
|
wantCalls := 1
|
||||||
|
if failFirstRead {
|
||||||
|
wantCalls = 2
|
||||||
|
}
|
||||||
|
if calls != wantCalls || receipts != 1 || !outcome.Approved || (failFirstRead && !firstClosed) {
|
||||||
|
t.Errorf("readFailure=%v calls/receipts/approved/closed=%d/%d/%v/%v", failFirstRead, calls, receipts, outcome.Approved, firstClosed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallStreamFailureNeverRestartsOrConfirms(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls++
|
||||||
|
if r.URL.Path != "/start-transaction-stream/" {
|
||||||
|
t.Errorf("unexpected fallback/confirmation %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
io.WriteString(w, "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"OnlineAuthCompleted\"}\n{partial")
|
||||||
|
})
|
||||||
|
app.creditCallReceipt = func(string) { t.Error("invalid upstream stream printed receipt") }
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
app.salePayment(recorder, saleRequest(true))
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
if calls != 1 || len(frames) != 2 || frames[1].Result == nil || frames[1].Result.Outcome != "error" || frames[1].Result.HTTPStatus != 502 {
|
||||||
|
t.Errorf("malformed stream calls=%d frames=%+v", calls, frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallStructuredFieldsExcludeRawData(t *testing.T) {
|
||||||
|
result := (creditCallSaleOutcome{Approved: true, Payment: creditcall.PaymentResult{Fields: map[string]string{
|
||||||
|
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",
|
||||||
|
}}}).streamResult()
|
||||||
|
body, err := json.Marshal(result)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, forbidden := range []string{"1234567890123456", "pan-secret", "cvv-secret", "pin-secret", "track-secret", "receipt-secret", "/successful", "/unsuccessful"} {
|
||||||
|
if bytes.Contains(body, []byte(forbidden)) {
|
||||||
|
t.Errorf("structured result exposed %q", forbidden)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if result.CardHash != "hash" || result.CardReference != "card-ref" || result.TransactionReference != "ref" {
|
||||||
|
t.Errorf("required identifiers missing: %+v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type blockedPaymentWriter struct {
|
||||||
|
*httptest.ResponseRecorder
|
||||||
|
started chan struct{}
|
||||||
|
release chan struct{}
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *blockedPaymentWriter) Write(data []byte) (int, error) {
|
||||||
|
w.once.Do(func() { close(w.started) })
|
||||||
|
<-w.release
|
||||||
|
return w.ResponseRecorder.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallBackpressureCannotBlockFinalizationOrLoseFinal(t *testing.T) {
|
||||||
|
nativeRelease, receiptPrinted := make(chan struct{}), make(chan struct{})
|
||||||
|
var nativeOnce, deliveryOnce sync.Once
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path == "/confirm-transaction/" {
|
||||||
|
io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: "Approved"}))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
line := "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"CardRequested\"}\n"
|
||||||
|
io.WriteString(w, line)
|
||||||
|
w.(http.Flusher).Flush()
|
||||||
|
<-nativeRelease
|
||||||
|
for i := 0; i < 1000; i++ {
|
||||||
|
io.WriteString(w, line)
|
||||||
|
}
|
||||||
|
io.WriteString(w, "{\"type\":\"result\",\"result\":{\"TRANSACTION_RESULT\":\"Approved\",\"REFERENCE\":\"ref\"}}\n")
|
||||||
|
})
|
||||||
|
app.creditCallReceipt = func(string) { close(receiptPrinted) }
|
||||||
|
writer := &blockedPaymentWriter{ResponseRecorder: httptest.NewRecorder(), started: make(chan struct{}), release: make(chan struct{})}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
nativeOnce.Do(func() { close(nativeRelease) })
|
||||||
|
deliveryOnce.Do(func() { close(writer.release) })
|
||||||
|
})
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { app.salePayment(writer, saleRequest(true)); close(done) }()
|
||||||
|
select {
|
||||||
|
case <-writer.started:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("progress was not live")
|
||||||
|
}
|
||||||
|
nativeOnce.Do(func() { close(nativeRelease) })
|
||||||
|
select {
|
||||||
|
case <-receiptPrinted:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("blocked writer stopped financial finalization")
|
||||||
|
}
|
||||||
|
deliveryOnce.Do(func() { close(writer.release) })
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("stream did not deliver final")
|
||||||
|
}
|
||||||
|
frames := decodePaymentStream(t, writer.Body)
|
||||||
|
if len(frames) != 130 || frames[len(frames)-1].Result == nil || frames[len(frames)-1].Result.Outcome != "approved" {
|
||||||
|
t.Errorf("backpressure frames=%d, last=%+v, want 129 statuses and final approval", len(frames), frames[len(frames)-1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type creditCallRoundTrip func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f creditCallRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
|
||||||
|
func chipDNAFixture(t *testing.T, fields map[string]string) string {
|
||||||
|
t.Helper()
|
||||||
|
var result creditcall.TransactionResultXML
|
||||||
|
for key, value := range fields {
|
||||||
|
result.Entries = append(result.Entries, creditcall.EntryXML{Key: key, Value: value})
|
||||||
|
}
|
||||||
|
data, err := xml.Marshal(result)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCreditCallTestApp(t *testing.T, handler http.HandlerFunc) *App {
|
||||||
|
t.Helper()
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
target, err := url.Parse(server.URL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return &App{isPayment: true, creditCallStreamEnabled: true, cfg: &config.ConfigRec{TimeoutSeconds: 1},
|
||||||
|
creditCallTransport: creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
clone := r.Clone(r.Context())
|
||||||
|
clone.URL.Scheme, clone.URL.Host = target.Scheme, target.Host
|
||||||
|
return server.Client().Transport.RoundTrip(clone)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func saleRequest(stream bool) *http.Request {
|
||||||
|
if stream {
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/api/payment/sale", strings.NewReader(`{"amount":1234}`))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/takepayment", strings.NewReader(`<TransactionPayload><Amount>1234</Amount><TransactionType>Sale</TransactionType></TransactionPayload>`))
|
||||||
|
r.Header.Set("Content-Type", "text/xml")
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name, startResult, confirmation string
|
||||||
|
confirms int
|
||||||
|
approved bool
|
||||||
|
receipt string
|
||||||
|
}{
|
||||||
|
{"approved", "Approved", "Approved", 1, true, "confirm receipt"},
|
||||||
|
{"declined", "Declined", "", 0, false, "start receipt"},
|
||||||
|
{"cancelled", "Cancelled", "", 0, false, "start receipt"},
|
||||||
|
{"timeout", "TIMEOUT", "", 0, false, "start receipt"},
|
||||||
|
{"confirmation declined", "Approved", "Declined", 1, false, "confirm receipt"},
|
||||||
|
{"confirmation omissions", "Approved", "omitted", 1, true, "start receipt"},
|
||||||
|
{"malformed confirmation", "Approved", "malformed", 1, true, "start receipt"},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
fields := map[string]string{types.TransactionResult: test.startResult, types.Reference: "native-ref",
|
||||||
|
types.CardType: "Visa", types.PanMasked: "************1234", types.ExpiryDate: "1228",
|
||||||
|
types.CardHash: "hash", types.CardReference: "card-ref", types.ReceiptDataCardholder: "start receipt"}
|
||||||
|
var legacy cmstypes.ResponseRec
|
||||||
|
for _, streaming := range []bool{false, true} {
|
||||||
|
var starts, confirms atomic.Int32
|
||||||
|
var receipts []string
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/start-transaction/":
|
||||||
|
starts.Add(1)
|
||||||
|
io.WriteString(w, chipDNAFixture(t, fields))
|
||||||
|
case "/start-transaction-stream/":
|
||||||
|
starts.Add(1)
|
||||||
|
var input struct{ Amount, TransactionType string }
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil || input.Amount != "1234" || input.TransactionType != "Sale" {
|
||||||
|
t.Errorf("stream start input = %+v, error %v", input, err)
|
||||||
|
}
|
||||||
|
io.WriteString(w, "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"CardRequested\"}\n")
|
||||||
|
io.WriteString(w, "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"OnlineAuthCompleted\"}\n")
|
||||||
|
io.WriteString(w, "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"Approved\"}\n")
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields})
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields})
|
||||||
|
case "/confirm-transaction/":
|
||||||
|
confirms.Add(1)
|
||||||
|
var input creditcall.ConfirmTransactionRequest
|
||||||
|
if err := xml.NewDecoder(r.Body).Decode(&input); err != nil || input.Amount != "1234" || input.Reference != "native-ref" {
|
||||||
|
t.Errorf("confirmation input = %+v, error %v", input, err)
|
||||||
|
}
|
||||||
|
switch test.confirmation {
|
||||||
|
case "omitted":
|
||||||
|
io.WriteString(w, "<TransactionResult/>")
|
||||||
|
case "malformed":
|
||||||
|
io.WriteString(w, "<TransactionResult><Entry>")
|
||||||
|
default:
|
||||||
|
io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: test.confirmation, types.ReceiptDataCardholder: "confirm receipt"}))
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
t.Errorf("unexpected ChipDNA path %q", r.URL.Path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) }
|
||||||
|
if got := app.creditCallClient().Timeout; got != 300*time.Second {
|
||||||
|
t.Fatalf("per-call timeout = %v, want 300s", got)
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
if streaming {
|
||||||
|
app.salePayment(recorder, saleRequest(true))
|
||||||
|
} else {
|
||||||
|
app.takePayment(recorder, saleRequest(false))
|
||||||
|
}
|
||||||
|
if starts.Load() != 1 || int(confirms.Load()) != test.confirms {
|
||||||
|
t.Errorf("stream=%v starts/confirms=%d/%d, want 1/%d", streaming, starts.Load(), confirms.Load(), test.confirms)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(receipts, []string{test.receipt}) {
|
||||||
|
t.Errorf("stream=%v receipts=%v, want [%s]", streaming, receipts, test.receipt)
|
||||||
|
}
|
||||||
|
if !streaming {
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &legacy); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(legacy.Data, "/successful") != test.approved {
|
||||||
|
t.Errorf("legacy result = %+v, approved want %v", legacy, test.approved)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
if len(frames) != 3 || frames[0].Code != paymentstatus.PresentCard || frames[1].Code != paymentstatus.PleaseWait || frames[2].Result == nil {
|
||||||
|
t.Fatalf("frames = %+v, want two ordered hints and one final", frames)
|
||||||
|
}
|
||||||
|
final := frames[2].Result
|
||||||
|
if final.HTTPStatus != http.StatusOK || final.Status != legacy.Status || (final.Outcome == "approved") != test.approved {
|
||||||
|
t.Errorf("structured final = %+v, legacy = %+v", final, legacy)
|
||||||
|
}
|
||||||
|
parsed, err := url.Parse(legacy.Data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if test.approved {
|
||||||
|
if final.TransactionReference != "native-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1234" || final.CardHash != "hash" || final.CardReference != "card-ref" || final.ExpiryDate != "1228" {
|
||||||
|
t.Errorf("retained structured fields = %+v", final)
|
||||||
|
}
|
||||||
|
} else if final.Message != parsed.Query().Get("Description") {
|
||||||
|
t.Errorf("structured message = %q, legacy description = %q", final.Message, parsed.Query().Get("Description"))
|
||||||
|
}
|
||||||
|
if frames[2].Response != nil {
|
||||||
|
t.Error("CreditCall stream included legacy response")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
|
||||||
|
for _, streaming := range []bool{false, true} {
|
||||||
|
var attempts int
|
||||||
|
var times []time.Time
|
||||||
|
app := &App{isPayment: true, creditCallStreamEnabled: true, cfg: &config.ConfigRec{}}
|
||||||
|
app.creditCallReceipt = func(string) { t.Error("transport-failed confirmation must not print a receipt") }
|
||||||
|
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
if r.Context().Err() != nil {
|
||||||
|
t.Error("transaction context was cancelled")
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/confirm-transaction/" {
|
||||||
|
attempts++
|
||||||
|
times = append(times, time.Now())
|
||||||
|
return nil, errors.New("test transport failure")
|
||||||
|
}
|
||||||
|
body := chipDNAFixture(t, map[string]string{types.TransactionResult: "Approved", types.Reference: "native-ref"})
|
||||||
|
if streaming {
|
||||||
|
body = "{\"type\":\"result\",\"result\":{\"TRANSACTION_RESULT\":\"Approved\",\"REFERENCE\":\"native-ref\"}}\n"
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
|
||||||
|
})
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
if streaming {
|
||||||
|
app.salePayment(recorder, saleRequest(true))
|
||||||
|
} else {
|
||||||
|
app.takePayment(recorder, saleRequest(false))
|
||||||
|
}
|
||||||
|
if attempts != 2 {
|
||||||
|
t.Fatalf("stream=%v confirms=%d, want 2", streaming, attempts)
|
||||||
|
}
|
||||||
|
if times[1].Sub(times[0]) < 2*time.Second {
|
||||||
|
t.Errorf("retry delay=%v, want at least 2s", times[1].Sub(times[0]))
|
||||||
|
}
|
||||||
|
if streaming {
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
if len(frames) != 1 || frames[0].Result.HTTPStatus != 502 || frames[0].Result.Status.Code != 500 || frames[0].Result.Message != "Transaction error" {
|
||||||
|
t.Fatalf("confirmation failure frames=%+v", frames)
|
||||||
|
}
|
||||||
|
} else if recorder.Code != 502 {
|
||||||
|
t.Errorf("legacy confirm failure HTTP=%d, want 502", recorder.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallLegacyMalformedStartAndPreauth(t *testing.T) {
|
||||||
|
for _, test := range []struct{ name, path, result, transactionType string }{
|
||||||
|
{"malformed sale", "/takepayment", "malformed", ""},
|
||||||
|
{"approved account verification", "/takepreauth", "Approved", types.AccountVerificationType},
|
||||||
|
{"declined preauth", "/takepreauth", "Declined", "Sale"},
|
||||||
|
{"malformed preauth", "/takepreauth", "malformed", ""},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
calls, prints := 0, 0
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls++
|
||||||
|
if r.URL.Path != "/start-transaction/" {
|
||||||
|
t.Errorf("legacy/preauth path=%s", r.URL.Path)
|
||||||
|
}
|
||||||
|
if test.result == "malformed" {
|
||||||
|
io.WriteString(w, "<TransactionResult><Entry>")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: test.result, types.TransactionType: test.transactionType}))
|
||||||
|
})
|
||||||
|
app.creditCallReceipt = func(string) { prints++ }
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := saleRequest(false)
|
||||||
|
if test.path == "/takepreauth" {
|
||||||
|
app.takePreauthorization(recorder, request)
|
||||||
|
} else {
|
||||||
|
app.takePayment(recorder, request)
|
||||||
|
}
|
||||||
|
var response cmstypes.ResponseRec
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if recorder.Code != 200 || calls != 1 || prints != 1 {
|
||||||
|
t.Errorf("legacy HTTP/calls/receipts=%d/%d/%d", recorder.Code, calls, prints)
|
||||||
|
}
|
||||||
|
if test.result == "malformed" && (response.Status.Code != 0 || response.Data != "/unsuccessful?Description=&MsgType=") {
|
||||||
|
t.Errorf("malformed legacy result=%+v", response)
|
||||||
|
}
|
||||||
|
if test.result == "Approved" && !strings.HasPrefix(response.Data, "/successful?") {
|
||||||
|
t.Errorf("approved preauth=%+v", response)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChipDNAStreamRejectsIncompleteOrInvalidFrames(t *testing.T) {
|
||||||
|
for _, body := range []string{"", "{", "{}\n", "<xml/>\n", "{\"type\":\"result\"}\n", "{\"type\":\"result\",\"result\":{}}\n", "{\"type\":\"error\",\"error\":\"sensitive diagnostic\"}\n", "{\"type\":\"result\",\"result\":{\"TRANSACTION_RESULT\":\"Approved\"}}", "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"Approved\"}\n"} {
|
||||||
|
client := &http.Client{Transport: creditCallRoundTrip(func(*http.Request) (*http.Response, error) {
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||||
|
})}
|
||||||
|
_, err := callChipDNAStream(client, 1234, func(code string) { t.Errorf("invalid stream produced status %q", code) })
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("callChipDNAStream(%q) succeeded, want error", body)
|
||||||
|
}
|
||||||
|
if err != nil && strings.Contains(err.Error(), "sensitive diagnostic") {
|
||||||
|
t.Error("raw diagnostic leaked")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type disconnectedPaymentWriter struct {
|
||||||
|
header http.Header
|
||||||
|
once sync.Once
|
||||||
|
failed chan struct{}
|
||||||
|
writes atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *disconnectedPaymentWriter) Header() http.Header { return w.header }
|
||||||
|
func (w *disconnectedPaymentWriter) WriteHeader(int) {}
|
||||||
|
func (w *disconnectedPaymentWriter) Flush() {}
|
||||||
|
func (w *disconnectedPaymentWriter) Write([]byte) (int, error) {
|
||||||
|
w.writes.Add(1)
|
||||||
|
w.once.Do(func() { close(w.failed) })
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallDisconnectStillConfirmsAndPrints(t *testing.T) {
|
||||||
|
release := make(chan struct{})
|
||||||
|
var confirms atomic.Int32
|
||||||
|
var receipts atomic.Int32
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path == "/confirm-transaction/" {
|
||||||
|
confirms.Add(1)
|
||||||
|
io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: "Approved", types.ReceiptDataCardholder: "receipt"}))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
io.WriteString(w, "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"CardRequested\"}\n")
|
||||||
|
w.(http.Flusher).Flush()
|
||||||
|
<-release
|
||||||
|
io.WriteString(w, "{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"OnlineAuthCompleted\"}\n")
|
||||||
|
io.WriteString(w, "{\"type\":\"result\",\"result\":{\"TRANSACTION_RESULT\":\"Approved\",\"REFERENCE\":\"ref\"}}\n")
|
||||||
|
})
|
||||||
|
app.creditCallReceipt = func(receipt string) {
|
||||||
|
if receipt != "receipt" {
|
||||||
|
t.Errorf("receipt=%q", receipt)
|
||||||
|
}
|
||||||
|
receipts.Add(1)
|
||||||
|
}
|
||||||
|
writer := &disconnectedPaymentWriter{header: make(http.Header), failed: make(chan struct{})}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { app.salePayment(writer, saleRequest(true).WithContext(ctx)); close(done) }()
|
||||||
|
select {
|
||||||
|
case <-writer.failed:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
close(release)
|
||||||
|
t.Fatal("no live progress before final result")
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
close(release)
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("finalization stopped after disconnect")
|
||||||
|
}
|
||||||
|
if confirms.Load() != 1 || receipts.Load() != 1 || writer.writes.Load() != 1 {
|
||||||
|
t.Errorf("disconnect confirms/receipts/writes=%d/%d/%d, want 1/1/1", confirms.Load(), receipts.Load(), writer.writes.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type creditCallStreamResult struct {
|
||||||
|
Outcome string `json:"outcome"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
HTTPStatus int `json:"httpStatus"`
|
||||||
|
Status cmstypes.StatusRec `json:"status"`
|
||||||
|
TransactionReference string `json:"transactionReference,omitempty"`
|
||||||
|
CardType string `json:"cardType,omitempty"`
|
||||||
|
MaskedCardNumber string `json:"maskedCardNumber,omitempty"`
|
||||||
|
ExpiryDate string `json:"expiryDate,omitempty"`
|
||||||
|
CardHash string `json:"cardHash,omitempty"`
|
||||||
|
CardReference string `json:"cardReference,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (outcome creditCallSaleOutcome) streamResult() creditCallStreamResult {
|
||||||
|
result := creditCallStreamResult{
|
||||||
|
Outcome: "error", HTTPStatus: outcome.HTTPStatus, Status: outcome.Status,
|
||||||
|
Message: creditcall.FailureDescription(outcome.FailureType, outcome.FailureDescription),
|
||||||
|
}
|
||||||
|
if !outcome.Approved {
|
||||||
|
switch strings.ToLower(outcome.FailureType) {
|
||||||
|
case "declined":
|
||||||
|
result.Outcome = "declined"
|
||||||
|
case "cancelled", "canceled":
|
||||||
|
result.Outcome = "cancelled"
|
||||||
|
case "timeout":
|
||||||
|
result.Outcome = "timeout"
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
fields := outcome.Payment.Fields
|
||||||
|
result.Outcome = "approved"
|
||||||
|
result.Message = "Payment approved"
|
||||||
|
result.TransactionReference = fields[types.Reference]
|
||||||
|
result.CardType = fields[types.CardType]
|
||||||
|
result.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
|
||||||
|
result.ExpiryDate = fields[types.ExpiryDate]
|
||||||
|
result.CardHash = fields[types.CardHash]
|
||||||
|
result.CardReference = fields[types.CardReference]
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnableCreditCallStreaming selects the CreditCall core without a generic provider.
|
||||||
|
func (app *App) EnableCreditCallStreaming() { app.creditCallStreamEnabled = true }
|
||||||
|
|
||||||
|
func (app *App) streamCreditCallSale(w http.ResponseWriter, r *http.Request) {
|
||||||
|
app.streamCreditCall(w, r, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (app *App) streamCreditCall(w http.ResponseWriter, r *http.Request, preauth bool) {
|
||||||
|
setPaymentCORS(w)
|
||||||
|
if r.Method == http.MethodOptions {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
controller := http.NewResponseController(w)
|
||||||
|
encoder := json.NewEncoder(w)
|
||||||
|
deliveryFailed := false
|
||||||
|
// Only this handler writes the response. The transaction worker never waits
|
||||||
|
// for network delivery, including when the peer stops reading without closing.
|
||||||
|
send := func(frame paymentStreamMessage) {
|
||||||
|
if deliveryFailed || r.Context().Err() != nil {
|
||||||
|
deliveryFailed = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := encoder.Encode(frame); err != nil {
|
||||||
|
deliveryFailed = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := controller.Flush(); err != nil {
|
||||||
|
deliveryFailed = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
reject := func(status int, message string) {
|
||||||
|
result := creditCallStreamResult{Outcome: "error", Message: message, HTTPStatus: status,
|
||||||
|
Status: cmstypes.StatusRec{Code: status, Message: http.StatusText(status)}}
|
||||||
|
w.WriteHeader(status)
|
||||||
|
send(paymentStreamMessage{Type: "result", Result: &result})
|
||||||
|
}
|
||||||
|
if preauth && !app.creditCallStreamEnabled {
|
||||||
|
reject(http.StatusServiceUnavailable, "CreditCall preauthorization streaming is not enabled")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !app.isPayment && !app.cfg.TestMode {
|
||||||
|
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Error", "Attempted payment while payment processing is disabled")
|
||||||
|
reject(http.StatusServiceUnavailable, "Payment processing is disabled")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
reject(http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
||||||
|
reject(http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
var transaction cmstypes.TransactionRec
|
||||||
|
if preauth {
|
||||||
|
var request creditCallPreauthRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
reject(http.StatusBadRequest, "Invalid JSON payload")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
transaction = cmstypes.TransactionRec{AmountMinorUnits: request.Amount, TransactionType: request.TransactionType, CheckoutDate: request.CheckoutDate}
|
||||||
|
} else {
|
||||||
|
var request SalePaymentRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
reject(http.StatusBadRequest, "Invalid JSON payload")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if request.Amount <= 0 {
|
||||||
|
reject(http.StatusBadRequest, "Amount must be greater than zero")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
transaction = cmstypes.TransactionRec{AmountMinorUnits: strconv.FormatInt(request.Amount, 10), TransactionType: "Sale"}
|
||||||
|
}
|
||||||
|
if _, ok := w.(http.Flusher); !ok {
|
||||||
|
reject(http.StatusInternalServerError, "Streaming payment updates are not supported")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validation belongs to the incoming request. This handoff owns financial dispatch.
|
||||||
|
if r.Context().Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
financialContext := context.WithoutCancel(r.Context())
|
||||||
|
progress := make(chan string, 128)
|
||||||
|
finished := make(chan creditCallSaleOutcome, 1)
|
||||||
|
go func() {
|
||||||
|
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
return callChipDNATransactionStream(financialContext, client, transaction, func(code string) {
|
||||||
|
select {
|
||||||
|
case progress <- code:
|
||||||
|
default: // Observational progress may be dropped under backpressure.
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
var outcome creditCallSaleOutcome
|
||||||
|
if preauth {
|
||||||
|
outcome = app.executeCreditCallPreauth(financialContext, transaction, start)
|
||||||
|
} else {
|
||||||
|
outcome = app.executeCreditCallSale(transaction, start)
|
||||||
|
}
|
||||||
|
close(progress)
|
||||||
|
finished <- outcome // Independent of the bounded progress queue.
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case code, ok := <-progress:
|
||||||
|
if !ok {
|
||||||
|
progress = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
send(paymentStreamMessage{Type: "status", Code: code})
|
||||||
|
case outcome := <-finished:
|
||||||
|
if progress != nil {
|
||||||
|
for code := range progress {
|
||||||
|
send(paymentStreamMessage{Type: "status", Code: code})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result := outcome.streamResult()
|
||||||
|
send(paymentStreamMessage{Type: "result", Result: &result})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func callChipDNAStream(client *http.Client, amount int64, onStatus func(string)) (creditcall.TransactionResultXML, error) {
|
||||||
|
return callChipDNATransactionStream(context.Background(), client, cmstypes.TransactionRec{
|
||||||
|
AmountMinorUnits: strconv.FormatInt(amount, 10), TransactionType: "Sale",
|
||||||
|
}, onStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
func callChipDNATransactionStream(ctx context.Context, client *http.Client, transaction cmstypes.TransactionRec, onStatus func(string)) (creditcall.TransactionResultXML, error) {
|
||||||
|
var result creditcall.TransactionResultXML
|
||||||
|
payload, err := json.Marshal(struct {
|
||||||
|
Amount string `json:"amount"`
|
||||||
|
TransactionType string `json:"transactionType"`
|
||||||
|
}{transaction.AmountMinorUnits, transaction.TransactionType})
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
// Dispatch owns ctx; Client.Timeout retains the independent 300-second call bound.
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, types.LinkStartTransactionStream, bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Accept", "application/x-ndjson")
|
||||||
|
response, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return result, fmt.Errorf("chipdna stream returned HTTP %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
reader := bufio.NewReader(response.Body)
|
||||||
|
for {
|
||||||
|
line, err := reader.ReadBytes('\n')
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
return result, fmt.Errorf("chipdna stream ended before a complete final frame")
|
||||||
|
}
|
||||||
|
return result, fmt.Errorf("read chipdna stream: %w", err)
|
||||||
|
}
|
||||||
|
var frame struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
Result map[string]string `json:"result"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(line, &frame); err != nil {
|
||||||
|
return result, fmt.Errorf("invalid chipdna JSON frame")
|
||||||
|
}
|
||||||
|
switch frame.Type {
|
||||||
|
case "status":
|
||||||
|
if code := creditcall.ProgressStatus(frame.Source, frame.Value); code != "" && onStatus != nil {
|
||||||
|
onStatus(code)
|
||||||
|
}
|
||||||
|
case "result":
|
||||||
|
if len(frame.Result) == 0 {
|
||||||
|
return result, fmt.Errorf("chipdna final frame has no transaction fields")
|
||||||
|
}
|
||||||
|
for key, value := range frame.Result {
|
||||||
|
result.Entries = append(result.Entries, creditcall.EntryXML{Key: key, Value: value})
|
||||||
|
}
|
||||||
|
return result, nil // Later frames cannot repeat confirmation/finalization.
|
||||||
|
case "error":
|
||||||
|
return result, fmt.Errorf("chipdna stream reported an error")
|
||||||
|
default:
|
||||||
|
return result, fmt.Errorf("unknown chipdna frame type")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
-131
@@ -35,17 +35,20 @@ type doorCardDispenser interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type App struct {
|
type App struct {
|
||||||
disp doorCardDispenser
|
disp doorCardDispenser
|
||||||
lockserver lockserver.LockServer
|
lockserver lockserver.LockServer
|
||||||
paymentService *paymentsvc.Service
|
paymentService *paymentsvc.Service
|
||||||
isPayment bool
|
creditCallStreamEnabled bool
|
||||||
db *sql.DB
|
creditCallTransport http.RoundTripper
|
||||||
cfg *config.ConfigRec
|
creditCallReceipt func(string)
|
||||||
dbMu sync.Mutex
|
isPayment bool
|
||||||
cardWellMu sync.RWMutex
|
db *sql.DB
|
||||||
cardWellStatus string
|
cfg *config.ConfigRec
|
||||||
availabilityMu sync.Mutex
|
dbMu sync.Mutex
|
||||||
availabilityTimers map[string]*time.Timer
|
cardWellMu sync.RWMutex
|
||||||
|
cardWellStatus string
|
||||||
|
availabilityMu sync.Mutex
|
||||||
|
availabilityTimers map[string]*time.Timer
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
||||||
@@ -75,6 +78,7 @@ func (app *App) RegisterRoutes(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("/ping-pdq", app.fetchChipDNAStatus)
|
mux.HandleFunc("/ping-pdq", app.fetchChipDNAStatus)
|
||||||
mux.HandleFunc("/logerror", app.onChipDNAError)
|
mux.HandleFunc("/logerror", app.onChipDNAError)
|
||||||
mux.HandleFunc("/api/payment/sale", app.salePayment)
|
mux.HandleFunc("/api/payment/sale", app.salePayment)
|
||||||
|
mux.HandleFunc("/api/payment/preauth", app.streamCreditCallPreauth)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -83,9 +87,6 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
|||||||
var (
|
var (
|
||||||
theResponse cmstypes.ResponseRec
|
theResponse cmstypes.ResponseRec
|
||||||
theRequest cmstypes.TransactionRec
|
theRequest cmstypes.TransactionRec
|
||||||
trResult creditcall.TransactionResultXML
|
|
||||||
result creditcall.PaymentResult
|
|
||||||
save bool
|
|
||||||
)
|
)
|
||||||
|
|
||||||
theResponse.Status.Code = http.StatusInternalServerError
|
theResponse.Status.Code = http.StatusInternalServerError
|
||||||
@@ -146,39 +147,18 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
|||||||
theRequest.TransactionType,
|
theRequest.TransactionType,
|
||||||
)
|
)
|
||||||
|
|
||||||
client := &http.Client{Timeout: 300 * time.Second}
|
outcome := app.executeCreditCallPreauth(context.Background(), theRequest, func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
var transaction creditcall.TransactionResultXML
|
||||||
// ---- START TRANSACTION ----
|
response, err := callChipDNA(client, types.LinkStartTransaction, body)
|
||||||
|
if err != nil {
|
||||||
body, err = callChipDNA(client, types.LinkStartTransaction, body)
|
return transaction, err
|
||||||
if err != nil {
|
}
|
||||||
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
if err := transaction.ParseTransactionResult(response); err != nil {
|
||||||
|
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||||
theResponse.Data = creditcall.BuildFailureURL(types.ResultError, "No response from payment processor")
|
}
|
||||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
return transaction, nil
|
||||||
return
|
})
|
||||||
}
|
writeTransactionResult(w, outcome.HTTPStatus, outcome.legacyResponse())
|
||||||
|
|
||||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
|
||||||
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
result.FillFromTransactionResult(trResult)
|
|
||||||
|
|
||||||
// ---- PRINT RECEIPT ----
|
|
||||||
|
|
||||||
printer.PrintReceipt(result.CardholderReceipt)
|
|
||||||
|
|
||||||
// ---- REDIRECT ----
|
|
||||||
|
|
||||||
theResponse.Status = result.Status
|
|
||||||
theResponse.Data, save = creditcall.BuildPreauthRedirectURL(result.Fields)
|
|
||||||
|
|
||||||
if save {
|
|
||||||
go app.persistPreauth(context.Background(), result.Fields, theRequest.CheckoutDate)
|
|
||||||
}
|
|
||||||
|
|
||||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -187,8 +167,6 @@ func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
var (
|
var (
|
||||||
theResponse cmstypes.ResponseRec
|
theResponse cmstypes.ResponseRec
|
||||||
theRequest cmstypes.TransactionRec
|
theRequest cmstypes.TransactionRec
|
||||||
trResult creditcall.TransactionResultXML
|
|
||||||
result creditcall.PaymentResult
|
|
||||||
)
|
)
|
||||||
|
|
||||||
theResponse.Status.Code = http.StatusInternalServerError
|
theResponse.Status.Code = http.StatusInternalServerError
|
||||||
@@ -250,90 +228,18 @@ func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
theRequest.TransactionType,
|
theRequest.TransactionType,
|
||||||
)
|
)
|
||||||
|
|
||||||
client := &http.Client{Timeout: 300 * time.Second}
|
outcome := app.executeCreditCallSale(theRequest, func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
var trResult creditcall.TransactionResultXML
|
||||||
// ---- START TRANSACTION ----
|
body, err := callChipDNA(client, types.LinkStartTransaction, body)
|
||||||
|
if err != nil {
|
||||||
body, err = callChipDNA(client, types.LinkStartTransaction, body)
|
return trResult, err
|
||||||
if err != nil {
|
|
||||||
logging.Error(types.ServiceName, err.Error(), "Start transaction error", string(op), "", "", 0)
|
|
||||||
|
|
||||||
theResponse.Data = creditcall.BuildFailureURL(types.ResultError, "No response from payment processor")
|
|
||||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
|
||||||
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
result.FillFromTransactionResult(trResult)
|
|
||||||
|
|
||||||
res := result.Fields[types.TransactionResult]
|
|
||||||
|
|
||||||
if !strings.EqualFold(res, types.ResultApproved) {
|
|
||||||
printer.PrintReceipt(result.CardholderReceipt)
|
|
||||||
desc := result.Fields[types.ErrorDescription]
|
|
||||||
if desc == "" {
|
|
||||||
desc = result.Fields[types.Errors]
|
|
||||||
}
|
}
|
||||||
logging.Error(types.ServiceName, "Preauthorization failed", "Result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||||
theResponse.Status = result.Status
|
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||||
theResponse.Data = creditcall.BuildFailureURL(res, result.Fields[types.Errors])
|
|
||||||
|
|
||||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- CONFIRM TRANSACTION ----
|
|
||||||
|
|
||||||
ref := result.Fields[types.Reference]
|
|
||||||
log.Printf("Preauth approved, reference: %s. Sending confirm...", ref)
|
|
||||||
confirmReq := creditcall.ConfirmTransactionRequest{
|
|
||||||
Amount: theRequest.AmountMinorUnits,
|
|
||||||
Reference: ref,
|
|
||||||
}
|
|
||||||
|
|
||||||
body, err = confirmWithRetry(client, confirmReq, 2)
|
|
||||||
if err != nil {
|
|
||||||
logging.Error(types.ServiceName, err.Error(), "Confirm transaction error", string(op), "", "", 0)
|
|
||||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error())
|
|
||||||
theResponse.Data = creditcall.BuildFailureURL(types.ResultError, "ConfirmTransactionError")
|
|
||||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
|
||||||
logging.Error(types.ServiceName, err.Error(), "Parse confirm result error", string(op), "", "", 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
result.FillFromTransactionResult(trResult)
|
|
||||||
|
|
||||||
res = result.Fields[types.TransactionResult]
|
|
||||||
|
|
||||||
if !strings.EqualFold(res, types.ResultApproved) {
|
|
||||||
printer.PrintReceipt(result.CardholderReceipt)
|
|
||||||
desc := result.Fields[types.ErrorDescription]
|
|
||||||
if desc == "" {
|
|
||||||
desc = result.Fields[types.Errors]
|
|
||||||
}
|
}
|
||||||
logging.Error(types.ServiceName, "Transaction not approved after confirm", "Confirm result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
return trResult, nil
|
||||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc)
|
})
|
||||||
theResponse.Status = result.Status
|
writeTransactionResult(w, outcome.HTTPStatus, outcome.legacyResponse())
|
||||||
theResponse.Data = creditcall.BuildFailureURL(res, result.Fields[types.Errors])
|
|
||||||
|
|
||||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- SUCCESS ----
|
|
||||||
|
|
||||||
printer.PrintReceipt(result.CardholderReceipt)
|
|
||||||
log.Printf("Transaction approved and confirmed, reference: %s", ref)
|
|
||||||
theResponse.Status = result.Status
|
|
||||||
theResponse.Data = creditcall.BuildSuccessURL(result.Fields)
|
|
||||||
|
|
||||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -30,14 +30,20 @@ type SalePaymentRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type paymentStreamMessage struct {
|
type paymentStreamMessage struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Code string `json:"code,omitempty"`
|
Code string `json:"code,omitempty"`
|
||||||
Response *cmstypes.ResponseRec `json:"response,omitempty"`
|
Response *cmstypes.ResponseRec `json:"response,omitempty"`
|
||||||
|
Result *creditCallStreamResult `json:"result,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
||||||
const op = logging.Op("salePayment")
|
const op = logging.Op("salePayment")
|
||||||
|
|
||||||
|
if app.creditCallStreamEnabled {
|
||||||
|
app.streamCreditCallSale(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
response := cmstypes.ResponseRec{
|
response := cmstypes.ResponseRec{
|
||||||
Status: cmstypes.StatusRec{
|
Status: cmstypes.StatusRec{
|
||||||
Code: http.StatusInternalServerError,
|
Code: http.StatusInternalServerError,
|
||||||
|
|||||||
+157
-78
@@ -245,95 +245,174 @@ func printCardholderReceipt(cardholderReceipt string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// receiptColumns follows the existing 44-column normal-size text convention.
|
||||||
|
const receiptColumns = 44
|
||||||
|
|
||||||
func BuildCardholderReceipt(entries []ReceiptEntryXML) ([]byte, error) {
|
func BuildCardholderReceipt(entries []ReceiptEntryXML) ([]byte, error) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
rendered := make([]bool, len(entries))
|
||||||
|
take := func(id string) string {
|
||||||
|
for i, entry := range entries {
|
||||||
|
if !rendered[i] && entry.ReceiptEntryId == id && entry.Value != "" {
|
||||||
|
rendered[i] = true
|
||||||
|
return receiptEntryText(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
write := func(b []byte) { buf.Write(b) }
|
// Set and restore only text state; leave printer setup and transport alone.
|
||||||
// writeStr := func(s string) { buf.WriteString(s) }
|
normal := func() { buf.Write([]byte{ESC, 'a', 0, ESC, 'E', BOLD_OFF, GS, '!', NORMAL_FONT}) }
|
||||||
writeln := func(s string) {
|
normal()
|
||||||
buf.WriteString(s)
|
hasRows, newSection := false, false
|
||||||
|
beginLine := func(center bool) {
|
||||||
|
if hasRows && newSection {
|
||||||
|
buf.WriteString(strings.Repeat("-", receiptColumns) + "\n")
|
||||||
|
}
|
||||||
|
hasRows, newSection = true, false
|
||||||
|
if center {
|
||||||
|
buf.Write([]byte{ESC, 'a', CENTER})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
text := func(value string, bold bool) {
|
||||||
|
if bold {
|
||||||
|
buf.Write([]byte{ESC, 'E', BOLD_ON})
|
||||||
|
}
|
||||||
|
buf.WriteString(value)
|
||||||
|
if bold {
|
||||||
|
buf.Write([]byte{ESC, 'E', BOLD_OFF})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line := func(value string, bold, center bool) {
|
||||||
|
if value == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
beginLine(center)
|
||||||
|
text(value, bold)
|
||||||
buf.WriteByte('\n')
|
buf.WriteByte('\n')
|
||||||
|
normal()
|
||||||
|
}
|
||||||
|
pair := func(left, right string, boldRight bool) {
|
||||||
|
if gap, fits := receiptPairGap(left, right); fits {
|
||||||
|
beginLine(false)
|
||||||
|
text(left+gap, false)
|
||||||
|
text(right, boldRight)
|
||||||
|
buf.WriteByte('\n')
|
||||||
|
normal()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
line(left, false, false)
|
||||||
|
line(right, boldRight, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build a lookup map by ReceiptEntryId
|
line(take("Recipient"), true, true)
|
||||||
m := make(map[string]ReceiptEntryXML, len(entries))
|
line(take("MerchantName"), false, true)
|
||||||
for _, e := range entries {
|
newSection = true
|
||||||
m[e.ReceiptEntryId] = e
|
line(take("CardScheme"), false, false)
|
||||||
|
line(take("PanMasked"), false, false)
|
||||||
|
pair(take("Aid"), take("PanSequence"), false)
|
||||||
|
pair(take("TransactionSource"), take("TransactionType"), false)
|
||||||
|
newSection = true
|
||||||
|
// Align the provider amount without parsing or modifying its value.
|
||||||
|
for i, entry := range entries {
|
||||||
|
if entry.ReceiptEntryId == "TotalAmount" && entry.Value != "" {
|
||||||
|
rendered[i] = true
|
||||||
|
label := entry.Label
|
||||||
|
if label == "" {
|
||||||
|
label = "TOTAL"
|
||||||
|
}
|
||||||
|
label = strings.TrimSuffix(label, ":") + ":"
|
||||||
|
if gap, fits := receiptPairGap(label, entry.Value); fits {
|
||||||
|
line(label+gap+entry.Value, true, false)
|
||||||
|
} else {
|
||||||
|
line(receiptEntryText(entry), true, false)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
pair(take("CardholderVerification"), take("TransactionResult"), true)
|
||||||
// Utility to center text
|
newSection = true
|
||||||
// center := func(s string) {
|
line(take("AuthCode"), false, false)
|
||||||
// write([]byte{ESC, 'a', CENTER})
|
line(take("AuthReference"), false, false)
|
||||||
// writeln(s)
|
line(take("TransactionSeqNumber"), false, false)
|
||||||
// write([]byte{ESC, 'a', 0})
|
pair(take("MerchantIdMasked"), take("TerminalIdMasked"), false)
|
||||||
// }
|
line(take("AuthDateTime"), false, false)
|
||||||
|
footer := take("RetentionMessage")
|
||||||
// Utility for bold lines
|
// Preserve every remaining occurrence, including unknown IDs, in provider order.
|
||||||
// boldOn := func() { write([]byte{GS, '!', WIDER_FONT}) }
|
for i, entry := range entries {
|
||||||
// boldOff := func() { write([]byte{GS, '!', NORMAL_FONT}) }
|
if !rendered[i] && entry.Value != "" {
|
||||||
|
line(receiptEntryText(entry), false, false)
|
||||||
// boldOn()
|
}
|
||||||
|
|
||||||
// 1) Header: CARDHOLDER COPY
|
|
||||||
writeln(m["Recipient"].Value)
|
|
||||||
// writeStr("\n\n")
|
|
||||||
// 2) Merchant name
|
|
||||||
writeln(m["MerchantName"].Value)
|
|
||||||
// writeStr("\n\n")
|
|
||||||
// 3) AID
|
|
||||||
writeln("AID: " + m["Aid"].Value)
|
|
||||||
|
|
||||||
// 4) Card scheme & pan
|
|
||||||
writeln(fmt.Sprintf("%s Card: %s", m["CardScheme"].Value, m["PanMasked"].Value))
|
|
||||||
|
|
||||||
// 5) PAN Seq No
|
|
||||||
writeln("PAN Seq No: " + m["PanSequence"].Value)
|
|
||||||
|
|
||||||
// 6) Transaction source
|
|
||||||
writeln(m["TransactionSource"].Value)
|
|
||||||
|
|
||||||
// 7) Transaction type (Sale/Account Verification)
|
|
||||||
writeln(m["TransactionType"].Value)
|
|
||||||
|
|
||||||
// 8) Total
|
|
||||||
// assuming value like "GBP1.50" — insert space after currency
|
|
||||||
total := m["TotalAmount"].Value
|
|
||||||
if !strings.HasPrefix(total, "GBP") && len(total) > 3 {
|
|
||||||
total = total[:3] + " " + total[3:]
|
|
||||||
}
|
}
|
||||||
writeln("TOTAL: " + total)
|
newSection = true
|
||||||
|
line(footer, false, true)
|
||||||
// 9) Cardholder verification
|
normal()
|
||||||
writeln(m["CardholderVerification"].Value)
|
buf.Write([]byte{ESC, 'd', 7})
|
||||||
|
buf.Write([]byte{GS, 'V', 1})
|
||||||
// 10) Approved/Declined
|
|
||||||
writeln(m["TransactionResult"].Value)
|
|
||||||
|
|
||||||
// 11) Auth code
|
|
||||||
writeln("Auth Code: " + m["AuthCode"].Value)
|
|
||||||
|
|
||||||
// 12) Reference
|
|
||||||
writeln("Ref: " + m["AuthReference"].Value)
|
|
||||||
|
|
||||||
// 13) Merchant & terminal IDs
|
|
||||||
writeln("MID: " + m["MerchantIdMasked"].Value)
|
|
||||||
writeln("TID: " + m["TerminalIdMasked"].Value)
|
|
||||||
|
|
||||||
// 14) Date/time
|
|
||||||
writeln(m["AuthDateTime"].Value)
|
|
||||||
|
|
||||||
// 15) Retention message
|
|
||||||
writeln(m["RetentionMessage"].Value)
|
|
||||||
|
|
||||||
// boldOff()
|
|
||||||
|
|
||||||
// finally feed & cut
|
|
||||||
write([]byte{ESC, 'd', 7}) // Feed 5 lines
|
|
||||||
write([]byte{GS, 'V', 1})
|
|
||||||
|
|
||||||
return buf.Bytes(), nil
|
return buf.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func receiptEntryText(entry ReceiptEntryXML) string {
|
||||||
|
label := entry.Label
|
||||||
|
if label == "" {
|
||||||
|
switch entry.ReceiptEntryId {
|
||||||
|
case "Recipient", "MerchantName", "CardScheme", "TransactionSource", "TransactionType",
|
||||||
|
"CardholderVerification", "TransactionResult", "AuthDateTime", "RetentionMessage":
|
||||||
|
return entry.Value
|
||||||
|
case "PanMasked":
|
||||||
|
label = "Card"
|
||||||
|
case "Aid":
|
||||||
|
label = "AID"
|
||||||
|
case "PanSequence":
|
||||||
|
label = "PAN Seq No"
|
||||||
|
case "TotalAmount":
|
||||||
|
label = "TOTAL"
|
||||||
|
case "AuthCode":
|
||||||
|
label = "Auth Code"
|
||||||
|
case "AuthReference":
|
||||||
|
label = "Ref"
|
||||||
|
case "TransactionSeqNumber":
|
||||||
|
label = "Transaction Seq. No"
|
||||||
|
case "MerchantIdMasked":
|
||||||
|
label = "MID"
|
||||||
|
case "TerminalIdMasked":
|
||||||
|
label = "TID"
|
||||||
|
default:
|
||||||
|
var readable strings.Builder
|
||||||
|
runes := []rune(entry.ReceiptEntryId)
|
||||||
|
for i, r := range runes {
|
||||||
|
if i > 0 && r >= 'A' && r <= 'Z' &&
|
||||||
|
((runes[i-1] >= 'a' && runes[i-1] <= 'z') ||
|
||||||
|
(i+1 < len(runes) && runes[i+1] >= 'a' && runes[i+1] <= 'z')) {
|
||||||
|
readable.WriteByte(' ')
|
||||||
|
}
|
||||||
|
if r == '_' || r == '-' {
|
||||||
|
r = ' '
|
||||||
|
}
|
||||||
|
readable.WriteRune(r)
|
||||||
|
}
|
||||||
|
label = strings.TrimSpace(readable.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if label == "" {
|
||||||
|
return entry.Value
|
||||||
|
}
|
||||||
|
return strings.TrimSuffix(label, ":") + ": " + entry.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
func receiptPairGap(left, right string) (string, bool) {
|
||||||
|
if left == "" || right == "" || len(left)+2+len(right) > receiptColumns {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
// Only printable ASCII has a predictable single-column width here.
|
||||||
|
for _, r := range left + right {
|
||||||
|
if r < ' ' || r > '~' {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Repeat(" ", receiptColumns-len(left)-len(right)), true
|
||||||
|
}
|
||||||
|
|
||||||
func printLogo(path string) ([]byte, error) {
|
func printLogo(path string) ([]byte, error) {
|
||||||
const maxLogoWidth = 384
|
const maxLogoWidth = 384
|
||||||
f, err := os.Open(path)
|
f, err := os.Open(path)
|
||||||
|
|||||||
@@ -0,0 +1,280 @@
|
|||||||
|
package printer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type receiptTestChar struct {
|
||||||
|
value byte
|
||||||
|
center, bold bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type receiptTestOutput struct {
|
||||||
|
lines []string
|
||||||
|
chars []receiptTestChar
|
||||||
|
feeds, cuts int
|
||||||
|
}
|
||||||
|
|
||||||
|
// readReceiptText understands only the commands emitted by this receipt builder.
|
||||||
|
func readReceiptText(t *testing.T, data []byte) receiptTestOutput {
|
||||||
|
t.Helper()
|
||||||
|
var out receiptTestOutput
|
||||||
|
var line strings.Builder
|
||||||
|
var center, bold bool
|
||||||
|
for i := 0; i < len(data); {
|
||||||
|
if data[i] == ESC || data[i] == GS {
|
||||||
|
if i+2 >= len(data) {
|
||||||
|
t.Fatalf("BuildCardholderReceipt control bytes = %v, want complete command", data[i:])
|
||||||
|
}
|
||||||
|
prefix, command, value := data[i], data[i+1], data[i+2]
|
||||||
|
switch {
|
||||||
|
case prefix == ESC && command == 'a':
|
||||||
|
if value != 0 && value != CENTER {
|
||||||
|
t.Errorf("receipt alignment = %d, want left or center", value)
|
||||||
|
}
|
||||||
|
center = value == CENTER
|
||||||
|
case prefix == ESC && command == 'E':
|
||||||
|
if value != BOLD_OFF && value != BOLD_ON {
|
||||||
|
t.Errorf("receipt bold = %d, want on or off", value)
|
||||||
|
}
|
||||||
|
bold = value == BOLD_ON
|
||||||
|
case prefix == GS && command == '!':
|
||||||
|
if value != NORMAL_FONT {
|
||||||
|
t.Errorf("receipt size = %d, want normal size", value)
|
||||||
|
}
|
||||||
|
case prefix == ESC && command == 'd':
|
||||||
|
out.feeds++
|
||||||
|
if value != 7 || center || bold || i != len(data)-6 {
|
||||||
|
t.Errorf("receipt feed = %d, center=%t bold=%t offset=%d, want final seven-line feed in normal state", value, center, bold, i)
|
||||||
|
}
|
||||||
|
case prefix == GS && command == 'V':
|
||||||
|
out.cuts++
|
||||||
|
if value != 1 || i != len(data)-3 {
|
||||||
|
t.Errorf("receipt cut = %d at %d, want final GS V 1", value, i)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
t.Fatalf("BuildCardholderReceipt command = %v, want supported text command", data[i:i+3])
|
||||||
|
}
|
||||||
|
i += 3
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if data[i] == '\n' {
|
||||||
|
out.lines = append(out.lines, line.String())
|
||||||
|
line.Reset()
|
||||||
|
} else {
|
||||||
|
line.WriteByte(data[i])
|
||||||
|
out.chars = append(out.chars, receiptTestChar{value: data[i], center: center, bold: bold})
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
if line.Len() != 0 || center || bold || out.feeds != 1 || out.cuts != 1 {
|
||||||
|
t.Errorf("receipt termination: trailing=%q center=%t bold=%t feeds=%d cuts=%d, want normal state and one feed/cut", line.String(), center, bold, out.feeds, out.cuts)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildReceiptText(t *testing.T, entries []ReceiptEntryXML) receiptTestOutput {
|
||||||
|
t.Helper()
|
||||||
|
before := append([]ReceiptEntryXML(nil), entries...)
|
||||||
|
data, err := BuildCardholderReceipt(entries)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildCardholderReceipt(%v) error = %v, want nil", entries, err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(entries, before) {
|
||||||
|
t.Errorf("BuildCardholderReceipt input = %v, want unchanged %v", entries, before)
|
||||||
|
}
|
||||||
|
if !bytes.HasSuffix(data, []byte{ESC, 'd', 7, GS, 'V', 1}) {
|
||||||
|
t.Errorf("BuildCardholderReceipt suffix = %v, want unchanged feed/cut", data)
|
||||||
|
}
|
||||||
|
return readReceiptText(t, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sampleReceipt(recipient string) []ReceiptEntryXML {
|
||||||
|
return []ReceiptEntryXML{
|
||||||
|
{ReceiptEntryId: "Recipient", Value: recipient},
|
||||||
|
{ReceiptEntryId: "MerchantName", Value: "Standard Test Merchant"},
|
||||||
|
{ReceiptEntryId: "Aid", Value: "A0000000031010", Label: "AID"},
|
||||||
|
{ReceiptEntryId: "CardScheme", Value: "VISA DEBIT"},
|
||||||
|
{ReceiptEntryId: "PanMasked", Value: "************1133", Label: "Card"},
|
||||||
|
{ReceiptEntryId: "PanSequence", Value: "01", Label: "PAN Seq No"},
|
||||||
|
{ReceiptEntryId: "TransactionSource", Value: "ICC"},
|
||||||
|
{ReceiptEntryId: "TransactionType", Value: "SALE"},
|
||||||
|
{ReceiptEntryId: "TotalAmount", Value: "GBP120.00", Label: "TOTAL"},
|
||||||
|
{ReceiptEntryId: "CardholderVerification", Value: "PIN VERIFIED"},
|
||||||
|
{ReceiptEntryId: "TransactionResult", Value: "APPROVED"},
|
||||||
|
{ReceiptEntryId: "AuthCode", Value: "D0A35D", Label: "Auth Code"},
|
||||||
|
{ReceiptEntryId: "AuthReference", Value: "ChipDNA-Sale-20260908144731", Label: "Ref"},
|
||||||
|
{ReceiptEntryId: "MerchantIdMasked", Value: "******7897", Label: "MID"},
|
||||||
|
{ReceiptEntryId: "TerminalIdMasked", Value: "****9508", Label: "TID"},
|
||||||
|
{ReceiptEntryId: "TransactionSeqNumber", Value: "00001059", Label: "Transaction Seq. No"},
|
||||||
|
{ReceiptEntryId: "AuthDateTime", Value: "08/09/2026 14:48:06"},
|
||||||
|
{ReceiptEntryId: "RetentionMessage", Value: "Please retain for your records"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCardholderReceiptCompleteLayout(t *testing.T) {
|
||||||
|
for _, recipient := range []string{"CARDHOLDER COPY", "MERCHANT COPY"} {
|
||||||
|
t.Run(recipient, func(t *testing.T) {
|
||||||
|
entries := sampleReceipt(recipient)
|
||||||
|
out := buildReceiptText(t, entries)
|
||||||
|
// Ignore padding used for left/right placement, not semantic row order.
|
||||||
|
var rows []string
|
||||||
|
for _, line := range out.lines {
|
||||||
|
rows = append(rows, strings.Join(strings.Fields(line), " "))
|
||||||
|
}
|
||||||
|
rule := strings.Repeat("-", 44)
|
||||||
|
want := []string{recipient, "Standard Test Merchant", rule, "VISA DEBIT", "Card: ************1133",
|
||||||
|
"AID: A0000000031010 PAN Seq No: 01", "ICC SALE", rule, "TOTAL: GBP120.00", "PIN VERIFIED APPROVED", rule,
|
||||||
|
"Auth Code: D0A35D", "Ref: ChipDNA-Sale-20260908144731", "Transaction Seq. No: 00001059",
|
||||||
|
"MID: ******7897 TID: ****9508", "08/09/2026 14:48:06", rule, "Please retain for your records"}
|
||||||
|
if !reflect.DeepEqual(rows, want) {
|
||||||
|
t.Errorf("BuildCardholderReceipt(%q) rows = %q, want %q", recipient, rows, want)
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
if !strings.Contains(strings.Join(out.lines, "\n"), entry.Value) {
|
||||||
|
t.Errorf("BuildCardholderReceipt(%q) lost %s=%q", recipient, entry.ReceiptEntryId, entry.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, line := range out.lines {
|
||||||
|
if line == "" || len(line) > 44 {
|
||||||
|
t.Errorf("BuildCardholderReceipt(%q) row = %q, want compact nonempty row within 44 columns", recipient, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(out.lines) > 19 {
|
||||||
|
t.Errorf("BuildCardholderReceipt(%q) rows = %d, want representative receipt at most 19", recipient, len(out.lines))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCardholderReceiptFormattingState(t *testing.T) {
|
||||||
|
out := buildReceiptText(t, sampleReceipt("CARDHOLDER COPY"))
|
||||||
|
var plain strings.Builder
|
||||||
|
for _, char := range out.chars {
|
||||||
|
plain.WriteByte(char.value)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
text string
|
||||||
|
center, bold bool
|
||||||
|
}{
|
||||||
|
{"CARDHOLDER COPY", true, true}, {"Standard Test Merchant", true, false},
|
||||||
|
{"VISA DEBIT", false, false}, {"TOTAL:", false, true}, {"GBP120.00", false, true},
|
||||||
|
{"PIN VERIFIED", false, false}, {"APPROVED", false, true}, {"Auth Code:", false, false},
|
||||||
|
{"Please retain for your records", true, false},
|
||||||
|
} {
|
||||||
|
start := strings.Index(plain.String(), tc.text)
|
||||||
|
if start < 0 {
|
||||||
|
t.Fatalf("receipt text lacks %q", tc.text)
|
||||||
|
}
|
||||||
|
for _, char := range out.chars[start : start+len(tc.text)] {
|
||||||
|
if char.center != tc.center || char.bold != tc.bold {
|
||||||
|
t.Errorf("receipt style for %q = center:%t bold:%t, want center:%t bold:%t", tc.text, char.center, char.bold, tc.center, tc.bold)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCardholderReceiptMissingFields(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
entries []ReceiptEntryXML
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{name: "empty"},
|
||||||
|
{name: "empty values", entries: []ReceiptEntryXML{{ReceiptEntryId: "Aid", Label: "AID"}, {ReceiptEntryId: "Unknown", Label: "Unused"}}},
|
||||||
|
{name: "one partner", entries: []ReceiptEntryXML{{ReceiptEntryId: "PanSequence", Value: "02"}}, want: []string{"PAN Seq No: 02"}},
|
||||||
|
{name: "result only", entries: []ReceiptEntryXML{{ReceiptEntryId: "TransactionResult", Value: "DECLINED"}}, want: []string{"DECLINED"}},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
out := buildReceiptText(t, tc.entries)
|
||||||
|
if !reflect.DeepEqual(out.lines, tc.want) {
|
||||||
|
t.Errorf("BuildCardholderReceipt(%v) rows = %q, want %q", tc.entries, out.lines, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCardholderReceiptPreservesRemainingEntries(t *testing.T) {
|
||||||
|
entries := []ReceiptEntryXML{
|
||||||
|
{ReceiptEntryId: "AuthCode", Value: ""},
|
||||||
|
{ReceiptEntryId: "FooBar", Value: "first-extra", Priority: "9"},
|
||||||
|
{ReceiptEntryId: "AuthCode", Value: "primary", Label: "Provider authorization"},
|
||||||
|
{ReceiptEntryId: "AuthCode", Value: "duplicate", Label: "Second authorization"},
|
||||||
|
{ReceiptEntryId: "FooBar", Value: "second-extra", Label: "Foo", Priority: "1"},
|
||||||
|
{ReceiptEntryId: "RetentionMessage", Value: "Retain this"},
|
||||||
|
{ReceiptEntryId: "RetentionMessage", Value: "Extra retention"},
|
||||||
|
{ReceiptEntryId: "HTTPCode", Value: "provider-code"},
|
||||||
|
{Value: "unlabelled-value"},
|
||||||
|
}
|
||||||
|
out := buildReceiptText(t, entries)
|
||||||
|
want := []string{"Provider authorization: primary", "Foo Bar: first-extra", "Second authorization: duplicate",
|
||||||
|
"Foo: second-extra", "Extra retention", "HTTP Code: provider-code", "unlabelled-value", strings.Repeat("-", 44), "Retain this"}
|
||||||
|
if !reflect.DeepEqual(out.lines, want) {
|
||||||
|
t.Errorf("BuildCardholderReceipt remaining rows = %q, want %q", out.lines, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCardholderReceiptPairBoundaries(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, left, right string
|
||||||
|
paired bool
|
||||||
|
}{
|
||||||
|
{"short", "ICC", "SALE", true},
|
||||||
|
{"exact width", strings.Repeat("L", 20), strings.Repeat("R", 22), true},
|
||||||
|
{"overflow", strings.Repeat("L", 21), strings.Repeat("R", 22), false},
|
||||||
|
{"unicode", "TAP \u00c9", "SALE", false},
|
||||||
|
{"multiline", "ICC\nFALLBACK", "SALE", false},
|
||||||
|
{"left missing", "", "SALE", false},
|
||||||
|
{"right missing", "ICC", "", false},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
out := buildReceiptText(t, []ReceiptEntryXML{{ReceiptEntryId: "TransactionSource", Value: tc.left}, {ReceiptEntryId: "TransactionType", Value: tc.right}})
|
||||||
|
var want []string
|
||||||
|
if tc.paired {
|
||||||
|
want = []string{tc.left + strings.Repeat(" ", 44-len(tc.left)-len(tc.right)) + tc.right}
|
||||||
|
} else {
|
||||||
|
if tc.left != "" {
|
||||||
|
want = append(want, strings.Split(tc.left, "\n")...)
|
||||||
|
}
|
||||||
|
if tc.right != "" {
|
||||||
|
want = append(want, tc.right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(out.lines, want) {
|
||||||
|
t.Errorf("BuildCardholderReceipt pair(%q,%q) rows = %q, want %q", tc.left, tc.right, out.lines, want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCardholderReceiptLongValuesAndLabels(t *testing.T) {
|
||||||
|
ref := strings.Repeat("long-reference-", 8)
|
||||||
|
verify := "CONSUMER DEVICE VERIFICATION WITH ADDITIONAL PROVIDER TEXT"
|
||||||
|
out := buildReceiptText(t, []ReceiptEntryXML{
|
||||||
|
{ReceiptEntryId: "CardholderVerification", Value: verify},
|
||||||
|
{ReceiptEntryId: "TransactionResult", Value: "DECLINED"},
|
||||||
|
{ReceiptEntryId: "AuthReference", Label: "Provider reference:", Value: ref},
|
||||||
|
{ReceiptEntryId: "MerchantIdMasked", Label: strings.Repeat("Merchant", 6), Value: "******7897"},
|
||||||
|
{ReceiptEntryId: "TerminalIdMasked", Value: "****9508"},
|
||||||
|
})
|
||||||
|
want := []string{verify, "DECLINED", strings.Repeat("-", 44), "Provider reference: " + ref,
|
||||||
|
strings.Repeat("Merchant", 6) + ": ******7897", "TID: ****9508"}
|
||||||
|
if !reflect.DeepEqual(out.lines, want) {
|
||||||
|
t.Errorf("BuildCardholderReceipt long fields rows = %q, want %q", out.lines, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCardholderReceiptProviderAmounts(t *testing.T) {
|
||||||
|
for _, amount := range []string{"GBP120.00", "EUR 42,50", "USD1.23", "amount supplied verbatim", strings.Repeat("9", 50)} {
|
||||||
|
t.Run(amount, func(t *testing.T) {
|
||||||
|
out := buildReceiptText(t, []ReceiptEntryXML{{ReceiptEntryId: "TotalAmount", Label: "Provider total", Value: amount}})
|
||||||
|
if len(out.lines) != 1 || !strings.HasPrefix(out.lines[0], "Provider total:") || !strings.HasSuffix(out.lines[0], amount) {
|
||||||
|
t.Errorf("BuildCardholderReceipt amount(%q) rows = %q, want provider label and unchanged amount", amount, out.lines)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ const (
|
|||||||
ServiceName = "hardlink"
|
ServiceName = "hardlink"
|
||||||
DateOnly = "2006-01-02"
|
DateOnly = "2006-01-02"
|
||||||
CustomLayout = "2006-01-02 15:04:05 -0700"
|
CustomLayout = "2006-01-02 15:04:05 -0700"
|
||||||
|
LinkStartTransactionStream = "http://127.0.0.1:18181/start-transaction-stream/"
|
||||||
LinkStartTransaction = "http://127.0.0.1:18181/start-transaction/"
|
LinkStartTransaction = "http://127.0.0.1:18181/start-transaction/"
|
||||||
LinkConfirmTransaction = "http://127.0.0.1:18181/confirm-transaction/"
|
LinkConfirmTransaction = "http://127.0.0.1:18181/confirm-transaction/"
|
||||||
LinkTransactionInformation = "http://127.0.0.1:18181/transaction-information/"
|
LinkTransactionInformation = "http://127.0.0.1:18181/transaction-information/"
|
||||||
|
|||||||
+6
-1
@@ -2,10 +2,15 @@
|
|||||||
|
|
||||||
builtVersion is a const in main.go
|
builtVersion is a const in main.go
|
||||||
|
|
||||||
|
#### v2.0.1 - 10 September 2026
|
||||||
|
feat: add CreditCall preauth streaming
|
||||||
|
|
||||||
|
#### v2.0.0 - 08 September 2026
|
||||||
|
feat: stream CreditCall payment progress and results
|
||||||
|
|
||||||
#### v1.3.6 - 28 August 2026
|
#### v1.3.6 - 28 August 2026
|
||||||
Refactor PDQ lookup for payment providers
|
Refactor PDQ lookup for payment providers
|
||||||
|
|
||||||
|
|
||||||
#### v1.3.5 - 23 July 2026
|
#### v1.3.5 - 23 July 2026
|
||||||
fixed dispenser delivery confirmation
|
fixed dispenser delivery confirmation
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user