restructure hardlink layout
This commit is contained in:
@@ -0,0 +1,206 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type preauthSpoolRecord struct {
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
CheckoutDate string `json:"checkoutDate"` // keep as received
|
||||
Fields map[string]string `json:"fields"` // ChipDNA result.Fields
|
||||
}
|
||||
|
||||
func (app *App) getDB(ctx context.Context) (*sql.DB, error) {
|
||||
app.dbMu.Lock()
|
||||
defer app.dbMu.Unlock()
|
||||
|
||||
// Fast path: db exists and is alive
|
||||
if app.db != nil {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := app.db.PingContext(pingCtx); err == nil {
|
||||
return app.db, nil
|
||||
}
|
||||
|
||||
// stale handle
|
||||
_ = app.db.Close()
|
||||
app.db = nil
|
||||
}
|
||||
|
||||
// Reconnect once, bounded
|
||||
dialCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dbConn, err := db.InitMSSQL(
|
||||
app.cfg.Dbport,
|
||||
app.cfg.Dbuser,
|
||||
app.cfg.Dbpassword,
|
||||
app.cfg.Dbname,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pingCtx, cancel2 := context.WithTimeout(dialCtx, 1*time.Second)
|
||||
defer cancel2()
|
||||
|
||||
if err := dbConn.PingContext(pingCtx); err != nil {
|
||||
_ = dbConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
app.db = dbConn
|
||||
return app.db, nil
|
||||
}
|
||||
|
||||
func (app *App) spoolPath() string {
|
||||
// keep it near logs; adjust if you prefer a dedicated dir
|
||||
// ensure LogDir ends with separator in your config loader
|
||||
return filepath.Join(app.cfg.LogDir, "preauth_spool.ndjson")
|
||||
}
|
||||
|
||||
// persistPreauth tries DB first; if DB is down or insert fails, it spools to file.
|
||||
// It never returns an error to the caller (so your HTTP flow stays simple),
|
||||
// but it logs failures.
|
||||
func (app *App) persistPreauth(ctx context.Context, fields map[string]string, checkoutDate string) {
|
||||
// First, try DB (with your reconnect logic inside getDB)
|
||||
dbConn, err := app.getDB(ctx)
|
||||
if err == nil && dbConn != nil {
|
||||
if err := db.InsertPreauth(ctx, dbConn, fields, checkoutDate); err == nil {
|
||||
// opportunistic drain once DB is alive
|
||||
go app.drainPreauthSpool(context.Background())
|
||||
return
|
||||
} else {
|
||||
log.WithError(err).Warn("DB insert failed; will spool preauth")
|
||||
}
|
||||
} else {
|
||||
log.WithError(err).Warn("DB unavailable; will spool preauth")
|
||||
}
|
||||
|
||||
// Fallback: spool to file
|
||||
rec := preauthSpoolRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
CheckoutDate: checkoutDate,
|
||||
Fields: fields,
|
||||
}
|
||||
if spErr := app.spoolPreauth(rec); spErr != nil {
|
||||
log.WithError(spErr).Error("failed to spool preauth")
|
||||
}
|
||||
}
|
||||
|
||||
// append one line JSON (NDJSON)
|
||||
func (app *App) spoolPreauth(rec preauthSpoolRecord) error {
|
||||
p := app.spoolPath()
|
||||
|
||||
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open spool file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
b, err := json.Marshal(rec)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal spool record: %w", err)
|
||||
}
|
||||
|
||||
if _, err := f.Write(append(b, '\n')); err != nil {
|
||||
return fmt.Errorf("write spool record: %w", err)
|
||||
}
|
||||
|
||||
return f.Sync() // ensure it's on disk
|
||||
}
|
||||
|
||||
// Drain spool into DB.
|
||||
// Strategy: read all lines, insert each; keep failures in a temp file; then replace original.
|
||||
func (app *App) drainPreauthSpool(ctx context.Context) {
|
||||
dbConn, err := app.getDB(ctx)
|
||||
if err != nil {
|
||||
return // still down, nothing to do
|
||||
}
|
||||
|
||||
spool := app.spoolPath()
|
||||
in, err := os.Open(spool)
|
||||
if err != nil {
|
||||
// no spool is fine
|
||||
return
|
||||
}
|
||||
defer in.Close()
|
||||
|
||||
tmp := spool + ".tmp"
|
||||
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
|
||||
if err != nil {
|
||||
log.WithError(err).Warn("drain spool: open tmp failed")
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
sc := bufio.NewScanner(in)
|
||||
// allow long lines if receipts ever sneak in (shouldn't, but safe)
|
||||
buf := make([]byte, 0, 64*1024)
|
||||
sc.Buffer(buf, 2*1024*1024)
|
||||
|
||||
var (
|
||||
okCount int
|
||||
failCount int
|
||||
)
|
||||
|
||||
for sc.Scan() {
|
||||
line := sc.Bytes()
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var rec preauthSpoolRecord
|
||||
if err := json.Unmarshal(line, &rec); err != nil {
|
||||
// malformed line: keep it so we don't lose evidence
|
||||
_, _ = out.Write(append(line, '\n'))
|
||||
failCount++
|
||||
continue
|
||||
}
|
||||
|
||||
// attempt insert
|
||||
if err := db.InsertPreauth(ctx, dbConn, rec.Fields, rec.CheckoutDate); err != nil {
|
||||
// DB still flaky or data issue: keep it for later retry
|
||||
_, _ = out.Write(append(line, '\n'))
|
||||
failCount++
|
||||
continue
|
||||
}
|
||||
|
||||
okCount++
|
||||
}
|
||||
|
||||
if err := sc.Err(); err != nil {
|
||||
log.WithError(err).Warn("drain spool: scanner error")
|
||||
// best effort; do not replace spool
|
||||
return
|
||||
}
|
||||
|
||||
_ = out.Sync()
|
||||
|
||||
// Replace original spool with temp (atomic on Windows is best-effort; still OK here)
|
||||
_ = in.Close()
|
||||
_ = out.Close()
|
||||
|
||||
if err := os.Rename(tmp, spool); err != nil {
|
||||
log.WithError(err).Warn("drain spool: rename failed")
|
||||
return
|
||||
}
|
||||
|
||||
if okCount > 0 || failCount > 0 {
|
||||
log.WithFields(log.Fields{
|
||||
"inserted": okCount,
|
||||
"remaining": failCount,
|
||||
}).Info("preauth spool drained")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
disp *dispenser.Client
|
||||
lockserver lockserver.LockServer
|
||||
isPayment bool
|
||||
db *sql.DB
|
||||
cfg *config.ConfigRec
|
||||
dbMu sync.Mutex
|
||||
cardWellMu sync.RWMutex
|
||||
cardWellStatus string
|
||||
availabilityMu sync.Mutex
|
||||
availabilityTimers map[string]*time.Timer
|
||||
}
|
||||
|
||||
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
||||
app := &App{
|
||||
isPayment: cfg.IsPayment,
|
||||
disp: disp,
|
||||
lockserver: lockserver.NewLockServer(lockType, encoderAddress, errorhandlers.FatalError),
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
availabilityTimers: make(map[string]*time.Timer),
|
||||
}
|
||||
app.SetCardWellStatus(cardWellStatus)
|
||||
return app
|
||||
}
|
||||
|
||||
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)
|
||||
mux.HandleFunc("/dispenserstatus", app.reportDispenserStatus)
|
||||
mux.HandleFunc("/testissuedoorcard", app.testIssueDoorCard)
|
||||
mux.HandleFunc("/ping-pdq", app.fetchChipDNAStatus)
|
||||
mux.HandleFunc("/logerror", app.onChipDNAError)
|
||||
}
|
||||
|
||||
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("takePreauthorization")
|
||||
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
theRequest cmstypes.TransactionRec
|
||||
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 {
|
||||
if !app.cfg.TestMode {
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Error", "Attempted preauthorization while payment processing is disabled")
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
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
|
||||
}
|
||||
|
||||
if r.Header.Get("Content-Type") != "text/xml" {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Content-Type must be text/xml")
|
||||
writeTransactionResult(w, http.StatusUnsupportedMediaType, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Read body error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Failed to read request body")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := xml.Unmarshal(body, &theRequest); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Invalid XML payload")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf(
|
||||
"Preauthorization payload: Amount=%s, Type=%s",
|
||||
theRequest.AmountMinorUnits,
|
||||
theRequest.TransactionType,
|
||||
)
|
||||
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
|
||||
// ---- START TRANSACTION ----
|
||||
|
||||
body, err = callChipDNA(client, types.LinkStartTransaction, body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
||||
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "No response from payment processor")
|
||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||
}
|
||||
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
// ---- PRINT RECEIPT ----
|
||||
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
|
||||
// ---- REDIRECT ----
|
||||
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data, save = payment.BuildPreauthRedirectURL(result.Fields)
|
||||
|
||||
if save {
|
||||
go app.persistPreauth(context.Background(), result.Fields, theRequest.CheckoutDate)
|
||||
}
|
||||
|
||||
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 {
|
||||
if !app.cfg.TestMode {
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Error", "Attempted payment while payment processing is disabled")
|
||||
theResponse.Status.Code = http.StatusServiceUnavailable
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Payment processing is disabled")
|
||||
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
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
|
||||
}
|
||||
|
||||
if r.Header.Get("Content-Type") != "text/xml" {
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Content-Type must be text/xml")
|
||||
writeTransactionResult(w, http.StatusUnsupportedMediaType, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Read body error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Failed to read request body")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := xml.Unmarshal(body, &theRequest); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "Invalid XML payload")
|
||||
writeTransactionResult(w, http.StatusBadRequest, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Transaction payload: Amount=%s, Type=%s",
|
||||
theRequest.AmountMinorUnits,
|
||||
theRequest.TransactionType,
|
||||
)
|
||||
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
|
||||
// ---- START TRANSACTION ----
|
||||
|
||||
body, err = callChipDNA(client, types.LinkStartTransaction, body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Start transaction error", string(op), "", "", 0)
|
||||
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "No response from payment processor")
|
||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
|
||||
}
|
||||
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
res := result.Fields[types.TransactionResult]
|
||||
|
||||
if !strings.EqualFold(res, types.ResultApproved) {
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
desc := result.Fields[types.ErrorDescription]
|
||||
if desc == "" {
|
||||
desc = result.Fields[types.Errors]
|
||||
}
|
||||
logging.Error(types.ServiceName, "Preauthorization failed", "Result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildFailureURL(res, result.Fields[types.Errors])
|
||||
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
// ---- CONFIRM TRANSACTION ----
|
||||
|
||||
ref := result.Fields[types.Reference]
|
||||
log.Printf("Preauth approved, reference: %s. Sending confirm...", ref)
|
||||
confirmReq := payment.ConfirmTransactionRequest{
|
||||
Amount: theRequest.AmountMinorUnits,
|
||||
Reference: ref,
|
||||
}
|
||||
|
||||
body, err = confirmWithRetry(client, confirmReq, 2)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Confirm transaction error", string(op), "", "", 0)
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Error: "+err.Error())
|
||||
theResponse.Data = payment.BuildFailureURL(types.ResultError, "ConfirmTransactionError")
|
||||
writeTransactionResult(w, http.StatusBadGateway, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
if err := trResult.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse confirm result error", string(op), "", "", 0)
|
||||
}
|
||||
|
||||
result.FillFromTransactionResult(trResult)
|
||||
|
||||
res = result.Fields[types.TransactionResult]
|
||||
|
||||
if !strings.EqualFold(res, types.ResultApproved) {
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
desc := result.Fields[types.ErrorDescription]
|
||||
if desc == "" {
|
||||
desc = result.Fields[types.Errors]
|
||||
}
|
||||
logging.Error(types.ServiceName, "Transaction not approved after confirm", "Confirm result: "+res+" Description: "+desc, string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment confirmation failed", "Reference: "+ref+", Confirm result: "+res+" Description: "+desc)
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildFailureURL(res, result.Fields[types.Errors])
|
||||
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
return
|
||||
}
|
||||
|
||||
// ---- SUCCESS ----
|
||||
|
||||
printer.PrintReceipt(result.CardholderReceipt)
|
||||
log.Printf("Transaction approved and confirmed, reference: %s", ref)
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildSuccessURL(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 {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
errorhandlers.WriteError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadJSON", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// parse times
|
||||
checkIn, err := time.Parse(types.CustomLayout, doorReq.CheckinTime)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid checkinTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
checkOut, err := time.Parse(types.CustomLayout, doorReq.CheckoutTime)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Invalid checkoutTime format", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid checkoutTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure dispenser ready (card at encoder) BEFORE we attempt encoding.
|
||||
// With queued dispenser ops, this will not clash with polling.
|
||||
status, err := app.disp.DispenserStart(r.Context())
|
||||
app.SetCardWellStatus(status)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Always attempt to finalize after we have moved a card / started an issuance flow.
|
||||
// This guarantees we eject and prepare the next card even on lock failures.
|
||||
finalize := func() {
|
||||
if app.disp == nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
status, ferr := app.disp.DispenserFinal(ctx)
|
||||
if ferr != nil {
|
||||
logging.Error(types.ServiceName, ferr.Error(), "Dispenser final error", string(op), "", "", 0)
|
||||
return
|
||||
}
|
||||
app.SetCardWellStatus(status)
|
||||
}
|
||||
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
|
||||
// lock server sequence
|
||||
if err := app.lockserver.LockSequence(); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
finalize()
|
||||
errorhandlers.WriteError(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// final dispenser steps
|
||||
finalize()
|
||||
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = "Card issued successfully"
|
||||
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 {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "xml") {
|
||||
errorhandlers.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(types.ServiceName, err.Error(), "ReadXML", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid XML payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
data, err := printer.BuildRoomTicket(roomDetails)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "BuildRoomTicket", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusInternalServerError, "BuildRoomTicket failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Send to the Windows Epson TM-T82II via the printer package
|
||||
if err := printer.SendToPrinter(data); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "printRoomTicket", "printRoomTicket", "", "", 0)
|
||||
errorhandlers.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",
|
||||
})
|
||||
}
|
||||
|
||||
func (app *App) reportDispenserStatus(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(cmstypes.StatusRec{
|
||||
Code: http.StatusOK,
|
||||
Message: app.CardWellStatus(),
|
||||
})
|
||||
}
|
||||
|
||||
func (app *App) SetCardWellStatus(s string) {
|
||||
app.cardWellMu.Lock()
|
||||
prev := app.cardWellStatus
|
||||
app.cardWellStatus = s
|
||||
app.cardWellMu.Unlock()
|
||||
|
||||
if s != "" && prev != s {
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Dispenser Error Status", "Status: "+s)
|
||||
}
|
||||
}
|
||||
|
||||
func (app *App) CardWellStatus() string {
|
||||
app.cardWellMu.RLock()
|
||||
defer app.cardWellMu.RUnlock()
|
||||
return app.cardWellStatus
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func writeTransactionResult(w http.ResponseWriter, status int, theResponse cmstypes.ResponseRec) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(theResponse); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "JSON encode error", "startTransaction", "", "", 0)
|
||||
}
|
||||
}
|
||||
|
||||
func callChipDNA(client *http.Client, url string, payload []byte) ([]byte, error) {
|
||||
|
||||
resp, err := client.Post(url, "text/xml", bytes.NewBuffer(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func confirmWithRetry(client *http.Client, req payment.ConfirmTransactionRequest, attempts int) ([]byte, error) {
|
||||
|
||||
payload, err := xml.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
|
||||
for i := 1; i <= attempts; i++ {
|
||||
|
||||
resp, err := client.Post(types.LinkConfirmTransaction, "text/xml", bytes.NewBuffer(payload))
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
} else {
|
||||
|
||||
body, readErr := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if readErr != nil {
|
||||
lastErr = readErr
|
||||
} else {
|
||||
return body, nil
|
||||
}
|
||||
}
|
||||
|
||||
log.Warnf("ConfirmTransaction attempt %d/%d failed: %v", i, attempts, lastErr)
|
||||
|
||||
if i < attempts {
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
return nil, lastErr
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/payment"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (app *App) testIssueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("issueDoorCard")
|
||||
var (
|
||||
doorReq lockserver.DoorCardRequest
|
||||
theResponse cmstypes.StatusRec
|
||||
)
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("issueDoorCard called")
|
||||
if r.Method != http.MethodPost {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
errorhandlers.WriteError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "ReadJSON", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
checkIn := time.Date(now.Year(), now.Month(), now.Day(), 23, 0, 0, 0, now.Location())
|
||||
checkOut := checkIn.Add(2 * time.Hour)
|
||||
|
||||
// Ensure dispenser ready (card at encoder) BEFORE we attempt encoding.
|
||||
// With queued dispenser ops, this will not clash with polling.
|
||||
status, err := app.disp.DispenserStart(r.Context())
|
||||
app.SetCardWellStatus(status)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
|
||||
// lock server sequence
|
||||
if err := app.lockserver.LockSequence(); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = "Card issued successfully"
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
func (app *App) fetchChipDNAStatus(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("fetchChipDNAStatus")
|
||||
var theResponse cmstypes.StatusRec
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
status, err := payment.ReadPdqStatus(app.cfg.Hotel, app.cfg.Kiosk)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "fetchChipDNAStatus", string(op), "", app.cfg.Hotel, app.cfg.Kiosk)
|
||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, err.Error())
|
||||
return
|
||||
}
|
||||
b, err := json.MarshalIndent(status, "", " ")
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "MarshalIndent", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusInternalServerError, "Failed to marshal status data")
|
||||
return
|
||||
}
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = string(b)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(theResponse)
|
||||
}
|
||||
|
||||
func (app *App) onChipDNAError(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("onChipDNAError")
|
||||
var tr payment.TransactionResultXML
|
||||
title := "ChipDNA Error"
|
||||
message := ""
|
||||
|
||||
log.Println("onChipDNAError called")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
message = "Failed to read request body: " + err.Error()
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, message)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Unable to read request body")
|
||||
return
|
||||
}
|
||||
|
||||
if len(body) == 0 {
|
||||
message = "Received empty request body"
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, message)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Empty body")
|
||||
return
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
logging.Error(
|
||||
types.ServiceName,
|
||||
err.Error(),
|
||||
"Parse transaction result error",
|
||||
string(op),
|
||||
"",
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
)
|
||||
message = "Failed to parse transaction result: " + err.Error()
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, message)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid XML")
|
||||
return
|
||||
}
|
||||
|
||||
for _, e := range tr.Entries {
|
||||
|
||||
switch e.Key {
|
||||
|
||||
case payment.KeyErrors:
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, title, e.Value)
|
||||
|
||||
case payment.KeyIsAvailable:
|
||||
isAvailable := strings.EqualFold(e.Value, "true")
|
||||
app.handleAvailabilityDebounced(isAvailable)
|
||||
}
|
||||
|
||||
logging.Error(
|
||||
types.ServiceName,
|
||||
e.Value,
|
||||
e.Key,
|
||||
string(op),
|
||||
"",
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"status":"received"}`))
|
||||
}
|
||||
|
||||
func (app *App) handleAvailabilityDebounced(isAvailable bool) {
|
||||
const (
|
||||
debounceDay = 30
|
||||
debounceNight = 600
|
||||
title = "ChipDNA Error"
|
||||
)
|
||||
|
||||
key := app.availabilityKey()
|
||||
|
||||
app.availabilityMu.Lock()
|
||||
defer app.availabilityMu.Unlock()
|
||||
|
||||
// If device becomes available -> cancel pending timer
|
||||
if isAvailable {
|
||||
if t, exists := app.availabilityTimers[key]; exists {
|
||||
t.Stop()
|
||||
delete(app.availabilityTimers, key)
|
||||
log.Println("PDQ availability restored - debounce timer cancelled")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Device became unavailable -> start 10s debounce if not already started
|
||||
if _, exists := app.availabilityTimers[key]; exists {
|
||||
return
|
||||
}
|
||||
|
||||
debounce := debounceDay
|
||||
|
||||
hour := time.Now().Hour()
|
||||
if hour < 6 {
|
||||
debounce = debounceNight
|
||||
}
|
||||
|
||||
log.Printf("PDQ reported unavailable - starting %ds debounce timer", debounce)
|
||||
|
||||
timer := time.AfterFunc(time.Duration(debounce)*time.Second, func() {
|
||||
mail.SendEmailOnError(
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
title,
|
||||
fmt.Sprintf("ChipDNA PDQ unavailable for more than %d seconds", debounce),
|
||||
)
|
||||
|
||||
app.availabilityMu.Lock()
|
||||
delete(app.availabilityTimers, key)
|
||||
app.availabilityMu.Unlock()
|
||||
})
|
||||
|
||||
app.availabilityTimers[key] = timer
|
||||
}
|
||||
|
||||
func (app *App) availabilityKey() string {
|
||||
return fmt.Sprintf("hotel=%s|kiosk=%d|app=%p",
|
||||
strings.TrimSpace(app.cfg.Hotel),
|
||||
app.cfg.Kiosk,
|
||||
app,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user