From f5e04b92aea8cfcbce483d80db9b842def2781fe Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 13:32:58 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20Customers:=20country=20flag,=20?= =?UTF-8?q?likely=20affiliation=20suggestion,=20notes=20rules=20documented?= =?UTF-8?q?=20and=20tested=20(#19085)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #19085 Signed-off-by: Andy Anderson --- .../added-customers-country-affiliation.md | 1 + dashboard/openapi.json | 6 +- src/docs/api-reference/customers.md | 4 +- src/docs/design/customers.md | 22 +- src/pkg/customers/affiliation.go | 158 +++++++++ src/pkg/customers/affiliation_test.go | 145 ++++++++ src/pkg/customers/country.go | 216 ++++++++++++ src/pkg/customers/country_data.go | 330 ++++++++++++++++++ src/pkg/customers/country_test.go | 154 ++++++++ src/pkg/customers/model.go | 15 +- src/pkg/customers/profilefetch_test.go | 6 +- src/pkg/customers/service.go | 12 +- src/pkg/customers/store.go | 66 +++- src/pkg/dashboard/api_customers.go | 4 +- src/pkg/dashboard/customers_ui_test.go | 13 + src/pkg/dashboard/static-src/js/customers.js | 55 ++- src/pkg/dashboard/static/index.html | 55 ++- 17 files changed, 1239 insertions(+), 23 deletions(-) create mode 100644 changelog.d/added-customers-country-affiliation.md create mode 100644 src/pkg/customers/affiliation.go create mode 100644 src/pkg/customers/affiliation_test.go create mode 100644 src/pkg/customers/country.go create mode 100644 src/pkg/customers/country_data.go create mode 100644 src/pkg/customers/country_test.go diff --git a/changelog.d/added-customers-country-affiliation.md b/changelog.d/added-customers-country-affiliation.md new file mode 100644 index 0000000000..31c0aa8226 --- /dev/null +++ b/changelog.d/added-customers-country-affiliation.md @@ -0,0 +1 @@ +- Customers: a profile now has a country, shown as a small flag with its ISO code on the row and by name under Details. It is worked out from the location text with a bundled table, offline, and marked as derived; a country you set or clear by hand is never changed, and "Auto" hands it back. A likely organization is offered as a suggestion with its evidence (the GitHub company text, or the domain of an email you confirmed by hand); Accept sets it by hand, Dismiss is remembered. Notes keep their rules: owner and read-write only, in the export, deleted on Forget. No new requests are made and nothing is read from the hub. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index c8a753cccc..594f03ab99 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -2042,7 +2042,7 @@ "Customers" ], "summary": "Edit a customer profile", - "description": "Applies one change, named by op: name, notes, profile (field real_name, organization or location, with value; state auto hands it back to GitHub), identity_add, identity_remove, tag (state on, off or auto), goal_add, goal_edit, goal_confirm, goal_reject, satisfaction_set, satisfaction_confirm, satisfaction_reject. Owner and read-write users may edit anyone. A read-only user may post only to /api/customers/me/edit, and only name, profile, identity, tag and goal changes; an identity they add is an unconfirmed claim that resolves nobody until someone with the full view confirms it. Audited as customer_edit with the person and the op, never the value.", + "description": "Applies one change, named by op: name, notes, profile (field real_name, organization, location or country, with value; a country is an ISO 3166 alpha-2 code or a country name; state auto hands it back to the automatic source, which derives a country from the location), affiliation_dismiss (value: a suggested organization the person refused), identity_add, identity_remove, tag (state on, off or auto), goal_add, goal_edit, goal_confirm, goal_reject, satisfaction_set, satisfaction_confirm, satisfaction_reject. Owner and read-write users may edit anyone. A read-only user may post only to /api/customers/me/edit, and only name, profile, affiliation_dismiss, identity, tag and goal changes; an identity they add is an unconfirmed claim that resolves nobody until someone with the full view confirms it. Audited as customer_edit with the person and the op, never the value.", "parameters": [ { "name": "id", @@ -2070,6 +2070,7 @@ "name", "notes", "profile", + "affiliation_dismiss", "identity_add", "identity_remove", "tag", @@ -2114,7 +2115,8 @@ "enum": [ "real_name", "organization", - "location" + "location", + "country" ] }, "goal_id": { diff --git a/src/docs/api-reference/customers.md b/src/docs/api-reference/customers.md index 7dd1364ad3..832e55ad20 100644 --- a/src/docs/api-reference/customers.md +++ b/src/docs/api-reference/customers.md @@ -14,8 +14,8 @@ The rules are enforced twice: by the handlers and again by the store's service o |---|---|---|---|---| | `GET` | `/api/customers` | Signed-in user | The Customers section: `{enabled, full, owner, me, people, suggestions, default_tags, levels}`. `me` is the viewer's own profile, created on first read. `people` and `suggestions` are empty without the full view | `pkg/dashboard/api_customers.go:178` | | `POST` | `/api/customers` | Full view | Add a customer by hand: `{name, identities?: [{kind, value}]}`. 409 when an identity belongs to another customer; a `hive_user` identity is refused. Audited as `customer_add` | `pkg/dashboard/api_customers.go:179` | -| `GET` | `/api/customers/{id}` | Signed-in user; self reaches only `me` | One profile, with edge counts and open "Same person?" hints for the full view. A viewer without the full view gets no notes, satisfaction, merge history, counts or hints. Opening someone else's profile is audited as `customer_profile_open` | `pkg/dashboard/api_customers.go:180` | -| `POST` | `/api/customers/{id}/edit` | Full view; self only as `/api/customers/me/edit` | One change: `{op, ...}` with `op` one of `name`, `notes`, `profile` (`field` of `real_name`, `organization` or `location`, `value`; `state` of `auto` hands the field back to GitHub), `identity_add` (`kind`, `value`), `identity_remove` (`key`), `tag` (`tag`, `state` of `on`, `off` or `auto`), `goal_add` (`text`), `goal_edit` (`goal_id`, `text`), `goal_confirm`, `goal_reject` (`goal_id`), `satisfaction_set` (`level`), `satisfaction_confirm`, `satisfaction_reject`. Self may use the name, profile, identity, tag and goal ops; an identity added by self is an unconfirmed claim that resolves nobody until the full view confirms it with `identity_add`. Audited as `customer_edit` with the person and the op, never the value | `pkg/dashboard/api_customers.go:181` | +| `GET` | `/api/customers/{id}` | Signed-in user; self reaches only `me` | One profile, with edge counts and open "Same person?" hints for the full view, and `affiliation_suggestion` (`{value, rule, evidence}`, never stored) when a likely organization can be offered. A viewer without the full view gets no notes, satisfaction, merge history, counts or hints. Opening someone else's profile is audited as `customer_profile_open` | `pkg/dashboard/api_customers.go:180` | +| `POST` | `/api/customers/{id}/edit` | Full view; self only as `/api/customers/me/edit` | One change: `{op, ...}` with `op` one of `name`, `notes`, `profile` (`field` of `real_name`, `organization`, `location` or `country`, `value`; a country is an ISO 3166 alpha-2 code or a country name; `state` of `auto` hands the field back to the automatic source, and a country is then derived again from the location), `affiliation_dismiss` (`value`, a suggested organization the person refused), `identity_add` (`kind`, `value`), `identity_remove` (`key`), `tag` (`tag`, `state` of `on`, `off` or `auto`), `goal_add` (`text`), `goal_edit` (`goal_id`, `text`), `goal_confirm`, `goal_reject` (`goal_id`), `satisfaction_set` (`level`), `satisfaction_confirm`, `satisfaction_reject`. Self may use the name, profile, affiliation_dismiss, identity, tag and goal ops; an identity added by self is an unconfirmed claim that resolves nobody until the full view confirms it with `identity_add`. Audited as `customer_edit` with the person and the op, never the value | `pkg/dashboard/api_customers.go:181` | | `DELETE` | `/api/customers/{id}` | Owner only | Forget: deletes the customer, their identities and every edge to them, and keeps one salted-hash tombstone per confirmed identity so discovery does not rebuild them. 200 `{forgotten, edges_removed}`. Audited as `customer_forget` | `pkg/dashboard/api_customers.go:182` | | `POST` | `/api/customers/suggestions/{sid}/accept` | Full view | Turn a suggested person into a customer. With the optional body `{into}` (an existing customer id, or `me`) it attaches the suggestion to that customer instead: the identity becomes one of theirs, pinned as a manual decision, no new person is created, the activity moves onto them on the next sweep, and `unmerge` undoes it with the id in the target's merge history. Audited as `customer_accept`, or `customer_attach` with the target's id and never a name. When `customers.mention_search.enabled` is on and the suggestion is a GitHub login, a budgeted background GitHub search adds `mentioned_in` and `commented_on` edges after the accept (see the design doc, step E) | `pkg/dashboard/api_customers.go:183` | | `POST` | `/api/customers/suggestions/{sid}/dismiss` | Full view | Delete a suggestion and tombstone its key, so it is not offered again. Audited as `customer_dismiss` | `pkg/dashboard/api_customers.go:184` | diff --git a/src/docs/design/customers.md b/src/docs/design/customers.md index c68bd76c92..c603a1148f 100644 --- a/src/docs/design/customers.md +++ b/src/docs/design/customers.md @@ -92,7 +92,7 @@ contributor is one of several sources of identity for a person. | `goals` | See section 8. | | `satisfaction` | See section 8. | | `notes` | Free text, written by people only. | -| `profile` | Optional `real_name`, `organization` and `location`, each `{value, source, rule, at, by}`. `source` is `auto` (the person's own public GitHub profile name, company and location, fetched once on accept) or `manual` (a person typed it or cleared it; the fetch never changes it; `auto` hands it back). Nothing here comes from the hub. | +| `profile` | Optional `real_name`, `organization`, `location` and `country`, each `{value, source, rule, at, by}`. `source` is `auto` (the person's own public GitHub profile name, company and location, fetched once on accept; the country derived offline from the location, rule `location`) or `manual` (a person typed it or cleared it; neither the fetch nor the location changes it; `auto` hands it back). `country` is an ISO 3166 alpha-2 code. Also `dismissed_affiliations`, the suggested organizations a person refused (at most 20). Nothing here comes from the hub. | | `merged_from` | Merge history, so a merge can be undone. | **Identity** `{kind, value, source, confidence, manual, at, by}`. Kinds: @@ -328,6 +328,26 @@ with the person and export includes them. The hub's own records of the same peop (name, company, country, notes, inferred affiliation) are not read or copied: that is the open question in section 15 and needs a consent decision first. +Country and likely affiliation add no request of their own. The country is derived +from the location text by a bundled table (country names and aliases, ISO codes, US +states and Canadian provinces, major cities; `pkg/customers/country_data.go`), offline +and deterministically. The last comma-separated piece decides, a bare two-letter code +after a comma reads as a US state first unless a city of another country precedes it +("Berlin, DE"), and "remote", "Earth" or an empty location give no country. It is a +guess about free text: a small city with no state or country, or a location that is +a joke, can be wrong or empty, so it is an automatic field a person overwrites or +clears, and a hand-set or hand-cleared country is never touched. A likely +affiliation is a view-time suggestion, never stored: the GitHub company text tidied +(legal suffix and "@" dropped, a bare handle capitalized), or, while the organization +is empty, the domain of an email identity a person confirmed by hand (never a +free-mail or code-host domain, and the address itself is not shown). It carries its +evidence ("from GitHub company field"), Accept writes it as a by-hand organization, +Dismiss remembers the refusal on the profile. Public GitHub organization membership +is deliberately not used: it is not fetched, and fetching it would be a new request. +Notes are free text up to 4000 bytes, written by the owner and read-write users, never +shown to a read-only user (not even on their own profile), part of the owner's export +and deleted with the person on Forget. + Step E, the budgeted GitHub search on accept, is built and opt-in. `customers.mention_search.enabled` defaults to **off** (env `HIVE_CUSTOMERS_MENTION_SEARCH_ENABLED`), because it asks GitHub about a person's diff --git a/src/pkg/customers/affiliation.go b/src/pkg/customers/affiliation.go new file mode 100644 index 0000000000..33e090f1b4 --- /dev/null +++ b/src/pkg/customers/affiliation.go @@ -0,0 +1,158 @@ +package customers + +import ( + "strings" + "unicode" +) + +// A likely affiliation is a suggestion about a person's organization, never a +// stored fact. SuggestAffiliation is pure and offline: it reads only what the +// profile already holds and makes no request. Accepting a suggestion writes it +// as a by-hand organization; dismissing it remembers the refusal. +// +// Rules, in order, for a profile whose organization a person has not set or +// cleared by hand: +// +// 1. company: the organization filled from the person's GitHub company text, +// tidied (legal suffix and "@" dropped, a bare lower-case handle given +// capitals). Offered only when the tidied form differs from what is shown. +// 2. email domain: the domain of an email identity a person confirmed by +// hand, when the organization is still empty and the domain is not a +// free-mail or code-host provider. +// +// Public GitHub organization membership is not used: it is not fetched today, +// and reading it would be a new network call. + +// Affiliation suggestion evidence kinds. +const ( + AffiliationFromCompany = "github_company" + AffiliationFromEmail = "email_domain" +) + +// AffiliationSuggestion is one suggested organization with where it came from. +// Evidence is human-readable and never includes the email local part. +type AffiliationSuggestion struct { + Value string `json:"value"` + Rule string `json:"rule"` + Evidence string `json:"evidence"` +} + +// shortOrgLen is the longest bare handle shown in capitals ("ibm" -> "IBM"). +const shortOrgLen = 3 + +var legalSuffixes = map[string]bool{ + "inc": true, "llc": true, "ltd": true, "corp": true, "corporation": true, + "gmbh": true, "co": true, "company": true, "ag": true, "plc": true, + "limited": true, "incorporated": true, "bv": true, "oy": true, "ab": true, +} + +// freeMailDomains name no organization: a person's mailbox provider says +// nothing about where they work. +var freeMailDomains = map[string]bool{ + "gmail.com": true, "googlemail.com": true, "outlook.com": true, "hotmail.com": true, + "live.com": true, "msn.com": true, "yahoo.com": true, "icloud.com": true, "me.com": true, + "proton.me": true, "protonmail.com": true, "aol.com": true, "gmx.com": true, "gmx.de": true, + "qq.com": true, "163.com": true, "126.com": true, "yandex.com": true, "mail.com": true, + "fastmail.com": true, "hey.com": true, "pm.me": true, "github.com": true, + "users.noreply.github.com": true, "noreply.github.com": true, +} + +// secondLevelLabels are the generic labels that precede a country code in a +// registrable domain ("example.co.uk"). +var secondLevelLabels = map[string]bool{"co": true, "com": true, "org": true, "net": true, "ac": true, "gov": true, "edu": true} + +// TidyCompany makes a GitHub company string presentable: it drops "@", a +// trailing legal suffix and trailing punctuation, and gives a lower-case +// single word capitals (up to three letters) or a leading capital. +func TidyCompany(s string) string { + s = strings.TrimPrefix(strings.TrimSpace(s), "@") + words := strings.Fields(s) + for len(words) > 1 { + last := strings.ToLower(strings.Trim(words[len(words)-1], ".,")) + if !legalSuffixes[last] { + break + } + words = words[:len(words)-1] + } + out := strings.TrimRight(strings.Join(words, " "), ".,;") + if len(words) == 1 && out == strings.ToLower(out) { + return capitalizeOrg(out) + } + return out +} + +func capitalizeOrg(s string) string { + if s == "" { + return "" + } + if len(s) <= shortOrgLen { + return strings.ToUpper(s) + } + r := []rune(s) + r[0] = unicode.ToUpper(r[0]) + return string(r) +} + +// orgFromDomain names the organization a mail domain implies, or "" for a +// free-mail or code-host domain. +func orgFromDomain(domain string) string { + domain = strings.ToLower(strings.Trim(strings.TrimSpace(domain), ".")) + if domain == "" || freeMailDomains[domain] || !strings.Contains(domain, ".") { + return "" + } + labels := strings.Split(domain, ".") + n := len(labels) + idx := n - 2 + if n >= 3 && len(labels[n-1]) == isoCodeLen && secondLevelLabels[labels[n-2]] { + idx = n - 3 + } + if labels[idx] == "" { + return "" + } + return capitalizeOrg(labels[idx]) +} + +func affiliationDismissed(pr Profile, key string) bool { + for _, d := range pr.DismissedAffiliations { + if d == key { + return true + } + } + return false +} + +// SuggestAffiliation returns the likely organization for p, or nil when a +// person has settled the field, nothing supports one, or the person refused it. +func SuggestAffiliation(p Person) *AffiliationSuggestion { + org := p.Profile.Organization + if org.Source == SourceManual { + return nil + } + ok := func(v string) bool { + return v != "" && len(v) <= MaxProfileFieldLen && !affiliationDismissed(p.Profile, strings.ToLower(v)) + } + if org.Value != "" && org.Rule == ProfileSourceGitHub { + if v := TidyCompany(org.Value); v != org.Value && ok(v) { + return &AffiliationSuggestion{Value: v, Rule: AffiliationFromCompany, + Evidence: "from GitHub company field \"" + org.Value + "\""} + } + return nil + } + if org.Value != "" { + return nil + } + for _, id := range p.Identities { + if id.Kind != KindEmail || !id.Manual || id.Claimed { + continue + } + _, domain, found := strings.Cut(id.Value, "@") + if !found { + continue + } + if v := orgFromDomain(domain); ok(v) { + return &AffiliationSuggestion{Value: v, Rule: AffiliationFromEmail, + Evidence: "from email domain " + strings.ToLower(domain)} + } + } + return nil +} diff --git a/src/pkg/customers/affiliation_test.go b/src/pkg/customers/affiliation_test.go new file mode 100644 index 0000000000..c328ff5ca0 --- /dev/null +++ b/src/pkg/customers/affiliation_test.go @@ -0,0 +1,145 @@ +package customers + +import ( + "strings" + "testing" +) + +func TestTidyCompany(t *testing.T) { + for in, want := range map[string]string{ + "acme": "Acme", "@acme": "Acme", "ibm": "IBM", "IBM": "IBM", "IBM Corp.": "IBM", "Acme, Inc.": "Acme", + "Red Hat": "Red Hat", "Globex GmbH": "Globex", "Inc": "Inc", "": "", + } { + if got := TidyCompany(in); got != want { + t.Errorf("TidyCompany(%q) = %q, want %q", in, got, want) + } + } +} + +func TestOrgFromDomain(t *testing.T) { + for in, want := range map[string]string{ + "ibm.com": "IBM", "research.ibm.com": "IBM", "redhat.com": "Redhat", "example.co.uk": "Example", + "gmail.com": "", "users.noreply.github.com": "", "localhost": "", "": "", + } { + if got := orgFromDomain(in); got != want { + t.Errorf("orgFromDomain(%q) = %q, want %q", in, got, want) + } + } +} + +func affPerson(org ProfileField, ids ...Identity) Person { + return Person{Profile: Profile{Organization: org}, Identities: ids} +} + +func TestSuggestAffiliationRules(t *testing.T) { + gh := ProfileField{Value: "acme", Source: SourceAuto, Rule: ProfileSourceGitHub} + hand := Identity{Kind: KindEmail, Value: "ada@ibm.com", Manual: true} + + s := SuggestAffiliation(affPerson(gh)) + if s == nil || s.Value != "Acme" || s.Rule != AffiliationFromCompany || !strings.Contains(s.Evidence, "GitHub company field") { + t.Fatalf("company rule = %+v", s) + } + if s := SuggestAffiliation(affPerson(ProfileField{Value: "IBM", Source: SourceAuto, Rule: ProfileSourceGitHub})); s != nil { + t.Fatalf("an already tidy company was suggested: %+v", s) + } + s = SuggestAffiliation(affPerson(ProfileField{}, hand)) + if s == nil || s.Value != "IBM" || s.Rule != AffiliationFromEmail || s.Evidence != "from email domain ibm.com" || strings.Contains(s.Evidence, "ada") { + t.Fatalf("email rule = %+v", s) + } + // Email never overrides an organization that is already shown. + if s := SuggestAffiliation(affPerson(gh, hand)); s == nil || s.Rule != AffiliationFromCompany { + t.Fatalf("company must outrank the email domain: %+v", s) + } + for name, p := range map[string]Person{ + "by hand": affPerson(ProfileField{Value: "Globex", Source: SourceManual}, hand), + "cleared by hand": affPerson(ProfileField{Source: SourceManual}, hand), + "claimed email": affPerson(ProfileField{}, Identity{Kind: KindEmail, Value: "ada@ibm.com", Manual: true, Claimed: true}), + "unconfirmed": affPerson(ProfileField{}, Identity{Kind: KindEmail, Value: "ada@ibm.com"}), + "git email": affPerson(ProfileField{}, Identity{Kind: KindGitEmail, Value: "ada@ibm.com", Manual: true}), + "free mail": affPerson(ProfileField{}, Identity{Kind: KindEmail, Value: "ada@gmail.com", Manual: true}), + "nothing": affPerson(ProfileField{}), + } { + if s := SuggestAffiliation(p); s != nil { + t.Errorf("%s: suggested %+v", name, s) + } + } +} + +func TestAffiliationDismissAcceptAndBounds(t *testing.T) { + s := newService(t) + p, err := s.Add(ownerV, "Ada", []Identity{{Kind: KindEmail, Value: "ada@ibm.com"}}) + if err != nil { + t.Fatal(err) + } + got, _ := s.Get(ownerV, p.ID) + if got.Affiliation == nil || got.Affiliation.Value != "IBM" { + t.Fatalf("view suggestion = %+v", got.Affiliation) + } + // A list view carries no suggestion. + if l, _ := s.List(ownerV); len(l.People) != 1 || l.People[0].Affiliation != nil { + t.Fatalf("list view carried a suggestion: %+v", l.People) + } + // Dismiss remembers the refusal, case-insensitively and once. + for _, v := range []string{"IBM", "ibm"} { + if _, err := s.Edit(ownerV, p.ID, Edit{Op: OpAffiliationDismiss, Value: v}); err != nil { + t.Fatal(err) + } + } + got, _ = s.Get(ownerV, p.ID) + if got.Affiliation != nil || len(got.Profile.DismissedAffiliations) != 1 { + t.Fatalf("after dismiss: %+v %v", got.Affiliation, got.Profile.DismissedAffiliations) + } + if _, err := s.Edit(ownerV, p.ID, Edit{Op: OpAffiliationDismiss, Value: " "}); err == nil { + t.Fatal("an empty dismissal was accepted") + } + for i := 0; i < MaxDismissedAffiliations+5; i++ { + if _, err := s.Edit(ownerV, p.ID, Edit{Op: OpAffiliationDismiss, Value: "org" + strings.Repeat("x", i)}); err != nil { + t.Fatal(err) + } + } + got, _ = s.Get(ownerV, p.ID) + if n := len(got.Profile.DismissedAffiliations); n != MaxDismissedAffiliations { + t.Fatalf("dismissals are not bounded: %d", n) + } + // Accept is an ordinary by-hand organization edit. + got, err = s.Edit(ownerV, p.ID, Edit{Op: OpProfile, Field: FieldOrganization, Value: "IBM"}) + if err != nil || got.Profile.Organization.Source != SourceManual || got.Affiliation != nil { + t.Fatalf("accept = %+v, %v", got.Profile.Organization, err) + } + // A read-only user may dismiss on their own profile only. + if _, err := s.Edit(readV, MeID, Edit{Op: OpAffiliationDismiss, Value: "x"}); err != nil { + t.Fatalf("self dismiss: %v", err) + } + if _, err := s.Edit(readV, p.ID, Edit{Op: OpAffiliationDismiss, Value: "x"}); err == nil { + t.Fatal("a read-only user dismissed on someone else") + } +} + +func TestNotesBoundsVisibilityExportAndForget(t *testing.T) { + s := newService(t) + p, _ := s.Add(ownerV, "Ada", []Identity{{Kind: KindGitHub, Value: "ada-gh"}}) + if _, err := s.Edit(ownerV, p.ID, Edit{Op: OpNotes, Notes: strings.Repeat("n", MaxNotesLen+1)}); err == nil { + t.Fatal("notes over the bound were accepted") + } + if got, err := s.Edit(rwV, p.ID, Edit{Op: OpNotes, Notes: strings.Repeat("n", MaxNotesLen)}); err != nil || len(got.Notes) != MaxNotesLen { + t.Fatalf("read-write notes at the bound = %d, %v", len(got.Notes), err) + } + if _, err := s.Edit(ownerV, p.ID, Edit{Op: OpProfile, Field: FieldCountry, Value: "fr"}); err != nil { + t.Fatal(err) + } + ex, err := s.Export(ownerV, p.ID) + if err != nil || len(ex.Person.Notes) != MaxNotesLen || ex.Person.Profile.Country.Value != "FR" { + t.Fatalf("export lacks notes or country: %v %+v", err, ex.Person.Profile.Country) + } + if _, err := s.Forget(ownerV, p.ID); err != nil { + t.Fatal(err) + } + if _, err := s.Get(ownerV, p.ID); err == nil { + t.Fatal("a forgotten customer is still readable") + } + for _, q := range s.Store().People() { + if q.ID == p.ID { + t.Fatalf("forgotten person left behind: %+v", q) + } + } +} diff --git a/src/pkg/customers/country.go b/src/pkg/customers/country.go new file mode 100644 index 0000000000..911ef251db --- /dev/null +++ b/src/pkg/customers/country.go @@ -0,0 +1,216 @@ +package customers + +import ( + "strings" + "unicode" +) + +// DeriveCountry turns a free-text location into an ISO 3166 alpha-2 country, +// deterministically and offline, from the bundled table in country_data.go. +// It is a best guess about a text the person typed, not a fact: callers store +// it as an automatic field a person can overwrite. + +// CountryRuleLocation is the rule name recorded on an automatic country. +const CountryRuleLocation = "location" + +// Limits on how much of a location is examined, so one long string cannot +// make a lookup expensive. +const ( + maxLocationSegments = 6 + maxSuffixWords = 3 + maxAbbrevLen = 4 + isoCodeLen = 2 + flagBase = 0x1F1E6 + flagLast = 0x1F1FF +) + +// ambiguousStates are US state names that are also a country; a city of that +// other country before them wins ("Tbilisi, Georgia"). +var ambiguousStates = map[string]bool{"georgia": true} + +var ( + countryNames = map[string]string{} // folded name or alias -> ISO + countryByCode = map[string]string{} // ISO -> English name (folded) + subdivisions = map[string]string{} // folded state, province -> ISO + stateAbbrevMap = map[string]string{} // upper-case abbreviation -> ISO + cityCountries = map[string]string{} // folded city -> ISO +) + +func init() { + for _, line := range strings.Split(countryTable, "\n") { + parts := strings.Split(line, "|") + if len(parts) != 3 { + continue + } + code := parts[0] + countryByCode[code] = parts[1] + countryNames[parts[1]] = code + for _, a := range strings.Split(parts[2], ";") { + if a != "" { + countryNames[a] = code + } + } + } + loadPlaces(subdivisionTable, subdivisions) + loadPlaces(cityTable, cityCountries) + for _, line := range strings.Split(stateAbbrevs, "\n") { + code, list, ok := strings.Cut(line, "|") + if !ok { + continue + } + for _, ab := range strings.Fields(list) { + stateAbbrevMap[ab] = code + } + } +} + +func loadPlaces(table string, into map[string]string) { + for _, line := range strings.Split(table, "\n") { + code, list, ok := strings.Cut(line, "|") + if !ok { + continue + } + for _, n := range strings.Split(list, ";") { + if n != "" { + into[n] = code + } + } + } +} + +var placeFolder = strings.NewReplacer( + "á", "a", "à", "a", "â", "a", "ã", "a", "ä", "a", "å", "a", "ā", "a", "ă", "a", + "ç", "c", "ć", "c", "č", "c", + "é", "e", "è", "e", "ê", "e", "ë", "e", "ě", "e", "ę", "e", + "í", "i", "ì", "i", "î", "i", "ï", "i", "ı", "i", + "ł", "l", "ñ", "n", "ń", "n", "ň", "n", + "ó", "o", "ò", "o", "ô", "o", "õ", "o", "ö", "o", "ø", "o", "ő", "o", + "ř", "r", "š", "s", "ş", "s", "ś", "s", "ß", "ss", + "ú", "u", "ù", "u", "û", "u", "ü", "u", "ű", "u", "ů", "u", + "ý", "y", "ž", "z", "ź", "z", "ż", "z", "ğ", "g", +) + +// foldPlace lower-cases s, folds common Latin accents, turns punctuation into +// spaces and collapses whitespace: "São Paulo" and "sao paulo" compare equal. +func foldPlace(s string) string { + s = placeFolder.Replace(strings.ToLower(s)) + var b strings.Builder + for _, r := range s { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + b.WriteRune(r) + } else { + b.WriteByte(' ') + } + } + f := strings.Join(strings.Fields(b.String()), " ") + switch f { + case "u s a", "u s": + return "usa" + case "u k": + return "uk" + } + return strings.TrimPrefix(f, "the ") +} + +// ValidCountry reports whether code is a known ISO 3166 alpha-2 code. +func ValidCountry(code string) bool { + _, ok := countryByCode[strings.ToUpper(strings.TrimSpace(code))] + return ok +} + +// CountryFromInput reads a country a person typed or picked: an ISO code +// ("de") or a country name or alias ("Germany", "UK"). It returns "" when the +// input is neither. +func CountryFromInput(s string) string { + t := strings.TrimSpace(s) + if len(t) == isoCodeLen && ValidCountry(t) { + return strings.ToUpper(t) + } + return countryNames[foldPlace(t)] +} + +// flagCountry returns the country of a regional-indicator flag emoji in s. +func flagCountry(s string) string { + rs := []rune(s) + for i := 0; i+1 < len(rs); i++ { + a, b := rs[i], rs[i+1] + if a >= flagBase && a <= flagLast && b >= flagBase && b <= flagLast { + code := string([]rune{'A' + (a - flagBase), 'A' + (b - flagBase)}) + if ValidCountry(code) { + return code + } + } + } + return "" +} + +// segmentCountry resolves one comma-separated piece. afterComma is true for +// the final piece of a multi-piece location, where an upper-case two-letter +// code reads as a US state first ("Austin, TX"). ambiguous reports a hit a +// city of another country before it may overrule ("Berlin, DE"). +func segmentCountry(raw string, afterComma bool) (code string, ambiguous bool) { + raw = strings.TrimSpace(raw) + if t := strings.ReplaceAll(raw, ".", ""); t != "" && len(t) <= maxAbbrevLen && t == strings.ToUpper(t) { + if c, ok := stateAbbrevMap[t]; ok && afterComma { + return c, ValidCountry(t) + } + if len(t) == isoCodeLen && ValidCountry(t) { + return t, false + } + } + words := strings.Fields(foldPlace(raw)) + // Longest word-suffix first, so "kansas city" beats "kansas" and + // "munich germany" resolves through "germany". + for n := min(len(words), maxSuffixWords); n >= 1; n-- { + cand := strings.Join(words[len(words)-n:], " ") + if cand == "us" && len(words) > 1 { + continue + } + if c, ok := countryNames[cand]; ok { + return c, false + } + if c, ok := subdivisions[cand]; ok { + return c, ambiguousStates[cand] + } + if c, ok := cityCountries[cand]; ok { + return c, false + } + } + return "", false +} + +// DeriveCountry returns the ISO alpha-2 country a free-text location names, +// or "" when it names none ("remote", "Earth", empty). The last +// comma-separated piece decides; earlier pieces are tried only when it names +// nothing, except that a known city before an ambiguous state name or code +// wins. +func DeriveCountry(location string) string { + loc := strings.TrimSpace(location) + if loc == "" { + return "" + } + if c := flagCountry(loc); c != "" { + return c + } + segs := strings.FieldsFunc(loc, func(r rune) bool { + return r == ',' || r == ';' || r == '/' || r == '|' || r == '(' || r == ')' || r == '\n' + }) + if len(segs) > maxLocationSegments { + segs = segs[len(segs)-maxLocationSegments:] + } + for i := len(segs) - 1; i >= 0; i-- { + c, amb := segmentCountry(segs[i], i == len(segs)-1 && i > 0) + if c == "" { + continue + } + if amb { + for j := i - 1; j >= 0; j-- { + if other := cityCountries[foldPlace(segs[j])]; other != "" { + return other + } + } + } + return c + } + return "" +} diff --git a/src/pkg/customers/country_data.go b/src/pkg/customers/country_data.go new file mode 100644 index 0000000000..f8c5cdd80a --- /dev/null +++ b/src/pkg/customers/country_data.go @@ -0,0 +1,330 @@ +package customers + +// The bundled place table behind DeriveCountry. It is data, not logic: every +// name is lower case with accents folded (see foldPlace), one country per +// line as "ISO|English name|alias;alias". No network, no geocoder. +const countryTable = `AD|andorra| +AE|united arab emirates|uae;emirates;dubai;abu dhabi +AF|afghanistan| +AG|antigua and barbuda|antigua +AI|anguilla| +AL|albania| +AM|armenia| +AO|angola| +AR|argentina| +AS|american samoa| +AT|austria|osterreich +AU|australia| +AW|aruba| +AX|aland islands| +AZ|azerbaijan| +BA|bosnia and herzegovina|bosnia +BB|barbados| +BD|bangladesh| +BE|belgium|belgique;belgie +BF|burkina faso| +BG|bulgaria| +BH|bahrain| +BI|burundi| +BJ|benin| +BL|saint barthelemy| +BM|bermuda| +BN|brunei|brunei darussalam +BO|bolivia| +BQ|bonaire sint eustatius and saba| +BR|brazil|brasil +BS|bahamas| +BT|bhutan| +BW|botswana| +BY|belarus| +BZ|belize| +CA|canada| +CC|cocos islands| +CD|democratic republic of the congo|dr congo;drc +CF|central african republic| +CG|republic of the congo|congo +CH|switzerland|schweiz;suisse;svizzera +CI|cote d ivoire|ivory coast +CK|cook islands| +CL|chile| +CM|cameroon| +CN|china|prc;peoples republic of china;mainland china +CO|colombia| +CR|costa rica| +CU|cuba| +CV|cabo verde|cape verde +CW|curacao| +CX|christmas island| +CY|cyprus| +CZ|czechia|czech republic +DE|germany|deutschland +DJ|djibouti| +DK|denmark|danmark +DM|dominica| +DO|dominican republic| +DZ|algeria| +EC|ecuador| +EE|estonia| +EG|egypt| +EH|western sahara| +ER|eritrea| +ES|spain|espana +ET|ethiopia| +FI|finland|suomi +FJ|fiji| +FK|falkland islands| +FM|micronesia| +FO|faroe islands| +FR|france| +GA|gabon| +GB|united kingdom|uk;great britain;britain;england;scotland;wales;northern ireland;united kingdom of great britain and northern ireland +GD|grenada| +GE|republic of georgia| +GF|french guiana| +GG|guernsey| +GH|ghana| +GI|gibraltar| +GL|greenland| +GM|gambia| +GN|guinea| +GP|guadeloupe| +GQ|equatorial guinea| +GR|greece| +GT|guatemala| +GU|guam| +GW|guinea bissau| +GY|guyana| +HK|hong kong| +HN|honduras| +HR|croatia|hrvatska +HT|haiti| +HU|hungary| +ID|indonesia| +IE|ireland|republic of ireland +IL|israel| +IM|isle of man| +IN|india|bharat +IO|british indian ocean territory| +IQ|iraq| +IR|iran| +IS|iceland| +IT|italy|italia +JE|jersey| +JM|jamaica| +JO|jordan| +JP|japan| +KE|kenya| +KG|kyrgyzstan| +KH|cambodia| +KI|kiribati| +KM|comoros| +KN|saint kitts and nevis| +KP|north korea| +KR|south korea|korea;republic of korea +KW|kuwait| +KY|cayman islands| +KZ|kazakhstan| +LA|laos| +LB|lebanon| +LC|saint lucia| +LI|liechtenstein| +LK|sri lanka| +LR|liberia| +LS|lesotho| +LT|lithuania| +LU|luxembourg| +LV|latvia| +LY|libya| +MA|morocco| +MC|monaco| +MD|moldova| +ME|montenegro| +MF|saint martin| +MG|madagascar| +MH|marshall islands| +MK|north macedonia|macedonia +ML|mali| +MM|myanmar|burma +MN|mongolia| +MO|macao|macau +MP|northern mariana islands| +MQ|martinique| +MR|mauritania| +MS|montserrat| +MT|malta| +MU|mauritius| +MV|maldives| +MW|malawi| +MX|mexico|mexico +MY|malaysia| +MZ|mozambique| +NA|namibia| +NC|new caledonia| +NE|niger| +NF|norfolk island| +NG|nigeria| +NI|nicaragua| +NL|netherlands|holland;nederland +NO|norway|norge +NP|nepal| +NR|nauru| +NU|niue| +NZ|new zealand|aotearoa +OM|oman| +PA|panama| +PE|peru| +PF|french polynesia| +PG|papua new guinea| +PH|philippines| +PK|pakistan| +PL|poland|polska +PM|saint pierre and miquelon| +PN|pitcairn islands| +PR|puerto rico| +PS|palestine| +PT|portugal| +PW|palau| +PY|paraguay| +QA|qatar| +RE|reunion| +RO|romania| +RS|serbia| +RU|russia|russian federation +RW|rwanda| +SA|saudi arabia|ksa +SB|solomon islands| +SC|seychelles| +SD|sudan| +SE|sweden|sverige +SG|singapore| +SH|saint helena| +SI|slovenia| +SJ|svalbard and jan mayen| +SK|slovakia|slovak republic +SL|sierra leone| +SM|san marino| +SN|senegal| +SO|somalia| +SR|suriname| +SS|south sudan| +ST|sao tome and principe| +SV|el salvador| +SX|sint maarten| +SY|syria| +SZ|eswatini|swaziland +TC|turks and caicos islands| +TD|chad| +TG|togo| +TH|thailand| +TJ|tajikistan| +TK|tokelau| +TL|timor leste|east timor +TM|turkmenistan| +TN|tunisia| +TO|tonga| +TR|turkey|turkiye +TT|trinidad and tobago|trinidad +TV|tuvalu| +TW|taiwan| +TZ|tanzania| +UA|ukraine| +UG|uganda| +US|united states|usa;us;america;united states of america +UY|uruguay| +UZ|uzbekistan| +VA|vatican city|holy see +VC|saint vincent and the grenadines| +VE|venezuela| +VG|british virgin islands| +VI|us virgin islands| +VN|vietnam|viet nam +VU|vanuatu| +WF|wallis and futuna| +WS|samoa| +XK|kosovo| +YE|yemen| +YT|mayotte| +ZA|south africa| +ZM|zambia| +ZW|zimbabwe|` + +// subdivisionTable maps the states, provinces and regions a location often +// ends with to their country: "ISO|name;name". Two-letter abbreviations are +// listed apart (stateAbbrevs) because they collide with ISO codes. +const subdivisionTable = `US|alabama;alaska;arizona;arkansas;california;colorado;connecticut;delaware;florida;georgia;hawaii;idaho;illinois;indiana;iowa;kansas;kentucky;louisiana;maine;maryland;massachusetts;michigan;minnesota;mississippi;missouri;montana;nebraska;nevada;new hampshire;new jersey;new mexico;new york;north carolina;north dakota;ohio;oklahoma;oregon;pennsylvania;rhode island;south carolina;south dakota;tennessee;texas;utah;vermont;virginia;washington dc;washington d c;west virginia;washington;wisconsin;wyoming;district of columbia +CA|alberta;british columbia;manitoba;new brunswick;newfoundland and labrador;nova scotia;ontario;prince edward island;quebec;saskatchewan;yukon;northwest territories;nunavut +AU|new south wales;queensland;south australia;tasmania;victoria australia;western australia;northern territory;australian capital territory +IN|maharashtra;karnataka;tamil nadu;kerala;telangana;gujarat;rajasthan;uttar pradesh;west bengal;haryana;punjab india;andhra pradesh +DE|bavaria;bayern;baden wurttemberg;north rhine westphalia;nordrhein westfalen;hessen;saxony;niedersachsen;lower saxony;brandenburg +BR|sao paulo state;rio grande do sul;minas gerais;santa catarina;parana` + +// stateAbbrevs are the two-letter postal codes of US states, and a few +// unambiguous Canadian and Australian ones, as they appear upper-case after a +// comma ("Austin, TX"). +const stateAbbrevs = `US|AL AK AZ AR CA CO CT DE DC FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY +CA|ON BC QC AB +AU|NSW QLD VIC` + +// cityTable lists major cities that name their country on their own: +// "ISO|city;city". A city that is also a US place (Paris, Texas) is overruled +// by an explicit state or country after it. +const cityTable = `US|new york city;nyc;los angeles;san francisco;sf bay area;bay area;silicon valley;san jose;san diego;seattle;boston;chicago;austin;houston;dallas;denver;atlanta;miami;portland;philadelphia;phoenix;san antonio;las vegas;pittsburgh;raleigh;durham;minneapolis;detroit;salt lake city;nashville;brooklyn;manhattan;cambridge ma;palo alto;mountain view;sunnyvale;redmond;cupertino;menlo park;boulder;baltimore;columbus;charlotte;st louis;kansas city;orlando;tampa;honolulu;anchorage +GB|london;manchester;birmingham;edinburgh;glasgow;bristol;leeds;liverpool;cardiff;belfast;oxford;cambridge uk;sheffield;newcastle;nottingham +CA|toronto;vancouver;montreal;ottawa;calgary;edmonton;winnipeg;halifax;waterloo +DE|berlin;munich;hamburg;frankfurt;cologne;stuttgart;dusseldorf;dresden;leipzig;nuremberg;karlsruhe;bonn;heidelberg +FR|paris;lyon;marseille;toulouse;nice;nantes;bordeaux;lille;strasbourg;grenoble;montpellier +ES|madrid;barcelona;valencia;seville;bilbao;malaga;zaragoza +IT|rome;milan;turin;naples;florence;bologna;venice +NL|amsterdam;rotterdam;utrecht;eindhoven;hague;den haag;delft +BE|brussels;antwerp;ghent;leuven +CH|zurich;geneva;basel;bern;lausanne +AT|vienna;graz;salzburg;linz +SE|stockholm;gothenburg;malmo;uppsala +NO|oslo;bergen;trondheim +DK|copenhagen;aarhus;odense +FI|helsinki;espoo;tampere;turku +IE|dublin;cork;galway +PT|lisbon;porto;braga +PL|warsaw;krakow;wroclaw;gdansk;poznan +CZ|prague;brno +HU|budapest +RO|bucharest;cluj napoca;cluj +GR|athens;thessaloniki +UA|kyiv;kiev;lviv;kharkiv;odesa +RU|moscow;saint petersburg;st petersburg;novosibirsk +TR|istanbul;ankara;izmir +IL|tel aviv;jerusalem;haifa +AE|dubai;abu dhabi +SA|riyadh;jeddah +EG|cairo;alexandria +ZA|cape town;johannesburg;pretoria;durban +NG|lagos;abuja +KE|nairobi +GH|accra +MA|casablanca;rabat +IN|bangalore;bengaluru;mumbai;delhi;new delhi;hyderabad;chennai;pune;kolkata;ahmedabad;gurgaon;gurugram;noida +PK|karachi;lahore;islamabad +BD|dhaka +LK|colombo +CN|beijing;shanghai;shenzhen;guangzhou;hangzhou;chengdu;wuhan;nanjing;xian +HK|hong kong +TW|taipei;hsinchu;kaohsiung +JP|tokyo;osaka;kyoto;yokohama;nagoya;fukuoka;sapporo +KR|seoul;busan;incheon +SG|singapore +MY|kuala lumpur;penang +TH|bangkok;chiang mai +VN|hanoi;ho chi minh city;saigon;da nang +ID|jakarta;bandung;bali;surabaya +PH|manila;cebu;quezon city +AU|sydney;melbourne;brisbane;perth;adelaide;canberra +NZ|auckland;wellington;christchurch +BR|sao paulo;rio de janeiro;brasilia;belo horizonte;curitiba;porto alegre;recife;florianopolis +AR|buenos aires;cordoba;rosario +CL|santiago +CO|bogota;medellin +PE|lima +MX|mexico city;guadalajara;monterrey;tijuana +UY|montevideo +CR|san jose costa rica +GE|tbilisi` diff --git a/src/pkg/customers/country_test.go b/src/pkg/customers/country_test.go new file mode 100644 index 0000000000..50a91195fe --- /dev/null +++ b/src/pkg/customers/country_test.go @@ -0,0 +1,154 @@ +package customers + +import ( + "context" + "testing" +) + +func TestDeriveCountry(t *testing.T) { + cases := []struct{ in, want string }{ + {"Carmel, New York", "US"}, + {"Berlin", "DE"}, + {"São Paulo, Brazil", "BR"}, + {"Sao Paulo", "BR"}, + {"UK", "GB"}, + {"U.K.", "GB"}, + {"London, England", "GB"}, + {"remote", ""}, + {"Remote", ""}, + {"Earth", ""}, + {"", ""}, + {" ", ""}, + {"Remote, UK", "GB"}, + {"Austin, TX", "US"}, + {"San Francisco, CA", "US"}, + {"Toronto, ON", "CA"}, + {"Toronto, CA", "CA"}, + {"Berlin, DE", "DE"}, + {"Wilmington, DE", "US"}, + {"Tbilisi, Georgia", "GE"}, + {"Atlanta, Georgia", "US"}, + {"Georgia", "US"}, + {"Paris, Texas", "US"}, + {"Paris", "FR"}, + {"London, Ontario", "CA"}, + {"Munich Germany", "DE"}, + {"Kansas City", "US"}, + {"USA", "US"}, + {"U.S.A.", "US"}, + {"The Netherlands", "NL"}, + {"Bengaluru, Karnataka, India", "IN"}, + {"IN", "IN"}, + {"Zürich, Schweiz", "CH"}, + {"Berlin \U0001F1E9\U0001F1EA", "DE"}, + {"\U0001F1EF\U0001F1F5", "JP"}, + {"Come visit us", ""}, + {"Somewhere over the rainbow", ""}, + {"Worldwide", ""}, + {"Cambridge, MA", "US"}, + {"San Francisco Bay Area", "US"}, + } + for _, c := range cases { + if got := DeriveCountry(c.in); got != c.want { + t.Errorf("DeriveCountry(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +func TestCountryTableIsConsistent(t *testing.T) { + if len(countryByCode) < 240 { + t.Fatalf("only %d countries in the table", len(countryByCode)) + } + for name, code := range countryNames { + if !ValidCountry(code) || name != foldPlace(name) && name != "uk" { + t.Errorf("country entry %q -> %q is not folded or not an ISO code", name, code) + } + } + for tbl, m := range map[string]map[string]string{"subdivision": subdivisions, "city": cityCountries, "abbrev": stateAbbrevMap} { + for name, code := range m { + if !ValidCountry(code) { + t.Errorf("%s %q -> %q is not an ISO code", tbl, name, code) + } + if tbl != "abbrev" && name != foldPlace(name) { + t.Errorf("%s %q is not folded", tbl, name) + } + } + } +} + +func TestCountryFromInput(t *testing.T) { + for in, want := range map[string]string{"de": "DE", "DE": "DE", "Germany": "DE", "uk": "GB", "United Kingdom": "GB", "": "", "Atlantis": "", "zz": "", "France ": "FR"} { + if got := CountryFromInput(in); got != want { + t.Errorf("CountryFromInput(%q) = %q, want %q", in, got, want) + } + } +} + +func TestCountryProvenanceAndNeverOverwrite(t *testing.T) { + st, err := Open(t.TempDir(), nil) + if err != nil { + t.Fatal(err) + } + p := mustAdd(t, st, "ada", adaLogin) + + // Location by hand derives an automatic country with its rule. + p, err = st.SetProfileField(p.ID, FieldLocation, "Berlin", "olivia") + if err != nil { + t.Fatal(err) + } + if c := p.Profile.Country; c.Value != "DE" || c.Source != SourceAuto || c.Rule != CountryRuleLocation { + t.Fatalf("derived country = %+v", c) + } + // A moved location follows; an unknown one drops the guess. + p, _ = st.SetProfileField(p.ID, FieldLocation, "Lyon", "olivia") + if p.Profile.Country.Value != "FR" { + t.Fatalf("country after move = %+v", p.Profile.Country) + } + p, _ = st.SetProfileField(p.ID, FieldLocation, "remote", "olivia") + if p.Profile.Country.Value != "" || p.Profile.Country.Source != "" { + t.Fatalf("country kept after an unplaceable location = %+v", p.Profile.Country) + } + + // A hand-set country is never changed by the location or by GitHub. + p, err = st.SetProfileField(p.ID, FieldCountry, "japan", "olivia") + if err != nil || p.Profile.Country.Value != "JP" || p.Profile.Country.Source != SourceManual { + t.Fatalf("manual country = %+v, %v", p.Profile.Country, err) + } + p, _ = st.SetProfileField(p.ID, FieldLocation, "Berlin", "olivia") + p, changed, err := st.ApplyAutoProfile(p.ID, map[string]string{FieldLocation: "Paris"}) + if err != nil || p.Profile.Country.Value != "JP" { + t.Fatalf("country after fetch = %+v, %v (changed=%v)", p.Profile.Country, err, changed) + } + // Clearing by hand is honored: it stays empty and manual. + p, _ = st.SetProfileField(p.ID, FieldCountry, "", "olivia") + if p.Profile.Country.Value != "" || p.Profile.Country.Source != SourceManual { + t.Fatalf("cleared country = %+v", p.Profile.Country) + } + p, _ = st.SetProfileField(p.ID, FieldLocation, "Madrid", "olivia") + if p.Profile.Country.Value != "" { + t.Fatalf("a cleared country was refilled: %+v", p.Profile.Country) + } + // Auto hands it back and derives again from the location now held. + p, _ = st.ResetProfileField(p.ID, FieldCountry) + if p.Profile.Country.Value != "ES" || p.Profile.Country.Source != SourceAuto { + t.Fatalf("country after Auto = %+v", p.Profile.Country) + } + // Garbage is refused, not stored. + if _, err := st.SetProfileField(p.ID, FieldCountry, "Atlantis", "olivia"); err == nil { + t.Fatal("an unknown country was accepted") + } + // Resetting the location drops the country it implied. + p, _ = st.ResetProfileField(p.ID, FieldLocation) + if p.Profile.Country.Value != "" { + t.Fatalf("country kept after the location was reset: %+v", p.Profile.Country) + } +} + +func TestFetchProfileDerivesCountry(t *testing.T) { + x, _ := profileFixture(t) + x.m.FetchProfile(context.Background(), x.person.ID, adaLogin) + p, _ := x.m.Store.Get(x.person.ID) + if c := p.Profile.Country; c.Value != "GB" || c.Source != SourceAuto || c.Rule != CountryRuleLocation { + t.Fatalf("country from the GitHub location = %+v", c) + } +} diff --git a/src/pkg/customers/model.go b/src/pkg/customers/model.go index 677200c8c9..88d8c48273 100644 --- a/src/pkg/customers/model.go +++ b/src/pkg/customers/model.go @@ -86,6 +86,10 @@ const ( // location). const MaxProfileFieldLen = 120 +// MaxDismissedAffiliations bounds how many refused affiliation suggestions a +// profile remembers. +const MaxDismissedAffiliations = 20 + // Sentinel errors. The dashboard maps them to status codes. var ( ErrNotFound = errors.New("customers: not found") @@ -270,10 +274,11 @@ const ( FieldRealName = "real_name" FieldOrganization = "organization" FieldLocation = "location" + FieldCountry = "country" ) // ProfileFields is every profile field, in display order. -var ProfileFields = []string{FieldRealName, FieldOrganization, FieldLocation} +var ProfileFields = []string{FieldRealName, FieldOrganization, FieldLocation, FieldCountry} // ProfileSourceGitHub names the automatic source of a profile field: the // person's own public GitHub profile. @@ -298,6 +303,12 @@ type Profile struct { RealName ProfileField `json:"real_name,omitempty"` Organization ProfileField `json:"organization,omitempty"` Location ProfileField `json:"location,omitempty"` + // Country is an ISO 3166 alpha-2 code. Automatic, it is derived offline + // from Location (rule "location"); manual, a person chose or cleared it. + Country ProfileField `json:"country,omitempty"` + // DismissedAffiliations are the suggested organizations a person turned + // down, lower case, so the same one is not offered again. + DismissedAffiliations []string `json:"dismissed_affiliations,omitempty"` } // Field returns a pointer to the named field, or nil for an unknown name. @@ -309,6 +320,8 @@ func (pr *Profile) Field(name string) *ProfileField { return &pr.Organization case FieldLocation: return &pr.Location + case FieldCountry: + return &pr.Country } return nil } diff --git a/src/pkg/customers/profilefetch_test.go b/src/pkg/customers/profilefetch_test.go index aa5f531359..c376e271b8 100644 --- a/src/pkg/customers/profilefetch_test.go +++ b/src/pkg/customers/profilefetch_test.go @@ -44,7 +44,11 @@ func TestFetchProfileFillsAutoFieldsWithProvenance(t *testing.T) { } for _, name := range ProfileFields { f := p.Profile.Field(name) - if f.Source != SourceAuto || f.Rule != ProfileSourceGitHub { + want := ProfileSourceGitHub + if name == FieldCountry { + want = CountryRuleLocation + } + if f.Source != SourceAuto || f.Rule != want { t.Fatalf("%s provenance = %+v", name, f) } } diff --git a/src/pkg/customers/service.go b/src/pkg/customers/service.go index 25bc3ef005..ab1ad6d6c7 100644 --- a/src/pkg/customers/service.go +++ b/src/pkg/customers/service.go @@ -20,6 +20,7 @@ const ( OpName = "name" OpNotes = "notes" OpProfile = "profile" + OpAffiliationDismiss = "affiliation_dismiss" OpIdentityAdd = "identity_add" OpIdentityRemove = "identity_remove" OpTag = "tag" @@ -38,7 +39,7 @@ const TagAuto = "auto" // selfOps is what a viewer without the full view may do, and only to their // own profile: name, identities, tags and goals. var selfOps = map[string]bool{ - OpName: true, OpProfile: true, OpIdentityAdd: true, OpIdentityRemove: true, OpTag: true, + OpName: true, OpProfile: true, OpAffiliationDismiss: true, OpIdentityAdd: true, OpIdentityRemove: true, OpTag: true, OpGoalAdd: true, OpGoalEdit: true, OpGoalConfirm: true, OpGoalReject: true, } @@ -79,6 +80,10 @@ type PersonView struct { // the identity belongs to someone else, and was raised as a question // instead. Hinted bool `json:"hinted,omitempty"` + // Affiliation is a suggested organization with its evidence, never a + // stored fact: Accept writes it as a by-hand organization. Detail views + // only. + Affiliation *AffiliationSuggestion `json:"affiliation_suggestion,omitempty"` } // ListView is the Customers list as one viewer sees it. @@ -154,6 +159,9 @@ func (s *Service) CanSee(v Viewer, id string) bool { // view builds what the viewer sees of p. func (s *Service) view(v Viewer, p Person, isMe, detail bool) PersonView { out := PersonView{Person: p, Me: isMe} + if detail { + out.Affiliation = SuggestAffiliation(p) + } if !v.Full { // A viewer without the full view sees what they may edit. Notes, // the satisfaction assessment, merge history and hints are the @@ -247,6 +255,8 @@ func (s *Service) Edit(v Viewer, id string, e Edit) (PersonView, error) { } else { p, err = s.store.SetProfileField(p.ID, e.Field, e.Value, v.User) } + case OpAffiliationDismiss: + p, err = s.store.DismissAffiliation(p.ID, e.Value) case OpIdentityAdd: id := Identity{Kind: IdentityKind(e.Kind), Value: e.Value} if !v.Full { diff --git a/src/pkg/customers/store.go b/src/pkg/customers/store.go index 423f9ff918..94bc1cbc63 100644 --- a/src/pkg/customers/store.go +++ b/src/pkg/customers/store.go @@ -527,24 +527,34 @@ func (s *Store) SetNotes(id, notes string) (Person, error) { // SetProfileField sets one profile field by hand. An empty value clears it // and keeps the manual mark, so the automatic source does not refill what a -// person removed. +// person removed. A country is read as an ISO code or a country name. Setting +// the location re-derives an automatic country from it. func (s *Store) SetProfileField(id, field, value, by string) (Person, error) { value, err := cleanText(value, MaxProfileFieldLen, false) if err != nil { return Person{}, err } + if field == FieldCountry && value != "" { + if value = CountryFromInput(value); value == "" { + return Person{}, fmt.Errorf("%w: not a country", ErrInvalid) + } + } return s.changePerson(id, func(p *Person) error { f := p.Profile.Field(field) if f == nil { return fmt.Errorf("%w: unknown profile field", ErrInvalid) } *f = ProfileField{Value: value, Source: SourceManual, At: s.now(), By: by} + if field == FieldLocation { + deriveAutoCountry(p, s.now()) + } return nil }) } // ResetProfileField hands a field back to the automatic source: it is -// emptied and the next accept-time fetch may fill it. +// emptied and the next accept-time fetch may fill it. A country is derived +// again at once from the location the profile already holds. func (s *Store) ResetProfileField(id, field string) (Person, error) { return s.changePerson(id, func(p *Person) error { f := p.Profile.Field(field) @@ -552,13 +562,60 @@ func (s *Store) ResetProfileField(id, field string) (Person, error) { return fmt.Errorf("%w: unknown profile field", ErrInvalid) } *f = ProfileField{} + deriveAutoCountry(p, s.now()) + return nil + }) +} + +// deriveAutoCountry keeps an automatic country in step with the location: it +// fills or updates it from DeriveCountry, and drops one the location no longer +// supports. A country a person set or cleared is never touched. It reports +// whether anything changed. +func deriveAutoCountry(p *Person, now time.Time) bool { + c := &p.Profile.Country + if c.Source == SourceManual { + return false + } + code := DeriveCountry(p.Profile.Location.Value) + if code == c.Value { + return false + } + if code == "" { + *c = ProfileField{} + return true + } + *c = ProfileField{Value: code, Source: SourceAuto, Rule: CountryRuleLocation, At: now} + return true +} + +// DismissAffiliation remembers a refused affiliation suggestion so it is not +// offered again. The list is bounded; the oldest refusal is forgotten first. +func (s *Store) DismissAffiliation(id, value string) (Person, error) { + value, err := cleanText(value, MaxProfileFieldLen, false) + if err != nil { + return Person{}, err + } + key := strings.ToLower(value) + if key == "" { + return Person{}, fmt.Errorf("%w: empty affiliation", ErrInvalid) + } + return s.changePerson(id, func(p *Person) error { + if affiliationDismissed(p.Profile, key) { + return nil + } + d := append(p.Profile.DismissedAffiliations, key) + if len(d) > MaxDismissedAffiliations { + d = d[len(d)-MaxDismissedAffiliations:] + } + p.Profile.DismissedAffiliations = d return nil }) } // ApplyAutoProfile fills profile fields from a public GitHub profile. It // only writes a field a person has not set (manual) and only with a -// non-empty value, and it reports whether anything changed. +// non-empty value, derives the country from the location, and reports +// whether anything changed. func (s *Store) ApplyAutoProfile(id string, values map[string]string) (Person, bool, error) { changed := false p, err := s.changePerson(id, func(p *Person) error { @@ -571,6 +628,9 @@ func (s *Store) ApplyAutoProfile(id string, values map[string]string) (Person, b *f = ProfileField{Value: v, Source: SourceAuto, Rule: ProfileSourceGitHub, At: s.now()} changed = true } + if deriveAutoCountry(p, s.now()) { + changed = true + } return nil }) return p, changed, err diff --git a/src/pkg/dashboard/api_customers.go b/src/pkg/dashboard/api_customers.go index bf43c6d88d..d0ffcf809e 100644 --- a/src/pkg/dashboard/api_customers.go +++ b/src/pkg/dashboard/api_customers.go @@ -72,7 +72,7 @@ type CustomerAddRequest struct { } // CustomerEditRequest is the body of POST /api/customers/{id}/edit: one -// change, named by Op (name, notes, profile, identity_add, identity_remove, tag, +// change, named by Op (name, notes, profile, affiliation_dismiss, identity_add, identity_remove, tag, // goal_add, goal_edit, goal_confirm, goal_reject, satisfaction_set, // satisfaction_confirm, satisfaction_reject). type CustomerEditRequest struct { @@ -88,7 +88,7 @@ type CustomerEditRequest struct { Text string `json:"text,omitempty"` Level string `json:"level,omitempty"` // Field names the profile field an "profile" op sets (real_name, - // organization, location); Value is its text and State "auto" hands it + // organization, location, country); Value is its text and State "auto" hands it // back to the automatic source. Field string `json:"field,omitempty"` } diff --git a/src/pkg/dashboard/customers_ui_test.go b/src/pkg/dashboard/customers_ui_test.go index 91d8e057a1..f385c3f589 100644 --- a/src/pkg/dashboard/customers_ui_test.go +++ b/src/pkg/dashboard/customers_ui_test.go @@ -98,6 +98,7 @@ func TestCustomersViewGates(t *testing.T) { "customersPickerOpen", "customersProfilePickerOpen", "customersPickerClose", "customersAttach", "customersHintAnswer", "customersAvatarsOn", "customersGithubLogin", "customersAvatarHtml", "customersMorePill", "customersSourcePills", "rowChevronHtml", "customersOriginPill", "customersTagPill", "customersTagPills", "customersIsOpenTarget", "customersOrgPill", "customersProfileValue", "customersDetailsHtml", + "customersFlagEmoji", "customersCountryName", "customersCountryPill", "customersAffiliationHtml", "graphcanvasRound", "graphcanvasLabel", "graphcanvasLayout", "graphcanvasSvg", } { fns = append(fns, jsFunc(t, html, name)) @@ -124,6 +125,8 @@ const person = { identities: [{ kind: 'hive_user', value: 'ada' }, { kind: 'email', value: 'ada@example.com', claimed: true }, { kind: 'github', value: 'ada', manual: true, by: 'olivia' }], tags: [{ name: 'maintainer', state: 'on', source: 'auto', rule: 'role:owner' }, { name: 'vip', state: 'on', source: 'manual', by: 'olivia' }, { name: 'end-user', state: 'off', source: 'auto' }], goals: [{ id: 'g_1', text: 'Ship exports', state: 'confirmed', source: 'manual', by: 'ada' }, { id: 'g_2', text: 'Wants SSO', state: 'suggested', source: 'auto', evidence: ['gh:issue:o/r#1'] }], + profile: { organization: { value: 'acme', source: 'auto', rule: 'github_profile' }, location: { value: 'Berlin', source: 'auto', rule: 'github_profile' }, country: { value: 'DE', source: 'auto', rule: 'location' } }, + affiliation_suggestion: { value: 'Acme', rule: 'github_company', evidence: 'from GitHub company field "acme"' }, satisfaction: { level: 'at_risk', source: 'manual', by: 'olivia', suggestion: { level: 'neutral', evidence: ['gh:pr:o/r#2'] } }, merged_from: [{ person: { id: 'p_old', name: 'Old ' }, by: 'olivia', at: '2026-10-01T00:00:00Z' }], counts: { authored: 3 }, hints: [{ id: 'h_1', other_kind: 'email', other_value: 'ada@.org', reason: 'the address and the login start the same' }, { id: 'h_2', other_kind: 'customer', other_value: 'Ada B' }] @@ -138,6 +141,12 @@ must(list.includes('data-action="customersAccept"') && list.includes('data-actio must(list.includes('data-arg0="me"') && list.includes('data-arg0="p_abc"'), 'list rows do not open me and the customer'); must(!list.includes('Ada') && list.includes('<b>Ada</b>'), 'a name reached the page unescaped'); must(prof.includes('data-action="customersForget"'), 'owner profile lacks Forget'); +must(customersFlagEmoji('DE') === '\u{1F1E9}\u{1F1EA}' && customersFlagEmoji('de') === '' && customersFlagEmoji('') === '' && customersFlagEmoji(null) === '', 'flag emoji'); +must(list.includes('class="kc-pill customers-pill customers-country" role="img" aria-label="Country: ') && list.includes(' DE'), 'the row lacks the country pill with its text code and accessible name'); +must(customersCountryPill({ profile: { country: { value: '' } } }) === '' && customersCountryPill({}) === '', 'a malformed or missing country must render nothing'); +must(prof.includes('data-customers-field="country-line"') && prof.includes('data-customers-field="profile-country"') && prof.includes('(from location)'), 'Details lack the country line, its field or its provenance'); +must(prof.includes('Likely: Acme') && prof.includes('from GitHub company field "acme"') && prof.includes('data-action="customersAffiliationAccept" data-arg0="Acme"') && prof.includes('data-action="customersAffiliationDismiss" data-arg0="Acme"'), 'the likely affiliation lacks its evidence, Accept or Dismiss'); +must(customersAffiliationHtml({}) === '' && customersAffiliationHtml({ affiliation_suggestion: { value: '' } }) === '', 'no suggestion must render nothing'); must(prof.includes('data-action="customersSatisfactionSet"') && prof.includes('data-action="customersSatisfactionConfirm"') && prof.includes('private note'), 'owner profile lacks satisfaction or notes'); must(prof.includes('data-action="customersIdentityConfirm"'), 'owner cannot confirm a claimed identity'); must(prof.includes('data-action="customersHintAnswer" data-arg0="h_1" data-arg1="yes"') && prof.includes('data-arg0="h_1" data-arg1="no"') && prof.includes('ada@<x>.org'), 'a suggested-identity hint lacks Yes, No or an escaped identity'); @@ -556,6 +565,10 @@ func TestCustomersProfileDetailsWiring(t *testing.T) { `customersOrgPill(p) + customersTagPills(p)`, `data-action="customersProfileSave"`, `data-action="customersProfileReset"`, + `function customersCountryPill(p)`, + `customersOrgPill(p) + customersCountryPill(p) + customersTagPills(p)`, + `{ op: 'affiliation_dismiss', value: value }`, + `{ op: 'profile', field: 'organization', value: value }`, `{ op: 'profile', field: f.key, value: next }`, `op: 'profile', field: key, state: 'auto'`, } { diff --git a/src/pkg/dashboard/static-src/js/customers.js b/src/pkg/dashboard/static-src/js/customers.js index 067b925a9d..2ca88e0f9a 100644 --- a/src/pkg/dashboard/static-src/js/customers.js +++ b/src/pkg/dashboard/static-src/js/customers.js @@ -201,7 +201,8 @@ const CUSTOMERS_PROFILE_FIELDS = [ { key: 'real_name', label: 'Real name', max: 120 }, { key: 'organization', label: 'Organization', max: 120 }, - { key: 'location', label: 'Location or country', max: 120 } + { key: 'location', label: 'Location', max: 120 }, + { key: 'country', label: 'Country (code or name)', max: 120 } ]; function customersProfileValue(p, key) { @@ -219,6 +220,44 @@ return '' + escapeHtml(v) + ''; } + // customersFlagEmoji: the flag for an ISO 3166 alpha-2 code, or '' when the + // code is not two letters. Some systems draw the flag as the two letters, + // so the code is always shown as text beside it. + function customersFlagEmoji(code) { + if (typeof code !== 'string' || !/^[A-Z]{2}$/.test(code)) return ''; + return String.fromCodePoint(0x1F1E6 + code.charCodeAt(0) - 65, 0x1F1E6 + code.charCodeAt(1) - 65); + } + + // customersCountryName: the country's name in the browser language, or the + // code itself when the browser cannot name it. + function customersCountryName(code) { + try { + const n = new Intl.DisplayNames(undefined, { type: 'region' }).of(code); + if (n) return n; + } catch (e) { /* no Intl.DisplayNames: fall back to the code */ } + return code; + } + + // customersCountryPill: a compact flag and ISO code on the row. The name is + // the accessible label, so the meaning never depends on the emoji. + function customersCountryPill(p) { + const code = customersProfileValue(p, 'country'); + if (!/^[A-Z]{2}$/.test(code)) return ''; + const name = customersCountryName(code); + return '' + + ' ' + escapeHtml(code) + ''; + } + + // customersAffiliationHtml: the likely organization, with its evidence, as + // a suggestion to accept or dismiss. Nothing is saved until Accept. + function customersAffiliationHtml(p) { + const s = p && p.affiliation_suggestion; + if (!s || !s.value) return ''; + return '
Likely: ' + escapeHtml(s.value) + ' (' + escapeHtml(s.evidence || 'a guess') + ')' + + '' + + '
'; + } + // customersOriginPill: where the person came from, in one short word. function customersOriginPill(p, updated) { const origin = p && p.origin; @@ -297,7 +336,7 @@ rowChevronHtml('customersToggle', isMe ? 'me' : p.id, open, 'profile of ' + name, pid) + customersAvatarHtml(name, customersGithubLogin(p), '', '') + '
' + escapeHtml(name) + '' + (isMe ? 'me' : '') + - customersSourcePills(p) + customersOriginPill(p, updated) + customersOrgPill(p) + customersTagPills(p) + extra.join('') + pill + '
' + + customersSourcePills(p) + customersOriginPill(p, updated) + customersOrgPill(p) + customersCountryPill(p) + customersTagPills(p) + extra.join('') + pill + '' + (updated ? '' + escapeHtml(updated) + '' : '') + '' + (open ? '
' + customersProfileHtml(_customersOpen) + '
' : '') + ''; } @@ -500,13 +539,15 @@ const rows = CUSTOMERS_PROFILE_FIELDS.map(function (f) { const cur = (p.profile && p.profile[f.key]) || {}; const manual = cur.source === 'manual'; - const mark = cur.value ? (manual ? 'set by hand' : 'from GitHub') : (manual ? 'cleared by hand' : 'not known'); + const mark = cur.value ? (manual ? 'set by hand' : (cur.rule === 'location' ? 'from location' : 'from GitHub')) : (manual ? 'cleared by hand' : 'not known'); return '' + (manual ? '' : ''); }).join(''); - return '
' + - '
' + rows + '
' + + const cc = customersProfileValue(p, 'country'); + const ccLine = /^[A-Z]{2}$/.test(cc) ? '
' + escapeHtml(cc) + ' ' + escapeHtml(customersCountryName(cc)) + '
' : ''; + return '
' + ccLine + + '
' + rows + '
' + customersAffiliationHtml(p) + '
'; } @@ -1003,6 +1044,10 @@ function customersProfileReset(key) { customersEdit({ op: 'profile', field: key, state: 'auto' }, 'Handed back to GitHub'); } + function customersAffiliationAccept(value) { customersEdit({ op: 'profile', field: 'organization', value: value }, 'Organization set'); } + + function customersAffiliationDismiss(value) { customersEdit({ op: 'affiliation_dismiss', value: value }, 'Suggestion dismissed'); } + function customersNotesSave() { customersEdit({ op: 'notes', notes: (customersField('notes') || {}).value || '' }, 'Notes saved'); } // customersHintAnswer answers a "Same person?" question about the open diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 3003d66cef..03b6c4b04a 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -54195,7 +54195,8 @@ const CUSTOMERS_PROFILE_FIELDS = [ { key: 'real_name', label: 'Real name', max: 120 }, { key: 'organization', label: 'Organization', max: 120 }, - { key: 'location', label: 'Location or country', max: 120 } + { key: 'location', label: 'Location', max: 120 }, + { key: 'country', label: 'Country (code or name)', max: 120 } ]; function customersProfileValue(p, key) { @@ -54213,6 +54214,44 @@ return '' + escapeHtml(v) + ''; } + // customersFlagEmoji: the flag for an ISO 3166 alpha-2 code, or '' when the + // code is not two letters. Some systems draw the flag as the two letters, + // so the code is always shown as text beside it. + function customersFlagEmoji(code) { + if (typeof code !== 'string' || !/^[A-Z]{2}$/.test(code)) return ''; + return String.fromCodePoint(0x1F1E6 + code.charCodeAt(0) - 65, 0x1F1E6 + code.charCodeAt(1) - 65); + } + + // customersCountryName: the country's name in the browser language, or the + // code itself when the browser cannot name it. + function customersCountryName(code) { + try { + const n = new Intl.DisplayNames(undefined, { type: 'region' }).of(code); + if (n) return n; + } catch (e) { /* no Intl.DisplayNames: fall back to the code */ } + return code; + } + + // customersCountryPill: a compact flag and ISO code on the row. The name is + // the accessible label, so the meaning never depends on the emoji. + function customersCountryPill(p) { + const code = customersProfileValue(p, 'country'); + if (!/^[A-Z]{2}$/.test(code)) return ''; + const name = customersCountryName(code); + return '' + + ' ' + escapeHtml(code) + ''; + } + + // customersAffiliationHtml: the likely organization, with its evidence, as + // a suggestion to accept or dismiss. Nothing is saved until Accept. + function customersAffiliationHtml(p) { + const s = p && p.affiliation_suggestion; + if (!s || !s.value) return ''; + return '
Likely: ' + escapeHtml(s.value) + ' (' + escapeHtml(s.evidence || 'a guess') + ')' + + '' + + '
'; + } + // customersOriginPill: where the person came from, in one short word. function customersOriginPill(p, updated) { const origin = p && p.origin; @@ -54291,7 +54330,7 @@ rowChevronHtml('customersToggle', isMe ? 'me' : p.id, open, 'profile of ' + name, pid) + customersAvatarHtml(name, customersGithubLogin(p), '', '') + '
' + escapeHtml(name) + '' + (isMe ? 'me' : '') + - customersSourcePills(p) + customersOriginPill(p, updated) + customersOrgPill(p) + customersTagPills(p) + extra.join('') + pill + '
' + + customersSourcePills(p) + customersOriginPill(p, updated) + customersOrgPill(p) + customersCountryPill(p) + customersTagPills(p) + extra.join('') + pill + '
' + (updated ? '' + escapeHtml(updated) + '' : '') + '' + (open ? '
' + customersProfileHtml(_customersOpen) + '
' : '') + ''; } @@ -54494,13 +54533,15 @@ const rows = CUSTOMERS_PROFILE_FIELDS.map(function (f) { const cur = (p.profile && p.profile[f.key]) || {}; const manual = cur.source === 'manual'; - const mark = cur.value ? (manual ? 'set by hand' : 'from GitHub') : (manual ? 'cleared by hand' : 'not known'); + const mark = cur.value ? (manual ? 'set by hand' : (cur.rule === 'location' ? 'from location' : 'from GitHub')) : (manual ? 'cleared by hand' : 'not known'); return '' + (manual ? '' : ''); }).join(''); - return '
' + - '
' + rows + '
' + + const cc = customersProfileValue(p, 'country'); + const ccLine = /^[A-Z]{2}$/.test(cc) ? '
' + escapeHtml(cc) + ' ' + escapeHtml(customersCountryName(cc)) + '
' : ''; + return '
' + ccLine + + '
' + rows + '
' + customersAffiliationHtml(p) + '
'; } @@ -54997,6 +55038,10 @@ function customersProfileReset(key) { customersEdit({ op: 'profile', field: key, state: 'auto' }, 'Handed back to GitHub'); } + function customersAffiliationAccept(value) { customersEdit({ op: 'profile', field: 'organization', value: value }, 'Organization set'); } + + function customersAffiliationDismiss(value) { customersEdit({ op: 'affiliation_dismiss', value: value }, 'Suggestion dismissed'); } + function customersNotesSave() { customersEdit({ op: 'notes', notes: (customersField('notes') || {}).value || '' }, 'Notes saved'); } // customersHintAnswer answers a "Same person?" question about the open From bc86c75ee46caea5ee10eed6e2f79e445e5c860b Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 13:40:20 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20Customers:=20update=20the=20?= =?UTF-8?q?details=20wiring=20pin=20for=20the=20country=20pill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/customers_ui_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pkg/dashboard/customers_ui_test.go b/src/pkg/dashboard/customers_ui_test.go index f385c3f589..791a13f313 100644 --- a/src/pkg/dashboard/customers_ui_test.go +++ b/src/pkg/dashboard/customers_ui_test.go @@ -562,7 +562,6 @@ func TestCustomersProfileDetailsWiring(t *testing.T) { for _, want := range []string{ `function customersDetailsHtml(p)`, `function customersOrgPill(p)`, - `customersOrgPill(p) + customersTagPills(p)`, `data-action="customersProfileSave"`, `data-action="customersProfileReset"`, `function customersCountryPill(p)`,