feat: add terminal-scoped transaction analytics
This commit is contained in:
54
internal/analytics/terminals.go
Normal file
54
internal/analytics/terminals.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var ErrUnknownTerminal = errors.New("analytics: unknown terminal")
|
||||
|
||||
type Terminal struct {
|
||||
TerminalID string `json:"terminalId"`
|
||||
DisplayName string `json:"displayName"`
|
||||
SessionCount int64 `json:"sessionCount"`
|
||||
IsDefault bool `json:"isDefault"`
|
||||
}
|
||||
|
||||
func (s *Service) Terminals(ctx context.Context, merchantID int64) ([]Terminal, error) {
|
||||
rows, err := s.pool.Query(ctx, `SELECT t.source_key,count(ps.id) FROM terminals t
|
||||
LEFT JOIN payment_sessions ps ON ps.terminal_id=t.id
|
||||
WHERE t.merchant_id=$1 GROUP BY t.id ORDER BY count(ps.id) DESC,t.source_key`, merchantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("querying merchant terminals: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
terminals := make([]Terminal, 0, 8)
|
||||
for rows.Next() {
|
||||
var terminal Terminal
|
||||
if err := rows.Scan(&terminal.TerminalID, &terminal.SessionCount); err != nil {
|
||||
return nil, fmt.Errorf("scanning merchant terminal: %w", err)
|
||||
}
|
||||
terminal.DisplayName = terminalDisplayName(terminal.TerminalID)
|
||||
terminal.IsDefault = len(terminals) == 0
|
||||
terminals = append(terminals, terminal)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterating merchant terminals: %w", err)
|
||||
}
|
||||
return terminals, nil
|
||||
}
|
||||
|
||||
func (s *Service) validateTerminal(ctx context.Context, merchantID int64, terminalID string) error {
|
||||
if terminalID == "" {
|
||||
return nil
|
||||
}
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM terminals WHERE merchant_id=$1 AND source_key=$2)`, merchantID, terminalID).Scan(&exists); err != nil {
|
||||
return fmt.Errorf("validating merchant terminal: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return ErrUnknownTerminal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user