How auto-assign works

State Usergroup Rules

How auto-assign works

The trigger is users.Service.ApplyStateUsergroups(ctx, userID, stateCode). It is called with the address's state value after CreateAddress and after an UpdateAddress that sets a state.

Flow

  1. Inputs. userID and the state code. Both required; empty inputs return early.
  2. Background run. The address service starts the assignment in the background after the address row is written, so the address request doesn't wait for it.
  3. Module gate. The service checks IsEnabled(tenant, "state-usergroup-rules"). On false (or on lookup error — fail closed) the function returns. No assignment happens.
  4. Rule lookup. SELECT usergroup_id FROM state_usergroup_rules WHERE state_code = $1 AND auto_assign = true. Pulls every active rule for that state.
  5. Upsert. For each matching usergroup, INSERT INTO usergroup_links (user_id, usergroup_id, status) VALUES (..., 'A') ON CONFLICT (user_id, usergroup_id) DO NOTHING. Already-assigned users are quietly skipped.
  6. Logging. One info line per assignment, one error line per failure.

What does NOT happen

  • No removal of stale groups. Moving from CA to NY does NOT remove the CA group. A user who lived in CA and then moved keeps the CA group unless a separate process trims it.
  • No retroactive re-evaluation. Changing a rule (e.g. setting its auto_assign to false, or deleting it) does NOT re-process existing customers. The rule applies forward only.
  • No conflict resolution. If three rules for state CA all auto-assign different usergroups, the user gets all three. State Usergroup Rules is additive — no winner-takes-all.
  • No transaction with the address write. The assignment runs in its own queries after the address commits. If the address commits but the assignment fails (DB hiccup), the address is correct and the user simply lacks the group; the next address update will retry.

Where the trigger lives

In the users service. Search for ApplyStateUsergroups to find every call site:

  • users.Service.CreateAddress — used by the customer's account address book and by the admin customer page.
  • users.Service.UpdateAddress — when the update includes a state.

If you build a NEW path that captures addresses, call ApplyStateUsergroups after the address row commits. Skipping the call leaves customers in a half-onboarded state where the address is right but the usergroup is empty.

Removal flow (manual)

If you want a "leaving CA" rule too — i.e. remove the CA group when the user changes state — that's not built in. Implement it at the address-update site (look up the OLD state's rules and DELETE the matching usergroup_links rows) before calling ApplyStateUsergroups with the new state.