Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
895849376e | ||
|
|
43f1e8787f | ||
|
|
7941e2065e | ||
|
|
b59d77a373 | ||
|
|
a4885be458 | ||
|
|
89dfa28e6f | ||
|
|
bb526a248d | ||
|
|
f4f44da541 | ||
|
|
7993a2360d | ||
|
|
c15ceba78f | ||
|
|
04c664294d | ||
|
|
da5cafe031 | ||
|
|
efa415e631 | ||
|
|
f1dc0ccce4 | ||
|
|
1bceb55285 | ||
|
|
bb8cdb1d84 | ||
|
|
251afd6aeb | ||
|
|
e6ff292706 | ||
|
|
b4d16f9021 | ||
|
|
c8f6c57983 |
@@ -28,6 +28,7 @@ Checkin.code-workspace
|
||||
_obj
|
||||
_test
|
||||
.vscode/
|
||||
ChipDNAClient/
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// internal/bootstrap/db.go
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
)
|
||||
|
||||
func OpenDB(cfg *config.ConfigRec) (*sql.DB, error) {
|
||||
return db.InitMSSQL(
|
||||
cfg.Dbport,
|
||||
cfg.Dbuser,
|
||||
cfg.Dbpassword,
|
||||
cfg.Dbname,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/handlers"
|
||||
log "github.com/sirupsen/logrus"
|
||||
yaml "gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// ReadConfig reads config.yml and applies defaults.
|
||||
func ReadHardlinkConfig() ConfigRec {
|
||||
var cfg ConfigRec
|
||||
const configName = "config.yml"
|
||||
defaultPort := 9091
|
||||
sep := string(os.PathSeparator)
|
||||
|
||||
data, err := os.ReadFile(configName)
|
||||
if err != nil {
|
||||
log.Warnf("ReadConfig %s: %v", configName, err)
|
||||
} else if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
log.Warnf("Unmarshal config: %v", err)
|
||||
}
|
||||
|
||||
if cfg.Port == 0 {
|
||||
cfg.Port = defaultPort
|
||||
}
|
||||
|
||||
if cfg.LockType == "" {
|
||||
err = fmt.Errorf("LockType is required in %s", configName)
|
||||
handlers.FatalError(err)
|
||||
}
|
||||
cfg.LockType = strings.ToLower(cfg.LockType)
|
||||
|
||||
if cfg.LogDir == "" {
|
||||
cfg.LogDir = "./logs" + sep
|
||||
} else if !strings.HasSuffix(cfg.LogDir, sep) {
|
||||
cfg.LogDir += sep
|
||||
}
|
||||
|
||||
if cfg.Dbport <= 0 || cfg.Dbuser == "" || cfg.Dbname == "" || cfg.Dbpassword == "" {
|
||||
err = fmt.Errorf("Database config (dbport, dbuser, dbname, dbpassword) are required in %s", configName)
|
||||
log.Warnf(err.Error())
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func ReadPreauthReleaserConfig() ConfigRec {
|
||||
var cfg ConfigRec
|
||||
const configName = "config.yml"
|
||||
sep := string(os.PathSeparator)
|
||||
|
||||
data, err := os.ReadFile(configName)
|
||||
if err != nil {
|
||||
log.Warnf("ReadConfig %s: %v", configName, err)
|
||||
} else if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
log.Warnf("Unmarshal config: %v", err)
|
||||
}
|
||||
|
||||
if cfg.Dbport <= 0 || cfg.Dbuser == "" || cfg.Dbname == "" || cfg.Dbpassword == "" {
|
||||
err = fmt.Errorf("Database config (dbport, dbuser, dbname, dbpassword) are required in %s", configName)
|
||||
handlers.FatalError(err)
|
||||
}
|
||||
|
||||
if cfg.LogDir == "" {
|
||||
cfg.LogDir = "./logs" + sep
|
||||
} else if !strings.HasSuffix(cfg.LogDir, sep) {
|
||||
cfg.LogDir += sep
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mssqldb "github.com/denisenkom/go-mssqldb" // for error inspection
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
)
|
||||
|
||||
// InitMSSQL opens and pings the SQL Server instance (keeps your original behaviour)
|
||||
func InitMSSQL(port int, user, password, database string) (*sql.DB, error) {
|
||||
if port <= 0 || user == "" || database == "" {
|
||||
return nil, errors.New("incomplete database configuration")
|
||||
}
|
||||
|
||||
dsn := fmt.Sprintf(
|
||||
"sqlserver://%s:%s@%s:%d?database=%s&encrypt=disable",
|
||||
user, password, "localhost", port, database,
|
||||
)
|
||||
|
||||
db, err := sql.Open("sqlserver", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := db.QueryRowContext(ctx, "SELECT 1").Scan(new(int)); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
log.Info("Database connection established")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func parseDateOnly(s string) (time.Time, error) {
|
||||
parsed, err := time.Parse(types.CustomLayout, s)
|
||||
if err == nil {
|
||||
// construct midnight in local timezone, then convert to UTC for storage consistency
|
||||
localMidnight := time.Date(parsed.Year(), parsed.Month(), parsed.Day(), 0, 0, 0, 0, time.Local)
|
||||
return localMidnight.UTC(), nil
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("parseDateOnly error: parsing %q: %w", s, err)
|
||||
}
|
||||
|
||||
// InsertPreauth stores a preauthorization record. It is idempotent: duplicate TxnReference is ignored.
|
||||
func InsertPreauth(ctx context.Context, db *sql.DB, m map[string]string, checkoutDate string) error {
|
||||
const funcName = "InsertPreauth"
|
||||
|
||||
totalMinorUnits := m[types.TotalAmount]
|
||||
txnReference := m[types.Reference]
|
||||
if txnReference == "" {
|
||||
return fmt.Errorf("%s: missing REFERENCE", funcName)
|
||||
}
|
||||
if totalMinorUnits == "" {
|
||||
return fmt.Errorf("%s: missing TotalAmount", funcName)
|
||||
}
|
||||
|
||||
// parse minor units, fallback to 0 on parse error but report it
|
||||
amountInt, err := strconv.ParseInt(totalMinorUnits, 10, 64)
|
||||
if err != nil {
|
||||
log.WithFields(log.Fields{
|
||||
"func": funcName,
|
||||
"value": totalMinorUnits,
|
||||
"error": err,
|
||||
}).Warnf("parsing TotalAmount, defaulting to 0")
|
||||
amountInt = 0
|
||||
}
|
||||
totalAmount := float64(amountInt) / 100.0
|
||||
|
||||
txnTime := time.Now().UTC()
|
||||
|
||||
// parse departure / checkout date and compute release date (48h after departure)
|
||||
checkOutDate, err := parseDateOnly(checkoutDate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("InsertPreauth: parsing checkoutDate %q: %w", checkoutDate, err)
|
||||
}
|
||||
releaseDate := checkOutDate.Add(48 * time.Hour)
|
||||
|
||||
const stmt = `
|
||||
INSERT INTO dbo.Preauthorizations
|
||||
(TxnReference, TotalMinorUnits, TotalAmount, TxnDateTime, DepartureDate, ReleaseDate)
|
||||
VALUES
|
||||
(@TxnReference, @TotalMinorUnits, @TotalAmount, @TxnDateTime, @DepartureDate, @ReleaseDate);
|
||||
`
|
||||
_, err = db.ExecContext(ctx, stmt,
|
||||
sql.Named("TxnReference", txnReference),
|
||||
sql.Named("TotalMinorUnits", totalMinorUnits),
|
||||
sql.Named("TotalAmount", totalAmount),
|
||||
sql.Named("TxnDateTime", txnTime),
|
||||
sql.Named("DepartureDate", checkOutDate),
|
||||
sql.Named("ReleaseDate", releaseDate),
|
||||
)
|
||||
if err != nil {
|
||||
// handle duplicate-key (unique constraint) gracefully: SQL Server error numbers 2601/2627
|
||||
var sqlErr mssqldb.Error
|
||||
if errors.As(err, &sqlErr) {
|
||||
if sqlErr.Number == 2627 || sqlErr.Number == 2601 {
|
||||
log.Infof("InsertPreauth: preauth %s already exists (duplicate key) - ignoring", txnReference)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("InsertPreauth exec: %w", err)
|
||||
}
|
||||
|
||||
log.Infof("Inserted preauth %s amount=%s minorUnits release=%s", txnReference, totalMinorUnits, releaseDate.Format(time.RFC3339))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDuePreauths returns preauths with ReleaseDate <= now where Released = 0.
|
||||
// If limit > 0, the query uses TOP(limit) to bound results at DB level.
|
||||
func GetDuePreauths(ctx context.Context, db *sql.DB, now time.Time, limit int) ([]types.PreauthRec, error) {
|
||||
baseQuery := `
|
||||
SELECT Id, TxnReference, TotalMinorUnits, TotalAmount, TxnDateTime, DepartureDate, ReleaseDate, Released, ReleasedAt
|
||||
FROM dbo.Preauthorizations
|
||||
WHERE Released = 0 AND ReleaseDate <= @Now
|
||||
ORDER BY ReleaseDate ASC
|
||||
`
|
||||
query := baseQuery
|
||||
if limit > 0 {
|
||||
// embed TOP to keep DB from returning everything; limit is controlled by the caller.
|
||||
query = strings.Replace(baseQuery, "SELECT", fmt.Sprintf("SELECT TOP (%d)", limit), 1)
|
||||
}
|
||||
|
||||
rows, err := db.QueryContext(ctx, query, sql.Named("Now", now))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetDuePreauths query: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []types.PreauthRec
|
||||
for rows.Next() {
|
||||
var r types.PreauthRec
|
||||
var departure sql.NullTime
|
||||
var releasedAt sql.NullTime
|
||||
// Note: adjust scanning targets if types.PreauthRec fields differ
|
||||
if err := rows.Scan(
|
||||
&r.Id,
|
||||
&r.TxnReference,
|
||||
&r.TotalMinorUnits,
|
||||
&r.TotalAmount,
|
||||
&r.TxnDateTime,
|
||||
&departure,
|
||||
&r.ReleaseDate,
|
||||
&r.Released,
|
||||
&releasedAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("GetDuePreauths scan: %w", err)
|
||||
}
|
||||
|
||||
if departure.Valid {
|
||||
r.DepartureDate = departure.Time
|
||||
} else {
|
||||
r.DepartureDate = time.Time{}
|
||||
}
|
||||
r.ReleasedAt = releasedAt
|
||||
|
||||
out = append(out, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("GetDuePreauths rows: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MarkPreauthReleased sets Released=1 and stores the timestamp. Returns error if no rows updated.
|
||||
func MarkPreauthReleased(ctx context.Context, db *sql.DB, txnReference string, releasedAt time.Time) error {
|
||||
const stmt = `
|
||||
UPDATE dbo.Preauthorizations
|
||||
SET Released = 1, ReleasedAt = @ReleasedAt
|
||||
WHERE TxnReference = @TxnReference AND Released = 0;
|
||||
`
|
||||
res, err := db.ExecContext(ctx, stmt, sql.Named("ReleasedAt", releasedAt), sql.Named("TxnReference", txnReference))
|
||||
if err != nil {
|
||||
return fmt.Errorf("MarkPreauthReleased exec: %w", err)
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return fmt.Errorf("MarkPreauthReleased RowsAffected: %w", err)
|
||||
}
|
||||
if n == 0 {
|
||||
return fmt.Errorf("no rows updated for %s (maybe already released)", txnReference)
|
||||
}
|
||||
log.Infof("Marked preauth %s released at %s", txnReference, releasedAt.Format(time.RFC3339))
|
||||
return nil
|
||||
}
|
||||
@@ -251,6 +251,8 @@ func CardToEncoderPosition(port *serial.Port) (string, error) {
|
||||
return "", fmt.Errorf("error sending ENQ to prompt device: %v", err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
|
||||
//Check card position status
|
||||
status, err := CheckDispenserStatus(port)
|
||||
if err != nil {
|
||||
@@ -281,6 +283,8 @@ func CardOutOfMouth(port *serial.Port) (string, error) {
|
||||
return "", fmt.Errorf("error sending ENQ to prompt device: %v", err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
|
||||
//Check card position status
|
||||
status, err := CheckDispenserStatus(port)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,7 +3,7 @@ module gitea.futuresens.co.uk/futuresens/hardlink
|
||||
go 1.23.2
|
||||
|
||||
require (
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.179
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.190
|
||||
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
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.179 h1:3OLzX6jJ2dwfZ9Fcijk5z6/GUdTl5FUNw3eWuRkDhZw=
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.179/go.mod h1:ABMUkdm+3VGrkuoCJsXMfPPud9GHDOwBb1NiifFqxes=
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.190 h1:OxP911wT8HQqBJ20KIZcBxi898rsYHhhCkne2u45p1A=
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.190/go.mod h1:ABMUkdm+3VGrkuoCJsXMfPPud9GHDOwBb1NiifFqxes=
|
||||
gitea.futuresens.co.uk/futuresens/fscrypto v0.0.0-20221125125050-9acaffd21362 h1:MnhYo7XtsECCU+5yVMo3tZZOOSOKGkl7NpOvTAieBTo=
|
||||
gitea.futuresens.co.uk/futuresens/fscrypto v0.0.0-20221125125050-9acaffd21362/go.mod h1:p95ouVfK4qyC20D3/k9QLsWSxD2pdweWiY6vcYi9hpM=
|
||||
gitea.futuresens.co.uk/futuresens/logging v1.0.9 h1:uvCQq/plecB0z/bUWOhFhwyYUWGPkTBZHsYNL+3RFvI=
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tarm/serial"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
|
||||
"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/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
dispPort *serial.Port
|
||||
lockserver lockserver.LockServer
|
||||
isPayment bool
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewApp(dispPort *serial.Port, lockType, encoderAddress string, db *sql.DB, isPayment bool) *App {
|
||||
return &App{
|
||||
isPayment: isPayment,
|
||||
dispPort: dispPort,
|
||||
lockserver: lockserver.NewLockServer(lockType, encoderAddress, FatalError),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (app *App) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/issuedoorcard", app.issueDoorCard)
|
||||
mux.HandleFunc("/printroomticket", app.printRoomTicket)
|
||||
mux.HandleFunc("/takepreauth", app.takePreauthorization)
|
||||
mux.HandleFunc("/takepayment", app.takePayment)
|
||||
}
|
||||
|
||||
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("takePreauthorization")
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
theRequest cmstypes.TransactionRec
|
||||
trResult payment.TransactionResultXML
|
||||
result payment.PaymentResult
|
||||
save bool
|
||||
)
|
||||
|
||||
theResponse.Status.Code = http.StatusInternalServerError
|
||||
theResponse.Status.Message = "500 Internal server error"
|
||||
|
||||
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 !app.isPayment {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("takePreauthorization called")
|
||||
if r.Method != http.MethodPost {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Method not allowed; use POST")
|
||||
writeTransactionResult(w, http.StatusMethodNotAllowed, theResponse)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "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)
|
||||
if err != nil {
|
||||
logging.Error(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)
|
||||
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
response, err := client.Post(types.LinkTakePreauthorization, "text/xml", bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Payment 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)
|
||||
}
|
||||
|
||||
// Compose JSON from responseEntries
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
if err := printer.PrintCardholderReceipt(result.CardholderReceipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
}
|
||||
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data, save = payment.BuildPreauthRedirectURL(result.Fields)
|
||||
if save {
|
||||
db.InsertPreauth(r.Context(), app.db, result.Fields, theRequest.CheckoutDate)
|
||||
}
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
}
|
||||
|
||||
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("takePayment")
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
theRequest cmstypes.TransactionRec
|
||||
trResult payment.TransactionResultXML
|
||||
result payment.PaymentResult
|
||||
)
|
||||
|
||||
theResponse.Status.Code = http.StatusInternalServerError
|
||||
theResponse.Status.Message = "500 Internal server error"
|
||||
|
||||
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 !app.isPayment {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("takePayment called")
|
||||
if r.Method != http.MethodPost {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Method not allowed; use POST")
|
||||
writeTransactionResult(w, http.StatusMethodNotAllowed, theResponse)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "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)
|
||||
if err != nil {
|
||||
logging.Error(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)
|
||||
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
response, err := client.Post(types.LinkTakePayment, "text/xml", bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Payment 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)
|
||||
}
|
||||
|
||||
// Compose JSON from responseEntries
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
if err := printer.PrintCardholderReceipt(result.CardholderReceipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
}
|
||||
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildPaymentRedirectURL(result.Fields)
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
}
|
||||
|
||||
func (app *App) issueDoorCard(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 {
|
||||
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadJSON", string(op), "", "", 0)
|
||||
writeError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// parse times
|
||||
checkIn, err := time.Parse(types.CustomLayout, doorReq.CheckinTime)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
|
||||
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)
|
||||
writeError(w, http.StatusBadRequest, "Invalid checkoutTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// dispenser sequence
|
||||
if status, err := dispenser.DispenserSequence(app.dispPort); err != nil {
|
||||
if status != "" {
|
||||
logging.Error(serviceName, status, "Dispense error", string(op), "", "", 0)
|
||||
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||
} else {
|
||||
logging.Error(serviceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error()+"; check card stock")
|
||||
}
|
||||
return
|
||||
} else {
|
||||
log.Info(status)
|
||||
}
|
||||
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
|
||||
// lock server sequence
|
||||
err = app.lockserver.LockSequence()
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
writeError(w, http.StatusBadGateway, err.Error())
|
||||
dispenser.CardOutOfMouth(app.dispPort)
|
||||
return
|
||||
}
|
||||
|
||||
// final dispenser steps
|
||||
if status, err := dispenser.CardOutOfMouth(app.dispPort); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Dispenser eject error", string(op), "", "", 0)
|
||||
writeError(w, http.StatusServiceUnavailable, "Dispenser eject error: "+err.Error())
|
||||
return
|
||||
} else {
|
||||
log.Info(status)
|
||||
}
|
||||
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = "Card issued successfully"
|
||||
// success! return 200 and any data you like
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("printRoomTicket")
|
||||
var roomDetails printer.RoomDetailsRec
|
||||
// Allow CORS preflight if needed
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
log.Println("printRoomTicket called")
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "xml") {
|
||||
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/xml")
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
if err := xml.NewDecoder(r.Body).Decode(&roomDetails); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
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)
|
||||
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)
|
||||
writeError(w, http.StatusInternalServerError, "Print failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Success
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(cmstypes.StatusRec{
|
||||
Code: http.StatusOK,
|
||||
Message: "Print job sent successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
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{
|
||||
Code: status,
|
||||
Message: msg,
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func FatalError(err error) {
|
||||
fmt.Println(err.Error())
|
||||
log.Errorf(err.Error())
|
||||
fmt.Println(". Press Enter to exit...")
|
||||
fmt.Scanln()
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// cmd/hardlink-preauth-release/main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/payment"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
buildVersion = "1.0.2"
|
||||
serviceName = "preauth-release"
|
||||
)
|
||||
|
||||
func main() {
|
||||
config := config.ReadPreauthReleaserConfig()
|
||||
// Setup logging and get file handle
|
||||
logFile, err := logging.SetupLogging(config.LogDir, serviceName, buildVersion)
|
||||
if err != nil {
|
||||
log.Printf("Failed to set up logging: %v\n", err)
|
||||
}
|
||||
defer logFile.Close()
|
||||
database, err := bootstrap.OpenDB(&config)
|
||||
if err != nil {
|
||||
log.WithError(err).Fatal("DB init failed")
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
if err := payment.ReleasePreauthorizations(database); err != nil {
|
||||
log.Error(err)
|
||||
fmt.Println(err)
|
||||
} else {
|
||||
log.Info("Task completed successfully")
|
||||
fmt.Println("Task completed successfully")
|
||||
}
|
||||
|
||||
for i := 20; i > 0; i-- {
|
||||
fmt.Printf("\rExiting in %2d seconds... ", i)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
fmt.Println("\rExiting now. ")
|
||||
os.Exit(0)
|
||||
}
|
||||
@@ -19,8 +19,15 @@ func (lock *AssaLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, check
|
||||
}
|
||||
|
||||
// Checks heart beat of the Assa Abloy lock server and perform key encoding
|
||||
func (lock *AssaLockServer) LockSequence(conn net.Conn) error {
|
||||
func (lock *AssaLockServer) LockSequence() error {
|
||||
const funcName = "AssaLockServer.LockSequence"
|
||||
|
||||
conn, err := InitializeServerConnection(LockServerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
resp, err := sendHeartbeatToServer(conn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%s] heartbeat failed: %v", funcName, err)
|
||||
|
||||
@@ -35,7 +35,7 @@ var (
|
||||
type (
|
||||
LockServer interface {
|
||||
BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error
|
||||
LockSequence(conn net.Conn) error
|
||||
LockSequence() error
|
||||
}
|
||||
|
||||
AssaLockServer struct {
|
||||
|
||||
@@ -53,8 +53,15 @@ func (lock *OmniLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, check
|
||||
}
|
||||
|
||||
// Starts link to the Omnitec lock server and perform key encoding
|
||||
func (lock *OmniLockServer) LockSequence(conn net.Conn) error {
|
||||
func (lock *OmniLockServer) LockSequence() error {
|
||||
const funcName = "OmniLockServer.LockSequence"
|
||||
|
||||
conn, err := InitializeServerConnection(LockServerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Start the link with the lock server
|
||||
regs, err := lock.linkStart(conn)
|
||||
if err != nil {
|
||||
|
||||
+119
-87
@@ -31,8 +31,8 @@ func calculateLRC(data []byte) byte {
|
||||
func (lock *SaltoLockServer) BuildCommand(req DoorCardRequest, checkIn, checkOut time.Time) error {
|
||||
// helper: hh[mm]DDMMYY
|
||||
fmtStamp := func(t time.Time) string {
|
||||
return fmt.Sprintf("%02d%02d%02d%02d%02d",
|
||||
t.Hour(), t.Minute(), t.Day(), int(t.Month()), t.Year()%100)
|
||||
return fmt.Sprintf("%02d%02d%02d%02d",
|
||||
t.Hour(), t.Day(), int(t.Month()), t.Year()%100)
|
||||
}
|
||||
start := fmtStamp(checkIn)
|
||||
expiry := fmtStamp(checkOut)
|
||||
@@ -75,120 +75,152 @@ func (lock *SaltoLockServer) BuildCommand(req DoorCardRequest, checkIn, checkOut
|
||||
return nil
|
||||
}
|
||||
|
||||
// LockSequence performs the full ENQ/ACK handshake and command exchange
|
||||
func (lock *SaltoLockServer) LockSequence(conn net.Conn) error {
|
||||
log.Infof("Sending command: %q", string(lock.command))
|
||||
// readFrame consumes a full frame starting with firstByte (expected STX).
|
||||
// It reads up to ETX and then attempts to read a trailing LRC (or CR). timeout controls read deadlines.
|
||||
func (lock *SaltoLockServer) readFrame(conn net.Conn, reader *bufio.Reader, firstByte byte, timeout time.Duration) ([]byte, error) {
|
||||
frame := []byte{firstByte}
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
b, e := reader.ReadByte()
|
||||
if e != nil {
|
||||
return frame, fmt.Errorf("error reading frame body: %w", e)
|
||||
}
|
||||
frame = append(frame, b)
|
||||
if b == ETX {
|
||||
break
|
||||
}
|
||||
}
|
||||
// read trailing LRC (or CR) if present (non-blocking w/ timeout)
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
if lrc, e := reader.ReadByte(); e == nil {
|
||||
frame = append(frame, lrc)
|
||||
} else {
|
||||
// Not fatal: some devices might omit LRC/CR — just log
|
||||
log.Warnf("readFrame: no trailing LRC/CR: %v", e)
|
||||
}
|
||||
return frame, nil
|
||||
}
|
||||
|
||||
const timeout = 10 * time.Second
|
||||
// waitForAck waits for ACK or NAK. If STX frames are encountered they are drained
|
||||
// using readFrame. drainedCount (if non-nil) accumulates the number of drained frames.
|
||||
func (lock *SaltoLockServer) waitForAck(conn net.Conn, reader *bufio.Reader, timeout time.Duration, drainedCount *int) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(time.Until(deadline)))
|
||||
b, e := reader.ReadByte()
|
||||
if e != nil {
|
||||
return fmt.Errorf("error waiting for ACK/NAK: %w", e)
|
||||
}
|
||||
switch b {
|
||||
case ACK:
|
||||
return nil
|
||||
case NAK:
|
||||
return fmt.Errorf("received NAK")
|
||||
case STX:
|
||||
// stale or queued full response: consume it and continue waiting
|
||||
frame, fe := lock.readFrame(conn, reader, b, timeout)
|
||||
if fe != nil {
|
||||
// if we can't consume frame, consider it an error
|
||||
return fmt.Errorf("failed to consume queued STX frame: %w", fe)
|
||||
}
|
||||
if drainedCount != nil {
|
||||
*drainedCount++
|
||||
log.Infof("Drained queued frame #%d (while waiting for ACK): %q", *drainedCount, string(frame))
|
||||
} else {
|
||||
log.Infof("Drained queued frame (while waiting for ACK): %q", string(frame))
|
||||
}
|
||||
// loop to keep waiting for ACK
|
||||
default:
|
||||
// Unexpected byte while waiting for ACK. Log and continue reading.
|
||||
log.Warnf("waitForAck: unexpected byte 0x%X while waiting for ACK; ignoring", b)
|
||||
// keep looping until timeout or ACK/NAK
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LockSequence performs the full ENQ/ACK handshake and command exchange
|
||||
func (lock *SaltoLockServer) LockSequence() error {
|
||||
const timeout = 20 * time.Second
|
||||
var (
|
||||
err error
|
||||
resp []byte
|
||||
resp []byte
|
||||
drained = 0 // count of stale frames consumed across waits
|
||||
)
|
||||
|
||||
conn, err := InitializeServerConnection(LockServerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
reader := bufio.NewReader(conn)
|
||||
|
||||
// 1. Send ENQ
|
||||
log.Infof("Sending ENQ")
|
||||
if _, e := conn.Write([]byte{ENQ}); e != nil {
|
||||
return fmt.Errorf("failed to send ENQ: %w", e)
|
||||
}
|
||||
|
||||
// 2. Expect ACK
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
if b, e := reader.ReadByte(); e != nil {
|
||||
// 2. Expect ACK (but drain any queued STX frames first)
|
||||
if e := lock.waitForAck(conn, reader, timeout, &drained); e != nil {
|
||||
return fmt.Errorf("error awaiting ACK to ENQ: %w", e)
|
||||
} else if b != ACK {
|
||||
return fmt.Errorf("expected ACK after ENQ, got 0x%X", b)
|
||||
}
|
||||
|
||||
// 3. Send command frame
|
||||
log.Infof("Sending encoding command: %q", string(lock.command))
|
||||
if _, e := conn.Write(lock.command); e != nil {
|
||||
return fmt.Errorf("failed to send command frame: %w", e)
|
||||
}
|
||||
|
||||
// 4. Expect ACK to command
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
if b, e := reader.ReadByte(); e != nil {
|
||||
// 4. Expect ACK to command (again drain any queued frames that might precede it)
|
||||
if e := lock.waitForAck(conn, reader, timeout, &drained); e != nil {
|
||||
return fmt.Errorf("error awaiting ACK to command: %w", e)
|
||||
} else if b == NAK {
|
||||
return fmt.Errorf("command rejected (NAK)")
|
||||
} else if b != ACK {
|
||||
return fmt.Errorf("expected ACK to command, got 0x%X", b)
|
||||
}
|
||||
|
||||
// 5. Expect STX
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
stx, e := reader.ReadByte()
|
||||
if e != nil {
|
||||
return fmt.Errorf("error reading STX: %w", e)
|
||||
}
|
||||
resp = append(resp, stx)
|
||||
if stx != STX {
|
||||
err = fmt.Errorf("expected STX, got 0x%X", stx)
|
||||
}
|
||||
|
||||
// 6. Read separator after STX
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
if sep, e := reader.ReadByte(); e == nil {
|
||||
resp = append(resp, sep)
|
||||
} else if err == nil {
|
||||
err = fmt.Errorf("error reading separator after STX: %w", e)
|
||||
}
|
||||
|
||||
// 7. Read command code (e.g., CN, TD)
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
b1, e1 := reader.ReadByte()
|
||||
if e1 == nil {
|
||||
resp = append(resp, b1)
|
||||
} else if err == nil {
|
||||
err = fmt.Errorf("error reading first response byte: %w", e1)
|
||||
}
|
||||
b2, e2 := reader.ReadByte()
|
||||
if e2 == nil {
|
||||
resp = append(resp, b2)
|
||||
} else if err == nil {
|
||||
err = fmt.Errorf("error reading second response byte: %w", e2)
|
||||
}
|
||||
|
||||
switch {
|
||||
case b1 == 'C' && b2 == 'N':
|
||||
log.Infof("LockSequence: command response is CN (normal)")
|
||||
case b1 == 'C' && b2 == 'C':
|
||||
log.Infof("LockSequence: command response is CC (follow-up)")
|
||||
case b1 == 'T' && b2 == 'D':
|
||||
log.Warnf("LockSequence: command response is TD (room does not exist)")
|
||||
if err == nil {
|
||||
err = fmt.Errorf("lock response indicates room does not exist")
|
||||
}
|
||||
default:
|
||||
log.Warnf("LockSequence: unexpected command response %q", string(resp))
|
||||
if err == nil {
|
||||
err = fmt.Errorf("error encoding keycard, unexpected response")
|
||||
}
|
||||
}
|
||||
|
||||
// 8. Read rest of message until ETX
|
||||
// 5. Now read the *next* STX frame which should be the response to our command.
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
c, e := reader.ReadByte()
|
||||
conn.SetReadDeadline(time.Now().Add(40 * time.Second))
|
||||
b, e := reader.ReadByte()
|
||||
if e != nil {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("error reading response body: %w", e)
|
||||
}
|
||||
break
|
||||
return fmt.Errorf("error reading response start: %w", e)
|
||||
}
|
||||
resp = append(resp, c)
|
||||
if c == ETX {
|
||||
break
|
||||
if b != STX {
|
||||
// If anything else arrives, it might be another control byte or noise;
|
||||
// log and keep consuming until we find STX.
|
||||
log.Warnf("expected STX to start response but got 0x%X; ignoring", b)
|
||||
continue
|
||||
}
|
||||
// consume full response frame
|
||||
frame, fe := lock.readFrame(conn, reader, b, timeout)
|
||||
if fe != nil {
|
||||
return fmt.Errorf("error reading response frame: %w", fe)
|
||||
}
|
||||
resp = append(resp, frame...)
|
||||
break
|
||||
}
|
||||
|
||||
// 9. Optional: read trailing byte (LRC or CR)
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
if lrc, e := reader.ReadByte(); e == nil {
|
||||
resp = append(resp, lrc)
|
||||
// parse the command code within response frame
|
||||
if len(resp) >= 4 {
|
||||
// The command bytes are usually at indices 2 and 3 if separator is at index 1
|
||||
sepIndex := 1
|
||||
b1 := resp[sepIndex+1]
|
||||
b2 := resp[sepIndex+2]
|
||||
switch {
|
||||
case b1 == 'C' && b2 == 'N':
|
||||
log.Infof("LockSequence: command response is CN (normal)")
|
||||
case b1 == 'C' && b2 == 'C':
|
||||
log.Infof("LockSequence: command response is CC (follow-up)")
|
||||
case b1 == 'T' && b2 == 'D':
|
||||
log.Warnf("LockSequence: command response is TD (room does not exist): %q", string(resp))
|
||||
return fmt.Errorf("lock response indicates room does not exist: %q", string(resp))
|
||||
default:
|
||||
log.Warnf("LockSequence: unexpected command response %q", string(resp))
|
||||
return fmt.Errorf("error encoding keycard, unexpected response: %q", string(resp))
|
||||
}
|
||||
} else {
|
||||
log.Warnf("LockSequence: failed to read trailing LRC/CR: %v", e)
|
||||
log.Warnf("LockSequence: response too short: %q", string(resp))
|
||||
return fmt.Errorf("response too short")
|
||||
}
|
||||
|
||||
log.Infof("LockSequence: received response: %q", string(resp))
|
||||
return err
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,8 +3,7 @@ package lockserver
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
@@ -36,8 +35,9 @@ func (lock *TLJLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, checkO
|
||||
return nil
|
||||
}
|
||||
|
||||
func (lock *TLJLockServer) LockSequence(conn net.Conn) error {
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
func (lock *TLJLockServer) LockSequence() error {
|
||||
log.Infof("Sending command: %q", lock.command)
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Get(lock.command)
|
||||
if err != nil {
|
||||
return fmt.Errorf("HTTP request failed: %v", err)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// setupLogging ensures log directory, opens log file, and configures logrus.
|
||||
// Returns the *os.File so caller can defer its Close().
|
||||
func SetupLogging(logDir, serviceName, buildVersion string) (*os.File, error) {
|
||||
fileName := logDir + serviceName + ".log"
|
||||
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open log file: %w", err)
|
||||
}
|
||||
|
||||
log.SetOutput(f)
|
||||
log.SetFormatter(&log.JSONFormatter{
|
||||
TimestampFormat: time.RFC3339,
|
||||
})
|
||||
log.SetLevel(log.InfoLevel)
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"buildVersion": buildVersion,
|
||||
}).Info("Logging initialized")
|
||||
|
||||
return f, nil
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
// "database/sql"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -18,486 +14,105 @@ import (
|
||||
"github.com/tarm/serial"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
yaml "gopkg.in/yaml.v3"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/handlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/printer"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
buildVersion = "1.0.9"
|
||||
serviceName = "hardlink"
|
||||
customLayout = "2006-01-02 15:04:05 -0700"
|
||||
transactionUrl = "http://127.0.0.1:18181/start-transaction/"
|
||||
buildVersion = "1.0.30"
|
||||
serviceName = "hardlink"
|
||||
)
|
||||
|
||||
// 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"`
|
||||
IsPayment bool `yaml:"isPayment"`
|
||||
}
|
||||
|
||||
// App holds shared resources.
|
||||
type App struct {
|
||||
dispPort *serial.Port
|
||||
lockConn net.Conn
|
||||
lockserver lockserver.LockServer
|
||||
}
|
||||
|
||||
func newApp(dispPort *serial.Port, lockConn net.Conn, config configRec) *App {
|
||||
return &App{
|
||||
dispPort: dispPort,
|
||||
lockConn: lockConn,
|
||||
lockserver: lockserver.NewLockServer(config.LockType, config.EncoderAddress, fatalError),
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Load config
|
||||
config := readConfig()
|
||||
config := config.ReadHardlinkConfig()
|
||||
printer.Layout = readTicketLayout()
|
||||
printer.PrinterName = config.PrinterName
|
||||
|
||||
var lockConn net.Conn
|
||||
lockserver.Cert = config.Cert
|
||||
lockserver.LockServerURL = config.LockserverUrl
|
||||
dispHandle := &serial.Port{}
|
||||
|
||||
// Setup logging and get file handle
|
||||
logFile, err := setupLogging(config.LogDir)
|
||||
logFile, err := logging.SetupLogging(config.LogDir, serviceName, buildVersion)
|
||||
if err != nil {
|
||||
log.Printf("Failed to set up logging: %v\n", err)
|
||||
}
|
||||
defer logFile.Close()
|
||||
|
||||
// Initialize dispenser
|
||||
dispenser.SerialPort = config.DispenserPort
|
||||
dispenser.Address = []byte(config.DispenserAdrr)
|
||||
dispHandle, err := dispenser.InitializeDispenser()
|
||||
if err != nil {
|
||||
fatalError(err)
|
||||
}
|
||||
defer dispHandle.Close()
|
||||
|
||||
status, err := dispenser.CheckDispenserStatus(dispHandle)
|
||||
if err != nil {
|
||||
if len(status) == 0 {
|
||||
err = fmt.Errorf("%s; wrong dispenser address: %s", err, config.DispenserAdrr)
|
||||
fatalError(err)
|
||||
} else {
|
||||
fmt.Println(status)
|
||||
fmt.Println(err.Error())
|
||||
if !config.TestMode {
|
||||
dispenser.SerialPort = config.DispenserPort
|
||||
dispenser.Address = []byte(config.DispenserAdrr)
|
||||
dispHandle, err = dispenser.InitializeDispenser()
|
||||
if err != nil {
|
||||
handlers.FatalError(err)
|
||||
}
|
||||
}
|
||||
log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status)
|
||||
defer dispHandle.Close()
|
||||
|
||||
// Initialize lock-server connection once
|
||||
status, err := dispenser.CheckDispenserStatus(dispHandle)
|
||||
if err != nil {
|
||||
if len(status) == 0 {
|
||||
err = fmt.Errorf("%s; wrong dispenser address: %s", err, config.DispenserAdrr)
|
||||
handlers.FatalError(err)
|
||||
} else {
|
||||
fmt.Println(status)
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
}
|
||||
log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status)
|
||||
}
|
||||
|
||||
// Test lock-server connection
|
||||
switch strings.ToLower(config.LockType) {
|
||||
case lockserver.TLJ:
|
||||
|
||||
default:
|
||||
lockConn, err = lockserver.InitializeServerConnection(config.LockserverUrl)
|
||||
lockConn, err := lockserver.InitializeServerConnection(config.LockserverUrl)
|
||||
if err != nil {
|
||||
fatalError(err)
|
||||
fmt.Println(err.Error())
|
||||
log.Errorf(err.Error())
|
||||
} else {
|
||||
fmt.Printf("Connected to the lock server successfuly at %s\n", config.LockserverUrl)
|
||||
log.Infof("Connected to the lock server successfuly at %s", config.LockserverUrl)
|
||||
lockConn.Close()
|
||||
}
|
||||
defer lockConn.Close()
|
||||
log.Infof("Connected to lock server at %s", config.LockserverUrl)
|
||||
}
|
||||
|
||||
// db, err := payment.InitMSSQL(config.dbport, config.dbname, config.dbuser, config.dbpassword)
|
||||
// if err != nil {
|
||||
// fatalError(fmt.Errorf("DB init failed: %v", err))
|
||||
// }
|
||||
// defer db.Close()
|
||||
database, err := bootstrap.OpenDB(&config)
|
||||
if err != nil {
|
||||
log.Warnf("DB init failed: %v", err)
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
if config.IsPayment {
|
||||
startClient := func() (*exec.Cmd, error) {
|
||||
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to start ChipDnaClient: %v", err)
|
||||
}
|
||||
log.Infof("ChipDnaClient started with PID %d", cmd.Process.Pid)
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
cmd, err := startClient()
|
||||
if err != nil {
|
||||
fatalError(err)
|
||||
}
|
||||
|
||||
// Restart loop
|
||||
go func() {
|
||||
for {
|
||||
err := cmd.Wait()
|
||||
if err != nil {
|
||||
log.Errorf("ChipDnaClient exited unexpectedly: %v", err)
|
||||
time.Sleep(2 * time.Second)
|
||||
cmd, err = startClient()
|
||||
if err != nil {
|
||||
log.Errorf("Restart failed: %v", err)
|
||||
return
|
||||
}
|
||||
log.Info("ChipDnaClient restarted successfully")
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle shutdown signals
|
||||
sigs := make(chan os.Signal, 1)
|
||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-sigs
|
||||
log.Info("Shutting down...")
|
||||
if cmd.Process != nil {
|
||||
log.Info("Sending SIGTERM to ChipDnaClient...")
|
||||
_ = cmd.Process.Signal(syscall.SIGTERM)
|
||||
// wait up to 5s for graceful shutdown
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
select {
|
||||
case <-time.After(5 * time.Second):
|
||||
log.Warn("ChipDnaClient did not exit in time, killing...")
|
||||
_ = cmd.Process.Kill()
|
||||
case err := <-done:
|
||||
log.Infof("ChipDnaClient exited cleanly: %v", err)
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
}()
|
||||
fmt.Println("Payment processing is enabled")
|
||||
log.Info("Payment processing is enabled")
|
||||
startChipDnaClient()
|
||||
} else {
|
||||
fmt.Println("Payment processing is disabled")
|
||||
log.Info("Payment processing is disabled")
|
||||
}
|
||||
|
||||
// Create App and wire routes
|
||||
// dispHandle := &serial.Port{} // Placeholder, replace with actual dispenser handle
|
||||
app := newApp(dispHandle, lockConn, config)
|
||||
app := handlers.NewApp(dispHandle, config.LockType, config.EncoderAddress, database, config.IsPayment)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
setUpRoutes(app, mux)
|
||||
app.RegisterRoutes(mux)
|
||||
|
||||
addr := fmt.Sprintf(":%d", config.Port)
|
||||
log.Infof("Starting HTTP server on http://localhost%s", addr)
|
||||
fmt.Printf("Starting HTTP server on http://localhost%s", addr)
|
||||
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||
fatalError(err)
|
||||
handlers.FatalError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func setUpRoutes(app *App, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/issuedoorcard", app.issueDoorCard)
|
||||
mux.HandleFunc("/printroomticket", app.printRoomTicket)
|
||||
mux.HandleFunc("/starttransaction", app.startTransaction)
|
||||
}
|
||||
|
||||
func fatalError(err error) {
|
||||
fmt.Println(err.Error())
|
||||
log.Errorf(err.Error())
|
||||
fmt.Println(". Press Enter to exit...")
|
||||
fmt.Scanln()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// setupLogging ensures log directory, opens log file, and configures logrus.
|
||||
// Returns the *os.File so caller can defer its Close().
|
||||
func setupLogging(logDir string) (*os.File, error) {
|
||||
fileName := logDir + serviceName + ".log"
|
||||
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open log file: %w", err)
|
||||
}
|
||||
|
||||
log.SetOutput(f)
|
||||
log.SetFormatter(&log.JSONFormatter{
|
||||
TimestampFormat: time.RFC3339,
|
||||
})
|
||||
log.SetLevel(log.InfoLevel)
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"buildVersion": buildVersion,
|
||||
}).Info("Logging initialized")
|
||||
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// 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{
|
||||
Code: status,
|
||||
Message: msg,
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
func (app *App) startTransaction(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("startTransaction")
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
cardholderReceipt string
|
||||
)
|
||||
|
||||
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("startTransaction called")
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "text/xml" {
|
||||
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be text/xml")
|
||||
return
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 90 * time.Second}
|
||||
response, err := client.Post(transactionUrl, "text/xml", r.Body)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
|
||||
writeError(w, http.StatusInternalServerError, "Payment processing failed: "+err.Error())
|
||||
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)
|
||||
writeError(w, http.StatusInternalServerError, "Failed to read response body: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
responseEntries, _ := payment.ParseTransactionResult(body)
|
||||
|
||||
// Compose JSON from responseEntries
|
||||
result := make(map[string]string)
|
||||
for _, e := range responseEntries {
|
||||
switch e.Key {
|
||||
case "RECEIPT_DATA", "RECEIPT_DATA_MERCHANT":
|
||||
case "RECEIPT_DATA_CARDHOLDER":
|
||||
cardholderReceipt = e.Value
|
||||
case "TRANSACTION_RESULT":
|
||||
theResponse.Status.Message = e.Value
|
||||
theResponse.Status.Code = http.StatusOK
|
||||
result[e.Key] = e.Value
|
||||
default:
|
||||
result[e.Key] = e.Value
|
||||
}
|
||||
}
|
||||
|
||||
if err := printer.PrintCardholderReceipt(cardholderReceipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
}
|
||||
|
||||
// Insert into DB
|
||||
// if err := payment.InsertTransactionRecord(r.Context(), app.db, result); err != nil {
|
||||
// log.Errorf("DB insert error: %v", err)
|
||||
// }
|
||||
|
||||
theResponse.Data = payment.BuildRedirectURL(result)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if err := json.NewEncoder(w).Encode(theResponse); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "JSON encode error", string(op), "", "", 0)
|
||||
}
|
||||
}
|
||||
|
||||
func (app *App) issueDoorCard(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 {
|
||||
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadJSON", string(op), "", "", 0)
|
||||
writeError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// parse times
|
||||
checkIn, err := time.Parse(customLayout, doorReq.CheckinTime)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
|
||||
writeError(w, http.StatusBadRequest, "Invalid checkinTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
checkOut, err := time.Parse(customLayout, doorReq.CheckoutTime)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Invalid checkoutTime format", string(op), "", "", 0)
|
||||
writeError(w, http.StatusBadRequest, "Invalid checkoutTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// dispenser sequence
|
||||
if status, err := dispenser.DispenserSequence(app.dispPort); err != nil {
|
||||
if status != "" {
|
||||
logging.Error(serviceName, status, "Dispense error", string(op), "", "", 0)
|
||||
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||
} else {
|
||||
logging.Error(serviceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error()+"; check card stock")
|
||||
}
|
||||
return
|
||||
} else {
|
||||
log.Info(status)
|
||||
}
|
||||
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
|
||||
// lock server sequence
|
||||
err = app.lockserver.LockSequence(app.lockConn)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
writeError(w, http.StatusBadGateway, err.Error())
|
||||
dispenser.CardOutOfMouth(app.dispPort)
|
||||
return
|
||||
}
|
||||
|
||||
// final dispenser steps
|
||||
if status, err := dispenser.CardOutOfMouth(app.dispPort); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Dispenser eject error", string(op), "", "", 0)
|
||||
writeError(w, http.StatusServiceUnavailable, "Dispenser eject error: "+err.Error())
|
||||
return
|
||||
} else {
|
||||
log.Info(status)
|
||||
}
|
||||
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = "Card issued successfully"
|
||||
// success! return 200 and any data you like
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("printRoomTicket")
|
||||
var roomDetails printer.RoomDetailsRec
|
||||
// Allow CORS preflight if needed
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
log.Println("printRoomTicket called")
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "xml") {
|
||||
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/xml")
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
if err := xml.NewDecoder(r.Body).Decode(&roomDetails); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
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)
|
||||
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)
|
||||
writeError(w, http.StatusInternalServerError, "Print failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Success
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(cmstypes.StatusRec{
|
||||
Code: http.StatusOK,
|
||||
Message: "Print job sent successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// readConfig reads config.yml and applies defaults.
|
||||
func readConfig() configRec {
|
||||
var cfg configRec
|
||||
const configName = "config.yml"
|
||||
defaultPort := 9091
|
||||
sep := string(os.PathSeparator)
|
||||
|
||||
data, err := os.ReadFile(configName)
|
||||
if err != nil {
|
||||
log.Warnf("ReadConfig %s: %v", configName, err)
|
||||
} else if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
log.Warnf("Unmarshal config: %v", err)
|
||||
}
|
||||
|
||||
if cfg.Port == 0 {
|
||||
cfg.Port = defaultPort
|
||||
}
|
||||
|
||||
if cfg.LockType == "" {
|
||||
err = fmt.Errorf("LockType is required in %s", configName)
|
||||
fatalError(err)
|
||||
}
|
||||
cfg.LockType = strings.ToLower(cfg.LockType)
|
||||
|
||||
if cfg.LogDir == "" {
|
||||
cfg.LogDir = "./logs" + sep
|
||||
} else if !strings.HasSuffix(cfg.LogDir, sep) {
|
||||
cfg.LogDir += sep
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func readTicketLayout() printer.LayoutOptions {
|
||||
const layoutName = "TicketLayout.xml"
|
||||
var layout printer.LayoutOptions
|
||||
@@ -505,13 +120,70 @@ func readTicketLayout() printer.LayoutOptions {
|
||||
// 1) Read the file
|
||||
data, err := os.ReadFile(layoutName)
|
||||
if err != nil {
|
||||
fatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
|
||||
handlers.FatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
|
||||
}
|
||||
|
||||
// 2) Unmarshal into your struct
|
||||
if err := xml.Unmarshal(data, &layout); err != nil {
|
||||
fatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
|
||||
handlers.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")
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to start ChipDnaClient: %v", err)
|
||||
}
|
||||
log.Infof("ChipDnaClient started with PID %d", cmd.Process.Pid)
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
cmd, err := startClient()
|
||||
if err != nil {
|
||||
handlers.FatalError(err)
|
||||
}
|
||||
|
||||
// Restart loop
|
||||
go func() {
|
||||
for {
|
||||
err := cmd.Wait()
|
||||
if err != nil {
|
||||
log.Errorf("ChipDnaClient exited unexpectedly: %v", err)
|
||||
time.Sleep(2 * time.Second)
|
||||
cmd, err = startClient()
|
||||
if err != nil {
|
||||
log.Errorf("Restart failed: %v", err)
|
||||
return
|
||||
}
|
||||
log.Info("ChipDnaClient restarted successfully")
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle shutdown signals
|
||||
sigs := make(chan os.Signal, 1)
|
||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-sigs
|
||||
log.Info("Shutting down...")
|
||||
if cmd.Process != nil {
|
||||
log.Info("Sending SIGTERM to ChipDnaClient...")
|
||||
_ = cmd.Process.Signal(syscall.SIGTERM)
|
||||
// wait up to 5s for graceful shutdown
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
select {
|
||||
case <-time.After(5 * time.Second):
|
||||
log.Warn("ChipDnaClient did not exit in time, killing...")
|
||||
_ = cmd.Process.Kill()
|
||||
case err := <-done:
|
||||
log.Infof("ChipDnaClient exited cleanly: %v", err)
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
}()
|
||||
}
|
||||
|
||||
+135
-233
@@ -1,30 +1,19 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
_ "github.com/denisenkom/go-mssqldb"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
ResultApproved = "approved"
|
||||
ResultDeclined = "declined"
|
||||
ResultCancelled = "cancelled"
|
||||
ResultPending = "pending"
|
||||
ResultError = "error"
|
||||
CheckinSuccessfulEndpoint = "/successful" // Endpoint to send guest to after successful payment
|
||||
CheckinUnsuccessfulEndpoint = "/unsuccessful"
|
||||
)
|
||||
|
||||
// XML parsing structs
|
||||
type (
|
||||
TransactionRec struct {
|
||||
@@ -42,240 +31,153 @@ type (
|
||||
Key string `xml:"Key"`
|
||||
Value string `xml:"Value"`
|
||||
}
|
||||
|
||||
TransactionConfirmation struct {
|
||||
XMLName xml.Name `xml:"TransactionConfirmation"`
|
||||
Result string `xml:"Result"`
|
||||
Errors string `xml:"Errors"`
|
||||
ErrorDescription string `xml:"ErrorDescription"`
|
||||
ReceiptDataCardholder string `xml:"ReceiptDataCardholder"`
|
||||
}
|
||||
|
||||
PaymentResult struct {
|
||||
Fields map[string]string
|
||||
CardholderReceipt string
|
||||
Status cmstypes.StatusRec
|
||||
}
|
||||
|
||||
TransactionInfo struct {
|
||||
transactionRes string
|
||||
transactionState string
|
||||
}
|
||||
)
|
||||
|
||||
// ParseTransactionResult parses the XML into entries.
|
||||
func ParseTransactionResult(data []byte) ([]EntryXML, error) {
|
||||
var tr TransactionResultXML
|
||||
func (tr *TransactionResultXML) ParseTransactionResult(data []byte) error {
|
||||
if err := xml.Unmarshal(data, &tr); err != nil {
|
||||
return nil, fmt.Errorf("XML unmarshal: %w", err)
|
||||
return fmt.Errorf("XML unmarshal: %w", err)
|
||||
}
|
||||
return tr.Entries, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// initMSSQL opens and pings the SQL Server instance localhost\SQLEXPRESS
|
||||
// using user=Kiosk, password=Gr33nfarm, database=TransactionDatabase.
|
||||
func InitMSSQL(port int, user, password, database string) (*sql.DB, error) {
|
||||
const server = "localhost"
|
||||
|
||||
// Use TCP; drop the \SQLEXPRESS instance name
|
||||
connString := fmt.Sprintf(
|
||||
"sqlserver://%s:%s@%s:%d?database=%s&encrypt=disable",
|
||||
user, password, server, port, database,
|
||||
)
|
||||
|
||||
db, err := sql.Open("sqlserver", connString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening DB: %w", err)
|
||||
}
|
||||
|
||||
// Verify connectivity
|
||||
if err := db.PingContext(context.Background()); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("pinging DB: %w", err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// insertTransactionRecord inserts one row into TransactionRecords.
|
||||
// m is the map from keys to string values as returned by ChipDNA.
|
||||
func InsertTransactionRecord(ctx context.Context, db *sql.DB, m map[string]string) error {
|
||||
// Extract fields with defaults or NULL handling.
|
||||
|
||||
// 1. TxnReference <- REFERENCE
|
||||
ref, ok := m["REFERENCE"]
|
||||
if !ok || ref == "" {
|
||||
return fmt.Errorf("missing REFERENCE in result map")
|
||||
}
|
||||
|
||||
// 2. TxnDateTime <- parse AUTH_DATE_TIME (layout "20060102150405"), else use now
|
||||
var txnTime time.Time
|
||||
if s, ok := m["AUTH_DATE_TIME"]; ok && s != "" {
|
||||
t, err := time.ParseInLocation("20060102150405", s, time.UTC)
|
||||
if err != nil {
|
||||
// fallback: use now
|
||||
txnTime = time.Now().UTC()
|
||||
} else {
|
||||
txnTime = t
|
||||
func (ti *TransactionInfo) FillFromTransactionResult(trResult TransactionResultXML) {
|
||||
for _, e := range trResult.Entries {
|
||||
switch e.Key {
|
||||
case types.TransactionResult:
|
||||
ti.transactionRes = e.Value
|
||||
case types.TransactionState:
|
||||
ti.transactionState = e.Value
|
||||
}
|
||||
} else {
|
||||
txnTime = time.Now().UTC()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PaymentResult) FillFromTransactionResult(trResult TransactionResultXML) {
|
||||
if r.Fields == nil {
|
||||
r.Fields = make(map[string]string)
|
||||
}
|
||||
|
||||
// 3. TotalAmount <- parse TOTAL_AMOUNT minor units into float (divide by 100)
|
||||
var totalAmount sql.NullFloat64
|
||||
if s, ok := m["TOTAL_AMOUNT"]; ok && s != "" {
|
||||
if iv, err := strconv.ParseInt(s, 10, 64); err == nil {
|
||||
// convert minor units to major (e.g. 150 -> 1.50)
|
||||
totalAmount.Float64 = float64(iv) / 100.0
|
||||
totalAmount.Valid = true
|
||||
for _, e := range trResult.Entries {
|
||||
switch e.Key {
|
||||
|
||||
case types.ReceiptData, types.ReceiptDataMerchant:
|
||||
// intentionally ignored
|
||||
|
||||
case types.ReceiptDataCardholder:
|
||||
r.CardholderReceipt = e.Value
|
||||
|
||||
case types.TransactionResult:
|
||||
r.Status.Message = e.Value
|
||||
r.Status.Code = http.StatusOK
|
||||
r.Fields[e.Key] = e.Value
|
||||
|
||||
default:
|
||||
r.Fields[e.Key] = e.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BuildRedirectURL builds the redirect URL to send the guest to after payment.
|
||||
func BuildPaymentRedirectURL(result map[string]string) string {
|
||||
res := result[types.TransactionResult]
|
||||
|
||||
// Transaction approved?
|
||||
if strings.EqualFold(res, types.ResultApproved) {
|
||||
// Transaction confirmed?
|
||||
if strings.EqualFold(result[types.ConfirmResult], types.ResultApproved) {
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Transaction approved and confirmed")
|
||||
|
||||
return buildSuccessURL(result)
|
||||
}
|
||||
|
||||
// Not confirmed
|
||||
log.WithFields(log.Fields{types.LogFieldError: result[types.ConfirmResult], types.LogFieldDescription: result[types.ConfirmErrors]}).
|
||||
Error("Transaction approved but not confirmed")
|
||||
|
||||
return BuildFailureURL(result[types.ConfirmResult], result[types.ConfirmErrors])
|
||||
}
|
||||
|
||||
// Not approved
|
||||
return BuildFailureURL(res, result[types.Errors])
|
||||
}
|
||||
|
||||
func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
||||
res := result[types.TransactionResult]
|
||||
tType := result[types.TransactionType]
|
||||
|
||||
// Transaction approved?
|
||||
if strings.EqualFold(res, types.ResultApproved) {
|
||||
switch {
|
||||
// Transaction type AccountVerification?
|
||||
case strings.EqualFold(tType, types.AccountVerificationType):
|
||||
log.WithField(types.LogResult, result[types.TransactionResult]).
|
||||
Info("Account verification approved")
|
||||
|
||||
return buildSuccessURL(result), false
|
||||
|
||||
// Transaction type Sale?
|
||||
case strings.EqualFold(tType, types.SaleTransactionType):
|
||||
// Transaction confirmed?
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Amount preauthorized successfully")
|
||||
|
||||
return buildSuccessURL(result), true
|
||||
}
|
||||
}
|
||||
|
||||
// 4. MerchantId <- MERCHANT_ID_MASKED
|
||||
merchantId := sql.NullString{String: m["MERCHANT_ID_MASKED"], Valid: m["MERCHANT_ID_MASKED"] != ""}
|
||||
|
||||
// 5. TerminalId <- TERMINAL_ID_MASKED
|
||||
terminalId := sql.NullString{String: m["TERMINAL_ID_MASKED"], Valid: m["TERMINAL_ID_MASKED"] != ""}
|
||||
|
||||
// 6. CardSchemeName <- CARD_SCHEME
|
||||
cardScheme := sql.NullString{String: m["CARD_SCHEME"], Valid: m["CARD_SCHEME"] != ""}
|
||||
|
||||
// 7. ExpiryDate <- EXPIRY_DATE
|
||||
expiryDate := sql.NullString{String: m["EXPIRY_DATE"], Valid: m["EXPIRY_DATE"] != ""}
|
||||
|
||||
// 8. RecordReference <- CARD_REFERENCE
|
||||
recordRef := sql.NullString{String: m["CARD_REFERENCE"], Valid: m["CARD_REFERENCE"] != ""}
|
||||
|
||||
// 9. Token1 <- CARD_HASH
|
||||
token1 := sql.NullString{String: m["CARD_HASH"], Valid: m["CARD_HASH"] != ""}
|
||||
|
||||
// 10. Token2 <- CARDEASE_REFERENCE
|
||||
token2 := sql.NullString{String: m["CARDEASE_REFERENCE"], Valid: m["CARDEASE_REFERENCE"] != ""}
|
||||
|
||||
// 11. PanMasked <- PAN_MASKED
|
||||
panMasked := sql.NullString{String: m["PAN_MASKED"], Valid: m["PAN_MASKED"] != ""}
|
||||
|
||||
// 12. AuthCode <- AUTH_CODE
|
||||
authCode := sql.NullString{String: m["AUTH_CODE"], Valid: m["AUTH_CODE"] != ""}
|
||||
|
||||
// 13. TransactionResult <- TRANSACTION_RESULT
|
||||
txnResult := sql.NullString{String: m["TRANSACTION_RESULT"], Valid: m["TRANSACTION_RESULT"] != ""}
|
||||
|
||||
// Build INSERT statement with named parameters.
|
||||
// Assuming your table is [TransactionDatabase].[dbo].[TransactionRecords].
|
||||
const stmt = `
|
||||
INSERT INTO [TransactionDatabase].[dbo].[TransactionRecords]
|
||||
(
|
||||
[TxnReference],
|
||||
[TxnDateTime],
|
||||
[TotalAmount],
|
||||
[MerchantId],
|
||||
[TerminalId],
|
||||
[CardSchemeName],
|
||||
[ExpiryDate],
|
||||
[RecordReference],
|
||||
[Token1],
|
||||
[Token2],
|
||||
[PanMasked],
|
||||
[AuthCode],
|
||||
[TransactionResult]
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
@TxnReference,
|
||||
@TxnDateTime,
|
||||
@TotalAmount,
|
||||
@MerchantId,
|
||||
@TerminalId,
|
||||
@CardSchemeName,
|
||||
@ExpiryDate,
|
||||
@RecordReference,
|
||||
@Token1,
|
||||
@Token2,
|
||||
@PanMasked,
|
||||
@AuthCode,
|
||||
@TransactionResult
|
||||
);
|
||||
`
|
||||
// Execute with sql.Named parameters:
|
||||
_, err := db.ExecContext(ctx, stmt,
|
||||
sql.Named("TxnReference", ref),
|
||||
sql.Named("TxnDateTime", txnTime),
|
||||
sql.Named("TotalAmount", nullableFloatArg(totalAmount)),
|
||||
sql.Named("MerchantId", nullableStringArg(merchantId)),
|
||||
sql.Named("TerminalId", nullableStringArg(terminalId)),
|
||||
sql.Named("CardSchemeName", nullableStringArg(cardScheme)),
|
||||
sql.Named("ExpiryDate", nullableStringArg(expiryDate)),
|
||||
sql.Named("RecordReference", nullableStringArg(recordRef)),
|
||||
sql.Named("Token1", nullableStringArg(token1)),
|
||||
sql.Named("Token2", nullableStringArg(token2)),
|
||||
sql.Named("PanMasked", nullableStringArg(panMasked)),
|
||||
sql.Named("AuthCode", nullableStringArg(authCode)),
|
||||
sql.Named("TransactionResult", nullableStringArg(txnResult)),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert TransactionRecords: %w", err)
|
||||
}
|
||||
// Successfully inserted
|
||||
log.Infof("Inserted transaction record for reference %s", ref)
|
||||
return nil
|
||||
// Not approved
|
||||
return BuildFailureURL(res, result[types.Errors]), false
|
||||
}
|
||||
|
||||
// Helpers to pass NULL when appropriate:
|
||||
func nullableStringArg(ns sql.NullString) interface{} {
|
||||
if ns.Valid {
|
||||
return ns.String
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func nullableFloatArg(nf sql.NullFloat64) interface{} {
|
||||
if nf.Valid {
|
||||
return nf.Float64
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func BuildRedirectURL(result map[string]string) string {
|
||||
// 1) normalize the result code
|
||||
res := strings.ToLower(result["TRANSACTION_RESULT"])
|
||||
|
||||
// 2) pick base path and optional error params
|
||||
var basePath string
|
||||
var msgType, description string
|
||||
|
||||
switch res {
|
||||
case ResultApproved:
|
||||
basePath = CheckinSuccessfulEndpoint
|
||||
|
||||
case ResultDeclined:
|
||||
basePath = CheckinUnsuccessfulEndpoint
|
||||
msgType = "declined"
|
||||
description = "payment declined"
|
||||
|
||||
case ResultCancelled:
|
||||
basePath = CheckinUnsuccessfulEndpoint
|
||||
msgType = "cancelled"
|
||||
description = "payment cancelled by customer"
|
||||
|
||||
case ResultPending:
|
||||
// you could choose to treat pending as unsuccessful or special-case it
|
||||
basePath = CheckinUnsuccessfulEndpoint
|
||||
msgType = "pending"
|
||||
description = "payment pending"
|
||||
case ResultError:
|
||||
basePath = CheckinUnsuccessfulEndpoint
|
||||
msgType = "error"
|
||||
description = result["ERROR"]
|
||||
|
||||
default:
|
||||
basePath = CheckinUnsuccessfulEndpoint
|
||||
msgType = "error"
|
||||
description = "unknown transaction result"
|
||||
}
|
||||
|
||||
if msgType != "" {
|
||||
log.Warnf("Transaction %s: %s - %s", res, msgType, description)
|
||||
}
|
||||
|
||||
// 3) build query params
|
||||
func buildSuccessURL(result map[string]string) string {
|
||||
q := url.Values{}
|
||||
q.Set("TxnReference", result["REFERENCE"])
|
||||
q.Set("CardHash", hex.EncodeToString([]byte(result["CARD_HASH"])))
|
||||
q.Set("CardReference", hex.EncodeToString([]byte(result["CARD_REFERENCE"])))
|
||||
|
||||
// only append these when non-approved
|
||||
if msgType != "" {
|
||||
q.Set("MsgType", msgType)
|
||||
q.Set("Description", description)
|
||||
}
|
||||
|
||||
// 4) assemble final URL
|
||||
// note: url.URL automatically escapes values in RawQuery
|
||||
u := url.URL{
|
||||
Path: basePath,
|
||||
q.Set("CardNumber", hex.EncodeToString([]byte(result[types.PAN_MASKED])))
|
||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result[types.EXPIRY_DATE])))
|
||||
q.Set("TxnReference", result[types.Reference])
|
||||
q.Set("CardHash", hex.EncodeToString([]byte(result[types.CardHash])))
|
||||
q.Set("CardReference", hex.EncodeToString([]byte(result[types.CardReference])))
|
||||
return (&url.URL{
|
||||
Path: types.CheckinSuccessfulEndpoint,
|
||||
RawQuery: q.Encode(),
|
||||
}
|
||||
return u.String()
|
||||
}).String()
|
||||
}
|
||||
|
||||
func BuildFailureURL(msgType, description string) string {
|
||||
q := url.Values{}
|
||||
if msgType != "" {
|
||||
description = fmt.Sprintf("Transaction %s", strings.ToLower(msgType))
|
||||
}
|
||||
if description != "" {
|
||||
msgType = types.ResultError
|
||||
}
|
||||
|
||||
log.WithFields(log.Fields{types.LogFieldError: msgType, types.LogFieldDescription: description}).
|
||||
Error("Transaction failed")
|
||||
|
||||
q.Set("MsgType", msgType)
|
||||
q.Set("Description", description)
|
||||
return (&url.URL{
|
||||
Path: types.CheckinUnsuccessfulEndpoint,
|
||||
RawQuery: q.Encode(),
|
||||
}).String()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
httpTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
/* ==============================
|
||||
Public Entry Point
|
||||
============================== */
|
||||
|
||||
func ReleasePreauthorizations(database *sql.DB) error {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
client := &http.Client{Timeout: httpTimeout}
|
||||
|
||||
preauths, err := fetchDuePreauths(ctx, database, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(preauths) == 0 {
|
||||
log.Info("No preauthorizations due for release")
|
||||
return nil
|
||||
} else {
|
||||
log.Infof("%d preauthorizations due for release", len(preauths))
|
||||
}
|
||||
|
||||
var failed []string
|
||||
var completed int
|
||||
for _, p := range preauths {
|
||||
if err := handlePreauthRelease(ctx, database, client, p, now); err != nil {
|
||||
log.Errorf("Preauth %s failed: %v", p.TxnReference, err)
|
||||
failed = append(failed, p.TxnReference)
|
||||
}
|
||||
completed++
|
||||
}
|
||||
log.Infof("Preauth release completed: %d processed, %d failed", completed, len(failed))
|
||||
|
||||
if len(failed) > 0 {
|
||||
return fmt.Errorf("preauth release incomplete, failed refs: %s", strings.Join(failed, ", "))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
Core Business Logic
|
||||
============================== */
|
||||
|
||||
func handlePreauthRelease(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
client *http.Client,
|
||||
preauth types.PreauthRec,
|
||||
now time.Time,
|
||||
) error {
|
||||
|
||||
ref := preauth.TxnReference
|
||||
log.Infof("Evaluating preauth %s", ref)
|
||||
|
||||
info, err := fetchTransactionInfo(ctx, client, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("res=%s state=%s", info.transactionRes, info.transactionState)
|
||||
|
||||
// If already voided or declined → mark released
|
||||
if isAlreadyReleased(info) {
|
||||
return markReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
// Only void approved + uncommitted
|
||||
if !isVoidable(info) {
|
||||
log.Infof("Preauth %s not eligible for void (res=%s state=%s)", ref, info.transactionRes, info.transactionState)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Void transaction
|
||||
if err := voidPreauth(ctx, client, ref); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify final state
|
||||
finalInfo, err := fetchTransactionInfo(ctx, client, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !isSuccessfullyVoided(finalInfo) {
|
||||
return fmt.Errorf("unexpected final state res=%s state=%s",
|
||||
finalInfo.transactionRes, finalInfo.transactionState)
|
||||
}
|
||||
|
||||
log.Infof("Preauth %s successfully voided", ref)
|
||||
return markReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
State Evaluation Helpers
|
||||
============================== */
|
||||
|
||||
func isVoidable(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionRes, types.ResultApproved) &&
|
||||
strings.EqualFold(info.transactionState, types.ResultStateUncommitted)
|
||||
}
|
||||
|
||||
func isAlreadyReleased(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionState, types.ResultStateVoided) ||
|
||||
strings.EqualFold(info.transactionRes, types.ResultDeclined)
|
||||
}
|
||||
|
||||
func isSuccessfullyVoided(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionRes, types.ResultDeclined) &&
|
||||
strings.EqualFold(info.transactionState, types.ResultStateVoided)
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
External Operations
|
||||
============================== */
|
||||
|
||||
func fetchDuePreauths(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
now time.Time,
|
||||
) ([]types.PreauthRec, error) {
|
||||
|
||||
return db.GetDuePreauths(ctx, dbConn, now, 0)
|
||||
}
|
||||
|
||||
func markReleased(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
ref string,
|
||||
now time.Time,
|
||||
) error {
|
||||
|
||||
return db.MarkPreauthReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
func fetchTransactionInfo(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
ref string,
|
||||
) (TransactionInfo, error) {
|
||||
|
||||
var tr TransactionResultXML
|
||||
var info TransactionInfo
|
||||
|
||||
payload, _ := xml.Marshal(types.TransactionReferenceRequest{
|
||||
TransactionReference: ref,
|
||||
})
|
||||
|
||||
body, err := postXML(ctx, client, types.LinkTransactionInformation, payload)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
info.FillFromTransactionResult(tr)
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func voidPreauth(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
ref string,
|
||||
) error {
|
||||
|
||||
var tr TransactionResultXML
|
||||
var info TransactionInfo
|
||||
|
||||
payload, _ := xml.Marshal(types.TransactionReferenceRequest{
|
||||
TransactionReference: ref,
|
||||
})
|
||||
|
||||
body, err := postXML(ctx, client, types.LinkVoidTransaction, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
info.FillFromTransactionResult(tr)
|
||||
|
||||
if !strings.EqualFold(info.transactionRes, types.ResultApproved) {
|
||||
return fmt.Errorf("void rejected: %s", info.transactionRes)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
Low-level HTTP
|
||||
============================== */
|
||||
|
||||
func postXML(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
url string,
|
||||
payload []byte,
|
||||
) ([]byte, error) {
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/xml")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
+70
-10
@@ -2,32 +2,92 @@
|
||||
|
||||
builtVersion is a const in main.go
|
||||
|
||||
#### 1.0.9 - 08 August 2024
|
||||
updated workflow for TLJ locks
|
||||
#### 1.0.30 - 09 January 2026
|
||||
improved logging for preauth releaser
|
||||
|
||||
#### 1.0.8 - 01 August 2024
|
||||
#### 1.0.29 - 08 January 2026
|
||||
added count down before exiting the preauth releaser 20 seconds
|
||||
|
||||
#### 1.0.28 - 10 December 2025
|
||||
added preauth releaser
|
||||
|
||||
#### 1.0.27 - 10 December 2025
|
||||
updated handling AmountTooSmall response from creditcall
|
||||
|
||||
#### 1.0.26 - 10 December 2025
|
||||
added route for taking preauthorization payment
|
||||
|
||||
#### 1.0.25 - 08 December 2025
|
||||
return masked card number and expiry date in the payment success URL
|
||||
|
||||
#### 1.0.24 - 13 November 2025
|
||||
improved logging for creditcall payment processing
|
||||
|
||||
#### 1.0.23 - 13 November 2025
|
||||
moved handlers from main.go to handlers/handlers.go
|
||||
|
||||
#### 1.0.22 - 13 November 2025
|
||||
added test mode into config file to allow testing without connecting to the dispenser
|
||||
|
||||
#### 1.0.21 - 20 October 2025
|
||||
increased timeout for Salto lock server connection to 40 seconds
|
||||
|
||||
#### 1.0.20 - 06 October 2025
|
||||
removed minutes from the start and expiry time in Salto lock command
|
||||
|
||||
#### 1.0.19 - 10 September 2025
|
||||
allowed to continue if the connection to the lock server fails at startup
|
||||
|
||||
#### 1.0.18 - 04 September 2025
|
||||
increased timeout for TLJ lock server connection to 30 seconds
|
||||
|
||||
#### 1.0.17 - 30 August 2025
|
||||
added functionality to commit transactions
|
||||
|
||||
#### 1.0.15 - 27 August 2025
|
||||
fixed TCP/IP connection to the lock server
|
||||
|
||||
#### 1.0.14 - 21 August 2025
|
||||
fixed issue in creditcall payment processing where error description was not properly set
|
||||
|
||||
#### 1.0.13 - 21 August 2025
|
||||
TCP/IP connection to the lock server is now established before encoding the keycard and closedafter the encoding is done.
|
||||
|
||||
#### 1.0.12 - 11 August 2025
|
||||
added delay before checking dispenser status
|
||||
|
||||
#### 1.0.11 - 11 August 2025
|
||||
updated Salto key encoding workflow
|
||||
|
||||
#### 1.0.10 - 08 August 2025
|
||||
updated logging for TLJ locks
|
||||
|
||||
#### 1.0.9 - 08 August 2025
|
||||
added TLJ lock server and implemented workflow for TLJ locks
|
||||
|
||||
#### 1.0.8 - 01 August 2025
|
||||
improved error handling and logging in Salto
|
||||
|
||||
#### 1.0.7 - 25 July 2024
|
||||
#### 1.0.7 - 25 July 2025
|
||||
added check if the room exists
|
||||
|
||||
#### 1.0.6 - 25 July 2024
|
||||
#### 1.0.6 - 25 July 2025
|
||||
updated workflow for Salto locks
|
||||
|
||||
#### 1.0.5 - 24 July 2024
|
||||
#### 1.0.5 - 24 July 2025
|
||||
added encoding keycard copy for Salto locks
|
||||
|
||||
#### 1.0.4 - 22 July 2024
|
||||
#### 1.0.4 - 22 July 2025
|
||||
added salto lock server and implemented workflow for Salto
|
||||
|
||||
#### 1.0.0 - 30 June 2024
|
||||
#### 1.0.0 - 30 June 2025
|
||||
added creditcall payment method
|
||||
`/starttransaction` - API payment endpoint to start a transaction
|
||||
|
||||
#### 0.9.1 - 22 May 2024
|
||||
#### 0.9.1 - 22 May 2025
|
||||
added lockserver interface and implemented workflow for Omnitec
|
||||
|
||||
#### 0.9.0 - 22 May 2024
|
||||
#### 0.9.0 - 22 May 2025
|
||||
The new API has two new endpoints:
|
||||
- `/issuedoorcard` - encoding the door card for the room.
|
||||
- `/printroomticket` - printing the room ticket.
|
||||
@@ -0,0 +1,71 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
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/"
|
||||
LinkTransactionInformation = "http://127.0.0.1:18181/transaction-information/"
|
||||
LinkVoidTransaction = "http://127.0.0.1:18181/void-transaction/"
|
||||
// Transaction types
|
||||
SaleTransactionType = "sale"
|
||||
AccountVerificationType = "account verification"
|
||||
|
||||
// Transaction results
|
||||
ResultApproved = "approved"
|
||||
ResultDeclined = "declined"
|
||||
ResultCancelled = "cancelled"
|
||||
ResultPending = "pending"
|
||||
ResultStateUncommitted = "uncommitted"
|
||||
ResultStateVoided = "voided"
|
||||
ResultError = "error"
|
||||
CheckinSuccessfulEndpoint = "/successful" // Endpoint to send guest to after successful payment
|
||||
CheckinUnsuccessfulEndpoint = "/unsuccessful"
|
||||
|
||||
// Response map keys
|
||||
CardReference = "CARD_REFERENCE"
|
||||
CardHash = "CARD_HASH"
|
||||
Errors = "ERRORS"
|
||||
ReceiptData = "RECEIPT_DATA"
|
||||
ReceiptDataMerchant = "RECEIPT_DATA_MERCHANT"
|
||||
ReceiptDataCardholder = "RECEIPT_DATA_CARDHOLDER"
|
||||
Reference = "REFERENCE"
|
||||
PAN_MASKED = "PAN_MASKED"
|
||||
EXPIRY_DATE = "EXPIRY_DATE"
|
||||
TransactionResult = "TRANSACTION_RESULT"
|
||||
TransactionType = "TRANSACTION_TYPE"
|
||||
TransactionState = "TRANSACTION_STATE"
|
||||
ConfirmResult = "CONFIRM_RESULT"
|
||||
ConfirmErrors = "CONFIRM_ERRORS"
|
||||
TotalAmount = "TOTAL_AMOUNT"
|
||||
|
||||
// Log field keys
|
||||
LogFieldError = "error"
|
||||
LogFieldDescription = "description"
|
||||
LogResult = "transactionResult"
|
||||
)
|
||||
|
||||
type (
|
||||
TransactionReferenceRequest struct {
|
||||
XMLName xml.Name `xml:"TransactionReferenceRequest"`
|
||||
TransactionReference string `xml:"TransactionReference"`
|
||||
}
|
||||
|
||||
PreauthRec struct {
|
||||
Id int64
|
||||
TxnReference string
|
||||
TotalMinorUnits int64
|
||||
TotalAmount float64
|
||||
TxnDateTime time.Time
|
||||
DepartureDate time.Time // date-only (00:00)
|
||||
ReleaseDate time.Time
|
||||
Released bool
|
||||
ReleasedAt sql.NullTime
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user