Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ffd814e076 | ||
|
|
b982698ccd | ||
|
|
af151fd389 | ||
|
|
20fcbe5499 | ||
|
|
c6c2b40f37 | ||
|
|
8f093159cd | ||
|
|
e1549dda2f | ||
|
|
163ac0e808 | ||
|
|
19cfbf185b | ||
|
|
48e2b6f568 | ||
|
|
eb80332c5a | ||
|
|
aeea755045 |
@@ -16,18 +16,20 @@ import (
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/handlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/printer"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/handlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer"
|
||||
)
|
||||
|
||||
const (
|
||||
buildVersion = "1.1.1"
|
||||
buildVersion = "1.2.9"
|
||||
serviceName = "hardlink"
|
||||
pollingFrequency = 8 * time.Second
|
||||
)
|
||||
@@ -38,7 +40,12 @@ func main() {
|
||||
printer.Layout = readTicketLayout()
|
||||
printer.PrinterName = cfg.PrinterName
|
||||
lockserver.Cert = cfg.Cert
|
||||
lockserver.LockServerURL = cfg.LockserverUrl
|
||||
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
|
||||
@@ -51,7 +58,9 @@ func main() {
|
||||
if err != nil {
|
||||
log.Printf("Failed to set up logging: %v\n", err)
|
||||
}
|
||||
defer logFile.Close()
|
||||
if logFile != nil {
|
||||
defer logFile.Close()
|
||||
}
|
||||
|
||||
// Initialize dispenser
|
||||
if !cfg.TestMode {
|
||||
@@ -60,21 +69,21 @@ func main() {
|
||||
|
||||
dispPort, err = dispenser.InitializeDispenser()
|
||||
if err != nil {
|
||||
mail.SendEmailOnError(cfg.Hotel, cfg.Kiosk, "Dispenser Initialization Error", fmt.Sprintf("Failed to initialize dispenser: %v", err))
|
||||
errorhandlers.FatalError(err)
|
||||
}
|
||||
defer dispPort.Close()
|
||||
|
||||
// Start queued dispenser client (single goroutine owns the serial port)
|
||||
disp = dispenser.NewClient(dispPort, 32)
|
||||
defer disp.Close()
|
||||
|
||||
// Prepare dispenser (ensures card at encoder position unless empty)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cardWellStatus, err = disp.DispenserPrepare(ctx)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("%s; wrong dispenser address: %s", err, cfg.DispenserAdrr)
|
||||
mail.SendEmailOnError(cfg.Hotel, cfg.Kiosk, "Dispenser Preparation Error", err.Error())
|
||||
errorhandlers.FatalError(err)
|
||||
}
|
||||
fmt.Println(cardWellStatus)
|
||||
@@ -83,15 +92,16 @@ func main() {
|
||||
// Test lock-server connection
|
||||
switch strings.ToLower(cfg.LockType) {
|
||||
case lockserver.TLJ:
|
||||
// TLJ uses HTTP - skip TCP probe here (as you did before)
|
||||
// TLJ uses HTTP - skip TCP probe here
|
||||
default:
|
||||
lockConn, err := lockserver.InitializeServerConnection(cfg.LockserverUrl)
|
||||
lockConn, err := lockserver.InitializeServerConnection(cfg.LockserverURL)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
log.Errorf(err.Error())
|
||||
mail.SendEmailOnError(cfg.Hotel, cfg.Kiosk, "Lock Server Connection Error", err.Error())
|
||||
} else {
|
||||
fmt.Printf("Connected to the lock server successfuly at %s\n", cfg.LockserverUrl)
|
||||
log.Infof("Connected to the lock server successfuly at %s", cfg.LockserverUrl)
|
||||
fmt.Printf("Connected to the lock server successfuly at %s\n", cfg.LockserverURL)
|
||||
log.Infof("Connected to the lock server successfuly at %s", cfg.LockserverURL)
|
||||
lockConn.Close()
|
||||
}
|
||||
}
|
||||
@@ -100,23 +110,37 @@ func main() {
|
||||
if err != nil {
|
||||
log.Warnf("DB init failed: %v", err)
|
||||
}
|
||||
defer database.Close()
|
||||
if database != nil {
|
||||
defer database.Close()
|
||||
}
|
||||
|
||||
if cfg.IsPayment {
|
||||
fmt.Println("Payment processing is enabled")
|
||||
log.Info("Payment processing is enabled")
|
||||
|
||||
startChipDnaClient()
|
||||
|
||||
// check ChipDNA and PDQ status and log any errors, but continue running even if it fails
|
||||
go func() {
|
||||
time.Sleep(30 * time.Second) // give ChipDNA client a moment to start
|
||||
pdqstatus, err := payment.ReadPdqStatus(cfg.Hotel, cfg.Kiosk)
|
||||
if err != nil {
|
||||
mail.SendEmailOnError(cfg.Hotel, cfg.Kiosk, "PDQ Status Read Error", err.Error())
|
||||
} else {
|
||||
fmt.Printf("\nPDQ availabile: %v\n", pdqstatus.IsAvailable)
|
||||
log.Infof("PDQ availabile: %v", pdqstatus.IsAvailable)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
fmt.Println("Payment processing is disabled")
|
||||
log.Info("Payment processing is disabled")
|
||||
}
|
||||
|
||||
// Create App and wire routes
|
||||
// NOTE: change handlers.NewApp signature to accept *dispenser.Client instead of *serial.Port
|
||||
app := handlers.NewApp(disp, cfg.LockType, cfg.EncoderAddress, cardWellStatus, database, &cfg)
|
||||
|
||||
// Update cardWellStatus when dispenser status changes
|
||||
if !cfg.TestMode {
|
||||
if !cfg.TestMode && disp != nil {
|
||||
// Set initial cardWellStatus
|
||||
app.SetCardWellStatus(cardWellStatus)
|
||||
|
||||
@@ -181,6 +205,7 @@ func startChipDnaClient() {
|
||||
err := cmd.Wait()
|
||||
if err != nil {
|
||||
log.Errorf("ChipDnaClient exited unexpectedly: %v", err)
|
||||
fmt.Printf("ChipDnaClient exited unexpectedly: %v", err)
|
||||
time.Sleep(2 * time.Second)
|
||||
cmd, err = startClient()
|
||||
if err != nil {
|
||||
@@ -188,6 +213,7 @@ func startChipDnaClient() {
|
||||
return
|
||||
}
|
||||
log.Info("ChipDnaClient restarted successfully")
|
||||
fmt.Printf("ChipDnaClient restarted successfully")
|
||||
}
|
||||
}
|
||||
}()
|
||||
+22
-18
@@ -1,3 +1,4 @@
|
||||
// Package config handles reading and parsing configuration from config.yml.
|
||||
package config
|
||||
|
||||
import (
|
||||
@@ -5,31 +6,34 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
||||
log "github.com/sirupsen/logrus"
|
||||
yaml "gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// configRec holds values from config.yml.
|
||||
// ConfigRec holds values from config.yml.
|
||||
type ConfigRec struct {
|
||||
Port int `yaml:"port"`
|
||||
LockserverUrl string `yaml:"lockservUrl"`
|
||||
LockType string `yaml:"lockType"`
|
||||
EncoderAddress string `yaml:"encoderAddr"`
|
||||
Cert string `yaml:"cert"`
|
||||
DispenserPort string `yaml:"dispensPort"`
|
||||
DispenserAdrr string `yaml:"dispensAddr"`
|
||||
PrinterName string `yaml:"printerName"`
|
||||
LogDir string `yaml:"logdir"`
|
||||
Dbport int `yaml:"dbport"` // Port for the database connection
|
||||
Dbname string `yaml:"dbname"` // Database name for the connection
|
||||
Dbuser string `yaml:"dbuser"` // User for the database connection
|
||||
Dbpassword string `yaml:"dbpassword"` // Password for the database connection
|
||||
IsPayment bool `yaml:"isPayment"`
|
||||
TestMode bool `yaml:"testMode"`
|
||||
Port int `yaml:"port"`
|
||||
LockserverURL string `yaml:"lockservUrl"`
|
||||
LockType string `yaml:"lockType"`
|
||||
EncoderAddress string `yaml:"encoderAddr"`
|
||||
Cert string `yaml:"cert"`
|
||||
DispenserPort string `yaml:"dispensPort"`
|
||||
DispenserAdrr string `yaml:"dispensAddr"`
|
||||
PrinterName string `yaml:"printerName"`
|
||||
LogDir string `yaml:"logdir"`
|
||||
Dbport int `yaml:"dbport"` // Port for the database connection
|
||||
Dbname string `yaml:"dbname"` // Database name for the connection
|
||||
Dbuser string `yaml:"dbuser"` // User for the database connection
|
||||
Dbpassword string `yaml:"dbpassword"` // Password for the database connection
|
||||
IsPayment bool `yaml:"isPayment"`
|
||||
TestMode bool `yaml:"testMode"`
|
||||
Hotel string `yaml:"hotel"`
|
||||
Kiosk int `yaml:"kiosk"`
|
||||
SendErrorEmails []string `yaml:"senderroremails"`
|
||||
}
|
||||
|
||||
// ReadConfig reads config.yml and applies defaults.
|
||||
// ReadHardlinkConfig reads config.yml and applies defaults.
|
||||
func ReadHardlinkConfig() ConfigRec {
|
||||
var cfg ConfigRec
|
||||
const configName = "config.yml"
|
||||
|
||||
@@ -7,6 +7,7 @@ require (
|
||||
gitea.futuresens.co.uk/futuresens/logging v1.0.9
|
||||
github.com/alexbrainman/printer v0.0.0-20200912035444-f40f26f0bdeb
|
||||
github.com/denisenkom/go-mssqldb v0.12.3
|
||||
github.com/mailjet/mailjet-apiv3-go v0.0.0-20201009050126-c24bc15a9394
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
|
||||
golang.org/x/image v0.27.0
|
||||
|
||||
@@ -19,6 +19,8 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZ
|
||||
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
|
||||
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
|
||||
github.com/mailjet/mailjet-apiv3-go v0.0.0-20201009050126-c24bc15a9394 h1:+6kiV40vfmh17TDlZG15C2uGje1/XBGT32j6xKmUkqM=
|
||||
github.com/mailjet/mailjet-apiv3-go v0.0.0-20201009050126-c24bc15a9394/go.mod h1:ogN8Sxy3n5VKLhQxbtSBM3ICG/VgjXS/akQJIoDSrgA=
|
||||
github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8=
|
||||
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
)
|
||||
|
||||
const serviceName = "hardlink"
|
||||
|
||||
func writeTransactionResult(w http.ResponseWriter, status int, theResponse cmstypes.ResponseRec) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(theResponse); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "JSON encode error", "startTransaction", "", "", 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,10 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"database/sql"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db"
|
||||
)
|
||||
|
||||
func OpenDB(cfg *config.ConfigRec) (*sql.DB, error) {
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
mssqldb "github.com/denisenkom/go-mssqldb" // for error inspection
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
)
|
||||
|
||||
// InitMSSQL opens and pings the SQL Server instance (keeps your original behaviour)
|
||||
@@ -37,6 +37,7 @@ var (
|
||||
0x32: "Preparing card fails",
|
||||
0x31: "Preparing card",
|
||||
0x30: "Normal",
|
||||
0x36: "Command cannot execute; Preparing card fails",
|
||||
}
|
||||
statusPos1 = map[byte]string{
|
||||
0x38: "Dispensing card",
|
||||
@@ -87,7 +88,7 @@ func logStatus(statusBytes []byte) {
|
||||
for _, p := range posStatus {
|
||||
statusMsg, exists := p.mapper[p.value]
|
||||
if !exists {
|
||||
statusMsg = fmt.Sprintf("Unknown status 0x%X", p.value)
|
||||
statusMsg = fmt.Sprintf("Unknown status 0x%X at position %d", p.value, p.pos)
|
||||
}
|
||||
if p.value != 0x30 {
|
||||
result.WriteString(statusMsg + "; ")
|
||||
@@ -105,6 +106,9 @@ func stockTake(statusBytes []byte) string {
|
||||
return ""
|
||||
}
|
||||
status := ""
|
||||
if statusBytes[0] == 0x32 || statusBytes[0] == 0x36 {
|
||||
status = statusPos0[statusBytes[0]]
|
||||
}
|
||||
if statusBytes[2] != 0x30 {
|
||||
status = statusPos2[statusBytes[2]]
|
||||
}
|
||||
@@ -178,7 +182,7 @@ func InitializeDispenser() (*serial.Port, error) {
|
||||
const (
|
||||
funcName = "InitializeDispenser"
|
||||
maxRetries = 3
|
||||
retryDelay = 2 * time.Second
|
||||
retryDelay = 4 * time.Second
|
||||
)
|
||||
|
||||
if SerialPort == "" {
|
||||
@@ -1,6 +1,4 @@
|
||||
// --------------------
|
||||
// Queue-based client (single owner of port)
|
||||
// --------------------
|
||||
// Package dispenser provides a queue-based client (single owner of port).
|
||||
package dispenser
|
||||
|
||||
import (
|
||||
@@ -74,7 +72,7 @@ func (c *Client) Close() {
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: tune cache TTL (how "fresh" cached status must be)
|
||||
// SetStatusTTL sets the duration for which cached status is considered fresh.
|
||||
func (c *Client) SetStatusTTL(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
c.statusTTL = d
|
||||
@@ -233,7 +231,7 @@ func (c *Client) OutOfMouth(ctx context.Context) error {
|
||||
// Public sequences updated to use Client (queue)
|
||||
// --------------------
|
||||
|
||||
// DispenserPrepare: check status; if empty => ok; else ensure at encoder.
|
||||
// DispenserPrepare checks status; if empty => ok; else ensure at encoder.
|
||||
func (c *Client) DispenserPrepare(ctx context.Context) (string, error) {
|
||||
const funcName = "DispenserPrepare"
|
||||
stockStatus := ""
|
||||
@@ -279,7 +277,9 @@ func (c *Client) DispenserStart(ctx context.Context) (string, error) {
|
||||
return stockStatus, fmt.Errorf("[%s] check status: %w", funcName, err)
|
||||
}
|
||||
|
||||
logStatus(status)
|
||||
defer func() {
|
||||
logStatus(status)
|
||||
}()
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
@@ -294,48 +294,87 @@ func (c *Client) DispenserStart(ctx context.Context) (string, error) {
|
||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
status, err = c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] re-check status: %w", funcName, err)
|
||||
}
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
halfway := time.Now().Add(6 * time.Second)
|
||||
deadline := time.Now().Add(12 * time.Second)
|
||||
|
||||
return stockStatus, nil
|
||||
for {
|
||||
time.Sleep(delay * 2)
|
||||
switch {
|
||||
case time.Now().After(halfway):
|
||||
if err := c.ToEncoder(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||
}
|
||||
case time.Now().After(deadline):
|
||||
return stockStatus, nil
|
||||
}
|
||||
|
||||
status, _ = c.do(ctx, cmdStatus)
|
||||
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
logStatus(status)
|
||||
|
||||
// error states first
|
||||
if isCardWellEmpty(status) {
|
||||
return stockStatus, fmt.Errorf(stockStatus)
|
||||
}
|
||||
|
||||
if isAtEncoderPosition(status) {
|
||||
return stockStatus, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) DispenserFinal(ctx context.Context) (string, error) {
|
||||
const funcName = "DispenserFinal"
|
||||
stockStatus := ""
|
||||
var status []byte
|
||||
|
||||
if err := c.OutOfMouth(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] out of mouth: %w", funcName, err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
status, err := c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] check status: %w", funcName, err)
|
||||
status, err := c.do(ctx, cmdStatus)
|
||||
if err == nil && len(status) >= 4 {
|
||||
c.setStock(status)
|
||||
}
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
time.Sleep(delay)
|
||||
if err := c.ToEncoder(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
status, err = c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] re-check status: %w", funcName, err)
|
||||
}
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
defer func() {
|
||||
logStatus(status)
|
||||
}()
|
||||
|
||||
return stockStatus, nil
|
||||
halfway := time.Now().Add(6 * time.Second)
|
||||
deadline := time.Now().Add(12 * time.Second)
|
||||
|
||||
for {
|
||||
time.Sleep(delay * 2)
|
||||
switch {
|
||||
case time.Now().After(halfway):
|
||||
if err := c.ToEncoder(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||
}
|
||||
case time.Now().After(deadline):
|
||||
return stockStatus, nil
|
||||
}
|
||||
|
||||
status, _ = c.do(ctx, cmdStatus)
|
||||
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
logStatus(status)
|
||||
|
||||
if isCardWellEmpty(status) {
|
||||
return stockStatus, nil
|
||||
}
|
||||
|
||||
if isAtEncoderPosition(status) {
|
||||
return stockStatus, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,6 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const serviceName = "hardlink"
|
||||
|
||||
// writeError is a helper to send a JSON error and HTTP status in one go.
|
||||
func WriteError(w http.ResponseWriter, status int, msg string) {
|
||||
theResponse := cmstypes.StatusRec{
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
@@ -14,34 +13,38 @@ import (
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/printer"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
disp *dispenser.Client
|
||||
lockserver lockserver.LockServer
|
||||
isPayment bool
|
||||
db *sql.DB
|
||||
cfg *config.ConfigRec
|
||||
dbMu sync.Mutex
|
||||
cardWellMu sync.RWMutex
|
||||
cardWellStatus string
|
||||
disp *dispenser.Client
|
||||
lockserver lockserver.LockServer
|
||||
isPayment bool
|
||||
db *sql.DB
|
||||
cfg *config.ConfigRec
|
||||
dbMu sync.Mutex
|
||||
cardWellMu sync.RWMutex
|
||||
cardWellStatus string
|
||||
availabilityMu sync.Mutex
|
||||
availabilityTimers map[string]*time.Timer
|
||||
}
|
||||
|
||||
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
||||
app := &App{
|
||||
isPayment: cfg.IsPayment,
|
||||
disp: disp,
|
||||
lockserver: lockserver.NewLockServer(lockType, encoderAddress, errorhandlers.FatalError),
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
isPayment: cfg.IsPayment,
|
||||
disp: disp,
|
||||
lockserver: lockserver.NewLockServer(lockType, encoderAddress, errorhandlers.FatalError),
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
availabilityTimers: make(map[string]*time.Timer),
|
||||
}
|
||||
app.SetCardWellStatus(cardWellStatus)
|
||||
return app
|
||||
@@ -53,10 +56,14 @@ func (app *App) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/takepreauth", app.takePreauthorization)
|
||||
mux.HandleFunc("/takepayment", app.takePayment)
|
||||
mux.HandleFunc("/dispenserstatus", app.reportDispenserStatus)
|
||||
mux.HandleFunc("/testissuedoorcard", app.testIssueDoorCard)
|
||||
mux.HandleFunc("/ping-pdq", app.fetchChipDNAStatus)
|
||||
mux.HandleFunc("/logerror", app.onChipDNAError)
|
||||
}
|
||||
|
||||
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("takePreauthorization")
|
||||
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
theRequest cmstypes.TransactionRec
|
||||
@@ -74,9 +81,12 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if !app.isPayment {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
if !app.cfg.TestMode {
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Error", "Attempted preauthorization while payment processing is disabled")
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
@@ -90,55 +100,64 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
writeTransactionResult(w, http.StatusMethodNotAllowed, theResponse)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "text/xml" {
|
||||
if r.Header.Get("Content-Type") != "text/xml" {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Content-Type must be text/xml")
|
||||
writeTransactionResult(w, http.StatusUnsupportedMediaType, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
err := xml.Unmarshal(body, &theRequest)
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Read body error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Failed to read request body")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := xml.Unmarshal(body, &theRequest); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Invalid XML payload")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
log.Printf("Transaction payload: Amount=%s, Type=%s", theRequest.AmountMinorUnits, theRequest.TransactionType)
|
||||
|
||||
log.Printf(
|
||||
"Preauthorization payload: Amount=%s, Type=%s",
|
||||
theRequest.AmountMinorUnits,
|
||||
theRequest.TransactionType,
|
||||
)
|
||||
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
response, err := client.Post(types.LinkTakePreauthorization, "text/xml", bytes.NewBuffer(body))
|
||||
|
||||
// ---- START TRANSACTION ----
|
||||
|
||||
body, err = callChipDNA(client, types.LinkStartTransaction, body)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
||||
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "No response from payment processor")
|
||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
body, err = io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Read response body error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Failed to read response body")
|
||||
writeTransactionResult(w, http.StatusInternalServerError, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||
}
|
||||
|
||||
// Compose JSON from responseEntries
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
if err := printer.PrintCardholderReceipt(result.CardholderReceipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
}
|
||||
// ---- PRINT RECEIPT ----
|
||||
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
|
||||
// ---- REDIRECT ----
|
||||
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data, save = payment.BuildPreauthRedirectURL(result.Fields)
|
||||
|
||||
if save {
|
||||
go app.persistPreauth(context.Background(), result.Fields, theRequest.CheckoutDate)
|
||||
}
|
||||
@@ -148,6 +167,7 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("takePayment")
|
||||
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
theRequest cmstypes.TransactionRec
|
||||
@@ -164,9 +184,14 @@ func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if !app.isPayment {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
if !app.cfg.TestMode {
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Error", "Attempted payment while payment processing is disabled")
|
||||
theResponse.Status.Code = http.StatusServiceUnavailable
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
@@ -180,55 +205,118 @@ func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||
writeTransactionResult(w, http.StatusMethodNotAllowed, theResponse)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "text/xml" {
|
||||
if r.Header.Get("Content-Type") != "text/xml" {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Content-Type must be text/xml")
|
||||
writeTransactionResult(w, http.StatusUnsupportedMediaType, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
err := xml.Unmarshal(body, &theRequest)
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Read body error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Failed to read request body")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := xml.Unmarshal(body, &theRequest); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Invalid XML payload")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
log.Printf("Transaction payload: Amount=%s, Type=%s", theRequest.AmountMinorUnits, theRequest.TransactionType)
|
||||
|
||||
log.Printf("Transaction payload: Amount=%s, Type=%s",
|
||||
theRequest.AmountMinorUnits,
|
||||
theRequest.TransactionType,
|
||||
)
|
||||
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
response, err := client.Post(types.LinkTakePayment, "text/xml", bytes.NewBuffer(body))
|
||||
|
||||
// ---- START TRANSACTION ----
|
||||
|
||||
body, err = callChipDNA(client, types.LinkStartTransaction, body)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Start transaction error", string(op), "", "", 0)
|
||||
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "No response from payment processor")
|
||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
body, err = io.ReadAll(response.Body)
|
||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||
}
|
||||
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
res := result.Fields[types.TransactionResult]
|
||||
|
||||
if !strings.EqualFold(res, types.ResultApproved) {
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
desc := result.Fields[types.ErrorDescription]
|
||||
if desc == "" {
|
||||
desc = result.Fields[types.Errors]
|
||||
}
|
||||
logging.Error(types.ServiceName, "Preauthorization failed", "Result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildFailureURL(res, result.Fields[types.Errors])
|
||||
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
// ---- CONFIRM TRANSACTION ----
|
||||
|
||||
ref := result.Fields[types.Reference]
|
||||
log.Printf("Preauth approved, reference: %s. Sending confirm...", ref)
|
||||
confirmReq := payment.ConfirmTransactionRequest{
|
||||
Amount: theRequest.AmountMinorUnits,
|
||||
Reference: ref,
|
||||
}
|
||||
|
||||
body, err = confirmWithRetry(client, confirmReq, 2)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Read response body error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Failed to read response body")
|
||||
writeTransactionResult(w, http.StatusInternalServerError, theResponse)
|
||||
logging.Error(types.ServiceName, err.Error(), "Confirm transaction error", string(op), "", "", 0)
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error())
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "ConfirmTransactionError")
|
||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse confirm result error", string(op), "", "", 0)
|
||||
}
|
||||
|
||||
// Compose JSON from responseEntries
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
if err := printer.PrintCardholderReceipt(result.CardholderReceipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
res = result.Fields[types.TransactionResult]
|
||||
|
||||
if !strings.EqualFold(res, types.ResultApproved) {
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
desc := result.Fields[types.ErrorDescription]
|
||||
if desc == "" {
|
||||
desc = result.Fields[types.Errors]
|
||||
}
|
||||
logging.Error(types.ServiceName, "Transaction not approved after confirm", "Confirm result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc)
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildFailureURL(res, result.Fields[types.Errors])
|
||||
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
// ---- SUCCESS ----
|
||||
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
log.Printf("Transaction approved and confirmed, reference: %s", ref)
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildPaymentRedirectURL(result.Fields)
|
||||
theResponse.Data = payment.BuildSuccessURL(result.Fields)
|
||||
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
}
|
||||
|
||||
@@ -262,7 +350,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadJSON", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadJSON", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -270,13 +358,13 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
// parse times
|
||||
checkIn, err := time.Parse(types.CustomLayout, doorReq.CheckinTime)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid checkinTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
checkOut, err := time.Parse(types.CustomLayout, doorReq.CheckoutTime)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Invalid checkoutTime format", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Invalid checkoutTime format", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid checkoutTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -286,7 +374,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
status, err := app.disp.DispenserStart(r.Context())
|
||||
app.SetCardWellStatus(status)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -302,7 +390,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
status, ferr := app.disp.DispenserFinal(ctx)
|
||||
if ferr != nil {
|
||||
logging.Error(serviceName, ferr.Error(), "Dispenser final error", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, ferr.Error(), "Dispenser final error", string(op), "", "", 0)
|
||||
return
|
||||
}
|
||||
app.SetCardWellStatus(status)
|
||||
@@ -313,7 +401,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// lock server sequence
|
||||
if err := app.lockserver.LockSequence(); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
finalize()
|
||||
errorhandlers.WriteError(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
@@ -352,21 +440,21 @@ func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
defer r.Body.Close()
|
||||
if err := xml.NewDecoder(r.Body).Decode(&roomDetails); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid XML payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
data, err := printer.BuildRoomTicket(roomDetails)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "BuildRoomTicket", string(op), "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "BuildRoomTicket", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusInternalServerError, "BuildRoomTicket failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Send to the Windows Epson TM-T82II via the printer package
|
||||
if err := printer.SendToPrinter(data); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "printRoomTicket", "printRoomTicket", "", "", 0)
|
||||
logging.Error(types.ServiceName, err.Error(), "printRoomTicket", "printRoomTicket", "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusInternalServerError, "Print failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -391,8 +479,13 @@ func (app *App) reportDispenserStatus(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (app *App) SetCardWellStatus(s string) {
|
||||
app.cardWellMu.Lock()
|
||||
prev := app.cardWellStatus
|
||||
app.cardWellStatus = s
|
||||
app.cardWellMu.Unlock()
|
||||
|
||||
if s != "" && prev != s {
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Dispenser Error Status", "Status: "+s)
|
||||
}
|
||||
}
|
||||
|
||||
func (app *App) CardWellStatus() string {
|
||||
@@ -0,0 +1,71 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func writeTransactionResult(w http.ResponseWriter, status int, theResponse cmstypes.ResponseRec) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(theResponse); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "JSON encode error", "startTransaction", "", "", 0)
|
||||
}
|
||||
}
|
||||
|
||||
func callChipDNA(client *http.Client, url string, payload []byte) ([]byte, error) {
|
||||
|
||||
resp, err := client.Post(url, "text/xml", bytes.NewBuffer(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func confirmWithRetry(client *http.Client, req payment.ConfirmTransactionRequest, attempts int) ([]byte, error) {
|
||||
|
||||
payload, err := xml.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
|
||||
for i := 1; i <= attempts; i++ {
|
||||
|
||||
resp, err := client.Post(types.LinkConfirmTransaction, "text/xml", bytes.NewBuffer(payload))
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
} else {
|
||||
|
||||
body, readErr := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if readErr != nil {
|
||||
lastErr = readErr
|
||||
} else {
|
||||
return body, nil
|
||||
}
|
||||
}
|
||||
|
||||
log.Warnf("ConfirmTransaction attempt %d/%d failed: %v", i, attempts, lastErr)
|
||||
|
||||
if i < attempts {
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
return nil, lastErr
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (app *App) testIssueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("issueDoorCard")
|
||||
var (
|
||||
doorReq lockserver.DoorCardRequest
|
||||
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")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("issueDoorCard called")
|
||||
if r.Method != http.MethodPost {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
errorhandlers.WriteError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadJSON", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
checkIn := time.Date(now.Year(), now.Month(), now.Day(), 23, 0, 0, 0, now.Location())
|
||||
checkOut := checkIn.Add(2 * time.Hour)
|
||||
|
||||
// Ensure dispenser ready (card at encoder) BEFORE we attempt encoding.
|
||||
// With queued dispenser ops, this will not clash with polling.
|
||||
status, err := app.disp.DispenserStart(r.Context())
|
||||
app.SetCardWellStatus(status)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
|
||||
// lock server sequence
|
||||
if err := app.lockserver.LockSequence(); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = "Card issued successfully"
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
func (app *App) fetchChipDNAStatus(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("fetchChipDNAStatus")
|
||||
var 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")
|
||||
status, err := payment.ReadPdqStatus(app.cfg.Hotel, app.cfg.Kiosk)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "fetchChipDNAStatus", string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, err.Error())
|
||||
return
|
||||
}
|
||||
b, err := json.MarshalIndent(status, "", " ")
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "MarshalIndent", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusInternalServerError, "Failed to marshal status data")
|
||||
return
|
||||
}
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = string(b)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
func (app *App) onChipDNAError(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("onChipDNAError")
|
||||
var tr payment.TransactionResultXML
|
||||
title := "ChipDNA Error"
|
||||
message := ""
|
||||
|
||||
log.Println("onChipDNAError called")
|
||||
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")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
message = "Failed to read request body: " + err.Error()
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, message)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Unable to read request body")
|
||||
return
|
||||
}
|
||||
|
||||
if len(body) == 0 {
|
||||
message = "Received empty request body"
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, message)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Empty body")
|
||||
return
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(
|
||||
types.ServiceName,
|
||||
err.Error(),
|
||||
"Parse transaction result error",
|
||||
string(op),
|
||||
"",
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
)
|
||||
message = "Failed to parse transaction result: " + err.Error()
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, message)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid XML")
|
||||
return
|
||||
}
|
||||
|
||||
for _, e := range tr.Entries {
|
||||
|
||||
switch e.Key {
|
||||
|
||||
case payment.KeyErrors:
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, e.Value)
|
||||
|
||||
case payment.KeyIsAvailable:
|
||||
isAvailable := strings.EqualFold(e.Value, "true")
|
||||
app.handleAvailabilityDebounced(isAvailable)
|
||||
}
|
||||
|
||||
logging.Error(
|
||||
types.ServiceName,
|
||||
e.Value,
|
||||
e.Key,
|
||||
string(op),
|
||||
"",
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"status":"received"}`))
|
||||
}
|
||||
|
||||
func (app *App) handleAvailabilityDebounced(isAvailable bool) {
|
||||
const (
|
||||
debounceDay = 30
|
||||
debounceNight = 600
|
||||
title = "ChipDNA Error"
|
||||
)
|
||||
|
||||
key := app.availabilityKey()
|
||||
|
||||
app.availabilityMu.Lock()
|
||||
defer app.availabilityMu.Unlock()
|
||||
|
||||
// If device becomes available -> cancel pending timer
|
||||
if isAvailable {
|
||||
if t, exists := app.availabilityTimers[key]; exists {
|
||||
t.Stop()
|
||||
delete(app.availabilityTimers, key)
|
||||
log.Println("PDQ availability restored - debounce timer cancelled")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Device became unavailable -> start 10s debounce if not already started
|
||||
if _, exists := app.availabilityTimers[key]; exists {
|
||||
return
|
||||
}
|
||||
|
||||
debounce := debounceDay
|
||||
|
||||
hour := time.Now().Hour()
|
||||
if hour < 6 {
|
||||
debounce = debounceNight
|
||||
}
|
||||
|
||||
log.Printf("PDQ reported unavailable - starting %ds debounce timer", debounce)
|
||||
|
||||
timer := time.AfterFunc(time.Duration(debounce)*time.Second, func() {
|
||||
mail.SendEmailOnError(
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
title,
|
||||
fmt.Sprintf("ChipDNA PDQ unavailable for more than %d seconds", debounce),
|
||||
)
|
||||
|
||||
app.availabilityMu.Lock()
|
||||
delete(app.availabilityTimers, key)
|
||||
app.availabilityMu.Unlock()
|
||||
})
|
||||
|
||||
app.availabilityTimers[key] = timer
|
||||
}
|
||||
|
||||
func (app *App) availabilityKey() string {
|
||||
return fmt.Sprintf("hotel=%s|kiosk=%d|app=%p",
|
||||
strings.TrimSpace(app.cfg.Hotel),
|
||||
app.cfg.Kiosk,
|
||||
app,
|
||||
)
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
// Package lockserver provides functionality for interacting with Assa Abloy lock servers.
|
||||
package lockserver
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
"strings"
|
||||
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Build key encoding request command for the Assa Abloy lock server.
|
||||
// BuildCommand builds a key encoding request command for the Assa Abloy lock server.
|
||||
func (lock *AssaLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error {
|
||||
ci := checkIn.Format("200601021504")
|
||||
co := checkOut.Format("200601021504")
|
||||
@@ -18,7 +19,7 @@ func (lock *AssaLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, check
|
||||
return nil
|
||||
}
|
||||
|
||||
// Checks heart beat of the Assa Abloy lock server and perform key encoding
|
||||
// LockSequence checks heartbeat of the Assa Abloy lock server and performs key encoding
|
||||
func (lock *AssaLockServer) LockSequence() error {
|
||||
const funcName = "AssaLockServer.LockSequence"
|
||||
|
||||
@@ -71,4 +72,3 @@ func parseAssaResponse(raw string) (string, error) {
|
||||
}
|
||||
return "Success: " + clean, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package lockserver
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
kabaSTX = 0x02
|
||||
kabaETX = 0x03
|
||||
kabaACK = 0x06
|
||||
kabaNAK = 0x15
|
||||
)
|
||||
|
||||
// BuildCommand builds a key encoding request command for the dormakaba/Kaba lock server.
|
||||
// KR|KTD|WS192.168.135.20|KC2|RN41|KO000000|GA241213|TI16:56|GD241214|DT11:00|G#75|
|
||||
func (lock *KabaLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error {
|
||||
const funcName = "DormakabaLockServer.BuildCommand"
|
||||
|
||||
room := strings.TrimSpace(doorReq.RoomField)
|
||||
if room == "" {
|
||||
return fmt.Errorf("[%s] roomField is required", funcName)
|
||||
}
|
||||
|
||||
if checkIn.IsZero() {
|
||||
return fmt.Errorf("[%s] checkin time is required", funcName)
|
||||
}
|
||||
|
||||
if checkOut.IsZero() {
|
||||
return fmt.Errorf("[%s] checkout time is required", funcName)
|
||||
}
|
||||
|
||||
ws := dormakabaWorkstationID()
|
||||
|
||||
ga := checkIn.Format("060102") // yyMMdd, example: 241213
|
||||
gd := checkOut.Format("060102") // yyMMdd, example: 241214
|
||||
ti := checkIn.Format("15:04") // HH:mm, example: 16:56
|
||||
dt := checkOut.Format("15:04") // HH:mm, example: 11:00
|
||||
|
||||
payload := fmt.Sprintf(
|
||||
"KR|KTD|WS%s|KC%s|RN%s|KO000000|GA%s|TI%s|GD%s|DT%s|G#75|",
|
||||
ws,
|
||||
lock.encoderAddr,
|
||||
room,
|
||||
ga,
|
||||
ti,
|
||||
gd,
|
||||
dt,
|
||||
)
|
||||
|
||||
lock.command = wrapKabaFrame(payload)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LockSequence starts the link and performs key encoding.
|
||||
func (lock *KabaLockServer) LockSequence() error {
|
||||
const funcName = "KabaLockServer.LockSequence"
|
||||
|
||||
conn, err := InitializeServerConnection(LockServerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
reader := bufio.NewReader(conn)
|
||||
|
||||
regs, err := lock.linkStart(conn, reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%s] linkStart failed: %v", funcName, err)
|
||||
}
|
||||
|
||||
for _, reg := range regs {
|
||||
log.Printf("Received: %q", reg)
|
||||
}
|
||||
|
||||
raw, err := lock.requestEncoding(conn, reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%s] request encoding failed: %v", funcName, err)
|
||||
}
|
||||
|
||||
log.Infof("Encoding response: %s", raw)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// linkStart sends the dormakaba/Kaba LS command.
|
||||
// LS|DA241213|TI165607|WS192.168.135.20|PW1234|
|
||||
func (lock *KabaLockServer) linkStart(conn net.Conn, reader *bufio.Reader) ([]string, error) {
|
||||
ws := dormakabaWorkstationID()
|
||||
pw := dormakabaPassword()
|
||||
|
||||
payload := fmt.Sprintf(
|
||||
"LS|DA%s|TI%s|WS%s|PW%s|",
|
||||
time.Now().Format("060102"), // yyMMdd
|
||||
time.Now().Format("150405"), // HHmmss
|
||||
ws,
|
||||
pw,
|
||||
)
|
||||
|
||||
command := wrapKabaFrame(payload)
|
||||
|
||||
log.Printf("Sending Link Start command: %q", command)
|
||||
|
||||
if _, err := conn.Write(command); err != nil {
|
||||
return nil, fmt.Errorf("failed to send Link Start command: %v", err)
|
||||
}
|
||||
|
||||
var registers []string
|
||||
timeout := 10 * time.Second
|
||||
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
|
||||
b, err := reader.ReadByte()
|
||||
if err != nil {
|
||||
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
if len(registers) > 0 {
|
||||
return registers, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("error reading Link Start response: %v", err)
|
||||
}
|
||||
|
||||
switch b {
|
||||
case kabaACK:
|
||||
registers = append(registers, "ACK")
|
||||
continue
|
||||
|
||||
case kabaNAK:
|
||||
return registers, fmt.Errorf("received NAK after Link Start")
|
||||
|
||||
case kabaSTX:
|
||||
frame, err := readKabaFrame(conn, reader, b, timeout)
|
||||
if err != nil {
|
||||
return registers, fmt.Errorf("failed to read Link Start frame: %v", err)
|
||||
}
|
||||
|
||||
frameText := string(frame)
|
||||
registers = append(registers, frameText)
|
||||
|
||||
clean := cleanKabaFrame(frameText)
|
||||
if strings.HasPrefix(clean, "LA|") {
|
||||
return registers, nil
|
||||
}
|
||||
|
||||
default:
|
||||
log.Warnf("Ignoring unexpected byte during Link Start: 0x%X", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (lock *KabaLockServer) requestEncoding(conn net.Conn, reader *bufio.Reader) (string, error) {
|
||||
log.Printf("Sending Encoding command: %q", lock.command)
|
||||
|
||||
if _, err := conn.Write(lock.command); err != nil {
|
||||
return "", fmt.Errorf("failed to send Encoding command: %v", err)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
|
||||
for {
|
||||
remaining := time.Until(deadline)
|
||||
if remaining <= 0 {
|
||||
return "", fmt.Errorf("timeout waiting for dormakaba encoding response")
|
||||
}
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(remaining))
|
||||
|
||||
b, err := reader.ReadByte()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading encoding response: %v", err)
|
||||
}
|
||||
|
||||
switch b {
|
||||
case kabaACK:
|
||||
log.Debug("Received ACK after Encoding command")
|
||||
continue
|
||||
|
||||
case kabaNAK:
|
||||
return "", fmt.Errorf("received NAK after Encoding command")
|
||||
|
||||
case kabaSTX:
|
||||
frame, err := readKabaFrame(conn, reader, b, 60*time.Second)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read encoding response frame: %v", err)
|
||||
}
|
||||
|
||||
raw := string(frame)
|
||||
clean := cleanKabaFrame(raw)
|
||||
|
||||
log.Printf("Received Encoding frame: %q", clean)
|
||||
|
||||
if strings.HasPrefix(clean, "KA|") {
|
||||
return parseDormakabaEncodingResponse(clean)
|
||||
}
|
||||
|
||||
log.Warnf("Ignoring non-KA frame while waiting for encoding result: %q", clean)
|
||||
|
||||
default:
|
||||
log.Warnf("Ignoring unexpected byte while waiting for encoding response: 0x%X", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseDormakabaEncodingResponse(clean string) (string, error) {
|
||||
if strings.Contains(clean, "|ASOK|") {
|
||||
return "Success: " + clean, nil
|
||||
}
|
||||
|
||||
if strings.Contains(clean, "|AS") {
|
||||
return "", fmt.Errorf("negative dormakaba response: %s", clean)
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("unexpected dormakaba response: %s", clean)
|
||||
}
|
||||
|
||||
func readKabaFrame(conn net.Conn, reader *bufio.Reader, firstByte byte, timeout time.Duration) ([]byte, error) {
|
||||
frame := []byte{firstByte}
|
||||
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
|
||||
b, err := reader.ReadByte()
|
||||
if err != nil {
|
||||
return frame, fmt.Errorf("error reading frame body: %w", err)
|
||||
}
|
||||
|
||||
frame = append(frame, b)
|
||||
|
||||
if b == kabaETX {
|
||||
return frame, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func wrapKabaFrame(payload string) []byte {
|
||||
command := make([]byte, 0, len(payload)+2)
|
||||
command = append(command, kabaSTX)
|
||||
command = append(command, []byte(payload)...)
|
||||
command = append(command, kabaETX)
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func cleanKabaFrame(raw string) string {
|
||||
return strings.Trim(raw, string([]byte{kabaSTX, kabaETX}))
|
||||
}
|
||||
|
||||
func dormakabaPassword() string {
|
||||
if strings.TrimSpace(Cert) != "" {
|
||||
return strings.TrimSpace(Cert)
|
||||
}
|
||||
|
||||
return "1234"
|
||||
}
|
||||
|
||||
func dormakabaWorkstationID() string {
|
||||
parsed, err := url.Parse(LockServerURL)
|
||||
if err == nil && parsed.Host != "" {
|
||||
host := parsed.Host
|
||||
|
||||
if h, _, splitErr := net.SplitHostPort(host); splitErr == nil {
|
||||
return h
|
||||
}
|
||||
|
||||
return strings.Trim(host, "/")
|
||||
}
|
||||
|
||||
raw := strings.TrimSpace(LockServerURL)
|
||||
raw = strings.TrimPrefix(raw, "http://")
|
||||
raw = strings.TrimPrefix(raw, "https://")
|
||||
raw = strings.Trim(raw, "/")
|
||||
|
||||
if h, _, splitErr := net.SplitHostPort(raw); splitErr == nil {
|
||||
return h
|
||||
}
|
||||
|
||||
if idx := strings.Index(raw, ":"); idx >= 0 {
|
||||
return raw[:idx]
|
||||
}
|
||||
|
||||
return raw
|
||||
}
|
||||
@@ -25,10 +25,11 @@ const (
|
||||
Omnitec = "omnitec"
|
||||
Salto = "salto"
|
||||
TLJ = "tlj"
|
||||
Dormakaba = "kaba"
|
||||
)
|
||||
|
||||
var (
|
||||
Cert string
|
||||
Cert string
|
||||
LockServerURL string
|
||||
)
|
||||
|
||||
@@ -38,6 +39,11 @@ type (
|
||||
LockSequence() error
|
||||
}
|
||||
|
||||
KabaLockServer struct {
|
||||
encoderAddr string
|
||||
command []byte
|
||||
}
|
||||
|
||||
AssaLockServer struct {
|
||||
encoderAddr string
|
||||
command string
|
||||
@@ -69,22 +75,24 @@ func NewLockServer(lockType, encoderAddr string, fatalError func(error)) LockSer
|
||||
return &SaltoLockServer{encoderAddr: encoderAddr}
|
||||
case TLJ:
|
||||
return &TLJLockServer{encoderAddr: encoderAddr}
|
||||
case Dormakaba:
|
||||
return &KabaLockServer{encoderAddr: encoderAddr}
|
||||
default:
|
||||
fatalError(fmt.Errorf("unsupported LockType: %s; must be 'assaabloy' or 'omnitec'", lockType))
|
||||
return nil // This line will never be reached, but is needed to satisfy the compiler
|
||||
}
|
||||
}
|
||||
|
||||
func InitializeServerConnection(LockserverUrl string) (net.Conn, error) {
|
||||
func InitializeServerConnection(LockserverURL string) (net.Conn, error) {
|
||||
const funcName = "InitializeServerConnection"
|
||||
// Parse the URL to extract host and port
|
||||
parsedUrl, err := url.Parse(LockserverUrl)
|
||||
parsedURL, err := url.Parse(LockserverURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[%s] failed to parse LockserverUrl: %v", funcName, err)
|
||||
return nil, fmt.Errorf("[%s] failed to parse LockserverURL: %v", funcName, err)
|
||||
}
|
||||
|
||||
// Remove any leading/trailing slashes just in case
|
||||
address := strings.Trim(parsedUrl.Host, "/")
|
||||
address := strings.Trim(parsedURL.Host, "/")
|
||||
|
||||
// Establish a TCP connection to the Visionline server
|
||||
conn, err := net.Dial("tcp", address)
|
||||
@@ -102,7 +110,7 @@ func sendAndReceive(conn net.Conn, command []byte) (string, error) {
|
||||
return "", fmt.Errorf("failed to send command: %v", err)
|
||||
}
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
conn.SetReadDeadline(time.Now().Add(20 * time.Second))
|
||||
|
||||
buf := make([]byte, 128)
|
||||
reader := bufio.NewReader(conn)
|
||||
@@ -7,12 +7,12 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Build key encoding request command for the Omnitec lock server.
|
||||
// BuildCommand builds key encoding request command for the Omnitec lock server.
|
||||
func (lock *OmniLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error {
|
||||
const funcName = "OmniLockServer.BuildCommand"
|
||||
hostname, err := os.Hostname()
|
||||
@@ -25,7 +25,7 @@ func (lock *OmniLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, check
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%s] failed to convert lockId to integer: %v", funcName, err)
|
||||
}
|
||||
formattedLockId := fmt.Sprintf("%04d", idInt)
|
||||
formattedLockID := fmt.Sprintf("%04d", idInt)
|
||||
|
||||
// Format date/time parts
|
||||
dt := checkOut.Format("15:04") // DT = HH:mm
|
||||
@@ -37,7 +37,7 @@ func (lock *OmniLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, check
|
||||
payload := fmt.Sprintf(
|
||||
"KR|KC%s|KTD|RN%s|%s|DT%s|G#75|GA%s|GD%s|KO0000|DA%s|TI%s|",
|
||||
lock.encoderAddr,
|
||||
formattedLockId,
|
||||
formattedLockID,
|
||||
hostname,
|
||||
dt,
|
||||
ga,
|
||||
@@ -52,7 +52,7 @@ func (lock *OmniLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, check
|
||||
return nil
|
||||
}
|
||||
|
||||
// Starts link to the Omnitec lock server and perform key encoding
|
||||
// LockSequence starts link to the Omnitec lock server and perform key encoding
|
||||
func (lock *OmniLockServer) LockSequence() error {
|
||||
const funcName = "OmniLockServer.LockSequence"
|
||||
|
||||
@@ -136,4 +136,4 @@ func parseOmniResponse(raw string) (string, error) {
|
||||
return "", fmt.Errorf("negative response code: %s", clean)
|
||||
}
|
||||
return "Success: " + clean, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package mail
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
mailjet "github.com/mailjet/mailjet-apiv3-go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
apiKey = "60f358a27e98562641c08f51e5450c9e"
|
||||
secretKey = "068b65c3b337a0e3c14389544ecd771f"
|
||||
)
|
||||
|
||||
const (
|
||||
moduleName = "mail"
|
||||
)
|
||||
|
||||
var (
|
||||
// sendErrorEmail is the e-mail address to which to send an e-mail if there is an error during checkin or payment
|
||||
SendErrorEmails []string
|
||||
)
|
||||
|
||||
// SendMail will send reception an e-mail
|
||||
func SendMail(recipient, title, message string) {
|
||||
const funcName = "SendMail"
|
||||
|
||||
mailjetClient := mailjet.NewMailjetClient(apiKey, secretKey)
|
||||
messagesInfo := []mailjet.InfoMessagesV31{
|
||||
mailjet.InfoMessagesV31{
|
||||
From: &mailjet.RecipientV31{
|
||||
Email: "kiosk@cms.futuresens.co.uk",
|
||||
Name: "Futuresens Kiosk",
|
||||
},
|
||||
To: &mailjet.RecipientsV31{
|
||||
mailjet.RecipientV31{
|
||||
Email: recipient,
|
||||
Name: "",
|
||||
},
|
||||
},
|
||||
Subject: title,
|
||||
TextPart: message,
|
||||
},
|
||||
}
|
||||
messages := mailjet.MessagesV31{Info: messagesInfo}
|
||||
_, err := mailjetClient.SendMailV31(&messages)
|
||||
if err != nil {
|
||||
theFields := log.Fields{}
|
||||
theFields["mailerror"] = true
|
||||
theFields["recipient"] = recipient
|
||||
theFields[logging.LogFunction] = funcName
|
||||
theFields[logging.LogModule] = moduleName
|
||||
theFields[logging.LogError] = err.Error()
|
||||
theFields["error"] = err.Error()
|
||||
|
||||
log.WithFields(theFields).Error("sendmail error")
|
||||
}
|
||||
}
|
||||
|
||||
func SendEmailOnError(hotel string, kiosk int, title, errMsg string) {
|
||||
log.Println("sendEmailOnError called")
|
||||
|
||||
message := fmt.Sprintf("Hotel: %s, kiosk: %d.\n%s", hotel, kiosk, errMsg)
|
||||
for _, recipient := range SendErrorEmails {
|
||||
SendMail(recipient, title, message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package mail
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_SendMail(t *testing.T) {
|
||||
SendMail("zotacrtx5@gmail.com", "Test Subjectp", "Test Message")
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
KeyErrors = "ERRORS"
|
||||
KeyVersionInformation = "VERSION_INFORMATION"
|
||||
KeyChipDnaStatus = "CHIPDNA_STATUS"
|
||||
KeyPaymentDeviceStatus = "PAYMENT_DEVICE_STATUS"
|
||||
KeyRequestQueueStatus = "REQUEST_QUEUE_STATUS"
|
||||
KeyTmsStatus = "TMS_STATUS"
|
||||
KeyPaymentPlatform = "PAYMENT_PLATFORM_STATUS"
|
||||
KeyPaymentDeviceModel = "PAYMENT_DEVICE_MODEL"
|
||||
KeyPaymentDeviceIdentifier = "PAYMENT_DEVICE_IDENTIFIER"
|
||||
KeyIsAvailable = "IS_AVAILABLE"
|
||||
KeyAvailabilityError = "AVAILABILITY_ERROR"
|
||||
KeyAvailabilityErrorInformation = "AVAILABILITY_ERROR_INFORMATION"
|
||||
)
|
||||
|
||||
type (
|
||||
ArrayOfParameter struct {
|
||||
Parameters []Parameter `xml:"Parameter" json:"Parameters"`
|
||||
}
|
||||
|
||||
Parameter struct {
|
||||
Key string `xml:"Key" json:"Key"`
|
||||
Value string `xml:"Value" json:"Value"`
|
||||
}
|
||||
|
||||
ServerStatus struct {
|
||||
IsProcessingTransaction bool `xml:"IsProcessingTransaction" json:"IsProcessingTransaction"`
|
||||
ChipDnaServerIssue string `xml:"ChipDnaServerIssue" json:"ChipDnaServerIssue"`
|
||||
}
|
||||
|
||||
ArrayOfPaymentDeviceStatus struct {
|
||||
Items []PaymentDeviceStatus `xml:"PaymentDeviceStatus" json:"Items"`
|
||||
}
|
||||
|
||||
PaymentDeviceStatus struct {
|
||||
ConfiguredDeviceId string `xml:"ConfiguredDeviceId" json:"ConfiguredDeviceId"`
|
||||
ConfiguredDeviceModel string `xml:"ConfiguredDeviceModel" json:"ConfiguredDeviceModel"`
|
||||
ProcessingTransaction bool `xml:"ProcessingTransaction" json:"ProcessingTransaction"`
|
||||
AvailabilityError string `xml:"AvailabilityError" json:"AvailabilityError"`
|
||||
AvailabilityErrorInformation string `xml:"AvailabilityErrorInformation" json:"AvailabilityErrorInformation"`
|
||||
ConfigurationState string `xml:"ConfigurationState" json:"ConfigurationState"`
|
||||
IsAvailable bool `xml:"IsAvailable" json:"IsAvailable"`
|
||||
BatteryPercentage int `xml:"BatteryPercentage" json:"BatteryPercentage"`
|
||||
BatteryChargingStatus string `xml:"BatteryChargingStatus" json:"BatteryChargingStatus"`
|
||||
BatteryStatusUpdateDateTime string `xml:"BatteryStatusUpdateDateTime" json:"BatteryStatusUpdateDateTime"`
|
||||
BatteryStatusUpdateDateTimeFormat string `xml:"BatteryStatusUpdateDateTimeFormat" json:"BatteryStatusUpdateDateTimeFormat"`
|
||||
}
|
||||
|
||||
RequestQueueStatus struct {
|
||||
CreditRequestCount int `xml:"CreditRequestCount" json:"CreditRequestCount"`
|
||||
CreditConfirmRequestCount int `xml:"CreditConfirmRequestCount" json:"CreditConfirmRequestCount"`
|
||||
CreditVoidRequestCount int `xml:"CreditVoidRequestCount" json:"CreditVoidRequestCount"`
|
||||
DebitRequestCount int `xml:"DebitRequestCount" json:"DebitRequestCount"`
|
||||
DebitConfirmRequestCount int `xml:"DebitConfirmRequestCount" json:"DebitConfirmRequestCount"`
|
||||
DebitVoidRequestCount int `xml:"DebitVoidRequestCount" json:"DebitVoidRequestCount"`
|
||||
}
|
||||
|
||||
TmsStatus struct {
|
||||
LastConfigUpdateDateTime string `xml:"LastConfigUpdateDateTime" json:"LastConfigUpdateDateTime"`
|
||||
DaysUntilConfigUpdateIsRequired int `xml:"DaysUntilConfigUpdateIsRequired" json:"DaysUntilConfigUpdateIsRequired"`
|
||||
RequiredConfigUpdateDateTime string `xml:"RequiredConfigUpdateDateTime" json:"RequiredConfigUpdateDateTime"`
|
||||
}
|
||||
|
||||
PaymentPlatformStatus struct {
|
||||
MachineLocalDateTime string `xml:"MachineLocalDateTime" json:"MachineLocalDateTime"`
|
||||
PaymentPlatformLocalDateTime string `xml:"PaymentPlatformLocalDateTime" json:"PaymentPlatformLocalDateTime"`
|
||||
PaymentPlatformLocalDateTimeFormat string `xml:"PaymentPlatformLocalDateTimeFormat" json:"PaymentPlatformLocalDateTimeFormat"`
|
||||
State string `xml:"State" json:"State"`
|
||||
}
|
||||
|
||||
ParsedStatus struct {
|
||||
Errors []string `json:"Errors"`
|
||||
VersionInfo map[string]string `json:"VersionInfo"`
|
||||
ChipDnaStatus *ServerStatus `json:"ChipDnaStatus"`
|
||||
PaymentDevices []PaymentDeviceStatus `json:"PaymentDevices"`
|
||||
RequestQueue *RequestQueueStatus `json:"RequestQueue"`
|
||||
TMS *TmsStatus `json:"TMS"`
|
||||
PaymentPlatform *PaymentPlatformStatus `json:"PaymentPlatform"`
|
||||
Unknown map[string]string `json:"Unknown"`
|
||||
}
|
||||
)
|
||||
|
||||
// ===========================
|
||||
// Parser
|
||||
// ===========================
|
||||
|
||||
func ParseStatusResult(data []byte) (*ParsedStatus, error) {
|
||||
var tr TransactionResultXML
|
||||
if err := tr.ParseTransactionResult(data); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal TransactionResult: %w", err)
|
||||
}
|
||||
|
||||
out := &ParsedStatus{
|
||||
VersionInfo: make(map[string]string),
|
||||
Unknown: make(map[string]string),
|
||||
}
|
||||
|
||||
for _, e := range tr.Entries {
|
||||
switch e.Key {
|
||||
|
||||
// Some responses return plain text (not escaped XML) for ERRORS.
|
||||
case KeyErrors:
|
||||
msg := html.UnescapeString(e.Value) // safe even if not escaped
|
||||
if msg != "" {
|
||||
out.Errors = append(out.Errors, msg)
|
||||
}
|
||||
|
||||
// Everything below is escaped XML inside <Value>
|
||||
case KeyVersionInformation:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var a ArrayOfParameter
|
||||
if err := xml.Unmarshal([]byte(unescaped), &a); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
for _, p := range a.Parameters {
|
||||
out.VersionInfo[p.Key] = p.Value
|
||||
}
|
||||
|
||||
case KeyChipDnaStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s ServerStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.ChipDnaStatus = &s
|
||||
|
||||
case KeyPaymentDeviceStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var a ArrayOfPaymentDeviceStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &a); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.PaymentDevices = append(out.PaymentDevices, a.Items...)
|
||||
|
||||
case KeyRequestQueueStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s RequestQueueStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.RequestQueue = &s
|
||||
|
||||
case KeyTmsStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s TmsStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.TMS = &s
|
||||
|
||||
case KeyPaymentPlatform:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s PaymentPlatformStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.PaymentPlatform = &s
|
||||
|
||||
default:
|
||||
// Keep for logging / future additions. Unescape so it's readable XML if it was escaped.
|
||||
out.Unknown[e.Key] = html.UnescapeString(e.Value)
|
||||
}
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func fetchChipDNAStatus() (*ParsedStatus, error) {
|
||||
const op = logging.Op("fetchChipDNAStatus")
|
||||
|
||||
body := []byte{}
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
response, err := client.Post(types.LinkChipDNAStatus, "text/xml", bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "error fetching ChipDNA status", string(op), "", "", 0)
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
body, err = io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Read response body error", string(op), "", "", 0)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := ParseStatusResult(body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse ChipDNA status error", string(op), "", "", 0)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func ReadPdqStatus(hotel string, kiosk int) (PaymentDeviceStatus, error) {
|
||||
const op = logging.Op("readPdqStatus")
|
||||
|
||||
status, err := fetchChipDNAStatus()
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "Failed to fetch ChipDNA status: "+err.Error(), string(op), "", hotel, kiosk)
|
||||
return PaymentDeviceStatus{}, fmt.Errorf("error fetch ChipDNA status: %w", err)
|
||||
}
|
||||
|
||||
if len(status.Errors) > 0 {
|
||||
msg := strings.Join(status.Errors, "; ")
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "ChipDNA status errors: "+msg, string(op), "", hotel, kiosk)
|
||||
return PaymentDeviceStatus{}, fmt.Errorf("ChipDNA status errors: %s", msg)
|
||||
}
|
||||
|
||||
if len(status.PaymentDevices) == 0 {
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "ChipDNA status has no PAYMENT_DEVICE_STATUS items", string(op), "", hotel, kiosk)
|
||||
return PaymentDeviceStatus{}, fmt.Errorf("no payment devices returned")
|
||||
}
|
||||
|
||||
dev := status.PaymentDevices[0]
|
||||
if !dev.IsAvailable {
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "Payment device unavailable", string(op), "", hotel, kiosk)
|
||||
return dev, fmt.Errorf("device unavailable")
|
||||
}
|
||||
|
||||
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,7 +9,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
_ "github.com/denisenkom/go-mssqldb"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -50,6 +50,12 @@ type (
|
||||
transactionRes string
|
||||
transactionState string
|
||||
}
|
||||
|
||||
ConfirmTransactionRequest struct {
|
||||
XMLName xml.Name `xml:"ConfirmTransactionRequest"`
|
||||
Amount string `xml:"Amount"`
|
||||
Reference string `xml:"TransactionReference"`
|
||||
}
|
||||
)
|
||||
|
||||
// ParseTransactionResult parses the XML into entries.
|
||||
@@ -72,9 +78,7 @@ func (ti *TransactionInfo) FillFromTransactionResult(trResult TransactionResultX
|
||||
}
|
||||
|
||||
func (r *PaymentResult) FillFromTransactionResult(trResult TransactionResultXML) {
|
||||
if r.Fields == nil {
|
||||
r.Fields = make(map[string]string)
|
||||
}
|
||||
r.Fields = make(map[string]string)
|
||||
|
||||
for _, e := range trResult.Entries {
|
||||
switch e.Key {
|
||||
@@ -107,7 +111,7 @@ func BuildPaymentRedirectURL(result map[string]string) string {
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Transaction approved and confirmed")
|
||||
|
||||
return buildSuccessURL(result)
|
||||
return BuildSuccessURL(result)
|
||||
}
|
||||
|
||||
// Not confirmed
|
||||
@@ -133,7 +137,7 @@ func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
||||
log.WithField(types.LogResult, result[types.TransactionResult]).
|
||||
Info("Account verification approved")
|
||||
|
||||
return buildSuccessURL(result), false
|
||||
return BuildSuccessURL(result), false
|
||||
|
||||
// Transaction type Sale?
|
||||
case strings.EqualFold(tType, types.SaleTransactionType):
|
||||
@@ -141,7 +145,7 @@ func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Amount preauthorized successfully")
|
||||
|
||||
return buildSuccessURL(result), true
|
||||
return BuildSuccessURL(result), true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,10 +153,11 @@ func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
||||
return BuildFailureURL(res, result[types.Errors]), false
|
||||
}
|
||||
|
||||
func buildSuccessURL(result map[string]string) string {
|
||||
func BuildSuccessURL(result map[string]string) string {
|
||||
q := url.Values{}
|
||||
q.Set("CardNumber", hex.EncodeToString([]byte(result[types.PAN_MASKED])))
|
||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result[types.EXPIRY_DATE])))
|
||||
q.Set("CardNumber", hex.EncodeToString([]byte(result[types.PanMasked])))
|
||||
q.Set("CardType", hex.EncodeToString([]byte(result[types.CardType])))
|
||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result[types.ExpiryDate])))
|
||||
q.Set("TxnReference", result[types.Reference])
|
||||
q.Set("CardHash", hex.EncodeToString([]byte(result[types.CardHash])))
|
||||
q.Set("CardReference", hex.EncodeToString([]byte(result[types.CardReference])))
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -167,7 +167,19 @@ func BuildRoomTicket(details RoomDetailsRec) ([]byte, error) {
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func PrintCardholderReceipt(cardholderReceipt string) error {
|
||||
func PrintReceipt(receipt string) {
|
||||
|
||||
if len(receipt) == 0 {
|
||||
log.Warn("Empty cardholder receipt, skipping print")
|
||||
return
|
||||
}
|
||||
|
||||
if err := printCardholderReceipt(receipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func printCardholderReceipt(cardholderReceipt string) error {
|
||||
receiptEntries, err := ParseCardholderReceipt([]byte(cardholderReceipt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("ParseCardholderReceipt: %w", err)
|
||||
@@ -7,11 +7,13 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
ServiceName = "hardlink"
|
||||
DateOnly = "2006-01-02"
|
||||
CustomLayout = "2006-01-02 15:04:05 -0700"
|
||||
LinkTakePreauthorization = "http://127.0.0.1:18181/start-transaction/"
|
||||
LinkTakePayment = "http://127.0.0.1:18181/start-and-confirm-transaction/"
|
||||
LinkStartTransaction = "http://127.0.0.1:18181/start-transaction/"
|
||||
LinkConfirmTransaction = "http://127.0.0.1:18181/confirm-transaction/"
|
||||
LinkTransactionInformation = "http://127.0.0.1:18181/transaction-information/"
|
||||
LinkChipDNAStatus = "http://127.0.0.1:18181/chipdna-status/"
|
||||
LinkVoidTransaction = "http://127.0.0.1:18181/void-transaction/"
|
||||
// Transaction types
|
||||
SaleTransactionType = "sale"
|
||||
@@ -32,12 +34,14 @@ const (
|
||||
CardReference = "CARD_REFERENCE"
|
||||
CardHash = "CARD_HASH"
|
||||
Errors = "ERRORS"
|
||||
ErrorDescription = "ERROR_DESCRIPTION"
|
||||
ReceiptData = "RECEIPT_DATA"
|
||||
ReceiptDataMerchant = "RECEIPT_DATA_MERCHANT"
|
||||
ReceiptDataCardholder = "RECEIPT_DATA_CARDHOLDER"
|
||||
Reference = "REFERENCE"
|
||||
PAN_MASKED = "PAN_MASKED"
|
||||
EXPIRY_DATE = "EXPIRY_DATE"
|
||||
CardType = "CARD_SCHEME_ID"
|
||||
PanMasked = "PAN_MASKED"
|
||||
ExpiryDate = "EXPIRY_DATE"
|
||||
TransactionResult = "TRANSACTION_RESULT"
|
||||
TransactionType = "TRANSACTION_TYPE"
|
||||
TransactionState = "TRANSACTION_STATE"
|
||||
@@ -2,6 +2,46 @@
|
||||
|
||||
builtVersion is a const in main.go
|
||||
|
||||
#### 1.2.9 - 02 June 2026
|
||||
added Dormakaba lock server integration
|
||||
|
||||
#### 1.2.8 - 14 May 2026
|
||||
Updated hardlink source layout to use cmd/hardlink for the main application entry point and internal/ for application packages. Runtime files and preauth-release layout remain unchanged. No functional changes.
|
||||
|
||||
#### 1.2.7 - 13 May 2026
|
||||
retrieve CardType from the ChepDNA response
|
||||
|
||||
#### 1.2.6 - 20 April 2026
|
||||
added the second attempt to send the card to the encoder after 6 seconds
|
||||
|
||||
#### 1.2.5 - 20 March 2026
|
||||
removed early return on error when checking dispenser status in the start and final loops.
|
||||
|
||||
#### 1.2.4 - 18 March 2026
|
||||
added check if keycard at the encoder position before trying to encode key
|
||||
|
||||
#### 1.2.3 - 17 March 2026
|
||||
added check if keycard at the encoder position before trying to encode key
|
||||
|
||||
#### 1.2.2 - 11 February 2026
|
||||
increased waiting time befor sending email on PDQ unavailability to 30 seconds day time and 10 minutes night time
|
||||
to give it a chance to become available again
|
||||
|
||||
#### 1.2.1 - 09 February 2026
|
||||
increased waiting time befor sending email on PDQ unavailability to 60 seconds
|
||||
|
||||
#### 1.2.0 - 09 February 2026
|
||||
added testissuedoorcard endpoint for testing the full workflow of encoding a door card without moving the card out
|
||||
added ping-pdq endpoint to check the status of the pdq terminal
|
||||
added sending the email on the pdq disconnect event to notify support about the issue
|
||||
added sending the email on the dispenser error status to notify support about the issue
|
||||
|
||||
#### 1.1.3 - 02 February 2026
|
||||
increased timeout for reading response from the Assa abloy lock server to 20 seconds
|
||||
|
||||
#### 1.1.2 - 02 February 2026
|
||||
added logging for unknown dispenser status positions
|
||||
|
||||
#### 1.1.1 - 02 February 2026
|
||||
added contionuous polling of the dispenser status every 8 seconds to update the card well status
|
||||
|
||||
|
||||
Reference in New Issue
Block a user