Compare commits

...
4 Commits
58 changed files with 2504 additions and 149 deletions
+9 -2
View File
@@ -5,6 +5,11 @@ encoding, room-ticket and payment-receipt printing, and terminal payments. It
supports Assa Abloy, Omnitec, Salto, TLJ and dormakaba lock servers, and CreditCall supports Assa Abloy, Omnitec, Salto, TLJ and dormakaba lock servers, and CreditCall
(ChipDNA), Dojo, PayBridge and Trust Payments providers. (ChipDNA), Dojo, PayBridge and Trust Payments providers.
The Go module is `gitea.futuresens.co.uk/futuresens/hardlink/v2`. Native kiosk clients import
`gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi` and
`gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus`.
The application build version is `v2.2.1`; publishing its release tag is a separate step.
## Documentation ## Documentation
- [Configuration](docs/configuration.md): local service/device settings, - [Configuration](docs/configuration.md): local service/device settings,
@@ -16,8 +21,6 @@ supports Assa Abloy, Omnitec, Salto, TLJ and dormakaba lock servers, and CreditC
- [K720 hardware contract](docs/hardware/k720.md): preparation, uncertain-handoff - [K720 hardware contract](docs/hardware/k720.md): preparation, uncertain-handoff
recovery, delivery clearance and maintenance invariants. recovery, delivery clearance and maintenance invariants.
- [Release history](docs/releases.md). - [Release history](docs/releases.md).
- [Historical archive](docs/archive/README.md): superseded Trust plans and
audits, retained as dated evidence rather than current operating instructions.
Hardlink owns payment-provider selection and terminal processing. The native Hardlink owns payment-provider selection and terminal processing. The native
Fyne applications use the common Sale/PREAUTH contract and own their financial Fyne applications use the common Sale/PREAUTH contract and own their financial
@@ -27,3 +30,7 @@ come from CMS; no local `trust:` YAML section or currency-evidence flag is neede
The deprecated XML payment routes remain solely for legacy compatibility. The deprecated XML payment routes remain solely for legacy compatibility.
`/testissuedoorcard` remains an operational diagnostic available on production `/testissuedoorcard` remains an operational diagnostic available on production
kiosks regardless of TestMode, and retains the encoded card inside the dispenser. kiosks regardless of TestMode, and retains the encoded card inside the dispenser.
Historical plans and independent audits remain unchanged in the local
`docs/archive/` collection. They are excluded from this module-migration commit
and are not current operating instructions.
+15 -15
View File
@@ -16,24 +16,24 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/cms" "gitea.futuresens.co.uk/futuresens/hardlink/v2/cms"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/bootstrap" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/bootstrap"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dispenser" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/dispenser"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dojo" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/dojo"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/errorhandlers"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/handlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/handlers"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/lockserver"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/logging" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/logging"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/mail"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paybridge" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paybridge"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/printer"
) )
const ( const (
buildVersion = "v2.2.0" buildVersion = "v2.2.4"
serviceName = "hardlink" serviceName = "hardlink"
pollingFrequency = 8 * time.Second pollingFrequency = 8 * time.Second
) )
+3 -3
View File
@@ -3,9 +3,9 @@ package main
import ( import (
"errors" "errors"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/handlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/handlers"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
) )
func configureTrust(app *handlers.App, cfg config.ConfigRec, hotel cmstypes.Hotel) error { func configureTrust(app *handlers.App, cfg config.ConfigRec, hotel cmstypes.Hotel) error {
+4 -4
View File
@@ -15,10 +15,10 @@ import (
"time" "time"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/cms" "gitea.futuresens.co.uk/futuresens/hardlink/v2/cms"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/handlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/handlers"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
yaml "gopkg.in/yaml.v3" yaml "gopkg.in/yaml.v3"
) )
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"os" "os"
"strings" "strings"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/errorhandlers"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v3" yaml "gopkg.in/yaml.v3"
) )
+88
View File
@@ -0,0 +1,88 @@
# Configuration
[Project overview](../README.md) | [Operations](operations.md) | [Payment API](payment-api.md)
## Local service configuration
Example `config.yml` for card issuance and printing:
```yaml
port: 9091
lockType: "assaabloy"
lockservUrl: "http://192.168.4.109:4000"
encoderAddr: "1"
dispensPort: "COM9"
dispensAddr: "15"
printerName: "EPSON TM-T82II Receipt"
logdir: "./logs"
isPayment: false
```
- `lockType` is required: `assaabloy`, `omnitec`, `salto`, `tlj` or `kaba`.
- `cert` supplies the certificate value used by TLJ's GuestCard API.
- `dispensAddr` is the two-character serial device address.
- `printerName` must match an installed Windows printer.
- Payment setup additionally uses `isPayment`, `hotel`, `kiosk`, `cmsurl` and,
when CMS does not select a provider, `paymentProvider` (`creditcall`, `dojo` or
`paybridge` or `trustpayments`). Provider-specific terminal settings are read from CMS.
- SQL configuration uses `dbport`, `dbname`, `dbuser` and `dbpassword`; configure
these for monetary CreditCall PREAUTH persistence and the release task.
- `senderroremails` contains recipients for operational error emails.
- `timeoutSeconds` defaults to `300`, with a 15-second shared worker margin. CreditCall
retains its independent 300-second start/confirmation call bounds.
## Room-ticket layout
Example `TicketLayout.xml`:
```xml
<LayoutOptions>
<LogoPath>C:/Logo/logo.png</LogoPath>
<TopMostText>Welcome to the hotel</TopMostText>
<BeforeRoomNumberText>Your room number is</BeforeRoomNumberText>
<BeforeDirectionsText></BeforeDirectionsText>
<HotelSpecificDetails>Hotel information</HotelSpecificDetails>
<CheckOutTimeText>Check Out Time</CheckOutTimeText>
<RoomMapFolderPath>C:/Logo/Roommaps</RoomMapFolderPath>
</LayoutOptions>
```
## Trust Payments: CMS-only configuration
Hardlink needs its ordinary local device/service configuration, including `isPayment`, `hotel`, `kiosk` and `cmsurl`. **Do not add a `trust:` section.** Existing CMS-first payment-provider selection and the generic local `paymentProvider` fallback are unchanged.
The existing hotel-details request is made once. `ReadHotelDetails` retains the complete `cmstypes.Hotel`; `ReadHotel` keeps the existing reservation-system-only API for callers that need it. The other provider branches receive the same reservation-system values as before.
| Trust value | Existing CMS source |
|---|---|
| Provider | `Hotel.ReservationSystem.PaymentSystem` |
| Gateway | `Hotel.ReservationSystem.PaymentGatewayURL` (`payurl`) |
| Site ID | `Hotel.ReservationSystem.PaymentGatewaySiteIDEPOS` (`paysiteidepos`) |
| Password | `Hotel.ReservationSystem.PaymentGatewayPasswordEPOS` (`paypassepos`) |
| PED | `Hotel.ReservationSystem.PDQs[].Serial` for the existing local kiosk identity (`pdq`) |
| Configured currency | `Hotel.Currency.Code` (`curr.code`); existing CMS currency metadata remains available |
| Signing timezone | `Hotel.ReservationSystem.TimeZone` (`tz`), the same CMS timezone source used by checkinfyne |
Gateway, credentials, a unique nonempty matching PED and a valid explicit CMS timezone are required before dispatch. There is no machine-local timezone fallback. Configuration errors identify the missing field without printing credential values. Existing HTTPS gateway restrictions remain.
`ContractsVerified`, configurable `CurrencyEvidence` and the local Trust configuration type have been removed. `default_currency` and `expected_currency` were audit references, not active settings in this checkout; no aliases or replacements are added. An old unused `trust:` section is ignored by the existing YAML decoder, but is no longer required or read.
### Currency policy: legacy behavior
Per the approved clarification, **Trust currency fields do not determine approval**. Missing, matching or differing provider currency does not create a new rejection, evidence requirement or approval switch. No currency field is added to TRU Link requests. The provider currency field is ignored rather than decoded into a validation gate.
CMS remains the configured hotel/payment currency for bookkeeping and receipt presentation. It does not independently prove terminal settlement currency. Hardlink manufactures no currency evidence. All providers use the unified [modern payment API](payment-api.md); the Fyne client has no Trust adapter or currency/evidence acceptance branch. The runtime service receives currency from the CMS hotel response. Shared money handling, PMS rules and posting validations are unchanged.
### Payment behavior retained
- Unified provider-independent Sale/PREAUTH NDJSON routes and existing Fyne screens.
- One financial POST; at most one read-only `/status` lookup for uncertainty, with the same reference and signing timestamp.
- Existing 300-second financial, 15-second status and 330-second kiosk budgets.
- Existing amount, reference, site/PED/type, approval and uncertainty checks; no automatic financial retry of an uncertain result.
- Existing approved-payment capture, ten-minute fallback, Guestline PostPayment, ZeroPreauth, per-room allocations, Registration and keycard prerequisites.
No Trust intent journal, extra recovery system, automatic cross-restart terminal deduplication or guest check-in resumption is introduced. Lost approvals before kiosk capture remain reception reconciliation work. Actual hotel data, gateway acceptance, settlement currency and physical devices were not tested.
For working-directory requirements, logging, offline verification and deployment,
see [operations](operations.md). Use synthetic credentials in examples; do not
copy hotel credentials into source control or diagnostics.
+376
View File
@@ -0,0 +1,376 @@
# K720 dispenser issuance contract
Hardlink treats the K720 as an unreliable mechanical peripheral with a strict transport
protocol and imperfect status telemetry. The implementation must keep transport
validation strict while making mechanical decisions from fresh, bounded observations.
Diagnostic bytes are useful evidence, but they must not override a valid physical
position or turn an uncertain observation into a fatal guest-facing error.
This document records the dispenser invariants agreed for the clean implementation.
It is intended to be a design contract: future changes should preserve these rules
unless production evidence justifies changing them explicitly.
## Ownership and concurrency
- The dispenser worker is the single owner of serial commands and `deliveryPending`.
New code must not access the serial port directly from handlers or background
goroutines.
- Commands that can move a card are serialized through the worker. There must never
be concurrent AP/FC7/FC0/RS traffic from separate flows.
- `deliveryPending` is worker-owned state. It must not be duplicated or mutated by
HTTP handlers.
- A real `/issuedoorcard` operation always has priority over maintenance/prestage
work.
- Cancellation of a real caller must stop caller-owned work. Internal bounded
observation timeouts must remain distinguishable from caller cancellation.
- Do not create overlapping maintenance goroutines or timers per request. Any
background maintenance must have one clear owner and lifecycle.
## Status and observation model
AP transport parsing is strict. A response is usable only when its framing and
contents are valid, including ACK/address/header/length/ETX/BCC/type checks.
Malformed, truncated, timed-out or otherwise invalid AP responses are unusable
observations. They are logged and discarded. They are never converted into a
fabricated physical state such as `0x30` or `0x38`.
Every fresh valid AP observation reclassifies the current mechanical state. No
physical position is latched across later observations.
The fourth AP status byte is the physical position used by the preparation logic:
- Encoder confirmed:
`0x32, 0x33, 0x36, 0x37, 0x3A, 0x3B, 0x3E, 0x3F`.
A card may be handed to `LockSequence` immediately.
- Valid but uncertain:
`0x31, 0x34, 0x35, 0x39, 0x3C, 0x3D`.
Continue bounded fresh observation; if no stronger state appears, one encoding
opportunity may still be granted after the uncertainty window.
- No card on sensors:
exact `0x30`.
This may trigger the bounded mechanical recovery sequence.
- Card well empty:
exact `0x38`.
This is the only physical state that becomes `ErrCardWellEmpty`.
The first three diagnostic bytes are advisory. Values such as `Preparing card fails`,
`Dispense card error`, `Card jammed`, or `Command cannot execute` may coexist with a
usable physical position. They may be logged, but they must not automatically block
encoding when the fourth byte confirms a usable card position.
## Preparing the current card
A `/issuedoorcard` request receives at most one `LockSequence` opportunity.
Preparation uses bounded fresh observation:
- Poll interval: 1 second.
- After a successful FC7, allow 3 seconds of observation before shake recovery is
eligible for a persistent exact `0x30`.
- For uncertain or unusable observations after a successful FC7, use one shared
4-second uncertainty window. Switching between uncertain and unusable observations
does not restart that window.
- A later usable observation always takes precedence:
encoder confirmed -> handoff;
exact `0x38` -> empty;
exact `0x30` -> resume the remaining shake budget and reset uncertainty timing.
- Total preparation budget: 32 seconds.
For persistent exact `0x30`, the request may perform at most three shake recoveries:
`RS -> 2 second settle -> FC7`
There is no additional plain FC7 retry. Including the initial dispatch, the maximum
per request is four FC7 commands and three RS commands.
If all three shakes are exhausted while the latest usable physical state remains
exact `0x30`, preparation fails. If the internal preparation deadline is reached
while the latest state is uncertain or unusable after a successful FC7, the request
may hand off one encoding opportunity. Exact `0x38` remains empty.
FC7 or RS dispatch failures are real transport/command failures. They are not
converted into status uncertainty and are not retried merely because their dispatch
failed.
## Encoding and delivery
`LockSequence` runs exactly once for a prepared card in a single `/issuedoorcard`
request. The dispenser layer does not implement a second encoding attempt on the same
physical card.
### Recovery during uncertain handoff
Only an uncertain preparation handoff enables concurrent recovery during the single
`LockSequence`. Encoder-confirmed preparation keeps its existing synchronous flow.
Preparation passes request-local stock, handoff reason, shakes already used, and the
last FC7 time to recovery. No counter is reset when encoding begins.
Recovery starts with fresh worker-owned AP. Encoder confirmation stops recovery
immediately; exact `0x38` stops recovery as empty. Neither recovery errors nor an empty
observation during encoding replace the original `LockSequence` result or its HTTP
mapping. Unusable AP observations remain diagnostic, not fabricated physical states.
With remaining shake budget, recovery uses:
`RS -> 2 second settle -> diagnostic AP -> FC7 -> AP`
An encoder-confirmed diagnostic AP stops recovery before FC7. An unusable diagnostic
AP is logged and does not prevent that FC7. RS/FC7 dispatch failures end recovery
without retrying the command. Between shakes, retain one-second AP observation and
the existing three-second minimum after FC7. At most three RS are permitted across
initial preparation and this recovery together; exhaustion ends recovery while the
original lock-server operation continues waiting.
The handler cancels recovery as soon as `LockSequence` returns and joins the recovery
goroutine before requesting FC0. Caller cancellation also stops recovery, including
settle waits and queued commands. An already-started serial exchange is limited by
the existing transport read timeout; the single worker prevents overlap with FC0.
No recovery survives the request or changes maintenance/prestage admission.
`LockSequence` itself retains its current cancellation and timeout contract: HTTP
cancellation does not interrupt an already-started encoding operation. After its
original result, the existing bounded FC0/finalization still runs. No second encoding,
new lock-server deadline, or automatic guest-facing retry is introduced.
Logs record uncertain handoff, encoding start/completion and duration, recovery AP
bytes/classification, RS/FC7 attempts, remaining budget, and the stop reason (encoder,
empty, exhausted budget, encoding completion, caller cancellation, or recovery error).
Hardware testing established that RS does not physically move the card and FC7 does
not move/eject a card already at the encoder. Concurrent recovery with the actual
lock server still requires physical validation.
After `LockSequence`, FC0 is dispatched exactly once to move the current card toward
the guest:
- `LockSequence` success -> FC0 once -> successful issuance remains successful.
- `LockSequence` failure -> FC0 once -> return the original encoding error.
- FC0 errors are logged only. They do not replace the original encoding result and
they do not become `ErrCardWellEmpty`.
A failed `LockSequence` does not start next-card prestaging.
The design intentionally does not add retained-card state, per-card failure counters,
provider-specific encoder retries, special bad-card recovery, CP/capture recovery, or
multiple encoding attempts per physical card without production evidence requiring
them.
## Delivery clearance
After FC0, the worker marks the previous delivery as pending. A later FC7 must not be
sent until the previous delivery has been considered clear.
Delivery clearance uses fresh AP observations and is owned by the worker.
Current bounds:
- Minimum clearance wait: 2 seconds.
- Clearance timeout: 6 seconds.
- Poll interval: 1 second.
A valid physical position of `0x30` or `0x34` may clear `deliveryPending` after the
minimum wait unless the same fresh observation explicitly indicates active
preparing/dispensing/capturing movement.
Exact `0x38` reports physical empty and does not silently clear the state.
If the internal clearance timeout is reached while the caller context is still
valid, the worker may make the bounded assumption that delivery has cleared unless
the latest fresh usable observation establishes exact physical empty (`0x38`) or
explicit active movement. This fallback may therefore occur while the latest
physical position is `0x33`; `0x33` itself is not positive clearance evidence.
The fallback is an internal timeout policy, not a reclassification of the observed
position.
If the latest fresh usable observation still explicitly indicates movement, that is
not treated as unknown. `deliveryPending` remains set and the clearance attempt
times out.
Caller cancellation or deadline always takes precedence over the internal clearance
fallback. If the caller context expires, return the caller error and do not admit a
subsequent FC7 from that caller-owned operation.
A later unusable observation supersedes older movement evidence; stale movement
information must not be latched indefinitely.
## Next-card prestage and guest UX
Preparing the next card is an optimization for the next guest, not part of the
business success of the current guest's issuance.
After a successful `LockSequence` and FC0, Hardlink may make a short best-effort
attempt to prestage the next card:
- wait for worker-owned delivery clearance;
- if clearance is obtained within the bounded prestage context, send exactly one FC7;
- do not run readiness polling, RS/shake recovery, or the full current-card
preparation flow;
- prestage failure is log-only and must not change the successful `/issuedoorcard`
result.
Do not extend the current guest's screen by 15-20 seconds merely to guarantee that
the next card reaches the encoder. The guest-facing flow must remain bounded even
when the dispenser is slow to become ready for prestage.
If the short prestage window expires, skip that prestage attempt. A later request or
maintenance cycle may prepare the next card.
## HTTP contract
Physical empty and operational failure are deliberately different outcomes.
- HTTP 503 is reserved for `ErrCardWellEmpty`, derived only from an exact valid
physical `0x38`.
- All other dispenser preparation, transport, command and encoding failures return
HTTP 502.
- Normal request/protocol validation keeps its existing 400/405/415 behavior.
- Diagnostic text such as `Preparing card fails` must never by itself produce 503.
Operafyne treats:
- 502 as retryable while attempts remain;
- 503 as terminal `dispenser_failed`;
- a maximum of three total issue attempts: the initial attempt plus up to two user
retries.
The dispenser layer must preserve this distinction.
## Passive status and alerts
Ordinary status queries remain strict and passive. They must not reuse tolerant
issuance semantics to fabricate a status or hide malformed transport.
Passive polling captures the current foreground activity generation when the poll is
queued. The worker skips a passive poll if foreground activity is active when it is
dispatched or if the captured generation has become obsolete. Passive polling does
not reset the idle-maintenance clock.
Status/diagnostic observations may be useful for logs and support alerts, but alerts
must not alter physical state classification or issuance success.
Idle maintenance observations are intentionally quiet: they do not invoke the normal
stock-update callback or generate repeated support email such as `Preparing card
fails`. Maintenance failures are local diagnostic events only.
## Idle prestage maintenance
Idle prestaging recovers from a short post-FC0 prestage timeout without keeping the
current guest waiting.
The implementation uses the existing dispenser worker as the single maintenance
owner:
- one resettable maintenance timer is owned by the serial-worker loop; there is no
maintenance goroutine and no timer created per request;
- `/issuedoorcard` and `/testissuedoorcard` register foreground activity before
using the dispenser/encoder and release it when the handler finishes;
- foreground activity is reference-counted so overlapping requests suppress
maintenance until the last active request finishes;
- each foreground registration increments an activity generation and invalidates the
previous idle deadline;
- when the last foreground request finishes, the next maintenance attempt is
scheduled one minute later;
- enabling maintenance at startup schedules the first check one minute later when
no foreground request is active;
- a stale timer or stale generation cannot perform maintenance;
- after a maintenance attempt, the next check is scheduled one minute from completion
only if the same generation is still authoritative. A later foreground completion
therefore cannot have its newer deadline overwritten by an older maintenance
attempt.
Foreground registration and maintenance transaction admission use the same activity
guard. The guard is used only for admission/state bookkeeping and is never held
across serial I/O, queue waits, sleeps, callbacks, or `LockSequence`.
A maintenance attempt is deliberately weaker than foreground preparation:
1. create a bounded 5-second maintenance context;
2. recheck maintenance admission before AP;
3. obtain one fresh AP using the existing strict transport parser;
4. classify the fresh status using the common physical classifier;
5. do nothing for encoder-present, exact `0x38`, unusable, explicit-movement, or
otherwise ineligible observations;
6. when `deliveryPending` is set, require fresh qualifying clearance evidence and the
existing minimum clearance wait before clearing it;
7. never use the foreground six-second assumed-clearance fallback;
8. recheck foreground count, activity generation, maintenance enabled state, and
maintenance context immediately before FC7 admission;
9. dispatch at most one FC7 and return immediately.
If foreground activity begins while an already-admitted maintenance AP is in
progress, that AP may finish, but the second admission check prevents maintenance
from sending FC7 afterward. An FC7 that was already admitted and dispatched before
foreground registration cannot be recalled.
Maintenance never performs:
- RS or shake recovery;
- `LockSequence`;
- `PrepareCurrentCard`;
- `PrepareNextCard` or `BeginPrepareNextCard`;
- readiness polling after FC7;
- the 32-second foreground preparation flow;
- repeated FC7 attempts;
- the foreground assumed-clearance fallback.
The 5-second maintenance context bounds new admissions and context-aware waits. An
already-admitted serial read may still finish according to the existing serial read
timeout, but no subsequent maintenance transaction is admitted after cancellation or
expiry.
`StartMaintenance` and `StopMaintenance` are idempotent lifecycle operations.
`Client.Close` disables maintenance and stops the timer.
Stopping maintenance cancels the current maintenance context and waits only for an
already-admitted maintenance transaction to finish under the existing bounded serial
behavior.
## Automated verification
Tests should preserve the behavioural contract rather than only exercise individual
functions.
At minimum, cover:
- strict AP framing and malformed/truncated/timeout responses;
- tolerant issuance observations never fabricating `0x30` or `0x38`;
- every physical position class and transitions between classes;
- exact `0x38` as the only `ErrCardWellEmpty` path;
- persistent `0x30` using at most three `RS -> settle -> FC7` recoveries;
- no extra FC7 after the shake budget;
- uncertain/unusable shared timing and later usable-state precedence;
- caller cancellation versus internal preparation timeout;
- exactly one `LockSequence` opportunity per request;
- FC0 exactly once after encoding success or failure;
- FC0 failure remaining log-only;
- failed encoding never starting prestage;
- worker-owned `deliveryPending` and guarded FC7 dispatch;
- bounded delivery-clearance fallback and explicit-movement timeout;
- successful issuance remaining successful when next-card prestage fails;
- HTTP 503 only for exact physical empty and 502 for other issuance failures;
- Operafyne retry semantics remaining three total attempts.
Idle maintenance verification additionally covers:
- first attempt occurs one minute after the latest issuance finishes;
- a new issuance resets that idle interval;
- overlapping foreground requests suppress maintenance until the last request
finishes;
- both `/issuedoorcard` and `/testissuedoorcard` participate in foreground activity
registration;
- stale timer events and stale activity generations cannot perform maintenance;
- foreground registration before maintenance AP prevents AP admission;
- foreground registration during an admitted AP prevents the later FC7;
- passive polls are skipped while foreground activity is active or when their
captured generation is stale;
- maintenance performs one AP and at most one FC7, with no RS/shake/encoding;
- encoder-present, exact-empty, movement and unusable observations are no-ops;
- pending delivery requires fresh normal clearance plus the minimum wait and never
uses the foreground assumed-clearance fallback;
- maintenance errors do not produce guest-facing failures, stock callbacks or
repeated alert email;
- repeated maintenance start/stop calls are safe and do not accumulate work;
- cancellation, `StopMaintenance` and `Client.Close` prevent subsequent maintenance
commands after shutdown admission is revoked.
For Hardlink verification, continue excluding the existing test that sends real
email when running the full suite.
+192
View File
@@ -0,0 +1,192 @@
# Operations
[Project overview](../README.md) | [Configuration](configuration.md) | [Payment API](payment-api.md)
## Build and run
Run from the repository root on Windows with Go 1.23.2 or newer and access to the
private Gitea modules. The entry point is `cmd/hardlink`, not the repository root.
```powershell
go build -mod=readonly -o hardlink.exe ./cmd/hardlink
go build -mod=readonly -o hardlink-preauth-release/preauth-release.exe ./hardlink-preauth-release
./hardlink.exe
```
`preauth-release.exe` is a separate task for releasing due CreditCall
preauthorizations; the HTTP service does not run it automatically.
Start Hardlink with the deployment directory as its working directory:
```text
hardlink/
hardlink.exe
config.yml
TicketLayout.xml
ChipDNAClient/ # Required for CreditCall
ChipDnaClient.exe
... SDK dependencies and terminal configuration
hardlink-preauth-release/
preauth-release.exe
config.yml # Configuration for the separate release task
logs/
```
`config.yml` and the ChipDNA executable path are relative to the working
directory. `TicketLayout.xml` is loaded beside the Hardlink executable. Configure
the release task's working directory to contain its own `config.yml`.
The HTTP server binds to `:<port>` on all interfaces; the default port is `9091`.
See [configuration](configuration.md) for local settings, the CMS payment field
mapping and the room-ticket layout.
## Door cards
`POST /issuedoorcard` accepts `Content-Type: application/json`:
```json
{
"roomField": "101",
"checkinTime": "2026-10-23 15:00:00 +0100",
"checkoutTime": "2026-10-24 11:00:00 +0100",
"followStr": "0"
}
```
Times use `2006-01-02 15:04:05 -0700`. Success returns:
```json
{"code":200,"message":"Card issued successfully"}
```
Errors use the same `code`/`message` JSON structure with an HTTP error status.
Exact physical empty (`0x38`) during preparation returns `503`; preparation
exhaustion and encoding errors return `502`.
The complete [K720 issuance contract](hardware/k720.md) covers worker ownership,
preparation, uncertain-handoff recovery, delivery clearance, cancellation and
idle maintenance. It includes the single `LockSequence`, shared three-shake
budget, log-only delivery errors and best-effort next-card prestaging rules.
Concurrent recovery with the actual dispenser and lock server still requires
controlled physical validation.
## Room tickets
`POST /printroomticket` accepts `Content-Type: application/xml`:
```xml
<roomdetails>
<customername>John Doe</customername>
<checkoutdatetime>24/10/2026 11:00 am</checkoutdatetime>
<roomno>103</roomno>
<roommap>map.png</roommap>
<roomdirections>Follow the corridor...</roomdirections>
</roomdetails>
```
Success returns HTTP `200` with:
```json
{"code":200,"message":"Print job sent successfully"}
```
The printer package loads the ticket layout, renders ESC/POS text and raster
images, and sends the output to the configured Windows printer.
## Additional endpoints
| Endpoint | Purpose |
| --- | --- |
| `GET /dispenserstatus` | Cached stock/status in a `code`/`message` JSON response |
| `POST /testissuedoorcard` | Operational diagnostic, available regardless of TestMode: encode and retain the card inside the dispenser; no guest delivery |
| `GET /ping-pdq` | Read ChipDNA terminal status |
| `POST /logerror` | Receive ChipDNA error notifications |
`/testissuedoorcard` is an operational hardware diagnostic available regardless
of TestMode. It prepares and encodes a card without FC0 guest delivery; the card
remains inside the dispenser for reuse. Its registration and hardware sequence
are separate from normal issuance and are not restricted to development kiosks.
## Native-only endpoint cleanup
The modern `/api/payment/sale`, `/api/payment/preauth`, `/issuedoorcard` and `/printroomticket` endpoints serve native Fyne HTTP clients. They no longer emit browser CORS headers or accept OPTIONS preflight requests; non-POST methods receive the existing method-rejection format. Successful POST payloads, responses, payment execution and hardware sequences are unchanged. Keycard requests need only `roomField`, `checkinTime`, `checkoutTime` and `followStr`.
`/dispenserstatus` and `/ping-pdq` are GET diagnostics (other methods return 405 with `Allow: GET`). The ChipDNA sidecar's asynchronous POST `/logerror`, error notifications and availability debounce remain operational. Background dispenser polling is unchanged.
`/testissuedoorcard` is unconditionally registered on production kiosks and retains its encoded card for reuse. No TestMode gate or automatic ejection has been added. The deprecated XML `/takepayment` and `/takepreauth` handlers and their required response/redirect helpers remain for their explicitly retained contract. Do not remove the active sidecar or printer/lock-server protocols as browser legacy.
## Logging
JSON logs are written to `<logdir>/hardlink.log`. Weekly rotation uses local
Monday midnight and retains `hardlink.1.log` through `hardlink.13.log`. The separate
release task writes `preauth-release.log` with the same rotation policy.
K720 logs include uncertain handoff, raw AP status/classification, RS/FC7 attempts,
remaining shake budget, recovery stop reason and encoding duration. PREAUTH logs
include processor result/type, transaction reference, approval/persistence
decision, missing fields, and SQL/spool outcomes without card or receipt payloads.
## Verification
Use repository-local build and temporary caches from PowerShell:
```powershell
New-Item -ItemType Directory -Force .cache/go-build, .cache/tmp | Out-Null
$env:GOCACHE = Join-Path $PWD '.cache/go-build'
$env:GOTMPDIR = Join-Path $PWD '.cache/tmp'
$env:TEMP = $env:GOTMPDIR
$env:TMP = $env:GOTMPDIR
go test -mod=readonly -count=1 ./internal/dispenser ./internal/handlers
go test -mod=readonly -race -count=1 ./internal/dispenser ./internal/handlers
go test -mod=readonly -count=1 -skip '^Test_SendMail$' ./...
go vet -mod=readonly ./...
go build -mod=readonly ./...
git diff --check
```
`Test_SendMail` sends real email and is excluded from offline verification.
Automated tests do not replace physical dispenser, encoder, terminal or printer
validation.
The existing `run_tests.sh` is not an offline verification entry point: it runs
`go mod tidy` and unfiltered full tests, including the live-email test. Use the
explicit commands above instead. Do not launch the service against hotel
configuration as part of offline validation.
## Deployment
Production deployment uses Salt. Build the intended revision and deploy the
versioned Windows package through the Salt repository and Hardlink pillar.
Where installed, local release tooling is invoked as `bash ./winbuild.sh <version>`
from the `development` branch. It builds Hardlink and the release task, packages
the existing `ChipDNAClient/` directory into `hardlink_windows_<version>.zip`, and
copies it to `salt/hardlink/files`. It also checks out/pulls the Salt and pillar
repositories and commits/pushes the package in Salt; it does not create a Git tag.
Ensure `ChipDNAClient/` contains the intended build before packaging.
Update `pillar/hardlink/init.sls` to select the package version, then apply the
Hardlink state to the intended hosts:
```bash
salt '<target-minion>' state.apply hardlink
```
## Coordinated application releases
Deploy compatible ChipDNAClientCLI, Hardlink and native Fyne versions together.
The module path is `gitea.futuresens.co.uk/futuresens/hardlink/v2`; internal and
public package imports include `/v2`. The application `buildVersion` does not
publish a module tag automatically.
The owner must commit and publish the intended v2 release before the Fyne
applications pin its actual tag with `go get` and regenerate sums with
`go mod tidy`. Until publication, their zero pseudo-version marker is local-only
and resolves through ignored alternate modfiles replacing the `/v2` module with
the sibling checkout. Do not commit that replacement or invent remote checksums.
The existing Fyne/CMS/translate dependency replacements are independent.
Hardlink itself builds and tests from this checkout using its tracked module
files. Release history is recorded in [releases](releases.md).
+184
View File
@@ -0,0 +1,184 @@
# Modern payment API
[Project overview](../README.md) | [Configuration](configuration.md) | [Operations](operations.md)
Hardlink owns CMS provider selection and all provider-specific processing. Operafyne and checkinfyne use only `POST /api/payment/sale` and `POST /api/payment/preauth`. Deploy matching versions together; older modern-endpoint request/result formats are no longer supported. The deprecated `/takepayment` and `/takepreauth` contracts and execution cores are unchanged.
| Endpoint | Request | Purpose |
| --- | --- | --- |
| `POST /api/payment/sale` | JSON integer minor units | Provider-independent Sale |
| `POST /api/payment/preauth` | JSON integer minor units | CreditCall PREAUTH/account verification or Trust positive PREAUTH |
| `POST /takepayment` | `text/xml` | Retained legacy CreditCall Sale; not used by Fyne |
| `POST /takepreauth` | `text/xml` | Retained legacy CreditCall PREAUTH/account verification; not used by Fyne |
## Request
Both endpoints accept JSON with integer minor units:
```json
{"reference":"SYNTH-BOOK","amount":2500,"currency":"GBP","checkoutDate":"2026-11-04 00:00:00 +0000"}
```
`reference` and `checkoutDate` are optional. Currency comes from the existing CMS hotel response. Startup supplies CMS currency to the selected service; no dedicated local currency setting exists. The currency is bookkeeping data, not evidence of terminal settlement currency. Trust does not transmit or validate provider currency.
A Sale that requires a later mandatory hold includes its prerequisite:
```json
{"reference":"SYNTH-BOOK","amount":10000,"currency":"GBP","requiredPreauth":{"amount":2500,"checkoutDate":"2026-11-04 00:00:00 +0000"}}
```
Hardlink validates that the selected provider supports that hold before dispatching the Sale. This field does not start PREAUTH. CreditCall supports positive PREAUTH and zero-amount account verification. Trust supports positive Sale/PREAUTH. The current Dojo and PayBridge implementations support Sale only and reject PREAUTH without dispatching a transaction.
## Stream
The response is `application/x-ndjson`. Progress is observational:
```json
{"type":"status","code":"PAYMENT_PROCESSING"}
{"type":"result","result":{"outcome":"approved","httpStatus":200,"retryable":false,"provider":"creditcall","amountMinor":2500,"currencyCode":"GBP","transactionReference":"SYNTH-REFERENCE","cardType":"Visa","maskedCardNumber":"************1133"}}
```
Every provider uses `result`; there is no redirect URL or `response` variant. Outcomes are `approved`, `declined`, `cancelled`, `timeout`, `error` and `unknown`. Definitive declines/cancellations, confirmed signature rejection and known pre-dispatch terminal-session unavailability retain their existing guest retry eligibility. A timeout, malformed result, connection loss, Dojo `Expired` or other unresolved post-dispatch result is `unknown` and requires reception review. Progress codes never establish approval or retry eligibility.
Hardlink returns real normalized card metadata: masked card number, card type, expiry, transaction reference, card hash and card reference, where available. Receipt number, sequence, authorization code and last four remain separate optional metadata. Authorization codes are not card hashes; card type plus last four is not a card reference. Unmasked PAN is omitted rather than encoded or sent to the kiosk.
CreditCall reports a valid returned `TOTAL_AMOUNT` as the actual terminal amount. If the field is absent, its existing approved-request amount contract is retained. A malformed, negative or out-of-range returned amount produces non-retryable uncertainty. Fyne's existing exact-amount guard sends a request/result mismatch to reception rather than treating the requested amount as the actual hold. CreditCall's legacy transaction and SQL-persistence code is unchanged.
Hardlink prints terminal receipts within provider execution. Fyne constructs complete PMS payment descriptions locally; Hardlink does not return PMS descriptions or add kiosk/Pay/Pre prefixes.
## Transaction ownership
The existing `paymentsvc` busy guard admits one modern Sale or PREAUTH at a time. There is no queue, durable terminal journal or recovery API. A detached transaction worker executes independently of HTTP disconnects and progress backpressure. The bounded progress queue may drop hints; final outcome has its own channel. Only the handler writes NDJSON.
The shared worker budget is configured `timeoutSeconds` (default 300) plus a 15-second status/delivery margin. Trust retains one financial POST bounded to 300 seconds and at most one same-reference `/status` lookup bounded to 15 seconds. CreditCall retains its separate 300-second start and confirmation call bounds; its existing confirmation and asynchronous PREAUTH persistence are not shortened by the shared response budget. Dojo and PayBridge retain their existing protocol exchanges and internal connection timeouts.
Printing/finalization continues after kiosk disconnect. A restart or disconnected process can nevertheless lose approval before kiosk capture. Reception must reconcile those transactions. No cross-restart terminal deduplication or automatic guest Check-In resumption is claimed. Existing Fyne approved-payment capture and ten-minute PMS fallback remain independent and unchanged.
## Reconciliation diagnostics
Dojo and PayBridge record provider-boundary warnings when transport fails or a result remains uncertain, including when no result object is returned. The structured fields include `provider`, `operation`, `stage`, `request_id`, the existing `transaction_reference` mapping, and a safe `error_category`. Known payment-intent, terminal-session, provider-transaction and provider-reference identifiers are included separately. A locally generated request/reference is not proof of provider receipt or approval.
Categories distinguish timeout, cancellation, connection failure, response loss, invalid response and unresolved/provider errors. HTTP status and WebSocket close codes are included where available. Raw error strings, response bodies, gateway query credentials, JWTs and card data are excluded. These diagnostics do not alter returned results/errors, retry eligibility, the NDJSON contract or financial dispatch.
Trust configuration/initialization failures use the existing fatal email-notification mechanism. The common provider-enabled startup message covers CreditCall, Trust, Dojo and PayBridge. No new configuration or notification system is required.
The shared client package is `gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi`; progress codes are in `/v2/paymentstatus`. Deploy compatible Hardlink and Fyne revisions together. Publish the actual v2 tag before replacing the Fyne local-validation marker and regenerating module sums. The application build version alone is not a dependency pin. See [operations](operations.md#coordinated-application-releases).
## Offline validation
Provider tests use loopback/in-memory transports; handler tests block default network access and inject fake printing. `internal/mail/Test_SendMail` is a pre-existing live-email test and must be excluded from offline runs. CreditCall PREAUTH persistence uses the established 96-hour release offset after the stored departure midnight; its characterization test asserts that contract without changing the returned terminal amount. The dispenser caller-deadline regression counts complete AP observations rather than partial ACK reads. Neither regression is excluded from the relevant suites.
## Native HTTP clients
Modern Sale/PREAUTH routes do not provide browser CORS headers or OPTIONS preflight handling. POST and the unified NDJSON contract are unchanged; non-POST requests use the existing 405 structured rejection. This does not alter deprecated `/takepayment` or `/takepreauth`, provider execution after disconnect, or the ChipDNA `/logerror` integration.
## CreditCall streaming and PREAUTH
This section preserves the ChipDNA integration contract separately from the
provider-independent Fyne wire format. Deploy compatible ChipDNAClientCLI,
Hardlink and Fyne binaries in one maintenance window. The unified wire contract
does not require a CreditCall SQL-schema migration.
### ChipDNAClientCLI contract
Both modern endpoints use the common request/result contract above. A positive CreditCall `/api/payment/preauth` amount maps internally to the existing unconfirmed `Sale`; zero maps to `AccountVerification`.
Hardlink calls `POST /start-transaction-stream/` on ChipDNAClientCLI with
`{"amount":"1234","transactionType":"Sale"}`. Its NDJSON consists of allowlisted
`status` frames (`source`, `value`), a single `result` containing allowlisted SDK
fields, or a sanitized `error`. `TRANSACTION_TYPE` and optional `TOTAL_AMOUNT`
are included only when returned by the provider. They are never synthesized and
are not forwarded as raw SDK fields to the kiosk. A valid `TOTAL_AMOUNT` is
normalized into `amountMinor` as described above. AccountVerification normally omits
`TOTAL_AMOUNT`. Receipt XML may be a JSON string field needed by
hardlink's existing receipt handler; it is never a raw line in the stream.
SALE confirmation continues through the existing, separate XML endpoint.
### Lifetime, confirmation and progress
- `/start-transaction/`, `/takepayment`, and `/takepreauth` retain their existing
external contracts. Both SALE and PREAUTH stream to the native Fyne clients;
existing SQL persistence/release behavior remains unchanged.
- Both Fyne applications use the common private 330-second terminal client for SALE and PREAUTH.
This is only the kiosk wait boundary for all providers.
Timeout/cancellation is technical, not an authoritative decline or automatically
retryable result. It never triggers a second start or legacy endpoint fallback.
- Validation uses the inbound request. At financial dispatch handoff, hardlink
detaches cancellation with `context.WithoutCancel`. Inbound cancellation and
write failures control only delivery; result processing, SALE confirmation,
receipts and PREAUTH persistence scheduling continue independently.
- Start and each SALE confirmation call retain their independent 300-second timeout.
Confirmation still uses two attempts, retrying transport/read errors with the
existing two-second delay. The generic whole-operation timeout is not used.
- Kiosk cancellation or failed/blocked kiosk delivery does not cancel upstream reading,
confirmation, receipt handling, or PREAUTH persistence scheduling. Progress queues may drop hints when full;
final results have a separate slot and are delivered at most once.
- Only the response writer writes frames. Transaction execution never waits
for progress delivery. No additional delivery timer or whole-operation deadline
shortens the existing HTTP call bounds.
- Native SDK 3.17 updates use `UPDATE`; card notifications use `NOTIFICATION`,
retained as `CARD_STATUS` on the internal wire. Normal progress does not require
a reference: it is accepted only inside the existing serial transaction's active
observational window. A supplied nonempty reference must match. The window opens
immediately before the SDK start call and closes immediately at
`TransactionFinished`; finalization never waits for card removal.
- `CardRemovalRequested` and `CardRemovalEnforced` follow the same active-window
rule as other progress, including when no reference is supplied. Real Miura
insertion-recovery sequences can repeat present-card and remove-card prompts
within one transaction; these repeated prompts are not deduplicated. Outside
the active window they are discarded. `Removed` remains omitted even with a
reference, and the existing `Inserted` mapping is unchanged.
- Ownership is best-effort UI observation. SDK 3.17 does not establish that every
queued reference-less callback, including removal, has drained before another transaction
starts. Such a callback may briefly display stale progress in a later active
window. This accepted limitation must never affect success, decline, cancellation,
timeout outcomes, confirmation, retry, receipts, PMS posting, or business state.
- After timeout, an ambiguous start error, an asynchronous SDK error during an
active window, or reference reuse/overlap, progress remains suppressed for that
`Client` lifetime across SALE and PREAUTH. New transactions, elapsed time, callbacks and automatic
reconnect do not reset the guard. Payments remain enabled.
- Only the exact synchronous `ClientNotConnectedToServer` error safely clears an
unsuppressed window and releases its unused reference: SDK 3.17 `StartCommand`
returns it before `SendRequest`. Validation errors, mixed errors and all other
unproven errors suppress observation. Safe pre-dispatch rejection never clears
an existing suppression latch.
- Progress cannot approve, decline, confirm, cancel, or retry a transaction.
`OnlineAuthCompleted` means waiting; `Removed` and unknown events are omitted.
### Persistence and release
Approved monetary PREAUTH schedules the existing asynchronous SQL persistence,
with spool handling on persistence failures. Account verification follows the
existing `PreauthDecision` without inventing `TOTAL_AMOUNT`. The stored departure
midnight plus 96 hours determines the release date. The separate
`hardlink-preauth-release` executable releases due CreditCall holds; the HTTP
service does not run that task automatically. Trust PREAUTH is not inserted into
the CreditCall SQL release workflow.
### Verification and physical acceptance
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 both Fyne applications, use their guarded offline terminal, posting and
fallback regression suites. Verify the shared `paymentapi` Sale/PREAUTH decoder,
common 330-second terminal client, cancellation after dispatch, uncertain-result
handling, retry limits and normal/fallback description parity. There is no
provider-specific Fyne parser or legacy `response` frame. Opera and Guestline
retain their separate financial and PMS posting workflows; follow each
application's current verification instructions.
Earlier integration notes recorded approved `ACCOUNT VERIFICATION` with no
`TOTAL_AMOUNT`. An earlier monetary `/takepayment` test recorded returned minor
units; positive PREAUTH through the modern transport still needs physical Miura
validation. Automated tests do not replace that check. Receipt fields such as
`NoChargeDeclaration` retain the existing provider-entry rendering behavior.
This documentation reorganization did not execute SDK, terminal or hardware tests.
+1 -1
View File
@@ -1,4 +1,4 @@
module gitea.futuresens.co.uk/futuresens/hardlink module gitea.futuresens.co.uk/futuresens/hardlink/v2
go 1.23.2 go 1.23.2
+4 -4
View File
@@ -6,10 +6,10 @@ import (
"os" "os"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/bootstrap" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/bootstrap"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/logging" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/logging"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+2 -2
View File
@@ -4,8 +4,8 @@ package bootstrap
import ( import (
"database/sql" "database/sql"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/db"
) )
func OpenDB(cfg *config.ConfigRec) (*sql.DB, error) { func OpenDB(cfg *config.ConfigRec) (*sql.DB, error) {
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"strings" "strings"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/logging" "gitea.futuresens.co.uk/futuresens/logging"
) )
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"strings" "strings"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
_ "github.com/denisenkom/go-mssqldb" _ "github.com/denisenkom/go-mssqldb"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+2 -2
View File
@@ -11,8 +11,8 @@ import (
"strings" "strings"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/db"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+1 -1
View File
@@ -3,7 +3,7 @@ package creditcall
import ( import (
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
) )
func TestPreauthLegacyDecision(t *testing.T) { func TestPreauthLegacyDecision(t *testing.T) {
+1 -1
View File
@@ -1,6 +1,6 @@
package creditcall package creditcall
import "gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" import "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
// ProgressStatus maps informational SDK events, never financial decisions. // ProgressStatus maps informational SDK events, never financial decisions.
func ProgressStatus(source, value string) string { func ProgressStatus(source, value string) string {
+1 -1
View File
@@ -1,7 +1,7 @@
package creditcall package creditcall
import ( import (
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
"testing" "testing"
) )
+1 -1
View File
@@ -12,7 +12,7 @@ import (
mssqldb "github.com/denisenkom/go-mssqldb" // for error inspection mssqldb "github.com/denisenkom/go-mssqldb" // for error inspection
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
) )
// InitMSSQL opens and pings the SQL Server instance (keeps your original behaviour) // InitMSSQL opens and pings the SQL Server instance (keeps your original behaviour)
+5 -5
View File
@@ -13,11 +13,11 @@ import (
"strings" "strings"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+2 -2
View File
@@ -11,8 +11,8 @@ import (
"sync/atomic" "sync/atomic"
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/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"}` 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"}`
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
logtest "github.com/sirupsen/logrus/hooks/test" logtest "github.com/sirupsen/logrus/hooks/test"
) )
+1 -1
View File
@@ -1,7 +1,7 @@
package dojo package dojo
import ( import (
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"testing" "testing"
) )
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"os" "os"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/mail"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
) )
func TestCardRoutesNeverExecuteStoredCommandAfterBuildFailure(t *testing.T) { func TestCardRoutesNeverExecuteStoredCommandAfterBuildFailure(t *testing.T) {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
) )
func TestCreditCallModernPreauthReportsActualReturnedAmount(t *testing.T) { func TestCreditCallModernPreauthReportsActualReturnedAmount(t *testing.T) {
+118
View File
@@ -0,0 +1,118 @@
package handlers
import (
"context"
"errors"
"net"
"net/url"
"strings"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
)
// creditCallDiagnostic carries allowlisted observations, never financial evidence.
type creditCallDiagnostic struct {
reason string
cause string
}
func (diagnostic creditCallDiagnostic) apply(final *paymentapi.Result) {
if diagnostic.reason == "" || final.Reason != "" {
return
}
switch final.Outcome {
case "unknown":
final.Message = "Payment outcome uncertain: " + diagnostic.cause + "; contact reception"
case "declined":
final.Message = "Transaction declined: " + diagnostic.cause
case "cancelled":
final.Message = "Transaction cancelled: " + diagnostic.cause
default:
return
}
final.Reason = diagnostic.reason
}
func creditCallInitialDiagnostic(result creditcall.TransactionResultXML) creditCallDiagnostic {
transactionResult, sdkError := creditCallDiagnosticFieldsFromEntries(result.Entries)
switch strings.ToLower(transactionResult) {
case types.ResultApproved:
return creditCallDiagnostic{}
case "timeout":
return creditCallDiagnostic{reason: "cli_timeout", cause: "CLI wait expired"}
}
if recognizedCreditCallSDKError(sdkError) {
return creditCallDiagnostic{reason: "sdk_" + sdkError, cause: sdkError}
}
return creditCallDiagnostic{}
}
func creditCallConfirmationErrorDiagnostic(err error) creditCallDiagnostic {
var networkError net.Error
if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &networkError) && networkError.Timeout()) {
return creditCallDiagnostic{reason: "confirmation_timeout", cause: "ConfirmTransaction timed out"}
}
var requestError *url.Error
if errors.As(err, &requestError) {
return creditCallDiagnostic{reason: "confirmation_request_error", cause: "ConfirmTransaction request failed"}
}
return creditCallDiagnostic{reason: "confirmation_response_read_error", cause: "ConfirmTransaction response could not be read"}
}
func creditCallConfirmationResultDiagnostic(entries []creditcall.EntryXML, invalidXML bool) creditCallDiagnostic {
if invalidXML {
return creditCallDiagnostic{reason: "confirmation_invalid_response", cause: "ConfirmTransaction response is invalid"}
}
transactionResult, sdkError := creditCallDiagnosticFieldsFromEntries(entries)
if recognizedCreditCallSDKError(sdkError) {
return creditCallDiagnostic{reason: "confirmation_sdk_" + sdkError, cause: "ConfirmTransaction: " + sdkError}
}
result := strings.ToLower(transactionResult)
if result == types.ResultError && strings.HasPrefix(sdkError, "ConfirmTransaction failed:") {
return creditCallDiagnostic{reason: "confirmation_cli_error", cause: "ConfirmTransaction CLI failed"}
}
switch result {
case "canceled", "cancelled":
result = "cancelled"
case types.ResultDeclined, types.ResultError, "timeout":
default:
result = "unknown"
}
return creditCallDiagnostic{reason: "confirmation_result_" + result, cause: "ConfirmTransaction result " + result}
}
func creditCallDiagnosticFieldsFromEntries(entries []creditcall.EntryXML) (transactionResult, sdkError string) {
for _, entry := range entries {
switch entry.Key {
case types.TransactionResult:
transactionResult = entry.Value
case types.Errors:
sdkError = entry.Value
}
}
return transactionResult, sdkError
}
// recognizedCreditCallSDKError matches exact symbolic names from the bundled
// ChipDNA SDK 3.17 transaction error types. Descriptions and numeric/compound
// errors are deliberately excluded; numeric values overlap between SDK types.
func recognizedCreditCallSDKError(code string) bool {
switch code {
case "ChipCardRemoved", "ClientNotConnectedToServer", "NoPinPadsAvailable", "AmountTooLarge", "AmountTooSmall",
"NoPinPadsConfigured", "PaymentDeviceUnavailable", "PaymentDeviceNotInitialized", "PinpadConnectionClosed",
"PinPadTransactionTerminated", "EposTransactionTerminated", "TransactionProcessingError", "TransactionInProgress",
"TransactionAlreadyInProgressError", "TransactionNotStarted", "MissingParameter", "InvalidParameter", "InvalidValue",
"UnexpectedParameters", "AmountZeroNotAllowed", "AmountInvalid", "AmountMissing",
"ReferenceAlreadyExistsForApprovedTransaction", "PinPadAmountInvalid", "PinpadAmountTooLarge",
"TransactionReferenceMissing", "TransactionReferenceEmpty", "TransactionForConfirmVoidNotFound", "TransactionNotFound",
"TransactionAlreadyConfirmed", "TransactionOriginallyDeclined", "TransactionNotCommitted", "ConfirmRequestFailed",
"ConfirmAccountVerificationNotAllowed", "ConfirmLinkedRefundNotAllowed", "RemoteServerAccessFailed",
"ServerCommunicationError", "ServerRequestError", "ServerResponseError", "NoResponseFromServer", "TemporarilyUnavailable",
"ChipCardBlocked", "ChipReadFailure", "SwipeReadFailure", "ExpiredCard", "BadCard", "CardSchemeNotSupported", "CardUsageExceeded",
"PinPadUserCancelled", "CardHolderActionTimedOut":
return true
}
return false
}
@@ -0,0 +1,563 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"reflect"
"strings"
"testing"
"time"
"gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
)
// This contract list is independent of the production allowlist.
var creditCallDiagnosticSDKFixtures = []string{
"ChipCardRemoved", "ClientNotConnectedToServer", "NoPinPadsAvailable", "AmountTooLarge", "AmountTooSmall",
"NoPinPadsConfigured", "PaymentDeviceUnavailable", "PaymentDeviceNotInitialized", "PinpadConnectionClosed",
"PinPadTransactionTerminated", "EposTransactionTerminated", "TransactionProcessingError", "TransactionInProgress",
"TransactionAlreadyInProgressError", "TransactionNotStarted", "MissingParameter", "InvalidParameter", "InvalidValue",
"UnexpectedParameters", "AmountZeroNotAllowed", "AmountInvalid", "AmountMissing",
"ReferenceAlreadyExistsForApprovedTransaction", "PinPadAmountInvalid", "PinpadAmountTooLarge",
"TransactionReferenceMissing", "TransactionReferenceEmpty", "TransactionForConfirmVoidNotFound", "TransactionNotFound",
"TransactionAlreadyConfirmed", "TransactionOriginallyDeclined", "TransactionNotCommitted", "ConfirmRequestFailed",
"ConfirmAccountVerificationNotAllowed", "ConfirmLinkedRefundNotAllowed", "RemoteServerAccessFailed",
"ServerCommunicationError", "ServerRequestError", "ServerResponseError", "NoResponseFromServer", "TemporarilyUnavailable",
"ChipCardBlocked", "ChipReadFailure", "SwipeReadFailure", "ExpiredCard", "BadCard", "CardSchemeNotSupported", "CardUsageExceeded",
"PinPadUserCancelled", "CardHolderActionTimedOut",
}
type creditCallDiagnosticFixture struct {
name, operation string
initial, confirmation map[string]string
startFailure, confirmFailure string
confirmationXML string
emptyConfirmation bool
correctedConfirmation bool
recoverConfirmation bool
zero bool
reason, message string
}
func creditCallDiagnosticFields(result, sdkError string) map[string]string {
return map[string]string{
types.TransactionResult: result, types.Errors: sdkError, types.TransactionType: "SALE",
types.Reference: "SYNTH-STAGE2", types.TotalAmount: "1234", types.ReceiptDataCardholder: "synthetic initial receipt",
types.CardType: "Visa", types.PanMasked: "************1133", types.ExpiryDate: "1230",
types.CardHash: "synthetic-hash", types.CardReference: "synthetic-card-reference",
}
}
func creditCallDiagnosticFixtures() []creditCallDiagnosticFixture {
var fixtures []creditCallDiagnosticFixture
for _, operation := range []string{"sale", "preauth"} {
for _, result := range []string{"ERROR", "DECLINED", "UNKNOWN", "CANCELLED", "TIMEOUT", "", "APPROVED"} {
for _, code := range creditCallDiagnosticSDKFixtures {
fixture := creditCallDiagnosticFixture{
name: operation + "/initial_" + result + "/" + code, operation: operation,
initial: creditCallDiagnosticFields(result, code), reason: "sdk_" + code,
message: "Payment outcome uncertain: " + code + "; contact reception",
}
switch result {
case "APPROVED":
fixture.reason, fixture.message = "", "Payment approved"
case "TIMEOUT":
fixture.reason, fixture.message = "cli_timeout", "Payment outcome uncertain: CLI wait expired; contact reception"
case "DECLINED":
fixture.message = "Transaction declined: " + code
case "CANCELLED":
fixture.message = "Transaction cancelled: " + code
}
if result == "" || result == "ERROR" || result == "DECLINED" {
if code == "PinPadUserCancelled" {
fixture.reason, fixture.message = "user_cancelled", "Transaction cancelled"
}
if code == "CardHolderActionTimedOut" {
fixture.reason, fixture.message = "cardholder_timeout", "Cardholder action timed out"
}
}
fixtures = append(fixtures, fixture)
}
}
for _, result := range []string{"ERROR", "DECLINED", "UNKNOWN", "CANCELLED", "TIMEOUT", ""} {
for _, unknown := range []struct{ name, code string }{
{"absent", ""}, {"unrecognized", "DeviceUnavailable"}, {"issuer", "InsufficientFunds"}, {"numeric", "500005"},
{"compound", "ChipCardRemoved,AmountTooSmall"}, {"whitespace", " ChipCardRemoved"},
{"case", "chipcardremoved"}, {"secret", "token=SYNTHETIC-SECRET; PAN=4111111111111111"},
} {
fixture := creditCallDiagnosticFixture{name: operation + "/fallback_" + result + "/" + unknown.name,
operation: operation, initial: creditCallDiagnosticFields(result, unknown.code),
message: "Payment outcome uncertain; contact reception"}
fixture.initial[types.ErrorDescription] = "ChipCardRemoved SYNTHETIC-SECRET"
switch result {
case "DECLINED":
fixture.message = "Transaction declined"
case "CANCELLED":
fixture.message = "Transaction cancelled"
case "TIMEOUT":
fixture.reason, fixture.message = "cli_timeout", "Payment outcome uncertain: CLI wait expired; contact reception"
}
fixtures = append(fixtures, fixture)
}
}
for _, failure := range []string{"transport", "incomplete", "malformed", "error_frame", "unknown_frame"} {
fixtures = append(fixtures, creditCallDiagnosticFixture{name: operation + "/start/" + failure, operation: operation,
initial: creditCallDiagnosticFields("ERROR", "ChipCardRemoved"), startFailure: failure,
message: "Payment outcome uncertain; contact reception"})
}
missing := creditCallDiagnosticFields("ERROR", "AmountTooSmall")
delete(missing, types.TransactionResult)
fixtures = append(fixtures, creditCallDiagnosticFixture{name: operation + "/missing_result", operation: operation, initial: missing,
reason: "sdk_AmountTooSmall", message: "Payment outcome uncertain: AmountTooSmall; contact reception"})
}
for _, code := range creditCallDiagnosticSDKFixtures {
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_sdk/" + code, operation: "sale",
initial: creditCallDiagnosticFields("APPROVED", "AmountTooLarge"),
confirmation: map[string]string{types.TransactionResult: "ERROR", types.Errors: code, types.ReceiptDataCardholder: "synthetic confirmation receipt"},
reason: "confirmation_sdk_" + code, message: "Payment outcome uncertain: ConfirmTransaction: " + code + "; contact reception"})
}
for _, result := range []string{"DECLINED", "CANCELLED", "CANCELED", "ERROR", "TIMEOUT", "UNKNOWN", ""} {
suffix := strings.ToLower(result)
if suffix == "canceled" {
suffix = "cancelled"
}
if suffix == "" || suffix == "unknown" {
suffix = "unknown"
}
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_result/" + result, operation: "sale",
initial: creditCallDiagnosticFields("APPROVED", "ChipCardRemoved"),
confirmation: map[string]string{types.TransactionResult: result}, reason: "confirmation_result_" + suffix,
message: "Payment outcome uncertain: ConfirmTransaction result " + suffix + "; contact reception"})
}
for _, failure := range []struct{ name, reason, cause string }{
{"deadline", "confirmation_timeout", "ConfirmTransaction timed out"},
{"timeout", "confirmation_timeout", "ConfirmTransaction timed out"},
{"request", "confirmation_request_error", "ConfirmTransaction request failed"},
{"read", "confirmation_response_read_error", "ConfirmTransaction response could not be read"},
} {
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_failure/" + failure.name, operation: "sale",
initial: creditCallDiagnosticFields("APPROVED", ""), confirmFailure: failure.name,
reason: failure.reason, message: "Payment outcome uncertain: " + failure.cause + "; contact reception"})
}
for _, failure := range []string{"request", "read"} {
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_recovers/" + failure, operation: "sale",
initial: creditCallDiagnosticFields("APPROVED", ""), confirmFailure: failure, recoverConfirmation: true, message: "Payment approved"})
}
const approvedEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value>APPROVED</Value></Entry>"
const declinedEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value>DECLINED</Value></Entry>"
const errorEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value>ERROR</Value></Entry>"
const emptyEntry = "<Entry><Key>TRANSACTION_RESULT</Key><Value></Value></Entry>"
for _, response := range []struct {
name, xml, reason, cause string
corrected bool
}{
{"mixed_case", "<TransactionResult><Entry><Key>TRANSACTION_RESULT</Key><Value>aPpRoVeD</Value></Entry></TransactionResult>", "", "", false},
{"omitted", "<TransactionResult/>", "confirmation_result_unknown", "ConfirmTransaction result unknown", true},
{"empty_body", "", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
{"whitespace_body", " \r\n\t", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
{"malformed_retains_approval", "<TransactionResult><Entry>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
{"malformed_after_approved", "<TransactionResult>" + approvedEntry + "<Entry>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
{"malformed_after_error", "<TransactionResult><Entry><Key>TRANSACTION_RESULT</Key><Value>ERROR</Value></Entry><Entry>",
"confirmation_invalid_response", "ConfirmTransaction response is invalid", false},
{"malformed_after_declined", "<TransactionResult>" + declinedEntry + "<Entry>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", false},
{"wrong_root", "<Unexpected/>", "confirmation_invalid_response", "ConfirmTransaction response is invalid", true},
{"sdk_only_disconnected", "<TransactionResult><Entry><Key>ERRORS</Key><Value>ClientNotConnectedToServer</Value></Entry></TransactionResult>",
"confirmation_sdk_ClientNotConnectedToServer", "ConfirmTransaction: ClientNotConnectedToServer", true},
{"sdk_only_not_found", "<TransactionResult><Entry><Key>ERRORS</Key><Value>TransactionNotFound</Value></Entry></TransactionResult>",
"confirmation_sdk_TransactionNotFound", "ConfirmTransaction: TransactionNotFound", true},
{"duplicate_approved_declined", "<TransactionResult>" + approvedEntry + declinedEntry + "</TransactionResult>",
"confirmation_result_declined", "ConfirmTransaction result declined", false},
{"duplicate_declined_approved", "<TransactionResult>" + declinedEntry + approvedEntry + "</TransactionResult>", "", "", false},
{"duplicate_error_approved", "<TransactionResult>" + errorEntry + approvedEntry + "</TransactionResult>", "", "", false},
{"duplicate_approved_empty", "<TransactionResult>" + approvedEntry + emptyEntry + "</TransactionResult>",
"confirmation_result_unknown", "ConfirmTransaction result unknown", false},
{"duplicate_empty_approved", "<TransactionResult>" + emptyEntry + approvedEntry + "</TransactionResult>", "", "", false},
{"duplicate_approved_error", "<TransactionResult>" + approvedEntry + errorEntry + "</TransactionResult>",
"confirmation_result_error", "ConfirmTransaction result error", false},
} {
message := "Payment approved"
if response.reason != "" {
message = "Payment outcome uncertain: " + response.cause + "; contact reception"
}
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_xml/" + response.name, operation: "sale",
initial: creditCallDiagnosticFields("APPROVED", "ChipCardRemoved"), confirmationXML: response.xml,
emptyConfirmation: response.xml == "", correctedConfirmation: response.corrected, reason: response.reason, message: message})
}
for _, metadata := range []string{"returned_amount", "overrides", "empty_overrides"} {
fields := creditCallDiagnosticFields("APPROVED", "")
fields[types.TotalAmount] = "3100"
confirmation := map[string]string{types.TransactionResult: "APPROVED"}
if metadata == "overrides" {
confirmation[types.Reference], confirmation[types.TotalAmount] = "SYNTH-CONFIRMATION", "2500"
confirmation[types.CardType], confirmation[types.PanMasked] = "Mastercard", "************7788"
confirmation[types.ExpiryDate], confirmation[types.CardReference] = "1231", "synthetic-confirmation-card"
confirmation[types.ReceiptDataCardholder] = "synthetic confirmation receipt"
}
if metadata == "empty_overrides" {
confirmation[types.ExpiryDate], confirmation[types.CardHash], confirmation[types.ReceiptDataCardholder] = "", "", ""
}
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/confirmation_metadata/" + metadata, operation: "sale",
initial: fields, confirmation: confirmation, message: "Payment approved"})
}
for _, code := range []string{"ConfirmTransaction failed: SYNTHETIC-SECRET PAN=4111111111111111", "ChipCardRemoved,SYNTHETIC-SECRET", "500005", "chipcardremoved"} {
reason, cause := "confirmation_result_error", "ConfirmTransaction result error"
name := "fallback_" + code
if strings.HasPrefix(code, "ConfirmTransaction failed:") {
reason, cause, name = "confirmation_cli_error", "ConfirmTransaction CLI failed", "cli_exception"
}
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "sale/" + name, operation: "sale",
initial: creditCallDiagnosticFields("APPROVED", ""), confirmation: map[string]string{types.TransactionResult: "ERROR", types.Errors: code},
reason: reason, message: "Payment outcome uncertain: " + cause + "; contact reception"})
}
for _, result := range []string{"APPROVED", "ERROR"} {
fields := creditCallDiagnosticFields(result, "ChipCardRemoved")
fields[types.TransactionType], fields[types.TotalAmount] = "ACCOUNT VERIFICATION", ""
reason, message := "sdk_ChipCardRemoved", "Payment outcome uncertain: ChipCardRemoved; contact reception"
if result == "APPROVED" {
reason, message = "", "Payment approved"
}
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "preauth/verification/" + result, operation: "preauth",
initial: fields, zero: true, reason: reason, message: message})
}
fields := creditCallDiagnosticFields("APPROVED", "ChipCardRemoved")
fields[types.TransactionType] = "Refund"
fixtures = append(fixtures, creditCallDiagnosticFixture{name: "preauth/unrecognized_approved_type", operation: "preauth", initial: fields,
message: "Payment outcome uncertain; contact reception"})
for _, operation := range []string{"sale", "preauth"} {
fields := creditCallDiagnosticFields("APPROVED", "ChipCardRemoved")
fields[types.TotalAmount], fields[types.TransactionType] = "invalid", "ACCOUNT VERIFICATION"
fixtures = append(fixtures, creditCallDiagnosticFixture{name: operation + "/amount_unverified", operation: operation, initial: fields,
reason: "amount_unverified", message: "Payment amount uncertain; contact reception"})
}
return fixtures
}
type creditCallDiagnosticRequest struct {
Method, Path, Body string
FreshCallDeadline bool
}
type creditCallDiagnosticObservation struct {
HTTPStatus int
Final *paymentapi.Result `json:",omitempty"`
Legacy *cmstypes.ResponseRec `json:",omitempty"`
Progress []string
Requests []creditCallDiagnosticRequest
Receipts []string
Persistence map[string]any
PersistenceCount int32
PersistenceTimeValid bool
BodiesClosed []bool
RetryDelayKept bool
}
type creditCallDiagnosticBody struct {
io.Reader
err error
closed bool
}
func (b *creditCallDiagnosticBody) Read(p []byte) (int, error) {
if b.err != nil {
return 0, b.err
}
return b.Reader.Read(p)
}
func (b *creditCallDiagnosticBody) Close() error { b.closed = true; return nil }
type creditCallDiagnosticTimeout struct{}
func (creditCallDiagnosticTimeout) Error() string { return "SYNTHETIC-SECRET timeout" }
func (creditCallDiagnosticTimeout) Timeout() bool { return true }
func (creditCallDiagnosticTimeout) Temporary() bool { return true }
func captureCreditCallDiagnostic(t *testing.T, fixture creditCallDiagnosticFixture, legacy bool) creditCallDiagnosticObservation {
t.Helper()
started := time.Now()
observation := creditCallDiagnosticObservation{RetryDelayKept: true}
app := &App{isPayment: true, cfg: &config.ConfigRec{TimeoutSeconds: 1}, creditCallReceipt: func(receipt string) {
observation.Receipts = append(observation.Receipts, receipt)
}}
database := preauthTestDatabase(t, app)
var bodies []*creditCallDiagnosticBody
var confirmations []time.Time
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
payload, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("read synthetic %s request: %v", fixture.name, err)
}
deadline, ok := r.Context().Deadline()
observation.Requests = append(observation.Requests, creditCallDiagnosticRequest{r.Method, r.URL.Path, string(payload), ok && time.Until(deadline) > 299*time.Second})
body := &creditCallDiagnosticBody{}
if r.URL.Path == "/confirm-transaction/" {
confirmations = append(confirmations, time.Now())
failure := fixture.confirmFailure
if fixture.recoverConfirmation && len(confirmations) > 1 {
failure = ""
}
switch failure {
case "deadline":
return nil, context.DeadlineExceeded
case "timeout":
return nil, creditCallDiagnosticTimeout{}
case "request":
return nil, errors.New("SYNTHETIC-SECRET request failure")
case "read":
body.err = errors.New("SYNTHETIC-SECRET body failure")
}
fields := fixture.confirmation
if fields == nil {
fields = map[string]string{types.TransactionResult: "APPROVED", types.ReceiptDataCardholder: "synthetic confirmation receipt"}
}
xmlBody := fixture.confirmationXML
if xmlBody == "" && !fixture.emptyConfirmation {
xmlBody = chipDNAFixture(t, fields)
}
body.Reader = strings.NewReader(xmlBody)
} else {
if fixture.startFailure == "transport" {
return nil, errors.New("SYNTHETIC-SECRET start failure")
}
if legacy {
body.Reader = strings.NewReader(chipDNAFixture(t, fixture.initial))
} else {
frame, err := json.Marshal(map[string]any{"type": "result", "result": fixture.initial})
if err != nil {
t.Errorf("marshal synthetic %s frame: %v", fixture.name, err)
}
wire := string(frame) + "\n"
switch fixture.startFailure {
case "incomplete":
wire = string(frame)
case "malformed":
wire = "{SYNTHETIC-SECRET\n"
case "error_frame":
wire = "{\"type\":\"error\",\"message\":\"SYNTHETIC-SECRET\"}\n"
case "unknown_frame":
wire = "{\"type\":\"SYNTHETIC-SECRET\"}\n"
}
body.Reader = strings.NewReader("{\"type\":\"status\",\"source\":\"UPDATE\",\"value\":\"CardRequested\"}\n" + wire)
}
}
bodies = append(bodies, body)
// Confirmation HTTP status remains ignored when its body is readable.
status := http.StatusOK
if r.URL.Path == "/confirm-transaction/" {
status = http.StatusServiceUnavailable
}
return &http.Response{StatusCode: status, Body: body, Header: make(http.Header)}, nil
})
app.EnableCreditCallStreaming()
recorder := httptest.NewRecorder()
amount := "1234"
if fixture.zero {
amount = "0"
}
if legacy {
if fixture.operation == "preauth" {
app.takePreauthorization(recorder, preauthLegacyRequest(amount, "Sale", "2030-01-02 00:00:00 +0000"))
} else {
app.takePayment(recorder, saleRequest(false))
}
observation.Legacy = &cmstypes.ResponseRec{}
if err := json.Unmarshal(recorder.Body.Bytes(), observation.Legacy); err != nil {
t.Fatalf("decode %s legacy result: %v", fixture.name, err)
}
} else {
request := httptest.NewRequest(http.MethodPost, "/api/payment/"+fixture.operation,
strings.NewReader(`{"reference":"SYNTH-STAGE2","amount":`+amount+`,"currency":"GBP","checkoutDate":"2030-01-02 00:00:00 +0000"}`))
request.Header.Set("Content-Type", "application/json")
app.streamPayment(recorder, request, fixture.operation == "preauth")
for _, frame := range decodePaymentStream(t, recorder.Body) {
if frame.Result != nil {
if observation.Final != nil {
t.Errorf("%s emitted multiple final results", fixture.name)
}
observation.Final = frame.Result
} else {
observation.Progress = append(observation.Progress, frame.Code)
}
}
if observation.Final == nil {
t.Fatalf("%s emitted no final result", fixture.name)
}
for _, secret := range []string{"SYNTHETIC-SECRET", "4111111111111111", "<TransactionResult", "synthetic initial receipt"} {
if strings.Contains(recorder.Body.String(), secret) {
t.Errorf("%s exposed synthetic private marker %q in API response", fixture.name, secret)
}
}
}
observation.HTTPStatus = recorder.Code
if fixture.operation == "preauth" && fixture.startFailure == "" && fixture.initial[types.TransactionResult] == "APPROVED" && fixture.initial[types.TransactionType] == "SALE" {
observation.Persistence = waitPreauthInsert(t, database)
timestamp, ok := observation.Persistence["TxnDateTime"].(time.Time)
observation.PersistenceTimeValid = ok && timestamp.Location() == time.UTC && !timestamp.Before(started) && !timestamp.After(time.Now())
if !observation.PersistenceTimeValid {
t.Errorf("%s persisted TxnDateTime=%v, want current UTC time within this run", fixture.name, observation.Persistence["TxnDateTime"])
}
}
observation.PersistenceCount = database.count.Load()
for _, body := range bodies {
observation.BodiesClosed = append(observation.BodiesClosed, body.closed)
if !body.closed {
t.Errorf("%s left a response body open", fixture.name)
}
}
if len(confirmations) > 1 {
observation.RetryDelayKept = confirmations[1].Sub(confirmations[0]) >= 2*time.Second
}
if !observation.RetryDelayKept {
t.Errorf("%s confirmation retry delay was shorter than two seconds", fixture.name)
}
return observation
}
// This test uses only pre-existing interfaces, so the same fixtures run against
// the captured unmodified production source and the diagnostic implementation.
func TestCreditCallDiagnosticParityCapture(t *testing.T) {
observations := map[string]creditCallDiagnosticObservation{}
corrections := map[string]creditCallDiagnosticFixture{}
for _, fixture := range creditCallDiagnosticFixtures() {
if fixture.correctedConfirmation {
corrections[fixture.name] = fixture
corrections["legacy/"+fixture.name] = fixture
}
t.Run(fixture.name, func(t *testing.T) {
observations[fixture.name] = captureCreditCallDiagnostic(t, fixture, false)
})
}
// Legacy observations use the same explicitly allowed correction cases.
for _, fixture := range creditCallDiagnosticFixtures() {
if fixture.startFailure != "" || fixture.zero || fixture.confirmFailure != "" {
continue
}
t.Run("legacy/"+fixture.name, func(t *testing.T) {
observations["legacy/"+fixture.name] = captureCreditCallDiagnostic(t, fixture, true)
})
}
if baseline := os.Getenv("HARDLINK_CREDITCALL_DIAGNOSTIC_BASELINE"); baseline != "" {
data, err := os.ReadFile(baseline)
if err != nil {
t.Fatal(err)
}
var before map[string]creditCallDiagnosticObservation
if err := json.Unmarshal(data, &before); err != nil {
t.Fatal(err)
}
// Round-trip current observations to match interface-valued SQL argument types.
data, err = json.Marshal(observations)
if err != nil {
t.Fatal(err)
}
var after map[string]creditCallDiagnosticObservation
if err := json.Unmarshal(data, &after); err != nil {
t.Fatal(err)
}
if len(before) != len(after) {
t.Errorf("capture cases=%d, want baseline %d", len(after), len(before))
}
for name, want := range before {
got, ok := after[name]
if !ok {
t.Errorf("missing baseline fixture %q", name)
continue
}
if fixture, corrected := corrections[name]; corrected {
if want.Final != nil {
if want.Final.Outcome != "approved" || want.Final.Retryable {
t.Fatalf("%s baseline=%+v, want the specifically identified false approval", name, want.Final)
}
want.Final = &paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Provider: "creditcall",
AmountMinor: 1234, CurrencyCode: "GBP", Reason: fixture.reason, Message: fixture.message}
} else {
if !strings.HasPrefix(want.Legacy.Data, "/successful?") {
t.Fatalf("%s baseline=%+v, want the specifically identified false success redirect", name, want.Legacy)
}
want.Legacy = &cmstypes.ResponseRec{Status: cmstypes.StatusRec{Code: http.StatusOK, Message: "unknown"},
Data: "/unsuccessful?Description=Transaction+unknown&MsgType=error"}
}
}
// SQL generates the transaction timestamp during each run. Its type,
// UTC location and range are asserted above; retain raw values in captures.
if want.Persistence != nil && got.Persistence != nil {
want.Persistence["TxnDateTime"], got.Persistence["TxnDateTime"] = "validated current UTC time", "validated current UTC time"
}
if !reflect.DeepEqual(got, want) {
t.Errorf("%s changed beyond the exact approved correction: got %+v, want %+v", name, got, want)
}
}
}
if destination := os.Getenv("HARDLINK_CREDITCALL_DIAGNOSTIC_CAPTURE"); destination != "" {
data, err := json.MarshalIndent(observations, "", " ")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(destination, data, 0600); err != nil {
t.Fatal(err)
}
}
}
func TestCreditCallDiagnosticReasons(t *testing.T) {
for _, fixture := range creditCallDiagnosticFixtures() {
t.Run(fixture.name, func(t *testing.T) {
got := captureCreditCallDiagnostic(t, fixture, false).Final
if got.Reason != fixture.reason || got.Message != fixture.message {
t.Errorf("%s Reason/Message=%q/%q, want %q/%q", fixture.name, got.Reason, got.Message, fixture.reason, fixture.message)
}
if strings.HasPrefix(got.Reason, "confirmation_") && (got.Outcome != "unknown" || got.Retryable) {
t.Errorf("%s final=%+v, want nonretryable confirmation uncertainty", fixture.name, got)
}
})
}
}
func TestCreditCallDiagnosticEntryOrderAndOwnership(t *testing.T) {
for _, fixture := range []struct {
name string
entries []creditcall.EntryXML
want creditCallDiagnostic
}{
{name: "last error unrecognized", entries: []creditcall.EntryXML{
{Key: types.Errors, Value: "ChipCardRemoved"}, {Key: types.Errors, Value: "DeviceUnavailable"},
}},
{name: "last error recognized", entries: []creditcall.EntryXML{
{Key: types.Errors, Value: "DeviceUnavailable"}, {Key: types.Errors, Value: "ChipCardRemoved"},
}, want: creditCallDiagnostic{reason: "sdk_ChipCardRemoved", cause: "ChipCardRemoved"}},
{name: "last result approved", entries: []creditcall.EntryXML{
{Key: types.TransactionResult, Value: "ERROR"}, {Key: types.Errors, Value: "ChipCardRemoved"}, {Key: types.TransactionResult, Value: "APPROVED"},
}},
} {
t.Run(fixture.name, func(t *testing.T) {
before := append([]creditcall.EntryXML(nil), fixture.entries...)
got := creditCallInitialDiagnostic(creditcall.TransactionResultXML{Entries: fixture.entries})
if got != fixture.want {
t.Errorf("creditCallInitialDiagnostic(%+v)=%+v, want %+v", fixture.entries, got, fixture.want)
}
if !reflect.DeepEqual(fixture.entries, before) {
t.Errorf("creditCallInitialDiagnostic changed entries: got %+v, want %+v", fixture.entries, before)
}
})
}
}
func TestCreditCallConfirmationSDKErrorWithoutResultRemainsUncertain(t *testing.T) {
fixture := creditCallDiagnosticFixture{name: "sale/confirmation_sdk_without_result", operation: "sale",
initial: creditCallDiagnosticFields("APPROVED", ""), confirmation: map[string]string{types.Errors: "ClientNotConnectedToServer"}}
got := captureCreditCallDiagnostic(t, fixture, false)
if got.Final.Outcome != "unknown" || got.Final.Retryable || got.Final.Reason != "confirmation_sdk_ClientNotConnectedToServer" || got.Final.TransactionReference != "" || got.Final.AmountMinor != 1234 {
t.Errorf("confirmation SDK error without TRANSACTION_RESULT final=%+v, want nonretryable uncertainty without approved-only metadata", got.Final)
}
if len(got.Requests) != 2 || !reflect.DeepEqual(got.Receipts, []string{"synthetic initial receipt"}) {
t.Errorf("confirmation SDK error without TRANSACTION_RESULT requests/receipts=%v/%v, want one start, one confirmation and inherited receipt", got.Requests, got.Receipts)
}
}
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"net/http" "net/http"
"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/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/logging" "gitea.futuresens.co.uk/futuresens/logging"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@@ -9,9 +9,9 @@ import (
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
logtest "github.com/sirupsen/logrus/hooks/test" logtest "github.com/sirupsen/logrus/hooks/test"
) )
+3 -3
View File
@@ -7,7 +7,7 @@ import (
"encoding/json" "encoding/json"
"encoding/xml" "encoding/xml"
"errors" "errors"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
"io" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -20,8 +20,8 @@ import (
"time" "time"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
) )
type preauthTestConnector struct { type preauthTestConnector struct {
+78 -13
View File
@@ -7,15 +7,31 @@ import (
"strings" "strings"
"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/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
) )
// creditCallProcessor delegates to the unchanged legacy execution/finalization core. // creditCallProcessor delegates to the unchanged legacy execution/finalization core.
type creditCallProcessor struct{ app *App } type creditCallProcessor struct{ app *App }
type creditCallInitialKind uint8
const (
creditCallInitialUnknown creditCallInitialKind = iota
creditCallInitialApproved
creditCallInitialDeclined
creditCallInitialCancelled
creditCallInitialTimeout
)
// creditCallInitialResult describes only the completed initial SDK response.
type creditCallInitialResult struct {
kind creditCallInitialKind
reason string
}
func (*creditCallProcessor) ValidatePreauth(req paymentsvc.SaleRequest) error { func (*creditCallProcessor) ValidatePreauth(req paymentsvc.SaleRequest) error {
if req.Amount < 0 { if req.Amount < 0 {
return paymentsvc.ErrPreauthUnsupported return paymentsvc.ErrPreauthUnsupported
@@ -34,12 +50,19 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
transaction.AmountMinorUnits = "" transaction.AmountMinorUnits = ""
transaction.TransactionType = "AccountVerification" transaction.TransactionType = "AccountVerification"
} }
var initial creditCallInitialResult
var diagnostic creditCallDiagnostic
start := func(client *http.Client) (creditcall.TransactionResultXML, error) { start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
return callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) { result, err := callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) {
if status != nil { if status != nil {
status(paymentsvc.StatusUpdate{Code: code}) status(paymentsvc.StatusUpdate{Code: code})
} }
}) })
if err == nil {
initial = classifyCreditCallInitialResult(result)
diagnostic = creditCallInitialDiagnostic(result)
}
return result, err
} }
var outcome creditCallSaleOutcome var outcome creditCallSaleOutcome
if preauth { if preauth {
@@ -48,7 +71,7 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
} else { } else {
outcome = p.app.executeCreditCallSale(transaction, start) outcome = p.app.executeCreditCallSale(transaction, start)
} }
final := outcome.streamResult() final := outcome.streamResult(initial)
final.AmountMinor, final.CurrencyCode = req.Amount, req.Currency final.AmountMinor, final.CurrencyCode = req.Amount, req.Currency
if outcome.Approved { if outcome.Approved {
if raw := outcome.Payment.Fields[types.TotalAmount]; raw != "" { if raw := outcome.Payment.Fields[types.TotalAmount]; raw != "" {
@@ -63,10 +86,44 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques
} }
} }
} }
if outcome.confirmationDiagnostic.reason != "" {
diagnostic = outcome.confirmationDiagnostic
}
diagnostic.apply(&final)
return &paymentsvc.Result{Terminal: final}, nil return &paymentsvc.Result{Terminal: final}, nil
} }
func (outcome creditCallSaleOutcome) streamResult() paymentapi.Result { func classifyCreditCallInitialResult(result creditcall.TransactionResultXML) creditCallInitialResult {
var transactionResult, sdkError string
for _, entry := range result.Entries {
switch entry.Key {
case types.TransactionResult:
transactionResult = entry.Value
case types.Errors:
sdkError = entry.Value
}
}
transactionResult = strings.ToLower(transactionResult)
switch transactionResult {
case types.ResultApproved:
return creditCallInitialResult{kind: creditCallInitialApproved}
case "cancelled", "canceled":
return creditCallInitialResult{kind: creditCallInitialCancelled}
case "", types.ResultError, types.ResultDeclined:
switch sdkError {
case "CardHolderActionTimedOut":
return creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}
case "PinPadUserCancelled":
return creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}
}
if transactionResult == types.ResultDeclined {
return creditCallInitialResult{kind: creditCallInitialDeclined}
}
}
return creditCallInitialResult{}
}
func (outcome creditCallSaleOutcome) streamResult(initial creditCallInitialResult) paymentapi.Result {
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: outcome.HTTPStatus, Provider: "creditcall", Message: "Payment outcome uncertain; contact reception"} final := paymentapi.Result{Outcome: "unknown", HTTPStatus: outcome.HTTPStatus, Provider: "creditcall", Message: "Payment outcome uncertain; contact reception"}
if final.HTTPStatus == 0 { if final.HTTPStatus == 0 {
final.HTTPStatus = http.StatusOK final.HTTPStatus = http.StatusOK
@@ -79,13 +136,21 @@ func (outcome creditCallSaleOutcome) streamResult() paymentapi.Result {
final.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked]) final.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
final.ExpiryDate = fields[types.ExpiryDate] final.ExpiryDate = fields[types.ExpiryDate]
final.CardHash, final.CardReference = fields[types.CardHash], fields[types.CardReference] final.CardHash, final.CardReference = fields[types.CardHash], fields[types.CardReference]
} else { return final
switch strings.ToLower(outcome.FailureType) {
case "declined":
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
case "cancelled", "canceled":
final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled"
} }
// Initial approval followed by unsuccessful confirmation must not permit another charge.
if initial.kind == creditCallInitialApproved {
return final
}
switch initial.kind {
case creditCallInitialDeclined:
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
case creditCallInitialCancelled:
final.Outcome, final.Retryable = "cancelled", true
final.Reason, final.Message = initial.reason, "Transaction cancelled"
case creditCallInitialTimeout:
final.Outcome, final.Retryable = "timeout", true
final.Reason, final.Message = initial.reason, "Cardholder action timed out"
} }
return final return final
} }
+30 -9
View File
@@ -6,10 +6,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/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/mail"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/printer"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/logging" "gitea.futuresens.co.uk/futuresens/logging"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@@ -22,6 +22,8 @@ type creditCallSaleOutcome struct {
Approved bool Approved bool
FailureType string FailureType string
FailureDescription string FailureDescription string
confirmationDiagnostic creditCallDiagnostic
} }
func (app *App) creditCallClient() *http.Client { func (app *App) creditCallClient() *http.Client {
@@ -84,17 +86,34 @@ func (app *App) executeCreditCallSale(
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error()) mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error())
outcome.FailureType = types.ResultError outcome.FailureType = types.ResultError
outcome.FailureDescription = "ConfirmTransactionError" outcome.FailureDescription = "ConfirmTransactionError"
outcome.confirmationDiagnostic = creditCallConfirmationErrorDiagnostic(err)
return outcome return outcome
} }
// Intentionally reuse both records: XML appends confirmation entries, and // Reuse both records to preserve metadata and receipt merging. Only fresh
// missing confirmation fields/receipts retain their existing legacy behavior. // confirmation entries can establish completion approval.
if err := trResult.ParseTransactionResult(body); err != nil { initialEntryCount := len(trResult.Entries)
logging.Error(types.ServiceName, err.Error(), "Parse confirm result error", string(op), "", "", 0) parseErr := trResult.ParseTransactionResult(body)
if parseErr != nil {
logging.Error(types.ServiceName, parseErr.Error(), "Parse confirm result error", string(op), "", "", 0)
} }
result.FillFromTransactionResult(trResult) result.FillFromTransactionResult(trResult)
res = result.Fields[types.TransactionResult] res = result.Fields[types.TransactionResult]
if !strings.EqualFold(res, types.ResultApproved) { confirmationEntries := trResult.Entries[initialEntryCount:]
var confirmationResult string
for _, entry := range confirmationEntries {
if entry.Key == types.TransactionResult {
confirmationResult = entry.Value
}
}
confirmationApproved := false
if parseErr == nil {
confirmationApproved = strings.EqualFold(confirmationResult, types.ResultApproved)
}
if !confirmationApproved {
if strings.EqualFold(res, types.ResultApproved) {
res = "unknown"
}
app.printCreditCallReceipt(result.CardholderReceipt) app.printCreditCallReceipt(result.CardholderReceipt)
desc := result.Fields[types.ErrorDescription] desc := result.Fields[types.ErrorDescription]
if desc == "" { if desc == "" {
@@ -104,9 +123,11 @@ func (app *App) executeCreditCallSale(
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc) mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc)
outcome.HTTPStatus = http.StatusOK outcome.HTTPStatus = http.StatusOK
outcome.Status = result.Status outcome.Status = result.Status
outcome.Status.Message = res
outcome.Payment = result outcome.Payment = result
outcome.FailureType = res outcome.FailureType = res
outcome.FailureDescription = result.Fields[types.Errors] outcome.FailureDescription = result.Fields[types.Errors]
outcome.confirmationDiagnostic = creditCallConfirmationResultDiagnostic(confirmationEntries, parseErr != nil)
return outcome return outcome
} }
+161 -7
View File
@@ -18,10 +18,10 @@ import (
"time" "time"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
) )
type failedCreditCallBody struct{ closed *bool } type failedCreditCallBody struct{ closed *bool }
@@ -84,7 +84,7 @@ func TestCreditCallStructuredFieldsExcludeRawData(t *testing.T) {
result := (creditCallSaleOutcome{Approved: true, Payment: creditcall.PaymentResult{Fields: map[string]string{ result := (creditCallSaleOutcome{Approved: true, Payment: creditcall.PaymentResult{Fields: map[string]string{
types.Reference: "ref", types.PanMasked: "1234567890123456", types.CardHash: "hash", types.CardReference: "card-ref", types.Reference: "ref", types.PanMasked: "1234567890123456", types.CardHash: "hash", types.CardReference: "card-ref",
"PAN": "pan-secret", "CVV": "cvv-secret", "PIN": "pin-secret", "TRACK_DATA": "track-secret", types.ReceiptDataCardholder: "receipt-secret", "PAN": "pan-secret", "CVV": "cvv-secret", "PIN": "pin-secret", "TRACK_DATA": "track-secret", types.ReceiptDataCardholder: "receipt-secret",
}}}).streamResult() }}}).streamResult(creditCallInitialResult{kind: creditCallInitialApproved})
body, err := json.Marshal(result) body, err := json.Marshal(result)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -219,8 +219,8 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
{"cancelled", "Cancelled", "", 0, false, "start receipt"}, {"cancelled", "Cancelled", "", 0, false, "start receipt"},
{"timeout", "TIMEOUT", "", 0, false, "start receipt"}, {"timeout", "TIMEOUT", "", 0, false, "start receipt"},
{"confirmation declined", "Approved", "Declined", 1, false, "confirm receipt"}, {"confirmation declined", "Approved", "Declined", 1, false, "confirm receipt"},
{"confirmation omissions", "Approved", "omitted", 1, true, "start receipt"}, {"confirmation omissions", "Approved", "omitted", 1, false, "start receipt"},
{"malformed confirmation", "Approved", "malformed", 1, true, "start receipt"}, {"malformed confirmation", "Approved", "malformed", 1, false, "start receipt"},
} { } {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
fields := map[string]string{types.TransactionResult: test.startResult, types.Reference: "native-ref", fields := map[string]string{types.TransactionResult: test.startResult, types.Reference: "native-ref",
@@ -314,6 +314,160 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
} }
} }
func TestCreditCallFreshConfirmationResults(t *testing.T) {
fixtures := map[string]creditCallDiagnosticFixture{}
for _, fixture := range creditCallDiagnosticFixtures() {
fixtures[fixture.name] = fixture
}
for _, tc := range []struct {
name, outcome string
amount int64
}{
{"confirmation_xml/mixed_case", "approved", 1234},
{"confirmation_xml/omitted", "unknown", 1234},
{"confirmation_xml/empty_body", "unknown", 1234},
{"confirmation_xml/whitespace_body", "unknown", 1234},
{"confirmation_xml/malformed_retains_approval", "unknown", 1234},
{"confirmation_xml/malformed_after_approved", "unknown", 1234},
{"confirmation_xml/malformed_after_error", "unknown", 1234},
{"confirmation_xml/malformed_after_declined", "unknown", 1234},
{"confirmation_xml/wrong_root", "unknown", 1234},
{"confirmation_xml/sdk_only_disconnected", "unknown", 1234},
{"confirmation_xml/sdk_only_not_found", "unknown", 1234},
{"confirmation_xml/duplicate_approved_declined", "unknown", 1234},
{"confirmation_xml/duplicate_declined_approved", "approved", 1234},
{"confirmation_xml/duplicate_error_approved", "approved", 1234},
{"confirmation_xml/duplicate_approved_empty", "unknown", 1234},
{"confirmation_xml/duplicate_empty_approved", "approved", 1234},
{"confirmation_xml/duplicate_approved_error", "unknown", 1234},
{"confirmation_result/DECLINED", "unknown", 1234},
{"confirmation_result/ERROR", "unknown", 1234},
{"confirmation_result/CANCELLED", "unknown", 1234},
{"confirmation_result/CANCELED", "unknown", 1234},
{"confirmation_result/TIMEOUT", "unknown", 1234},
{"confirmation_result/UNKNOWN", "unknown", 1234},
{"confirmation_result/", "unknown", 1234},
{"confirmation_metadata/returned_amount", "approved", 3100},
{"confirmation_metadata/overrides", "approved", 2500},
{"confirmation_metadata/empty_overrides", "approved", 3100},
} {
for _, legacy := range []bool{false, true} {
mode := "modern"
if legacy {
mode = "legacy"
}
t.Run(mode+"/"+tc.name, func(t *testing.T) {
fixture, ok := fixtures["sale/"+tc.name]
if !ok {
t.Fatalf("missing confirmation fixture %q", tc.name)
}
got := captureCreditCallDiagnostic(t, fixture, legacy)
if len(got.Requests) != 2 {
t.Fatalf("Sale(%s) requests=%+v, want one start and one confirmation", tc.name, got.Requests)
}
if got.HTTPStatus != http.StatusOK || got.Requests[1].Path != "/confirm-transaction/" {
t.Errorf("Sale(%s) HTTP/requests=%d/%+v, want HTTP 200, one start and one confirmation", tc.name, got.HTTPStatus, got.Requests)
}
for _, request := range got.Requests {
if !request.FreshCallDeadline || request.Method != http.MethodPost {
t.Errorf("Sale(%s) request=%+v, want POST with an independent 300-second timeout", tc.name, request)
}
}
var confirmation creditcall.ConfirmTransactionRequest
if err := xml.Unmarshal([]byte(got.Requests[1].Body), &confirmation); err != nil {
t.Fatal(err)
}
if confirmation.Amount != "1234" || confirmation.Reference != "SYNTH-STAGE2" {
t.Errorf("Sale(%s) confirmation=%+v, want the original requested amount and authorization reference", tc.name, confirmation)
}
if legacy {
if strings.HasPrefix(got.Legacy.Data, "/successful?") != (tc.outcome == "approved") {
t.Errorf("Sale(%s) legacy=%+v, want success only for fresh approval", tc.name, got.Legacy)
}
if fixture.correctedConfirmation && (got.Legacy.Status.Code != http.StatusOK || got.Legacy.Status.Message != "unknown" || got.Legacy.Data != "/unsuccessful?Description=Transaction+unknown&MsgType=error") {
t.Errorf("Sale(%s) legacy=%+v, want unchanged status code and explicit uncertainty failure response", tc.name, got.Legacy)
}
} else if got.Final.Outcome != tc.outcome || got.Final.Retryable || got.Final.HTTPStatus != http.StatusOK || got.Final.AmountMinor != tc.amount || got.Final.Reason != fixture.reason || got.Final.Message != fixture.message {
t.Errorf("Sale(%s) final=%+v, want %s/nonretryable/HTTP200/amount%d and %q/%q", tc.name, got.Final, tc.outcome, tc.amount, fixture.reason, fixture.message)
}
wantReceipt := "synthetic initial receipt"
if tc.name == "confirmation_metadata/overrides" {
wantReceipt = "synthetic confirmation receipt"
}
if tc.name == "confirmation_metadata/empty_overrides" {
wantReceipt = ""
}
if !reflect.DeepEqual(got.Receipts, []string{wantReceipt}) || got.PersistenceCount != 0 {
t.Errorf("Sale(%s) receipts/persistence=%v/%d, want [%q]/0", tc.name, got.Receipts, got.PersistenceCount, wantReceipt)
}
})
}
}
}
func TestCreditCallSaleConfirmationPreservesMergedFields(t *testing.T) {
for _, tc := range []struct {
name, rawXML, receipt string
confirmation map[string]string
approved bool
}{
{name: "minimal approval", confirmation: map[string]string{types.TransactionResult: "APPROVED"}, receipt: "synthetic initial receipt", approved: true},
{name: "confirmation overrides", confirmation: map[string]string{types.TransactionResult: "APPROVED", types.Reference: "SYNTH-CONFIRMED", types.TotalAmount: "2500", types.CardHash: "", types.ReceiptDataCardholder: "synthetic confirmation receipt"}, receipt: "synthetic confirmation receipt", approved: true},
{name: "SDK-only uncertainty", confirmation: map[string]string{types.Errors: "ClientNotConnectedToServer"}, receipt: "synthetic initial receipt"},
{name: "partial approved XML", rawXML: "<TransactionResult><Entry><Key>TRANSACTION_RESULT</Key><Value>APPROVED</Value></Entry><Entry>", receipt: "synthetic initial receipt"},
} {
t.Run(tc.name, func(t *testing.T) {
initial := creditCallDiagnosticFields("APPROVED", "")
initial[types.TotalAmount] = "3100"
initial["AUTH_DATE_TIME"], initial["CARDEASE_REFERENCE"] = "20300101120000", "synthetic-authorization"
expected := map[string]string{}
for key, value := range initial {
if key != types.ReceiptDataCardholder {
expected[key] = value
}
}
for key, value := range tc.confirmation {
if key != types.ReceiptDataCardholder {
expected[key] = value
}
}
var receipts []string
starts, confirms := 0, 0
body := &creditCallDiagnosticBody{}
app := &App{cfg: &config.ConfigRec{}, creditCallReceipt: func(receipt string) { receipts = append(receipts, receipt) }}
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
confirms++
if r.URL.Path != "/confirm-transaction/" {
t.Errorf("unexpected confirmation path %q", r.URL.Path)
}
wire := tc.rawXML
if wire == "" {
wire = chipDNAFixture(t, tc.confirmation)
}
body.Reader = strings.NewReader(wire)
return &http.Response{StatusCode: http.StatusOK, Body: body}, nil
})
outcome := app.executeCreditCallSale(cmstypes.TransactionRec{AmountMinorUnits: "1234"}, func(*http.Client) (creditcall.TransactionResultXML, error) {
starts++
var result creditcall.TransactionResultXML
for key, value := range initial {
result.Entries = append(result.Entries, creditcall.EntryXML{Key: key, Value: value})
}
return result, nil
})
if outcome.Approved != tc.approved || !reflect.DeepEqual(outcome.Payment.Fields, expected) || outcome.Payment.CardholderReceipt != tc.receipt {
t.Errorf("Sale(%s) approved/fields/receipt=%t/%v/%q, want %t/%v/%q", tc.name, outcome.Approved, outcome.Payment.Fields, outcome.Payment.CardholderReceipt, tc.approved, expected, tc.receipt)
}
if !tc.approved && (outcome.Status.Message != "unknown" || outcome.FailureType != "unknown" || outcome.Payment.Status.Message != "APPROVED") {
t.Errorf("Sale(%s) status/failure/payment status=%+v/%q/%+v, want uncertainty without mutating merged authorization evidence", tc.name, outcome.Status, outcome.FailureType, outcome.Payment.Status)
}
if starts != 1 || confirms != 1 || !body.closed || !reflect.DeepEqual(receipts, []string{tc.receipt}) {
t.Errorf("Sale(%s) starts/confirms/closed/receipts=%d/%d/%t/%v, want 1/1/true/[%q]", tc.name, starts, confirms, body.closed, receipts, tc.receipt)
}
})
}
}
func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) { func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
for _, streaming := range []bool{false, true} { for _, streaming := range []bool{false, true} {
var attempts int var attempts int
+3 -3
View File
@@ -12,9 +12,9 @@ import (
"strconv" "strconv"
"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/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
) )
// EnableCreditCallStreaming selects the existing CreditCall execution core. // EnableCreditCallStreaming selects the existing CreditCall execution core.
@@ -0,0 +1,369 @@
package handlers
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync/atomic"
"testing"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
)
func TestClassifyCreditCallInitialResult(t *testing.T) {
for _, tc := range []struct {
name, result, sdkError string
want creditCallInitialResult
}{
{name: "empty", want: creditCallInitialResult{kind: creditCallInitialUnknown}},
{name: "approval wins over cancellation error", result: "APPROVED", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialApproved}},
{name: "mixed-case approval wins over timeout", result: "Approved", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialApproved}},
{name: "ordinary decline", result: "DECLINED", sdkError: "InsufficientFunds", want: creditCallInitialResult{kind: creditCallInitialDeclined}},
{name: "declined cancellation", result: "DECLINED", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}},
{name: "declined cardholder timeout", result: "DECLINED", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}},
{name: "explicit cancellation", result: "CANCELLED", want: creditCallInitialResult{kind: creditCallInitialCancelled}},
{name: "alternate cancellation spelling", result: "Canceled", want: creditCallInitialResult{kind: creditCallInitialCancelled}},
{name: "SDK timeout", result: "ERROR", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}},
{name: "SDK cancellation", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}},
{name: "CLI wait expiry with SDK timeout", result: "TIMEOUT", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{}},
{name: "CLI wait expiry with SDK cancellation", result: "TIMEOUT", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{}},
{name: "unknown result", result: "UNKNOWN", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{}},
{name: "compound error", result: "ERROR", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: creditCallInitialResult{}},
{name: "case-sensitive SDK error", result: "ERROR", sdkError: "pinpadusercancelled", want: creditCallInitialResult{}},
} {
t.Run(tc.name, func(t *testing.T) {
input := creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{
{Key: types.TransactionResult, Value: tc.result}, {Key: types.Errors, Value: tc.sdkError},
}}
if got := classifyCreditCallInitialResult(input); got != tc.want {
t.Errorf("classifyCreditCallInitialResult(%q,%q)=%+v, want %+v", tc.result, tc.sdkError, got, tc.want)
}
})
}
}
func TestClassifyCreditCallInitialResultLastEntryWins(t *testing.T) {
for _, tc := range []struct {
name string
entries []creditcall.EntryXML
want creditCallInitialResult
}{
{name: "no response fields", want: creditCallInitialResult{}},
{name: "last result is approval", entries: []creditcall.EntryXML{
{Key: types.TransactionResult, Value: "DECLINED"}, {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.TransactionResult, Value: "APPROVED"},
}, want: creditCallInitialResult{kind: creditCallInitialApproved}},
{name: "last result is declined cancellation", entries: []creditcall.EntryXML{
{Key: types.TransactionResult, Value: "APPROVED"}, {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.TransactionResult, Value: "DECLINED"},
}, want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}},
{name: "last error is unknown", entries: []creditcall.EntryXML{
{Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.Errors, Value: "DeviceUnavailable"},
}, want: creditCallInitialResult{}},
{name: "last error is SDK timeout", entries: []creditcall.EntryXML{
{Key: types.Errors, Value: "DeviceUnavailable"}, {Key: types.Errors, Value: "CardHolderActionTimedOut"},
}, want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}},
{name: "description is not an SDK code", entries: []creditcall.EntryXML{
{Key: types.ErrorDescription, Value: "PinPadUserCancelled"},
}, want: creditCallInitialResult{}},
} {
t.Run(tc.name, func(t *testing.T) {
input := creditcall.TransactionResultXML{Entries: tc.entries}
before := append([]creditcall.EntryXML(nil), input.Entries...)
if got := classifyCreditCallInitialResult(input); got != tc.want {
t.Errorf("classifyCreditCallInitialResult(%+v)=%+v, want %+v", input.Entries, got, tc.want)
}
if !reflect.DeepEqual(input.Entries, before) {
t.Errorf("classifyCreditCallInitialResult mutated entries: got %+v, want %+v", input.Entries, before)
}
})
}
}
func TestCreditCallInitialSDKErrorClassification(t *testing.T) {
for _, operation := range []string{"sale", "preauth"} {
for _, tc := range []struct {
name, result, sdkError, description, want, reason string
retryable, resultPresent bool
}{
{name: "missing result", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true},
{name: "empty result", resultPresent: true, sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true},
{name: "error result", result: "ERROR", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true},
{name: "mixed-case error result", result: "Error", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true},
{name: "CLI wait timeout", result: "TIMEOUT", sdkError: "Transaction timed out waiting for device response", want: "unknown"},
{name: "CLI timeout with conflicting SDK error", result: "TIMEOUT", sdkError: "CardHolderActionTimedOut", want: "unknown"},
{name: "other SDK error", result: "ERROR", sdkError: "DeviceUnavailable", want: "unknown"},
{name: "compound error", sdkError: "CardHolderActionTimedOut, DeviceUnavailable", want: "unknown"},
{name: "description only", description: "CardHolderActionTimedOut", sdkError: "DeviceUnavailable", want: "unknown"},
{name: "cardholder timeout with declined result", result: "DECLINED", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true},
{name: "cardholder timeout with mixed-case decline", result: "Declined", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true},
{name: "cancelled retains classification", result: "Cancelled", sdkError: "CardHolderActionTimedOut", want: "cancelled", retryable: true},
{name: "explicit cancellation", result: "CANCELLED", want: "cancelled", retryable: true},
{name: "alternate cancellation spelling", result: "CANCELED", want: "cancelled", retryable: true},
{name: "user cancel missing result", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"},
{name: "user cancel empty result", resultPresent: true, sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"},
{name: "user cancel error result", result: "ERROR", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"},
{name: "user cancel mixed-case error result", result: "Error", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"},
{name: "user cancel with CLI timeout", result: "TIMEOUT", sdkError: "PinPadUserCancelled", want: "unknown"},
{name: "user cancel with unknown result", result: "UNKNOWN", sdkError: "PinPadUserCancelled", want: "unknown"},
{name: "user cancel with declined result", result: "DECLINED", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"},
{name: "user cancel with mixed-case decline", result: "Declined", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"},
{name: "ordinary decline", result: "DECLINED", sdkError: "InsufficientFunds", want: "declined", retryable: true},
{name: "decline without SDK error", result: "DECLINED", want: "declined", retryable: true},
{name: "decline with compound timeout error", result: "DECLINED", sdkError: "CardHolderActionTimedOut, DeviceUnavailable", want: "declined", retryable: true},
{name: "decline with compound cancellation error", result: "DECLINED", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: "declined", retryable: true},
{name: "user cancel compound error", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: "unknown"},
{name: "user cancel description only", description: "PinPadUserCancelled", sdkError: "DeviceUnavailable", want: "unknown"},
} {
t.Run(operation+"/"+tc.name, func(t *testing.T) {
var starts, confirms atomic.Int32
fields := map[string]string{types.Errors: tc.sdkError, types.ReceiptDataCardholder: "synthetic initial receipt"}
if tc.result != "" || tc.resultPresent {
fields[types.TransactionResult] = tc.result
}
if tc.description != "" {
fields[types.ErrorDescription] = tc.description
}
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/start-transaction-stream/" {
confirms.Add(1)
t.Errorf("initial %s response reached unexpected path %q", operation, r.URL.Path)
w.WriteHeader(http.StatusBadRequest)
return
}
starts.Add(1)
if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil {
t.Errorf("encode synthetic SDK result: %v", err)
}
})
var receipts []string
app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) }
recorder := httptest.NewRecorder()
if operation == "preauth" {
app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", ""))
} else {
app.salePayment(recorder, saleRequest(true))
}
frames := decodePaymentStream(t, recorder.Body)
if len(frames) != 1 || frames[0].Result == nil {
t.Fatalf("%s(%s) frames=%+v, want one final result", operation, tc.name, frames)
}
final := frames[0].Result
if final.Outcome != tc.want || final.Retryable != tc.retryable || final.HTTPStatus != http.StatusOK {
t.Errorf("%s(%s) final=%+v, want %s retryable=%t HTTP 200", operation, tc.name, final, tc.want, tc.retryable)
}
if tc.want == "timeout" && (final.Reason != "cardholder_timeout" || final.Message != "Cardholder action timed out") {
t.Errorf("%s(%s) reason/message=%q/%q, want sanitized cardholder timeout", operation, tc.name, final.Reason, final.Message)
}
if tc.reason != "" && (final.Reason != tc.reason || final.Message != "Transaction cancelled") {
t.Errorf("%s(%s) reason/message=%q/%q, want %q/Transaction cancelled", operation, tc.name, final.Reason, final.Message, tc.reason)
}
if starts.Load() != 1 || confirms.Load() != 0 || !reflect.DeepEqual(receipts, []string{"synthetic initial receipt"}) {
t.Errorf("%s(%s) starts/confirms/receipts=%d/%d/%v, want 1/0/[synthetic initial receipt]", operation, tc.name, starts.Load(), confirms.Load(), receipts)
}
})
}
}
}
func TestCreditCallInitialSDKErrorRequiresCompleteResponse(t *testing.T) {
for _, operation := range []string{"sale", "preauth"} {
for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} {
for _, failure := range []string{"transport loss", "interrupted execution", "truncated result", "error frame", "HTTP failure"} {
t.Run(operation+"/"+sdkError+"/"+failure, func(t *testing.T) {
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
body := fmt.Sprintf(`{"type":"result","result":{"ERRORS":%q}}`, sdkError)
switch failure {
case "error frame":
body = fmt.Sprintf("{\"type\":\"error\",\"error\":%q}\n", sdkError)
case "HTTP failure":
w.WriteHeader(http.StatusBadGateway)
body += "\n"
}
if _, err := io.WriteString(w, body); err != nil {
t.Errorf("write synthetic incomplete SDK result: %v", err)
}
})
transport := app.creditCallTransport
var calls atomic.Int32
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
calls.Add(1)
if failure == "transport loss" {
return nil, io.ErrUnexpectedEOF
}
if failure == "interrupted execution" {
return nil, context.Canceled
}
return transport.RoundTrip(r)
})
app.creditCallReceipt = func(string) { t.Error("incomplete SDK result printed a receipt") }
recorder := httptest.NewRecorder()
if operation == "preauth" {
app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", ""))
} else {
app.salePayment(recorder, saleRequest(true))
}
frames := decodePaymentStream(t, recorder.Body)
if len(frames) != 1 || frames[0].Result == nil {
t.Fatalf("%s(%s) frames=%+v, want one uncertain result", operation, failure, frames)
}
final := frames[0].Result
if calls.Load() != 1 || final.Outcome != "unknown" || final.Retryable || final.HTTPStatus != http.StatusBadGateway || strings.Contains(final.Message, sdkError) {
t.Errorf("%s(%s) calls/final=%d/%+v, want one dispatch and sanitized nonretryable uncertainty", operation, failure, calls.Load(), final)
}
})
}
}
}
}
func TestCreditCallInitialSDKErrorDuringConfirmationRemainsUncertain(t *testing.T) {
for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} {
for _, result := range []string{"", "ERROR", "TIMEOUT", "DECLINED", "CANCELLED", "CANCELED"} {
t.Run(sdkError+"/confirmation result="+result, func(t *testing.T) {
var starts, confirms atomic.Int32
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/start-transaction-stream/" {
starts.Add(1)
fields := map[string]string{types.TransactionResult: "Approved", types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234"}
if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil {
t.Errorf("encode initial approval: %v", err)
}
return
}
if r.URL.Path != "/confirm-transaction/" {
t.Errorf("unexpected SDK path %q", r.URL.Path)
w.WriteHeader(http.StatusBadRequest)
return
}
confirms.Add(1)
fields := map[string]string{types.TransactionResult: result, types.Errors: sdkError, types.ReceiptDataCardholder: "synthetic confirmation receipt"}
if _, err := io.WriteString(w, chipDNAFixture(t, fields)); err != nil {
t.Errorf("write confirmation result: %v", err)
}
})
var receipts []string
app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) }
recorder := httptest.NewRecorder()
app.salePayment(recorder, saleRequest(true))
frames := decodePaymentStream(t, recorder.Body)
if len(frames) != 1 || frames[0].Result == nil {
t.Fatalf("confirmation(%q) frames=%+v, want one uncertain final result", result, frames)
}
final := frames[0].Result
if final.Outcome != "unknown" || final.Retryable {
t.Errorf("confirmation(%q) final=%+v, want nonretryable uncertainty after initial approval", result, final)
}
if starts.Load() != 1 || confirms.Load() != 1 || !reflect.DeepEqual(receipts, []string{"synthetic confirmation receipt"}) {
t.Errorf("confirmation(%q) starts/confirms/receipts=%d/%d/%v, want 1/1/[synthetic confirmation receipt]", result, starts.Load(), confirms.Load(), receipts)
}
})
}
}
}
func TestCreditCallInitialApprovalPreservesExecutionWithSDKError(t *testing.T) {
for _, operation := range []string{"sale", "preauth"} {
for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} {
t.Run(operation+"/"+sdkError, func(t *testing.T) {
var starts, confirms atomic.Int32
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/start-transaction-stream/" {
starts.Add(1)
fields := map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "SALE", types.Errors: sdkError,
types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234", types.ReceiptDataCardholder: "synthetic initial receipt"}
if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil {
t.Errorf("encode initial approval: %v", err)
}
return
}
if r.URL.Path != "/confirm-transaction/" {
t.Errorf("unexpected SDK path %q", r.URL.Path)
w.WriteHeader(http.StatusBadRequest)
return
}
confirms.Add(1)
if _, err := io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: "APPROVED", types.ReceiptDataCardholder: "synthetic confirmation receipt"})); err != nil {
t.Errorf("write confirmation approval: %v", err)
}
})
var receipts []string
app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) }
recorder := httptest.NewRecorder()
wantConfirms, wantReceipt := int32(1), "synthetic confirmation receipt"
if operation == "preauth" {
database := preauthTestDatabase(t, app)
app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", "2026-11-10 00:00:00 +0000"))
persisted := waitPreauthInsert(t, database)
if persisted["TxnReference"] != "SYNTH-APPROVED" || persisted["TotalMinorUnits"] != "1234" {
t.Errorf("approved PREAUTH persisted=%v, want unchanged reference and terminal amount", persisted)
}
if database.count.Load() != 1 {
t.Errorf("approved PREAUTH persistence calls=%d, want 1", database.count.Load())
}
wantConfirms, wantReceipt = 0, "synthetic initial receipt"
} else {
app.salePayment(recorder, saleRequest(true))
}
frames := decodePaymentStream(t, recorder.Body)
if len(frames) != 1 || frames[0].Result == nil {
t.Fatalf("%s approval(%s) frames=%+v, want one approved result", operation, sdkError, frames)
}
final := frames[0].Result
if final.Outcome != "approved" || final.Retryable || final.TransactionReference != "SYNTH-APPROVED" || final.AmountMinor != 1234 {
t.Errorf("%s approval(%s) final=%+v, want approved with unchanged reference and amount", operation, sdkError, final)
}
if starts.Load() != 1 || confirms.Load() != wantConfirms || !reflect.DeepEqual(receipts, []string{wantReceipt}) {
t.Errorf("%s approval(%s) starts/confirms/receipts=%d/%d/%v, want 1/%d/[%s]", operation, sdkError, starts.Load(), confirms.Load(), receipts, wantConfirms, wantReceipt)
}
})
}
}
}
func TestCreditCallInitialApprovalConfirmationReadFailureRemainsUncertain(t *testing.T) {
var starts, confirms atomic.Int32
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/start-transaction-stream/" {
t.Errorf("unexpected SDK path %q", r.URL.Path)
w.WriteHeader(http.StatusBadRequest)
return
}
starts.Add(1)
fields := map[string]string{types.TransactionResult: "APPROVED", types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234"}
if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil {
t.Errorf("encode initial approval: %v", err)
}
})
transport := app.creditCallTransport
closed := [2]bool{}
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Path != "/confirm-transaction/" {
return transport.RoundTrip(r)
}
attempt := int(confirms.Add(1)) - 1
if attempt >= len(closed) {
t.Error("more than two confirmation attempts")
return nil, io.ErrUnexpectedEOF
}
return &http.Response{StatusCode: http.StatusOK, Body: failedCreditCallBody{closed: &closed[attempt]}}, nil
})
app.creditCallReceipt = func(string) { t.Error("failed confirmation printed a receipt") }
recorder := httptest.NewRecorder()
app.salePayment(recorder, saleRequest(true))
frames := decodePaymentStream(t, recorder.Body)
if len(frames) != 1 || frames[0].Result == nil {
t.Fatalf("confirmation read failure frames=%+v, want one uncertain final result", frames)
}
final := frames[0].Result
if final.Outcome != "unknown" || final.Retryable || final.HTTPStatus != http.StatusBadGateway {
t.Errorf("confirmation read failure final=%+v, want nonretryable uncertainty", final)
}
if starts.Load() != 1 || confirms.Load() != 2 || !closed[0] || !closed[1] {
t.Errorf("starts/confirms/closed=%d/%d/%v, want one dispatch and two closed confirmation bodies", starts.Load(), confirms.Load(), closed)
}
}
+2 -2
View File
@@ -10,8 +10,8 @@ import (
"path/filepath" "path/filepath"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/db"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+3 -3
View File
@@ -15,9 +15,9 @@ import (
"time" "time"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dispenser" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/dispenser"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/lockserver"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+9 -9
View File
@@ -13,15 +13,15 @@ import (
"time" "time"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dispenser" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/dispenser"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/errorhandlers"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/lockserver"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/mail"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/printer"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/logging" "gitea.futuresens.co.uk/futuresens/logging"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+2 -2
View File
@@ -9,8 +9,8 @@ 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/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/logging" "gitea.futuresens.co.uk/futuresens/logging"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+4 -4
View File
@@ -15,10 +15,10 @@ import (
"time" "time"
"gitea.futuresens.co.uk/futuresens/cmstypes" "gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/mail"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
) )
func TestModernRoutesRejectNonPOSTWithoutDispatch(t *testing.T) { func TestModernRoutesRejectNonPOSTWithoutDispatch(t *testing.T) {
+2 -2
View File
@@ -9,8 +9,8 @@ import (
"strings" "strings"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
"github.com/google/uuid" "github.com/google/uuid"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+4 -4
View File
@@ -10,10 +10,10 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
) )
type paymentProviderFunc func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) type paymentProviderFunc func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error)
+5 -5
View File
@@ -9,11 +9,11 @@ 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/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/errorhandlers"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/lockserver"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/mail"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/logging" "gitea.futuresens.co.uk/futuresens/logging"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+3 -3
View File
@@ -11,9 +11,9 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+2 -2
View File
@@ -1,8 +1,8 @@
package handlers package handlers
import ( import (
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
) )
// SetTrustPayments selects Trust while preserving the deprecated endpoint guard. // SetTrustPayments selects Trust while preserving the deprecated endpoint guard.
+3 -3
View File
@@ -15,9 +15,9 @@ import (
"testing" "testing"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
) )
type trustFixtureTransport func(*http.Request) (*http.Response, error) type trustFixtureTransport func(*http.Request) (*http.Response, error)
+5 -5
View File
@@ -10,11 +10,11 @@ import (
"strings" "strings"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+1 -1
View File
@@ -12,7 +12,7 @@ import (
"testing" "testing"
"time" "time"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
logtest "github.com/sirupsen/logrus/hooks/test" logtest "github.com/sirupsen/logrus/hooks/test"
+1 -1
View File
@@ -1,6 +1,6 @@
package paybridge package paybridge
import "gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" import "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
func mapPaymentResult(res PaymentResultEnvelope) *paymentsvc.Result { func mapPaymentResult(res PaymentResultEnvelope) *paymentsvc.Result {
var merchantReceipt string var merchantReceipt string
+1 -1
View File
@@ -1,7 +1,7 @@
package paybridge package paybridge
import ( import (
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"testing" "testing"
) )
+1 -1
View File
@@ -3,7 +3,7 @@ package paybridge
import ( import (
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
) )
func TestMapPayBridgeFinalStatus(t *testing.T) { func TestMapPayBridgeFinalStatus(t *testing.T) {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"sync/atomic" "sync/atomic"
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
) )
type testProcessor struct { type testProcessor struct {
+1 -1
View File
@@ -1,6 +1,6 @@
package paymentsvc package paymentsvc
import "gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" import "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
type SaleRequest struct { type SaleRequest struct {
RequestID string `json:"requestId"` RequestID string `json:"requestId"`
+1 -1
View File
@@ -13,7 +13,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers" "gitea.futuresens.co.uk/futuresens/hardlink/v2/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"
+4 -4
View File
@@ -5,10 +5,10 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/printer"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus" "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
) )
func TestFixedStatusValues(t *testing.T) { func TestFixedStatusValues(t *testing.T) {
+218
View File
@@ -0,0 +1,218 @@
## Release notes
`buildVersion` is a const in `cmd/hardlink/main.go`.
#### v2.2.4 - 05 November 2026
fix(creditcall): require fresh confirmation approval for sale
#### v2.2.3 - 05 November 2026
fix(creditcall): preserve detailed SDK failure diagnostics
#### v2.2.2 - 05 November 2026
fix(creditcall): restore SDK timeout and cancellation classification
#### v2.2.1 - 04 November 2026
refactor: migrate the Go module and active imports to `gitea.futuresens.co.uk/futuresens/hardlink/v2`; include current module/build documentation.
#### v2.2.0 - 02 November 2026
feat: integrate Trust Payments with existing payment flow
#### v2.1.5 - 22 October 2026
feat(dispenser): recover K720 card position during uncertain encoding
#### v2.1.4 - 19 October 2026
added detailed logging for preauth payment processing and result streaming
#### v2.1.3 - 30 September 2026
feat(logging): add weekly log rotation and retention
#### v2.1.2 - 30 September 2026
fix(dispenser): scan ACK responses without assuming 3-byte reads
#### v2.1.1 - 28 September 2026
feat(dispenser): add worker-owned idle card prestaging
#### v2.1.0 - 28 September 2026
fix(dispenser): tolerate unusable AP observations during card preparation
#### v2.0.3 - 24 September 2026
fix(dispenser): recover stuck card preparation with reset
#### v2.0.2 - 22 September 2026
fix(dispenser): retry on transient prepare failure
#### v2.0.1 - 10 September 2026
feat: add CreditCall preauth streaming
#### v2.0.0 - 08 September 2026
feat: stream CreditCall payment progress and results
#### v1.3.6 - 28 August 2026
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
make dojo decline payment in case of signature required
#### 1.3.1 - 17 July 2026
added receipt printing functionality to the Dojo and Paybridge payment flow
#### 1.3.0 - 03 July 2026
added pluggable PayBridge and Dojo payment flow with CMS credentials
#### 1.2.11 - 26 June 2026
added PayBridge integration for payment processing functionality
#### 1.2.10 - 26 June 2026
added voucher field to the guest receipt
#### 1.2.9 - 02 June 2026
added Dormakaba lock server integration
#### 1.2.8 - 14 May 2026
Updated hardlink source layout to use cmd/hardlink for the main application entry point and internal/ for application packages. Runtime files and preauth-release layout remain unchanged. No functional changes.
#### 1.2.7 - 13 May 2026
retrieve CardType from the ChepDNA response
#### 1.2.6 - 20 April 2026
added the second attempt to send the card to the encoder after 6 seconds
#### 1.2.5 - 20 March 2026
removed early return on error when checking dispenser status in the start and final loops.
#### 1.2.4 - 18 March 2026
added check if keycard at the encoder position before trying to encode key
#### 1.2.3 - 17 March 2026
added check if keycard at the encoder position before trying to encode key
#### 1.2.2 - 11 February 2026
increased waiting time befor sending email on PDQ unavailability to 30 seconds day time and 10 minutes night time
to give it a chance to become available again
#### 1.2.1 - 09 February 2026
increased waiting time befor sending email on PDQ unavailability to 60 seconds
#### 1.2.0 - 09 February 2026
added testissuedoorcard endpoint for testing the full workflow of encoding a door card without moving the card out
added ping-pdq endpoint to check the status of the pdq terminal
added sending the email on the pdq disconnect event to notify support about the issue
added sending the email on the dispenser error status to notify support about the issue
#### 1.1.3 - 02 February 2026
increased timeout for reading response from the Assa abloy lock server to 20 seconds
#### 1.1.2 - 02 February 2026
added logging for unknown dispenser status positions
#### 1.1.1 - 02 February 2026
added contionuous polling of the dispenser status every 8 seconds to update the card well status
#### 1.1.0 - 26 January 2026
divided `/starttransaction` endpoint into two separate endpoints:
`/takepreauth` to request preauthorization payment
`/takepayment` to request taking payment
added preauth releaser functionality to release preauthorization payments after a defined time period
added db connection check before adding a transaction to the database
and reconnection functionality if the connection to the database is lost
added `/dispenserstatus` endpoint
key card always stays at encoder position
#### 1.0.30 - 09 January 2026
improved logging for preauth releaser
#### 1.0.29 - 08 January 2026
added count down before exiting the preauth releaser 20 seconds
#### 1.0.28 - 10 December 2025
added preauth releaser
#### 1.0.27 - 10 December 2025
updated handling AmountTooSmall response from creditcall
#### 1.0.26 - 10 December 2025
added route for taking preauthorization payment
#### 1.0.25 - 08 December 2025
return masked card number and expiry date in the payment success URL
#### 1.0.24 - 13 November 2025
improved logging for creditcall payment processing
#### 1.0.23 - 13 November 2025
moved handlers from main.go to handlers/handlers.go
#### 1.0.22 - 13 November 2025
added test mode into config file to allow testing without connecting to the dispenser
#### 1.0.21 - 20 October 2025
increased timeout for Salto lock server connection to 40 seconds
#### 1.0.20 - 06 October 2025
removed minutes from the start and expiry time in Salto lock command
#### 1.0.19 - 10 September 2025
allowed to continue if the connection to the lock server fails at startup
#### 1.0.18 - 04 September 2025
increased timeout for TLJ lock server connection to 30 seconds
#### 1.0.17 - 30 August 2025
added functionality to commit transactions
#### 1.0.15 - 27 August 2025
fixed TCP/IP connection to the lock server
#### 1.0.14 - 21 August 2025
fixed issue in creditcall payment processing where error description was not properly set
#### 1.0.13 - 21 August 2025
TCP/IP connection to the lock server is now established before encoding the keycard and closedafter the encoding is done.
#### 1.0.12 - 11 August 2025
added delay before checking dispenser status
#### 1.0.11 - 11 August 2025
updated Salto key encoding workflow
#### 1.0.10 - 08 August 2025
updated logging for TLJ locks
#### 1.0.9 - 08 August 2025
added TLJ lock server and implemented workflow for TLJ locks
#### 1.0.8 - 01 August 2025
improved error handling and logging in Salto
#### 1.0.7 - 25 July 2025
added check if the room exists
#### 1.0.6 - 25 July 2025
updated workflow for Salto locks
#### 1.0.5 - 24 July 2025
added encoding keycard copy for Salto locks
#### 1.0.4 - 22 July 2025
added salto lock server and implemented workflow for Salto
#### 1.0.0 - 30 June 2025
added creditcall payment method
`/starttransaction` - API payment endpoint to start a transaction
#### 0.9.1 - 22 May 2025
added lockserver interface and implemented workflow for Omnitec
#### 0.9.0 - 22 May 2025
The new API has two new endpoints:
- `/issuedoorcard` - encoding the door card for the room.
- `/printroomticket` - printing the room ticket.