192 lines
6.6 KiB
Go
192 lines
6.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
|
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/paymentapi"
|
|
"github.com/google/uuid"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
|
app.streamPayment(w, r, false)
|
|
}
|
|
|
|
func (app *App) streamPayment(w http.ResponseWriter, r *http.Request, preauth bool) {
|
|
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
controller := http.NewResponseController(w)
|
|
encoder := json.NewEncoder(w)
|
|
deliveryFailed := false
|
|
deliveryFailure := ""
|
|
send := func(frame paymentapi.Frame) bool {
|
|
if deliveryFailed {
|
|
return false
|
|
}
|
|
if r.Context().Err() != nil {
|
|
deliveryFailure = "client_disconnected"
|
|
return false
|
|
}
|
|
if err := controller.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil && !errors.Is(err, http.ErrNotSupported) {
|
|
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
|
return false
|
|
}
|
|
if err := encoder.Encode(frame); err != nil {
|
|
deliveryFailed = true
|
|
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
|
return false
|
|
}
|
|
if err := controller.Flush(); err != nil {
|
|
deliveryFailed = true
|
|
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
reject := func(code int, reason, message string) {
|
|
w.WriteHeader(code)
|
|
result := paymentapi.Result{Outcome: "error", HTTPStatus: code, Reason: reason, Message: message}
|
|
send(paymentapi.Frame{Type: "result", Result: &result})
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
reject(http.StatusMethodNotAllowed, "invalid_request", "Use POST")
|
|
return
|
|
}
|
|
if !app.isPayment || app.paymentService == nil {
|
|
reject(http.StatusServiceUnavailable, "terminal_unavailable", "Payment service is unavailable")
|
|
return
|
|
}
|
|
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
|
reject(http.StatusUnsupportedMediaType, "invalid_request", "Use application/json")
|
|
return
|
|
}
|
|
defer r.Body.Close()
|
|
var input paymentapi.Request
|
|
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&input) != nil {
|
|
reject(http.StatusBadRequest, "invalid_request", "Invalid JSON payload")
|
|
return
|
|
}
|
|
if input.Amount < 0 || (!preauth && input.Amount == 0) {
|
|
reject(http.StatusBadRequest, "invalid_request", "Invalid payment amount")
|
|
return
|
|
}
|
|
if input.RequiredPreauth != nil && input.RequiredPreauth.Amount < 0 {
|
|
reject(http.StatusBadRequest, "invalid_request", "Invalid required preauthorisation amount")
|
|
return
|
|
}
|
|
if _, ok := w.(http.Flusher); !ok {
|
|
reject(http.StatusInternalServerError, "stream_unavailable", "Streaming payment updates are unavailable")
|
|
return
|
|
}
|
|
if r.Context().Err() != nil {
|
|
return
|
|
}
|
|
if input.Reference == "" {
|
|
input.Reference = uuid.NewString()
|
|
}
|
|
req := paymentsvc.SaleRequest{RequestID: buildPaymentRequestID(input.Reference), Reference: input.Reference, Amount: input.Amount, Currency: input.Currency, CheckoutDate: input.CheckoutDate, RequiredPreauth: input.RequiredPreauth}
|
|
operation := paymentapi.Sale
|
|
if preauth {
|
|
operation = paymentapi.Preauth
|
|
}
|
|
reconciliationFields := func(final paymentapi.Result) log.Fields {
|
|
return log.Fields{
|
|
"hotel": app.cfg.Hotel, "kiosk": app.cfg.Kiosk, "operation": operation,
|
|
"request_id": req.RequestID, "request_reference": req.Reference,
|
|
"provider": final.Provider, "transaction_reference": final.TransactionReference,
|
|
"outcome": final.Outcome, "reason": final.Reason,
|
|
}
|
|
}
|
|
progress := make(chan string, 128)
|
|
finished := make(chan paymentapi.Result, 1)
|
|
go func() {
|
|
// Financial dispatch owns its lifetime; HTTP disconnect only ends observation.
|
|
timeout := app.cfg.TimeoutSeconds
|
|
if timeout <= 0 {
|
|
timeout = 300
|
|
}
|
|
timeout += 15 // Delivery/status margin; provider financial calls retain their own bounds.
|
|
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), time.Duration(timeout)*time.Second)
|
|
defer cancel()
|
|
status := func(update paymentsvc.StatusUpdate) {
|
|
if update.Code != "" {
|
|
select {
|
|
case progress <- update.Code:
|
|
default:
|
|
}
|
|
}
|
|
}
|
|
var result *paymentsvc.Result
|
|
var err error
|
|
if preauth {
|
|
result, err = app.paymentService.Preauth(ctx, req, status)
|
|
} else {
|
|
result, err = app.paymentService.Sale(ctx, req, status)
|
|
}
|
|
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Message: "Payment outcome uncertain; contact reception"}
|
|
if result != nil {
|
|
final = result.Terminal
|
|
}
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, paymentsvc.ErrPaymentInProgress):
|
|
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusConflict, Reason: "payment_in_progress", Message: "Payment is already in progress"}
|
|
case errors.Is(err, paymentsvc.ErrPreauthUnsupported):
|
|
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusUnprocessableEntity, Reason: "unsupported_operation", Message: "Preauthorisation is unavailable; contact reception"}
|
|
case errors.Is(err, paymentsvc.ErrProviderNotConfigured):
|
|
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusServiceUnavailable, Reason: "terminal_unavailable", Message: "Payment service is unavailable"}
|
|
}
|
|
}
|
|
if final.Outcome == "" {
|
|
final = paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Message: "Payment outcome uncertain; contact reception"}
|
|
}
|
|
if final.Outcome == "unknown" {
|
|
log.WithFields(reconciliationFields(final)).WithField("transport_error", err != nil).
|
|
Warn("Payment outcome requires reception reconciliation")
|
|
}
|
|
close(progress)
|
|
finished <- final
|
|
}()
|
|
for {
|
|
select {
|
|
case code, ok := <-progress:
|
|
if !ok {
|
|
progress = nil
|
|
continue
|
|
}
|
|
send(paymentapi.Frame{Type: "status", Code: code})
|
|
case final := <-finished:
|
|
if progress != nil {
|
|
for code := range progress {
|
|
send(paymentapi.Frame{Type: "status", Code: code})
|
|
}
|
|
}
|
|
if !send(paymentapi.Frame{Type: "result", Result: &final}) {
|
|
log.WithFields(reconciliationFields(final)).WithField("error_category", deliveryFailure).
|
|
Warn("Payment final result delivery failed; reception reconciliation required")
|
|
}
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func buildPaymentRequestID(reference string) string {
|
|
const prefix = "REQ_"
|
|
const maxLength = 60
|
|
suffix := fmt.Sprintf("_%d", time.Now().UnixMilli())
|
|
maxReferenceLength := maxLength - len(prefix) - len(suffix)
|
|
runes := []rune(reference)
|
|
if len(runes) > maxReferenceLength {
|
|
runes = runes[:maxReferenceLength]
|
|
}
|
|
return prefix + string(runes) + suffix
|
|
}
|