droboticflow/internal/api/account_hierarchy_flow_readback_test.go
eust-w 106235bb02 ✨ Remove Email field, complete phone-only account identity (ticket 05)
Contract step of the account-phone-login expand-migrate-contract rollout.
Phone is now the sole account identifier end to end:

- domain.UserRecord/CreateUserInput: delete Email, drop Phone's omitempty
  (required going forward).
- store: delete email_unique Mongo index; phone_unique is now non-sparse
  (unique, not sparse) since every account creation path requires a phone.
  Delete FindUserByEmail, ensureUserEmailAvailableLocked, and
  ErrDuplicateUserEmail (confirmed dead via grep - all real call sites were
  already migrated to the *Phone equivalents by tickets 01-03). Mongo
  duplicate-key fallback and the account-mutation-guard's stale-write
  snapshot/filter now key off Phone instead of Email.
- api: drop the now-impossible ErrDuplicateUserEmail branch in
  renderUserMutationError. The account-hierarchy audit endpoint and the
  supplier-deletion receipt struct both switch their identifying field from
  Email to Phone, since both are populated fresh from current account state
  (not frozen historical snapshots) - continuing to read a "email" key would
  silently go blank for every account created after this change.
- frontend: src/types.ts User.phone is now required (email removed);
  AccountHierarchyIssue.email -> .phone in services/api/users.ts and
  pages/Users.tsx to match the backend audit endpoint's renamed field.
