refactor(hardlink): migrate Go module to v2

This commit is contained in:
2026-11-04 18:50:00 +00:00
parent 814d87768d
commit e07afd9df1
55 changed files with 1187 additions and 131 deletions
+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.
+209
View File
@@ -0,0 +1,209 @@
## Release notes
`buildVersion` is a const in `cmd/hardlink/main.go`.
#### v2.2.1 - Unreleased
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.