feat(admin): documents, indexes and the plan seed

Adds admin's own documents, its unique indexes and the plan seed from
shared/license.

Licences are append-only -- a renewal writes a new row and supersedes the
old one -- because the history is the support tool. Plans are seeded with
$setOnInsert only, so a redeploy never stamps over staff edits to limits,
features or Paddle IDs.

admin_instances.instance_id unique is a correctness property, not an
optimisation: without it two customers could both claim one self-hosted
UUID and both be issued licences for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
mrhid6
2026-07-25 19:00:37 +01:00
co-authored by Claude Opus 5
parent 64eac6dbc7
commit b8fcf89ee7
6 changed files with 289 additions and 0 deletions
+52
View File
@@ -12,6 +12,7 @@ import (
"time"
"github.com/mrhid6/vantage/admin/internal/config"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
@@ -59,3 +60,54 @@ func Control(name string) *mongo.Collection { return controlDB.Collection(name)
func Ctx() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), 10*time.Second)
}
// EnsureIndexes creates admin's unique indexes.
//
// These are a correctness property, not an optimisation. In particular
// admin_instances.instance_id unique is what stops the same self-hosted UUID
// being linked to two accounts — without it, two customers could both claim one
// instance and both be issued licences for it.
func EnsureIndexes(ctx context.Context) error {
unique := []struct {
coll string
field string
}{
{"accounts", "account_id"},
{"admin_instances", "instance_id"},
{"licenses", "license_id"},
{"plans", "tier"},
{"staff_users", "email"},
{"customer_users", "email"},
}
for _, u := range unique {
if _, err := Admin(u.coll).Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: u.field, Value: 1}},
Options: options.Index().SetUnique(true).SetName(u.field + "_unique"),
}); err != nil {
return fmt.Errorf("index %s.%s: %w", u.coll, u.field, err)
}
}
// Sparse: a subscription exists before Paddle assigns an ID, so empty must
// not collide with empty.
if _, err := Admin("subscriptions").Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: "paddle_subscription_id", Value: 1}},
Options: options.Index().SetUnique(true).SetSparse(true).SetName("paddle_subscription_id_unique"),
}); err != nil {
return fmt.Errorf("index subscriptions.paddle_subscription_id: %w", err)
}
for _, idx := range []struct {
coll string
keys bson.D
}{
{"licenses", bson.D{{Key: "instance_id", Value: 1}, {Key: "issued_at", Value: -1}}},
{"admin_instances", bson.D{{Key: "account_id", Value: 1}}},
{"admin_audit", bson.D{{Key: "created_at", Value: -1}}},
} {
if _, err := Admin(idx.coll).Indexes().CreateOne(ctx, mongo.IndexModel{Keys: idx.keys}); err != nil {
return fmt.Errorf("index %s: %w", idx.coll, err)
}
}
return nil
}