- Rewrote the wide blast radius of Go test fixtures that constructed users
  by email across internal/api/*_test.go and internal/store/*_test.go,
  including the two dedicated memory-store uniqueness tests (merged into
  phone-only equivalents) and several opt-in "live" acceptance-fixture
  tests gated behind env vars for real Fanyu deployments.

Repo-wide grep of Go and TS/TSX for Email/email/邮箱 turned up no remaining
account-identifier references outside of a few harmless test-only cosmetic
labels (e.g. "Email Tenant" as an org display name in a seed helper) and
assertions that explicitly check "邮箱" text is absent from API responses.

go build/vet clean. go test ./internal/api/... ./internal/store/...
./internal/domain/... : 75 failures, identical test names to the
pre-ticket-05 baseline (diffed against a throwaway worktree at the prior
tip). npm run lint:web (tsc --noEmit) clean. npm run test:frontend:
599/586/13, matching the stated baseline exactly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-22 14:30:50 +08:00

138 lines
5.2 KiB
Go

package api
import (
"context"
"encoding/json"
"fmt"
"os"
"testing"
"time"
"droboticflow/internal/domain"
"droboticflow/internal/store"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func TestAccountHierarchyFlowReadback(t *testing.T) {
if os.Getenv("ACCOUNT_FLOW_READBACK") != "1" {
t.Skip("explicit isolated flow inspection")
}
const project = "project-discard-verify-20260921accountsflow1"
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel()
c, e := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
if e != nil {
t.Fatal("database connection")
}
defer c.Disconnect(context.Background())
db := c.Database(os.Getenv("MONGO_DB"))
s := store.NewMongoStore(db)
p, e := s.GetProject(ctx, project)
if e != nil || p == nil || p.Description != "Isolated slice-discard acceptance fixture; no intake listener" {
t.Fatal("fixture scope mismatch")
}
runs, e := s.ListRunsByOrganization(ctx, p.OrganizationID, "")
if e != nil {
t.Fatal(e)
}
out := []map[string]any{}
allDone := true
runIDs := []string{}
for _, r := range runs {
if r.ProjectID != project {
continue
}
runIDs = append(runIDs, r.ID)
if r.Status != domain.RunStatusCompleted {
allDone = false
}
nodes := []map[string]any{}
for _, n := range r.NodeExecutions {
nodes = append(nodes, map[string]any{"id": n.NodeID, "status": n.Status, "message": n.Error})
}
artifacts := []map[string]any{}
for _, a := range r.Artifacts {
artifacts = append(artifacts, map[string]any{"id": a.ID, "name": a.Name, "type": a.Type, "path": a.Path})
}
out = append(out, map[string]any{"id": r.ID, "status": r.Status, "nodes": nodes, "artifacts": artifacts})
}
packages := []bson.M{}
cursor, e := db.Collection("deliveryPackages").Find(ctx, bson.M{"projectId": project}, options.Find().SetProjection(bson.M{"_id": 0, "id": 1, "supplierId": 1, "status": 1, "parentRunId": 1, "childRunId": 1, "finalExportArtifactIds": 1}))
if e != nil {
t.Fatal(e)
}
if e = cursor.All(ctx, &packages); e != nil {
t.Fatal(e)
}
result := map[string]any{"projectId": project, "runs": out, "deliveryPackages": packages, "allRunsCompleted": allDone}
if os.Getenv("ACCOUNT_FLOW_CLEANUP") == "1" {
if len(runIDs) < 2 || !allDone {
t.Fatal("test runs must finish before scoped cleanup")
}
// Keep exported verification evidence; remove only this task's generated
// business records so real supplier/account directories are not polluted.
taskIDs, e := db.Collection("annotationTasks").Distinct(ctx, "id", bson.M{"projectId": project})
if e != nil {
t.Fatal(e)
}
items, e := db.Collection("humanItems").Distinct(ctx, "id", bson.M{"projectId": project})
if e != nil {
t.Fatal(e)
}
batchIDs, e := db.Collection("humanBatches").Distinct(ctx, "id", bson.M{"projectId": project})
if e != nil {
t.Fatal(e)
}
_, e = db.Collection("project_deletion_tasks").UpdateOne(ctx, bson.M{"_id": "project-deletion-" + project}, bson.M{"$setOnInsert": bson.M{"id": "project-deletion-" + project, "projectId": project, "organizationId": p.OrganizationID, "plan": bson.M{"projectId": project, "organizationId": p.OrganizationID, "projectName": p.Name}, "status": "completed", "reason": "scoped account hierarchy QA cleanup", "createdAt": nowISO()}}, options.Update().SetUpsert(true))
if e != nil {
t.Fatal(e)
}
if _, e = s.DeleteProject(ctx, project); e != nil {
t.Fatal(e)
}
for _, col := range []string{"annotationRevisions", "sliceRevisions", "annotationReviews", "annotationWorklogEvents"} {
if _, e = db.Collection(col).DeleteMany(ctx, bson.M{"taskId": bson.M{"$in": taskIDs}}); e != nil {
t.Fatal(e)
}
}
for _, col := range []string{"humanEvents", "humanStageAttempts", "humanClaimRequests"} {
if _, e = db.Collection(col).DeleteMany(ctx, bson.M{"itemId": bson.M{"$in": items}}); e != nil {
t.Fatal(e)
}
}
if _, e = db.Collection("releasePartitions").DeleteMany(ctx, bson.M{"batchId": bson.M{"$in": batchIDs}}); e != nil {
t.Fatal(e)
}
for _, nonce := range []string{"20260921accountsa1", "20260921accountsb1"} {
supplier := "supplier-discard-verify-" + nonce
for _, role := range []string{"annotator", "quality_reviewer", "acceptance_reviewer"} {
id := "user-discard-verify-" + nonce + "-" + role
u, e := s.GetUser(ctx, id)
if e != nil || u == nil || u.OrganizationID != p.OrganizationID || u.SupplierID != supplier || u.Phone != testPhoneFromSeed("discard-"+nonce+"-"+role) {
t.Fatal("QA account cleanup identity")
}
if e = s.DeleteSessionsByUser(ctx, id); e != nil {
t.Fatal(e)
}
if _, e = s.DeleteUser(ctx, id); e != nil {
t.Fatal(e)
}
}
if _, e = s.MutateSupplier(ctx, p.OrganizationID, supplier, "", true); e != nil {
t.Fatal(e)
}
if _, e = db.Collection("annotationLabels").DeleteOne(ctx, bson.M{"id": "slice-label-discard-verify-" + nonce, "organizationId": p.OrganizationID}); e != nil {
t.Fatal(e)
}
}
if _, e = db.Collection("projectAnnotationLabels").DeleteOne(ctx, bson.M{"projectId": project, "organizationId": p.OrganizationID}); e != nil {
t.Fatal(e)
}
result["cleaned"] = true
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}