fix(backend): bootstrap admin reuses existing platform company on duplicate CNPJ

When the platform company (CNPJ 00000000000000) already exists in the DB,
RegisterAccount was failing with a unique constraint error before creating
the admin user. Now the bootstrap checks for the existing company first
and binds the new admin user directly to it.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Tiago Yamamoto 2026-03-07 08:57:57 -06:00
parent 2829a3e87c
commit a5f50321b9

View file

@ -228,32 +228,48 @@ func (s *Server) Start(ctx context.Context) error {
if err != nil { if err != nil {
log.Printf("Seeding admin user: %s", adminEmail) log.Printf("Seeding admin user: %s", adminEmail)
company := &domain.Company{ // Reuse existing platform company if CNPJ already exists
ID: uuid.Nil, var platformCompanyID uuid.UUID
CNPJ: "00000000000000", if dbErr := s.db.QueryRowContext(ctx, `SELECT id FROM companies WHERE cnpj = $1 LIMIT 1`, "00000000000000").Scan(&platformCompanyID); dbErr != nil {
CorporateName: "SaveInMed Platform", // Company doesn't exist — create it via RegisterAccount
Category: "platform", company := &domain.Company{
LicenseNumber: "ADMIN", ID: uuid.Nil,
IsVerified: true, CNPJ: "00000000000000",
CreatedAt: time.Now().UTC(), CorporateName: "SaveInMed Platform",
UpdatedAt: time.Now().UTC(), Category: "platform",
} LicenseNumber: "ADMIN",
IsVerified: true,
err := s.svc.RegisterAccount(ctx, company, &domain.User{ CreatedAt: time.Now().UTC(),
Role: domain.RoleAdmin, UpdatedAt: time.Now().UTC(),
Name: bootstrapAdminName, }
Username: bootstrapAdminUsername, if err := s.svc.RegisterAccount(ctx, company, &domain.User{
Email: adminEmail, Role: domain.RoleAdmin,
Superadmin: false, Name: bootstrapAdminName,
}, adminPassword) Username: bootstrapAdminUsername,
Email: adminEmail,
if err != nil { Superadmin: false,
log.Printf("Failed to seed admin: %v", err) }, adminPassword); err != nil {
} else { log.Printf("Failed to seed admin: %v", err)
if _, err := s.svc.VerifyCompany(ctx, company.ID); err != nil { } else {
log.Printf("Failed to verify platform company: %v", err) if _, err := s.svc.VerifyCompany(ctx, company.ID); err != nil {
log.Printf("Failed to verify platform company: %v", err)
}
log.Printf("Admin user created: email=%s", adminEmail)
}
} else {
// Company exists — create user bound to it directly
if err := s.svc.CreateUser(ctx, &domain.User{
CompanyID: platformCompanyID,
Role: domain.RoleAdmin,
Name: bootstrapAdminName,
Username: bootstrapAdminUsername,
Email: adminEmail,
Superadmin: false,
}, adminPassword); err != nil {
log.Printf("Failed to seed admin (existing company): %v", err)
} else {
log.Printf("Admin user created: email=%s", adminEmail)
} }
log.Printf("Admin user created: email=%s", adminEmail)
} }
} else { } else {
existingUser.Role = domain.RoleAdmin existingUser.Role = domain.RoleAdmin