423 lines
12 KiB
Go
423 lines
12 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgerrcode"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
)
|
|
|
|
// ─── M-MIG-7: subscriptions / usage / outbox / receipts / licences (Postgres) ─
|
|
|
|
func isFKViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation
|
|
}
|
|
|
|
func isInvalidUUID(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.InvalidTextRepresentation
|
|
}
|
|
|
|
const subscriptionSelect = `
|
|
SELECT id::text, tenant_id::text, product, sku, plan, seats, status,
|
|
erp_sales_order, erp_subscription, period_start, period_end, created_at, updated_at
|
|
FROM subscriptions `
|
|
|
|
func scanSubscription(row pgx.Row) (*Subscription, error) {
|
|
var s Subscription
|
|
var ps, pe *time.Time
|
|
err := row.Scan(&s.ID, &s.TenantID, &s.Product, &s.SKU, &s.Plan, &s.Seats, &s.Status,
|
|
&s.ErpSalesOrder, &s.ErpSubscription, &ps, &pe, &s.CreatedAt, &s.UpdatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.PeriodStart, s.PeriodEnd = ps, pe
|
|
return &s, nil
|
|
}
|
|
|
|
func (p *Postgres) UpsertSubscription(ctx context.Context, sub Subscription) (*Subscription, error) {
|
|
if sub.SKU == "" || sub.Product == "" {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
row := p.pool.QueryRow(ctx, `
|
|
INSERT INTO subscriptions (tenant_id, product, sku, plan, seats, status, erp_sales_order, erp_subscription, period_start, period_end)
|
|
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
ON CONFLICT (tenant_id, sku, erp_sales_order) DO UPDATE SET
|
|
product = EXCLUDED.product, plan = EXCLUDED.plan, seats = EXCLUDED.seats, status = EXCLUDED.status,
|
|
erp_subscription = EXCLUDED.erp_subscription, period_start = EXCLUDED.period_start, period_end = EXCLUDED.period_end
|
|
RETURNING id::text, tenant_id::text, product, sku, plan, seats, status,
|
|
erp_sales_order, erp_subscription, period_start, period_end, created_at, updated_at`,
|
|
sub.TenantID, sub.Product, sub.SKU, sub.Plan, sub.Seats, firstNonEmpty(sub.Status, SubscriptionActive),
|
|
sub.ErpSalesOrder, sub.ErpSubscription, nullableTime(sub.PeriodStart), nullableTime(sub.PeriodEnd))
|
|
out, err := scanSubscription(row)
|
|
if err != nil {
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if isCheckViolation(err) {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
return nil, err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p *Postgres) ListSubscriptions(ctx context.Context, tenantID string) ([]Subscription, error) {
|
|
if _, err := p.GetTenant(ctx, tenantID); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := p.pool.Query(ctx, subscriptionSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []Subscription{}
|
|
for rows.Next() {
|
|
s, err := scanSubscription(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *s)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
const usageSelect = `
|
|
SELECT id, idempotency_key, tenant_id::text, product, metric, quantity, occurred_at, properties, received_at, erp_synced_at
|
|
FROM usage_events `
|
|
|
|
func scanUsage(row pgx.Row) (*UsageEvent, error) {
|
|
var u UsageEvent
|
|
var props []byte
|
|
var synced *time.Time
|
|
err := row.Scan(&u.ID, &u.IdempotencyKey, &u.TenantID, &u.Product, &u.Metric, &u.Quantity, &u.OccurredAt, &props, &u.ReceivedAt, &synced)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
u.ErpSyncedAt = synced
|
|
if err := json.Unmarshal(props, &u.Properties); err != nil || u.Properties == nil {
|
|
u.Properties = map[string]interface{}{}
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
func (p *Postgres) InsertUsageEvent(ctx context.Context, ev UsageEvent) (*UsageEvent, bool, error) {
|
|
if ev.IdempotencyKey == "" || ev.Metric == "" || ev.Product == "" {
|
|
return nil, false, ErrInvalidInput
|
|
}
|
|
props, err := json.Marshal(ev.Properties)
|
|
if err != nil || string(props) == "null" {
|
|
props = []byte("{}")
|
|
}
|
|
occurred := ev.OccurredAt
|
|
if occurred.IsZero() {
|
|
occurred = time.Now().UTC()
|
|
}
|
|
row := p.pool.QueryRow(ctx, `
|
|
INSERT INTO usage_events (idempotency_key, tenant_id, product, metric, quantity, occurred_at, properties)
|
|
VALUES ($1, $2::uuid, $3, $4, $5, $6, $7::jsonb)
|
|
ON CONFLICT (idempotency_key) DO NOTHING
|
|
RETURNING id, idempotency_key, tenant_id::text, product, metric, quantity, occurred_at, properties, received_at, erp_synced_at`,
|
|
ev.IdempotencyKey, ev.TenantID, ev.Product, ev.Metric, ev.Quantity, occurred, props)
|
|
u, err := scanUsage(row)
|
|
if err == nil {
|
|
return u, true, nil
|
|
}
|
|
if errors.Is(err, ErrNotFound) {
|
|
// duplicate key → return the stored row
|
|
u, err = scanUsage(p.pool.QueryRow(ctx, usageSelect+`WHERE idempotency_key = $1`, ev.IdempotencyKey))
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
return u, false, nil
|
|
}
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, false, ErrNotFound
|
|
}
|
|
return nil, false, err
|
|
}
|
|
|
|
func (p *Postgres) ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageEvent, error) {
|
|
limit := f.Limit
|
|
if limit <= 0 || limit > 1000 {
|
|
limit = 200
|
|
}
|
|
where := []string{"TRUE"}
|
|
args := []any{}
|
|
add := func(clause string, v any) {
|
|
args = append(args, v)
|
|
where = append(where, fmt.Sprintf(clause, len(args)))
|
|
}
|
|
if f.TenantID != "" {
|
|
add("tenant_id = $%d::uuid", f.TenantID)
|
|
}
|
|
if f.Product != "" {
|
|
add("product = $%d", f.Product)
|
|
}
|
|
if f.Metric != "" {
|
|
add("metric = $%d", f.Metric)
|
|
}
|
|
if f.Since != nil {
|
|
add("occurred_at >= $%d", *f.Since)
|
|
}
|
|
if f.Until != nil {
|
|
add("occurred_at <= $%d", *f.Until)
|
|
}
|
|
args = append(args, limit)
|
|
rows, err := p.pool.Query(ctx, usageSelect+`WHERE `+strings.Join(where, " AND ")+
|
|
fmt.Sprintf(` ORDER BY occurred_at DESC, id DESC LIMIT $%d`, len(args)), args...)
|
|
if err != nil {
|
|
if isInvalidUUID(err) {
|
|
return []UsageEvent{}, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []UsageEvent{}
|
|
for rows.Next() {
|
|
u, err := scanUsage(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *u)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (p *Postgres) MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error {
|
|
if len(ids) == 0 {
|
|
return nil
|
|
}
|
|
_, err := p.pool.Exec(ctx, `UPDATE usage_events SET erp_synced_at = $2 WHERE id = ANY($1)`, ids, at)
|
|
return err
|
|
}
|
|
|
|
func scanOutbox(row pgx.Row) (*OutboxItem, error) {
|
|
var o OutboxItem
|
|
var payload []byte
|
|
var done *time.Time
|
|
err := row.Scan(&o.ID, &o.Kind, &o.TenantID, &payload, &o.Attempts, &o.NextAttemptAt, &o.LastError, &done, &o.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
o.DoneAt = done
|
|
if err := json.Unmarshal(payload, &o.Payload); err != nil || o.Payload == nil {
|
|
o.Payload = map[string]interface{}{}
|
|
}
|
|
return &o, nil
|
|
}
|
|
|
|
func (p *Postgres) EnqueueOutbox(ctx context.Context, item OutboxItem) (*OutboxItem, error) {
|
|
if item.Kind == "" {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
payload, err := json.Marshal(item.Payload)
|
|
if err != nil || string(payload) == "null" {
|
|
payload = []byte("{}")
|
|
}
|
|
next := item.NextAttemptAt
|
|
if next.IsZero() {
|
|
next = time.Now().UTC()
|
|
}
|
|
var tenant any
|
|
if item.TenantID != "" {
|
|
tenant = item.TenantID
|
|
}
|
|
o, err := scanOutbox(p.pool.QueryRow(ctx, `
|
|
INSERT INTO erp_outbox (kind, tenant_id, payload, next_attempt_at)
|
|
VALUES ($1, $2::uuid, $3::jsonb, $4)
|
|
RETURNING id, kind, COALESCE(tenant_id::text, ''), payload, attempts, next_attempt_at, last_error, done_at, created_at`,
|
|
item.Kind, tenant, payload, next))
|
|
if err != nil {
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return o, nil
|
|
}
|
|
|
|
func (p *Postgres) ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error) {
|
|
if limit <= 0 {
|
|
limit = 50
|
|
}
|
|
rows, err := p.pool.Query(ctx, `
|
|
UPDATE erp_outbox SET next_attempt_at = $1::timestamptz + $2::interval
|
|
WHERE id IN (
|
|
SELECT id FROM erp_outbox
|
|
WHERE done_at IS NULL AND next_attempt_at <= $1
|
|
ORDER BY next_attempt_at, id
|
|
LIMIT $3
|
|
FOR UPDATE SKIP LOCKED
|
|
)
|
|
RETURNING id, kind, COALESCE(tenant_id::text, ''), payload, attempts, next_attempt_at, last_error, done_at, created_at`,
|
|
now, lease, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []OutboxItem{}
|
|
for rows.Next() {
|
|
o, err := scanOutbox(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *o)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (p *Postgres) CompleteOutbox(ctx context.Context, id int64, at time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET done_at = $2, attempts = attempts + 1, last_error = '' WHERE id = $1`, id, at)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, next_attempt_at = $3 WHERE id = $1`, id, errMsg, nextAttempt)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) PendingOutbox(ctx context.Context) (int, error) {
|
|
var n int
|
|
err := p.pool.QueryRow(ctx, `SELECT COUNT(*) FROM erp_outbox WHERE done_at IS NULL`).Scan(&n)
|
|
return n, err
|
|
}
|
|
|
|
func (p *Postgres) RecordWebhookReceipt(ctx context.Context, eventID string) (bool, error) {
|
|
if eventID == "" {
|
|
return false, ErrInvalidInput
|
|
}
|
|
tag, err := p.pool.Exec(ctx, `INSERT INTO erp_webhook_receipts (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, eventID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return tag.RowsAffected() == 1, nil
|
|
}
|
|
|
|
const licenceSelect = `
|
|
SELECT id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at
|
|
FROM licences `
|
|
|
|
func scanLicence(row pgx.Row) (*Licence, error) {
|
|
var l Licence
|
|
var revoked, seen *time.Time
|
|
err := row.Scan(&l.ID, &l.Kid, &l.TenantID, &l.Product, &l.Subject, &l.Device, &l.ExpiresAt, &revoked, &seen, &l.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
l.RevokedAt, l.LastSeenAt = revoked, seen
|
|
return &l, nil
|
|
}
|
|
|
|
func (p *Postgres) CreateLicence(ctx context.Context, l Licence) (*Licence, error) {
|
|
if l.Product == "" || l.Subject == "" || l.Kid == "" || l.ExpiresAt.IsZero() {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
var id any
|
|
if l.ID != "" {
|
|
id = l.ID
|
|
}
|
|
out, err := scanLicence(p.pool.QueryRow(ctx, `
|
|
INSERT INTO licences (id, kid, tenant_id, product, subject, device, expires_at)
|
|
VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3::uuid, $4, $5, $6, $7)
|
|
RETURNING id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at`,
|
|
id, l.Kid, l.TenantID, l.Product, l.Subject, l.Device, l.ExpiresAt))
|
|
if err != nil {
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if isUniqueViolation(err) {
|
|
return nil, ErrConflict
|
|
}
|
|
return nil, err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p *Postgres) GetLicence(ctx context.Context, id string) (*Licence, error) {
|
|
l, err := scanLicence(p.pool.QueryRow(ctx, licenceSelect+`WHERE id = $1::uuid`, id))
|
|
if err != nil && isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return l, err
|
|
}
|
|
|
|
func (p *Postgres) ListLicences(ctx context.Context, tenantID string) ([]Licence, error) {
|
|
if _, err := p.GetTenant(ctx, tenantID); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := p.pool.Query(ctx, licenceSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []Licence{}
|
|
for rows.Next() {
|
|
l, err := scanLicence(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *l)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (p *Postgres) RevokeLicence(ctx context.Context, id string, at time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE licences SET revoked_at = COALESCE(revoked_at, $2) WHERE id = $1::uuid`, id, at)
|
|
if err != nil {
|
|
if isInvalidUUID(err) {
|
|
return ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) TouchLicence(ctx context.Context, id string, at time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE licences SET last_seen_at = $2 WHERE id = $1::uuid`, id, at)
|
|
if err != nil {
|
|
if isInvalidUUID(err) {
|
|
return ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|