Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18b22b4ea7 |
@@ -1,93 +0,0 @@
|
|||||||
# 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 route; 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.
|
|
||||||
|
|
||||||
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
|
|
||||||
the existing confirmation behavior. `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 the required SDK
|
|
||||||
fields, or a sanitized `error`. Receipt XML may be a JSON string field needed by
|
|
||||||
hardlink's existing receipt handler; it is never a raw line in the stream.
|
|
||||||
Confirmation continues through the existing, separate XML endpoint.
|
|
||||||
|
|
||||||
## Lifetime and compatibility
|
|
||||||
|
|
||||||
- `/start-transaction/`, `/takepayment`, and `/takepreauth` retain their existing
|
|
||||||
external contracts. Preauthorization and SQL persistence/release remain legacy.
|
|
||||||
- Start and each 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, or receipt handling. 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.
|
|
||||||
- Unidentified `CardRemovalRequested` and `CardRemovalEnforced` updates are omitted
|
|
||||||
because they can arrive after financial completion. They require a matching
|
|
||||||
explicit reference. `Removed` remains omitted even with a reference.
|
|
||||||
- Ownership is best-effort UI observation. SDK 3.17 does not establish that every
|
|
||||||
queued reference-less non-removal callback 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. 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 sales, unchanged preauth requests, failure/retry parity, and existing
|
|
||||||
Dojo/PayBridge response handling. Run `go vet ./...`, `go build ./...`, and
|
|
||||||
`git diff --check` in both Go repositories.
|
|
||||||
+29
-40
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/xml"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -33,7 +34,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
buildVersion = "v2.0.0"
|
buildVersion = "1.3.2"
|
||||||
serviceName = "hardlink"
|
serviceName = "hardlink"
|
||||||
pollingFrequency = 8 * time.Second
|
pollingFrequency = 8 * time.Second
|
||||||
)
|
)
|
||||||
@@ -41,6 +42,7 @@ const (
|
|||||||
func main() {
|
func main() {
|
||||||
// Load config
|
// Load config
|
||||||
cfg := config.ReadHardlinkConfig()
|
cfg := config.ReadHardlinkConfig()
|
||||||
|
printer.Layout = readTicketLayout()
|
||||||
printer.PrinterName = cfg.PrinterName
|
printer.PrinterName = cfg.PrinterName
|
||||||
lockserver.Cert = cfg.Cert
|
lockserver.Cert = cfg.Cert
|
||||||
lockserver.LockServerURL = cfg.LockserverURL
|
lockserver.LockServerURL = cfg.LockserverURL
|
||||||
@@ -135,8 +137,7 @@ func main() {
|
|||||||
|
|
||||||
switch paymentProvider {
|
switch paymentProvider {
|
||||||
case cmstypes.PaySystemCreditCall:
|
case cmstypes.PaySystemCreditCall:
|
||||||
// CreditCall streaming shares its proven legacy transaction core.
|
// CreditCall keeps using the existing /takepayment and /takepreauth endpoints.
|
||||||
app.EnableCreditCallStreaming()
|
|
||||||
startChipDnaClient()
|
startChipDnaClient()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -156,29 +157,27 @@ func main() {
|
|||||||
fmt.Println("CreditCall payment provider enabled")
|
fmt.Println("CreditCall payment provider enabled")
|
||||||
|
|
||||||
case cmstypes.PaySystemPayBridge:
|
case cmstypes.PaySystemPayBridge:
|
||||||
websocketURL := pdqSerialForKiosk(reservationSystem.PDQs, cfg.Kiosk)
|
if reservationSystem.PaymentGatewayURL == "" {
|
||||||
|
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Payment Gateway URL not found", fmt.Errorf("payment provider paybridge requires paybridge.websocket_url"))
|
||||||
if websocketURL == "" {
|
|
||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "PayBridge websocket URL not found", fmt.Errorf("payment provider paybridge requires paybridge.websocket_url"))
|
|
||||||
}
|
}
|
||||||
if reservationSystem.PaymentGatewayAPIKeyWeb == "" {
|
if reservationSystem.PaymentGatewayAPIKeyWeb == "" {
|
||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Payment Gateway API Key not found", fmt.Errorf("payment provider paybridge requires paybridge.api_key"))
|
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Payment Gateway API Key not found", fmt.Errorf("payment provider paybridge requires paybridge.api_key"))
|
||||||
}
|
}
|
||||||
|
|
||||||
provider = paybridge.NewClient(
|
provider = paybridge.NewClient(
|
||||||
websocketURL,
|
reservationSystem.PaymentGatewayURL,
|
||||||
reservationSystem.PaymentGatewayAPIKeyWeb,
|
reservationSystem.PaymentGatewayAPIKeyWeb,
|
||||||
cfg.TimeoutSeconds,
|
cfg.TimeoutSeconds,
|
||||||
)
|
)
|
||||||
|
|
||||||
case cmstypes.PaySystemDojo:
|
case cmstypes.PaySystemDojo:
|
||||||
TerminalID := pdqSerialForKiosk(reservationSystem.PDQs, cfg.Kiosk)
|
var TerminalID string
|
||||||
|
for _, item := range reservationSystem.PDQs {
|
||||||
if TerminalID == "" {
|
if item.Kiosk != cfg.Kiosk {
|
||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Dojo Terminal ID not found", fmt.Errorf("payment provider dojo requires a terminal ID for kiosk %q in the CMS", cfg.Kiosk))
|
continue
|
||||||
}
|
}
|
||||||
if reservationSystem.PaymentGatewayURL == "" {
|
TerminalID = item.Serial
|
||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Payment Gateway URL not found", fmt.Errorf("payment provider dojo requires dojo.websocket_url"))
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
dojoClient, err := dojo.NewClient(dojo.Config{
|
dojoClient, err := dojo.NewClient(dojo.Config{
|
||||||
@@ -204,7 +203,7 @@ func main() {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
// PayBridge and Dojo use the generic payment service.
|
// Only PayBridge and Dojo use POST /api/payment/sale.
|
||||||
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])
|
||||||
@@ -241,23 +240,23 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// func readTicketLayout() printer.LayoutOptions {
|
func readTicketLayout() printer.LayoutOptions {
|
||||||
// const layoutName = "TicketLayout.xml"
|
const layoutName = "TicketLayout.xml"
|
||||||
// var layout printer.LayoutOptions
|
var layout printer.LayoutOptions
|
||||||
|
|
||||||
// // 1) Read the file
|
// 1) Read the file
|
||||||
// data, err := os.ReadFile(layoutName)
|
data, err := os.ReadFile(layoutName)
|
||||||
// if err != nil {
|
if err != nil {
|
||||||
// errorhandlers.FatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
|
errorhandlers.FatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
|
||||||
// }
|
}
|
||||||
|
|
||||||
// // 2) Unmarshal into your struct
|
// 2) Unmarshal into your struct
|
||||||
// if err := xml.Unmarshal(data, &layout); err != nil {
|
if err := xml.Unmarshal(data, &layout); err != nil {
|
||||||
// errorhandlers.FatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
|
errorhandlers.FatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
|
||||||
// }
|
}
|
||||||
|
|
||||||
// return layout
|
return layout
|
||||||
// }
|
}
|
||||||
|
|
||||||
func startChipDnaClient() {
|
func startChipDnaClient() {
|
||||||
startClient := func() (*exec.Cmd, error) {
|
startClient := func() (*exec.Cmd, error) {
|
||||||
@@ -317,13 +316,3 @@ func startChipDnaClient() {
|
|||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func pdqSerialForKiosk(pdqs []cmstypes.PDQRec, kiosk int) string {
|
|
||||||
for _, item := range pdqs {
|
|
||||||
if item.Kiosk == kiosk {
|
|
||||||
return item.Serial
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -168,7 +168,9 @@ 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{}
|
||||||
description = FailureDescription(msgType, description)
|
if msgType != "" {
|
||||||
|
description = fmt.Sprintf("Transaction %s", strings.ToLower(msgType))
|
||||||
|
}
|
||||||
if description != "" {
|
if description != "" {
|
||||||
msgType = types.ResultError
|
msgType = types.ResultError
|
||||||
}
|
}
|
||||||
@@ -183,12 +185,3 @@ 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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package dispenser
|
package dispenser
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -23,13 +22,9 @@ const (
|
|||||||
|
|
||||||
// cache freshness for "continuous status" reads (tune as you wish)
|
// cache freshness for "continuous status" reads (tune as you wish)
|
||||||
defaultStatusTTL = 1500 * time.Millisecond
|
defaultStatusTTL = 1500 * time.Millisecond
|
||||||
|
|
||||||
CardWellEmptyMessage = "Card well is empty"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrCardWellEmpty = errors.New(CardWellEmptyMessage)
|
|
||||||
|
|
||||||
SerialPort string
|
SerialPort string
|
||||||
Address []byte
|
Address []byte
|
||||||
|
|
||||||
@@ -72,9 +67,10 @@ var (
|
|||||||
// Status helpers
|
// Status helpers
|
||||||
// --------------------
|
// --------------------
|
||||||
|
|
||||||
func statusDescription(statusBytes []byte) string {
|
func logStatus(statusBytes []byte) {
|
||||||
if len(statusBytes) < 4 {
|
if len(statusBytes) < 4 {
|
||||||
return fmt.Sprintf("<invalid len=%d>", len(statusBytes))
|
log.Infof("Dispenser status: <invalid len=%d>", len(statusBytes))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
posStatus := []struct {
|
posStatus := []struct {
|
||||||
@@ -98,58 +94,13 @@ func statusDescription(statusBytes []byte) string {
|
|||||||
result.WriteString(statusMsg + "; ")
|
result.WriteString(statusMsg + "; ")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result.String()
|
log.Infof("Dispenser status: %s", result.String())
|
||||||
}
|
|
||||||
|
|
||||||
func logStatus(statusBytes []byte) {
|
|
||||||
log.Infof("Dispenser status: %s", statusDescription(statusBytes))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func isAtEncoderPosition(statusBytes []byte) bool {
|
func isAtEncoderPosition(statusBytes []byte) bool {
|
||||||
return len(statusBytes) >= 4 && statusBytes[3] == 0x33
|
return len(statusBytes) >= 4 && statusBytes[3] == 0x33
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateDispenserStatusData(statusBytes []byte) error {
|
|
||||||
if len(statusBytes) != 4 {
|
|
||||||
return fmt.Errorf("malformed dispenser status: got %d bytes, want 4", len(statusBytes))
|
|
||||||
}
|
|
||||||
|
|
||||||
statusMaps := []map[byte]string{statusPos0, statusPos1, statusPos2, statusPos3}
|
|
||||||
for position, mapper := range statusMaps {
|
|
||||||
if _, ok := mapper[statusBytes[position]]; !ok {
|
|
||||||
return fmt.Errorf("unknown dispenser status 0x%X at position %d", statusBytes[position], position+1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func dispenserStatusError(statusBytes []byte) error {
|
|
||||||
switch statusBytes[0] {
|
|
||||||
case 0x34, 0x32, 0x36:
|
|
||||||
return fmt.Errorf("dispenser error: %s", statusPos0[statusBytes[0]])
|
|
||||||
}
|
|
||||||
switch statusBytes[1] {
|
|
||||||
case 0x32, 0x31:
|
|
||||||
return fmt.Errorf("dispenser error: %s", statusPos1[statusBytes[1]])
|
|
||||||
}
|
|
||||||
switch statusBytes[2] {
|
|
||||||
case 0x34, 0x32:
|
|
||||||
return fmt.Errorf("dispenser error: %s", statusPos2[statusBytes[2]])
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isPreparationMoving(statusBytes []byte) bool {
|
|
||||||
return len(statusBytes) == 4 &&
|
|
||||||
(statusBytes[0] == 0x31 || statusBytes[1] == 0x38)
|
|
||||||
}
|
|
||||||
|
|
||||||
func hasPreparationDiagnostics(statusBytes []byte) bool {
|
|
||||||
return len(statusBytes) == 4 &&
|
|
||||||
(statusBytes[0] != 0x30 || statusBytes[1] != 0x30 || statusBytes[2] != 0x30)
|
|
||||||
}
|
|
||||||
|
|
||||||
func stockTake(statusBytes []byte) string {
|
func stockTake(statusBytes []byte) string {
|
||||||
if len(statusBytes) < 4 {
|
if len(statusBytes) < 4 {
|
||||||
return ""
|
return ""
|
||||||
|
|||||||
@@ -30,25 +30,12 @@ type cmdResp struct {
|
|||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
type sequenceTiming struct {
|
|
||||||
now func() time.Time
|
|
||||||
wait func(context.Context, time.Duration) error
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
sequencePollInterval = time.Second
|
|
||||||
sequenceRetryAfter = 6 * time.Second
|
|
||||||
sequenceTimeout = 12 * time.Second
|
|
||||||
)
|
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
port *serial.Port
|
port *serial.Port
|
||||||
|
|
||||||
reqCh chan cmdReq
|
reqCh chan cmdReq
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
|
|
||||||
sequenceTiming sequenceTiming
|
|
||||||
|
|
||||||
// status cache
|
// status cache
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
lastStatus []byte
|
lastStatus []byte
|
||||||
@@ -67,31 +54,15 @@ func NewClient(port *serial.Port, queueSize int) *Client {
|
|||||||
queueSize = 16
|
queueSize = 16
|
||||||
}
|
}
|
||||||
c := &Client{
|
c := &Client{
|
||||||
port: port,
|
port: port,
|
||||||
reqCh: make(chan cmdReq, queueSize),
|
reqCh: make(chan cmdReq, queueSize),
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
sequenceTiming: sequenceTiming{
|
|
||||||
now: time.Now,
|
|
||||||
wait: waitForSequence,
|
|
||||||
},
|
|
||||||
statusTTL: defaultStatusTTL,
|
statusTTL: defaultStatusTTL,
|
||||||
}
|
}
|
||||||
go c.loop()
|
go c.loop()
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
func waitForSequence(ctx context.Context, duration time.Duration) error {
|
|
||||||
timer := time.NewTimer(duration)
|
|
||||||
defer timer.Stop()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-timer.C:
|
|
||||||
return nil
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) Close() {
|
func (c *Client) Close() {
|
||||||
select {
|
select {
|
||||||
case <-c.done:
|
case <-c.done:
|
||||||
@@ -297,152 +268,113 @@ func (c *Client) DispenserPrepare(ctx context.Context) (string, error) {
|
|||||||
return stockStatus, nil
|
return stockStatus, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) readSequenceStatus(ctx context.Context, operation string) ([]byte, string, error) {
|
func (c *Client) DispenserStart(ctx context.Context) (string, error) {
|
||||||
status, err := c.do(ctx, cmdStatus)
|
const funcName = "DispenserStart"
|
||||||
if err != nil {
|
|
||||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
|
||||||
return nil, "", fmt.Errorf("[%s] read status: %w", operation, ctxErr)
|
|
||||||
}
|
|
||||||
return nil, "", fmt.Errorf("[%s] read status: %w", operation, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
stockStatus := ""
|
stockStatus := ""
|
||||||
if len(status) == 4 {
|
|
||||||
stockStatus = stockTake(status)
|
|
||||||
c.setStock(status)
|
|
||||||
logStatus(status)
|
|
||||||
}
|
|
||||||
return status, stockStatus, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func preparationStatus(operation string, status []byte) (bool, error) {
|
status, err := c.CheckStatus(ctx)
|
||||||
if len(status) != 4 {
|
if err != nil {
|
||||||
return false, fmt.Errorf("[%s] %w", operation, validateDispenserStatusData(status))
|
return stockStatus, fmt.Errorf("[%s] check status: %w", funcName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
logStatus(status)
|
||||||
|
}()
|
||||||
|
stockStatus = stockTake(status)
|
||||||
|
c.setStock(status)
|
||||||
|
|
||||||
|
if isCardWellEmpty(status) {
|
||||||
|
return stockStatus, fmt.Errorf(stockStatus)
|
||||||
}
|
}
|
||||||
if isAtEncoderPosition(status) {
|
if isAtEncoderPosition(status) {
|
||||||
if hasPreparationDiagnostics(status) {
|
|
||||||
log.Warnf(
|
|
||||||
"[%s] card confirmed at encoder with dispenser diagnostics: %s raw status: % X",
|
|
||||||
operation,
|
|
||||||
statusDescription(status),
|
|
||||||
status,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
if err := validateDispenserStatusData(status); err != nil {
|
|
||||||
return false, fmt.Errorf("[%s] %w", operation, err)
|
|
||||||
}
|
|
||||||
if isCardWellEmpty(status) {
|
|
||||||
return false, fmt.Errorf("[%s] %w", operation, ErrCardWellEmpty)
|
|
||||||
}
|
|
||||||
if isPreparationMoving(status) {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
if err := dispenserStatusError(status); err != nil {
|
|
||||||
return false, fmt.Errorf("[%s] %w", operation, err)
|
|
||||||
}
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) pollForEncoderPosition(
|
|
||||||
ctx context.Context,
|
|
||||||
operation string,
|
|
||||||
retryCommand func(context.Context) error,
|
|
||||||
) (string, error) {
|
|
||||||
started := c.sequenceTiming.now()
|
|
||||||
halfway := started.Add(sequenceRetryAfter)
|
|
||||||
deadline := started.Add(sequenceTimeout)
|
|
||||||
retried := false
|
|
||||||
stockStatus := ""
|
|
||||||
|
|
||||||
for {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return stockStatus, fmt.Errorf("[%s] %w", operation, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
now := c.sequenceTiming.now()
|
|
||||||
if !now.Before(deadline) {
|
|
||||||
return stockStatus, fmt.Errorf("[%s] timed out after %s", operation, sequenceTimeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
status, currentStockStatus, err := c.readSequenceStatus(ctx, operation)
|
|
||||||
stockStatus = currentStockStatus
|
|
||||||
if err != nil {
|
|
||||||
return stockStatus, err
|
|
||||||
}
|
|
||||||
ready, err := preparationStatus(operation, status)
|
|
||||||
if err != nil {
|
|
||||||
return stockStatus, err
|
|
||||||
}
|
|
||||||
if ready {
|
|
||||||
return stockStatus, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
now = c.sequenceTiming.now()
|
|
||||||
if !now.Before(deadline) {
|
|
||||||
return stockStatus, fmt.Errorf("[%s] timed out after %s", operation, sequenceTimeout)
|
|
||||||
}
|
|
||||||
if retryCommand != nil && !retried && !now.Before(halfway) {
|
|
||||||
if err := retryCommand(ctx); err != nil {
|
|
||||||
return stockStatus, fmt.Errorf("[%s] retry command: %w", operation, err)
|
|
||||||
}
|
|
||||||
retried = true
|
|
||||||
}
|
|
||||||
|
|
||||||
wait := sequencePollInterval
|
|
||||||
if remaining := deadline.Sub(now); remaining < wait {
|
|
||||||
wait = remaining
|
|
||||||
}
|
|
||||||
if err := c.sequenceTiming.wait(ctx, wait); err != nil {
|
|
||||||
return stockStatus, fmt.Errorf("[%s] %w", operation, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) prepareCardAtEncoder(ctx context.Context, operation string) (string, error) {
|
|
||||||
status, stockStatus, err := c.readSequenceStatus(ctx, operation)
|
|
||||||
if err != nil {
|
|
||||||
return stockStatus, err
|
|
||||||
}
|
|
||||||
ready, err := preparationStatus(operation, status)
|
|
||||||
if err != nil {
|
|
||||||
return stockStatus, err
|
|
||||||
}
|
|
||||||
if ready {
|
|
||||||
return stockStatus, nil
|
return stockStatus, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := c.ToEncoder(ctx); err != nil {
|
if err := c.ToEncoder(ctx); err != nil {
|
||||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", operation, err)
|
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
halfway := time.Now().Add(6 * time.Second)
|
||||||
|
deadline := time.Now().Add(12 * time.Second)
|
||||||
|
|
||||||
|
for {
|
||||||
|
time.Sleep(delay * 2)
|
||||||
|
switch {
|
||||||
|
case time.Now().After(halfway):
|
||||||
|
if err := c.ToEncoder(ctx); err != nil {
|
||||||
|
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||||
|
}
|
||||||
|
case time.Now().After(deadline):
|
||||||
|
return stockStatus, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
status, _ = c.do(ctx, cmdStatus)
|
||||||
|
|
||||||
|
stockStatus = stockTake(status)
|
||||||
|
c.setStock(status)
|
||||||
|
logStatus(status)
|
||||||
|
|
||||||
|
// error states first
|
||||||
|
if isCardWellEmpty(status) {
|
||||||
|
return stockStatus, fmt.Errorf(stockStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
if isAtEncoderPosition(status) {
|
||||||
|
return stockStatus, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return c.pollForEncoderPosition(ctx, operation, c.ToEncoder)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PrepareCurrentCard authoritatively places the card to be encoded at the encoder.
|
func (c *Client) DispenserFinal(ctx context.Context) (string, error) {
|
||||||
func (c *Client) PrepareCurrentCard(ctx context.Context) (string, error) {
|
const funcName = "DispenserFinal"
|
||||||
return c.prepareCardAtEncoder(ctx, "PrepareCurrentCard")
|
stockStatus := ""
|
||||||
}
|
var status []byte
|
||||||
|
|
||||||
// DeliverCurrentCard presents the encoded card and confirms command acceptance.
|
|
||||||
func (c *Client) DeliverCurrentCard(ctx context.Context) (string, error) {
|
|
||||||
const operation = "DeliverCurrentCard"
|
|
||||||
|
|
||||||
if err := c.OutOfMouth(ctx); err != nil {
|
if err := c.OutOfMouth(ctx); err != nil {
|
||||||
return "", fmt.Errorf("[%s] out of mouth: %w", operation, err)
|
return stockStatus, fmt.Errorf("[%s] out of mouth: %w", funcName, err)
|
||||||
}
|
}
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// BeginPrepareNextCard starts moving the next card to the encoder without waiting for readiness.
|
time.Sleep(delay)
|
||||||
func (c *Client) BeginPrepareNextCard(ctx context.Context) error {
|
status, err := c.do(ctx, cmdStatus)
|
||||||
|
if err == nil && len(status) >= 4 {
|
||||||
|
c.setStock(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(delay)
|
||||||
if err := c.ToEncoder(ctx); err != nil {
|
if err := c.ToEncoder(ctx); err != nil {
|
||||||
return fmt.Errorf("[BeginPrepareNextCard] to encoder: %w", err)
|
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrepareNextCard places a new card at the encoder for a later issuance attempt.
|
defer func() {
|
||||||
func (c *Client) PrepareNextCard(ctx context.Context) (string, error) {
|
logStatus(status)
|
||||||
return c.prepareCardAtEncoder(ctx, "PrepareNextCard")
|
}()
|
||||||
|
|
||||||
|
halfway := time.Now().Add(6 * time.Second)
|
||||||
|
deadline := time.Now().Add(12 * time.Second)
|
||||||
|
|
||||||
|
for {
|
||||||
|
time.Sleep(delay * 2)
|
||||||
|
switch {
|
||||||
|
case time.Now().After(halfway):
|
||||||
|
if err := c.ToEncoder(ctx); err != nil {
|
||||||
|
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||||
|
}
|
||||||
|
case time.Now().After(deadline):
|
||||||
|
return stockStatus, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
status, _ = c.do(ctx, cmdStatus)
|
||||||
|
|
||||||
|
stockStatus = stockTake(status)
|
||||||
|
c.setStock(status)
|
||||||
|
logStatus(status)
|
||||||
|
|
||||||
|
if isCardWellEmpty(status) {
|
||||||
|
return stockStatus, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if isAtEncoderPosition(status) {
|
||||||
|
return stockStatus, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,404 +0,0 @@
|
|||||||
package dispenser
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
type fakeSequenceDevice struct {
|
|
||||||
statusResponses []cmdResp
|
|
||||||
commandErrors map[cmdType][]error
|
|
||||||
commands []cmdType
|
|
||||||
}
|
|
||||||
|
|
||||||
func newSequenceTestClient(t *testing.T, statusResponses ...cmdResp) (*Client, *fakeSequenceDevice) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
device := &fakeSequenceDevice{
|
|
||||||
statusResponses: append([]cmdResp(nil), statusResponses...),
|
|
||||||
commandErrors: make(map[cmdType][]error),
|
|
||||||
}
|
|
||||||
now := time.Date(2026, time.July, 23, 12, 0, 0, 0, time.UTC)
|
|
||||||
client := &Client{
|
|
||||||
reqCh: make(chan cmdReq),
|
|
||||||
done: make(chan struct{}),
|
|
||||||
sequenceTiming: sequenceTiming{
|
|
||||||
now: func() time.Time {
|
|
||||||
return now
|
|
||||||
},
|
|
||||||
wait: func(ctx context.Context, duration time.Duration) error {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
default:
|
|
||||||
now = now.Add(duration)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-client.done:
|
|
||||||
return
|
|
||||||
case request := <-client.reqCh:
|
|
||||||
device.commands = append(device.commands, request.typ)
|
|
||||||
if request.typ == cmdStatus {
|
|
||||||
if len(device.statusResponses) == 0 {
|
|
||||||
request.respCh <- cmdResp{err: errors.New("unexpected status read")}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
response := device.statusResponses[0]
|
|
||||||
device.statusResponses = device.statusResponses[1:]
|
|
||||||
request.respCh <- response
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
if queued := device.commandErrors[request.typ]; len(queued) > 0 {
|
|
||||||
err = queued[0]
|
|
||||||
device.commandErrors[request.typ] = queued[1:]
|
|
||||||
}
|
|
||||||
request.respCh <- cmdResp{err: err}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
t.Cleanup(client.Close)
|
|
||||||
|
|
||||||
return client, device
|
|
||||||
}
|
|
||||||
|
|
||||||
func status(position byte) []byte {
|
|
||||||
return []byte{0x30, 0x30, 0x30, position}
|
|
||||||
}
|
|
||||||
|
|
||||||
func commandCount(commands []cmdType, target cmdType) int {
|
|
||||||
count := 0
|
|
||||||
for _, command := range commands {
|
|
||||||
if command == target {
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return count
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareCurrentCardAcceptsEncoderPositionWithStaleDiagnostics(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
status []byte
|
|
||||||
wantStock string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "dispense error and jam",
|
|
||||||
status: []byte{0x30, 0x32, 0x32, 0x33},
|
|
||||||
wantStock: "Card jammed",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "supply diagnostics",
|
|
||||||
status: []byte{0x32, 0x30, 0x31, 0x33},
|
|
||||||
wantStock: "Card pre-empty",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "combined stale jam and supply diagnostics",
|
|
||||||
status: []byte{0x30, 0x32, 0x33, 0x33},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
var logOutput bytes.Buffer
|
|
||||||
standardLogger := log.StandardLogger()
|
|
||||||
previousOutput := standardLogger.Out
|
|
||||||
standardLogger.SetOutput(&logOutput)
|
|
||||||
t.Cleanup(func() {
|
|
||||||
standardLogger.SetOutput(previousOutput)
|
|
||||||
})
|
|
||||||
|
|
||||||
client, device := newSequenceTestClient(t, cmdResp{status: test.status})
|
|
||||||
|
|
||||||
stock, err := client.PrepareCurrentCard(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if stock != test.wantStock {
|
|
||||||
t.Fatalf("stock status = %q, want %q", stock, test.wantStock)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdToEncoder); got != 0 {
|
|
||||||
t.Fatalf("to-encoder commands = %d, want 0", got)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdStatus); got != 1 {
|
|
||||||
t.Fatalf("status reads = %d, want 1", got)
|
|
||||||
}
|
|
||||||
logged := logOutput.String()
|
|
||||||
if !strings.Contains(logged, "card confirmed at encoder") ||
|
|
||||||
!strings.Contains(logged, statusDescription(test.status)) ||
|
|
||||||
!strings.Contains(logged, "raw status") {
|
|
||||||
t.Fatalf("encoder diagnostic log = %q", logged)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareCurrentCardPollingAllowsTransientMovementWithStaleErrors(t *testing.T) {
|
|
||||||
client, device := newSequenceTestClient(t,
|
|
||||||
cmdResp{status: status(0x34)},
|
|
||||||
cmdResp{status: []byte{0x31, 0x38, 0x32, 0x30}},
|
|
||||||
cmdResp{status: []byte{0x30, 0x32, 0x32, 0x33}},
|
|
||||||
)
|
|
||||||
|
|
||||||
stock, err := client.PrepareCurrentCard(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if stock != "Card jammed" {
|
|
||||||
t.Fatalf("stock status = %q, want Card jammed", stock)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdToEncoder); got != 1 {
|
|
||||||
t.Fatalf("to-encoder commands = %d, want 1", got)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdStatus); got != 3 {
|
|
||||||
t.Fatalf("status reads = %d, want 3", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareCurrentCardRejectsFailureWithoutEncoderOrMovement(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
response cmdResp
|
|
||||||
wantError string
|
|
||||||
wantStock string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "status read error",
|
|
||||||
response: cmdResp{err: errors.New("serial read failed")},
|
|
||||||
wantError: "serial read failed",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "malformed status",
|
|
||||||
response: cmdResp{status: []byte{0x30, 0x30, 0x31}},
|
|
||||||
wantError: "malformed dispenser status",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "unknown status",
|
|
||||||
response: cmdResp{status: []byte{0x30, 0x30, 0x30, 0x39}},
|
|
||||||
wantError: "unknown dispenser status",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "jammed preparation",
|
|
||||||
response: cmdResp{status: []byte{0x30, 0x30, 0x32, 0x34}},
|
|
||||||
wantError: "Card jammed",
|
|
||||||
wantStock: "Card jammed",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
client, _ := newSequenceTestClient(t, test.response)
|
|
||||||
|
|
||||||
stock, err := client.PrepareCurrentCard(context.Background())
|
|
||||||
if err == nil || !strings.Contains(err.Error(), test.wantError) {
|
|
||||||
t.Fatalf("error = %v, want containing %q", err, test.wantError)
|
|
||||||
}
|
|
||||||
if stock != test.wantStock {
|
|
||||||
t.Fatalf("stock status = %q, want %q", stock, test.wantStock)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareCurrentCardReturnsAuthoritativeEmptyWellError(t *testing.T) {
|
|
||||||
client, device := newSequenceTestClient(t, cmdResp{status: status(0x38)})
|
|
||||||
|
|
||||||
stock, err := client.PrepareCurrentCard(context.Background())
|
|
||||||
if !errors.Is(err, ErrCardWellEmpty) {
|
|
||||||
t.Fatalf("error = %v, want ErrCardWellEmpty", err)
|
|
||||||
}
|
|
||||||
if stock != "Card empty" {
|
|
||||||
t.Fatalf("stock status = %q, want Card empty", stock)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdToEncoder); got != 0 {
|
|
||||||
t.Fatalf("to-encoder commands = %d, want 0", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeliverCurrentCardSucceedsAfterCommandAcceptanceWithoutStatusPolling(t *testing.T) {
|
|
||||||
staleStatus := []byte{0x30, 0x32, 0x32, 0x33}
|
|
||||||
client, device := newSequenceTestClient(t, cmdResp{status: staleStatus})
|
|
||||||
|
|
||||||
stock, err := client.DeliverCurrentCard(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if stock != "" {
|
|
||||||
t.Fatalf("stock status = %q, want empty", stock)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdOutOfMouth); got != 1 {
|
|
||||||
t.Fatalf("out-of-mouth commands = %d, want 1", got)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdStatus); got != 0 {
|
|
||||||
t.Fatalf("status reads = %d, want 0", got)
|
|
||||||
}
|
|
||||||
if len(device.statusResponses) != 1 {
|
|
||||||
t.Fatalf("queued status responses = %d, want stale status unread", len(device.statusResponses))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeliverCurrentCardRejectsCommandFailures(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
err error
|
|
||||||
}{
|
|
||||||
{name: "serial dispatch failure", err: errors.New("serial write failed")},
|
|
||||||
{name: "invalid acknowledgement", err: errors.New("unexpected response status")},
|
|
||||||
{name: "missing acknowledgement", err: errors.New("no response from dispenser")},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
client, device := newSequenceTestClient(t)
|
|
||||||
device.commandErrors[cmdOutOfMouth] = []error{test.err}
|
|
||||||
|
|
||||||
_, err := client.DeliverCurrentCard(context.Background())
|
|
||||||
if err == nil || !strings.Contains(err.Error(), test.err.Error()) {
|
|
||||||
t.Fatalf("error = %v, want containing %q", err, test.err)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdOutOfMouth); got != 1 {
|
|
||||||
t.Fatalf("out-of-mouth commands = %d, want 1", got)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdStatus); got != 0 {
|
|
||||||
t.Fatalf("status reads = %d, want 0", got)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeliverCurrentCardPreservesContextCancellation(t *testing.T) {
|
|
||||||
client, _ := newSequenceTestClient(t)
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
cancel()
|
|
||||||
|
|
||||||
_, err := client.DeliverCurrentCard(ctx)
|
|
||||||
if !errors.Is(err, context.Canceled) {
|
|
||||||
t.Fatalf("error = %v, want context.Canceled", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareCurrentCardRetriesOnceThenTimesOut(t *testing.T) {
|
|
||||||
responses := make([]cmdResp, 13)
|
|
||||||
for index := range responses {
|
|
||||||
responses[index] = cmdResp{status: status(0x34)}
|
|
||||||
}
|
|
||||||
client, device := newSequenceTestClient(t, responses...)
|
|
||||||
|
|
||||||
_, err := client.PrepareCurrentCard(context.Background())
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "timed out") {
|
|
||||||
t.Fatalf("error = %v, want preparation timeout", err)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdToEncoder); got != 2 {
|
|
||||||
t.Fatalf("to-encoder commands = %d, want initial command plus one halfway retry", got)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdStatus); got != 13 {
|
|
||||||
t.Fatalf("status reads = %d, want 13", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareCurrentCardPropagatesContextCancellation(t *testing.T) {
|
|
||||||
client, _ := newSequenceTestClient(t,
|
|
||||||
cmdResp{status: status(0x34)},
|
|
||||||
cmdResp{status: status(0x34)},
|
|
||||||
)
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
client.sequenceTiming.wait = func(context.Context, time.Duration) error {
|
|
||||||
cancel()
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := client.PrepareCurrentCard(ctx)
|
|
||||||
if !errors.Is(err, context.Canceled) {
|
|
||||||
t.Fatalf("error = %v, want context.Canceled", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBeginPrepareNextCardDispatchesWithoutReadinessPolling(t *testing.T) {
|
|
||||||
client, device := newSequenceTestClient(t)
|
|
||||||
|
|
||||||
if err := client.BeginPrepareNextCard(context.Background()); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdToEncoder); got != 1 {
|
|
||||||
t.Fatalf("to-encoder commands = %d, want 1", got)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdStatus); got != 0 {
|
|
||||||
t.Fatalf("status reads = %d, want 0", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBeginPrepareNextCardReturnsDispatchFailureWithoutPolling(t *testing.T) {
|
|
||||||
client, device := newSequenceTestClient(t)
|
|
||||||
device.commandErrors[cmdToEncoder] = []error{errors.New("dispatch failed")}
|
|
||||||
|
|
||||||
err := client.BeginPrepareNextCard(context.Background())
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "dispatch failed") {
|
|
||||||
t.Fatalf("error = %v, want dispatch failure", err)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdToEncoder); got != 1 {
|
|
||||||
t.Fatalf("to-encoder commands = %d, want 1", got)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdStatus); got != 0 {
|
|
||||||
t.Fatalf("status reads = %d, want 0", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareCardAtEncoderRequiresConfirmedEncoderState(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
responses []cmdResp
|
|
||||||
wantError string
|
|
||||||
wantToEncoder int
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "already at encoder",
|
|
||||||
responses: []cmdResp{{status: status(0x33)}},
|
|
||||||
wantToEncoder: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "moves ready card to encoder",
|
|
||||||
responses: []cmdResp{
|
|
||||||
{status: status(0x34)},
|
|
||||||
{status: status(0x33)},
|
|
||||||
},
|
|
||||||
wantToEncoder: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "empty card well",
|
|
||||||
responses: []cmdResp{{status: status(0x38)}},
|
|
||||||
wantError: CardWellEmptyMessage,
|
|
||||||
wantToEncoder: 0,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
client, device := newSequenceTestClient(t, test.responses...)
|
|
||||||
|
|
||||||
_, err := client.PrepareNextCard(context.Background())
|
|
||||||
if test.wantError == "" && err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if test.wantError != "" && (err == nil || !strings.Contains(err.Error(), test.wantError)) {
|
|
||||||
t.Fatalf("error = %v, want containing %q", err, test.wantError)
|
|
||||||
}
|
|
||||||
if got := commandCount(device.commands, cmdToEncoder); got != test.wantToEncoder {
|
|
||||||
t.Fatalf("to-encoder commands = %d, want %d", got, test.wantToEncoder)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+17
-295
@@ -4,18 +4,15 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"sort"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -36,43 +33,6 @@ type Client struct {
|
|||||||
httpClient *http.Client
|
httpClient *http.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
|
||||||
dojoTerminalUnavailableStatus = "TERMINAL_UNAVAILABLE"
|
|
||||||
dojoTerminalUnavailableMessage = "Payment terminal is unavailable"
|
|
||||||
)
|
|
||||||
|
|
||||||
type httpResponseError struct {
|
|
||||||
StatusCode int
|
|
||||||
Body string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *httpResponseError) Error() string {
|
|
||||||
return fmt.Sprintf("Dojo returned HTTP %d: %s", e.StatusCode, e.Body)
|
|
||||||
}
|
|
||||||
|
|
||||||
type terminalSessionWithUpdates struct {
|
|
||||||
terminalSessionResponse
|
|
||||||
|
|
||||||
NotificationEvents []terminalNotificationEvent `json:"notificationEvents"`
|
|
||||||
StatusEvents []terminalStatusEvent `json:"statusEvents"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type terminalNotificationEvent struct {
|
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
|
||||||
NotificationType string `json:"notificationType"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type terminalStatusEvent struct {
|
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type terminalDisplayEvent struct {
|
|
||||||
createdAt time.Time
|
|
||||||
code string
|
|
||||||
sessionStatus string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(cfg Config) (*Client, error) {
|
func NewClient(cfg Config) (*Client, error) {
|
||||||
if cfg.BaseURL == "" {
|
if cfg.BaseURL == "" {
|
||||||
return nil, fmt.Errorf("dojo base_url is required")
|
return nil, fmt.Errorf("dojo base_url is required")
|
||||||
@@ -100,17 +60,11 @@ func NewClient(cfg Config) (*Client, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) Sale(
|
func (c *Client) Sale(ctx context.Context, req paymentsvc.SaleRequest) (*paymentsvc.Result, error) {
|
||||||
ctx context.Context,
|
|
||||||
req paymentsvc.SaleRequest,
|
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
) (*paymentsvc.Result, error) {
|
|
||||||
if req.Currency == "" {
|
if req.Currency == "" {
|
||||||
req.Currency = "GBP"
|
req.Currency = "GBP"
|
||||||
}
|
}
|
||||||
|
|
||||||
sendPaymentStatus(onStatus, paymentstatus.Starting)
|
|
||||||
|
|
||||||
intent, err := c.createPaymentIntent(ctx, req)
|
intent, err := c.createPaymentIntent(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -118,25 +72,10 @@ func (c *Client) Sale(
|
|||||||
|
|
||||||
session, err := c.createTerminalSession(ctx, intent.ID)
|
session, err := c.createTerminalSession(ctx, intent.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var responseErr *httpResponseError
|
|
||||||
if errors.As(err, &responseErr) && responseErr.StatusCode == http.StatusConflict {
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"provider": "Dojo",
|
|
||||||
"operation": "createTerminalSession",
|
|
||||||
"status": responseErr.StatusCode,
|
|
||||||
"terminal_unavailable": true,
|
|
||||||
}).Warn(dojoTerminalUnavailableMessage)
|
|
||||||
|
|
||||||
sendPaymentStatus(onStatus, paymentstatus.TerminalUnavailable)
|
|
||||||
result := c.baseResult(req, nil)
|
|
||||||
result.Status = dojoTerminalUnavailableStatus
|
|
||||||
result.ErrorMessage = dojoTerminalUnavailableMessage
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
session, err = c.waitForTerminalSession(ctx, session.ID, onStatus)
|
session, err = c.waitForTerminalSession(ctx, session.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -211,17 +150,10 @@ func (c *Client) createTerminalSession(ctx context.Context, paymentIntentID stri
|
|||||||
return &response, nil
|
return &response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) waitForTerminalSession(
|
func (c *Client) waitForTerminalSession(ctx context.Context, terminalSessionID string) (*terminalSessionResponse, error) {
|
||||||
ctx context.Context,
|
|
||||||
terminalSessionID string,
|
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
) (*terminalSessionResponse, error) {
|
|
||||||
ticker := time.NewTicker(time.Second)
|
ticker := time.NewTicker(time.Second)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
notificationCount := 0
|
|
||||||
statusCount := 0
|
|
||||||
lastSessionStatus := ""
|
|
||||||
signatureRejected := false
|
signatureRejected := false
|
||||||
|
|
||||||
for {
|
for {
|
||||||
@@ -232,40 +164,12 @@ func (c *Client) waitForTerminalSession(
|
|||||||
|
|
||||||
log.Println("session status:", session.Status)
|
log.Println("session status:", session.Status)
|
||||||
|
|
||||||
emitNewTerminalSessionEvents(
|
switch strings.ToLower(session.Status) {
|
||||||
session,
|
case types.ResultInitiateRequested, types.ResultInitiated, types.ResultAuthorized, types.ResultCancelRequested:
|
||||||
¬ificationCount,
|
|
||||||
&statusCount,
|
|
||||||
&lastSessionStatus,
|
|
||||||
onStatus,
|
|
||||||
)
|
|
||||||
|
|
||||||
currentStatus := strings.ToLower(session.Status)
|
|
||||||
if currentStatus != lastSessionStatus {
|
|
||||||
lastSessionStatus = currentStatus
|
|
||||||
sendPaymentStatus(
|
|
||||||
onStatus,
|
|
||||||
mapDojoSessionStatus(session.Status),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch currentStatus {
|
|
||||||
case types.ResultInitiateRequested,
|
|
||||||
types.ResultInitiated,
|
|
||||||
types.ResultAuthorized,
|
|
||||||
types.ResultCancelRequested:
|
|
||||||
|
|
||||||
case types.ResultSignatureRequired:
|
case types.ResultSignatureRequired:
|
||||||
if !signatureRejected {
|
if !signatureRejected {
|
||||||
sendPaymentStatus(
|
rejectedSession, err := c.rejectSignature(ctx, terminalSessionID)
|
||||||
onStatus,
|
|
||||||
paymentstatus.SignatureRejecting,
|
|
||||||
)
|
|
||||||
|
|
||||||
rejectedSession, err := c.rejectSignature(
|
|
||||||
ctx,
|
|
||||||
terminalSessionID,
|
|
||||||
)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -273,206 +177,30 @@ func (c *Client) waitForTerminalSession(
|
|||||||
signatureRejected = true
|
signatureRejected = true
|
||||||
|
|
||||||
if rejectedSession != nil {
|
if rejectedSession != nil {
|
||||||
rejectedStatus := strings.ToLower(
|
switch strings.ToLower(rejectedSession.Status) {
|
||||||
rejectedSession.Status,
|
case types.ResultCaptured, types.ResultCancelled, types.ResultCanceled, types.ResultDeclined,
|
||||||
)
|
types.ResultExpired, types.ResultSignatureAccepted, types.ResultSignatureRejected:
|
||||||
|
|
||||||
if rejectedStatus != lastSessionStatus {
|
|
||||||
lastSessionStatus = rejectedStatus
|
|
||||||
sendPaymentStatus(
|
|
||||||
onStatus,
|
|
||||||
mapDojoSessionStatus(
|
|
||||||
rejectedSession.Status,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch rejectedStatus {
|
|
||||||
case types.ResultCaptured,
|
|
||||||
types.ResultCancelled,
|
|
||||||
types.ResultCanceled,
|
|
||||||
types.ResultDeclined,
|
|
||||||
types.ResultExpired,
|
|
||||||
types.ResultSignatureAccepted,
|
|
||||||
types.ResultSignatureRejected:
|
|
||||||
return rejectedSession, nil
|
return rejectedSession, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case types.ResultCaptured,
|
case types.ResultCaptured, types.ResultCancelled, types.ResultCanceled, types.ResultDeclined,
|
||||||
types.ResultCancelled,
|
types.ResultExpired, types.ResultSignatureAccepted, types.ResultSignatureRejected:
|
||||||
types.ResultCanceled,
|
return session, nil
|
||||||
types.ResultDeclined,
|
|
||||||
types.ResultExpired,
|
|
||||||
types.ResultSignatureAccepted,
|
|
||||||
types.ResultSignatureRejected:
|
|
||||||
return &session.terminalSessionResponse, nil
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf(
|
return nil, fmt.Errorf("unexpected Dojo terminal session status %q", session.Status)
|
||||||
"unexpected Dojo terminal session status %q",
|
|
||||||
session.Status,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return nil, ctx.Err()
|
return nil, ctx.Err()
|
||||||
|
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func emitNewTerminalSessionEvents(
|
|
||||||
session *terminalSessionWithUpdates,
|
|
||||||
notificationCount *int,
|
|
||||||
statusCount *int,
|
|
||||||
lastSessionStatus *string,
|
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
) {
|
|
||||||
if *notificationCount > len(session.NotificationEvents) {
|
|
||||||
*notificationCount = len(session.NotificationEvents)
|
|
||||||
}
|
|
||||||
if *statusCount > len(session.StatusEvents) {
|
|
||||||
*statusCount = len(session.StatusEvents)
|
|
||||||
}
|
|
||||||
|
|
||||||
newEventCount := len(session.NotificationEvents) - *notificationCount +
|
|
||||||
len(session.StatusEvents) - *statusCount
|
|
||||||
events := make([]terminalDisplayEvent, 0, newEventCount)
|
|
||||||
|
|
||||||
// Add status events first so a notification wins when timestamps are equal.
|
|
||||||
for *statusCount < len(session.StatusEvents) {
|
|
||||||
event := session.StatusEvents[*statusCount]
|
|
||||||
*statusCount = *statusCount + 1
|
|
||||||
|
|
||||||
events = append(events, terminalDisplayEvent{
|
|
||||||
createdAt: event.CreatedAt,
|
|
||||||
code: mapDojoSessionStatus(event.Status),
|
|
||||||
sessionStatus: event.Status,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
for *notificationCount < len(session.NotificationEvents) {
|
|
||||||
event := session.NotificationEvents[*notificationCount]
|
|
||||||
*notificationCount = *notificationCount + 1
|
|
||||||
|
|
||||||
events = append(events, terminalDisplayEvent{
|
|
||||||
createdAt: event.CreatedAt,
|
|
||||||
code: mapDojoNotification(event.NotificationType),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.SliceStable(events, func(i, j int) bool {
|
|
||||||
return events[i].createdAt.Before(events[j].createdAt)
|
|
||||||
})
|
|
||||||
|
|
||||||
for _, event := range events {
|
|
||||||
if event.sessionStatus != "" {
|
|
||||||
*lastSessionStatus = strings.ToLower(event.sessionStatus)
|
|
||||||
}
|
|
||||||
|
|
||||||
sendPaymentStatus(onStatus, event.code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendPaymentStatus(
|
|
||||||
handler paymentsvc.StatusHandler,
|
|
||||||
code string,
|
|
||||||
) {
|
|
||||||
if handler == nil || code == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
handler(paymentsvc.StatusUpdate{
|
|
||||||
Code: code,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapDojoNotification(notification string) string {
|
|
||||||
switch notification {
|
|
||||||
case "PresentCard":
|
|
||||||
return paymentstatus.PresentCard
|
|
||||||
|
|
||||||
case "InsertCard":
|
|
||||||
return paymentstatus.InsertCard
|
|
||||||
|
|
||||||
case "SwipeCard":
|
|
||||||
return paymentstatus.SwipeCard
|
|
||||||
|
|
||||||
case "EnterPin":
|
|
||||||
return paymentstatus.EnterPIN
|
|
||||||
|
|
||||||
case "RemoveCard":
|
|
||||||
return paymentstatus.RemoveCard
|
|
||||||
|
|
||||||
case "PleaseWait":
|
|
||||||
return paymentstatus.PleaseWait
|
|
||||||
|
|
||||||
default:
|
|
||||||
return dojoFallbackStatusCode(
|
|
||||||
paymentstatus.DojoNotificationPrefix,
|
|
||||||
notification,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapDojoSessionStatus(status string) string {
|
|
||||||
switch strings.ToLower(status) {
|
|
||||||
case types.ResultInitiateRequested:
|
|
||||||
return paymentstatus.Starting
|
|
||||||
|
|
||||||
case types.ResultInitiated:
|
|
||||||
return paymentstatus.Started
|
|
||||||
|
|
||||||
case types.ResultAuthorized:
|
|
||||||
return paymentstatus.Authorized
|
|
||||||
|
|
||||||
case types.ResultCancelRequested:
|
|
||||||
return paymentstatus.Cancelling
|
|
||||||
|
|
||||||
case types.ResultSignatureRequired:
|
|
||||||
return paymentstatus.SignatureRequired
|
|
||||||
|
|
||||||
case types.ResultCaptured, types.ResultSignatureAccepted:
|
|
||||||
return paymentstatus.Approved
|
|
||||||
|
|
||||||
case types.ResultCancelled, types.ResultCanceled:
|
|
||||||
return paymentstatus.Cancelled
|
|
||||||
|
|
||||||
case types.ResultDeclined:
|
|
||||||
return paymentstatus.Declined
|
|
||||||
|
|
||||||
case types.ResultExpired:
|
|
||||||
return paymentstatus.Expired
|
|
||||||
|
|
||||||
case types.ResultSignatureRejected:
|
|
||||||
return paymentstatus.SignatureRejected
|
|
||||||
|
|
||||||
default:
|
|
||||||
return dojoFallbackStatusCode(
|
|
||||||
paymentstatus.DojoStatusPrefix,
|
|
||||||
status,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func dojoFallbackStatusCode(prefix, value string) string {
|
|
||||||
value = strings.TrimSpace(value)
|
|
||||||
if value == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
replacer := strings.NewReplacer(
|
|
||||||
" ", "_",
|
|
||||||
"-", "_",
|
|
||||||
)
|
|
||||||
|
|
||||||
return prefix + strings.ToUpper(replacer.Replace(value))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) rejectSignature(ctx context.Context, terminalSessionID string) (*terminalSessionResponse, error) {
|
func (c *Client) rejectSignature(ctx context.Context, terminalSessionID string) (*terminalSessionResponse, error) {
|
||||||
payload := signatureVerificationRequest{
|
payload := signatureVerificationRequest{
|
||||||
Accepted: false,
|
Accepted: false,
|
||||||
@@ -488,11 +216,8 @@ func (c *Client) rejectSignature(ctx context.Context, terminalSessionID string)
|
|||||||
return &response, nil
|
return &response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) getTerminalSession(
|
func (c *Client) getTerminalSession(ctx context.Context, terminalSessionID string) (*terminalSessionResponse, error) {
|
||||||
ctx context.Context,
|
var response terminalSessionResponse
|
||||||
terminalSessionID string,
|
|
||||||
) (*terminalSessionWithUpdates, error) {
|
|
||||||
var response terminalSessionWithUpdates
|
|
||||||
path := "/terminal-sessions/" + url.PathEscape(terminalSessionID)
|
path := "/terminal-sessions/" + url.PathEscape(terminalSessionID)
|
||||||
if err := c.doJSON(ctx, http.MethodGet, path, nil, true, &response); err != nil {
|
if err := c.doJSON(ctx, http.MethodGet, path, nil, true, &response); err != nil {
|
||||||
return nil, fmt.Errorf("get Dojo terminal session: %w", err)
|
return nil, fmt.Errorf("get Dojo terminal session: %w", err)
|
||||||
@@ -599,13 +324,10 @@ func (c *Client) doJSON(ctx context.Context, method, path string, payload any, t
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("read response: %w", err)
|
return fmt.Errorf("read response: %w", err)
|
||||||
}
|
}
|
||||||
// log.Println("Dojo payment result raw:", string(responseBody))
|
|
||||||
if resp.StatusCode < http.StatusOK ||
|
if resp.StatusCode < http.StatusOK ||
|
||||||
resp.StatusCode >= http.StatusMultipleChoices {
|
resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
return &httpResponseError{
|
return fmt.Errorf("Dojo returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(responseBody)))
|
||||||
StatusCode: resp.StatusCode,
|
|
||||||
Body: strings.TrimSpace(string(responseBody)),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if target == nil || len(responseBody) == 0 {
|
if target == nil || len(responseBody) == 0 {
|
||||||
|
|||||||
@@ -1,199 +0,0 @@
|
|||||||
package dojo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
|
||||||
)
|
|
||||||
|
|
||||||
const terminalUnavailableBody = `{"detail":"the terminal is either offline or currently in use","errors":{},"status":409,"title":"terminal unavailable","traceId":"trace-secret","type":"https://docs.dojo.tech/problems/terminal-unavailable"}`
|
|
||||||
|
|
||||||
func TestDoJSONReturnsStructuredHTTPResponseError(t *testing.T) {
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
_, _ = w.Write([]byte(" " + terminalUnavailableBody + " "))
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
client := newDojoTestClient(t, server)
|
|
||||||
err := client.doJSON(context.Background(), http.MethodPost, "/payment-intents", nil, false, nil)
|
|
||||||
|
|
||||||
var responseErr *httpResponseError
|
|
||||||
if !errors.As(err, &responseErr) {
|
|
||||||
t.Fatalf("error = %T %v, want *httpResponseError", err, err)
|
|
||||||
}
|
|
||||||
if responseErr.StatusCode != http.StatusConflict {
|
|
||||||
t.Fatalf("StatusCode = %d, want %d", responseErr.StatusCode, http.StatusConflict)
|
|
||||||
}
|
|
||||||
if responseErr.Body != terminalUnavailableBody {
|
|
||||||
t.Fatalf("Body = %q, want retained trimmed response", responseErr.Body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSaleMapsCreateTerminalSessionConflictToTerminalUnavailable(t *testing.T) {
|
|
||||||
var paymentIntentRequests atomic.Int32
|
|
||||||
var terminalSessionRequests atomic.Int32
|
|
||||||
var unexpectedRequests atomic.Int32
|
|
||||||
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch {
|
|
||||||
case r.Method == http.MethodPost && r.URL.Path == "/payment-intents":
|
|
||||||
paymentIntentRequests.Add(1)
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_, _ = fmt.Fprintln(w, `{"id":"intent-123"}`)
|
|
||||||
case r.Method == http.MethodPost && r.URL.Path == "/terminal-sessions":
|
|
||||||
terminalSessionRequests.Add(1)
|
|
||||||
w.Header().Set("Content-Type", "application/problem+json")
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
_, _ = fmt.Fprintln(w, terminalUnavailableBody)
|
|
||||||
default:
|
|
||||||
unexpectedRequests.Add(1)
|
|
||||||
http.Error(w, "unexpected request", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
client := newDojoTestClient(t, server)
|
|
||||||
request := paymentsvc.SaleRequest{
|
|
||||||
RequestID: "REQ-123",
|
|
||||||
Reference: "BOOKING-123",
|
|
||||||
Amount: 10852,
|
|
||||||
Currency: "GBP",
|
|
||||||
}
|
|
||||||
var statuses []string
|
|
||||||
result, err := client.Sale(context.Background(), request, func(update paymentsvc.StatusUpdate) {
|
|
||||||
statuses = append(statuses, update.Code)
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if result == nil {
|
|
||||||
t.Fatal("Sale returned nil result")
|
|
||||||
}
|
|
||||||
if result.Success || result.Status == "APPROVED" {
|
|
||||||
t.Fatalf("result was accidentally successful: %+v", result)
|
|
||||||
}
|
|
||||||
if result.Status != dojoTerminalUnavailableStatus || result.ErrorMessage != dojoTerminalUnavailableMessage {
|
|
||||||
t.Fatalf("terminal-unavailable result = %+v", result)
|
|
||||||
}
|
|
||||||
if result.RequestID != request.RequestID ||
|
|
||||||
result.Operation != "SALE" ||
|
|
||||||
result.Amount != request.Amount ||
|
|
||||||
result.Currency != request.Currency ||
|
|
||||||
result.DeviceUsed != "terminal-1" ||
|
|
||||||
result.DeviceType != "Dojo Terminal" {
|
|
||||||
t.Fatalf("base result fields were not retained: %+v", result)
|
|
||||||
}
|
|
||||||
if result.TransactionID != "" || result.CustomerReceipt != "" || result.MerchantReceipt != "" {
|
|
||||||
t.Fatalf("terminal-unavailable result invented transaction data: %+v", result)
|
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(statuses, []string{paymentstatus.Starting, paymentstatus.TerminalUnavailable}) {
|
|
||||||
t.Fatalf("statuses = %#v", statuses)
|
|
||||||
}
|
|
||||||
if paymentIntentRequests.Load() != 1 || terminalSessionRequests.Load() != 1 || unexpectedRequests.Load() != 0 {
|
|
||||||
t.Fatalf(
|
|
||||||
"requests: intent=%d terminal=%d unexpected=%d",
|
|
||||||
paymentIntentRequests.Load(),
|
|
||||||
terminalSessionRequests.Load(),
|
|
||||||
unexpectedRequests.Load(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
resultText := fmt.Sprintf("%+v", result)
|
|
||||||
for _, forbidden := range []string{"offline or currently in use", "trace-secret", "docs.dojo.tech", terminalUnavailableBody} {
|
|
||||||
if strings.Contains(resultText, forbidden) {
|
|
||||||
t.Fatalf("result exposed %q: %s", forbidden, resultText)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSaleDoesNotClassifyPaymentIntentConflictAsTerminalUnavailable(t *testing.T) {
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.URL.Path != "/payment-intents" {
|
|
||||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
_, _ = fmt.Fprintln(w, terminalUnavailableBody)
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
client := newDojoTestClient(t, server)
|
|
||||||
var statuses []string
|
|
||||||
result, err := client.Sale(context.Background(), paymentsvc.SaleRequest{
|
|
||||||
RequestID: "REQ-123",
|
|
||||||
Amount: 10852,
|
|
||||||
Currency: "GBP",
|
|
||||||
}, func(update paymentsvc.StatusUpdate) {
|
|
||||||
statuses = append(statuses, update.Code)
|
|
||||||
})
|
|
||||||
|
|
||||||
if result != nil || err == nil {
|
|
||||||
t.Fatalf("Sale result/error = %+v/%v, want nil generic error", result, err)
|
|
||||||
}
|
|
||||||
var responseErr *httpResponseError
|
|
||||||
if !errors.As(err, &responseErr) || responseErr.StatusCode != http.StatusConflict {
|
|
||||||
t.Fatalf("error = %T %v, want wrapped HTTP 409", err, err)
|
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(statuses, []string{paymentstatus.Starting}) {
|
|
||||||
t.Fatalf("statuses = %#v, want only PAYMENT_STARTING", statuses)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSaleRetainsGenericCreateTerminalSessionErrors(t *testing.T) {
|
|
||||||
for _, statusCode := range []int{http.StatusBadRequest, http.StatusBadGateway} {
|
|
||||||
t.Run(http.StatusText(statusCode), func(t *testing.T) {
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/payment-intents":
|
|
||||||
_, _ = fmt.Fprintln(w, `{"id":"intent-123"}`)
|
|
||||||
case "/terminal-sessions":
|
|
||||||
w.WriteHeader(statusCode)
|
|
||||||
_, _ = fmt.Fprintln(w, `{"detail":"provider failure"}`)
|
|
||||||
default:
|
|
||||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
client := newDojoTestClient(t, server)
|
|
||||||
result, err := client.Sale(context.Background(), paymentsvc.SaleRequest{
|
|
||||||
RequestID: "REQ-123",
|
|
||||||
Amount: 10852,
|
|
||||||
Currency: "GBP",
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if result != nil || err == nil {
|
|
||||||
t.Fatalf("Sale result/error = %+v/%v, want nil generic error", result, err)
|
|
||||||
}
|
|
||||||
var responseErr *httpResponseError
|
|
||||||
if !errors.As(err, &responseErr) || responseErr.StatusCode != statusCode {
|
|
||||||
t.Fatalf("error = %T %v, want wrapped HTTP %d", err, err, statusCode)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newDojoTestClient(t *testing.T, server *httptest.Server) *Client {
|
|
||||||
t.Helper()
|
|
||||||
client, err := NewClient(Config{
|
|
||||||
BaseURL: server.URL,
|
|
||||||
APIKey: "test-api-key",
|
|
||||||
SoftwareHouseID: "software-house-1",
|
|
||||||
TerminalID: "terminal-1",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
client.httpClient = server.Client()
|
|
||||||
return client
|
|
||||||
}
|
|
||||||
@@ -1,130 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,480 +0,0 @@
|
|||||||
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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,226 +0,0 @@
|
|||||||
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) {
|
|
||||||
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 !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 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
|
|
||||||
}
|
|
||||||
if _, ok := w.(http.Flusher); !ok {
|
|
||||||
reject(http.StatusInternalServerError, "Streaming payment updates are not supported")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
progress := make(chan string, 128)
|
|
||||||
finished := make(chan creditCallSaleOutcome, 1)
|
|
||||||
go func() {
|
|
||||||
outcome := app.executeCreditCallSale(cmstypes.TransactionRec{
|
|
||||||
AmountMinorUnits: strconv.FormatInt(request.Amount, 10), TransactionType: "Sale",
|
|
||||||
}, func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
|
||||||
return callChipDNAStream(client, request.Amount, func(code string) {
|
|
||||||
select {
|
|
||||||
case progress <- code:
|
|
||||||
default: // Observational progress may be dropped under backpressure.
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
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) {
|
|
||||||
var result creditcall.TransactionResultXML
|
|
||||||
payload, err := json.Marshal(struct {
|
|
||||||
Amount string `json:"amount"`
|
|
||||||
TransactionType string `json:"transactionType"`
|
|
||||||
}{strconv.FormatInt(amount, 10), "Sale"})
|
|
||||||
if err != nil {
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
// Background plus Client.Timeout reproduces the independent per-call bound.
|
|
||||||
req, err := http.NewRequestWithContext(context.Background(), 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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,313 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dispenser"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
type dispenserCallResult struct {
|
|
||||||
status string
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
type fakeDoorCardDispenser struct {
|
|
||||||
prepareCurrent dispenserCallResult
|
|
||||||
deliverCurrent dispenserCallResult
|
|
||||||
beginNextErr error
|
|
||||||
beginNext func() error
|
|
||||||
prepareNext dispenserCallResult
|
|
||||||
calls []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *fakeDoorCardDispenser) PrepareCurrentCard(context.Context) (string, error) {
|
|
||||||
d.calls = append(d.calls, "prepare current")
|
|
||||||
return d.prepareCurrent.status, d.prepareCurrent.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *fakeDoorCardDispenser) DeliverCurrentCard(context.Context) (string, error) {
|
|
||||||
d.calls = append(d.calls, "deliver current")
|
|
||||||
return d.deliverCurrent.status, d.deliverCurrent.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *fakeDoorCardDispenser) BeginPrepareNextCard(context.Context) error {
|
|
||||||
d.calls = append(d.calls, "begin prepare next")
|
|
||||||
if d.beginNext != nil {
|
|
||||||
return d.beginNext()
|
|
||||||
}
|
|
||||||
return d.beginNextErr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *fakeDoorCardDispenser) PrepareNextCard(context.Context) (string, error) {
|
|
||||||
d.calls = append(d.calls, "prepare next")
|
|
||||||
return d.prepareNext.status, d.prepareNext.err
|
|
||||||
}
|
|
||||||
|
|
||||||
type fakeDoorCardLockServer struct {
|
|
||||||
sequenceErr error
|
|
||||||
buildCalls int
|
|
||||||
sequenceCalls int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *fakeDoorCardLockServer) BuildCommand(lockserver.DoorCardRequest, time.Time, time.Time) error {
|
|
||||||
l.buildCalls++
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *fakeDoorCardLockServer) LockSequence() error {
|
|
||||||
l.sequenceCalls++
|
|
||||||
return l.sequenceErr
|
|
||||||
}
|
|
||||||
|
|
||||||
func performIssueDoorCardRequest(
|
|
||||||
t *testing.T,
|
|
||||||
dispenser *fakeDoorCardDispenser,
|
|
||||||
lock *fakeDoorCardLockServer,
|
|
||||||
) (*httptest.ResponseRecorder, cmstypes.StatusRec, *App) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
payload := lockserver.DoorCardRequest{
|
|
||||||
RoomField: "101",
|
|
||||||
CheckinTime: "2026-07-23 15:00:00 +0100",
|
|
||||||
CheckoutTime: "2026-07-24 11:00:00 +0100",
|
|
||||||
FollowStr: "0",
|
|
||||||
}
|
|
||||||
body, err := json.Marshal(payload)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
app := &App{
|
|
||||||
disp: dispenser,
|
|
||||||
lockserver: lock,
|
|
||||||
cfg: &config.ConfigRec{},
|
|
||||||
}
|
|
||||||
request := httptest.NewRequest(http.MethodPost, "/issuedoorcard", bytes.NewReader(body))
|
|
||||||
request.Header.Set("Content-Type", "application/json")
|
|
||||||
recorder := httptest.NewRecorder()
|
|
||||||
|
|
||||||
app.issueDoorCard(recorder, request)
|
|
||||||
|
|
||||||
var response cmstypes.StatusRec
|
|
||||||
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
|
||||||
t.Fatalf("decode response %q: %v", recorder.Body.String(), err)
|
|
||||||
}
|
|
||||||
return recorder, response, app
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIssueDoorCardPhysicalOutcomeContract(t *testing.T) {
|
|
||||||
encodingErr := errors.New("key encoding failed")
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
dispenser fakeDoorCardDispenser
|
|
||||||
lockErr error
|
|
||||||
wantHTTP int
|
|
||||||
wantMessage string
|
|
||||||
wantCalls []string
|
|
||||||
wantLockSequence int
|
|
||||||
wantCardWell string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "initial dispenser preparation failure is unavailable",
|
|
||||||
dispenser: fakeDoorCardDispenser{
|
|
||||||
prepareCurrent: dispenserCallResult{status: "Card jammed", err: errors.New("card jammed")},
|
|
||||||
},
|
|
||||||
wantHTTP: http.StatusServiceUnavailable,
|
|
||||||
wantMessage: "Dispense error: card jammed",
|
|
||||||
wantCalls: []string{"prepare current"},
|
|
||||||
wantCardWell: "Card jammed",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "initial empty card well has stable message",
|
|
||||||
dispenser: fakeDoorCardDispenser{
|
|
||||||
prepareCurrent: dispenserCallResult{status: "Card empty", err: dispenser.ErrCardWellEmpty},
|
|
||||||
},
|
|
||||||
wantHTTP: http.StatusServiceUnavailable,
|
|
||||||
wantMessage: dispenser.CardWellEmptyMessage,
|
|
||||||
wantCalls: []string{"prepare current"},
|
|
||||||
wantCardWell: "Card empty",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "encoding and accepted delivery command succeed",
|
|
||||||
wantHTTP: http.StatusOK,
|
|
||||||
wantMessage: "Card issued successfully",
|
|
||||||
wantCalls: []string{"prepare current", "deliver current", "begin prepare next"},
|
|
||||||
wantLockSequence: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "successful encoding with delivery command failure is unavailable",
|
|
||||||
dispenser: fakeDoorCardDispenser{
|
|
||||||
deliverCurrent: dispenserCallResult{status: "Card jammed", err: errors.New("delivery jammed")},
|
|
||||||
},
|
|
||||||
wantHTTP: http.StatusServiceUnavailable,
|
|
||||||
wantMessage: "Card delivery could not be confirmed",
|
|
||||||
wantCalls: []string{"prepare current", "deliver current"},
|
|
||||||
wantLockSequence: 1,
|
|
||||||
wantCardWell: "Card jammed",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "failed next-card dispatch does not undo delivered card",
|
|
||||||
dispenser: fakeDoorCardDispenser{
|
|
||||||
beginNextErr: errors.New("dispatch failed"),
|
|
||||||
},
|
|
||||||
wantHTTP: http.StatusOK,
|
|
||||||
wantMessage: "Card issued successfully",
|
|
||||||
wantCalls: []string{"prepare current", "deliver current", "begin prepare next"},
|
|
||||||
wantLockSequence: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "encoding failure with safe recovery remains retryable",
|
|
||||||
lockErr: encodingErr,
|
|
||||||
wantHTTP: http.StatusBadGateway,
|
|
||||||
wantMessage: encodingErr.Error(),
|
|
||||||
wantCalls: []string{"prepare current", "deliver current", "prepare next"},
|
|
||||||
wantLockSequence: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "encoding failure with failed-card delivery failure is unavailable",
|
|
||||||
dispenser: fakeDoorCardDispenser{
|
|
||||||
deliverCurrent: dispenserCallResult{status: "Card jammed", err: errors.New("delivery jammed")},
|
|
||||||
},
|
|
||||||
lockErr: encodingErr,
|
|
||||||
wantHTTP: http.StatusServiceUnavailable,
|
|
||||||
wantMessage: "Dispenser recovery failed; another encoding attempt is not safe",
|
|
||||||
wantCalls: []string{"prepare current", "deliver current"},
|
|
||||||
wantLockSequence: 1,
|
|
||||||
wantCardWell: "Card jammed",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "encoding failure with empty card well has stable message",
|
|
||||||
dispenser: fakeDoorCardDispenser{
|
|
||||||
prepareNext: dispenserCallResult{status: "Card empty", err: dispenser.ErrCardWellEmpty},
|
|
||||||
},
|
|
||||||
lockErr: encodingErr,
|
|
||||||
wantHTTP: http.StatusServiceUnavailable,
|
|
||||||
wantMessage: dispenser.CardWellEmptyMessage,
|
|
||||||
wantCalls: []string{"prepare current", "deliver current", "prepare next"},
|
|
||||||
wantLockSequence: 1,
|
|
||||||
wantCardWell: "Card empty",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
dispenser := test.dispenser
|
|
||||||
lock := &fakeDoorCardLockServer{sequenceErr: test.lockErr}
|
|
||||||
|
|
||||||
recorder, response, app := performIssueDoorCardRequest(t, &dispenser, lock)
|
|
||||||
|
|
||||||
if recorder.Code != test.wantHTTP {
|
|
||||||
t.Fatalf("HTTP status = %d, want %d", recorder.Code, test.wantHTTP)
|
|
||||||
}
|
|
||||||
if response.Code != test.wantHTTP {
|
|
||||||
t.Fatalf("response code = %d, want %d", response.Code, test.wantHTTP)
|
|
||||||
}
|
|
||||||
if response.Message != test.wantMessage {
|
|
||||||
t.Fatalf("response message = %q, want %q", response.Message, test.wantMessage)
|
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(dispenser.calls, test.wantCalls) {
|
|
||||||
t.Fatalf("dispenser calls = %#v, want %#v", dispenser.calls, test.wantCalls)
|
|
||||||
}
|
|
||||||
if lock.sequenceCalls != test.wantLockSequence {
|
|
||||||
t.Fatalf("lock sequence calls = %d, want %d", lock.sequenceCalls, test.wantLockSequence)
|
|
||||||
}
|
|
||||||
if test.wantLockSequence > 0 && lock.buildCalls != 1 {
|
|
||||||
t.Fatalf("build command calls = %d, want 1", lock.buildCalls)
|
|
||||||
}
|
|
||||||
if test.wantLockSequence == 0 && lock.buildCalls != 0 {
|
|
||||||
t.Fatalf("build command calls = %d, want 0", lock.buildCalls)
|
|
||||||
}
|
|
||||||
if got := app.CardWellStatus(); got != test.wantCardWell {
|
|
||||||
t.Fatalf("card-well status = %q, want %q", got, test.wantCardWell)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type responseTrackingRecorder struct {
|
|
||||||
*httptest.ResponseRecorder
|
|
||||||
wroteResponse bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *responseTrackingRecorder) WriteHeader(statusCode int) {
|
|
||||||
r.wroteResponse = true
|
|
||||||
r.ResponseRecorder.WriteHeader(statusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *responseTrackingRecorder) Write(body []byte) (int, error) {
|
|
||||||
r.wroteResponse = true
|
|
||||||
return r.ResponseRecorder.Write(body)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIssueDoorCardDispatchesNextCardBeforeHTTP200(t *testing.T) {
|
|
||||||
var recorder *responseTrackingRecorder
|
|
||||||
dispatchCalled := false
|
|
||||||
dispenser := &fakeDoorCardDispenser{
|
|
||||||
beginNext: func() error {
|
|
||||||
dispatchCalled = true
|
|
||||||
if recorder.wroteResponse {
|
|
||||||
t.Error("HTTP response started before next-card preparation was dispatched")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
lock := &fakeDoorCardLockServer{}
|
|
||||||
payload := lockserver.DoorCardRequest{
|
|
||||||
RoomField: "101",
|
|
||||||
CheckinTime: "2026-07-23 15:00:00 +0100",
|
|
||||||
CheckoutTime: "2026-07-24 11:00:00 +0100",
|
|
||||||
}
|
|
||||||
body, err := json.Marshal(payload)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
app := &App{disp: dispenser, lockserver: lock, cfg: &config.ConfigRec{}}
|
|
||||||
request := httptest.NewRequest(http.MethodPost, "/issuedoorcard", bytes.NewReader(body))
|
|
||||||
request.Header.Set("Content-Type", "application/json")
|
|
||||||
recorder = &responseTrackingRecorder{ResponseRecorder: httptest.NewRecorder()}
|
|
||||||
|
|
||||||
app.issueDoorCard(recorder, request)
|
|
||||||
|
|
||||||
if !dispatchCalled {
|
|
||||||
t.Fatal("next-card preparation was not dispatched")
|
|
||||||
}
|
|
||||||
if recorder.Code != http.StatusOK {
|
|
||||||
t.Fatalf("HTTP status = %d, want %d", recorder.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIssueDoorCardLogsNextCardDispatchFailureAndStillSucceeds(t *testing.T) {
|
|
||||||
var logOutput bytes.Buffer
|
|
||||||
standardLogger := log.StandardLogger()
|
|
||||||
previousOutput := standardLogger.Out
|
|
||||||
standardLogger.SetOutput(&logOutput)
|
|
||||||
t.Cleanup(func() {
|
|
||||||
standardLogger.SetOutput(previousOutput)
|
|
||||||
})
|
|
||||||
|
|
||||||
dispenser := &fakeDoorCardDispenser{beginNextErr: errors.New("dispatch failed")}
|
|
||||||
lock := &fakeDoorCardLockServer{}
|
|
||||||
recorder, _, _ := performIssueDoorCardRequest(t, dispenser, lock)
|
|
||||||
|
|
||||||
if recorder.Code != http.StatusOK {
|
|
||||||
t.Fatalf("HTTP status = %d, want %d", recorder.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
logged := logOutput.String()
|
|
||||||
if !strings.Contains(logged, "dispatch failed") ||
|
|
||||||
!strings.Contains(logged, "Next card preparation dispatch") {
|
|
||||||
t.Fatalf("dispatch failure log = %q", logged)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+123
-83
@@ -5,8 +5,6 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -27,28 +25,18 @@ import (
|
|||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
type doorCardDispenser interface {
|
|
||||||
PrepareCurrentCard(context.Context) (string, error)
|
|
||||||
DeliverCurrentCard(context.Context) (string, error)
|
|
||||||
BeginPrepareNextCard(context.Context) error
|
|
||||||
PrepareNextCard(context.Context) (string, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type App struct {
|
type App struct {
|
||||||
disp doorCardDispenser
|
disp *dispenser.Client
|
||||||
lockserver lockserver.LockServer
|
lockserver lockserver.LockServer
|
||||||
paymentService *paymentsvc.Service
|
paymentService *paymentsvc.Service
|
||||||
creditCallStreamEnabled bool
|
isPayment bool
|
||||||
creditCallTransport http.RoundTripper
|
db *sql.DB
|
||||||
creditCallReceipt func(string)
|
cfg *config.ConfigRec
|
||||||
isPayment bool
|
dbMu sync.Mutex
|
||||||
db *sql.DB
|
cardWellMu sync.RWMutex
|
||||||
cfg *config.ConfigRec
|
cardWellStatus string
|
||||||
dbMu sync.Mutex
|
availabilityMu sync.Mutex
|
||||||
cardWellMu sync.RWMutex
|
availabilityTimers map[string]*time.Timer
|
||||||
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 {
|
||||||
@@ -149,7 +137,7 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
|||||||
theRequest.TransactionType,
|
theRequest.TransactionType,
|
||||||
)
|
)
|
||||||
|
|
||||||
client := app.creditCallClient()
|
client := &http.Client{Timeout: 300 * time.Second}
|
||||||
|
|
||||||
// ---- START TRANSACTION ----
|
// ---- START TRANSACTION ----
|
||||||
|
|
||||||
@@ -170,7 +158,7 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// ---- PRINT RECEIPT ----
|
// ---- PRINT RECEIPT ----
|
||||||
|
|
||||||
app.printCreditCallReceipt(result.CardholderReceipt)
|
printer.PrintReceipt(result.CardholderReceipt)
|
||||||
|
|
||||||
// ---- REDIRECT ----
|
// ---- REDIRECT ----
|
||||||
|
|
||||||
@@ -190,6 +178,8 @@ 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
|
||||||
@@ -251,18 +241,90 @@ func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
theRequest.TransactionType,
|
theRequest.TransactionType,
|
||||||
)
|
)
|
||||||
|
|
||||||
outcome := app.executeCreditCallSale(theRequest, func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
client := &http.Client{Timeout: 300 * time.Second}
|
||||||
var trResult creditcall.TransactionResultXML
|
|
||||||
body, err := callChipDNA(client, types.LinkStartTransaction, body)
|
// ---- START TRANSACTION ----
|
||||||
if err != nil {
|
|
||||||
return trResult, err
|
body, err = callChipDNA(client, types.LinkStartTransaction, body)
|
||||||
|
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]
|
||||||
}
|
}
|
||||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
logging.Error(types.ServiceName, "Preauthorization failed", "Result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||||
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
theResponse.Status = result.Status
|
||||||
|
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]
|
||||||
}
|
}
|
||||||
return trResult, nil
|
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)
|
||||||
writeTransactionResult(w, outcome.HTTPStatus, outcome.legacyResponse())
|
theResponse.Status = result.Status
|
||||||
|
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) {
|
||||||
@@ -314,69 +376,47 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
status, err := app.disp.PrepareCurrentCard(r.Context())
|
// Ensure dispenser ready (card at encoder) BEFORE we attempt encoding.
|
||||||
|
// With queued dispenser ops, this will not clash with polling.
|
||||||
|
status, err := app.disp.DispenserStart(r.Context())
|
||||||
app.SetCardWellStatus(status)
|
app.SetCardWellStatus(status)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||||
if errors.Is(err, dispenser.ErrCardWellEmpty) {
|
|
||||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, dispenser.CardWellEmptyMessage)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Always attempt to finalize after we have moved a card / started an issuance flow.
|
||||||
|
// This guarantees we eject and prepare the next card even on lock failures.
|
||||||
|
finalize := func() {
|
||||||
|
if app.disp == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
status, ferr := app.disp.DispenserFinal(ctx)
|
||||||
|
if ferr != nil {
|
||||||
|
logging.Error(types.ServiceName, ferr.Error(), "Dispenser final error", string(op), "", "", 0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
app.SetCardWellStatus(status)
|
||||||
|
}
|
||||||
|
|
||||||
// doorReq.RoomField = "104"
|
// doorReq.RoomField = "104"
|
||||||
// build lock server command
|
// build lock server command
|
||||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||||
|
|
||||||
// lock server sequence
|
// lock server sequence
|
||||||
encodingErr := app.lockserver.LockSequence()
|
if err := app.lockserver.LockSequence(); err != nil {
|
||||||
if encodingErr != nil {
|
logging.Error(types.ServiceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||||
logging.Error(types.ServiceName, encodingErr.Error(), "Key encoding", string(op), "", "", 0)
|
finalize()
|
||||||
}
|
errorhandlers.WriteError(w, http.StatusBadGateway, err.Error())
|
||||||
|
|
||||||
// Once encoding has started, finish the physical dispenser sequence even if
|
|
||||||
// the HTTP client disconnects. Finalization remains bounded by one shared timeout.
|
|
||||||
finalizeCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
status, deliveryErr := app.disp.DeliverCurrentCard(finalizeCtx)
|
|
||||||
app.SetCardWellStatus(status)
|
|
||||||
if deliveryErr != nil {
|
|
||||||
if encodingErr != nil {
|
|
||||||
recoveryErr := fmt.Errorf("key encoding failed: %v; dispenser recovery failed: %w", encodingErr, deliveryErr)
|
|
||||||
logging.Error(types.ServiceName, recoveryErr.Error(), "Dispenser recovery", string(op), "", "", 0)
|
|
||||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispenser recovery failed; another encoding attempt is not safe")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
logging.Error(types.ServiceName, deliveryErr.Error(), "Card delivery", string(op), "", "", 0)
|
|
||||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Card delivery could not be confirmed")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if encodingErr != nil {
|
// final dispenser steps
|
||||||
status, preparationErr := app.disp.PrepareNextCard(finalizeCtx)
|
finalize()
|
||||||
app.SetCardWellStatus(status)
|
|
||||||
if preparationErr != nil {
|
|
||||||
recoveryErr := fmt.Errorf("key encoding failed: %v; dispenser recovery failed: %w", encodingErr, preparationErr)
|
|
||||||
logging.Error(types.ServiceName, recoveryErr.Error(), "Dispenser recovery", string(op), "", "", 0)
|
|
||||||
if errors.Is(preparationErr, dispenser.ErrCardWellEmpty) {
|
|
||||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, dispenser.CardWellEmptyMessage)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispenser recovery failed; another encoding attempt is not safe")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
errorhandlers.WriteError(w, http.StatusBadGateway, encodingErr.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if preparationErr := app.disp.BeginPrepareNextCard(finalizeCtx); preparationErr != nil {
|
|
||||||
logging.Error(types.ServiceName, preparationErr.Error(), "Next card preparation dispatch", string(op), "", "", 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
theResponse.Code = http.StatusOK
|
theResponse.Code = http.StatusOK
|
||||||
theResponse.Message = "Card issued successfully"
|
theResponse.Message = "Card issued successfully"
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
@@ -29,22 +28,9 @@ type SalePaymentRequest struct {
|
|||||||
Currency string `json:"currency,omitempty"`
|
Currency string `json:"currency,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type paymentStreamMessage struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
Code string `json:"code,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")
|
||||||
|
var response = cmstypes.ResponseRec{
|
||||||
if app.creditCallStreamEnabled {
|
|
||||||
app.streamCreditCallSale(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
response := cmstypes.ResponseRec{
|
|
||||||
Status: cmstypes.StatusRec{
|
Status: cmstypes.StatusRec{
|
||||||
Code: http.StatusInternalServerError,
|
Code: http.StatusInternalServerError,
|
||||||
Message: http.StatusText(http.StatusInternalServerError),
|
Message: http.StatusText(http.StatusInternalServerError),
|
||||||
@@ -63,40 +49,22 @@ func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeTransactionResult(w, http.StatusMethodNotAllowed, response)
|
writeTransactionResult(w, http.StatusMethodNotAllowed, response)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if app.paymentService == nil {
|
if app.paymentService == nil {
|
||||||
mail.SendEmailOnError(
|
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Service Not Configured", "Payment service is not configured; cannot process payment requests")
|
||||||
app.cfg.Hotel,
|
|
||||||
app.cfg.Kiosk,
|
|
||||||
"Payment Service Not Configured",
|
|
||||||
"Payment service is not configured; cannot process payment requests",
|
|
||||||
)
|
|
||||||
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "Payment service is not configured")
|
response.Data = buildPaymentFailureURL(types.ResultError, "Payment service is not configured")
|
||||||
writeTransactionResult(w, http.StatusInternalServerError, response)
|
writeTransactionResult(w, http.StatusInternalServerError, response)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "Content-Type must be application/json")
|
response.Data = buildPaymentFailureURL(types.ResultError, "Content-Type must be application/json")
|
||||||
writeTransactionResult(w, http.StatusUnsupportedMediaType, response)
|
writeTransactionResult(w, http.StatusUnsupportedMediaType, response)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
|
|
||||||
var req SalePaymentRequest
|
var req SalePaymentRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
logging.Error(
|
logging.Error(types.ServiceName, err.Error(), "ReadJSON", string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||||
types.ServiceName,
|
|
||||||
err.Error(),
|
|
||||||
"ReadJSON",
|
|
||||||
string(op),
|
|
||||||
"",
|
|
||||||
app.cfg.Hotel,
|
|
||||||
app.cfg.Kiosk,
|
|
||||||
)
|
|
||||||
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "invalid JSON payload: "+err.Error())
|
response.Data = buildPaymentFailureURL(types.ResultError, "invalid JSON payload: "+err.Error())
|
||||||
writeTransactionResult(w, http.StatusBadRequest, response)
|
writeTransactionResult(w, http.StatusBadRequest, response)
|
||||||
return
|
return
|
||||||
@@ -107,90 +75,31 @@ func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeTransactionResult(w, http.StatusBadRequest, response)
|
writeTransactionResult(w, http.StatusBadRequest, response)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Currency == "" {
|
if req.Currency == "" {
|
||||||
req.Currency = "GBP"
|
req.Currency = "GBP"
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Reference == "" {
|
if req.Reference == "" {
|
||||||
req.Reference = req.ConfirmNo
|
req.Reference = req.ConfirmNo
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Reference == "" {
|
if req.Reference == "" {
|
||||||
req.Reference = uuid.NewString()
|
req.Reference = uuid.NewString()
|
||||||
}
|
}
|
||||||
|
|
||||||
requestID := buildPaymentRequestID(req.Reference)
|
requestID := buildPaymentRequestID(req.Reference)
|
||||||
|
|
||||||
timeoutSeconds := app.cfg.TimeoutSeconds
|
timeoutSeconds := app.cfg.TimeoutSeconds
|
||||||
if timeoutSeconds <= 0 {
|
if timeoutSeconds <= 0 {
|
||||||
timeoutSeconds = 300
|
timeoutSeconds = 300
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(
|
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(timeoutSeconds)*time.Second)
|
||||||
r.Context(),
|
|
||||||
time.Duration(timeoutSeconds)*time.Second,
|
|
||||||
)
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
flusher, ok := w.(http.Flusher)
|
result, err := app.paymentService.Sale(ctx, paymentsvc.SaleRequest{
|
||||||
if !ok {
|
RequestID: requestID,
|
||||||
response.Data = buildPaymentFailureURL(
|
Reference: req.Reference,
|
||||||
types.ResultError,
|
Amount: req.Amount,
|
||||||
"Streaming payment updates are not supported",
|
Currency: req.Currency,
|
||||||
)
|
})
|
||||||
writeTransactionResult(w, http.StatusInternalServerError, response)
|
|
||||||
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")
|
|
||||||
|
|
||||||
encoder := json.NewEncoder(w)
|
|
||||||
|
|
||||||
var streamMu sync.Mutex
|
|
||||||
streamStarted := false
|
|
||||||
streamFailed := false
|
|
||||||
|
|
||||||
sendStreamMessage := func(message paymentStreamMessage) {
|
|
||||||
streamMu.Lock()
|
|
||||||
defer streamMu.Unlock()
|
|
||||||
|
|
||||||
if streamFailed {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := encoder.Encode(message); err != nil {
|
|
||||||
streamFailed = true
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
streamStarted = true
|
|
||||||
flusher.Flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
onStatus := func(update paymentsvc.StatusUpdate) {
|
|
||||||
if update.Code == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "status",
|
|
||||||
Code: update.Code,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := app.paymentService.Sale(
|
|
||||||
ctx,
|
|
||||||
paymentsvc.SaleRequest{
|
|
||||||
RequestID: requestID,
|
|
||||||
Reference: req.Reference,
|
|
||||||
Amount: req.Amount,
|
|
||||||
Currency: req.Currency,
|
|
||||||
},
|
|
||||||
onStatus,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
status := http.StatusBadGateway
|
status := http.StatusBadGateway
|
||||||
@@ -198,51 +107,20 @@ func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
status = http.StatusConflict
|
status = http.StatusConflict
|
||||||
}
|
}
|
||||||
|
|
||||||
logging.Error(
|
logging.Error(types.ServiceName, err.Error(), "Payment provider error", string(op), req.Reference, app.cfg.Hotel, app.cfg.Kiosk)
|
||||||
types.ServiceName,
|
|
||||||
err.Error(),
|
|
||||||
"Payment provider error",
|
|
||||||
string(op),
|
|
||||||
req.Reference,
|
|
||||||
app.cfg.Hotel,
|
|
||||||
app.cfg.Kiosk,
|
|
||||||
)
|
|
||||||
|
|
||||||
response.Status.Code = status
|
response.Status.Code = status
|
||||||
response.Status.Message = http.StatusText(status)
|
response.Status.Message = http.StatusText(status)
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, err.Error())
|
response.Data = buildPaymentFailureURL(types.ResultError, err.Error())
|
||||||
|
writeTransactionResult(w, status, response)
|
||||||
if !streamStarted {
|
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
||||||
writeTransactionResult(w, status, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if result == nil {
|
if result == nil {
|
||||||
response.Status.Code = http.StatusBadGateway
|
response.Status.Code = http.StatusBadGateway
|
||||||
response.Status.Message = "Empty payment result"
|
response.Status.Message = "Empty payment result"
|
||||||
response.Data = buildPaymentFailureURL(
|
response.Data = buildPaymentFailureURL(types.ResultError, "Payment provider returned an empty result")
|
||||||
types.ResultError,
|
writeTransactionResult(w, http.StatusBadGateway, response)
|
||||||
"Payment provider returned an empty result",
|
|
||||||
)
|
|
||||||
|
|
||||||
if !streamStarted {
|
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
||||||
writeTransactionResult(w, http.StatusBadGateway, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,14 +128,10 @@ func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
if result.Success && strings.EqualFold(result.Status, "APPROVED") {
|
if result.Success && strings.EqualFold(result.Status, "APPROVED") {
|
||||||
printer.PrintSaleReceipt(result.CustomerReceipt)
|
printer.PrintSaleReceipt(result.CustomerReceipt)
|
||||||
|
response.Status.Code = http.StatusOK
|
||||||
response.Status.Message = result.Message
|
response.Status.Message = result.Message
|
||||||
response.Data = buildPaymentSuccessURL(result)
|
response.Data = buildPaymentSuccessURL(result)
|
||||||
|
writeTransactionResult(w, http.StatusOK, response)
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,14 +145,9 @@ func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
log.Printf("Transaction failed: %s", description)
|
log.Printf("Transaction failed: %s", description)
|
||||||
printer.PrintSaleReceipt(result.CustomerReceipt)
|
printer.PrintSaleReceipt(result.CustomerReceipt)
|
||||||
|
|
||||||
response.Status.Message = "Payment unsuccessful"
|
response.Status.Message = "Payment unsuccessful"
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, description)
|
response.Data = buildPaymentFailureURL(types.ResultError, description)
|
||||||
|
writeTransactionResult(w, http.StatusOK, response)
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildPaymentRequestID(reference string) string {
|
func buildPaymentRequestID(reference string) string {
|
||||||
@@ -304,16 +173,16 @@ func setPaymentCORS(w http.ResponseWriter) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func buildPaymentSuccessURL(result *paymentsvc.Result) string {
|
func buildPaymentSuccessURL(result *paymentsvc.Result) string {
|
||||||
// txnReference := result.ReferenceNumber
|
txnReference := result.ReferenceNumber
|
||||||
// if txnReference == "" {
|
if txnReference == "" {
|
||||||
// txnReference = result.TransactionID
|
txnReference = result.TransactionID
|
||||||
// }
|
}
|
||||||
|
|
||||||
q := url.Values{}
|
q := url.Values{}
|
||||||
q.Set("CardNumber", hex.EncodeToString([]byte(result.CardNumber)))
|
q.Set("CardNumber", hex.EncodeToString([]byte(result.CardNumber)))
|
||||||
q.Set("CardType", hex.EncodeToString([]byte(result.CardType)))
|
q.Set("CardType", hex.EncodeToString([]byte(result.CardType)))
|
||||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result.ExpiryDate)))
|
q.Set("ExpiryDate", hex.EncodeToString([]byte(result.ExpiryDate)))
|
||||||
q.Set("TxnReference", result.RequestID)
|
q.Set("TxnReference", txnReference)
|
||||||
q.Set("CardHash", hex.EncodeToString([]byte(result.CardHash)))
|
q.Set("CardHash", hex.EncodeToString([]byte(result.CardHash)))
|
||||||
q.Set("CardReference", hex.EncodeToString([]byte(result.CardReference)))
|
q.Set("CardReference", hex.EncodeToString([]byte(result.CardReference)))
|
||||||
|
|
||||||
|
|||||||
@@ -1,162 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
|
||||||
)
|
|
||||||
|
|
||||||
type paymentProviderFunc func(
|
|
||||||
context.Context,
|
|
||||||
paymentsvc.SaleRequest,
|
|
||||||
paymentsvc.StatusHandler,
|
|
||||||
) (*paymentsvc.Result, error)
|
|
||||||
|
|
||||||
func (f paymentProviderFunc) Sale(
|
|
||||||
ctx context.Context,
|
|
||||||
request paymentsvc.SaleRequest,
|
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
) (*paymentsvc.Result, error) {
|
|
||||||
return f(ctx, request, onStatus)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSalePaymentStreamsTerminalUnavailableAsAuthoritativeUnsuccessfulResult(t *testing.T) {
|
|
||||||
provider := paymentProviderFunc(func(
|
|
||||||
_ context.Context,
|
|
||||||
request paymentsvc.SaleRequest,
|
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
) (*paymentsvc.Result, error) {
|
|
||||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
|
||||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.TerminalUnavailable})
|
|
||||||
return &paymentsvc.Result{
|
|
||||||
RequestID: request.RequestID,
|
|
||||||
Operation: "SALE",
|
|
||||||
Status: "TERMINAL_UNAVAILABLE",
|
|
||||||
ErrorMessage: "Payment terminal is unavailable",
|
|
||||||
Amount: request.Amount,
|
|
||||||
Currency: request.Currency,
|
|
||||||
DeviceUsed: "terminal-1",
|
|
||||||
DeviceType: "Dojo Terminal",
|
|
||||||
}, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
recorder := performSalePaymentRequest(t, provider)
|
|
||||||
if recorder.Code != http.StatusOK {
|
|
||||||
t.Fatalf("outer status = %d, want %d", recorder.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
messages := decodePaymentStream(t, recorder.Body)
|
|
||||||
if len(messages) != 3 {
|
|
||||||
t.Fatalf("stream messages = %#v, want two statuses and one result", messages)
|
|
||||||
}
|
|
||||||
if messages[0].Type != "status" || messages[0].Code != paymentstatus.Starting ||
|
|
||||||
messages[1].Type != "status" || messages[1].Code != paymentstatus.TerminalUnavailable {
|
|
||||||
t.Fatalf("status frames = %#v", messages[:2])
|
|
||||||
}
|
|
||||||
final := messages[2]
|
|
||||||
if final.Type != "result" || final.Response == nil {
|
|
||||||
t.Fatalf("final frame = %#v", final)
|
|
||||||
}
|
|
||||||
if final.Response.Status.Code != http.StatusOK {
|
|
||||||
t.Fatalf("nested status = %d, want %d", final.Response.Status.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
resultURL, err := url.Parse(final.Response.Data)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if resultURL.Path != types.CheckinUnsuccessfulEndpoint {
|
|
||||||
t.Fatalf("result path = %q, want %q", resultURL.Path, types.CheckinUnsuccessfulEndpoint)
|
|
||||||
}
|
|
||||||
if got := resultURL.Query().Get("Description"); got != "Payment terminal is unavailable" {
|
|
||||||
t.Fatalf("Description = %q", got)
|
|
||||||
}
|
|
||||||
|
|
||||||
body := recorder.Body.String()
|
|
||||||
for _, forbidden := range []string{
|
|
||||||
"Dojo returned HTTP 409",
|
|
||||||
"offline or currently in use",
|
|
||||||
"traceId",
|
|
||||||
"docs.dojo.tech",
|
|
||||||
} {
|
|
||||||
if strings.Contains(body, forbidden) {
|
|
||||||
t.Fatalf("stream exposed %q: %s", forbidden, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSalePaymentRetainsNestedBadGatewayForProviderErrorsAfterStreamingStarts(t *testing.T) {
|
|
||||||
provider := paymentProviderFunc(func(
|
|
||||||
_ context.Context,
|
|
||||||
_ paymentsvc.SaleRequest,
|
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
) (*paymentsvc.Result, error) {
|
|
||||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
|
||||||
return nil, errors.New("provider failed")
|
|
||||||
})
|
|
||||||
|
|
||||||
recorder := performSalePaymentRequest(t, provider)
|
|
||||||
if recorder.Code != http.StatusOK {
|
|
||||||
t.Fatalf("outer status = %d, want streaming status %d", recorder.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
messages := decodePaymentStream(t, recorder.Body)
|
|
||||||
if len(messages) != 2 || messages[1].Type != "result" || messages[1].Response == nil {
|
|
||||||
t.Fatalf("stream messages = %#v", messages)
|
|
||||||
}
|
|
||||||
if messages[1].Response.Status.Code != http.StatusBadGateway {
|
|
||||||
t.Fatalf("nested status = %d, want %d", messages[1].Response.Status.Code, http.StatusBadGateway)
|
|
||||||
}
|
|
||||||
resultURL, err := url.Parse(messages[1].Response.Data)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if resultURL.Path != types.CheckinUnsuccessfulEndpoint {
|
|
||||||
t.Fatalf("result path = %q, want %q", resultURL.Path, types.CheckinUnsuccessfulEndpoint)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func performSalePaymentRequest(t *testing.T, provider paymentsvc.Provider) *httptest.ResponseRecorder {
|
|
||||||
t.Helper()
|
|
||||||
app := &App{
|
|
||||||
paymentService: paymentsvc.NewService(provider),
|
|
||||||
cfg: &config.ConfigRec{
|
|
||||||
Hotel: "HOTEL",
|
|
||||||
Kiosk: 7,
|
|
||||||
TimeoutSeconds: 5,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
request := httptest.NewRequest(
|
|
||||||
http.MethodPost,
|
|
||||||
"/api/payment/sale",
|
|
||||||
strings.NewReader(`{"reference":"BOOKING-123","amount":10852,"currency":"GBP"}`),
|
|
||||||
)
|
|
||||||
request.Header.Set("Content-Type", "application/json")
|
|
||||||
recorder := httptest.NewRecorder()
|
|
||||||
app.salePayment(recorder, request)
|
|
||||||
return recorder
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodePaymentStream(t *testing.T, body io.Reader) []paymentStreamMessage {
|
|
||||||
t.Helper()
|
|
||||||
decoder := json.NewDecoder(body)
|
|
||||||
var messages []paymentStreamMessage
|
|
||||||
for {
|
|
||||||
var message paymentStreamMessage
|
|
||||||
if err := decoder.Decode(&message); err != nil {
|
|
||||||
if errors.Is(err, io.EOF) {
|
|
||||||
return messages
|
|
||||||
}
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
messages = append(messages, message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9,10 +9,10 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
"gitea.futuresens.co.uk/futuresens/logging"
|
"gitea.futuresens.co.uk/futuresens/logging"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
@@ -59,7 +59,7 @@ func (app *App) testIssueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// Ensure dispenser ready (card at encoder) BEFORE we attempt encoding.
|
// Ensure dispenser ready (card at encoder) BEFORE we attempt encoding.
|
||||||
// With queued dispenser ops, this will not clash with polling.
|
// With queued dispenser ops, this will not clash with polling.
|
||||||
status, err := app.disp.PrepareCurrentCard(r.Context())
|
status, err := app.disp.DispenserStart(r.Context())
|
||||||
app.SetCardWellStatus(status)
|
app.SetCardWellStatus(status)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||||
|
|||||||
+21
-288
@@ -10,9 +10,7 @@ import (
|
|||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
@@ -33,7 +31,7 @@ func NewClient(url, apiKey string, timeoutSeconds int) *Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) Sale(ctx context.Context, req paymentsvc.SaleRequest, onStatus paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
func (c *Client) Sale(ctx context.Context, req paymentsvc.SaleRequest) (*paymentsvc.Result, error) {
|
||||||
if req.Currency == "" {
|
if req.Currency == "" {
|
||||||
req.Currency = "GBP"
|
req.Currency = "GBP"
|
||||||
}
|
}
|
||||||
@@ -46,12 +44,10 @@ func (c *Client) Sale(ctx context.Context, req paymentsvc.SaleRequest, onStatus
|
|||||||
TimeoutSeconds: c.TimeoutSeconds,
|
TimeoutSeconds: c.TimeoutSeconds,
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.doPayment(ctx, payBridgeReq, onStatus)
|
return c.doPayment(ctx, payBridgeReq)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
func (c *Client) doPayment(ctx context.Context, req PaymentRequest) (*paymentsvc.Result, error) {
|
||||||
emitStatus(onStatus, paymentstatus.Starting)
|
|
||||||
|
|
||||||
connectURL, err := c.connectURL()
|
connectURL, err := c.connectURL()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -79,9 +75,6 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info("PayBridge authentication successful")
|
|
||||||
emitStatus(onStatus, paymentstatus.Started)
|
|
||||||
|
|
||||||
if err := ws.WriteJSON(Envelope{
|
if err := ws.WriteJSON(Envelope{
|
||||||
Type: types.MesTypePaymentRequest,
|
Type: types.MesTypePaymentRequest,
|
||||||
JWT: jwt,
|
JWT: jwt,
|
||||||
@@ -91,109 +84,36 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
return nil, fmt.Errorf("send PayBridge payment_request: %w", err)
|
return nil, fmt.Errorf("send PayBridge payment_request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"requestId": req.RequestID,
|
|
||||||
"operation": req.Operation,
|
|
||||||
"amount": req.Amount,
|
|
||||||
"currency": req.Currency,
|
|
||||||
}).Info("PayBridge payment request sent")
|
|
||||||
|
|
||||||
emitStatus(onStatus, paymentstatus.RequestSent)
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
_, raw, err := ws.ReadMessage()
|
_, raw, err := ws.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
return nil, ctx.Err()
|
return nil, ctx.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, fmt.Errorf("read PayBridge message: %w", err)
|
return nil, fmt.Errorf("read PayBridge message: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var head struct {
|
var head struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := json.Unmarshal(raw, &head); err != nil {
|
if err := json.Unmarshal(raw, &head); err != nil {
|
||||||
return nil, fmt.Errorf("decode PayBridge message header: %w", err)
|
return nil, fmt.Errorf("decode PayBridge message header: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
messageType := strings.ToLower(head.Type)
|
switch strings.ToLower(head.Type) {
|
||||||
|
|
||||||
switch messageType {
|
|
||||||
case types.MesTypePaymentStatusUpdate:
|
|
||||||
var update StatusUpdateEnvelope
|
|
||||||
if err := json.Unmarshal(raw, &update); err != nil {
|
|
||||||
return nil, fmt.Errorf("decode payment_status_update: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"status": update.Data.Status,
|
|
||||||
"code": update.Data.Code,
|
|
||||||
}).Info("PayBridge status update")
|
|
||||||
|
|
||||||
statusCode, known := mapPayBridgeStatus(
|
|
||||||
update.Data.Status,
|
|
||||||
update.Data.Code,
|
|
||||||
)
|
|
||||||
|
|
||||||
if !known {
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"status": update.Data.Status,
|
|
||||||
"code": update.Data.Code,
|
|
||||||
}).Warn("Unknown PayBridge status update")
|
|
||||||
}
|
|
||||||
|
|
||||||
emitStatus(onStatus, statusCode)
|
|
||||||
|
|
||||||
case types.MesTypePaymentAccepted:
|
|
||||||
log.Info("PayBridge payment request accepted")
|
|
||||||
emitStatus(onStatus, paymentstatus.Accepted)
|
|
||||||
|
|
||||||
case types.MesTypePaymentResult:
|
case types.MesTypePaymentResult:
|
||||||
var result PaymentResultEnvelope
|
var result PaymentResultEnvelope
|
||||||
// log.Println("PayBridge payment result raw:", string(raw))
|
|
||||||
if err := json.Unmarshal(raw, &result); err != nil {
|
if err := json.Unmarshal(raw, &result); err != nil {
|
||||||
return nil, fmt.Errorf("decode payment_result: %w", err)
|
return nil, fmt.Errorf("decode payment_result: %w", err)
|
||||||
}
|
}
|
||||||
|
return mapPaymentResult(result), nil
|
||||||
mapped := mapPaymentResult(result)
|
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"requestId": mapped.RequestID,
|
|
||||||
"transactionId": mapped.TransactionID,
|
|
||||||
"status": mapped.Status,
|
|
||||||
"success": mapped.Success,
|
|
||||||
}).Info("PayBridge payment result received")
|
|
||||||
|
|
||||||
emitStatus(
|
|
||||||
onStatus,
|
|
||||||
mapPayBridgeFinalStatus(mapped.Status, mapped.Success),
|
|
||||||
)
|
|
||||||
|
|
||||||
return mapped, nil
|
|
||||||
|
|
||||||
case types.MesTypePaymentError:
|
case types.MesTypePaymentError:
|
||||||
var paymentErr PaymentErrorEnvelope
|
var paymentErr PaymentErrorEnvelope
|
||||||
if err := json.Unmarshal(raw, &paymentErr); err != nil {
|
if err := json.Unmarshal(raw, &paymentErr); err != nil {
|
||||||
return nil, fmt.Errorf("decode payment_error: %w", err)
|
return nil, fmt.Errorf("decode payment_error: %w", err)
|
||||||
}
|
}
|
||||||
|
return mapPaymentError(req, paymentErr), nil
|
||||||
mapped := mapPaymentError(req, paymentErr)
|
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"requestId": mapped.RequestID,
|
|
||||||
"transactionId": mapped.TransactionID,
|
|
||||||
"status": mapped.Status,
|
|
||||||
"error": mapped.ErrorMessage,
|
|
||||||
}).Warn("PayBridge payment error received")
|
|
||||||
|
|
||||||
emitStatus(
|
|
||||||
onStatus,
|
|
||||||
mapPayBridgeFinalStatus(mapped.Status, false),
|
|
||||||
)
|
|
||||||
|
|
||||||
return mapped, nil
|
|
||||||
|
|
||||||
case types.ResultError:
|
case types.ResultError:
|
||||||
var genericErr struct {
|
var genericErr struct {
|
||||||
@@ -202,47 +122,20 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
} `json:"error"`
|
} `json:"error"`
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := json.Unmarshal(raw, &genericErr); err != nil {
|
if err := json.Unmarshal(raw, &genericErr); err != nil {
|
||||||
return nil, fmt.Errorf(
|
return nil, fmt.Errorf("%w: %s", ErrUnexpectedMessage, string(raw))
|
||||||
"%w: %s",
|
|
||||||
ErrUnexpectedMessage,
|
|
||||||
string(raw),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"code": genericErr.Error.Code,
|
|
||||||
"message": genericErr.Error.Message,
|
|
||||||
}).Error("PayBridge error message received")
|
|
||||||
|
|
||||||
emitStatus(onStatus, paymentstatus.Error)
|
|
||||||
|
|
||||||
if genericErr.Error.Message != "" {
|
if genericErr.Error.Message != "" {
|
||||||
return nil, fmt.Errorf(
|
return nil, fmt.Errorf("%w: %s: %s", ErrUnexpectedMessage, genericErr.Error.Code, genericErr.Error.Message)
|
||||||
"%w: %s: %s",
|
|
||||||
ErrUnexpectedMessage,
|
|
||||||
genericErr.Error.Code,
|
|
||||||
genericErr.Error.Message,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrUnexpectedMessage, string(raw))
|
||||||
|
|
||||||
return nil, fmt.Errorf(
|
case types.MesTypePaymentStatusUpdate, types.MesTypePaymentAccepted, types.MesTypeAuthSuccess:
|
||||||
"%w: %s",
|
// Intermediate message. Keep waiting for payment_result or payment_error.
|
||||||
ErrUnexpectedMessage,
|
|
||||||
string(raw),
|
|
||||||
)
|
|
||||||
|
|
||||||
case types.MesTypeAuthSuccess:
|
|
||||||
log.Info("Additional PayBridge auth_success message received")
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
log.WithField(
|
// PayBridge may introduce additional intermediate message types.
|
||||||
"messageType",
|
// Ignore them and continue waiting for the final result.
|
||||||
head.Type,
|
|
||||||
).Warn("Unknown PayBridge intermediate message type")
|
|
||||||
|
|
||||||
emitStatus(onStatus, paymentstatus.Processing)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -250,10 +143,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
func (c *Client) connectURL() (string, error) {
|
func (c *Client) connectURL() (string, error) {
|
||||||
u, err := url.Parse(c.URL)
|
u, err := url.Parse(c.URL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf(
|
return "", fmt.Errorf("parse PayBridge WebSocket URL: %w", err)
|
||||||
"parse PayBridge WebSocket URL: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
q := u.Query()
|
q := u.Query()
|
||||||
@@ -264,186 +154,29 @@ func (c *Client) connectURL() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) readAuthSuccess(ws *websocket.Conn) (string, error) {
|
func (c *Client) readAuthSuccess(ws *websocket.Conn) (string, error) {
|
||||||
if err := ws.SetReadDeadline(
|
if err := ws.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {
|
||||||
time.Now().Add(10 * time.Second),
|
return "", fmt.Errorf("%w: set auth read deadline: %v", ErrAuthFailed, err)
|
||||||
); err != nil {
|
|
||||||
return "", fmt.Errorf(
|
|
||||||
"%w: set auth read deadline: %v",
|
|
||||||
ErrAuthFailed,
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
defer ws.SetReadDeadline(time.Time{})
|
defer ws.SetReadDeadline(time.Time{})
|
||||||
|
|
||||||
_, raw, err := ws.ReadMessage()
|
_, raw, err := ws.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf(
|
return "", fmt.Errorf("%w: read auth_success: %v", ErrAuthFailed, err)
|
||||||
"%w: read auth_success: %v",
|
|
||||||
ErrAuthFailed,
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var auth struct {
|
var auth struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
JWT string `json:"jwt"`
|
JWT string `json:"jwt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := json.Unmarshal(raw, &auth); err != nil {
|
if err := json.Unmarshal(raw, &auth); err != nil {
|
||||||
return "", fmt.Errorf(
|
return "", fmt.Errorf("%w: decode auth_success: %v", ErrAuthFailed, err)
|
||||||
"%w: decode auth_success: %v",
|
|
||||||
ErrAuthFailed,
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
if !strings.EqualFold(auth.Type, types.MesTypeAuthSuccess) {
|
||||||
if !strings.EqualFold(
|
return "", fmt.Errorf("%w: expected auth_success, got %s: %s", ErrAuthFailed, auth.Type, string(raw))
|
||||||
auth.Type,
|
|
||||||
types.MesTypeAuthSuccess,
|
|
||||||
) {
|
|
||||||
return "", fmt.Errorf(
|
|
||||||
"%w: expected auth_success, got %s: %s",
|
|
||||||
ErrAuthFailed,
|
|
||||||
auth.Type,
|
|
||||||
string(raw),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if auth.JWT == "" {
|
if auth.JWT == "" {
|
||||||
return "", fmt.Errorf(
|
return "", fmt.Errorf("%w: auth_success did not contain jwt", ErrAuthFailed)
|
||||||
"%w: auth_success did not contain jwt",
|
|
||||||
ErrAuthFailed,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return auth.JWT, nil
|
return auth.JWT, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func emitStatus(
|
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
code string,
|
|
||||||
) {
|
|
||||||
if onStatus == nil || code == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
onStatus(paymentsvc.StatusUpdate{
|
|
||||||
Code: code,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapPayBridgeStatus(
|
|
||||||
status string,
|
|
||||||
code string,
|
|
||||||
) (string, bool) {
|
|
||||||
normalizedStatus := strings.ToLower(
|
|
||||||
strings.TrimSpace(status),
|
|
||||||
)
|
|
||||||
|
|
||||||
switch normalizedStatus {
|
|
||||||
case payBridgeMessageInsertOrSwipeCard,
|
|
||||||
payBridgeMessageInsertSwipeOrPresentCard:
|
|
||||||
return paymentstatus.PresentCard, true
|
|
||||||
|
|
||||||
case payBridgeMessageInsertCard:
|
|
||||||
return paymentstatus.InsertCard, true
|
|
||||||
|
|
||||||
case payBridgeMessagePleaseWait:
|
|
||||||
return paymentstatus.PleaseWait, true
|
|
||||||
|
|
||||||
case payBridgeMessageDoNotRemoveCard:
|
|
||||||
return paymentstatus.DoNotRemoveCard, true
|
|
||||||
|
|
||||||
case payBridgeMessageTryAnotherInterface:
|
|
||||||
return paymentstatus.TryAnotherInterface, true
|
|
||||||
|
|
||||||
case payBridgeMessagePIN:
|
|
||||||
return paymentstatus.EnterPIN, true
|
|
||||||
|
|
||||||
case payBridgeMessagePINAgain:
|
|
||||||
return paymentstatus.EnterPINAgain, true
|
|
||||||
|
|
||||||
case payBridgeMessageTransactionCancelled:
|
|
||||||
return paymentstatus.Cancelled, true
|
|
||||||
|
|
||||||
case payBridgeMessageProcessing:
|
|
||||||
return paymentstatus.Processing, true
|
|
||||||
|
|
||||||
case payBridgeMessageApproved:
|
|
||||||
// Это ещё промежуточный статус.
|
|
||||||
// Финальный успех определяется только по payment_result.
|
|
||||||
return paymentstatus.Authorized, true
|
|
||||||
|
|
||||||
case payBridgeMessageDeclined:
|
|
||||||
return paymentstatus.Declined, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback по фактически обнаруженным кодам терминала.
|
|
||||||
switch strings.TrimSpace(code) {
|
|
||||||
case payBridgeCodeInsertCard:
|
|
||||||
return paymentstatus.InsertCard, true
|
|
||||||
|
|
||||||
case payBridgeCodeEnterPIN:
|
|
||||||
return paymentstatus.EnterPIN, true
|
|
||||||
|
|
||||||
case payBridgeCodeCancelled:
|
|
||||||
return paymentstatus.Cancelled, true
|
|
||||||
|
|
||||||
case payBridgeCodePleaseWait:
|
|
||||||
return paymentstatus.PleaseWait, true
|
|
||||||
|
|
||||||
case payBridgeCodePresentCard, payBridgeCodePresentCardAlternate:
|
|
||||||
return paymentstatus.PresentCard, true
|
|
||||||
|
|
||||||
case payBridgeCodeEnterPINAgain:
|
|
||||||
return paymentstatus.EnterPINAgain, true
|
|
||||||
|
|
||||||
case payBridgeCodeTryAnotherInterface:
|
|
||||||
return paymentstatus.TryAnotherInterface, true
|
|
||||||
|
|
||||||
case payBridgeCodeDoNotRemoveCard:
|
|
||||||
return paymentstatus.DoNotRemoveCard, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Пока назначение кодов 200, 201, 205 и 210 неизвестно.
|
|
||||||
// Они останутся в логах, но на экране будет общий статус.
|
|
||||||
return paymentstatus.Processing, false
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapPayBridgeFinalStatus(
|
|
||||||
status string,
|
|
||||||
success bool,
|
|
||||||
) string {
|
|
||||||
if success && strings.EqualFold(status, payBridgeFinalStatusApproved) {
|
|
||||||
return paymentstatus.Approved
|
|
||||||
}
|
|
||||||
|
|
||||||
switch strings.ToUpper(status) {
|
|
||||||
case payBridgeFinalStatusDeclined:
|
|
||||||
return paymentstatus.Declined
|
|
||||||
|
|
||||||
case payBridgeFinalStatusCancelled:
|
|
||||||
return paymentstatus.Cancelled
|
|
||||||
|
|
||||||
case payBridgeFinalStatusTimeout:
|
|
||||||
return paymentstatus.Timeout
|
|
||||||
|
|
||||||
case payBridgeFinalStatusVoided:
|
|
||||||
return paymentstatus.Voided
|
|
||||||
|
|
||||||
case payBridgeFinalStatusVoidedDailyLimitExceeded:
|
|
||||||
return paymentstatus.DailyLimitExceeded
|
|
||||||
|
|
||||||
case payBridgeFinalStatusDailyLimitVoidFailed:
|
|
||||||
return paymentstatus.VoidFailed
|
|
||||||
|
|
||||||
case payBridgeFinalStatusDailyLimitValidationError:
|
|
||||||
return paymentstatus.LimitValidationError
|
|
||||||
|
|
||||||
case payBridgeFinalStatusError, payBridgeFinalStatusFailed:
|
|
||||||
return paymentstatus.Error
|
|
||||||
|
|
||||||
default:
|
|
||||||
return paymentstatus.Error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
package paybridge
|
|
||||||
|
|
||||||
const (
|
|
||||||
payBridgeFinalStatusApproved = "APPROVED"
|
|
||||||
payBridgeFinalStatusDeclined = "DECLINED"
|
|
||||||
payBridgeFinalStatusCancelled = "CANCELLED"
|
|
||||||
payBridgeFinalStatusTimeout = "TIMEOUT"
|
|
||||||
payBridgeFinalStatusVoided = "VOIDED"
|
|
||||||
payBridgeFinalStatusVoidedDailyLimitExceeded = "VOIDED_DAILY_LIMIT_EXCEEDED"
|
|
||||||
payBridgeFinalStatusDailyLimitVoidFailed = "DAILY_LIMIT_EXCEEDED_VOID_FAILED"
|
|
||||||
payBridgeFinalStatusDailyLimitValidationError = "DAILY_LIMIT_VALIDATION_ERROR"
|
|
||||||
payBridgeFinalStatusError = "ERROR"
|
|
||||||
payBridgeFinalStatusFailed = "FAILED"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
payBridgeMessageInsertOrSwipeCard = "insert or swipe card"
|
|
||||||
payBridgeMessageInsertSwipeOrPresentCard = "insert, swipe or present card"
|
|
||||||
payBridgeMessageInsertCard = "insert card"
|
|
||||||
payBridgeMessagePleaseWait = "please wait"
|
|
||||||
payBridgeMessageDoNotRemoveCard = "please wait. do not remove card"
|
|
||||||
payBridgeMessageTryAnotherInterface = "please try another interface"
|
|
||||||
payBridgeMessagePIN = "pin"
|
|
||||||
payBridgeMessagePINAgain = "pin again"
|
|
||||||
payBridgeMessageTransactionCancelled = "transaction cancelled"
|
|
||||||
payBridgeMessageProcessing = "processing"
|
|
||||||
payBridgeMessageApproved = "approved"
|
|
||||||
payBridgeMessageDeclined = "declined"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
payBridgeCodeInsertCard = "101"
|
|
||||||
payBridgeCodeEnterPIN = "106"
|
|
||||||
payBridgeCodeCancelled = "124"
|
|
||||||
payBridgeCodePleaseWait = "1017"
|
|
||||||
payBridgeCodePresentCard = "1109"
|
|
||||||
payBridgeCodePresentCardAlternate = "1113"
|
|
||||||
payBridgeCodeEnterPINAgain = "1129"
|
|
||||||
payBridgeCodeTryAnotherInterface = "1274"
|
|
||||||
payBridgeCodeDoNotRemoveCard = "1312"
|
|
||||||
)
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
package paybridge
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestMapPayBridgeFinalStatus(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
status string
|
|
||||||
success bool
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"approved success", "APPROVED", true, paymentstatus.Approved},
|
|
||||||
{"approved without success", "APPROVED", false, paymentstatus.Error},
|
|
||||||
{"declined", "DECLINED", false, paymentstatus.Declined},
|
|
||||||
{"cancelled", "CANCELLED", false, paymentstatus.Cancelled},
|
|
||||||
{"timeout", "TIMEOUT", false, paymentstatus.Timeout},
|
|
||||||
{"voided", "VOIDED", false, paymentstatus.Voided},
|
|
||||||
{"voided daily limit exceeded", "VOIDED_DAILY_LIMIT_EXCEEDED", false, paymentstatus.DailyLimitExceeded},
|
|
||||||
{"daily limit void failed", "DAILY_LIMIT_EXCEEDED_VOID_FAILED", false, paymentstatus.VoidFailed},
|
|
||||||
{"daily limit validation error", "DAILY_LIMIT_VALIDATION_ERROR", false, paymentstatus.LimitValidationError},
|
|
||||||
{"error", "ERROR", false, paymentstatus.Error},
|
|
||||||
{"failed", "FAILED", false, paymentstatus.Error},
|
|
||||||
{"unknown", "UNKNOWN", false, paymentstatus.Error},
|
|
||||||
{"approved case insensitive", "approved", true, paymentstatus.Approved},
|
|
||||||
{"declined case insensitive", "declined", false, paymentstatus.Declined},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
got := mapPayBridgeFinalStatus(test.status, test.success)
|
|
||||||
if got != test.want {
|
|
||||||
t.Fatalf("got %q, want %q", got, test.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMapPayBridgeStatusMessages(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
status string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"insert or swipe card", "insert or swipe card", paymentstatus.PresentCard},
|
|
||||||
{"insert swipe or present card", "insert, swipe or present card", paymentstatus.PresentCard},
|
|
||||||
{"insert card", "insert card", paymentstatus.InsertCard},
|
|
||||||
{"please wait", "please wait", paymentstatus.PleaseWait},
|
|
||||||
{"do not remove card", "please wait. do not remove card", paymentstatus.DoNotRemoveCard},
|
|
||||||
{"try another interface", "please try another interface", paymentstatus.TryAnotherInterface},
|
|
||||||
{"pin", "pin", paymentstatus.EnterPIN},
|
|
||||||
{"pin again", "pin again", paymentstatus.EnterPINAgain},
|
|
||||||
{"transaction cancelled", "transaction cancelled", paymentstatus.Cancelled},
|
|
||||||
{"processing", "processing", paymentstatus.Processing},
|
|
||||||
{"approved", "approved", paymentstatus.Authorized},
|
|
||||||
{"declined", "declined", paymentstatus.Declined},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
got, matched := mapPayBridgeStatus(test.status, "")
|
|
||||||
if !matched {
|
|
||||||
t.Fatal("expected status to match")
|
|
||||||
}
|
|
||||||
if got != test.want {
|
|
||||||
t.Fatalf("got %q, want %q", got, test.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMapPayBridgeStatusCodes(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
code string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"insert card", "101", paymentstatus.InsertCard},
|
|
||||||
{"enter pin", "106", paymentstatus.EnterPIN},
|
|
||||||
{"cancelled", "124", paymentstatus.Cancelled},
|
|
||||||
{"please wait", "1017", paymentstatus.PleaseWait},
|
|
||||||
{"present card", "1109", paymentstatus.PresentCard},
|
|
||||||
{"present card alternate", "1113", paymentstatus.PresentCard},
|
|
||||||
{"enter pin again", "1129", paymentstatus.EnterPINAgain},
|
|
||||||
{"try another interface", "1274", paymentstatus.TryAnotherInterface},
|
|
||||||
{"do not remove card", "1312", paymentstatus.DoNotRemoveCard},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
got, matched := mapPayBridgeStatus("", test.code)
|
|
||||||
if !matched {
|
|
||||||
t.Fatal("expected code to match")
|
|
||||||
}
|
|
||||||
if got != test.want {
|
|
||||||
t.Fatalf("got %q, want %q", got, test.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMapPayBridgeStatusNormalization(t *testing.T) {
|
|
||||||
got, matched := mapPayBridgeStatus(" PiN AgAiN ", "")
|
|
||||||
if !matched || got != paymentstatus.EnterPINAgain {
|
|
||||||
t.Fatalf("normalized message got (%q, %t), want (%q, true)", got, matched, paymentstatus.EnterPINAgain)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, matched = mapPayBridgeStatus("", " 101 ")
|
|
||||||
if !matched || got != paymentstatus.InsertCard {
|
|
||||||
t.Fatalf("trimmed code got (%q, %t), want (%q, true)", got, matched, paymentstatus.InsertCard)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMapPayBridgeStatusUnknown(t *testing.T) {
|
|
||||||
got, matched := mapPayBridgeStatus("unknown message", "999")
|
|
||||||
if matched {
|
|
||||||
t.Fatal("unknown status and code must not match")
|
|
||||||
}
|
|
||||||
if got != paymentstatus.Processing {
|
|
||||||
t.Fatalf("got %q, want %q", got, paymentstatus.Processing)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -53,13 +53,3 @@ type PaymentErrorEnvelope struct {
|
|||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
} `json:"data"`
|
} `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type StatusUpdateEnvelope struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
|
|
||||||
Data struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
Code string `json:"code"`
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
} `json:"data"`
|
|
||||||
}
|
|
||||||
@@ -6,23 +6,10 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var ErrPaymentInProgress = errors.New("payment is already in progress")
|
||||||
ErrPaymentInProgress = errors.New("payment is already in progress")
|
|
||||||
ErrProviderNotConfigured = errors.New("payment provider is not configured")
|
|
||||||
)
|
|
||||||
|
|
||||||
type StatusUpdate struct {
|
|
||||||
Code string `json:"code"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type StatusHandler func(StatusUpdate)
|
|
||||||
|
|
||||||
type Provider interface {
|
type Provider interface {
|
||||||
Sale(
|
Sale(ctx context.Context, req SaleRequest) (*Result, error)
|
||||||
ctx context.Context,
|
|
||||||
req SaleRequest,
|
|
||||||
onStatus StatusHandler,
|
|
||||||
) (*Result, error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
@@ -33,20 +20,10 @@ type Service struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewService(provider Provider) *Service {
|
func NewService(provider Provider) *Service {
|
||||||
return &Service{
|
return &Service{provider: provider}
|
||||||
provider: provider,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) Sale(
|
func (s *Service) Sale(ctx context.Context, req SaleRequest) (*Result, error) {
|
||||||
ctx context.Context,
|
|
||||||
req SaleRequest,
|
|
||||||
onStatus StatusHandler,
|
|
||||||
) (*Result, error) {
|
|
||||||
if s == nil || s.provider == nil {
|
|
||||||
return nil, ErrProviderNotConfigured
|
|
||||||
}
|
|
||||||
|
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
if s.busy {
|
if s.busy {
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
@@ -61,5 +38,5 @@ func (s *Service) Sale(
|
|||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return s.provider.Sale(ctx, req, onStatus)
|
return s.provider.Sale(ctx, req)
|
||||||
}
|
}
|
||||||
@@ -13,7 +13,6 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
|
||||||
"github.com/alexbrainman/printer"
|
"github.com/alexbrainman/printer"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
imagedraw "golang.org/x/image/draw"
|
imagedraw "golang.org/x/image/draw"
|
||||||
@@ -95,30 +94,7 @@ func ParseCardholderReceipt(data []byte) ([]ReceiptEntryXML, error) {
|
|||||||
return tr.ReceiptEntries.ReceiptEntry, nil
|
return tr.ReceiptEntries.ReceiptEntry, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func readTicketLayout() LayoutOptions {
|
|
||||||
var layout LayoutOptions
|
|
||||||
|
|
||||||
executablePath, err := os.Executable()
|
|
||||||
if err != nil {
|
|
||||||
errorhandlers.FatalError(fmt.Errorf("failed to locate application executable: %v", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
layoutName := filepath.Join(filepath.Dir(executablePath), "TicketLayout.xml")
|
|
||||||
data, err := os.ReadFile(layoutName)
|
|
||||||
if err != nil {
|
|
||||||
errorhandlers.FatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := xml.Unmarshal(data, &layout); err != nil {
|
|
||||||
errorhandlers.FatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
|
|
||||||
}
|
|
||||||
|
|
||||||
return layout
|
|
||||||
}
|
|
||||||
|
|
||||||
func BuildRoomTicket(details RoomDetailsRec) ([]byte, error) {
|
func BuildRoomTicket(details RoomDetailsRec) ([]byte, error) {
|
||||||
Layout = readTicketLayout()
|
|
||||||
|
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
|
||||||
// shortcuts
|
// shortcuts
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ 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/"
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
// Package paymentstatus defines progress codes emitted by Hardlink's
|
|
||||||
// POST /api/payment/sale stream. These codes are not authoritative final
|
|
||||||
// transaction decisions: clients may continue check-in only after receiving a
|
|
||||||
// final result frame whose response.data begins with /successful.
|
|
||||||
package paymentstatus
|
|
||||||
|
|
||||||
const (
|
|
||||||
Starting = "PAYMENT_STARTING"
|
|
||||||
Started = "PAYMENT_STARTED"
|
|
||||||
RequestSent = "PAYMENT_REQUEST_SENT"
|
|
||||||
Accepted = "PAYMENT_ACCEPTED"
|
|
||||||
PresentCard = "PAYMENT_PRESENT_CARD"
|
|
||||||
InsertCard = "PAYMENT_INSERT_CARD"
|
|
||||||
SwipeCard = "PAYMENT_SWIPE_CARD"
|
|
||||||
EnterPIN = "PAYMENT_ENTER_PIN"
|
|
||||||
EnterPINAgain = "PAYMENT_ENTER_PIN_AGAIN"
|
|
||||||
PleaseWait = "PAYMENT_PLEASE_WAIT"
|
|
||||||
DoNotRemoveCard = "PAYMENT_DO_NOT_REMOVE_CARD"
|
|
||||||
RemoveCard = "PAYMENT_REMOVE_CARD"
|
|
||||||
TryAnotherInterface = "PAYMENT_TRY_ANOTHER_INTERFACE"
|
|
||||||
Processing = "PAYMENT_PROCESSING"
|
|
||||||
Authorized = "PAYMENT_AUTHORIZED"
|
|
||||||
Approved = "PAYMENT_APPROVED"
|
|
||||||
Cancelling = "PAYMENT_CANCELLING"
|
|
||||||
Cancelled = "PAYMENT_CANCELLED"
|
|
||||||
Declined = "PAYMENT_DECLINED"
|
|
||||||
Expired = "PAYMENT_EXPIRED"
|
|
||||||
Timeout = "PAYMENT_TIMEOUT"
|
|
||||||
SignatureRequired = "PAYMENT_SIGNATURE_REQUIRED"
|
|
||||||
SignatureRejecting = "PAYMENT_SIGNATURE_REJECTING"
|
|
||||||
SignatureRejected = "PAYMENT_SIGNATURE_REJECTED"
|
|
||||||
Voided = "PAYMENT_VOIDED"
|
|
||||||
DailyLimitExceeded = "PAYMENT_DAILY_LIMIT_EXCEEDED"
|
|
||||||
VoidFailed = "PAYMENT_VOID_FAILED"
|
|
||||||
LimitValidationError = "PAYMENT_LIMIT_VALIDATION_ERROR"
|
|
||||||
Error = "PAYMENT_ERROR"
|
|
||||||
TerminalUnavailable = "PAYMENT_TERMINAL_UNAVAILABLE"
|
|
||||||
|
|
||||||
DojoNotificationPrefix = "PAYMENT_DOJO_NOTIFICATION_"
|
|
||||||
DojoStatusPrefix = "PAYMENT_DOJO_STATUS_"
|
|
||||||
)
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package paymentstatus_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestFixedStatusValues(t *testing.T) {
|
|
||||||
statuses := []struct {
|
|
||||||
name string
|
|
||||||
value string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"Starting", paymentstatus.Starting, "PAYMENT_STARTING"},
|
|
||||||
{"Started", paymentstatus.Started, "PAYMENT_STARTED"},
|
|
||||||
{"RequestSent", paymentstatus.RequestSent, "PAYMENT_REQUEST_SENT"},
|
|
||||||
{"Accepted", paymentstatus.Accepted, "PAYMENT_ACCEPTED"},
|
|
||||||
{"PresentCard", paymentstatus.PresentCard, "PAYMENT_PRESENT_CARD"},
|
|
||||||
{"InsertCard", paymentstatus.InsertCard, "PAYMENT_INSERT_CARD"},
|
|
||||||
{"SwipeCard", paymentstatus.SwipeCard, "PAYMENT_SWIPE_CARD"},
|
|
||||||
{"EnterPIN", paymentstatus.EnterPIN, "PAYMENT_ENTER_PIN"},
|
|
||||||
{"EnterPINAgain", paymentstatus.EnterPINAgain, "PAYMENT_ENTER_PIN_AGAIN"},
|
|
||||||
{"PleaseWait", paymentstatus.PleaseWait, "PAYMENT_PLEASE_WAIT"},
|
|
||||||
{"DoNotRemoveCard", paymentstatus.DoNotRemoveCard, "PAYMENT_DO_NOT_REMOVE_CARD"},
|
|
||||||
{"RemoveCard", paymentstatus.RemoveCard, "PAYMENT_REMOVE_CARD"},
|
|
||||||
{"TryAnotherInterface", paymentstatus.TryAnotherInterface, "PAYMENT_TRY_ANOTHER_INTERFACE"},
|
|
||||||
{"Processing", paymentstatus.Processing, "PAYMENT_PROCESSING"},
|
|
||||||
{"Authorized", paymentstatus.Authorized, "PAYMENT_AUTHORIZED"},
|
|
||||||
{"Approved", paymentstatus.Approved, "PAYMENT_APPROVED"},
|
|
||||||
{"Cancelling", paymentstatus.Cancelling, "PAYMENT_CANCELLING"},
|
|
||||||
{"Cancelled", paymentstatus.Cancelled, "PAYMENT_CANCELLED"},
|
|
||||||
{"Declined", paymentstatus.Declined, "PAYMENT_DECLINED"},
|
|
||||||
{"Expired", paymentstatus.Expired, "PAYMENT_EXPIRED"},
|
|
||||||
{"Timeout", paymentstatus.Timeout, "PAYMENT_TIMEOUT"},
|
|
||||||
{"SignatureRequired", paymentstatus.SignatureRequired, "PAYMENT_SIGNATURE_REQUIRED"},
|
|
||||||
{"SignatureRejecting", paymentstatus.SignatureRejecting, "PAYMENT_SIGNATURE_REJECTING"},
|
|
||||||
{"SignatureRejected", paymentstatus.SignatureRejected, "PAYMENT_SIGNATURE_REJECTED"},
|
|
||||||
{"Voided", paymentstatus.Voided, "PAYMENT_VOIDED"},
|
|
||||||
{"DailyLimitExceeded", paymentstatus.DailyLimitExceeded, "PAYMENT_DAILY_LIMIT_EXCEEDED"},
|
|
||||||
{"VoidFailed", paymentstatus.VoidFailed, "PAYMENT_VOID_FAILED"},
|
|
||||||
{"LimitValidationError", paymentstatus.LimitValidationError, "PAYMENT_LIMIT_VALIDATION_ERROR"},
|
|
||||||
{"Error", paymentstatus.Error, "PAYMENT_ERROR"},
|
|
||||||
{"TerminalUnavailable", paymentstatus.TerminalUnavailable, "PAYMENT_TERMINAL_UNAVAILABLE"},
|
|
||||||
}
|
|
||||||
|
|
||||||
seen := make(map[string]string, len(statuses))
|
|
||||||
for _, status := range statuses {
|
|
||||||
t.Run(status.name, func(t *testing.T) {
|
|
||||||
if status.value != status.want {
|
|
||||||
t.Fatalf("got %q, want %q", status.value, status.want)
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(status.value, "PAYMENT_") {
|
|
||||||
t.Fatalf("status %q does not have PAYMENT_ prefix", status.value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if previous, exists := seen[status.value]; exists {
|
|
||||||
t.Errorf("%s and %s have duplicate value %q", previous, status.name, status.value)
|
|
||||||
}
|
|
||||||
seen[status.value] = status.name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDojoPrefixes(t *testing.T) {
|
|
||||||
if paymentstatus.DojoNotificationPrefix != "PAYMENT_DOJO_NOTIFICATION_" {
|
|
||||||
t.Fatalf(
|
|
||||||
"DojoNotificationPrefix = %q, want %q",
|
|
||||||
paymentstatus.DojoNotificationPrefix,
|
|
||||||
"PAYMENT_DOJO_NOTIFICATION_",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if paymentstatus.DojoStatusPrefix != "PAYMENT_DOJO_STATUS_" {
|
|
||||||
t.Fatalf(
|
|
||||||
"DojoStatusPrefix = %q, want %q",
|
|
||||||
paymentstatus.DojoStatusPrefix,
|
|
||||||
"PAYMENT_DOJO_STATUS_",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if paymentstatus.DojoNotificationPrefix == paymentstatus.DojoStatusPrefix {
|
|
||||||
t.Fatal("Dojo prefixes must differ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+1
-16
@@ -2,23 +2,8 @@
|
|||||||
|
|
||||||
builtVersion is a const in main.go
|
builtVersion is a const in main.go
|
||||||
|
|
||||||
#### v2.0.0 - 08 September 2026
|
|
||||||
feat: stream CreditCall payment progress and results
|
|
||||||
|
|
||||||
#### v1.3.6 - 28 August 2026
|
|
||||||
Refactor PDQ lookup for payment providers
|
|
||||||
|
|
||||||
#### v1.3.5 - 23 July 2026
|
|
||||||
fixed dispenser delivery confirmation
|
|
||||||
|
|
||||||
#### v1.3.4 - 23 July 2026
|
|
||||||
added support for Dojo terminal-unavailable responses
|
|
||||||
|
|
||||||
#### v1.3.3 - 21 July 2026
|
|
||||||
added PDQ status streaming to the payment flow to allow the front end to display the status of the PDQ terminal
|
|
||||||
|
|
||||||
#### 1.3.2 - 20 July 2026
|
#### 1.3.2 - 20 July 2026
|
||||||
make dojo decline payment in case of signature required
|
make dojo decline payment it case of signature required
|
||||||
|
|
||||||
#### 1.3.1 - 17 July 2026
|
#### 1.3.1 - 17 July 2026
|
||||||
added receipt printing functionality to the Dojo and Paybridge payment flow
|
added receipt printing functionality to the Dojo and Paybridge payment flow
|
||||||
|
|||||||
Reference in New Issue
Block a user