feat(hardlink): unify kiosk payments and finalize legacy cleanup

This commit is contained in:
2026-11-04 17:43:10 +00:00
parent 568adc034b
commit 814d87768d
57 changed files with 3624 additions and 1762 deletions
+17 -33
View File
@@ -33,7 +33,7 @@ import (
)
const (
buildVersion = "v2.1.5"
buildVersion = "v2.2.0"
serviceName = "hardlink"
pollingFrequency = 8 * time.Second
)
@@ -46,10 +46,6 @@ func main() {
lockserver.LockServerURL = cfg.LockserverURL
mail.SendErrorEmails = cfg.SendErrorEmails
// Root context for background goroutines
// rootCtx, rootCancel := context.WithCancel(context.Background())
// defer rootCancel()
var (
dispPort *serial.Port
disp *dispenser.Client
@@ -123,17 +119,22 @@ func main() {
log.Info("Payment processing is enabled")
var provider paymentsvc.Provider
reservationSystem, err := cms.ReadHotel(cfg.Hotel, cfg.CMSBaseURL)
hotel, err := cms.ReadHotelDetails(cfg.Hotel, cfg.CMSBaseURL)
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))
}
reservationSystem := hotel.ReservationSystem
paymentProvider := reservationSystem.PaymentSystem
if paymentProvider == 0 {
paymentProvider = cms.PaymentSystemIndex(cfg.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:
// CreditCall streaming shares its proven legacy transaction core.
app.EnableCreditCallStreaming()
@@ -152,9 +153,6 @@ func main() {
log.Infof("PDQ available: %v", pdqStatus.IsAvailable)
}()
log.Info("CreditCall payment provider enabled")
fmt.Println("CreditCall payment provider enabled")
case cmstypes.PaySystemPayBridge:
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"))
}
provider = paybridge.NewClient(
payBridgeClient := paybridge.NewClient(
websocketURL,
reservationSystem.PaymentGatewayAPIKeyWeb,
cfg.TimeoutSeconds,
)
payBridgeClient.PrintReceipt = printer.PrintSaleReceipt
provider = payBridgeClient
case cmstypes.PaySystemDojo:
TerminalID := pdqSerialForKiosk(reservationSystem.PDQs, cfg.Kiosk)
@@ -182,6 +182,7 @@ func main() {
}
dojoClient, err := dojo.NewClient(dojo.Config{
PrintReceipt: printer.PrintSaleReceipt,
BaseURL: reservationSystem.PaymentGatewayURL,
APIKey: reservationSystem.PaymentGatewayAPIKeyWeb,
SoftwareHouseID: reservationSystem.PaymentGatewaySiteIDEPOS,
@@ -195,21 +196,22 @@ func main() {
provider = dojoClient
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:
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,
))
}
// PayBridge and Dojo use the generic payment service.
// All modern endpoint providers use the same payment service.
if provider != nil {
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 {
fmt.Println("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() {
startClient := func() (*exec.Cmd, error) {
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
+236
View File
@@ -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(&notification); 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)
}
}
}
+36
View File
@@ -0,0 +1,36 @@
package main
import (
"errors"
"gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/handlers"
"gitea.futuresens.co.uk/futuresens/hardlink/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
}
+155
View File
@@ -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/cms"
"gitea.futuresens.co.uk/futuresens/hardlink/config"
"gitea.futuresens.co.uk/futuresens/hardlink/internal/handlers"
"gitea.futuresens.co.uk/futuresens/hardlink/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())
}
}