package abono_test import ( "context" "errors" "net/http" "sort" "strings" "sync" "testing" "gorm.io/gorm" "amadan.net/rastrillo/abono" ) func TestAdoptAddsTheLegacyPriceAndSyncs(t *testing.T) { now := t0 d := newStripeDouble(t) rec := &recorder{subject: "42"} s, db := d.service(t, &now, rec.config()) seedPlans(t, s) ctx := context.Background() // A WordPress-era subscription on a price no plan knows. d.put(t, subSpec{ID: "sub_wp", Status: "active", Price: "price_wp", Interval: "year", Customer: "cus_wp", Email: "wp@example.com", End: t0.Add(100 * day)}) if err := s.Adopt(ctx, "sub_wp", "3", "annual"); err != nil { t.Fatalf("Adopt: %v", err) } if got := db.dump("SELECT plan, sold, interval FROM abono_prices WHERE stripe_price_id = 'price_wp'"); got != "annual|0|year\n" { t.Errorf("price_wp = %q, want a legacy price of annual", got) } if got, want := db.dump(rowsQuery), "sub_wp|cus_wp|3|annual|price_wp|active|0|wp@example.com\n"; got != want { t.Errorf("rows =\n%s\nwant\n%s", got, want) } if !hasPlan(t, s, "3", "annual") { t.Error("HasPlan(3, annual) is false after Adopt") } asked, changes := rec.take() eq(t, "Holder asked", asked, nil) eq(t, "OnChange", changes, []string{"3"}) // Adopting it again is a no-op. if err := s.Adopt(ctx, "sub_wp", "3", "annual"); err != nil { t.Fatalf("Adopt again: %v", err) } if _, changes := rec.take(); len(changes) != 0 { t.Errorf("a second Adopt told %q", changes) } // A price already on another plan is refused, and nothing is written. d.put(t, subSpec{ID: "sub_m", Status: "active", Price: "price_M", Customer: "cus_m", Email: "m@example.com", End: t0.Add(10 * day)}) if err := s.Adopt(ctx, "sub_m", "3", "annual"); err == nil { t.Error("Adopt onto annual of a subscription on monthly's price succeeded") } if got := db.dump("SELECT plan, sold FROM abono_prices WHERE stripe_price_id = 'price_M'"); got != "monthly|1\n" { t.Errorf("price_M = %q, want it left on monthly", got) } if got := db.dump("SELECT * FROM abono_subscriptions WHERE stripe_subscription_id = 'sub_m'"); got != "" { t.Errorf("a refused Adopt wrote a row: %q", got) } if err := s.Adopt(ctx, "sub_wp", "3", "nonesuch"); !errors.Is(err, abono.ErrNotFound) { t.Errorf("Adopt onto a plan with no offer: err = %v, want ErrNotFound", err) } if err := s.Adopt(ctx, "sub_gone", "3", "annual"); err == nil { t.Error("Adopt of a subscription Stripe does not have succeeded") } } // TestAdoptWithoutSubjectFindsTheHolder is ruling R7: an unrecognised // row usually has no subject, so Adopt finds one as sync does. func TestAdoptWithoutSubjectFindsTheHolder(t *testing.T) { now := t0 d := newStripeDouble(t) rec := &recorder{subject: "42"} s, db := d.service(t, &now, rec.config()) seedPlans(t, s) ctx := context.Background() sub := d.put(t, subSpec{ID: "sub_z", Status: "active", Price: "price_Z", Customer: "cus_z", Email: "zed@example.com", End: t0.Add(30 * day)}) if err := s.Sync(ctx, sub, abono.Hint{Email: "zed@example.com"}); err != nil { t.Fatalf("Sync: %v", err) } if asked, _ := rec.take(); len(asked) != 0 { t.Fatalf("Holder asked %q for an unrecognised price", asked) } if err := s.Adopt(ctx, "sub_z", "", "monthly"); err != nil { t.Fatalf("Adopt with no subject: %v", err) } if got, want := db.dump(rowsQuery), "sub_z|cus_z|42|monthly|price_Z|active|0|zed@example.com\n"; got != want { t.Errorf("rows =\n%s\nwant\n%s", got, want) } asked, changes := rec.take() eq(t, "Holder asked", asked, []string{"zed@example.com"}) eq(t, "OnChange", changes, []string{"42"}) if un, err := s.Unrecognised(ctx); err != nil || len(un) != 0 { t.Errorf("Unrecognised after Adopt = %+v, %v; want none", un, err) } // A customer already mapped decides before Holder is asked. db.exec(`INSERT INTO abono_customers (stripe_customer_id, subject) VALUES ('cus_y', '8')`) d.put(t, subSpec{ID: "sub_y", Status: "active", Price: "price_Y", Customer: "cus_y", Email: "why@example.com", End: t0.Add(30 * day)}) if err := s.Adopt(ctx, "sub_y", "", "monthly"); err != nil { t.Fatalf("Adopt of a mapped customer: %v", err) } if got := db.dump("SELECT subject FROM abono_subscriptions WHERE stripe_subscription_id = 'sub_y'"); got != "8\n" { t.Errorf("sub_y subject = %q, want 8", got) } if asked, _ := rec.take(); len(asked) != 0 { t.Errorf("Holder asked %q for a mapped customer", asked) } } // TestAnOwnersAdoptionOutlastsLaterHints is final review I3 (ruling R36): // A bought the subscription signed in, so its metadata and its Checkout // session both name A. The owner then adopts it for B. Later events, a // second visit to Checkout's return and the reconcile all carry A as a // hint; none of them gives it back to A. Claim pins a row the same way. func TestAnOwnersAdoptionOutlastsLaterHints(t *testing.T) { now := t0 d := newStripeDouble(t) rec := &recorder{} s, db := d.service(t, &now, rec.config()) seedPlans(t, s) ctx := context.Background() d.put(t, subSpec{ID: "sub_1", Status: "active", Price: "price_A", Customer: "cus_1", Email: "ana@example.com", End: t0.Add(30 * day), Metadata: map[string]string{"abono_subject": "A"}}) d.session("cs_1", "complete", "sub_1", "A", "ana@example.com") if _, err := s.Finish(ctx, "cs_1"); err != nil { t.Fatalf("Finish: %v", err) } if err := s.Adopt(ctx, "sub_1", "B", "annual"); err != nil { t.Fatalf("Adopt for B: %v", err) } holder := func(when string) { t.Helper() if got := db.dump(`SELECT subject FROM abono_subscriptions WHERE stripe_subscription_id = 'sub_1'`); got != "B\n" { t.Errorf("%s: subject = %q, want B, whom the owner adopted it for", when, got) } if got := db.dump(`SELECT subject FROM abono_customers WHERE stripe_customer_id = 'cus_1'`); got != "B\n" { t.Errorf("%s: cus_1 is mapped to %q, want B", when, got) } } holder("after Adopt") wantStatus(t, deliver(t, s, event("evt_1", "customer.subscription.updated", map[string]any{"id": "sub_1"})), http.StatusOK) holder("after a subscription event naming A") wantStatus(t, deliver(t, s, event("evt_2", "checkout.session.completed", map[string]any{"id": "cs_1", "subscription": "sub_1", "client_reference_id": "A"})), http.StatusOK) holder("after a Checkout event naming A") if f, err := s.Finish(ctx, "cs_1"); err != nil || f.Subject != "B" { t.Errorf("Finish again = %+v, %v; want B's", f, err) } holder("after Checkout's return again") if _, err := s.Reconcile(ctx); err != nil { t.Fatalf("Reconcile: %v", err) } holder("after Reconcile") if hasPlan(t, s, "A", "annual") || !hasPlan(t, s, "B", "annual") { t.Error("the plan went back to A") } // Claim is an explicit decision too. d.put(t, subSpec{ID: "sub_2", Status: "active", Price: "price_M", Customer: "cus_2", Email: "walkin@example.com", End: t0.Add(30 * day)}) if err := s.Sync(ctx, d.sub(t, "sub_2"), abono.Hint{}); err != nil { t.Fatalf("Sync: %v", err) } if n, err := s.Claim(ctx, "C", "walkin@example.com"); err != nil || n != 1 { t.Fatalf("Claim = %d, %v", n, err) } if err := s.Sync(ctx, d.sub(t, "sub_2"), abono.Hint{Subject: "D"}); err != nil { t.Fatalf("Sync with D's hint: %v", err) } if got := db.dump(`SELECT subject FROM abono_subscriptions WHERE stripe_subscription_id = 'sub_2'`); got != "C\n" { t.Errorf("a claimed subscription went to %q on a later hint, want C", got) } } // TestAdoptBringsEveryoneOnThePrice is final review I11 (ruling R40): the // page promises that adopting one subscription puts everyone paying that // price onto the plan. Two holders are recorded on a price no plan has; // adopting one makes both members at once, each told through OnChange, // before Adopt returns. func TestAdoptBringsEveryoneOnThePrice(t *testing.T) { now := t0 d := newStripeDouble(t) var mu sync.Mutex var told []string s, db := d.service(t, &now, abono.Config{ Holder: func(_ context.Context, _ *gorm.DB, email, _ string) (string, error) { return strings.TrimSuffix(email, "@example.com"), nil }, OnChange: func(_ context.Context, _ *gorm.DB, subject string) error { mu.Lock() defer mu.Unlock() told = append(told, subject) return nil }, }) seedPlans(t, s) ctx := context.Background() for _, sp := range []subSpec{ {ID: "sub_z1", Status: "active", Price: "price_Z", Customer: "cus_1", Email: "one@example.com", End: t0.Add(30 * day)}, {ID: "sub_z2", Status: "active", Price: "price_Z", Customer: "cus_2", Email: "two@example.com", End: t0.Add(30 * day)}, } { if err := s.Sync(ctx, d.put(t, sp), abono.Hint{}); err != nil { t.Fatalf("Sync %s: %v", sp.ID, err) } } if un, err := s.Unrecognised(ctx); err != nil || len(un) != 2 { t.Fatalf("Unrecognised = %+v, %v; want both", un, err) } if err := s.Adopt(ctx, "sub_z1", "", "monthly"); err != nil { t.Fatalf("Adopt: %v", err) } if got := db.dump(`SELECT stripe_subscription_id, subject, plan FROM abono_subscriptions ORDER BY stripe_subscription_id`); got != "sub_z1|one|monthly\nsub_z2|two|monthly\n" { t.Errorf("rows after Adopt =\n%s\nwant both on monthly, each with its holder", got) } for _, who := range []string{"one", "two"} { if !hasPlan(t, s, who, "monthly") { t.Errorf("%s does not hold monthly after the adoption", who) } } mu.Lock() sort.Strings(told) got := strings.Join(told, ",") mu.Unlock() if got != "one,two" { t.Errorf("OnChange told %q, want one and two", got) } if un, err := s.Unrecognised(ctx); err != nil || len(un) != 0 { t.Errorf("Unrecognised after Adopt = %+v, %v; want none", un, err) } }