diff --git a/AGENTS.md b/AGENTS.md index 0f2c50a..16cd3e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -165,6 +165,7 @@ tests/ # pytest suite (file naming: *_test.py) ├── logout_pair_test.py # logout revokes the pair (Bearer or refresh-body form) ├── auth_backend_unavailable_test.py # 503 auth_backend_unavailable: bounded retry, never a logout ├── standalone_org_login_test.py # standalone Dailybot orgs in the login picker +├── kudos_send_as_user_test.py # kudos give --send-as-user (admin-only, in a member's name) ├── effective_tier_test.py # cached plan tier refreshed from /v1/organization/ ├── org_channels_test.py # `dailybot org` chat platforms (ChatPlatformSummary) ├── cli_auth_deprecation_test.py # the cli_auth_deprecated notice on email-code sign-in diff --git a/README.md b/README.md index 5ef0eec..335d4cc 100644 --- a/README.md +++ b/README.md @@ -436,6 +436,9 @@ dailybot kudos give --to "Jane Doe" --message "Great!" --value ``` If `--to` or `--team` matches more than one name partially, the CLI lists the ambiguous matches and exits — it never guesses. Pass the full name or a UUID to be precise. At least one of `--to` or `--team` is required. @@ -450,6 +453,7 @@ Team kudos pass through the backend's team manager, which expands the team into | `--team` | | Team name or UUID. Optional when `--to` is provided. | | `--message` | `-m` | Kudos message (team-visible). Required. | | `--value` | | Optional company value UUID. | +| `--send-as-user` | | Give the kudos in the name of this member (user UUID). Organization admins only; the kudos rules (not to yourself, daily limits) apply to that member. | | `--yes` | `-y` | Skip the confirmation prompt. | | `--json` | | Emit machine-readable JSON to stdout. | diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 08298ce..0855cbd 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -2273,6 +2273,7 @@ def give_kudos( user_uuid_receivers: list[str] | None = None, team_uuid_receivers: list[str] | None = None, company_value: str | None = None, + send_as_user: str | None = None, ) -> dict[str, Any]: """POST /v1/kudos/ @@ -2280,6 +2281,9 @@ def give_kudos( validation) plus the type-specific ``users_receivers`` / ``teams_receivers`` lists the server uses to expand teams into their members. At least one receiver must be present — the backend rejects an empty set. + + ``send_as_user`` (a member UUID, org admins only) gives the kudos in that + member's name. It is sent only when set, so the default body is unchanged. """ payload: dict[str, Any] = {"content": content} receivers: list[str] = [*(user_uuid_receivers or []), *(team_uuid_receivers or [])] @@ -2291,6 +2295,8 @@ def give_kudos( payload["teams_receivers"] = team_uuid_receivers if company_value: payload["company_value"] = company_value + if send_as_user is not None: + payload["send_as_user"] = send_as_user response: httpx.Response = self._request( "POST", f"{self.api_url}/v1/kudos/", diff --git a/dailybot_cli/commands/kudos.py b/dailybot_cli/commands/kudos.py index 77c34c3..42b2361 100644 --- a/dailybot_cli/commands/kudos.py +++ b/dailybot_cli/commands/kudos.py @@ -8,6 +8,7 @@ from dailybot_cli.commands.public_api_helpers import ( EXIT_PERMISSION_DENIED, EXIT_USAGE_ERROR, + UUID_PATTERN, confirm_write, emit_json, enforce_plan_access, @@ -27,6 +28,28 @@ print_pagination_footer, ) +# Server refusals of ``send_as_user`` reworded for this command. The shared +# messages in ``ERROR_CODE_MESSAGES`` name the chat-send flags. +SEND_AS_USER_OVERRIDES: dict[str, str] = { + "org_admin_required": ( + "Giving kudos in another member's name (--send-as-user) requires organization " + "admin privileges. Run it with an admin account or an org admin's API key. " + "No kudos was given." + ), + "send_as_user_invalid_uuid": "Invalid UUID for --send-as-user.", + "send_as_user_not_found": ( + "--send-as-user must be the UUID of an active member of your organization. " + "Run 'dailybot user list' to find it." + ), + # The API refuses send_as_user together with by_dailybot (a kudos credited to + # Dailybot itself) or is_anonymous (a kudos given in someone's name can't hide + # its sender). The CLI sends neither; kept in case a server returns it anyway. + "send_as_user_conflict": ( + "--send-as-user can't be combined with an anonymous kudos or one given by " + "Dailybot itself: a kudos given in someone's name always shows its sender." + ), +} + def execute_kudos_give( client: DailyBotClient, @@ -40,12 +63,18 @@ def execute_kudos_give( json_mode: bool = False, receiver_uuid: str | None = None, receiver_name: str | None = None, + send_as_user: str | None = None, + send_as_name: str | None = None, ) -> None: """Send kudos with already-resolved user / team receivers. ``receiver_uuid`` / ``receiver_name`` are a legacy single-user shortcut kept for interactive mode; new callers should use ``user_receivers`` / ``team_receivers`` lists of (uuid, display_name) pairs. + + ``send_as_user`` gives the kudos in that member's name (org admins only). + The server applies the kudos rules to that member, so the local + "not to yourself" check compares the receivers with them, not the caller. """ users: list[tuple[str, str]] = list(user_receivers or []) teams: list[tuple[str, str]] = list(team_receivers or []) @@ -53,10 +82,15 @@ def execute_kudos_give( if receiver_uuid: users.append((receiver_uuid, receiver_name or receiver_uuid)) - if current_uuid: + giver_uuid: str | None = send_as_user or current_uuid + if giver_uuid: for user_uuid, _name in users: - if user_uuid == current_uuid: - error_message: str = "You cannot give kudos to yourself." + if user_uuid.lower() == giver_uuid.lower(): + error_message: str = ( + "A member cannot receive kudos given in their own name." + if send_as_user + else "You cannot give kudos to yourself." + ) if json_mode: emit_json({"error": error_message, "status": 403}) else: @@ -83,9 +117,16 @@ def execute_kudos_give( summary_lines.append(f"Message: {message}") if value: summary_lines.append(f"Company value: {value}") + if send_as_user: + summary_lines.append( + f"Given in the name of: {send_as_name} ({send_as_user})" + if send_as_name + else f"Given in the name of: {send_as_user} (not found in your directory)" + ) confirm_write(summary_lines, assume_yes) + extra_fields: dict[str, Any] = {"send_as_user": send_as_user} if send_as_user else {} try: with console.status("Sending kudos..."): result: dict[str, Any] = client.give_kudos( @@ -93,16 +134,19 @@ def execute_kudos_give( user_uuid_receivers=[u for u, _ in users] or None, team_uuid_receivers=[t for t, _ in teams] or None, company_value=value, + **extra_fields, ) except APIError as exc: - exit_for_api_error(exc, json_mode) + exit_for_api_error( + exc, json_mode, code_overrides=SEND_AS_USER_OVERRIDES if send_as_user else None + ) if json_mode: emit_json(result) return label_parts: list[str] = [name for _, name in users] + [f"team {name}" for _, name in teams] - print_kudos_result(", ".join(label_parts) or "receiver", result) + print_kudos_result(", ".join(label_parts) or "receiver", result, given_as=send_as_user) @click.group() @@ -139,6 +183,15 @@ def kudos() -> None: default=None, help="Optional company value UUID.", ) +@click.option( + "--send-as-user", + "send_as_user", + default=None, + help=( + "Give the kudos in the name of this member (user UUID). Admin-only; use it " + "only when asked to give kudos on someone else's behalf." + ), +) @click.option("--yes", "-y", "assume_yes", is_flag=True, help="Skip the confirmation prompt.") @click.option("--json", "json_mode", is_flag=True, help="Emit machine-readable JSON to stdout.") def kudos_give( @@ -146,6 +199,7 @@ def kudos_give( team_identifier: str | None, message: str, value: str | None, + send_as_user: str | None, assume_yes: bool, json_mode: bool, ) -> None: @@ -163,7 +217,19 @@ def kudos_give( dailybot kudos give --to "Jane Doe" --message "Great release work!" dailybot kudos give --team "Engineering" --message "Shipped flawlessly" dailybot kudos give --to "Alice" --team "QA" --message "Both nailed it" + dailybot kudos give --to "Jane Doe" --message "Thanks!" --send-as-user + + \b + --send-as-user gives the kudos in another member's name (org admins only; + the kudos rules apply to that member). """ + if send_as_user is not None and not UUID_PATTERN.match(send_as_user): + invalid_message: str = "Invalid UUID for --send-as-user." + if json_mode: + emit_json({"error": invalid_message, "status": 0}) + else: + print_error(invalid_message) + raise SystemExit(EXIT_USAGE_ERROR) if not receiver and not team_identifier: message_err: str = "At least one of --to or --team is required." if json_mode: @@ -177,6 +243,7 @@ def kudos_give( user_receivers: list[tuple[str, str]] = [] team_receivers: list[tuple[str, str]] = [] current_uuid: str | None = None + send_as_name: str | None = None try: if receiver: @@ -185,6 +252,21 @@ def kudos_give( user_uuid, user_name = resolve_user_by_name_or_uuid(users, receiver) user_receivers.append((user_uuid, user_name)) current_uuid = get_current_user_uuid(client) + if send_as_user: + # Name the member in the confirmation, so a wrong UUID is easy to catch. + with console.status("Resolving the member..."): + directory: list[dict[str, Any]] = client.list_users(include_inactive=True) + send_as_name = ( + next( + ( + str(u.get("full_name") or u.get("name") or "") + for u in directory + if str(u.get("uuid") or "").lower() == send_as_user.lower() + ), + None, + ) + or None + ) if team_identifier: with console.status("Resolving team receiver..."): teams: list[dict[str, Any]] = client.list_teams() @@ -208,6 +290,8 @@ def kudos_give( value=value, assume_yes=assume_yes, json_mode=json_mode, + send_as_user=send_as_user, + send_as_name=send_as_name, ) diff --git a/dailybot_cli/commands/task.py b/dailybot_cli/commands/task.py index 00c9c29..d93821b 100644 --- a/dailybot_cli/commands/task.py +++ b/dailybot_cli/commands/task.py @@ -2062,9 +2062,9 @@ def task_delete( """Archive a task. An alias of `task archive` — nothing is destroyed. \b - The server treats DELETE on a task as an archive: it is reversible and audited - as `task.archived`. This command says "archived" for that reason, and names - the restore path, rather than implying a deletion that does not happen. + This command posts to the archive door, so the task is archived: it is + reversible with `task restore` and audited as `task.archived`. (The API's own + DELETE on a task now moves it to a trash instead; this command does not use it.) \b Examples: diff --git a/dailybot_cli/display.py b/dailybot_cli/display.py index 92eacf0..bad87b9 100644 --- a/dailybot_cli/display.py +++ b/dailybot_cli/display.py @@ -1231,10 +1231,32 @@ def print_form_submit_result(form_name: str, data: dict[str, Any]) -> None: print_info(f"Response ID: {response_id}") -def print_kudos_result(receiver_name: str, data: dict[str, Any]) -> None: - """Display the result of giving kudos.""" +def print_kudos_result( + receiver_name: str, data: dict[str, Any], *, given_as: str | None = None +) -> None: + """Display the result of giving kudos. + + ``given_as`` names the member the kudos was given in the name of + (``--send-as-user``); the server's ``user`` in the answer wins when present. + """ kudos_id: str = resource_uuid(data) or "N/A" print_success(f"Kudos sent to {receiver_name}") + if given_as: + giver: Any = data.get("user") + giver_uuid: str = str(giver.get("uuid") or "") if isinstance(giver, dict) else "" + if giver_uuid and giver_uuid.lower() == given_as.lower(): + giver_label: str = str(giver.get("full_name") or giver.get("name") or given_as) + print_info(f"Given in the name of: {plain_text(giver_label)}") + elif giver_uuid: + print_warning( + f"The server recorded a different giver ({plain_text(giver_uuid)}) than " + f"--send-as-user ({plain_text(given_as)}). Check the kudos before relying on it." + ) + else: + print_warning( + "The server did not confirm the giver. An API without --send-as-user support " + "gives the kudos as you." + ) print_info(f"Kudos ID: {kudos_id}") diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 856038b..9e6a821 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -288,18 +288,21 @@ Creating and configuring forms/check-ins (as opposed to filling them in). All au ### `dailybot kudos` (group) — user-scoped, Bearer or API key auth -#### `dailybot kudos give [--to ] [--team ] --message [--value ] [--yes] [--json]` +#### `dailybot kudos give [--to ] [--team ] --message [--value ] [--send-as-user ] [--yes] [--json]` Gives kudos to a user, a team, or both. Users are resolved by name (exact then partial match) against `GET /v1/users/`. Teams are resolved by name against `GET /v1/teams/` (server-scoped by role). At least one of `--to` / `--team` is required. The POST `/v1/kudos/` payload uses a single `receivers` list of UUIDs (users and teams merged — the server resolves each UUID's type); the backend manager expands team UUIDs into their active members and excludes the caller, so giving kudos to a team you belong to is valid. (The legacy `user_uuid_receivers` / `team_uuid_receivers` fields are still accepted server-side during a deprecation window, but the CLI now sends `receivers`.) +`--send-as-user ` (organization admins only) adds `send_as_user` to the body: the kudos is given in that member's name, and the kudos rules (no kudos to yourself, daily limits) apply to that member. The member must be active in the caller's organization. The refusals are `403 org_admin_required` (nothing is created), `400 send_as_user_invalid_uuid`, `400 send_as_user_not_found` and `400 send_as_user_conflict` (sent with `by_dailybot` or `is_anonymous`, which the CLI never sends); `kudos give` maps each to its own message. An API that predates the field ignores it and gives the kudos as the caller, so this flag needs an API that supports it. + | Flag | Short | Notes | |------|-------|-------| | `--to` | `-t` | User full name or UUID. Optional when `--team` is provided. | | `--team` | | Team name or UUID. Optional when `--to` is provided. | | `--message` | `-m` | Kudos message. Required. | | `--value` | | Optional company value UUID. | +| `--send-as-user` | | Give the kudos in the name of this member (user UUID). Org admins only. The confirmation names the member from your directory; the success line names them only when the server's answer confirms it, and warns otherwise. | | `--yes` | `-y` | Skip confirmation prompt. | | `--json` | | Machine-readable JSON output. | @@ -445,7 +448,7 @@ Server-side `code` values mapped to messages (see `ERROR_CODE_MESSAGES` in `comm | `free_plan_daily_limit_exceeded` | 403 → exit 4 | | `send_as_user_conflict` | 400 → exit 2 | | `send_as_user_invalid_uuid` | 400 → exit 2 | -| `send_as_user_not_found` | 404 → exit 5 | +| `send_as_user_not_found` | 404 → exit 5 on `chat send`; 400 → exit 2 on `kudos give` | The CLI dispatches on the machine-readable `code` field (never the `detail` prose). `plan_upgrade_required` additionally surfaces the `upgrade_url` from the payload. @@ -743,7 +746,7 @@ key, so all of these commands work with `DAILYBOT_API_KEY` set even without | `GET` | `/v1/teams/` | — | `{ results: [{ uuid, name, active, members_count, is_default }], next? }` | Server-scoped: admins see all, members see own | | `GET` | `/v1/teams//` | — | `{ uuid, name, active, ... }` | Same scoping | | `GET` | `/v1/teams//members/` | — | `[{ uuid, full_name, email }]` | Members of a team the caller can see | -| `POST` | `/v1/kudos/` | `{ content, receivers: [...uuid], users_receivers?: [...], teams_receivers?: [...], company_value? }` | `{ uuid }` | `receivers` = users+teams merged (validation); `users_receivers`/`teams_receivers` drive team expansion. Payload contract is being reconciled server-side — see the integration prompt. 406 = daily limit | +| `POST` | `/v1/kudos/` | `{ content, receivers: [...uuid], users_receivers?: [...], teams_receivers?: [...], company_value?, send_as_user? }` | `{ uuid }` | `receivers` = users+teams merged (validation); `users_receivers`/`teams_receivers` drive team expansion. `send_as_user` (`--send-as-user`, org admins only) gives the kudos in that member's name; sent only when set. Refusals: 403 `org_admin_required`, 400 `send_as_user_invalid_uuid` / `send_as_user_not_found` / `send_as_user_conflict`. 406 = daily limit | | `GET` | `/v1/kudos/` | `?filter=kudos_received\|kudos_given` (the CLI accepts `received`/`given` and the `KUDOS_*` forms and normalizes them), shared list params (all optional) | `{ count, next, previous, results }` | `kudos list` | | `GET` | `/v1/kudos/organization/` | list flags | `{count, next, previous, results}` | `kudos org`; admin-only (Bearer or X-API-KEY) | | `GET` | `/v1/kudos/wall-of-fame/` | `?limit` (optional) | `{ top_receiver, top_giver, dna_distribution, leaderboard: { count, next, previous, results }, leaderboard_summary }` | `kudos wall-of-fame` | diff --git a/tests/kudos_send_as_user_test.py b/tests/kudos_send_as_user_test.py new file mode 100644 index 0000000..daafaf0 --- /dev/null +++ b/tests/kudos_send_as_user_test.py @@ -0,0 +1,165 @@ +"""`kudos give --send-as-user`: give a kudos in another member's name (org admins only). + +The wire field is `send_as_user` on POST /v1/kudos/, the same admin-only parameter +POST /v1/send-message/ has. HTTP is mocked at the call site. +""" + +import json +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest +from click.testing import CliRunner, Result + +from dailybot_cli.api_client import APIError, DailyBotClient +from dailybot_cli.main import cli + +POST: str = "dailybot_cli.api_client.httpx.post" +GIVER: str = "11111111-2222-3333-4444-555555555555" +RECEIVER: str = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" +CALLER: str = "99999999-8888-7777-6666-555555555555" + + +def _response(status: int, body: dict[str, Any]) -> MagicMock: + response: MagicMock = MagicMock() + response.status_code = status + response.headers = {} + response.json.return_value = body + response.text = json.dumps(body) + return response + + +@pytest.fixture +def client() -> MagicMock: + with ( + patch("dailybot_cli.commands.public_api_helpers.get_agent_auth", return_value="tok"), + patch("dailybot_cli.commands.public_api_helpers.DailyBotClient") as cls, + patch("dailybot_cli.commands.kudos.get_current_user_uuid", return_value=CALLER), + ): + mock: MagicMock = cls.return_value + mock.list_users.return_value = [ + {"uuid": RECEIVER, "full_name": "Jane Doe"}, + {"uuid": GIVER, "full_name": "Alex Admin"}, + ] + mock.give_kudos.return_value = { + "uuid": "kudos-uuid", + "user": {"uuid": GIVER, "full_name": "Alex Admin"}, + } + yield mock + + +def _give(*extra: str) -> Result: + return CliRunner().invoke( + cli, ["kudos", "give", "--to", "Jane Doe", "--message", "Thanks!", "--yes", *extra] + ) + + +class TestWire: + def test_the_field_is_sent_only_when_set(self) -> None: + api: DailyBotClient = DailyBotClient(api_url="https://api.example.com", token="tok") + with patch(POST, return_value=_response(201, {"uuid": "k"})) as request: + api.give_kudos(content="Hi", user_uuid_receivers=[RECEIVER]) + api.give_kudos(content="Hi", user_uuid_receivers=[RECEIVER], send_as_user=GIVER) + first: dict[str, Any] = request.call_args_list[0].kwargs["json"] + second: dict[str, Any] = request.call_args_list[1].kwargs["json"] + assert "send_as_user" not in first + assert second["send_as_user"] == GIVER + + +class TestCommand: + def test_it_forwards_the_member(self, client: MagicMock) -> None: + result: Result = _give("--send-as-user", GIVER) + assert result.exit_code == 0, result.output + assert client.give_kudos.call_args.kwargs["send_as_user"] == GIVER + assert "Given in the name of: Alex Admin" in result.output + + def test_without_the_flag_the_call_is_unchanged(self, client: MagicMock) -> None: + result: Result = _give() + assert result.exit_code == 0, result.output + assert "send_as_user" not in client.give_kudos.call_args.kwargs + assert "Given in the name of" not in result.output + + def test_a_malformed_uuid_stops_before_any_call(self, client: MagicMock) -> None: + result: Result = _give("--send-as-user", "not-a-uuid") + assert result.exit_code == 2 + assert "Invalid UUID for --send-as-user." in result.output + client.give_kudos.assert_not_called() + + def test_the_named_member_cannot_receive_their_own_kudos(self, client: MagicMock) -> None: + client.list_users.return_value = [{"uuid": GIVER, "full_name": "Jane Doe"}] + result: Result = _give("--send-as-user", GIVER) + assert result.exit_code == 4 + assert "in their own name" in result.output + client.give_kudos.assert_not_called() + + def test_the_own_name_check_ignores_uuid_case(self, client: MagicMock) -> None: + client.list_users.return_value = [{"uuid": RECEIVER, "full_name": "Jane Doe"}] + result: Result = _give("--send-as-user", RECEIVER.upper()) + assert result.exit_code == 4 + client.give_kudos.assert_not_called() + + def test_an_admin_may_give_the_caller_kudos_in_another_name(self, client: MagicMock) -> None: + client.list_users.return_value = [{"uuid": CALLER, "full_name": "Jane Doe"}] + result: Result = _give("--send-as-user", GIVER) + assert result.exit_code == 0, result.output + + def test_the_confirmation_names_the_member(self, client: MagicMock) -> None: + result: Result = CliRunner().invoke( + cli, + ["kudos", "give", "--to", "Jane Doe", "-m", "Thanks!", "--send-as-user", GIVER], + input="n\n", + ) + assert f"Given in the name of: Alex Admin ({GIVER})" in result.output + client.give_kudos.assert_not_called() + + def test_the_confirmation_flags_a_member_missing_from_the_directory( + self, client: MagicMock + ) -> None: + client.list_users.return_value = [{"uuid": RECEIVER, "full_name": "Jane Doe"}] + result: Result = CliRunner().invoke( + cli, + ["kudos", "give", "--to", "Jane Doe", "-m", "Thanks!", "--send-as-user", GIVER], + input="n\n", + ) + assert f"{GIVER} (not found in your directory)" in " ".join(result.output.split()) + + def test_an_unconfirmed_giver_warns_instead_of_claiming(self, client: MagicMock) -> None: + client.give_kudos.return_value = {"uuid": "kudos-uuid"} + result: Result = _give("--send-as-user", GIVER) + assert result.exit_code == 0, result.output + assert "Given in the name of" not in result.output + assert "did not confirm the giver" in " ".join(result.output.split()) + + def test_a_different_giver_warns(self, client: MagicMock) -> None: + client.give_kudos.return_value = {"uuid": "kudos-uuid", "user": {"uuid": CALLER}} + result: Result = _give("--send-as-user", GIVER) + assert result.exit_code == 0, result.output + assert "Given in the name of" not in result.output + assert "different giver" in " ".join(result.output.split()) + + +class TestRefusals: + @pytest.mark.parametrize( + ("status", "code", "expected", "exit_code"), + [ + (403, "org_admin_required", "requires organization admin privileges", 4), + (400, "send_as_user_invalid_uuid", "Invalid UUID for --send-as-user.", 2), + (400, "send_as_user_not_found", "active member of your organization", 2), + (400, "send_as_user_conflict", "always shows its sender", 2), + ], + ) + def test_each_code_has_a_clear_message( + self, client: MagicMock, status: int, code: str, expected: str, exit_code: int + ) -> None: + client.give_kudos.side_effect = APIError(status, "server detail", code=code) + result: Result = _give("--send-as-user", GIVER) + assert result.exit_code == exit_code + assert expected in " ".join(result.output.split()) + + def test_json_mode_keeps_the_code(self, client: MagicMock) -> None: + client.give_kudos.side_effect = APIError( + 403, "Only organization admins can do this.", code="org_admin_required" + ) + result: Result = _give("--send-as-user", GIVER, "--json") + assert result.exit_code != 0 + assert "org_admin_required" in result.output