Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf84caecc8 | ||
|
|
c2e640a720 | ||
|
|
242af6063b | ||
|
|
3aae843011 | ||
|
|
e07afd9df1 | ||
|
|
814d87768d | ||
|
|
568adc034b | ||
|
|
8c5e61efd0 | ||
|
|
28aea4aab2 | ||
|
|
8a5325414b |
@@ -1,124 +0,0 @@
|
|||||||
# CreditCall payment streaming
|
|
||||||
|
|
||||||
Deploy ChipDNAClientCLI, then hardlink, then Operafyne. No database or configuration
|
|
||||||
migration is needed. The existing CreditCall provider selection enables the new
|
|
||||||
SALE and PREAUTH routes; CreditCall does not implement the generic payment provider interface.
|
|
||||||
|
|
||||||
## Contracts
|
|
||||||
|
|
||||||
`POST /api/payment/sale` accepts the existing JSON sale request, for example
|
|
||||||
`{"amount":1234,"confirmNo":"BOOKING-123","currency":"GBP"}`. Amount remains in
|
|
||||||
minor units. CreditCall uses its existing SDK transaction reference generation.
|
|
||||||
|
|
||||||
`POST /api/payment/preauth` accepts string fields `amount`, `transactionType`
|
|
||||||
and `checkoutDate`. Positive preauth sends the existing `Sale` input and checkout
|
|
||||||
string; zero-value verification sends `{"amount":"","transactionType":"AccountVerification","checkoutDate":""}`.
|
|
||||||
The returned `ACCOUNT VERIFICATION` type is matched case-insensitively and succeeds
|
|
||||||
without persistence. Returned approved `SALE` schedules existing SQL persistence
|
|
||||||
using provider-returned `TOTAL_AMOUNT`, never the request amount. PREAUTH does not
|
|
||||||
confirm. Checkout remains departure-derived midnight UTC in the existing string
|
|
||||||
format; SQL's existing date conversion and 48-hour release calculation are unchanged.
|
|
||||||
|
|
||||||
For CreditCall, responses contain newline-delimited JSON:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"type":"status","code":"PAYMENT_PRESENT_CARD"}
|
|
||||||
{"type":"result","result":{"outcome":"approved","message":"Payment approved","httpStatus":200,"status":{"code":200,"message":"Approved"},"transactionReference":"native-reference","cardType":"Visa","maskedCardNumber":"************1234","expiryDate":"1228","cardHash":"existing-hash","cardReference":"existing-card-reference"}}
|
|
||||||
```
|
|
||||||
|
|
||||||
`outcome` is `approved`, `declined`, `cancelled`, `timeout`, or `error`. Approval
|
|
||||||
is produced only by the shared CreditCall transaction/finalization core, including
|
|
||||||
SALE confirmation behavior; PREAUTH uses its existing unconfirmed-result rules. `httpStatus` preserves the equivalent legacy
|
|
||||||
operation status even after streaming commits HTTP 200. `status` preserves the
|
|
||||||
existing processor `StatusRec`. Failure `message` preserves the plain description
|
|
||||||
used by the legacy flow, including its existing interpretation quirks.
|
|
||||||
|
|
||||||
Card fields are emitted only on success. Unmasked or unexpected card-number data
|
|
||||||
is omitted; encoding is not masking. Receipts and raw SDK parameter bags are not
|
|
||||||
sent to Operafyne. The new adapter never builds a redirect URL. Dojo and PayBridge
|
|
||||||
continue using their existing `{"type":"result","response":...}` contract.
|
|
||||||
|
|
||||||
Hardlink calls `POST /start-transaction-stream/` on ChipDNAClientCLI with
|
|
||||||
`{"amount":"1234","transactionType":"Sale"}`. Its NDJSON consists of allowlisted
|
|
||||||
`status` frames (`source`, `value`), a single `result` containing allowlisted SDK
|
|
||||||
fields, or a sanitized `error`. `TRANSACTION_TYPE` and optional `TOTAL_AMOUNT`
|
|
||||||
are included only when returned by the provider. They are never synthesized and
|
|
||||||
are not added to the kiosk-facing result. AccountVerification normally omits
|
|
||||||
`TOTAL_AMOUNT`. Receipt XML may be a JSON string field needed by
|
|
||||||
hardlink's existing receipt handler; it is never a raw line in the stream.
|
|
||||||
SALE confirmation continues through the existing, separate XML endpoint.
|
|
||||||
|
|
||||||
## Lifetime and compatibility
|
|
||||||
|
|
||||||
- `/start-transaction/`, `/takepayment`, and `/takepreauth` retain their existing
|
|
||||||
external contracts. Both SALE and PREAUTH now stream to Operafyne; existing SQL
|
|
||||||
persistence/release behavior remains unchanged.
|
|
||||||
- Operafyne uses a private 120-second CreditCall client for SALE and PREAUTH.
|
|
||||||
This is only the kiosk wait boundary; Dojo/PayBridge clients are unchanged.
|
|
||||||
Timeout/cancellation is technical, not an authoritative decline or automatically
|
|
||||||
retryable result. It never triggers a second start or legacy endpoint fallback.
|
|
||||||
- Validation uses the inbound request. At financial dispatch handoff, hardlink
|
|
||||||
detaches cancellation with `context.WithoutCancel`. Inbound cancellation and
|
|
||||||
write failures control only delivery; result processing, SALE confirmation,
|
|
||||||
receipts and PREAUTH persistence scheduling continue independently.
|
|
||||||
- Start and each SALE confirmation call retain their independent 300-second timeout.
|
|
||||||
Confirmation still uses two attempts, retrying transport/read errors with the
|
|
||||||
existing two-second delay. The generic whole-operation timeout is not used.
|
|
||||||
- Kiosk cancellation or failed/blocked kiosk delivery does not cancel upstream reading,
|
|
||||||
confirmation, receipt handling, or PREAUTH persistence scheduling. Progress queues may drop hints when full;
|
|
||||||
final results have a separate slot and are delivered at most once.
|
|
||||||
- Only the response writer writes frames. Transaction execution never waits
|
|
||||||
for progress delivery. No additional delivery timer or whole-operation deadline
|
|
||||||
shortens the existing HTTP call bounds.
|
|
||||||
- Native SDK 3.17 updates use `UPDATE`; card notifications use `NOTIFICATION`,
|
|
||||||
retained as `CARD_STATUS` on the internal wire. Normal progress does not require
|
|
||||||
a reference: it is accepted only inside the existing serial transaction's active
|
|
||||||
observational window. A supplied nonempty reference must match. The window opens
|
|
||||||
immediately before the SDK start call and closes immediately at
|
|
||||||
`TransactionFinished`; finalization never waits for card removal.
|
|
||||||
- `CardRemovalRequested` and `CardRemovalEnforced` follow the same active-window
|
|
||||||
rule as other progress, including when no reference is supplied. Real Miura
|
|
||||||
insertion-recovery sequences can repeat present-card and remove-card prompts
|
|
||||||
within one transaction; these repeated prompts are not deduplicated. Outside
|
|
||||||
the active window they are discarded. `Removed` remains omitted even with a
|
|
||||||
reference, and the existing `Inserted` mapping is unchanged.
|
|
||||||
- Ownership is best-effort UI observation. SDK 3.17 does not establish that every
|
|
||||||
queued reference-less callback, including removal, has drained before another transaction
|
|
||||||
starts. Such a callback may briefly display stale progress in a later active
|
|
||||||
window. This accepted limitation must never affect success, decline, cancellation,
|
|
||||||
timeout outcomes, confirmation, retry, receipts, PMS posting, or business state.
|
|
||||||
- After timeout, an ambiguous start error, an asynchronous SDK error during an
|
|
||||||
active window, or reference reuse/overlap, progress remains suppressed for that
|
|
||||||
`Client` lifetime across SALE and PREAUTH. New transactions, elapsed time, callbacks and automatic
|
|
||||||
reconnect do not reset the guard. Payments remain enabled.
|
|
||||||
- Only the exact synchronous `ClientNotConnectedToServer` error safely clears an
|
|
||||||
unsuppressed window and releases its unused reference: SDK 3.17 `StartCommand`
|
|
||||||
returns it before `SendRequest`. Validation errors, mixed errors and all other
|
|
||||||
unproven errors suppress observation. Safe pre-dispatch rejection never clears
|
|
||||||
an existing suppression latch.
|
|
||||||
- Progress cannot approve, decline, confirm, cancel, or retry a transaction.
|
|
||||||
`OnlineAuthCompleted` means waiting; `Removed` and unknown events are omitted.
|
|
||||||
|
|
||||||
## Automated verification
|
|
||||||
|
|
||||||
In hardlink, use `go test -count=1 -skip '^Test_SendMail$' ./...` to exclude the
|
|
||||||
existing test that sends real email. Focused tests cover legacy parity, malformed
|
|
||||||
XML/NDJSON, retained confirmation fields and receipts, retries, disconnects,
|
|
||||||
backpressure, field filtering, and conservative status mapping. Race checks cover
|
|
||||||
the changed handler and mapper packages. No test proves absence of orphan holds.
|
|
||||||
|
|
||||||
In ChipDNAClientCLI, build `ChipDnaClient.sln` and `Tests/StreamingTests.csproj`
|
|
||||||
with MSBuild, then run `Tests/bin/Debug/ChipDNAClient.StreamingTests.exe`. The
|
|
||||||
test executable links the production streaming code and needs no terminal.
|
|
||||||
|
|
||||||
In Operafyne, run `go test -count=1 ./...`; the service tests cover structured
|
|
||||||
CreditCall SALE/PREAUTH, unchanged legacy requests, the 120-second UX boundary,
|
|
||||||
cancellation after dispatch, failure/retry parity, and existing
|
|
||||||
Dojo/PayBridge response handling. Run `go vet ./...`, `go build ./...`, and
|
|
||||||
`git diff --check` in both Go repositories.
|
|
||||||
|
|
||||||
Physical account-verification testing confirmed approved `ACCOUNT VERIFICATION`
|
|
||||||
with no `TOTAL_AMOUNT`. A monetary `/takepayment` test confirmed returned minor
|
|
||||||
units; positive PREAUTH through the new transport still needs physical Miura
|
|
||||||
validation. Automated tests do not replace that check. Receipt fields such as
|
|
||||||
`NoChargeDeclaration` retain the existing provider-entry rendering behavior.
|
|
||||||
@@ -1,153 +1,36 @@
|
|||||||
# Access Point
|
# Hardlink
|
||||||
|
|
||||||
This service handles door card issuance and room ticket printing for hotels. It interacts with the card dispenser over serial, the Assa Abloy lock server, and prints receipts.
|
Hardlink is the Windows hotel-kiosk service for K720 card dispensing, door-key
|
||||||
|
encoding, room-ticket and payment-receipt printing, and terminal payments. It
|
||||||
|
supports Assa Abloy, Omnitec, Salto, TLJ and dormakaba lock servers, and CreditCall
|
||||||
|
(ChipDNA), Dojo, PayBridge and Trust Payments providers.
|
||||||
|
|
||||||
## Deployment
|
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.
|
||||||
|
|
||||||
We use Salt for deployment. To build and deploy a new version:
|
## Documentation
|
||||||
|
|
||||||
1. **Push your branch** with a meaningful commit message:
|
- [Configuration](docs/configuration.md): local service/device settings,
|
||||||
```bash
|
room-ticket layout and CMS-only Trust configuration.
|
||||||
git push origin <branch>
|
- [Operations](docs/operations.md): builds, deployment layout, hardware HTTP
|
||||||
```
|
endpoints, diagnostics, logs and offline verification.
|
||||||
2. **Tag and build**:
|
- [Payment API](docs/payment-api.md): unified Sale/PREAUTH requests, NDJSON
|
||||||
```bash
|
results, transaction ownership, receipts and CreditCall streaming details.
|
||||||
./tagbuild.sh
|
- [K720 hardware contract](docs/hardware/k720.md): preparation, uncertain-handoff
|
||||||
```
|
recovery, delivery clearance and maintenance invariants.
|
||||||
This script:
|
- [Release history](docs/releases.md).
|
||||||
- Builds the latest `hardlink.exe` binary
|
|
||||||
- Tags the repository with the new version
|
|
||||||
- Copies `hardlink_<tag>.exe` to `salt/hardlink/files`
|
|
||||||
3. **Commit the new binary** in Salt:
|
|
||||||
```bash
|
|
||||||
cd salt
|
|
||||||
git add hardlink/files/hardlink_<tag>.exe
|
|
||||||
git commit -m "added hardlink"
|
|
||||||
git push
|
|
||||||
```
|
|
||||||
4. **Update pillar** (`pillar/hardlink/init.sls`) to point to the new version.
|
|
||||||
5. **Apply the state** on your hosts:
|
|
||||||
```bash
|
|
||||||
salt '*' state.apply hardlink
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration
|
Hardlink owns payment-provider selection and terminal processing. The native
|
||||||
|
Fyne applications use the common Sale/PREAUTH contract and own their financial
|
||||||
|
calculations, PMS descriptions, PMS posting and guest journeys. Trust settings
|
||||||
|
come from CMS; no local `trust:` YAML section or currency-evidence flag is needed.
|
||||||
|
|
||||||
Place `config.yml` alongside `hardlink.exe`:
|
The deprecated XML payment routes remain solely for legacy compatibility.
|
||||||
|
`/testissuedoorcard` remains an operational diagnostic available on production
|
||||||
|
kiosks regardless of TestMode, and retains the encoded card inside the dispenser.
|
||||||
|
|
||||||
```yaml
|
Historical plans and independent audits remain unchanged in the local
|
||||||
port: 9091
|
`docs/archive/` collection. They are excluded from this module-migration commit
|
||||||
lockservUrl: "http://192.168.4.109:4000"
|
and are not current operating instructions.
|
||||||
encoderAddr: "1"
|
|
||||||
dispensPort: "COM9"
|
|
||||||
dispensAddr: "15"
|
|
||||||
printerName: "EPSON TM-T82II Receipt"
|
|
||||||
logdir: "./logs"
|
|
||||||
```
|
|
||||||
|
|
||||||
Provide `TicketLayout.xml` for print layout:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<LayoutOptions>
|
|
||||||
<LogoPath>C:/Logo/logo.png</LogoPath>
|
|
||||||
<TopMostText>Welcome to The Bike and Boot</TopMostText>
|
|
||||||
<BeforeRoomNumberText>Your room number is</BeforeRoomNumberText>
|
|
||||||
<BeforeDirectionsText></BeforeDirectionsText>
|
|
||||||
<HotelSpecificDetails>This is the hotel details section</HotelSpecificDetails>
|
|
||||||
<CheckOutTimeText>Check Out Time</CheckOutTimeText>
|
|
||||||
<RoomMapFolderPath>C:/Logo/Roommaps</RoomMapFolderPath>
|
|
||||||
</LayoutOptions>
|
|
||||||
```
|
|
||||||
|
|
||||||
## Build & Run
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Install dependencies
|
|
||||||
go mod tidy
|
|
||||||
|
|
||||||
# Build the executable
|
|
||||||
go build -o hardlink.exe
|
|
||||||
|
|
||||||
# Run
|
|
||||||
./hardlink.exe
|
|
||||||
```
|
|
||||||
|
|
||||||
The HTTP server listens on `http://localhost:<port>` (default `9091`).
|
|
||||||
|
|
||||||
## API Endpoints
|
|
||||||
|
|
||||||
### 1. Issue Door Card
|
|
||||||
|
|
||||||
- **Endpoint**: `POST /issuedoorcard`
|
|
||||||
- **Headers**: `Content-Type: application/json`
|
|
||||||
- **Body**:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"roomField": "101",
|
|
||||||
"checkinTime": "2025-04-08 11:16:05 +0100",
|
|
||||||
"checkoutTime": "2025-04-08 12:00:00 +0100",
|
|
||||||
"followStr": "0"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
- **Responses**:
|
|
||||||
- `200 OK`
|
|
||||||
```json
|
|
||||||
{ "Code": 200, "Message": "Card issued successfully" }
|
|
||||||
```
|
|
||||||
- `4XX` / `5XX`
|
|
||||||
```json
|
|
||||||
{ "Code": <status>, "Message": "<error>" }
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Print Room Ticket
|
|
||||||
|
|
||||||
- **Endpoint**: `POST /printroomticket`
|
|
||||||
- **Headers**: `Content-Type: application/xml`
|
|
||||||
- **Body**:
|
|
||||||
```xml
|
|
||||||
<roomdetails>
|
|
||||||
<customername>John Doe</customername>
|
|
||||||
<checkoutdatetime>16/05/2025 11:00 am</checkoutdatetime>
|
|
||||||
<roomno>103</roomno>
|
|
||||||
<roommap>map.png</roommap>
|
|
||||||
<roomdirections>Follow corridor...</roomdirections>
|
|
||||||
</roomdetails>
|
|
||||||
```
|
|
||||||
- **Responses**:
|
|
||||||
- `200 OK`
|
|
||||||
```json
|
|
||||||
{ "Code": 200, "Message": "Print job sent successfully" }
|
|
||||||
```
|
|
||||||
- `4XX` / `5XX`
|
|
||||||
```json
|
|
||||||
{ "Code": <status>, "Message": "<error>" }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Packages
|
|
||||||
|
|
||||||
### `main`
|
|
||||||
- Entry point: reads config, sets up logging, initializes dispenser and lock server, loads print layout, and starts HTTP server.
|
|
||||||
|
|
||||||
### `dispenser`
|
|
||||||
- Communicates with the card dispenser via serial port.
|
|
||||||
- Commands: check status, move card, eject card.
|
|
||||||
|
|
||||||
### `lockserver`
|
|
||||||
- Manages TCP connection to the Assa Abloy lock server.
|
|
||||||
- Sends heartbeat and encoding commands.
|
|
||||||
|
|
||||||
### `printer`
|
|
||||||
- Loads `TicketLayout.xml` into `LayoutOptions`.
|
|
||||||
- Provides `printLogo`, `printMap`, `BuildRoomTicket`, `SendToPrinter`.
|
|
||||||
- Converts images to ESC/POS raster commands with dithering and transparency support.
|
|
||||||
|
|
||||||
### `cmstypes`
|
|
||||||
- Defines JSON and XML payload structures for door cards and room details.
|
|
||||||
|
|
||||||
## Logging
|
|
||||||
|
|
||||||
Logs are written in JSON format to `<logdir>/hardlink.log`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
MIT © FutureSens Systems
|
|
||||||
|
|||||||
+31
-47
@@ -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.1.2"
|
buildVersion = "v2.2.5"
|
||||||
serviceName = "hardlink"
|
serviceName = "hardlink"
|
||||||
pollingFrequency = 8 * time.Second
|
pollingFrequency = 8 * time.Second
|
||||||
)
|
)
|
||||||
@@ -46,10 +46,6 @@ func main() {
|
|||||||
lockserver.LockServerURL = cfg.LockserverURL
|
lockserver.LockServerURL = cfg.LockserverURL
|
||||||
mail.SendErrorEmails = cfg.SendErrorEmails
|
mail.SendErrorEmails = cfg.SendErrorEmails
|
||||||
|
|
||||||
// Root context for background goroutines
|
|
||||||
// rootCtx, rootCancel := context.WithCancel(context.Background())
|
|
||||||
// defer rootCancel()
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
dispPort *serial.Port
|
dispPort *serial.Port
|
||||||
disp *dispenser.Client
|
disp *dispenser.Client
|
||||||
@@ -123,17 +119,22 @@ func main() {
|
|||||||
log.Info("Payment processing is enabled")
|
log.Info("Payment processing is enabled")
|
||||||
|
|
||||||
var provider paymentsvc.Provider
|
var provider paymentsvc.Provider
|
||||||
reservationSystem, err := cms.ReadHotel(cfg.Hotel, cfg.CMSBaseURL)
|
hotel, err := cms.ReadHotelDetails(cfg.Hotel, cfg.CMSBaseURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Failed to read hotel from CMS", fmt.Errorf("failed to read hotel from CMS: %v", err))
|
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Failed to read hotel from CMS", fmt.Errorf("failed to read hotel from CMS: %v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
reservationSystem := hotel.ReservationSystem
|
||||||
paymentProvider := reservationSystem.PaymentSystem
|
paymentProvider := reservationSystem.PaymentSystem
|
||||||
if paymentProvider == 0 {
|
if paymentProvider == 0 {
|
||||||
paymentProvider = cms.PaymentSystemIndex(cfg.PaymentProvider)
|
paymentProvider = cms.PaymentSystemIndex(cfg.PaymentProvider)
|
||||||
}
|
}
|
||||||
|
|
||||||
switch paymentProvider {
|
switch paymentProvider {
|
||||||
|
case cmstypes.PaySystemTrustPayments:
|
||||||
|
if err := configureTrust(app, cfg, hotel); err != nil {
|
||||||
|
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Failed to initialize Trust Payments", err)
|
||||||
|
}
|
||||||
case cmstypes.PaySystemCreditCall:
|
case cmstypes.PaySystemCreditCall:
|
||||||
// CreditCall streaming shares its proven legacy transaction core.
|
// CreditCall streaming shares its proven legacy transaction core.
|
||||||
app.EnableCreditCallStreaming()
|
app.EnableCreditCallStreaming()
|
||||||
@@ -152,9 +153,6 @@ func main() {
|
|||||||
log.Infof("PDQ available: %v", pdqStatus.IsAvailable)
|
log.Infof("PDQ available: %v", pdqStatus.IsAvailable)
|
||||||
}()
|
}()
|
||||||
|
|
||||||
log.Info("CreditCall payment provider enabled")
|
|
||||||
fmt.Println("CreditCall payment provider enabled")
|
|
||||||
|
|
||||||
case cmstypes.PaySystemPayBridge:
|
case cmstypes.PaySystemPayBridge:
|
||||||
websocketURL := pdqSerialForKiosk(reservationSystem.PDQs, cfg.Kiosk)
|
websocketURL := pdqSerialForKiosk(reservationSystem.PDQs, cfg.Kiosk)
|
||||||
|
|
||||||
@@ -165,11 +163,13 @@ func main() {
|
|||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Payment Gateway API Key not found", fmt.Errorf("payment provider paybridge requires paybridge.api_key"))
|
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Payment Gateway API Key not found", fmt.Errorf("payment provider paybridge requires paybridge.api_key"))
|
||||||
}
|
}
|
||||||
|
|
||||||
provider = paybridge.NewClient(
|
payBridgeClient := paybridge.NewClient(
|
||||||
websocketURL,
|
websocketURL,
|
||||||
reservationSystem.PaymentGatewayAPIKeyWeb,
|
reservationSystem.PaymentGatewayAPIKeyWeb,
|
||||||
cfg.TimeoutSeconds,
|
cfg.TimeoutSeconds,
|
||||||
)
|
)
|
||||||
|
payBridgeClient.PrintReceipt = printer.PrintSaleReceipt
|
||||||
|
provider = payBridgeClient
|
||||||
|
|
||||||
case cmstypes.PaySystemDojo:
|
case cmstypes.PaySystemDojo:
|
||||||
TerminalID := pdqSerialForKiosk(reservationSystem.PDQs, cfg.Kiosk)
|
TerminalID := pdqSerialForKiosk(reservationSystem.PDQs, cfg.Kiosk)
|
||||||
@@ -182,6 +182,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dojoClient, err := dojo.NewClient(dojo.Config{
|
dojoClient, err := dojo.NewClient(dojo.Config{
|
||||||
|
PrintReceipt: printer.PrintSaleReceipt,
|
||||||
BaseURL: reservationSystem.PaymentGatewayURL,
|
BaseURL: reservationSystem.PaymentGatewayURL,
|
||||||
APIKey: reservationSystem.PaymentGatewayAPIKeyWeb,
|
APIKey: reservationSystem.PaymentGatewayAPIKeyWeb,
|
||||||
SoftwareHouseID: reservationSystem.PaymentGatewaySiteIDEPOS,
|
SoftwareHouseID: reservationSystem.PaymentGatewaySiteIDEPOS,
|
||||||
@@ -195,21 +196,22 @@ func main() {
|
|||||||
provider = dojoClient
|
provider = dojoClient
|
||||||
|
|
||||||
case cmstypes.PaySystemNone:
|
case cmstypes.PaySystemNone:
|
||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "No payment provider selected", fmt.Errorf("payment processing is enabled, but no payment provider selected; expected creditcall, paybridge or dojo"))
|
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "No payment provider selected", fmt.Errorf("payment processing is enabled, but no payment provider selected; expected creditcall, trustpayments, paybridge or dojo"))
|
||||||
|
|
||||||
default:
|
default:
|
||||||
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Unsupported Payment Provider", fmt.Errorf(
|
errorhandlers.FatalErrorWithMail(cfg.Hotel, cfg.Kiosk, "Unsupported Payment Provider", fmt.Errorf(
|
||||||
"unsupported payment provider %q; expected creditcall, paybridge or dojo",
|
"unsupported payment provider %q; expected creditcall, trustpayments, paybridge or dojo",
|
||||||
cfg.PaymentProvider,
|
cfg.PaymentProvider,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
// PayBridge and Dojo use the generic payment service.
|
// All modern endpoint providers use the same payment service.
|
||||||
if provider != nil {
|
if provider != nil {
|
||||||
app.SetPaymentService(paymentsvc.NewService(provider))
|
app.SetPaymentService(paymentsvc.NewService(provider))
|
||||||
log.Infof("Payment provider enabled for POST /api/payment/sale: %s", cmstypes.PaySystemNames[paymentProvider])
|
|
||||||
fmt.Printf("Payment provider enabled for POST /api/payment/sale: %s\n", cmstypes.PaySystemNames[paymentProvider])
|
|
||||||
}
|
}
|
||||||
|
app.SetPaymentCurrency(hotel.Currency.Code)
|
||||||
|
log.Infof("Payment provider enabled for POST /api/payment/sale: %s", cmstypes.PaySystemNames[paymentProvider])
|
||||||
|
fmt.Printf("Payment provider enabled for POST /api/payment/sale: %s\n", cmstypes.PaySystemNames[paymentProvider])
|
||||||
} else {
|
} else {
|
||||||
fmt.Println("Payment processing is disabled")
|
fmt.Println("Payment processing is disabled")
|
||||||
log.Info("Payment processing is disabled")
|
log.Info("Payment processing is disabled")
|
||||||
@@ -242,24 +244,6 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// func readTicketLayout() printer.LayoutOptions {
|
|
||||||
// const layoutName = "TicketLayout.xml"
|
|
||||||
// var layout printer.LayoutOptions
|
|
||||||
|
|
||||||
// // 1) Read the file
|
|
||||||
// data, err := os.ReadFile(layoutName)
|
|
||||||
// if err != nil {
|
|
||||||
// errorhandlers.FatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // 2) Unmarshal into your struct
|
|
||||||
// if err := xml.Unmarshal(data, &layout); err != nil {
|
|
||||||
// errorhandlers.FatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
|
|
||||||
// }
|
|
||||||
|
|
||||||
// return layout
|
|
||||||
// }
|
|
||||||
|
|
||||||
func startChipDnaClient() {
|
func startChipDnaClient() {
|
||||||
startClient := func() (*exec.Cmd, error) {
|
startClient := func() (*exec.Cmd, error) {
|
||||||
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
|
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
type startupFixtureStop struct{}
|
||||||
|
type startupLogHook struct{}
|
||||||
|
|
||||||
|
func (startupLogHook) Levels() []log.Level { return log.AllLevels }
|
||||||
|
func (startupLogHook) Fire(entry *log.Entry) error {
|
||||||
|
if strings.HasPrefix(entry.Message, "Payment provider enabled for POST /api/payment/sale:") {
|
||||||
|
if err := os.WriteFile("provider-started.txt", []byte(entry.Message), 0600); err != nil {
|
||||||
|
os.Exit(92)
|
||||||
|
}
|
||||||
|
// Stop before main binds HTTP or admits any financial/device operation.
|
||||||
|
panic(startupFixtureStop{})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// This child process executes the real startup/fatal-notification path. TestMode
|
||||||
|
// and TLJ bypass devices; missing DB configuration returns before opening SQL.
|
||||||
|
func TestPostAuditStartupFixture(t *testing.T) {
|
||||||
|
scenario := os.Getenv("HARDLINK_POST_AUDIT_STARTUP")
|
||||||
|
if scenario == "" {
|
||||||
|
t.Skip("isolated startup fixture")
|
||||||
|
}
|
||||||
|
hotel := syntheticTrustHotel()
|
||||||
|
switch scenario {
|
||||||
|
case "gateway":
|
||||||
|
hotel.ReservationSystem.PaymentGatewayURL = ""
|
||||||
|
case "password":
|
||||||
|
hotel.ReservationSystem.PaymentGatewayPasswordEPOS = ""
|
||||||
|
case "ped":
|
||||||
|
hotel.ReservationSystem.PDQs = nil
|
||||||
|
case "timezone":
|
||||||
|
hotel.ReservationSystem.TimeZone = "SYNTH/INVALID"
|
||||||
|
case "none":
|
||||||
|
hotel.ReservationSystem.PaymentSystem = cmstypes.PaySystemNone
|
||||||
|
case "unsupported":
|
||||||
|
hotel.ReservationSystem.PaymentSystem = 999
|
||||||
|
case "ready":
|
||||||
|
default:
|
||||||
|
t.Fatal("unrecognized synthetic startup scenario")
|
||||||
|
}
|
||||||
|
transport := cmsTrustTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
var body []byte
|
||||||
|
switch r.URL.Hostname() {
|
||||||
|
case "cms.invalid":
|
||||||
|
response := cmstypes.HotelResponseRec{TheHotel: hotel}
|
||||||
|
response.Status.Code = cmstypes.StatusSuccessCode
|
||||||
|
var err error
|
||||||
|
body, err = json.Marshal(response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case "api.mailjet.com":
|
||||||
|
var notification struct {
|
||||||
|
Messages []struct{ Subject, TextPart string }
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(¬ification); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Retain only notification text, never headers or API authentication.
|
||||||
|
encoded, err := json.Marshal(notification)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile("notification.json", encoded, 0600); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = []byte(`{"Messages":[{"Status":"success"}]}`)
|
||||||
|
default:
|
||||||
|
if err := os.WriteFile("unexpected-network.txt", []byte("rejected non-mock request"), 0600); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return nil, errors.New("offline startup fixture prohibits network")
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(string(body)))}, nil
|
||||||
|
})
|
||||||
|
http.DefaultTransport = transport
|
||||||
|
http.DefaultClient = &http.Client{Transport: transport}
|
||||||
|
log.AddHook(startupLogHook{})
|
||||||
|
defer func() {
|
||||||
|
if stopped := recover(); stopped != nil {
|
||||||
|
if _, ok := stopped.(startupFixtureStop); !ok {
|
||||||
|
panic(stopped)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
main()
|
||||||
|
t.Fatal("startup fixture unexpectedly returned from main")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustStartupUsesExistingFatalNotification(t *testing.T) {
|
||||||
|
for _, tc := range []struct{ name, field string }{
|
||||||
|
{"gateway", "PaymentGatewayURL"}, {"password", "PaymentGatewayPasswordEPOS"},
|
||||||
|
{"ped", "PED"}, {"timezone", "TimeZone"},
|
||||||
|
{"none", "expected creditcall, trustpayments, paybridge or dojo"},
|
||||||
|
{"unsupported", "expected creditcall, trustpayments, paybridge or dojo"},
|
||||||
|
{"ready", ""},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
configuration := "hotel: SYNTH-HOTEL\nkiosk: 9\nlockType: tlj\ntestMode: true\nisPayment: true\ncmsurl: http://cms.invalid\nsenderroremails:\n - operator@example.test\nlogdir: ./logs\n"
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "config.yml"), []byte(configuration), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
process := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestPostAuditStartupFixture$")
|
||||||
|
process.Dir = dir
|
||||||
|
process.Env = append(os.Environ(), "HARDLINK_POST_AUDIT_STARTUP="+tc.name)
|
||||||
|
process.Stdin = strings.NewReader("\n")
|
||||||
|
output, err := process.CombinedOutput()
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
t.Fatalf("Startup(%s) timed out: %v", tc.name, ctx.Err())
|
||||||
|
}
|
||||||
|
if tc.name == "ready" {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Startup(ready) error=%v output=%s, want successful synthetic initialization", err, output)
|
||||||
|
}
|
||||||
|
started, readErr := os.ReadFile(filepath.Join(dir, "provider-started.txt"))
|
||||||
|
if readErr != nil || !strings.HasSuffix(string(started), "trustpayments") {
|
||||||
|
t.Errorf("Startup(ready) log=%q error=%v, want common Trust provider-enabled log", started, readErr)
|
||||||
|
}
|
||||||
|
if _, statErr := os.Stat(filepath.Join(dir, "notification.json")); !os.IsNotExist(statErr) {
|
||||||
|
t.Errorf("Startup(ready) notification error=%v, want no failure notification", statErr)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var exitError *exec.ExitError
|
||||||
|
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
|
||||||
|
t.Fatalf("Startup(%s) error=%v output=%s, want fatal exit1", tc.name, err, output)
|
||||||
|
}
|
||||||
|
notification, readErr := os.ReadFile(filepath.Join(dir, "notification.json"))
|
||||||
|
if readErr != nil {
|
||||||
|
t.Fatalf("Startup(%s) notification error=%v, want existing fatal mail attempted", tc.name, readErr)
|
||||||
|
}
|
||||||
|
text := string(notification)
|
||||||
|
for _, want := range []string{"SYNTH-HOTEL", "kiosk: 9", tc.field} {
|
||||||
|
if !strings.Contains(text, want) {
|
||||||
|
t.Errorf("Startup(%s) notification missing %q", tc.name, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tc.name != "none" && tc.name != "unsupported" && !strings.Contains(text, "Failed to initialize Trust Payments") {
|
||||||
|
t.Errorf("Startup(%s) notification lacks Trust initialization title", tc.name)
|
||||||
|
}
|
||||||
|
logs, _ := os.ReadFile(filepath.Join(dir, "logs", "hardlink.log"))
|
||||||
|
for _, secret := range []string{"SYNTH-PASSWORD", "SYNTH-PED"} {
|
||||||
|
if strings.Contains(text+string(output)+string(logs), secret) {
|
||||||
|
t.Errorf("Startup(%s) diagnostic leaked synthetic secret %q", tc.name, secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, statErr := os.Stat(filepath.Join(dir, "unexpected-network.txt")); !os.IsNotExist(statErr) {
|
||||||
|
t.Errorf("Startup(%s) attempted a non-mock request", tc.name)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProviderEnabledLoggingIsSharedByAllSelections(t *testing.T) {
|
||||||
|
file, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var paymentBody *ast.BlockStmt
|
||||||
|
ast.Inspect(file, func(node ast.Node) bool {
|
||||||
|
if statement, ok := node.(*ast.IfStmt); ok {
|
||||||
|
if condition, ok := statement.Cond.(*ast.SelectorExpr); ok && condition.Sel.Name == "IsPayment" {
|
||||||
|
paymentBody = statement.Body
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if paymentBody == nil {
|
||||||
|
t.Fatal("main has no payment startup block")
|
||||||
|
}
|
||||||
|
sharedMessages := 0
|
||||||
|
for _, statement := range paymentBody.List {
|
||||||
|
expression, ok := statement.(*ast.ExprStmt)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
call, ok := expression.X.(*ast.CallExpr)
|
||||||
|
if !ok || len(call.Args) != 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
format, ok := call.Args[0].(*ast.BasicLit)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text, err := strconv.Unquote(format.Value)
|
||||||
|
if err != nil || !strings.HasPrefix(text, "Payment provider enabled for POST /api/payment/sale:") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
index, ok := call.Args[1].(*ast.IndexExpr)
|
||||||
|
if !ok {
|
||||||
|
t.Error("common startup message does not use selected provider name")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name, ok := index.X.(*ast.SelectorExpr)
|
||||||
|
if !ok || name.Sel.Name != "PaySystemNames" {
|
||||||
|
t.Error("common startup message lost standard provider names")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sharedMessages++
|
||||||
|
}
|
||||||
|
if sharedMessages != 2 {
|
||||||
|
t.Errorf("main has %d unconditional common provider messages, want logging and console outside provider-specific branches", sharedMessages)
|
||||||
|
}
|
||||||
|
for _, provider := range []int{cmstypes.PaySystemCreditCall, cmstypes.PaySystemTrustPayments, cmstypes.PaySystemDojo, cmstypes.PaySystemPayBridge} {
|
||||||
|
if cmstypes.PaySystemNames[provider] == "" {
|
||||||
|
t.Errorf("common startup name for provider%d is empty", provider)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/handlers"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
|
||||||
|
)
|
||||||
|
|
||||||
|
func configureTrust(app *handlers.App, cfg config.ConfigRec, hotel cmstypes.Hotel) error {
|
||||||
|
res := hotel.ReservationSystem
|
||||||
|
serial, count := "", 0
|
||||||
|
for _, pdq := range res.PDQs {
|
||||||
|
if pdq.Kiosk == cfg.Kiosk {
|
||||||
|
serial = pdq.Serial
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count != 1 || serial == "" {
|
||||||
|
return errors.New("exactly one Trust PED serial required")
|
||||||
|
}
|
||||||
|
client, err := trustpayments.New(
|
||||||
|
trustpayments.Config{
|
||||||
|
BaseURL: res.PaymentGatewayURL,
|
||||||
|
SiteID: res.PaymentGatewaySiteIDEPOS,
|
||||||
|
Password: res.PaymentGatewayPasswordEPOS,
|
||||||
|
Terminal: serial,
|
||||||
|
Currency: hotel.Currency.Code,
|
||||||
|
Timezone: res.TimeZone})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
app.SetTrustPayments(client)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/cms"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/handlers"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
|
||||||
|
yaml "gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type cmsTrustTransport func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f cmsTrustTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
|
||||||
|
func syntheticTrustHotel() cmstypes.Hotel {
|
||||||
|
hotel := cmstypes.Hotel{Currency: cmstypes.CurrencyRec{Code: "GBP", NumDecimals: 2}}
|
||||||
|
hotel.Updated = 1
|
||||||
|
hotel.ReservationSystem = cmstypes.ReservationSystemRec{PaymentSystem: cmstypes.PaySystemTrustPayments, PaymentGatewayURL: "https://sandbox.link.trustpayments.com/trustpayments/rest", PaymentGatewaySiteIDEPOS: "SYNTH-SITE", PaymentGatewayPasswordEPOS: "SYNTH-PASSWORD", TimeZone: "Europe/London", PDQs: []cmstypes.PDQRec{{Kiosk: 4, Serial: "OTHER-PED"}, {Kiosk: 9, Serial: "SYNTH-PED"}}}
|
||||||
|
return hotel
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureTrustUsesCMSWithoutLocalTrustYAML(t *testing.T) {
|
||||||
|
var cfg config.ConfigRec
|
||||||
|
if err := yaml.Unmarshal([]byte("hotel: SYNTH-HOTEL\nkiosk: 9\nlockType: assaabloy\nisPayment: true\n"), &cfg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, exists := reflect.TypeOf(cfg).FieldByName("Trust"); exists {
|
||||||
|
t.Fatal("ConfigRec still exposes local Trust configuration")
|
||||||
|
}
|
||||||
|
hotel := syntheticTrustHotel()
|
||||||
|
var cmsCalls, financialCalls atomic.Int32
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cmsCalls.Add(1)
|
||||||
|
response := cmstypes.HotelResponseRec{TheHotel: hotel}
|
||||||
|
response.Status.Code = cmstypes.StatusSuccessCode
|
||||||
|
_ = json.NewEncoder(w).Encode(response)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
cfg.CMSBaseURL = server.URL
|
||||||
|
original := http.DefaultTransport
|
||||||
|
base := original.(*http.Transport).Clone()
|
||||||
|
base.Proxy = nil
|
||||||
|
dialer := &net.Dialer{}
|
||||||
|
base.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
if address != server.Listener.Addr().String() {
|
||||||
|
return nil, errors.New("offline test rejected non-mock dial")
|
||||||
|
}
|
||||||
|
return dialer.DialContext(ctx, network, address)
|
||||||
|
}
|
||||||
|
http.DefaultTransport = cmsTrustTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
if r.URL.Host == server.Listener.Addr().String() {
|
||||||
|
return base.RoundTrip(r)
|
||||||
|
}
|
||||||
|
if r.URL.Host != "sandbox.link.trustpayments.com" || r.URL.Path != "/trustpayments/rest/sale" {
|
||||||
|
return nil, errors.New("offline test rejected unregistered request")
|
||||||
|
}
|
||||||
|
financialCalls.Add(1)
|
||||||
|
var payload map[string]string
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if payload["siteid"] != hotel.ReservationSystem.PaymentGatewaySiteIDEPOS || payload["terminalserialnumber"] != "SYNTH-PED" || payload["amount"] != "25.00" {
|
||||||
|
t.Errorf("provider request = %v, want CMS credentials/PED and exact amount", payload)
|
||||||
|
}
|
||||||
|
wantToken := trustpayments.Token(hotel.ReservationSystem.PaymentGatewaySiteIDEPOS, payload["txndate"], payload["refid"], hotel.ReservationSystem.PaymentGatewayPasswordEPOS)
|
||||||
|
if r.Header.Get("token") != wantToken {
|
||||||
|
t.Error("request was not signed with CMS credentials")
|
||||||
|
}
|
||||||
|
location, _ := time.LoadLocation(hotel.ReservationSystem.TimeZone)
|
||||||
|
signedAt, err := time.ParseInLocation("2006-01-02:15:04:05", payload["txndate"], location)
|
||||||
|
if err != nil || time.Since(signedAt) < -time.Second || time.Since(signedAt) > 5*time.Second {
|
||||||
|
t.Errorf("CMS signing timezone was not used: %q/%v", payload["txndate"], err)
|
||||||
|
}
|
||||||
|
// A definite refusal exercises dispatch without invoking any receipt printer.
|
||||||
|
body, _ := json.Marshal(map[string]string{"refid": payload["refid"], "siteid": payload["siteid"], "terminalserialnumber": payload["terminalserialnumber"], "type": "sale", "resultcode": "Declined"})
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(body)))}, nil
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { http.DefaultTransport = original; base.CloseIdleConnections() })
|
||||||
|
loaded, err := cms.ReadHotelDetails(cfg.Hotel, cfg.CMSBaseURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if loaded.Currency != hotel.Currency {
|
||||||
|
t.Fatal("full CMS hotel currency was discarded")
|
||||||
|
}
|
||||||
|
app := handlers.NewApp(nil, cfg.LockType, "synthetic", "", nil, &cfg)
|
||||||
|
if err := configureTrust(app, cfg, loaded); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cmsCalls.Load() != 1 || financialCalls.Load() != 0 {
|
||||||
|
t.Fatal("initialization made extra CMS or financial requests")
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r := httptest.NewRequest("POST", "/api/payment/sale", strings.NewReader(`{"amount":2500,"currency":"DIFFERENT"}`))
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
if w.Code != 200 || !strings.Contains(w.Body.String(), `"outcome":"declined"`) || financialCalls.Load() != 1 {
|
||||||
|
t.Fatalf("CMS-only terminal request = HTTP %d/%s calls=%d", w.Code, w.Body.String(), financialCalls.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureTrustRejectsMissingEssentialCMSSettingsBeforeDispatch(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name, field string
|
||||||
|
change func(*cmstypes.Hotel)
|
||||||
|
}{
|
||||||
|
{"gateway", "PaymentGatewayURL", func(h *cmstypes.Hotel) { h.ReservationSystem.PaymentGatewayURL = "" }},
|
||||||
|
{"invalid gateway", "PaymentGatewayURL", func(h *cmstypes.Hotel) { h.ReservationSystem.PaymentGatewayURL = "http://synthetic.invalid" }},
|
||||||
|
{"site", "PaymentGatewaySiteIDEPOS", func(h *cmstypes.Hotel) { h.ReservationSystem.PaymentGatewaySiteIDEPOS = "" }},
|
||||||
|
{"password", "PaymentGatewayPasswordEPOS", func(h *cmstypes.Hotel) { h.ReservationSystem.PaymentGatewayPasswordEPOS = "" }},
|
||||||
|
{"missing PED", "PED", func(h *cmstypes.Hotel) { h.ReservationSystem.PDQs = nil }},
|
||||||
|
{"empty PED", "PED", func(h *cmstypes.Hotel) { h.ReservationSystem.PDQs[1].Serial = "" }},
|
||||||
|
{"duplicate PED", "PED", func(h *cmstypes.Hotel) {
|
||||||
|
h.ReservationSystem.PDQs = append(h.ReservationSystem.PDQs, h.ReservationSystem.PDQs[1])
|
||||||
|
}},
|
||||||
|
{"timezone", "TimeZone", func(h *cmstypes.Hotel) { h.ReservationSystem.TimeZone = "" }},
|
||||||
|
{"invalid timezone", "TimeZone", func(h *cmstypes.Hotel) { h.ReservationSystem.TimeZone = "SYNTH/INVALID" }},
|
||||||
|
{"machine timezone", "TimeZone", func(h *cmstypes.Hotel) { h.ReservationSystem.TimeZone = "Local" }},
|
||||||
|
}
|
||||||
|
var networkCalls atomic.Int32
|
||||||
|
original := http.DefaultTransport
|
||||||
|
http.DefaultTransport = cmsTrustTransport(func(*http.Request) (*http.Response, error) {
|
||||||
|
networkCalls.Add(1)
|
||||||
|
return nil, errors.New("offline test rejects all network")
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { http.DefaultTransport = original })
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
hotel := syntheticTrustHotel()
|
||||||
|
tc.change(&hotel)
|
||||||
|
err := configureTrust(&handlers.App{}, config.ConfigRec{Kiosk: 9}, hotel)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tc.field) || strings.Contains(err.Error(), "SYNTH-PASSWORD") {
|
||||||
|
t.Errorf("configureTrust(%s)=%v, want safe field-specific error", tc.name, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if networkCalls.Load() != 0 {
|
||||||
|
t.Fatalf("invalid CMS settings triggered %d requests", networkCalls.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-12
@@ -17,14 +17,20 @@ import (
|
|||||||
// ReadHotel gets the hotel record from CMS and returns its reservation system
|
// ReadHotel gets the hotel record from CMS and returns its reservation system
|
||||||
// configuration if the record has been updated since the last read.
|
// configuration if the record has been updated since the last read.
|
||||||
func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, error) {
|
func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, error) {
|
||||||
var reservationSystem cmstypes.ReservationSystemRec
|
hotel, err := ReadHotelDetails(hotelCode, CMSBaseURL)
|
||||||
|
return hotel.ReservationSystem, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadHotelDetails retains the complete hotel response, including its currency.
|
||||||
|
func ReadHotelDetails(hotelCode, CMSBaseURL string) (cmstypes.Hotel, error) {
|
||||||
|
var hotel cmstypes.Hotel
|
||||||
|
|
||||||
if hotelCode == "" {
|
if hotelCode == "" {
|
||||||
return reservationSystem, errors.New("hotel code is empty")
|
return hotel, errors.New("hotel code is empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
if CMSBaseURL == "" {
|
if CMSBaseURL == "" {
|
||||||
return reservationSystem, errors.New("CMS base URL is empty")
|
return hotel, errors.New("CMS base URL is empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
var request cmstypes.RequestRec
|
var request cmstypes.RequestRec
|
||||||
@@ -36,7 +42,7 @@ func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, err
|
|||||||
|
|
||||||
requestData, err := json.Marshal(request)
|
requestData, err := json.Marshal(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return reservationSystem, fmt.Errorf(
|
return hotel, fmt.Errorf(
|
||||||
"marshal CMS hotel request: %w",
|
"marshal CMS hotel request: %w",
|
||||||
err,
|
err,
|
||||||
)
|
)
|
||||||
@@ -46,7 +52,7 @@ func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, err
|
|||||||
|
|
||||||
req, err := http.NewRequest(http.MethodPost, requestURL, bytes.NewReader(requestData))
|
req, err := http.NewRequest(http.MethodPost, requestURL, bytes.NewReader(requestData))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return reservationSystem, fmt.Errorf(
|
return hotel, fmt.Errorf(
|
||||||
"create CMS hotel request: %w",
|
"create CMS hotel request: %w",
|
||||||
err,
|
err,
|
||||||
)
|
)
|
||||||
@@ -61,7 +67,7 @@ func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, err
|
|||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return reservationSystem, fmt.Errorf(
|
return hotel, fmt.Errorf(
|
||||||
"perform CMS hotel request: %w",
|
"perform CMS hotel request: %w",
|
||||||
err,
|
err,
|
||||||
)
|
)
|
||||||
@@ -70,7 +76,7 @@ func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, err
|
|||||||
|
|
||||||
body, err := io.ReadAll(resp.Body)
|
body, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return reservationSystem, fmt.Errorf(
|
return hotel, fmt.Errorf(
|
||||||
"read CMS hotel response: %w",
|
"read CMS hotel response: %w",
|
||||||
err,
|
err,
|
||||||
)
|
)
|
||||||
@@ -78,7 +84,7 @@ func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, err
|
|||||||
|
|
||||||
if resp.StatusCode < http.StatusOK ||
|
if resp.StatusCode < http.StatusOK ||
|
||||||
resp.StatusCode >= http.StatusMultipleChoices {
|
resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
return reservationSystem, fmt.Errorf(
|
return hotel, fmt.Errorf(
|
||||||
"CMS hotel request returned HTTP %s: %s",
|
"CMS hotel request returned HTTP %s: %s",
|
||||||
resp.Status,
|
resp.Status,
|
||||||
string(body),
|
string(body),
|
||||||
@@ -88,26 +94,26 @@ func ReadHotel(hotelCode, CMSBaseURL string) (cmstypes.ReservationSystemRec, err
|
|||||||
var hotelResponse cmstypes.HotelResponseRec
|
var hotelResponse cmstypes.HotelResponseRec
|
||||||
|
|
||||||
if err := json.Unmarshal(body, &hotelResponse); err != nil {
|
if err := json.Unmarshal(body, &hotelResponse); err != nil {
|
||||||
return reservationSystem, fmt.Errorf(
|
return hotel, fmt.Errorf(
|
||||||
"unmarshal CMS hotel response: %w",
|
"unmarshal CMS hotel response: %w",
|
||||||
err,
|
err,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if hotelResponse.Status.Code != cmstypes.StatusSuccessCode {
|
if hotelResponse.Status.Code != cmstypes.StatusSuccessCode {
|
||||||
return reservationSystem, fmt.Errorf(
|
return hotel, fmt.Errorf(
|
||||||
"CMS hotel request failed: %s",
|
"CMS hotel request failed: %s",
|
||||||
hotelResponse.Status.Message,
|
hotelResponse.Status.Message,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if hotelResponse.TheHotel.Updated <= -1 {
|
if hotelResponse.TheHotel.Updated <= -1 {
|
||||||
return reservationSystem, errors.New(
|
return hotel, errors.New(
|
||||||
"hotel record not updated since last read",
|
"hotel record not updated since last read",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return hotelResponse.TheHotel.ReservationSystem, nil
|
return hotelResponse.TheHotel, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func PaymentSystemIndex(name string) int {
|
func PaymentSystemIndex(name string) int {
|
||||||
|
|||||||
+5
-6
@@ -4,7 +4,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -17,7 +16,7 @@ func TestReadHotelSuccess(t *testing.T) {
|
|||||||
|
|
||||||
expected := cmstypes.ReservationSystemRec{}
|
expected := cmstypes.ReservationSystemRec{}
|
||||||
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(
|
server := newCMSMockServer(http.HandlerFunc(
|
||||||
func(w http.ResponseWriter, r *http.Request) {
|
func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
t.Errorf(
|
t.Errorf(
|
||||||
@@ -157,7 +156,7 @@ func TestReadHotelValidation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestReadHotelNotUpdated(t *testing.T) {
|
func TestReadHotelNotUpdated(t *testing.T) {
|
||||||
server := httptest.NewServer(http.HandlerFunc(
|
server := newCMSMockServer(http.HandlerFunc(
|
||||||
func(w http.ResponseWriter, _ *http.Request) {
|
func(w http.ResponseWriter, _ *http.Request) {
|
||||||
response := cmstypes.HotelResponseRec{}
|
response := cmstypes.HotelResponseRec{}
|
||||||
response.Status.Code = cmstypes.StatusSuccessCode
|
response.Status.Code = cmstypes.StatusSuccessCode
|
||||||
@@ -185,7 +184,7 @@ func TestReadHotelNotUpdated(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestReadHotelHTTPError(t *testing.T) {
|
func TestReadHotelHTTPError(t *testing.T) {
|
||||||
server := httptest.NewServer(http.HandlerFunc(
|
server := newCMSMockServer(http.HandlerFunc(
|
||||||
func(w http.ResponseWriter, _ *http.Request) {
|
func(w http.ResponseWriter, _ *http.Request) {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
|
||||||
@@ -211,7 +210,7 @@ func TestReadHotelHTTPError(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestReadHotelInvalidJSON(t *testing.T) {
|
func TestReadHotelInvalidJSON(t *testing.T) {
|
||||||
server := httptest.NewServer(http.HandlerFunc(
|
server := newCMSMockServer(http.HandlerFunc(
|
||||||
func(w http.ResponseWriter, _ *http.Request) {
|
func(w http.ResponseWriter, _ *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
@@ -230,4 +229,4 @@ func TestReadHotelInvalidJSON(t *testing.T) {
|
|||||||
if !strings.Contains(err.Error(), "unmarshal CMS hotel response") {
|
if !strings.Contains(err.Error(), "unmarshal CMS hotel response") {
|
||||||
t.Errorf("unexpected error: %v", err)
|
t.Errorf("unexpected error: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package cms
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReadHotelDetailsRetainsCMSPaymentConfiguration(t *testing.T) {
|
||||||
|
var calls atomic.Int32
|
||||||
|
hotel := cmstypes.Hotel{Currency: cmstypes.CurrencyRec{Code: "GBP", NumDecimals: 2}}
|
||||||
|
hotel.Updated = 1
|
||||||
|
hotel.ReservationSystem = cmstypes.ReservationSystemRec{PaymentSystem: cmstypes.PaySystemTrustPayments, PaymentGatewayURL: "https://sandbox.link.trustpayments.com/trustpayments/rest", PaymentGatewaySiteIDEPOS: "SYNTH-SITE", PaymentGatewayPasswordEPOS: "SYNTH-PASSWORD", TimeZone: "Europe/London", PDQs: []cmstypes.PDQRec{{Kiosk: 9, Serial: "SYNTH-PED"}}}
|
||||||
|
server := newCMSMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls.Add(1)
|
||||||
|
if r.Method != http.MethodPost || r.URL.Path != cmstypes.APIHotelDetails {
|
||||||
|
t.Errorf("CMS request = %s %s, want existing hotel-details POST", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
var request cmstypes.RequestRec
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
if request.Auth.Hotel != "SYNTH-HOTEL" || request.Data != "SYNTH-HOTEL" {
|
||||||
|
t.Error("CMS hotel identity changed")
|
||||||
|
}
|
||||||
|
response := cmstypes.HotelResponseRec{TheHotel: hotel}
|
||||||
|
response.Status.Code = cmstypes.StatusSuccessCode
|
||||||
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
got, err := ReadHotelDetails("SYNTH-HOTEL", server.URL)
|
||||||
|
if err != nil || !reflect.DeepEqual(got, hotel) || calls.Load() != 1 {
|
||||||
|
t.Fatalf("ReadHotelDetails = %+v/%v requests=%d, want complete CMS hotel in one request", got, err, calls.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadHotelProjectionPreservesOtherProviderSettings(t *testing.T) {
|
||||||
|
for _, provider := range []int{cmstypes.PaySystemCreditCall, cmstypes.PaySystemDojo, cmstypes.PaySystemPayBridge} {
|
||||||
|
t.Run(cmstypes.PaySystemNames[provider], func(t *testing.T) {
|
||||||
|
var calls atomic.Int32
|
||||||
|
response := cmstypes.HotelResponseRec{}
|
||||||
|
response.Status.Code = cmstypes.StatusSuccessCode
|
||||||
|
response.TheHotel.Updated = 1
|
||||||
|
response.TheHotel.Currency = cmstypes.CurrencyRec{Code: "GBP", NumDecimals: 2}
|
||||||
|
response.TheHotel.ReservationSystem = cmstypes.ReservationSystemRec{PaymentSystem: provider, PaymentGatewayURL: "https://synthetic.invalid", PaymentGatewayAPIKeyWeb: "SYNTH-API", PaymentGatewaySiteIDEPOS: "SYNTH-SITE", PaymentGatewayPasswordEPOS: "SYNTH-PASSWORD", PDQs: []cmstypes.PDQRec{{Kiosk: 9, Serial: "SYNTH-PED"}}}
|
||||||
|
server := newCMSMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); _ = json.NewEncoder(w).Encode(response) }))
|
||||||
|
defer server.Close()
|
||||||
|
got, err := ReadHotel("SYNTH-HOTEL", server.URL)
|
||||||
|
if err != nil || !reflect.DeepEqual(got, response.TheHotel.ReservationSystem) || calls.Load() != 1 {
|
||||||
|
t.Fatalf("ReadHotel projection = %+v/%v calls=%d, want unchanged provider settings and one request", got, err, calls.Load())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package cms
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var cmsMockHosts = struct {
|
||||||
|
sync.RWMutex
|
||||||
|
values map[string]bool
|
||||||
|
}{values: make(map[string]bool)}
|
||||||
|
|
||||||
|
type cmsOfflineTransport struct{ base http.RoundTripper }
|
||||||
|
|
||||||
|
func (t cmsOfflineTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||||
|
cmsMockHosts.RLock()
|
||||||
|
allowed := cmsMockHosts.values[r.URL.Host]
|
||||||
|
cmsMockHosts.RUnlock()
|
||||||
|
if !allowed {
|
||||||
|
return nil, errors.New("offline CMS tests reject unregistered endpoints")
|
||||||
|
}
|
||||||
|
return t.base.RoundTrip(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCMSMockServer(handler http.Handler) *httptest.Server {
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
cmsMockHosts.Lock()
|
||||||
|
cmsMockHosts.values[server.Listener.Addr().String()] = true
|
||||||
|
cmsMockHosts.Unlock()
|
||||||
|
return server
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
base := http.DefaultTransport.(*http.Transport).Clone()
|
||||||
|
base.Proxy = nil
|
||||||
|
http.DefaultTransport = cmsOfflineTransport{base: base}
|
||||||
|
http.DefaultClient = &http.Client{Transport: http.DefaultTransport}
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
+1
-1
@@ -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"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -99,6 +99,47 @@ failed.
|
|||||||
request. The dispenser layer does not implement a second encoding attempt on the same
|
request. The dispenser layer does not implement a second encoding attempt on the same
|
||||||
physical card.
|
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
|
After `LockSequence`, FC0 is dispatched exactly once to move the current card toward
|
||||||
the guest:
|
the guest:
|
||||||
|
|
||||||
@@ -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).
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
# 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. Supported progress is forwarded
|
||||||
|
directly to the active stream, regardless of its reference. The request registers
|
||||||
|
its listener around the existing transaction execution and removes it in `finally`
|
||||||
|
before queuing the final frame. Finalization never waits for card removal.
|
||||||
|
- `CardRemovalRequested` and `CardRemovalEnforced` follow the same active-window
|
||||||
|
rule as other progress, regardless of the supplied reference. 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 callback, including removal, has drained before another transaction starts.
|
||||||
|
References are not used to correlate progress. A late callback may briefly display
|
||||||
|
stale progress in a later active stream. This accepted limitation must never affect
|
||||||
|
success, decline, cancellation, timeout outcomes, confirmation, retry, receipts,
|
||||||
|
PMS posting, or business state.
|
||||||
|
- Every stream request creates a fresh writer and empty bounded progress queue.
|
||||||
|
Timeout and exception cleanup removes only that request's listener; SDK errors
|
||||||
|
and repeated references do not disable progress for later SALE or PREAUTH requests.
|
||||||
|
The Client-wide SDK subscriptions remain unchanged. Slow or disconnected consumers
|
||||||
|
cannot block SDK callbacks on socket I/O; a full queue may drop progress hints.
|
||||||
|
- 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,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
|
||||||
|
|
||||||
|
|||||||
@@ -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"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package creditcall
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html"
|
"html"
|
||||||
@@ -11,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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -243,36 +242,3 @@ func ReadPdqStatus(hotel string, kiosk int) (PaymentDeviceStatus, error) {
|
|||||||
|
|
||||||
return dev, nil
|
return dev, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func StartPdqHourlyCheck(ctx context.Context, hotel string, kiosk int) {
|
|
||||||
// waitUntilNextHour(ctx)
|
|
||||||
|
|
||||||
// First execution exactly at round hour
|
|
||||||
_, _ = ReadPdqStatus(hotel, kiosk)
|
|
||||||
|
|
||||||
ticker := time.NewTicker(10 * time.Second)
|
|
||||||
defer ticker.Stop()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-ticker.C:
|
|
||||||
_, _ = ReadPdqStatus(hotel, kiosk)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func waitUntilNextHour(ctx context.Context) {
|
|
||||||
now := time.Now()
|
|
||||||
next := now.Truncate(time.Hour).Add(time.Hour)
|
|
||||||
d := time.Until(next)
|
|
||||||
|
|
||||||
timer := time.NewTimer(d)
|
|
||||||
defer timer.Stop()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
case <-timer.C:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,19 +9,13 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
// XML parsing structs
|
// XML parsing structs
|
||||||
type (
|
type (
|
||||||
TransactionRec struct {
|
|
||||||
XMLName xml.Name `xml:"TransactionPayload"`
|
|
||||||
AmountMinorUnits string `xml:"amount"`
|
|
||||||
TransactionType string `xml:"transactionType"`
|
|
||||||
}
|
|
||||||
|
|
||||||
TransactionResultXML struct {
|
TransactionResultXML struct {
|
||||||
XMLName xml.Name `xml:"TransactionResult"`
|
XMLName xml.Name `xml:"TransactionResult"`
|
||||||
Entries []EntryXML `xml:"Entry"`
|
Entries []EntryXML `xml:"Entry"`
|
||||||
@@ -99,39 +93,6 @@ func (r *PaymentResult) FillFromTransactionResult(trResult TransactionResultXML)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// BuildPaymentRedirectURL builds the redirect URL to send the guest to after payment.
|
|
||||||
func BuildPaymentRedirectURL(result map[string]string) string {
|
|
||||||
res := result[types.TransactionResult]
|
|
||||||
|
|
||||||
// Transaction approved?
|
|
||||||
if strings.EqualFold(res, types.ResultApproved) {
|
|
||||||
// Transaction confirmed?
|
|
||||||
if strings.EqualFold(result[types.ConfirmResult], types.ResultApproved) {
|
|
||||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
|
||||||
Info("Transaction approved and confirmed")
|
|
||||||
|
|
||||||
return BuildSuccessURL(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not confirmed
|
|
||||||
log.WithFields(log.Fields{types.LogFieldError: result[types.ConfirmResult], types.LogFieldDescription: result[types.ConfirmErrors]}).
|
|
||||||
Error("Transaction approved but not confirmed")
|
|
||||||
|
|
||||||
return BuildFailureURL(result[types.ConfirmResult], result[types.ConfirmErrors])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not approved
|
|
||||||
return BuildFailureURL(res, result[types.Errors])
|
|
||||||
}
|
|
||||||
|
|
||||||
func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
|
||||||
approved, persist := PreauthDecision(result)
|
|
||||||
if approved {
|
|
||||||
return BuildSuccessURL(result), persist
|
|
||||||
}
|
|
||||||
return BuildFailureURL(result[types.TransactionResult], result[types.Errors]), false
|
|
||||||
}
|
|
||||||
|
|
||||||
// PreauthDecision preserves the returned-type approval and persistence rules.
|
// PreauthDecision preserves the returned-type approval and persistence rules.
|
||||||
func PreauthDecision(result map[string]string) (approved, persist bool) {
|
func PreauthDecision(result map[string]string) (approved, persist bool) {
|
||||||
res := result[types.TransactionResult]
|
res := result[types.TransactionResult]
|
||||||
|
|||||||
@@ -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,10 +1,9 @@
|
|||||||
package creditcall
|
package creditcall
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
|
||||||
"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) {
|
||||||
@@ -23,12 +22,12 @@ func TestPreauthLegacyDecision(t *testing.T) {
|
|||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
fields := map[string]string{types.TransactionResult: tc.result, types.TransactionType: tc.kind, types.Errors: "provider detail"}
|
fields := map[string]string{types.TransactionResult: tc.result, types.TransactionType: tc.kind, types.Errors: "provider detail"}
|
||||||
redirect, save := BuildPreauthRedirectURL(fields)
|
approved, save := PreauthDecision(fields)
|
||||||
if strings.HasPrefix(redirect, "/successful?") != tc.approved || save != tc.save {
|
if approved != tc.approved || save != tc.save {
|
||||||
t.Errorf("BuildPreauthRedirectURL(%v) = %q,%t, want approved=%t save=%t", fields, redirect, save, tc.approved, tc.save)
|
t.Errorf("PreauthDecision(%v) = %t,%t, want approved=%t save=%t", fields, approved, save, tc.approved, tc.save)
|
||||||
}
|
}
|
||||||
if _, ok := fields[types.TotalAmount]; ok {
|
if _, ok := fields[types.TotalAmount]; ok {
|
||||||
t.Error("BuildPreauthRedirectURL fabricated TOTAL_AMOUNT")
|
t.Error("PreauthDecision fabricated TOTAL_AMOUNT")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,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"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+3
-4
@@ -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)
|
||||||
@@ -84,12 +84,12 @@ func InsertPreauth(ctx context.Context, db *sql.DB, m map[string]string, checkou
|
|||||||
|
|
||||||
txnTime := time.Now().UTC()
|
txnTime := time.Now().UTC()
|
||||||
|
|
||||||
// parse departure / checkout date and compute release date (48h after departure)
|
// Parse departure / checkout date and compute release date (96h after departure).
|
||||||
checkOutDate, err := parseDateOnly(checkoutDate)
|
checkOutDate, err := parseDateOnly(checkoutDate)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("InsertPreauth: parsing checkoutDate %q: %w", checkoutDate, err)
|
return fmt.Errorf("InsertPreauth: parsing checkoutDate %q: %w", checkoutDate, err)
|
||||||
}
|
}
|
||||||
releaseDate := checkOutDate.Add(48 * time.Hour)
|
releaseDate := checkOutDate.Add(96 * time.Hour)
|
||||||
|
|
||||||
const stmt = `
|
const stmt = `
|
||||||
INSERT INTO dbo.Preauthorizations
|
INSERT INTO dbo.Preauthorizations
|
||||||
@@ -198,4 +198,3 @@ WHERE TxnReference = @TxnReference AND Released = 0;
|
|||||||
log.Infof("Marked preauth %s released at %s", txnReference, releasedAt.Format(time.RFC3339))
|
log.Infof("Marked preauth %s released at %s", txnReference, releasedAt.Format(time.RFC3339))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -545,10 +545,24 @@ func (c *Client) waitForDeliveryClearance(ctx context.Context, operation string)
|
|||||||
return r.status, stock, nil
|
return r.status, stock, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) prepareCardAtEncoder(parent context.Context, operation string) (stock string, resultErr error) {
|
// PreparationResult carries this issuance attempt's handoff and recovery budget.
|
||||||
|
type PreparationResult struct {
|
||||||
|
Stock string
|
||||||
|
UncertainHandoff bool
|
||||||
|
ShakesUsed int
|
||||||
|
lastFC7 time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) prepareCardAtEncoder(ctx context.Context, operation string) (string, error) {
|
||||||
|
preparation, err := c.prepareCardForEncoding(ctx, operation)
|
||||||
|
return preparation.Stock, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) prepareCardForEncoding(parent context.Context, operation string) (preparation PreparationResult, resultErr error) {
|
||||||
status, stock, err := c.waitForDeliveryClearance(parent, operation)
|
status, stock, err := c.waitForDeliveryClearance(parent, operation)
|
||||||
|
preparation.Stock = stock
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
status = usableObservation(status, nil, operation)
|
status = usableObservation(status, nil, operation)
|
||||||
started := c.now()
|
started := c.now()
|
||||||
@@ -560,6 +574,13 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
var lastFC7, uncertainSince time.Time
|
var lastFC7, uncertainSince time.Time
|
||||||
var previous preparationClass
|
var previous preparationClass
|
||||||
defer func() {
|
defer func() {
|
||||||
|
preparation.Stock = stock
|
||||||
|
preparation.ShakesUsed = shakes
|
||||||
|
preparation.lastFC7 = lastFC7
|
||||||
|
if resultErr == nil && !lastFC7.IsZero() {
|
||||||
|
class, _ := classifyPreparationStatus(status)
|
||||||
|
preparation.UncertainHandoff = class != encoderConfirmed
|
||||||
|
}
|
||||||
log.Infof("[%s] preparation finished; stage=%s shakes=%d elapsed=%s raw status: % X error=%v", operation, stage, shakes, c.now().Sub(started), status, resultErr)
|
log.Infof("[%s] preparation finished; stage=%s shakes=%d elapsed=%s raw status: % X error=%v", operation, stage, shakes, c.now().Sub(started), status, resultErr)
|
||||||
}()
|
}()
|
||||||
checkDeadline := func() error {
|
checkDeadline := func() error {
|
||||||
@@ -624,7 +645,7 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
if err := checkDeadline(); err != nil {
|
if err := checkDeadline(); err != nil {
|
||||||
return stock, observationResult(err)
|
return preparation, observationResult(err)
|
||||||
}
|
}
|
||||||
class, _ := classifyPreparationStatus(status)
|
class, _ := classifyPreparationStatus(status)
|
||||||
// No class means unusable telemetry, sharing the uncertainty timer.
|
// No class means unusable telemetry, sharing the uncertainty timer.
|
||||||
@@ -634,41 +655,41 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
switch class {
|
switch class {
|
||||||
case encoderConfirmed:
|
case encoderConfirmed:
|
||||||
stage = "encoder sensor handoff"
|
stage = "encoder sensor handoff"
|
||||||
return stock, observationResult(checkDeadline())
|
return preparation, observationResult(checkDeadline())
|
||||||
case positionWellEmpty:
|
case positionWellEmpty:
|
||||||
stage = "empty"
|
stage = "empty"
|
||||||
return stock, ErrCardWellEmpty
|
return preparation, ErrCardWellEmpty
|
||||||
}
|
}
|
||||||
if lastFC7.IsZero() {
|
if lastFC7.IsZero() {
|
||||||
if err := sendFC7(); err != nil {
|
if err := sendFC7(); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
} else if class == positionNoCard && c.now().Sub(lastFC7) >= sequenceShakeAfter {
|
} else if class == positionNoCard && c.now().Sub(lastFC7) >= sequenceShakeAfter {
|
||||||
uncertainSince = time.Time{}
|
uncertainSince = time.Time{}
|
||||||
if shakes == sequenceMaxShakes {
|
if shakes == sequenceMaxShakes {
|
||||||
stage = "three shakes exhausted"
|
stage = "three shakes exhausted"
|
||||||
return stock, ErrPreparationExhausted
|
return preparation, ErrPreparationExhausted
|
||||||
}
|
}
|
||||||
shakes++
|
shakes++
|
||||||
stage = "RS dispatch"
|
stage = "RS dispatch"
|
||||||
if err := checkDeadline(); err != nil {
|
if err := checkDeadline(); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
err := c.Reset(ctx)
|
err := c.Reset(ctx)
|
||||||
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
||||||
return stock, deadlineErr
|
return preparation, deadlineErr
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return stock, fmt.Errorf("[%s] RS dispatch: %w", operation, err)
|
return preparation, fmt.Errorf("[%s] RS dispatch: %w", operation, err)
|
||||||
}
|
}
|
||||||
stage = "reset settling"
|
stage = "reset settling"
|
||||||
log.Infof("[%s] RS dispatched; shake=%d settling=%s", operation, shakes, sequenceResetWait)
|
log.Infof("[%s] RS dispatched; shake=%d settling=%s", operation, shakes, sequenceResetWait)
|
||||||
if err := wait(sequenceResetWait); err != nil {
|
if err := wait(sequenceResetWait); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
log.Infof("[%s] reset settle wait completed; shake=%d", operation, shakes)
|
log.Infof("[%s] reset settle wait completed; shake=%d", operation, shakes)
|
||||||
if err := sendFC7(); err != nil {
|
if err := sendFC7(); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if class == positionUncertain || class == "" {
|
if class == positionUncertain || class == "" {
|
||||||
@@ -677,26 +698,26 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
}
|
}
|
||||||
if c.now().Sub(uncertainSince) >= sequenceUncertainWait {
|
if c.now().Sub(uncertainSince) >= sequenceUncertainWait {
|
||||||
stage = "uncertain position handoff"
|
stage = "uncertain position handoff"
|
||||||
return stock, observationResult(checkDeadline())
|
return preparation, observationResult(checkDeadline())
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
uncertainSince = time.Time{}
|
uncertainSince = time.Time{}
|
||||||
}
|
}
|
||||||
stage = "polling"
|
stage = "polling"
|
||||||
if err := wait(sequencePollInterval); err != nil {
|
if err := wait(sequencePollInterval); err != nil {
|
||||||
return stock, observationResult(err)
|
return preparation, observationResult(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
stage = "fresh AP"
|
stage = "fresh AP"
|
||||||
if err := checkDeadline(); err != nil {
|
if err := checkDeadline(); err != nil {
|
||||||
return stock, observationResult(err)
|
return preparation, observationResult(err)
|
||||||
}
|
}
|
||||||
status, stock, err = c.readSequenceStatus(ctx, operation)
|
status, stock, err = c.readSequenceStatus(ctx, operation)
|
||||||
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
||||||
return stock, observationResult(deadlineErr)
|
return preparation, observationResult(deadlineErr)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -706,6 +727,80 @@ func (c *Client) PrepareCurrentCard(ctx context.Context) (string, error) {
|
|||||||
return c.prepareCardAtEncoder(ctx, "PrepareCurrentCard")
|
return c.prepareCardAtEncoder(ctx, "PrepareCurrentCard")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PrepareCurrentCardForEncoding preserves preparation while exposing uncertain handoff.
|
||||||
|
func (c *Client) PrepareCurrentCardForEncoding(ctx context.Context) (PreparationResult, error) {
|
||||||
|
return c.prepareCardForEncoding(ctx, "PrepareCurrentCard")
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecoverCurrentCard spends only the remaining issuance budget during encoding.
|
||||||
|
// It must be cancelled and joined before delivery; all commands use the serial worker.
|
||||||
|
func (c *Client) RecoverCurrentCard(ctx context.Context, preparation PreparationResult) (resultErr error) {
|
||||||
|
if !preparation.UncertainHandoff {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
const operation = "uncertain encoding recovery"
|
||||||
|
started := c.now()
|
||||||
|
shakes, lastFC7 := preparation.ShakesUsed, preparation.lastFC7
|
||||||
|
reason := "recovery error"
|
||||||
|
defer func() {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
reason = context.Cause(ctx).Error()
|
||||||
|
}
|
||||||
|
log.Infof("[%s] stopped; reason=%s shakes=%d remaining=%d elapsed=%s error=%v", operation, reason, shakes, sequenceMaxShakes-shakes, c.now().Sub(started), resultErr)
|
||||||
|
}()
|
||||||
|
log.Infof("[%s] started; shakes=%d remaining=%d", operation, shakes, sequenceMaxShakes-shakes)
|
||||||
|
observe := func() (bool, error) {
|
||||||
|
status, _, err := c.readSequenceStatus(ctx, operation)
|
||||||
|
if err != nil {
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
class, _ := classifyPreparationStatus(status)
|
||||||
|
log.Infof("[%s] fresh AP; class=%s shakes=%d remaining=%d raw status: % X", operation, class, shakes, sequenceMaxShakes-shakes, status)
|
||||||
|
switch class {
|
||||||
|
case encoderConfirmed:
|
||||||
|
reason = "encoder confirmed"
|
||||||
|
return true, nil
|
||||||
|
case positionWellEmpty:
|
||||||
|
reason = "card well empty"
|
||||||
|
return true, ErrCardWellEmpty
|
||||||
|
default:
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
if stopped, err := observe(); stopped {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if shakes >= sequenceMaxShakes {
|
||||||
|
reason = "shake budget exhausted"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if remaining := sequenceShakeAfter - c.now().Sub(lastFC7); remaining > 0 {
|
||||||
|
if err := c.sequenceTiming.wait(ctx, min(sequencePollInterval, remaining)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
shakes++
|
||||||
|
log.Infof("[%s] RS attempt; shake=%d remaining=%d", operation, shakes, sequenceMaxShakes-shakes)
|
||||||
|
if err := c.Reset(ctx); err != nil {
|
||||||
|
return fmt.Errorf("[%s] RS dispatch: %w", operation, err)
|
||||||
|
}
|
||||||
|
if err := c.sequenceTiming.wait(ctx, sequenceResetWait); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// A diagnostic AP cannot turn unusable telemetry into a fatal error.
|
||||||
|
if stopped, err := observe(); stopped {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
log.Infof("[%s] FC7 attempt; shake=%d remaining=%d", operation, shakes, sequenceMaxShakes-shakes)
|
||||||
|
if err := c.ToEncoder(ctx); err != nil {
|
||||||
|
return fmt.Errorf("[%s] FC7 dispatch: %w", operation, err)
|
||||||
|
}
|
||||||
|
lastFC7 = c.now()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// DeliverCurrentCard presents the encoded card and confirms command acceptance.
|
// DeliverCurrentCard presents the encoded card and confirms command acceptance.
|
||||||
func (c *Client) DeliverCurrentCard(ctx context.Context) (string, error) {
|
func (c *Client) DeliverCurrentCard(ctx context.Context) (string, error) {
|
||||||
const operation = "DeliverCurrentCard"
|
const operation = "DeliverCurrentCard"
|
||||||
|
|||||||
@@ -112,6 +112,154 @@ func TestResetPacket(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUncertainRecoveryContinuesPreparationBudget(t *testing.T) {
|
||||||
|
responses := append(positionResponses(0x30, 5), positionResponses(0x35, 5)...)
|
||||||
|
responses = append(responses, cmdResp{status: status(0x35)}, cmdResp{err: errors.New("unusable diagnostic AP")})
|
||||||
|
responses = append(responses, positionResponses(0x30, 4)...)
|
||||||
|
responses = append(responses, cmdResp{status: status(0x35)}, cmdResp{status: status(0x37)})
|
||||||
|
c, d := newSequenceTestClient(t, responses...)
|
||||||
|
preparation, err := c.PrepareCurrentCardForEncoding(context.Background())
|
||||||
|
if err != nil || !preparation.UncertainHandoff || preparation.ShakesUsed != 1 {
|
||||||
|
t.Fatalf("preparation=%+v error=%v, want uncertain handoff after one shake", preparation, err)
|
||||||
|
}
|
||||||
|
before := len(d.commands)
|
||||||
|
if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []cmdType{cmdStatus, cmdReset, cmdStatus, cmdToEncoder, cmdStatus, cmdStatus, cmdStatus, cmdStatus, cmdReset, cmdStatus, cmdToEncoder, cmdStatus}
|
||||||
|
if !reflect.DeepEqual(d.commands[before:], want) {
|
||||||
|
t.Errorf("recovery commands=%v, want %v", d.commands[before:], want)
|
||||||
|
}
|
||||||
|
if commandCount(d.commands, cmdReset) != 3 || commandCount(d.commands, cmdToEncoder) != 4 {
|
||||||
|
t.Errorf("whole issuance commands=%v, want three RS and four FC7", d.commands)
|
||||||
|
}
|
||||||
|
for i := before; i < len(d.commands); i++ {
|
||||||
|
if d.commands[i] == cmdToEncoder && d.commandTimes[i].Sub(d.commandTimes[i-2]) != sequenceResetWait {
|
||||||
|
t.Errorf("recovery FC7 at %d did not follow RS, settle and diagnostic AP: %v", i, d.commands)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUncertainRecoveryProductionTrace(t *testing.T) {
|
||||||
|
responses := []cmdResp{{status: status(0x30)}}
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
responses = append(responses, cmdResp{err: errors.New("AP unavailable")})
|
||||||
|
}
|
||||||
|
responses = append(responses, cmdResp{status: status(0x35)}, cmdResp{status: status(0x35)}, cmdResp{status: status(0x37)})
|
||||||
|
c, d := newSequenceTestClient(t, responses...)
|
||||||
|
preparation, err := c.PrepareCurrentCardForEncoding(context.Background())
|
||||||
|
if err != nil || !preparation.UncertainHandoff || preparation.ShakesUsed != 0 {
|
||||||
|
t.Fatalf("production trace preparation=%+v error=%v, want uncertain handoff with unused budget", preparation, err)
|
||||||
|
}
|
||||||
|
if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if commandCount(d.commands, cmdReset) != 1 || commandCount(d.commands, cmdToEncoder) != 2 {
|
||||||
|
t.Errorf("production trace commands=%v, want one shake after initial FC7", d.commands)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUncertainRecoveryStopsAtPhysicalPosition(t *testing.T) {
|
||||||
|
for _, position := range []byte{0x32, 0x33, 0x37, 0x3F, 0x38} {
|
||||||
|
for _, afterReset := range []bool{false, true} {
|
||||||
|
t.Run(fmt.Sprintf("position=%X afterReset=%t", position, afterReset), func(t *testing.T) {
|
||||||
|
responses := []cmdResp{{status: status(position)}}
|
||||||
|
if afterReset {
|
||||||
|
responses = append([]cmdResp{{status: status(0x35)}}, responses...)
|
||||||
|
}
|
||||||
|
c, d := newSequenceTestClient(t, responses...)
|
||||||
|
err := c.RecoverCurrentCard(context.Background(), PreparationResult{UncertainHandoff: true})
|
||||||
|
var wantErr error
|
||||||
|
if position == 0x38 {
|
||||||
|
wantErr = ErrCardWellEmpty
|
||||||
|
}
|
||||||
|
wantRS := 0
|
||||||
|
if afterReset {
|
||||||
|
wantRS = 1
|
||||||
|
}
|
||||||
|
if !errors.Is(err, wantErr) || commandCount(d.commands, cmdReset) != wantRS || commandCount(d.commands, cmdToEncoder) != 0 {
|
||||||
|
t.Errorf("position %X recovery error=%v commands=%v, want error=%v RS=%d FC7=0", position, err, d.commands, wantErr, wantRS)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUncertainRecoveryExhaustsOnlyRemainingShakes(t *testing.T) {
|
||||||
|
for used := 0; used <= sequenceMaxShakes; used++ {
|
||||||
|
t.Run(fmt.Sprint(used), func(t *testing.T) {
|
||||||
|
c, d := newSequenceTestClient(t, positionResponses(0x35, 30)...)
|
||||||
|
preparation := PreparationResult{UncertainHandoff: true, ShakesUsed: used, lastFC7: c.now().Add(-sequenceShakeAfter)}
|
||||||
|
if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := sequenceMaxShakes - used
|
||||||
|
if commandCount(d.commands, cmdReset) != want || commandCount(d.commands, cmdToEncoder) != want {
|
||||||
|
t.Errorf("used=%d commands=%v, want %d RS/FC7", used, d.commands, want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUncertainRecoveryPreservesFC7ObservationDelay(t *testing.T) {
|
||||||
|
c, d := newSequenceTestClient(t, positionResponses(0x35, 4)...)
|
||||||
|
d.statusResponses = append(d.statusResponses, cmdResp{status: status(0x37)})
|
||||||
|
started := c.now()
|
||||||
|
if err := c.RecoverCurrentCard(context.Background(), PreparationResult{UncertainHandoff: true, lastFC7: started}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if commandCount(d.commands, cmdReset) != 1 || d.commandTimes[4].Sub(started) != sequenceShakeAfter {
|
||||||
|
t.Errorf("commands=%v times=%v, want first RS after three seconds", d.commands, d.commandTimes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUncertainRecoveryCommandFailuresAndCancellation(t *testing.T) {
|
||||||
|
for _, command := range []cmdType{cmdReset, cmdToEncoder} {
|
||||||
|
c, d := newSequenceTestClient(t, positionResponses(0x35, 3)...)
|
||||||
|
failure := errors.New("recovery dispatch failed")
|
||||||
|
d.commandErrors[command] = []error{failure}
|
||||||
|
if err := c.RecoverCurrentCard(context.Background(), PreparationResult{UncertainHandoff: true}); !errors.Is(err, failure) {
|
||||||
|
t.Errorf("command=%v error=%v, want %v", command, err, failure)
|
||||||
|
}
|
||||||
|
if commandCount(d.commands, command) != 1 {
|
||||||
|
t.Errorf("failed command=%v commands=%v, want one attempt", command, d.commands)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, d := newSequenceTestClient(t, cmdResp{status: status(0x35)})
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
t.Cleanup(cancel)
|
||||||
|
c.sequenceTiming.wait = func(ctx context.Context, duration time.Duration) error {
|
||||||
|
if duration != sequenceResetWait {
|
||||||
|
t.Errorf("wait=%s, want reset settle", duration)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
if err := c.RecoverCurrentCard(ctx, PreparationResult{UncertainHandoff: true}); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Errorf("settle cancellation=%v, want context.Canceled", err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(d.commands, []cmdType{cmdStatus, cmdReset}) {
|
||||||
|
t.Errorf("cancelled commands=%v, want AP/RS only", d.commands)
|
||||||
|
}
|
||||||
|
if err := c.RecoverCurrentCard(ctx, PreparationResult{UncertainHandoff: true}); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Errorf("already cancelled recovery=%v, want context.Canceled", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfirmedPreparationNeverRecovers(t *testing.T) {
|
||||||
|
c, d := newSequenceTestClient(t, cmdResp{status: status(0x37)})
|
||||||
|
preparation, err := c.PrepareCurrentCardForEncoding(context.Background())
|
||||||
|
if err != nil || preparation.UncertainHandoff {
|
||||||
|
t.Fatalf("confirmed preparation=%+v error=%v", preparation, err)
|
||||||
|
}
|
||||||
|
if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(d.commands, []cmdType{cmdStatus}) {
|
||||||
|
t.Errorf("confirmed commands=%v, want initial AP only", d.commands)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestDeliverCurrentCardSucceedsAfterCommandAcceptanceWithoutStatusPolling(t *testing.T) {
|
func TestDeliverCurrentCardSucceedsAfterCommandAcceptanceWithoutStatusPolling(t *testing.T) {
|
||||||
staleStatus := []byte{0x30, 0x32, 0x32, 0x33}
|
staleStatus := []byte{0x30, 0x32, 0x32, 0x33}
|
||||||
client, device := newSequenceTestClient(t, cmdResp{status: staleStatus})
|
client, device := newSequenceTestClient(t, cmdResp{status: staleStatus})
|
||||||
|
|||||||
@@ -303,12 +303,17 @@ func TestForegroundEncoderClearanceCallerDeadline(t *testing.T) {
|
|||||||
c.deliveryStarted = *now
|
c.deliveryStarted = *now
|
||||||
start := *now
|
start := *now
|
||||||
samples := 0
|
samples := 0
|
||||||
|
remainingChunks := len(p.chunks)
|
||||||
p.afterRead = func() {
|
p.afterRead = func() {
|
||||||
if len(p.chunks)%2 == 0 { // Only complete frame reads advance the observation clock.
|
// ACK and frame headers can take several reads without consuming a chunk.
|
||||||
if len(p.chunks) == 4 || len(p.chunks) == 2 || len(p.chunks) == 0 {
|
// Advance once per completed AP frame, not during a partial ACK read.
|
||||||
samples++
|
if len(p.chunks) == remainingChunks {
|
||||||
*now = now.Add(time.Second)
|
return
|
||||||
}
|
}
|
||||||
|
remainingChunks = len(p.chunks)
|
||||||
|
if remainingChunks%2 == 0 {
|
||||||
|
samples++
|
||||||
|
*now = now.Add(time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||||
@@ -326,7 +331,10 @@ func TestForegroundEncoderClearanceCallerDeadline(t *testing.T) {
|
|||||||
t.Errorf("caller deadline err=%v pending=%t", r.err, c.deliveryPending)
|
t.Errorf("caller deadline err=%v pending=%t", r.err, c.deliveryPending)
|
||||||
}
|
}
|
||||||
if got := wireCommands(p); !reflect.DeepEqual(got, []string{"AP", "AP", "AP"}) {
|
if got := wireCommands(p); !reflect.DeepEqual(got, []string{"AP", "AP", "AP"}) {
|
||||||
t.Errorf("caller deadline commands=%v want AP only", got)
|
t.Errorf("caller deadline commands=%v, want three AP observations and no movement", got)
|
||||||
|
}
|
||||||
|
if samples != 3 {
|
||||||
|
t.Errorf("caller deadline completed AP frames=%d, want 3", samples)
|
||||||
}
|
}
|
||||||
if elapsed := now.Sub(start); elapsed != 5*time.Second {
|
if elapsed := now.Sub(start); elapsed != 5*time.Second {
|
||||||
t.Errorf("last observation elapsed=%v want 5s", elapsed)
|
t.Errorf("last observation elapsed=%v want 5s", elapsed)
|
||||||
|
|||||||
+96
-6
@@ -13,13 +13,16 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
"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/paymentsvc"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
|
PrintReceipt func(string)
|
||||||
BaseURL string
|
BaseURL string
|
||||||
APIKey string
|
APIKey string
|
||||||
SoftwareHouseID string
|
SoftwareHouseID string
|
||||||
@@ -28,6 +31,7 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
|
printReceipt func(string)
|
||||||
baseURL string
|
baseURL string
|
||||||
apiKey string
|
apiKey string
|
||||||
version string
|
version string
|
||||||
@@ -91,6 +95,7 @@ func NewClient(cfg Config) (*Client, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &Client{
|
return &Client{
|
||||||
|
printReceipt: cfg.PrintReceipt,
|
||||||
baseURL: strings.TrimRight(cfg.BaseURL, "/"),
|
baseURL: strings.TrimRight(cfg.BaseURL, "/"),
|
||||||
apiKey: cfg.APIKey,
|
apiKey: cfg.APIKey,
|
||||||
version: cfg.Version,
|
version: cfg.Version,
|
||||||
@@ -104,7 +109,49 @@ func (c *Client) Sale(
|
|||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
req paymentsvc.SaleRequest,
|
req paymentsvc.SaleRequest,
|
||||||
onStatus paymentsvc.StatusHandler,
|
onStatus paymentsvc.StatusHandler,
|
||||||
) (*paymentsvc.Result, error) {
|
) (returned *paymentsvc.Result, resultErr error) {
|
||||||
|
stage := "create_payment_intent"
|
||||||
|
var intentID, sessionID, transactionID string
|
||||||
|
observeSession := func(session *terminalSessionResponse) {
|
||||||
|
if session != nil {
|
||||||
|
if session.ID != "" {
|
||||||
|
sessionID = session.ID
|
||||||
|
}
|
||||||
|
if session.PaymentDetails != nil && session.PaymentDetails.TransactionID != "" {
|
||||||
|
transactionID = session.PaymentDetails.TransactionID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if returned != nil {
|
||||||
|
returned.Terminal = dojoTerminalResult(returned)
|
||||||
|
if c.printReceipt != nil {
|
||||||
|
c.printReceipt(returned.CustomerReceipt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if resultErr != nil || (returned != nil && returned.Terminal.Outcome == "unknown") {
|
||||||
|
fields := log.Fields{
|
||||||
|
"provider": "dojo", "operation": "sale", "stage": stage,
|
||||||
|
"request_id": req.RequestID, "transaction_reference": req.RequestID,
|
||||||
|
"error_category": paymentsvc.SafeErrorCategory(resultErr),
|
||||||
|
}
|
||||||
|
if intentID != "" {
|
||||||
|
fields["payment_intent_id"] = intentID
|
||||||
|
}
|
||||||
|
if sessionID != "" {
|
||||||
|
fields["terminal_session_id"] = sessionID
|
||||||
|
}
|
||||||
|
if transactionID != "" {
|
||||||
|
fields["provider_transaction_id"] = transactionID
|
||||||
|
}
|
||||||
|
var responseError *httpResponseError
|
||||||
|
if errors.As(resultErr, &responseError) {
|
||||||
|
fields["http_status"] = responseError.StatusCode
|
||||||
|
fields["error_category"] = "http_error"
|
||||||
|
}
|
||||||
|
log.WithFields(fields).Warn("Dojo payment requires reconciliation")
|
||||||
|
}
|
||||||
|
}()
|
||||||
if req.Currency == "" {
|
if req.Currency == "" {
|
||||||
req.Currency = "GBP"
|
req.Currency = "GBP"
|
||||||
}
|
}
|
||||||
@@ -115,7 +162,12 @@ func (c *Client) Sale(
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
intentID = intent.ID
|
||||||
|
if intent.PaymentDetails != nil {
|
||||||
|
transactionID = intent.PaymentDetails.TransactionID
|
||||||
|
}
|
||||||
|
|
||||||
|
stage = "create_terminal_session"
|
||||||
session, err := c.createTerminalSession(ctx, intent.ID)
|
session, err := c.createTerminalSession(ctx, intent.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var responseErr *httpResponseError
|
var responseErr *httpResponseError
|
||||||
@@ -125,6 +177,8 @@ func (c *Client) Sale(
|
|||||||
"operation": "createTerminalSession",
|
"operation": "createTerminalSession",
|
||||||
"status": responseErr.StatusCode,
|
"status": responseErr.StatusCode,
|
||||||
"terminal_unavailable": true,
|
"terminal_unavailable": true,
|
||||||
|
"request_id": req.RequestID, "transaction_reference": req.RequestID,
|
||||||
|
"payment_intent_id": intentID,
|
||||||
}).Warn(dojoTerminalUnavailableMessage)
|
}).Warn(dojoTerminalUnavailableMessage)
|
||||||
|
|
||||||
sendPaymentStatus(onStatus, paymentstatus.TerminalUnavailable)
|
sendPaymentStatus(onStatus, paymentstatus.TerminalUnavailable)
|
||||||
@@ -135,18 +189,24 @@ func (c *Client) Sale(
|
|||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
observeSession(session)
|
||||||
|
|
||||||
session, err = c.waitForTerminalSession(ctx, session.ID, onStatus)
|
stage = "read_terminal_session"
|
||||||
|
session, err = c.waitForTerminalSession(ctx, session.ID, onStatus, observeSession)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
switch strings.ToLower(session.Status) {
|
switch strings.ToLower(session.Status) {
|
||||||
case types.ResultCaptured, types.ResultSignatureAccepted:
|
case types.ResultCaptured, types.ResultSignatureAccepted:
|
||||||
|
stage = "read_payment_intent"
|
||||||
intent, err = c.getPaymentIntent(ctx, intent.ID)
|
intent, err = c.getPaymentIntent(ctx, intent.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if intent.PaymentDetails != nil && intent.PaymentDetails.TransactionID != "" {
|
||||||
|
transactionID = intent.PaymentDetails.TransactionID
|
||||||
|
}
|
||||||
if strings.ToLower(intent.Status) != types.ResultCaptured {
|
if strings.ToLower(intent.Status) != types.ResultCaptured {
|
||||||
return nil, fmt.Errorf("Dojo terminal session is %s but payment intent is %s", session.Status, intent.Status)
|
return nil, fmt.Errorf("Dojo terminal session is %s but payment intent is %s", session.Status, intent.Status)
|
||||||
}
|
}
|
||||||
@@ -215,6 +275,7 @@ func (c *Client) waitForTerminalSession(
|
|||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
terminalSessionID string,
|
terminalSessionID string,
|
||||||
onStatus paymentsvc.StatusHandler,
|
onStatus paymentsvc.StatusHandler,
|
||||||
|
observeSession func(*terminalSessionResponse),
|
||||||
) (*terminalSessionResponse, error) {
|
) (*terminalSessionResponse, error) {
|
||||||
ticker := time.NewTicker(time.Second)
|
ticker := time.NewTicker(time.Second)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
@@ -230,7 +291,9 @@ func (c *Client) waitForTerminalSession(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("session status:", session.Status)
|
observeSession(&session.terminalSessionResponse)
|
||||||
|
log.WithFields(log.Fields{"provider": "dojo", "terminal_session_id": terminalSessionID,
|
||||||
|
"status": mapDojoSessionStatus(session.Status)}).Info("Dojo terminal session observed")
|
||||||
|
|
||||||
emitNewTerminalSessionEvents(
|
emitNewTerminalSessionEvents(
|
||||||
session,
|
session,
|
||||||
@@ -273,6 +336,7 @@ func (c *Client) waitForTerminalSession(
|
|||||||
signatureRejected = true
|
signatureRejected = true
|
||||||
|
|
||||||
if rejectedSession != nil {
|
if rejectedSession != nil {
|
||||||
|
observeSession(rejectedSession)
|
||||||
rejectedStatus := strings.ToLower(
|
rejectedStatus := strings.ToLower(
|
||||||
rejectedSession.Status,
|
rejectedSession.Status,
|
||||||
)
|
)
|
||||||
@@ -672,3 +736,29 @@ func normalizeReceiptText(value string) string {
|
|||||||
|
|
||||||
return replacer.Replace(value)
|
return replacer.Replace(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (*Client) ValidatePreauth(paymentsvc.SaleRequest) error { return paymentsvc.ErrPreauthUnsupported }
|
||||||
|
func (*Client) Preauth(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
return nil, paymentsvc.ErrPreauthUnsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
func dojoTerminalResult(r *paymentsvc.Result) paymentapi.Result {
|
||||||
|
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Provider: "dojo", AmountMinor: r.Amount, CurrencyCode: r.Currency, TransactionReference: r.RequestID, CardType: r.CardType, MaskedCardNumber: creditcall.MaskedCardNumber(r.CardNumber), ExpiryDate: r.ExpiryDate, CardHash: r.CardHash, CardReference: r.CardReference, AuthorizationCode: r.AuthCode, LastFour: r.LastFourDigits, Message: "Payment outcome uncertain; contact reception"}
|
||||||
|
if r.Success && strings.EqualFold(r.Status, "APPROVED") {
|
||||||
|
final.Outcome, final.Message = "approved", "Payment approved"
|
||||||
|
return final
|
||||||
|
}
|
||||||
|
switch strings.ToUpper(r.Status) {
|
||||||
|
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"
|
||||||
|
case "SIGNATUREVERIFICATIONREJECTED", "SIGNATURE_VERIFICATION_REJECTED":
|
||||||
|
final.Outcome, final.Reason, final.Message = "declined", "signature_verification", "Signature verification declined"
|
||||||
|
final.Retryable = true
|
||||||
|
case dojoTerminalUnavailableStatus:
|
||||||
|
final.Outcome, final.Reason, final.Message = "error", "terminal_unavailable", dojoTerminalUnavailableMessage
|
||||||
|
final.Retryable = true
|
||||||
|
}
|
||||||
|
return final
|
||||||
|
}
|
||||||
|
|||||||
@@ -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"}`
|
||||||
@@ -86,6 +86,9 @@ func TestSaleMapsCreateTerminalSessionConflictToTerminalUnavailable(t *testing.T
|
|||||||
if result.Status != dojoTerminalUnavailableStatus || result.ErrorMessage != dojoTerminalUnavailableMessage {
|
if result.Status != dojoTerminalUnavailableStatus || result.ErrorMessage != dojoTerminalUnavailableMessage {
|
||||||
t.Fatalf("terminal-unavailable result = %+v", result)
|
t.Fatalf("terminal-unavailable result = %+v", result)
|
||||||
}
|
}
|
||||||
|
if !result.Terminal.Retryable || result.Terminal.Reason != "terminal_unavailable" || result.Terminal.Outcome != "error" {
|
||||||
|
t.Errorf("Sale(session conflict) terminal=%+v, want safely retryable pre-dispatch unavailability", result.Terminal)
|
||||||
|
}
|
||||||
if result.RequestID != request.RequestID ||
|
if result.RequestID != request.RequestID ||
|
||||||
result.Operation != "SALE" ||
|
result.Operation != "SALE" ||
|
||||||
result.Amount != request.Amount ||
|
result.Amount != request.Amount ||
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package dojo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
logtest "github.com/sirupsen/logrus/hooks/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
type diagnosticTransport func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f diagnosticTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
|
||||||
|
func dojoDiagnosticLog(t *testing.T) *logtest.Hook {
|
||||||
|
t.Helper()
|
||||||
|
logger := log.StandardLogger()
|
||||||
|
oldOutput := logger.Out
|
||||||
|
oldHooks := logger.ReplaceHooks(make(log.LevelHooks))
|
||||||
|
hook := logtest.NewGlobal()
|
||||||
|
log.SetOutput(io.Discard)
|
||||||
|
t.Cleanup(func() { log.SetOutput(oldOutput); logger.ReplaceHooks(oldHooks) })
|
||||||
|
return hook
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDojoFailureDiagnosticsKeepIdentityWithoutRawErrors(t *testing.T) {
|
||||||
|
for _, failure := range []string{"transport", "lost", "malformed", "http", "expired"} {
|
||||||
|
t.Run(failure, func(t *testing.T) {
|
||||||
|
hook := dojoDiagnosticLog(t)
|
||||||
|
financialPosts := 0
|
||||||
|
client, err := NewClient(Config{BaseURL: "https://synthetic.invalid", APIKey: "SYNTH-CREDENTIAL", SoftwareHouseID: "SYNTH-HOUSE", TerminalID: "SYNTH-PED"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
client.httpClient = &http.Client{Transport: diagnosticTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
body := ""
|
||||||
|
switch {
|
||||||
|
case r.Method == http.MethodPost && r.URL.Path == "/payment-intents":
|
||||||
|
financialPosts++
|
||||||
|
if failure == "transport" {
|
||||||
|
return nil, errors.New("SYNTH-RAW-SECRET https://user:password@private.invalid")
|
||||||
|
}
|
||||||
|
body = `{"id":"SYNTH-INTENT"}`
|
||||||
|
case r.Method == http.MethodPost && r.URL.Path == "/terminal-sessions":
|
||||||
|
body = `{"id":"SYNTH-SESSION","paymentDetails":{"transactionId":"SYNTH-PROVIDER-TXN"}}`
|
||||||
|
case r.Method == http.MethodGet && r.URL.Path == "/terminal-sessions/SYNTH-SESSION":
|
||||||
|
switch failure {
|
||||||
|
case "lost":
|
||||||
|
return nil, io.ErrUnexpectedEOF
|
||||||
|
case "malformed":
|
||||||
|
body = `{"SYNTH-RAW-SECRET":nope}`
|
||||||
|
case "http":
|
||||||
|
return &http.Response{StatusCode: 502, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("SYNTH-RAW-SECRET card 4111111111111111"))}, nil
|
||||||
|
case "expired":
|
||||||
|
body = `{"id":"SYNTH-SESSION","status":"Expired","paymentDetails":{"transactionId":"SYNTH-PROVIDER-TXN"}}`
|
||||||
|
default:
|
||||||
|
t.Errorf("unexpected poll for %s", failure)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
t.Errorf("Dojo Sale requested unexpected %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||||
|
})}
|
||||||
|
request := paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Reference: "SYNTH-BOOK", Amount: 2500, Currency: "GBP"}
|
||||||
|
result, err := client.Sale(context.Background(), request, nil)
|
||||||
|
if failure == "expired" {
|
||||||
|
if err != nil || result == nil || result.Terminal.Outcome != "unknown" || result.Terminal.Retryable {
|
||||||
|
t.Fatalf("Sale(expired)=%+v/%v, want unchanged nonretryable unknown", result, err)
|
||||||
|
}
|
||||||
|
} else if err == nil || result != nil {
|
||||||
|
t.Fatalf("Sale(%s)=%+v/%v, want original nil-result error", failure, result, err)
|
||||||
|
}
|
||||||
|
if failure == "http" && !strings.Contains(err.Error(), "SYNTH-RAW-SECRET") {
|
||||||
|
t.Error("Sale(http) changed the existing returned error")
|
||||||
|
}
|
||||||
|
if financialPosts != 1 {
|
||||||
|
t.Errorf("Sale(%s) financial posts=%d, want one", failure, financialPosts)
|
||||||
|
}
|
||||||
|
var diagnostic *log.Entry
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
data, _ := json.Marshal(entry.Data)
|
||||||
|
for _, secret := range []string{"SYNTH-CREDENTIAL", "SYNTH-RAW-SECRET", "4111111111111111", "user:password"} {
|
||||||
|
if strings.Contains(string(data)+entry.Message, secret) {
|
||||||
|
t.Errorf("Sale(%s) logged sensitive marker %q", failure, secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entry.Message == "Dojo payment requires reconciliation" {
|
||||||
|
diagnostic = entry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if diagnostic == nil {
|
||||||
|
t.Fatal("Sale failure emitted no reconciliation diagnostic")
|
||||||
|
}
|
||||||
|
for key, want := range map[string]any{"provider": "dojo", "request_id": "SYNTH-REQUEST", "transaction_reference": "SYNTH-REQUEST"} {
|
||||||
|
if diagnostic.Data[key] != want {
|
||||||
|
t.Errorf("Sale(%s) diagnostic[%s]=%v, want %v", failure, key, diagnostic.Data[key], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wantStage, wantCategory := "read_terminal_session", "unresolved_result"
|
||||||
|
switch failure {
|
||||||
|
case "transport":
|
||||||
|
wantStage, wantCategory = "create_payment_intent", "connection_failure"
|
||||||
|
case "lost":
|
||||||
|
wantCategory = "response_lost"
|
||||||
|
case "malformed":
|
||||||
|
wantCategory = "invalid_response"
|
||||||
|
case "http":
|
||||||
|
wantCategory = "http_error"
|
||||||
|
}
|
||||||
|
if diagnostic.Data["stage"] != wantStage || diagnostic.Data["error_category"] != wantCategory {
|
||||||
|
t.Errorf("Sale(%s) diagnostic=%v, want stage=%s category=%s", failure, diagnostic.Data, wantStage, wantCategory)
|
||||||
|
}
|
||||||
|
if failure != "transport" {
|
||||||
|
for key, want := range map[string]string{"payment_intent_id": "SYNTH-INTENT", "terminal_session_id": "SYNTH-SESSION", "provider_transaction_id": "SYNTH-PROVIDER-TXN"} {
|
||||||
|
if diagnostic.Data[key] != want {
|
||||||
|
t.Errorf("Sale(%s) diagnostic[%s]=%v, want %s", failure, key, diagnostic.Data[key], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if failure == "http" && diagnostic.Data["http_status"] != 502 {
|
||||||
|
t.Errorf("Sale(http) status=%v, want 502", diagnostic.Data["http_status"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDojoPollFailureRetainsLastObservedTransactionIdentity(t *testing.T) {
|
||||||
|
hook := dojoDiagnosticLog(t)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
client, err := NewClient(Config{BaseURL: "https://synthetic.invalid", APIKey: "SYNTH", SoftwareHouseID: "SYNTH", TerminalID: "SYNTH"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
client.httpClient = &http.Client{Transport: diagnosticTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
body := `{"id":"SYNTH-INTENT"}`
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/terminal-sessions") {
|
||||||
|
body = `{"id":"SYNTH-SESSION"}`
|
||||||
|
}
|
||||||
|
if r.Method == "GET" {
|
||||||
|
body = `{"id":"SYNTH-SESSION","status":"Initiated","paymentDetails":{"transactionId":"SYNTH-POLL-TXN"}}`
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||||
|
})}
|
||||||
|
result, err := client.Sale(ctx, paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Amount: 2500}, nil)
|
||||||
|
if result != nil || !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("Sale(cancel after poll)=%+v/%v, want unchanged cancellation", result, err)
|
||||||
|
}
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
if entry.Message == "Dojo payment requires reconciliation" {
|
||||||
|
if entry.Data["provider_transaction_id"] != "SYNTH-POLL-TXN" || entry.Data["error_category"] != "cancelled" {
|
||||||
|
t.Errorf("Sale(cancel after poll) diagnostic=%v, want last observed transaction and cancellation", entry.Data)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("Sale(cancel after poll) emitted no diagnostic; entries=%d", len(hook.AllEntries()))
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package dojo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTerminalResultKeepsExistingIdentityAndOnlyRealMetadata(t *testing.T) {
|
||||||
|
raw := &paymentsvc.Result{Success: true, Status: "APPROVED", RequestID: "SYNTH-REQUEST", TransactionID: "SYNTH-PROVIDER-ID", Amount: 1234, Currency: "EUR", CardNumber: "************1133", CardType: "Visa", ExpiryDate: "1228", AuthCode: "SYNTH-AUTH"}
|
||||||
|
result := dojoTerminalResult(raw)
|
||||||
|
if result.Outcome != "approved" || result.TransactionReference != "SYNTH-REQUEST" || result.MaskedCardNumber != raw.CardNumber || result.ExpiryDate != "1228" || result.CardHash != "" || result.CardReference != "" {
|
||||||
|
t.Errorf("dojoTerminalResult(%+v)=%+v, want current request identity and only supplied card data", raw, result)
|
||||||
|
}
|
||||||
|
raw.CardNumber = "4111111111111111"
|
||||||
|
if got := dojoTerminalResult(raw).MaskedCardNumber; got != "" {
|
||||||
|
t.Errorf("dojoTerminalResult(unmasked PAN) masked=%q, want omitted", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestExpiredTerminalResultIsUncertain(t *testing.T) {
|
||||||
|
result := dojoTerminalResult(&paymentsvc.Result{Status: "EXPIRED"})
|
||||||
|
if result.Outcome != "unknown" || result.Retryable {
|
||||||
|
t.Errorf("dojoTerminalResult(EXPIRED)=%+v, want nonretryable unknown", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfirmedSignatureRejectionRemainsRetryable(t *testing.T) {
|
||||||
|
result := dojoTerminalResult(&paymentsvc.Result{Status: "SIGNATUREVERIFICATIONREJECTED"})
|
||||||
|
if result.Outcome != "declined" || result.Reason != "signature_verification" || !result.Retryable {
|
||||||
|
t.Errorf("dojoTerminalResult(signature rejected)=%+v, want safely retryable confirmed rejection", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCardRoutesNeverExecuteStoredCommandAfterBuildFailure(t *testing.T) {
|
||||||
|
for _, path := range []string{"/issuedoorcard", "/testissuedoorcard"} {
|
||||||
|
t.Run(path, func(t *testing.T) {
|
||||||
|
d := &fakeDoorCardDispenser{}
|
||||||
|
lock := &fakeDoorCardLockServer{buildErr: errors.New("synthetic invalid lock command"), storedCommand: "PREVIOUS-ROOM"}
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"roomField":"CURRENT-ROOM","checkinTime":"2026-11-04 15:00:00 +0000","checkoutTime":"2026-11-05 11:00:00 +0000","followStr":"0"}`))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
var response cmstypes.StatusRec
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w.Code != http.StatusBadGateway || response.Code != http.StatusBadGateway || !strings.Contains(response.Message, "Build key command failed") {
|
||||||
|
t.Errorf("POST %s = %d %+v, want existing 502 JSON error", path, w.Code, response)
|
||||||
|
}
|
||||||
|
if lock.buildCalls != 1 || lock.sequenceCalls != 0 || lock.storedCommand != "PREVIOUS-ROOM" {
|
||||||
|
t.Errorf("POST %s build=%d sequence=%d stored=%q, want one rejected build and no execution of previous command", path, lock.buildCalls, lock.sequenceCalls, lock.storedCommand)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(d.calls, []string{"prepare current"}) || d.activity != 0 || d.outsideActivity {
|
||||||
|
t.Errorf("POST %s dispenser=%v active=%d outside=%t, want preparation only and released foreground", path, d.calls, d.activity, d.outsideActivity)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreditCallModernPreauthReportsActualReturnedAmount(t *testing.T) {
|
||||||
|
for _, total := range []string{"3100", "12000"} {
|
||||||
|
t.Run(total, func(t *testing.T) {
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "SALE", types.TotalAmount: total, types.Reference: "SYNTH-HOLD"}})
|
||||||
|
})
|
||||||
|
database := preauthTestDatabase(t, app)
|
||||||
|
app.creditCallReceipt = func(string) {}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
app.preauthPayment(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
want := int64(12000)
|
||||||
|
if total == "3100" {
|
||||||
|
want = 3100
|
||||||
|
}
|
||||||
|
if len(frames) != 1 || frames[0].Result == nil || frames[0].Result.Outcome != "approved" || frames[0].Result.AmountMinor != want {
|
||||||
|
t.Errorf("Preauth(request12000,total%s) frames=%+v, want approved actual%d", total, frames, want)
|
||||||
|
}
|
||||||
|
if got := waitPreauthInsert(t, database)["TotalMinorUnits"]; got != total {
|
||||||
|
t.Errorf("Preauth(total%s) SQLamount=%v, want unchanged provider amount", total, got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallModernPreauthMalformedAmountRequiresReception(t *testing.T) {
|
||||||
|
for _, total := range []string{"bad", "-1", "9223372036854775808"} {
|
||||||
|
t.Run(total, func(t *testing.T) {
|
||||||
|
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "ACCOUNT VERIFICATION", types.TotalAmount: total, types.Reference: "SYNTH-HOLD"}})
|
||||||
|
})
|
||||||
|
app.creditCallReceipt = func(string) {}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
app.preauthPayment(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
if len(frames) != 1 || frames[0].Result == nil {
|
||||||
|
t.Fatalf("Preauth(total%s) frames=%+v, want final uncertainty", total, frames)
|
||||||
|
}
|
||||||
|
final := frames[0].Result
|
||||||
|
if final.Outcome != "unknown" || final.Retryable || final.AmountMinor != 0 || final.Reason != "amount_unverified" {
|
||||||
|
t.Errorf("Preauth(total%s) final=%+v, want nonretryable unknown without fabricated amount", total, final)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,19 +5,15 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
type creditCallPreauthRequest struct {
|
func (app *App) preauthPayment(w http.ResponseWriter, r *http.Request) {
|
||||||
Amount string `json:"amount"`
|
log.Printf("preauthPayment called")
|
||||||
TransactionType string `json:"transactionType"`
|
app.streamPayment(w, r, true)
|
||||||
CheckoutDate string `json:"checkoutDate"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (app *App) streamCreditCallPreauth(w http.ResponseWriter, r *http.Request) {
|
|
||||||
app.streamCreditCall(w, r, true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// executeCreditCallPreauth finalizes the existing unconfirmed transaction.
|
// executeCreditCallPreauth finalizes the existing unconfirmed transaction.
|
||||||
@@ -25,6 +21,11 @@ func (app *App) streamCreditCallPreauth(w http.ResponseWriter, r *http.Request)
|
|||||||
func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.TransactionRec,
|
func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.TransactionRec,
|
||||||
start func(*http.Client) (creditcall.TransactionResultXML, error)) creditCallSaleOutcome {
|
start func(*http.Client) (creditcall.TransactionResultXML, error)) creditCallSaleOutcome {
|
||||||
const op = logging.Op("takePreauthorization")
|
const op = logging.Op("takePreauthorization")
|
||||||
|
entry := log.WithFields(log.Fields{
|
||||||
|
"operation": "preauth", "hotel": app.cfg.Hotel, "kiosk": app.cfg.Kiosk,
|
||||||
|
"requestedType": request.TransactionType, "requestedAmount": request.AmountMinorUnits,
|
||||||
|
})
|
||||||
|
entry.Info("CreditCall PREAUTH started")
|
||||||
outcome := creditCallSaleOutcome{
|
outcome := creditCallSaleOutcome{
|
||||||
HTTPStatus: http.StatusBadGateway,
|
HTTPStatus: http.StatusBadGateway,
|
||||||
Status: cmstypes.StatusRec{Code: http.StatusInternalServerError, Message: "500 Internal server error"},
|
Status: cmstypes.StatusRec{Code: http.StatusInternalServerError, Message: "500 Internal server error"},
|
||||||
@@ -32,14 +33,32 @@ func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.T
|
|||||||
transaction, err := start(app.creditCallClient())
|
transaction, err := start(app.creditCallClient())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
||||||
|
entry.Error("CreditCall PREAUTH ended without a processor result")
|
||||||
outcome.FailureType = types.ResultError
|
outcome.FailureType = types.ResultError
|
||||||
outcome.FailureDescription = "No response from payment processor"
|
outcome.FailureDescription = "No response from payment processor"
|
||||||
return outcome
|
return outcome
|
||||||
}
|
}
|
||||||
var result creditcall.PaymentResult
|
var result creditcall.PaymentResult
|
||||||
result.FillFromTransactionResult(transaction)
|
result.FillFromTransactionResult(transaction)
|
||||||
|
entry = entry.WithFields(log.Fields{
|
||||||
|
"reference": result.Fields[types.Reference],
|
||||||
|
"transactionResult": result.Fields[types.TransactionResult],
|
||||||
|
"transactionType": result.Fields[types.TransactionType],
|
||||||
|
"totalAmount": result.Fields[types.TotalAmount],
|
||||||
|
"receiptPresent": result.CardholderReceipt != "",
|
||||||
|
})
|
||||||
|
entry.Info("CreditCall PREAUTH processor result received")
|
||||||
|
if result.Fields[types.TransactionType] == "" {
|
||||||
|
entry.Warn("CreditCall PREAUTH result has no TRANSACTION_TYPE")
|
||||||
|
}
|
||||||
app.printCreditCallReceipt(result.CardholderReceipt)
|
app.printCreditCallReceipt(result.CardholderReceipt)
|
||||||
approved, persist := creditcall.PreauthDecision(result.Fields)
|
approved, persist := creditcall.PreauthDecision(result.Fields)
|
||||||
|
decision := entry.WithFields(log.Fields{"approved": approved, "persist": persist})
|
||||||
|
if approved {
|
||||||
|
decision.Info("CreditCall PREAUTH decision")
|
||||||
|
} else {
|
||||||
|
decision.Warn("CreditCall PREAUTH decision")
|
||||||
|
}
|
||||||
outcome.HTTPStatus = http.StatusOK
|
outcome.HTTPStatus = http.StatusOK
|
||||||
outcome.Status = result.Status
|
outcome.Status = result.Status
|
||||||
outcome.Payment = result
|
outcome.Payment = result
|
||||||
@@ -47,6 +66,10 @@ func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.T
|
|||||||
outcome.FailureType = result.Fields[types.TransactionResult]
|
outcome.FailureType = result.Fields[types.TransactionResult]
|
||||||
outcome.FailureDescription = result.Fields[types.Errors]
|
outcome.FailureDescription = result.Fields[types.Errors]
|
||||||
if persist {
|
if persist {
|
||||||
|
if result.Fields[types.TotalAmount] == "" {
|
||||||
|
entry.Warn("CreditCall PREAUTH persistence requested without TOTAL_AMOUNT")
|
||||||
|
}
|
||||||
|
entry.Info("CreditCall PREAUTH persistence scheduled")
|
||||||
go app.persistPreauth(ctx, result.Fields, request.CheckoutDate)
|
go app.persistPreauth(ctx, result.Fields, request.CheckoutDate)
|
||||||
}
|
}
|
||||||
return outcome
|
return outcome
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
logtest "github.com/sirupsen/logrus/hooks/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
func capturePreauthLogs(t *testing.T) *logtest.Hook {
|
||||||
|
t.Helper()
|
||||||
|
logger := log.StandardLogger()
|
||||||
|
previousHooks := logger.ReplaceHooks(make(log.LevelHooks))
|
||||||
|
previousLevel := logger.GetLevel()
|
||||||
|
logger.SetLevel(log.InfoLevel)
|
||||||
|
hook := logtest.NewGlobal()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
logger.ReplaceHooks(previousHooks)
|
||||||
|
logger.SetLevel(previousLevel)
|
||||||
|
})
|
||||||
|
return hook
|
||||||
|
}
|
||||||
|
|
||||||
|
func requirePreauthLog(t *testing.T, hook *logtest.Hook, message string, level log.Level) *log.Entry {
|
||||||
|
t.Helper()
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
if entry.Message == message {
|
||||||
|
if entry.Level != level {
|
||||||
|
t.Errorf("log %q level=%v, want %v", message, entry.Level, level)
|
||||||
|
}
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("missing log %q", message)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthDecisionLogging(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, result, kind string
|
||||||
|
approved bool
|
||||||
|
level log.Level
|
||||||
|
}{
|
||||||
|
{"verification", "APPROVED", "ACCOUNT VERIFICATION", true, log.InfoLevel},
|
||||||
|
{"missing type", "APPROVED", "", false, log.WarnLevel},
|
||||||
|
{"declined", "DECLINED", "SALE", false, log.WarnLevel},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
hook := capturePreauthLogs(t)
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, creditCallReceipt: func(string) {}}
|
||||||
|
outcome := app.executeCreditCallPreauth(context.Background(), cmstypes.TransactionRec{TransactionType: "AccountVerification"},
|
||||||
|
func(*http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
return creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{
|
||||||
|
{Key: types.TransactionResult, Value: tc.result},
|
||||||
|
{Key: types.TransactionType, Value: tc.kind},
|
||||||
|
{Key: types.Reference, Value: "log-test-ref"},
|
||||||
|
{Key: types.PanMasked, Value: "sensitive-card-sentinel"},
|
||||||
|
{Key: types.CardHash, Value: "sensitive-hash-sentinel"},
|
||||||
|
{Key: types.ReceiptDataCardholder, Value: "sensitive-receipt-sentinel"},
|
||||||
|
}}, nil
|
||||||
|
})
|
||||||
|
if outcome.Approved != tc.approved {
|
||||||
|
t.Errorf("approved=%t, want %t", outcome.Approved, tc.approved)
|
||||||
|
}
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH started", log.InfoLevel)
|
||||||
|
provider := requirePreauthLog(t, hook, "CreditCall PREAUTH processor result received", log.InfoLevel)
|
||||||
|
if provider.Data["transactionType"] != tc.kind || provider.Data["transactionResult"] != tc.result || provider.Data["receiptPresent"] != true {
|
||||||
|
t.Errorf("provider log=%v, want type=%q result=%q receiptPresent=true", provider.Data, tc.kind, tc.result)
|
||||||
|
}
|
||||||
|
decision := requirePreauthLog(t, hook, "CreditCall PREAUTH decision", tc.level)
|
||||||
|
if decision.Data["approved"] != tc.approved || decision.Data["persist"] != false || decision.Data["reference"] != "log-test-ref" {
|
||||||
|
t.Errorf("decision log=%v, want approved=%t persist=false reference=log-test-ref", decision.Data, tc.approved)
|
||||||
|
}
|
||||||
|
if tc.kind == "" {
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH result has no TRANSACTION_TYPE", log.WarnLevel)
|
||||||
|
}
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
for key, value := range entry.Data {
|
||||||
|
if value == "sensitive-card-sentinel" || value == "sensitive-hash-sentinel" || value == "sensitive-receipt-sentinel" {
|
||||||
|
t.Errorf("log %q exposed sensitive field %q", entry.Message, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entry.Message == "CreditCall PREAUTH persistence scheduled" {
|
||||||
|
t.Error("non-persisting result logged persistence scheduling")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthStartFailureLogging(t *testing.T) {
|
||||||
|
hook := capturePreauthLogs(t)
|
||||||
|
app := &App{cfg: &config.ConfigRec{}}
|
||||||
|
outcome := app.executeCreditCallPreauth(context.Background(), cmstypes.TransactionRec{},
|
||||||
|
func(*http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
return creditcall.TransactionResultXML{}, errors.New("test transport failure")
|
||||||
|
})
|
||||||
|
if outcome.HTTPStatus != http.StatusBadGateway {
|
||||||
|
t.Errorf("HTTPStatus=%d, want 502", outcome.HTTPStatus)
|
||||||
|
}
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH started", log.InfoLevel)
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH ended without a processor result", log.ErrorLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthPersistenceLogging(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, amount, message string
|
||||||
|
level log.Level
|
||||||
|
breakSpool bool
|
||||||
|
}{
|
||||||
|
{"SQL", "3100", "CreditCall PREAUTH SQL persistence completed", log.InfoLevel, false},
|
||||||
|
{"spool", "", "CreditCall PREAUTH saved to spool; SQL persistence pending", log.WarnLevel, false},
|
||||||
|
{"spool failure", "", "failed to spool preauth", log.ErrorLevel, true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
hook := capturePreauthLogs(t)
|
||||||
|
app := &App{cfg: &config.ConfigRec{}}
|
||||||
|
preauthTestDatabase(t, app)
|
||||||
|
if tc.breakSpool {
|
||||||
|
path := filepath.Join(app.cfg.LogDir, "not-a-directory")
|
||||||
|
if err := os.WriteFile(path, nil, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app.cfg.LogDir = path
|
||||||
|
}
|
||||||
|
app.persistPreauth(context.Background(), map[string]string{
|
||||||
|
types.Reference: "persist-test-ref", types.TotalAmount: tc.amount,
|
||||||
|
}, "2026-10-21 00:00:00 +0000")
|
||||||
|
entry := requirePreauthLog(t, hook, tc.message, tc.level)
|
||||||
|
if entry.Data["reference"] != "persist-test-ref" || entry.Data["operation"] != "preauth" {
|
||||||
|
t.Errorf("persistence log=%v, want reference=persist-test-ref operation=preauth", entry.Data)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,19 +7,21 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"errors"
|
"errors"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"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 {
|
||||||
@@ -143,8 +145,8 @@ func TestCreditCallPreauthLegacyCharacterization(t *testing.T) {
|
|||||||
t.Errorf("persisted=%v, want provider amount/reference", got)
|
t.Errorf("persisted=%v, want provider amount/reference", got)
|
||||||
}
|
}
|
||||||
departure := time.Date(2026, 9, 11, 0, 0, 0, 0, time.Local).UTC()
|
departure := time.Date(2026, 9, 11, 0, 0, 0, 0, time.Local).UTC()
|
||||||
if got["DepartureDate"] != departure || got["ReleaseDate"] != departure.Add(48*time.Hour) {
|
if got["DepartureDate"] != departure || got["ReleaseDate"] != departure.Add(96*time.Hour) {
|
||||||
t.Errorf("persisted dates=%v, want existing local midnight plus 48 hours", got)
|
t.Errorf("persisted dates=%v, want existing local midnight plus 96 hours", got)
|
||||||
}
|
}
|
||||||
} else if c.count.Load() != 0 {
|
} else if c.count.Load() != 0 {
|
||||||
t.Error("non-persisting result inserted SQL")
|
t.Error("non-persisting result inserted SQL")
|
||||||
@@ -154,7 +156,8 @@ func TestCreditCallPreauthLegacyCharacterization(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func preauthStreamRequest(amount, kind, checkout string) *http.Request {
|
func preauthStreamRequest(amount, kind, checkout string) *http.Request {
|
||||||
body, _ := json.Marshal(creditCallPreauthRequest{Amount: amount, TransactionType: kind, CheckoutDate: checkout})
|
value, _ := strconv.ParseInt(amount, 10, 64)
|
||||||
|
body, _ := json.Marshal(paymentapi.Request{Amount: value, CheckoutDate: checkout})
|
||||||
r := httptest.NewRequest(http.MethodPost, "/api/payment/preauth", strings.NewReader(string(body)))
|
r := httptest.NewRequest(http.MethodPost, "/api/payment/preauth", strings.NewReader(string(body)))
|
||||||
r.Header.Set("Content-Type", "application/json")
|
r.Header.Set("Content-Type", "application/json")
|
||||||
return r
|
return r
|
||||||
@@ -214,7 +217,7 @@ func TestCreditCallPreauthStreamingParity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
if stream {
|
if stream {
|
||||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest(amount, kind, date))
|
app.preauthPayment(recorder, preauthStreamRequest(amount, kind, date))
|
||||||
frames := decodePaymentStream(t, recorder.Body)
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
var statuses []string
|
var statuses []string
|
||||||
for _, frame := range frames {
|
for _, frame := range frames {
|
||||||
@@ -230,7 +233,7 @@ func TestCreditCallPreauthStreamingParity(t *testing.T) {
|
|||||||
if final == nil {
|
if final == nil {
|
||||||
t.Fatal("missing structured final")
|
t.Fatal("missing structured final")
|
||||||
}
|
}
|
||||||
if (final.Outcome == "approved") != tc.approved || final.Status != legacy.Status || final.HTTPStatus != 200 {
|
if (final.Outcome == "approved") != tc.approved || final.HTTPStatus != 200 {
|
||||||
t.Errorf("stream final=%+v, legacy=%+v", final, legacy)
|
t.Errorf("stream final=%+v, legacy=%+v", final, legacy)
|
||||||
}
|
}
|
||||||
if tc.approved && (final.TransactionReference != "preauth-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1133" || final.ExpiryDate != "1228" || final.CardHash != "hash" || final.CardReference != "cardref") {
|
if tc.approved && (final.TransactionReference != "preauth-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1133" || final.ExpiryDate != "1228" || final.CardHash != "hash" || final.CardReference != "cardref") {
|
||||||
@@ -296,9 +299,9 @@ func TestCreditCallInboundCancellationAfterDispatch(t *testing.T) {
|
|||||||
go func() {
|
go func() {
|
||||||
defer close(done)
|
defer close(done)
|
||||||
if preauth {
|
if preauth {
|
||||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000").WithContext(ctx))
|
app.preauthPayment(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000").WithContext(ctx))
|
||||||
} else {
|
} else {
|
||||||
app.streamCreditCallSale(recorder, saleRequest(true).WithContext(ctx))
|
app.salePayment(recorder, saleRequest(true).WithContext(ctx))
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
select {
|
select {
|
||||||
@@ -342,9 +345,9 @@ func TestCreditCallPreauthMissingAmountNeverSynthesized(t *testing.T) {
|
|||||||
c := preauthTestDatabase(t, app)
|
c := preauthTestDatabase(t, app)
|
||||||
app.creditCallReceipt = func(string) {}
|
app.creditCallReceipt = func(string) {}
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest("9999", "Sale", "2026-09-11 00:00:00 +0000"))
|
app.preauthPayment(recorder, preauthStreamRequest("9999", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||||
frames := decodePaymentStream(t, recorder.Body)
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
if frames[0].Result.Outcome != "approved" {
|
if frames[0].Result.Outcome != "approved" || frames[0].Result.AmountMinor != 9999 {
|
||||||
t.Fatalf("missing amount changed approval: %+v", frames[0].Result)
|
t.Fatalf("missing amount changed approval: %+v", frames[0].Result)
|
||||||
}
|
}
|
||||||
deadline := time.Now().Add(3 * time.Second)
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
@@ -378,16 +381,22 @@ func TestCreditCallPreauthStreamFailureAndCancelledBeforeDispatch(t *testing.T)
|
|||||||
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { calls++; return transport.RoundTrip(r) })
|
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { calls++; return transport.RoundTrip(r) })
|
||||||
app.creditCallReceipt = func(string) { t.Error("malformed stream printed receipt") }
|
app.creditCallReceipt = func(string) { t.Error("malformed stream printed receipt") }
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest("", "AccountVerification", ""))
|
app.preauthPayment(recorder, preauthStreamRequest("", "AccountVerification", ""))
|
||||||
frames := decodePaymentStream(t, recorder.Body)
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
if calls != 1 || len(frames) != 1 || frames[0].Result.Outcome != "error" || frames[0].Result.HTTPStatus != 502 {
|
if calls != 1 || len(frames) != 1 || frames[0].Result.Outcome != "unknown" || frames[0].Result.HTTPStatus != 502 {
|
||||||
t.Errorf("invalid stream %q: calls=%d frames=%+v", body, calls, frames)
|
t.Errorf("invalid stream %q: calls=%d frames=%+v", body, calls, frames)
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
cancel()
|
cancel()
|
||||||
app.streamCreditCallPreauth(httptest.NewRecorder(), preauthStreamRequest("", "AccountVerification", "").WithContext(ctx))
|
app.preauthPayment(httptest.NewRecorder(), preauthStreamRequest("", "AccountVerification", "").WithContext(ctx))
|
||||||
if calls != 1 {
|
if calls != 1 {
|
||||||
t.Error("already-cancelled request dispatched a transaction")
|
t.Error("already-cancelled request dispatched a transaction")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type creditCallPreauthRequest struct {
|
||||||
|
Amount string `json:"amount"`
|
||||||
|
TransactionType string `json:"transactionType"`
|
||||||
|
CheckoutDate string `json:"checkoutDate"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// creditCallProcessor delegates to the unchanged legacy execution/finalization core.
|
||||||
|
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 {
|
||||||
|
if req.Amount < 0 {
|
||||||
|
return paymentsvc.ErrPreauthUnsupported
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (p *creditCallProcessor) Sale(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
return p.run(ctx, req, status, false)
|
||||||
|
}
|
||||||
|
func (p *creditCallProcessor) Preauth(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
return p.run(ctx, req, status, true)
|
||||||
|
}
|
||||||
|
func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler, preauth bool) (*paymentsvc.Result, error) {
|
||||||
|
transaction := cmstypes.TransactionRec{AmountMinorUnits: strconv.FormatInt(req.Amount, 10), TransactionType: "Sale", CheckoutDate: req.CheckoutDate}
|
||||||
|
if preauth && req.Amount == 0 {
|
||||||
|
transaction.AmountMinorUnits = ""
|
||||||
|
transaction.TransactionType = "AccountVerification"
|
||||||
|
}
|
||||||
|
var initial creditCallInitialResult
|
||||||
|
var diagnostic creditCallDiagnostic
|
||||||
|
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
result, err := callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) {
|
||||||
|
if status != nil {
|
||||||
|
status(paymentsvc.StatusUpdate{Code: code})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
initial = classifyCreditCallInitialResult(result)
|
||||||
|
diagnostic = creditCallInitialDiagnostic(result)
|
||||||
|
}
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
var outcome creditCallSaleOutcome
|
||||||
|
if preauth {
|
||||||
|
// The existing asynchronous PREAUTH persistence must outlive response delivery.
|
||||||
|
outcome = p.app.executeCreditCallPreauth(context.WithoutCancel(ctx), transaction, start)
|
||||||
|
} else {
|
||||||
|
outcome = p.app.executeCreditCallSale(transaction, start)
|
||||||
|
}
|
||||||
|
final := outcome.streamResult(initial)
|
||||||
|
final.AmountMinor, final.CurrencyCode = req.Amount, req.Currency
|
||||||
|
if outcome.Approved {
|
||||||
|
if raw := outcome.Payment.Fields[types.TotalAmount]; raw != "" {
|
||||||
|
amount, err := strconv.ParseInt(raw, 10, 64)
|
||||||
|
if err != nil || amount < 0 {
|
||||||
|
final.Outcome, final.Retryable = "unknown", false
|
||||||
|
final.AmountMinor = 0
|
||||||
|
final.Reason = "amount_unverified"
|
||||||
|
final.Message = "Payment amount uncertain; contact reception"
|
||||||
|
} else {
|
||||||
|
final.AmountMinor = amount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if outcome.confirmationDiagnostic.reason != "" {
|
||||||
|
diagnostic = outcome.confirmationDiagnostic
|
||||||
|
}
|
||||||
|
diagnostic.apply(&final)
|
||||||
|
return &paymentsvc.Result{Terminal: final}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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"}
|
||||||
|
if final.HTTPStatus == 0 {
|
||||||
|
final.HTTPStatus = http.StatusOK
|
||||||
|
}
|
||||||
|
if outcome.Approved {
|
||||||
|
fields := outcome.Payment.Fields
|
||||||
|
final.Outcome, final.Message = "approved", "Payment approved"
|
||||||
|
final.TransactionReference = fields[types.Reference]
|
||||||
|
final.CardType = fields[types.CardType]
|
||||||
|
final.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
|
||||||
|
final.ExpiryDate = fields[types.ExpiryDate]
|
||||||
|
final.CardHash, final.CardReference = fields[types.CardHash], fields[types.CardReference]
|
||||||
|
return final
|
||||||
|
}
|
||||||
|
// 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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 }
|
||||||
@@ -75,7 +75,7 @@ func TestCreditCallStreamFailureNeverRestartsOrConfirms(t *testing.T) {
|
|||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
app.salePayment(recorder, saleRequest(true))
|
app.salePayment(recorder, saleRequest(true))
|
||||||
frames := decodePaymentStream(t, recorder.Body)
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
if calls != 1 || len(frames) != 2 || frames[1].Result == nil || frames[1].Result.Outcome != "error" || frames[1].Result.HTTPStatus != 502 {
|
if calls != 1 || len(frames) != 2 || frames[1].Result == nil || frames[1].Result.Outcome != "unknown" || frames[1].Result.HTTPStatus != 502 {
|
||||||
t.Errorf("malformed stream calls=%d frames=%+v", calls, frames)
|
t.Errorf("malformed stream calls=%d frames=%+v", calls, frames)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
@@ -185,13 +185,15 @@ func newCreditCallTestApp(t *testing.T, handler http.HandlerFunc) *App {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return &App{isPayment: true, creditCallStreamEnabled: true, cfg: &config.ConfigRec{TimeoutSeconds: 1},
|
app := &App{isPayment: true, cfg: &config.ConfigRec{TimeoutSeconds: 1},
|
||||||
creditCallTransport: creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
creditCallTransport: creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
clone := r.Clone(r.Context())
|
clone := r.Clone(r.Context())
|
||||||
clone.URL.Scheme, clone.URL.Host = target.Scheme, target.Host
|
clone.URL.Scheme, clone.URL.Host = target.Scheme, target.Host
|
||||||
return server.Client().Transport.RoundTrip(clone)
|
return server.Client().Transport.RoundTrip(clone)
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
app.EnableCreditCallStreaming()
|
||||||
|
return app
|
||||||
}
|
}
|
||||||
|
|
||||||
func saleRequest(stream bool) *http.Request {
|
func saleRequest(stream bool) *http.Request {
|
||||||
@@ -217,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",
|
||||||
@@ -292,7 +294,7 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
|
|||||||
t.Fatalf("frames = %+v, want two ordered hints and one final", frames)
|
t.Fatalf("frames = %+v, want two ordered hints and one final", frames)
|
||||||
}
|
}
|
||||||
final := frames[2].Result
|
final := frames[2].Result
|
||||||
if final.HTTPStatus != http.StatusOK || final.Status != legacy.Status || (final.Outcome == "approved") != test.approved {
|
if final.HTTPStatus != http.StatusOK || (final.Outcome == "approved") != test.approved {
|
||||||
t.Errorf("structured final = %+v, legacy = %+v", final, legacy)
|
t.Errorf("structured final = %+v, legacy = %+v", final, legacy)
|
||||||
}
|
}
|
||||||
parsed, err := url.Parse(legacy.Data)
|
parsed, err := url.Parse(legacy.Data)
|
||||||
@@ -303,12 +305,164 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
|
|||||||
if final.TransactionReference != "native-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1234" || final.CardHash != "hash" || final.CardReference != "card-ref" || final.ExpiryDate != "1228" {
|
if final.TransactionReference != "native-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1234" || final.CardHash != "hash" || final.CardReference != "card-ref" || final.ExpiryDate != "1228" {
|
||||||
t.Errorf("retained structured fields = %+v", final)
|
t.Errorf("retained structured fields = %+v", final)
|
||||||
}
|
}
|
||||||
} else if final.Message != parsed.Query().Get("Description") {
|
} else if final.Outcome == "approved" {
|
||||||
t.Errorf("structured message = %q, legacy description = %q", final.Message, parsed.Query().Get("Description"))
|
t.Errorf("structured message = %q, legacy description = %q", final.Message, parsed.Query().Get("Description"))
|
||||||
}
|
}
|
||||||
if frames[2].Response != nil {
|
|
||||||
t.Error("CreditCall stream included legacy response")
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func 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)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -318,7 +472,8 @@ func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
|
|||||||
for _, streaming := range []bool{false, true} {
|
for _, streaming := range []bool{false, true} {
|
||||||
var attempts int
|
var attempts int
|
||||||
var times []time.Time
|
var times []time.Time
|
||||||
app := &App{isPayment: true, creditCallStreamEnabled: true, cfg: &config.ConfigRec{}}
|
app := &App{isPayment: true, cfg: &config.ConfigRec{}}
|
||||||
|
app.EnableCreditCallStreaming()
|
||||||
app.creditCallReceipt = func(string) { t.Error("transport-failed confirmation must not print a receipt") }
|
app.creditCallReceipt = func(string) { t.Error("transport-failed confirmation must not print a receipt") }
|
||||||
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
if r.Context().Err() != nil {
|
if r.Context().Err() != nil {
|
||||||
@@ -349,7 +504,7 @@ func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
if streaming {
|
if streaming {
|
||||||
frames := decodePaymentStream(t, recorder.Body)
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
if len(frames) != 1 || frames[0].Result.HTTPStatus != 502 || frames[0].Result.Status.Code != 500 || frames[0].Result.Message != "Transaction error" {
|
if len(frames) != 1 || frames[0].Result.HTTPStatus != 502 || frames[0].Result.Outcome != "unknown" || frames[0].Result.Retryable {
|
||||||
t.Fatalf("confirmation failure frames=%+v", frames)
|
t.Fatalf("confirmation failure frames=%+v", frames)
|
||||||
}
|
}
|
||||||
} else if recorder.Code != 502 {
|
} else if recorder.Code != 502 {
|
||||||
|
|||||||
@@ -10,184 +10,16 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"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/mail"
|
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
type creditCallStreamResult struct {
|
// EnableCreditCallStreaming selects the existing CreditCall execution core.
|
||||||
Outcome string `json:"outcome"`
|
func (app *App) EnableCreditCallStreaming() {
|
||||||
Message string `json:"message"`
|
app.paymentService = paymentsvc.NewService(&creditCallProcessor{app: app})
|
||||||
HTTPStatus int `json:"httpStatus"`
|
|
||||||
Status cmstypes.StatusRec `json:"status"`
|
|
||||||
TransactionReference string `json:"transactionReference,omitempty"`
|
|
||||||
CardType string `json:"cardType,omitempty"`
|
|
||||||
MaskedCardNumber string `json:"maskedCardNumber,omitempty"`
|
|
||||||
ExpiryDate string `json:"expiryDate,omitempty"`
|
|
||||||
CardHash string `json:"cardHash,omitempty"`
|
|
||||||
CardReference string `json:"cardReference,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (outcome creditCallSaleOutcome) streamResult() creditCallStreamResult {
|
|
||||||
result := creditCallStreamResult{
|
|
||||||
Outcome: "error", HTTPStatus: outcome.HTTPStatus, Status: outcome.Status,
|
|
||||||
Message: creditcall.FailureDescription(outcome.FailureType, outcome.FailureDescription),
|
|
||||||
}
|
|
||||||
if !outcome.Approved {
|
|
||||||
switch strings.ToLower(outcome.FailureType) {
|
|
||||||
case "declined":
|
|
||||||
result.Outcome = "declined"
|
|
||||||
case "cancelled", "canceled":
|
|
||||||
result.Outcome = "cancelled"
|
|
||||||
case "timeout":
|
|
||||||
result.Outcome = "timeout"
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
fields := outcome.Payment.Fields
|
|
||||||
result.Outcome = "approved"
|
|
||||||
result.Message = "Payment approved"
|
|
||||||
result.TransactionReference = fields[types.Reference]
|
|
||||||
result.CardType = fields[types.CardType]
|
|
||||||
result.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
|
|
||||||
result.ExpiryDate = fields[types.ExpiryDate]
|
|
||||||
result.CardHash = fields[types.CardHash]
|
|
||||||
result.CardReference = fields[types.CardReference]
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnableCreditCallStreaming selects the CreditCall core without a generic provider.
|
|
||||||
func (app *App) EnableCreditCallStreaming() { app.creditCallStreamEnabled = true }
|
|
||||||
|
|
||||||
func (app *App) streamCreditCallSale(w http.ResponseWriter, r *http.Request) {
|
|
||||||
app.streamCreditCall(w, r, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (app *App) streamCreditCall(w http.ResponseWriter, r *http.Request, preauth bool) {
|
|
||||||
setPaymentCORS(w)
|
|
||||||
if r.Method == http.MethodOptions {
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
|
||||||
w.Header().Set("Cache-Control", "no-cache")
|
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
||||||
controller := http.NewResponseController(w)
|
|
||||||
encoder := json.NewEncoder(w)
|
|
||||||
deliveryFailed := false
|
|
||||||
// Only this handler writes the response. The transaction worker never waits
|
|
||||||
// for network delivery, including when the peer stops reading without closing.
|
|
||||||
send := func(frame paymentStreamMessage) {
|
|
||||||
if deliveryFailed || r.Context().Err() != nil {
|
|
||||||
deliveryFailed = true
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := encoder.Encode(frame); err != nil {
|
|
||||||
deliveryFailed = true
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := controller.Flush(); err != nil {
|
|
||||||
deliveryFailed = true
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
reject := func(status int, message string) {
|
|
||||||
result := creditCallStreamResult{Outcome: "error", Message: message, HTTPStatus: status,
|
|
||||||
Status: cmstypes.StatusRec{Code: status, Message: http.StatusText(status)}}
|
|
||||||
w.WriteHeader(status)
|
|
||||||
send(paymentStreamMessage{Type: "result", Result: &result})
|
|
||||||
}
|
|
||||||
if preauth && !app.creditCallStreamEnabled {
|
|
||||||
reject(http.StatusServiceUnavailable, "CreditCall preauthorization streaming is not enabled")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !app.isPayment && !app.cfg.TestMode {
|
|
||||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Error", "Attempted payment while payment processing is disabled")
|
|
||||||
reject(http.StatusServiceUnavailable, "Payment processing is disabled")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
reject(http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
|
||||||
reject(http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer r.Body.Close()
|
|
||||||
var transaction cmstypes.TransactionRec
|
|
||||||
if preauth {
|
|
||||||
var request creditCallPreauthRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
|
||||||
reject(http.StatusBadRequest, "Invalid JSON payload")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
transaction = cmstypes.TransactionRec{AmountMinorUnits: request.Amount, TransactionType: request.TransactionType, CheckoutDate: request.CheckoutDate}
|
|
||||||
} else {
|
|
||||||
var request SalePaymentRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
|
||||||
reject(http.StatusBadRequest, "Invalid JSON payload")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if request.Amount <= 0 {
|
|
||||||
reject(http.StatusBadRequest, "Amount must be greater than zero")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
transaction = cmstypes.TransactionRec{AmountMinorUnits: strconv.FormatInt(request.Amount, 10), TransactionType: "Sale"}
|
|
||||||
}
|
|
||||||
if _, ok := w.(http.Flusher); !ok {
|
|
||||||
reject(http.StatusInternalServerError, "Streaming payment updates are not supported")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validation belongs to the incoming request. This handoff owns financial dispatch.
|
|
||||||
if r.Context().Err() != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
financialContext := context.WithoutCancel(r.Context())
|
|
||||||
progress := make(chan string, 128)
|
|
||||||
finished := make(chan creditCallSaleOutcome, 1)
|
|
||||||
go func() {
|
|
||||||
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
|
||||||
return callChipDNATransactionStream(financialContext, client, transaction, func(code string) {
|
|
||||||
select {
|
|
||||||
case progress <- code:
|
|
||||||
default: // Observational progress may be dropped under backpressure.
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
var outcome creditCallSaleOutcome
|
|
||||||
if preauth {
|
|
||||||
outcome = app.executeCreditCallPreauth(financialContext, transaction, start)
|
|
||||||
} else {
|
|
||||||
outcome = app.executeCreditCallSale(transaction, start)
|
|
||||||
}
|
|
||||||
close(progress)
|
|
||||||
finished <- outcome // Independent of the bounded progress queue.
|
|
||||||
}()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case code, ok := <-progress:
|
|
||||||
if !ok {
|
|
||||||
progress = nil
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
send(paymentStreamMessage{Type: "status", Code: code})
|
|
||||||
case outcome := <-finished:
|
|
||||||
if progress != nil {
|
|
||||||
for code := range progress {
|
|
||||||
send(paymentStreamMessage{Type: "status", Code: code})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
result := outcome.streamResult()
|
|
||||||
send(paymentStreamMessage{Type: "result", Result: &result})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func callChipDNAStream(client *http.Client, amount int64, onStatus func(string)) (creditcall.TransactionResultXML, error) {
|
func callChipDNAStream(client *http.Client, amount int64, onStatus func(string)) (creditcall.TransactionResultXML, error) {
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,7 +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/v2/internal/types"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -74,18 +75,23 @@ func (app *App) spoolPath() string {
|
|||||||
// It never returns an error to the caller (so your HTTP flow stays simple),
|
// It never returns an error to the caller (so your HTTP flow stays simple),
|
||||||
// but it logs failures.
|
// but it logs failures.
|
||||||
func (app *App) persistPreauth(ctx context.Context, fields map[string]string, checkoutDate string) {
|
func (app *App) persistPreauth(ctx context.Context, fields map[string]string, checkoutDate string) {
|
||||||
|
entry := log.WithFields(log.Fields{
|
||||||
|
"operation": "preauth", "reference": fields[types.Reference],
|
||||||
|
"hotel": app.cfg.Hotel, "kiosk": app.cfg.Kiosk,
|
||||||
|
})
|
||||||
// First, try DB (with your reconnect logic inside getDB)
|
// First, try DB (with your reconnect logic inside getDB)
|
||||||
dbConn, err := app.getDB(ctx)
|
dbConn, err := app.getDB(ctx)
|
||||||
if err == nil && dbConn != nil {
|
if err == nil && dbConn != nil {
|
||||||
if err := db.InsertPreauth(ctx, dbConn, fields, checkoutDate); err == nil {
|
if err := db.InsertPreauth(ctx, dbConn, fields, checkoutDate); err == nil {
|
||||||
|
entry.Info("CreditCall PREAUTH SQL persistence completed")
|
||||||
// opportunistic drain once DB is alive
|
// opportunistic drain once DB is alive
|
||||||
go app.drainPreauthSpool(context.Background())
|
go app.drainPreauthSpool(context.Background())
|
||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
log.WithError(err).Warn("DB insert failed; will spool preauth")
|
entry.WithError(err).Warn("DB insert failed; will spool preauth")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.WithError(err).Warn("DB unavailable; will spool preauth")
|
entry.WithError(err).Warn("DB unavailable; will spool preauth")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: spool to file
|
// Fallback: spool to file
|
||||||
@@ -95,7 +101,9 @@ func (app *App) persistPreauth(ctx context.Context, fields map[string]string, ch
|
|||||||
Fields: fields,
|
Fields: fields,
|
||||||
}
|
}
|
||||||
if spErr := app.spoolPreauth(rec); spErr != nil {
|
if spErr := app.spoolPreauth(rec); spErr != nil {
|
||||||
log.WithError(spErr).Error("failed to spool preauth")
|
entry.WithError(spErr).Error("failed to spool preauth")
|
||||||
|
} else {
|
||||||
|
entry.Warn("CreditCall PREAUTH saved to spool; SQL persistence pending")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,17 +5,19 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,6 +27,10 @@ type dispenserCallResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type fakeDoorCardDispenser struct {
|
type fakeDoorCardDispenser struct {
|
||||||
|
preparation dispenser.PreparationResult
|
||||||
|
recoverCurrent func(context.Context, dispenser.PreparationResult) error
|
||||||
|
deliver func()
|
||||||
|
|
||||||
prepareCurrent dispenserCallResult
|
prepareCurrent dispenserCallResult
|
||||||
deliverCurrent dispenserCallResult
|
deliverCurrent dispenserCallResult
|
||||||
beginNextErr error
|
beginNextErr error
|
||||||
@@ -45,8 +51,25 @@ func (d *fakeDoorCardDispenser) PrepareCurrentCard(context.Context) (string, err
|
|||||||
return d.prepareCurrent.status, d.prepareCurrent.err
|
return d.prepareCurrent.status, d.prepareCurrent.err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *fakeDoorCardDispenser) PrepareCurrentCardForEncoding(ctx context.Context) (dispenser.PreparationResult, error) {
|
||||||
|
stock, err := d.PrepareCurrentCard(ctx)
|
||||||
|
result := d.preparation
|
||||||
|
result.Stock = stock
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *fakeDoorCardDispenser) RecoverCurrentCard(ctx context.Context, result dispenser.PreparationResult) error {
|
||||||
|
if d.recoverCurrent != nil {
|
||||||
|
return d.recoverCurrent(ctx, result)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (d *fakeDoorCardDispenser) DeliverCurrentCard(context.Context) (string, error) {
|
func (d *fakeDoorCardDispenser) DeliverCurrentCard(context.Context) (string, error) {
|
||||||
d.calls = append(d.calls, "deliver current")
|
d.calls = append(d.calls, "deliver current")
|
||||||
|
if d.deliver != nil {
|
||||||
|
d.deliver()
|
||||||
|
}
|
||||||
return d.deliverCurrent.status, d.deliverCurrent.err
|
return d.deliverCurrent.status, d.deliverCurrent.err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,18 +87,29 @@ func (d *fakeDoorCardDispenser) PrepareNextCard(context.Context) (string, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
type fakeDoorCardLockServer struct {
|
type fakeDoorCardLockServer struct {
|
||||||
|
sequence func() error
|
||||||
|
|
||||||
sequenceErr error
|
sequenceErr error
|
||||||
|
buildErr error
|
||||||
|
storedCommand string
|
||||||
buildCalls int
|
buildCalls int
|
||||||
sequenceCalls int
|
sequenceCalls int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *fakeDoorCardLockServer) BuildCommand(lockserver.DoorCardRequest, time.Time, time.Time) error {
|
func (l *fakeDoorCardLockServer) BuildCommand(request lockserver.DoorCardRequest, _ time.Time, _ time.Time) error {
|
||||||
l.buildCalls++
|
l.buildCalls++
|
||||||
|
if l.buildErr != nil {
|
||||||
|
return l.buildErr
|
||||||
|
}
|
||||||
|
l.storedCommand = request.RoomField
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *fakeDoorCardLockServer) LockSequence() error {
|
func (l *fakeDoorCardLockServer) LockSequence() error {
|
||||||
l.sequenceCalls++
|
l.sequenceCalls++
|
||||||
|
if l.sequence != nil {
|
||||||
|
return l.sequence()
|
||||||
|
}
|
||||||
return l.sequenceErr
|
return l.sequenceErr
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,3 +443,159 @@ func TestDoorCardForegroundLifecycle(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func waitDoorCardSignal(t *testing.T, signal <-chan struct{}, name string) {
|
||||||
|
t.Helper()
|
||||||
|
select {
|
||||||
|
case <-signal:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatalf("timed out waiting for %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func startUncertainDoorCardRequest(t *testing.T, ctx context.Context, d *fakeDoorCardDispenser, lock *fakeDoorCardLockServer) (*httptest.ResponseRecorder, <-chan struct{}) {
|
||||||
|
t.Helper()
|
||||||
|
app := &App{disp: d, lockserver: lock, cfg: &config.ConfigRec{}}
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/issuedoorcard", strings.NewReader(`{"roomField":"101","checkinTime":"2026-07-23 15:00:00 +0100","checkoutTime":"2026-07-24 11:00:00 +0100"}`)).WithContext(ctx)
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
app.issueDoorCard(recorder, request)
|
||||||
|
}()
|
||||||
|
return recorder, done
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIssueDoorCardJoinsUncertainRecoveryBeforeDelivery(t *testing.T) {
|
||||||
|
for _, encodingErr := range []error{nil, errors.New("original lock-server failure")} {
|
||||||
|
t.Run(fmt.Sprint(encodingErr), func(t *testing.T) {
|
||||||
|
lockStarted := make(chan struct{})
|
||||||
|
recoveryStarted := make(chan struct{})
|
||||||
|
recoveryStopped := make(chan struct{})
|
||||||
|
d := &fakeDoorCardDispenser{preparation: dispenser.PreparationResult{UncertainHandoff: true, ShakesUsed: 1}}
|
||||||
|
d.recoverCurrent = func(ctx context.Context, preparation dispenser.PreparationResult) error {
|
||||||
|
defer close(recoveryStopped)
|
||||||
|
<-lockStarted
|
||||||
|
if preparation.ShakesUsed != 1 || !preparation.UncertainHandoff {
|
||||||
|
t.Errorf("recovery preparation=%+v, want same uncertain request and used budget", preparation)
|
||||||
|
}
|
||||||
|
close(recoveryStarted)
|
||||||
|
<-ctx.Done()
|
||||||
|
if context.Cause(ctx).Error() != "LockSequence completed" {
|
||||||
|
t.Errorf("recovery cause=%v, want LockSequence completed", context.Cause(ctx))
|
||||||
|
}
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
d.deliver = func() {
|
||||||
|
select {
|
||||||
|
case <-recoveryStopped:
|
||||||
|
default:
|
||||||
|
t.Error("FC0 started before recovery stopped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lock := &fakeDoorCardLockServer{sequence: func() error {
|
||||||
|
close(lockStarted)
|
||||||
|
<-recoveryStarted
|
||||||
|
return encodingErr
|
||||||
|
}}
|
||||||
|
recorder, done := startUncertainDoorCardRequest(t, context.Background(), d, lock)
|
||||||
|
waitDoorCardSignal(t, done, "encoding and recovery shutdown")
|
||||||
|
wantHTTP := http.StatusOK
|
||||||
|
wantCalls := []string{"prepare current", "deliver current", "begin prepare next"}
|
||||||
|
if encodingErr != nil {
|
||||||
|
wantHTTP = http.StatusBadGateway
|
||||||
|
wantCalls = []string{"prepare current", "deliver current"}
|
||||||
|
if !strings.Contains(recorder.Body.String(), encodingErr.Error()) {
|
||||||
|
t.Errorf("response=%s, want original encoding failure", recorder.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if recorder.Code != wantHTTP || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, wantCalls) {
|
||||||
|
t.Errorf("HTTP=%d lock calls=%d dispenser calls=%v, want HTTP=%d one encoding and %v", recorder.Code, lock.sequenceCalls, d.calls, wantHTTP, wantCalls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIssueDoorCardRecoveryEndingDoesNotEndEncoding(t *testing.T) {
|
||||||
|
for _, recoveryErr := range []error{nil, dispenser.ErrCardWellEmpty, errors.New("RS dispatch failed")} {
|
||||||
|
t.Run(fmt.Sprint(recoveryErr), func(t *testing.T) {
|
||||||
|
lockStarted := make(chan struct{})
|
||||||
|
recoveryStopped := make(chan struct{})
|
||||||
|
releaseLock := make(chan struct{})
|
||||||
|
var releaseOnce sync.Once
|
||||||
|
release := func() { releaseOnce.Do(func() { close(releaseLock) }) }
|
||||||
|
t.Cleanup(release)
|
||||||
|
encodingErr := errors.New("original encoding timed out")
|
||||||
|
d := &fakeDoorCardDispenser{preparation: dispenser.PreparationResult{UncertainHandoff: true, ShakesUsed: 3}}
|
||||||
|
d.recoverCurrent = func(ctx context.Context, preparation dispenser.PreparationResult) error {
|
||||||
|
<-lockStarted
|
||||||
|
close(recoveryStopped) // Encoder arrival, exhaustion or a mechanical failure.
|
||||||
|
return recoveryErr
|
||||||
|
}
|
||||||
|
lock := &fakeDoorCardLockServer{sequence: func() error {
|
||||||
|
close(lockStarted)
|
||||||
|
<-releaseLock
|
||||||
|
return encodingErr
|
||||||
|
}}
|
||||||
|
recorder, done := startUncertainDoorCardRequest(t, context.Background(), d, lock)
|
||||||
|
waitDoorCardSignal(t, recoveryStopped, "recovery ending while lock waits")
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
t.Error("recovery ending replaced still-running LockSequence")
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
waitDoorCardSignal(t, done, "original LockSequence result")
|
||||||
|
if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), encodingErr.Error()) || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current", "deliver current"}) {
|
||||||
|
t.Errorf("HTTP=%d body=%s locks=%d commands=%v, want original encoding error and one FC0", recorder.Code, recorder.Body.String(), lock.sequenceCalls, d.calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIssueDoorCardCancellationStopsOnlyUncertainRecovery(t *testing.T) {
|
||||||
|
lockStarted := make(chan struct{})
|
||||||
|
recoveryStarted := make(chan struct{})
|
||||||
|
recoveryStopped := make(chan struct{})
|
||||||
|
releaseLock := make(chan struct{})
|
||||||
|
var releaseOnce sync.Once
|
||||||
|
release := func() { releaseOnce.Do(func() { close(releaseLock) }) }
|
||||||
|
t.Cleanup(release)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
t.Cleanup(cancel)
|
||||||
|
d := &fakeDoorCardDispenser{preparation: dispenser.PreparationResult{UncertainHandoff: true}}
|
||||||
|
d.recoverCurrent = func(ctx context.Context, preparation dispenser.PreparationResult) error {
|
||||||
|
defer close(recoveryStopped)
|
||||||
|
<-lockStarted
|
||||||
|
close(recoveryStarted)
|
||||||
|
<-ctx.Done()
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
d.deliver = func() {
|
||||||
|
select {
|
||||||
|
case <-recoveryStopped:
|
||||||
|
default:
|
||||||
|
t.Error("delivery raced cancelled recovery")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lock := &fakeDoorCardLockServer{sequence: func() error {
|
||||||
|
close(lockStarted)
|
||||||
|
<-releaseLock
|
||||||
|
return nil
|
||||||
|
}}
|
||||||
|
recorder, done := startUncertainDoorCardRequest(t, ctx, d, lock)
|
||||||
|
waitDoorCardSignal(t, recoveryStarted, "concurrent recovery")
|
||||||
|
cancel()
|
||||||
|
waitDoorCardSignal(t, recoveryStopped, "cancelled recovery")
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
t.Error("caller cancellation ended the original LockSequence")
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
waitDoorCardSignal(t, done, "delivery after encoding")
|
||||||
|
if recorder.Code != http.StatusOK || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current", "deliver current", "begin prepare next"}) {
|
||||||
|
t.Errorf("cancelled HTTP=%d lock calls=%d commands=%v, want original successful encoding and one delivery", recorder.Code, lock.sequenceCalls, d.calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
)
|
)
|
||||||
@@ -29,26 +29,28 @@ import (
|
|||||||
type doorCardDispenser interface {
|
type doorCardDispenser interface {
|
||||||
BeginForeground() func()
|
BeginForeground() func()
|
||||||
PrepareCurrentCard(context.Context) (string, error)
|
PrepareCurrentCard(context.Context) (string, error)
|
||||||
|
PrepareCurrentCardForEncoding(context.Context) (dispenser.PreparationResult, error)
|
||||||
|
RecoverCurrentCard(context.Context, dispenser.PreparationResult) error
|
||||||
DeliverCurrentCard(context.Context) (string, error)
|
DeliverCurrentCard(context.Context) (string, error)
|
||||||
BeginPrepareNextCard(context.Context) error
|
BeginPrepareNextCard(context.Context) error
|
||||||
PrepareNextCard(context.Context) (string, error)
|
PrepareNextCard(context.Context) (string, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type App struct {
|
type App struct {
|
||||||
disp doorCardDispenser
|
trustSelected bool
|
||||||
lockserver lockserver.LockServer
|
disp doorCardDispenser
|
||||||
paymentService *paymentsvc.Service
|
lockserver lockserver.LockServer
|
||||||
creditCallStreamEnabled bool
|
paymentService *paymentsvc.Service
|
||||||
creditCallTransport http.RoundTripper
|
creditCallTransport http.RoundTripper
|
||||||
creditCallReceipt func(string)
|
creditCallReceipt func(string)
|
||||||
isPayment bool
|
isPayment bool
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
cfg *config.ConfigRec
|
cfg *config.ConfigRec
|
||||||
dbMu sync.Mutex
|
dbMu sync.Mutex
|
||||||
cardWellMu sync.RWMutex
|
cardWellMu sync.RWMutex
|
||||||
cardWellStatus string
|
cardWellStatus string
|
||||||
availabilityMu sync.Mutex
|
availabilityMu sync.Mutex
|
||||||
availabilityTimers map[string]*time.Timer
|
availabilityTimers map[string]*time.Timer
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
||||||
@@ -64,6 +66,13 @@ func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus str
|
|||||||
return app
|
return app
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetPaymentCurrency supplies the CMS currency to the selected modern processor.
|
||||||
|
func (app *App) SetPaymentCurrency(currency string) {
|
||||||
|
if app.paymentService != nil {
|
||||||
|
app.paymentService.SetCurrency(currency)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (app *App) SetPaymentService(service *paymentsvc.Service) {
|
func (app *App) SetPaymentService(service *paymentsvc.Service) {
|
||||||
app.paymentService = service
|
app.paymentService = service
|
||||||
}
|
}
|
||||||
@@ -78,10 +87,14 @@ func (app *App) RegisterRoutes(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("/ping-pdq", app.fetchChipDNAStatus)
|
mux.HandleFunc("/ping-pdq", app.fetchChipDNAStatus)
|
||||||
mux.HandleFunc("/logerror", app.onChipDNAError)
|
mux.HandleFunc("/logerror", app.onChipDNAError)
|
||||||
mux.HandleFunc("/api/payment/sale", app.salePayment)
|
mux.HandleFunc("/api/payment/sale", app.salePayment)
|
||||||
mux.HandleFunc("/api/payment/preauth", app.streamCreditCallPreauth)
|
mux.HandleFunc("/api/payment/preauth", app.preauthPayment)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if app.trustSelected {
|
||||||
|
http.Error(w, "Trust uses /api/payment/preauth", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
const op = logging.Op("takePreauthorization")
|
const op = logging.Op("takePreauthorization")
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -162,6 +175,10 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if app.trustSelected {
|
||||||
|
http.Error(w, "Trust uses /api/payment/sale", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
const op = logging.Op("takePayment")
|
const op = logging.Op("takePayment")
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -249,16 +266,8 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
theResponse cmstypes.StatusRec
|
theResponse cmstypes.StatusRec
|
||||||
)
|
)
|
||||||
|
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
if r.Method == http.MethodOptions {
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("issueDoorCard called")
|
log.Println("issueDoorCard called")
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||||
@@ -294,8 +303,8 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
release := app.disp.BeginForeground()
|
release := app.disp.BeginForeground()
|
||||||
defer release()
|
defer release()
|
||||||
|
|
||||||
status, err := app.disp.PrepareCurrentCard(r.Context())
|
preparation, err := app.disp.PrepareCurrentCardForEncoding(r.Context())
|
||||||
app.SetCardWellStatus(status)
|
app.SetCardWellStatus(preparation.Stock)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||||
if errors.Is(err, dispenser.ErrCardWellEmpty) {
|
if errors.Is(err, dispenser.ErrCardWellEmpty) {
|
||||||
@@ -312,13 +321,37 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// doorReq.RoomField = "104"
|
// doorReq.RoomField = "104"
|
||||||
// build lock server command
|
// build lock server command
|
||||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
if err := app.lockserver.BuildCommand(doorReq, checkIn, checkOut); err != nil {
|
||||||
|
logging.Error(types.ServiceName, err.Error(), "Build key command", string(op), "", "", 0)
|
||||||
|
errorhandlers.WriteError(w, http.StatusBadGateway, "Build key command failed: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Each request performs at most one encoder operation.
|
// Each request performs at most one encoder operation.
|
||||||
encodingStarted := time.Now()
|
encodingStarted := time.Now()
|
||||||
log.Info("LockSequence started")
|
log.Info("LockSequence started")
|
||||||
|
var stopRecovery context.CancelCauseFunc
|
||||||
|
var recoveryDone chan struct{}
|
||||||
|
if preparation.UncertainHandoff {
|
||||||
|
log.Infof("uncertain handoff; concurrent K720 recovery enabled; shakes=%d", preparation.ShakesUsed)
|
||||||
|
var recoveryCtx context.Context
|
||||||
|
recoveryCtx, stopRecovery = context.WithCancelCause(r.Context())
|
||||||
|
recoveryDone = make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(recoveryDone)
|
||||||
|
if err := app.disp.RecoverCurrentCard(recoveryCtx, preparation); err != nil && recoveryCtx.Err() == nil {
|
||||||
|
log.WithError(err).Warn("K720 recovery failed; awaiting original LockSequence result")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
encodingErr := app.lockserver.LockSequence()
|
encodingErr := app.lockserver.LockSequence()
|
||||||
|
if stopRecovery != nil {
|
||||||
|
stopRecovery(errors.New("LockSequence completed"))
|
||||||
|
}
|
||||||
log.Infof("LockSequence finished; success=%t duration=%s", encodingErr == nil, time.Since(encodingStarted))
|
log.Infof("LockSequence finished; success=%t duration=%s", encodingErr == nil, time.Since(encodingStarted))
|
||||||
|
if recoveryDone != nil {
|
||||||
|
<-recoveryDone
|
||||||
|
}
|
||||||
if encodingErr != nil {
|
if encodingErr != nil {
|
||||||
logging.Error(types.ServiceName, encodingErr.Error(), "Key encoding", string(op), "", "", 0)
|
logging.Error(types.ServiceName, encodingErr.Error(), "Key encoding", string(op), "", "", 0)
|
||||||
}
|
}
|
||||||
@@ -352,15 +385,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
||||||
const op = logging.Op("printRoomTicket")
|
const op = logging.Op("printRoomTicket")
|
||||||
var roomDetails printer.RoomDetailsRec
|
var roomDetails printer.RoomDetailsRec
|
||||||
// Allow CORS preflight if needed
|
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
||||||
|
|
||||||
if r.Method == http.MethodOptions {
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Println("printRoomTicket called")
|
log.Println("printRoomTicket called")
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||||
@@ -402,6 +427,12 @@ func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) reportDispenserStatus(w http.ResponseWriter, r *http.Request) {
|
func (app *App) reportDispenserStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
w.Header().Set("Allow", http.MethodGet)
|
||||||
|
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use GET")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
_ = json.NewEncoder(w).Encode(cmstypes.StatusRec{
|
_ = json.NewEncoder(w).Encode(cmstypes.StatusRec{
|
||||||
|
|||||||
@@ -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"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"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/mail"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestModernRoutesRejectNonPOSTWithoutDispatch(t *testing.T) {
|
||||||
|
var payments atomic.Int32
|
||||||
|
d := &fakeDoorCardDispenser{}
|
||||||
|
lock := &fakeDoorCardLockServer{}
|
||||||
|
provider := paymentProviderFunc(func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
payments.Add(1)
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock, isPayment: true, paymentService: paymentsvc.NewService(provider)}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
for _, path := range []string{"/issuedoorcard", "/printroomticket", "/api/payment/sale", "/api/payment/preauth"} {
|
||||||
|
for _, method := range []string{http.MethodGet, http.MethodOptions, http.MethodPut} {
|
||||||
|
t.Run(method+path, func(t *testing.T) {
|
||||||
|
r := httptest.NewRequest(method, path, nil)
|
||||||
|
r.Header.Set("Origin", "http://retired-browser.invalid")
|
||||||
|
r.Header.Set("Access-Control-Request-Method", http.MethodPost)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
if w.Code != http.StatusMethodNotAllowed {
|
||||||
|
t.Errorf("%s %s status = %d, want 405", method, path, w.Code)
|
||||||
|
}
|
||||||
|
for key := range w.Header() {
|
||||||
|
if strings.HasPrefix(key, "Access-Control-") {
|
||||||
|
t.Errorf("%s %s header %s = %q, want no browser CORS", method, path, key, w.Header().Get(key))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(path, "/api/payment/") {
|
||||||
|
frames := decodePaymentStream(t, w.Body)
|
||||||
|
if len(frames) != 1 || frames[0].Result == nil || frames[0].Result.HTTPStatus != 405 || frames[0].Result.Reason != "invalid_request" {
|
||||||
|
t.Errorf("%s %s frames = %+v, want one structured method rejection", method, path, frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if payments.Load() != 0 || len(d.calls) != 0 || lock.sequenceCalls != 0 {
|
||||||
|
t.Errorf("Rejected requests dispatched payments=%d dispenser=%v encoder=%d, want none", payments.Load(), d.calls, lock.sequenceCalls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOperationalDiagnosticIssuanceRetainsEncodedCard(t *testing.T) {
|
||||||
|
d := &fakeDoorCardDispenser{}
|
||||||
|
lock := &fakeDoorCardLockServer{}
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/testissuedoorcard", strings.NewReader(`{"roomField":"SYNTH-101"}`))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
if w.Code != http.StatusOK || lock.buildCalls != 1 || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current"}) {
|
||||||
|
t.Errorf("Diagnostic issuance status=%d build=%d encode=%d dispenser=%v, want 200, one build/encode and preparation only", w.Code, lock.buildCalls, lock.sequenceCalls, d.calls)
|
||||||
|
}
|
||||||
|
if d.activity != 0 || d.outsideActivity {
|
||||||
|
t.Errorf("Diagnostic issuance activity=%d outside=%t, want released foreground ownership", d.activity, d.outsideActivity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModernPOSTValidationHasNoBrowserCORS(t *testing.T) {
|
||||||
|
var dispatched bool
|
||||||
|
provider := paymentProviderFunc(func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
dispatched = true
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, isPayment: true, paymentService: paymentsvc.NewService(provider)}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
for _, path := range []string{"/issuedoorcard", "/printroomticket", "/api/payment/sale", "/api/payment/preauth"} {
|
||||||
|
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader("{"))
|
||||||
|
r.Header.Set("Origin", "http://retired-browser.invalid")
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
if path == "/printroomticket" {
|
||||||
|
r.Header.Set("Content-Type", "application/xml")
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
if w.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("POST %s with malformed payload = %d, want unchanged 400 validation", path, w.Code)
|
||||||
|
}
|
||||||
|
for key := range w.Header() {
|
||||||
|
if strings.HasPrefix(key, "Access-Control-") {
|
||||||
|
t.Errorf("POST %s header %s = %q, want no browser CORS", path, key, w.Header().Get(key))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dispatched {
|
||||||
|
t.Error("Malformed modern POST dispatched a payment, want validation before dispatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModernIssueDoorCardRouteStillDelivers(t *testing.T) {
|
||||||
|
d := &fakeDoorCardDispenser{}
|
||||||
|
lock := &fakeDoorCardLockServer{}
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/issuedoorcard", strings.NewReader(`{"roomField":"SYNTH-101","checkinTime":"2026-11-04 15:00:00 +0000","checkoutTime":"2026-11-05 11:00:00 +0000","followStr":"0"}`))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
if w.Code != http.StatusOK || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current", "deliver current", "begin prepare next"}) {
|
||||||
|
t.Errorf("Normal issuance status=%d encode=%d dispenser=%v, want 200, one encoding, delivery and next preparation", w.Code, lock.sequenceCalls, d.calls)
|
||||||
|
}
|
||||||
|
if got := w.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||||
|
t.Errorf("Normal issuance CORS = %q, want absent", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOperationalDiagnosticsUseGET(t *testing.T) {
|
||||||
|
previous := http.DefaultTransport
|
||||||
|
var sidecarCalls int
|
||||||
|
http.DefaultTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
if r.Method != http.MethodPost || r.URL.Path != "/chipdna-status/" {
|
||||||
|
return nil, fmt.Errorf("unexpected synthetic sidecar request: %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
sidecarCalls++
|
||||||
|
deviceXML := `<ArrayOfPaymentDeviceStatus><PaymentDeviceStatus><ConfiguredDeviceId>SYNTH-PED</ConfiguredDeviceId><IsAvailable>true</IsAvailable></PaymentDeviceStatus></ArrayOfPaymentDeviceStatus>`
|
||||||
|
body, err := xml.Marshal(creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{{Key: creditcall.KeyPaymentDeviceStatus, Value: deviceXML}}})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(body))), Header: make(http.Header)}, nil
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { http.DefaultTransport = previous })
|
||||||
|
app := &App{cfg: &config.ConfigRec{Hotel: "SYNTH", Kiosk: 9}, cardWellStatus: "Card present"}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
for _, path := range []string{"/dispenserstatus", "/ping-pdq"} {
|
||||||
|
for _, method := range []string{http.MethodPost, http.MethodOptions, http.MethodDelete} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, httptest.NewRequest(method, path, nil))
|
||||||
|
if w.Code != 405 || w.Header().Get("Allow") != http.MethodGet {
|
||||||
|
t.Errorf("%s %s status=%d Allow=%q, want 405 and GET", method, path, w.Code, w.Header().Get("Allow"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
|
||||||
|
var status cmstypes.StatusRec
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &status); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w.Code != 200 || status.Code != 200 || (path == "/dispenserstatus" && status.Message != "Card present") || (path == "/ping-pdq" && !strings.Contains(status.Message, "SYNTH-PED")) {
|
||||||
|
t.Errorf("GET %s = %d %+v, want unchanged diagnostic response", path, w.Code, status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sidecarCalls != 1 {
|
||||||
|
t.Errorf("Diagnostic sidecar calls = %d, want one for GET only", sidecarCalls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChipDNAErrorRoutePreservesXMLNotificationsAndDebounce(t *testing.T) {
|
||||||
|
previousTransport, previousClient, previousRecipients := http.DefaultTransport, http.DefaultClient, mail.SendErrorEmails
|
||||||
|
var notifications int
|
||||||
|
http.DefaultTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
if r.URL.Host != "api.mailjet.com" || r.Method != http.MethodPost {
|
||||||
|
return nil, fmt.Errorf("unexpected synthetic notification transport")
|
||||||
|
}
|
||||||
|
notifications++
|
||||||
|
body, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(body), "SYNTH-DEVICE-ERROR") || !strings.Contains(string(body), "SYNTH-HOTEL") {
|
||||||
|
t.Error("ChipDNA notification lacks synthetic hotel/error context")
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"Messages":[{"Status":"success"}]}`)), Header: make(http.Header)}, nil
|
||||||
|
})
|
||||||
|
http.DefaultClient = &http.Client{Transport: http.DefaultTransport}
|
||||||
|
mail.SendErrorEmails = []string{"operator@example.test"}
|
||||||
|
app := &App{cfg: &config.ConfigRec{Hotel: "SYNTH-HOTEL", Kiosk: 9}, availabilityTimers: make(map[string]*time.Timer)}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
app.availabilityMu.Lock()
|
||||||
|
for _, timer := range app.availabilityTimers {
|
||||||
|
timer.Stop()
|
||||||
|
}
|
||||||
|
app.availabilityMu.Unlock()
|
||||||
|
http.DefaultTransport, http.DefaultClient, mail.SendErrorEmails = previousTransport, previousClient, previousRecipients
|
||||||
|
})
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
post := func(key, value string) {
|
||||||
|
t.Helper()
|
||||||
|
body, err := xml.Marshal(creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{{Key: key, Value: value}}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/logerror", strings.NewReader(string(body)))
|
||||||
|
r.Header.Set("Content-Type", "application/xml")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
if w.Code != 200 || w.Body.String() != `{"status":"received"}` {
|
||||||
|
t.Errorf("POST /logerror(%s) = %d %s, want unchanged acknowledgement", key, w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
post(creditcall.KeyErrors, "SYNTH-DEVICE-ERROR")
|
||||||
|
post(creditcall.KeyIsAvailable, "false")
|
||||||
|
key := app.availabilityKey()
|
||||||
|
first := app.availabilityTimers[key]
|
||||||
|
post(creditcall.KeyIsAvailable, "false")
|
||||||
|
if first == nil || len(app.availabilityTimers) != 1 || app.availabilityTimers[key] != first {
|
||||||
|
t.Errorf("Repeated unavailable notifications timers=%d, want same single debounce timer", len(app.availabilityTimers))
|
||||||
|
}
|
||||||
|
post(creditcall.KeyIsAvailable, "true")
|
||||||
|
if len(app.availabilityTimers) != 0 || notifications != 1 {
|
||||||
|
t.Errorf("Restored availability timers=%d notifications=%d, want zero timers and one error notification", len(app.availabilityTimers), notifications)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type offlineDefaultTransport struct{}
|
||||||
|
|
||||||
|
func (offlineDefaultTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
||||||
|
return nil, errors.New("offline handler tests prohibit default network access")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
// Fixtures supply in-memory transports or httptest server-specific clients.
|
||||||
|
// In particular, error-notification code cannot reach a live email service.
|
||||||
|
http.DefaultTransport = offlineDefaultTransport{}
|
||||||
|
http.DefaultClient = &http.Client{Transport: http.DefaultTransport}
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
@@ -2,339 +2,191 @@ package handlers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
|
||||||
"gitea.futuresens.co.uk/futuresens/logging"
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
type SalePaymentRequest struct {
|
|
||||||
Reference string `json:"reference,omitempty"`
|
|
||||||
ConfirmNo string `json:"confirmNo,omitempty"`
|
|
||||||
Amount int64 `json:"amount"`
|
|
||||||
Currency string `json:"currency,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type paymentStreamMessage struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
Code string `json:"code,omitempty"`
|
|
||||||
Response *cmstypes.ResponseRec `json:"response,omitempty"`
|
|
||||||
Result *creditCallStreamResult `json:"result,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
||||||
const op = logging.Op("salePayment")
|
log.Printf("salePayment called")
|
||||||
|
app.streamPayment(w, r, false)
|
||||||
if app.creditCallStreamEnabled {
|
}
|
||||||
app.streamCreditCallSale(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
response := cmstypes.ResponseRec{
|
|
||||||
Status: cmstypes.StatusRec{
|
|
||||||
Code: http.StatusInternalServerError,
|
|
||||||
Message: http.StatusText(http.StatusInternalServerError),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
setPaymentCORS(w)
|
|
||||||
|
|
||||||
if r.Method == http.MethodOptions {
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "Method not allowed; use POST")
|
|
||||||
writeTransactionResult(w, http.StatusMethodNotAllowed, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if app.paymentService == nil {
|
|
||||||
mail.SendEmailOnError(
|
|
||||||
app.cfg.Hotel,
|
|
||||||
app.cfg.Kiosk,
|
|
||||||
"Payment Service Not Configured",
|
|
||||||
"Payment service is not configured; cannot process payment requests",
|
|
||||||
)
|
|
||||||
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "Payment service is not configured")
|
|
||||||
writeTransactionResult(w, http.StatusInternalServerError, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "Content-Type must be application/json")
|
|
||||||
writeTransactionResult(w, http.StatusUnsupportedMediaType, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
defer r.Body.Close()
|
|
||||||
|
|
||||||
var req SalePaymentRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
logging.Error(
|
|
||||||
types.ServiceName,
|
|
||||||
err.Error(),
|
|
||||||
"ReadJSON",
|
|
||||||
string(op),
|
|
||||||
"",
|
|
||||||
app.cfg.Hotel,
|
|
||||||
app.cfg.Kiosk,
|
|
||||||
)
|
|
||||||
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "invalid JSON payload: "+err.Error())
|
|
||||||
writeTransactionResult(w, http.StatusBadRequest, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Amount <= 0 {
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, "Amount must be greater than zero")
|
|
||||||
writeTransactionResult(w, http.StatusBadRequest, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Currency == "" {
|
|
||||||
req.Currency = "GBP"
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Reference == "" {
|
|
||||||
req.Reference = req.ConfirmNo
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Reference == "" {
|
|
||||||
req.Reference = uuid.NewString()
|
|
||||||
}
|
|
||||||
|
|
||||||
requestID := buildPaymentRequestID(req.Reference)
|
|
||||||
|
|
||||||
timeoutSeconds := app.cfg.TimeoutSeconds
|
|
||||||
if timeoutSeconds <= 0 {
|
|
||||||
timeoutSeconds = 300
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(
|
|
||||||
r.Context(),
|
|
||||||
time.Duration(timeoutSeconds)*time.Second,
|
|
||||||
)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
flusher, ok := w.(http.Flusher)
|
|
||||||
if !ok {
|
|
||||||
response.Data = buildPaymentFailureURL(
|
|
||||||
types.ResultError,
|
|
||||||
"Streaming payment updates are not supported",
|
|
||||||
)
|
|
||||||
writeTransactionResult(w, http.StatusInternalServerError, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
|
func (app *App) streamPayment(w http.ResponseWriter, r *http.Request, preauth bool) {
|
||||||
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
||||||
w.Header().Set("Cache-Control", "no-cache")
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
controller := http.NewResponseController(w)
|
||||||
encoder := json.NewEncoder(w)
|
encoder := json.NewEncoder(w)
|
||||||
|
deliveryFailed := false
|
||||||
var streamMu sync.Mutex
|
deliveryFailure := ""
|
||||||
streamStarted := false
|
send := func(frame paymentapi.Frame) bool {
|
||||||
streamFailed := false
|
if deliveryFailed {
|
||||||
|
return false
|
||||||
sendStreamMessage := func(message paymentStreamMessage) {
|
|
||||||
streamMu.Lock()
|
|
||||||
defer streamMu.Unlock()
|
|
||||||
|
|
||||||
if streamFailed {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
if r.Context().Err() != nil {
|
||||||
if err := encoder.Encode(message); err != nil {
|
deliveryFailure = "client_disconnected"
|
||||||
streamFailed = true
|
return false
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
if err := controller.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil && !errors.Is(err, http.ErrNotSupported) {
|
||||||
streamStarted = true
|
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
||||||
flusher.Flush()
|
return false
|
||||||
|
}
|
||||||
|
if err := encoder.Encode(frame); err != nil {
|
||||||
|
deliveryFailed = true
|
||||||
|
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if err := controller.Flush(); err != nil {
|
||||||
|
deliveryFailed = true
|
||||||
|
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
reject := func(code int, reason, message string) {
|
||||||
onStatus := func(update paymentsvc.StatusUpdate) {
|
w.WriteHeader(code)
|
||||||
if update.Code == "" {
|
result := paymentapi.Result{Outcome: "error", HTTPStatus: code, Reason: reason, Message: message}
|
||||||
return
|
send(paymentapi.Frame{Type: "result", Result: &result})
|
||||||
}
|
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "status",
|
|
||||||
Code: update.Code,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
result, err := app.paymentService.Sale(
|
reject(http.StatusMethodNotAllowed, "invalid_request", "Use POST")
|
||||||
ctx,
|
|
||||||
paymentsvc.SaleRequest{
|
|
||||||
RequestID: requestID,
|
|
||||||
Reference: req.Reference,
|
|
||||||
Amount: req.Amount,
|
|
||||||
Currency: req.Currency,
|
|
||||||
},
|
|
||||||
onStatus,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
status := http.StatusBadGateway
|
|
||||||
if errors.Is(err, paymentsvc.ErrPaymentInProgress) {
|
|
||||||
status = http.StatusConflict
|
|
||||||
}
|
|
||||||
|
|
||||||
logging.Error(
|
|
||||||
types.ServiceName,
|
|
||||||
err.Error(),
|
|
||||||
"Payment provider error",
|
|
||||||
string(op),
|
|
||||||
req.Reference,
|
|
||||||
app.cfg.Hotel,
|
|
||||||
app.cfg.Kiosk,
|
|
||||||
)
|
|
||||||
|
|
||||||
response.Status.Code = status
|
|
||||||
response.Status.Message = http.StatusText(status)
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, err.Error())
|
|
||||||
|
|
||||||
if !streamStarted {
|
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
||||||
writeTransactionResult(w, status, response)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !app.isPayment || app.paymentService == nil {
|
||||||
if result == nil {
|
reject(http.StatusServiceUnavailable, "terminal_unavailable", "Payment service is unavailable")
|
||||||
response.Status.Code = http.StatusBadGateway
|
return
|
||||||
response.Status.Message = "Empty payment result"
|
}
|
||||||
response.Data = buildPaymentFailureURL(
|
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
||||||
types.ResultError,
|
reject(http.StatusUnsupportedMediaType, "invalid_request", "Use application/json")
|
||||||
"Payment provider returned an empty result",
|
return
|
||||||
)
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
if !streamStarted {
|
var input paymentapi.Request
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&input) != nil {
|
||||||
writeTransactionResult(w, http.StatusBadGateway, response)
|
reject(http.StatusBadRequest, "invalid_request", "Invalid JSON payload")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if input.Amount < 0 || (!preauth && input.Amount == 0) {
|
||||||
|
reject(http.StatusBadRequest, "invalid_request", "Invalid payment amount")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if input.RequiredPreauth != nil && input.RequiredPreauth.Amount < 0 {
|
||||||
|
reject(http.StatusBadRequest, "invalid_request", "Invalid required preauthorisation amount")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, ok := w.(http.Flusher); !ok {
|
||||||
|
reject(http.StatusInternalServerError, "stream_unavailable", "Streaming payment updates are unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Context().Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if input.Reference == "" {
|
||||||
|
input.Reference = uuid.NewString()
|
||||||
|
}
|
||||||
|
req := paymentsvc.SaleRequest{RequestID: buildPaymentRequestID(input.Reference), Reference: input.Reference, Amount: input.Amount, Currency: input.Currency, CheckoutDate: input.CheckoutDate, RequiredPreauth: input.RequiredPreauth}
|
||||||
|
operation := paymentapi.Sale
|
||||||
|
if preauth {
|
||||||
|
operation = paymentapi.Preauth
|
||||||
|
}
|
||||||
|
reconciliationFields := func(final paymentapi.Result) log.Fields {
|
||||||
|
return log.Fields{
|
||||||
|
"hotel": app.cfg.Hotel, "kiosk": app.cfg.Kiosk, "operation": operation,
|
||||||
|
"request_id": req.RequestID, "request_reference": req.Reference,
|
||||||
|
"provider": final.Provider, "transaction_reference": final.TransactionReference,
|
||||||
|
"outcome": final.Outcome, "reason": final.Reason,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
progress := make(chan string, 128)
|
||||||
|
finished := make(chan paymentapi.Result, 1)
|
||||||
|
go func() {
|
||||||
|
// Financial dispatch owns its lifetime; HTTP disconnect only ends observation.
|
||||||
|
timeout := app.cfg.TimeoutSeconds
|
||||||
|
if timeout <= 0 {
|
||||||
|
timeout = 300
|
||||||
|
}
|
||||||
|
timeout += 15 // Delivery/status margin; provider financial calls retain their own bounds.
|
||||||
|
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), time.Duration(timeout)*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
status := func(update paymentsvc.StatusUpdate) {
|
||||||
|
if update.Code != "" {
|
||||||
|
select {
|
||||||
|
case progress <- update.Code:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var result *paymentsvc.Result
|
||||||
|
var err error
|
||||||
|
if preauth {
|
||||||
|
result, err = app.paymentService.Preauth(ctx, req, status)
|
||||||
|
} else {
|
||||||
|
result, err = app.paymentService.Sale(ctx, req, status)
|
||||||
|
}
|
||||||
|
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Message: "Payment outcome uncertain; contact reception"}
|
||||||
|
if result != nil {
|
||||||
|
final = result.Terminal
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, paymentsvc.ErrPaymentInProgress):
|
||||||
|
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusConflict, Reason: "payment_in_progress", Message: "Payment is already in progress"}
|
||||||
|
case errors.Is(err, paymentsvc.ErrPreauthUnsupported):
|
||||||
|
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusUnprocessableEntity, Reason: "unsupported_operation", Message: "Preauthorisation is unavailable; contact reception"}
|
||||||
|
case errors.Is(err, paymentsvc.ErrProviderNotConfigured):
|
||||||
|
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusServiceUnavailable, Reason: "terminal_unavailable", Message: "Payment service is unavailable"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if final.Outcome == "" {
|
||||||
|
final = paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Message: "Payment outcome uncertain; contact reception"}
|
||||||
|
}
|
||||||
|
if final.Outcome == "unknown" {
|
||||||
|
log.WithFields(reconciliationFields(final)).WithField("transport_error", err != nil).
|
||||||
|
Warn("Payment outcome requires reception reconciliation")
|
||||||
|
}
|
||||||
|
close(progress)
|
||||||
|
finished <- final
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case code, ok := <-progress:
|
||||||
|
if !ok {
|
||||||
|
progress = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
send(paymentapi.Frame{Type: "status", Code: code})
|
||||||
|
case final := <-finished:
|
||||||
|
if progress != nil {
|
||||||
|
for code := range progress {
|
||||||
|
send(paymentapi.Frame{Type: "status", Code: code})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !send(paymentapi.Frame{Type: "result", Result: &final}) {
|
||||||
|
log.WithFields(reconciliationFields(final)).WithField("error_category", deliveryFailure).
|
||||||
|
Warn("Payment final result delivery failed; reception reconciliation required")
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
response.Status.Code = http.StatusOK
|
|
||||||
|
|
||||||
if result.Success && strings.EqualFold(result.Status, "APPROVED") {
|
|
||||||
printer.PrintSaleReceipt(result.CustomerReceipt)
|
|
||||||
|
|
||||||
response.Status.Message = result.Message
|
|
||||||
response.Data = buildPaymentSuccessURL(result)
|
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
description := result.ErrorMessage
|
|
||||||
if description == "" {
|
|
||||||
description = result.Message
|
|
||||||
}
|
|
||||||
if description == "" {
|
|
||||||
description = result.Status
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("Transaction failed: %s", description)
|
|
||||||
printer.PrintSaleReceipt(result.CustomerReceipt)
|
|
||||||
|
|
||||||
response.Status.Message = "Payment unsuccessful"
|
|
||||||
response.Data = buildPaymentFailureURL(types.ResultError, description)
|
|
||||||
|
|
||||||
sendStreamMessage(paymentStreamMessage{
|
|
||||||
Type: "result",
|
|
||||||
Response: &response,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildPaymentRequestID(reference string) string {
|
func buildPaymentRequestID(reference string) string {
|
||||||
const prefix = "REQ_"
|
const prefix = "REQ_"
|
||||||
const maxLength = 60
|
const maxLength = 60
|
||||||
|
|
||||||
suffix := fmt.Sprintf("_%d", time.Now().UnixMilli())
|
suffix := fmt.Sprintf("_%d", time.Now().UnixMilli())
|
||||||
maxReferenceLength := maxLength - len(prefix) - len(suffix)
|
maxReferenceLength := maxLength - len(prefix) - len(suffix)
|
||||||
|
|
||||||
runes := []rune(reference)
|
runes := []rune(reference)
|
||||||
if len(runes) > maxReferenceLength {
|
if len(runes) > maxReferenceLength {
|
||||||
runes = runes[:maxReferenceLength]
|
runes = runes[:maxReferenceLength]
|
||||||
}
|
}
|
||||||
|
|
||||||
return prefix + string(runes) + suffix
|
return prefix + string(runes) + suffix
|
||||||
}
|
}
|
||||||
|
|
||||||
func setPaymentCORS(w http.ResponseWriter) {
|
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildPaymentSuccessURL(result *paymentsvc.Result) string {
|
|
||||||
// txnReference := result.ReferenceNumber
|
|
||||||
// if txnReference == "" {
|
|
||||||
// txnReference = result.TransactionID
|
|
||||||
// }
|
|
||||||
|
|
||||||
q := url.Values{}
|
|
||||||
q.Set("CardNumber", hex.EncodeToString([]byte(result.CardNumber)))
|
|
||||||
q.Set("CardType", hex.EncodeToString([]byte(result.CardType)))
|
|
||||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result.ExpiryDate)))
|
|
||||||
q.Set("TxnReference", result.RequestID)
|
|
||||||
q.Set("CardHash", hex.EncodeToString([]byte(result.CardHash)))
|
|
||||||
q.Set("CardReference", hex.EncodeToString([]byte(result.CardReference)))
|
|
||||||
|
|
||||||
return (&url.URL{
|
|
||||||
Path: types.CheckinSuccessfulEndpoint,
|
|
||||||
RawQuery: q.Encode(),
|
|
||||||
}).String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildPaymentFailureURL(msgType, description string) string {
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
types.LogFieldError: msgType,
|
|
||||||
types.LogFieldDescription: description,
|
|
||||||
}).Error("Transaction failed")
|
|
||||||
|
|
||||||
q := url.Values{}
|
|
||||||
q.Set("MsgType", msgType)
|
|
||||||
q.Set("Description", description)
|
|
||||||
|
|
||||||
return (&url.URL{
|
|
||||||
Path: types.CheckinUnsuccessfulEndpoint,
|
|
||||||
RawQuery: q.Encode(),
|
|
||||||
}).String()
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -7,156 +7,88 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
|
||||||
"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/types"
|
"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(
|
type paymentProviderFunc func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error)
|
||||||
context.Context,
|
|
||||||
paymentsvc.SaleRequest,
|
|
||||||
paymentsvc.StatusHandler,
|
|
||||||
) (*paymentsvc.Result, error)
|
|
||||||
|
|
||||||
func (f paymentProviderFunc) Sale(
|
func (f paymentProviderFunc) Sale(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
ctx context.Context,
|
return f(ctx, req, status)
|
||||||
request paymentsvc.SaleRequest,
|
}
|
||||||
onStatus paymentsvc.StatusHandler,
|
func (paymentProviderFunc) ValidatePreauth(paymentsvc.SaleRequest) error {
|
||||||
) (*paymentsvc.Result, error) {
|
return paymentsvc.ErrPreauthUnsupported
|
||||||
return f(ctx, request, onStatus)
|
}
|
||||||
|
func (paymentProviderFunc) Preauth(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
return nil, paymentsvc.ErrPreauthUnsupported
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type paymentStreamMessage = paymentapi.Frame
|
||||||
|
|
||||||
func TestSalePaymentStreamsTerminalUnavailableAsAuthoritativeUnsuccessfulResult(t *testing.T) {
|
func TestSalePaymentStreamsTerminalUnavailableAsAuthoritativeUnsuccessfulResult(t *testing.T) {
|
||||||
provider := paymentProviderFunc(func(
|
provider := paymentProviderFunc(func(_ context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
_ context.Context,
|
status(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
||||||
request paymentsvc.SaleRequest,
|
status(paymentsvc.StatusUpdate{Code: paymentstatus.TerminalUnavailable})
|
||||||
onStatus paymentsvc.StatusHandler,
|
return &paymentsvc.Result{Terminal: paymentapi.Result{Outcome: "error", HTTPStatus: 200, Reason: "terminal_unavailable", Message: "Payment terminal is unavailable"}}, nil
|
||||||
) (*paymentsvc.Result, error) {
|
|
||||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
|
||||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.TerminalUnavailable})
|
|
||||||
return &paymentsvc.Result{
|
|
||||||
RequestID: request.RequestID,
|
|
||||||
Operation: "SALE",
|
|
||||||
Status: "TERMINAL_UNAVAILABLE",
|
|
||||||
ErrorMessage: "Payment terminal is unavailable",
|
|
||||||
Amount: request.Amount,
|
|
||||||
Currency: request.Currency,
|
|
||||||
DeviceUsed: "terminal-1",
|
|
||||||
DeviceType: "Dojo Terminal",
|
|
||||||
}, nil
|
|
||||||
})
|
})
|
||||||
|
|
||||||
recorder := performSalePaymentRequest(t, provider)
|
recorder := performSalePaymentRequest(t, provider)
|
||||||
if recorder.Code != http.StatusOK {
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
t.Fatalf("outer status = %d, want %d", recorder.Code, http.StatusOK)
|
if recorder.Code != 200 || len(frames) != 3 || frames[0].Code != paymentstatus.Starting || frames[1].Code != paymentstatus.TerminalUnavailable || frames[2].Result == nil {
|
||||||
|
t.Fatalf("SalePayment() HTTP/frames=%d/%+v, want 200 and two statuses plus final", recorder.Code, frames)
|
||||||
}
|
}
|
||||||
messages := decodePaymentStream(t, recorder.Body)
|
final := frames[2].Result
|
||||||
if len(messages) != 3 {
|
if final.Outcome != "error" || final.Reason != "terminal_unavailable" || final.Retryable {
|
||||||
t.Fatalf("stream messages = %#v, want two statuses and one result", messages)
|
t.Errorf("SalePayment() final=%+v, want definite nonretryable terminal unavailability", final)
|
||||||
}
|
}
|
||||||
if messages[0].Type != "status" || messages[0].Code != paymentstatus.Starting ||
|
for _, forbidden := range []string{"Dojo returned HTTP 409", "offline or currently in use", "traceId", "docs.dojo.tech", "\"response\""} {
|
||||||
messages[1].Type != "status" || messages[1].Code != paymentstatus.TerminalUnavailable {
|
if strings.Contains(recorder.Body.String(), forbidden) {
|
||||||
t.Fatalf("status frames = %#v", messages[:2])
|
t.Errorf("SalePayment() leaked %q", forbidden)
|
||||||
}
|
|
||||||
final := messages[2]
|
|
||||||
if final.Type != "result" || final.Response == nil {
|
|
||||||
t.Fatalf("final frame = %#v", final)
|
|
||||||
}
|
|
||||||
if final.Response.Status.Code != http.StatusOK {
|
|
||||||
t.Fatalf("nested status = %d, want %d", final.Response.Status.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
resultURL, err := url.Parse(final.Response.Data)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if resultURL.Path != types.CheckinUnsuccessfulEndpoint {
|
|
||||||
t.Fatalf("result path = %q, want %q", resultURL.Path, types.CheckinUnsuccessfulEndpoint)
|
|
||||||
}
|
|
||||||
if got := resultURL.Query().Get("Description"); got != "Payment terminal is unavailable" {
|
|
||||||
t.Fatalf("Description = %q", got)
|
|
||||||
}
|
|
||||||
|
|
||||||
body := recorder.Body.String()
|
|
||||||
for _, forbidden := range []string{
|
|
||||||
"Dojo returned HTTP 409",
|
|
||||||
"offline or currently in use",
|
|
||||||
"traceId",
|
|
||||||
"docs.dojo.tech",
|
|
||||||
} {
|
|
||||||
if strings.Contains(body, forbidden) {
|
|
||||||
t.Fatalf("stream exposed %q: %s", forbidden, body)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSalePaymentRetainsNestedBadGatewayForProviderErrorsAfterStreamingStarts(t *testing.T) {
|
func TestSalePaymentRetainsUncertaintyForProviderErrorsAfterStreamingStarts(t *testing.T) {
|
||||||
provider := paymentProviderFunc(func(
|
provider := paymentProviderFunc(func(_ context.Context, _ paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
_ context.Context,
|
status(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
||||||
_ paymentsvc.SaleRequest,
|
return nil, errors.New("raw secret provider error")
|
||||||
onStatus paymentsvc.StatusHandler,
|
|
||||||
) (*paymentsvc.Result, error) {
|
|
||||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
|
||||||
return nil, errors.New("provider failed")
|
|
||||||
})
|
})
|
||||||
|
|
||||||
recorder := performSalePaymentRequest(t, provider)
|
recorder := performSalePaymentRequest(t, provider)
|
||||||
if recorder.Code != http.StatusOK {
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
t.Fatalf("outer status = %d, want streaming status %d", recorder.Code, http.StatusOK)
|
if len(frames) != 2 || frames[1].Result == nil || frames[1].Result.Outcome != "unknown" || frames[1].Result.Retryable {
|
||||||
|
t.Fatalf("SalePayment() frames=%+v, want progress then nonretryable uncertainty", frames)
|
||||||
}
|
}
|
||||||
messages := decodePaymentStream(t, recorder.Body)
|
if strings.Contains(recorder.Body.String(), "secret") {
|
||||||
if len(messages) != 2 || messages[1].Type != "result" || messages[1].Response == nil {
|
t.Error("SalePayment() exposed raw provider diagnostics")
|
||||||
t.Fatalf("stream messages = %#v", messages)
|
|
||||||
}
|
|
||||||
if messages[1].Response.Status.Code != http.StatusBadGateway {
|
|
||||||
t.Fatalf("nested status = %d, want %d", messages[1].Response.Status.Code, http.StatusBadGateway)
|
|
||||||
}
|
|
||||||
resultURL, err := url.Parse(messages[1].Response.Data)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if resultURL.Path != types.CheckinUnsuccessfulEndpoint {
|
|
||||||
t.Fatalf("result path = %q, want %q", resultURL.Path, types.CheckinUnsuccessfulEndpoint)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func performSalePaymentRequest(t *testing.T, provider paymentsvc.Provider) *httptest.ResponseRecorder {
|
func performSalePaymentRequest(t *testing.T, provider paymentsvc.Provider) *httptest.ResponseRecorder {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
app := &App{
|
app := &App{isPayment: true, paymentService: paymentsvc.NewService(provider), cfg: &config.ConfigRec{TimeoutSeconds: 1}}
|
||||||
paymentService: paymentsvc.NewService(provider),
|
request := httptest.NewRequest(http.MethodPost, paymentapi.SalePath, strings.NewReader(`{"amount":1234,"currency":"GBP","reference":"SYNTH"}`))
|
||||||
cfg: &config.ConfigRec{
|
|
||||||
Hotel: "HOTEL",
|
|
||||||
Kiosk: 7,
|
|
||||||
TimeoutSeconds: 5,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
request := httptest.NewRequest(
|
|
||||||
http.MethodPost,
|
|
||||||
"/api/payment/sale",
|
|
||||||
strings.NewReader(`{"reference":"BOOKING-123","amount":10852,"currency":"GBP"}`),
|
|
||||||
)
|
|
||||||
request.Header.Set("Content-Type", "application/json")
|
request.Header.Set("Content-Type", "application/json")
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
app.salePayment(recorder, request)
|
app.salePayment(recorder, request)
|
||||||
return recorder
|
return recorder
|
||||||
}
|
}
|
||||||
|
func decodePaymentStream(t *testing.T, body io.Reader) []paymentapi.Frame {
|
||||||
func decodePaymentStream(t *testing.T, body io.Reader) []paymentStreamMessage {
|
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
var frames []paymentapi.Frame
|
||||||
decoder := json.NewDecoder(body)
|
decoder := json.NewDecoder(body)
|
||||||
var messages []paymentStreamMessage
|
|
||||||
for {
|
for {
|
||||||
var message paymentStreamMessage
|
var frame paymentapi.Frame
|
||||||
if err := decoder.Decode(&message); err != nil {
|
err := decoder.Decode(&frame)
|
||||||
if errors.Is(err, io.EOF) {
|
if err == io.EOF {
|
||||||
return messages
|
return frames
|
||||||
}
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
}
|
||||||
messages = append(messages, message)
|
if err != nil {
|
||||||
|
t.Fatalf("DecodePaymentStream() error=%v, want valid frames", err)
|
||||||
|
}
|
||||||
|
frames = append(frames, frame)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
)
|
)
|
||||||
@@ -71,7 +71,11 @@ func (app *App) testIssueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// build lock server command
|
// build lock server command
|
||||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
if err := app.lockserver.BuildCommand(doorReq, checkIn, checkOut); err != nil {
|
||||||
|
logging.Error(types.ServiceName, err.Error(), "Build key command", string(op), "", "", 0)
|
||||||
|
errorhandlers.WriteError(w, http.StatusBadGateway, "Build key command failed: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// lock server sequence
|
// lock server sequence
|
||||||
if err := app.lockserver.LockSequence(); err != nil {
|
if err := app.lockserver.LockSequence(); err != nil {
|
||||||
@@ -90,8 +94,14 @@ func (app *App) fetchChipDNAStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
const op = logging.Op("fetchChipDNAStatus")
|
const op = logging.Op("fetchChipDNAStatus")
|
||||||
var theResponse cmstypes.StatusRec
|
var theResponse cmstypes.StatusRec
|
||||||
|
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
w.Header().Set("Allow", http.MethodGet)
|
||||||
|
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use GET")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
status, err := creditcall.ReadPdqStatus(app.cfg.Hotel, app.cfg.Kiosk)
|
status, err := creditcall.ReadPdqStatus(app.cfg.Hotel, app.cfg.Kiosk)
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
type failedDiagnosticWriter struct{ header http.Header }
|
||||||
|
|
||||||
|
func (w *failedDiagnosticWriter) Header() http.Header { return w.header }
|
||||||
|
func (*failedDiagnosticWriter) WriteHeader(int) {}
|
||||||
|
func (*failedDiagnosticWriter) Flush() {}
|
||||||
|
func (*failedDiagnosticWriter) Write([]byte) (int, error) {
|
||||||
|
return 0, errors.New("https://user:WRITE_PRIVATE_MARKER@gateway.invalid/4111111111111111")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustReconciliationLogsPreserveIdentityAndFinancialOutcome(t *testing.T) {
|
||||||
|
for _, preauth := range []bool{false, true} {
|
||||||
|
for _, mode := range []string{"unknown", "unknown-transport", "unknown-write-failure", "approved-client-closed", "approved-write-failure"} {
|
||||||
|
operation := "sale"
|
||||||
|
if preauth {
|
||||||
|
operation = "preauth"
|
||||||
|
}
|
||||||
|
t.Run(operation+"/"+mode, func(t *testing.T) {
|
||||||
|
var output bytes.Buffer
|
||||||
|
logger := log.StandardLogger()
|
||||||
|
oldOutput, oldFormatter := logger.Out, logger.Formatter
|
||||||
|
logger.SetOutput(&output)
|
||||||
|
logger.SetFormatter(&log.JSONFormatter{})
|
||||||
|
t.Cleanup(func() { logger.SetOutput(oldOutput); logger.SetFormatter(oldFormatter) })
|
||||||
|
unknown := strings.HasPrefix(mode, "unknown")
|
||||||
|
financial, lookups, prints := 0, 0, 0
|
||||||
|
var ref string
|
||||||
|
var tokens []string
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
t.Cleanup(cancel)
|
||||||
|
client, err := trustpayments.New(trustpayments.Config{
|
||||||
|
BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "SYNTH-SITE", Password: "PASSWORD_PRIVATE_MARKER", Terminal: "SYNTH-PED", Currency: "GBP", Timezone: "Europe/London",
|
||||||
|
Transport: trustFixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
var input map[string]string
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tokens = append(tokens, r.Header.Get("token"))
|
||||||
|
if strings.HasSuffix(r.URL.Path, "/status") {
|
||||||
|
lookups++
|
||||||
|
if input["refid"] != ref {
|
||||||
|
t.Errorf("Status RefID=%q, want original %q", input["refid"], ref)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
financial++
|
||||||
|
ref = input["refid"]
|
||||||
|
if !strings.HasSuffix(r.URL.Path, "/"+operation) || input["type"] != operation {
|
||||||
|
t.Errorf("Financial request path/type=%s/%s, want %s", r.URL.Path, input["type"], operation)
|
||||||
|
}
|
||||||
|
if mode == "approved-client-closed" {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if mode == "unknown-transport" {
|
||||||
|
return nil, errors.New("https://user:PASSWORD_PRIVATE_MARKER@gateway.invalid/4111111111111111/JWT_PRIVATE_MARKER")
|
||||||
|
}
|
||||||
|
body := map[string]any{"refid": ref, "siteid": "SYNTH-SITE", "terminalserialnumber": "SYNTH-PED", "type": operation, "amount": "25.00", "finalamount": "25.00", "resultcode": "Approved", "authcode": "AUTH_PRIVATE_MARKER", "cardtype": "Visa", "last4": "1133", "receipt": "PAN: 4111111111111111\nRAW_PRIVATE_MARKER"}
|
||||||
|
if unknown {
|
||||||
|
body["errorcode"], body["errormessage"] = 2003, "RAW_PRIVATE_MARKER JWT_PRIVATE_MARKER"
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(encoded)), Header: make(http.Header)}, nil
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := &App{cfg: &config.ConfigRec{Hotel: "SYNTH-HOTEL", Kiosk: 9}, isPayment: true}
|
||||||
|
app.SetPaymentService(paymentsvc.NewService(&trustpayments.Processor{Client: client, PrintReceipt: func(string) { prints++ }}))
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/api/payment/"+operation, strings.NewReader(`{"reference":"SYNTH-BOOK","amount":2500,"currency":"GBP"}`)).WithContext(ctx)
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
var writer http.ResponseWriter = recorder
|
||||||
|
if strings.Contains(mode, "write-failure") {
|
||||||
|
writer = &failedDiagnosticWriter{header: make(http.Header)}
|
||||||
|
}
|
||||||
|
app.streamPayment(writer, request, preauth)
|
||||||
|
wantLookups, wantPrints, wantOutcome := 0, 1, "approved"
|
||||||
|
if unknown {
|
||||||
|
wantLookups, wantPrints, wantOutcome = 1, 0, "unknown"
|
||||||
|
}
|
||||||
|
if financial != 1 || lookups != wantLookups || prints != wantPrints || len(ref) != 32 {
|
||||||
|
t.Fatalf("Trust(%s) financial/status/prints/ref=%d/%d/%d/%q, want 1/%d/%d and original RefID", mode, financial, lookups, prints, ref, wantLookups, wantPrints)
|
||||||
|
}
|
||||||
|
if unknown && !strings.Contains(mode, "write-failure") {
|
||||||
|
frames := decodePaymentStream(t, recorder.Body)
|
||||||
|
if len(frames) == 0 {
|
||||||
|
t.Fatal("Unknown payment stream is empty, want final result")
|
||||||
|
}
|
||||||
|
final := frames[len(frames)-1].Result
|
||||||
|
if final == nil || final.Outcome != wantOutcome || final.Retryable || final.TransactionReference != ref {
|
||||||
|
t.Errorf("Unknown terminal result=%+v, want unchanged nonretryable outcome and RefID %s", final, ref)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var requestID string
|
||||||
|
warnings := 0
|
||||||
|
decoder := json.NewDecoder(strings.NewReader(output.String()))
|
||||||
|
for {
|
||||||
|
var entry map[string]any
|
||||||
|
if err := decoder.Decode(&entry); err == io.EOF {
|
||||||
|
break
|
||||||
|
} else if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if entry["level"] != "warning" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
warnings++
|
||||||
|
id, _ := entry["request_id"].(string)
|
||||||
|
if requestID == "" {
|
||||||
|
requestID = id
|
||||||
|
}
|
||||||
|
if id == "" || id != requestID || entry["request_reference"] != "SYNTH-BOOK" || entry["transaction_reference"] != ref || entry["provider"] != "TrustPayments" || entry["operation"] != operation || entry["outcome"] != wantOutcome {
|
||||||
|
t.Errorf("Reconciliation warning=%v, want same request ID, Trust RefID, provider, operation and financial outcome", entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wantWarnings := 0
|
||||||
|
if unknown {
|
||||||
|
wantWarnings = 2
|
||||||
|
}
|
||||||
|
if strings.Contains(mode, "write-failure") || mode == "approved-client-closed" {
|
||||||
|
wantWarnings++
|
||||||
|
}
|
||||||
|
if warnings != wantWarnings {
|
||||||
|
t.Errorf("Trust(%s) reconciliation warnings=%d, want %d", mode, warnings, wantWarnings)
|
||||||
|
}
|
||||||
|
for _, secret := range append(tokens, "PASSWORD_PRIVATE_MARKER", "AUTH_PRIVATE_MARKER", "RAW_PRIVATE_MARKER", "JWT_PRIVATE_MARKER", "WRITE_PRIVATE_MARKER", "4111111111111111") {
|
||||||
|
if secret != "" && strings.Contains(output.String(), secret) {
|
||||||
|
t.Errorf("Trust(%s) diagnostics contain private fixture data", mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SetTrustPayments selects Trust while preserving the deprecated endpoint guard.
|
||||||
|
func (app *App) SetTrustPayments(client *trustpayments.Client) {
|
||||||
|
app.trustSelected = true
|
||||||
|
app.paymentService = paymentsvc.NewService(&trustpayments.Processor{Client: client})
|
||||||
|
}
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments"
|
||||||
|
)
|
||||||
|
|
||||||
|
type trustFixtureTransport func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f trustFixtureTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
|
||||||
|
func fixtureTrustApp(t *testing.T, dir string) *trustFixtureApp {
|
||||||
|
t.Helper()
|
||||||
|
client, err := trustpayments.New(trustpayments.Config{BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "fixture-site", Password: "synthetic", Terminal: "fixture-ped", Currency: "GBP", Timezone: "Europe/London", Transport: trustFixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
var input map[string]string
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(r.URL.Path, "/status") {
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"errorcode":2003}`))}, nil
|
||||||
|
}
|
||||||
|
f, err := os.OpenFile(filepath.Join(dir, "starts"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, err = f.WriteString(input["refid"] + "\n")
|
||||||
|
closeErr := f.Close()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return nil, closeErr
|
||||||
|
}
|
||||||
|
outcome, auth := "Approved", "123456"
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "decline-preauth")); err == nil && input["type"] == "preauth" {
|
||||||
|
outcome, auth = "Declined", ""
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "uncertain")); err == nil {
|
||||||
|
outcome, auth = "Pending", ""
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(map[string]string{"refid": input["refid"], "siteid": "fixture-site", "terminalserialnumber": "fixture-ped", "type": input["type"], "amount": input["amount"], "finalamount": input["amount"], "resultcode": outcome, "authcode": auth, "cardtype": "Visa", "last4": "1133", "receipt": "Receipt: 31\nSequence number: 42\nPAN: 4111111111111111"})
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(body))}, nil
|
||||||
|
})})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := &trustFixtureApp{App: &App{isPayment: true, cfg: &config.ConfigRec{Hotel: "SYNTH-HOTEL", Kiosk: 9}}, trustReceipt: func(string) {}}
|
||||||
|
app.SetTrustPayments(client)
|
||||||
|
app.SetPaymentService(paymentsvc.NewService(&trustpayments.Processor{Client: client, PrintReceipt: func(s string) { app.trustReceipt(s) }}))
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
// This opt-in subprocess only uses an in-memory gateway and synthetic receipts.
|
||||||
|
func TestTrustFixtureProcess(t *testing.T) {
|
||||||
|
dir := os.Getenv("TRUST_FIXTURE_DIR")
|
||||||
|
if dir == "" {
|
||||||
|
t.Skip("offline subprocess helper")
|
||||||
|
}
|
||||||
|
app := fixtureTrustApp(t, dir)
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
server := httptest.NewServer(mux)
|
||||||
|
defer server.Close()
|
||||||
|
b, _ := json.Marshal(map[string]string{"url": server.URL})
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "ready.json"), b, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "stop")); err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func trustStreamRequest(preauth bool) *http.Request {
|
||||||
|
path, body := "/api/payment/sale", `{"reference":"SYNTH-BOOK","amount":2500,"currency":"GBP"}`
|
||||||
|
if preauth {
|
||||||
|
path, body = "/api/payment/preauth", `{"amount":2500,"currency":"GBP","transactionType":"Sale","checkoutDate":"synthetic"}`
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustExistingEndpointsAndSafeFrames(t *testing.T) {
|
||||||
|
for _, preauth := range []bool{false, true} {
|
||||||
|
t.Run(map[bool]string{false: "sale", true: "preauth"}[preauth], func(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
app := fixtureTrustApp(t, dir)
|
||||||
|
prints := 0
|
||||||
|
app.trustReceipt = func(s string) {
|
||||||
|
prints++
|
||||||
|
if strings.Contains(s, "4111111111111111") || !strings.Contains(s, "************1133") {
|
||||||
|
t.Error("unsafe or missing masked receipt")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, trustStreamRequest(preauth))
|
||||||
|
decoder := json.NewDecoder(w.Body)
|
||||||
|
statuses, results := 0, 0
|
||||||
|
for {
|
||||||
|
var frame paymentStreamMessage
|
||||||
|
if err := decoder.Decode(&frame); err == io.EOF {
|
||||||
|
break
|
||||||
|
} else if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if frame.Type == "status" {
|
||||||
|
statuses++
|
||||||
|
if strings.Contains(frame.Code, "PIN") || strings.Contains(frame.Code, "INSERT") {
|
||||||
|
t.Error("invented terminal prompt")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if frame.Result != nil {
|
||||||
|
results++
|
||||||
|
if frame.Result.Outcome != "approved" || frame.Result.AmountMinor != 2500 || frame.Result.CurrencyCode != "GBP" || frame.Result.ReceiptNumber != "31" || frame.Result.SequenceNumber != "42" {
|
||||||
|
t.Errorf("approved result=%+v", frame.Result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if w.Code != 200 || statuses != 3 || results != 1 || prints != 1 {
|
||||||
|
t.Errorf("HTTP/statuses/results/prints=%d/%d/%d/%d", w.Code, statuses, results, prints)
|
||||||
|
}
|
||||||
|
starts, _ := os.ReadFile(filepath.Join(dir, "starts"))
|
||||||
|
if strings.Count(string(starts), "\n") != 1 {
|
||||||
|
t.Errorf("financial starts=%q", starts)
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), "4111111111111111") || strings.Contains(w.Body.String(), "synthetic") {
|
||||||
|
t.Error("private provider data escaped")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustUnknownNeverDeclinesOrReposts(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "uncertain"), nil, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := fixtureTrustApp(t, dir)
|
||||||
|
app.trustReceipt = func(string) { t.Error("uncertain payment printed approval") }
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
app.streamTrustPayment(w, trustStreamRequest(false), false)
|
||||||
|
if !strings.Contains(w.Body.String(), `"outcome":"unknown"`) || strings.Contains(w.Body.String(), `"outcome":"declined"`) {
|
||||||
|
t.Errorf("uncertain stream=%s", w.Body.String())
|
||||||
|
}
|
||||||
|
starts, _ := os.ReadFile(filepath.Join(dir, "starts"))
|
||||||
|
if strings.Count(string(starts), "\n") != 1 {
|
||||||
|
t.Errorf("financial starts=%q", starts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustInvalidRequestsAndNoOperationAPI(t *testing.T) {
|
||||||
|
app := fixtureTrustApp(t, t.TempDir())
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
app.RegisterRoutes(mux)
|
||||||
|
for _, body := range []string{`{"amount":0,"currency":"GBP"}`, `{`} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r := httptest.NewRequest("POST", "/api/payment/sale", strings.NewReader(body))
|
||||||
|
mux.ServeHTTP(w, r)
|
||||||
|
if w.Code != 400 {
|
||||||
|
t.Errorf("invalid input=%q status=%d", body, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/payment/trust/v1/capabilities", nil))
|
||||||
|
if w.Code != 404 {
|
||||||
|
t.Errorf("removed operation API=%d", w.Code)
|
||||||
|
}
|
||||||
|
r := trustStreamRequest(false)
|
||||||
|
ctx, cancel := context.WithCancel(r.Context())
|
||||||
|
cancel()
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
if w.Body.Len() != 0 {
|
||||||
|
t.Error("cancelled-before-dispatch request produced result")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type trustBlockingWriter struct {
|
||||||
|
entered chan struct{}
|
||||||
|
release chan struct{}
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *trustBlockingWriter) Header() http.Header { return make(http.Header) }
|
||||||
|
func (w *trustBlockingWriter) WriteHeader(int) {}
|
||||||
|
func (w *trustBlockingWriter) Flush() {}
|
||||||
|
func (w *trustBlockingWriter) Write(p []byte) (int, error) {
|
||||||
|
w.once.Do(func() { close(w.entered) })
|
||||||
|
<-w.release
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustBackpressureAndDisconnectDoNotCancelFinancialWorker(t *testing.T) {
|
||||||
|
for _, disconnect := range []bool{false, true} {
|
||||||
|
t.Run(map[bool]string{false: "backpressure", true: "disconnect"}[disconnect], func(t *testing.T) {
|
||||||
|
app := fixtureTrustApp(t, t.TempDir())
|
||||||
|
printed := make(chan struct{})
|
||||||
|
var prints atomic.Int32
|
||||||
|
app.trustReceipt = func(string) { prints.Add(1); close(printed) }
|
||||||
|
writer := &trustBlockingWriter{entered: make(chan struct{}), release: make(chan struct{})}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { app.streamTrustPayment(writer, trustStreamRequest(false).WithContext(ctx), false); close(done) }()
|
||||||
|
var once sync.Once
|
||||||
|
t.Cleanup(func() { once.Do(func() { close(writer.release) }); <-done })
|
||||||
|
select {
|
||||||
|
case <-writer.entered:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("handler did not reach blocked writer")
|
||||||
|
}
|
||||||
|
if disconnect {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-printed:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("delivery blocked provider finalization/printing")
|
||||||
|
}
|
||||||
|
once.Do(func() { close(writer.release) })
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("handler did not finish after delivery released")
|
||||||
|
}
|
||||||
|
if prints.Load() != 1 {
|
||||||
|
t.Errorf("prints=%d, want 1", prints.Load())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustDisconnectDuringProviderCallAndConcurrentAdmission(t *testing.T) {
|
||||||
|
entered, release := make(chan struct{}), make(chan struct{})
|
||||||
|
var calls atomic.Int32
|
||||||
|
client, err := trustpayments.New(trustpayments.Config{BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "fixture-site", Password: "synthetic", Terminal: "fixture-ped", Currency: "GBP", Timezone: "Europe/London", Transport: trustFixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
calls.Add(1)
|
||||||
|
var input map[string]string
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
close(entered)
|
||||||
|
<-release
|
||||||
|
if r.Context().Err() != nil {
|
||||||
|
t.Error("incoming disconnect cancelled admitted provider request")
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(map[string]string{"refid": input["refid"], "siteid": "fixture-site", "terminalserialnumber": "fixture-ped", "type": input["type"], "amount": input["amount"], "resultcode": "Approved"})
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(body))}, nil
|
||||||
|
})})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := &trustFixtureApp{App: &App{isPayment: true, cfg: &config.ConfigRec{}}, trustReceipt: func(string) {}}
|
||||||
|
app.SetTrustPayments(client)
|
||||||
|
app.SetPaymentService(paymentsvc.NewService(&trustpayments.Processor{Client: client, PrintReceipt: func(s string) { app.trustReceipt(s) }}))
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
app.streamTrustPayment(httptest.NewRecorder(), trustStreamRequest(false).WithContext(ctx), false)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
var once sync.Once
|
||||||
|
t.Cleanup(func() { once.Do(func() { close(release) }); <-done })
|
||||||
|
select {
|
||||||
|
case <-entered:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("provider request was not admitted")
|
||||||
|
}
|
||||||
|
second := httptest.NewRecorder()
|
||||||
|
app.streamTrustPayment(second, trustStreamRequest(false), false)
|
||||||
|
if !strings.Contains(second.Body.String(), `"httpStatus":409`) {
|
||||||
|
t.Errorf("concurrent admission status=%d, want 409", second.Code)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
once.Do(func() { close(release) })
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("admitted provider did not finish after disconnect")
|
||||||
|
}
|
||||||
|
if calls.Load() != 1 {
|
||||||
|
t.Errorf("financial requests=%d, want 1", calls.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type trustFixtureApp struct {
|
||||||
|
*App
|
||||||
|
trustReceipt func(string)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *trustFixtureApp) streamTrustPayment(w http.ResponseWriter, r *http.Request, preauth bool) {
|
||||||
|
a.streamPayment(w, r, preauth)
|
||||||
|
}
|
||||||
@@ -2,17 +2,22 @@ package logging
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
// setupLogging ensures log directory, opens log file, and configures logrus.
|
// SetupLogging ensures the log directory, opens the rotating log writer, and configures logrus.
|
||||||
// Returns the *os.File so caller can defer its Close().
|
func SetupLogging(logDir, serviceName, buildVersion string) (io.WriteCloser, error) {
|
||||||
func SetupLogging(logDir, serviceName, buildVersion string) (*os.File, error) {
|
if err := os.MkdirAll(logDir, 0o755); err != nil {
|
||||||
fileName := logDir + serviceName + ".log"
|
return nil, fmt.Errorf("create log directory: %w", err)
|
||||||
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
|
}
|
||||||
|
|
||||||
|
fileName := filepath.Join(logDir, serviceName+".log")
|
||||||
|
f, err := newWeeklyLogWriter(fileName, time.Local, defaultWeeklyLogRuntime())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("open log file: %w", err)
|
return nil, fmt.Errorf("open log file: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,319 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
_ "time/tzdata"
|
||||||
|
)
|
||||||
|
|
||||||
|
const weeklyLogRetention = 13
|
||||||
|
|
||||||
|
type logRotationTimer interface {
|
||||||
|
C() <-chan time.Time
|
||||||
|
Stop() bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type realLogRotationTimer struct {
|
||||||
|
*time.Timer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t realLogRotationTimer) C() <-chan time.Time {
|
||||||
|
return t.Timer.C
|
||||||
|
}
|
||||||
|
|
||||||
|
type weeklyLogRuntime struct {
|
||||||
|
now func() time.Time
|
||||||
|
newTimer func(time.Duration) logRotationTimer
|
||||||
|
rename func(string, string) error
|
||||||
|
diagnostic io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultWeeklyLogRuntime() weeklyLogRuntime {
|
||||||
|
return weeklyLogRuntime{
|
||||||
|
now: time.Now,
|
||||||
|
newTimer: func(duration time.Duration) logRotationTimer {
|
||||||
|
return realLogRotationTimer{Timer: time.NewTimer(duration)}
|
||||||
|
},
|
||||||
|
rename: os.Rename,
|
||||||
|
diagnostic: os.Stderr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type weeklyLogWriter struct {
|
||||||
|
path string
|
||||||
|
location *time.Location
|
||||||
|
now func() time.Time
|
||||||
|
newTimer func(time.Duration) logRotationTimer
|
||||||
|
rename func(string, string) error
|
||||||
|
diagnostic io.Writer
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
file *os.File
|
||||||
|
weekStart time.Time
|
||||||
|
closed bool
|
||||||
|
stop chan struct{}
|
||||||
|
done chan struct{}
|
||||||
|
closeOnce sync.Once
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func newWeeklyLogWriter(path string, location *time.Location, runtime weeklyLogRuntime) (*weeklyLogWriter, error) {
|
||||||
|
if location == nil {
|
||||||
|
location = time.Local
|
||||||
|
}
|
||||||
|
if runtime.now == nil {
|
||||||
|
runtime.now = time.Now
|
||||||
|
}
|
||||||
|
if runtime.newTimer == nil {
|
||||||
|
runtime.newTimer = defaultWeeklyLogRuntime().newTimer
|
||||||
|
}
|
||||||
|
if runtime.rename == nil {
|
||||||
|
runtime.rename = os.Rename
|
||||||
|
}
|
||||||
|
if runtime.diagnostic == nil {
|
||||||
|
runtime.diagnostic = os.Stderr
|
||||||
|
}
|
||||||
|
|
||||||
|
now := runtime.now().In(location)
|
||||||
|
weekStart := logWeekStart(now, location)
|
||||||
|
if info, err := os.Stat(path); err == nil {
|
||||||
|
weekStart = logWeekStart(info.ModTime(), location)
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, fmt.Errorf("inspect active log: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
writer := &weeklyLogWriter{
|
||||||
|
path: path,
|
||||||
|
location: location,
|
||||||
|
now: runtime.now,
|
||||||
|
newTimer: runtime.newTimer,
|
||||||
|
rename: runtime.rename,
|
||||||
|
diagnostic: runtime.diagnostic,
|
||||||
|
file: file,
|
||||||
|
weekStart: weekStart,
|
||||||
|
stop: make(chan struct{}),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(now)
|
||||||
|
go writer.run()
|
||||||
|
return writer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) Write(data []byte) (int, error) {
|
||||||
|
now := w.now().In(w.location)
|
||||||
|
w.mu.Lock()
|
||||||
|
rotationErr := w.rotateIfNeededLocked(now)
|
||||||
|
if w.closed || w.file == nil {
|
||||||
|
w.mu.Unlock()
|
||||||
|
w.reportRotationError(rotationErr)
|
||||||
|
return 0, os.ErrClosed
|
||||||
|
}
|
||||||
|
n, writeErr := w.file.Write(data)
|
||||||
|
w.mu.Unlock()
|
||||||
|
w.reportRotationError(rotationErr)
|
||||||
|
return n, writeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) Close() error {
|
||||||
|
w.closeOnce.Do(func() {
|
||||||
|
close(w.stop)
|
||||||
|
<-w.done
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
w.closed = true
|
||||||
|
if w.file != nil {
|
||||||
|
w.closeErr = w.file.Close()
|
||||||
|
w.file = nil
|
||||||
|
}
|
||||||
|
w.mu.Unlock()
|
||||||
|
})
|
||||||
|
return w.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) run() {
|
||||||
|
defer close(w.done)
|
||||||
|
for {
|
||||||
|
now := w.now().In(w.location)
|
||||||
|
next := nextLogWeekStart(now, w.location)
|
||||||
|
duration := next.Sub(now)
|
||||||
|
if duration <= 0 {
|
||||||
|
duration = time.Nanosecond
|
||||||
|
}
|
||||||
|
timer := w.newTimer(duration)
|
||||||
|
select {
|
||||||
|
case <-timer.C():
|
||||||
|
w.rotateIfNeeded(w.now().In(w.location))
|
||||||
|
case <-w.stop:
|
||||||
|
timer.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) rotateIfNeeded(now time.Time) {
|
||||||
|
w.mu.Lock()
|
||||||
|
err := w.rotateIfNeededLocked(now)
|
||||||
|
w.mu.Unlock()
|
||||||
|
w.reportRotationError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) rotateIfNeededLocked(now time.Time) error {
|
||||||
|
if w.closed {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
targetWeek := logWeekStart(now, w.location)
|
||||||
|
if !targetWeek.After(w.weekStart) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record the attempted week even if rotation fails so every write in a
|
||||||
|
// broken environment does not retry and emit another diagnostic.
|
||||||
|
w.weekStart = targetWeek
|
||||||
|
return w.rotateLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) rotateLocked() error {
|
||||||
|
if w.file == nil {
|
||||||
|
return fmt.Errorf("active log file is unavailable")
|
||||||
|
}
|
||||||
|
if err := w.file.Close(); err != nil {
|
||||||
|
w.file = nil
|
||||||
|
return errors.Join(fmt.Errorf("close active log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
w.file = nil
|
||||||
|
|
||||||
|
if err := w.cleanupOlderGenerationsLocked(); err != nil {
|
||||||
|
return errors.Join(err, w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
if err := removeIfExists(w.generationPath(weeklyLogRetention)); err != nil {
|
||||||
|
return errors.Join(fmt.Errorf("remove oldest weekly log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
for generation := weeklyLogRetention - 1; generation >= 1; generation-- {
|
||||||
|
source := w.generationPath(generation)
|
||||||
|
if _, err := os.Stat(source); err != nil {
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return errors.Join(fmt.Errorf("inspect weekly log generation %d: %w", generation, err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
if err := w.rename(source, w.generationPath(generation+1)); err != nil {
|
||||||
|
return errors.Join(fmt.Errorf("shift weekly log generation %d: %w", generation, err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
activeRenamed := false
|
||||||
|
if _, err := os.Stat(w.path); err == nil {
|
||||||
|
if err := w.rename(w.path, w.generationPath(1)); err != nil {
|
||||||
|
return errors.Join(fmt.Errorf("archive active log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
activeRenamed = true
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return errors.Join(fmt.Errorf("inspect active log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.OpenFile(w.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)
|
||||||
|
if err == nil {
|
||||||
|
w.file = file
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rotationErr := fmt.Errorf("open new active log: %w", err)
|
||||||
|
if activeRenamed {
|
||||||
|
if rollbackErr := w.rename(w.generationPath(1), w.path); rollbackErr != nil {
|
||||||
|
rotationErr = errors.Join(rotationErr, fmt.Errorf("restore archived active log: %w", rollbackErr))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.Join(rotationErr, w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) cleanupOlderGenerationsLocked() error {
|
||||||
|
directory := filepath.Dir(w.path)
|
||||||
|
entries, err := os.ReadDir(directory)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("list weekly log directory: %w", err)
|
||||||
|
}
|
||||||
|
base := filepath.Base(w.path)
|
||||||
|
extension := filepath.Ext(base)
|
||||||
|
stem := strings.TrimSuffix(base, extension)
|
||||||
|
prefix := stem + "."
|
||||||
|
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name := entry.Name()
|
||||||
|
if !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, extension) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
generationText := strings.TrimSuffix(strings.TrimPrefix(name, prefix), extension)
|
||||||
|
generation, err := strconv.Atoi(generationText)
|
||||||
|
if err != nil || generation <= weeklyLogRetention {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := os.Remove(filepath.Join(directory, name)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return fmt.Errorf("remove weekly log generation %d: %w", generation, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) reopenActiveLocked() error {
|
||||||
|
file, err := os.OpenFile(w.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("reopen active log: %w", err)
|
||||||
|
}
|
||||||
|
w.file = file
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) generationPath(generation int) string {
|
||||||
|
extension := filepath.Ext(w.path)
|
||||||
|
stem := strings.TrimSuffix(w.path, extension)
|
||||||
|
return fmt.Sprintf("%s.%d%s", stem, generation, extension)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) reportRotationError(err error) {
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
slog.New(slog.NewJSONHandler(w.diagnostic, nil)).Warn(
|
||||||
|
"weekly log rotation failed",
|
||||||
|
"module", "logging",
|
||||||
|
"action", "weekly_log_rotation_failed",
|
||||||
|
"path", w.path,
|
||||||
|
"error.message", err.Error(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func logWeekStart(value time.Time, location *time.Location) time.Time {
|
||||||
|
local := value.In(location)
|
||||||
|
daysSinceMonday := (int(local.Weekday()) + 6) % 7
|
||||||
|
monday := local.AddDate(0, 0, -daysSinceMonday)
|
||||||
|
return time.Date(monday.Year(), monday.Month(), monday.Day(), 0, 0, 0, 0, location)
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextLogWeekStart(value time.Time, location *time.Location) time.Time {
|
||||||
|
return logWeekStart(value, location).AddDate(0, 0, 7)
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeIfExists(path string) error {
|
||||||
|
err := os.Remove(path)
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWeeklyLogRotationShiftsAndRetainsExactGenerations(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "active")
|
||||||
|
for generation := 1; generation <= 14; generation++ {
|
||||||
|
writeLogTestFile(t, weeklyLogTestGeneration(path, generation), fmt.Sprintf("generation-%d", generation))
|
||||||
|
}
|
||||||
|
writeLogTestFile(t, weeklyLogTestGeneration(path, 19), "generation-19")
|
||||||
|
for name, contents := range map[string]string{
|
||||||
|
"hardlink.backup.14.log": "related-looking backup",
|
||||||
|
"another.14.log": "unrelated log",
|
||||||
|
"hardlink.14.log.bak": "different extension",
|
||||||
|
} {
|
||||||
|
writeLogTestFile(t, filepath.Join(directory, name), contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
writer := newLogTestWriter(t, path, sunday, weeklyLogRuntime{})
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, path, "")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "active")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 2), "generation-1")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 13), "generation-12")
|
||||||
|
for _, generation := range []int{14, 19} {
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, generation)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("generation %d exists after rotation, want removed: %v", generation, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, contents := range map[string]string{
|
||||||
|
"hardlink.backup.14.log": "related-looking backup",
|
||||||
|
"another.14.log": "unrelated log",
|
||||||
|
"hardlink.14.log.bak": "different extension",
|
||||||
|
} {
|
||||||
|
requireLogTestContents(t, filepath.Join(directory, name), contents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogRotationOccursOncePerWeek(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "week-zero\n")
|
||||||
|
sunday := time.Date(2026, time.January, 4, 18, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
writer := newLogTestWriter(t, path, sunday, weeklyLogRuntime{})
|
||||||
|
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.January, 4, 23, 59, 59, 0, time.UTC))
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, 1)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("rotation before Monday: %v, want no generation", err)
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.January, 5, 0, 0, 0, 0, time.UTC))
|
||||||
|
if _, err := writer.Write([]byte("week-one\n")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.January, 6, 12, 0, 0, 0, time.UTC))
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "week-zero\n")
|
||||||
|
requireLogTestContents(t, path, "week-one\n")
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, 2)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("same-week rotation created generation 2: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogStartupRotatesOnceAfterSeveralMissedWeeks(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "old active")
|
||||||
|
writeLogTestFile(t, weeklyLogTestGeneration(path, 1), "older history")
|
||||||
|
setLogTestModTime(t, path, time.Date(2026, time.January, 5, 12, 0, 0, 0, time.UTC))
|
||||||
|
|
||||||
|
now := time.Date(2026, time.February, 23, 9, 0, 0, 0, time.UTC)
|
||||||
|
writer := newLogTestWriter(t, path, now, weeklyLogRuntime{})
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "old active")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 2), "older history")
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, 3)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("missed weeks created generation 3: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogSchedulerUsesLocalMondayBoundary(t *testing.T) {
|
||||||
|
location, err := time.LoadLocation("Europe/London")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "sunday")
|
||||||
|
sunday := time.Date(2026, time.March, 29, 0, 0, 0, 0, location)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
|
||||||
|
clock := &atomic.Pointer[time.Time]{}
|
||||||
|
clock.Store(&sunday)
|
||||||
|
created := make(chan *logTestTimer, 2)
|
||||||
|
rotated := make(chan struct{})
|
||||||
|
runtime := weeklyLogRuntime{
|
||||||
|
now: func() time.Time { return *clock.Load() },
|
||||||
|
newTimer: func(duration time.Duration) logRotationTimer {
|
||||||
|
timer := &logTestTimer{duration: duration, ch: make(chan time.Time, 1)}
|
||||||
|
created <- timer
|
||||||
|
return timer
|
||||||
|
},
|
||||||
|
rename: func(oldPath, newPath string) error {
|
||||||
|
err := os.Rename(oldPath, newPath)
|
||||||
|
if oldPath == path && err == nil {
|
||||||
|
close(rotated)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
},
|
||||||
|
}
|
||||||
|
writer, err := newWeeklyLogWriter(path, location, runtime)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
timer := <-created
|
||||||
|
if timer.duration != 23*time.Hour {
|
||||||
|
t.Fatalf("timer duration = %v, want 23h across DST boundary", timer.duration)
|
||||||
|
}
|
||||||
|
monday := time.Date(2026, time.March, 30, 0, 0, 0, 0, location)
|
||||||
|
clock.Store(&monday)
|
||||||
|
timer.ch <- monday
|
||||||
|
<-rotated
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "sunday")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogConcurrentWritesRemainCompleteAcrossRotation(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
writer := newLogTestWriter(t, path, sunday, weeklyLogRuntime{})
|
||||||
|
|
||||||
|
const goroutines = 8
|
||||||
|
const recordsPerGoroutine = 100
|
||||||
|
writeErrors := make(chan error, goroutines)
|
||||||
|
var writers sync.WaitGroup
|
||||||
|
writers.Add(goroutines)
|
||||||
|
for worker := 0; worker < goroutines; worker++ {
|
||||||
|
go func() {
|
||||||
|
defer writers.Done()
|
||||||
|
for record := 0; record < recordsPerGoroutine; record++ {
|
||||||
|
if _, err := writer.Write([]byte(fmt.Sprintf("%d:%d\n", worker, record))); err != nil {
|
||||||
|
writeErrors <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
writers.Wait()
|
||||||
|
close(writeErrors)
|
||||||
|
for err := range writeErrors {
|
||||||
|
t.Errorf("weeklyLogWriter.Write() error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
contents := readLogTestFile(t, weeklyLogTestGeneration(path, 1)) + readLogTestFile(t, path)
|
||||||
|
lines := strings.Split(strings.TrimSpace(contents), "\n")
|
||||||
|
if len(lines) != goroutines*recordsPerGoroutine {
|
||||||
|
t.Fatalf("record count = %d, want %d", len(lines), goroutines*recordsPerGoroutine)
|
||||||
|
}
|
||||||
|
seen := make(map[string]bool, len(lines))
|
||||||
|
for _, line := range lines {
|
||||||
|
if _, _, ok := strings.Cut(line, ":"); !ok {
|
||||||
|
t.Fatalf("record %q has no separator", line)
|
||||||
|
}
|
||||||
|
seen[line] = true
|
||||||
|
}
|
||||||
|
if len(seen) != goroutines*recordsPerGoroutine {
|
||||||
|
t.Errorf("unique record count = %d, want %d", len(seen), goroutines*recordsPerGoroutine)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogCloseWaitsForRotationAndIsIdempotent(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "active")
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
started := make(chan struct{})
|
||||||
|
release := make(chan struct{})
|
||||||
|
runtime := weeklyLogRuntime{rename: func(oldPath, newPath string) error {
|
||||||
|
if oldPath == path {
|
||||||
|
close(started)
|
||||||
|
<-release
|
||||||
|
}
|
||||||
|
return os.Rename(oldPath, newPath)
|
||||||
|
}}
|
||||||
|
writer := newLogTestWriter(t, path, sunday, runtime)
|
||||||
|
rotationDone := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
close(rotationDone)
|
||||||
|
}()
|
||||||
|
<-started
|
||||||
|
|
||||||
|
closeDone := make(chan error, 1)
|
||||||
|
go func() { closeDone <- writer.Close() }()
|
||||||
|
select {
|
||||||
|
case err := <-closeDone:
|
||||||
|
t.Fatalf("weeklyLogWriter.Close() during rotation returned %v, want blocked", err)
|
||||||
|
case <-time.After(20 * time.Millisecond):
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
<-rotationDone
|
||||||
|
if err := <-closeDone; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Errorf("second weeklyLogWriter.Close() error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if _, err := writer.Write([]byte("after close")); !errors.Is(err, os.ErrClosed) {
|
||||||
|
t.Errorf("weeklyLogWriter.Write() after close error = %v, want os.ErrClosed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogRotationFailureIsNonRecursiveAndPreservesWrites(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "before\n")
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
var diagnostics bytes.Buffer
|
||||||
|
runtime := weeklyLogRuntime{
|
||||||
|
rename: func(oldPath, newPath string) error {
|
||||||
|
if oldPath == path {
|
||||||
|
return errors.New("injected rename failure")
|
||||||
|
}
|
||||||
|
return os.Rename(oldPath, newPath)
|
||||||
|
},
|
||||||
|
diagnostic: &diagnostics,
|
||||||
|
}
|
||||||
|
writer := newLogTestWriter(t, path, sunday, runtime)
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
if _, err := writer.Write([]byte("after\n")); err != nil {
|
||||||
|
t.Fatalf("weeklyLogWriter.Write() after failed rotation error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, path, "before\nafter\n")
|
||||||
|
if !strings.Contains(diagnostics.String(), "weekly_log_rotation_failed") || !strings.Contains(diagnostics.String(), "injected rename failure") {
|
||||||
|
t.Errorf("rotation diagnostic = %q, want action and injected error", diagnostics.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(readLogTestFile(t, path), "weekly log rotation failed") {
|
||||||
|
t.Error("rotation diagnostic recursively entered active log")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetupLoggingKeepsFilenameAndJSONFormat(t *testing.T) {
|
||||||
|
logger := log.StandardLogger()
|
||||||
|
previousOutput := logger.Out
|
||||||
|
previousFormatter := logger.Formatter
|
||||||
|
previousLevel := logger.Level
|
||||||
|
t.Cleanup(func() {
|
||||||
|
logger.SetOutput(previousOutput)
|
||||||
|
logger.SetFormatter(previousFormatter)
|
||||||
|
logger.SetLevel(previousLevel)
|
||||||
|
})
|
||||||
|
|
||||||
|
directory := filepath.Join(t.TempDir(), "nested", "logs")
|
||||||
|
writer, err := SetupLogging(directory, "hardlink", "v-test")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
log.WithField("probe", "value").Info("test record")
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
contents := readLogTestFile(t, filepath.Join(directory, "hardlink.log"))
|
||||||
|
for _, want := range []string{`"buildVersion":"v-test"`, `"msg":"Logging initialized"`, `"probe":"value"`, `"msg":"test record"`} {
|
||||||
|
if !strings.Contains(contents, want) {
|
||||||
|
t.Errorf("hardlink.log contents missing %q: %s", want, contents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(directory, "hardlink.1.log")); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("SetupLogging() created archive during current week: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type logTestTimer struct {
|
||||||
|
duration time.Duration
|
||||||
|
ch chan time.Time
|
||||||
|
stopped atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *logTestTimer) C() <-chan time.Time {
|
||||||
|
return t.ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *logTestTimer) Stop() bool {
|
||||||
|
return !t.stopped.Swap(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLogTestWriter(t *testing.T, path string, now time.Time, overrides weeklyLogRuntime) *weeklyLogWriter {
|
||||||
|
t.Helper()
|
||||||
|
runtime := defaultWeeklyLogRuntime()
|
||||||
|
runtime.now = func() time.Time { return now }
|
||||||
|
if overrides.now != nil {
|
||||||
|
runtime.now = overrides.now
|
||||||
|
}
|
||||||
|
if overrides.newTimer != nil {
|
||||||
|
runtime.newTimer = overrides.newTimer
|
||||||
|
}
|
||||||
|
if overrides.rename != nil {
|
||||||
|
runtime.rename = overrides.rename
|
||||||
|
}
|
||||||
|
if overrides.diagnostic != nil {
|
||||||
|
runtime.diagnostic = overrides.diagnostic
|
||||||
|
}
|
||||||
|
writer, err := newWeeklyLogWriter(path, now.Location(), runtime)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func weeklyLogTestGeneration(path string, generation int) string {
|
||||||
|
extension := filepath.Ext(path)
|
||||||
|
return fmt.Sprintf("%s.%d%s", strings.TrimSuffix(path, extension), generation, extension)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLogTestFile(t *testing.T, path, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setLogTestModTime(t *testing.T, path string, value time.Time) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.Chtimes(path, value, value); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLogTestFile(t *testing.T, path string) string {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireLogTestContents(t *testing.T, path, want string) {
|
||||||
|
t.Helper()
|
||||||
|
if got := readLogTestFile(t, path); got != want {
|
||||||
|
t.Errorf("%s contents = %q, want %q", filepath.Base(path), got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ io.WriteCloser = (*weeklyLogWriter)(nil)
|
||||||
+102
-28
@@ -3,19 +3,24 @@ package paybridge
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
"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/paymentsvc"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
|
PrintReceipt func(string)
|
||||||
URL string
|
URL string
|
||||||
APIKey string
|
APIKey string
|
||||||
TimeoutSeconds int
|
TimeoutSeconds int
|
||||||
@@ -46,10 +51,57 @@ func (c *Client) Sale(ctx context.Context, req paymentsvc.SaleRequest, onStatus
|
|||||||
TimeoutSeconds: c.TimeoutSeconds,
|
TimeoutSeconds: c.TimeoutSeconds,
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.doPayment(ctx, payBridgeReq, onStatus)
|
result, err := c.doPayment(ctx, payBridgeReq, onStatus)
|
||||||
|
if result != nil {
|
||||||
|
result.Terminal = payBridgeTerminalResult(result)
|
||||||
|
if c.PrintReceipt != nil {
|
||||||
|
c.PrintReceipt(result.CustomerReceipt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus paymentsvc.StatusHandler) (returned *paymentsvc.Result, resultErr error) {
|
||||||
|
stage := "configure_connection"
|
||||||
|
var httpStatus int
|
||||||
|
defer func() {
|
||||||
|
if resultErr != nil || (returned != nil && payBridgeTerminalResult(returned).Outcome == "unknown") {
|
||||||
|
fields := log.Fields{
|
||||||
|
"provider": "paybridge", "operation": "sale", "stage": stage,
|
||||||
|
"request_id": req.RequestID, "transaction_reference": req.RequestID,
|
||||||
|
"error_category": paymentsvc.SafeErrorCategory(resultErr),
|
||||||
|
}
|
||||||
|
if returned != nil {
|
||||||
|
if returned.RequestID != "" {
|
||||||
|
fields["transaction_reference"] = returned.RequestID
|
||||||
|
}
|
||||||
|
if returned.TransactionID != "" {
|
||||||
|
fields["provider_transaction_id"] = returned.TransactionID
|
||||||
|
}
|
||||||
|
if returned.ReferenceNumber != "" {
|
||||||
|
fields["provider_reference"] = returned.ReferenceNumber
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
fields["error_category"] = paymentsvc.SafeErrorCategory(ctx.Err())
|
||||||
|
} else if errors.Is(resultErr, ErrConnectionFailed) {
|
||||||
|
fields["error_category"] = "connection_failure"
|
||||||
|
} else if errors.Is(resultErr, ErrAuthFailed) {
|
||||||
|
fields["error_category"] = "authentication_failed"
|
||||||
|
} else if errors.Is(resultErr, ErrUnexpectedMessage) {
|
||||||
|
fields["error_category"] = "invalid_response"
|
||||||
|
}
|
||||||
|
var closeError *websocket.CloseError
|
||||||
|
if errors.As(resultErr, &closeError) {
|
||||||
|
fields["error_category"] = "response_lost"
|
||||||
|
fields["websocket_close_code"] = closeError.Code
|
||||||
|
}
|
||||||
|
if httpStatus != 0 {
|
||||||
|
fields["http_status"] = httpStatus
|
||||||
|
}
|
||||||
|
log.WithFields(fields).Warn("PayBridge payment requires reconciliation")
|
||||||
|
}
|
||||||
|
}()
|
||||||
emitStatus(onStatus, paymentstatus.Starting)
|
emitStatus(onStatus, paymentstatus.Starting)
|
||||||
|
|
||||||
connectURL, err := c.connectURL()
|
connectURL, err := c.connectURL()
|
||||||
@@ -57,8 +109,15 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ws, _, err := websocket.DefaultDialer.DialContext(ctx, connectURL, nil)
|
stage = "connect"
|
||||||
|
ws, response, err := websocket.DefaultDialer.DialContext(ctx, connectURL, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if response != nil {
|
||||||
|
httpStatus = response.StatusCode
|
||||||
|
if response.Body != nil {
|
||||||
|
response.Body.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
return nil, fmt.Errorf("%w: %v", ErrConnectionFailed, err)
|
return nil, fmt.Errorf("%w: %v", ErrConnectionFailed, err)
|
||||||
}
|
}
|
||||||
defer ws.Close()
|
defer ws.Close()
|
||||||
@@ -74,6 +133,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
stage = "authenticate"
|
||||||
jwt, err := c.readAuthSuccess(ws)
|
jwt, err := c.readAuthSuccess(ws)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -82,6 +142,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
log.Info("PayBridge authentication successful")
|
log.Info("PayBridge authentication successful")
|
||||||
emitStatus(onStatus, paymentstatus.Started)
|
emitStatus(onStatus, paymentstatus.Started)
|
||||||
|
|
||||||
|
stage = "send_payment"
|
||||||
if err := ws.WriteJSON(Envelope{
|
if err := ws.WriteJSON(Envelope{
|
||||||
Type: types.MesTypePaymentRequest,
|
Type: types.MesTypePaymentRequest,
|
||||||
JWT: jwt,
|
JWT: jwt,
|
||||||
@@ -101,6 +162,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
emitStatus(onStatus, paymentstatus.RequestSent)
|
emitStatus(onStatus, paymentstatus.RequestSent)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
|
stage = "read_result"
|
||||||
_, raw, err := ws.ReadMessage()
|
_, raw, err := ws.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
@@ -122,26 +184,20 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
|
|
||||||
switch messageType {
|
switch messageType {
|
||||||
case types.MesTypePaymentStatusUpdate:
|
case types.MesTypePaymentStatusUpdate:
|
||||||
|
stage = "decode_status"
|
||||||
var update StatusUpdateEnvelope
|
var update StatusUpdateEnvelope
|
||||||
if err := json.Unmarshal(raw, &update); err != nil {
|
if err := json.Unmarshal(raw, &update); err != nil {
|
||||||
return nil, fmt.Errorf("decode payment_status_update: %w", err)
|
return nil, fmt.Errorf("decode payment_status_update: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"status": update.Data.Status,
|
|
||||||
"code": update.Data.Code,
|
|
||||||
}).Info("PayBridge status update")
|
|
||||||
|
|
||||||
statusCode, known := mapPayBridgeStatus(
|
statusCode, known := mapPayBridgeStatus(
|
||||||
update.Data.Status,
|
update.Data.Status,
|
||||||
update.Data.Code,
|
update.Data.Code,
|
||||||
)
|
)
|
||||||
|
log.WithField("status", statusCode).Info("PayBridge status update")
|
||||||
|
|
||||||
if !known {
|
if !known {
|
||||||
log.WithFields(log.Fields{
|
log.Warn("Unknown PayBridge status update")
|
||||||
"status": update.Data.Status,
|
|
||||||
"code": update.Data.Code,
|
|
||||||
}).Warn("Unknown PayBridge status update")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
emitStatus(onStatus, statusCode)
|
emitStatus(onStatus, statusCode)
|
||||||
@@ -151,6 +207,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
emitStatus(onStatus, paymentstatus.Accepted)
|
emitStatus(onStatus, paymentstatus.Accepted)
|
||||||
|
|
||||||
case types.MesTypePaymentResult:
|
case types.MesTypePaymentResult:
|
||||||
|
stage = "decode_result"
|
||||||
var result PaymentResultEnvelope
|
var result PaymentResultEnvelope
|
||||||
// log.Println("PayBridge payment result raw:", string(raw))
|
// log.Println("PayBridge payment result raw:", string(raw))
|
||||||
if err := json.Unmarshal(raw, &result); err != nil {
|
if err := json.Unmarshal(raw, &result); err != nil {
|
||||||
@@ -162,7 +219,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
log.WithFields(log.Fields{
|
log.WithFields(log.Fields{
|
||||||
"requestId": mapped.RequestID,
|
"requestId": mapped.RequestID,
|
||||||
"transactionId": mapped.TransactionID,
|
"transactionId": mapped.TransactionID,
|
||||||
"status": mapped.Status,
|
"status": mapPayBridgeFinalStatus(mapped.Status, mapped.Success),
|
||||||
"success": mapped.Success,
|
"success": mapped.Success,
|
||||||
}).Info("PayBridge payment result received")
|
}).Info("PayBridge payment result received")
|
||||||
|
|
||||||
@@ -174,6 +231,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
return mapped, nil
|
return mapped, nil
|
||||||
|
|
||||||
case types.MesTypePaymentError:
|
case types.MesTypePaymentError:
|
||||||
|
stage = "decode_payment_error"
|
||||||
var paymentErr PaymentErrorEnvelope
|
var paymentErr PaymentErrorEnvelope
|
||||||
if err := json.Unmarshal(raw, &paymentErr); err != nil {
|
if err := json.Unmarshal(raw, &paymentErr); err != nil {
|
||||||
return nil, fmt.Errorf("decode payment_error: %w", err)
|
return nil, fmt.Errorf("decode payment_error: %w", err)
|
||||||
@@ -182,10 +240,10 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
mapped := mapPaymentError(req, paymentErr)
|
mapped := mapPaymentError(req, paymentErr)
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
log.WithFields(log.Fields{
|
||||||
"requestId": mapped.RequestID,
|
"requestId": mapped.RequestID,
|
||||||
"transactionId": mapped.TransactionID,
|
"transactionId": mapped.TransactionID,
|
||||||
"status": mapped.Status,
|
"status": mapPayBridgeFinalStatus(mapped.Status, false),
|
||||||
"error": mapped.ErrorMessage,
|
"error_category": "provider_error",
|
||||||
}).Warn("PayBridge payment error received")
|
}).Warn("PayBridge payment error received")
|
||||||
|
|
||||||
emitStatus(
|
emitStatus(
|
||||||
@@ -196,6 +254,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
return mapped, nil
|
return mapped, nil
|
||||||
|
|
||||||
case types.ResultError:
|
case types.ResultError:
|
||||||
|
stage = "provider_error"
|
||||||
var genericErr struct {
|
var genericErr struct {
|
||||||
Error struct {
|
Error struct {
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
@@ -211,10 +270,8 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
log.WithFields(log.Fields{"provider": "paybridge", "request_id": req.RequestID,
|
||||||
"code": genericErr.Error.Code,
|
"error_category": "provider_error"}).Error("PayBridge error message received")
|
||||||
"message": genericErr.Error.Message,
|
|
||||||
}).Error("PayBridge error message received")
|
|
||||||
|
|
||||||
emitStatus(onStatus, paymentstatus.Error)
|
emitStatus(onStatus, paymentstatus.Error)
|
||||||
|
|
||||||
@@ -237,10 +294,7 @@ func (c *Client) doPayment(ctx context.Context, req PaymentRequest, onStatus pay
|
|||||||
log.Info("Additional PayBridge auth_success message received")
|
log.Info("Additional PayBridge auth_success message received")
|
||||||
|
|
||||||
default:
|
default:
|
||||||
log.WithField(
|
log.Warn("Unknown PayBridge intermediate message type")
|
||||||
"messageType",
|
|
||||||
head.Type,
|
|
||||||
).Warn("Unknown PayBridge intermediate message type")
|
|
||||||
|
|
||||||
emitStatus(onStatus, paymentstatus.Processing)
|
emitStatus(onStatus, paymentstatus.Processing)
|
||||||
}
|
}
|
||||||
@@ -447,3 +501,23 @@ func mapPayBridgeFinalStatus(
|
|||||||
return paymentstatus.Error
|
return paymentstatus.Error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (*Client) ValidatePreauth(paymentsvc.SaleRequest) error { return paymentsvc.ErrPreauthUnsupported }
|
||||||
|
func (*Client) Preauth(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
return nil, paymentsvc.ErrPreauthUnsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
func payBridgeTerminalResult(r *paymentsvc.Result) paymentapi.Result {
|
||||||
|
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Provider: "paybridge", AmountMinor: r.Amount, CurrencyCode: r.Currency, TransactionReference: r.RequestID, CardType: r.CardType, MaskedCardNumber: creditcall.MaskedCardNumber(r.CardNumber), ExpiryDate: r.ExpiryDate, CardHash: r.CardHash, CardReference: r.CardReference, AuthorizationCode: r.AuthCode, LastFour: r.LastFourDigits, Message: "Payment outcome uncertain; contact reception"}
|
||||||
|
if r.Success && strings.EqualFold(r.Status, payBridgeFinalStatusApproved) {
|
||||||
|
final.Outcome, final.Message = "approved", "Payment approved"
|
||||||
|
return final
|
||||||
|
}
|
||||||
|
switch strings.ToUpper(r.Status) {
|
||||||
|
case payBridgeFinalStatusDeclined:
|
||||||
|
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
|
||||||
|
case payBridgeFinalStatusCancelled:
|
||||||
|
final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled"
|
||||||
|
}
|
||||||
|
return final
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package paybridge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
logtest "github.com/sirupsen/logrus/hooks/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
func paybridgeDiagnosticLog(t *testing.T) *logtest.Hook {
|
||||||
|
t.Helper()
|
||||||
|
logger := log.StandardLogger()
|
||||||
|
oldOutput := logger.Out
|
||||||
|
oldHooks := logger.ReplaceHooks(make(log.LevelHooks))
|
||||||
|
hook := logtest.NewGlobal()
|
||||||
|
log.SetOutput(io.Discard)
|
||||||
|
t.Cleanup(func() { log.SetOutput(oldOutput); logger.ReplaceHooks(oldHooks) })
|
||||||
|
return hook
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPayBridgeFailureDiagnosticsKeepIdentityAndDoNotRetry(t *testing.T) {
|
||||||
|
for _, failure := range []string{"connect", "auth", "lost", "malformed", "uncertain", "provider_error", "payment_error", "cancelled"} {
|
||||||
|
t.Run(failure, func(t *testing.T) {
|
||||||
|
hook := paybridgeDiagnosticLog(t)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
var financialPosts atomic.Int32
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Query().Get("api_key") != "SYNTH-CREDENTIAL" {
|
||||||
|
t.Error("PayBridge connection omitted synthetic credential")
|
||||||
|
}
|
||||||
|
if failure == "connect" {
|
||||||
|
http.Error(w, "SYNTH-RAW-SECRET", 503)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connection, err := (&websocket.Upgrader{}).Upgrade(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer connection.Close()
|
||||||
|
auth := `{"type":"auth_success","jwt":"SYNTH-JWT-PRIVATE"}`
|
||||||
|
if failure == "auth" {
|
||||||
|
auth = `{"type":"SYNTH-RAW-SECRET","jwt":"SYNTH-JWT-PRIVATE"}`
|
||||||
|
}
|
||||||
|
if err := connection.WriteMessage(websocket.TextMessage, []byte(auth)); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if failure == "auth" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request struct {
|
||||||
|
Data PaymentRequest `json:"data"`
|
||||||
|
}
|
||||||
|
if err := connection.ReadJSON(&request); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
financialPosts.Add(1)
|
||||||
|
if request.Data.RequestID != "SYNTH-REQUEST" || request.Data.Amount != 2500 {
|
||||||
|
t.Errorf("PayBridge dispatched %+v, want original request identity/amount", request.Data)
|
||||||
|
}
|
||||||
|
body := ""
|
||||||
|
switch failure {
|
||||||
|
case "lost":
|
||||||
|
if err := connection.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "SYNTH-RAW-SECRET"), time.Now().Add(time.Second)); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
case "malformed":
|
||||||
|
body = `{"type":"payment_result","data":"SYNTH-RAW-SECRET"}`
|
||||||
|
case "uncertain":
|
||||||
|
body = `{"type":"payment_result","data":{"requestId":"SYNTH-REQUEST","transactionId":"SYNTH-PROVIDER-TXN","referenceNumber":"SYNTH-PROVIDER-REF","success":false,"status":"TIMEOUT","errorMessage":"SYNTH-RAW-SECRET card 4111111111111111","amount":2500}}`
|
||||||
|
case "provider_error":
|
||||||
|
body = `{"type":"error","error":{"code":"SYNTH-PRIVATE-CODE","message":"SYNTH-RAW-SECRET"}}`
|
||||||
|
case "payment_error":
|
||||||
|
body = `{"type":"payment_error","data":{"transactionId":"SYNTH-PROVIDER-TXN","status":"TIMEOUT","error":"SYNTH-RAW-SECRET"}}`
|
||||||
|
case "cancelled":
|
||||||
|
cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := connection.WriteMessage(websocket.TextMessage, []byte(body)); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
client := NewClient("ws"+strings.TrimPrefix(server.URL, "http"), "SYNTH-CREDENTIAL", 5)
|
||||||
|
result, err := client.Sale(ctx, paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Amount: 2500, Currency: "GBP"}, nil)
|
||||||
|
wantPosts := int32(1)
|
||||||
|
if failure == "connect" || failure == "auth" {
|
||||||
|
wantPosts = 0
|
||||||
|
}
|
||||||
|
if financialPosts.Load() != wantPosts {
|
||||||
|
t.Errorf("Sale(%s) dispatches=%d, want %d without retry", failure, financialPosts.Load(), wantPosts)
|
||||||
|
}
|
||||||
|
if failure == "uncertain" || failure == "payment_error" {
|
||||||
|
if err != nil || result == nil || result.Terminal.Outcome != "unknown" || result.Terminal.Retryable {
|
||||||
|
t.Fatalf("Sale(%s)=%+v/%v, want unchanged nonretryable unknown", failure, result, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(result.ErrorMessage, "SYNTH-RAW-SECRET") {
|
||||||
|
t.Error("diagnostic changes mutated the existing provider result")
|
||||||
|
}
|
||||||
|
} else if result != nil || err == nil {
|
||||||
|
t.Fatalf("Sale(%s)=%+v/%v, want original nil-result failure", failure, result, err)
|
||||||
|
}
|
||||||
|
if failure == "connect" && !errors.Is(err, ErrConnectionFailed) {
|
||||||
|
t.Errorf("Sale(connect) error=%v, want ErrConnectionFailed", err)
|
||||||
|
}
|
||||||
|
if failure == "cancelled" && !errors.Is(err, context.Canceled) {
|
||||||
|
t.Errorf("Sale(cancelled) error=%v, want context.Canceled", err)
|
||||||
|
}
|
||||||
|
var diagnostic *log.Entry
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
data, _ := json.Marshal(entry.Data)
|
||||||
|
for _, secret := range []string{"SYNTH-CREDENTIAL", "SYNTH-JWT-PRIVATE", "SYNTH-RAW-SECRET", "SYNTH-PRIVATE-CODE", "4111111111111111"} {
|
||||||
|
if strings.Contains(string(data)+entry.Message, secret) {
|
||||||
|
t.Errorf("Sale(%s) logged sensitive marker %q", failure, secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entry.Message == "PayBridge payment requires reconciliation" {
|
||||||
|
diagnostic = entry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if diagnostic == nil {
|
||||||
|
t.Fatal("Sale failure emitted no reconciliation diagnostic")
|
||||||
|
}
|
||||||
|
for key, want := range map[string]string{"provider": "paybridge", "request_id": "SYNTH-REQUEST", "transaction_reference": "SYNTH-REQUEST"} {
|
||||||
|
if diagnostic.Data[key] != want {
|
||||||
|
t.Errorf("Sale(%s) diagnostic[%s]=%v, want %s", failure, key, diagnostic.Data[key], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stages := map[string]string{"connect": "connect", "auth": "authenticate", "lost": "read_result", "malformed": "decode_result", "uncertain": "decode_result", "provider_error": "provider_error", "payment_error": "decode_payment_error", "cancelled": "read_result"}
|
||||||
|
categories := map[string]string{"connect": "connection_failure", "auth": "authentication_failed", "lost": "response_lost", "malformed": "invalid_response", "uncertain": "unresolved_result", "provider_error": "invalid_response", "payment_error": "unresolved_result", "cancelled": "cancelled"}
|
||||||
|
if diagnostic.Data["stage"] != stages[failure] || diagnostic.Data["error_category"] != categories[failure] {
|
||||||
|
t.Errorf("Sale(%s) diagnostic=%v, want stage=%s category=%s", failure, diagnostic.Data, stages[failure], categories[failure])
|
||||||
|
}
|
||||||
|
if failure == "lost" && diagnostic.Data["websocket_close_code"] != websocket.ClosePolicyViolation {
|
||||||
|
t.Errorf("Sale(lost) close code=%v, want 1008", diagnostic.Data["websocket_close_code"])
|
||||||
|
}
|
||||||
|
if failure == "connect" && diagnostic.Data["http_status"] != 503 {
|
||||||
|
t.Errorf("Sale(connect) HTTP status=%v, want 503", diagnostic.Data["http_status"])
|
||||||
|
}
|
||||||
|
if failure == "uncertain" || failure == "payment_error" {
|
||||||
|
if diagnostic.Data["provider_transaction_id"] != "SYNTH-PROVIDER-TXN" {
|
||||||
|
t.Errorf("Sale(%s) provider transaction=%v, want retained identity", failure, diagnostic.Data["provider_transaction_id"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package paybridge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTerminalResultKeepsExistingIdentityAndMetadata(t *testing.T) {
|
||||||
|
raw := &paymentsvc.Result{Success: true, Status: "APPROVED", RequestID: "SYNTH-REQUEST", TransactionID: "SYNTH-PROVIDER-ID", Amount: 1234, Currency: "EUR", CardNumber: "************1133", CardType: "Visa", ExpiryDate: "1228", CardHash: "SYNTH-HASH", CardReference: "SYNTH-CARD"}
|
||||||
|
result := payBridgeTerminalResult(raw)
|
||||||
|
if result.Outcome != "approved" || result.TransactionReference != "SYNTH-REQUEST" || result.MaskedCardNumber != raw.CardNumber || result.CardHash != raw.CardHash || result.CardReference != raw.CardReference {
|
||||||
|
t.Errorf("payBridgeTerminalResult(%+v)=%+v, want current request identity and unchanged metadata", raw, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestTimeoutTerminalResultIsUncertain(t *testing.T) {
|
||||||
|
result := payBridgeTerminalResult(&paymentsvc.Result{Status: "TIMEOUT"})
|
||||||
|
if result.Outcome != "unknown" || result.Retryable {
|
||||||
|
t.Errorf("payBridgeTerminalResult(TIMEOUT)=%+v, want nonretryable unknown", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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) {
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package paymentsvc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SafeErrorCategory describes a failure without exposing URLs, payloads or credentials.
|
||||||
|
// It is diagnostic only and must not determine financial outcomes or retry eligibility.
|
||||||
|
func SafeErrorCategory(err error) string {
|
||||||
|
if err == nil {
|
||||||
|
return "unresolved_result"
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, context.DeadlineExceeded):
|
||||||
|
return "timeout"
|
||||||
|
case errors.Is(err, context.Canceled):
|
||||||
|
return "cancelled"
|
||||||
|
case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF):
|
||||||
|
return "response_lost"
|
||||||
|
}
|
||||||
|
var networkError net.Error
|
||||||
|
if errors.As(err, &networkError) {
|
||||||
|
if networkError.Timeout() {
|
||||||
|
return "timeout"
|
||||||
|
}
|
||||||
|
return "connection_failure"
|
||||||
|
}
|
||||||
|
var syntaxError *json.SyntaxError
|
||||||
|
var typeError *json.UnmarshalTypeError
|
||||||
|
if errors.As(err, &syntaxError) || errors.As(err, &typeError) {
|
||||||
|
return "invalid_response"
|
||||||
|
}
|
||||||
|
return "provider_error"
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package paymentsvc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSafeErrorCategory(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
err error
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"missing result", nil, "unresolved_result"},
|
||||||
|
{"timeout", fmt.Errorf("private URL: %w", context.DeadlineExceeded), "timeout"},
|
||||||
|
{"cancel", fmt.Errorf("private token: %w", context.Canceled), "cancelled"},
|
||||||
|
{"eof", fmt.Errorf("raw response: %w", io.EOF), "response_lost"},
|
||||||
|
{"truncated", io.ErrUnexpectedEOF, "response_lost"},
|
||||||
|
{"connection", &url.Error{Op: "Post", URL: "https://user:secret@synthetic.invalid", Err: &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("private credential")}}, "connection_failure"},
|
||||||
|
{"json syntax", &json.SyntaxError{Offset: 1}, "invalid_response"},
|
||||||
|
{"json type", &json.UnmarshalTypeError{Value: "private card", Field: "secret"}, "invalid_response"},
|
||||||
|
{"other", errors.New("raw provider response with sensitive content"), "provider_error"},
|
||||||
|
}
|
||||||
|
for _, tc := range tests {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
if got := SafeErrorCategory(tc.err); got != tc.want {
|
||||||
|
t.Errorf("SafeErrorCategory(%s)=%q, want %q", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
var (
|
var (
|
||||||
ErrPaymentInProgress = errors.New("payment is already in progress")
|
ErrPaymentInProgress = errors.New("payment is already in progress")
|
||||||
ErrProviderNotConfigured = errors.New("payment provider is not configured")
|
ErrProviderNotConfigured = errors.New("payment provider is not configured")
|
||||||
|
ErrPreauthUnsupported = errors.New("configured payment provider does not support preauthorisation")
|
||||||
)
|
)
|
||||||
|
|
||||||
type StatusUpdate struct {
|
type StatusUpdate struct {
|
||||||
@@ -23,15 +24,21 @@ type Provider interface {
|
|||||||
req SaleRequest,
|
req SaleRequest,
|
||||||
onStatus StatusHandler,
|
onStatus StatusHandler,
|
||||||
) (*Result, error)
|
) (*Result, error)
|
||||||
|
Preauth(context.Context, SaleRequest, StatusHandler) (*Result, error)
|
||||||
|
ValidatePreauth(SaleRequest) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
provider Provider
|
provider Provider
|
||||||
|
currency string
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
busy bool
|
busy bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetCurrency supplies the currency from the existing CMS hotel response at startup.
|
||||||
|
func (s *Service) SetCurrency(currency string) { s.currency = currency }
|
||||||
|
|
||||||
func NewService(provider Provider) *Service {
|
func NewService(provider Provider) *Service {
|
||||||
return &Service{
|
return &Service{
|
||||||
provider: provider,
|
provider: provider,
|
||||||
@@ -43,9 +50,32 @@ func (s *Service) Sale(
|
|||||||
req SaleRequest,
|
req SaleRequest,
|
||||||
onStatus StatusHandler,
|
onStatus StatusHandler,
|
||||||
) (*Result, error) {
|
) (*Result, error) {
|
||||||
|
return s.run(ctx, req, onStatus, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preauth uses the same terminal ownership as Sale.
|
||||||
|
func (s *Service) Preauth(ctx context.Context, req SaleRequest, onStatus StatusHandler) (*Result, error) {
|
||||||
|
return s.run(ctx, req, onStatus, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) run(ctx context.Context, req SaleRequest, onStatus StatusHandler, preauth bool) (*Result, error) {
|
||||||
if s == nil || s.provider == nil {
|
if s == nil || s.provider == nil {
|
||||||
return nil, ErrProviderNotConfigured
|
return nil, ErrProviderNotConfigured
|
||||||
}
|
}
|
||||||
|
if s.currency != "" {
|
||||||
|
req.Currency = s.currency
|
||||||
|
}
|
||||||
|
if preauth {
|
||||||
|
if err := s.provider.ValidatePreauth(req); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else if req.RequiredPreauth != nil {
|
||||||
|
hold := req
|
||||||
|
hold.Amount, hold.CheckoutDate = req.RequiredPreauth.Amount, req.RequiredPreauth.CheckoutDate
|
||||||
|
if err := s.provider.ValidatePreauth(hold); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
if s.busy {
|
if s.busy {
|
||||||
@@ -61,5 +91,8 @@ func (s *Service) Sale(
|
|||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
if preauth {
|
||||||
|
return s.provider.Preauth(ctx, req, onStatus)
|
||||||
|
}
|
||||||
return s.provider.Sale(ctx, req, onStatus)
|
return s.provider.Sale(ctx, req, onStatus)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package paymentsvc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
type testProcessor struct {
|
||||||
|
entered chan SaleRequest
|
||||||
|
release chan struct{}
|
||||||
|
saleCalls atomic.Int32
|
||||||
|
preauthCalls atomic.Int32
|
||||||
|
validation func(SaleRequest) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *testProcessor) ValidatePreauth(req SaleRequest) error {
|
||||||
|
if p.validation != nil {
|
||||||
|
return p.validation(req)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (p *testProcessor) Sale(_ context.Context, req SaleRequest, _ StatusHandler) (*Result, error) {
|
||||||
|
p.saleCalls.Add(1)
|
||||||
|
if p.entered != nil {
|
||||||
|
p.entered <- req
|
||||||
|
}
|
||||||
|
if p.release != nil {
|
||||||
|
<-p.release
|
||||||
|
}
|
||||||
|
return &Result{Terminal: paymentapi.Result{Outcome: "approved", HTTPStatus: 200}}, nil
|
||||||
|
}
|
||||||
|
func (p *testProcessor) Preauth(context.Context, SaleRequest, StatusHandler) (*Result, error) {
|
||||||
|
p.preauthCalls.Add(1)
|
||||||
|
return &Result{Terminal: paymentapi.Result{Outcome: "approved", HTTPStatus: 200}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSaleAndPreauthShareAdmission(t *testing.T) {
|
||||||
|
p := &testProcessor{entered: make(chan SaleRequest, 1), release: make(chan struct{})}
|
||||||
|
s := NewService(p)
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { _, err := s.Sale(context.Background(), SaleRequest{Amount: 100}, nil); done <- err }()
|
||||||
|
<-p.entered
|
||||||
|
if _, err := s.Preauth(context.Background(), SaleRequest{Amount: 50}, nil); !errors.Is(err, ErrPaymentInProgress) {
|
||||||
|
t.Errorf("Preauth(during Sale) error=%v, want ErrPaymentInProgress", err)
|
||||||
|
}
|
||||||
|
close(p.release)
|
||||||
|
if err := <-done; err != nil {
|
||||||
|
t.Fatalf("Sale() error=%v, want nil", err)
|
||||||
|
}
|
||||||
|
if _, err := s.Preauth(context.Background(), SaleRequest{Amount: 50}, nil); err != nil {
|
||||||
|
t.Errorf("Preauth(after Sale) error=%v, want nil", err)
|
||||||
|
}
|
||||||
|
if p.saleCalls.Load() != 1 || p.preauthCalls.Load() != 1 {
|
||||||
|
t.Errorf("Provider calls=%d/%d, want Sale=1/PREAUTH=1", p.saleCalls.Load(), p.preauthCalls.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequiredPreauthValidatedBeforeSale(t *testing.T) {
|
||||||
|
p := &testProcessor{validation: func(req SaleRequest) error {
|
||||||
|
if req.Amount != 2500 || req.CheckoutDate != "SYNTH-DATE" {
|
||||||
|
t.Errorf("ValidatePreauth() request=%+v, want planned 2500 hold/date", req)
|
||||||
|
}
|
||||||
|
return ErrPreauthUnsupported
|
||||||
|
}}
|
||||||
|
_, err := NewService(p).Sale(context.Background(), SaleRequest{Amount: 10000, RequiredPreauth: &paymentapi.PreauthRequirement{Amount: 2500, CheckoutDate: "SYNTH-DATE"}}, nil)
|
||||||
|
if !errors.Is(err, ErrPreauthUnsupported) || p.saleCalls.Load() != 0 || p.preauthCalls.Load() != 0 {
|
||||||
|
t.Errorf("Sale(required unsupported hold) error/calls=%v/%d/%d, want unsupported/no dispatch", err, p.saleCalls.Load(), p.preauthCalls.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCMSCurrencyReachesProviderWithoutLocalDefault(t *testing.T) {
|
||||||
|
p := &testProcessor{entered: make(chan SaleRequest, 1)}
|
||||||
|
s := NewService(p)
|
||||||
|
s.SetCurrency("EUR")
|
||||||
|
if _, err := s.Sale(context.Background(), SaleRequest{Amount: 100, Currency: "GBP"}, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := (<-p.entered).Currency; got != "EUR" {
|
||||||
|
t.Errorf("Sale() provider currency=%q, want CMS EUR", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,25 @@
|
|||||||
package paymentsvc
|
package paymentsvc
|
||||||
|
|
||||||
|
import "gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
|
||||||
type SaleRequest struct {
|
type SaleRequest struct {
|
||||||
RequestID string `json:"requestId"`
|
RequestID string `json:"requestId"`
|
||||||
Reference string `json:"reference"`
|
Reference string `json:"reference"`
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency"`
|
||||||
|
CheckoutDate string `json:"checkoutDate,omitempty"`
|
||||||
|
RequiredPreauth *paymentapi.PreauthRequirement `json:"requiredPreauth,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Result struct {
|
type Result struct {
|
||||||
Success bool `json:"success"`
|
// Terminal is the provider-independent result exposed by the modern endpoints.
|
||||||
RequestID string `json:"requestId,omitempty"`
|
Terminal paymentapi.Result `json:"-"`
|
||||||
Operation string `json:"operation,omitempty"`
|
Success bool `json:"success"`
|
||||||
Status string `json:"status"`
|
RequestID string `json:"requestId,omitempty"`
|
||||||
Message string `json:"message,omitempty"`
|
Operation string `json:"operation,omitempty"`
|
||||||
ErrorMessage string `json:"errorMessage,omitempty"`
|
Status string `json:"status"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
ErrorMessage string `json:"errorMessage,omitempty"`
|
||||||
|
|
||||||
TransactionID string `json:"transactionId,omitempty"`
|
TransactionID string `json:"transactionId,omitempty"`
|
||||||
ReferenceNumber string `json:"referenceNumber,omitempty"`
|
ReferenceNumber string `json:"referenceNumber,omitempty"`
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -55,20 +55,6 @@ type (
|
|||||||
CheckOutTimeText string `xml:"CheckOutTimeText"`
|
CheckOutTimeText string `xml:"CheckOutTimeText"`
|
||||||
RoomMapFolderPath string `xml:"RoomMapFolderPath"`
|
RoomMapFolderPath string `xml:"RoomMapFolderPath"`
|
||||||
}
|
}
|
||||||
|
|
||||||
RoomTicket struct {
|
|
||||||
Logo string
|
|
||||||
TopMostText string
|
|
||||||
Name string
|
|
||||||
BeforeRoomNumberText string
|
|
||||||
RoomID string
|
|
||||||
BeforeDirectionsText string
|
|
||||||
Directions string
|
|
||||||
HotelSpecificDetails string
|
|
||||||
Map string
|
|
||||||
CheckOutTimeText string
|
|
||||||
Checkout string
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -220,7 +206,6 @@ func PrintSaleReceipt(receipt string) {
|
|||||||
buf.Write([]byte{ESC, 'd', 7})
|
buf.Write([]byte{ESC, 'd', 7})
|
||||||
buf.Write([]byte{GS, 'V', 1})
|
buf.Write([]byte{GS, 'V', 1})
|
||||||
|
|
||||||
|
|
||||||
if err := SendToPrinter(buf.Bytes()); err != nil {
|
if err := SendToPrinter(buf.Bytes()); err != nil {
|
||||||
log.Errorf("SendToPrinter error: %v", err)
|
log.Errorf("SendToPrinter error: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,276 @@
|
|||||||
|
// Package trustpayments implements bounded TRU Link calls without financial retries.
|
||||||
|
package trustpayments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
BaseURL string
|
||||||
|
SiteID string
|
||||||
|
Password string
|
||||||
|
Terminal string
|
||||||
|
Currency string
|
||||||
|
Timezone string
|
||||||
|
// Transport is an explicit fixture seam; production leaves it nil.
|
||||||
|
Transport http.RoundTripper
|
||||||
|
}
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
cfg Config
|
||||||
|
http *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(cfg Config) (*Client, error) {
|
||||||
|
u, err := url.Parse(cfg.BaseURL)
|
||||||
|
if err != nil || u.Scheme != "https" || u.User != nil || u.RawQuery != "" || u.Fragment != "" ||
|
||||||
|
(u.Host != "link.trustpayments.com" && u.Host != "sandbox.link.trustpayments.com") ||
|
||||||
|
strings.TrimRight(u.Path, "/") != "/trustpayments/rest" {
|
||||||
|
return nil, errors.New("invalid CMS ReservationSystem.PaymentGatewayURL for Trust")
|
||||||
|
}
|
||||||
|
for _, field := range []struct{ name, value string }{
|
||||||
|
{"ReservationSystem.PaymentGatewaySiteIDEPOS", cfg.SiteID},
|
||||||
|
{"ReservationSystem.PaymentGatewayPasswordEPOS", cfg.Password},
|
||||||
|
{"ReservationSystem.PDQs.Serial", cfg.Terminal},
|
||||||
|
} {
|
||||||
|
if strings.TrimSpace(field.value) == "" {
|
||||||
|
return nil, fmt.Errorf("CMS %s is required for Trust", field.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := time.LoadLocation(cfg.Timezone); err != nil || cfg.Timezone == "" || cfg.Timezone == "Local" {
|
||||||
|
return nil, errors.New("valid CMS ReservationSystem.TimeZone is required for Trust")
|
||||||
|
}
|
||||||
|
return &Client{cfg: cfg, http: &http.Client{Transport: cfg.Transport, Timeout: 300 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("Trust redirects prohibited") }}}, nil
|
||||||
|
}
|
||||||
|
func (c *Client) ValidRequest(request Request) bool {
|
||||||
|
return (request.Kind == "sale" || request.Kind == "preauth") && request.Amount > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process makes one financial request and at most one observational status call.
|
||||||
|
// Its reference exists for this attempt only; no restart recovery is provided.
|
||||||
|
func (c *Client) Process(ctx context.Context, request Request) (Result, error) {
|
||||||
|
if !c.ValidRequest(request) {
|
||||||
|
return Result{State: Unknown}, errors.New("invalid or unavailable Trust request")
|
||||||
|
}
|
||||||
|
op := Operation{Request: request, RefID: strings.ReplaceAll(uuid.NewString(), "-", ""), TxnDate: c.Timestamp(time.Now())}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 315*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
result, err := c.Execute(ctx, op, false)
|
||||||
|
if (result.State == Unknown || result.State == Pending) && ctx.Err() == nil {
|
||||||
|
return c.Execute(ctx, op, true)
|
||||||
|
}
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
func (c *Client) Timestamp(t time.Time) string {
|
||||||
|
loc, _ := time.LoadLocation(c.cfg.Timezone)
|
||||||
|
return t.In(loc).Format("2006-01-02:15:04:05")
|
||||||
|
}
|
||||||
|
func Token(site, date, ref, password string) string {
|
||||||
|
h := sha256.Sum256([]byte(site + ":" + date + ":" + ref + ":" + password))
|
||||||
|
return hex.EncodeToString(h[:])
|
||||||
|
}
|
||||||
|
func Decimal(n int64) string { return fmt.Sprintf("%d.%02d", n/100, n%100) }
|
||||||
|
|
||||||
|
func ParseAmount(s string) (int64, error) {
|
||||||
|
if s == "" || strings.Trim(s, "0123456789.") != "" {
|
||||||
|
return 0, errors.New("invalid provider amount")
|
||||||
|
}
|
||||||
|
parts := strings.Split(s, ".")
|
||||||
|
if len(parts) != 2 || len(parts[0]) == 0 || len(parts[1]) != 2 {
|
||||||
|
return 0, errors.New("invalid provider amount scale")
|
||||||
|
}
|
||||||
|
n, err := strconv.ParseInt(parts[0]+parts[1], 10, 64)
|
||||||
|
if err != nil || n <= 0 {
|
||||||
|
return 0, errors.New("invalid provider amount range")
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type response struct {
|
||||||
|
RefID string `json:"refid"`
|
||||||
|
Site string `json:"siteid"`
|
||||||
|
Terminal string `json:"terminalserialnumber"`
|
||||||
|
Kind string `json:"type"`
|
||||||
|
Result string `json:"resultcode"`
|
||||||
|
Amount string `json:"amount"`
|
||||||
|
Final string `json:"finalamount"`
|
||||||
|
Error json.RawMessage `json:"error"`
|
||||||
|
ErrorMessage string `json:"errormessage"`
|
||||||
|
Code json.RawMessage `json:"errorcode"`
|
||||||
|
Auth string `json:"authcode"`
|
||||||
|
Card string `json:"cardtype"`
|
||||||
|
Last string `json:"last4"`
|
||||||
|
Receipt string `json:"receipt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func safe(s string) string {
|
||||||
|
if len(s) > 80 || strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_./") != "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
func receiptFields(s string) (string, string) {
|
||||||
|
var receipt, sequence string
|
||||||
|
for _, line := range strings.Split(strings.ReplaceAll(s, "\r\n", "\n"), "\n") {
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
if strings.HasPrefix(line, "Receipt:") {
|
||||||
|
receipt = safe(strings.TrimSpace(strings.TrimPrefix(line, "Receipt:")))
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "Sequence number:") {
|
||||||
|
sequence = safe(strings.TrimSpace(strings.TrimPrefix(line, "Sequence number:")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return receipt, sequence
|
||||||
|
}
|
||||||
|
func (c *Client) Execute(ctx context.Context, op Operation, status bool) (Result, error) {
|
||||||
|
result := Result{State: Unknown, RefID: op.RefID}
|
||||||
|
if (op.Request.Kind != "sale" && op.Request.Kind != "preauth") || op.Request.Amount <= 0 || op.RefID == "" || op.TxnDate == "" {
|
||||||
|
return result, errors.New("invalid Trust operation context")
|
||||||
|
}
|
||||||
|
payload := map[string]string{"siteid": c.cfg.SiteID, "txndate": op.TxnDate, "refid": op.RefID}
|
||||||
|
endpoint := "status"
|
||||||
|
timeout := 15 * time.Second
|
||||||
|
if !status {
|
||||||
|
endpoint = op.Request.Kind
|
||||||
|
timeout = 300 * time.Second
|
||||||
|
payload["amount"] = Decimal(op.Request.Amount)
|
||||||
|
payload["type"] = op.Request.Kind
|
||||||
|
payload["terminalserialnumber"] = c.cfg.Terminal
|
||||||
|
payload["wait"] = "y"
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
b, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(c.cfg.BaseURL, "/")+"/"+endpoint, bytes.NewReader(b))
|
||||||
|
if err != nil {
|
||||||
|
return result, errors.New("invalid Trust endpoint")
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("token", Token(c.cfg.SiteID, op.TxnDate, op.RefID, c.cfg.Password))
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return result, errors.New("Trust transport outcome unavailable")
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return result, fmt.Errorf("Trust HTTP status %d; financial outcome unknown", resp.StatusCode)
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024+1))
|
||||||
|
if err != nil || len(data) > 1024*1024 {
|
||||||
|
return result, errors.New("Trust result unreadable")
|
||||||
|
}
|
||||||
|
var r response
|
||||||
|
if err = json.Unmarshal(data, &r); err != nil {
|
||||||
|
return result, errors.New("Trust result invalid")
|
||||||
|
}
|
||||||
|
// Preserve bounded, parsed observations for operator reconciliation without
|
||||||
|
// representing mismatched values as admitted approval evidence.
|
||||||
|
if n, e := ParseAmount(r.Amount); e == nil {
|
||||||
|
result.ObservedAmount = n
|
||||||
|
result.ObservedAmountKnown = true
|
||||||
|
}
|
||||||
|
if n, e := ParseAmount(r.Final); e == nil {
|
||||||
|
result.ObservedFinalAmount = n
|
||||||
|
result.ObservedFinalKnown = true
|
||||||
|
}
|
||||||
|
code := strings.Trim(string(r.Code), `"`)
|
||||||
|
if code == "null" {
|
||||||
|
code = ""
|
||||||
|
}
|
||||||
|
if len(code) <= 6 && strings.Trim(code, "0123456789") == "" {
|
||||||
|
result.Code = code
|
||||||
|
}
|
||||||
|
// Duplicate identity, any error code and incomplete responses are never refusals.
|
||||||
|
if code != "" && code != "0" {
|
||||||
|
// This attempt never resubmits a financial POST. A duplicate on its first
|
||||||
|
// dispatch may belong to another owner; Status alone cannot prove that
|
||||||
|
// ownership when terminal/timestamp evidence is absent.
|
||||||
|
if code == "1008" || code == "1011" {
|
||||||
|
result.State = Review
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
if (len(r.Error) > 0 && string(r.Error) != "null" && string(r.Error) != "0" && string(r.Error) != "\"\"") || r.ErrorMessage != "" {
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
if r.RefID != op.RefID || r.Site != c.cfg.SiteID || (r.Terminal != "" && r.Terminal != c.cfg.Terminal) ||
|
||||||
|
(status && !strings.EqualFold(r.Kind, op.Request.Kind)) || (!status && r.Terminal != c.cfg.Terminal) ||
|
||||||
|
(r.Kind != "" && !strings.EqualFold(r.Kind, op.Request.Kind)) {
|
||||||
|
result.State = Review
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
switch strings.ToLower(r.Result) {
|
||||||
|
case "pending":
|
||||||
|
result.State = Pending
|
||||||
|
return result, nil
|
||||||
|
case "declined":
|
||||||
|
if r.Auth != "" {
|
||||||
|
result.State = Review
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
result.State = Declined
|
||||||
|
return result, nil
|
||||||
|
case "cancelled":
|
||||||
|
if r.Auth != "" {
|
||||||
|
result.State = Review
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
result.State = Cancelled
|
||||||
|
return result, nil
|
||||||
|
case "approved":
|
||||||
|
default:
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
amountText := r.Amount
|
||||||
|
if status {
|
||||||
|
amountText = r.Final
|
||||||
|
}
|
||||||
|
amount, err := ParseAmount(amountText)
|
||||||
|
if err != nil || amount != op.Request.Amount {
|
||||||
|
result.State = Review
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
if r.Final != "" {
|
||||||
|
final, e := ParseAmount(r.Final)
|
||||||
|
if e != nil || final != amount {
|
||||||
|
result.State = Review
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.State = Approved
|
||||||
|
result.Amount = amount
|
||||||
|
// Legacy TRU approval does not validate currency; this is CMS bookkeeping only.
|
||||||
|
result.Currency = c.cfg.Currency
|
||||||
|
receipt, sequence := receiptFields(r.Receipt)
|
||||||
|
result.Metadata = Metadata{Receipt: shortIdentifier(receipt), Sequence: shortIdentifier(sequence), AuthCode: shortIdentifier(r.Auth)}
|
||||||
|
if len(r.Card) <= 24 && strings.Trim(r.Card, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ") == "" {
|
||||||
|
result.Metadata.CardType = r.Card
|
||||||
|
}
|
||||||
|
if len(r.Last) == 4 && strings.Trim(r.Last, "0123456789") == "" {
|
||||||
|
result.Metadata.LastFour = r.Last
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
func shortIdentifier(s string) string {
|
||||||
|
if len(s) > 12 || strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_/") != "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package trustpayments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type transportFunc func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
func fixtureConfig() Config {
|
||||||
|
return Config{BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "site", Password: "test-secret", Terminal: "terminal", Currency: "GBP", Timezone: "Europe/London"}
|
||||||
|
}
|
||||||
|
func TestTrustSigningMoneyAndConfiguration(t *testing.T) {
|
||||||
|
if got := Token("123456", "2020-03-01:10:20:05", "7876547", "tv%61w%5"); got != "990bc7bb7efee9e383a96f6f929fd00c90f4ec94f4344270c1552e4d5d4d80c5" {
|
||||||
|
t.Errorf("Token=%s", got)
|
||||||
|
}
|
||||||
|
for _, s := range []string{"", "0.00", "-1.00", "1.001", "1", "NaN", "92233720368547758.08", "1e2"} {
|
||||||
|
if _, e := ParseAmount(s); e == nil {
|
||||||
|
t.Errorf("ParseAmount(%q) accepted", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n, e := ParseAmount("123456.78"); e != nil || Decimal(n) != "123456.78" {
|
||||||
|
t.Fatalf("money=%d/%v", n, e)
|
||||||
|
}
|
||||||
|
for _, url := range []string{"", "http://link.trustpayments.com/trustpayments/rest/", "https://other.invalid/trustpayments/rest/", "https://link.trustpayments.com:443/trustpayments/rest/", "https://link.trustpayments.com/trustpayments/rest/?x=1"} {
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
cfg.BaseURL = url
|
||||||
|
if _, e := New(cfg); e == nil {
|
||||||
|
t.Errorf("New(%q) accepted", url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestTrustFinancialEvidenceAndUncertainErrors(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
change func(map[string]any)
|
||||||
|
status bool
|
||||||
|
state string
|
||||||
|
}{
|
||||||
|
{"sale", nil, false, Approved}, {"status", nil, true, Approved},
|
||||||
|
{"adjusted", func(r map[string]any) { r["finalamount"] = "11.00" }, false, Review},
|
||||||
|
{"wrongAmount", func(r map[string]any) { r["amount"] = "9.00" }, false, Review},
|
||||||
|
{"providerCurrencyIgnored", func(r map[string]any) { r["currency"] = "EUR" }, false, Approved},
|
||||||
|
{"wrongRef", func(r map[string]any) { r["refid"] = "other" }, false, Review},
|
||||||
|
{"wrongSite", func(r map[string]any) { r["siteid"] = "other" }, true, Review},
|
||||||
|
{"wrongType", func(r map[string]any) { r["type"] = "preauth" }, true, Review},
|
||||||
|
{"noAmount", func(r map[string]any) { delete(r, "finalamount") }, true, Review},
|
||||||
|
{"declined", func(r map[string]any) { r["resultcode"] = "Declined"; delete(r, "authcode") }, false, Declined},
|
||||||
|
{"cancelled", func(r map[string]any) { r["resultcode"] = "Cancelled"; delete(r, "authcode") }, false, Cancelled},
|
||||||
|
{"pending", func(r map[string]any) { r["resultcode"] = "Pending" }, false, Pending},
|
||||||
|
{"2003", func(r map[string]any) { r["errorcode"] = 2003 }, false, Unknown},
|
||||||
|
{"2005", func(r map[string]any) { r["errorcode"] = "2005" }, false, Unknown},
|
||||||
|
{"2006", func(r map[string]any) { r["errorcode"] = 2006 }, false, Unknown},
|
||||||
|
{"1011", func(r map[string]any) { r["errorcode"] = 1011 }, false, Review},
|
||||||
|
{"1008", func(r map[string]any) { r["errorcode"] = 1008 }, false, Review},
|
||||||
|
{"offline", func(r map[string]any) { r["resultcode"] = "Terminal Busy" }, false, Unknown},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
calls := 0
|
||||||
|
cfg.Transport = transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
var input map[string]string
|
||||||
|
if e := json.NewDecoder(req.Body).Decode(&input); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if input["txndate"] != "2026-10-23:12:00:00" || req.Header.Get("token") != Token(cfg.SiteID, input["txndate"], "ref", cfg.Password) {
|
||||||
|
t.Error("signing context changed")
|
||||||
|
}
|
||||||
|
if !tc.status && (input["wait"] != "y" || input["amount"] != "10.00") {
|
||||||
|
t.Error("incorrect financial payload")
|
||||||
|
}
|
||||||
|
r := map[string]any{"refid": "ref", "siteid": "site", "terminalserialnumber": "terminal", "type": "sale", "amount": "10.00", "finalamount": "10.00", "resultcode": "Approved", "receipt": "Sequence number: 42\r\nReceipt: 31\r\nPAN: 4111111111111111", "authcode": "123456", "cardtype": "Visa", "last4": "1133"}
|
||||||
|
if tc.change != nil {
|
||||||
|
tc.change(r)
|
||||||
|
}
|
||||||
|
b, _ := json.Marshal(r)
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(b)))}, nil
|
||||||
|
})
|
||||||
|
c, e := New(cfg)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
result, e := c.Execute(context.Background(), Operation{RefID: "ref", TxnDate: "2026-10-23:12:00:00", Request: Request{Kind: "sale", Amount: 1000, Currency: "GBP"}}, tc.status)
|
||||||
|
if e != nil || result.State != tc.state || calls != 1 {
|
||||||
|
t.Fatalf("Execute=%+v/%v, calls=%d, want %s/1", result, e, calls, tc.state)
|
||||||
|
}
|
||||||
|
if result.State == Approved && (result.Metadata.Receipt != "31" || result.Metadata.Sequence != "42" || result.Metadata.LastFour != "1133") {
|
||||||
|
t.Error("metadata lost")
|
||||||
|
}
|
||||||
|
if result.State == Approved && result.Currency != cfg.Currency {
|
||||||
|
t.Errorf("currency metadata=%q, want CMS currency %q", result.Currency, cfg.Currency)
|
||||||
|
}
|
||||||
|
if tc.name == "adjusted" && (!result.ObservedFinalKnown || result.ObservedFinalAmount != 1100 || result.Amount != 0) {
|
||||||
|
t.Fatal("financial mismatch evidence was lost or admitted")
|
||||||
|
}
|
||||||
|
b, _ := json.Marshal(result)
|
||||||
|
if strings.Contains(string(b), "4111111111111111") || strings.Contains(string(b), cfg.Password) {
|
||||||
|
t.Error("sensitive data escaped")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
c, _ := New(cfg)
|
||||||
|
r, e := c.Execute(context.Background(), Operation{}, false)
|
||||||
|
if e == nil || r.State == Approved {
|
||||||
|
t.Fatal("invalid operation admitted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestTrustTransportHTTPAndMalformedResultsRemainUnknown(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, body string
|
||||||
|
status int
|
||||||
|
}{{"http500", `{"resultcode":"Approved"}`, 500}, {"http401", "", 401}, {"malformed", "{", 200}, {"empty", "{}", 200}, {"unexpectedError", `{"resultcode":"Approved","error":"private-token"}`, 200}} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
calls := 0
|
||||||
|
cfg.Transport = transportFunc(func(*http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body))}, nil
|
||||||
|
})
|
||||||
|
c, e := New(cfg)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
r, _ := c.Execute(context.Background(), Operation{RefID: "ref", TxnDate: "2026-10-23:12:00:00", Request: Request{Kind: "sale", Amount: 1000, Currency: "GBP"}}, false)
|
||||||
|
if r.State == Approved || r.State == Declined || calls != 1 {
|
||||||
|
t.Fatalf("uncertain=%+v calls=%d", r, calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package trustpayments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLegacyTrustCurrencyDoesNotDetermineApproval(t *testing.T) {
|
||||||
|
for _, providerCurrency := range []any{nil, "", "GBP", "EUR", "NOT-AN-ISO-CODE", 123, map[string]any{"unexpected": "value"}} {
|
||||||
|
t.Run(fmt.Sprint("provider=", providerCurrency), func(t *testing.T) {
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
cfg.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
|
||||||
|
var input map[string]string
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, exists := input["currency"]; exists {
|
||||||
|
t.Error("TRU request gained a currency field")
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(map[string]any{"refid": "SYNTH-REF", "siteid": cfg.SiteID, "terminalserialnumber": cfg.Terminal, "type": "sale", "resultcode": "Approved", "amount": "25.00", "currency": providerCurrency})
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(body)))}, nil
|
||||||
|
})
|
||||||
|
client, err := New(cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
op := Operation{RefID: "SYNTH-REF", TxnDate: "2026-11-03:12:00:00", Request: Request{Kind: "sale", Amount: 2500, Currency: "REQUEST-CURRENCY-IS-NOT-A-GATE"}}
|
||||||
|
result, err := client.Execute(context.Background(), op, false)
|
||||||
|
if err != nil || result.State != Approved || result.Amount != 2500 || result.Currency != cfg.Currency {
|
||||||
|
t.Fatalf("Execute(provider currency %v)=%+v/%v, want approval and CMS bookkeeping only", providerCurrency, result, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCMSCurrencyIsMetadataNotAClientValidationFlag(t *testing.T) {
|
||||||
|
for _, currency := range []string{"", "GBP", "NOT-AN-ISO-CODE"} {
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
cfg.Currency = currency
|
||||||
|
client, err := New(cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("New(CMS currency %q)=%v, want no Trust currency gate", currency, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !client.ValidRequest(Request{Kind: "preauth", Amount: 2500, Currency: "different"}) {
|
||||||
|
t.Errorf("ValidRequest(CMS currency %q) imposed currency validation", currency)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package trustpayments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTrustProcessOneFinancialPostAndBoundedStatus(t *testing.T) {
|
||||||
|
for _, first := range []string{"Approved", "Declined", "Cancelled", "Pending", "2003", "2005", "2006", "transport", "1011", "mismatch"} {
|
||||||
|
t.Run(first, func(t *testing.T) {
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
var ref, timestamp string
|
||||||
|
financial, status := 0, 0
|
||||||
|
cfg.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
|
||||||
|
var input map[string]string
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
lookup := strings.HasSuffix(r.URL.Path, "/status")
|
||||||
|
deadline, ok := r.Context().Deadline()
|
||||||
|
remaining := time.Until(deadline)
|
||||||
|
if !lookup {
|
||||||
|
financial++
|
||||||
|
ref, timestamp = input["refid"], input["txndate"]
|
||||||
|
if !ok || remaining > 300*time.Second || remaining < 299*time.Second || input["wait"] != "y" {
|
||||||
|
t.Errorf("financial deadline/payload=%s/%v", remaining, input)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
status++
|
||||||
|
if input["refid"] != ref || input["txndate"] != timestamp || !ok || remaining > 15*time.Second || remaining < 14*time.Second || input["amount"] != "" {
|
||||||
|
t.Errorf("status changed identity/budget/payload=%s/%v", remaining, input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !lookup && first == "transport" {
|
||||||
|
return nil, errors.New("synthetic disconnected provider")
|
||||||
|
}
|
||||||
|
body := map[string]any{"refid": ref, "siteid": "site", "terminalserialnumber": "terminal", "type": "sale", "amount": "10.00", "finalamount": "10.00", "resultcode": "Approved", "authcode": "123456"}
|
||||||
|
if !lookup {
|
||||||
|
switch first {
|
||||||
|
case "Declined", "Cancelled":
|
||||||
|
body["resultcode"], body["authcode"] = first, ""
|
||||||
|
case "Pending":
|
||||||
|
body["resultcode"] = first
|
||||||
|
case "2003", "2005", "2006", "1011":
|
||||||
|
body["errorcode"] = first
|
||||||
|
case "mismatch":
|
||||||
|
body["amount"] = "9.00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
encoded, _ := json.Marshal(body)
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(encoded)))}, nil
|
||||||
|
})
|
||||||
|
client, err := New(cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.Process(context.Background(), Request{Kind: "sale", Amount: 1000, Currency: "GBP"})
|
||||||
|
wantStatus := 0
|
||||||
|
if first == "Pending" || first == "transport" || first == "2003" || first == "2005" || first == "2006" {
|
||||||
|
wantStatus = 1
|
||||||
|
}
|
||||||
|
want := Approved
|
||||||
|
if first == "Declined" {
|
||||||
|
want = Declined
|
||||||
|
}
|
||||||
|
if first == "Cancelled" {
|
||||||
|
want = Cancelled
|
||||||
|
}
|
||||||
|
if first == "1011" || first == "mismatch" {
|
||||||
|
want = Review
|
||||||
|
}
|
||||||
|
if err != nil || financial != 1 || status != wantStatus || result.State != want || len(ref) != 32 {
|
||||||
|
t.Fatalf("Process(%s) state/error/posts/status=%s/%v/%d/%d, want %s/nil/1/%d", first, result.State, err, financial, status, want, wantStatus)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustProcessStatusStillUnknownAndPreauth(t *testing.T) {
|
||||||
|
for _, kind := range []string{"sale", "preauth"} {
|
||||||
|
t.Run(kind, func(t *testing.T) {
|
||||||
|
cfg := fixtureConfig()
|
||||||
|
calls := 0
|
||||||
|
cfg.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
if calls == 1 && !strings.HasSuffix(r.URL.Path, "/"+kind) {
|
||||||
|
t.Errorf("provider endpoint=%s", r.URL.Path)
|
||||||
|
}
|
||||||
|
if calls == 2 && !strings.HasSuffix(r.URL.Path, "/status") {
|
||||||
|
t.Errorf("second call=%s, want status", r.URL.Path)
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"errorcode":2003}`))}, nil
|
||||||
|
})
|
||||||
|
client, err := New(cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := client.Process(context.Background(), Request{Kind: kind, Amount: 2500, Currency: "GBP"})
|
||||||
|
if err != nil || result.State != Unknown || calls != 2 {
|
||||||
|
t.Fatalf("unresolved result=%+v/%v calls=%d", result, err, calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package trustpayments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/printer"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentstatus"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Processor owns Trust execution and terminal receipt printing.
|
||||||
|
type Processor struct {
|
||||||
|
Client *Client
|
||||||
|
PrintReceipt func(string)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Processor) ValidatePreauth(req paymentsvc.SaleRequest) error {
|
||||||
|
if p.Client == nil || !p.Client.ValidRequest(Request{Kind: "preauth", Amount: req.Amount}) {
|
||||||
|
return paymentsvc.ErrPreauthUnsupported
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (p *Processor) Sale(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
return p.run(ctx, req, status, "sale")
|
||||||
|
}
|
||||||
|
func (p *Processor) Preauth(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||||
|
return p.run(ctx, req, status, "preauth")
|
||||||
|
}
|
||||||
|
func (p *Processor) run(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler, kind string) (*paymentsvc.Result, error) {
|
||||||
|
for _, code := range []string{paymentstatus.Starting, paymentstatus.RequestSent, paymentstatus.Processing} {
|
||||||
|
if status != nil {
|
||||||
|
status(paymentsvc.StatusUpdate{Code: code})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result, err := p.Client.Process(ctx, Request{Kind: kind, Amount: req.Amount, Currency: req.Currency})
|
||||||
|
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Provider: "TrustPayments", Message: "Payment outcome uncertain; contact reception", TransactionReference: result.RefID}
|
||||||
|
switch result.State {
|
||||||
|
case Approved:
|
||||||
|
final.Outcome, final.Message = "approved", "Payment approved"
|
||||||
|
final.AmountMinor, final.CurrencyCode = result.Amount, result.Currency
|
||||||
|
m := result.Metadata
|
||||||
|
final.ReceiptNumber, final.SequenceNumber, final.AuthorizationCode = m.Receipt, m.Sequence, m.AuthCode
|
||||||
|
final.CardType, final.LastFour = m.CardType, m.LastFour
|
||||||
|
receipt := fmt.Sprintf("Trust Payments\n%s %s\n%s\nCard ************%s", Decimal(result.Amount), result.Currency, m.Description(result.RefID), m.LastFour)
|
||||||
|
if p.PrintReceipt != nil {
|
||||||
|
p.PrintReceipt(receipt)
|
||||||
|
} else {
|
||||||
|
printer.PrintSaleReceipt(receipt)
|
||||||
|
}
|
||||||
|
case Declined:
|
||||||
|
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
|
||||||
|
case Cancelled:
|
||||||
|
final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled"
|
||||||
|
}
|
||||||
|
if final.Outcome != "unknown" {
|
||||||
|
err = nil
|
||||||
|
} else {
|
||||||
|
fields := log.Fields{
|
||||||
|
"provider": final.Provider, "operation": kind, "outcome": final.Outcome,
|
||||||
|
"request_id": req.RequestID, "request_reference": req.Reference,
|
||||||
|
"transaction_reference": result.RefID, "provider_state": result.State,
|
||||||
|
"provider_code": result.Code, "error_category": paymentsvc.SafeErrorCategory(err),
|
||||||
|
}
|
||||||
|
if result.ObservedAmountKnown {
|
||||||
|
fields["observed_amount_minor"] = result.ObservedAmount
|
||||||
|
}
|
||||||
|
if result.ObservedFinalKnown {
|
||||||
|
fields["observed_final_amount_minor"] = result.ObservedFinalAmount
|
||||||
|
}
|
||||||
|
log.WithFields(fields).Warn("Trust payment outcome requires reception reconciliation")
|
||||||
|
}
|
||||||
|
return &paymentsvc.Result{Terminal: final}, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package trustpayments
|
||||||
|
|
||||||
|
// These are provider-call values, not persistent operations or kiosk sessions.
|
||||||
|
const (
|
||||||
|
Approved = "APPROVED_VALIDATED"
|
||||||
|
Declined = "DECLINED"
|
||||||
|
Cancelled = "CANCELLED"
|
||||||
|
Pending = "PENDING"
|
||||||
|
Unknown = "UNKNOWN"
|
||||||
|
Review = "REVIEW_REQUIRED"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
Kind string
|
||||||
|
Amount int64
|
||||||
|
Currency string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Operation struct {
|
||||||
|
Request Request
|
||||||
|
RefID, TxnDate string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Metadata struct {
|
||||||
|
Receipt, Sequence, AuthCode, CardType, LastFour string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Metadata) Description(ref string) string {
|
||||||
|
s := "Tx " + ref
|
||||||
|
for _, v := range [][2]string{{"Rec", m.Receipt}, {"Seq", m.Sequence}, {"Hash", m.AuthCode}, {"Ref", m.CardType + m.LastFour}} {
|
||||||
|
if v[1] != "" {
|
||||||
|
s += " " + v[0] + " " + v[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
State, RefID, Currency, Code string
|
||||||
|
Amount int64
|
||||||
|
Metadata Metadata
|
||||||
|
ObservedAmount, ObservedFinalAmount int64
|
||||||
|
ObservedAmountKnown, ObservedFinalKnown bool
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package paymentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Execute sends exactly one request. Missing, malformed or interrupted results are
|
||||||
|
// uncertain; this client never retries a financial request.
|
||||||
|
func Execute(ctx context.Context, client *http.Client, baseURL, operation string, request Request, onStatus func(string)) (Result, error) {
|
||||||
|
var path string
|
||||||
|
switch operation {
|
||||||
|
case Sale:
|
||||||
|
path = SalePath
|
||||||
|
if request.Amount <= 0 {
|
||||||
|
return Result{}, errors.New("sale amount must be positive")
|
||||||
|
}
|
||||||
|
case Preauth:
|
||||||
|
path = PreauthPath
|
||||||
|
if request.Amount < 0 {
|
||||||
|
return Result{}, errors.New("preauth amount must not be negative")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return Result{}, errors.New("invalid terminal operation")
|
||||||
|
}
|
||||||
|
if client == nil || strings.TrimSpace(baseURL) == "" {
|
||||||
|
return Result{}, errors.New("terminal client is not configured")
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(request)
|
||||||
|
if err != nil {
|
||||||
|
return Result{}, fmt.Errorf("encode terminal request: %w", err)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(baseURL, `/\`)+path, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return Result{}, errors.New("invalid terminal endpoint")
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Accept", "application/x-ndjson")
|
||||||
|
response, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return Result{}, fmt.Errorf("terminal request interrupted: %w", ctx.Err())
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
return Result{}, fmt.Errorf("terminal request interrupted: %w", context.DeadlineExceeded)
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.Canceled) {
|
||||||
|
return Result{}, fmt.Errorf("terminal request interrupted: %w", context.Canceled)
|
||||||
|
}
|
||||||
|
// Do not expose a transport error that may contain a URL or raw payload.
|
||||||
|
return Result{}, errors.New("terminal request failed; outcome is uncertain")
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if !strings.HasPrefix(response.Header.Get("Content-Type"), "application/x-ndjson") {
|
||||||
|
return Result{}, fmt.Errorf("terminal returned an invalid response contract (HTTP %d)", response.StatusCode)
|
||||||
|
}
|
||||||
|
decoder := json.NewDecoder(response.Body)
|
||||||
|
for {
|
||||||
|
var frame struct {
|
||||||
|
Frame
|
||||||
|
Legacy json.RawMessage `json:"response"`
|
||||||
|
}
|
||||||
|
if err := decoder.Decode(&frame); err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return Result{}, fmt.Errorf("terminal stream interrupted: %w", ctx.Err())
|
||||||
|
}
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
return Result{}, errors.New("terminal stream ended before a final result")
|
||||||
|
}
|
||||||
|
return Result{}, errors.New("terminal stream is invalid; outcome is uncertain")
|
||||||
|
}
|
||||||
|
if len(frame.Legacy) != 0 {
|
||||||
|
return Result{}, errors.New("terminal returned a legacy result contract")
|
||||||
|
}
|
||||||
|
switch frame.Type {
|
||||||
|
case "status":
|
||||||
|
if frame.Code == "" || frame.Result != nil {
|
||||||
|
return Result{}, errors.New("invalid terminal status frame")
|
||||||
|
}
|
||||||
|
if onStatus != nil {
|
||||||
|
onStatus(frame.Code)
|
||||||
|
}
|
||||||
|
case "result":
|
||||||
|
if frame.Result == nil || frame.Code != "" {
|
||||||
|
return Result{}, errors.New("invalid terminal result frame")
|
||||||
|
}
|
||||||
|
result := *frame.Result
|
||||||
|
switch result.Outcome {
|
||||||
|
case "approved", "declined", "cancelled", "timeout", "error", "unknown":
|
||||||
|
default:
|
||||||
|
return Result{}, errors.New("invalid terminal outcome")
|
||||||
|
}
|
||||||
|
if result.HTTPStatus < 100 || result.HTTPStatus > 599 {
|
||||||
|
return Result{}, errors.New("invalid terminal operation status")
|
||||||
|
}
|
||||||
|
if result.Outcome == "approved" && (result.HTTPStatus < 200 || result.HTTPStatus >= 300 || response.StatusCode < 200 || response.StatusCode >= 300 || result.Retryable) {
|
||||||
|
return Result{}, errors.New("contradictory terminal approval")
|
||||||
|
}
|
||||||
|
if result.Outcome == "unknown" && result.Retryable {
|
||||||
|
return Result{}, errors.New("uncertain terminal result cannot permit retry")
|
||||||
|
}
|
||||||
|
if response.StatusCode < 200 || response.StatusCode >= 300 || result.HTTPStatus < 200 || result.HTTPStatus >= 300 {
|
||||||
|
return result, fmt.Errorf("terminal operation failed (HTTP %d, operation %d)", response.StatusCode, result.HTTPStatus)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
default:
|
||||||
|
return Result{}, errors.New("invalid terminal frame type")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
package paymentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExecuteUsesOneContractForSaleAndPreauth(t *testing.T) {
|
||||||
|
for _, operation := range []string{Sale, Preauth} {
|
||||||
|
t.Run(operation, func(t *testing.T) {
|
||||||
|
input := Request{Reference: "SYNTH-BOOK", Amount: 2500, Currency: "GBP", CheckoutDate: "12 Oct 2030"}
|
||||||
|
if operation == Sale {
|
||||||
|
input.RequiredPreauth = &PreauthRequirement{Amount: 5000, CheckoutDate: "12 Oct 2030"}
|
||||||
|
}
|
||||||
|
calls := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls++
|
||||||
|
if r.Method != http.MethodPost || r.URL.Path != "/api/payment/"+operation {
|
||||||
|
t.Errorf("Execute(%q) sent %s %s, want POST modern operation", operation, r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
var got Request
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, input) {
|
||||||
|
t.Errorf("Execute(%q) request=%+v, want %+v", operation, got, input)
|
||||||
|
}
|
||||||
|
if r.Header.Get("Accept") != "application/x-ndjson" || r.Header.Get("Content-Type") != "application/json" {
|
||||||
|
t.Errorf("Execute(%q) headers=%v, want JSON request/NDJSON response", operation, r.Header)
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
||||||
|
encoder := json.NewEncoder(w)
|
||||||
|
for _, frame := range []Frame{{Type: "status", Code: "PAYMENT_PROCESSING"}, {Type: "status", Code: "FUTURE_OBSERVATIONAL_CODE"}, {Type: "result", Result: &Result{Outcome: "approved", HTTPStatus: 200, Provider: "FutureProcessor", AmountMinor: 2500, TransactionReference: "SYNTH-REFERENCE", CardType: "Visa"}}} {
|
||||||
|
if err := encoder.Encode(frame); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
var progress []string
|
||||||
|
got, err := Execute(context.Background(), server.Client(), server.URL, operation, input, func(code string) { progress = append(progress, code) })
|
||||||
|
if err != nil || got.Outcome != "approved" || got.TransactionReference != "SYNTH-REFERENCE" || calls != 1 {
|
||||||
|
t.Fatalf("Execute(%q)=%+v/%v calls=%d, want one approved request", operation, got, err, calls)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(progress, []string{"PAYMENT_PROCESSING", "FUTURE_OBSERVATIONAL_CODE"}) {
|
||||||
|
t.Errorf("Execute(%q) progress=%v, want observed codes in order", operation, progress)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type testTransport func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f testTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
|
||||||
|
type trackedBody struct {
|
||||||
|
io.Reader
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *trackedBody) Close() error { b.closed = true; return nil }
|
||||||
|
|
||||||
|
func TestExecuteRejectsIncompleteOrContradictoryResultsAndClosesBodies(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name, body string
|
||||||
|
status int
|
||||||
|
}{
|
||||||
|
{"eof", `{"type":"status","code":"PAYMENT_APPROVED"}`, 200},
|
||||||
|
{"malformed", `{"type":`, 200},
|
||||||
|
{"legacy", `{"type":"result","response":{"status":{"code":200},"data":"/successful"}}`, 200},
|
||||||
|
{"mixed", `{"type":"result","result":{"outcome":"approved","httpStatus":200},"response":{}}`, 200},
|
||||||
|
{"empty_status", `{"type":"status","code":""}`, 200},
|
||||||
|
{"status_result", `{"type":"status","code":"X","result":{"outcome":"approved","httpStatus":200}}`, 200},
|
||||||
|
{"unknown_frame", `{"type":"other"}`, 200},
|
||||||
|
{"unknown_outcome", `{"type":"result","result":{"outcome":"maybe","httpStatus":200}}`, 200},
|
||||||
|
{"invalid_status", `{"type":"result","result":{"outcome":"approved","httpStatus":0}}`, 200},
|
||||||
|
{"http_approval_conflict", `{"type":"result","result":{"outcome":"approved","httpStatus":200}}`, 502},
|
||||||
|
{"operation_approval_conflict", `{"type":"result","result":{"outcome":"approved","httpStatus":502}}`, 200},
|
||||||
|
{"retryable_approval", `{"type":"result","result":{"outcome":"approved","httpStatus":200,"retryable":true}}`, 200},
|
||||||
|
{"retryable_unknown", `{"type":"result","result":{"outcome":"unknown","httpStatus":200,"retryable":true}}`, 200},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
body := &trackedBody{Reader: strings.NewReader(test.body)}
|
||||||
|
calls := 0
|
||||||
|
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
return &http.Response{StatusCode: test.status, Header: http.Header{"Content-Type": []string{"application/x-ndjson"}}, Body: body}, nil
|
||||||
|
})}
|
||||||
|
_, err := Execute(context.Background(), client, "http://synthetic.invalid", Sale, Request{Amount: 100}, nil)
|
||||||
|
if err == nil || !body.closed || calls != 1 {
|
||||||
|
t.Errorf("Execute(%s) error=%v closed=%t calls=%d, want error/closed/one request", test.name, err, body.closed, calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteProgressCannotApproveOrRetryUnknown(t *testing.T) {
|
||||||
|
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) {
|
||||||
|
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/x-ndjson"}}, Body: io.NopCloser(strings.NewReader("{\"type\":\"status\",\"code\":\"PAYMENT_APPROVED\"}\n{\"type\":\"result\",\"result\":{\"outcome\":\"unknown\",\"httpStatus\":200}}"))}, nil
|
||||||
|
})}
|
||||||
|
got, err := Execute(context.Background(), client, "http://synthetic.invalid", Sale, Request{Amount: 100}, nil)
|
||||||
|
if err != nil || got.Outcome != "unknown" || got.Retryable {
|
||||||
|
t.Errorf("Execute(progress approved then unknown)=%+v/%v, want nonretryable unknown", got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecutePreservesCancellationWithoutLeakingTransportDiagnostics(t *testing.T) {
|
||||||
|
for _, cause := range []error{context.Canceled, context.DeadlineExceeded} {
|
||||||
|
t.Run(cause.Error(), func(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
return nil, fmt.Errorf("synthetic-private-payload: %w", cause)
|
||||||
|
})}
|
||||||
|
_, err := Execute(context.Background(), client, "http://synthetic.invalid", Sale, Request{Amount: 100}, nil)
|
||||||
|
if !errors.Is(err, cause) || strings.Contains(err.Error(), "synthetic-private-payload") || calls != 1 {
|
||||||
|
t.Errorf("Execute(transport %v)=%v calls=%d, want sanitized wrapped cause and one attempt", cause, err, calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteRejectsInvalidRequestsWithoutDispatch(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
operation string
|
||||||
|
amount int64
|
||||||
|
}{{Sale, 0}, {Sale, -1}, {Preauth, -1}, {"refund", 1}} {
|
||||||
|
calls := 0
|
||||||
|
client := &http.Client{Transport: testTransport(func(*http.Request) (*http.Response, error) { calls++; return nil, errors.New("must not dispatch") })}
|
||||||
|
_, err := Execute(context.Background(), client, "http://synthetic.invalid", test.operation, Request{Amount: test.amount}, nil)
|
||||||
|
if err == nil || calls != 0 {
|
||||||
|
t.Errorf("Execute(%q,%d) error=%v calls=%d, want validation error without dispatch", test.operation, test.amount, err, calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// Package paymentapi defines the modern Hardlink terminal contract and its HTTP client.
|
||||||
|
// It contains no provider selection, PMS posting or guest-journey logic.
|
||||||
|
package paymentapi
|
||||||
|
|
||||||
|
const (
|
||||||
|
Sale = "sale"
|
||||||
|
Preauth = "preauth"
|
||||||
|
SalePath = "/api/payment/sale"
|
||||||
|
PreauthPath = "/api/payment/preauth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PreauthRequirement describes a later required hold; validating it never executes it.
|
||||||
|
type PreauthRequirement struct {
|
||||||
|
Amount int64 `json:"amount"`
|
||||||
|
CheckoutDate string `json:"checkoutDate,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request uses integer minor units and currency supplied by CMS.
|
||||||
|
type Request struct {
|
||||||
|
Reference string `json:"reference,omitempty"`
|
||||||
|
Amount int64 `json:"amount"`
|
||||||
|
Currency string `json:"currency,omitempty"`
|
||||||
|
CheckoutDate string `json:"checkoutDate,omitempty"`
|
||||||
|
RequiredPreauth *PreauthRequirement `json:"requiredPreauth,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result is authoritative terminal outcome and metadata, never a PMS description.
|
||||||
|
// CurrencyCode is configured bookkeeping currency, not settlement-currency evidence.
|
||||||
|
type Result struct {
|
||||||
|
Outcome string `json:"outcome"`
|
||||||
|
HTTPStatus int `json:"httpStatus"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
Retryable bool `json:"retryable"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Provider string `json:"provider,omitempty"`
|
||||||
|
AmountMinor int64 `json:"amountMinor"`
|
||||||
|
CurrencyCode string `json:"currencyCode,omitempty"`
|
||||||
|
TransactionReference string `json:"transactionReference,omitempty"`
|
||||||
|
CardType string `json:"cardType,omitempty"`
|
||||||
|
MaskedCardNumber string `json:"maskedCardNumber,omitempty"`
|
||||||
|
ExpiryDate string `json:"expiryDate,omitempty"`
|
||||||
|
CardHash string `json:"cardHash,omitempty"`
|
||||||
|
CardReference string `json:"cardReference,omitempty"`
|
||||||
|
ReceiptNumber string `json:"receiptNumber,omitempty"`
|
||||||
|
SequenceNumber string `json:"sequenceNumber,omitempty"`
|
||||||
|
AuthorizationCode string `json:"authorizationCode,omitempty"`
|
||||||
|
LastFour string `json:"lastFour,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Frame carries observational progress or one final result.
|
||||||
|
type Frame struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Code string `json:"code,omitempty"`
|
||||||
|
Result *Result `json:"result,omitempty"`
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
// Package paymentstatus defines progress codes emitted by Hardlink's
|
// Package paymentstatus defines progress codes emitted by Hardlink's
|
||||||
// POST /api/payment/sale stream. These codes are not authoritative final
|
// modern Sale/PREAUTH streams. Progress codes are not final transaction decisions;
|
||||||
// transaction decisions: clients may continue check-in only after receiving a
|
// clients must use the structured result frame and their PMS completion rules.
|
||||||
// final result frame whose response.data begins with /successful.
|
|
||||||
package paymentstatus
|
package paymentstatus
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
+34
-7
@@ -1,6 +1,33 @@
|
|||||||
## Release notes
|
## Release notes
|
||||||
|
|
||||||
builtVersion is a const in main.go
|
`buildVersion` is a const in `cmd/hardlink/main.go`.
|
||||||
|
|
||||||
|
#### v2.2.5 - 16 November 2026
|
||||||
|
docs(payment): update CreditCall progress streaming behavior
|
||||||
|
|
||||||
|
#### 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
|
#### v2.1.2 - 30 September 2026
|
||||||
fix(dispenser): scan ACK responses without assuming 3-byte reads
|
fix(dispenser): scan ACK responses without assuming 3-byte reads
|
||||||
@@ -48,7 +75,7 @@ added pluggable PayBridge and Dojo payment flow with CMS credentials
|
|||||||
added PayBridge integration for payment processing functionality
|
added PayBridge integration for payment processing functionality
|
||||||
|
|
||||||
#### 1.2.10 - 26 June 2026
|
#### 1.2.10 - 26 June 2026
|
||||||
added voucher field to the guest receipt
|
added voucher field to the guest receipt
|
||||||
|
|
||||||
#### 1.2.9 - 02 June 2026
|
#### 1.2.9 - 02 June 2026
|
||||||
added Dormakaba lock server integration
|
added Dormakaba lock server integration
|
||||||
@@ -179,16 +206,16 @@ updated workflow for Salto locks
|
|||||||
added encoding keycard copy for Salto locks
|
added encoding keycard copy for Salto locks
|
||||||
|
|
||||||
#### 1.0.4 - 22 July 2025
|
#### 1.0.4 - 22 July 2025
|
||||||
added salto lock server and implemented workflow for Salto
|
added salto lock server and implemented workflow for Salto
|
||||||
|
|
||||||
#### 1.0.0 - 30 June 2025
|
#### 1.0.0 - 30 June 2025
|
||||||
added creditcall payment method
|
added creditcall payment method
|
||||||
`/starttransaction` - API payment endpoint to start a transaction
|
`/starttransaction` - API payment endpoint to start a transaction
|
||||||
|
|
||||||
#### 0.9.1 - 22 May 2025
|
#### 0.9.1 - 22 May 2025
|
||||||
added lockserver interface and implemented workflow for Omnitec
|
added lockserver interface and implemented workflow for Omnitec
|
||||||
|
|
||||||
#### 0.9.0 - 22 May 2025
|
#### 0.9.0 - 22 May 2025
|
||||||
The new API has two new endpoints:
|
The new API has two new endpoints:
|
||||||
- `/issuedoorcard` - encoding the door card for the room.
|
- `/issuedoorcard` - encoding the door card for the room.
|
||||||
- `/printroomticket` - printing the room ticket.
|
- `/printroomticket` - printing the room ticket.
|
||||||
|
|||||||
Reference in New Issue
Block a user